OLD | NEW |
(Empty) | |
| 1 // Copyright 2015 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 "content/browser/zygote_host/zygote_communication_linux.h" |
| 6 |
| 7 #include <string.h> |
| 8 #include <sys/socket.h> |
| 9 |
| 10 #include "base/base_switches.h" |
| 11 #include "base/logging.h" |
| 12 #include "base/metrics/histogram.h" |
| 13 #include "base/metrics/sparse_histogram.h" |
| 14 #include "base/path_service.h" |
| 15 #include "base/pickle.h" |
| 16 #include "base/posix/eintr_wrapper.h" |
| 17 #include "base/posix/unix_domain_socket_linux.h" |
| 18 #include "content/browser/renderer_host/render_sandbox_host_linux.h" |
| 19 #include "content/browser/zygote_host/zygote_host_impl_linux.h" |
| 20 #include "content/common/child_process_sandbox_support_impl_linux.h" |
| 21 #include "content/common/zygote_commands_linux.h" |
| 22 #include "content/public/browser/content_browser_client.h" |
| 23 #include "content/public/common/content_switches.h" |
| 24 #include "content/public/common/result_codes.h" |
| 25 #include "sandbox/linux/services/credentials.h" |
| 26 #include "sandbox/linux/services/namespace_sandbox.h" |
| 27 #include "sandbox/linux/suid/client/setuid_sandbox_host.h" |
| 28 #include "ui/gfx/switches.h" |
| 29 |
| 30 namespace content { |
| 31 |
| 32 namespace { |
| 33 |
| 34 // Receive a fixed message on fd and return the sender's PID. |
| 35 // Returns true if the message received matches the expected message. |
| 36 bool ReceiveFixedMessage(int fd, |
| 37 const char* expect_msg, |
| 38 size_t expect_len, |
| 39 base::ProcessId* sender_pid) { |
| 40 char buf[expect_len + 1]; |
| 41 std::vector<base::ScopedFD> fds_vec; |
| 42 |
| 43 const ssize_t len = base::UnixDomainSocket::RecvMsgWithPid( |
| 44 fd, buf, sizeof(buf), &fds_vec, sender_pid); |
| 45 if (static_cast<size_t>(len) != expect_len) |
| 46 return false; |
| 47 if (memcmp(buf, expect_msg, expect_len) != 0) |
| 48 return false; |
| 49 if (!fds_vec.empty()) |
| 50 return false; |
| 51 return true; |
| 52 } |
| 53 |
| 54 } // namespace |
| 55 |
| 56 ZygoteCommunication::ZygoteCommunication() |
| 57 : control_fd_(-1), |
| 58 control_lock_(), |
| 59 pid_(), |
| 60 list_of_running_zygote_children_(), |
| 61 child_tracking_lock_(), |
| 62 sandbox_status_(0), |
| 63 have_read_sandbox_status_word_(false), |
| 64 use_suid_sandbox_for_adj_oom_score_(false), |
| 65 init_(false) {} |
| 66 |
| 67 ZygoteCommunication::~ZygoteCommunication() {} |
| 68 |
| 69 bool ZygoteCommunication::SendMessage(const base::Pickle& data, |
| 70 const std::vector<int>* fds) { |
| 71 DCHECK_NE(-1, control_fd_); |
| 72 CHECK(data.size() <= kZygoteMaxMessageLength) |
| 73 << "Trying to send too-large message to zygote (sending " << data.size() |
| 74 << " bytes, max is " << kZygoteMaxMessageLength << ")"; |
| 75 CHECK(!fds || fds->size() <= base::UnixDomainSocket::kMaxFileDescriptors) |
| 76 << "Trying to send message with too many file descriptors to zygote " |
| 77 << "(sending " << fds->size() << ", max is " |
| 78 << base::UnixDomainSocket::kMaxFileDescriptors << ")"; |
| 79 |
| 80 return base::UnixDomainSocket::SendMsg(control_fd_, data.data(), data.size(), |
| 81 fds ? *fds : std::vector<int>()); |
| 82 } |
| 83 |
| 84 ssize_t ZygoteCommunication::ReadSandboxStatus() { |
| 85 DCHECK_NE(-1, control_fd_); |
| 86 // At startup we send a kZygoteCommandGetSandboxStatus request to the zygote, |
| 87 // but don't wait for the reply. Thus, the first time that we read from the |
| 88 // zygote, we get the reply to that request. |
| 89 ssize_t bytes_read = HANDLE_EINTR( |
| 90 read(control_fd_, &sandbox_status_, sizeof(sandbox_status_))); |
| 91 if (bytes_read != sizeof(sandbox_status_)) { |
| 92 return -1; |
| 93 } |
| 94 return bytes_read; |
| 95 } |
| 96 |
| 97 ssize_t ZygoteCommunication::ReadReply(void* buf, size_t buf_len) { |
| 98 DCHECK_NE(-1, control_fd_); |
| 99 if (!have_read_sandbox_status_word_) { |
| 100 if (ReadSandboxStatus() == -1) { |
| 101 return -1; |
| 102 } |
| 103 have_read_sandbox_status_word_ = true; |
| 104 UMA_HISTOGRAM_SPARSE_SLOWLY("Linux.SandboxStatus", sandbox_status_); |
| 105 } |
| 106 |
| 107 return HANDLE_EINTR(read(control_fd_, buf, buf_len)); |
| 108 } |
| 109 |
| 110 pid_t ZygoteCommunication::ForkRequest(const std::vector<std::string>& argv, |
| 111 scoped_ptr<FileDescriptorInfo> mapping, |
| 112 const std::string& process_type) { |
| 113 DCHECK(init_); |
| 114 |
| 115 base::Pickle pickle; |
| 116 int raw_socks[2]; |
| 117 PCHECK(0 == socketpair(AF_UNIX, SOCK_SEQPACKET, 0, raw_socks)); |
| 118 base::ScopedFD my_sock(raw_socks[0]); |
| 119 base::ScopedFD peer_sock(raw_socks[1]); |
| 120 CHECK(base::UnixDomainSocket::EnableReceiveProcessId(my_sock.get())); |
| 121 |
| 122 pickle.WriteInt(kZygoteCommandFork); |
| 123 pickle.WriteString(process_type); |
| 124 pickle.WriteInt(argv.size()); |
| 125 for (std::vector<std::string>::const_iterator i = argv.begin(); |
| 126 i != argv.end(); ++i) |
| 127 pickle.WriteString(*i); |
| 128 |
| 129 // Fork requests contain one file descriptor for the PID oracle, and one |
| 130 // more for each file descriptor mapping for the child process. |
| 131 const size_t num_fds_to_send = 1 + mapping->GetMappingSize(); |
| 132 pickle.WriteInt(num_fds_to_send); |
| 133 |
| 134 std::vector<int> fds; |
| 135 |
| 136 // First FD to send is peer_sock. |
| 137 // TODO(morrita): Ideally, this should be part of the mapping so that |
| 138 // FileDescriptorInfo can manages its lifetime. |
| 139 fds.push_back(peer_sock.get()); |
| 140 |
| 141 // The rest come from mapping. |
| 142 for (size_t i = 0; i < mapping->GetMappingSize(); ++i) { |
| 143 pickle.WriteUInt32(mapping->GetIDAt(i)); |
| 144 fds.push_back(mapping->GetFDAt(i)); |
| 145 } |
| 146 |
| 147 // Sanity check that we've populated |fds| correctly. |
| 148 DCHECK_EQ(num_fds_to_send, fds.size()); |
| 149 |
| 150 pid_t pid; |
| 151 { |
| 152 base::AutoLock lock(control_lock_); |
| 153 if (!SendMessage(pickle, &fds)) |
| 154 return base::kNullProcessHandle; |
| 155 mapping.reset(); |
| 156 peer_sock.reset(); |
| 157 |
| 158 { |
| 159 char buf[sizeof(kZygoteChildPingMessage) + 1]; |
| 160 std::vector<base::ScopedFD> recv_fds; |
| 161 base::ProcessId real_pid; |
| 162 |
| 163 ssize_t n = base::UnixDomainSocket::RecvMsgWithPid( |
| 164 my_sock.get(), buf, sizeof(buf), &recv_fds, &real_pid); |
| 165 if (n != sizeof(kZygoteChildPingMessage) || |
| 166 0 != memcmp(buf, kZygoteChildPingMessage, |
| 167 sizeof(kZygoteChildPingMessage))) { |
| 168 // Zygote children should still be trustworthy when they're supposed to |
| 169 // ping us, so something's broken if we don't receive a valid ping. |
| 170 LOG(ERROR) << "Did not receive ping from zygote child"; |
| 171 NOTREACHED(); |
| 172 real_pid = -1; |
| 173 } |
| 174 my_sock.reset(); |
| 175 |
| 176 // Always send PID back to zygote. |
| 177 base::Pickle pid_pickle; |
| 178 pid_pickle.WriteInt(kZygoteCommandForkRealPID); |
| 179 pid_pickle.WriteInt(real_pid); |
| 180 if (!SendMessage(pid_pickle, NULL)) |
| 181 return base::kNullProcessHandle; |
| 182 } |
| 183 |
| 184 // Read the reply, which pickles the PID and an optional UMA enumeration. |
| 185 static const unsigned kMaxReplyLength = 2048; |
| 186 char buf[kMaxReplyLength]; |
| 187 const ssize_t len = ReadReply(buf, sizeof(buf)); |
| 188 |
| 189 base::Pickle reply_pickle(buf, len); |
| 190 base::PickleIterator iter(reply_pickle); |
| 191 if (len <= 0 || !iter.ReadInt(&pid)) |
| 192 return base::kNullProcessHandle; |
| 193 |
| 194 // If there is a nonempty UMA name string, then there is a UMA |
| 195 // enumeration to record. |
| 196 std::string uma_name; |
| 197 int uma_sample; |
| 198 int uma_boundary_value; |
| 199 if (iter.ReadString(&uma_name) && !uma_name.empty() && |
| 200 iter.ReadInt(&uma_sample) && iter.ReadInt(&uma_boundary_value)) { |
| 201 // We cannot use the UMA_HISTOGRAM_ENUMERATION macro here, |
| 202 // because that's only for when the name is the same every time. |
| 203 // Here we're using whatever name we got from the other side. |
| 204 // But since it's likely that the same one will be used repeatedly |
| 205 // (even though it's not guaranteed), we cache it here. |
| 206 static base::HistogramBase* uma_histogram; |
| 207 if (!uma_histogram || uma_histogram->histogram_name() != uma_name) { |
| 208 uma_histogram = base::LinearHistogram::FactoryGet( |
| 209 uma_name, 1, uma_boundary_value, uma_boundary_value + 1, |
| 210 base::HistogramBase::kUmaTargetedHistogramFlag); |
| 211 } |
| 212 uma_histogram->Add(uma_sample); |
| 213 } |
| 214 |
| 215 if (pid <= 0) |
| 216 return base::kNullProcessHandle; |
| 217 } |
| 218 |
| 219 #if !defined(OS_OPENBSD) |
| 220 // This is just a starting score for a renderer or extension (the |
| 221 // only types of processes that will be started this way). It will |
| 222 // get adjusted as time goes on. (This is the same value as |
| 223 // chrome::kLowestRendererOomScore in chrome/chrome_constants.h, but |
| 224 // that's not something we can include here.) |
| 225 const int kLowestRendererOomScore = 300; |
| 226 ZygoteHostImpl::GetInstance()->AdjustRendererOOMScore( |
| 227 pid, kLowestRendererOomScore); |
| 228 #endif |
| 229 |
| 230 ZygoteChildBorn(pid); |
| 231 return pid; |
| 232 } |
| 233 |
| 234 void ZygoteCommunication::EnsureProcessTerminated(pid_t process) { |
| 235 DCHECK(init_); |
| 236 base::Pickle pickle; |
| 237 |
| 238 pickle.WriteInt(kZygoteCommandReap); |
| 239 pickle.WriteInt(process); |
| 240 if (!SendMessage(pickle, NULL)) |
| 241 LOG(ERROR) << "Failed to send Reap message to zygote"; |
| 242 ZygoteChildDied(process); |
| 243 } |
| 244 |
| 245 void ZygoteCommunication::ZygoteChildBorn(pid_t process) { |
| 246 base::AutoLock lock(child_tracking_lock_); |
| 247 bool new_element_inserted = |
| 248 list_of_running_zygote_children_.insert(process).second; |
| 249 DCHECK(new_element_inserted); |
| 250 } |
| 251 |
| 252 void ZygoteCommunication::ZygoteChildDied(pid_t process) { |
| 253 base::AutoLock lock(child_tracking_lock_); |
| 254 size_t num_erased = list_of_running_zygote_children_.erase(process); |
| 255 DCHECK_EQ(1U, num_erased); |
| 256 } |
| 257 |
| 258 void ZygoteCommunication::Init() { |
| 259 CHECK(!init_); |
| 260 |
| 261 base::FilePath chrome_path; |
| 262 CHECK(PathService::Get(base::FILE_EXE, &chrome_path)); |
| 263 base::CommandLine cmd_line(chrome_path); |
| 264 |
| 265 cmd_line.AppendSwitchASCII(switches::kProcessType, switches::kZygoteProcess); |
| 266 |
| 267 int fds[2]; |
| 268 CHECK(socketpair(AF_UNIX, SOCK_SEQPACKET, 0, fds) == 0); |
| 269 CHECK(base::UnixDomainSocket::EnableReceiveProcessId(fds[0])); |
| 270 base::FileHandleMappingVector fds_to_map; |
| 271 fds_to_map.push_back(std::make_pair(fds[1], kZygoteSocketPairFd)); |
| 272 |
| 273 base::LaunchOptions options; |
| 274 const base::CommandLine& browser_command_line = |
| 275 *base::CommandLine::ForCurrentProcess(); |
| 276 if (browser_command_line.HasSwitch(switches::kZygoteCmdPrefix)) { |
| 277 cmd_line.PrependWrapper( |
| 278 browser_command_line.GetSwitchValueNative(switches::kZygoteCmdPrefix)); |
| 279 } |
| 280 // Append any switches from the browser process that need to be forwarded on |
| 281 // to the zygote/renderers. |
| 282 // Should this list be obtained from browser_render_process_host.cc? |
| 283 static const char* kForwardSwitches[] = { |
| 284 switches::kAllowSandboxDebugging, switches::kDisableSeccompFilterSandbox, |
| 285 switches::kEnableHeapProfiling, |
| 286 switches::kEnableLogging, // Support, e.g., --enable-logging=stderr. |
| 287 // Zygote process needs to know what resources to have loaded when it |
| 288 // becomes a renderer process. |
| 289 switches::kForceDeviceScaleFactor, switches::kLoggingLevel, |
| 290 switches::kNoSandbox, switches::kPpapiInProcess, |
| 291 switches::kRegisterPepperPlugins, switches::kV, switches::kVModule, |
| 292 }; |
| 293 cmd_line.CopySwitchesFrom(browser_command_line, kForwardSwitches, |
| 294 arraysize(kForwardSwitches)); |
| 295 |
| 296 GetContentClient()->browser()->AppendExtraCommandLineSwitches(&cmd_line, -1); |
| 297 |
| 298 const bool using_namespace_sandbox = ShouldUseNamespaceSandbox(); |
| 299 // A non empty sandbox_cmd means we want a SUID sandbox. |
| 300 const bool using_suid_sandbox = |
| 301 !ZygoteHostImpl::GetInstance()->SandboxCommand().empty() && |
| 302 !using_namespace_sandbox; |
| 303 // Use the SUID sandbox for adjusting OOM scores when we are using the setuid |
| 304 // or namespace sandbox. This is needed beacuse the processes are |
| 305 // non-dumpable, so /proc/pid/oom_score_adj can only be written by root. |
| 306 use_suid_sandbox_for_adj_oom_score_ = |
| 307 !ZygoteHostImpl::GetInstance()->SandboxCommand().empty() && |
| 308 using_suid_sandbox; |
| 309 |
| 310 // Start up the sandbox host process and get the file descriptor for the |
| 311 // renderers to talk to it. |
| 312 const int sfd = RenderSandboxHostLinux::GetInstance()->GetRendererSocket(); |
| 313 fds_to_map.push_back(std::make_pair(sfd, GetSandboxFD())); |
| 314 |
| 315 base::ScopedFD dummy_fd; |
| 316 if (using_suid_sandbox) { |
| 317 scoped_ptr<sandbox::SetuidSandboxHost> sandbox_host( |
| 318 sandbox::SetuidSandboxHost::Create()); |
| 319 sandbox_host->PrependWrapper(&cmd_line); |
| 320 sandbox_host->SetupLaunchOptions(&options, &fds_to_map, &dummy_fd); |
| 321 sandbox_host->SetupLaunchEnvironment(); |
| 322 } |
| 323 |
| 324 options.fds_to_remap = &fds_to_map; |
| 325 base::Process process = |
| 326 using_namespace_sandbox |
| 327 ? sandbox::NamespaceSandbox::LaunchProcess(cmd_line, options) |
| 328 : base::LaunchProcess(cmd_line, options); |
| 329 CHECK(process.IsValid()) << "Failed to launch zygote process"; |
| 330 |
| 331 dummy_fd.reset(); |
| 332 |
| 333 if (using_suid_sandbox || using_namespace_sandbox) { |
| 334 // The SUID sandbox will execute the zygote in a new PID namespace, and |
| 335 // the main zygote process will then fork from there. Watch now our |
| 336 // elaborate dance to find and validate the zygote's PID. |
| 337 |
| 338 // First we receive a message from the zygote boot process. |
| 339 base::ProcessId boot_pid; |
| 340 CHECK(ReceiveFixedMessage(fds[0], kZygoteBootMessage, |
| 341 sizeof(kZygoteBootMessage), &boot_pid)); |
| 342 |
| 343 // Within the PID namespace, the zygote boot process thinks it's PID 1, |
| 344 // but its real PID can never be 1. This gives us a reliable test that |
| 345 // the kernel is translating the sender's PID to our namespace. |
| 346 CHECK_GT(boot_pid, 1) |
| 347 << "Received invalid process ID for zygote; kernel might be too old? " |
| 348 "See crbug.com/357670 or try using --" |
| 349 << switches::kDisableSetuidSandbox << " to workaround."; |
| 350 |
| 351 // Now receive the message that the zygote's ready to go, along with the |
| 352 // main zygote process's ID. |
| 353 CHECK(ReceiveFixedMessage(fds[0], kZygoteHelloMessage, |
| 354 sizeof(kZygoteHelloMessage), &pid_)); |
| 355 CHECK_GT(pid_, 1); |
| 356 |
| 357 if (process.Pid() != pid_) { |
| 358 // Reap the sandbox. |
| 359 base::EnsureProcessGetsReaped(process.Pid()); |
| 360 } |
| 361 } else { |
| 362 // Not using the SUID sandbox. |
| 363 // Note that ~base::Process() will reset the internal value, but there's no |
| 364 // real "handle" on POSIX so that is safe. |
| 365 pid_ = process.Pid(); |
| 366 } |
| 367 |
| 368 close(fds[1]); |
| 369 control_fd_ = fds[0]; |
| 370 |
| 371 ZygoteHostImpl::GetInstance()->AddZygotePid(pid_); |
| 372 |
| 373 base::Pickle pickle; |
| 374 pickle.WriteInt(kZygoteCommandGetSandboxStatus); |
| 375 if (!SendMessage(pickle, NULL)) |
| 376 LOG(FATAL) << "Cannot communicate with zygote"; |
| 377 |
| 378 init_ = true; |
| 379 } |
| 380 |
| 381 base::TerminationStatus ZygoteCommunication::GetTerminationStatus( |
| 382 base::ProcessHandle handle, |
| 383 bool known_dead, |
| 384 int* exit_code) { |
| 385 DCHECK(init_); |
| 386 base::Pickle pickle; |
| 387 pickle.WriteInt(kZygoteCommandGetTerminationStatus); |
| 388 pickle.WriteBool(known_dead); |
| 389 pickle.WriteInt(handle); |
| 390 |
| 391 static const unsigned kMaxMessageLength = 128; |
| 392 char buf[kMaxMessageLength]; |
| 393 ssize_t len; |
| 394 { |
| 395 base::AutoLock lock(control_lock_); |
| 396 if (!SendMessage(pickle, NULL)) |
| 397 LOG(ERROR) << "Failed to send GetTerminationStatus message to zygote"; |
| 398 len = ReadReply(buf, sizeof(buf)); |
| 399 } |
| 400 |
| 401 // Set this now to handle the error cases. |
| 402 if (exit_code) |
| 403 *exit_code = RESULT_CODE_NORMAL_EXIT; |
| 404 int status = base::TERMINATION_STATUS_NORMAL_TERMINATION; |
| 405 |
| 406 if (len == -1) { |
| 407 LOG(WARNING) << "Error reading message from zygote: " << errno; |
| 408 } else if (len == 0) { |
| 409 LOG(WARNING) << "Socket closed prematurely."; |
| 410 } else { |
| 411 base::Pickle read_pickle(buf, len); |
| 412 int tmp_status, tmp_exit_code; |
| 413 base::PickleIterator iter(read_pickle); |
| 414 if (!iter.ReadInt(&tmp_status) || !iter.ReadInt(&tmp_exit_code)) { |
| 415 LOG(WARNING) |
| 416 << "Error parsing GetTerminationStatus response from zygote."; |
| 417 } else { |
| 418 if (exit_code) |
| 419 *exit_code = tmp_exit_code; |
| 420 status = tmp_status; |
| 421 } |
| 422 } |
| 423 |
| 424 if (status != base::TERMINATION_STATUS_STILL_RUNNING) { |
| 425 ZygoteChildDied(handle); |
| 426 } |
| 427 return static_cast<base::TerminationStatus>(status); |
| 428 } |
| 429 |
| 430 bool ZygoteCommunication::ShouldUseNamespaceSandbox() { |
| 431 const base::CommandLine& command_line = |
| 432 *base::CommandLine::ForCurrentProcess(); |
| 433 if (command_line.HasSwitch(switches::kNoSandbox)) { |
| 434 return false; |
| 435 } |
| 436 |
| 437 if (command_line.HasSwitch(switches::kDisableNamespaceSandbox)) { |
| 438 return false; |
| 439 } |
| 440 |
| 441 if (!sandbox::Credentials::CanCreateProcessInNewUserNS()) { |
| 442 return false; |
| 443 } |
| 444 |
| 445 return true; |
| 446 } |
| 447 |
| 448 int ZygoteCommunication::GetSandboxStatus() { |
| 449 if (have_read_sandbox_status_word_) { |
| 450 return sandbox_status_; |
| 451 } |
| 452 if (ReadSandboxStatus() == -1) { |
| 453 return 0; |
| 454 } |
| 455 have_read_sandbox_status_word_ = true; |
| 456 UMA_HISTOGRAM_SPARSE_SLOWLY("Linux.SandboxStatus", sandbox_status_); |
| 457 return sandbox_status_; |
| 458 } |
| 459 |
| 460 } // namespace content |
OLD | NEW |