1 // Copyright (c) 2011 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/browser/zygote_host_linux.h"
7 #include <sys/socket.h>
12 #include "base/base_switches.h"
13 #include "base/command_line.h"
14 #include "base/eintr_wrapper.h"
15 #include "base/environment.h"
16 #include "base/file_util.h"
17 #include "base/linux_util.h"
18 #include "base/logging.h"
19 #include "base/memory/scoped_ptr.h"
20 #include "base/metrics/histogram.h"
21 #include "base/path_service.h"
22 #include "base/pickle.h"
23 #include "base/process_util.h"
24 #include "base/string_number_conversions.h"
25 #include "base/string_util.h"
26 #include "base/time.h"
27 #include "base/utf_string_conversions.h"
28 #include "content/browser/renderer_host/render_sandbox_host_linux.h"
29 #include "content/common/process_watcher.h"
30 #include "content/common/result_codes.h"
31 #include "content/common/unix_domain_socket_posix.h"
32 #include "content/public/browser/content_browser_client.h"
33 #include "content/public/common/content_switches.h"
34 #include "sandbox/linux/suid/suid_unsafe_environment_variables.h"
36 #if defined(USE_TCMALLOC)
37 #include "third_party/tcmalloc/chromium/src/google/heap-profiler.h"
40 static void SaveSUIDUnsafeEnvironmentVariables() {
41 // The ELF loader will clear many environment variables so we save them to
42 // different names here so that the SUID sandbox can resolve them for the
45 for (unsigned i
= 0; kSUIDUnsafeEnvironmentVariables
[i
]; ++i
) {
46 const char* const envvar
= kSUIDUnsafeEnvironmentVariables
[i
];
47 char* const saved_envvar
= SandboxSavedEnvironmentVariable(envvar
);
51 scoped_ptr
<base::Environment
> env(base::Environment::Create());
53 if (env
->GetVar(envvar
, &value
))
54 env
->SetVar(saved_envvar
, value
);
56 env
->UnSetVar(saved_envvar
);
62 ZygoteHost::ZygoteHost()
66 using_suid_sandbox_(false),
67 have_read_sandbox_status_word_(false),
70 ZygoteHost::~ZygoteHost() {
76 ZygoteHost
* ZygoteHost::GetInstance() {
77 return Singleton
<ZygoteHost
>::get();
80 void ZygoteHost::Init(const std::string
& sandbox_cmd
) {
85 CHECK(PathService::Get(base::FILE_EXE
, &chrome_path
));
86 CommandLine
cmd_line(chrome_path
);
88 cmd_line
.AppendSwitchASCII(switches::kProcessType
, switches::kZygoteProcess
);
91 #if defined(OS_FREEBSD) || defined(OS_OPENBSD)
92 // The BSDs often don't support SOCK_SEQPACKET yet, so fall back to
93 // SOCK_DGRAM if necessary.
94 if (socketpair(PF_UNIX
, SOCK_SEQPACKET
, 0, fds
) != 0)
95 CHECK(socketpair(PF_UNIX
, SOCK_DGRAM
, 0, fds
) == 0);
97 CHECK(socketpair(PF_UNIX
, SOCK_SEQPACKET
, 0, fds
) == 0);
99 base::file_handle_mapping_vector fds_to_map
;
100 fds_to_map
.push_back(std::make_pair(fds
[1], 3));
102 const CommandLine
& browser_command_line
= *CommandLine::ForCurrentProcess();
103 if (browser_command_line
.HasSwitch(switches::kZygoteCmdPrefix
)) {
104 cmd_line
.PrependWrapper(
105 browser_command_line
.GetSwitchValueNative(switches::kZygoteCmdPrefix
));
107 // Append any switches from the browser process that need to be forwarded on
108 // to the zygote/renderers.
109 // Should this list be obtained from browser_render_process_host.cc?
110 static const char* kForwardSwitches
[] = {
111 switches::kAllowSandboxDebugging
,
112 switches::kLoggingLevel
,
113 switches::kEnableLogging
, // Support, e.g., --enable-logging=stderr.
116 switches::kRegisterPepperPlugins
,
117 switches::kDisableSeccompSandbox
,
118 switches::kEnableSeccompSandbox
,
120 cmd_line
.CopySwitchesFrom(browser_command_line
, kForwardSwitches
,
121 arraysize(kForwardSwitches
));
123 content::GetContentClient()->browser()->AppendExtraCommandLineSwitches(
126 sandbox_binary_
= sandbox_cmd
.c_str();
128 if (!sandbox_cmd
.empty()) {
130 if (stat(sandbox_binary_
.c_str(), &st
) != 0) {
131 LOG(FATAL
) << "The SUID sandbox helper binary is missing: "
132 << sandbox_binary_
<< " Aborting now.";
135 if (access(sandbox_binary_
.c_str(), X_OK
) == 0 &&
137 (st
.st_mode
& S_ISUID
) &&
138 (st
.st_mode
& S_IXOTH
)) {
139 using_suid_sandbox_
= true;
140 cmd_line
.PrependWrapper(sandbox_binary_
);
142 SaveSUIDUnsafeEnvironmentVariables();
144 LOG(FATAL
) << "The SUID sandbox helper binary was found, but is not "
145 "configured correctly. Rather than run without sandboxing "
146 "I'm aborting now. You need to make sure that "
147 << sandbox_binary_
<< " is owned by root and has mode 4755.";
150 LOG(WARNING
) << "Running without the SUID sandbox! See "
151 "http://code.google.com/p/chromium/wiki/LinuxSUIDSandboxDevelopment "
152 "for more information on developing with the sandbox on.";
155 // Start up the sandbox host process and get the file descriptor for the
156 // renderers to talk to it.
157 const int sfd
= RenderSandboxHostLinux::GetInstance()->GetRendererSocket();
158 fds_to_map
.push_back(std::make_pair(sfd
, 5));
161 if (using_suid_sandbox_
) {
162 dummy_fd
= socket(PF_UNIX
, SOCK_DGRAM
, 0);
163 CHECK(dummy_fd
>= 0);
164 fds_to_map
.push_back(std::make_pair(dummy_fd
, 7));
167 base::ProcessHandle process
= -1;
168 base::LaunchOptions options
;
169 options
.fds_to_remap
= &fds_to_map
;
170 base::LaunchProcess(cmd_line
.argv(), options
, &process
);
171 CHECK(process
!= -1) << "Failed to launch zygote process";
173 if (using_suid_sandbox_
) {
174 // In the SUID sandbox, the real zygote is forked from the sandbox.
175 // We need to look for it.
176 // But first, wait for the zygote to tell us it's running.
177 // The sending code is in content/browser/zygote_main_linux.cc.
178 std::vector
<int> fds_vec
;
179 const int kExpectedLength
= sizeof(kZygoteMagic
);
180 char buf
[kExpectedLength
];
181 const ssize_t len
= UnixDomainSocket::RecvMsg(fds
[0], buf
, sizeof(buf
),
183 CHECK(len
== kExpectedLength
) << "Incorrect zygote magic length";
184 CHECK(0 == strcmp(buf
, kZygoteMagic
)) << "Incorrect zygote magic";
186 std::string inode_output
;
188 // Figure out the inode for |dummy_fd|, close |dummy_fd| on our end,
189 // and find the zygote process holding |dummy_fd|.
190 if (base::FileDescriptorGetInode(&inode
, dummy_fd
)) {
192 std::vector
<std::string
> get_inode_cmdline
;
193 get_inode_cmdline
.push_back(sandbox_binary_
);
194 get_inode_cmdline
.push_back(base::kFindInodeSwitch
);
195 get_inode_cmdline
.push_back(base::Int64ToString(inode
));
196 CommandLine
get_inode_cmd(get_inode_cmdline
);
197 if (base::GetAppOutput(get_inode_cmd
, &inode_output
)) {
198 base::StringToInt(inode_output
, &pid_
);
201 CHECK(pid_
> 0) << "Did not find zygote process (using sandbox binary "
202 << sandbox_binary_
<< ")";
204 if (process
!= pid_
) {
206 ProcessWatcher::EnsureProcessGetsReaped(process
);
209 // Not using the SUID sandbox.
214 control_fd_
= fds
[0];
217 pickle
.WriteInt(kCmdGetSandboxStatus
);
218 std::vector
<int> empty_fds
;
219 if (!UnixDomainSocket::SendMsg(control_fd_
, pickle
.data(), pickle
.size(),
221 LOG(FATAL
) << "Cannot communicate with zygote";
222 // We don't wait for the reply. We'll read it in ReadReply.
225 ssize_t
ZygoteHost::ReadReply(void* buf
, size_t buf_len
) {
226 // At startup we send a kCmdGetSandboxStatus request to the zygote, but don't
227 // wait for the reply. Thus, the first time that we read from the zygote, we
228 // get the reply to that request.
229 if (!have_read_sandbox_status_word_
) {
230 if (HANDLE_EINTR(read(control_fd_
, &sandbox_status_
,
231 sizeof(sandbox_status_
))) !=
232 sizeof(sandbox_status_
)) {
235 have_read_sandbox_status_word_
= true;
238 return HANDLE_EINTR(read(control_fd_
, buf
, buf_len
));
241 pid_t
ZygoteHost::ForkRequest(
242 const std::vector
<std::string
>& argv
,
243 const base::GlobalDescriptors::Mapping
& mapping
,
244 const std::string
& process_type
) {
248 pickle
.WriteInt(kCmdFork
);
249 pickle
.WriteString(process_type
);
250 pickle
.WriteInt(argv
.size());
251 for (std::vector
<std::string
>::const_iterator
252 i
= argv
.begin(); i
!= argv
.end(); ++i
)
253 pickle
.WriteString(*i
);
255 pickle
.WriteInt(mapping
.size());
257 std::vector
<int> fds
;
258 for (base::GlobalDescriptors::Mapping::const_iterator
259 i
= mapping
.begin(); i
!= mapping
.end(); ++i
) {
260 pickle
.WriteUInt32(i
->first
);
261 fds
.push_back(i
->second
);
266 base::AutoLock
lock(control_lock_
);
267 if (!UnixDomainSocket::SendMsg(control_fd_
, pickle
.data(), pickle
.size(),
269 return base::kNullProcessHandle
;
271 // Read the reply, which pickles the PID and an optional UMA enumeration.
272 static const unsigned kMaxReplyLength
= 2048;
273 char buf
[kMaxReplyLength
];
274 const ssize_t len
= ReadReply(buf
, sizeof(buf
));
276 Pickle
reply_pickle(buf
, len
);
278 if (len
<= 0 || !reply_pickle
.ReadInt(&iter
, &pid
))
279 return base::kNullProcessHandle
;
281 // If there is a nonempty UMA name string, then there is a UMA
282 // enumeration to record.
283 std::string uma_name
;
285 int uma_boundary_value
;
286 if (reply_pickle
.ReadString(&iter
, &uma_name
) &&
288 reply_pickle
.ReadInt(&iter
, &uma_sample
) &&
289 reply_pickle
.ReadInt(&iter
, &uma_boundary_value
)) {
290 // We cannot use the UMA_HISTOGRAM_ENUMERATION macro here,
291 // because that's only for when the name is the same every time.
292 // Here we're using whatever name we got from the other side.
293 // But since it's likely that the same one will be used repeatedly
294 // (even though it's not guaranteed), we cache it here.
295 static base::Histogram
* uma_histogram
;
296 if (!uma_histogram
|| uma_histogram
->histogram_name() != uma_name
) {
297 uma_histogram
= base::LinearHistogram::FactoryGet(
300 uma_boundary_value
+ 1, base::Histogram::kUmaTargetedHistogramFlag
);
302 uma_histogram
->Add(uma_sample
);
306 return base::kNullProcessHandle
;
309 // This is just a starting score for a renderer or extension (the
310 // only types of processes that will be started this way). It will
311 // get adjusted as time goes on. (This is the same value as
312 // chrome::kLowestRendererOomScore in chrome/chrome_constants.h, but
313 // that's not something we can include here.)
314 const int kLowestRendererOomScore
= 300;
315 AdjustRendererOOMScore(pid
, kLowestRendererOomScore
);
320 void ZygoteHost::AdjustRendererOOMScore(base::ProcessHandle pid
, int score
) {
321 // 1) You can't change the oom_score_adj of a non-dumpable process
322 // (EPERM) unless you're root. Because of this, we can't set the
323 // oom_adj from the browser process.
325 // 2) We can't set the oom_score_adj before entering the sandbox
326 // because the zygote is in the sandbox and the zygote is as
327 // critical as the browser process. Its oom_adj value shouldn't
330 // 3) A non-dumpable process can't even change its own oom_score_adj
331 // because it's root owned 0644. The sandboxed processes don't
332 // even have /proc, but one could imagine passing in a descriptor
335 // So, in the normal case, we use the SUID binary to change it for us.
336 // However, Fedora (and other SELinux systems) don't like us touching other
337 // process's oom_score_adj (or oom_adj) values
338 // (https://bugzilla.redhat.com/show_bug.cgi?id=581256).
340 // The offical way to get the SELinux mode is selinux_getenforcemode, but I
341 // don't want to add another library to the build as it's sure to cause
342 // problems with other, non-SELinux distros.
344 // So we just check for files in /selinux. This isn't foolproof, but it's not
345 // bad and it's easy.
348 static bool selinux_valid
= false;
350 if (!selinux_valid
) {
351 const FilePath
kSelinuxPath("/selinux");
352 selinux
= access(kSelinuxPath
.value().c_str(), X_OK
) == 0 &&
353 file_util::CountFilesCreatedAfter(kSelinuxPath
,
354 base::Time::UnixEpoch()) > 0;
355 selinux_valid
= true;
358 if (using_suid_sandbox_
&& !selinux
) {
359 #if defined(USE_TCMALLOC)
360 // If heap profiling is running, these processes are not exiting, at least
361 // on ChromeOS. The easiest thing to do is not launch them when profiling.
362 // TODO(stevenjb): Investigate further and fix.
363 if (IsHeapProfilerRunning())
366 // The command line switch used for supplying the OOM adjustment score
367 // to the setuid sandbox.
368 static const char kAdjustOOMScoreSwitch
[] = "--adjust-oom-score";
370 std::vector
<std::string
> adj_oom_score_cmdline
;
371 adj_oom_score_cmdline
.push_back(sandbox_binary_
);
372 adj_oom_score_cmdline
.push_back(kAdjustOOMScoreSwitch
);
373 adj_oom_score_cmdline
.push_back(base::Int64ToString(pid
));
374 adj_oom_score_cmdline
.push_back(base::IntToString(score
));
376 base::ProcessHandle sandbox_helper_process
;
377 if (base::LaunchProcess(adj_oom_score_cmdline
, base::LaunchOptions(),
378 &sandbox_helper_process
)) {
379 ProcessWatcher::EnsureProcessGetsReaped(sandbox_helper_process
);
381 } else if (!using_suid_sandbox_
) {
382 if (!base::AdjustOOMScore(pid
, score
))
383 PLOG(ERROR
) << "Failed to adjust OOM score of renderer with pid " << pid
;
387 void ZygoteHost::EnsureProcessTerminated(pid_t process
) {
391 pickle
.WriteInt(kCmdReap
);
392 pickle
.WriteInt(process
);
394 if (HANDLE_EINTR(write(control_fd_
, pickle
.data(), pickle
.size())) < 0)
395 PLOG(ERROR
) << "write";
398 base::TerminationStatus
ZygoteHost::GetTerminationStatus(
399 base::ProcessHandle handle
,
403 pickle
.WriteInt(kCmdGetTerminationStatus
);
404 pickle
.WriteInt(handle
);
406 // Set this now to handle the early termination cases.
408 *exit_code
= content::RESULT_CODE_NORMAL_EXIT
;
410 static const unsigned kMaxMessageLength
= 128;
411 char buf
[kMaxMessageLength
];
414 base::AutoLock
lock(control_lock_
);
415 if (HANDLE_EINTR(write(control_fd_
, pickle
.data(), pickle
.size())) < 0)
416 PLOG(ERROR
) << "write";
418 len
= ReadReply(buf
, sizeof(buf
));
422 LOG(WARNING
) << "Error reading message from zygote: " << errno
;
423 return base::TERMINATION_STATUS_NORMAL_TERMINATION
;
424 } else if (len
== 0) {
425 LOG(WARNING
) << "Socket closed prematurely.";
426 return base::TERMINATION_STATUS_NORMAL_TERMINATION
;
429 Pickle
read_pickle(buf
, len
);
430 int status
, tmp_exit_code
;
432 if (!read_pickle
.ReadInt(&iter
, &status
) ||
433 !read_pickle
.ReadInt(&iter
, &tmp_exit_code
)) {
434 LOG(WARNING
) << "Error parsing GetTerminationStatus response from zygote.";
435 return base::TERMINATION_STATUS_NORMAL_TERMINATION
;
439 *exit_code
= tmp_exit_code
;
441 return static_cast<base::TerminationStatus
>(status
);