1 // Copyright 2014 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/yama.h"
10 #include <sys/types.h>
13 #include "base/files/file_util.h"
14 #include "base/files/scoped_file.h"
15 #include "base/logging.h"
16 #include "base/posix/eintr_wrapper.h"
18 #if !defined(PR_SET_PTRACER_ANY)
19 #define PR_SET_PTRACER_ANY ((unsigned long)-1)
22 #if !defined(PR_SET_PTRACER)
23 #define PR_SET_PTRACER 0x59616d61
30 // Enable or disable the Yama ptracers restrictions.
31 // Return false if Yama is not present on this kernel.
32 bool SetYamaPtracersRestriction(bool enable_restrictions
) {
33 unsigned long set_ptracer_arg
;
34 if (enable_restrictions
) {
37 set_ptracer_arg
= PR_SET_PTRACER_ANY
;
40 const int ret
= prctl(PR_SET_PTRACER
, set_ptracer_arg
);
41 const int prctl_errno
= errno
;
46 // ENOSYS or EINVAL means Yama is not in the current kernel.
47 CHECK(ENOSYS
== prctl_errno
|| EINVAL
== prctl_errno
);
52 bool CanAccessProcFS() {
53 static const char kProcfsKernelSysPath
[] = "/proc/sys/kernel/";
54 int ret
= access(kProcfsKernelSysPath
, F_OK
);
64 bool Yama::RestrictPtracersToAncestors() {
65 return SetYamaPtracersRestriction(true /* enable_restrictions */);
69 bool Yama::DisableYamaRestrictions() {
70 return SetYamaPtracersRestriction(false /* enable_restrictions */);
74 int Yama::GetStatus() {
75 if (!CanAccessProcFS()) {
79 static const char kPtraceScopePath
[] = "/proc/sys/kernel/yama/ptrace_scope";
81 base::ScopedFD
yama_scope(HANDLE_EINTR(open(kPtraceScopePath
, O_RDONLY
)));
83 if (!yama_scope
.is_valid()) {
84 const int open_errno
= errno
;
85 DCHECK(ENOENT
== open_errno
);
86 // The status is known, yama is not present.
90 char yama_scope_value
= 0;
91 ssize_t num_read
= HANDLE_EINTR(read(yama_scope
.get(), &yama_scope_value
, 1));
92 PCHECK(1 == num_read
);
94 switch (yama_scope_value
) {
96 return STATUS_KNOWN
| STATUS_PRESENT
;
98 return STATUS_KNOWN
| STATUS_PRESENT
| STATUS_ENFORCING
;
101 return STATUS_KNOWN
| STATUS_PRESENT
| STATUS_ENFORCING
|
102 STATUS_STRICT_ENFORCING
;
110 bool Yama::IsPresent() { return GetStatus() & STATUS_PRESENT
; }
113 bool Yama::IsEnforcing() { return GetStatus() & STATUS_ENFORCING
; }
115 } // namespace sandbox