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
= UnixDomainSocket::SendRecvMsg(
103 GetSandboxFD(), reply_buf
, sizeof(reply_buf
), NULL
,
106 memset(output
, 0, sizeof(struct tm
));
110 Pickle
reply(reinterpret_cast<char*>(reply_buf
), r
);
111 PickleIterator
iter(reply
);
112 std::string result
, timezone
;
113 if (!iter
.ReadString(&result
) ||
114 !iter
.ReadString(&timezone
) ||
115 result
.size() != sizeof(struct tm
)) {
116 memset(output
, 0, sizeof(struct tm
));
120 memcpy(output
, result
.data(), sizeof(struct tm
));
121 if (timezone_out_len
) {
122 const size_t copy_len
= std::min(timezone_out_len
- 1, timezone
.size());
123 memcpy(timezone_out
, timezone
.data(), copy_len
);
124 timezone_out
[copy_len
] = 0;
125 output
->tm_zone
= timezone_out
;
127 output
->tm_zone
= NULL
;
131 static bool g_am_zygote_or_renderer
= false;
133 // Sandbox interception of libc calls.
135 // Because we are running in a sandbox certain libc calls will fail (localtime
136 // being the motivating example - it needs to read /etc/localtime). We need to
137 // intercept these calls and proxy them to the browser. However, these calls
138 // may come from us or from our libraries. In some cases we can't just change
141 // It's for these cases that we have the following setup:
143 // We define global functions for those functions which we wish to override.
144 // Since we will be first in the dynamic resolution order, the dynamic linker
145 // will point callers to our versions of these functions. However, we have the
146 // same binary for both the browser and the renderers, which means that our
147 // overrides will apply in the browser too.
149 // The global |g_am_zygote_or_renderer| is true iff we are in a zygote or
150 // renderer process. It's set in ZygoteMain and inherited by the renderers when
151 // they fork. (This means that it'll be incorrect for global constructor
152 // functions and before ZygoteMain is called - beware).
154 // Our replacement functions can check this global and either proxy
155 // the call to the browser over the sandbox IPC
156 // (http://code.google.com/p/chromium/wiki/LinuxSandboxIPC) or they can use
157 // dlsym with RTLD_NEXT to resolve the symbol, ignoring any symbols in the
162 // Our first attempt involved some assembly to patch the GOT of the current
163 // module. This worked, but was platform specific and doesn't catch the case
164 // where a library makes a call rather than current module.
166 // We also considered patching the function in place, but this would again by
167 // platform specific and the above technique seems to work well enough.
169 typedef struct tm
* (*LocaltimeFunction
)(const time_t* timep
);
170 typedef struct tm
* (*LocaltimeRFunction
)(const time_t* timep
,
173 static pthread_once_t g_libc_localtime_funcs_guard
= PTHREAD_ONCE_INIT
;
174 static LocaltimeFunction g_libc_localtime
;
175 static LocaltimeFunction g_libc_localtime64
;
176 static LocaltimeRFunction g_libc_localtime_r
;
177 static LocaltimeRFunction g_libc_localtime64_r
;
179 static void InitLibcLocaltimeFunctions() {
180 g_libc_localtime
= reinterpret_cast<LocaltimeFunction
>(
181 dlsym(RTLD_NEXT
, "localtime"));
182 g_libc_localtime64
= reinterpret_cast<LocaltimeFunction
>(
183 dlsym(RTLD_NEXT
, "localtime64"));
184 g_libc_localtime_r
= reinterpret_cast<LocaltimeRFunction
>(
185 dlsym(RTLD_NEXT
, "localtime_r"));
186 g_libc_localtime64_r
= reinterpret_cast<LocaltimeRFunction
>(
187 dlsym(RTLD_NEXT
, "localtime64_r"));
189 if (!g_libc_localtime
|| !g_libc_localtime_r
) {
190 // http://code.google.com/p/chromium/issues/detail?id=16800
192 // Nvidia's libGL.so overrides dlsym for an unknown reason and replaces
193 // it with a version which doesn't work. In this case we'll get a NULL
194 // result. There's not a lot we can do at this point, so we just bodge it!
195 LOG(ERROR
) << "Your system is broken: dlsym doesn't work! This has been "
196 "reported to be caused by Nvidia's libGL. You should expect"
197 " time related functions to misbehave. "
198 "http://code.google.com/p/chromium/issues/detail?id=16800";
201 if (!g_libc_localtime
)
202 g_libc_localtime
= gmtime
;
203 if (!g_libc_localtime64
)
204 g_libc_localtime64
= g_libc_localtime
;
205 if (!g_libc_localtime_r
)
206 g_libc_localtime_r
= gmtime_r
;
207 if (!g_libc_localtime64_r
)
208 g_libc_localtime64_r
= g_libc_localtime_r
;
211 // Define localtime_override() function with asm name "localtime", so that all
212 // references to localtime() will resolve to this function. Notice that we need
213 // to set visibility attribute to "default" to export the symbol, as it is set
214 // to "hidden" by default in chrome per build/common.gypi.
215 __attribute__ ((__visibility__("default")))
216 struct tm
* localtime_override(const time_t* timep
) __asm__ ("localtime");
218 __attribute__ ((__visibility__("default")))
219 struct tm
* localtime_override(const time_t* timep
) {
220 if (g_am_zygote_or_renderer
) {
221 static struct tm time_struct
;
222 static char timezone_string
[64];
223 ProxyLocaltimeCallToBrowser(*timep
, &time_struct
, timezone_string
,
224 sizeof(timezone_string
));
227 CHECK_EQ(0, pthread_once(&g_libc_localtime_funcs_guard
,
228 InitLibcLocaltimeFunctions
));
229 struct tm
* res
= g_libc_localtime(timep
);
230 #if defined(MEMORY_SANITIZER)
231 if (res
) __msan_unpoison(res
, sizeof(*res
));
232 if (res
->tm_zone
) __msan_unpoison_string(res
->tm_zone
);
238 // Use same trick to override localtime64(), localtime_r() and localtime64_r().
239 __attribute__ ((__visibility__("default")))
240 struct tm
* localtime64_override(const time_t* timep
) __asm__ ("localtime64");
242 __attribute__ ((__visibility__("default")))
243 struct tm
* localtime64_override(const time_t* timep
) {
244 if (g_am_zygote_or_renderer
) {
245 static struct tm time_struct
;
246 static char timezone_string
[64];
247 ProxyLocaltimeCallToBrowser(*timep
, &time_struct
, timezone_string
,
248 sizeof(timezone_string
));
251 CHECK_EQ(0, pthread_once(&g_libc_localtime_funcs_guard
,
252 InitLibcLocaltimeFunctions
));
253 struct tm
* res
= g_libc_localtime64(timep
);
254 #if defined(MEMORY_SANITIZER)
255 if (res
) __msan_unpoison(res
, sizeof(*res
));
256 if (res
->tm_zone
) __msan_unpoison_string(res
->tm_zone
);
262 __attribute__ ((__visibility__("default")))
263 struct tm
* localtime_r_override(const time_t* timep
,
264 struct tm
* result
) __asm__ ("localtime_r");
266 __attribute__ ((__visibility__("default")))
267 struct tm
* localtime_r_override(const time_t* timep
, struct tm
* result
) {
268 if (g_am_zygote_or_renderer
) {
269 ProxyLocaltimeCallToBrowser(*timep
, result
, NULL
, 0);
272 CHECK_EQ(0, pthread_once(&g_libc_localtime_funcs_guard
,
273 InitLibcLocaltimeFunctions
));
274 struct tm
* res
= g_libc_localtime_r(timep
, result
);
275 #if defined(MEMORY_SANITIZER)
276 if (res
) __msan_unpoison(res
, sizeof(*res
));
277 if (res
->tm_zone
) __msan_unpoison_string(res
->tm_zone
);
283 __attribute__ ((__visibility__("default")))
284 struct tm
* localtime64_r_override(const time_t* timep
,
285 struct tm
* result
) __asm__ ("localtime64_r");
287 __attribute__ ((__visibility__("default")))
288 struct tm
* localtime64_r_override(const time_t* timep
, struct tm
* result
) {
289 if (g_am_zygote_or_renderer
) {
290 ProxyLocaltimeCallToBrowser(*timep
, result
, NULL
, 0);
293 CHECK_EQ(0, pthread_once(&g_libc_localtime_funcs_guard
,
294 InitLibcLocaltimeFunctions
));
295 struct tm
* res
= g_libc_localtime64_r(timep
, result
);
296 #if defined(MEMORY_SANITIZER)
297 if (res
) __msan_unpoison(res
, sizeof(*res
));
298 if (res
->tm_zone
) __msan_unpoison_string(res
->tm_zone
);
304 #if defined(ENABLE_PLUGINS)
305 // Loads the (native) libraries but does not initialize them (i.e., does not
306 // call PPP_InitializeModule). This is needed by the zygote on Linux to get
307 // access to the plugins before entering the sandbox.
308 void PreloadPepperPlugins() {
309 std::vector
<PepperPluginInfo
> plugins
;
310 ComputePepperPluginList(&plugins
);
311 for (size_t i
= 0; i
< plugins
.size(); ++i
) {
312 if (!plugins
[i
].is_internal
) {
313 base::NativeLibraryLoadError error
;
314 base::NativeLibrary library
= base::LoadNativeLibrary(plugins
[i
].path
,
316 VLOG_IF(1, !library
) << "Unable to load plugin "
317 << plugins
[i
].path
.value() << " "
320 (void)library
; // Prevent release-mode warning.
326 // This function triggers the static and lazy construction of objects that need
327 // to be created before imposing the sandbox.
328 static void ZygotePreSandboxInit() {
331 base::SysInfo::AmountOfPhysicalMemory();
332 base::SysInfo::MaxSharedMemorySize();
333 base::SysInfo::NumberOfProcessors();
335 // ICU DateFormat class (used in base/time_format.cc) needs to get the
336 // Olson timezone ID by accessing the zoneinfo files on disk. After
337 // TimeZone::createDefault is called once here, the timezone ID is
338 // cached and there's no more need to access the file system.
339 scoped_ptr
<icu::TimeZone
> zone(icu::TimeZone::createDefault());
341 #if defined(USE_NSS_CERTS)
342 // NSS libraries are loaded before sandbox is activated. This is to allow
343 // successful initialization of NSS which tries to load extra library files.
344 crypto::LoadNSSLibraries();
345 #elif defined(USE_OPENSSL)
346 // Read a random byte in order to cause BoringSSL to open a file descriptor
349 RAND_bytes(&scratch
, 1);
351 // It's possible that another hypothetical crypto stack would not require
352 // pre-sandbox init, but more likely this is just a build configuration error.
353 #error Which SSL library are you using?
355 #if defined(ENABLE_PLUGINS)
356 // Ensure access to the Pepper plugins before the sandbox is turned on.
357 PreloadPepperPlugins();
359 #if defined(ENABLE_WEBRTC)
360 InitializeWebRtcModule();
362 SkFontConfigInterface::SetGlobal(
363 new FontConfigIPC(GetSandboxFD()))->unref();
366 static bool CreateInitProcessReaper(base::Closure
* post_fork_parent_callback
) {
367 // The current process becomes init(1), this function returns from a
368 // newly created process.
369 const bool init_created
=
370 sandbox::CreateInitProcessReaper(post_fork_parent_callback
);
372 LOG(ERROR
) << "Error creating an init process to reap zombies";
378 // Enter the setuid sandbox. This requires the current process to have been
379 // created through the setuid sandbox.
380 static bool EnterSuidSandbox(sandbox::SetuidSandboxClient
* setuid_sandbox
,
381 base::Closure
* post_fork_parent_callback
) {
382 DCHECK(setuid_sandbox
);
383 DCHECK(setuid_sandbox
->IsSuidSandboxChild());
385 // Use the SUID sandbox. This still allows the seccomp sandbox to
386 // be enabled by the process later.
388 if (!setuid_sandbox
->IsSuidSandboxUpToDate()) {
390 "You are using a wrong version of the setuid binary!\n"
392 "https://code.google.com/p/chromium/wiki/LinuxSUIDSandboxDevelopment."
396 if (!setuid_sandbox
->ChrootMe())
399 if (setuid_sandbox
->IsInNewPIDNamespace()) {
400 CHECK_EQ(1, getpid())
401 << "The SUID sandbox created a new PID namespace but Zygote "
402 "is not the init process. Please, make sure the SUID "
403 "binary is up to date.";
407 // The setuid sandbox has created a new PID namespace and we need
408 // to assume the role of init.
409 CHECK(CreateInitProcessReaper(post_fork_parent_callback
));
412 CHECK(SandboxDebugHandling::SetDumpableStatusAndHandlers());
416 static void DropAllCapabilities(int proc_fd
) {
417 CHECK(sandbox::Credentials::DropAllCapabilities(proc_fd
));
420 static void EnterNamespaceSandbox(LinuxSandbox
* linux_sandbox
,
421 base::Closure
* post_fork_parent_callback
) {
422 linux_sandbox
->EngageNamespaceSandbox();
425 base::Closure drop_all_caps_callback
=
426 base::Bind(&DropAllCapabilities
, linux_sandbox
->proc_fd());
427 base::Closure callback
= base::Bind(
428 &RunTwoClosures
, &drop_all_caps_callback
, post_fork_parent_callback
);
429 CHECK(CreateInitProcessReaper(&callback
));
433 #if defined(SANITIZER_COVERAGE)
434 const size_t kSanitizerMaxMessageLength
= 1 * 1024 * 1024;
436 // A helper process which collects code coverage data from the renderers over a
437 // socket and dumps it to a file. See http://crbug.com/336212 for discussion.
438 static void SanitizerCoverageHelper(int socket_fd
, int file_fd
) {
439 scoped_ptr
<char[]> buffer(new char[kSanitizerMaxMessageLength
]);
441 ssize_t received_size
= HANDLE_EINTR(
442 recv(socket_fd
, buffer
.get(), kSanitizerMaxMessageLength
, 0));
443 PCHECK(received_size
>= 0);
444 if (received_size
== 0)
445 // All clients have closed the socket. We should die.
447 PCHECK(file_fd
>= 0);
448 ssize_t written_size
= 0;
449 while (written_size
< received_size
) {
451 HANDLE_EINTR(write(file_fd
, buffer
.get() + written_size
,
452 received_size
- written_size
));
453 PCHECK(write_res
>= 0);
454 written_size
+= write_res
;
456 PCHECK(0 == HANDLE_EINTR(fsync(file_fd
)));
460 // fds[0] is the read end, fds[1] is the write end.
461 static void CreateSanitizerCoverageSocketPair(int fds
[2]) {
462 PCHECK(0 == socketpair(AF_UNIX
, SOCK_SEQPACKET
, 0, fds
));
463 PCHECK(0 == shutdown(fds
[0], SHUT_WR
));
464 PCHECK(0 == shutdown(fds
[1], SHUT_RD
));
467 static pid_t
ForkSanitizerCoverageHelper(
470 base::ScopedFD file_fd
,
471 const std::vector
<int>& extra_fds_to_close
) {
476 PCHECK(0 == IGNORE_EINTR(close(parent_fd
)));
477 CloseFds(extra_fds_to_close
);
478 SanitizerCoverageHelper(child_fd
, file_fd
.get());
482 PCHECK(0 == IGNORE_EINTR(close(child_fd
)));
487 #endif // defined(SANITIZER_COVERAGE)
489 static void EnterLayerOneSandbox(LinuxSandbox
* linux_sandbox
,
490 const bool using_layer1_sandbox
,
491 base::Closure
* post_fork_parent_callback
) {
492 DCHECK(linux_sandbox
);
494 ZygotePreSandboxInit();
496 // Check that the pre-sandbox initialization didn't spawn threads.
497 #if !defined(THREAD_SANITIZER)
498 DCHECK(sandbox::ThreadHelpers::IsSingleThreaded());
501 sandbox::SetuidSandboxClient
* setuid_sandbox
=
502 linux_sandbox
->setuid_sandbox_client();
503 if (setuid_sandbox
->IsSuidSandboxChild()) {
504 CHECK(EnterSuidSandbox(setuid_sandbox
, post_fork_parent_callback
))
505 << "Failed to enter setuid sandbox";
506 } else if (sandbox::NamespaceSandbox::InNewUserNamespace()) {
507 EnterNamespaceSandbox(linux_sandbox
, post_fork_parent_callback
);
509 CHECK(!using_layer1_sandbox
);
513 bool ZygoteMain(const MainFunctionParams
& params
,
514 ScopedVector
<ZygoteForkDelegate
> fork_delegates
) {
515 g_am_zygote_or_renderer
= true;
516 sandbox::InitLibcUrandomOverrides();
518 std::vector
<int> fds_to_close_post_fork
;
520 LinuxSandbox
* linux_sandbox
= LinuxSandbox::GetInstance();
522 #if defined(SANITIZER_COVERAGE)
523 const std::string sancov_file_name
=
524 "zygote." + base::Uint64ToString(base::RandUint64());
525 base::ScopedFD
sancov_file_fd(
526 __sanitizer_maybe_open_cov_file(sancov_file_name
.c_str()));
527 int sancov_socket_fds
[2] = {-1, -1};
528 CreateSanitizerCoverageSocketPair(sancov_socket_fds
);
529 linux_sandbox
->sanitizer_args()->coverage_sandboxed
= 1;
530 linux_sandbox
->sanitizer_args()->coverage_fd
= sancov_socket_fds
[1];
531 linux_sandbox
->sanitizer_args()->coverage_max_block_size
=
532 kSanitizerMaxMessageLength
;
533 // Zygote termination will block until the helper process exits, which will
534 // not happen until the write end of the socket is closed everywhere. Make
535 // sure the init process does not hold on to it.
536 fds_to_close_post_fork
.push_back(sancov_socket_fds
[0]);
537 fds_to_close_post_fork
.push_back(sancov_socket_fds
[1]);
538 #endif // SANITIZER_COVERAGE
540 // Skip pre-initializing sandbox under --no-sandbox for crbug.com/444900.
541 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
542 switches::kNoSandbox
)) {
543 // This will pre-initialize the various sandboxes that need it.
544 linux_sandbox
->PreinitializeSandbox();
547 const bool using_setuid_sandbox
=
548 linux_sandbox
->setuid_sandbox_client()->IsSuidSandboxChild();
549 const bool using_namespace_sandbox
=
550 sandbox::NamespaceSandbox::InNewUserNamespace();
551 const bool using_layer1_sandbox
=
552 using_setuid_sandbox
|| using_namespace_sandbox
;
554 if (using_setuid_sandbox
) {
555 linux_sandbox
->setuid_sandbox_client()->CloseDummyFile();
558 if (using_layer1_sandbox
) {
559 // Let the ZygoteHost know we're booting up.
560 CHECK(UnixDomainSocket::SendMsg(kZygoteSocketPairFd
,
562 sizeof(kZygoteBootMessage
),
563 std::vector
<int>()));
566 VLOG(1) << "ZygoteMain: initializing " << fork_delegates
.size()
567 << " fork delegates";
568 for (ZygoteForkDelegate
* fork_delegate
: fork_delegates
) {
569 fork_delegate
->Init(GetSandboxFD(), using_layer1_sandbox
);
572 const std::vector
<int> sandbox_fds_to_close_post_fork
=
573 linux_sandbox
->GetFileDescriptorsToClose();
575 fds_to_close_post_fork
.insert(fds_to_close_post_fork
.end(),
576 sandbox_fds_to_close_post_fork
.begin(),
577 sandbox_fds_to_close_post_fork
.end());
578 base::Closure post_fork_parent_callback
=
579 base::Bind(&CloseFds
, fds_to_close_post_fork
);
581 // Turn on the first layer of the sandbox if the configuration warrants it.
582 EnterLayerOneSandbox(linux_sandbox
, using_layer1_sandbox
,
583 &post_fork_parent_callback
);
585 // Extra children and file descriptors created that the Zygote must have
587 std::vector
<pid_t
> extra_children
;
588 std::vector
<int> extra_fds
;
590 #if defined(SANITIZER_COVERAGE)
591 pid_t sancov_helper_pid
= ForkSanitizerCoverageHelper(
592 sancov_socket_fds
[0], sancov_socket_fds
[1], sancov_file_fd
.Pass(),
593 sandbox_fds_to_close_post_fork
);
594 // It's important that the zygote reaps the helper before dying. Otherwise,
595 // the destruction of the PID namespace could kill the helper before it
596 // completes its I/O tasks. |sancov_helper_pid| will exit once the last
597 // renderer holding the write end of |sancov_socket_fds| closes it.
598 extra_children
.push_back(sancov_helper_pid
);
599 // Sanitizer code in the renderers will inherit the write end of the socket
600 // from the zygote. We must keep it open until the very end of the zygote's
601 // lifetime, even though we don't explicitly use it.
602 extra_fds
.push_back(sancov_socket_fds
[1]);
603 #endif // SANITIZER_COVERAGE
605 const int sandbox_flags
= linux_sandbox
->GetStatus();
607 const bool setuid_sandbox_engaged
= sandbox_flags
& kSandboxLinuxSUID
;
608 CHECK_EQ(using_setuid_sandbox
, setuid_sandbox_engaged
);
610 const bool namespace_sandbox_engaged
= sandbox_flags
& kSandboxLinuxUserNS
;
611 CHECK_EQ(using_namespace_sandbox
, namespace_sandbox_engaged
);
613 Zygote
zygote(sandbox_flags
, fork_delegates
.Pass(), extra_children
,
615 // This function call can return multiple times, once per fork().
616 return zygote
.ProcessRequests();
619 } // namespace content