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 "content/zygote/zygote_main.h"
12 #include <sys/socket.h>
13 #include <sys/types.h>
18 #include "base/basictypes.h"
19 #include "base/bind.h"
20 #include "base/command_line.h"
21 #include "base/compiler_specific.h"
22 #include "base/memory/scoped_vector.h"
23 #include "base/native_library.h"
24 #include "base/pickle.h"
25 #include "base/posix/eintr_wrapper.h"
26 #include "base/posix/unix_domain_socket_linux.h"
27 #include "base/rand_util.h"
28 #include "base/strings/safe_sprintf.h"
29 #include "base/strings/string_number_conversions.h"
30 #include "base/sys_info.h"
31 #include "build/build_config.h"
32 #include "content/common/child_process_sandbox_support_impl_linux.h"
33 #include "content/common/font_config_ipc_linux.h"
34 #include "content/common/sandbox_linux/sandbox_debug_handling_linux.h"
35 #include "content/common/sandbox_linux/sandbox_linux.h"
36 #include "content/common/zygote_commands_linux.h"
37 #include "content/public/common/content_switches.h"
38 #include "content/public/common/main_function_params.h"
39 #include "content/public/common/sandbox_linux.h"
40 #include "content/public/common/zygote_fork_delegate_linux.h"
41 #include "content/zygote/zygote_linux.h"
42 #include "crypto/nss_util.h"
43 #include "sandbox/linux/services/credentials.h"
44 #include "sandbox/linux/services/init_process_reaper.h"
45 #include "sandbox/linux/services/libc_urandom_override.h"
46 #include "sandbox/linux/services/namespace_sandbox.h"
47 #include "sandbox/linux/services/thread_helpers.h"
48 #include "sandbox/linux/suid/client/setuid_sandbox_client.h"
49 #include "third_party/icu/source/i18n/unicode/timezone.h"
50 #include "third_party/skia/include/ports/SkFontConfigInterface.h"
53 #include <sys/prctl.h>
56 #if defined(USE_OPENSSL)
57 #include <openssl/rand.h>
60 #if defined(ENABLE_PLUGINS)
61 #include "content/common/pepper_plugin_list.h"
62 #include "content/public/common/pepper_plugin_info.h"
65 #if defined(ENABLE_WEBRTC)
66 #include "third_party/libjingle/overrides/init_webrtc.h"
69 #if defined(SANITIZER_COVERAGE)
70 #include <sanitizer/common_interface_defs.h>
71 #include <sanitizer/coverage_interface.h>
78 void CloseFds(const std::vector
<int>& fds
) {
79 for (const auto& it
: fds
) {
80 PCHECK(0 == IGNORE_EINTR(close(it
)));
84 void RunTwoClosures(const base::Closure
* first
, const base::Closure
* second
) {
91 // See http://code.google.com/p/chromium/wiki/LinuxZygote
93 static void ProxyLocaltimeCallToBrowser(time_t input
, struct tm
* output
,
95 size_t timezone_out_len
) {
97 request
.WriteInt(LinuxSandbox::METHOD_LOCALTIME
);
99 std::string(reinterpret_cast<char*>(&input
), sizeof(input
)));
101 uint8_t reply_buf
[512];
102 const ssize_t r
= base::UnixDomainSocket::SendRecvMsg(
103 GetSandboxFD(), reply_buf
, sizeof(reply_buf
), NULL
, request
);
105 memset(output
, 0, sizeof(struct tm
));
109 base::Pickle
reply(reinterpret_cast<char*>(reply_buf
), r
);
110 base::PickleIterator
iter(reply
);
111 std::string result
, timezone
;
112 if (!iter
.ReadString(&result
) ||
113 !iter
.ReadString(&timezone
) ||
114 result
.size() != sizeof(struct tm
)) {
115 memset(output
, 0, sizeof(struct tm
));
119 memcpy(output
, result
.data(), sizeof(struct tm
));
120 if (timezone_out_len
) {
121 const size_t copy_len
= std::min(timezone_out_len
- 1, timezone
.size());
122 memcpy(timezone_out
, timezone
.data(), copy_len
);
123 timezone_out
[copy_len
] = 0;
124 output
->tm_zone
= timezone_out
;
126 output
->tm_zone
= NULL
;
130 static bool g_am_zygote_or_renderer
= false;
132 // Sandbox interception of libc calls.
134 // Because we are running in a sandbox certain libc calls will fail (localtime
135 // being the motivating example - it needs to read /etc/localtime). We need to
136 // intercept these calls and proxy them to the browser. However, these calls
137 // may come from us or from our libraries. In some cases we can't just change
140 // It's for these cases that we have the following setup:
142 // We define global functions for those functions which we wish to override.
143 // Since we will be first in the dynamic resolution order, the dynamic linker
144 // will point callers to our versions of these functions. However, we have the
145 // same binary for both the browser and the renderers, which means that our
146 // overrides will apply in the browser too.
148 // The global |g_am_zygote_or_renderer| is true iff we are in a zygote or
149 // renderer process. It's set in ZygoteMain and inherited by the renderers when
150 // they fork. (This means that it'll be incorrect for global constructor
151 // functions and before ZygoteMain is called - beware).
153 // Our replacement functions can check this global and either proxy
154 // the call to the browser over the sandbox IPC
155 // (http://code.google.com/p/chromium/wiki/LinuxSandboxIPC) or they can use
156 // dlsym with RTLD_NEXT to resolve the symbol, ignoring any symbols in the
161 // Our first attempt involved some assembly to patch the GOT of the current
162 // module. This worked, but was platform specific and doesn't catch the case
163 // where a library makes a call rather than current module.
165 // We also considered patching the function in place, but this would again by
166 // platform specific and the above technique seems to work well enough.
168 typedef struct tm
* (*LocaltimeFunction
)(const time_t* timep
);
169 typedef struct tm
* (*LocaltimeRFunction
)(const time_t* timep
,
172 static pthread_once_t g_libc_localtime_funcs_guard
= PTHREAD_ONCE_INIT
;
173 static LocaltimeFunction g_libc_localtime
;
174 static LocaltimeFunction g_libc_localtime64
;
175 static LocaltimeRFunction g_libc_localtime_r
;
176 static LocaltimeRFunction g_libc_localtime64_r
;
178 static void InitLibcLocaltimeFunctions() {
179 g_libc_localtime
= reinterpret_cast<LocaltimeFunction
>(
180 dlsym(RTLD_NEXT
, "localtime"));
181 g_libc_localtime64
= reinterpret_cast<LocaltimeFunction
>(
182 dlsym(RTLD_NEXT
, "localtime64"));
183 g_libc_localtime_r
= reinterpret_cast<LocaltimeRFunction
>(
184 dlsym(RTLD_NEXT
, "localtime_r"));
185 g_libc_localtime64_r
= reinterpret_cast<LocaltimeRFunction
>(
186 dlsym(RTLD_NEXT
, "localtime64_r"));
188 if (!g_libc_localtime
|| !g_libc_localtime_r
) {
189 // http://code.google.com/p/chromium/issues/detail?id=16800
191 // Nvidia's libGL.so overrides dlsym for an unknown reason and replaces
192 // it with a version which doesn't work. In this case we'll get a NULL
193 // result. There's not a lot we can do at this point, so we just bodge it!
194 LOG(ERROR
) << "Your system is broken: dlsym doesn't work! This has been "
195 "reported to be caused by Nvidia's libGL. You should expect"
196 " time related functions to misbehave. "
197 "http://code.google.com/p/chromium/issues/detail?id=16800";
200 if (!g_libc_localtime
)
201 g_libc_localtime
= gmtime
;
202 if (!g_libc_localtime64
)
203 g_libc_localtime64
= g_libc_localtime
;
204 if (!g_libc_localtime_r
)
205 g_libc_localtime_r
= gmtime_r
;
206 if (!g_libc_localtime64_r
)
207 g_libc_localtime64_r
= g_libc_localtime_r
;
210 // Define localtime_override() function with asm name "localtime", so that all
211 // references to localtime() will resolve to this function. Notice that we need
212 // to set visibility attribute to "default" to export the symbol, as it is set
213 // to "hidden" by default in chrome per build/common.gypi.
214 __attribute__ ((__visibility__("default")))
215 struct tm
* localtime_override(const time_t* timep
) __asm__ ("localtime");
217 __attribute__ ((__visibility__("default")))
218 struct tm
* localtime_override(const time_t* timep
) {
219 if (g_am_zygote_or_renderer
) {
220 static struct tm time_struct
;
221 static char timezone_string
[64];
222 ProxyLocaltimeCallToBrowser(*timep
, &time_struct
, timezone_string
,
223 sizeof(timezone_string
));
226 CHECK_EQ(0, pthread_once(&g_libc_localtime_funcs_guard
,
227 InitLibcLocaltimeFunctions
));
228 struct tm
* res
= g_libc_localtime(timep
);
229 #if defined(MEMORY_SANITIZER)
230 if (res
) __msan_unpoison(res
, sizeof(*res
));
231 if (res
->tm_zone
) __msan_unpoison_string(res
->tm_zone
);
237 // Use same trick to override localtime64(), localtime_r() and localtime64_r().
238 __attribute__ ((__visibility__("default")))
239 struct tm
* localtime64_override(const time_t* timep
) __asm__ ("localtime64");
241 __attribute__ ((__visibility__("default")))
242 struct tm
* localtime64_override(const time_t* timep
) {
243 if (g_am_zygote_or_renderer
) {
244 static struct tm time_struct
;
245 static char timezone_string
[64];
246 ProxyLocaltimeCallToBrowser(*timep
, &time_struct
, timezone_string
,
247 sizeof(timezone_string
));
250 CHECK_EQ(0, pthread_once(&g_libc_localtime_funcs_guard
,
251 InitLibcLocaltimeFunctions
));
252 struct tm
* res
= g_libc_localtime64(timep
);
253 #if defined(MEMORY_SANITIZER)
254 if (res
) __msan_unpoison(res
, sizeof(*res
));
255 if (res
->tm_zone
) __msan_unpoison_string(res
->tm_zone
);
261 __attribute__ ((__visibility__("default")))
262 struct tm
* localtime_r_override(const time_t* timep
,
263 struct tm
* result
) __asm__ ("localtime_r");
265 __attribute__ ((__visibility__("default")))
266 struct tm
* localtime_r_override(const time_t* timep
, struct tm
* result
) {
267 if (g_am_zygote_or_renderer
) {
268 ProxyLocaltimeCallToBrowser(*timep
, result
, NULL
, 0);
271 CHECK_EQ(0, pthread_once(&g_libc_localtime_funcs_guard
,
272 InitLibcLocaltimeFunctions
));
273 struct tm
* res
= g_libc_localtime_r(timep
, result
);
274 #if defined(MEMORY_SANITIZER)
275 if (res
) __msan_unpoison(res
, sizeof(*res
));
276 if (res
->tm_zone
) __msan_unpoison_string(res
->tm_zone
);
282 __attribute__ ((__visibility__("default")))
283 struct tm
* localtime64_r_override(const time_t* timep
,
284 struct tm
* result
) __asm__ ("localtime64_r");
286 __attribute__ ((__visibility__("default")))
287 struct tm
* localtime64_r_override(const time_t* timep
, struct tm
* result
) {
288 if (g_am_zygote_or_renderer
) {
289 ProxyLocaltimeCallToBrowser(*timep
, result
, NULL
, 0);
292 CHECK_EQ(0, pthread_once(&g_libc_localtime_funcs_guard
,
293 InitLibcLocaltimeFunctions
));
294 struct tm
* res
= g_libc_localtime64_r(timep
, result
);
295 #if defined(MEMORY_SANITIZER)
296 if (res
) __msan_unpoison(res
, sizeof(*res
));
297 if (res
->tm_zone
) __msan_unpoison_string(res
->tm_zone
);
303 #if defined(ENABLE_PLUGINS)
304 // Loads the (native) libraries but does not initialize them (i.e., does not
305 // call PPP_InitializeModule). This is needed by the zygote on Linux to get
306 // access to the plugins before entering the sandbox.
307 void PreloadPepperPlugins() {
308 std::vector
<PepperPluginInfo
> plugins
;
309 ComputePepperPluginList(&plugins
);
310 for (size_t i
= 0; i
< plugins
.size(); ++i
) {
311 if (!plugins
[i
].is_internal
) {
312 base::NativeLibraryLoadError error
;
313 base::NativeLibrary library
= base::LoadNativeLibrary(plugins
[i
].path
,
315 VLOG_IF(1, !library
) << "Unable to load plugin "
316 << plugins
[i
].path
.value() << " "
319 (void)library
; // Prevent release-mode warning.
325 // This function triggers the static and lazy construction of objects that need
326 // to be created before imposing the sandbox.
327 static void ZygotePreSandboxInit() {
330 base::SysInfo::AmountOfPhysicalMemory();
331 base::SysInfo::MaxSharedMemorySize();
332 base::SysInfo::NumberOfProcessors();
334 // ICU DateFormat class (used in base/time_format.cc) needs to get the
335 // Olson timezone ID by accessing the zoneinfo files on disk. After
336 // TimeZone::createDefault is called once here, the timezone ID is
337 // cached and there's no more need to access the file system.
338 scoped_ptr
<icu::TimeZone
> zone(icu::TimeZone::createDefault());
340 #if defined(USE_NSS_CERTS)
341 // NSS libraries are loaded before sandbox is activated. This is to allow
342 // successful initialization of NSS which tries to load extra library files.
343 crypto::LoadNSSLibraries();
344 #elif defined(USE_OPENSSL)
345 // Read a random byte in order to cause BoringSSL to open a file descriptor
348 RAND_bytes(&scratch
, 1);
350 // It's possible that another hypothetical crypto stack would not require
351 // pre-sandbox init, but more likely this is just a build configuration error.
352 #error Which SSL library are you using?
354 #if defined(ENABLE_PLUGINS)
355 // Ensure access to the Pepper plugins before the sandbox is turned on.
356 PreloadPepperPlugins();
358 #if defined(ENABLE_WEBRTC)
359 InitializeWebRtcModule();
361 SkFontConfigInterface::SetGlobal(
362 new FontConfigIPC(GetSandboxFD()))->unref();
365 static bool CreateInitProcessReaper(base::Closure
* post_fork_parent_callback
) {
366 // The current process becomes init(1), this function returns from a
367 // newly created process.
368 const bool init_created
=
369 sandbox::CreateInitProcessReaper(post_fork_parent_callback
);
371 LOG(ERROR
) << "Error creating an init process to reap zombies";
377 // Enter the setuid sandbox. This requires the current process to have been
378 // created through the setuid sandbox.
379 static bool EnterSuidSandbox(sandbox::SetuidSandboxClient
* setuid_sandbox
,
380 base::Closure
* post_fork_parent_callback
) {
381 DCHECK(setuid_sandbox
);
382 DCHECK(setuid_sandbox
->IsSuidSandboxChild());
384 // Use the SUID sandbox. This still allows the seccomp sandbox to
385 // be enabled by the process later.
387 if (!setuid_sandbox
->IsSuidSandboxUpToDate()) {
389 "You are using a wrong version of the setuid binary!\n"
391 "https://code.google.com/p/chromium/wiki/LinuxSUIDSandboxDevelopment."
395 if (!setuid_sandbox
->ChrootMe())
398 if (setuid_sandbox
->IsInNewPIDNamespace()) {
399 CHECK_EQ(1, getpid())
400 << "The SUID sandbox created a new PID namespace but Zygote "
401 "is not the init process. Please, make sure the SUID "
402 "binary is up to date.";
406 // The setuid sandbox has created a new PID namespace and we need
407 // to assume the role of init.
408 CHECK(CreateInitProcessReaper(post_fork_parent_callback
));
411 CHECK(SandboxDebugHandling::SetDumpableStatusAndHandlers());
415 static void DropAllCapabilities(int proc_fd
) {
416 CHECK(sandbox::Credentials::DropAllCapabilities(proc_fd
));
419 static void EnterNamespaceSandbox(LinuxSandbox
* linux_sandbox
,
420 base::Closure
* post_fork_parent_callback
) {
421 linux_sandbox
->EngageNamespaceSandbox();
424 base::Closure drop_all_caps_callback
=
425 base::Bind(&DropAllCapabilities
, linux_sandbox
->proc_fd());
426 base::Closure callback
= base::Bind(
427 &RunTwoClosures
, &drop_all_caps_callback
, post_fork_parent_callback
);
428 CHECK(CreateInitProcessReaper(&callback
));
432 #if defined(SANITIZER_COVERAGE)
433 const size_t kSanitizerMaxMessageLength
= 1 * 1024 * 1024;
435 // A helper process which collects code coverage data from the renderers over a
436 // socket and dumps it to a file. See http://crbug.com/336212 for discussion.
437 static void SanitizerCoverageHelper(int socket_fd
, int file_fd
) {
438 scoped_ptr
<char[]> buffer(new char[kSanitizerMaxMessageLength
]);
440 ssize_t received_size
= HANDLE_EINTR(
441 recv(socket_fd
, buffer
.get(), kSanitizerMaxMessageLength
, 0));
442 PCHECK(received_size
>= 0);
443 if (received_size
== 0)
444 // All clients have closed the socket. We should die.
446 PCHECK(file_fd
>= 0);
447 ssize_t written_size
= 0;
448 while (written_size
< received_size
) {
450 HANDLE_EINTR(write(file_fd
, buffer
.get() + written_size
,
451 received_size
- written_size
));
452 PCHECK(write_res
>= 0);
453 written_size
+= write_res
;
455 PCHECK(0 == HANDLE_EINTR(fsync(file_fd
)));
459 // fds[0] is the read end, fds[1] is the write end.
460 static void CreateSanitizerCoverageSocketPair(int fds
[2]) {
461 PCHECK(0 == socketpair(AF_UNIX
, SOCK_SEQPACKET
, 0, fds
));
462 PCHECK(0 == shutdown(fds
[0], SHUT_WR
));
463 PCHECK(0 == shutdown(fds
[1], SHUT_RD
));
466 static pid_t
ForkSanitizerCoverageHelper(
469 base::ScopedFD file_fd
,
470 const std::vector
<int>& extra_fds_to_close
) {
475 PCHECK(0 == IGNORE_EINTR(close(parent_fd
)));
476 CloseFds(extra_fds_to_close
);
477 SanitizerCoverageHelper(child_fd
, file_fd
.get());
481 PCHECK(0 == IGNORE_EINTR(close(child_fd
)));
486 #endif // defined(SANITIZER_COVERAGE)
488 static void EnterLayerOneSandbox(LinuxSandbox
* linux_sandbox
,
489 const bool using_layer1_sandbox
,
490 base::Closure
* post_fork_parent_callback
) {
491 DCHECK(linux_sandbox
);
493 ZygotePreSandboxInit();
495 // Check that the pre-sandbox initialization didn't spawn threads.
496 #if !defined(THREAD_SANITIZER)
497 DCHECK(sandbox::ThreadHelpers::IsSingleThreaded());
500 sandbox::SetuidSandboxClient
* setuid_sandbox
=
501 linux_sandbox
->setuid_sandbox_client();
502 if (setuid_sandbox
->IsSuidSandboxChild()) {
503 CHECK(EnterSuidSandbox(setuid_sandbox
, post_fork_parent_callback
))
504 << "Failed to enter setuid sandbox";
505 } else if (sandbox::NamespaceSandbox::InNewUserNamespace()) {
506 EnterNamespaceSandbox(linux_sandbox
, post_fork_parent_callback
);
508 CHECK(!using_layer1_sandbox
);
512 bool ZygoteMain(const MainFunctionParams
& params
,
513 ScopedVector
<ZygoteForkDelegate
> fork_delegates
) {
514 g_am_zygote_or_renderer
= true;
515 sandbox::InitLibcUrandomOverrides();
517 std::vector
<int> fds_to_close_post_fork
;
519 LinuxSandbox
* linux_sandbox
= LinuxSandbox::GetInstance();
521 #if defined(SANITIZER_COVERAGE)
522 const std::string sancov_file_name
=
523 "zygote." + base::Uint64ToString(base::RandUint64());
524 base::ScopedFD
sancov_file_fd(
525 __sanitizer_maybe_open_cov_file(sancov_file_name
.c_str()));
526 int sancov_socket_fds
[2] = {-1, -1};
527 CreateSanitizerCoverageSocketPair(sancov_socket_fds
);
528 linux_sandbox
->sanitizer_args()->coverage_sandboxed
= 1;
529 linux_sandbox
->sanitizer_args()->coverage_fd
= sancov_socket_fds
[1];
530 linux_sandbox
->sanitizer_args()->coverage_max_block_size
=
531 kSanitizerMaxMessageLength
;
532 // Zygote termination will block until the helper process exits, which will
533 // not happen until the write end of the socket is closed everywhere. Make
534 // sure the init process does not hold on to it.
535 fds_to_close_post_fork
.push_back(sancov_socket_fds
[0]);
536 fds_to_close_post_fork
.push_back(sancov_socket_fds
[1]);
537 #endif // SANITIZER_COVERAGE
539 // Skip pre-initializing sandbox under --no-sandbox for crbug.com/444900.
540 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
541 switches::kNoSandbox
)) {
542 // This will pre-initialize the various sandboxes that need it.
543 linux_sandbox
->PreinitializeSandbox();
546 const bool using_setuid_sandbox
=
547 linux_sandbox
->setuid_sandbox_client()->IsSuidSandboxChild();
548 const bool using_namespace_sandbox
=
549 sandbox::NamespaceSandbox::InNewUserNamespace();
550 const bool using_layer1_sandbox
=
551 using_setuid_sandbox
|| using_namespace_sandbox
;
553 if (using_setuid_sandbox
) {
554 linux_sandbox
->setuid_sandbox_client()->CloseDummyFile();
557 if (using_layer1_sandbox
) {
558 // Let the ZygoteHost know we're booting up.
559 CHECK(base::UnixDomainSocket::SendMsg(kZygoteSocketPairFd
,
561 sizeof(kZygoteBootMessage
),
562 std::vector
<int>()));
565 VLOG(1) << "ZygoteMain: initializing " << fork_delegates
.size()
566 << " fork delegates";
567 for (ZygoteForkDelegate
* fork_delegate
: fork_delegates
) {
568 fork_delegate
->Init(GetSandboxFD(), using_layer1_sandbox
);
571 const std::vector
<int> sandbox_fds_to_close_post_fork
=
572 linux_sandbox
->GetFileDescriptorsToClose();
574 fds_to_close_post_fork
.insert(fds_to_close_post_fork
.end(),
575 sandbox_fds_to_close_post_fork
.begin(),
576 sandbox_fds_to_close_post_fork
.end());
577 base::Closure post_fork_parent_callback
=
578 base::Bind(&CloseFds
, fds_to_close_post_fork
);
580 // Turn on the first layer of the sandbox if the configuration warrants it.
581 EnterLayerOneSandbox(linux_sandbox
, using_layer1_sandbox
,
582 &post_fork_parent_callback
);
584 // Extra children and file descriptors created that the Zygote must have
586 std::vector
<pid_t
> extra_children
;
587 std::vector
<int> extra_fds
;
589 #if defined(SANITIZER_COVERAGE)
590 pid_t sancov_helper_pid
= ForkSanitizerCoverageHelper(
591 sancov_socket_fds
[0], sancov_socket_fds
[1], sancov_file_fd
.Pass(),
592 sandbox_fds_to_close_post_fork
);
593 // It's important that the zygote reaps the helper before dying. Otherwise,
594 // the destruction of the PID namespace could kill the helper before it
595 // completes its I/O tasks. |sancov_helper_pid| will exit once the last
596 // renderer holding the write end of |sancov_socket_fds| closes it.
597 extra_children
.push_back(sancov_helper_pid
);
598 // Sanitizer code in the renderers will inherit the write end of the socket
599 // from the zygote. We must keep it open until the very end of the zygote's
600 // lifetime, even though we don't explicitly use it.
601 extra_fds
.push_back(sancov_socket_fds
[1]);
602 #endif // SANITIZER_COVERAGE
604 const int sandbox_flags
= linux_sandbox
->GetStatus();
606 const bool setuid_sandbox_engaged
= sandbox_flags
& kSandboxLinuxSUID
;
607 CHECK_EQ(using_setuid_sandbox
, setuid_sandbox_engaged
);
609 const bool namespace_sandbox_engaged
= sandbox_flags
& kSandboxLinuxUserNS
;
610 CHECK_EQ(using_namespace_sandbox
, namespace_sandbox_engaged
);
612 Zygote
zygote(sandbox_flags
, fork_delegates
.Pass(), extra_children
,
614 // This function call can return multiple times, once per fork().
615 return zygote
.ProcessRequests();
618 } // namespace content