Adding Peter Thatcher to the owners file.
[chromium-blink-merge.git] / sandbox / linux / services / credentials.cc
blob23e87eae1f5e735fdbdfe96b7510c5eac293e821
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/syscall.h>
11 #include <sys/types.h>
12 #include <sys/wait.h>
13 #include <unistd.h>
15 #include "base/basictypes.h"
16 #include "base/bind.h"
17 #include "base/files/file_path.h"
18 #include "base/files/file_util.h"
19 #include "base/logging.h"
20 #include "base/posix/eintr_wrapper.h"
21 #include "base/process/launch.h"
22 #include "base/template_util.h"
23 #include "base/third_party/valgrind/valgrind.h"
24 #include "build/build_config.h"
25 #include "sandbox/linux/services/namespace_utils.h"
26 #include "sandbox/linux/services/proc_util.h"
27 #include "sandbox/linux/services/syscall_wrappers.h"
28 #include "sandbox/linux/services/thread_helpers.h"
29 #include "sandbox/linux/system_headers/capability.h"
31 namespace sandbox {
33 namespace {
35 bool IsRunningOnValgrind() { return RUNNING_ON_VALGRIND; }
37 // Checks that the set of RES-uids and the set of RES-gids have
38 // one element each and return that element in |resuid| and |resgid|
39 // respectively. It's ok to pass NULL as one or both of the ids.
40 bool GetRESIds(uid_t* resuid, gid_t* resgid) {
41 uid_t ruid, euid, suid;
42 gid_t rgid, egid, sgid;
43 PCHECK(sys_getresuid(&ruid, &euid, &suid) == 0);
44 PCHECK(sys_getresgid(&rgid, &egid, &sgid) == 0);
45 const bool uids_are_equal = (ruid == euid) && (ruid == suid);
46 const bool gids_are_equal = (rgid == egid) && (rgid == sgid);
47 if (!uids_are_equal || !gids_are_equal) return false;
48 if (resuid) *resuid = euid;
49 if (resgid) *resgid = egid;
50 return true;
53 const int kExitSuccess = 0;
55 int ChrootToSelfFdinfo(void*) {
56 RAW_CHECK(sys_chroot("/proc/self/fdinfo/") == 0);
58 // CWD is essentially an implicit file descriptor, so be careful to not
59 // leave it behind.
60 RAW_CHECK(chdir("/") == 0);
61 _exit(kExitSuccess);
64 // chroot() to an empty dir that is "safe". To be safe, it must not contain
65 // any subdirectory (chroot-ing there would allow a chroot escape) and it must
66 // be impossible to create an empty directory there.
67 // We achieve this by doing the following:
68 // 1. We create a new process sharing file system information.
69 // 2. In the child, we chroot to /proc/self/fdinfo/
70 // This is already "safe", since fdinfo/ does not contain another directory and
71 // one cannot create another directory there.
72 // 3. The process dies
73 // After (3) happens, the directory is not available anymore in /proc.
74 bool ChrootToSafeEmptyDir() {
75 // We need to chroot to a fdinfo that is unique to a process and have that
76 // process die.
77 // 1. We don't want to simply fork() because duplicating the page tables is
78 // slow with a big address space.
79 // 2. We do not use a regular thread (that would unshare CLONE_FILES) because
80 // when we are in a PID namespace, we cannot easily get a handle to the
81 // /proc/tid directory for the thread (since /proc may not be aware of the
82 // PID namespace). With a process, we can just use /proc/self.
83 pid_t pid = -1;
84 char stack_buf[PTHREAD_STACK_MIN];
85 #if defined(ARCH_CPU_X86_FAMILY) || defined(ARCH_CPU_ARM_FAMILY) || \
86 defined(ARCH_CPU_MIPS64_FAMILY) || defined(ARCH_CPU_MIPS_FAMILY)
87 // The stack grows downward.
88 void* stack = stack_buf + sizeof(stack_buf);
89 #else
90 #error "Unsupported architecture"
91 #endif
92 pid = clone(ChrootToSelfFdinfo, stack,
93 CLONE_VM | CLONE_VFORK | CLONE_FS | SIGCHLD, nullptr, nullptr,
94 nullptr, nullptr);
95 PCHECK(pid != -1);
97 int status = -1;
98 PCHECK(HANDLE_EINTR(waitpid(pid, &status, 0)) == pid);
100 return WIFEXITED(status) && WEXITSTATUS(status) == kExitSuccess;
103 // CHECK() that an attempt to move to a new user namespace raised an expected
104 // errno.
105 void CheckCloneNewUserErrno(int error) {
106 // EPERM can happen if already in a chroot. EUSERS if too many nested
107 // namespaces are used. EINVAL for kernels that don't support the feature.
108 // Valgrind will ENOSYS unshare().
109 PCHECK(error == EPERM || error == EUSERS || error == EINVAL ||
110 error == ENOSYS);
113 // Converts a Capability to the corresponding Linux CAP_XXX value.
114 int CapabilityToKernelValue(Credentials::Capability cap) {
115 switch (cap) {
116 case Credentials::Capability::SYS_CHROOT:
117 return CAP_SYS_CHROOT;
118 case Credentials::Capability::SYS_ADMIN:
119 return CAP_SYS_ADMIN;
122 LOG(FATAL) << "Invalid Capability: " << static_cast<int>(cap);
123 return 0;
126 } // namespace.
128 // static
129 bool Credentials::DropAllCapabilities(int proc_fd) {
130 if (!SetCapabilities(proc_fd, std::vector<Capability>())) {
131 return false;
134 CHECK(!HasAnyCapability());
135 return true;
138 // static
139 bool Credentials::DropAllCapabilities() {
140 base::ScopedFD proc_fd(ProcUtil::OpenProc());
141 return Credentials::DropAllCapabilities(proc_fd.get());
144 // static
145 bool Credentials::DropAllCapabilitiesOnCurrentThread() {
146 return SetCapabilitiesOnCurrentThread(std::vector<Capability>());
149 // static
150 bool Credentials::SetCapabilitiesOnCurrentThread(
151 const std::vector<Capability>& caps) {
152 struct cap_hdr hdr = {};
153 hdr.version = _LINUX_CAPABILITY_VERSION_3;
154 struct cap_data data[_LINUX_CAPABILITY_U32S_3] = {{}};
156 // Initially, cap has no capability flags set. Enable the effective and
157 // permitted flags only for the requested capabilities.
158 for (const Capability cap : caps) {
159 const int cap_num = CapabilityToKernelValue(cap);
160 const size_t index = CAP_TO_INDEX(cap_num);
161 const uint32_t mask = CAP_TO_MASK(cap_num);
162 data[index].effective |= mask;
163 data[index].permitted |= mask;
166 return sys_capset(&hdr, data) == 0;
169 // static
170 bool Credentials::SetCapabilities(int proc_fd,
171 const std::vector<Capability>& caps) {
172 DCHECK_LE(0, proc_fd);
174 #if !defined(THREAD_SANITIZER)
175 // With TSAN, accept to break the security model as it is a testing
176 // configuration.
177 CHECK(ThreadHelpers::IsSingleThreaded(proc_fd));
178 #endif
180 return SetCapabilitiesOnCurrentThread(caps);
183 bool Credentials::HasAnyCapability() {
184 struct cap_hdr hdr = {};
185 hdr.version = _LINUX_CAPABILITY_VERSION_3;
186 struct cap_data data[_LINUX_CAPABILITY_U32S_3] = {{}};
188 PCHECK(sys_capget(&hdr, data) == 0);
190 for (size_t i = 0; i < arraysize(data); ++i) {
191 if (data[i].effective || data[i].permitted || data[i].inheritable) {
192 return true;
196 return false;
199 bool Credentials::HasCapability(Capability cap) {
200 struct cap_hdr hdr = {};
201 hdr.version = _LINUX_CAPABILITY_VERSION_3;
202 struct cap_data data[_LINUX_CAPABILITY_U32S_3] = {{}};
204 PCHECK(sys_capget(&hdr, data) == 0);
206 const int cap_num = CapabilityToKernelValue(cap);
207 const size_t index = CAP_TO_INDEX(cap_num);
208 const uint32_t mask = CAP_TO_MASK(cap_num);
210 return (data[index].effective | data[index].permitted |
211 data[index].inheritable) &
212 mask;
215 // static
216 bool Credentials::CanCreateProcessInNewUserNS() {
217 // Valgrind will let clone(2) pass-through, but doesn't support unshare(),
218 // so always consider UserNS unsupported there.
219 if (IsRunningOnValgrind()) {
220 return false;
223 #if defined(THREAD_SANITIZER)
224 // With TSAN, processes will always have threads running and can never
225 // enter a new user namespace with MoveToNewUserNS().
226 return false;
227 #endif
229 // This is roughly a fork().
230 const pid_t pid = sys_clone(CLONE_NEWUSER | SIGCHLD, 0, 0, 0, 0);
232 if (pid == -1) {
233 CheckCloneNewUserErrno(errno);
234 return false;
237 // The parent process could have had threads. In the child, these threads
238 // have disappeared. Make sure to not do anything in the child, as this is a
239 // fragile execution environment.
240 if (pid == 0) {
241 _exit(kExitSuccess);
244 // Always reap the child.
245 int status = -1;
246 PCHECK(HANDLE_EINTR(waitpid(pid, &status, 0)) == pid);
247 CHECK(WIFEXITED(status));
248 CHECK_EQ(kExitSuccess, WEXITSTATUS(status));
250 // clone(2) succeeded, we can use CLONE_NEWUSER.
251 return true;
254 bool Credentials::MoveToNewUserNS() {
255 uid_t uid;
256 gid_t gid;
257 if (!GetRESIds(&uid, &gid)) {
258 // If all the uids (or gids) are not equal to each other, the security
259 // model will most likely confuse the caller, abort.
260 DVLOG(1) << "uids or gids differ!";
261 return false;
263 int ret = sys_unshare(CLONE_NEWUSER);
264 if (ret) {
265 const int unshare_errno = errno;
266 VLOG(1) << "Looks like unprivileged CLONE_NEWUSER may not be available "
267 << "on this kernel.";
268 CheckCloneNewUserErrno(unshare_errno);
269 return false;
272 if (NamespaceUtils::KernelSupportsDenySetgroups()) {
273 PCHECK(NamespaceUtils::DenySetgroups());
276 // The current {r,e,s}{u,g}id is now an overflow id (c.f.
277 // /proc/sys/kernel/overflowuid). Setup the uid and gid maps.
278 DCHECK(GetRESIds(NULL, NULL));
279 const char kGidMapFile[] = "/proc/self/gid_map";
280 const char kUidMapFile[] = "/proc/self/uid_map";
281 PCHECK(NamespaceUtils::WriteToIdMapFile(kGidMapFile, gid));
282 PCHECK(NamespaceUtils::WriteToIdMapFile(kUidMapFile, uid));
283 DCHECK(GetRESIds(NULL, NULL));
284 return true;
287 bool Credentials::DropFileSystemAccess(int proc_fd) {
288 CHECK_LE(0, proc_fd);
290 CHECK(ChrootToSafeEmptyDir());
291 CHECK(!base::DirectoryExists(base::FilePath("/proc")));
292 CHECK(!ProcUtil::HasOpenDirectory(proc_fd));
293 // We never let this function fail.
294 return true;
297 } // namespace sandbox.