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/credentials.h"
45 #include "sandbox/linux/services/namespace_sandbox.h"
47 #if defined(OS_NACL_NONSFI)
48 #include "native_client/src/public/nonsfi/irt_exception_handling.h"
51 #include "components/nacl/loader/nonsfi/irt_exception_handling.h"
54 #if !defined(USE_OPENSSL)
55 #include "sandbox/linux/services/libc_urandom_override.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 nacl_sandbox
->InitializeLayerTwoSandbox(uses_nonsfi_mode
);
117 nacl_sandbox
->SealLayerOneSandbox();
118 nacl_sandbox
->CheckSandboxingStateWithPolicy();
120 base::GlobalDescriptors::GetInstance()->Set(kPrimaryIPCChannel
,
121 browser_fd
.release());
123 base::MessageLoopForIO main_message_loop
;
124 #if defined(OS_NACL_NONSFI)
125 CHECK(uses_nonsfi_mode
);
126 nacl::nonsfi::NonSfiListener listener
;
129 CHECK(!uses_nonsfi_mode
);
130 NaClListener listener
;
131 listener
.set_prereserved_sandbox_size(system_info
.prereserved_sandbox_size
);
132 listener
.set_number_of_cores(system_info
.number_of_cores
);
138 // Start the NaCl loader in a child created by the NaCl loader Zygote.
139 void ChildNaClLoaderInit(ScopedVector
<base::ScopedFD
> child_fds
,
140 const NaClLoaderSystemInfo
& system_info
,
141 bool uses_nonsfi_mode
,
142 nacl::NaClSandbox
* nacl_sandbox
,
143 const std::string
& channel_id
) {
144 DCHECK(child_fds
.size() >
145 std::max(content::ZygoteForkDelegate::kPIDOracleFDIndex
,
146 content::ZygoteForkDelegate::kBrowserFDIndex
));
148 // Ping the PID oracle socket.
149 CHECK(content::SendZygoteChildPing(
150 child_fds
[content::ZygoteForkDelegate::kPIDOracleFDIndex
]->get()));
152 base::CommandLine::ForCurrentProcess()->AppendSwitchASCII(
153 switches::kProcessChannelID
, channel_id
);
155 // Save the browser socket and close the rest.
156 base::ScopedFD
browser_fd(
157 child_fds
[content::ZygoteForkDelegate::kBrowserFDIndex
]->Pass());
161 browser_fd
.Pass(), system_info
, uses_nonsfi_mode
, nacl_sandbox
);
165 // Handle a fork request from the Zygote.
166 // Some of this code was lifted from
167 // content/browser/zygote_main_linux.cc:ForkWithRealPid()
168 bool HandleForkRequest(ScopedVector
<base::ScopedFD
> child_fds
,
169 const NaClLoaderSystemInfo
& system_info
,
170 nacl::NaClSandbox
* nacl_sandbox
,
171 base::PickleIterator
* input_iter
,
172 base::Pickle
* output_pickle
) {
173 bool uses_nonsfi_mode
;
174 if (!input_iter
->ReadBool(&uses_nonsfi_mode
)) {
175 LOG(ERROR
) << "Could not read uses_nonsfi_mode status";
179 std::string channel_id
;
180 if (!input_iter
->ReadString(&channel_id
)) {
181 LOG(ERROR
) << "Could not read channel_id string";
185 if (content::ZygoteForkDelegate::kNumPassedFDs
!= child_fds
.size()) {
186 LOG(ERROR
) << "nacl_helper: unexpected number of fds, got "
191 VLOG(1) << "nacl_helper: forking";
193 if (sandbox::NamespaceSandbox::InNewUserNamespace()) {
194 child_pid
= sandbox::NamespaceSandbox::ForkInNewPidNamespace(
195 /*drop_capabilities_in_child=*/true);
197 child_pid
= sandbox::Credentials::ForkAndDropCapabilitiesInChild();
201 PLOG(ERROR
) << "*** fork() failed.";
204 if (child_pid
== 0) {
205 // Install termiantion signal handlers for nonsfi NaCl. The SFI NaCl runtime
206 // will install signal handlers for SIGINT, SIGTERM, etc. so we do not need
207 // to install termination signal handlers ourselves (in fact, it will crash
208 // if signal handlers for these are present).
209 if (uses_nonsfi_mode
&& getpid() == 1) {
210 // Note that nonsfi NaCl may override some of these signal handlers, which
212 sandbox::NamespaceSandbox::InstallDefaultTerminationSignalHandlers();
214 ChildNaClLoaderInit(child_fds
.Pass(),
223 // First, close the dummy_fd so the sandbox won't find me when
224 // looking for the child's pid in /proc. Also close other fds.
226 VLOG(1) << "nacl_helper: child_pid is " << child_pid
;
228 // Now send child_pid (eventually -1 if fork failed) to the Chrome Zygote.
229 output_pickle
->WriteInt(child_pid
);
233 bool HandleGetTerminationStatusRequest(base::PickleIterator
* input_iter
,
234 base::Pickle
* output_pickle
) {
236 if (!input_iter
->ReadInt(&child_to_wait
)) {
237 LOG(ERROR
) << "Could not read pid to wait for";
242 if (!input_iter
->ReadBool(&known_dead
)) {
243 LOG(ERROR
) << "Could not read known_dead status";
246 // TODO(jln): With NaCl, known_dead seems to never be set to true (unless
247 // called from the Zygote's kZygoteCommandReap command). This means that we
248 // will sometimes detect the process as still running when it's not. Fix
252 base::TerminationStatus status
;
254 status
= base::GetKnownDeadTerminationStatus(child_to_wait
, &exit_code
);
256 status
= base::GetTerminationStatus(child_to_wait
, &exit_code
);
257 output_pickle
->WriteInt(static_cast<int>(status
));
258 output_pickle
->WriteInt(exit_code
);
262 // Honor a command |command_type|. Eventual command parameters are
263 // available in |input_iter| and eventual file descriptors attached to
264 // the command are in |attached_fds|.
265 // Reply to the command on |reply_fds|.
266 bool HonorRequestAndReply(int reply_fd
,
268 ScopedVector
<base::ScopedFD
> attached_fds
,
269 const NaClLoaderSystemInfo
& system_info
,
270 nacl::NaClSandbox
* nacl_sandbox
,
271 base::PickleIterator
* input_iter
) {
272 base::Pickle write_pickle
;
273 bool have_to_reply
= false;
274 // Commands must write anything to send back to |write_pickle|.
275 switch (command_type
) {
276 case nacl::kNaClForkRequest
:
277 have_to_reply
= HandleForkRequest(attached_fds
.Pass(),
283 case nacl::kNaClGetTerminationStatusRequest
:
285 HandleGetTerminationStatusRequest(input_iter
, &write_pickle
);
288 LOG(ERROR
) << "Unsupported command from Zygote";
293 const std::vector
<int> empty
; // We never send file descriptors back.
294 if (!base::UnixDomainSocket::SendMsg(reply_fd
, write_pickle
.data(),
295 write_pickle
.size(), empty
)) {
296 LOG(ERROR
) << "*** send() to zygote failed";
302 // Read a request from the Zygote from |zygote_ipc_fd| and handle it.
303 // Die on EOF from |zygote_ipc_fd|.
304 bool HandleZygoteRequest(int zygote_ipc_fd
,
305 const NaClLoaderSystemInfo
& system_info
,
306 nacl::NaClSandbox
* nacl_sandbox
) {
307 ScopedVector
<base::ScopedFD
> fds
;
308 char buf
[kNaClMaxIPCMessageLength
];
309 const ssize_t msglen
= base::UnixDomainSocket::RecvMsg(zygote_ipc_fd
,
310 &buf
, sizeof(buf
), &fds
);
311 // If the Zygote has started handling requests, we should be sandboxed via
312 // the setuid sandbox.
313 if (!nacl_sandbox
->layer_one_enabled()) {
314 LOG(ERROR
) << "NaCl helper process running without a sandbox!\n"
315 << "Most likely you need to configure your SUID sandbox "
318 if (msglen
== 0 || (msglen
== -1 && errno
== ECONNRESET
)) {
319 // EOF from the browser. Goodbye!
323 PLOG(ERROR
) << "nacl_helper: receive from zygote failed";
327 base::Pickle
read_pickle(buf
, msglen
);
328 base::PickleIterator
read_iter(read_pickle
);
330 if (!read_iter
.ReadInt(&command_type
)) {
331 LOG(ERROR
) << "Unable to read command from Zygote";
334 return HonorRequestAndReply(zygote_ipc_fd
,
342 #if !defined(OS_NACL_NONSFI)
343 static const char kNaClHelperReservedAtZero
[] = "reserved_at_zero";
344 static const char kNaClHelperRDebug
[] = "r_debug";
346 // Since we were started by nacl_helper_bootstrap rather than in the
347 // usual way, the debugger cannot figure out where our executable
348 // or the dynamic linker or the shared libraries are in memory,
349 // so it won't find any symbols. But we can fake it out to find us.
351 // The zygote passes --r_debug=0xXXXXXXXXXXXXXXXX.
352 // nacl_helper_bootstrap replaces the Xs with the address of its _r_debug
353 // structure. The debugger will look for that symbol by name to
354 // discover the addresses of key dynamic linker data structures.
355 // Since all it knows about is the original main executable, which
356 // is the bootstrap program, it finds the symbol defined there. The
357 // dynamic linker's structure is somewhere else, but it is filled in
358 // after initialization. The parts that really matter to the
359 // debugger never change. So we just copy the contents of the
360 // dynamic linker's structure into the address provided by the option.
361 // Hereafter, if someone attaches a debugger (or examines a core dump),
362 // the debugger will find all the symbols in the normal way.
364 // Non-SFI mode does not use nacl_helper_bootstrap, so it doesn't need to
365 // process the --r_debug option.
366 static void CheckRDebug(char* argv0
) {
367 std::string r_debug_switch_value
=
368 base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
370 if (!r_debug_switch_value
.empty()) {
372 uintptr_t r_debug_addr
= strtoul(r_debug_switch_value
.c_str(), &endp
, 0);
373 if (r_debug_addr
!= 0 && *endp
== '\0') {
374 r_debug
* bootstrap_r_debug
= reinterpret_cast<r_debug
*>(r_debug_addr
);
375 *bootstrap_r_debug
= _r_debug
;
377 // Since the main executable (the bootstrap program) does not
378 // have a dynamic section, the debugger will not skip the
379 // first element of the link_map list as it usually would for
380 // an executable or PIE that was loaded normally. But the
381 // dynamic linker has set l_name for the PIE to "" as is
382 // normal for the main executable. So the debugger doesn't
383 // know which file it is. Fill in the actual file name, which
384 // came in as our argv[0].
385 link_map
* l
= _r_debug
.r_map
;
386 if (l
->l_name
[0] == '\0')
392 // The zygote passes --reserved_at_zero=0xXXXXXXXXXXXXXXXX.
393 // nacl_helper_bootstrap replaces the Xs with the amount of prereserved
396 // CheckReservedAtZero parses the value of the argument reserved_at_zero
397 // and returns the amount of prereserved sandbox memory.
398 static size_t CheckReservedAtZero() {
399 size_t prereserved_sandbox_size
= 0;
400 std::string reserved_at_zero_switch_value
=
401 base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
402 kNaClHelperReservedAtZero
);
403 if (!reserved_at_zero_switch_value
.empty()) {
405 prereserved_sandbox_size
=
406 strtoul(reserved_at_zero_switch_value
.c_str(), &endp
, 0);
408 LOG(ERROR
) << "Could not parse reserved_at_zero argument value of "
409 << reserved_at_zero_switch_value
;
411 return prereserved_sandbox_size
;
417 #if defined(ADDRESS_SANITIZER)
418 // Do not install the SIGSEGV handler in ASan. This should make the NaCl
419 // platform qualification test pass.
420 // detect_odr_violation=0: http://crbug.com/376306
421 static const char kAsanDefaultOptionsNaCl
[] =
422 "handle_segv=0:detect_odr_violation=0";
424 // Override the default ASan options for the NaCl helper.
425 // __asan_default_options should not be instrumented, because it is called
426 // before ASan is initialized.
428 __attribute__((no_sanitize_address
))
429 // The function isn't referenced from the executable itself. Make sure it isn't
430 // stripped by the linker.
431 __attribute__((used
))
432 __attribute__((visibility("default")))
433 const char* __asan_default_options() {
434 return kAsanDefaultOptionsNaCl
;
438 int main(int argc
, char* argv
[]) {
439 base::CommandLine::Init(argc
, argv
);
440 base::AtExitManager exit_manager
;
441 base::RandUint64(); // acquire /dev/urandom fd before sandbox is raised
443 // NSS is only needed for SFI NaCl.
444 #if !defined(OS_NACL_NONSFI) && !defined(USE_OPENSSL)
445 // Allows NSS to fopen() /dev/urandom.
446 sandbox::InitLibcUrandomOverrides();
447 // Configure NSS for use inside the NaCl process.
448 // The fork check has not caused problems for NaCl, but this appears to be
449 // best practice (see other places LoadNSSLibraries is called.)
450 crypto::DisableNSSForkCheck();
451 // Without this line on Linux, HMAC::Init will instantiate a singleton that
452 // in turn attempts to open a file. Disabling this behavior avoids a ~70 ms
453 // stall the first time HMAC is used.
454 crypto::ForceNSSNoDBInit();
455 // Load shared libraries before sandbox is raised.
456 // NSS is needed to perform hashing for validation caching.
457 crypto::LoadNSSLibraries();
458 #endif // !defined(OS_NACL_NONSFI) && !defined(USE_OPENSSL)
459 const NaClLoaderSystemInfo system_info
= {
460 #if !defined(OS_NACL_NONSFI)
461 // These are not used by nacl_helper_nonsfi.
462 CheckReservedAtZero(),
463 sysconf(_SC_NPROCESSORS_ONLN
)
467 #if !defined(OS_NACL_NONSFI)
468 CheckRDebug(argv
[0]);
471 scoped_ptr
<nacl::NaClSandbox
> nacl_sandbox(new nacl::NaClSandbox
);
472 // Make sure that the early initialization did not start any spurious
474 #if !defined(THREAD_SANITIZER)
475 CHECK(nacl_sandbox
->IsSingleThreaded());
478 const bool is_init_process
= 1 == getpid();
479 nacl_sandbox
->InitializeLayerOneSandbox();
480 CHECK_EQ(is_init_process
, nacl_sandbox
->layer_one_enabled());
482 const std::vector
<int> empty
;
483 // Send the zygote a message to let it know we are ready to help
484 if (!base::UnixDomainSocket::SendMsg(kNaClZygoteDescriptor
,
485 kNaClHelperStartupAck
,
486 sizeof(kNaClHelperStartupAck
), empty
)) {
487 LOG(ERROR
) << "*** send() to zygote failed";
490 // Now handle requests from the Zygote.
492 bool request_handled
= HandleZygoteRequest(
493 kNaClZygoteDescriptor
, system_info
, nacl_sandbox
.get());
494 // Do not turn this into a CHECK() without thinking about robustness
495 // against malicious IPC requests.
496 DCHECK(request_handled
);