Broke ContentSettingBubbleModelTest.Plugins on Android.
[chromium-blink-merge.git] / content / zygote / zygote_main_linux.cc
blob5396e440b8cc01415d2a60f086444166e936d806
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 #include <dlfcn.h>
6 #include <fcntl.h>
7 #include <pthread.h>
8 #include <stdio.h>
9 #include <sys/socket.h>
10 #include <sys/stat.h>
11 #include <sys/types.h>
12 #include <sys/wait.h>
13 #include <unistd.h>
15 #include "base/basictypes.h"
16 #include "base/command_line.h"
17 #include "base/file_path.h"
18 #include "base/hash_tables.h"
19 #include "base/linux_util.h"
20 #include "base/memory/scoped_ptr.h"
21 #include "base/pickle.h"
22 #include "base/posix/eintr_wrapper.h"
23 #include "base/posix/unix_domain_socket_linux.h"
24 #include "base/process_util.h"
25 #include "base/rand_util.h"
26 #include "base/sys_info.h"
27 #include "build/build_config.h"
28 #include "content/common/font_config_ipc_linux.h"
29 #include "content/common/pepper_plugin_registry.h"
30 #include "content/common/sandbox_linux.h"
31 #include "content/common/zygote_commands_linux.h"
32 #include "content/public/common/content_switches.h"
33 #include "content/public/common/main_function_params.h"
34 #include "content/public/common/sandbox_linux.h"
35 #include "content/public/common/zygote_fork_delegate_linux.h"
36 #include "content/zygote/zygote_linux.h"
37 #include "crypto/nss_util.h"
38 #include "sandbox/linux/services/libc_urandom_override.h"
39 #include "sandbox/linux/suid/client/setuid_sandbox_client.h"
40 #include "skia/ext/SkFontHost_fontconfig_control.h"
41 #include "third_party/icu/public/i18n/unicode/timezone.h"
43 #if defined(OS_LINUX)
44 #include <sys/epoll.h>
45 #include <sys/prctl.h>
46 #include <sys/signal.h>
47 #else
48 #include <signal.h>
49 #endif
51 namespace content {
53 // See http://code.google.com/p/chromium/wiki/LinuxZygote
55 // With SELinux we can carve out a precise sandbox, so we don't have to play
56 // with intercepting libc calls.
57 #if !defined(CHROMIUM_SELINUX)
59 static void ProxyLocaltimeCallToBrowser(time_t input, struct tm* output,
60 char* timezone_out,
61 size_t timezone_out_len) {
62 Pickle request;
63 request.WriteInt(LinuxSandbox::METHOD_LOCALTIME);
64 request.WriteString(
65 std::string(reinterpret_cast<char*>(&input), sizeof(input)));
67 uint8_t reply_buf[512];
68 const ssize_t r = UnixDomainSocket::SendRecvMsg(
69 Zygote::kMagicSandboxIPCDescriptor, reply_buf, sizeof(reply_buf), NULL,
70 request);
71 if (r == -1) {
72 memset(output, 0, sizeof(struct tm));
73 return;
76 Pickle reply(reinterpret_cast<char*>(reply_buf), r);
77 PickleIterator iter(reply);
78 std::string result, timezone;
79 if (!reply.ReadString(&iter, &result) ||
80 !reply.ReadString(&iter, &timezone) ||
81 result.size() != sizeof(struct tm)) {
82 memset(output, 0, sizeof(struct tm));
83 return;
86 memcpy(output, result.data(), sizeof(struct tm));
87 if (timezone_out_len) {
88 const size_t copy_len = std::min(timezone_out_len - 1, timezone.size());
89 memcpy(timezone_out, timezone.data(), copy_len);
90 timezone_out[copy_len] = 0;
91 output->tm_zone = timezone_out;
92 } else {
93 output->tm_zone = NULL;
97 static bool g_am_zygote_or_renderer = false;
99 // Sandbox interception of libc calls.
101 // Because we are running in a sandbox certain libc calls will fail (localtime
102 // being the motivating example - it needs to read /etc/localtime). We need to
103 // intercept these calls and proxy them to the browser. However, these calls
104 // may come from us or from our libraries. In some cases we can't just change
105 // our code.
107 // It's for these cases that we have the following setup:
109 // We define global functions for those functions which we wish to override.
110 // Since we will be first in the dynamic resolution order, the dynamic linker
111 // will point callers to our versions of these functions. However, we have the
112 // same binary for both the browser and the renderers, which means that our
113 // overrides will apply in the browser too.
115 // The global |g_am_zygote_or_renderer| is true iff we are in a zygote or
116 // renderer process. It's set in ZygoteMain and inherited by the renderers when
117 // they fork. (This means that it'll be incorrect for global constructor
118 // functions and before ZygoteMain is called - beware).
120 // Our replacement functions can check this global and either proxy
121 // the call to the browser over the sandbox IPC
122 // (http://code.google.com/p/chromium/wiki/LinuxSandboxIPC) or they can use
123 // dlsym with RTLD_NEXT to resolve the symbol, ignoring any symbols in the
124 // current module.
126 // Other avenues:
128 // Our first attempt involved some assembly to patch the GOT of the current
129 // module. This worked, but was platform specific and doesn't catch the case
130 // where a library makes a call rather than current module.
132 // We also considered patching the function in place, but this would again by
133 // platform specific and the above technique seems to work well enough.
135 typedef struct tm* (*LocaltimeFunction)(const time_t* timep);
136 typedef struct tm* (*LocaltimeRFunction)(const time_t* timep,
137 struct tm* result);
139 static pthread_once_t g_libc_localtime_funcs_guard = PTHREAD_ONCE_INIT;
140 static LocaltimeFunction g_libc_localtime;
141 static LocaltimeFunction g_libc_localtime64;
142 static LocaltimeRFunction g_libc_localtime_r;
143 static LocaltimeRFunction g_libc_localtime64_r;
145 static void InitLibcLocaltimeFunctions() {
146 g_libc_localtime = reinterpret_cast<LocaltimeFunction>(
147 dlsym(RTLD_NEXT, "localtime"));
148 g_libc_localtime64 = reinterpret_cast<LocaltimeFunction>(
149 dlsym(RTLD_NEXT, "localtime64"));
150 g_libc_localtime_r = reinterpret_cast<LocaltimeRFunction>(
151 dlsym(RTLD_NEXT, "localtime_r"));
152 g_libc_localtime64_r = reinterpret_cast<LocaltimeRFunction>(
153 dlsym(RTLD_NEXT, "localtime64_r"));
155 if (!g_libc_localtime || !g_libc_localtime_r) {
156 // http://code.google.com/p/chromium/issues/detail?id=16800
158 // Nvidia's libGL.so overrides dlsym for an unknown reason and replaces
159 // it with a version which doesn't work. In this case we'll get a NULL
160 // result. There's not a lot we can do at this point, so we just bodge it!
161 LOG(ERROR) << "Your system is broken: dlsym doesn't work! This has been "
162 "reported to be caused by Nvidia's libGL. You should expect"
163 " time related functions to misbehave. "
164 "http://code.google.com/p/chromium/issues/detail?id=16800";
167 if (!g_libc_localtime)
168 g_libc_localtime = gmtime;
169 if (!g_libc_localtime64)
170 g_libc_localtime64 = g_libc_localtime;
171 if (!g_libc_localtime_r)
172 g_libc_localtime_r = gmtime_r;
173 if (!g_libc_localtime64_r)
174 g_libc_localtime64_r = g_libc_localtime_r;
177 // Define localtime_override() function with asm name "localtime", so that all
178 // references to localtime() will resolve to this function. Notice that we need
179 // to set visibility attribute to "default" to export the symbol, as it is set
180 // to "hidden" by default in chrome per build/common.gypi.
181 __attribute__ ((__visibility__("default")))
182 struct tm* localtime_override(const time_t* timep) __asm__ ("localtime");
184 __attribute__ ((__visibility__("default")))
185 struct tm* localtime_override(const time_t* timep) {
186 if (g_am_zygote_or_renderer) {
187 static struct tm time_struct;
188 static char timezone_string[64];
189 ProxyLocaltimeCallToBrowser(*timep, &time_struct, timezone_string,
190 sizeof(timezone_string));
191 return &time_struct;
192 } else {
193 CHECK_EQ(0, pthread_once(&g_libc_localtime_funcs_guard,
194 InitLibcLocaltimeFunctions));
195 return g_libc_localtime(timep);
199 // Use same trick to override localtime64(), localtime_r() and localtime64_r().
200 __attribute__ ((__visibility__("default")))
201 struct tm* localtime64_override(const time_t* timep) __asm__ ("localtime64");
203 __attribute__ ((__visibility__("default")))
204 struct tm* localtime64_override(const time_t* timep) {
205 if (g_am_zygote_or_renderer) {
206 static struct tm time_struct;
207 static char timezone_string[64];
208 ProxyLocaltimeCallToBrowser(*timep, &time_struct, timezone_string,
209 sizeof(timezone_string));
210 return &time_struct;
211 } else {
212 CHECK_EQ(0, pthread_once(&g_libc_localtime_funcs_guard,
213 InitLibcLocaltimeFunctions));
214 return g_libc_localtime64(timep);
218 __attribute__ ((__visibility__("default")))
219 struct tm* localtime_r_override(const time_t* timep,
220 struct tm* result) __asm__ ("localtime_r");
222 __attribute__ ((__visibility__("default")))
223 struct tm* localtime_r_override(const time_t* timep, struct tm* result) {
224 if (g_am_zygote_or_renderer) {
225 ProxyLocaltimeCallToBrowser(*timep, result, NULL, 0);
226 return result;
227 } else {
228 CHECK_EQ(0, pthread_once(&g_libc_localtime_funcs_guard,
229 InitLibcLocaltimeFunctions));
230 return g_libc_localtime_r(timep, result);
234 __attribute__ ((__visibility__("default")))
235 struct tm* localtime64_r_override(const time_t* timep,
236 struct tm* result) __asm__ ("localtime64_r");
238 __attribute__ ((__visibility__("default")))
239 struct tm* localtime64_r_override(const time_t* timep, struct tm* result) {
240 if (g_am_zygote_or_renderer) {
241 ProxyLocaltimeCallToBrowser(*timep, result, NULL, 0);
242 return result;
243 } else {
244 CHECK_EQ(0, pthread_once(&g_libc_localtime_funcs_guard,
245 InitLibcLocaltimeFunctions));
246 return g_libc_localtime64_r(timep, result);
250 #endif // !CHROMIUM_SELINUX
252 // This function triggers the static and lazy construction of objects that need
253 // to be created before imposing the sandbox.
254 static void PreSandboxInit() {
255 base::RandUint64();
257 base::SysInfo::MaxSharedMemorySize();
259 // ICU DateFormat class (used in base/time_format.cc) needs to get the
260 // Olson timezone ID by accessing the zoneinfo files on disk. After
261 // TimeZone::createDefault is called once here, the timezone ID is
262 // cached and there's no more need to access the file system.
263 scoped_ptr<icu::TimeZone> zone(icu::TimeZone::createDefault());
265 #if defined(USE_NSS)
266 // NSS libraries are loaded before sandbox is activated. This is to allow
267 // successful initialization of NSS which tries to load extra library files.
268 crypto::LoadNSSLibraries();
269 #elif defined(USE_OPENSSL)
270 // OpenSSL is intentionally not supported in the sandboxed processes, see
271 // http://crbug.com/99163. If that ever changes we'll likely need to init
272 // OpenSSL here (at least, load the library and error strings).
273 #else
274 // It's possible that another hypothetical crypto stack would not require
275 // pre-sandbox init, but more likely this is just a build configuration error.
276 #error Which SSL library are you using?
277 #endif
279 // Ensure access to the Pepper plugins before the sandbox is turned on.
280 PepperPluginRegistry::PreloadModules();
283 #if !defined(CHROMIUM_SELINUX)
284 // Do nothing here
285 static void SIGCHLDHandler(int signal) {
288 // The current process will become a process reaper like init.
289 // We fork a child that will continue normally, when it dies, we can safely
290 // exit.
291 // We need to be careful we close the magic kZygoteIdFd properly in the parent
292 // before this function returns.
293 static bool CreateInitProcessReaper() {
294 int sync_fds[2];
295 // We want to use send, so we can't use a pipe
296 if (socketpair(AF_UNIX, SOCK_STREAM, 0, sync_fds)) {
297 LOG(ERROR) << "Failed to create socketpair";
298 return false;
301 // We use normal fork, not the ForkDelegate in this case since we are not a
302 // true Zygote yet.
303 pid_t child_pid = fork();
304 if (child_pid == -1) {
305 (void) HANDLE_EINTR(close(sync_fds[0]));
306 (void) HANDLE_EINTR(close(sync_fds[1]));
307 return false;
309 if (child_pid) {
310 // We are the parent, assuming the role of an init process.
311 // The disposition for SIGCHLD cannot be SIG_IGN or wait() will only return
312 // once all of our childs are dead. Since we're init we need to reap childs
313 // as they come.
314 struct sigaction action;
315 memset(&action, 0, sizeof(action));
316 action.sa_handler = &SIGCHLDHandler;
317 CHECK(sigaction(SIGCHLD, &action, NULL) == 0);
319 (void) HANDLE_EINTR(close(sync_fds[0]));
320 shutdown(sync_fds[1], SHUT_RD);
321 // This "magic" socket must only appear in one process.
322 (void) HANDLE_EINTR(close(kZygoteIdFd));
323 // Tell the child to continue
324 CHECK(HANDLE_EINTR(send(sync_fds[1], "C", 1, MSG_NOSIGNAL)) == 1);
325 (void) HANDLE_EINTR(close(sync_fds[1]));
327 for (;;) {
328 // Loop until we have reaped our one natural child
329 siginfo_t reaped_child_info;
330 int wait_ret =
331 HANDLE_EINTR(waitid(P_ALL, 0, &reaped_child_info, WEXITED));
332 if (wait_ret)
333 _exit(1);
334 if (reaped_child_info.si_pid == child_pid) {
335 int exit_code = 0;
336 // We're done waiting
337 if (reaped_child_info.si_code == CLD_EXITED) {
338 exit_code = reaped_child_info.si_status;
340 // Exit with the same exit code as our parent. This is most likely
341 // useless. _exit with 0 if we got signaled.
342 _exit(exit_code);
345 } else {
346 // The child needs to wait for the parent to close kZygoteIdFd to avoid a
347 // race condition
348 (void) HANDLE_EINTR(close(sync_fds[1]));
349 shutdown(sync_fds[0], SHUT_WR);
350 char should_continue;
351 int read_ret = HANDLE_EINTR(read(sync_fds[0], &should_continue, 1));
352 (void) HANDLE_EINTR(close(sync_fds[0]));
353 if (read_ret == 1)
354 return true;
355 else
356 return false;
360 // This will set the *using_suid_sandbox variable to true if the SUID sandbox
361 // is enabled. This does not necessarily exclude other types of sandboxing.
362 static bool EnterSandbox(sandbox::SetuidSandboxClient* setuid_sandbox,
363 bool* using_suid_sandbox, bool* has_started_new_init) {
364 *using_suid_sandbox = false;
365 *has_started_new_init = false;
366 if (!setuid_sandbox)
367 return false;
369 PreSandboxInit();
370 SkiaFontConfigSetImplementation(
371 new FontConfigIPC(Zygote::kMagicSandboxIPCDescriptor));
373 if (setuid_sandbox->IsSuidSandboxChild()) {
374 // Use the SUID sandbox. This still allows the seccomp sandbox to
375 // be enabled by the process later.
376 *using_suid_sandbox = true;
378 if (!setuid_sandbox->IsSuidSandboxUpToDate()) {
379 LOG(WARNING) << "You are using a wrong version of the setuid binary!\n"
380 "Please read "
381 "https://code.google.com/p/chromium/wiki/LinuxSUIDSandboxDevelopment."
382 "\n\n";
385 if (!setuid_sandbox->ChrootMe())
386 return false;
388 if (getpid() == 1) {
389 // The setuid sandbox has created a new PID namespace and we need
390 // to assume the role of init.
391 if (!CreateInitProcessReaper()) {
392 LOG(ERROR) << "Error creating an init process to reap zombies";
393 return false;
395 *has_started_new_init = true;
398 #if !defined(OS_OPENBSD)
399 // Previously, we required that the binary be non-readable. This causes the
400 // kernel to mark the process as non-dumpable at startup. The thinking was
401 // that, although we were putting the renderers into a PID namespace (with
402 // the SUID sandbox), they would nonetheless be in the /same/ PID
403 // namespace. So they could ptrace each other unless they were non-dumpable.
405 // If the binary was readable, then there would be a window between process
406 // startup and the point where we set the non-dumpable flag in which a
407 // compromised renderer could ptrace attach.
409 // However, now that we have a zygote model, only the (trusted) zygote
410 // exists at this point and we can set the non-dumpable flag which is
411 // inherited by all our renderer children.
413 // Note: a non-dumpable process can't be debugged. To debug sandbox-related
414 // issues, one can specify --allow-sandbox-debugging to let the process be
415 // dumpable.
416 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
417 if (!command_line.HasSwitch(switches::kAllowSandboxDebugging)) {
418 prctl(PR_SET_DUMPABLE, 0, 0, 0, 0);
419 if (prctl(PR_GET_DUMPABLE, 0, 0, 0, 0)) {
420 LOG(ERROR) << "Failed to set non-dumpable flag";
421 return false;
424 #endif
427 return true;
429 #else // CHROMIUM_SELINUX
431 static bool EnterSandbox(sandbox::SetuidSandboxClient* setuid_sandbox,
432 bool* using_suid_sandbox, bool* has_started_new_init) {
433 *using_suid_sandbox = false;
434 *has_started_new_init = false;
436 if (!setuid_sandbox)
437 return false;
439 PreSandboxInit();
440 SkiaFontConfigSetImplementation(
441 new FontConfigIPC(Zygote::kMagicSandboxIPCDescriptor));
442 return true;
445 #endif // CHROMIUM_SELINUX
447 bool ZygoteMain(const MainFunctionParams& params,
448 ZygoteForkDelegate* forkdelegate) {
449 #if !defined(CHROMIUM_SELINUX)
450 g_am_zygote_or_renderer = true;
451 sandbox::InitLibcUrandomOverrides();
452 #endif
454 LinuxSandbox* linux_sandbox = LinuxSandbox::GetInstance();
455 // This will pre-initialize the various sandboxes that need it.
456 // There need to be a corresponding call to PreinitializeSandboxFinish()
457 // for each new process, this will be done in the Zygote child, once we know
458 // our process type.
459 linux_sandbox->PreinitializeSandboxBegin();
461 sandbox::SetuidSandboxClient* setuid_sandbox =
462 linux_sandbox->setuid_sandbox_client();
464 if (forkdelegate != NULL) {
465 VLOG(1) << "ZygoteMain: initializing fork delegate";
466 forkdelegate->Init(Zygote::kMagicSandboxIPCDescriptor);
467 } else {
468 VLOG(1) << "ZygoteMain: fork delegate is NULL";
471 // Turn on the SELinux or SUID sandbox.
472 bool using_suid_sandbox = false;
473 bool has_started_new_init = false;
475 if (!EnterSandbox(setuid_sandbox,
476 &using_suid_sandbox,
477 &has_started_new_init)) {
478 LOG(FATAL) << "Failed to enter sandbox. Fail safe abort. (errno: "
479 << errno << ")";
480 return false;
483 if (setuid_sandbox->IsInNewPIDNamespace() && !has_started_new_init) {
484 LOG(ERROR) << "The SUID sandbox created a new PID namespace but Zygote "
485 "is not the init process. Please, make sure the SUID "
486 "binary is up to date.";
489 int sandbox_flags = linux_sandbox->GetStatus();
491 Zygote zygote(sandbox_flags, forkdelegate);
492 // This function call can return multiple times, once per fork().
493 return zygote.ProcessRequests();
496 } // namespace content