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"
15 #include <sys/socket.h>
17 #include <sys/types.h>
22 #include "base/at_exit.h"
23 #include "base/command_line.h"
24 #include "base/files/scoped_file.h"
25 #include "base/logging.h"
26 #include "base/memory/scoped_ptr.h"
27 #include "base/memory/scoped_vector.h"
28 #include "base/message_loop/message_loop.h"
29 #include "base/posix/eintr_wrapper.h"
30 #include "base/posix/global_descriptors.h"
31 #include "base/posix/unix_domain_socket_linux.h"
32 #include "base/process/kill.h"
33 #include "base/process/process_handle.h"
34 #include "base/rand_util.h"
35 #include "components/nacl/common/nacl_switches.h"
36 #include "components/nacl/loader/nacl_listener.h"
37 #include "components/nacl/loader/nonsfi/irt_exception_handling.h"
38 #include "components/nacl/loader/sandbox_linux/nacl_sandbox_linux.h"
39 #include "content/public/common/child_process_sandbox_support_linux.h"
40 #include "content/public/common/content_descriptors.h"
41 #include "content/public/common/zygote_fork_delegate_linux.h"
42 #include "crypto/nss_util.h"
43 #include "ipc/ipc_descriptors.h"
44 #include "ipc/ipc_switches.h"
45 #include "sandbox/linux/services/libc_urandom_override.h"
49 struct NaClLoaderSystemInfo {
50 size_t prereserved_sandbox_size;
54 // Replace |file_descriptor| with the reading end of a closed pipe.
55 void ReplaceFDWithDummy(int file_descriptor) {
56 // Make sure that file_descriptor is an open descriptor.
57 PCHECK(-1 != fcntl(file_descriptor, F_GETFD, 0));
59 PCHECK(0 == pipe(pipefd));
60 PCHECK(-1 != dup2(pipefd[0], file_descriptor));
61 PCHECK(0 == IGNORE_EINTR(close(pipefd[0])));
62 PCHECK(0 == IGNORE_EINTR(close(pipefd[1])));
65 // The child must mimic the behavior of zygote_main_linux.cc on the child
66 // side of the fork. See zygote_main_linux.cc:HandleForkRequest from
68 void BecomeNaClLoader(base::ScopedFD browser_fd,
69 const NaClLoaderSystemInfo& system_info,
70 bool uses_nonsfi_mode,
71 nacl::NaClSandbox* nacl_sandbox) {
73 VLOG(1) << "NaCl loader: setting up IPC descriptor";
74 // Close or shutdown IPC channels that we don't need anymore.
75 PCHECK(0 == IGNORE_EINTR(close(kNaClZygoteDescriptor)));
76 // In Non-SFI mode, it's important to close any non-expected IPC channels.
77 if (uses_nonsfi_mode) {
78 // The low-level kSandboxIPCChannel is used by renderers and NaCl for
79 // various operations. See the LinuxSandbox::METHOD_* methods. NaCl uses
80 // LinuxSandbox::METHOD_MAKE_SHARED_MEMORY_SEGMENT in SFI mode, so this
81 // should only be closed in Non-SFI mode.
82 // This file descriptor is insidiously used by a number of APIs. Closing it
83 // could lead to difficult to debug issues. Instead of closing it, replace
85 const int sandbox_ipc_channel =
86 base::GlobalDescriptors::kBaseDescriptor + kSandboxIPCChannel;
88 ReplaceFDWithDummy(sandbox_ipc_channel);
90 // Install crash signal handlers before disallowing system calls.
91 nacl::nonsfi::InitializeSignalHandler();
94 // Finish layer-1 sandbox initialization and initialize the layer-2 sandbox.
95 CHECK(!nacl_sandbox->HasOpenDirectory());
96 nacl_sandbox->InitializeLayerTwoSandbox(uses_nonsfi_mode);
97 nacl_sandbox->SealLayerOneSandbox();
98 nacl_sandbox->CheckSandboxingStateWithPolicy();
100 base::GlobalDescriptors::GetInstance()->Set(kPrimaryIPCChannel,
101 browser_fd.release());
103 base::MessageLoopForIO main_message_loop;
104 NaClListener listener;
105 listener.set_uses_nonsfi_mode(uses_nonsfi_mode);
106 listener.set_prereserved_sandbox_size(system_info.prereserved_sandbox_size);
107 listener.set_number_of_cores(system_info.number_of_cores);
112 // Start the NaCl loader in a child created by the NaCl loader Zygote.
113 void ChildNaClLoaderInit(ScopedVector<base::ScopedFD> child_fds,
114 const NaClLoaderSystemInfo& system_info,
115 bool uses_nonsfi_mode,
116 nacl::NaClSandbox* nacl_sandbox,
117 const std::string& channel_id) {
118 DCHECK(child_fds.size() >
119 std::max(content::ZygoteForkDelegate::kPIDOracleFDIndex,
120 content::ZygoteForkDelegate::kBrowserFDIndex));
122 // Ping the PID oracle socket.
123 CHECK(content::SendZygoteChildPing(
124 child_fds[content::ZygoteForkDelegate::kPIDOracleFDIndex]->get()));
126 CommandLine::ForCurrentProcess()->AppendSwitchASCII(
127 switches::kProcessChannelID, channel_id);
129 // Save the browser socket and close the rest.
130 base::ScopedFD browser_fd(
131 child_fds[content::ZygoteForkDelegate::kBrowserFDIndex]->Pass());
135 browser_fd.Pass(), system_info, uses_nonsfi_mode, nacl_sandbox);
139 // Handle a fork request from the Zygote.
140 // Some of this code was lifted from
141 // content/browser/zygote_main_linux.cc:ForkWithRealPid()
142 bool HandleForkRequest(ScopedVector<base::ScopedFD> child_fds,
143 const NaClLoaderSystemInfo& system_info,
144 nacl::NaClSandbox* nacl_sandbox,
145 PickleIterator* input_iter,
146 Pickle* output_pickle) {
147 bool uses_nonsfi_mode;
148 if (!input_iter->ReadBool(&uses_nonsfi_mode)) {
149 LOG(ERROR) << "Could not read uses_nonsfi_mode status";
153 std::string channel_id;
154 if (!input_iter->ReadString(&channel_id)) {
155 LOG(ERROR) << "Could not read channel_id string";
159 if (content::ZygoteForkDelegate::kNumPassedFDs != child_fds.size()) {
160 LOG(ERROR) << "nacl_helper: unexpected number of fds, got "
165 VLOG(1) << "nacl_helper: forking";
166 pid_t child_pid = fork();
168 PLOG(ERROR) << "*** fork() failed.";
171 if (child_pid == 0) {
172 ChildNaClLoaderInit(child_fds.Pass(),
181 // First, close the dummy_fd so the sandbox won't find me when
182 // looking for the child's pid in /proc. Also close other fds.
184 VLOG(1) << "nacl_helper: child_pid is " << child_pid;
186 // Now send child_pid (eventually -1 if fork failed) to the Chrome Zygote.
187 output_pickle->WriteInt(child_pid);
191 bool HandleGetTerminationStatusRequest(PickleIterator* input_iter,
192 Pickle* output_pickle) {
194 if (!input_iter->ReadInt(&child_to_wait)) {
195 LOG(ERROR) << "Could not read pid to wait for";
200 if (!input_iter->ReadBool(&known_dead)) {
201 LOG(ERROR) << "Could not read known_dead status";
204 // TODO(jln): With NaCl, known_dead seems to never be set to true (unless
205 // called from the Zygote's kZygoteCommandReap command). This means that we
206 // will sometimes detect the process as still running when it's not. Fix
210 base::TerminationStatus status;
212 status = base::GetKnownDeadTerminationStatus(child_to_wait, &exit_code);
214 status = base::GetTerminationStatus(child_to_wait, &exit_code);
215 output_pickle->WriteInt(static_cast<int>(status));
216 output_pickle->WriteInt(exit_code);
220 // Honor a command |command_type|. Eventual command parameters are
221 // available in |input_iter| and eventual file descriptors attached to
222 // the command are in |attached_fds|.
223 // Reply to the command on |reply_fds|.
224 bool HonorRequestAndReply(int reply_fd,
226 ScopedVector<base::ScopedFD> attached_fds,
227 const NaClLoaderSystemInfo& system_info,
228 nacl::NaClSandbox* nacl_sandbox,
229 PickleIterator* input_iter) {
231 bool have_to_reply = false;
232 // Commands must write anything to send back to |write_pickle|.
233 switch (command_type) {
234 case nacl::kNaClForkRequest:
235 have_to_reply = HandleForkRequest(attached_fds.Pass(),
241 case nacl::kNaClGetTerminationStatusRequest:
243 HandleGetTerminationStatusRequest(input_iter, &write_pickle);
246 LOG(ERROR) << "Unsupported command from Zygote";
251 const std::vector<int> empty; // We never send file descriptors back.
252 if (!UnixDomainSocket::SendMsg(reply_fd, write_pickle.data(),
253 write_pickle.size(), empty)) {
254 LOG(ERROR) << "*** send() to zygote failed";
260 // Read a request from the Zygote from |zygote_ipc_fd| and handle it.
261 // Die on EOF from |zygote_ipc_fd|.
262 bool HandleZygoteRequest(int zygote_ipc_fd,
263 const NaClLoaderSystemInfo& system_info,
264 nacl::NaClSandbox* nacl_sandbox) {
265 ScopedVector<base::ScopedFD> fds;
266 char buf[kNaClMaxIPCMessageLength];
267 const ssize_t msglen = UnixDomainSocket::RecvMsg(zygote_ipc_fd,
268 &buf, sizeof(buf), &fds);
269 // If the Zygote has started handling requests, we should be sandboxed via
270 // the setuid sandbox.
271 if (!nacl_sandbox->layer_one_enabled()) {
272 LOG(ERROR) << "NaCl helper process running without a sandbox!\n"
273 << "Most likely you need to configure your SUID sandbox "
276 if (msglen == 0 || (msglen == -1 && errno == ECONNRESET)) {
277 // EOF from the browser. Goodbye!
281 PLOG(ERROR) << "nacl_helper: receive from zygote failed";
285 Pickle read_pickle(buf, msglen);
286 PickleIterator read_iter(read_pickle);
288 if (!read_iter.ReadInt(&command_type)) {
289 LOG(ERROR) << "Unable to read command from Zygote";
292 return HonorRequestAndReply(zygote_ipc_fd,
300 static const char kNaClHelperReservedAtZero[] = "reserved_at_zero";
301 static const char kNaClHelperRDebug[] = "r_debug";
303 // Since we were started by nacl_helper_bootstrap rather than in the
304 // usual way, the debugger cannot figure out where our executable
305 // or the dynamic linker or the shared libraries are in memory,
306 // so it won't find any symbols. But we can fake it out to find us.
308 // The zygote passes --r_debug=0xXXXXXXXXXXXXXXXX.
309 // nacl_helper_bootstrap replaces the Xs with the address of its _r_debug
310 // structure. The debugger will look for that symbol by name to
311 // discover the addresses of key dynamic linker data structures.
312 // Since all it knows about is the original main executable, which
313 // is the bootstrap program, it finds the symbol defined there. The
314 // dynamic linker's structure is somewhere else, but it is filled in
315 // after initialization. The parts that really matter to the
316 // debugger never change. So we just copy the contents of the
317 // dynamic linker's structure into the address provided by the option.
318 // Hereafter, if someone attaches a debugger (or examines a core dump),
319 // the debugger will find all the symbols in the normal way.
320 static void CheckRDebug(char* argv0) {
321 std::string r_debug_switch_value =
322 CommandLine::ForCurrentProcess()->GetSwitchValueASCII(kNaClHelperRDebug);
323 if (!r_debug_switch_value.empty()) {
325 uintptr_t r_debug_addr = strtoul(r_debug_switch_value.c_str(), &endp, 0);
326 if (r_debug_addr != 0 && *endp == '\0') {
327 r_debug* bootstrap_r_debug = reinterpret_cast<r_debug*>(r_debug_addr);
328 *bootstrap_r_debug = _r_debug;
330 // Since the main executable (the bootstrap program) does not
331 // have a dynamic section, the debugger will not skip the
332 // first element of the link_map list as it usually would for
333 // an executable or PIE that was loaded normally. But the
334 // dynamic linker has set l_name for the PIE to "" as is
335 // normal for the main executable. So the debugger doesn't
336 // know which file it is. Fill in the actual file name, which
337 // came in as our argv[0].
338 link_map* l = _r_debug.r_map;
339 if (l->l_name[0] == '\0')
345 // The zygote passes --reserved_at_zero=0xXXXXXXXXXXXXXXXX.
346 // nacl_helper_bootstrap replaces the Xs with the amount of prereserved
349 // CheckReservedAtZero parses the value of the argument reserved_at_zero
350 // and returns the amount of prereserved sandbox memory.
351 static size_t CheckReservedAtZero() {
352 size_t prereserved_sandbox_size = 0;
353 std::string reserved_at_zero_switch_value =
354 CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
355 kNaClHelperReservedAtZero);
356 if (!reserved_at_zero_switch_value.empty()) {
358 prereserved_sandbox_size =
359 strtoul(reserved_at_zero_switch_value.c_str(), &endp, 0);
361 LOG(ERROR) << "Could not parse reserved_at_zero argument value of "
362 << reserved_at_zero_switch_value;
364 return prereserved_sandbox_size;
369 #if defined(ADDRESS_SANITIZER)
370 // Do not install the SIGSEGV handler in ASan. This should make the NaCl
371 // platform qualification test pass.
372 static const char kAsanDefaultOptionsNaCl[] = "handle_segv=0";
374 // Override the default ASan options for the NaCl helper.
375 // __asan_default_options should not be instrumented, because it is called
376 // before ASan is initialized.
378 __attribute__((no_sanitize_address))
379 // The function isn't referenced from the executable itself. Make sure it isn't
380 // stripped by the linker.
381 __attribute__((used))
382 __attribute__((visibility("default")))
383 const char* __asan_default_options() {
384 return kAsanDefaultOptionsNaCl;
388 int main(int argc, char* argv[]) {
389 CommandLine::Init(argc, argv);
390 base::AtExitManager exit_manager;
391 base::RandUint64(); // acquire /dev/urandom fd before sandbox is raised
392 // Allows NSS to fopen() /dev/urandom.
393 sandbox::InitLibcUrandomOverrides();
395 // Configure NSS for use inside the NaCl process.
396 // The fork check has not caused problems for NaCl, but this appears to be
397 // best practice (see other places LoadNSSLibraries is called.)
398 crypto::DisableNSSForkCheck();
399 // Without this line on Linux, HMAC::Init will instantiate a singleton that
400 // in turn attempts to open a file. Disabling this behavior avoids a ~70 ms
401 // stall the first time HMAC is used.
402 crypto::ForceNSSNoDBInit();
403 // Load shared libraries before sandbox is raised.
404 // NSS is needed to perform hashing for validation caching.
405 crypto::LoadNSSLibraries();
407 const NaClLoaderSystemInfo system_info = {
408 CheckReservedAtZero(),
409 sysconf(_SC_NPROCESSORS_ONLN)
412 CheckRDebug(argv[0]);
414 scoped_ptr<nacl::NaClSandbox> nacl_sandbox(new nacl::NaClSandbox);
415 // Make sure that the early initialization did not start any spurious
417 #if !defined(THREAD_SANITIZER)
418 CHECK(nacl_sandbox->IsSingleThreaded());
421 const bool is_init_process = 1 == getpid();
422 nacl_sandbox->InitializeLayerOneSandbox();
423 CHECK_EQ(is_init_process, nacl_sandbox->layer_one_enabled());
425 const std::vector<int> empty;
426 // Send the zygote a message to let it know we are ready to help
427 if (!UnixDomainSocket::SendMsg(kNaClZygoteDescriptor,
428 kNaClHelperStartupAck,
429 sizeof(kNaClHelperStartupAck), empty)) {
430 LOG(ERROR) << "*** send() to zygote failed";
433 // Now handle requests from the Zygote.
435 bool request_handled = HandleZygoteRequest(
436 kNaClZygoteDescriptor, system_info, nacl_sandbox.get());
437 // Do not turn this into a CHECK() without thinking about robustness
438 // against malicious IPC requests.
439 DCHECK(request_handled);