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"
10 #include <sys/syscall.h>
11 #include <sys/types.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"
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
;
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
60 RAW_CHECK(chdir("/") == 0);
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
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.
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
);
90 #error "Unsupported architecture"
92 pid
= clone(ChrootToSelfFdinfo
, stack
,
93 CLONE_VM
| CLONE_VFORK
| CLONE_FS
| SIGCHLD
, nullptr, nullptr,
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
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
||
113 // Converts a Capability to the corresponding Linux CAP_XXX value.
114 int CapabilityToKernelValue(Credentials::Capability 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
);
129 bool Credentials::DropAllCapabilities(int proc_fd
) {
130 if (!SetCapabilities(proc_fd
, std::vector
<Capability
>())) {
134 CHECK(!HasAnyCapability());
139 bool Credentials::DropAllCapabilities() {
140 base::ScopedFD
proc_fd(ProcUtil::OpenProc());
141 return Credentials::DropAllCapabilities(proc_fd
.get());
145 bool Credentials::DropAllCapabilitiesOnCurrentThread() {
146 return SetCapabilitiesOnCurrentThread(std::vector
<Capability
>());
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;
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
177 CHECK(ThreadHelpers::IsSingleThreaded(proc_fd
));
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
) {
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
) &
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()) {
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().
229 // This is roughly a fork().
230 const pid_t pid
= sys_clone(CLONE_NEWUSER
| SIGCHLD
, 0, 0, 0, 0);
233 CheckCloneNewUserErrno(errno
);
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.
244 // Always reap the child.
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.
254 bool Credentials::MoveToNewUserNS() {
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!";
263 int ret
= sys_unshare(CLONE_NEWUSER
);
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
);
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
));
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.
297 } // namespace sandbox.