Add UMA reports for Linux nacl_helper startup status
[chromium-blink-merge.git] / content / browser / zygote_main_linux.cc
blob10c4983e208df9284bb4620da576bd2b4cdda9ca
1 // Copyright (c) 2011 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 "content/browser/zygote_host_linux.h"
7 #include <dlfcn.h>
8 #include <fcntl.h>
9 #include <pthread.h>
10 #include <sys/socket.h>
11 #include <sys/stat.h>
12 #include <sys/types.h>
13 #include <sys/wait.h>
14 #include <unistd.h>
16 #include "base/basictypes.h"
17 #include "base/command_line.h"
18 #include "base/eintr_wrapper.h"
19 #include "base/file_path.h"
20 #include "base/file_util.h"
21 #include "base/global_descriptors_posix.h"
22 #include "base/hash_tables.h"
23 #include "base/linux_util.h"
24 #include "base/memory/scoped_ptr.h"
25 #include "base/pickle.h"
26 #include "base/process_util.h"
27 #include "base/rand_util.h"
28 #include "base/sys_info.h"
29 #include "build/build_config.h"
30 #include "crypto/nss_util.h"
31 #include "content/common/chrome_descriptors.h"
32 #include "content/common/font_config_ipc_linux.h"
33 #include "content/common/main_function_params.h"
34 #include "content/common/pepper_plugin_registry.h"
35 #include "content/common/process_watcher.h"
36 #include "content/common/result_codes.h"
37 #include "content/common/sandbox_methods_linux.h"
38 #include "content/common/seccomp_sandbox.h"
39 #include "content/common/set_process_title.h"
40 #include "content/common/unix_domain_socket_posix.h"
41 #include "content/common/zygote_fork_delegate_linux.h"
42 #include "content/public/common/content_switches.h"
43 #include "skia/ext/SkFontHost_fontconfig_control.h"
44 #include "unicode/timezone.h"
45 #include "ipc/ipc_channel.h"
46 #include "ipc/ipc_switches.h"
48 #if defined(OS_LINUX)
49 #include <sys/epoll.h>
50 #include <sys/prctl.h>
51 #include <sys/signal.h>
52 #else
53 #include <signal.h>
54 #endif
56 #if defined(CHROMIUM_SELINUX)
57 #include <selinux/selinux.h>
58 #include <selinux/context.h>
59 #endif
61 // http://code.google.com/p/chromium/wiki/LinuxZygote
63 static const int kBrowserDescriptor = 3;
64 static const int kMagicSandboxIPCDescriptor = 5;
65 static const int kZygoteIdDescriptor = 7;
66 static bool g_suid_sandbox_active = false;
68 #if defined(SECCOMP_SANDBOX)
69 static int g_proc_fd = -1;
70 #endif
72 #if defined(CHROMIUM_SELINUX)
73 static void SELinuxTransitionToTypeOrDie(const char* type) {
74 security_context_t security_context;
75 if (getcon(&security_context))
76 LOG(FATAL) << "Cannot get SELinux context";
78 context_t context = context_new(security_context);
79 context_type_set(context, type);
80 const int r = setcon(context_str(context));
81 context_free(context);
82 freecon(security_context);
84 if (r) {
85 LOG(FATAL) << "dynamic transition to type '" << type << "' failed. "
86 "(this binary has been built with SELinux support, but maybe "
87 "the policies haven't been loaded into the kernel?)";
90 #endif // CHROMIUM_SELINUX
92 // This is the object which implements the zygote. The ZygoteMain function,
93 // which is called from ChromeMain, simply constructs one of these objects and
94 // runs it.
95 class Zygote {
96 public:
97 Zygote(int sandbox_flags, ZygoteForkDelegate* helper)
98 : sandbox_flags_(sandbox_flags), helper_(helper) {
99 if (helper_)
100 helper_->InitialUMA(&initial_uma_name_,
101 &initial_uma_sample_,
102 &initial_uma_boundary_value_);
105 bool ProcessRequests() {
106 // A SOCK_SEQPACKET socket is installed in fd 3. We get commands from the
107 // browser on it.
108 // A SOCK_DGRAM is installed in fd 5. This is the sandbox IPC channel.
109 // See http://code.google.com/p/chromium/wiki/LinuxSandboxIPC
111 // We need to accept SIGCHLD, even though our handler is a no-op because
112 // otherwise we cannot wait on children. (According to POSIX 2001.)
113 struct sigaction action;
114 memset(&action, 0, sizeof(action));
115 action.sa_handler = SIGCHLDHandler;
116 CHECK(sigaction(SIGCHLD, &action, NULL) == 0);
118 if (g_suid_sandbox_active) {
119 // Let the ZygoteHost know we are ready to go.
120 // The receiving code is in content/browser/zygote_host_linux.cc.
121 std::vector<int> empty;
122 bool r = UnixDomainSocket::SendMsg(kBrowserDescriptor, kZygoteMagic,
123 sizeof(kZygoteMagic), empty);
124 #if defined(OS_CHROMEOS)
125 LOG_IF(WARNING, r) << "Sending zygote magic failed";
126 // Exit normally on chromeos because session manager may send SIGTERM
127 // right after the process starts and it may fail to send zygote magic
128 // number to browser process.
129 if (!r)
130 _exit(content::RESULT_CODE_NORMAL_EXIT);
131 #else
132 CHECK(r) << "Sending zygote magic failed";
133 #endif
136 for (;;) {
137 // This function call can return multiple times, once per fork().
138 if (HandleRequestFromBrowser(kBrowserDescriptor))
139 return true;
143 private:
144 // See comment below, where sigaction is called.
145 static void SIGCHLDHandler(int signal) { }
147 // ---------------------------------------------------------------------------
148 // Requests from the browser...
150 // Read and process a request from the browser. Returns true if we are in a
151 // new process and thus need to unwind back into ChromeMain.
152 bool HandleRequestFromBrowser(int fd) {
153 std::vector<int> fds;
154 static const unsigned kMaxMessageLength = 2048;
155 char buf[kMaxMessageLength];
156 const ssize_t len = UnixDomainSocket::RecvMsg(fd, buf, sizeof(buf), &fds);
158 if (len == 0 || (len == -1 && errno == ECONNRESET)) {
159 // EOF from the browser. We should die.
160 _exit(0);
161 return false;
164 if (len == -1) {
165 PLOG(ERROR) << "Error reading message from browser";
166 return false;
169 Pickle pickle(buf, len);
170 void* iter = NULL;
172 int kind;
173 if (pickle.ReadInt(&iter, &kind)) {
174 switch (kind) {
175 case ZygoteHost::kCmdFork:
176 // This function call can return multiple times, once per fork().
177 return HandleForkRequest(fd, pickle, iter, fds);
179 case ZygoteHost::kCmdReap:
180 if (!fds.empty())
181 break;
182 HandleReapRequest(fd, pickle, iter);
183 return false;
184 case ZygoteHost::kCmdGetTerminationStatus:
185 if (!fds.empty())
186 break;
187 HandleGetTerminationStatus(fd, pickle, iter);
188 return false;
189 case ZygoteHost::kCmdGetSandboxStatus:
190 HandleGetSandboxStatus(fd, pickle, iter);
191 return false;
192 default:
193 NOTREACHED();
194 break;
198 LOG(WARNING) << "Error parsing message from browser";
199 for (std::vector<int>::const_iterator
200 i = fds.begin(); i != fds.end(); ++i)
201 close(*i);
202 return false;
205 void HandleReapRequest(int fd, const Pickle& pickle, void* iter) {
206 base::ProcessId child;
207 base::ProcessId actual_child;
209 if (!pickle.ReadInt(&iter, &child)) {
210 LOG(WARNING) << "Error parsing reap request from browser";
211 return;
214 if (g_suid_sandbox_active) {
215 actual_child = real_pids_to_sandbox_pids[child];
216 if (!actual_child)
217 return;
218 real_pids_to_sandbox_pids.erase(child);
219 } else {
220 actual_child = child;
223 ProcessWatcher::EnsureProcessTerminated(actual_child);
226 void HandleGetTerminationStatus(int fd, const Pickle& pickle, void* iter) {
227 base::ProcessHandle child;
229 if (!pickle.ReadInt(&iter, &child)) {
230 LOG(WARNING) << "Error parsing GetTerminationStatus request "
231 << "from browser";
232 return;
235 base::TerminationStatus status;
236 int exit_code;
237 if (g_suid_sandbox_active)
238 child = real_pids_to_sandbox_pids[child];
239 if (child) {
240 status = base::GetTerminationStatus(child, &exit_code);
241 } else {
242 // Assume that if we can't find the child in the sandbox, then
243 // it terminated normally.
244 status = base::TERMINATION_STATUS_NORMAL_TERMINATION;
245 exit_code = content::RESULT_CODE_NORMAL_EXIT;
248 Pickle write_pickle;
249 write_pickle.WriteInt(static_cast<int>(status));
250 write_pickle.WriteInt(exit_code);
251 ssize_t written =
252 HANDLE_EINTR(write(fd, write_pickle.data(), write_pickle.size()));
253 if (written != static_cast<ssize_t>(write_pickle.size()))
254 PLOG(ERROR) << "write";
257 // This is equivalent to fork(), except that, when using the SUID
258 // sandbox, it returns the real PID of the child process as it
259 // appears outside the sandbox, rather than returning the PID inside
260 // the sandbox. Optionally, it fills in uma_name et al with a report
261 // the helper wants to make via UMA_HISTOGRAM_ENUMERATION.
262 int ForkWithRealPid(const std::string& process_type, std::vector<int>& fds,
263 const std::string& channel_switch,
264 std::string* uma_name,
265 int* uma_sample, int* uma_boundary_value) {
266 const bool use_helper = (helper_ && helper_->CanHelp(process_type,
267 uma_name,
268 uma_sample,
269 uma_boundary_value));
270 if (!(use_helper || g_suid_sandbox_active)) {
271 return fork();
274 int dummy_fd;
275 ino_t dummy_inode;
276 int pipe_fds[2] = { -1, -1 };
277 base::ProcessId pid = 0;
279 dummy_fd = socket(PF_UNIX, SOCK_DGRAM, 0);
280 if (dummy_fd < 0) {
281 LOG(ERROR) << "Failed to create dummy FD";
282 goto error;
284 if (!base::FileDescriptorGetInode(&dummy_inode, dummy_fd)) {
285 LOG(ERROR) << "Failed to get inode for dummy FD";
286 goto error;
288 if (pipe(pipe_fds) != 0) {
289 LOG(ERROR) << "Failed to create pipe";
290 goto error;
293 if (use_helper) {
294 fds.push_back(dummy_fd);
295 fds.push_back(pipe_fds[0]);
296 pid = helper_->Fork(fds);
297 } else {
298 pid = fork();
300 if (pid < 0) {
301 goto error;
302 } else if (pid == 0) {
303 // In the child process.
304 close(pipe_fds[1]);
305 base::ProcessId real_pid;
306 // Wait until the parent process has discovered our PID. We
307 // should not fork any child processes (which the seccomp
308 // sandbox does) until then, because that can interfere with the
309 // parent's discovery of our PID.
310 if (!file_util::ReadFromFD(pipe_fds[0],
311 reinterpret_cast<char*>(&real_pid),
312 sizeof(real_pid))) {
313 LOG(FATAL) << "Failed to synchronise with parent zygote process";
315 if (real_pid <= 0) {
316 LOG(FATAL) << "Invalid pid from parent zygote";
318 #if defined(OS_LINUX)
319 // Sandboxed processes need to send the global, non-namespaced PID when
320 // setting up an IPC channel to their parent.
321 IPC::Channel::SetGlobalPid(real_pid);
322 #endif
323 close(pipe_fds[0]);
324 close(dummy_fd);
325 return 0;
326 } else {
327 // In the parent process.
328 close(dummy_fd);
329 dummy_fd = -1;
330 close(pipe_fds[0]);
331 pipe_fds[0] = -1;
332 base::ProcessId real_pid;
333 if (g_suid_sandbox_active) {
334 uint8_t reply_buf[512];
335 Pickle request;
336 request.WriteInt(LinuxSandbox::METHOD_GET_CHILD_WITH_INODE);
337 request.WriteUInt64(dummy_inode);
339 const ssize_t r = UnixDomainSocket::SendRecvMsg(
340 kMagicSandboxIPCDescriptor, reply_buf, sizeof(reply_buf), NULL,
341 request);
342 if (r == -1) {
343 LOG(ERROR) << "Failed to get child process's real PID";
344 goto error;
347 Pickle reply(reinterpret_cast<char*>(reply_buf), r);
348 void* iter = NULL;
349 if (!reply.ReadInt(&iter, &real_pid))
350 goto error;
351 if (real_pid <= 0) {
352 // METHOD_GET_CHILD_WITH_INODE failed. Did the child die already?
353 LOG(ERROR) << "METHOD_GET_CHILD_WITH_INODE failed";
354 goto error;
356 real_pids_to_sandbox_pids[real_pid] = pid;
358 if (use_helper) {
359 real_pid = pid;
360 if (!helper_->AckChild(pipe_fds[1], channel_switch)) {
361 LOG(ERROR) << "Failed to synchronise with zygote fork helper";
362 goto error;
364 } else {
365 int written =
366 HANDLE_EINTR(write(pipe_fds[1], &real_pid, sizeof(real_pid)));
367 if (written != sizeof(real_pid)) {
368 LOG(ERROR) << "Failed to synchronise with child process";
369 goto error;
372 close(pipe_fds[1]);
373 return real_pid;
376 error:
377 if (pid > 0) {
378 if (waitpid(pid, NULL, WNOHANG) == -1)
379 LOG(ERROR) << "Failed to wait for process";
381 if (dummy_fd >= 0)
382 close(dummy_fd);
383 if (pipe_fds[0] >= 0)
384 close(pipe_fds[0]);
385 if (pipe_fds[1] >= 0)
386 close(pipe_fds[1]);
387 return -1;
390 // Unpacks process type and arguments from |pickle| and forks a new process.
391 // Returns -1 on error, otherwise returns twice, returning 0 to the child
392 // process and the child process ID to the parent process, like fork().
393 base::ProcessId ReadArgsAndFork(const Pickle& pickle,
394 void* iter,
395 std::vector<int>& fds,
396 std::string* uma_name,
397 int* uma_sample,
398 int* uma_boundary_value) {
399 std::vector<std::string> args;
400 int argc = 0;
401 int numfds = 0;
402 base::GlobalDescriptors::Mapping mapping;
403 std::string process_type;
404 std::string channel_id;
405 const std::string channel_id_prefix = std::string("--")
406 + switches::kProcessChannelID + std::string("=");
408 if (!pickle.ReadString(&iter, &process_type))
409 return -1;
410 if (!pickle.ReadInt(&iter, &argc))
411 return -1;
413 for (int i = 0; i < argc; ++i) {
414 std::string arg;
415 if (!pickle.ReadString(&iter, &arg))
416 return -1;
417 args.push_back(arg);
418 if (arg.compare(0, channel_id_prefix.length(), channel_id_prefix) == 0)
419 channel_id = arg;
422 if (!pickle.ReadInt(&iter, &numfds))
423 return -1;
424 if (numfds != static_cast<int>(fds.size()))
425 return -1;
427 for (int i = 0; i < numfds; ++i) {
428 base::GlobalDescriptors::Key key;
429 if (!pickle.ReadUInt32(&iter, &key))
430 return -1;
431 mapping.push_back(std::make_pair(key, fds[i]));
434 mapping.push_back(std::make_pair(
435 static_cast<uint32_t>(kSandboxIPCChannel), kMagicSandboxIPCDescriptor));
437 // Returns twice, once per process.
438 base::ProcessId child_pid = ForkWithRealPid(process_type, fds, channel_id,
439 uma_name, uma_sample,
440 uma_boundary_value);
441 if (!child_pid) {
442 // This is the child process.
443 #if defined(SECCOMP_SANDBOX)
444 if (SeccompSandboxEnabled() && g_proc_fd >= 0) {
445 // Try to open /proc/self/maps as the seccomp sandbox needs access to it
446 int proc_self_maps = openat(g_proc_fd, "self/maps", O_RDONLY);
447 if (proc_self_maps >= 0) {
448 SeccompSandboxSetProcSelfMaps(proc_self_maps);
449 } else {
450 PLOG(ERROR) << "openat(/proc/self/maps)";
452 close(g_proc_fd);
453 g_proc_fd = -1;
455 #endif
457 close(kBrowserDescriptor); // our socket from the browser
458 if (g_suid_sandbox_active)
459 close(kZygoteIdDescriptor); // another socket from the browser
460 base::GlobalDescriptors::GetInstance()->Reset(mapping);
462 #if defined(CHROMIUM_SELINUX)
463 SELinuxTransitionToTypeOrDie("chromium_renderer_t");
464 #endif
466 // Reset the process-wide command line to our new command line.
467 CommandLine::Reset();
468 CommandLine::Init(0, NULL);
469 CommandLine::ForCurrentProcess()->InitFromArgv(args);
471 // Update the process title. The argv was already cached by the call to
472 // SetProcessTitleFromCommandLine in ChromeMain, so we can pass NULL here
473 // (we don't have the original argv at this point).
474 SetProcessTitleFromCommandLine(NULL);
475 } else if (child_pid < 0) {
476 LOG(ERROR) << "Zygote could not fork: process_type " << process_type
477 << " numfds " << numfds << " child_pid " << child_pid;
479 return child_pid;
482 // Handle a 'fork' request from the browser: this means that the browser
483 // wishes to start a new renderer. Returns true if we are in a new process,
484 // otherwise writes the child_pid back to the browser via |fd|. Writes a
485 // child_pid of -1 on error.
486 bool HandleForkRequest(int fd, const Pickle& pickle,
487 void* iter, std::vector<int>& fds) {
488 std::string uma_name;
489 int uma_sample;
490 int uma_boundary_value;
491 base::ProcessId child_pid = ReadArgsAndFork(pickle, iter, fds,
492 &uma_name, &uma_sample,
493 &uma_boundary_value);
494 if (child_pid == 0)
495 return true;
496 for (std::vector<int>::const_iterator
497 i = fds.begin(); i != fds.end(); ++i)
498 close(*i);
499 if (uma_name.empty()) {
500 // There is no UMA report from this particular fork.
501 // Use the initial UMA report if any, and clear that record for next time.
502 // Note the swap method here is the efficient way to do this, since
503 // we know uma_name is empty.
504 uma_name.swap(initial_uma_name_);
505 uma_sample = initial_uma_sample_;
506 uma_boundary_value = initial_uma_boundary_value_;
508 // Must always send reply, as ZygoteHost blocks while waiting for it.
509 Pickle reply_pickle;
510 reply_pickle.WriteInt(child_pid);
511 reply_pickle.WriteString(uma_name);
512 if (!uma_name.empty()) {
513 reply_pickle.WriteInt(uma_sample);
514 reply_pickle.WriteInt(uma_boundary_value);
516 if (HANDLE_EINTR(write(fd, reply_pickle.data(), reply_pickle.size())) !=
517 static_cast<ssize_t> (reply_pickle.size()))
518 PLOG(ERROR) << "write";
519 return false;
522 bool HandleGetSandboxStatus(int fd, const Pickle& pickle, void* iter) {
523 if (HANDLE_EINTR(write(fd, &sandbox_flags_, sizeof(sandbox_flags_)) !=
524 sizeof(sandbox_flags_))) {
525 PLOG(ERROR) << "write";
528 return false;
531 // In the SUID sandbox, we try to use a new PID namespace. Thus the PIDs
532 // fork() returns are not the real PIDs, so we need to map the Real PIDS
533 // into the sandbox PID namespace.
534 typedef base::hash_map<base::ProcessHandle, base::ProcessHandle> ProcessMap;
535 ProcessMap real_pids_to_sandbox_pids;
537 const int sandbox_flags_;
538 ZygoteForkDelegate* helper_;
540 // These might be set by helper_->InitialUMA. They supply a UMA
541 // enumeration sample we should report on the first fork.
542 std::string initial_uma_name_;
543 int initial_uma_sample_;
544 int initial_uma_boundary_value_;
547 // With SELinux we can carve out a precise sandbox, so we don't have to play
548 // with intercepting libc calls.
549 #if !defined(CHROMIUM_SELINUX)
551 static void ProxyLocaltimeCallToBrowser(time_t input, struct tm* output,
552 char* timezone_out,
553 size_t timezone_out_len) {
554 Pickle request;
555 request.WriteInt(LinuxSandbox::METHOD_LOCALTIME);
556 request.WriteString(
557 std::string(reinterpret_cast<char*>(&input), sizeof(input)));
559 uint8_t reply_buf[512];
560 const ssize_t r = UnixDomainSocket::SendRecvMsg(
561 kMagicSandboxIPCDescriptor, reply_buf, sizeof(reply_buf), NULL, request);
562 if (r == -1) {
563 memset(output, 0, sizeof(struct tm));
564 return;
567 Pickle reply(reinterpret_cast<char*>(reply_buf), r);
568 void* iter = NULL;
569 std::string result, timezone;
570 if (!reply.ReadString(&iter, &result) ||
571 !reply.ReadString(&iter, &timezone) ||
572 result.size() != sizeof(struct tm)) {
573 memset(output, 0, sizeof(struct tm));
574 return;
577 memcpy(output, result.data(), sizeof(struct tm));
578 if (timezone_out_len) {
579 const size_t copy_len = std::min(timezone_out_len - 1, timezone.size());
580 memcpy(timezone_out, timezone.data(), copy_len);
581 timezone_out[copy_len] = 0;
582 output->tm_zone = timezone_out;
583 } else {
584 output->tm_zone = NULL;
588 static bool g_am_zygote_or_renderer = false;
590 // Sandbox interception of libc calls.
592 // Because we are running in a sandbox certain libc calls will fail (localtime
593 // being the motivating example - it needs to read /etc/localtime). We need to
594 // intercept these calls and proxy them to the browser. However, these calls
595 // may come from us or from our libraries. In some cases we can't just change
596 // our code.
598 // It's for these cases that we have the following setup:
600 // We define global functions for those functions which we wish to override.
601 // Since we will be first in the dynamic resolution order, the dynamic linker
602 // will point callers to our versions of these functions. However, we have the
603 // same binary for both the browser and the renderers, which means that our
604 // overrides will apply in the browser too.
606 // The global |g_am_zygote_or_renderer| is true iff we are in a zygote or
607 // renderer process. It's set in ZygoteMain and inherited by the renderers when
608 // they fork. (This means that it'll be incorrect for global constructor
609 // functions and before ZygoteMain is called - beware).
611 // Our replacement functions can check this global and either proxy
612 // the call to the browser over the sandbox IPC
613 // (http://code.google.com/p/chromium/wiki/LinuxSandboxIPC) or they can use
614 // dlsym with RTLD_NEXT to resolve the symbol, ignoring any symbols in the
615 // current module.
617 // Other avenues:
619 // Our first attempt involved some assembly to patch the GOT of the current
620 // module. This worked, but was platform specific and doesn't catch the case
621 // where a library makes a call rather than current module.
623 // We also considered patching the function in place, but this would again by
624 // platform specific and the above technique seems to work well enough.
626 typedef struct tm* (*LocaltimeFunction)(const time_t* timep);
627 typedef struct tm* (*LocaltimeRFunction)(const time_t* timep,
628 struct tm* result);
630 static pthread_once_t g_libc_localtime_funcs_guard = PTHREAD_ONCE_INIT;
631 static LocaltimeFunction g_libc_localtime;
632 static LocaltimeRFunction g_libc_localtime_r;
634 static void InitLibcLocaltimeFunctions() {
635 g_libc_localtime = reinterpret_cast<LocaltimeFunction>(
636 dlsym(RTLD_NEXT, "localtime"));
637 g_libc_localtime_r = reinterpret_cast<LocaltimeRFunction>(
638 dlsym(RTLD_NEXT, "localtime_r"));
640 if (!g_libc_localtime || !g_libc_localtime_r) {
641 // http://code.google.com/p/chromium/issues/detail?id=16800
643 // Nvidia's libGL.so overrides dlsym for an unknown reason and replaces
644 // it with a version which doesn't work. In this case we'll get a NULL
645 // result. There's not a lot we can do at this point, so we just bodge it!
646 LOG(ERROR) << "Your system is broken: dlsym doesn't work! This has been "
647 "reported to be caused by Nvidia's libGL. You should expect"
648 " time related functions to misbehave. "
649 "http://code.google.com/p/chromium/issues/detail?id=16800";
652 if (!g_libc_localtime)
653 g_libc_localtime = gmtime;
654 if (!g_libc_localtime_r)
655 g_libc_localtime_r = gmtime_r;
658 struct tm* localtime(const time_t* timep) {
659 if (g_am_zygote_or_renderer) {
660 static struct tm time_struct;
661 static char timezone_string[64];
662 ProxyLocaltimeCallToBrowser(*timep, &time_struct, timezone_string,
663 sizeof(timezone_string));
664 return &time_struct;
665 } else {
666 CHECK_EQ(0, pthread_once(&g_libc_localtime_funcs_guard,
667 InitLibcLocaltimeFunctions));
668 return g_libc_localtime(timep);
672 struct tm* localtime_r(const time_t* timep, struct tm* result) {
673 if (g_am_zygote_or_renderer) {
674 ProxyLocaltimeCallToBrowser(*timep, result, NULL, 0);
675 return result;
676 } else {
677 CHECK_EQ(0, pthread_once(&g_libc_localtime_funcs_guard,
678 InitLibcLocaltimeFunctions));
679 return g_libc_localtime_r(timep, result);
683 #endif // !CHROMIUM_SELINUX
685 // This function triggers the static and lazy construction of objects that need
686 // to be created before imposing the sandbox.
687 static void PreSandboxInit() {
688 base::RandUint64();
690 base::SysInfo::MaxSharedMemorySize();
692 // ICU DateFormat class (used in base/time_format.cc) needs to get the
693 // Olson timezone ID by accessing the zoneinfo files on disk. After
694 // TimeZone::createDefault is called once here, the timezone ID is
695 // cached and there's no more need to access the file system.
696 scoped_ptr<icu::TimeZone> zone(icu::TimeZone::createDefault());
698 #if defined(USE_NSS)
699 // NSS libraries are loaded before sandbox is activated. This is to allow
700 // successful initialization of NSS which tries to load extra library files.
701 crypto::LoadNSSLibraries();
702 #elif defined(USE_OPENSSL)
703 // OpenSSL is intentionally not supported in the sandboxed processes, see
704 // http://crbug.com/99163. If that ever changes we'll likely need to init
705 // OpenSSL here (at least, load the library and error strings).
706 #else
707 // It's possible that another hypothetical crypto stack would not require
708 // pre-sandbox init, but more likely this is just a build configuration error.
709 #error Which SSL library are you using?
710 #endif
712 // Ensure access to the Pepper plugins before the sandbox is turned on.
713 PepperPluginRegistry::PreloadModules();
716 #if !defined(CHROMIUM_SELINUX)
717 static bool EnterSandbox() {
718 // The SUID sandbox sets this environment variable to a file descriptor
719 // over which we can signal that we have completed our startup and can be
720 // chrooted.
721 const char* const sandbox_fd_string = getenv("SBX_D");
723 if (sandbox_fd_string) {
724 // Use the SUID sandbox. This still allows the seccomp sandbox to
725 // be enabled by the process later.
726 g_suid_sandbox_active = true;
728 char* endptr;
729 const long fd_long = strtol(sandbox_fd_string, &endptr, 10);
730 if (!*sandbox_fd_string || *endptr || fd_long < 0 || fd_long > INT_MAX)
731 return false;
732 const int fd = fd_long;
734 PreSandboxInit();
736 static const char kMsgChrootMe = 'C';
737 static const char kMsgChrootSuccessful = 'O';
739 if (HANDLE_EINTR(write(fd, &kMsgChrootMe, 1)) != 1) {
740 LOG(ERROR) << "Failed to write to chroot pipe: " << errno;
741 return false;
744 // We need to reap the chroot helper process in any event:
745 wait(NULL);
747 char reply;
748 if (HANDLE_EINTR(read(fd, &reply, 1)) != 1) {
749 LOG(ERROR) << "Failed to read from chroot pipe: " << errno;
750 return false;
753 if (reply != kMsgChrootSuccessful) {
754 LOG(ERROR) << "Error code reply from chroot helper";
755 return false;
758 SkiaFontConfigSetImplementation(
759 new FontConfigIPC(kMagicSandboxIPCDescriptor));
761 // Previously, we required that the binary be non-readable. This causes the
762 // kernel to mark the process as non-dumpable at startup. The thinking was
763 // that, although we were putting the renderers into a PID namespace (with
764 // the SUID sandbox), they would nonetheless be in the /same/ PID
765 // namespace. So they could ptrace each other unless they were non-dumpable.
767 // If the binary was readable, then there would be a window between process
768 // startup and the point where we set the non-dumpable flag in which a
769 // compromised renderer could ptrace attach.
771 // However, now that we have a zygote model, only the (trusted) zygote
772 // exists at this point and we can set the non-dumpable flag which is
773 // inherited by all our renderer children.
775 // Note: a non-dumpable process can't be debugged. To debug sandbox-related
776 // issues, one can specify --allow-sandbox-debugging to let the process be
777 // dumpable.
778 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
779 if (!command_line.HasSwitch(switches::kAllowSandboxDebugging)) {
780 prctl(PR_SET_DUMPABLE, 0, 0, 0, 0);
781 if (prctl(PR_GET_DUMPABLE, 0, 0, 0, 0)) {
782 LOG(ERROR) << "Failed to set non-dumpable flag";
783 return false;
786 #if defined(SECCOMP_SANDBOX)
787 } else if (SeccompSandboxEnabled()) {
788 PreSandboxInit();
789 SkiaFontConfigSetImplementation(
790 new FontConfigIPC(kMagicSandboxIPCDescriptor));
791 #endif
792 } else {
793 SkiaFontConfigUseDirectImplementation();
796 return true;
798 #else // CHROMIUM_SELINUX
800 static bool EnterSandbox() {
801 PreSandboxInit();
802 SkiaFontConfigUseIPCImplementation(kMagicSandboxIPCDescriptor);
803 return true;
806 #endif // CHROMIUM_SELINUX
808 bool ZygoteMain(const MainFunctionParams& params,
809 ZygoteForkDelegate* forkdelegate) {
810 #if !defined(CHROMIUM_SELINUX)
811 g_am_zygote_or_renderer = true;
812 #endif
814 #if defined(SECCOMP_SANDBOX)
815 if (SeccompSandboxEnabled()) {
816 // The seccomp sandbox needs access to files in /proc, which might be denied
817 // after one of the other sandboxes have been started. So, obtain a suitable
818 // file handle in advance.
819 g_proc_fd = open("/proc", O_DIRECTORY | O_RDONLY);
820 if (g_proc_fd < 0) {
821 LOG(ERROR) << "WARNING! Cannot access \"/proc\". Disabling seccomp "
822 "sandboxing.";
825 #endif // SECCOMP_SANDBOX
827 if (forkdelegate != NULL) {
828 VLOG(1) << "ZygoteMain: initializing fork delegate";
829 forkdelegate->Init(getenv("SBX_D") != NULL, // g_suid_sandbox_active,
830 kBrowserDescriptor,
831 kMagicSandboxIPCDescriptor);
832 } else {
833 VLOG(1) << "ZygoteMain: fork delegate is NULL";
836 // Turn on the SELinux or SUID sandbox
837 if (!EnterSandbox()) {
838 LOG(FATAL) << "Failed to enter sandbox. Fail safe abort. (errno: "
839 << errno << ")";
840 return false;
843 int sandbox_flags = 0;
844 if (getenv("SBX_D"))
845 sandbox_flags |= ZygoteHost::kSandboxSUID;
846 if (getenv("SBX_PID_NS"))
847 sandbox_flags |= ZygoteHost::kSandboxPIDNS;
848 if (getenv("SBX_NET_NS"))
849 sandbox_flags |= ZygoteHost::kSandboxNetNS;
851 #if defined(SECCOMP_SANDBOX)
852 // The seccomp sandbox will be turned on when the renderers start. But we can
853 // already check if sufficient support is available so that we only need to
854 // print one error message for the entire browser session.
855 if (g_proc_fd >= 0 && SeccompSandboxEnabled()) {
856 if (!SupportsSeccompSandbox(g_proc_fd)) {
857 // There are a good number of users who cannot use the seccomp sandbox
858 // (e.g. because their distribution does not enable seccomp mode by
859 // default). While we would prefer to deny execution in this case, it
860 // seems more realistic to continue in degraded mode.
861 LOG(ERROR) << "WARNING! This machine lacks support needed for the "
862 "Seccomp sandbox. Running renderers with Seccomp "
863 "sandboxing disabled.";
864 } else {
865 VLOG(1) << "Enabling experimental Seccomp sandbox.";
866 sandbox_flags |= ZygoteHost::kSandboxSeccomp;
869 #endif // SECCOMP_SANDBOX
871 Zygote zygote(sandbox_flags, forkdelegate);
872 // This function call can return multiple times, once per fork().
873 return zygote.ProcessRequests();