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"
11 #include <sys/socket.h>
12 #include <sys/types.h>
15 #include "base/basictypes.h"
16 #include "base/bind.h"
17 #include "base/command_line.h"
18 #include "base/compiler_specific.h"
19 #include "base/memory/scoped_vector.h"
20 #include "base/native_library.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/rand_util.h"
25 #include "base/strings/string_number_conversions.h"
26 #include "base/sys_info.h"
27 #include "build/build_config.h"
28 #include "content/common/child_process_sandbox_support_impl_linux.h"
29 #include "content/common/font_config_ipc_linux.h"
30 #include "content/common/pepper_plugin_list.h"
31 #include "content/common/sandbox_linux/sandbox_linux.h"
32 #include "content/common/zygote_commands_linux.h"
33 #include "content/public/common/content_switches.h"
34 #include "content/public/common/main_function_params.h"
35 #include "content/public/common/pepper_plugin_info.h"
36 #include "content/public/common/sandbox_linux.h"
37 #include "content/public/common/zygote_fork_delegate_linux.h"
38 #include "content/zygote/zygote_linux.h"
39 #include "crypto/nss_util.h"
40 #include "sandbox/linux/services/init_process_reaper.h"
41 #include "sandbox/linux/services/libc_urandom_override.h"
42 #include "sandbox/linux/suid/client/setuid_sandbox_client.h"
43 #include "third_party/icu/source/i18n/unicode/timezone.h"
44 #include "third_party/skia/include/ports/SkFontConfigInterface.h"
47 #include <sys/prctl.h>
50 #if defined(USE_OPENSSL)
51 #include <openssl/rand.h>
54 #if defined(ENABLE_WEBRTC)
55 #include "third_party/libjingle/overrides/init_webrtc.h"
58 #if defined(ADDRESS_SANITIZER)
59 #include <sanitizer/asan_interface.h>
64 // See http://code.google.com/p/chromium/wiki/LinuxZygote
66 static void ProxyLocaltimeCallToBrowser(time_t input
, struct tm
* output
,
68 size_t timezone_out_len
) {
70 request
.WriteInt(LinuxSandbox::METHOD_LOCALTIME
);
72 std::string(reinterpret_cast<char*>(&input
), sizeof(input
)));
74 uint8_t reply_buf
[512];
75 const ssize_t r
= UnixDomainSocket::SendRecvMsg(
76 GetSandboxFD(), reply_buf
, sizeof(reply_buf
), NULL
,
79 memset(output
, 0, sizeof(struct tm
));
83 Pickle
reply(reinterpret_cast<char*>(reply_buf
), r
);
84 PickleIterator
iter(reply
);
85 std::string result
, timezone
;
86 if (!reply
.ReadString(&iter
, &result
) ||
87 !reply
.ReadString(&iter
, &timezone
) ||
88 result
.size() != sizeof(struct tm
)) {
89 memset(output
, 0, sizeof(struct tm
));
93 memcpy(output
, result
.data(), sizeof(struct tm
));
94 if (timezone_out_len
) {
95 const size_t copy_len
= std::min(timezone_out_len
- 1, timezone
.size());
96 memcpy(timezone_out
, timezone
.data(), copy_len
);
97 timezone_out
[copy_len
] = 0;
98 output
->tm_zone
= timezone_out
;
100 output
->tm_zone
= NULL
;
104 static bool g_am_zygote_or_renderer
= false;
106 // Sandbox interception of libc calls.
108 // Because we are running in a sandbox certain libc calls will fail (localtime
109 // being the motivating example - it needs to read /etc/localtime). We need to
110 // intercept these calls and proxy them to the browser. However, these calls
111 // may come from us or from our libraries. In some cases we can't just change
114 // It's for these cases that we have the following setup:
116 // We define global functions for those functions which we wish to override.
117 // Since we will be first in the dynamic resolution order, the dynamic linker
118 // will point callers to our versions of these functions. However, we have the
119 // same binary for both the browser and the renderers, which means that our
120 // overrides will apply in the browser too.
122 // The global |g_am_zygote_or_renderer| is true iff we are in a zygote or
123 // renderer process. It's set in ZygoteMain and inherited by the renderers when
124 // they fork. (This means that it'll be incorrect for global constructor
125 // functions and before ZygoteMain is called - beware).
127 // Our replacement functions can check this global and either proxy
128 // the call to the browser over the sandbox IPC
129 // (http://code.google.com/p/chromium/wiki/LinuxSandboxIPC) or they can use
130 // dlsym with RTLD_NEXT to resolve the symbol, ignoring any symbols in the
135 // Our first attempt involved some assembly to patch the GOT of the current
136 // module. This worked, but was platform specific and doesn't catch the case
137 // where a library makes a call rather than current module.
139 // We also considered patching the function in place, but this would again by
140 // platform specific and the above technique seems to work well enough.
142 typedef struct tm
* (*LocaltimeFunction
)(const time_t* timep
);
143 typedef struct tm
* (*LocaltimeRFunction
)(const time_t* timep
,
146 static pthread_once_t g_libc_localtime_funcs_guard
= PTHREAD_ONCE_INIT
;
147 static LocaltimeFunction g_libc_localtime
;
148 static LocaltimeFunction g_libc_localtime64
;
149 static LocaltimeRFunction g_libc_localtime_r
;
150 static LocaltimeRFunction g_libc_localtime64_r
;
152 static void InitLibcLocaltimeFunctions() {
153 g_libc_localtime
= reinterpret_cast<LocaltimeFunction
>(
154 dlsym(RTLD_NEXT
, "localtime"));
155 g_libc_localtime64
= reinterpret_cast<LocaltimeFunction
>(
156 dlsym(RTLD_NEXT
, "localtime64"));
157 g_libc_localtime_r
= reinterpret_cast<LocaltimeRFunction
>(
158 dlsym(RTLD_NEXT
, "localtime_r"));
159 g_libc_localtime64_r
= reinterpret_cast<LocaltimeRFunction
>(
160 dlsym(RTLD_NEXT
, "localtime64_r"));
162 if (!g_libc_localtime
|| !g_libc_localtime_r
) {
163 // http://code.google.com/p/chromium/issues/detail?id=16800
165 // Nvidia's libGL.so overrides dlsym for an unknown reason and replaces
166 // it with a version which doesn't work. In this case we'll get a NULL
167 // result. There's not a lot we can do at this point, so we just bodge it!
168 LOG(ERROR
) << "Your system is broken: dlsym doesn't work! This has been "
169 "reported to be caused by Nvidia's libGL. You should expect"
170 " time related functions to misbehave. "
171 "http://code.google.com/p/chromium/issues/detail?id=16800";
174 if (!g_libc_localtime
)
175 g_libc_localtime
= gmtime
;
176 if (!g_libc_localtime64
)
177 g_libc_localtime64
= g_libc_localtime
;
178 if (!g_libc_localtime_r
)
179 g_libc_localtime_r
= gmtime_r
;
180 if (!g_libc_localtime64_r
)
181 g_libc_localtime64_r
= g_libc_localtime_r
;
184 // Define localtime_override() function with asm name "localtime", so that all
185 // references to localtime() will resolve to this function. Notice that we need
186 // to set visibility attribute to "default" to export the symbol, as it is set
187 // to "hidden" by default in chrome per build/common.gypi.
188 __attribute__ ((__visibility__("default")))
189 struct tm
* localtime_override(const time_t* timep
) __asm__ ("localtime");
191 __attribute__ ((__visibility__("default")))
192 struct tm
* localtime_override(const time_t* timep
) {
193 if (g_am_zygote_or_renderer
) {
194 static struct tm time_struct
;
195 static char timezone_string
[64];
196 ProxyLocaltimeCallToBrowser(*timep
, &time_struct
, timezone_string
,
197 sizeof(timezone_string
));
200 CHECK_EQ(0, pthread_once(&g_libc_localtime_funcs_guard
,
201 InitLibcLocaltimeFunctions
));
202 struct tm
* res
= g_libc_localtime(timep
);
203 #if defined(MEMORY_SANITIZER)
204 if (res
) __msan_unpoison(res
, sizeof(*res
));
205 if (res
->tm_zone
) __msan_unpoison_string(res
->tm_zone
);
211 // Use same trick to override localtime64(), localtime_r() and localtime64_r().
212 __attribute__ ((__visibility__("default")))
213 struct tm
* localtime64_override(const time_t* timep
) __asm__ ("localtime64");
215 __attribute__ ((__visibility__("default")))
216 struct tm
* localtime64_override(const time_t* timep
) {
217 if (g_am_zygote_or_renderer
) {
218 static struct tm time_struct
;
219 static char timezone_string
[64];
220 ProxyLocaltimeCallToBrowser(*timep
, &time_struct
, timezone_string
,
221 sizeof(timezone_string
));
224 CHECK_EQ(0, pthread_once(&g_libc_localtime_funcs_guard
,
225 InitLibcLocaltimeFunctions
));
226 struct tm
* res
= g_libc_localtime64(timep
);
227 #if defined(MEMORY_SANITIZER)
228 if (res
) __msan_unpoison(res
, sizeof(*res
));
229 if (res
->tm_zone
) __msan_unpoison_string(res
->tm_zone
);
235 __attribute__ ((__visibility__("default")))
236 struct tm
* localtime_r_override(const time_t* timep
,
237 struct tm
* result
) __asm__ ("localtime_r");
239 __attribute__ ((__visibility__("default")))
240 struct tm
* localtime_r_override(const time_t* timep
, struct tm
* result
) {
241 if (g_am_zygote_or_renderer
) {
242 ProxyLocaltimeCallToBrowser(*timep
, result
, NULL
, 0);
245 CHECK_EQ(0, pthread_once(&g_libc_localtime_funcs_guard
,
246 InitLibcLocaltimeFunctions
));
247 struct tm
* res
= g_libc_localtime_r(timep
, result
);
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
* localtime64_r_override(const time_t* timep
,
258 struct tm
* result
) __asm__ ("localtime64_r");
260 __attribute__ ((__visibility__("default")))
261 struct tm
* localtime64_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_localtime64_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 #if defined(ENABLE_PLUGINS)
278 // Loads the (native) libraries but does not initialize them (i.e., does not
279 // call PPP_InitializeModule). This is needed by the zygote on Linux to get
280 // access to the plugins before entering the sandbox.
281 void PreloadPepperPlugins() {
282 std::vector
<PepperPluginInfo
> plugins
;
283 ComputePepperPluginList(&plugins
);
284 for (size_t i
= 0; i
< plugins
.size(); ++i
) {
285 if (!plugins
[i
].is_internal
&& plugins
[i
].is_sandboxed
) {
286 base::NativeLibraryLoadError error
;
287 base::NativeLibrary library
= base::LoadNativeLibrary(plugins
[i
].path
,
289 VLOG_IF(1, !library
) << "Unable to load plugin "
290 << plugins
[i
].path
.value() << " "
293 (void)library
; // Prevent release-mode warning.
299 // This function triggers the static and lazy construction of objects that need
300 // to be created before imposing the sandbox.
301 static void ZygotePreSandboxInit() {
304 base::SysInfo::AmountOfPhysicalMemory();
305 base::SysInfo::MaxSharedMemorySize();
306 base::SysInfo::NumberOfProcessors();
308 // ICU DateFormat class (used in base/time_format.cc) needs to get the
309 // Olson timezone ID by accessing the zoneinfo files on disk. After
310 // TimeZone::createDefault is called once here, the timezone ID is
311 // cached and there's no more need to access the file system.
312 scoped_ptr
<icu::TimeZone
> zone(icu::TimeZone::createDefault());
315 // NSS libraries are loaded before sandbox is activated. This is to allow
316 // successful initialization of NSS which tries to load extra library files.
317 crypto::LoadNSSLibraries();
318 #elif defined(USE_OPENSSL)
319 // Read a random byte in order to cause BoringSSL to open a file descriptor
322 RAND_bytes(&scratch
, 1);
324 // It's possible that another hypothetical crypto stack would not require
325 // pre-sandbox init, but more likely this is just a build configuration error.
326 #error Which SSL library are you using?
328 #if defined(ENABLE_PLUGINS)
329 // Ensure access to the Pepper plugins before the sandbox is turned on.
330 PreloadPepperPlugins();
332 #if defined(ENABLE_WEBRTC)
333 InitializeWebRtcModule();
335 SkFontConfigInterface::SetGlobal(
336 new FontConfigIPC(GetSandboxFD()))->unref();
339 static bool CreateInitProcessReaper(base::Closure
* post_fork_parent_callback
) {
340 // The current process becomes init(1), this function returns from a
341 // newly created process.
342 const bool init_created
=
343 sandbox::CreateInitProcessReaper(post_fork_parent_callback
);
345 LOG(ERROR
) << "Error creating an init process to reap zombies";
351 // Enter the setuid sandbox. This requires the current process to have been
352 // created through the setuid sandbox.
353 static bool EnterSuidSandbox(sandbox::SetuidSandboxClient
* setuid_sandbox
,
354 base::Closure
* post_fork_parent_callback
) {
355 DCHECK(setuid_sandbox
);
356 DCHECK(setuid_sandbox
->IsSuidSandboxChild());
358 // Use the SUID sandbox. This still allows the seccomp sandbox to
359 // be enabled by the process later.
361 if (!setuid_sandbox
->IsSuidSandboxUpToDate()) {
363 "You are using a wrong version of the setuid binary!\n"
365 "https://code.google.com/p/chromium/wiki/LinuxSUIDSandboxDevelopment."
369 if (!setuid_sandbox
->ChrootMe())
372 if (setuid_sandbox
->IsInNewPIDNamespace()) {
373 CHECK_EQ(1, getpid())
374 << "The SUID sandbox created a new PID namespace but Zygote "
375 "is not the init process. Please, make sure the SUID "
376 "binary is up to date.";
380 // The setuid sandbox has created a new PID namespace and we need
381 // to assume the role of init.
382 CHECK(CreateInitProcessReaper(post_fork_parent_callback
));
385 #if !defined(OS_OPENBSD)
386 // Previously, we required that the binary be non-readable. This causes the
387 // kernel to mark the process as non-dumpable at startup. The thinking was
388 // that, although we were putting the renderers into a PID namespace (with
389 // the SUID sandbox), they would nonetheless be in the /same/ PID
390 // namespace. So they could ptrace each other unless they were non-dumpable.
392 // If the binary was readable, then there would be a window between process
393 // startup and the point where we set the non-dumpable flag in which a
394 // compromised renderer could ptrace attach.
396 // However, now that we have a zygote model, only the (trusted) zygote
397 // exists at this point and we can set the non-dumpable flag which is
398 // inherited by all our renderer children.
400 // Note: a non-dumpable process can't be debugged. To debug sandbox-related
401 // issues, one can specify --allow-sandbox-debugging to let the process be
403 const CommandLine
& command_line
= *CommandLine::ForCurrentProcess();
404 if (!command_line
.HasSwitch(switches::kAllowSandboxDebugging
)) {
405 prctl(PR_SET_DUMPABLE
, 0, 0, 0, 0);
406 if (prctl(PR_GET_DUMPABLE
, 0, 0, 0, 0)) {
407 LOG(ERROR
) << "Failed to set non-dumpable flag";
416 #if defined(ADDRESS_SANITIZER)
417 const size_t kSanitizerMaxMessageLength
= 1 * 1024 * 1024;
419 // A helper process which collects code coverage data from the renderers over a
420 // socket and dumps it to a file. See http://crbug.com/336212 for discussion.
421 static void SanitizerCoverageHelper(int socket_fd
, int file_fd
) {
422 scoped_ptr
<char[]> buffer(new char[kSanitizerMaxMessageLength
]);
424 ssize_t received_size
= HANDLE_EINTR(
425 recv(socket_fd
, buffer
.get(), kSanitizerMaxMessageLength
, 0));
426 PCHECK(received_size
>= 0);
427 if (received_size
== 0)
428 // All clients have closed the socket. We should die.
430 PCHECK(file_fd
>= 0);
431 ssize_t written_size
= 0;
432 while (written_size
< received_size
) {
434 HANDLE_EINTR(write(file_fd
, buffer
.get() + written_size
,
435 received_size
- written_size
));
436 PCHECK(write_res
>= 0);
437 written_size
+= write_res
;
439 PCHECK(0 == HANDLE_EINTR(fsync(file_fd
)));
443 // fds[0] is the read end, fds[1] is the write end.
444 static void CreateSanitizerCoverageSocketPair(int fds
[2]) {
445 PCHECK(0 == socketpair(AF_UNIX
, SOCK_SEQPACKET
, 0, fds
));
446 PCHECK(0 == shutdown(fds
[0], SHUT_WR
));
447 PCHECK(0 == shutdown(fds
[1], SHUT_RD
));
450 static pid_t
ForkSanitizerCoverageHelper(int child_fd
, int parent_fd
,
451 base::ScopedFD file_fd
) {
456 PCHECK(0 == IGNORE_EINTR(close(parent_fd
)));
457 SanitizerCoverageHelper(child_fd
, file_fd
.get());
461 PCHECK(0 == IGNORE_EINTR(close(child_fd
)));
466 void CloseFdPair(const int fds
[2]) {
467 PCHECK(0 == IGNORE_EINTR(close(fds
[0])));
468 PCHECK(0 == IGNORE_EINTR(close(fds
[1])));
470 #endif // defined(ADDRESS_SANITIZER)
472 // If |is_suid_sandbox_child|, then make sure that the setuid sandbox is
474 static void EnterLayerOneSandbox(LinuxSandbox
* linux_sandbox
,
475 bool is_suid_sandbox_child
,
476 base::Closure
* post_fork_parent_callback
) {
477 DCHECK(linux_sandbox
);
479 ZygotePreSandboxInit();
481 // Check that the pre-sandbox initialization didn't spawn threads.
482 #if !defined(THREAD_SANITIZER)
483 DCHECK(linux_sandbox
->IsSingleThreaded());
486 sandbox::SetuidSandboxClient
* setuid_sandbox
=
487 linux_sandbox
->setuid_sandbox_client();
489 if (is_suid_sandbox_child
) {
490 CHECK(EnterSuidSandbox(setuid_sandbox
, post_fork_parent_callback
))
491 << "Failed to enter setuid sandbox";
495 bool ZygoteMain(const MainFunctionParams
& params
,
496 ScopedVector
<ZygoteForkDelegate
> fork_delegates
) {
497 g_am_zygote_or_renderer
= true;
498 sandbox::InitLibcUrandomOverrides();
500 base::Closure
*post_fork_parent_callback
= NULL
;
502 LinuxSandbox
* linux_sandbox
= LinuxSandbox::GetInstance();
504 #if defined(ADDRESS_SANITIZER)
505 const std::string sancov_file_name
=
506 "zygote." + base::Uint64ToString(base::RandUint64());
507 base::ScopedFD
sancov_file_fd(
508 __sanitizer_maybe_open_cov_file(sancov_file_name
.c_str()));
509 int sancov_socket_fds
[2] = {-1, -1};
510 CreateSanitizerCoverageSocketPair(sancov_socket_fds
);
511 linux_sandbox
->sanitizer_args()->coverage_sandboxed
= 1;
512 linux_sandbox
->sanitizer_args()->coverage_fd
= sancov_socket_fds
[1];
513 linux_sandbox
->sanitizer_args()->coverage_max_block_size
=
514 kSanitizerMaxMessageLength
;
515 // Zygote termination will block until the helper process exits, which will
516 // not happen until the write end of the socket is closed everywhere. Make
517 // sure the init process does not hold on to it.
518 base::Closure close_sancov_socket_fds
=
519 base::Bind(&CloseFdPair
, sancov_socket_fds
);
520 post_fork_parent_callback
= &close_sancov_socket_fds
;
523 // This will pre-initialize the various sandboxes that need it.
524 linux_sandbox
->PreinitializeSandbox();
526 const bool must_enable_setuid_sandbox
=
527 linux_sandbox
->setuid_sandbox_client()->IsSuidSandboxChild();
528 if (must_enable_setuid_sandbox
) {
529 linux_sandbox
->setuid_sandbox_client()->CloseDummyFile();
531 // Let the ZygoteHost know we're booting up.
532 CHECK(UnixDomainSocket::SendMsg(kZygoteSocketPairFd
,
534 sizeof(kZygoteBootMessage
),
535 std::vector
<int>()));
538 VLOG(1) << "ZygoteMain: initializing " << fork_delegates
.size()
539 << " fork delegates";
540 for (ScopedVector
<ZygoteForkDelegate
>::iterator i
= fork_delegates
.begin();
541 i
!= fork_delegates
.end();
543 (*i
)->Init(GetSandboxFD(), must_enable_setuid_sandbox
);
546 // Turn on the first layer of the sandbox if the configuration warrants it.
547 EnterLayerOneSandbox(linux_sandbox
, must_enable_setuid_sandbox
,
548 post_fork_parent_callback
);
550 std::vector
<pid_t
> extra_children
;
551 std::vector
<int> extra_fds
;
553 #if defined(ADDRESS_SANITIZER)
554 pid_t sancov_helper_pid
= ForkSanitizerCoverageHelper(
555 sancov_socket_fds
[0], sancov_socket_fds
[1], sancov_file_fd
.Pass());
556 // It's important that the zygote reaps the helper before dying. Otherwise,
557 // the destruction of the PID namespace could kill the helper before it
558 // completes its I/O tasks. |sancov_helper_pid| will exit once the last
559 // renderer holding the write end of |sancov_socket_fds| closes it.
560 extra_children
.push_back(sancov_helper_pid
);
561 // Sanitizer code in the renderers will inherit the write end of the socket
562 // from the zygote. We must keep it open until the very end of the zygote's
563 // lifetime, even though we don't explicitly use it.
564 extra_fds
.push_back(sancov_socket_fds
[1]);
567 int sandbox_flags
= linux_sandbox
->GetStatus();
568 bool setuid_sandbox_engaged
= sandbox_flags
& kSandboxLinuxSUID
;
569 CHECK_EQ(must_enable_setuid_sandbox
, setuid_sandbox_engaged
);
571 Zygote
zygote(sandbox_flags
, fork_delegates
.Pass(), extra_children
,
573 // This function call can return multiple times, once per fork().
574 return zygote
.ProcessRequests();
577 } // namespace content