1 /*
2  * Copyright (C) 2017 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include "security.h"
18 
19 #include <errno.h>
20 #include <fcntl.h>
21 #include <linux/perf_event.h>
22 #include <selinux/selinux.h>
23 #include <sys/ioctl.h>
24 #include <sys/syscall.h>
25 #include <unistd.h>
26 
27 #include <fstream>
28 
29 #include <android-base/logging.h>
30 #include <android-base/properties.h>
31 #include <android-base/unique_fd.h>
32 
33 using android::base::unique_fd;
34 using android::base::SetProperty;
35 
36 namespace android {
37 namespace init {
38 
SetHighestAvailableOptionValue(const std::string & path,int min,int max)39 static bool SetHighestAvailableOptionValue(const std::string& path, int min, int max) {
40     std::ifstream inf(path, std::fstream::in);
41     if (!inf) {
42         LOG(ERROR) << "Cannot open for reading: " << path;
43         return false;
44     }
45 
46     int current = max;
47     while (current >= min) {
48         // try to write out new value
49         std::string str_val = std::to_string(current);
50         std::ofstream of(path, std::fstream::out);
51         if (!of) {
52             LOG(ERROR) << "Cannot open for writing: " << path;
53             return false;
54         }
55         of << str_val << std::endl;
56         of.close();
57 
58         // check to make sure it was recorded
59         inf.seekg(0);
60         std::string str_rec;
61         inf >> str_rec;
62         if (str_val.compare(str_rec) == 0) {
63             break;
64         }
65         current--;
66     }
67     inf.close();
68 
69     if (current < min) {
70         LOG(ERROR) << "Unable to set minimum option value " << min << " in " << path;
71         return false;
72     }
73     return true;
74 }
75 
76 #define MMAP_RND_PATH "/proc/sys/vm/mmap_rnd_bits"
77 #define MMAP_RND_COMPAT_PATH "/proc/sys/vm/mmap_rnd_compat_bits"
78 
SetMmapRndBitsMin(int start,int min,bool compat)79 static bool SetMmapRndBitsMin(int start, int min, bool compat) {
80     std::string path;
81     if (compat) {
82         path = MMAP_RND_COMPAT_PATH;
83     } else {
84         path = MMAP_RND_PATH;
85     }
86 
87     return SetHighestAvailableOptionValue(path, min, start);
88 }
89 
90 // Set /proc/sys/vm/mmap_rnd_bits and potentially
91 // /proc/sys/vm/mmap_rnd_compat_bits to the maximum supported values.
92 // Returns -1 if unable to set these to an acceptable value.
93 //
94 // To support this sysctl, the following upstream commits are needed:
95 //
96 // d07e22597d1d mm: mmap: add new /proc tunable for mmap_base ASLR
97 // e0c25d958f78 arm: mm: support ARCH_MMAP_RND_BITS
98 // 8f0d3aa9de57 arm64: mm: support ARCH_MMAP_RND_BITS
99 // 9e08f57d684a x86: mm: support ARCH_MMAP_RND_BITS
100 // ec9ee4acd97c drivers: char: random: add get_random_long()
101 // 5ef11c35ce86 mm: ASLR: use get_random_long()
SetMmapRndBitsAction(const BuiltinArguments &)102 Result<void> SetMmapRndBitsAction(const BuiltinArguments&) {
103 // values are arch-dependent
104 #if defined(USER_MODE_LINUX)
105     // uml does not support mmap_rnd_bits
106     return {};
107 #elif defined(__aarch64__)
108     // arm64 supports 18 - 33 bits depending on pagesize and VA_SIZE
109     if (SetMmapRndBitsMin(33, 24, false) && SetMmapRndBitsMin(16, 16, true)) {
110         return {};
111     }
112 #elif defined(__x86_64__)
113     // x86_64 supports 28 - 32 bits
114     if (SetMmapRndBitsMin(32, 32, false) && SetMmapRndBitsMin(16, 16, true)) {
115         return {};
116     }
117 #elif defined(__arm__) || defined(__i386__)
118     // check to see if we're running on 64-bit kernel
119     bool h64 = !access(MMAP_RND_COMPAT_PATH, F_OK);
120     // supported 32-bit architecture must have 16 bits set
121     if (SetMmapRndBitsMin(16, 16, h64)) {
122         return {};
123     }
124 #else
125     LOG(ERROR) << "Unknown architecture";
126 #endif
127 
128     LOG(FATAL) << "Unable to set adequate mmap entropy value!";
129     return Error();
130 }
131 
132 #define KPTR_RESTRICT_PATH "/proc/sys/kernel/kptr_restrict"
133 #define KPTR_RESTRICT_MINVALUE 2
134 #define KPTR_RESTRICT_MAXVALUE 4
135 
136 // Set kptr_restrict to the highest available level.
137 //
138 // Aborts if unable to set this to an acceptable value.
SetKptrRestrictAction(const BuiltinArguments &)139 Result<void> SetKptrRestrictAction(const BuiltinArguments&) {
140     std::string path = KPTR_RESTRICT_PATH;
141 
142     if (!SetHighestAvailableOptionValue(path, KPTR_RESTRICT_MINVALUE, KPTR_RESTRICT_MAXVALUE)) {
143         LOG(FATAL) << "Unable to set adequate kptr_restrict value!";
144         return Error();
145     }
146     return {};
147 }
148 
149 // Test for whether the kernel has SELinux hooks for the perf_event_open()
150 // syscall. If the hooks are present, we can stop using the other permission
151 // mechanism (perf_event_paranoid sysctl), and use only the SELinux policy to
152 // control access to the syscall. The hooks are expected on all Android R
153 // release kernels, but might be absent on devices that upgrade while keeping an
154 // older kernel.
155 //
156 // There is no direct/synchronous way of finding out that a syscall failed due
157 // to SELinux. Therefore we test for a combination of a success and a failure
158 // that are explained by the platform's SELinux policy for the "init" domain:
159 // * cpu-scoped perf_event is allowed
160 // * ioctl() on the event fd is disallowed with EACCES
161 //
162 // Since init has CAP_SYS_ADMIN, these tests are not affected by the system-wide
163 // perf_event_paranoid sysctl.
164 //
165 // If the SELinux hooks are detected, a special sysprop
166 // (sys.init.perf_lsm_hooks) is set, which translates to a modification of
167 // perf_event_paranoid (through init.rc sysprop actions).
168 //
169 // TODO(b/137092007): this entire test can be removed once the platform stops
170 // supporting kernels that precede the perf_event_open hooks (Android common
171 // kernels 4.4 and 4.9).
TestPerfEventSelinuxAction(const BuiltinArguments &)172 Result<void> TestPerfEventSelinuxAction(const BuiltinArguments&) {
173     // Special case: for *development devices* that boot with permissive
174     // SELinux, treat the LSM hooks as present for the effect of lowering the
175     // perf_event_paranoid sysctl. The sysprop is reused for pragmatic reasons,
176     // as there no existing way for init rules to check for permissive boot at
177     // the time of writing.
178     if (ALLOW_PERMISSIVE_SELINUX) {
179         if (!security_getenforce()) {
180             LOG(INFO) << "Permissive SELinux boot, forcing sys.init.perf_lsm_hooks to 1.";
181             SetProperty("sys.init.perf_lsm_hooks", "1");
182             return {};
183         }
184     }
185 
186     // Use a trivial event that will be configured, but not started.
187     struct perf_event_attr pe = {
188             .type = PERF_TYPE_SOFTWARE,
189             .size = sizeof(struct perf_event_attr),
190             .config = PERF_COUNT_SW_TASK_CLOCK,
191             .disabled = 1,
192             .exclude_kernel = 1,
193     };
194 
195     // Open the above event targeting cpu 0. (EINTR not possible.)
196     unique_fd fd(static_cast<int>(syscall(__NR_perf_event_open, &pe, /*pid=*/-1,
197                                           /*cpu=*/0,
198                                           /*group_fd=*/-1, /*flags=*/0)));
199     if (fd == -1) {
200         PLOG(ERROR) << "Unexpected perf_event_open error";
201         return {};
202     }
203 
204     int ioctl_ret = ioctl(fd, PERF_EVENT_IOC_RESET);
205     if (ioctl_ret != -1) {
206         // Success implies that the kernel doesn't have the hooks.
207         return {};
208     } else if (errno != EACCES) {
209         PLOG(ERROR) << "Unexpected perf_event ioctl error";
210         return {};
211     }
212 
213     // Conclude that the SELinux hooks are present.
214     SetProperty("sys.init.perf_lsm_hooks", "1");
215     return {};
216 }
217 
218 }  // namespace init
219 }  // namespace android
220