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.
7 #include <sys/resource.h>
10 #include <sys/types.h>
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"
42 inline void operator()(int* fd) const {
44 PCHECK(0 == IGNORE_EINTR(close(*fd)));
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: " +
56 #if defined(OS_CHROMEOS)
57 LOG(WARNING) << activated_sandbox;
59 VLOG(1) << activated_sandbox;
63 #if !defined(ADDRESS_SANITIZER) && !defined(MEMORY_SANITIZER)
64 bool AddResourceLimit(int resource, rlim_t limit) {
65 struct rlimit old_rlimit;
66 if (getrlimit(resource, &old_rlimit))
68 // Make sure we don't raise the existing limit.
69 const struct rlimit new_rlimit = {
70 std::min(old_rlimit.rlim_cur, limit),
71 std::min(old_rlimit.rlim_max, limit)
73 int rc = setrlimit(resource, &new_rlimit);
78 bool IsRunningTSAN() {
79 #if defined(THREAD_SANITIZER)
86 // Try to open /proc/self/task/ with the help of |proc_fd|. |proc_fd| can be
87 // -1. Will return -1 on error and set errno like open(2).
88 int OpenProcTaskFd(int proc_fd) {
89 int proc_self_task = -1;
91 // If a handle to /proc is available, use it. This allows to bypass file
92 // system restrictions.
93 proc_self_task = openat(proc_fd, "self/task/", O_RDONLY | O_DIRECTORY);
95 // Otherwise, make an attempt to access the file system directly.
96 proc_self_task = open("/proc/self/task/", O_RDONLY | O_DIRECTORY);
98 return proc_self_task;
105 LinuxSandbox::LinuxSandbox()
107 seccomp_bpf_started_(false),
108 sandbox_status_flags_(kSandboxLinuxInvalid),
109 pre_initialized_(false),
110 seccomp_bpf_supported_(false),
111 yama_is_enforcing_(false),
112 setuid_sandbox_client_(sandbox::SetuidSandboxClient::Create()) {
113 if (setuid_sandbox_client_ == NULL) {
114 LOG(FATAL) << "Failed to instantiate the setuid sandbox client.";
118 LinuxSandbox::~LinuxSandbox() {
121 LinuxSandbox* LinuxSandbox::GetInstance() {
122 LinuxSandbox* instance = Singleton<LinuxSandbox>::get();
127 #if (defined(ADDRESS_SANITIZER) || defined(MEMORY_SANITIZER) || \
128 defined(LEAK_SANITIZER)) && defined(OS_LINUX)
129 // Sanitizer API call to notify the tool the sandbox is going to be turned on.
130 extern "C" void __sanitizer_sandbox_on_notify(void *reserved);
133 void LinuxSandbox::PreinitializeSandbox() {
134 CHECK(!pre_initialized_);
135 seccomp_bpf_supported_ = false;
136 #if (defined(ADDRESS_SANITIZER) || defined(MEMORY_SANITIZER) || \
137 defined(LEAK_SANITIZER)) && defined(OS_LINUX)
138 // Sanitizers need to open some resources before the sandbox is enabled.
139 // This should not fork, not launch threads, not open a directory.
140 __sanitizer_sandbox_on_notify(/*reserved*/ NULL);
144 // The in-process stack dumping needs to open /proc/self/maps and cache
145 // its contents before the sandbox is enabled. It also pre-opens the
146 // object files that are already loaded in the process address space.
147 base::debug::EnableInProcessStackDumpingForSandbox();
149 // Open proc_fd_ only in Debug mode so that forgetting to close it doesn't
150 // produce a sandbox escape in Release mode.
151 proc_fd_ = open("/proc", O_DIRECTORY | O_RDONLY | O_CLOEXEC);
152 CHECK_GE(proc_fd_, 0);
153 #endif // !defined(NDEBUG)
154 // We "pre-warm" the code that detects supports for seccomp BPF.
155 if (SandboxSeccompBPF::IsSeccompBPFDesired()) {
156 if (!SandboxSeccompBPF::SupportsSandbox()) {
157 VLOG(1) << "Lacking support for seccomp-bpf sandbox.";
159 seccomp_bpf_supported_ = true;
163 // Yama is a "global", system-level status. We assume it will not regress
165 const int yama_status = Yama::GetStatus();
166 yama_is_enforcing_ = (yama_status & Yama::STATUS_PRESENT) &&
167 (yama_status & Yama::STATUS_ENFORCING);
168 pre_initialized_ = true;
171 bool LinuxSandbox::InitializeSandbox() {
172 LinuxSandbox* linux_sandbox = LinuxSandbox::GetInstance();
173 return linux_sandbox->InitializeSandboxImpl();
176 void LinuxSandbox::StopThread(base::Thread* thread) {
177 LinuxSandbox* linux_sandbox = LinuxSandbox::GetInstance();
178 linux_sandbox->StopThreadImpl(thread);
181 int LinuxSandbox::GetStatus() {
182 CHECK(pre_initialized_);
183 if (kSandboxLinuxInvalid == sandbox_status_flags_) {
184 // Initialize sandbox_status_flags_.
185 sandbox_status_flags_ = 0;
186 if (setuid_sandbox_client_->IsSandboxed()) {
187 sandbox_status_flags_ |= kSandboxLinuxSUID;
188 if (setuid_sandbox_client_->IsInNewPIDNamespace())
189 sandbox_status_flags_ |= kSandboxLinuxPIDNS;
190 if (setuid_sandbox_client_->IsInNewNETNamespace())
191 sandbox_status_flags_ |= kSandboxLinuxNetNS;
194 // We report whether the sandbox will be activated when renderers, workers
195 // and PPAPI plugins go through sandbox initialization.
196 if (seccomp_bpf_supported() &&
197 SandboxSeccompBPF::ShouldEnableSeccompBPF(switches::kRendererProcess)) {
198 sandbox_status_flags_ |= kSandboxLinuxSeccompBPF;
201 if (yama_is_enforcing_) {
202 sandbox_status_flags_ |= kSandboxLinuxYama;
206 return sandbox_status_flags_;
209 // Threads are counted via /proc/self/task. This is a little hairy because of
210 // PID namespaces and existing sandboxes, so "self" must really be used instead
212 bool LinuxSandbox::IsSingleThreaded() const {
213 bool is_single_threaded = false;
214 base::ScopedFD proc_self_task(OpenProcTaskFd(proc_fd_));
216 // In Debug mode, it's mandatory to be able to count threads to catch bugs.
218 // Using CHECK here since we want to check all the cases where
221 CHECK(proc_self_task.is_valid())
222 << "Could not count threads, the sandbox was not "
223 << "pre-initialized properly.";
224 #endif // !defined(NDEBUG)
226 if (!proc_self_task.is_valid()) {
227 // Pretend to be monothreaded if it can't be determined (for instance the
228 // setuid sandbox is already engaged but no proc_fd_ is available).
229 is_single_threaded = true;
232 sandbox::ThreadHelpers::IsSingleThreaded(proc_self_task.get());
235 return is_single_threaded;
238 bool LinuxSandbox::seccomp_bpf_started() const {
239 return seccomp_bpf_started_;
242 sandbox::SetuidSandboxClient*
243 LinuxSandbox::setuid_sandbox_client() const {
244 return setuid_sandbox_client_.get();
247 // For seccomp-bpf, we use the SandboxSeccompBPF class.
248 bool LinuxSandbox::StartSeccompBPF(const std::string& process_type) {
249 CHECK(!seccomp_bpf_started_);
250 CHECK(pre_initialized_);
251 if (seccomp_bpf_supported())
252 seccomp_bpf_started_ = SandboxSeccompBPF::StartSandbox(process_type);
254 if (seccomp_bpf_started_)
255 LogSandboxStarted("seccomp-bpf");
257 return seccomp_bpf_started_;
260 bool LinuxSandbox::InitializeSandboxImpl() {
261 CommandLine* command_line = CommandLine::ForCurrentProcess();
262 const std::string process_type =
263 command_line->GetSwitchValueASCII(switches::kProcessType);
265 // We need to make absolutely sure that our sandbox is "sealed" before
267 // Unretained() since the current object is a Singleton.
268 base::ScopedClosureRunner sandbox_sealer(
269 base::Bind(&LinuxSandbox::SealSandbox, base::Unretained(this)));
270 // Make sure that this function enables sandboxes as promised by GetStatus().
271 // Unretained() since the current object is a Singleton.
272 base::ScopedClosureRunner sandbox_promise_keeper(
273 base::Bind(&LinuxSandbox::CheckForBrokenPromises,
274 base::Unretained(this),
277 // No matter what, it's always an error to call InitializeSandbox() after
278 // threads have been created.
279 if (!IsSingleThreaded()) {
280 std::string error_message = "InitializeSandbox() called with multiple "
281 "threads in process " + process_type;
282 // TSAN starts a helper thread, so we don't start the sandbox and don't
283 // even report an error about it.
287 // The GPU process is allowed to call InitializeSandbox() with threads.
288 bool sandbox_failure_fatal = process_type != switches::kGpuProcess;
289 // This can be disabled with the '--gpu-sandbox-failures-fatal' flag.
290 // Setting the flag with no value or any value different than 'yes' or 'no'
291 // is equal to setting '--gpu-sandbox-failures-fatal=yes'.
292 if (process_type == switches::kGpuProcess &&
293 command_line->HasSwitch(switches::kGpuSandboxFailuresFatal)) {
294 const std::string switch_value =
295 command_line->GetSwitchValueASCII(switches::kGpuSandboxFailuresFatal);
296 sandbox_failure_fatal = switch_value != "no";
299 if (sandbox_failure_fatal)
300 LOG(FATAL) << error_message;
302 LOG(ERROR) << error_message;
306 // Only one thread is running, pre-initialize if not already done.
307 if (!pre_initialized_)
308 PreinitializeSandbox();
310 DCHECK(!HasOpenDirectories()) <<
311 "InitializeSandbox() called after unexpected directories have been " <<
312 "opened. This breaks the security of the setuid sandbox.";
314 // Attempt to limit the future size of the address space of the process.
315 LimitAddressSpace(process_type);
317 // Try to enable seccomp-bpf.
318 bool seccomp_bpf_started = StartSeccompBPF(process_type);
320 return seccomp_bpf_started;
323 void LinuxSandbox::StopThreadImpl(base::Thread* thread) {
325 StopThreadAndEnsureNotCounted(thread);
328 bool LinuxSandbox::seccomp_bpf_supported() const {
329 CHECK(pre_initialized_);
330 return seccomp_bpf_supported_;
333 bool LinuxSandbox::LimitAddressSpace(const std::string& process_type) {
335 #if !defined(ADDRESS_SANITIZER) && !defined(MEMORY_SANITIZER)
336 CommandLine* command_line = CommandLine::ForCurrentProcess();
337 if (command_line->HasSwitch(switches::kNoSandbox)) {
341 // Limit the address space to 4GB.
342 // This is in the hope of making some kernel exploits more complex and less
343 // reliable. It also limits sprays a little on 64-bit.
344 rlim_t address_space_limit = std::numeric_limits<uint32_t>::max();
345 #if defined(__LP64__)
346 // On 64 bits, V8 and possibly others will reserve massive memory ranges and
347 // rely on on-demand paging for allocation. Unfortunately, even
348 // MADV_DONTNEED ranges count towards RLIMIT_AS so this is not an option.
349 // See crbug.com/169327 for a discussion.
350 // On the GPU process, irrespective of V8, we can exhaust a 4GB address space
351 // under normal usage, see crbug.com/271119
352 // For now, increase limit to 16GB for renderer and worker and gpu processes
354 if (process_type == switches::kRendererProcess ||
355 process_type == switches::kWorkerProcess ||
356 process_type == switches::kGpuProcess) {
357 address_space_limit = 1L << 34;
359 #endif // defined(__LP64__)
361 // On all platforms, add a limit to the brk() heap that would prevent
362 // allocations that can't be index by an int.
363 const rlim_t kNewDataSegmentMaxSize = std::numeric_limits<int>::max();
365 bool limited_as = AddResourceLimit(RLIMIT_AS, address_space_limit);
366 bool limited_data = AddResourceLimit(RLIMIT_DATA, kNewDataSegmentMaxSize);
368 // Cache the resource limit before turning on the sandbox.
369 base::SysInfo::AmountOfVirtualMemory();
371 return limited_as && limited_data;
373 base::SysInfo::AmountOfVirtualMemory();
375 #endif // !defined(ADDRESS_SANITIZER) && !defined(MEMORY_SANITIZER)
378 bool LinuxSandbox::HasOpenDirectories() const {
379 return sandbox::Credentials().HasOpenDirectory(proc_fd_);
382 void LinuxSandbox::SealSandbox() {
384 int ret = IGNORE_EINTR(close(proc_fd_));
390 void LinuxSandbox::CheckForBrokenPromises(const std::string& process_type) {
391 // Make sure that any promise made with GetStatus() wasn't broken.
392 bool promised_seccomp_bpf_would_start = false;
393 if (process_type == switches::kRendererProcess ||
394 process_type == switches::kWorkerProcess ||
395 process_type == switches::kPpapiPluginProcess) {
396 promised_seccomp_bpf_would_start =
397 (sandbox_status_flags_ != kSandboxLinuxInvalid) &&
398 (GetStatus() & kSandboxLinuxSeccompBPF);
400 if (promised_seccomp_bpf_would_start) {
401 CHECK(seccomp_bpf_started_);
405 void LinuxSandbox::StopThreadAndEnsureNotCounted(base::Thread* thread) const {
407 base::ScopedFD proc_self_task(OpenProcTaskFd(proc_fd_));
408 PCHECK(proc_self_task.is_valid());
409 CHECK(sandbox::ThreadHelpers::StopThreadAndWatchProcFS(proc_self_task.get(),
413 } // namespace content