Cast: Stop logging kVideoFrameSentToEncoder and rename a couple events.
[chromium-blink-merge.git] / content / common / sandbox_linux / sandbox_linux.cc
blobf3a1b2f0283a9bca0973400501409fc9211e2371
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 <dirent.h>
6 #include <fcntl.h>
7 #include <sys/resource.h>
8 #include <sys/stat.h>
9 #include <sys/time.h>
10 #include <sys/types.h>
11 #include <unistd.h>
13 #include <limits>
15 #include "base/bind.h"
16 #include "base/callback_helpers.h"
17 #include "base/command_line.h"
18 #include "base/debug/stack_trace.h"
19 #include "base/files/scoped_file.h"
20 #include "base/logging.h"
21 #include "base/memory/scoped_ptr.h"
22 #include "base/memory/singleton.h"
23 #include "base/posix/eintr_wrapper.h"
24 #include "base/strings/string_number_conversions.h"
25 #include "base/sys_info.h"
26 #include "base/time/time.h"
27 #include "build/build_config.h"
28 #include "content/common/sandbox_linux/sandbox_linux.h"
29 #include "content/common/sandbox_linux/sandbox_seccomp_bpf_linux.h"
30 #include "content/public/common/content_switches.h"
31 #include "content/public/common/sandbox_linux.h"
32 #include "sandbox/linux/services/credentials.h"
33 #include "sandbox/linux/services/thread_helpers.h"
34 #include "sandbox/linux/services/yama.h"
35 #include "sandbox/linux/suid/client/setuid_sandbox_client.h"
37 using sandbox::Yama;
39 namespace {
41 struct FDCloser {
42 inline void operator()(int* fd) const {
43 DCHECK(fd);
44 PCHECK(0 == IGNORE_EINTR(close(*fd)));
45 *fd = -1;
49 void LogSandboxStarted(const std::string& sandbox_name) {
50 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
51 const std::string process_type =
52 command_line.GetSwitchValueASCII(switches::kProcessType);
53 const std::string activated_sandbox =
54 "Activated " + sandbox_name + " sandbox for process type: " +
55 process_type + ".";
56 #if defined(OS_CHROMEOS)
57 LOG(WARNING) << activated_sandbox;
58 #else
59 VLOG(1) << activated_sandbox;
60 #endif
63 bool AddResourceLimit(int resource, rlim_t limit) {
64 struct rlimit old_rlimit;
65 if (getrlimit(resource, &old_rlimit))
66 return false;
67 // Make sure we don't raise the existing limit.
68 const struct rlimit new_rlimit = {
69 std::min(old_rlimit.rlim_cur, limit),
70 std::min(old_rlimit.rlim_max, limit)
72 int rc = setrlimit(resource, &new_rlimit);
73 return rc == 0;
76 bool IsRunningTSAN() {
77 #if defined(THREAD_SANITIZER)
78 return true;
79 #else
80 return false;
81 #endif
84 // Try to open /proc/self/task/ with the help of |proc_fd|. |proc_fd| can be
85 // -1. Will return -1 on error and set errno like open(2).
86 int OpenProcTaskFd(int proc_fd) {
87 int proc_self_task = -1;
88 if (proc_fd >= 0) {
89 // If a handle to /proc is available, use it. This allows to bypass file
90 // system restrictions.
91 proc_self_task = openat(proc_fd, "self/task/", O_RDONLY | O_DIRECTORY);
92 } else {
93 // Otherwise, make an attempt to access the file system directly.
94 proc_self_task = open("/proc/self/task/", O_RDONLY | O_DIRECTORY);
96 return proc_self_task;
99 } // namespace
101 namespace content {
103 LinuxSandbox::LinuxSandbox()
104 : proc_fd_(-1),
105 seccomp_bpf_started_(false),
106 sandbox_status_flags_(kSandboxLinuxInvalid),
107 pre_initialized_(false),
108 seccomp_bpf_supported_(false),
109 yama_is_enforcing_(false),
110 setuid_sandbox_client_(sandbox::SetuidSandboxClient::Create()) {
111 if (setuid_sandbox_client_ == NULL) {
112 LOG(FATAL) << "Failed to instantiate the setuid sandbox client.";
116 LinuxSandbox::~LinuxSandbox() {
119 LinuxSandbox* LinuxSandbox::GetInstance() {
120 LinuxSandbox* instance = Singleton<LinuxSandbox>::get();
121 CHECK(instance);
122 return instance;
125 #if defined(ADDRESS_SANITIZER) && defined(OS_LINUX)
126 // ASan API call to notify the tool the sandbox is going to be turned on.
127 extern "C" void __sanitizer_sandbox_on_notify(void *reserved);
128 #endif
130 void LinuxSandbox::PreinitializeSandbox() {
131 CHECK(!pre_initialized_);
132 seccomp_bpf_supported_ = false;
133 #if defined(ADDRESS_SANITIZER) && defined(OS_LINUX)
134 // ASan needs to open some resources before the sandbox is enabled.
135 // This should not fork, not launch threads, not open a directory.
136 __sanitizer_sandbox_on_notify(/*reserved*/ NULL);
137 #endif
139 #if !defined(NDEBUG)
140 // The in-process stack dumping needs to open /proc/self/maps and cache
141 // its contents before the sandbox is enabled. It also pre-opens the
142 // object files that are already loaded in the process address space.
143 base::debug::EnableInProcessStackDumpingForSandbox();
145 // Open proc_fd_ only in Debug mode so that forgetting to close it doesn't
146 // produce a sandbox escape in Release mode.
147 proc_fd_ = open("/proc", O_DIRECTORY | O_RDONLY | O_CLOEXEC);
148 CHECK_GE(proc_fd_, 0);
149 #endif // !defined(NDEBUG)
150 // We "pre-warm" the code that detects supports for seccomp BPF.
151 if (SandboxSeccompBPF::IsSeccompBPFDesired()) {
152 if (!SandboxSeccompBPF::SupportsSandbox()) {
153 VLOG(1) << "Lacking support for seccomp-bpf sandbox.";
154 } else {
155 seccomp_bpf_supported_ = true;
159 // Yama is a "global", system-level status. We assume it will not regress
160 // after startup.
161 const int yama_status = Yama::GetStatus();
162 yama_is_enforcing_ = (yama_status & Yama::STATUS_PRESENT) &&
163 (yama_status & Yama::STATUS_ENFORCING);
164 pre_initialized_ = true;
167 bool LinuxSandbox::InitializeSandbox() {
168 LinuxSandbox* linux_sandbox = LinuxSandbox::GetInstance();
169 return linux_sandbox->InitializeSandboxImpl();
172 void LinuxSandbox::StopThread(base::Thread* thread) {
173 LinuxSandbox* linux_sandbox = LinuxSandbox::GetInstance();
174 linux_sandbox->StopThreadImpl(thread);
177 int LinuxSandbox::GetStatus() {
178 CHECK(pre_initialized_);
179 if (kSandboxLinuxInvalid == sandbox_status_flags_) {
180 // Initialize sandbox_status_flags_.
181 sandbox_status_flags_ = 0;
182 if (setuid_sandbox_client_->IsSandboxed()) {
183 sandbox_status_flags_ |= kSandboxLinuxSUID;
184 if (setuid_sandbox_client_->IsInNewPIDNamespace())
185 sandbox_status_flags_ |= kSandboxLinuxPIDNS;
186 if (setuid_sandbox_client_->IsInNewNETNamespace())
187 sandbox_status_flags_ |= kSandboxLinuxNetNS;
190 // We report whether the sandbox will be activated when renderers, workers
191 // and PPAPI plugins go through sandbox initialization.
192 if (seccomp_bpf_supported() &&
193 SandboxSeccompBPF::ShouldEnableSeccompBPF(switches::kRendererProcess)) {
194 sandbox_status_flags_ |= kSandboxLinuxSeccompBPF;
197 if (yama_is_enforcing_) {
198 sandbox_status_flags_ |= kSandboxLinuxYama;
202 return sandbox_status_flags_;
205 // Threads are counted via /proc/self/task. This is a little hairy because of
206 // PID namespaces and existing sandboxes, so "self" must really be used instead
207 // of using the pid.
208 bool LinuxSandbox::IsSingleThreaded() const {
209 bool is_single_threaded = false;
210 base::ScopedFD proc_self_task(OpenProcTaskFd(proc_fd_));
212 // In Debug mode, it's mandatory to be able to count threads to catch bugs.
213 #if !defined(NDEBUG)
214 // Using CHECK here since we want to check all the cases where
215 // !defined(NDEBUG)
216 // gets built.
217 CHECK(proc_self_task.is_valid())
218 << "Could not count threads, the sandbox was not "
219 << "pre-initialized properly.";
220 #endif // !defined(NDEBUG)
222 if (!proc_self_task.is_valid()) {
223 // Pretend to be monothreaded if it can't be determined (for instance the
224 // setuid sandbox is already engaged but no proc_fd_ is available).
225 is_single_threaded = true;
226 } else {
227 is_single_threaded =
228 sandbox::ThreadHelpers::IsSingleThreaded(proc_self_task.get());
231 return is_single_threaded;
234 bool LinuxSandbox::seccomp_bpf_started() const {
235 return seccomp_bpf_started_;
238 sandbox::SetuidSandboxClient*
239 LinuxSandbox::setuid_sandbox_client() const {
240 return setuid_sandbox_client_.get();
243 // For seccomp-bpf, we use the SandboxSeccompBPF class.
244 bool LinuxSandbox::StartSeccompBPF(const std::string& process_type) {
245 CHECK(!seccomp_bpf_started_);
246 CHECK(pre_initialized_);
247 if (seccomp_bpf_supported())
248 seccomp_bpf_started_ = SandboxSeccompBPF::StartSandbox(process_type);
250 if (seccomp_bpf_started_)
251 LogSandboxStarted("seccomp-bpf");
253 return seccomp_bpf_started_;
256 bool LinuxSandbox::InitializeSandboxImpl() {
257 CommandLine* command_line = CommandLine::ForCurrentProcess();
258 const std::string process_type =
259 command_line->GetSwitchValueASCII(switches::kProcessType);
261 // We need to make absolutely sure that our sandbox is "sealed" before
262 // returning.
263 // Unretained() since the current object is a Singleton.
264 base::ScopedClosureRunner sandbox_sealer(
265 base::Bind(&LinuxSandbox::SealSandbox, base::Unretained(this)));
266 // Make sure that this function enables sandboxes as promised by GetStatus().
267 // Unretained() since the current object is a Singleton.
268 base::ScopedClosureRunner sandbox_promise_keeper(
269 base::Bind(&LinuxSandbox::CheckForBrokenPromises,
270 base::Unretained(this),
271 process_type));
273 // No matter what, it's always an error to call InitializeSandbox() after
274 // threads have been created.
275 if (!IsSingleThreaded()) {
276 std::string error_message = "InitializeSandbox() called with multiple "
277 "threads in process " + process_type;
278 // TSAN starts a helper thread, so we don't start the sandbox and don't
279 // even report an error about it.
280 if (IsRunningTSAN())
281 return false;
283 // The GPU process is allowed to call InitializeSandbox() with threads.
284 bool sandbox_failure_fatal = process_type != switches::kGpuProcess;
285 // This can be disabled with the '--gpu-sandbox-failures-fatal' flag.
286 // Setting the flag with no value or any value different than 'yes' or 'no'
287 // is equal to setting '--gpu-sandbox-failures-fatal=yes'.
288 if (process_type == switches::kGpuProcess &&
289 command_line->HasSwitch(switches::kGpuSandboxFailuresFatal)) {
290 const std::string switch_value =
291 command_line->GetSwitchValueASCII(switches::kGpuSandboxFailuresFatal);
292 sandbox_failure_fatal = switch_value != "no";
295 if (sandbox_failure_fatal)
296 LOG(FATAL) << error_message;
298 LOG(ERROR) << error_message;
299 return false;
302 // Only one thread is running, pre-initialize if not already done.
303 if (!pre_initialized_)
304 PreinitializeSandbox();
306 DCHECK(!HasOpenDirectories()) <<
307 "InitializeSandbox() called after unexpected directories have been " <<
308 "opened. This breaks the security of the setuid sandbox.";
310 // Attempt to limit the future size of the address space of the process.
311 LimitAddressSpace(process_type);
313 // Try to enable seccomp-bpf.
314 bool seccomp_bpf_started = StartSeccompBPF(process_type);
316 return seccomp_bpf_started;
319 void LinuxSandbox::StopThreadImpl(base::Thread* thread) {
320 DCHECK(thread);
321 StopThreadAndEnsureNotCounted(thread);
324 bool LinuxSandbox::seccomp_bpf_supported() const {
325 CHECK(pre_initialized_);
326 return seccomp_bpf_supported_;
329 bool LinuxSandbox::LimitAddressSpace(const std::string& process_type) {
330 (void) process_type;
331 #if !defined(ADDRESS_SANITIZER)
332 CommandLine* command_line = CommandLine::ForCurrentProcess();
333 if (command_line->HasSwitch(switches::kNoSandbox)) {
334 return false;
337 // Limit the address space to 4GB.
338 // This is in the hope of making some kernel exploits more complex and less
339 // reliable. It also limits sprays a little on 64-bit.
340 rlim_t address_space_limit = std::numeric_limits<uint32_t>::max();
341 #if defined(__LP64__)
342 // On 64 bits, V8 and possibly others will reserve massive memory ranges and
343 // rely on on-demand paging for allocation. Unfortunately, even
344 // MADV_DONTNEED ranges count towards RLIMIT_AS so this is not an option.
345 // See crbug.com/169327 for a discussion.
346 // On the GPU process, irrespective of V8, we can exhaust a 4GB address space
347 // under normal usage, see crbug.com/271119
348 // For now, increase limit to 16GB for renderer and worker and gpu processes
349 // to accomodate.
350 if (process_type == switches::kRendererProcess ||
351 process_type == switches::kWorkerProcess ||
352 process_type == switches::kGpuProcess) {
353 address_space_limit = 1L << 34;
355 #endif // defined(__LP64__)
357 // On all platforms, add a limit to the brk() heap that would prevent
358 // allocations that can't be index by an int.
359 const rlim_t kNewDataSegmentMaxSize = std::numeric_limits<int>::max();
361 bool limited_as = AddResourceLimit(RLIMIT_AS, address_space_limit);
362 bool limited_data = AddResourceLimit(RLIMIT_DATA, kNewDataSegmentMaxSize);
364 // Cache the resource limit before turning on the sandbox.
365 base::SysInfo::AmountOfVirtualMemory();
367 return limited_as && limited_data;
368 #else
369 base::SysInfo::AmountOfVirtualMemory();
370 return false;
371 #endif // !defined(ADDRESS_SANITIZER)
374 bool LinuxSandbox::HasOpenDirectories() const {
375 return sandbox::Credentials().HasOpenDirectory(proc_fd_);
378 void LinuxSandbox::SealSandbox() {
379 if (proc_fd_ >= 0) {
380 int ret = IGNORE_EINTR(close(proc_fd_));
381 CHECK_EQ(0, ret);
382 proc_fd_ = -1;
386 void LinuxSandbox::CheckForBrokenPromises(const std::string& process_type) {
387 // Make sure that any promise made with GetStatus() wasn't broken.
388 bool promised_seccomp_bpf_would_start = false;
389 if (process_type == switches::kRendererProcess ||
390 process_type == switches::kWorkerProcess ||
391 process_type == switches::kPpapiPluginProcess) {
392 promised_seccomp_bpf_would_start =
393 (sandbox_status_flags_ != kSandboxLinuxInvalid) &&
394 (GetStatus() & kSandboxLinuxSeccompBPF);
396 if (promised_seccomp_bpf_would_start) {
397 CHECK(seccomp_bpf_started_);
401 void LinuxSandbox::StopThreadAndEnsureNotCounted(base::Thread* thread) const {
402 DCHECK(thread);
403 base::ScopedFD proc_self_task(OpenProcTaskFd(proc_fd_));
404 PCHECK(proc_self_task.is_valid());
405 CHECK(sandbox::ThreadHelpers::StopThreadAndWatchProcFS(proc_self_task.get(),
406 thread));
409 } // namespace content