1 // Copyright (c) 2012 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/common/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/logging.h"
25 #include "base/message_loop/message_loop.h"
26 #include "base/posix/eintr_wrapper.h"
27 #include "base/posix/global_descriptors.h"
28 #include "base/posix/unix_domain_socket_linux.h"
29 #include "base/process/kill.h"
30 #include "base/rand_util.h"
31 #include "components/nacl/loader/nacl_listener.h"
32 #include "components/nacl/loader/nacl_sandbox_linux.h"
33 #include "crypto/nss_util.h"
34 #include "ipc/ipc_descriptors.h"
35 #include "ipc/ipc_switches.h"
36 #include "sandbox/linux/services/libc_urandom_override.h"
40 struct NaClLoaderSystemInfo
{
41 size_t prereserved_sandbox_size
;
45 // The child must mimic the behavior of zygote_main_linux.cc on the child
46 // side of the fork. See zygote_main_linux.cc:HandleForkRequest from
48 void BecomeNaClLoader(const std::vector
<int>& child_fds
,
49 const NaClLoaderSystemInfo
& system_info
) {
50 VLOG(1) << "NaCl loader: setting up IPC descriptor";
51 // don't need zygote FD any more
52 if (HANDLE_EINTR(close(kNaClZygoteDescriptor
)) != 0)
53 LOG(ERROR
) << "close(kNaClZygoteDescriptor) failed.";
54 bool sandbox_initialized
= InitializeBpfSandbox();
55 if (!sandbox_initialized
) {
56 LOG(ERROR
) << "Could not initialize NaCl's second "
57 << "layer sandbox (seccomp-bpf).";
59 base::GlobalDescriptors::GetInstance()->Set(kPrimaryIPCChannel
,
60 child_fds
[kNaClBrowserFDIndex
]);
62 base::MessageLoopForIO main_message_loop
;
63 NaClListener listener
;
64 listener
.set_prereserved_sandbox_size(system_info
.prereserved_sandbox_size
);
65 listener
.set_number_of_cores(system_info
.number_of_cores
);
70 // Start the NaCl loader in a child created by the NaCl loader Zygote.
71 void ChildNaClLoaderInit(const std::vector
<int>& child_fds
,
72 const NaClLoaderSystemInfo
& system_info
) {
73 bool validack
= false;
74 const size_t kMaxReadSize
= 1024;
75 char buffer
[kMaxReadSize
];
76 // Wait until the parent process has discovered our PID. We
77 // should not fork any child processes (which the seccomp
78 // sandbox does) until then, because that can interfere with the
79 // parent's discovery of our PID.
80 const int nread
= HANDLE_EINTR(read(child_fds
[kNaClParentFDIndex
], buffer
,
82 const std::string switch_prefix
= std::string("--") +
83 switches::kProcessChannelID
+ std::string("=");
84 const size_t len
= switch_prefix
.length();
88 LOG(ERROR
) << "read returned " << nread
;
89 } else if (nread
> static_cast<int>(len
)) {
90 if (switch_prefix
.compare(0, len
, buffer
, 0, len
) == 0) {
91 VLOG(1) << "NaCl loader is synchronised with Chrome zygote";
92 CommandLine::ForCurrentProcess()->AppendSwitchASCII(
93 switches::kProcessChannelID
,
94 std::string(&buffer
[len
], nread
- len
));
98 if (HANDLE_EINTR(close(child_fds
[kNaClDummyFDIndex
])) != 0)
99 LOG(ERROR
) << "close(child_fds[kNaClDummyFDIndex]) failed";
100 if (HANDLE_EINTR(close(child_fds
[kNaClParentFDIndex
])) != 0)
101 LOG(ERROR
) << "close(child_fds[kNaClParentFDIndex]) failed";
103 BecomeNaClLoader(child_fds
, system_info
);
105 LOG(ERROR
) << "Failed to synch with zygote";
110 // Handle a fork request from the Zygote.
111 // Some of this code was lifted from
112 // content/browser/zygote_main_linux.cc:ForkWithRealPid()
113 bool HandleForkRequest(const std::vector
<int>& child_fds
,
114 const NaClLoaderSystemInfo
& system_info
,
115 Pickle
* output_pickle
) {
116 if (kNaClParentFDIndex
+ 1 != child_fds
.size()) {
117 LOG(ERROR
) << "nacl_helper: unexpected number of fds, got "
122 VLOG(1) << "nacl_helper: forking";
123 pid_t child_pid
= fork();
125 PLOG(ERROR
) << "*** fork() failed.";
128 if (child_pid
== 0) {
129 ChildNaClLoaderInit(child_fds
, system_info
);
134 // First, close the dummy_fd so the sandbox won't find me when
135 // looking for the child's pid in /proc. Also close other fds.
136 for (size_t i
= 0; i
< child_fds
.size(); i
++) {
137 if (HANDLE_EINTR(close(child_fds
[i
])) != 0)
138 LOG(ERROR
) << "close(child_fds[i]) failed";
140 VLOG(1) << "nacl_helper: child_pid is " << child_pid
;
142 // Now send child_pid (eventually -1 if fork failed) to the Chrome Zygote.
143 output_pickle
->WriteInt(child_pid
);
147 bool HandleGetTerminationStatusRequest(PickleIterator
* input_iter
,
148 Pickle
* output_pickle
) {
150 if (!input_iter
->ReadInt(&child_to_wait
)) {
151 LOG(ERROR
) << "Could not read pid to wait for";
156 if (!input_iter
->ReadBool(&known_dead
)) {
157 LOG(ERROR
) << "Could not read known_dead status";
160 // TODO(jln): With NaCl, known_dead seems to never be set to true (unless
161 // called from the Zygote's kZygoteCommandReap command). This means that we
162 // will sometimes detect the process as still running when it's not. Fix
166 base::TerminationStatus status
;
167 // See the comment in the Zygote about known_dead.
169 // Make sure to not perform a blocking wait on something that
170 // could still be alive.
171 if (kill(child_to_wait
, SIGKILL
)) {
172 PLOG(ERROR
) << "kill (" << child_to_wait
<< ")";
174 status
= base::WaitForTerminationStatus(child_to_wait
, &exit_code
);
176 status
= base::GetTerminationStatus(child_to_wait
, &exit_code
);
178 output_pickle
->WriteInt(static_cast<int>(status
));
179 output_pickle
->WriteInt(exit_code
);
183 // This is a poor man's check on whether we are sandboxed.
185 int proc_fd
= open("/proc/self/exe", O_RDONLY
);
187 HANDLE_EINTR(close(proc_fd
));
193 // Honor a command |command_type|. Eventual command parameters are
194 // available in |input_iter| and eventual file descriptors attached to
195 // the command are in |attached_fds|.
196 // Reply to the command on |reply_fds|.
197 bool HonorRequestAndReply(int reply_fd
,
199 const std::vector
<int>& attached_fds
,
200 const NaClLoaderSystemInfo
& system_info
,
201 PickleIterator
* input_iter
) {
203 bool have_to_reply
= false;
204 // Commands must write anything to send back to |write_pickle|.
205 switch (command_type
) {
206 case kNaClForkRequest
:
207 have_to_reply
= HandleForkRequest(attached_fds
, system_info
,
210 case kNaClGetTerminationStatusRequest
:
212 HandleGetTerminationStatusRequest(input_iter
, &write_pickle
);
215 LOG(ERROR
) << "Unsupported command from Zygote";
220 const std::vector
<int> empty
; // We never send file descriptors back.
221 if (!UnixDomainSocket::SendMsg(reply_fd
, write_pickle
.data(),
222 write_pickle
.size(), empty
)) {
223 LOG(ERROR
) << "*** send() to zygote failed";
229 // Read a request from the Zygote from |zygote_ipc_fd| and handle it.
230 // Die on EOF from |zygote_ipc_fd|.
231 bool HandleZygoteRequest(int zygote_ipc_fd
,
232 const NaClLoaderSystemInfo
& system_info
) {
233 std::vector
<int> fds
;
234 char buf
[kNaClMaxIPCMessageLength
];
235 const ssize_t msglen
= UnixDomainSocket::RecvMsg(zygote_ipc_fd
,
236 &buf
, sizeof(buf
), &fds
);
237 // If the Zygote has started handling requests, we should be sandboxed via
238 // the setuid sandbox.
239 if (!IsSandboxed()) {
240 LOG(ERROR
) << "NaCl helper process running without a sandbox!\n"
241 << "Most likely you need to configure your SUID sandbox "
244 if (msglen
== 0 || (msglen
== -1 && errno
== ECONNRESET
)) {
245 // EOF from the browser. Goodbye!
249 PLOG(ERROR
) << "nacl_helper: receive from zygote failed";
253 Pickle
read_pickle(buf
, msglen
);
254 PickleIterator
read_iter(read_pickle
);
256 if (!read_iter
.ReadInt(&command_type
)) {
257 LOG(ERROR
) << "Unable to read command from Zygote";
260 return HonorRequestAndReply(zygote_ipc_fd
, command_type
, fds
, system_info
,
264 static const char kNaClHelperReservedAtZero
[] = "reserved_at_zero";
265 static const char kNaClHelperRDebug
[] = "r_debug";
267 // Since we were started by nacl_helper_bootstrap rather than in the
268 // usual way, the debugger cannot figure out where our executable
269 // or the dynamic linker or the shared libraries are in memory,
270 // so it won't find any symbols. But we can fake it out to find us.
272 // The zygote passes --r_debug=0xXXXXXXXXXXXXXXXX.
273 // nacl_helper_bootstrap replaces the Xs with the address of its _r_debug
274 // structure. The debugger will look for that symbol by name to
275 // discover the addresses of key dynamic linker data structures.
276 // Since all it knows about is the original main executable, which
277 // is the bootstrap program, it finds the symbol defined there. The
278 // dynamic linker's structure is somewhere else, but it is filled in
279 // after initialization. The parts that really matter to the
280 // debugger never change. So we just copy the contents of the
281 // dynamic linker's structure into the address provided by the option.
282 // Hereafter, if someone attaches a debugger (or examines a core dump),
283 // the debugger will find all the symbols in the normal way.
284 static void CheckRDebug(char* argv0
) {
285 std::string r_debug_switch_value
=
286 CommandLine::ForCurrentProcess()->GetSwitchValueASCII(kNaClHelperRDebug
);
287 if (!r_debug_switch_value
.empty()) {
289 uintptr_t r_debug_addr
= strtoul(r_debug_switch_value
.c_str(), &endp
, 0);
290 if (r_debug_addr
!= 0 && *endp
== '\0') {
291 r_debug
* bootstrap_r_debug
= reinterpret_cast<r_debug
*>(r_debug_addr
);
292 *bootstrap_r_debug
= _r_debug
;
294 // Since the main executable (the bootstrap program) does not
295 // have a dynamic section, the debugger will not skip the
296 // first element of the link_map list as it usually would for
297 // an executable or PIE that was loaded normally. But the
298 // dynamic linker has set l_name for the PIE to "" as is
299 // normal for the main executable. So the debugger doesn't
300 // know which file it is. Fill in the actual file name, which
301 // came in as our argv[0].
302 link_map
* l
= _r_debug
.r_map
;
303 if (l
->l_name
[0] == '\0')
309 // The zygote passes --reserved_at_zero=0xXXXXXXXXXXXXXXXX.
310 // nacl_helper_bootstrap replaces the Xs with the amount of prereserved
313 // CheckReservedAtZero parses the value of the argument reserved_at_zero
314 // and returns the amount of prereserved sandbox memory.
315 static size_t CheckReservedAtZero() {
316 size_t prereserved_sandbox_size
= 0;
317 std::string reserved_at_zero_switch_value
=
318 CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
319 kNaClHelperReservedAtZero
);
320 if (!reserved_at_zero_switch_value
.empty()) {
322 prereserved_sandbox_size
=
323 strtoul(reserved_at_zero_switch_value
.c_str(), &endp
, 0);
325 LOG(ERROR
) << "Could not parse reserved_at_zero argument value of "
326 << reserved_at_zero_switch_value
;
328 return prereserved_sandbox_size
;
333 #if defined(ADDRESS_SANITIZER)
334 // Do not install the SIGSEGV handler in ASan. This should make the NaCl
335 // platform qualification test pass.
336 static const char kAsanDefaultOptionsNaCl
[] = "handle_segv=0";
338 // Override the default ASan options for the NaCl helper.
339 // __asan_default_options should not be instrumented, because it is called
340 // before ASan is initialized.
342 __attribute__((no_address_safety_analysis
))
343 const char* __asan_default_options() {
344 return kAsanDefaultOptionsNaCl
;
348 int main(int argc
, char* argv
[]) {
349 CommandLine::Init(argc
, argv
);
350 base::AtExitManager exit_manager
;
351 base::RandUint64(); // acquire /dev/urandom fd before sandbox is raised
352 // Allows NSS to fopen() /dev/urandom.
353 sandbox::InitLibcUrandomOverrides();
355 // Configure NSS for use inside the NaCl process.
356 // The fork check has not caused problems for NaCl, but this appears to be
357 // best practice (see other places LoadNSSLibraries is called.)
358 crypto::DisableNSSForkCheck();
359 // Without this line on Linux, HMAC::Init will instantiate a singleton that
360 // in turn attempts to open a file. Disabling this behavior avoids a ~70 ms
361 // stall the first time HMAC is used.
362 crypto::ForceNSSNoDBInit();
363 // Load shared libraries before sandbox is raised.
364 // NSS is needed to perform hashing for validation caching.
365 crypto::LoadNSSLibraries();
367 const NaClLoaderSystemInfo system_info
= {
368 CheckReservedAtZero(),
369 sysconf(_SC_NPROCESSORS_ONLN
)
372 CheckRDebug(argv
[0]);
374 // Check that IsSandboxed() works. We should not be sandboxed at this point.
375 CHECK(!IsSandboxed()) << "Unexpectedly sandboxed!";
377 const std::vector
<int> empty
;
378 // Send the zygote a message to let it know we are ready to help
379 if (!UnixDomainSocket::SendMsg(kNaClZygoteDescriptor
,
380 kNaClHelperStartupAck
,
381 sizeof(kNaClHelperStartupAck
), empty
)) {
382 LOG(ERROR
) << "*** send() to zygote failed";
385 // Now handle requests from the Zygote.
387 bool request_handled
= HandleZygoteRequest(kNaClZygoteDescriptor
,
389 // Do not turn this into a CHECK() without thinking about robustness
390 // against malicious IPC requests.
391 DCHECK(request_handled
);