1 // Copyright 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "components/nacl/loader/nacl_listener.h"
16 #include "base/command_line.h"
17 #include "base/logging.h"
18 #include "base/memory/scoped_ptr.h"
19 #include "base/message_loop/message_loop.h"
20 #include "base/rand_util.h"
21 #include "components/nacl/common/nacl_messages.h"
22 #include "components/nacl/common/nacl_renderer_messages.h"
23 #include "components/nacl/common/nacl_switches.h"
24 #include "components/nacl/loader/nacl_ipc_adapter.h"
25 #include "components/nacl/loader/nacl_validation_db.h"
26 #include "components/nacl/loader/nacl_validation_query.h"
27 #include "ipc/ipc_channel_handle.h"
28 #include "ipc/ipc_switches.h"
29 #include "ipc/ipc_sync_channel.h"
30 #include "ipc/ipc_sync_message_filter.h"
31 #include "mojo/nacl/mojo_syscall.h"
32 #include "native_client/src/public/chrome_main.h"
33 #include "native_client/src/public/nacl_app.h"
34 #include "native_client/src/public/nacl_desc.h"
35 #include "third_party/mojo/src/mojo/edk/embedder/embedder.h"
36 #include "third_party/mojo/src/mojo/edk/embedder/platform_support.h"
37 #include "third_party/mojo/src/mojo/edk/embedder/simple_platform_support.h"
40 #include "base/file_descriptor_posix.h"
44 #include "content/public/common/child_process_sandbox_support_linux.h"
50 #include "content/public/common/sandbox_init.h"
55 NaClListener
* g_listener
;
57 void FatalLogHandler(const char* data
, size_t bytes
) {
58 // We use uint32_t rather than size_t for the case when the browser and NaCl
59 // processes are a mix of 32-bit and 64-bit processes.
60 uint32_t copy_bytes
= std::min
<uint32_t>(static_cast<uint32_t>(bytes
),
61 nacl::kNaClCrashInfoMaxLogSize
);
63 // We copy the length of the crash data to the start of the shared memory
64 // segment so we know how much to copy.
65 memcpy(g_listener
->crash_info_shmem_memory(), ©_bytes
, sizeof(uint32_t));
67 memcpy((char*)g_listener
->crash_info_shmem_memory() + sizeof(uint32_t),
72 #if defined(OS_MACOSX)
74 // On Mac OS X, shm_open() works in the sandbox but does not give us
75 // an FD that we can map as PROT_EXEC. Rather than doing an IPC to
76 // get an executable SHM region when CreateMemoryObject() is called,
77 // we preallocate one on startup, since NaCl's sel_ldr only needs one
78 // of them. This saves a round trip.
80 base::subtle::Atomic32 g_shm_fd
= -1;
82 int CreateMemoryObject(size_t size
, int executable
) {
83 if (executable
&& size
> 0) {
84 int result_fd
= base::subtle::NoBarrier_AtomicExchange(&g_shm_fd
, -1);
85 if (result_fd
!= -1) {
86 // ftruncate() is disallowed by the Mac OS X sandbox and
87 // returns EPERM. Luckily, we can get the same effect with
89 if (lseek(result_fd
, size
- 1, SEEK_SET
) == -1) {
90 LOG(ERROR
) << "lseek() failed: " << errno
;
93 if (write(result_fd
, "", 1) != 1) {
94 LOG(ERROR
) << "write() failed: " << errno
;
100 // Fall back to NaCl's default implementation.
104 #elif defined(OS_LINUX)
106 int CreateMemoryObject(size_t size
, int executable
) {
107 return content::MakeSharedMemorySegmentViaIPC(size
, executable
);
110 #elif defined(OS_WIN)
111 // We wrap the function to convert the bool return value to an int.
112 int BrokerDuplicateHandle(NaClHandle source_handle
,
114 NaClHandle
* target_handle
,
115 uint32_t desired_access
,
117 return content::BrokerDuplicateHandle(source_handle
, process_id
,
118 target_handle
, desired_access
,
122 int AttachDebugExceptionHandler(const void* info
, size_t info_size
) {
123 std::string
info_string(reinterpret_cast<const char*>(info
), info_size
);
125 if (!g_listener
->Send(new NaClProcessMsg_AttachDebugExceptionHandler(
126 info_string
, &result
)))
131 void DebugStubPortSelectedHandler(uint16_t port
) {
132 g_listener
->Send(new NaClProcessHostMsg_DebugStubPortSelected(port
));
137 // Creates the PPAPI IPC channel between the NaCl IRT and the host
138 // (browser/renderer) process, and starts to listen it on the thread where
139 // the given message_loop_proxy runs.
140 // Also, creates and sets the corresponding NaClDesc to the given nap with
142 scoped_refptr
<NaClIPCAdapter
> SetUpIPCAdapter(
143 IPC::ChannelHandle
* handle
,
144 scoped_refptr
<base::MessageLoopProxy
> message_loop_proxy
,
147 scoped_refptr
<NaClIPCAdapter
> ipc_adapter(
148 new NaClIPCAdapter(*handle
, message_loop_proxy
.get()));
149 ipc_adapter
->ConnectChannel();
150 #if defined(OS_POSIX)
152 base::FileDescriptor(ipc_adapter
->TakeClientFileDescriptor());
155 // Pass a NaClDesc to the untrusted side. This will hold a ref to the
157 NaClAppSetDesc(nap
, nacl_fd
, ipc_adapter
->MakeNaClDesc());
163 class BrowserValidationDBProxy
: public NaClValidationDB
{
165 explicit BrowserValidationDBProxy(NaClListener
* listener
)
166 : listener_(listener
) {
169 bool QueryKnownToValidate(const std::string
& signature
) override
{
170 // Initialize to false so that if the Send fails to write to the return
171 // value we're safe. For example if the message is (for some reason)
172 // dispatched as an async message the return parameter will not be written.
174 if (!listener_
->Send(new NaClProcessMsg_QueryKnownToValidate(signature
,
176 LOG(ERROR
) << "Failed to query NaCl validation cache.";
182 void SetKnownToValidate(const std::string
& signature
) override
{
183 // Caching is optional: NaCl will still work correctly if the IPC fails.
184 if (!listener_
->Send(new NaClProcessMsg_SetKnownToValidate(signature
))) {
185 LOG(ERROR
) << "Failed to update NaCl validation cache.";
190 // The listener never dies, otherwise this might be a dangling reference.
191 NaClListener
* listener_
;
195 NaClListener::NaClListener() : shutdown_event_(true, false),
196 io_thread_("NaCl_IOThread"),
197 #if defined(OS_LINUX)
198 prereserved_sandbox_size_(0),
200 #if defined(OS_POSIX)
201 number_of_cores_(-1), // unknown/error
204 io_thread_
.StartWithOptions(
205 base::Thread::Options(base::MessageLoop::TYPE_IO
, 0));
206 DCHECK(g_listener
== NULL
);
210 NaClListener::~NaClListener() {
212 shutdown_event_
.Signal();
216 bool NaClListener::Send(IPC::Message
* msg
) {
217 DCHECK(main_loop_
!= NULL
);
218 if (base::MessageLoop::current() == main_loop_
) {
219 // This thread owns the channel.
220 return channel_
->Send(msg
);
222 // This thread does not own the channel.
223 return filter_
->Send(msg
);
227 // The NaClProcessMsg_ResolveFileTokenAsyncReply message must be
228 // processed in a MessageFilter so it can be handled on the IO thread.
229 // The main thread used by NaClListener is busy in
230 // NaClChromeMainAppStart(), so it can't be used for servicing messages.
231 class FileTokenMessageFilter
: public IPC::MessageFilter
{
233 bool OnMessageReceived(const IPC::Message
& msg
) override
{
235 IPC_BEGIN_MESSAGE_MAP(FileTokenMessageFilter
, msg
)
236 IPC_MESSAGE_HANDLER(NaClProcessMsg_ResolveFileTokenReply
,
237 OnResolveFileTokenReply
)
238 IPC_MESSAGE_UNHANDLED(handled
= false)
239 IPC_END_MESSAGE_MAP()
243 void OnResolveFileTokenReply(
246 IPC::PlatformFileForTransit ipc_fd
,
247 base::FilePath file_path
) {
249 g_listener
->OnFileTokenResolved(token_lo
, token_hi
, ipc_fd
, file_path
);
252 ~FileTokenMessageFilter() override
{}
255 void NaClListener::Listen() {
256 std::string channel_name
=
257 base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
258 switches::kProcessChannelID
);
259 channel_
= IPC::SyncChannel::Create(
260 this, io_thread_
.message_loop_proxy().get(), &shutdown_event_
);
261 filter_
= new IPC::SyncMessageFilter(&shutdown_event_
);
262 channel_
->AddFilter(filter_
.get());
263 channel_
->AddFilter(new FileTokenMessageFilter());
264 channel_
->Init(channel_name
, IPC::Channel::MODE_CLIENT
, true);
265 main_loop_
= base::MessageLoop::current();
269 bool NaClListener::OnMessageReceived(const IPC::Message
& msg
) {
271 IPC_BEGIN_MESSAGE_MAP(NaClListener
, msg
)
272 IPC_MESSAGE_HANDLER(NaClProcessMsg_Start
, OnStart
)
273 IPC_MESSAGE_UNHANDLED(handled
= false)
274 IPC_END_MESSAGE_MAP()
278 void NaClListener::OnStart(const nacl::NaClStartParams
& params
) {
279 #if defined(OS_LINUX) || defined(OS_MACOSX)
280 int urandom_fd
= dup(base::GetUrandomFD());
281 if (urandom_fd
< 0) {
282 LOG(ERROR
) << "Failed to dup() the urandom FD";
285 NaClChromeMainSetUrandomFd(urandom_fd
);
287 struct NaClApp
* nap
= NULL
;
288 NaClChromeMainInit();
290 crash_info_shmem_
.reset(new base::SharedMemory(params
.crash_info_shmem_handle
,
292 CHECK(crash_info_shmem_
->Map(nacl::kNaClCrashInfoShmemSize
));
293 NaClSetFatalErrorCallback(&FatalLogHandler
);
295 nap
= NaClAppCreate();
297 LOG(ERROR
) << "NaClAppCreate() failed";
301 IPC::ChannelHandle browser_handle
;
302 IPC::ChannelHandle ppapi_renderer_handle
;
303 IPC::ChannelHandle manifest_service_handle
;
305 if (params
.enable_ipc_proxy
) {
306 browser_handle
= IPC::Channel::GenerateVerifiedChannelID("nacl");
307 ppapi_renderer_handle
= IPC::Channel::GenerateVerifiedChannelID("nacl");
308 manifest_service_handle
= IPC::Channel::GenerateVerifiedChannelID("nacl");
310 // Create the PPAPI IPC channels between the NaCl IRT and the host
311 // (browser/renderer) processes. The IRT uses these channels to
312 // communicate with the host and to initialize the IPC dispatchers.
313 SetUpIPCAdapter(&browser_handle
, io_thread_
.message_loop_proxy(),
314 nap
, NACL_CHROME_DESC_BASE
);
315 SetUpIPCAdapter(&ppapi_renderer_handle
, io_thread_
.message_loop_proxy(),
316 nap
, NACL_CHROME_DESC_BASE
+ 1);
318 scoped_refptr
<NaClIPCAdapter
> manifest_ipc_adapter
=
319 SetUpIPCAdapter(&manifest_service_handle
,
320 io_thread_
.message_loop_proxy(),
322 NACL_CHROME_DESC_BASE
+ 2);
323 manifest_ipc_adapter
->set_resolve_file_token_callback(
324 base::Bind(&NaClListener::ResolveFileToken
, base::Unretained(this)));
327 trusted_listener_
= new NaClTrustedListener(
328 IPC::Channel::GenerateVerifiedChannelID("nacl"),
329 io_thread_
.message_loop_proxy().get(),
331 if (!Send(new NaClProcessHostMsg_PpapiChannelsCreated(
333 ppapi_renderer_handle
,
334 trusted_listener_
->TakeClientChannelHandle(),
335 manifest_service_handle
)))
336 LOG(ERROR
) << "Failed to send IPC channel handle to NaClProcessHost.";
338 std::vector
<nacl::FileDescriptor
> handles
= params
.handles
;
339 struct NaClChromeMainArgs
* args
= NaClChromeMainArgsCreate();
341 LOG(ERROR
) << "NaClChromeMainArgsCreate() failed";
345 #if defined(OS_LINUX) || defined(OS_MACOSX)
346 args
->number_of_cores
= number_of_cores_
;
347 args
->create_memory_object_func
= CreateMemoryObject
;
348 # if defined(OS_MACOSX)
349 CHECK(handles
.size() >= 1);
350 g_shm_fd
= nacl::ToNativeHandle(handles
[handles
.size() - 1]);
355 DCHECK(params
.process_type
!= nacl::kUnknownNaClProcessType
);
356 CHECK(handles
.size() >= 1);
357 NaClHandle irt_handle
= nacl::ToNativeHandle(handles
[handles
.size() - 1]);
361 args
->irt_fd
= _open_osfhandle(reinterpret_cast<intptr_t>(irt_handle
),
362 _O_RDONLY
| _O_BINARY
);
363 if (args
->irt_fd
< 0) {
364 LOG(ERROR
) << "_open_osfhandle() failed";
368 args
->irt_fd
= irt_handle
;
371 if (params
.validation_cache_enabled
) {
372 // SHA256 block size.
373 CHECK_EQ(params
.validation_cache_key
.length(), (size_t) 64);
374 // The cache structure is not freed and exists until the NaCl process exits.
375 args
->validation_cache
= CreateValidationCache(
376 new BrowserValidationDBProxy(this), params
.validation_cache_key
,
380 CHECK(handles
.size() == 1);
381 args
->imc_bootstrap_handle
= nacl::ToNativeHandle(handles
[0]);
382 args
->enable_debug_stub
= params
.enable_debug_stub
;
384 // Now configure parts that depend on process type.
385 // Start with stricter settings.
386 args
->enable_exception_handling
= 0;
387 args
->enable_dyncode_syscalls
= 0;
388 // pnacl_mode=1 mostly disables things (IRT interfaces and syscalls).
389 args
->pnacl_mode
= 1;
390 // Bound the initial nexe's code segment size under PNaCl to reduce the
391 // chance of a code spraying attack succeeding (see
392 // https://code.google.com/p/nativeclient/issues/detail?id=3572).
393 // We can't apply this arbitrary limit outside of PNaCl because it might
394 // break existing NaCl apps, and this limit is only useful if the dyncode
395 // syscalls are disabled.
396 args
->initial_nexe_max_code_bytes
= 64 << 20; // 64 MB.
398 if (params
.process_type
== nacl::kNativeNaClProcessType
) {
399 args
->enable_exception_handling
= 1;
400 args
->enable_dyncode_syscalls
= 1;
401 args
->pnacl_mode
= 0;
402 args
->initial_nexe_max_code_bytes
= 0;
403 } else if (params
.process_type
== nacl::kPNaClTranslatorProcessType
) {
404 // Transitioning the PNaCl translators to use the IRT again:
405 // https://code.google.com/p/nativeclient/issues/detail?id=3914.
406 // Once done, this can be removed.
407 args
->irt_load_optional
= 1;
408 args
->pnacl_mode
= 0;
411 #if defined(OS_LINUX) || defined(OS_MACOSX)
412 args
->debug_stub_server_bound_socket_fd
= nacl::ToNativeHandle(
413 params
.debug_stub_server_bound_socket
);
416 args
->broker_duplicate_handle_func
= BrokerDuplicateHandle
;
417 args
->attach_debug_exception_handler_func
= AttachDebugExceptionHandler
;
418 args
->debug_stub_server_port_selected_handler_func
=
419 DebugStubPortSelectedHandler
;
421 #if defined(OS_LINUX)
422 args
->prereserved_sandbox_size
= prereserved_sandbox_size_
;
425 base::PlatformFile nexe_file
= IPC::PlatformFileForTransitToPlatformFile(
427 std::string file_path_str
= params
.nexe_file_path_metadata
.AsUTF8Unsafe();
428 args
->nexe_desc
= NaClDescCreateWithFilePathMetadata(nexe_file
,
429 file_path_str
.c_str());
431 #if defined(OS_POSIX)
432 if (params
.enable_mojo
) {
433 #if !defined(OS_MACOSX)
434 // Don't call mojo::embedder::Init on Mac; it's already been called from
435 // ChromeMain() (see chrome/app/chrome_exe_main_mac.cc).
436 mojo::embedder::Init(make_scoped_ptr(
437 new mojo::embedder::SimplePlatformSupport()));
439 // InjectMojo adds a file descriptor to the process that allows Mojo calls
440 // to use an implementation defined outside the NaCl sandbox. See
441 // //mojo/nacl for implementation details.
444 // When Mojo isn't enabled, we inject a file descriptor that intentionally
445 // fails on any imc_sendmsg() call to make debugging easier.
446 InjectDisabledMojo(nap
);
449 InjectDisabledMojo(nap
);
453 if (!NaClChromeMainStart(nap
, args
, &exit_status
))
456 // Report the plugin's exit status if the application started successfully.
457 trusted_listener_
->Send(new NaClRendererMsg_ReportExitStatus(exit_status
));
458 NaClExit(exit_status
);
461 void NaClListener::ResolveFileToken(
464 base::Callback
<void(IPC::PlatformFileForTransit
, base::FilePath
)> cb
) {
465 if (!Send(new NaClProcessMsg_ResolveFileToken(token_lo
, token_hi
))) {
466 cb
.Run(IPC::PlatformFileForTransit(), base::FilePath());
472 void NaClListener::OnFileTokenResolved(
475 IPC::PlatformFileForTransit ipc_fd
,
476 base::FilePath file_path
) {
477 resolved_cb_
.Run(ipc_fd
, file_path
);
478 resolved_cb_
.Reset();