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/init_process_reaper.h"
44 #include "sandbox/linux/services/libc_urandom_override.h"
45 #include "sandbox/linux/services/namespace_sandbox.h"
46 #include "sandbox/linux/services/thread_helpers.h"
47 #include "sandbox/linux/suid/client/setuid_sandbox_client.h"
48 #include "third_party/icu/source/i18n/unicode/timezone.h"
49 #include "third_party/skia/include/ports/SkFontConfigInterface.h"
52 #include <sys/prctl.h>
55 #if defined(USE_OPENSSL)
56 #include <openssl/rand.h>
59 #if defined(ENABLE_PLUGINS)
60 #include "content/common/pepper_plugin_list.h"
61 #include "content/public/common/pepper_plugin_info.h"
64 #if defined(ENABLE_WEBRTC)
65 #include "third_party/libjingle/overrides/init_webrtc.h"
68 #if defined(SANITIZER_COVERAGE)
69 #include <sanitizer/common_interface_defs.h>
70 #include <sanitizer/coverage_interface.h>
77 void CloseFds(const std::vector
<int>& fds
) {
78 for (const auto& it
: fds
) {
79 PCHECK(0 == IGNORE_EINTR(close(it
)));
85 // See http://code.google.com/p/chromium/wiki/LinuxZygote
87 static void ProxyLocaltimeCallToBrowser(time_t input
, struct tm
* output
,
89 size_t timezone_out_len
) {
91 request
.WriteInt(LinuxSandbox::METHOD_LOCALTIME
);
93 std::string(reinterpret_cast<char*>(&input
), sizeof(input
)));
95 uint8_t reply_buf
[512];
96 const ssize_t r
= UnixDomainSocket::SendRecvMsg(
97 GetSandboxFD(), reply_buf
, sizeof(reply_buf
), NULL
,
100 memset(output
, 0, sizeof(struct tm
));
104 Pickle
reply(reinterpret_cast<char*>(reply_buf
), r
);
105 PickleIterator
iter(reply
);
106 std::string result
, timezone
;
107 if (!iter
.ReadString(&result
) ||
108 !iter
.ReadString(&timezone
) ||
109 result
.size() != sizeof(struct tm
)) {
110 memset(output
, 0, sizeof(struct tm
));
114 memcpy(output
, result
.data(), sizeof(struct tm
));
115 if (timezone_out_len
) {
116 const size_t copy_len
= std::min(timezone_out_len
- 1, timezone
.size());
117 memcpy(timezone_out
, timezone
.data(), copy_len
);
118 timezone_out
[copy_len
] = 0;
119 output
->tm_zone
= timezone_out
;
121 output
->tm_zone
= NULL
;
125 static bool g_am_zygote_or_renderer
= false;
127 // Sandbox interception of libc calls.
129 // Because we are running in a sandbox certain libc calls will fail (localtime
130 // being the motivating example - it needs to read /etc/localtime). We need to
131 // intercept these calls and proxy them to the browser. However, these calls
132 // may come from us or from our libraries. In some cases we can't just change
135 // It's for these cases that we have the following setup:
137 // We define global functions for those functions which we wish to override.
138 // Since we will be first in the dynamic resolution order, the dynamic linker
139 // will point callers to our versions of these functions. However, we have the
140 // same binary for both the browser and the renderers, which means that our
141 // overrides will apply in the browser too.
143 // The global |g_am_zygote_or_renderer| is true iff we are in a zygote or
144 // renderer process. It's set in ZygoteMain and inherited by the renderers when
145 // they fork. (This means that it'll be incorrect for global constructor
146 // functions and before ZygoteMain is called - beware).
148 // Our replacement functions can check this global and either proxy
149 // the call to the browser over the sandbox IPC
150 // (http://code.google.com/p/chromium/wiki/LinuxSandboxIPC) or they can use
151 // dlsym with RTLD_NEXT to resolve the symbol, ignoring any symbols in the
156 // Our first attempt involved some assembly to patch the GOT of the current
157 // module. This worked, but was platform specific and doesn't catch the case
158 // where a library makes a call rather than current module.
160 // We also considered patching the function in place, but this would again by
161 // platform specific and the above technique seems to work well enough.
163 typedef struct tm
* (*LocaltimeFunction
)(const time_t* timep
);
164 typedef struct tm
* (*LocaltimeRFunction
)(const time_t* timep
,
167 static pthread_once_t g_libc_localtime_funcs_guard
= PTHREAD_ONCE_INIT
;
168 static LocaltimeFunction g_libc_localtime
;
169 static LocaltimeFunction g_libc_localtime64
;
170 static LocaltimeRFunction g_libc_localtime_r
;
171 static LocaltimeRFunction g_libc_localtime64_r
;
173 static void InitLibcLocaltimeFunctions() {
174 g_libc_localtime
= reinterpret_cast<LocaltimeFunction
>(
175 dlsym(RTLD_NEXT
, "localtime"));
176 g_libc_localtime64
= reinterpret_cast<LocaltimeFunction
>(
177 dlsym(RTLD_NEXT
, "localtime64"));
178 g_libc_localtime_r
= reinterpret_cast<LocaltimeRFunction
>(
179 dlsym(RTLD_NEXT
, "localtime_r"));
180 g_libc_localtime64_r
= reinterpret_cast<LocaltimeRFunction
>(
181 dlsym(RTLD_NEXT
, "localtime64_r"));
183 if (!g_libc_localtime
|| !g_libc_localtime_r
) {
184 // http://code.google.com/p/chromium/issues/detail?id=16800
186 // Nvidia's libGL.so overrides dlsym for an unknown reason and replaces
187 // it with a version which doesn't work. In this case we'll get a NULL
188 // result. There's not a lot we can do at this point, so we just bodge it!
189 LOG(ERROR
) << "Your system is broken: dlsym doesn't work! This has been "
190 "reported to be caused by Nvidia's libGL. You should expect"
191 " time related functions to misbehave. "
192 "http://code.google.com/p/chromium/issues/detail?id=16800";
195 if (!g_libc_localtime
)
196 g_libc_localtime
= gmtime
;
197 if (!g_libc_localtime64
)
198 g_libc_localtime64
= g_libc_localtime
;
199 if (!g_libc_localtime_r
)
200 g_libc_localtime_r
= gmtime_r
;
201 if (!g_libc_localtime64_r
)
202 g_libc_localtime64_r
= g_libc_localtime_r
;
205 // Define localtime_override() function with asm name "localtime", so that all
206 // references to localtime() will resolve to this function. Notice that we need
207 // to set visibility attribute to "default" to export the symbol, as it is set
208 // to "hidden" by default in chrome per build/common.gypi.
209 __attribute__ ((__visibility__("default")))
210 struct tm
* localtime_override(const time_t* timep
) __asm__ ("localtime");
212 __attribute__ ((__visibility__("default")))
213 struct tm
* localtime_override(const time_t* timep
) {
214 if (g_am_zygote_or_renderer
) {
215 static struct tm time_struct
;
216 static char timezone_string
[64];
217 ProxyLocaltimeCallToBrowser(*timep
, &time_struct
, timezone_string
,
218 sizeof(timezone_string
));
221 CHECK_EQ(0, pthread_once(&g_libc_localtime_funcs_guard
,
222 InitLibcLocaltimeFunctions
));
223 struct tm
* res
= g_libc_localtime(timep
);
224 #if defined(MEMORY_SANITIZER)
225 if (res
) __msan_unpoison(res
, sizeof(*res
));
226 if (res
->tm_zone
) __msan_unpoison_string(res
->tm_zone
);
232 // Use same trick to override localtime64(), localtime_r() and localtime64_r().
233 __attribute__ ((__visibility__("default")))
234 struct tm
* localtime64_override(const time_t* timep
) __asm__ ("localtime64");
236 __attribute__ ((__visibility__("default")))
237 struct tm
* localtime64_override(const time_t* timep
) {
238 if (g_am_zygote_or_renderer
) {
239 static struct tm time_struct
;
240 static char timezone_string
[64];
241 ProxyLocaltimeCallToBrowser(*timep
, &time_struct
, timezone_string
,
242 sizeof(timezone_string
));
245 CHECK_EQ(0, pthread_once(&g_libc_localtime_funcs_guard
,
246 InitLibcLocaltimeFunctions
));
247 struct tm
* res
= g_libc_localtime64(timep
);
248 #if defined(MEMORY_SANITIZER)
249 if (res
) __msan_unpoison(res
, sizeof(*res
));
250 if (res
->tm_zone
) __msan_unpoison_string(res
->tm_zone
);
256 __attribute__ ((__visibility__("default")))
257 struct tm
* localtime_r_override(const time_t* timep
,
258 struct tm
* result
) __asm__ ("localtime_r");
260 __attribute__ ((__visibility__("default")))
261 struct tm
* localtime_r_override(const time_t* timep
, struct tm
* result
) {
262 if (g_am_zygote_or_renderer
) {
263 ProxyLocaltimeCallToBrowser(*timep
, result
, NULL
, 0);
266 CHECK_EQ(0, pthread_once(&g_libc_localtime_funcs_guard
,
267 InitLibcLocaltimeFunctions
));
268 struct tm
* res
= g_libc_localtime_r(timep
, result
);
269 #if defined(MEMORY_SANITIZER)
270 if (res
) __msan_unpoison(res
, sizeof(*res
));
271 if (res
->tm_zone
) __msan_unpoison_string(res
->tm_zone
);
277 __attribute__ ((__visibility__("default")))
278 struct tm
* localtime64_r_override(const time_t* timep
,
279 struct tm
* result
) __asm__ ("localtime64_r");
281 __attribute__ ((__visibility__("default")))
282 struct tm
* localtime64_r_override(const time_t* timep
, struct tm
* result
) {
283 if (g_am_zygote_or_renderer
) {
284 ProxyLocaltimeCallToBrowser(*timep
, result
, NULL
, 0);
287 CHECK_EQ(0, pthread_once(&g_libc_localtime_funcs_guard
,
288 InitLibcLocaltimeFunctions
));
289 struct tm
* res
= g_libc_localtime64_r(timep
, result
);
290 #if defined(MEMORY_SANITIZER)
291 if (res
) __msan_unpoison(res
, sizeof(*res
));
292 if (res
->tm_zone
) __msan_unpoison_string(res
->tm_zone
);
298 #if defined(ENABLE_PLUGINS)
299 // Loads the (native) libraries but does not initialize them (i.e., does not
300 // call PPP_InitializeModule). This is needed by the zygote on Linux to get
301 // access to the plugins before entering the sandbox.
302 void PreloadPepperPlugins() {
303 std::vector
<PepperPluginInfo
> plugins
;
304 ComputePepperPluginList(&plugins
);
305 for (size_t i
= 0; i
< plugins
.size(); ++i
) {
306 if (!plugins
[i
].is_internal
&& plugins
[i
].is_sandboxed
) {
307 base::NativeLibraryLoadError error
;
308 base::NativeLibrary library
= base::LoadNativeLibrary(plugins
[i
].path
,
310 VLOG_IF(1, !library
) << "Unable to load plugin "
311 << plugins
[i
].path
.value() << " "
314 (void)library
; // Prevent release-mode warning.
320 // This function triggers the static and lazy construction of objects that need
321 // to be created before imposing the sandbox.
322 static void ZygotePreSandboxInit() {
325 base::SysInfo::AmountOfPhysicalMemory();
326 base::SysInfo::MaxSharedMemorySize();
327 base::SysInfo::NumberOfProcessors();
329 // ICU DateFormat class (used in base/time_format.cc) needs to get the
330 // Olson timezone ID by accessing the zoneinfo files on disk. After
331 // TimeZone::createDefault is called once here, the timezone ID is
332 // cached and there's no more need to access the file system.
333 scoped_ptr
<icu::TimeZone
> zone(icu::TimeZone::createDefault());
336 // NSS libraries are loaded before sandbox is activated. This is to allow
337 // successful initialization of NSS which tries to load extra library files.
338 crypto::LoadNSSLibraries();
339 #elif defined(USE_OPENSSL)
340 // Read a random byte in order to cause BoringSSL to open a file descriptor
343 RAND_bytes(&scratch
, 1);
345 // It's possible that another hypothetical crypto stack would not require
346 // pre-sandbox init, but more likely this is just a build configuration error.
347 #error Which SSL library are you using?
349 #if defined(ENABLE_PLUGINS)
350 // Ensure access to the Pepper plugins before the sandbox is turned on.
351 PreloadPepperPlugins();
353 #if defined(ENABLE_WEBRTC)
354 InitializeWebRtcModule();
356 SkFontConfigInterface::SetGlobal(
357 new FontConfigIPC(GetSandboxFD()))->unref();
360 static bool CreateInitProcessReaper(base::Closure
* post_fork_parent_callback
) {
361 // The current process becomes init(1), this function returns from a
362 // newly created process.
363 const bool init_created
=
364 sandbox::CreateInitProcessReaper(post_fork_parent_callback
);
366 LOG(ERROR
) << "Error creating an init process to reap zombies";
372 // Enter the setuid sandbox. This requires the current process to have been
373 // created through the setuid sandbox.
374 static bool EnterSuidSandbox(sandbox::SetuidSandboxClient
* setuid_sandbox
,
375 base::Closure
* post_fork_parent_callback
) {
376 DCHECK(setuid_sandbox
);
377 DCHECK(setuid_sandbox
->IsSuidSandboxChild());
379 // Use the SUID sandbox. This still allows the seccomp sandbox to
380 // be enabled by the process later.
382 if (!setuid_sandbox
->IsSuidSandboxUpToDate()) {
384 "You are using a wrong version of the setuid binary!\n"
386 "https://code.google.com/p/chromium/wiki/LinuxSUIDSandboxDevelopment."
390 if (!setuid_sandbox
->ChrootMe())
393 if (setuid_sandbox
->IsInNewPIDNamespace()) {
394 CHECK_EQ(1, getpid())
395 << "The SUID sandbox created a new PID namespace but Zygote "
396 "is not the init process. Please, make sure the SUID "
397 "binary is up to date.";
401 // The setuid sandbox has created a new PID namespace and we need
402 // to assume the role of init.
403 CHECK(CreateInitProcessReaper(post_fork_parent_callback
));
406 CHECK(SandboxDebugHandling::SetDumpableStatusAndHandlers());
410 static void EnterNamespaceSandbox(LinuxSandbox
* linux_sandbox
,
411 base::Closure
* post_fork_parent_callback
) {
412 linux_sandbox
->EngageNamespaceSandbox();
415 CHECK(CreateInitProcessReaper(post_fork_parent_callback
));
419 #if defined(SANITIZER_COVERAGE)
420 const size_t kSanitizerMaxMessageLength
= 1 * 1024 * 1024;
422 // A helper process which collects code coverage data from the renderers over a
423 // socket and dumps it to a file. See http://crbug.com/336212 for discussion.
424 static void SanitizerCoverageHelper(int socket_fd
, int file_fd
) {
425 scoped_ptr
<char[]> buffer(new char[kSanitizerMaxMessageLength
]);
427 ssize_t received_size
= HANDLE_EINTR(
428 recv(socket_fd
, buffer
.get(), kSanitizerMaxMessageLength
, 0));
429 PCHECK(received_size
>= 0);
430 if (received_size
== 0)
431 // All clients have closed the socket. We should die.
433 PCHECK(file_fd
>= 0);
434 ssize_t written_size
= 0;
435 while (written_size
< received_size
) {
437 HANDLE_EINTR(write(file_fd
, buffer
.get() + written_size
,
438 received_size
- written_size
));
439 PCHECK(write_res
>= 0);
440 written_size
+= write_res
;
442 PCHECK(0 == HANDLE_EINTR(fsync(file_fd
)));
446 // fds[0] is the read end, fds[1] is the write end.
447 static void CreateSanitizerCoverageSocketPair(int fds
[2]) {
448 PCHECK(0 == socketpair(AF_UNIX
, SOCK_SEQPACKET
, 0, fds
));
449 PCHECK(0 == shutdown(fds
[0], SHUT_WR
));
450 PCHECK(0 == shutdown(fds
[1], SHUT_RD
));
453 static pid_t
ForkSanitizerCoverageHelper(
456 base::ScopedFD file_fd
,
457 const std::vector
<int>& extra_fds_to_close
) {
462 PCHECK(0 == IGNORE_EINTR(close(parent_fd
)));
463 CloseFds(extra_fds_to_close
);
464 SanitizerCoverageHelper(child_fd
, file_fd
.get());
468 PCHECK(0 == IGNORE_EINTR(close(child_fd
)));
473 #endif // defined(SANITIZER_COVERAGE)
475 static void EnterLayerOneSandbox(LinuxSandbox
* linux_sandbox
,
476 const bool using_layer1_sandbox
,
477 base::Closure
* post_fork_parent_callback
) {
478 DCHECK(linux_sandbox
);
480 ZygotePreSandboxInit();
482 // Check that the pre-sandbox initialization didn't spawn threads.
483 #if !defined(THREAD_SANITIZER)
484 DCHECK(sandbox::ThreadHelpers::IsSingleThreaded());
487 sandbox::SetuidSandboxClient
* setuid_sandbox
=
488 linux_sandbox
->setuid_sandbox_client();
489 if (setuid_sandbox
->IsSuidSandboxChild()) {
490 CHECK(EnterSuidSandbox(setuid_sandbox
, post_fork_parent_callback
))
491 << "Failed to enter setuid sandbox";
492 } else if (sandbox::NamespaceSandbox::InNewUserNamespace()) {
493 EnterNamespaceSandbox(linux_sandbox
, post_fork_parent_callback
);
495 CHECK(!using_layer1_sandbox
);
499 bool ZygoteMain(const MainFunctionParams
& params
,
500 ScopedVector
<ZygoteForkDelegate
> fork_delegates
) {
501 g_am_zygote_or_renderer
= true;
502 sandbox::InitLibcUrandomOverrides();
504 std::vector
<int> fds_to_close_post_fork
;
506 LinuxSandbox
* linux_sandbox
= LinuxSandbox::GetInstance();
508 #if defined(SANITIZER_COVERAGE)
509 const std::string sancov_file_name
=
510 "zygote." + base::Uint64ToString(base::RandUint64());
511 base::ScopedFD
sancov_file_fd(
512 __sanitizer_maybe_open_cov_file(sancov_file_name
.c_str()));
513 int sancov_socket_fds
[2] = {-1, -1};
514 CreateSanitizerCoverageSocketPair(sancov_socket_fds
);
515 linux_sandbox
->sanitizer_args()->coverage_sandboxed
= 1;
516 linux_sandbox
->sanitizer_args()->coverage_fd
= sancov_socket_fds
[1];
517 linux_sandbox
->sanitizer_args()->coverage_max_block_size
=
518 kSanitizerMaxMessageLength
;
519 // Zygote termination will block until the helper process exits, which will
520 // not happen until the write end of the socket is closed everywhere. Make
521 // sure the init process does not hold on to it.
522 fds_to_close_post_fork
.push_back(sancov_socket_fds
[0]);
523 fds_to_close_post_fork
.push_back(sancov_socket_fds
[1]);
524 #endif // SANITIZER_COVERAGE
526 // Skip pre-initializing sandbox under --no-sandbox for crbug.com/444900.
527 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
528 switches::kNoSandbox
)) {
529 // This will pre-initialize the various sandboxes that need it.
530 linux_sandbox
->PreinitializeSandbox();
533 const bool using_setuid_sandbox
=
534 linux_sandbox
->setuid_sandbox_client()->IsSuidSandboxChild();
535 const bool using_namespace_sandbox
=
536 sandbox::NamespaceSandbox::InNewUserNamespace();
537 const bool using_layer1_sandbox
=
538 using_setuid_sandbox
|| using_namespace_sandbox
;
540 if (using_setuid_sandbox
) {
541 linux_sandbox
->setuid_sandbox_client()->CloseDummyFile();
544 if (using_layer1_sandbox
) {
545 // Let the ZygoteHost know we're booting up.
546 CHECK(UnixDomainSocket::SendMsg(kZygoteSocketPairFd
,
548 sizeof(kZygoteBootMessage
),
549 std::vector
<int>()));
552 VLOG(1) << "ZygoteMain: initializing " << fork_delegates
.size()
553 << " fork delegates";
554 for (ZygoteForkDelegate
* fork_delegate
: fork_delegates
) {
555 fork_delegate
->Init(GetSandboxFD(), using_layer1_sandbox
);
558 const std::vector
<int> sandbox_fds_to_close_post_fork
=
559 linux_sandbox
->GetFileDescriptorsToClose();
561 fds_to_close_post_fork
.insert(fds_to_close_post_fork
.end(),
562 sandbox_fds_to_close_post_fork
.begin(),
563 sandbox_fds_to_close_post_fork
.end());
564 base::Closure post_fork_parent_callback
=
565 base::Bind(&CloseFds
, fds_to_close_post_fork
);
567 // Turn on the first layer of the sandbox if the configuration warrants it.
568 EnterLayerOneSandbox(linux_sandbox
, using_layer1_sandbox
,
569 &post_fork_parent_callback
);
571 // Extra children and file descriptors created that the Zygote must have
573 std::vector
<pid_t
> extra_children
;
574 std::vector
<int> extra_fds
;
576 #if defined(SANITIZER_COVERAGE)
577 pid_t sancov_helper_pid
= ForkSanitizerCoverageHelper(
578 sancov_socket_fds
[0], sancov_socket_fds
[1], sancov_file_fd
.Pass(),
579 sandbox_fds_to_close_post_fork
);
580 // It's important that the zygote reaps the helper before dying. Otherwise,
581 // the destruction of the PID namespace could kill the helper before it
582 // completes its I/O tasks. |sancov_helper_pid| will exit once the last
583 // renderer holding the write end of |sancov_socket_fds| closes it.
584 extra_children
.push_back(sancov_helper_pid
);
585 // Sanitizer code in the renderers will inherit the write end of the socket
586 // from the zygote. We must keep it open until the very end of the zygote's
587 // lifetime, even though we don't explicitly use it.
588 extra_fds
.push_back(sancov_socket_fds
[1]);
589 #endif // SANITIZER_COVERAGE
591 const int sandbox_flags
= linux_sandbox
->GetStatus();
593 const bool setuid_sandbox_engaged
= sandbox_flags
& kSandboxLinuxSUID
;
594 CHECK_EQ(using_setuid_sandbox
, setuid_sandbox_engaged
);
596 const bool namespace_sandbox_engaged
= sandbox_flags
& kSandboxLinuxUserNS
;
597 CHECK_EQ(using_namespace_sandbox
, namespace_sandbox_engaged
);
599 Zygote
zygote(sandbox_flags
, fork_delegates
.Pass(), extra_children
,
601 // This function call can return multiple times, once per fork().
602 return zygote
.ProcessRequests();
605 } // namespace content