Roll src/third_party/skia c877a71:fa77eb1
[chromium-blink-merge.git] / sandbox / linux / services / credentials.cc
blob6f84a66b7a60f2877a7dc2d85ab7a1d31983c27b
1 // Copyright (c) 2013 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 "sandbox/linux/services/credentials.h"
7 #include <errno.h>
8 #include <signal.h>
9 #include <stdio.h>
10 #include <sys/capability.h>
11 #include <sys/syscall.h>
12 #include <sys/types.h>
13 #include <sys/wait.h>
14 #include <unistd.h>
16 #include "base/basictypes.h"
17 #include "base/bind.h"
18 #include "base/files/file_path.h"
19 #include "base/files/file_util.h"
20 #include "base/logging.h"
21 #include "base/posix/eintr_wrapper.h"
22 #include "base/process/launch.h"
23 #include "base/template_util.h"
24 #include "base/third_party/valgrind/valgrind.h"
25 #include "build/build_config.h"
26 #include "sandbox/linux/services/namespace_utils.h"
27 #include "sandbox/linux/services/proc_util.h"
28 #include "sandbox/linux/services/syscall_wrappers.h"
29 #include "sandbox/linux/services/thread_helpers.h"
31 namespace sandbox {
33 namespace {
35 bool IsRunningOnValgrind() { return RUNNING_ON_VALGRIND; }
37 struct CapFreeDeleter {
38 inline void operator()(cap_t cap) const {
39 int ret = cap_free(cap);
40 CHECK_EQ(0, ret);
44 // Wrapper to manage libcap2's cap_t type.
45 typedef scoped_ptr<typeof(*((cap_t)0)), CapFreeDeleter> ScopedCap;
47 struct CapTextFreeDeleter {
48 inline void operator()(char* cap_text) const {
49 int ret = cap_free(cap_text);
50 CHECK_EQ(0, ret);
54 // Wrapper to manage the result from libcap2's cap_from_text().
55 typedef scoped_ptr<char, CapTextFreeDeleter> ScopedCapText;
57 // Checks that the set of RES-uids and the set of RES-gids have
58 // one element each and return that element in |resuid| and |resgid|
59 // respectively. It's ok to pass NULL as one or both of the ids.
60 bool GetRESIds(uid_t* resuid, gid_t* resgid) {
61 uid_t ruid, euid, suid;
62 gid_t rgid, egid, sgid;
63 PCHECK(getresuid(&ruid, &euid, &suid) == 0);
64 PCHECK(getresgid(&rgid, &egid, &sgid) == 0);
65 const bool uids_are_equal = (ruid == euid) && (ruid == suid);
66 const bool gids_are_equal = (rgid == egid) && (rgid == sgid);
67 if (!uids_are_equal || !gids_are_equal) return false;
68 if (resuid) *resuid = euid;
69 if (resgid) *resgid = egid;
70 return true;
73 const int kExitSuccess = 0;
75 int ChrootToSelfFdinfo(void*) {
76 RAW_CHECK(chroot("/proc/self/fdinfo/") == 0);
78 // CWD is essentially an implicit file descriptor, so be careful to not
79 // leave it behind.
80 RAW_CHECK(chdir("/") == 0);
81 _exit(kExitSuccess);
84 // chroot() to an empty dir that is "safe". To be safe, it must not contain
85 // any subdirectory (chroot-ing there would allow a chroot escape) and it must
86 // be impossible to create an empty directory there.
87 // We achieve this by doing the following:
88 // 1. We create a new process sharing file system information.
89 // 2. In the child, we chroot to /proc/self/fdinfo/
90 // This is already "safe", since fdinfo/ does not contain another directory and
91 // one cannot create another directory there.
92 // 3. The process dies
93 // After (3) happens, the directory is not available anymore in /proc.
94 bool ChrootToSafeEmptyDir() {
95 // We need to chroot to a fdinfo that is unique to a process and have that
96 // process die.
97 // 1. We don't want to simply fork() because duplicating the page tables is
98 // slow with a big address space.
99 // 2. We do not use a regular thread (that would unshare CLONE_FILES) because
100 // when we are in a PID namespace, we cannot easily get a handle to the
101 // /proc/tid directory for the thread (since /proc may not be aware of the
102 // PID namespace). With a process, we can just use /proc/self.
103 pid_t pid = -1;
104 char stack_buf[PTHREAD_STACK_MIN];
105 #if defined(ARCH_CPU_X86_FAMILY) || defined(ARCH_CPU_ARM_FAMILY) || \
106 defined(ARCH_CPU_MIPS64_FAMILY) || defined(ARCH_CPU_MIPS_FAMILY)
107 // The stack grows downward.
108 void* stack = stack_buf + sizeof(stack_buf);
109 #else
110 #error "Unsupported architecture"
111 #endif
112 pid = clone(ChrootToSelfFdinfo, stack,
113 CLONE_VM | CLONE_VFORK | CLONE_FS | SIGCHLD, nullptr, nullptr,
114 nullptr, nullptr);
115 PCHECK(pid != -1);
117 int status = -1;
118 PCHECK(HANDLE_EINTR(waitpid(pid, &status, 0)) == pid);
120 return WIFEXITED(status) && WEXITSTATUS(status) == kExitSuccess;
123 // CHECK() that an attempt to move to a new user namespace raised an expected
124 // errno.
125 void CheckCloneNewUserErrno(int error) {
126 // EPERM can happen if already in a chroot. EUSERS if too many nested
127 // namespaces are used. EINVAL for kernels that don't support the feature.
128 // Valgrind will ENOSYS unshare().
129 PCHECK(error == EPERM || error == EUSERS || error == EINVAL ||
130 error == ENOSYS);
133 } // namespace.
135 bool Credentials::DropAllCapabilities(int proc_fd) {
136 DCHECK_LE(0, proc_fd);
137 #if !defined(THREAD_SANITIZER)
138 // With TSAN, accept to break the security model as it is a testing
139 // configuration.
140 CHECK(ThreadHelpers::IsSingleThreaded(proc_fd));
141 #endif
143 ScopedCap cap(cap_init());
144 CHECK(cap);
145 PCHECK(0 == cap_set_proc(cap.get()));
146 CHECK(!HasAnyCapability());
147 // We never let this function fail.
148 return true;
151 bool Credentials::DropAllCapabilities() {
152 base::ScopedFD proc_fd(ProcUtil::OpenProc());
153 return Credentials::DropAllCapabilities(proc_fd.get());
156 bool Credentials::HasAnyCapability() {
157 ScopedCap current_cap(cap_get_proc());
158 CHECK(current_cap);
159 ScopedCap empty_cap(cap_init());
160 CHECK(empty_cap);
161 return cap_compare(current_cap.get(), empty_cap.get()) != 0;
164 scoped_ptr<std::string> Credentials::GetCurrentCapString() {
165 ScopedCap current_cap(cap_get_proc());
166 CHECK(current_cap);
167 ScopedCapText cap_text(cap_to_text(current_cap.get(), NULL));
168 CHECK(cap_text);
169 return scoped_ptr<std::string> (new std::string(cap_text.get()));
172 // static
173 bool Credentials::CanCreateProcessInNewUserNS() {
174 // Valgrind will let clone(2) pass-through, but doesn't support unshare(),
175 // so always consider UserNS unsupported there.
176 if (IsRunningOnValgrind()) {
177 return false;
180 #if defined(THREAD_SANITIZER)
181 // With TSAN, processes will always have threads running and can never
182 // enter a new user namespace with MoveToNewUserNS().
183 return false;
184 #endif
186 // This is roughly a fork().
187 const pid_t pid = sys_clone(CLONE_NEWUSER | SIGCHLD, 0, 0, 0, 0);
189 if (pid == -1) {
190 CheckCloneNewUserErrno(errno);
191 return false;
194 // The parent process could have had threads. In the child, these threads
195 // have disappeared. Make sure to not do anything in the child, as this is a
196 // fragile execution environment.
197 if (pid == 0) {
198 _exit(kExitSuccess);
201 // Always reap the child.
202 int status = -1;
203 PCHECK(HANDLE_EINTR(waitpid(pid, &status, 0)) == pid);
204 CHECK(WIFEXITED(status));
205 CHECK_EQ(kExitSuccess, WEXITSTATUS(status));
207 // clone(2) succeeded, we can use CLONE_NEWUSER.
208 return true;
211 bool Credentials::MoveToNewUserNS() {
212 uid_t uid;
213 gid_t gid;
214 if (!GetRESIds(&uid, &gid)) {
215 // If all the uids (or gids) are not equal to each other, the security
216 // model will most likely confuse the caller, abort.
217 DVLOG(1) << "uids or gids differ!";
218 return false;
220 int ret = unshare(CLONE_NEWUSER);
221 if (ret) {
222 const int unshare_errno = errno;
223 VLOG(1) << "Looks like unprivileged CLONE_NEWUSER may not be available "
224 << "on this kernel.";
225 CheckCloneNewUserErrno(unshare_errno);
226 return false;
229 if (NamespaceUtils::KernelSupportsDenySetgroups()) {
230 PCHECK(NamespaceUtils::DenySetgroups());
233 // The current {r,e,s}{u,g}id is now an overflow id (c.f.
234 // /proc/sys/kernel/overflowuid). Setup the uid and gid maps.
235 DCHECK(GetRESIds(NULL, NULL));
236 const char kGidMapFile[] = "/proc/self/gid_map";
237 const char kUidMapFile[] = "/proc/self/uid_map";
238 PCHECK(NamespaceUtils::WriteToIdMapFile(kGidMapFile, gid));
239 PCHECK(NamespaceUtils::WriteToIdMapFile(kUidMapFile, uid));
240 DCHECK(GetRESIds(NULL, NULL));
241 return true;
244 bool Credentials::DropFileSystemAccess(int proc_fd) {
245 CHECK_LE(0, proc_fd);
247 CHECK(ChrootToSafeEmptyDir());
248 CHECK(!base::DirectoryExists(base::FilePath("/proc")));
249 CHECK(!ProcUtil::HasOpenDirectory(proc_fd));
250 // We never let this function fail.
251 return true;
254 } // namespace sandbox.