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"
37 #if defined(ADDRESS_SANITIZER) || defined(MEMORY_SANITIZER) || \
38 defined(LEAK_SANITIZER) || defined(UNDEFINED_SANITIZER)
39 #include <sanitizer/common_interface_defs.h>
47 inline void operator()(int* fd
) const {
49 PCHECK(0 == IGNORE_EINTR(close(*fd
)));
54 void LogSandboxStarted(const std::string
& sandbox_name
) {
55 const CommandLine
& command_line
= *CommandLine::ForCurrentProcess();
56 const std::string process_type
=
57 command_line
.GetSwitchValueASCII(switches::kProcessType
);
58 const std::string activated_sandbox
=
59 "Activated " + sandbox_name
+ " sandbox for process type: " +
61 VLOG(1) << activated_sandbox
;
64 #if !defined(ADDRESS_SANITIZER) && !defined(MEMORY_SANITIZER)
65 bool AddResourceLimit(int resource
, rlim_t limit
) {
66 struct rlimit old_rlimit
;
67 if (getrlimit(resource
, &old_rlimit
))
69 // Make sure we don't raise the existing limit.
70 const struct rlimit new_rlimit
= {
71 std::min(old_rlimit
.rlim_cur
, limit
),
72 std::min(old_rlimit
.rlim_max
, limit
)
74 int rc
= setrlimit(resource
, &new_rlimit
);
79 bool IsRunningTSAN() {
80 #if defined(THREAD_SANITIZER)
87 // Try to open /proc/self/task/ with the help of |proc_fd|. |proc_fd| can be
88 // -1. Will return -1 on error and set errno like open(2).
89 int OpenProcTaskFd(int proc_fd
) {
90 int proc_self_task
= -1;
92 // If a handle to /proc is available, use it. This allows to bypass file
93 // system restrictions.
94 proc_self_task
= openat(proc_fd
, "self/task/", O_RDONLY
| O_DIRECTORY
);
96 // Otherwise, make an attempt to access the file system directly.
97 proc_self_task
= open("/proc/self/task/", O_RDONLY
| O_DIRECTORY
);
99 return proc_self_task
;
106 LinuxSandbox::LinuxSandbox()
108 seccomp_bpf_started_(false),
109 sandbox_status_flags_(kSandboxLinuxInvalid
),
110 pre_initialized_(false),
111 seccomp_bpf_supported_(false),
112 yama_is_enforcing_(false),
113 setuid_sandbox_client_(sandbox::SetuidSandboxClient::Create())
115 if (setuid_sandbox_client_
== NULL
) {
116 LOG(FATAL
) << "Failed to instantiate the setuid sandbox client.";
118 #if defined(ADDRESS_SANITIZER) || defined(MEMORY_SANITIZER) || \
119 defined(LEAK_SANITIZER) || defined(UNDEFINED_SANITIZER)
120 sanitizer_args_
= make_scoped_ptr(new __sanitizer_sandbox_arguments
);
121 *sanitizer_args_
= {0};
125 LinuxSandbox::~LinuxSandbox() {
128 LinuxSandbox
* LinuxSandbox::GetInstance() {
129 LinuxSandbox
* instance
= Singleton
<LinuxSandbox
>::get();
134 void LinuxSandbox::PreinitializeSandbox() {
135 CHECK(!pre_initialized_
);
136 seccomp_bpf_supported_
= false;
137 #if defined(ADDRESS_SANITIZER) || defined(MEMORY_SANITIZER) || \
138 defined(LEAK_SANITIZER) || defined(UNDEFINED_SANITIZER)
139 // Sanitizers need to open some resources before the sandbox is enabled.
140 // This should not fork, not launch threads, not open a directory.
141 __sanitizer_sandbox_on_notify(sanitizer_args());
142 sanitizer_args_
.reset();
146 // The in-process stack dumping needs to open /proc/self/maps and cache
147 // its contents before the sandbox is enabled. It also pre-opens the
148 // object files that are already loaded in the process address space.
149 base::debug::EnableInProcessStackDumpingForSandbox();
151 // Open proc_fd_ only in Debug mode so that forgetting to close it doesn't
152 // produce a sandbox escape in Release mode.
153 proc_fd_
= open("/proc", O_DIRECTORY
| O_RDONLY
| O_CLOEXEC
);
154 CHECK_GE(proc_fd_
, 0);
155 #endif // !defined(NDEBUG)
156 // We "pre-warm" the code that detects supports for seccomp BPF.
157 if (SandboxSeccompBPF::IsSeccompBPFDesired()) {
158 if (!SandboxSeccompBPF::SupportsSandbox()) {
159 VLOG(1) << "Lacking support for seccomp-bpf sandbox.";
161 seccomp_bpf_supported_
= true;
165 // Yama is a "global", system-level status. We assume it will not regress
167 const int yama_status
= Yama::GetStatus();
168 yama_is_enforcing_
= (yama_status
& Yama::STATUS_PRESENT
) &&
169 (yama_status
& Yama::STATUS_ENFORCING
);
170 pre_initialized_
= true;
173 bool LinuxSandbox::InitializeSandbox() {
174 LinuxSandbox
* linux_sandbox
= LinuxSandbox::GetInstance();
175 return linux_sandbox
->InitializeSandboxImpl();
178 void LinuxSandbox::StopThread(base::Thread
* thread
) {
179 LinuxSandbox
* linux_sandbox
= LinuxSandbox::GetInstance();
180 linux_sandbox
->StopThreadImpl(thread
);
183 int LinuxSandbox::GetStatus() {
184 CHECK(pre_initialized_
);
185 if (kSandboxLinuxInvalid
== sandbox_status_flags_
) {
186 // Initialize sandbox_status_flags_.
187 sandbox_status_flags_
= 0;
188 if (setuid_sandbox_client_
->IsSandboxed()) {
189 sandbox_status_flags_
|= kSandboxLinuxSUID
;
190 if (setuid_sandbox_client_
->IsInNewPIDNamespace())
191 sandbox_status_flags_
|= kSandboxLinuxPIDNS
;
192 if (setuid_sandbox_client_
->IsInNewNETNamespace())
193 sandbox_status_flags_
|= kSandboxLinuxNetNS
;
196 // We report whether the sandbox will be activated when renderers, workers
197 // and PPAPI plugins go through sandbox initialization.
198 if (seccomp_bpf_supported() &&
199 SandboxSeccompBPF::ShouldEnableSeccompBPF(switches::kRendererProcess
)) {
200 sandbox_status_flags_
|= kSandboxLinuxSeccompBPF
;
203 if (yama_is_enforcing_
) {
204 sandbox_status_flags_
|= kSandboxLinuxYama
;
208 return sandbox_status_flags_
;
211 // Threads are counted via /proc/self/task. This is a little hairy because of
212 // PID namespaces and existing sandboxes, so "self" must really be used instead
214 bool LinuxSandbox::IsSingleThreaded() const {
215 bool is_single_threaded
= false;
216 base::ScopedFD
proc_self_task(OpenProcTaskFd(proc_fd_
));
218 // In Debug mode, it's mandatory to be able to count threads to catch bugs.
220 // Using CHECK here since we want to check all the cases where
223 CHECK(proc_self_task
.is_valid())
224 << "Could not count threads, the sandbox was not "
225 << "pre-initialized properly.";
226 #endif // !defined(NDEBUG)
228 if (!proc_self_task
.is_valid()) {
229 // Pretend to be monothreaded if it can't be determined (for instance the
230 // setuid sandbox is already engaged but no proc_fd_ is available).
231 is_single_threaded
= true;
234 sandbox::ThreadHelpers::IsSingleThreaded(proc_self_task
.get());
237 return is_single_threaded
;
240 bool LinuxSandbox::seccomp_bpf_started() const {
241 return seccomp_bpf_started_
;
244 sandbox::SetuidSandboxClient
*
245 LinuxSandbox::setuid_sandbox_client() const {
246 return setuid_sandbox_client_
.get();
249 // For seccomp-bpf, we use the SandboxSeccompBPF class.
250 bool LinuxSandbox::StartSeccompBPF(const std::string
& process_type
) {
251 CHECK(!seccomp_bpf_started_
);
252 CHECK(pre_initialized_
);
253 if (seccomp_bpf_supported())
254 seccomp_bpf_started_
= SandboxSeccompBPF::StartSandbox(process_type
);
256 if (seccomp_bpf_started_
)
257 LogSandboxStarted("seccomp-bpf");
259 return seccomp_bpf_started_
;
262 bool LinuxSandbox::InitializeSandboxImpl() {
263 CommandLine
* command_line
= CommandLine::ForCurrentProcess();
264 const std::string process_type
=
265 command_line
->GetSwitchValueASCII(switches::kProcessType
);
267 // We need to make absolutely sure that our sandbox is "sealed" before
269 // Unretained() since the current object is a Singleton.
270 base::ScopedClosureRunner
sandbox_sealer(
271 base::Bind(&LinuxSandbox::SealSandbox
, base::Unretained(this)));
272 // Make sure that this function enables sandboxes as promised by GetStatus().
273 // Unretained() since the current object is a Singleton.
274 base::ScopedClosureRunner
sandbox_promise_keeper(
275 base::Bind(&LinuxSandbox::CheckForBrokenPromises
,
276 base::Unretained(this),
279 // No matter what, it's always an error to call InitializeSandbox() after
280 // threads have been created.
281 if (!IsSingleThreaded()) {
282 std::string error_message
= "InitializeSandbox() called with multiple "
283 "threads in process " + process_type
;
284 // TSAN starts a helper thread, so we don't start the sandbox and don't
285 // even report an error about it.
289 // The GPU process is allowed to call InitializeSandbox() with threads.
290 bool sandbox_failure_fatal
= process_type
!= switches::kGpuProcess
;
291 // This can be disabled with the '--gpu-sandbox-failures-fatal' flag.
292 // Setting the flag with no value or any value different than 'yes' or 'no'
293 // is equal to setting '--gpu-sandbox-failures-fatal=yes'.
294 if (process_type
== switches::kGpuProcess
&&
295 command_line
->HasSwitch(switches::kGpuSandboxFailuresFatal
)) {
296 const std::string switch_value
=
297 command_line
->GetSwitchValueASCII(switches::kGpuSandboxFailuresFatal
);
298 sandbox_failure_fatal
= switch_value
!= "no";
301 if (sandbox_failure_fatal
)
302 LOG(FATAL
) << error_message
;
304 LOG(ERROR
) << error_message
;
308 // Only one thread is running, pre-initialize if not already done.
309 if (!pre_initialized_
)
310 PreinitializeSandbox();
312 DCHECK(!HasOpenDirectories()) <<
313 "InitializeSandbox() called after unexpected directories have been " <<
314 "opened. This breaks the security of the setuid sandbox.";
316 // Attempt to limit the future size of the address space of the process.
317 LimitAddressSpace(process_type
);
319 // Try to enable seccomp-bpf.
320 bool seccomp_bpf_started
= StartSeccompBPF(process_type
);
322 return seccomp_bpf_started
;
325 void LinuxSandbox::StopThreadImpl(base::Thread
* thread
) {
327 StopThreadAndEnsureNotCounted(thread
);
330 bool LinuxSandbox::seccomp_bpf_supported() const {
331 CHECK(pre_initialized_
);
332 return seccomp_bpf_supported_
;
335 bool LinuxSandbox::LimitAddressSpace(const std::string
& process_type
) {
337 #if !defined(ADDRESS_SANITIZER) && !defined(MEMORY_SANITIZER)
338 CommandLine
* command_line
= CommandLine::ForCurrentProcess();
339 if (command_line
->HasSwitch(switches::kNoSandbox
)) {
343 // Limit the address space to 4GB.
344 // This is in the hope of making some kernel exploits more complex and less
345 // reliable. It also limits sprays a little on 64-bit.
346 rlim_t address_space_limit
= std::numeric_limits
<uint32_t>::max();
347 #if defined(__LP64__)
348 // On 64 bits, V8 and possibly others will reserve massive memory ranges and
349 // rely on on-demand paging for allocation. Unfortunately, even
350 // MADV_DONTNEED ranges count towards RLIMIT_AS so this is not an option.
351 // See crbug.com/169327 for a discussion.
352 // On the GPU process, irrespective of V8, we can exhaust a 4GB address space
353 // under normal usage, see crbug.com/271119
354 // For now, increase limit to 16GB for renderer and worker and gpu processes
356 if (process_type
== switches::kRendererProcess
||
357 process_type
== switches::kWorkerProcess
||
358 process_type
== switches::kGpuProcess
) {
359 address_space_limit
= 1L << 34;
361 #endif // defined(__LP64__)
363 // On all platforms, add a limit to the brk() heap that would prevent
364 // allocations that can't be index by an int.
365 const rlim_t kNewDataSegmentMaxSize
= std::numeric_limits
<int>::max();
367 bool limited_as
= AddResourceLimit(RLIMIT_AS
, address_space_limit
);
368 bool limited_data
= AddResourceLimit(RLIMIT_DATA
, kNewDataSegmentMaxSize
);
370 // Cache the resource limit before turning on the sandbox.
371 base::SysInfo::AmountOfVirtualMemory();
373 return limited_as
&& limited_data
;
375 base::SysInfo::AmountOfVirtualMemory();
377 #endif // !defined(ADDRESS_SANITIZER) && !defined(MEMORY_SANITIZER)
380 bool LinuxSandbox::HasOpenDirectories() const {
381 return sandbox::Credentials().HasOpenDirectory(proc_fd_
);
384 void LinuxSandbox::SealSandbox() {
386 int ret
= IGNORE_EINTR(close(proc_fd_
));
392 void LinuxSandbox::CheckForBrokenPromises(const std::string
& process_type
) {
393 // Make sure that any promise made with GetStatus() wasn't broken.
394 bool promised_seccomp_bpf_would_start
= false;
395 if (process_type
== switches::kRendererProcess
||
396 process_type
== switches::kWorkerProcess
||
397 process_type
== switches::kPpapiPluginProcess
) {
398 promised_seccomp_bpf_would_start
=
399 (sandbox_status_flags_
!= kSandboxLinuxInvalid
) &&
400 (GetStatus() & kSandboxLinuxSeccompBPF
);
402 if (promised_seccomp_bpf_would_start
) {
403 CHECK(seccomp_bpf_started_
);
407 void LinuxSandbox::StopThreadAndEnsureNotCounted(base::Thread
* thread
) const {
409 base::ScopedFD
proc_self_task(OpenProcTaskFd(proc_fd_
));
410 PCHECK(proc_self_task
.is_valid());
411 CHECK(sandbox::ThreadHelpers::StopThreadAndWatchProcFS(proc_self_task
.get(),
415 } // namespace content