blob: ac9067f4180f6f898e8ab0a2777daf645659d52a [file] [log] [blame]
[email protected]cc8f1462009-06-12 17:36:551// Copyright (c) 2009 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.
4
[email protected]a0f200ea2009-08-06 18:44:065#include <dlfcn.h>
[email protected]cc8f1462009-06-12 17:36:556#include <unistd.h>
7#include <sys/epoll.h>
8#include <sys/types.h>
9#include <sys/socket.h>
10#include <sys/signal.h>
[email protected]abe3ad92009-06-15 18:15:0811#include <sys/prctl.h>
[email protected]87ed6952009-07-16 02:52:1512#include <sys/wait.h>
[email protected]cc8f1462009-06-12 17:36:5513
[email protected]789f70c72009-07-24 13:55:4314#include "base/basictypes.h"
[email protected]cc8f1462009-06-12 17:36:5515#include "base/command_line.h"
16#include "base/eintr_wrapper.h"
17#include "base/global_descriptors_posix.h"
[email protected]c9e45da02009-08-05 17:35:0818#include "base/path_service.h"
[email protected]cc8f1462009-06-12 17:36:5519#include "base/pickle.h"
[email protected]4378a822009-07-08 01:15:1420#include "base/rand_util.h"
[email protected]80a086c52009-08-04 17:52:0421#include "base/sys_info.h"
[email protected]cc8f1462009-06-12 17:36:5522#include "base/unix_domain_socket_posix.h"
23
24#include "chrome/browser/zygote_host_linux.h"
25#include "chrome/common/chrome_descriptors.h"
[email protected]4730db92009-07-22 00:40:4826#include "chrome/common/chrome_switches.h"
[email protected]cc8f1462009-06-12 17:36:5527#include "chrome/common/main_function_params.h"
28#include "chrome/common/process_watcher.h"
[email protected]73fa63992009-07-20 20:30:0729#include "chrome/common/sandbox_methods_linux.h"
[email protected]cc8f1462009-06-12 17:36:5530
[email protected]c9e45da02009-08-05 17:35:0831#include "media/base/media.h"
32
[email protected]abe3ad92009-06-15 18:15:0833#include "skia/ext/SkFontHost_fontconfig_control.h"
34
[email protected]cc8f1462009-06-12 17:36:5535// http://code.google.com/p/chromium/wiki/LinuxZygote
36
[email protected]73fa63992009-07-20 20:30:0737static const int kMagicSandboxIPCDescriptor = 5;
38
[email protected]cc8f1462009-06-12 17:36:5539// This is the object which implements the zygote. The ZygoteMain function,
40// which is called from ChromeMain, at the the bottom and simple constructs one
41// of these objects and runs it.
42class Zygote {
43 public:
44 bool ProcessRequests() {
45 // A SOCK_SEQPACKET socket is installed in fd 3. We get commands from the
46 // browser on it.
[email protected]abe3ad92009-06-15 18:15:0847 // A SOCK_DGRAM is installed in fd 4. This is the sandbox IPC channel.
48 // See http://code.google.com/p/chromium/wiki/LinuxSandboxIPC
[email protected]cc8f1462009-06-12 17:36:5549
50 // We need to accept SIGCHLD, even though our handler is a no-op because
51 // otherwise we cannot wait on children. (According to POSIX 2001.)
52 struct sigaction action;
53 memset(&action, 0, sizeof(action));
54 action.sa_handler = SIGCHLDHandler;
55 CHECK(sigaction(SIGCHLD, &action, NULL) == 0);
56
57 for (;;) {
58 if (HandleRequestFromBrowser(3))
59 return true;
60 }
61 }
62
63 private:
64 // See comment below, where sigaction is called.
65 static void SIGCHLDHandler(int signal) { }
66
67 // ---------------------------------------------------------------------------
68 // Requests from the browser...
69
70 // Read and process a request from the browser. Returns true if we are in a
71 // new process and thus need to unwind back into ChromeMain.
72 bool HandleRequestFromBrowser(int fd) {
73 std::vector<int> fds;
[email protected]abe3ad92009-06-15 18:15:0874 static const unsigned kMaxMessageLength = 1024;
[email protected]cc8f1462009-06-12 17:36:5575 char buf[kMaxMessageLength];
76 const ssize_t len = base::RecvMsg(fd, buf, sizeof(buf), &fds);
77 if (len == -1) {
78 LOG(WARNING) << "Error reading message from browser: " << errno;
79 return false;
80 }
81
82 if (len == 0) {
83 // EOF from the browser. We should die.
84 _exit(0);
85 return false;
86 }
87
88 Pickle pickle(buf, len);
89 void* iter = NULL;
90
91 int kind;
[email protected]57113ea2009-06-18 02:23:1692 if (pickle.ReadInt(&iter, &kind)) {
93 switch (kind) {
94 case ZygoteHost::kCmdFork:
95 return HandleForkRequest(fd, pickle, iter, fds);
96 case ZygoteHost::kCmdReap:
97 if (!fds.empty())
98 break;
99 return HandleReapRequest(fd, pickle, iter);
100 case ZygoteHost::kCmdDidProcessCrash:
101 if (!fds.empty())
102 break;
103 return HandleDidProcessCrash(fd, pickle, iter);
104 default:
105 NOTREACHED();
106 break;
107 }
[email protected]cc8f1462009-06-12 17:36:55108 }
109
[email protected]cc8f1462009-06-12 17:36:55110 LOG(WARNING) << "Error parsing message from browser";
111 for (std::vector<int>::const_iterator
112 i = fds.begin(); i != fds.end(); ++i)
113 close(*i);
114 return false;
115 }
116
117 bool HandleReapRequest(int fd, Pickle& pickle, void* iter) {
118 pid_t child;
119
120 if (!pickle.ReadInt(&iter, &child)) {
121 LOG(WARNING) << "Error parsing reap request from browser";
122 return false;
123 }
124
125 ProcessWatcher::EnsureProcessTerminated(child);
126
127 return false;
128 }
129
[email protected]57113ea2009-06-18 02:23:16130 bool HandleDidProcessCrash(int fd, Pickle& pickle, void* iter) {
131 base::ProcessHandle child;
132
133 if (!pickle.ReadInt(&iter, &child)) {
134 LOG(WARNING) << "Error parsing DidProcessCrash request from browser";
135 return false;
136 }
137
138 bool child_exited;
139 bool did_crash = base::DidProcessCrash(&child_exited, child);
140
141 Pickle write_pickle;
142 write_pickle.WriteBool(did_crash);
143 write_pickle.WriteBool(child_exited);
144 HANDLE_EINTR(write(fd, write_pickle.data(), write_pickle.size()));
145
146 return false;
147 }
148
[email protected]cc8f1462009-06-12 17:36:55149 // Handle a 'fork' request from the browser: this means that the browser
150 // wishes to start a new renderer.
151 bool HandleForkRequest(int fd, Pickle& pickle, void* iter,
152 std::vector<int>& fds) {
153 std::vector<std::string> args;
154 int argc, numfds;
155 base::GlobalDescriptors::Mapping mapping;
156 pid_t child;
157
158 if (!pickle.ReadInt(&iter, &argc))
159 goto error;
160
161 for (int i = 0; i < argc; ++i) {
162 std::string arg;
163 if (!pickle.ReadString(&iter, &arg))
164 goto error;
165 args.push_back(arg);
166 }
167
168 if (!pickle.ReadInt(&iter, &numfds))
169 goto error;
170 if (numfds != static_cast<int>(fds.size()))
171 goto error;
172
173 for (int i = 0; i < numfds; ++i) {
174 base::GlobalDescriptors::Key key;
175 if (!pickle.ReadUInt32(&iter, &key))
176 goto error;
177 mapping.push_back(std::make_pair(key, fds[i]));
178 }
179
[email protected]abe3ad92009-06-15 18:15:08180 mapping.push_back(std::make_pair(
[email protected]e00f9da2009-06-26 00:47:05181 static_cast<uint32_t>(kSandboxIPCChannel), 5));
[email protected]abe3ad92009-06-15 18:15:08182
[email protected]cc8f1462009-06-12 17:36:55183 child = fork();
184
185 if (!child) {
186 close(3); // our socket from the browser is in fd 3
187 Singleton<base::GlobalDescriptors>()->Reset(mapping);
188 CommandLine::Reset();
189 CommandLine::Init(args);
[email protected]7f113f32009-09-10 18:02:17190 CommandLine::SetProcTitle();
[email protected]cc8f1462009-06-12 17:36:55191 return true;
192 }
193
194 for (std::vector<int>::const_iterator
195 i = fds.begin(); i != fds.end(); ++i)
196 close(*i);
197
198 HANDLE_EINTR(write(fd, &child, sizeof(child)));
199 return false;
200
201 error:
202 LOG(WARNING) << "Error parsing fork request from browser";
203 for (std::vector<int>::const_iterator
204 i = fds.begin(); i != fds.end(); ++i)
205 close(*i);
206 return false;
207 }
[email protected]cc8f1462009-06-12 17:36:55208};
209
[email protected]a0f200ea2009-08-06 18:44:06210static void ProxyLocaltimeCallToBrowser(time_t input, struct tm* output,
211 char* timezone_out,
212 size_t timezone_out_len) {
[email protected]73fa63992009-07-20 20:30:07213 Pickle request;
214 request.WriteInt(LinuxSandbox::METHOD_LOCALTIME);
215 request.WriteString(
216 std::string(reinterpret_cast<char*>(&input), sizeof(input)));
217
218 uint8_t reply_buf[512];
219 const ssize_t r = base::SendRecvMsg(
220 kMagicSandboxIPCDescriptor, reply_buf, sizeof(reply_buf), NULL, request);
221 if (r == -1) {
222 memset(output, 0, sizeof(struct tm));
223 return;
224 }
225
226 Pickle reply(reinterpret_cast<char*>(reply_buf), r);
227 void* iter = NULL;
[email protected]9debcda52009-07-22 20:06:51228 std::string result, timezone;
[email protected]73fa63992009-07-20 20:30:07229 if (!reply.ReadString(&iter, &result) ||
[email protected]9debcda52009-07-22 20:06:51230 !reply.ReadString(&iter, &timezone) ||
[email protected]73fa63992009-07-20 20:30:07231 result.size() != sizeof(struct tm)) {
232 memset(output, 0, sizeof(struct tm));
233 return;
234 }
235
236 memcpy(output, result.data(), sizeof(struct tm));
[email protected]9debcda52009-07-22 20:06:51237 if (timezone_out_len) {
238 const size_t copy_len = std::min(timezone_out_len - 1, timezone.size());
239 memcpy(timezone_out, timezone.data(), copy_len);
240 timezone_out[copy_len] = 0;
241 output->tm_zone = timezone_out;
242 } else {
243 output->tm_zone = NULL;
244 }
[email protected]73fa63992009-07-20 20:30:07245}
246
[email protected]a0f200ea2009-08-06 18:44:06247static bool g_am_zygote_or_renderer = false;
248
249// Sandbox interception of libc calls.
250//
251// Because we are running in a sandbox certain libc calls will fail (localtime
252// being the motivating example - it needs to read /etc/localtime). We need to
253// intercept these calls and proxy them to the browser. However, these calls
254// may come from us or from our libraries. In some cases we can't just change
255// our code.
256//
257// It's for these cases that we have the following setup:
258//
259// We define global functions for those functions which we wish to override.
260// Since we will be first in the dynamic resolution order, the dynamic linker
261// will point callers to our versions of these functions. However, we have the
262// same binary for both the browser and the renderers, which means that our
263// overrides will apply in the browser too.
264//
265// The global |g_am_zygote_or_renderer| is true iff we are in a zygote or
266// renderer process. It's set in ZygoteMain and inherited by the renderers when
267// they fork. (This means that it'll be incorrect for global constructor
268// functions and before ZygoteMain is called - beware).
269//
270// Our replacement functions can check this global and either proxy
271// the call to the browser over the sandbox IPC
272// (http://code.google.com/p/chromium/wiki/LinuxSandboxIPC) or they can use
273// dlsym with RTLD_NEXT to resolve the symbol, ignoring any symbols in the
274// current module.
275//
276// Other avenues:
277//
278// Our first attempt involved some assembly to patch the GOT of the current
279// module. This worked, but was platform specific and doesn't catch the case
280// where a library makes a call rather than current module.
281//
282// We also considered patching the function in place, but this would again by
283// platform specific and the above technique seems to work well enough.
284
[email protected]a5d7bb82009-09-08 22:30:58285static void WarnOnceAboutBrokenDlsym();
286
[email protected]73fa63992009-07-20 20:30:07287struct tm* localtime(const time_t* timep) {
[email protected]a0f200ea2009-08-06 18:44:06288 if (g_am_zygote_or_renderer) {
289 static struct tm time_struct;
290 static char timezone_string[64];
291 ProxyLocaltimeCallToBrowser(*timep, &time_struct, timezone_string,
292 sizeof(timezone_string));
293 return &time_struct;
294 } else {
295 typedef struct tm* (*LocaltimeFunction)(const time_t* timep);
296 static LocaltimeFunction libc_localtime;
[email protected]a5d7bb82009-09-08 22:30:58297 static bool have_libc_localtime = false;
298 if (!have_libc_localtime) {
[email protected]a0f200ea2009-08-06 18:44:06299 libc_localtime = (LocaltimeFunction) dlsym(RTLD_NEXT, "localtime");
[email protected]a5d7bb82009-09-08 22:30:58300 have_libc_localtime = true;
301 }
302
303 if (!libc_localtime) {
304 // http://code.google.com/p/chromium/issues/detail?id=16800
305 //
306 // Nvidia's libGL.so overrides dlsym for an unknown reason and replaces
307 // it with a version which doesn't work. In this case we'll get a NULL
308 // result. There's not a lot we can do at this point, so we just bodge it!
309 WarnOnceAboutBrokenDlsym();
310
311 return gmtime(timep);
312 }
[email protected]a0f200ea2009-08-06 18:44:06313
314 return libc_localtime(timep);
315 }
[email protected]73fa63992009-07-20 20:30:07316}
317
318struct tm* localtime_r(const time_t* timep, struct tm* result) {
[email protected]a0f200ea2009-08-06 18:44:06319 if (g_am_zygote_or_renderer) {
320 ProxyLocaltimeCallToBrowser(*timep, result, NULL, 0);
321 return result;
322 } else {
323 typedef struct tm* (*LocaltimeRFunction)(const time_t* timep,
324 struct tm* result);
325 static LocaltimeRFunction libc_localtime_r;
[email protected]a5d7bb82009-09-08 22:30:58326 static bool have_libc_localtime_r = false;
327 if (!have_libc_localtime_r) {
[email protected]a0f200ea2009-08-06 18:44:06328 libc_localtime_r = (LocaltimeRFunction) dlsym(RTLD_NEXT, "localtime_r");
[email protected]a5d7bb82009-09-08 22:30:58329 have_libc_localtime_r = true;
330 }
331
332 if (!libc_localtime_r) {
333 // See |localtime|, above.
334 WarnOnceAboutBrokenDlsym();
335
336 return gmtime_r(timep, result);
337 }
[email protected]a0f200ea2009-08-06 18:44:06338
339 return libc_localtime_r(timep, result);
340 }
[email protected]73fa63992009-07-20 20:30:07341}
342
[email protected]a5d7bb82009-09-08 22:30:58343// See the comments at the callsite in |localtime| about this function.
344static void WarnOnceAboutBrokenDlsym() {
345 static bool have_shown_warning = false;
346 if (!have_shown_warning) {
347 LOG(ERROR) << "Your system is broken: dlsym doesn't work! This has been "
348 "reported to be caused by Nvidia's libGL. You should expect "
349 "time related functions to misbehave. "
350 "http://code.google.com/p/chromium/issues/detail?id=16800";
351 have_shown_warning = true;
352 }
353}
354
[email protected]abe3ad92009-06-15 18:15:08355static bool MaybeEnterChroot() {
356 const char* const sandbox_fd_string = getenv("SBX_D");
357 if (sandbox_fd_string) {
358 // The SUID sandbox sets this environment variable to a file descriptor
359 // over which we can signal that we have completed our startup and can be
360 // chrooted.
361
362 char* endptr;
363 const long fd_long = strtol(sandbox_fd_string, &endptr, 10);
364 if (!*sandbox_fd_string || *endptr || fd_long < 0 || fd_long > INT_MAX)
365 return false;
366 const int fd = fd_long;
367
[email protected]4378a822009-07-08 01:15:14368 // Before entering the sandbox, "prime" any systems that need to open
369 // files and cache the results or the descriptors.
370 base::RandUint64();
371
[email protected]80a086c52009-08-04 17:52:04372 base::SysInfo::MaxSharedMemorySize();
373
[email protected]e6acd672009-07-24 21:51:33374 // To make wcstombs/mbstowcs work in a renderer, setlocale() has to be
375 // called before the sandbox is triggered. It's possible to avoid calling
376 // setlocale() by pulling out the conversion between FilePath and
377 // WebCore String out of the renderer and using string16 in place of
378 // FilePath for IPC.
379 const char* locale = setlocale(LC_ALL, "");
380 LOG_IF(WARNING, locale == NULL) << "setlocale failed.";
381
[email protected]c9e45da02009-08-05 17:35:08382 FilePath module_path;
383 if (PathService::Get(base::DIR_MODULE, &module_path))
384 media::InitializeMediaLibrary(module_path);
385
[email protected]abe3ad92009-06-15 18:15:08386 static const char kChrootMe = 'C';
387 static const char kChrootMeSuccess = 'O';
388
[email protected]0e1611122009-07-10 18:17:32389 if (HANDLE_EINTR(write(fd, &kChrootMe, 1)) != 1) {
390 LOG(ERROR) << "Failed to write to chroot pipe: " << errno;
[email protected]abe3ad92009-06-15 18:15:08391 return false;
[email protected]0e1611122009-07-10 18:17:32392 }
[email protected]abe3ad92009-06-15 18:15:08393
[email protected]87ed6952009-07-16 02:52:15394 // We need to reap the chroot helper process in any event:
395 wait(NULL);
396
[email protected]abe3ad92009-06-15 18:15:08397 char reply;
[email protected]87f8ce62009-07-10 19:14:31398 if (HANDLE_EINTR(read(fd, &reply, 1)) != 1) {
[email protected]0e1611122009-07-10 18:17:32399 LOG(ERROR) << "Failed to read from chroot pipe: " << errno;
[email protected]abe3ad92009-06-15 18:15:08400 return false;
[email protected]0e1611122009-07-10 18:17:32401 }
[email protected]87f8ce62009-07-10 19:14:31402
[email protected]0e1611122009-07-10 18:17:32403 if (reply != kChrootMeSuccess) {
404 LOG(ERROR) << "Error code reply from chroot helper";
[email protected]abe3ad92009-06-15 18:15:08405 return false;
[email protected]0e1611122009-07-10 18:17:32406 }
[email protected]abe3ad92009-06-15 18:15:08407
[email protected]abe3ad92009-06-15 18:15:08408 SkiaFontConfigUseIPCImplementation(kMagicSandboxIPCDescriptor);
409
[email protected]415493be2009-07-10 17:50:24410 // Previously, we required that the binary be non-readable. This causes the
411 // kernel to mark the process as non-dumpable at startup. The thinking was
412 // that, although we were putting the renderers into a PID namespace (with
413 // the SUID sandbox), they would nonetheless be in the /same/ PID
414 // namespace. So they could ptrace each other unless they were non-dumpable.
415 //
416 // If the binary was readable, then there would be a window between process
417 // startup and the point where we set the non-dumpable flag in which a
418 // compromised renderer could ptrace attach.
419 //
420 // However, now that we have a zygote model, only the (trusted) zygote
421 // exists at this point and we can set the non-dumpable flag which is
422 // inherited by all our renderer children.
[email protected]4730db92009-07-22 00:40:48423 //
424 // Note: a non-dumpable process can't be debugged. To debug sandbox-related
425 // issues, one can specify --allow-sandbox-debugging to let the process be
426 // dumpable.
427 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
428 if (!command_line.HasSwitch(switches::kAllowSandboxDebugging)) {
429 prctl(PR_SET_DUMPABLE, 0, 0, 0, 0);
430 if (prctl(PR_GET_DUMPABLE, 0, 0, 0, 0)) {
431 LOG(ERROR) << "Failed to set non-dumpable flag";
432 return false;
433 }
[email protected]0e1611122009-07-10 18:17:32434 }
[email protected]abe3ad92009-06-15 18:15:08435 } else {
436 SkiaFontConfigUseDirectImplementation();
437 }
438
439 return true;
440}
441
[email protected]cc8f1462009-06-12 17:36:55442bool ZygoteMain(const MainFunctionParams& params) {
[email protected]a0f200ea2009-08-06 18:44:06443 g_am_zygote_or_renderer = true;
444
[email protected]abe3ad92009-06-15 18:15:08445 if (!MaybeEnterChroot()) {
446 LOG(FATAL) << "Failed to enter sandbox. Fail safe abort. (errno: "
447 << errno << ")";
448 return false;
449 }
450
[email protected]cc8f1462009-06-12 17:36:55451 Zygote zygote;
452 return zygote.ProcessRequests();
453}