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 <sys/ioctl.h>
23 #include <sys/syscall.h>
24 #include <unistd.h>
25
26 #include <fstream>
27
28 #include <android-base/logging.h>
29 #include <android-base/properties.h>
30 #include <android-base/unique_fd.h>
31
32 using android::base::unique_fd;
33 using android::base::SetProperty;
34
35 namespace android {
36 namespace init {
37
38 // Writes 512 bytes of output from Hardware RNG (/dev/hw_random, backed
39 // by Linux kernel's hw_random framework) into Linux RNG's via /dev/urandom.
40 // Does nothing if Hardware RNG is not present.
41 //
42 // Since we don't yet trust the quality of Hardware RNG, these bytes are not
43 // mixed into the primary pool of Linux RNG and the entropy estimate is left
44 // unmodified.
45 //
46 // If the HW RNG device /dev/hw_random is present, we require that at least
47 // 512 bytes read from it are written into Linux RNG. QA is expected to catch
48 // devices/configurations where these I/O operations are blocking for a long
49 // time. We do not reboot or halt on failures, as this is a best-effort
50 // attempt.
MixHwrngIntoLinuxRngAction(const BuiltinArguments &)51 Result<void> MixHwrngIntoLinuxRngAction(const BuiltinArguments&) {
52 unique_fd hwrandom_fd(
53 TEMP_FAILURE_RETRY(open("/dev/hw_random", O_RDONLY | O_NOFOLLOW | O_CLOEXEC)));
54 if (hwrandom_fd == -1) {
55 if (errno == ENOENT) {
56 LOG(INFO) << "/dev/hw_random not found";
57 // It's not an error to not have a Hardware RNG.
58 return {};
59 }
60 return ErrnoError() << "Failed to open /dev/hw_random";
61 }
62
63 unique_fd urandom_fd(
64 TEMP_FAILURE_RETRY(open("/dev/urandom", O_WRONLY | O_NOFOLLOW | O_CLOEXEC)));
65 if (urandom_fd == -1) {
66 return ErrnoError() << "Failed to open /dev/urandom";
67 }
68
69 char buf[512];
70 size_t total_bytes_written = 0;
71 while (total_bytes_written < sizeof(buf)) {
72 ssize_t chunk_size =
73 TEMP_FAILURE_RETRY(read(hwrandom_fd, buf, sizeof(buf) - total_bytes_written));
74 if (chunk_size == -1) {
75 return ErrnoError() << "Failed to read from /dev/hw_random";
76 } else if (chunk_size == 0) {
77 return Error() << "Failed to read from /dev/hw_random: EOF";
78 }
79
80 chunk_size = TEMP_FAILURE_RETRY(write(urandom_fd, buf, chunk_size));
81 if (chunk_size == -1) {
82 return ErrnoError() << "Failed to write to /dev/urandom";
83 }
84 total_bytes_written += chunk_size;
85 }
86
87 LOG(INFO) << "Mixed " << total_bytes_written << " bytes from /dev/hw_random into /dev/urandom";
88 return {};
89 }
90
SetHighestAvailableOptionValue(const std::string & path,int min,int max)91 static bool SetHighestAvailableOptionValue(const std::string& path, int min, int max) {
92 std::ifstream inf(path, std::fstream::in);
93 if (!inf) {
94 LOG(ERROR) << "Cannot open for reading: " << path;
95 return false;
96 }
97
98 int current = max;
99 while (current >= min) {
100 // try to write out new value
101 std::string str_val = std::to_string(current);
102 std::ofstream of(path, std::fstream::out);
103 if (!of) {
104 LOG(ERROR) << "Cannot open for writing: " << path;
105 return false;
106 }
107 of << str_val << std::endl;
108 of.close();
109
110 // check to make sure it was recorded
111 inf.seekg(0);
112 std::string str_rec;
113 inf >> str_rec;
114 if (str_val.compare(str_rec) == 0) {
115 break;
116 }
117 current--;
118 }
119 inf.close();
120
121 if (current < min) {
122 LOG(ERROR) << "Unable to set minimum option value " << min << " in " << path;
123 return false;
124 }
125 return true;
126 }
127
128 #define MMAP_RND_PATH "/proc/sys/vm/mmap_rnd_bits"
129 #define MMAP_RND_COMPAT_PATH "/proc/sys/vm/mmap_rnd_compat_bits"
130
131 // __attribute__((unused)) due to lack of mips support: see mips block in SetMmapRndBitsAction
SetMmapRndBitsMin(int start,int min,bool compat)132 static bool __attribute__((unused)) SetMmapRndBitsMin(int start, int min, bool compat) {
133 std::string path;
134 if (compat) {
135 path = MMAP_RND_COMPAT_PATH;
136 } else {
137 path = MMAP_RND_PATH;
138 }
139
140 return SetHighestAvailableOptionValue(path, min, start);
141 }
142
143 // Set /proc/sys/vm/mmap_rnd_bits and potentially
144 // /proc/sys/vm/mmap_rnd_compat_bits to the maximum supported values.
145 // Returns -1 if unable to set these to an acceptable value.
146 //
147 // To support this sysctl, the following upstream commits are needed:
148 //
149 // d07e22597d1d mm: mmap: add new /proc tunable for mmap_base ASLR
150 // e0c25d958f78 arm: mm: support ARCH_MMAP_RND_BITS
151 // 8f0d3aa9de57 arm64: mm: support ARCH_MMAP_RND_BITS
152 // 9e08f57d684a x86: mm: support ARCH_MMAP_RND_BITS
153 // ec9ee4acd97c drivers: char: random: add get_random_long()
154 // 5ef11c35ce86 mm: ASLR: use get_random_long()
SetMmapRndBitsAction(const BuiltinArguments &)155 Result<void> SetMmapRndBitsAction(const BuiltinArguments&) {
156 // values are arch-dependent
157 #if defined(USER_MODE_LINUX)
158 // uml does not support mmap_rnd_bits
159 return {};
160 #elif defined(__aarch64__)
161 // arm64 supports 18 - 33 bits depending on pagesize and VA_SIZE
162 if (SetMmapRndBitsMin(33, 24, false) && SetMmapRndBitsMin(16, 16, true)) {
163 return {};
164 }
165 #elif defined(__x86_64__)
166 // x86_64 supports 28 - 32 bits
167 if (SetMmapRndBitsMin(32, 32, false) && SetMmapRndBitsMin(16, 16, true)) {
168 return {};
169 }
170 #elif defined(__arm__) || defined(__i386__)
171 // check to see if we're running on 64-bit kernel
172 bool h64 = !access(MMAP_RND_COMPAT_PATH, F_OK);
173 // supported 32-bit architecture must have 16 bits set
174 if (SetMmapRndBitsMin(16, 16, h64)) {
175 return {};
176 }
177 #elif defined(__mips__) || defined(__mips64__)
178 // TODO: add mips support b/27788820
179 return {};
180 #else
181 LOG(ERROR) << "Unknown architecture";
182 #endif
183
184 LOG(FATAL) << "Unable to set adequate mmap entropy value!";
185 return Error();
186 }
187
188 #define KPTR_RESTRICT_PATH "/proc/sys/kernel/kptr_restrict"
189 #define KPTR_RESTRICT_MINVALUE 2
190 #define KPTR_RESTRICT_MAXVALUE 4
191
192 // Set kptr_restrict to the highest available level.
193 //
194 // Aborts if unable to set this to an acceptable value.
SetKptrRestrictAction(const BuiltinArguments &)195 Result<void> SetKptrRestrictAction(const BuiltinArguments&) {
196 std::string path = KPTR_RESTRICT_PATH;
197
198 if (!SetHighestAvailableOptionValue(path, KPTR_RESTRICT_MINVALUE, KPTR_RESTRICT_MAXVALUE)) {
199 LOG(FATAL) << "Unable to set adequate kptr_restrict value!";
200 return Error();
201 }
202 return {};
203 }
204
205 // Test for whether the kernel has SELinux hooks for the perf_event_open()
206 // syscall. If the hooks are present, we can stop using the other permission
207 // mechanism (perf_event_paranoid sysctl), and use only the SELinux policy to
208 // control access to the syscall. The hooks are expected on all Android R
209 // release kernels, but might be absent on devices that upgrade while keeping an
210 // older kernel.
211 //
212 // There is no direct/synchronous way of finding out that a syscall failed due
213 // to SELinux. Therefore we test for a combination of a success and a failure
214 // that are explained by the platform's SELinux policy for the "init" domain:
215 // * cpu-scoped perf_event is allowed
216 // * ioctl() on the event fd is disallowed with EACCES
217 //
218 // Since init has CAP_SYS_ADMIN, these tests are not affected by the system-wide
219 // perf_event_paranoid sysctl.
220 //
221 // If the SELinux hooks are detected, a special sysprop
222 // (sys.init.perf_lsm_hooks) is set, which translates to a modification of
223 // perf_event_paranoid (through init.rc sysprop actions).
224 //
225 // TODO(b/137092007): this entire test can be removed once the platform stops
226 // supporting kernels that precede the perf_event_open hooks (Android common
227 // kernels 4.4 and 4.9).
TestPerfEventSelinuxAction(const BuiltinArguments &)228 Result<void> TestPerfEventSelinuxAction(const BuiltinArguments&) {
229 // Use a trivial event that will be configured, but not started.
230 struct perf_event_attr pe = {
231 .type = PERF_TYPE_SOFTWARE,
232 .size = sizeof(struct perf_event_attr),
233 .config = PERF_COUNT_SW_TASK_CLOCK,
234 .disabled = 1,
235 .exclude_kernel = 1,
236 };
237
238 // Open the above event targeting cpu 0. (EINTR not possible.)
239 unique_fd fd(static_cast<int>(syscall(__NR_perf_event_open, &pe, /*pid=*/-1,
240 /*cpu=*/0,
241 /*group_fd=*/-1, /*flags=*/0)));
242 if (fd == -1) {
243 PLOG(ERROR) << "Unexpected perf_event_open error";
244 return {};
245 }
246
247 int ioctl_ret = ioctl(fd, PERF_EVENT_IOC_RESET);
248 if (ioctl_ret != -1) {
249 // Success implies that the kernel doesn't have the hooks.
250 return {};
251 } else if (errno != EACCES) {
252 PLOG(ERROR) << "Unexpected perf_event ioctl error";
253 return {};
254 }
255
256 // Conclude that the SELinux hooks are present.
257 SetProperty("sys.init.perf_lsm_hooks", "1");
258 return {};
259 }
260
261 } // namespace init
262 } // namespace android
263