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/basictypes.h"
14 #include "base/file_util.h"
15 #include "base/files/scoped_file.h"
16 #include "base/logging.h"
17 #include "base/posix/eintr_wrapper.h"
19 #if !defined(PR_SET_PTRACER_ANY)
20 #define PR_SET_PTRACER_ANY ((unsigned long)-1)
23 #if !defined(PR_SET_PTRACER)
24 #define PR_SET_PTRACER 0x59616d61
31 // Enable or disable the Yama ptracers restrictions.
32 // Return false if Yama is not present on this kernel.
33 bool SetYamaPtracersRestriction(bool enable_restrictions
) {
34 unsigned long set_ptracer_arg
;
35 if (enable_restrictions
) {
38 set_ptracer_arg
= PR_SET_PTRACER_ANY
;
41 const int ret
= prctl(PR_SET_PTRACER
, set_ptracer_arg
);
42 const int prctl_errno
= errno
;
47 // ENOSYS or EINVAL means Yama is not in the current kernel.
48 CHECK(ENOSYS
== prctl_errno
|| EINVAL
== prctl_errno
);
53 bool CanAccessProcFS() {
54 static const char kProcfsKernelSysPath
[] = "/proc/sys/kernel/";
55 int ret
= access(kProcfsKernelSysPath
, F_OK
);
65 bool Yama::RestrictPtracersToAncestors() {
66 return SetYamaPtracersRestriction(true /* enable_restrictions */);
70 bool Yama::DisableYamaRestrictions() {
71 return SetYamaPtracersRestriction(false /* enable_restrictions */);
75 int Yama::GetStatus() {
76 if (!CanAccessProcFS()) {
80 static const char kPtraceScopePath
[] = "/proc/sys/kernel/yama/ptrace_scope";
82 base::ScopedFD
yama_scope(HANDLE_EINTR(open(kPtraceScopePath
, O_RDONLY
)));
84 if (!yama_scope
.is_valid()) {
85 const int open_errno
= errno
;
86 DCHECK(ENOENT
== open_errno
);
87 // The status is known, yama is not present.
91 char yama_scope_value
= 0;
92 ssize_t num_read
= HANDLE_EINTR(read(yama_scope
.get(), &yama_scope_value
, 1));
93 PCHECK(1 == num_read
);
95 switch (yama_scope_value
) {
97 return STATUS_KNOWN
| STATUS_PRESENT
;
99 return STATUS_KNOWN
| STATUS_PRESENT
| STATUS_ENFORCING
;
102 return STATUS_KNOWN
| STATUS_PRESENT
| STATUS_ENFORCING
|
103 STATUS_STRICT_ENFORCING
;
111 bool Yama::IsPresent() { return GetStatus() & STATUS_PRESENT
; }
114 bool Yama::IsEnforcing() { return GetStatus() & STATUS_ENFORCING
; }
116 } // namespace sandbox