blob: 7c50e14858b230f78708bdc14a724a61e322eab3 [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
5#include <unistd.h>
6#include <sys/epoll.h>
7#include <sys/types.h>
8#include <sys/socket.h>
9#include <sys/signal.h>
[email protected]abe3ad92009-06-15 18:15:0810#include <sys/prctl.h>
[email protected]87ed6952009-07-16 02:52:1511#include <sys/wait.h>
[email protected]cc8f1462009-06-12 17:36:5512
[email protected]789f70c72009-07-24 13:55:4313#include "base/basictypes.h"
[email protected]cc8f1462009-06-12 17:36:5514#include "base/command_line.h"
15#include "base/eintr_wrapper.h"
16#include "base/global_descriptors_posix.h"
17#include "base/pickle.h"
[email protected]4378a822009-07-08 01:15:1418#include "base/rand_util.h"
[email protected]cc8f1462009-06-12 17:36:5519#include "base/unix_domain_socket_posix.h"
20
21#include "chrome/browser/zygote_host_linux.h"
22#include "chrome/common/chrome_descriptors.h"
[email protected]4730db92009-07-22 00:40:4823#include "chrome/common/chrome_switches.h"
[email protected]cc8f1462009-06-12 17:36:5524#include "chrome/common/main_function_params.h"
25#include "chrome/common/process_watcher.h"
[email protected]73fa63992009-07-20 20:30:0726#include "chrome/common/sandbox_methods_linux.h"
[email protected]cc8f1462009-06-12 17:36:5527
[email protected]abe3ad92009-06-15 18:15:0828#include "skia/ext/SkFontHost_fontconfig_control.h"
29
[email protected]cc8f1462009-06-12 17:36:5530// http://code.google.com/p/chromium/wiki/LinuxZygote
31
[email protected]73fa63992009-07-20 20:30:0732static const int kMagicSandboxIPCDescriptor = 5;
33
[email protected]cc8f1462009-06-12 17:36:5534// This is the object which implements the zygote. The ZygoteMain function,
35// which is called from ChromeMain, at the the bottom and simple constructs one
36// of these objects and runs it.
37class Zygote {
38 public:
39 bool ProcessRequests() {
40 // A SOCK_SEQPACKET socket is installed in fd 3. We get commands from the
41 // browser on it.
[email protected]abe3ad92009-06-15 18:15:0842 // A SOCK_DGRAM is installed in fd 4. This is the sandbox IPC channel.
43 // See http://code.google.com/p/chromium/wiki/LinuxSandboxIPC
[email protected]cc8f1462009-06-12 17:36:5544
45 // We need to accept SIGCHLD, even though our handler is a no-op because
46 // otherwise we cannot wait on children. (According to POSIX 2001.)
47 struct sigaction action;
48 memset(&action, 0, sizeof(action));
49 action.sa_handler = SIGCHLDHandler;
50 CHECK(sigaction(SIGCHLD, &action, NULL) == 0);
51
52 for (;;) {
53 if (HandleRequestFromBrowser(3))
54 return true;
55 }
56 }
57
58 private:
59 // See comment below, where sigaction is called.
60 static void SIGCHLDHandler(int signal) { }
61
62 // ---------------------------------------------------------------------------
63 // Requests from the browser...
64
65 // Read and process a request from the browser. Returns true if we are in a
66 // new process and thus need to unwind back into ChromeMain.
67 bool HandleRequestFromBrowser(int fd) {
68 std::vector<int> fds;
[email protected]abe3ad92009-06-15 18:15:0869 static const unsigned kMaxMessageLength = 1024;
[email protected]cc8f1462009-06-12 17:36:5570 char buf[kMaxMessageLength];
71 const ssize_t len = base::RecvMsg(fd, buf, sizeof(buf), &fds);
72 if (len == -1) {
73 LOG(WARNING) << "Error reading message from browser: " << errno;
74 return false;
75 }
76
77 if (len == 0) {
78 // EOF from the browser. We should die.
79 _exit(0);
80 return false;
81 }
82
83 Pickle pickle(buf, len);
84 void* iter = NULL;
85
86 int kind;
[email protected]57113ea2009-06-18 02:23:1687 if (pickle.ReadInt(&iter, &kind)) {
88 switch (kind) {
89 case ZygoteHost::kCmdFork:
90 return HandleForkRequest(fd, pickle, iter, fds);
91 case ZygoteHost::kCmdReap:
92 if (!fds.empty())
93 break;
94 return HandleReapRequest(fd, pickle, iter);
95 case ZygoteHost::kCmdDidProcessCrash:
96 if (!fds.empty())
97 break;
98 return HandleDidProcessCrash(fd, pickle, iter);
99 default:
100 NOTREACHED();
101 break;
102 }
[email protected]cc8f1462009-06-12 17:36:55103 }
104
[email protected]cc8f1462009-06-12 17:36:55105 LOG(WARNING) << "Error parsing message from browser";
106 for (std::vector<int>::const_iterator
107 i = fds.begin(); i != fds.end(); ++i)
108 close(*i);
109 return false;
110 }
111
112 bool HandleReapRequest(int fd, Pickle& pickle, void* iter) {
113 pid_t child;
114
115 if (!pickle.ReadInt(&iter, &child)) {
116 LOG(WARNING) << "Error parsing reap request from browser";
117 return false;
118 }
119
120 ProcessWatcher::EnsureProcessTerminated(child);
121
122 return false;
123 }
124
[email protected]57113ea2009-06-18 02:23:16125 bool HandleDidProcessCrash(int fd, Pickle& pickle, void* iter) {
126 base::ProcessHandle child;
127
128 if (!pickle.ReadInt(&iter, &child)) {
129 LOG(WARNING) << "Error parsing DidProcessCrash request from browser";
130 return false;
131 }
132
133 bool child_exited;
134 bool did_crash = base::DidProcessCrash(&child_exited, child);
135
136 Pickle write_pickle;
137 write_pickle.WriteBool(did_crash);
138 write_pickle.WriteBool(child_exited);
139 HANDLE_EINTR(write(fd, write_pickle.data(), write_pickle.size()));
140
141 return false;
142 }
143
[email protected]cc8f1462009-06-12 17:36:55144 // Handle a 'fork' request from the browser: this means that the browser
145 // wishes to start a new renderer.
146 bool HandleForkRequest(int fd, Pickle& pickle, void* iter,
147 std::vector<int>& fds) {
148 std::vector<std::string> args;
149 int argc, numfds;
150 base::GlobalDescriptors::Mapping mapping;
151 pid_t child;
152
153 if (!pickle.ReadInt(&iter, &argc))
154 goto error;
155
156 for (int i = 0; i < argc; ++i) {
157 std::string arg;
158 if (!pickle.ReadString(&iter, &arg))
159 goto error;
160 args.push_back(arg);
161 }
162
163 if (!pickle.ReadInt(&iter, &numfds))
164 goto error;
165 if (numfds != static_cast<int>(fds.size()))
166 goto error;
167
168 for (int i = 0; i < numfds; ++i) {
169 base::GlobalDescriptors::Key key;
170 if (!pickle.ReadUInt32(&iter, &key))
171 goto error;
172 mapping.push_back(std::make_pair(key, fds[i]));
173 }
174
[email protected]abe3ad92009-06-15 18:15:08175 mapping.push_back(std::make_pair(
[email protected]e00f9da2009-06-26 00:47:05176 static_cast<uint32_t>(kSandboxIPCChannel), 5));
[email protected]abe3ad92009-06-15 18:15:08177
[email protected]cc8f1462009-06-12 17:36:55178 child = fork();
179
180 if (!child) {
181 close(3); // our socket from the browser is in fd 3
182 Singleton<base::GlobalDescriptors>()->Reset(mapping);
183 CommandLine::Reset();
184 CommandLine::Init(args);
185 return true;
186 }
187
188 for (std::vector<int>::const_iterator
189 i = fds.begin(); i != fds.end(); ++i)
190 close(*i);
191
192 HANDLE_EINTR(write(fd, &child, sizeof(child)));
193 return false;
194
195 error:
196 LOG(WARNING) << "Error parsing fork request from browser";
197 for (std::vector<int>::const_iterator
198 i = fds.begin(); i != fds.end(); ++i)
199 close(*i);
200 return false;
201 }
[email protected]cc8f1462009-06-12 17:36:55202};
203
[email protected]73fa63992009-07-20 20:30:07204// Patched dynamic symbol wrapper functions...
205namespace sandbox_wrapper {
206
[email protected]9debcda52009-07-22 20:06:51207void do_localtime(time_t input, struct tm* output, char* timezone_out,
208 size_t timezone_out_len) {
[email protected]73fa63992009-07-20 20:30:07209 Pickle request;
210 request.WriteInt(LinuxSandbox::METHOD_LOCALTIME);
211 request.WriteString(
212 std::string(reinterpret_cast<char*>(&input), sizeof(input)));
213
214 uint8_t reply_buf[512];
215 const ssize_t r = base::SendRecvMsg(
216 kMagicSandboxIPCDescriptor, reply_buf, sizeof(reply_buf), NULL, request);
217 if (r == -1) {
218 memset(output, 0, sizeof(struct tm));
219 return;
220 }
221
222 Pickle reply(reinterpret_cast<char*>(reply_buf), r);
223 void* iter = NULL;
[email protected]9debcda52009-07-22 20:06:51224 std::string result, timezone;
[email protected]73fa63992009-07-20 20:30:07225 if (!reply.ReadString(&iter, &result) ||
[email protected]9debcda52009-07-22 20:06:51226 !reply.ReadString(&iter, &timezone) ||
[email protected]73fa63992009-07-20 20:30:07227 result.size() != sizeof(struct tm)) {
228 memset(output, 0, sizeof(struct tm));
229 return;
230 }
231
232 memcpy(output, result.data(), sizeof(struct tm));
[email protected]9debcda52009-07-22 20:06:51233 if (timezone_out_len) {
234 const size_t copy_len = std::min(timezone_out_len - 1, timezone.size());
235 memcpy(timezone_out, timezone.data(), copy_len);
236 timezone_out[copy_len] = 0;
237 output->tm_zone = timezone_out;
238 } else {
239 output->tm_zone = NULL;
240 }
[email protected]73fa63992009-07-20 20:30:07241}
242
243struct tm* localtime(const time_t* timep) {
244 static struct tm time_struct;
[email protected]9debcda52009-07-22 20:06:51245 static char timezone_string[64];
246 do_localtime(*timep, &time_struct, timezone_string, sizeof(timezone_string));
[email protected]73fa63992009-07-20 20:30:07247 return &time_struct;
248}
249
250struct tm* localtime_r(const time_t* timep, struct tm* result) {
[email protected]9debcda52009-07-22 20:06:51251 do_localtime(*timep, result, NULL, 0);
[email protected]73fa63992009-07-20 20:30:07252 return result;
253}
254
255} // namespace sandbox_wrapper
256
257/* On IA-32, function calls which need to be resolved by the dynamic linker are
258 * directed to the producure linking table (PLT). Each PLT entry contains code
259 * which jumps (indirectly) via the global offset table (GOT):
260 * Dump of assembler code for function f@plt:
261 * 0x0804830c <f@plt+0>: jmp *0x804a004 # GOT indirect jump
262 * 0x08048312 <f@plt+6>: push $0x8
263 * 0x08048317 <f@plt+11>: jmp 0x80482ec <_init+48>
264 *
265 * At the beginning of a process's lifetime, the GOT entry jumps back to
266 * <f@plt+6> end then enters the dynamic linker. Once the symbol has been
267 * resolved, the GOT entry is patched so that future calls go directly to the
268 * resolved function.
269 *
270 * This macro finds the PLT entry for a given symbol, |symbol|, and reads the
271 * GOT entry address from the first instruction. It then patches that address
272 * with the address of a replacement function, |replacement|.
273 */
274#define PATCH_GLOBAL_OFFSET_TABLE(symbol, replacement) \
275 /* First, get the current instruction pointer since the PLT address */ \
276 /* is IP relative */ \
277 asm ("call 0f\n" \
278 "0: pop %%ecx\n" \
279 /* Move the IP relative address of the PLT entry into EAX */ \
280 "mov $" #symbol "@plt,%%eax\n" \
281 /* Add EAX to ECX to get an absolute entry */ \
282 "add %%eax,%%ecx\n" \
283 /* The value in ECX was relative to the add instruction, however, */ \
284 /* the IP value was that of the pop. The pop and mov take 6 */ \
285 /* bytes, so adding 6 gets us the correct address for the PLT. The */ \
286 /* first instruction at the PLT is FF 25 <abs address>, so we skip 2 */ \
287 /* bytes to get to the address. 6 + 2 = 8: */ \
288 "movl 8(%%ecx),%%ecx\n" \
289 /* Now ECX contains the address of the GOT entry, we poke our */ \
290 /* replacement function in there: */ \
291 "movl %0,(%%ecx)\n" \
292 : /* no output */ \
293 : "r" (replacement) \
294 : "memory", "%eax", "%ecx");
295
[email protected]abe3ad92009-06-15 18:15:08296static bool MaybeEnterChroot() {
297 const char* const sandbox_fd_string = getenv("SBX_D");
298 if (sandbox_fd_string) {
299 // The SUID sandbox sets this environment variable to a file descriptor
300 // over which we can signal that we have completed our startup and can be
301 // chrooted.
302
303 char* endptr;
304 const long fd_long = strtol(sandbox_fd_string, &endptr, 10);
305 if (!*sandbox_fd_string || *endptr || fd_long < 0 || fd_long > INT_MAX)
306 return false;
307 const int fd = fd_long;
308
[email protected]4378a822009-07-08 01:15:14309 // Before entering the sandbox, "prime" any systems that need to open
310 // files and cache the results or the descriptors.
311 base::RandUint64();
312
[email protected]e6acd672009-07-24 21:51:33313 // To make wcstombs/mbstowcs work in a renderer, setlocale() has to be
314 // called before the sandbox is triggered. It's possible to avoid calling
315 // setlocale() by pulling out the conversion between FilePath and
316 // WebCore String out of the renderer and using string16 in place of
317 // FilePath for IPC.
318 const char* locale = setlocale(LC_ALL, "");
319 LOG_IF(WARNING, locale == NULL) << "setlocale failed.";
320
[email protected]789f70c72009-07-24 13:55:43321#if defined(ARCH_CPU_X86_FAMILY)
[email protected]73fa63992009-07-20 20:30:07322 PATCH_GLOBAL_OFFSET_TABLE(localtime, sandbox_wrapper::localtime);
323 PATCH_GLOBAL_OFFSET_TABLE(localtime_r, sandbox_wrapper::localtime_r);
[email protected]789f70c72009-07-24 13:55:43324#endif
[email protected]73fa63992009-07-20 20:30:07325
[email protected]abe3ad92009-06-15 18:15:08326 static const char kChrootMe = 'C';
327 static const char kChrootMeSuccess = 'O';
328
[email protected]0e1611122009-07-10 18:17:32329 if (HANDLE_EINTR(write(fd, &kChrootMe, 1)) != 1) {
330 LOG(ERROR) << "Failed to write to chroot pipe: " << errno;
[email protected]abe3ad92009-06-15 18:15:08331 return false;
[email protected]0e1611122009-07-10 18:17:32332 }
[email protected]abe3ad92009-06-15 18:15:08333
[email protected]87ed6952009-07-16 02:52:15334 // We need to reap the chroot helper process in any event:
335 wait(NULL);
336
[email protected]abe3ad92009-06-15 18:15:08337 char reply;
[email protected]87f8ce62009-07-10 19:14:31338 if (HANDLE_EINTR(read(fd, &reply, 1)) != 1) {
[email protected]0e1611122009-07-10 18:17:32339 LOG(ERROR) << "Failed to read from chroot pipe: " << errno;
[email protected]abe3ad92009-06-15 18:15:08340 return false;
[email protected]0e1611122009-07-10 18:17:32341 }
[email protected]87f8ce62009-07-10 19:14:31342
[email protected]0e1611122009-07-10 18:17:32343 if (reply != kChrootMeSuccess) {
344 LOG(ERROR) << "Error code reply from chroot helper";
[email protected]abe3ad92009-06-15 18:15:08345 return false;
[email protected]0e1611122009-07-10 18:17:32346 }
[email protected]abe3ad92009-06-15 18:15:08347
[email protected]abe3ad92009-06-15 18:15:08348 SkiaFontConfigUseIPCImplementation(kMagicSandboxIPCDescriptor);
349
[email protected]415493be2009-07-10 17:50:24350 // Previously, we required that the binary be non-readable. This causes the
351 // kernel to mark the process as non-dumpable at startup. The thinking was
352 // that, although we were putting the renderers into a PID namespace (with
353 // the SUID sandbox), they would nonetheless be in the /same/ PID
354 // namespace. So they could ptrace each other unless they were non-dumpable.
355 //
356 // If the binary was readable, then there would be a window between process
357 // startup and the point where we set the non-dumpable flag in which a
358 // compromised renderer could ptrace attach.
359 //
360 // However, now that we have a zygote model, only the (trusted) zygote
361 // exists at this point and we can set the non-dumpable flag which is
362 // inherited by all our renderer children.
[email protected]4730db92009-07-22 00:40:48363 //
364 // Note: a non-dumpable process can't be debugged. To debug sandbox-related
365 // issues, one can specify --allow-sandbox-debugging to let the process be
366 // dumpable.
367 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
368 if (!command_line.HasSwitch(switches::kAllowSandboxDebugging)) {
369 prctl(PR_SET_DUMPABLE, 0, 0, 0, 0);
370 if (prctl(PR_GET_DUMPABLE, 0, 0, 0, 0)) {
371 LOG(ERROR) << "Failed to set non-dumpable flag";
372 return false;
373 }
[email protected]0e1611122009-07-10 18:17:32374 }
[email protected]abe3ad92009-06-15 18:15:08375 } else {
376 SkiaFontConfigUseDirectImplementation();
377 }
378
379 return true;
380}
381
[email protected]cc8f1462009-06-12 17:36:55382bool ZygoteMain(const MainFunctionParams& params) {
[email protected]abe3ad92009-06-15 18:15:08383 if (!MaybeEnterChroot()) {
384 LOG(FATAL) << "Failed to enter sandbox. Fail safe abort. (errno: "
385 << errno << ")";
386 return false;
387 }
388
[email protected]cc8f1462009-06-12 17:36:55389 Zygote zygote;
390 return zygote.ProcessRequests();
391}