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 // A mini-zygote specifically for Native Client.
7 #include "components/nacl/loader/nacl_helper_linux.h"
14 #include <sys/socket.h>
16 #include <sys/types.h>
21 #include "base/at_exit.h"
22 #include "base/command_line.h"
23 #include "base/files/scoped_file.h"
24 #include "base/logging.h"
25 #include "base/memory/scoped_ptr.h"
26 #include "base/memory/scoped_vector.h"
27 #include "base/message_loop/message_loop.h"
28 #include "base/posix/eintr_wrapper.h"
29 #include "base/posix/global_descriptors.h"
30 #include "base/posix/unix_domain_socket_linux.h"
31 #include "base/process/kill.h"
32 #include "base/process/process_handle.h"
33 #include "base/rand_util.h"
34 #include "components/nacl/common/nacl_switches.h"
35 #include "components/nacl/loader/nacl_listener.h"
36 #include "components/nacl/loader/nonsfi/nonsfi_listener.h"
37 #include "components/nacl/loader/sandbox_linux/nacl_sandbox_linux.h"
38 #include "content/public/common/content_descriptors.h"
39 #include "content/public/common/send_zygote_child_ping_linux.h"
40 #include "content/public/common/zygote_fork_delegate_linux.h"
41 #include "crypto/nss_util.h"
42 #include "ipc/ipc_descriptors.h"
43 #include "ipc/ipc_switches.h"
44 #include "sandbox/linux/services/libc_urandom_override.h"
46 #if !defined(OS_NACL_NONSFI)
47 #include "third_party/mojo/src/mojo/edk/embedder/embedder.h"
48 #include "third_party/mojo/src/mojo/edk/embedder/simple_platform_support.h"
51 #if defined(OS_NACL_NONSFI)
52 #include "native_client/src/public/nonsfi/irt_exception_handling.h"
55 #include "components/nacl/loader/nonsfi/irt_exception_handling.h"
60 struct NaClLoaderSystemInfo
{
61 size_t prereserved_sandbox_size
;
65 // Replace |file_descriptor| with the reading end of a closed pipe.
66 void ReplaceFDWithDummy(int file_descriptor
) {
67 // Make sure that file_descriptor is an open descriptor.
68 PCHECK(-1 != fcntl(file_descriptor
, F_GETFD
, 0));
70 PCHECK(0 == pipe(pipefd
));
71 PCHECK(-1 != dup2(pipefd
[0], file_descriptor
));
72 PCHECK(0 == IGNORE_EINTR(close(pipefd
[0])));
73 PCHECK(0 == IGNORE_EINTR(close(pipefd
[1])));
76 // The child must mimic the behavior of zygote_main_linux.cc on the child
77 // side of the fork. See zygote_main_linux.cc:HandleForkRequest from
79 void BecomeNaClLoader(base::ScopedFD browser_fd
,
80 const NaClLoaderSystemInfo
& system_info
,
81 bool uses_nonsfi_mode
,
82 nacl::NaClSandbox
* nacl_sandbox
) {
84 VLOG(1) << "NaCl loader: setting up IPC descriptor";
85 // Close or shutdown IPC channels that we don't need anymore.
86 PCHECK(0 == IGNORE_EINTR(close(kNaClZygoteDescriptor
)));
87 // In Non-SFI mode, it's important to close any non-expected IPC channels.
88 if (uses_nonsfi_mode
) {
89 // The low-level kSandboxIPCChannel is used by renderers and NaCl for
90 // various operations. See the LinuxSandbox::METHOD_* methods. NaCl uses
91 // LinuxSandbox::METHOD_MAKE_SHARED_MEMORY_SEGMENT in SFI mode, so this
92 // should only be closed in Non-SFI mode.
93 // This file descriptor is insidiously used by a number of APIs. Closing it
94 // could lead to difficult to debug issues. Instead of closing it, replace
96 const int sandbox_ipc_channel
=
97 base::GlobalDescriptors::kBaseDescriptor
+ kSandboxIPCChannel
;
99 ReplaceFDWithDummy(sandbox_ipc_channel
);
101 // Install crash signal handlers before disallowing system calls.
102 #if defined(OS_NACL_NONSFI)
103 nonsfi_initialize_signal_handler();
105 nacl::nonsfi::InitializeSignalHandler();
109 // Always ignore SIGPIPE, for consistency with other Chrome processes and
110 // because some IPC code, such as sync_socket_posix.cc, requires this.
111 // We do this before seccomp-bpf is initialized.
112 PCHECK(signal(SIGPIPE
, SIG_IGN
) != SIG_ERR
);
114 // Finish layer-1 sandbox initialization and initialize the layer-2 sandbox.
115 CHECK(!nacl_sandbox
->HasOpenDirectory());
116 #if !defined(OS_NACL_NONSFI)
117 // Currently Layer-two sandbox is not yet supported on nacl_helper_nonsfi.
118 // TODO(hidehiko): Enable the sandbox.
119 nacl_sandbox
->InitializeLayerTwoSandbox(uses_nonsfi_mode
);
121 nacl_sandbox
->SealLayerOneSandbox();
122 nacl_sandbox
->CheckSandboxingStateWithPolicy();
124 base::GlobalDescriptors::GetInstance()->Set(kPrimaryIPCChannel
,
125 browser_fd
.release());
127 base::MessageLoopForIO main_message_loop
;
128 #if defined(OS_NACL_NONSFI)
129 CHECK(uses_nonsfi_mode
);
130 nacl::nonsfi::NonSfiListener listener
;
133 // TODO(hidehiko): Drop Non-SFI supporting from nacl_helper after the
134 // nacl_helper_nonsfi switching is done.
135 if (uses_nonsfi_mode
) {
136 nacl::nonsfi::NonSfiListener listener
;
139 NaClListener listener
;
140 listener
.set_prereserved_sandbox_size(system_info
.prereserved_sandbox_size
);
141 listener
.set_number_of_cores(system_info
.number_of_cores
);
148 // Start the NaCl loader in a child created by the NaCl loader Zygote.
149 void ChildNaClLoaderInit(ScopedVector
<base::ScopedFD
> child_fds
,
150 const NaClLoaderSystemInfo
& system_info
,
151 bool uses_nonsfi_mode
,
152 nacl::NaClSandbox
* nacl_sandbox
,
153 const std::string
& channel_id
) {
154 DCHECK(child_fds
.size() >
155 std::max(content::ZygoteForkDelegate::kPIDOracleFDIndex
,
156 content::ZygoteForkDelegate::kBrowserFDIndex
));
158 // Ping the PID oracle socket.
159 CHECK(content::SendZygoteChildPing(
160 child_fds
[content::ZygoteForkDelegate::kPIDOracleFDIndex
]->get()));
162 base::CommandLine::ForCurrentProcess()->AppendSwitchASCII(
163 switches::kProcessChannelID
, channel_id
);
165 // Save the browser socket and close the rest.
166 base::ScopedFD
browser_fd(
167 child_fds
[content::ZygoteForkDelegate::kBrowserFDIndex
]->Pass());
171 browser_fd
.Pass(), system_info
, uses_nonsfi_mode
, nacl_sandbox
);
175 // Handle a fork request from the Zygote.
176 // Some of this code was lifted from
177 // content/browser/zygote_main_linux.cc:ForkWithRealPid()
178 bool HandleForkRequest(ScopedVector
<base::ScopedFD
> child_fds
,
179 const NaClLoaderSystemInfo
& system_info
,
180 nacl::NaClSandbox
* nacl_sandbox
,
181 PickleIterator
* input_iter
,
182 Pickle
* output_pickle
) {
183 bool uses_nonsfi_mode
;
184 if (!input_iter
->ReadBool(&uses_nonsfi_mode
)) {
185 LOG(ERROR
) << "Could not read uses_nonsfi_mode status";
189 std::string channel_id
;
190 if (!input_iter
->ReadString(&channel_id
)) {
191 LOG(ERROR
) << "Could not read channel_id string";
195 if (content::ZygoteForkDelegate::kNumPassedFDs
!= child_fds
.size()) {
196 LOG(ERROR
) << "nacl_helper: unexpected number of fds, got "
201 VLOG(1) << "nacl_helper: forking";
202 pid_t child_pid
= fork();
204 PLOG(ERROR
) << "*** fork() failed.";
207 if (child_pid
== 0) {
208 ChildNaClLoaderInit(child_fds
.Pass(),
217 // First, close the dummy_fd so the sandbox won't find me when
218 // looking for the child's pid in /proc. Also close other fds.
220 VLOG(1) << "nacl_helper: child_pid is " << child_pid
;
222 // Now send child_pid (eventually -1 if fork failed) to the Chrome Zygote.
223 output_pickle
->WriteInt(child_pid
);
227 bool HandleGetTerminationStatusRequest(PickleIterator
* input_iter
,
228 Pickle
* output_pickle
) {
230 if (!input_iter
->ReadInt(&child_to_wait
)) {
231 LOG(ERROR
) << "Could not read pid to wait for";
236 if (!input_iter
->ReadBool(&known_dead
)) {
237 LOG(ERROR
) << "Could not read known_dead status";
240 // TODO(jln): With NaCl, known_dead seems to never be set to true (unless
241 // called from the Zygote's kZygoteCommandReap command). This means that we
242 // will sometimes detect the process as still running when it's not. Fix
246 base::TerminationStatus status
;
248 status
= base::GetKnownDeadTerminationStatus(child_to_wait
, &exit_code
);
250 status
= base::GetTerminationStatus(child_to_wait
, &exit_code
);
251 output_pickle
->WriteInt(static_cast<int>(status
));
252 output_pickle
->WriteInt(exit_code
);
256 // Honor a command |command_type|. Eventual command parameters are
257 // available in |input_iter| and eventual file descriptors attached to
258 // the command are in |attached_fds|.
259 // Reply to the command on |reply_fds|.
260 bool HonorRequestAndReply(int reply_fd
,
262 ScopedVector
<base::ScopedFD
> attached_fds
,
263 const NaClLoaderSystemInfo
& system_info
,
264 nacl::NaClSandbox
* nacl_sandbox
,
265 PickleIterator
* input_iter
) {
267 bool have_to_reply
= false;
268 // Commands must write anything to send back to |write_pickle|.
269 switch (command_type
) {
270 case nacl::kNaClForkRequest
:
271 have_to_reply
= HandleForkRequest(attached_fds
.Pass(),
277 case nacl::kNaClGetTerminationStatusRequest
:
279 HandleGetTerminationStatusRequest(input_iter
, &write_pickle
);
282 LOG(ERROR
) << "Unsupported command from Zygote";
287 const std::vector
<int> empty
; // We never send file descriptors back.
288 if (!UnixDomainSocket::SendMsg(reply_fd
, write_pickle
.data(),
289 write_pickle
.size(), empty
)) {
290 LOG(ERROR
) << "*** send() to zygote failed";
296 // Read a request from the Zygote from |zygote_ipc_fd| and handle it.
297 // Die on EOF from |zygote_ipc_fd|.
298 bool HandleZygoteRequest(int zygote_ipc_fd
,
299 const NaClLoaderSystemInfo
& system_info
,
300 nacl::NaClSandbox
* nacl_sandbox
) {
301 ScopedVector
<base::ScopedFD
> fds
;
302 char buf
[kNaClMaxIPCMessageLength
];
303 const ssize_t msglen
= UnixDomainSocket::RecvMsg(zygote_ipc_fd
,
304 &buf
, sizeof(buf
), &fds
);
305 // If the Zygote has started handling requests, we should be sandboxed via
306 // the setuid sandbox.
307 if (!nacl_sandbox
->layer_one_enabled()) {
308 LOG(ERROR
) << "NaCl helper process running without a sandbox!\n"
309 << "Most likely you need to configure your SUID sandbox "
312 if (msglen
== 0 || (msglen
== -1 && errno
== ECONNRESET
)) {
313 // EOF from the browser. Goodbye!
317 PLOG(ERROR
) << "nacl_helper: receive from zygote failed";
321 Pickle
read_pickle(buf
, msglen
);
322 PickleIterator
read_iter(read_pickle
);
324 if (!read_iter
.ReadInt(&command_type
)) {
325 LOG(ERROR
) << "Unable to read command from Zygote";
328 return HonorRequestAndReply(zygote_ipc_fd
,
336 #if !defined(OS_NACL_NONSFI)
337 static const char kNaClHelperReservedAtZero
[] = "reserved_at_zero";
338 static const char kNaClHelperRDebug
[] = "r_debug";
340 // Since we were started by nacl_helper_bootstrap rather than in the
341 // usual way, the debugger cannot figure out where our executable
342 // or the dynamic linker or the shared libraries are in memory,
343 // so it won't find any symbols. But we can fake it out to find us.
345 // The zygote passes --r_debug=0xXXXXXXXXXXXXXXXX.
346 // nacl_helper_bootstrap replaces the Xs with the address of its _r_debug
347 // structure. The debugger will look for that symbol by name to
348 // discover the addresses of key dynamic linker data structures.
349 // Since all it knows about is the original main executable, which
350 // is the bootstrap program, it finds the symbol defined there. The
351 // dynamic linker's structure is somewhere else, but it is filled in
352 // after initialization. The parts that really matter to the
353 // debugger never change. So we just copy the contents of the
354 // dynamic linker's structure into the address provided by the option.
355 // Hereafter, if someone attaches a debugger (or examines a core dump),
356 // the debugger will find all the symbols in the normal way.
358 // Non-SFI mode does not use nacl_helper_bootstrap, so it doesn't need to
359 // process the --r_debug option.
360 static void CheckRDebug(char* argv0
) {
361 std::string r_debug_switch_value
=
362 base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
364 if (!r_debug_switch_value
.empty()) {
366 uintptr_t r_debug_addr
= strtoul(r_debug_switch_value
.c_str(), &endp
, 0);
367 if (r_debug_addr
!= 0 && *endp
== '\0') {
368 r_debug
* bootstrap_r_debug
= reinterpret_cast<r_debug
*>(r_debug_addr
);
369 *bootstrap_r_debug
= _r_debug
;
371 // Since the main executable (the bootstrap program) does not
372 // have a dynamic section, the debugger will not skip the
373 // first element of the link_map list as it usually would for
374 // an executable or PIE that was loaded normally. But the
375 // dynamic linker has set l_name for the PIE to "" as is
376 // normal for the main executable. So the debugger doesn't
377 // know which file it is. Fill in the actual file name, which
378 // came in as our argv[0].
379 link_map
* l
= _r_debug
.r_map
;
380 if (l
->l_name
[0] == '\0')
386 // The zygote passes --reserved_at_zero=0xXXXXXXXXXXXXXXXX.
387 // nacl_helper_bootstrap replaces the Xs with the amount of prereserved
390 // CheckReservedAtZero parses the value of the argument reserved_at_zero
391 // and returns the amount of prereserved sandbox memory.
392 static size_t CheckReservedAtZero() {
393 size_t prereserved_sandbox_size
= 0;
394 std::string reserved_at_zero_switch_value
=
395 base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
396 kNaClHelperReservedAtZero
);
397 if (!reserved_at_zero_switch_value
.empty()) {
399 prereserved_sandbox_size
=
400 strtoul(reserved_at_zero_switch_value
.c_str(), &endp
, 0);
402 LOG(ERROR
) << "Could not parse reserved_at_zero argument value of "
403 << reserved_at_zero_switch_value
;
405 return prereserved_sandbox_size
;
411 #if defined(ADDRESS_SANITIZER)
412 // Do not install the SIGSEGV handler in ASan. This should make the NaCl
413 // platform qualification test pass.
414 // detect_odr_violation=0: http://crbug.com/376306
415 static const char kAsanDefaultOptionsNaCl
[] =
416 "handle_segv=0:detect_odr_violation=0";
418 // Override the default ASan options for the NaCl helper.
419 // __asan_default_options should not be instrumented, because it is called
420 // before ASan is initialized.
422 __attribute__((no_sanitize_address
))
423 // The function isn't referenced from the executable itself. Make sure it isn't
424 // stripped by the linker.
425 __attribute__((used
))
426 __attribute__((visibility("default")))
427 const char* __asan_default_options() {
428 return kAsanDefaultOptionsNaCl
;
432 int main(int argc
, char* argv
[]) {
433 base::CommandLine::Init(argc
, argv
);
434 base::AtExitManager exit_manager
;
435 base::RandUint64(); // acquire /dev/urandom fd before sandbox is raised
437 #if !defined(OS_NACL_NONSFI)
438 // NSS is only needed for SFI NaCl.
439 // Allows NSS to fopen() /dev/urandom.
440 sandbox::InitLibcUrandomOverrides();
442 // Configure NSS for use inside the NaCl process.
443 // The fork check has not caused problems for NaCl, but this appears to be
444 // best practice (see other places LoadNSSLibraries is called.)
445 crypto::DisableNSSForkCheck();
446 // Without this line on Linux, HMAC::Init will instantiate a singleton that
447 // in turn attempts to open a file. Disabling this behavior avoids a ~70 ms
448 // stall the first time HMAC is used.
449 crypto::ForceNSSNoDBInit();
450 // Load shared libraries before sandbox is raised.
451 // NSS is needed to perform hashing for validation caching.
452 crypto::LoadNSSLibraries();
453 #endif // defined(USE_NSS)
454 #endif // defined(OS_NACL_NONSFI)
455 const NaClLoaderSystemInfo system_info
= {
456 #if !defined(OS_NACL_NONSFI)
457 // These are not used by nacl_helper_nonsfi.
458 CheckReservedAtZero(),
459 sysconf(_SC_NPROCESSORS_ONLN
)
463 #if !defined(OS_NACL_NONSFI)
464 CheckRDebug(argv
[0]);
467 // TODO(teravest): Enable mojo for nonsfi. http://crbug.com/473418
468 #if !defined(OS_NACL_NONSFI)
469 mojo::embedder::Init(
470 make_scoped_ptr(new mojo::embedder::SimplePlatformSupport()));
473 scoped_ptr
<nacl::NaClSandbox
> nacl_sandbox(new nacl::NaClSandbox
);
474 // Make sure that the early initialization did not start any spurious
476 #if !defined(THREAD_SANITIZER)
477 CHECK(nacl_sandbox
->IsSingleThreaded());
480 const bool is_init_process
= 1 == getpid();
481 nacl_sandbox
->InitializeLayerOneSandbox();
482 CHECK_EQ(is_init_process
, nacl_sandbox
->layer_one_enabled());
484 const std::vector
<int> empty
;
485 // Send the zygote a message to let it know we are ready to help
486 if (!UnixDomainSocket::SendMsg(kNaClZygoteDescriptor
,
487 kNaClHelperStartupAck
,
488 sizeof(kNaClHelperStartupAck
), empty
)) {
489 LOG(ERROR
) << "*** send() to zygote failed";
492 // Now handle requests from the Zygote.
494 bool request_handled
= HandleZygoteRequest(
495 kNaClZygoteDescriptor
, system_info
, nacl_sandbox
.get());
496 // Do not turn this into a CHECK() without thinking about robustness
497 // against malicious IPC requests.
498 DCHECK(request_handled
);