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/capability.h>
11 #include <sys/syscall.h>
12 #include <sys/types.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"
35 bool IsRunningOnValgrind() { return RUNNING_ON_VALGRIND
; }
37 struct CapFreeDeleter
{
38 inline void operator()(cap_t cap
) const {
39 int ret
= cap_free(cap
);
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
);
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
;
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
80 RAW_CHECK(chdir("/") == 0);
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
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.
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
);
110 #error "Unsupported architecture"
112 pid
= clone(ChrootToSelfFdinfo
, stack
,
113 CLONE_VM
| CLONE_VFORK
| CLONE_FS
| SIGCHLD
, nullptr, nullptr,
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
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
||
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
140 CHECK(ThreadHelpers::IsSingleThreaded(proc_fd
));
143 ScopedCap
cap(cap_init());
145 PCHECK(0 == cap_set_proc(cap
.get()));
146 CHECK(!HasAnyCapability());
147 // We never let this function fail.
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());
159 ScopedCap
empty_cap(cap_init());
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());
167 ScopedCapText
cap_text(cap_to_text(current_cap
.get(), NULL
));
169 return scoped_ptr
<std::string
> (new std::string(cap_text
.get()));
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()) {
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().
186 // This is roughly a fork().
187 const pid_t pid
= sys_clone(CLONE_NEWUSER
| SIGCHLD
, 0, 0, 0, 0);
190 CheckCloneNewUserErrno(errno
);
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.
201 // Always reap the child.
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.
211 bool Credentials::MoveToNewUserNS() {
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!";
220 int ret
= unshare(CLONE_NEWUSER
);
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
);
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
));
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.
254 } // namespace sandbox.