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/sandbox_linux/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/init_process_reaper.h"
39 #include "sandbox/linux/services/libc_urandom_override.h"
40 #include "sandbox/linux/suid/client/setuid_sandbox_client.h"
41 #include "third_party/icu/source/i18n/unicode/timezone.h"
42 #include "third_party/skia/include/ports/SkFontConfigInterface.h"
45 #include <sys/prctl.h>
48 #if defined(USE_OPENSSL)
49 #include <openssl/rand.h>
52 #if defined(ENABLE_PLUGINS)
53 #include "content/common/pepper_plugin_list.h"
54 #include "content/public/common/pepper_plugin_info.h"
57 #if defined(ENABLE_WEBRTC)
58 #include "third_party/libjingle/overrides/init_webrtc.h"
61 #if defined(ADDRESS_SANITIZER)
62 #include <sanitizer/asan_interface.h>
67 // See http://code.google.com/p/chromium/wiki/LinuxZygote
69 static void ProxyLocaltimeCallToBrowser(time_t input
, struct tm
* output
,
71 size_t timezone_out_len
) {
73 request
.WriteInt(LinuxSandbox::METHOD_LOCALTIME
);
75 std::string(reinterpret_cast<char*>(&input
), sizeof(input
)));
77 uint8_t reply_buf
[512];
78 const ssize_t r
= UnixDomainSocket::SendRecvMsg(
79 GetSandboxFD(), reply_buf
, sizeof(reply_buf
), NULL
,
82 memset(output
, 0, sizeof(struct tm
));
86 Pickle
reply(reinterpret_cast<char*>(reply_buf
), r
);
87 PickleIterator
iter(reply
);
88 std::string result
, timezone
;
89 if (!reply
.ReadString(&iter
, &result
) ||
90 !reply
.ReadString(&iter
, &timezone
) ||
91 result
.size() != sizeof(struct tm
)) {
92 memset(output
, 0, sizeof(struct tm
));
96 memcpy(output
, result
.data(), sizeof(struct tm
));
97 if (timezone_out_len
) {
98 const size_t copy_len
= std::min(timezone_out_len
- 1, timezone
.size());
99 memcpy(timezone_out
, timezone
.data(), copy_len
);
100 timezone_out
[copy_len
] = 0;
101 output
->tm_zone
= timezone_out
;
103 output
->tm_zone
= NULL
;
107 static bool g_am_zygote_or_renderer
= false;
109 // Sandbox interception of libc calls.
111 // Because we are running in a sandbox certain libc calls will fail (localtime
112 // being the motivating example - it needs to read /etc/localtime). We need to
113 // intercept these calls and proxy them to the browser. However, these calls
114 // may come from us or from our libraries. In some cases we can't just change
117 // It's for these cases that we have the following setup:
119 // We define global functions for those functions which we wish to override.
120 // Since we will be first in the dynamic resolution order, the dynamic linker
121 // will point callers to our versions of these functions. However, we have the
122 // same binary for both the browser and the renderers, which means that our
123 // overrides will apply in the browser too.
125 // The global |g_am_zygote_or_renderer| is true iff we are in a zygote or
126 // renderer process. It's set in ZygoteMain and inherited by the renderers when
127 // they fork. (This means that it'll be incorrect for global constructor
128 // functions and before ZygoteMain is called - beware).
130 // Our replacement functions can check this global and either proxy
131 // the call to the browser over the sandbox IPC
132 // (http://code.google.com/p/chromium/wiki/LinuxSandboxIPC) or they can use
133 // dlsym with RTLD_NEXT to resolve the symbol, ignoring any symbols in the
138 // Our first attempt involved some assembly to patch the GOT of the current
139 // module. This worked, but was platform specific and doesn't catch the case
140 // where a library makes a call rather than current module.
142 // We also considered patching the function in place, but this would again by
143 // platform specific and the above technique seems to work well enough.
145 typedef struct tm
* (*LocaltimeFunction
)(const time_t* timep
);
146 typedef struct tm
* (*LocaltimeRFunction
)(const time_t* timep
,
149 static pthread_once_t g_libc_localtime_funcs_guard
= PTHREAD_ONCE_INIT
;
150 static LocaltimeFunction g_libc_localtime
;
151 static LocaltimeFunction g_libc_localtime64
;
152 static LocaltimeRFunction g_libc_localtime_r
;
153 static LocaltimeRFunction g_libc_localtime64_r
;
155 static void InitLibcLocaltimeFunctions() {
156 g_libc_localtime
= reinterpret_cast<LocaltimeFunction
>(
157 dlsym(RTLD_NEXT
, "localtime"));
158 g_libc_localtime64
= reinterpret_cast<LocaltimeFunction
>(
159 dlsym(RTLD_NEXT
, "localtime64"));
160 g_libc_localtime_r
= reinterpret_cast<LocaltimeRFunction
>(
161 dlsym(RTLD_NEXT
, "localtime_r"));
162 g_libc_localtime64_r
= reinterpret_cast<LocaltimeRFunction
>(
163 dlsym(RTLD_NEXT
, "localtime64_r"));
165 if (!g_libc_localtime
|| !g_libc_localtime_r
) {
166 // http://code.google.com/p/chromium/issues/detail?id=16800
168 // Nvidia's libGL.so overrides dlsym for an unknown reason and replaces
169 // it with a version which doesn't work. In this case we'll get a NULL
170 // result. There's not a lot we can do at this point, so we just bodge it!
171 LOG(ERROR
) << "Your system is broken: dlsym doesn't work! This has been "
172 "reported to be caused by Nvidia's libGL. You should expect"
173 " time related functions to misbehave. "
174 "http://code.google.com/p/chromium/issues/detail?id=16800";
177 if (!g_libc_localtime
)
178 g_libc_localtime
= gmtime
;
179 if (!g_libc_localtime64
)
180 g_libc_localtime64
= g_libc_localtime
;
181 if (!g_libc_localtime_r
)
182 g_libc_localtime_r
= gmtime_r
;
183 if (!g_libc_localtime64_r
)
184 g_libc_localtime64_r
= g_libc_localtime_r
;
187 // Define localtime_override() function with asm name "localtime", so that all
188 // references to localtime() will resolve to this function. Notice that we need
189 // to set visibility attribute to "default" to export the symbol, as it is set
190 // to "hidden" by default in chrome per build/common.gypi.
191 __attribute__ ((__visibility__("default")))
192 struct tm
* localtime_override(const time_t* timep
) __asm__ ("localtime");
194 __attribute__ ((__visibility__("default")))
195 struct tm
* localtime_override(const time_t* timep
) {
196 if (g_am_zygote_or_renderer
) {
197 static struct tm time_struct
;
198 static char timezone_string
[64];
199 ProxyLocaltimeCallToBrowser(*timep
, &time_struct
, timezone_string
,
200 sizeof(timezone_string
));
203 CHECK_EQ(0, pthread_once(&g_libc_localtime_funcs_guard
,
204 InitLibcLocaltimeFunctions
));
205 struct tm
* res
= g_libc_localtime(timep
);
206 #if defined(MEMORY_SANITIZER)
207 if (res
) __msan_unpoison(res
, sizeof(*res
));
208 if (res
->tm_zone
) __msan_unpoison_string(res
->tm_zone
);
214 // Use same trick to override localtime64(), localtime_r() and localtime64_r().
215 __attribute__ ((__visibility__("default")))
216 struct tm
* localtime64_override(const time_t* timep
) __asm__ ("localtime64");
218 __attribute__ ((__visibility__("default")))
219 struct tm
* localtime64_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_localtime64(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 __attribute__ ((__visibility__("default")))
239 struct tm
* localtime_r_override(const time_t* timep
,
240 struct tm
* result
) __asm__ ("localtime_r");
242 __attribute__ ((__visibility__("default")))
243 struct tm
* localtime_r_override(const time_t* timep
, struct tm
* result
) {
244 if (g_am_zygote_or_renderer
) {
245 ProxyLocaltimeCallToBrowser(*timep
, result
, NULL
, 0);
248 CHECK_EQ(0, pthread_once(&g_libc_localtime_funcs_guard
,
249 InitLibcLocaltimeFunctions
));
250 struct tm
* res
= g_libc_localtime_r(timep
, result
);
251 #if defined(MEMORY_SANITIZER)
252 if (res
) __msan_unpoison(res
, sizeof(*res
));
253 if (res
->tm_zone
) __msan_unpoison_string(res
->tm_zone
);
259 __attribute__ ((__visibility__("default")))
260 struct tm
* localtime64_r_override(const time_t* timep
,
261 struct tm
* result
) __asm__ ("localtime64_r");
263 __attribute__ ((__visibility__("default")))
264 struct tm
* localtime64_r_override(const time_t* timep
, struct tm
* result
) {
265 if (g_am_zygote_or_renderer
) {
266 ProxyLocaltimeCallToBrowser(*timep
, result
, NULL
, 0);
269 CHECK_EQ(0, pthread_once(&g_libc_localtime_funcs_guard
,
270 InitLibcLocaltimeFunctions
));
271 struct tm
* res
= g_libc_localtime64_r(timep
, result
);
272 #if defined(MEMORY_SANITIZER)
273 if (res
) __msan_unpoison(res
, sizeof(*res
));
274 if (res
->tm_zone
) __msan_unpoison_string(res
->tm_zone
);
280 #if defined(ENABLE_PLUGINS)
281 // Loads the (native) libraries but does not initialize them (i.e., does not
282 // call PPP_InitializeModule). This is needed by the zygote on Linux to get
283 // access to the plugins before entering the sandbox.
284 void PreloadPepperPlugins() {
285 std::vector
<PepperPluginInfo
> plugins
;
286 ComputePepperPluginList(&plugins
);
287 for (size_t i
= 0; i
< plugins
.size(); ++i
) {
288 if (!plugins
[i
].is_internal
&& plugins
[i
].is_sandboxed
) {
289 base::NativeLibraryLoadError error
;
290 base::NativeLibrary library
= base::LoadNativeLibrary(plugins
[i
].path
,
292 VLOG_IF(1, !library
) << "Unable to load plugin "
293 << plugins
[i
].path
.value() << " "
296 (void)library
; // Prevent release-mode warning.
302 // This function triggers the static and lazy construction of objects that need
303 // to be created before imposing the sandbox.
304 static void ZygotePreSandboxInit() {
307 base::SysInfo::AmountOfPhysicalMemory();
308 base::SysInfo::MaxSharedMemorySize();
309 base::SysInfo::NumberOfProcessors();
311 // ICU DateFormat class (used in base/time_format.cc) needs to get the
312 // Olson timezone ID by accessing the zoneinfo files on disk. After
313 // TimeZone::createDefault is called once here, the timezone ID is
314 // cached and there's no more need to access the file system.
315 scoped_ptr
<icu::TimeZone
> zone(icu::TimeZone::createDefault());
318 // NSS libraries are loaded before sandbox is activated. This is to allow
319 // successful initialization of NSS which tries to load extra library files.
320 crypto::LoadNSSLibraries();
321 #elif defined(USE_OPENSSL)
322 // Read a random byte in order to cause BoringSSL to open a file descriptor
325 RAND_bytes(&scratch
, 1);
327 // It's possible that another hypothetical crypto stack would not require
328 // pre-sandbox init, but more likely this is just a build configuration error.
329 #error Which SSL library are you using?
331 #if defined(ENABLE_PLUGINS)
332 // Ensure access to the Pepper plugins before the sandbox is turned on.
333 PreloadPepperPlugins();
335 #if defined(ENABLE_WEBRTC)
336 InitializeWebRtcModule();
338 SkFontConfigInterface::SetGlobal(
339 new FontConfigIPC(GetSandboxFD()))->unref();
342 static bool CreateInitProcessReaper(base::Closure
* post_fork_parent_callback
) {
343 // The current process becomes init(1), this function returns from a
344 // newly created process.
345 const bool init_created
=
346 sandbox::CreateInitProcessReaper(post_fork_parent_callback
);
348 LOG(ERROR
) << "Error creating an init process to reap zombies";
354 // Enter the setuid sandbox. This requires the current process to have been
355 // created through the setuid sandbox.
356 static bool EnterSuidSandbox(sandbox::SetuidSandboxClient
* setuid_sandbox
,
357 base::Closure
* post_fork_parent_callback
) {
358 DCHECK(setuid_sandbox
);
359 DCHECK(setuid_sandbox
->IsSuidSandboxChild());
361 // Use the SUID sandbox. This still allows the seccomp sandbox to
362 // be enabled by the process later.
364 if (!setuid_sandbox
->IsSuidSandboxUpToDate()) {
366 "You are using a wrong version of the setuid binary!\n"
368 "https://code.google.com/p/chromium/wiki/LinuxSUIDSandboxDevelopment."
372 if (!setuid_sandbox
->ChrootMe())
375 if (setuid_sandbox
->IsInNewPIDNamespace()) {
376 CHECK_EQ(1, getpid())
377 << "The SUID sandbox created a new PID namespace but Zygote "
378 "is not the init process. Please, make sure the SUID "
379 "binary is up to date.";
383 // The setuid sandbox has created a new PID namespace and we need
384 // to assume the role of init.
385 CHECK(CreateInitProcessReaper(post_fork_parent_callback
));
388 #if !defined(OS_OPENBSD)
389 // Previously, we required that the binary be non-readable. This causes the
390 // kernel to mark the process as non-dumpable at startup. The thinking was
391 // that, although we were putting the renderers into a PID namespace (with
392 // the SUID sandbox), they would nonetheless be in the /same/ PID
393 // namespace. So they could ptrace each other unless they were non-dumpable.
395 // If the binary was readable, then there would be a window between process
396 // startup and the point where we set the non-dumpable flag in which a
397 // compromised renderer could ptrace attach.
399 // However, now that we have a zygote model, only the (trusted) zygote
400 // exists at this point and we can set the non-dumpable flag which is
401 // inherited by all our renderer children.
403 // Note: a non-dumpable process can't be debugged. To debug sandbox-related
404 // issues, one can specify --allow-sandbox-debugging to let the process be
406 const CommandLine
& command_line
= *CommandLine::ForCurrentProcess();
407 if (!command_line
.HasSwitch(switches::kAllowSandboxDebugging
)) {
408 prctl(PR_SET_DUMPABLE
, 0, 0, 0, 0);
409 if (prctl(PR_GET_DUMPABLE
, 0, 0, 0, 0)) {
410 LOG(ERROR
) << "Failed to set non-dumpable flag";
419 #if defined(ADDRESS_SANITIZER)
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(int child_fd
, int parent_fd
,
454 base::ScopedFD file_fd
) {
459 PCHECK(0 == IGNORE_EINTR(close(parent_fd
)));
460 SanitizerCoverageHelper(child_fd
, file_fd
.get());
464 PCHECK(0 == IGNORE_EINTR(close(child_fd
)));
469 void CloseFdPair(const int fds
[2]) {
470 PCHECK(0 == IGNORE_EINTR(close(fds
[0])));
471 PCHECK(0 == IGNORE_EINTR(close(fds
[1])));
473 #endif // defined(ADDRESS_SANITIZER)
475 // If |is_suid_sandbox_child|, then make sure that the setuid sandbox is
477 static void EnterLayerOneSandbox(LinuxSandbox
* linux_sandbox
,
478 bool is_suid_sandbox_child
,
479 base::Closure
* post_fork_parent_callback
) {
480 DCHECK(linux_sandbox
);
482 ZygotePreSandboxInit();
484 // Check that the pre-sandbox initialization didn't spawn threads.
485 #if !defined(THREAD_SANITIZER)
486 DCHECK(linux_sandbox
->IsSingleThreaded());
489 sandbox::SetuidSandboxClient
* setuid_sandbox
=
490 linux_sandbox
->setuid_sandbox_client();
492 if (is_suid_sandbox_child
) {
493 CHECK(EnterSuidSandbox(setuid_sandbox
, post_fork_parent_callback
))
494 << "Failed to enter setuid sandbox";
498 bool ZygoteMain(const MainFunctionParams
& params
,
499 ScopedVector
<ZygoteForkDelegate
> fork_delegates
) {
500 g_am_zygote_or_renderer
= true;
501 sandbox::InitLibcUrandomOverrides();
503 base::Closure
*post_fork_parent_callback
= NULL
;
505 LinuxSandbox
* linux_sandbox
= LinuxSandbox::GetInstance();
507 #if defined(ADDRESS_SANITIZER)
508 const std::string sancov_file_name
=
509 "zygote." + base::Uint64ToString(base::RandUint64());
510 base::ScopedFD
sancov_file_fd(
511 __sanitizer_maybe_open_cov_file(sancov_file_name
.c_str()));
512 int sancov_socket_fds
[2] = {-1, -1};
513 CreateSanitizerCoverageSocketPair(sancov_socket_fds
);
514 linux_sandbox
->sanitizer_args()->coverage_sandboxed
= 1;
515 linux_sandbox
->sanitizer_args()->coverage_fd
= sancov_socket_fds
[1];
516 linux_sandbox
->sanitizer_args()->coverage_max_block_size
=
517 kSanitizerMaxMessageLength
;
518 // Zygote termination will block until the helper process exits, which will
519 // not happen until the write end of the socket is closed everywhere. Make
520 // sure the init process does not hold on to it.
521 base::Closure close_sancov_socket_fds
=
522 base::Bind(&CloseFdPair
, sancov_socket_fds
);
523 post_fork_parent_callback
= &close_sancov_socket_fds
;
526 // This will pre-initialize the various sandboxes that need it.
527 linux_sandbox
->PreinitializeSandbox();
529 const bool must_enable_setuid_sandbox
=
530 linux_sandbox
->setuid_sandbox_client()->IsSuidSandboxChild();
531 if (must_enable_setuid_sandbox
) {
532 linux_sandbox
->setuid_sandbox_client()->CloseDummyFile();
534 // Let the ZygoteHost know we're booting up.
535 CHECK(UnixDomainSocket::SendMsg(kZygoteSocketPairFd
,
537 sizeof(kZygoteBootMessage
),
538 std::vector
<int>()));
541 VLOG(1) << "ZygoteMain: initializing " << fork_delegates
.size()
542 << " fork delegates";
543 for (ScopedVector
<ZygoteForkDelegate
>::iterator i
= fork_delegates
.begin();
544 i
!= fork_delegates
.end();
546 (*i
)->Init(GetSandboxFD(), must_enable_setuid_sandbox
);
549 // Turn on the first layer of the sandbox if the configuration warrants it.
550 EnterLayerOneSandbox(linux_sandbox
, must_enable_setuid_sandbox
,
551 post_fork_parent_callback
);
553 std::vector
<pid_t
> extra_children
;
554 std::vector
<int> extra_fds
;
556 #if defined(ADDRESS_SANITIZER)
557 pid_t sancov_helper_pid
= ForkSanitizerCoverageHelper(
558 sancov_socket_fds
[0], sancov_socket_fds
[1], sancov_file_fd
.Pass());
559 // It's important that the zygote reaps the helper before dying. Otherwise,
560 // the destruction of the PID namespace could kill the helper before it
561 // completes its I/O tasks. |sancov_helper_pid| will exit once the last
562 // renderer holding the write end of |sancov_socket_fds| closes it.
563 extra_children
.push_back(sancov_helper_pid
);
564 // Sanitizer code in the renderers will inherit the write end of the socket
565 // from the zygote. We must keep it open until the very end of the zygote's
566 // lifetime, even though we don't explicitly use it.
567 extra_fds
.push_back(sancov_socket_fds
[1]);
570 int sandbox_flags
= linux_sandbox
->GetStatus();
571 bool setuid_sandbox_engaged
= sandbox_flags
& kSandboxLinuxSUID
;
572 CHECK_EQ(must_enable_setuid_sandbox
, setuid_sandbox_engaged
);
574 Zygote
zygote(sandbox_flags
, fork_delegates
.Pass(), extra_children
,
576 // This function call can return multiple times, once per fork().
577 return zygote
.ProcessRequests();
580 } // namespace content