Change the WebCrypto behavior when exporting EC private keys that were imported witho...
[chromium-blink-merge.git] / content / zygote / zygote_linux.cc
blobba2097ae277f921ec1eae356b211a8b2ec594b08
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_linux.h"
7 #include <fcntl.h>
8 #include <string.h>
9 #include <sys/socket.h>
10 #include <sys/types.h>
11 #include <sys/wait.h>
13 #include "base/command_line.h"
14 #include "base/debug/trace_event.h"
15 #include "base/files/file_util.h"
16 #include "base/linux_util.h"
17 #include "base/logging.h"
18 #include "base/macros.h"
19 #include "base/memory/scoped_vector.h"
20 #include "base/pickle.h"
21 #include "base/posix/eintr_wrapper.h"
22 #include "base/posix/global_descriptors.h"
23 #include "base/posix/unix_domain_socket_linux.h"
24 #include "base/process/kill.h"
25 #include "content/common/child_process_sandbox_support_impl_linux.h"
26 #include "content/common/sandbox_linux/sandbox_linux.h"
27 #include "content/common/set_process_title.h"
28 #include "content/common/zygote_commands_linux.h"
29 #include "content/public/common/content_descriptors.h"
30 #include "content/public/common/result_codes.h"
31 #include "content/public/common/sandbox_linux.h"
32 #include "content/public/common/send_zygote_child_ping_linux.h"
33 #include "content/public/common/zygote_fork_delegate_linux.h"
34 #include "ipc/ipc_channel.h"
35 #include "ipc/ipc_switches.h"
36 #include "sandbox/linux/services/syscall_wrappers.h"
38 #if defined(ADDRESS_SANITIZER)
39 #include <sanitizer/asan_interface.h>
40 #endif
42 // See http://code.google.com/p/chromium/wiki/LinuxZygote
44 namespace content {
46 namespace {
48 // NOP function. See below where this handler is installed.
49 void SIGCHLDHandler(int signal) {
52 int LookUpFd(const base::GlobalDescriptors::Mapping& fd_mapping, uint32_t key) {
53 for (size_t index = 0; index < fd_mapping.size(); ++index) {
54 if (fd_mapping[index].key == key)
55 return fd_mapping[index].fd;
57 return -1;
60 void CreatePipe(base::ScopedFD* read_pipe, base::ScopedFD* write_pipe) {
61 int raw_pipe[2];
62 PCHECK(0 == pipe(raw_pipe));
63 read_pipe->reset(raw_pipe[0]);
64 write_pipe->reset(raw_pipe[1]);
67 void KillAndReap(pid_t pid, ZygoteForkDelegate* helper) {
68 if (helper) {
69 // Helper children may be forked in another PID namespace, so |pid| might
70 // be meaningless to us; or we just might not be able to directly send it
71 // signals. So we can't kill it.
72 // Additionally, we're not its parent, so we can't reap it anyway.
73 // TODO(mdempsky): Extend the ZygoteForkDelegate API to handle this.
74 LOG(WARNING) << "Unable to kill or reap helper children";
75 return;
78 // Kill the child process in case it's not already dead, so we can safely
79 // perform a blocking wait.
80 PCHECK(0 == kill(pid, SIGKILL));
81 PCHECK(pid == HANDLE_EINTR(waitpid(pid, NULL, 0)));
84 } // namespace
86 Zygote::Zygote(int sandbox_flags, ScopedVector<ZygoteForkDelegate> helpers,
87 const std::vector<base::ProcessHandle>& extra_children,
88 const std::vector<int>& extra_fds)
89 : sandbox_flags_(sandbox_flags),
90 helpers_(helpers.Pass()),
91 initial_uma_index_(0),
92 extra_children_(extra_children),
93 extra_fds_(extra_fds) {}
95 Zygote::~Zygote() {
98 bool Zygote::ProcessRequests() {
99 // A SOCK_SEQPACKET socket is installed in fd 3. We get commands from the
100 // browser on it.
101 // A SOCK_DGRAM is installed in fd 5. This is the sandbox IPC channel.
102 // See http://code.google.com/p/chromium/wiki/LinuxSandboxIPC
104 // We need to accept SIGCHLD, even though our handler is a no-op because
105 // otherwise we cannot wait on children. (According to POSIX 2001.)
106 struct sigaction action;
107 memset(&action, 0, sizeof(action));
108 action.sa_handler = &SIGCHLDHandler;
109 CHECK(sigaction(SIGCHLD, &action, NULL) == 0);
111 if (UsingSUIDSandbox()) {
112 // Let the ZygoteHost know we are ready to go.
113 // The receiving code is in content/browser/zygote_host_linux.cc.
114 bool r = UnixDomainSocket::SendMsg(kZygoteSocketPairFd,
115 kZygoteHelloMessage,
116 sizeof(kZygoteHelloMessage),
117 std::vector<int>());
118 #if defined(OS_CHROMEOS)
119 LOG_IF(WARNING, !r) << "Sending zygote magic failed";
120 // Exit normally on chromeos because session manager may send SIGTERM
121 // right after the process starts and it may fail to send zygote magic
122 // number to browser process.
123 if (!r)
124 _exit(RESULT_CODE_NORMAL_EXIT);
125 #else
126 CHECK(r) << "Sending zygote magic failed";
127 #endif
130 for (;;) {
131 // This function call can return multiple times, once per fork().
132 if (HandleRequestFromBrowser(kZygoteSocketPairFd))
133 return true;
137 bool Zygote::GetProcessInfo(base::ProcessHandle pid,
138 ZygoteProcessInfo* process_info) {
139 DCHECK(process_info);
140 const ZygoteProcessMap::const_iterator it = process_info_map_.find(pid);
141 if (it == process_info_map_.end()) {
142 return false;
144 *process_info = it->second;
145 return true;
148 bool Zygote::UsingSUIDSandbox() const {
149 return sandbox_flags_ & kSandboxLinuxSUID;
152 bool Zygote::HandleRequestFromBrowser(int fd) {
153 ScopedVector<base::ScopedFD> fds;
154 char buf[kZygoteMaxMessageLength];
155 const ssize_t len = UnixDomainSocket::RecvMsg(fd, buf, sizeof(buf), &fds);
157 if (len == 0 || (len == -1 && errno == ECONNRESET)) {
158 // EOF from the browser. We should die.
159 // TODO(earthdok): call __sanititizer_cov_dump() here to obtain code
160 // coverage for the Zygote. Currently it's not possible because of
161 // confusion over who is responsible for closing the file descriptor.
162 for (std::vector<int>::iterator it = extra_fds_.begin();
163 it < extra_fds_.end(); ++it) {
164 PCHECK(0 == IGNORE_EINTR(close(*it)));
166 #if !defined(ADDRESS_SANITIZER)
167 // TODO(earthdok): add watchdog thread before using this in non-ASAN builds.
168 CHECK(extra_children_.empty());
169 #endif
170 for (std::vector<base::ProcessHandle>::iterator it =
171 extra_children_.begin();
172 it < extra_children_.end(); ++it) {
173 PCHECK(*it == HANDLE_EINTR(waitpid(*it, NULL, 0)));
175 _exit(0);
176 return false;
179 if (len == -1) {
180 PLOG(ERROR) << "Error reading message from browser";
181 return false;
184 Pickle pickle(buf, len);
185 PickleIterator iter(pickle);
187 int kind;
188 if (iter.ReadInt(&kind)) {
189 switch (kind) {
190 case kZygoteCommandFork:
191 // This function call can return multiple times, once per fork().
192 return HandleForkRequest(fd, iter, fds.Pass());
194 case kZygoteCommandReap:
195 if (!fds.empty())
196 break;
197 HandleReapRequest(fd, iter);
198 return false;
199 case kZygoteCommandGetTerminationStatus:
200 if (!fds.empty())
201 break;
202 HandleGetTerminationStatus(fd, iter);
203 return false;
204 case kZygoteCommandGetSandboxStatus:
205 HandleGetSandboxStatus(fd, iter);
206 return false;
207 case kZygoteCommandForkRealPID:
208 // This shouldn't happen in practice, but some failure paths in
209 // HandleForkRequest (e.g., if ReadArgsAndFork fails during depickling)
210 // could leave this command pending on the socket.
211 LOG(ERROR) << "Unexpected real PID message from browser";
212 NOTREACHED();
213 return false;
214 default:
215 NOTREACHED();
216 break;
220 LOG(WARNING) << "Error parsing message from browser";
221 return false;
224 // TODO(jln): remove callers to this broken API. See crbug.com/274855.
225 void Zygote::HandleReapRequest(int fd,
226 PickleIterator iter) {
227 base::ProcessId child;
229 if (!iter.ReadInt(&child)) {
230 LOG(WARNING) << "Error parsing reap request from browser";
231 return;
234 ZygoteProcessInfo child_info;
235 if (!GetProcessInfo(child, &child_info)) {
236 LOG(ERROR) << "Child not found!";
237 NOTREACHED();
238 return;
241 if (!child_info.started_from_helper) {
242 // Do not call base::EnsureProcessTerminated() under ThreadSanitizer, as it
243 // spawns a separate thread which may live until the call to fork() in the
244 // zygote. As a result, ThreadSanitizer will report an error and almost
245 // disable race detection in the child process.
246 // Not calling EnsureProcessTerminated() may result in zombie processes
247 // sticking around. This will only happen during testing, so we can live
248 // with this for now.
249 #if !defined(THREAD_SANITIZER)
250 // TODO(jln): this old code is completely broken. See crbug.com/274855.
251 base::EnsureProcessTerminated(base::Process(child_info.internal_pid));
252 #else
253 LOG(WARNING) << "Zygote process omitting a call to "
254 << "base::EnsureProcessTerminated() for child pid " << child
255 << " under ThreadSanitizer. See http://crbug.com/274855.";
256 #endif
257 } else {
258 // For processes from the helper, send a GetTerminationStatus request
259 // with known_dead set to true.
260 // This is not perfect, as the process may be killed instantly, but is
261 // better than ignoring the request.
262 base::TerminationStatus status;
263 int exit_code;
264 bool got_termination_status =
265 GetTerminationStatus(child, true /* known_dead */, &status, &exit_code);
266 DCHECK(got_termination_status);
268 process_info_map_.erase(child);
271 bool Zygote::GetTerminationStatus(base::ProcessHandle real_pid,
272 bool known_dead,
273 base::TerminationStatus* status,
274 int* exit_code) {
276 ZygoteProcessInfo child_info;
277 if (!GetProcessInfo(real_pid, &child_info)) {
278 LOG(ERROR) << "Zygote::GetTerminationStatus for unknown PID "
279 << real_pid;
280 NOTREACHED();
281 return false;
283 // We know about |real_pid|.
284 const base::ProcessHandle child = child_info.internal_pid;
285 if (child_info.started_from_helper) {
286 if (!child_info.started_from_helper->GetTerminationStatus(
287 child, known_dead, status, exit_code)) {
288 return false;
290 } else {
291 // Handle the request directly.
292 if (known_dead) {
293 *status = base::GetKnownDeadTerminationStatus(child, exit_code);
294 } else {
295 // We don't know if the process is dying, so get its status but don't
296 // wait.
297 *status = base::GetTerminationStatus(child, exit_code);
300 // Successfully got a status for |real_pid|.
301 if (*status != base::TERMINATION_STATUS_STILL_RUNNING) {
302 // Time to forget about this process.
303 process_info_map_.erase(real_pid);
305 return true;
308 void Zygote::HandleGetTerminationStatus(int fd,
309 PickleIterator iter) {
310 bool known_dead;
311 base::ProcessHandle child_requested;
313 if (!iter.ReadBool(&known_dead) || !iter.ReadInt(&child_requested)) {
314 LOG(WARNING) << "Error parsing GetTerminationStatus request "
315 << "from browser";
316 return;
319 base::TerminationStatus status;
320 int exit_code;
322 bool got_termination_status =
323 GetTerminationStatus(child_requested, known_dead, &status, &exit_code);
324 if (!got_termination_status) {
325 // Assume that if we can't find the child in the sandbox, then
326 // it terminated normally.
327 NOTREACHED();
328 status = base::TERMINATION_STATUS_NORMAL_TERMINATION;
329 exit_code = RESULT_CODE_NORMAL_EXIT;
332 Pickle write_pickle;
333 write_pickle.WriteInt(static_cast<int>(status));
334 write_pickle.WriteInt(exit_code);
335 ssize_t written =
336 HANDLE_EINTR(write(fd, write_pickle.data(), write_pickle.size()));
337 if (written != static_cast<ssize_t>(write_pickle.size()))
338 PLOG(ERROR) << "write";
341 int Zygote::ForkWithRealPid(const std::string& process_type,
342 const base::GlobalDescriptors::Mapping& fd_mapping,
343 const std::string& channel_id,
344 base::ScopedFD pid_oracle,
345 std::string* uma_name,
346 int* uma_sample,
347 int* uma_boundary_value) {
348 ZygoteForkDelegate* helper = NULL;
349 for (ScopedVector<ZygoteForkDelegate>::iterator i = helpers_.begin();
350 i != helpers_.end();
351 ++i) {
352 if ((*i)->CanHelp(process_type, uma_name, uma_sample, uma_boundary_value)) {
353 helper = *i;
354 break;
358 base::ScopedFD read_pipe, write_pipe;
359 base::ProcessId pid = 0;
360 if (helper) {
361 int ipc_channel_fd = LookUpFd(fd_mapping, kPrimaryIPCChannel);
362 if (ipc_channel_fd < 0) {
363 DLOG(ERROR) << "Failed to find kPrimaryIPCChannel in FD mapping";
364 return -1;
366 std::vector<int> fds;
367 fds.push_back(ipc_channel_fd); // kBrowserFDIndex
368 fds.push_back(pid_oracle.get()); // kPIDOracleFDIndex
369 pid = helper->Fork(process_type, fds, channel_id);
371 // Helpers should never return in the child process.
372 CHECK_NE(pid, 0);
373 } else {
374 CreatePipe(&read_pipe, &write_pipe);
375 // This is roughly equivalent to a fork(). We are using ForkWithFlags mainly
376 // to give it some more diverse test coverage.
377 pid = base::ForkWithFlags(SIGCHLD, nullptr, nullptr);
380 if (pid == 0) {
381 // In the child process.
382 write_pipe.reset();
384 // Ping the PID oracle socket so the browser can find our PID.
385 CHECK(SendZygoteChildPing(pid_oracle.get()));
387 // Now read back our real PID from the zygote.
388 base::ProcessId real_pid;
389 if (!base::ReadFromFD(read_pipe.get(),
390 reinterpret_cast<char*>(&real_pid),
391 sizeof(real_pid))) {
392 LOG(FATAL) << "Failed to synchronise with parent zygote process";
394 if (real_pid <= 0) {
395 LOG(FATAL) << "Invalid pid from parent zygote";
397 #if defined(OS_LINUX)
398 // Sandboxed processes need to send the global, non-namespaced PID when
399 // setting up an IPC channel to their parent.
400 IPC::Channel::SetGlobalPid(real_pid);
401 // Force the real PID so chrome event data have a PID that corresponds
402 // to system trace event data.
403 base::debug::TraceLog::GetInstance()->SetProcessID(
404 static_cast<int>(real_pid));
405 #endif
406 return 0;
409 // In the parent process.
410 read_pipe.reset();
411 pid_oracle.reset();
413 // Always receive a real PID from the zygote host, though it might
414 // be invalid (see below).
415 base::ProcessId real_pid;
417 ScopedVector<base::ScopedFD> recv_fds;
418 char buf[kZygoteMaxMessageLength];
419 const ssize_t len = UnixDomainSocket::RecvMsg(
420 kZygoteSocketPairFd, buf, sizeof(buf), &recv_fds);
421 CHECK_GT(len, 0);
422 CHECK(recv_fds.empty());
424 Pickle pickle(buf, len);
425 PickleIterator iter(pickle);
427 int kind;
428 CHECK(iter.ReadInt(&kind));
429 CHECK(kind == kZygoteCommandForkRealPID);
430 CHECK(iter.ReadInt(&real_pid));
433 // Fork failed.
434 if (pid < 0) {
435 return -1;
438 // If we successfully forked a child, but it crashed without sending
439 // a message to the browser, the browser won't have found its PID.
440 if (real_pid < 0) {
441 KillAndReap(pid, helper);
442 return -1;
445 // If we're not using a helper, send the PID back to the child process.
446 if (!helper) {
447 ssize_t written =
448 HANDLE_EINTR(write(write_pipe.get(), &real_pid, sizeof(real_pid)));
449 if (written != sizeof(real_pid)) {
450 KillAndReap(pid, helper);
451 return -1;
455 // Now set-up this process to be tracked by the Zygote.
456 if (process_info_map_.find(real_pid) != process_info_map_.end()) {
457 LOG(ERROR) << "Already tracking PID " << real_pid;
458 NOTREACHED();
460 process_info_map_[real_pid].internal_pid = pid;
461 process_info_map_[real_pid].started_from_helper = helper;
463 return real_pid;
466 base::ProcessId Zygote::ReadArgsAndFork(PickleIterator iter,
467 ScopedVector<base::ScopedFD> fds,
468 std::string* uma_name,
469 int* uma_sample,
470 int* uma_boundary_value) {
471 std::vector<std::string> args;
472 int argc = 0;
473 int numfds = 0;
474 base::GlobalDescriptors::Mapping mapping;
475 std::string process_type;
476 std::string channel_id;
477 const std::string channel_id_prefix = std::string("--")
478 + switches::kProcessChannelID + std::string("=");
480 if (!iter.ReadString(&process_type))
481 return -1;
482 if (!iter.ReadInt(&argc))
483 return -1;
485 for (int i = 0; i < argc; ++i) {
486 std::string arg;
487 if (!iter.ReadString(&arg))
488 return -1;
489 args.push_back(arg);
490 if (arg.compare(0, channel_id_prefix.length(), channel_id_prefix) == 0)
491 channel_id = arg.substr(channel_id_prefix.length());
494 if (!iter.ReadInt(&numfds))
495 return -1;
496 if (numfds != static_cast<int>(fds.size()))
497 return -1;
499 // First FD is the PID oracle socket.
500 if (fds.size() < 1)
501 return -1;
502 base::ScopedFD pid_oracle(fds[0]->Pass());
504 // Remaining FDs are for the global descriptor mapping.
505 for (int i = 1; i < numfds; ++i) {
506 base::GlobalDescriptors::Key key;
507 if (!iter.ReadUInt32(&key))
508 return -1;
509 mapping.push_back(base::GlobalDescriptors::Descriptor(key, fds[i]->get()));
512 mapping.push_back(base::GlobalDescriptors::Descriptor(
513 static_cast<uint32_t>(kSandboxIPCChannel), GetSandboxFD()));
515 // Returns twice, once per process.
516 base::ProcessId child_pid = ForkWithRealPid(process_type,
517 mapping,
518 channel_id,
519 pid_oracle.Pass(),
520 uma_name,
521 uma_sample,
522 uma_boundary_value);
523 if (!child_pid) {
524 // This is the child process.
526 // Our socket from the browser.
527 PCHECK(0 == IGNORE_EINTR(close(kZygoteSocketPairFd)));
529 // Pass ownership of file descriptors from fds to GlobalDescriptors.
530 for (ScopedVector<base::ScopedFD>::iterator i = fds.begin(); i != fds.end();
531 ++i)
532 ignore_result((*i)->release());
533 base::GlobalDescriptors::GetInstance()->Reset(mapping);
535 // Reset the process-wide command line to our new command line.
536 base::CommandLine::Reset();
537 base::CommandLine::Init(0, NULL);
538 base::CommandLine::ForCurrentProcess()->InitFromArgv(args);
540 // Update the process title. The argv was already cached by the call to
541 // SetProcessTitleFromCommandLine in ChromeMain, so we can pass NULL here
542 // (we don't have the original argv at this point).
543 SetProcessTitleFromCommandLine(NULL);
544 } else if (child_pid < 0) {
545 LOG(ERROR) << "Zygote could not fork: process_type " << process_type
546 << " numfds " << numfds << " child_pid " << child_pid;
548 return child_pid;
551 bool Zygote::HandleForkRequest(int fd,
552 PickleIterator iter,
553 ScopedVector<base::ScopedFD> fds) {
554 std::string uma_name;
555 int uma_sample;
556 int uma_boundary_value;
557 base::ProcessId child_pid = ReadArgsAndFork(
558 iter, fds.Pass(), &uma_name, &uma_sample, &uma_boundary_value);
559 if (child_pid == 0)
560 return true;
561 // If there's no UMA report for this particular fork, then check if any
562 // helpers have an initial UMA report for us to send instead.
563 while (uma_name.empty() && initial_uma_index_ < helpers_.size()) {
564 helpers_[initial_uma_index_++]->InitialUMA(
565 &uma_name, &uma_sample, &uma_boundary_value);
567 // Must always send reply, as ZygoteHost blocks while waiting for it.
568 Pickle reply_pickle;
569 reply_pickle.WriteInt(child_pid);
570 reply_pickle.WriteString(uma_name);
571 if (!uma_name.empty()) {
572 reply_pickle.WriteInt(uma_sample);
573 reply_pickle.WriteInt(uma_boundary_value);
575 if (HANDLE_EINTR(write(fd, reply_pickle.data(), reply_pickle.size())) !=
576 static_cast<ssize_t> (reply_pickle.size()))
577 PLOG(ERROR) << "write";
578 return false;
581 bool Zygote::HandleGetSandboxStatus(int fd,
582 PickleIterator iter) {
583 if (HANDLE_EINTR(write(fd, &sandbox_flags_, sizeof(sandbox_flags_))) !=
584 sizeof(sandbox_flags_)) {
585 PLOG(ERROR) << "write";
588 return false;
591 } // namespace content