File: nacl_listener.cc

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (424 lines) | stat: -rw-r--r-- 15,417 bytes parent folder | download | duplicates (6)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
// Copyright 2013 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifdef UNSAFE_BUFFERS_BUILD
// TODO(crbug.com/40285824): Remove this and convert code to safer constructs.
#pragma allow_unsafe_buffers
#endif

#include "components/nacl/loader/nacl_listener.h"

#include <errno.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>

#include <memory>
#include <utility>

#include "base/functional/bind.h"
#include "base/memory/raw_ptr.h"
#include "base/task/single_thread_task_runner.h"
#include "build/build_config.h"

#if BUILDFLAG(IS_POSIX)
#include <unistd.h>
#endif

#include "base/command_line.h"
#include "base/logging.h"
#include "base/memory/read_only_shared_memory_region.h"
#include "base/message_loop/message_pump_type.h"
#include "base/rand_util.h"
#include "base/run_loop.h"
#include "base/synchronization/waitable_event.h"
#include "base/task/single_thread_task_runner.h"
#include "components/nacl/common/nacl.mojom.h"
#include "components/nacl/common/nacl_messages.h"
#include "components/nacl/common/nacl_service.h"
#include "components/nacl/common/nacl_switches.h"
#include "components/nacl/loader/nacl_ipc_adapter.h"
#include "components/nacl/loader/nacl_validation_db.h"
#include "components/nacl/loader/nacl_validation_query.h"
#include "ipc/ipc_channel_handle.h"
#include "ipc/ipc_sync_channel.h"
#include "ipc/ipc_sync_message_filter.h"
#include "mojo/public/cpp/bindings/pending_remote.h"
#include "native_client/src/public/chrome_main.h"
#include "native_client/src/public/nacl_app.h"
#include "native_client/src/public/nacl_desc.h"

#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
#include "content/public/common/zygote/sandbox_support_linux.h"
#endif

#if BUILDFLAG(IS_POSIX)
#include "base/posix/eintr_wrapper.h"
#endif

namespace {

NaClListener* g_listener;

void FatalLogHandler(const char* data, size_t bytes) {
  // We use uint32_t rather than size_t for the case when the browser and NaCl
  // processes are a mix of 32-bit and 64-bit processes.
  uint32_t copy_bytes = std::min<uint32_t>(static_cast<uint32_t>(bytes),
                                           nacl::kNaClCrashInfoMaxLogSize);

  // We copy the length of the crash data to the start of the shared memory
  // segment so we know how much to copy.
  memcpy(g_listener->crash_info_shmem_memory(), &copy_bytes, sizeof(uint32_t));

  memcpy((char*)g_listener->crash_info_shmem_memory() + sizeof(uint32_t),
         data,
         copy_bytes);
}

void LoadStatusCallback(int load_status) {
  g_listener->trusted_listener()->renderer_host()->ReportLoadStatus(
      static_cast<NaClErrorCode>(load_status));
}

// Creates the PPAPI IPC channel between the NaCl IRT and the host
// (browser/renderer) process, and starts to listen it on the thread where
// the given task runner runs.
// Also, creates and sets the corresponding NaClDesc to the given nap with
// the FD #.
void SetUpIPCAdapter(
    IPC::ChannelHandle* handle,
    scoped_refptr<base::SingleThreadTaskRunner> task_runner,
    struct NaClApp* nap,
    int nacl_fd,
    NaClIPCAdapter::ResolveFileTokenCallback resolve_file_token_cb,
    NaClIPCAdapter::OpenResourceCallback open_resource_cb) {
  mojo::MessagePipe pipe;
  scoped_refptr<NaClIPCAdapter> ipc_adapter(new NaClIPCAdapter(
      pipe.handle0.release(), task_runner, std::move(resolve_file_token_cb),
      std::move(open_resource_cb)));
  ipc_adapter->ConnectChannel();
  *handle = pipe.handle1.release();

  // Pass a NaClDesc to the untrusted side. This will hold a ref to the
  // NaClIPCAdapter.
  NaClAppSetDesc(nap, nacl_fd, ipc_adapter->MakeNaClDesc());
}

}  // namespace

class BrowserValidationDBProxy : public NaClValidationDB {
 public:
  explicit BrowserValidationDBProxy(NaClListener* listener)
      : listener_(listener) {
  }

  bool QueryKnownToValidate(const std::string& signature) override {
    // Initialize to false so that if the Send fails to write to the return
    // value we're safe.  For example if the message is (for some reason)
    // dispatched as an async message the return parameter will not be written.
    bool result = false;
    if (!listener_->Send(new NaClProcessMsg_QueryKnownToValidate(signature,
                                                                 &result))) {
      LOG(ERROR) << "Failed to query NaCl validation cache.";
      result = false;
    }
    return result;
  }

  void SetKnownToValidate(const std::string& signature) override {
    // Caching is optional: NaCl will still work correctly if the IPC fails.
    if (!listener_->Send(new NaClProcessMsg_SetKnownToValidate(signature))) {
      LOG(ERROR) << "Failed to update NaCl validation cache.";
    }
  }

 private:
  // The listener never dies, otherwise this might be a dangling reference.
  raw_ptr<NaClListener> listener_;
};

NaClListener::NaClListener()
    : shutdown_event_(base::WaitableEvent::ResetPolicy::MANUAL,
                      base::WaitableEvent::InitialState::NOT_SIGNALED),
      io_thread_("NaCl_IOThread"),
#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
      prereserved_sandbox_size_(0),
#endif
#if BUILDFLAG(IS_POSIX)
      number_of_cores_(-1),  // unknown/error
#endif
      is_started_(false) {
  io_thread_.StartWithOptions(
      base::Thread::Options(base::MessagePumpType::IO, 0));
  DCHECK(g_listener == NULL);
  g_listener = this;
}

NaClListener::~NaClListener() {
  NOTREACHED();
}

bool NaClListener::Send(IPC::Message* msg) {
  DCHECK(!!main_task_runner_);
  if (main_task_runner_->BelongsToCurrentThread()) {
    // This thread owns the channel.
    return channel_->Send(msg);
  }
  // This thread does not own the channel.
  return filter_->Send(msg);
}

// The NaClProcessMsg_ResolveFileTokenAsyncReply message must be
// processed in a MessageFilter so it can be handled on the IO thread.
// The main thread used by NaClListener is busy in
// NaClChromeMainAppStart(), so it can't be used for servicing messages.
class FileTokenMessageFilter : public IPC::MessageFilter {
 public:
  bool OnMessageReceived(const IPC::Message& msg) override {
    bool handled = true;
    IPC_BEGIN_MESSAGE_MAP(FileTokenMessageFilter, msg)
      IPC_MESSAGE_HANDLER(NaClProcessMsg_ResolveFileTokenReply,
                          OnResolveFileTokenReply)
      IPC_MESSAGE_UNHANDLED(handled = false)
    IPC_END_MESSAGE_MAP()
    return handled;
  }

  void OnResolveFileTokenReply(
      uint64_t token_lo,
      uint64_t token_hi,
      IPC::PlatformFileForTransit ipc_fd,
      base::FilePath file_path) {
    CHECK(g_listener);
    g_listener->OnFileTokenResolved(token_lo, token_hi, ipc_fd, file_path);
  }
 private:
  ~FileTokenMessageFilter() override = default;
};

void NaClListener::Listen() {
  NaClService service(io_thread_.task_runner());
  channel_ = IPC::SyncChannel::Create(
      this, io_thread_.task_runner().get(),
      base::SingleThreadTaskRunner::GetCurrentDefault(), &shutdown_event_);
  filter_ = channel_->CreateSyncMessageFilter();
  channel_->AddFilter(new FileTokenMessageFilter());
  channel_->Init(service.TakeChannelPipe().release(), IPC::Channel::MODE_CLIENT,
                 true);
  main_task_runner_ = base::SingleThreadTaskRunner::GetCurrentDefault();
  base::RunLoop().Run();
}

#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
// static
int NaClListener::MakeSharedMemorySegment(size_t length, int executable) {
  return content::SharedMemoryIPCSupport::MakeSharedMemorySegment(length,
                                                                  executable);
}
#endif

bool NaClListener::OnMessageReceived(const IPC::Message& msg) {
  bool handled = true;
  IPC_BEGIN_MESSAGE_MAP(NaClListener, msg)
      IPC_MESSAGE_HANDLER(NaClProcessMsg_AddPrefetchedResource,
                          OnAddPrefetchedResource)
      IPC_MESSAGE_HANDLER(NaClProcessMsg_Start, OnStart)
      IPC_MESSAGE_UNHANDLED(handled = false)
  IPC_END_MESSAGE_MAP()
  return handled;
}

bool NaClListener::OnOpenResource(
    const IPC::Message& msg,
    const std::string& key,
    NaClIPCAdapter::OpenResourceReplyCallback cb) {
  // This callback is executed only on |io_thread_| with NaClIPCAdapter's
  // |lock_| not being held.
  DCHECK(!cb.is_null());
  auto it = prefetched_resource_files_.find(key);

  if (it != prefetched_resource_files_.end()) {
    // Fast path for prefetched FDs.
    IPC::PlatformFileForTransit file = it->second.first;
    base::FilePath path = it->second.second;
    prefetched_resource_files_.erase(it);
    // A pre-opened resource descriptor is available. Run the reply callback
    // and return true.
    std::move(cb).Run(msg, file, path);
    return true;
  }

  // Return false to fall back to the slow path. Let NaClIPCAdapter issue an
  // IPC to the renderer.
  return false;
}

void NaClListener::OnAddPrefetchedResource(
    const nacl::NaClResourcePrefetchResult& prefetched_resource_file) {
  DCHECK(!is_started_);
  if (is_started_)
    return;
  bool result = prefetched_resource_files_.insert(std::make_pair(
      prefetched_resource_file.file_key,
      std::make_pair(
          prefetched_resource_file.file,
          prefetched_resource_file.file_path_metadata))).second;
  if (!result) {
    LOG(FATAL) << "Duplicated open_resource key: "
               << prefetched_resource_file.file_key;
  }
}

void NaClListener::OnStart(nacl::NaClStartParams params) {
  is_started_ = true;
#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
  int urandom_fd = HANDLE_EINTR(dup(base::GetUrandomFD()));
  if (urandom_fd < 0) {
    LOG(FATAL) << "Failed to dup() the urandom FD";
  }
  NaClChromeMainSetUrandomFd(urandom_fd);
#endif
  struct NaClApp* nap = NULL;
  NaClChromeMainInit();

  CHECK(params.crash_info_shmem_region.IsValid());
  crash_info_shmem_mapping_ = params.crash_info_shmem_region.Map();
  base::ReadOnlySharedMemoryRegion ro_shmem_region =
      base::WritableSharedMemoryRegion::ConvertToReadOnly(
          std::move(params.crash_info_shmem_region));
  CHECK(crash_info_shmem_mapping_.IsValid());
  CHECK(ro_shmem_region.IsValid());
  NaClSetFatalErrorCallback(&FatalLogHandler);

  nap = NaClAppCreate();
  if (nap == NULL) {
    LOG(FATAL) << "NaClAppCreate() failed";
  }

  IPC::ChannelHandle browser_handle;
  IPC::ChannelHandle ppapi_renderer_handle;
  IPC::ChannelHandle manifest_service_handle;

  // Create the PPAPI IPC channels between the NaCl IRT and the host
  // (browser/renderer) processes. The IRT uses these channels to
  // communicate with the host and to initialize the IPC dispatchers.
  SetUpIPCAdapter(&browser_handle, io_thread_.task_runner(), nap,
                  NACL_CHROME_DESC_BASE,
                  NaClIPCAdapter::ResolveFileTokenCallback(),
                  NaClIPCAdapter::OpenResourceCallback());
  SetUpIPCAdapter(&ppapi_renderer_handle, io_thread_.task_runner(), nap,
                  NACL_CHROME_DESC_BASE + 1,
                  NaClIPCAdapter::ResolveFileTokenCallback(),
                  NaClIPCAdapter::OpenResourceCallback());
  SetUpIPCAdapter(&manifest_service_handle, io_thread_.task_runner(), nap,
                  NACL_CHROME_DESC_BASE + 2,
                  base::BindRepeating(&NaClListener::ResolveFileToken,
                                      base::Unretained(this)),
                  base::BindRepeating(&NaClListener::OnOpenResource,
                                      base::Unretained(this)));

  mojo::PendingRemote<nacl::mojom::NaClRendererHost> renderer_host;
  if (!Send(new NaClProcessHostMsg_PpapiChannelsCreated(
          browser_handle, ppapi_renderer_handle,
          renderer_host.InitWithNewPipeAndPassReceiver().PassPipe().release(),
          manifest_service_handle, ro_shmem_region)))
    LOG(FATAL) << "Failed to send IPC channel handle to NaClProcessHost.";

  trusted_listener_ = std::make_unique<NaClTrustedListener>(
      std::move(renderer_host), io_thread_.task_runner().get());
  struct NaClChromeMainArgs* args = NaClChromeMainArgsCreate();
  if (args == NULL) {
    LOG(FATAL) << "NaClChromeMainArgsCreate() failed";
  }

#if BUILDFLAG(IS_POSIX)
  args->number_of_cores = number_of_cores_;
#endif

#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
  args->create_memory_object_func = &MakeSharedMemorySegment;
#endif

  DCHECK(params.process_type != nacl::kUnknownNaClProcessType);
  CHECK(params.irt_handle != IPC::InvalidPlatformFileForTransit());
  args->irt_fd = IPC::PlatformFileForTransitToPlatformFile(params.irt_handle);

  if (params.validation_cache_enabled) {
    // SHA256 block size.
    CHECK_EQ(params.validation_cache_key.length(), (size_t) 64);
    // The cache structure is not freed and exists until the NaCl process exits.
    args->validation_cache = CreateValidationCache(
        new BrowserValidationDBProxy(this), params.validation_cache_key,
        params.version);
  }

  args->enable_debug_stub = params.enable_debug_stub;

  // Now configure parts that depend on process type.
  // Start with stricter settings.
  args->enable_exception_handling = 0;
  args->enable_dyncode_syscalls = 0;
  // pnacl_mode=1 mostly disables things (IRT interfaces and syscalls).
  args->pnacl_mode = 1;
  // Bound the initial nexe's code segment size under PNaCl to reduce the
  // chance of a code spraying attack succeeding (see
  // https://code.google.com/p/nativeclient/issues/detail?id=3572).
  // We can't apply this arbitrary limit outside of PNaCl because it might
  // break existing NaCl apps, and this limit is only useful if the dyncode
  // syscalls are disabled.
  args->initial_nexe_max_code_bytes = 64 << 20;  // 64 MB.

  if (params.process_type == nacl::kNativeNaClProcessType) {
    args->enable_exception_handling = 1;
    args->enable_dyncode_syscalls = 1;
    args->pnacl_mode = 0;
    args->initial_nexe_max_code_bytes = 0;
  } else if (params.process_type == nacl::kPNaClTranslatorProcessType) {
    args->pnacl_mode = 0;
  }

#if BUILDFLAG(IS_POSIX)
  args->debug_stub_server_bound_socket_fd =
      IPC::PlatformFileForTransitToPlatformFile(
          params.debug_stub_server_bound_socket);
#endif
  args->load_status_handler_func = LoadStatusCallback;
#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
  args->prereserved_sandbox_size = prereserved_sandbox_size_;
#endif

  base::PlatformFile nexe_file = IPC::PlatformFileForTransitToPlatformFile(
      params.nexe_file);
  std::string file_path_str = params.nexe_file_path_metadata.AsUTF8Unsafe();
  args->nexe_desc = NaClDescCreateWithFilePathMetadata(nexe_file,
                                                       file_path_str.c_str());

  int exit_status;
  if (!NaClChromeMainStart(nap, args, &exit_status))
    NaClExit(1);

  // Report the plugin's exit status if the application started successfully.
  trusted_listener_->renderer_host()->ReportExitStatus(exit_status);
  NaClExit(exit_status);
}

void NaClListener::ResolveFileToken(
    uint64_t token_lo,
    uint64_t token_hi,
    NaClIPCAdapter::ResolveFileTokenReplyCallback cb) {
  if (!Send(new NaClProcessMsg_ResolveFileToken(token_lo, token_hi))) {
    std::move(cb).Run(IPC::PlatformFileForTransit(), base::FilePath());
    return;
  }
  resolved_cb_ = std::move(cb);
}

void NaClListener::OnFileTokenResolved(
    uint64_t token_lo,
    uint64_t token_hi,
    IPC::PlatformFileForTransit ipc_fd,
    base::FilePath file_path) {
  if (resolved_cb_)
    std::move(resolved_cb_).Run(ipc_fd, file_path);
}