Upstream version 7.36.149.0
[platform/framework/web/crosswalk.git] / src / content / common / sandbox_linux / sandbox_linux.cc
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.
4
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>
12
13 #include <limits>
14
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"
36
37 using sandbox::Yama;
38
39 namespace {
40
41 struct FDCloser {
42   inline void operator()(int* fd) const {
43     DCHECK(fd);
44     PCHECK(0 == IGNORE_EINTR(close(*fd)));
45     *fd = -1;
46   }
47 };
48
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
61 }
62
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))
67     return false;
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)
72       };
73   int rc = setrlimit(resource, &new_rlimit);
74   return rc == 0;
75 }
76 #endif
77
78 bool IsRunningTSAN() {
79 #if defined(THREAD_SANITIZER)
80   return true;
81 #else
82   return false;
83 #endif
84 }
85
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;
90   if (proc_fd >= 0) {
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);
94   } else {
95     // Otherwise, make an attempt to access the file system directly.
96     proc_self_task = open("/proc/self/task/", O_RDONLY | O_DIRECTORY);
97   }
98   return proc_self_task;
99 }
100
101 }  // namespace
102
103 namespace content {
104
105 LinuxSandbox::LinuxSandbox()
106     : proc_fd_(-1),
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.";
115   }
116 }
117
118 LinuxSandbox::~LinuxSandbox() {
119 }
120
121 LinuxSandbox* LinuxSandbox::GetInstance() {
122   LinuxSandbox* instance = Singleton<LinuxSandbox>::get();
123   CHECK(instance);
124   return instance;
125 }
126
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);
131 #endif
132
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);
141 #endif
142
143 #if !defined(NDEBUG)
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();
148
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.";
158     } else {
159       seccomp_bpf_supported_ = true;
160     }
161   }
162
163   // Yama is a "global", system-level status. We assume it will not regress
164   // after startup.
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;
169 }
170
171 bool LinuxSandbox::InitializeSandbox() {
172   LinuxSandbox* linux_sandbox = LinuxSandbox::GetInstance();
173   return linux_sandbox->InitializeSandboxImpl();
174 }
175
176 void LinuxSandbox::StopThread(base::Thread* thread) {
177   LinuxSandbox* linux_sandbox = LinuxSandbox::GetInstance();
178   linux_sandbox->StopThreadImpl(thread);
179 }
180
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;
192     }
193
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;
199     }
200
201     if (yama_is_enforcing_) {
202       sandbox_status_flags_ |= kSandboxLinuxYama;
203     }
204   }
205
206   return sandbox_status_flags_;
207 }
208
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
211 // of using the pid.
212 bool LinuxSandbox::IsSingleThreaded() const {
213   bool is_single_threaded = false;
214   base::ScopedFD proc_self_task(OpenProcTaskFd(proc_fd_));
215
216 // In Debug mode, it's mandatory to be able to count threads to catch bugs.
217 #if !defined(NDEBUG)
218   // Using CHECK here since we want to check all the cases where
219   // !defined(NDEBUG)
220   // gets built.
221   CHECK(proc_self_task.is_valid())
222       << "Could not count threads, the sandbox was not "
223       << "pre-initialized properly.";
224 #endif  // !defined(NDEBUG)
225
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;
230   } else {
231     is_single_threaded =
232         sandbox::ThreadHelpers::IsSingleThreaded(proc_self_task.get());
233   }
234
235   return is_single_threaded;
236 }
237
238 bool LinuxSandbox::seccomp_bpf_started() const {
239   return seccomp_bpf_started_;
240 }
241
242 sandbox::SetuidSandboxClient*
243     LinuxSandbox::setuid_sandbox_client() const {
244   return setuid_sandbox_client_.get();
245 }
246
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);
253
254   if (seccomp_bpf_started_)
255     LogSandboxStarted("seccomp-bpf");
256
257   return seccomp_bpf_started_;
258 }
259
260 bool LinuxSandbox::InitializeSandboxImpl() {
261   CommandLine* command_line = CommandLine::ForCurrentProcess();
262   const std::string process_type =
263       command_line->GetSwitchValueASCII(switches::kProcessType);
264
265   // We need to make absolutely sure that our sandbox is "sealed" before
266   // returning.
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),
275                  process_type));
276
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.
284     if (IsRunningTSAN())
285       return false;
286
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";
297     }
298
299     if (sandbox_failure_fatal)
300       LOG(FATAL) << error_message;
301
302     LOG(ERROR) << error_message;
303     return false;
304   }
305
306   // Only one thread is running, pre-initialize if not already done.
307   if (!pre_initialized_)
308     PreinitializeSandbox();
309
310   DCHECK(!HasOpenDirectories()) <<
311       "InitializeSandbox() called after unexpected directories have been " <<
312       "opened. This breaks the security of the setuid sandbox.";
313
314   // Attempt to limit the future size of the address space of the process.
315   LimitAddressSpace(process_type);
316
317   // Try to enable seccomp-bpf.
318   bool seccomp_bpf_started = StartSeccompBPF(process_type);
319
320   return seccomp_bpf_started;
321 }
322
323 void LinuxSandbox::StopThreadImpl(base::Thread* thread) {
324   DCHECK(thread);
325   StopThreadAndEnsureNotCounted(thread);
326 }
327
328 bool LinuxSandbox::seccomp_bpf_supported() const {
329   CHECK(pre_initialized_);
330   return seccomp_bpf_supported_;
331 }
332
333 bool LinuxSandbox::LimitAddressSpace(const std::string& process_type) {
334   (void) process_type;
335 #if !defined(ADDRESS_SANITIZER) && !defined(MEMORY_SANITIZER)
336   CommandLine* command_line = CommandLine::ForCurrentProcess();
337   if (command_line->HasSwitch(switches::kNoSandbox)) {
338     return false;
339   }
340
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
353   // to accomodate.
354   if (process_type == switches::kRendererProcess ||
355       process_type == switches::kWorkerProcess ||
356       process_type == switches::kGpuProcess) {
357     address_space_limit = 1L << 34;
358   }
359 #endif  // defined(__LP64__)
360
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();
364
365   bool limited_as = AddResourceLimit(RLIMIT_AS, address_space_limit);
366   bool limited_data = AddResourceLimit(RLIMIT_DATA, kNewDataSegmentMaxSize);
367
368   // Cache the resource limit before turning on the sandbox.
369   base::SysInfo::AmountOfVirtualMemory();
370
371   return limited_as && limited_data;
372 #else
373   base::SysInfo::AmountOfVirtualMemory();
374   return false;
375 #endif  // !defined(ADDRESS_SANITIZER) && !defined(MEMORY_SANITIZER)
376 }
377
378 bool LinuxSandbox::HasOpenDirectories() const {
379   return sandbox::Credentials().HasOpenDirectory(proc_fd_);
380 }
381
382 void LinuxSandbox::SealSandbox() {
383   if (proc_fd_ >= 0) {
384     int ret = IGNORE_EINTR(close(proc_fd_));
385     CHECK_EQ(0, ret);
386     proc_fd_ = -1;
387   }
388 }
389
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);
399   }
400   if (promised_seccomp_bpf_would_start) {
401     CHECK(seccomp_bpf_started_);
402   }
403 }
404
405 void LinuxSandbox::StopThreadAndEnsureNotCounted(base::Thread* thread) const {
406   DCHECK(thread);
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(),
410                                                          thread));
411 }
412
413 }  // namespace content