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/sys_info.h"
26 #include "build/build_config.h"
27 #include "content/common/child_process_sandbox_support_impl_linux.h"
28 #include "content/common/font_config_ipc_linux.h"
29 #include "content/common/pepper_plugin_list.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/pepper_plugin_info.h"
35 #include "content/public/common/sandbox_linux.h"
36 #include "content/public/common/zygote_fork_delegate_linux.h"
37 #include "content/zygote/zygote_linux.h"
38 #include "crypto/nss_util.h"
39 #include "sandbox/linux/services/init_process_reaper.h"
40 #include "sandbox/linux/services/libc_urandom_override.h"
41 #include "sandbox/linux/suid/client/setuid_sandbox_client.h"
42 #include "third_party/icu/source/i18n/unicode/timezone.h"
43 #include "third_party/skia/include/ports/SkFontConfigInterface.h"
46 #include <sys/prctl.h>
49 #if defined(ENABLE_WEBRTC)
50 #include "third_party/libjingle/overrides/init_webrtc.h"
53 #if defined(ADDRESS_SANITIZER)
54 #include <sanitizer/asan_interface.h>
59 // See http://code.google.com/p/chromium/wiki/LinuxZygote
61 static void ProxyLocaltimeCallToBrowser(time_t input
, struct tm
* output
,
63 size_t timezone_out_len
) {
65 request
.WriteInt(LinuxSandbox::METHOD_LOCALTIME
);
67 std::string(reinterpret_cast<char*>(&input
), sizeof(input
)));
69 uint8_t reply_buf
[512];
70 const ssize_t r
= UnixDomainSocket::SendRecvMsg(
71 GetSandboxFD(), reply_buf
, sizeof(reply_buf
), NULL
,
74 memset(output
, 0, sizeof(struct tm
));
78 Pickle
reply(reinterpret_cast<char*>(reply_buf
), r
);
79 PickleIterator
iter(reply
);
80 std::string result
, timezone
;
81 if (!reply
.ReadString(&iter
, &result
) ||
82 !reply
.ReadString(&iter
, &timezone
) ||
83 result
.size() != sizeof(struct tm
)) {
84 memset(output
, 0, sizeof(struct tm
));
88 memcpy(output
, result
.data(), sizeof(struct tm
));
89 if (timezone_out_len
) {
90 const size_t copy_len
= std::min(timezone_out_len
- 1, timezone
.size());
91 memcpy(timezone_out
, timezone
.data(), copy_len
);
92 timezone_out
[copy_len
] = 0;
93 output
->tm_zone
= timezone_out
;
95 output
->tm_zone
= NULL
;
99 static bool g_am_zygote_or_renderer
= false;
101 // Sandbox interception of libc calls.
103 // Because we are running in a sandbox certain libc calls will fail (localtime
104 // being the motivating example - it needs to read /etc/localtime). We need to
105 // intercept these calls and proxy them to the browser. However, these calls
106 // may come from us or from our libraries. In some cases we can't just change
109 // It's for these cases that we have the following setup:
111 // We define global functions for those functions which we wish to override.
112 // Since we will be first in the dynamic resolution order, the dynamic linker
113 // will point callers to our versions of these functions. However, we have the
114 // same binary for both the browser and the renderers, which means that our
115 // overrides will apply in the browser too.
117 // The global |g_am_zygote_or_renderer| is true iff we are in a zygote or
118 // renderer process. It's set in ZygoteMain and inherited by the renderers when
119 // they fork. (This means that it'll be incorrect for global constructor
120 // functions and before ZygoteMain is called - beware).
122 // Our replacement functions can check this global and either proxy
123 // the call to the browser over the sandbox IPC
124 // (http://code.google.com/p/chromium/wiki/LinuxSandboxIPC) or they can use
125 // dlsym with RTLD_NEXT to resolve the symbol, ignoring any symbols in the
130 // Our first attempt involved some assembly to patch the GOT of the current
131 // module. This worked, but was platform specific and doesn't catch the case
132 // where a library makes a call rather than current module.
134 // We also considered patching the function in place, but this would again by
135 // platform specific and the above technique seems to work well enough.
137 typedef struct tm
* (*LocaltimeFunction
)(const time_t* timep
);
138 typedef struct tm
* (*LocaltimeRFunction
)(const time_t* timep
,
141 static pthread_once_t g_libc_localtime_funcs_guard
= PTHREAD_ONCE_INIT
;
142 static LocaltimeFunction g_libc_localtime
;
143 static LocaltimeFunction g_libc_localtime64
;
144 static LocaltimeRFunction g_libc_localtime_r
;
145 static LocaltimeRFunction g_libc_localtime64_r
;
147 static void InitLibcLocaltimeFunctions() {
148 g_libc_localtime
= reinterpret_cast<LocaltimeFunction
>(
149 dlsym(RTLD_NEXT
, "localtime"));
150 g_libc_localtime64
= reinterpret_cast<LocaltimeFunction
>(
151 dlsym(RTLD_NEXT
, "localtime64"));
152 g_libc_localtime_r
= reinterpret_cast<LocaltimeRFunction
>(
153 dlsym(RTLD_NEXT
, "localtime_r"));
154 g_libc_localtime64_r
= reinterpret_cast<LocaltimeRFunction
>(
155 dlsym(RTLD_NEXT
, "localtime64_r"));
157 if (!g_libc_localtime
|| !g_libc_localtime_r
) {
158 // http://code.google.com/p/chromium/issues/detail?id=16800
160 // Nvidia's libGL.so overrides dlsym for an unknown reason and replaces
161 // it with a version which doesn't work. In this case we'll get a NULL
162 // result. There's not a lot we can do at this point, so we just bodge it!
163 LOG(ERROR
) << "Your system is broken: dlsym doesn't work! This has been "
164 "reported to be caused by Nvidia's libGL. You should expect"
165 " time related functions to misbehave. "
166 "http://code.google.com/p/chromium/issues/detail?id=16800";
169 if (!g_libc_localtime
)
170 g_libc_localtime
= gmtime
;
171 if (!g_libc_localtime64
)
172 g_libc_localtime64
= g_libc_localtime
;
173 if (!g_libc_localtime_r
)
174 g_libc_localtime_r
= gmtime_r
;
175 if (!g_libc_localtime64_r
)
176 g_libc_localtime64_r
= g_libc_localtime_r
;
179 // Define localtime_override() function with asm name "localtime", so that all
180 // references to localtime() will resolve to this function. Notice that we need
181 // to set visibility attribute to "default" to export the symbol, as it is set
182 // to "hidden" by default in chrome per build/common.gypi.
183 __attribute__ ((__visibility__("default")))
184 struct tm
* localtime_override(const time_t* timep
) __asm__ ("localtime");
186 __attribute__ ((__visibility__("default")))
187 struct tm
* localtime_override(const time_t* timep
) {
188 if (g_am_zygote_or_renderer
) {
189 static struct tm time_struct
;
190 static char timezone_string
[64];
191 ProxyLocaltimeCallToBrowser(*timep
, &time_struct
, timezone_string
,
192 sizeof(timezone_string
));
195 CHECK_EQ(0, pthread_once(&g_libc_localtime_funcs_guard
,
196 InitLibcLocaltimeFunctions
));
197 struct tm
* res
= g_libc_localtime(timep
);
198 #if defined(MEMORY_SANITIZER)
199 if (res
) __msan_unpoison(res
, sizeof(*res
));
200 if (res
->tm_zone
) __msan_unpoison_string(res
->tm_zone
);
206 // Use same trick to override localtime64(), localtime_r() and localtime64_r().
207 __attribute__ ((__visibility__("default")))
208 struct tm
* localtime64_override(const time_t* timep
) __asm__ ("localtime64");
210 __attribute__ ((__visibility__("default")))
211 struct tm
* localtime64_override(const time_t* timep
) {
212 if (g_am_zygote_or_renderer
) {
213 static struct tm time_struct
;
214 static char timezone_string
[64];
215 ProxyLocaltimeCallToBrowser(*timep
, &time_struct
, timezone_string
,
216 sizeof(timezone_string
));
219 CHECK_EQ(0, pthread_once(&g_libc_localtime_funcs_guard
,
220 InitLibcLocaltimeFunctions
));
221 struct tm
* res
= g_libc_localtime64(timep
);
222 #if defined(MEMORY_SANITIZER)
223 if (res
) __msan_unpoison(res
, sizeof(*res
));
224 if (res
->tm_zone
) __msan_unpoison_string(res
->tm_zone
);
230 __attribute__ ((__visibility__("default")))
231 struct tm
* localtime_r_override(const time_t* timep
,
232 struct tm
* result
) __asm__ ("localtime_r");
234 __attribute__ ((__visibility__("default")))
235 struct tm
* localtime_r_override(const time_t* timep
, struct tm
* result
) {
236 if (g_am_zygote_or_renderer
) {
237 ProxyLocaltimeCallToBrowser(*timep
, result
, NULL
, 0);
240 CHECK_EQ(0, pthread_once(&g_libc_localtime_funcs_guard
,
241 InitLibcLocaltimeFunctions
));
242 struct tm
* res
= g_libc_localtime_r(timep
, result
);
243 #if defined(MEMORY_SANITIZER)
244 if (res
) __msan_unpoison(res
, sizeof(*res
));
245 if (res
->tm_zone
) __msan_unpoison_string(res
->tm_zone
);
251 __attribute__ ((__visibility__("default")))
252 struct tm
* localtime64_r_override(const time_t* timep
,
253 struct tm
* result
) __asm__ ("localtime64_r");
255 __attribute__ ((__visibility__("default")))
256 struct tm
* localtime64_r_override(const time_t* timep
, struct tm
* result
) {
257 if (g_am_zygote_or_renderer
) {
258 ProxyLocaltimeCallToBrowser(*timep
, result
, NULL
, 0);
261 CHECK_EQ(0, pthread_once(&g_libc_localtime_funcs_guard
,
262 InitLibcLocaltimeFunctions
));
263 struct tm
* res
= g_libc_localtime64_r(timep
, result
);
264 #if defined(MEMORY_SANITIZER)
265 if (res
) __msan_unpoison(res
, sizeof(*res
));
266 if (res
->tm_zone
) __msan_unpoison_string(res
->tm_zone
);
272 #if defined(ENABLE_PLUGINS)
273 // Loads the (native) libraries but does not initialize them (i.e., does not
274 // call PPP_InitializeModule). This is needed by the zygote on Linux to get
275 // access to the plugins before entering the sandbox.
276 void PreloadPepperPlugins() {
277 std::vector
<PepperPluginInfo
> plugins
;
278 ComputePepperPluginList(&plugins
);
279 for (size_t i
= 0; i
< plugins
.size(); ++i
) {
280 if (!plugins
[i
].is_internal
&& plugins
[i
].is_sandboxed
) {
281 base::NativeLibraryLoadError error
;
282 base::NativeLibrary library
= base::LoadNativeLibrary(plugins
[i
].path
,
284 VLOG_IF(1, !library
) << "Unable to load plugin "
285 << plugins
[i
].path
.value() << " "
288 (void)library
; // Prevent release-mode warning.
294 // This function triggers the static and lazy construction of objects that need
295 // to be created before imposing the sandbox.
296 static void ZygotePreSandboxInit() {
299 base::SysInfo::AmountOfPhysicalMemory();
300 base::SysInfo::MaxSharedMemorySize();
301 base::SysInfo::NumberOfProcessors();
303 // ICU DateFormat class (used in base/time_format.cc) needs to get the
304 // Olson timezone ID by accessing the zoneinfo files on disk. After
305 // TimeZone::createDefault is called once here, the timezone ID is
306 // cached and there's no more need to access the file system.
307 scoped_ptr
<icu::TimeZone
> zone(icu::TimeZone::createDefault());
310 // NSS libraries are loaded before sandbox is activated. This is to allow
311 // successful initialization of NSS which tries to load extra library files.
312 crypto::LoadNSSLibraries();
313 #elif defined(USE_OPENSSL)
314 // OpenSSL is intentionally not supported in the sandboxed processes, see
315 // http://crbug.com/99163. If that ever changes we'll likely need to init
316 // OpenSSL here (at least, load the library and error strings).
318 // It's possible that another hypothetical crypto stack would not require
319 // pre-sandbox init, but more likely this is just a build configuration error.
320 #error Which SSL library are you using?
322 #if defined(ENABLE_PLUGINS)
323 // Ensure access to the Pepper plugins before the sandbox is turned on.
324 PreloadPepperPlugins();
326 #if defined(ENABLE_WEBRTC)
327 InitializeWebRtcModule();
329 SkFontConfigInterface::SetGlobal(
330 new FontConfigIPC(GetSandboxFD()))->unref();
333 static bool CreateInitProcessReaper(base::Closure
* post_fork_parent_callback
) {
334 // The current process becomes init(1), this function returns from a
335 // newly created process.
336 const bool init_created
=
337 sandbox::CreateInitProcessReaper(post_fork_parent_callback
);
339 LOG(ERROR
) << "Error creating an init process to reap zombies";
345 // Enter the setuid sandbox. This requires the current process to have been
346 // created through the setuid sandbox.
347 static bool EnterSuidSandbox(sandbox::SetuidSandboxClient
* setuid_sandbox
,
348 base::Closure
* post_fork_parent_callback
) {
349 DCHECK(setuid_sandbox
);
350 DCHECK(setuid_sandbox
->IsSuidSandboxChild());
352 // Use the SUID sandbox. This still allows the seccomp sandbox to
353 // be enabled by the process later.
355 if (!setuid_sandbox
->IsSuidSandboxUpToDate()) {
357 "You are using a wrong version of the setuid binary!\n"
359 "https://code.google.com/p/chromium/wiki/LinuxSUIDSandboxDevelopment."
363 if (!setuid_sandbox
->ChrootMe())
366 if (setuid_sandbox
->IsInNewPIDNamespace()) {
367 CHECK_EQ(1, getpid())
368 << "The SUID sandbox created a new PID namespace but Zygote "
369 "is not the init process. Please, make sure the SUID "
370 "binary is up to date.";
374 // The setuid sandbox has created a new PID namespace and we need
375 // to assume the role of init.
376 CHECK(CreateInitProcessReaper(post_fork_parent_callback
));
379 #if !defined(OS_OPENBSD)
380 // Previously, we required that the binary be non-readable. This causes the
381 // kernel to mark the process as non-dumpable at startup. The thinking was
382 // that, although we were putting the renderers into a PID namespace (with
383 // the SUID sandbox), they would nonetheless be in the /same/ PID
384 // namespace. So they could ptrace each other unless they were non-dumpable.
386 // If the binary was readable, then there would be a window between process
387 // startup and the point where we set the non-dumpable flag in which a
388 // compromised renderer could ptrace attach.
390 // However, now that we have a zygote model, only the (trusted) zygote
391 // exists at this point and we can set the non-dumpable flag which is
392 // inherited by all our renderer children.
394 // Note: a non-dumpable process can't be debugged. To debug sandbox-related
395 // issues, one can specify --allow-sandbox-debugging to let the process be
397 const CommandLine
& command_line
= *CommandLine::ForCurrentProcess();
398 if (!command_line
.HasSwitch(switches::kAllowSandboxDebugging
)) {
399 prctl(PR_SET_DUMPABLE
, 0, 0, 0, 0);
400 if (prctl(PR_GET_DUMPABLE
, 0, 0, 0, 0)) {
401 LOG(ERROR
) << "Failed to set non-dumpable flag";
410 #if defined(ADDRESS_SANITIZER)
411 const size_t kSanitizerMaxMessageLength
= 1 * 1024 * 1024;
413 // A helper process which collects code coverage data from the renderers over a
414 // socket and dumps it to a file. See http://crbug.com/336212 for discussion.
415 static void SanitizerCoverageHelper(int socket_fd
, int file_fd
) {
416 scoped_ptr
<char[]> buffer(new char[kSanitizerMaxMessageLength
]);
418 ssize_t received_size
= HANDLE_EINTR(
419 recv(socket_fd
, buffer
.get(), kSanitizerMaxMessageLength
, 0));
420 PCHECK(received_size
>= 0);
421 if (received_size
== 0)
422 // All clients have closed the socket. We should die.
424 PCHECK(file_fd
>= 0);
425 ssize_t written_size
= 0;
426 while (written_size
< received_size
) {
428 HANDLE_EINTR(write(file_fd
, buffer
.get() + written_size
,
429 received_size
- written_size
));
430 PCHECK(write_res
>= 0);
431 written_size
+= write_res
;
433 PCHECK(0 == HANDLE_EINTR(fsync(file_fd
)));
437 // fds[0] is the read end, fds[1] is the write end.
438 static void CreateSanitizerCoverageSocketPair(int fds
[2]) {
439 PCHECK(0 == socketpair(AF_UNIX
, SOCK_SEQPACKET
, 0, fds
));
440 PCHECK(0 == shutdown(fds
[0], SHUT_WR
));
441 PCHECK(0 == shutdown(fds
[1], SHUT_RD
));
444 static pid_t
ForkSanitizerCoverageHelper(int child_fd
, int parent_fd
,
445 base::ScopedFD file_fd
) {
450 PCHECK(0 == IGNORE_EINTR(close(parent_fd
)));
451 SanitizerCoverageHelper(child_fd
, file_fd
.get());
455 PCHECK(0 == IGNORE_EINTR(close(child_fd
)));
460 void CloseFdPair(const int fds
[2]) {
461 PCHECK(0 == IGNORE_EINTR(close(fds
[0])));
462 PCHECK(0 == IGNORE_EINTR(close(fds
[1])));
464 #endif // defined(ADDRESS_SANITIZER)
466 // If |is_suid_sandbox_child|, then make sure that the setuid sandbox is
468 static void EnterLayerOneSandbox(LinuxSandbox
* linux_sandbox
,
469 bool is_suid_sandbox_child
,
470 base::Closure
* post_fork_parent_callback
) {
471 DCHECK(linux_sandbox
);
473 ZygotePreSandboxInit();
475 // Check that the pre-sandbox initialization didn't spawn threads.
476 #if !defined(THREAD_SANITIZER)
477 DCHECK(linux_sandbox
->IsSingleThreaded());
480 sandbox::SetuidSandboxClient
* setuid_sandbox
=
481 linux_sandbox
->setuid_sandbox_client();
483 if (is_suid_sandbox_child
) {
484 CHECK(EnterSuidSandbox(setuid_sandbox
, post_fork_parent_callback
))
485 << "Failed to enter setuid sandbox";
489 bool ZygoteMain(const MainFunctionParams
& params
,
490 ScopedVector
<ZygoteForkDelegate
> fork_delegates
) {
491 g_am_zygote_or_renderer
= true;
492 sandbox::InitLibcUrandomOverrides();
494 base::Closure
*post_fork_parent_callback
= NULL
;
496 LinuxSandbox
* linux_sandbox
= LinuxSandbox::GetInstance();
498 #if defined(ADDRESS_SANITIZER)
499 base::ScopedFD
sancov_file_fd(__sanitizer_maybe_open_cov_file("zygote"));
500 int sancov_socket_fds
[2] = {-1, -1};
501 CreateSanitizerCoverageSocketPair(sancov_socket_fds
);
502 linux_sandbox
->sanitizer_args()->coverage_sandboxed
= 1;
503 linux_sandbox
->sanitizer_args()->coverage_fd
= sancov_socket_fds
[1];
504 linux_sandbox
->sanitizer_args()->coverage_max_block_size
=
505 kSanitizerMaxMessageLength
;
506 // Zygote termination will block until the helper process exits, which will
507 // not happen until the write end of the socket is closed everywhere. Make
508 // sure the init process does not hold on to it.
509 base::Closure close_sancov_socket_fds
=
510 base::Bind(&CloseFdPair
, sancov_socket_fds
);
511 post_fork_parent_callback
= &close_sancov_socket_fds
;
514 // This will pre-initialize the various sandboxes that need it.
515 linux_sandbox
->PreinitializeSandbox();
517 const bool must_enable_setuid_sandbox
=
518 linux_sandbox
->setuid_sandbox_client()->IsSuidSandboxChild();
519 if (must_enable_setuid_sandbox
) {
520 linux_sandbox
->setuid_sandbox_client()->CloseDummyFile();
522 // Let the ZygoteHost know we're booting up.
523 CHECK(UnixDomainSocket::SendMsg(kZygoteSocketPairFd
,
525 sizeof(kZygoteBootMessage
),
526 std::vector
<int>()));
529 VLOG(1) << "ZygoteMain: initializing " << fork_delegates
.size()
530 << " fork delegates";
531 for (ScopedVector
<ZygoteForkDelegate
>::iterator i
= fork_delegates
.begin();
532 i
!= fork_delegates
.end();
534 (*i
)->Init(GetSandboxFD(), must_enable_setuid_sandbox
);
537 // Turn on the first layer of the sandbox if the configuration warrants it.
538 EnterLayerOneSandbox(linux_sandbox
, must_enable_setuid_sandbox
,
539 post_fork_parent_callback
);
541 std::vector
<pid_t
> extra_children
;
542 std::vector
<int> extra_fds
;
544 #if defined(ADDRESS_SANITIZER)
545 pid_t sancov_helper_pid
= ForkSanitizerCoverageHelper(
546 sancov_socket_fds
[0], sancov_socket_fds
[1], sancov_file_fd
.Pass());
547 // It's important that the zygote reaps the helper before dying. Otherwise,
548 // the destruction of the PID namespace could kill the helper before it
549 // completes its I/O tasks. |sancov_helper_pid| will exit once the last
550 // renderer holding the write end of |sancov_socket_fds| closes it.
551 extra_children
.push_back(sancov_helper_pid
);
552 // Sanitizer code in the renderers will inherit the write end of the socket
553 // from the zygote. We must keep it open until the very end of the zygote's
554 // lifetime, even though we don't explicitly use it.
555 extra_fds
.push_back(sancov_socket_fds
[1]);
558 int sandbox_flags
= linux_sandbox
->GetStatus();
559 bool setuid_sandbox_engaged
= sandbox_flags
& kSandboxLinuxSUID
;
560 CHECK_EQ(must_enable_setuid_sandbox
, setuid_sandbox_engaged
);
562 Zygote
zygote(sandbox_flags
, fork_delegates
.Pass(), extra_children
,
564 // This function call can return multiple times, once per fork().
565 return zygote
.ProcessRequests();
568 } // namespace content