blob: ac784a32af8e937916ac0ec88e8ce9e30e333eaa [file] [log] [blame]
Tom Cherry0c8d6d22017-08-10 12:22:44 -07001/*
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>
Ryan Savitskif0f7e702020-01-14 22:02:53 +000021#include <linux/perf_event.h>
Ryan Savitskiea93f112020-10-28 18:01:35 +000022#include <selinux/selinux.h>
Ryan Savitskif0f7e702020-01-14 22:02:53 +000023#include <sys/ioctl.h>
24#include <sys/syscall.h>
Tom Cherry0c8d6d22017-08-10 12:22:44 -070025#include <unistd.h>
26
27#include <fstream>
28
29#include <android-base/logging.h>
Ryan Savitskif0f7e702020-01-14 22:02:53 +000030#include <android-base/properties.h>
Tom Cherry0c8d6d22017-08-10 12:22:44 -070031#include <android-base/unique_fd.h>
32
Tom Cherry0c8d6d22017-08-10 12:22:44 -070033using android::base::unique_fd;
Ryan Savitskif0f7e702020-01-14 22:02:53 +000034using android::base::SetProperty;
Tom Cherry0c8d6d22017-08-10 12:22:44 -070035
36namespace android {
37namespace init {
38
39// Writes 512 bytes of output from Hardware RNG (/dev/hw_random, backed
40// by Linux kernel's hw_random framework) into Linux RNG's via /dev/urandom.
41// Does nothing if Hardware RNG is not present.
42//
43// Since we don't yet trust the quality of Hardware RNG, these bytes are not
44// mixed into the primary pool of Linux RNG and the entropy estimate is left
45// unmodified.
46//
47// If the HW RNG device /dev/hw_random is present, we require that at least
48// 512 bytes read from it are written into Linux RNG. QA is expected to catch
49// devices/configurations where these I/O operations are blocking for a long
50// time. We do not reboot or halt on failures, as this is a best-effort
51// attempt.
Tom Cherrybbcbc2f2019-06-10 11:08:01 -070052Result<void> MixHwrngIntoLinuxRngAction(const BuiltinArguments&) {
Tom Cherry0c8d6d22017-08-10 12:22:44 -070053 unique_fd hwrandom_fd(
54 TEMP_FAILURE_RETRY(open("/dev/hw_random", O_RDONLY | O_NOFOLLOW | O_CLOEXEC)));
55 if (hwrandom_fd == -1) {
56 if (errno == ENOENT) {
57 LOG(INFO) << "/dev/hw_random not found";
58 // It's not an error to not have a Hardware RNG.
Tom Cherrybbcbc2f2019-06-10 11:08:01 -070059 return {};
Tom Cherry0c8d6d22017-08-10 12:22:44 -070060 }
Tom Cherry557946e2017-08-01 13:50:23 -070061 return ErrnoError() << "Failed to open /dev/hw_random";
Tom Cherry0c8d6d22017-08-10 12:22:44 -070062 }
63
64 unique_fd urandom_fd(
65 TEMP_FAILURE_RETRY(open("/dev/urandom", O_WRONLY | O_NOFOLLOW | O_CLOEXEC)));
66 if (urandom_fd == -1) {
Tom Cherry557946e2017-08-01 13:50:23 -070067 return ErrnoError() << "Failed to open /dev/urandom";
Tom Cherry0c8d6d22017-08-10 12:22:44 -070068 }
69
70 char buf[512];
71 size_t total_bytes_written = 0;
72 while (total_bytes_written < sizeof(buf)) {
73 ssize_t chunk_size =
74 TEMP_FAILURE_RETRY(read(hwrandom_fd, buf, sizeof(buf) - total_bytes_written));
75 if (chunk_size == -1) {
Tom Cherry557946e2017-08-01 13:50:23 -070076 return ErrnoError() << "Failed to read from /dev/hw_random";
Tom Cherry0c8d6d22017-08-10 12:22:44 -070077 } else if (chunk_size == 0) {
Tom Cherry557946e2017-08-01 13:50:23 -070078 return Error() << "Failed to read from /dev/hw_random: EOF";
Tom Cherry0c8d6d22017-08-10 12:22:44 -070079 }
80
81 chunk_size = TEMP_FAILURE_RETRY(write(urandom_fd, buf, chunk_size));
82 if (chunk_size == -1) {
Tom Cherry557946e2017-08-01 13:50:23 -070083 return ErrnoError() << "Failed to write to /dev/urandom";
Tom Cherry0c8d6d22017-08-10 12:22:44 -070084 }
85 total_bytes_written += chunk_size;
86 }
87
88 LOG(INFO) << "Mixed " << total_bytes_written << " bytes from /dev/hw_random into /dev/urandom";
Tom Cherrybbcbc2f2019-06-10 11:08:01 -070089 return {};
Tom Cherry0c8d6d22017-08-10 12:22:44 -070090}
91
Tom Cherry7c1d87e2019-07-10 11:18:24 -070092static bool SetHighestAvailableOptionValue(const std::string& path, int min, int max) {
Tom Cherry0c8d6d22017-08-10 12:22:44 -070093 std::ifstream inf(path, std::fstream::in);
94 if (!inf) {
95 LOG(ERROR) << "Cannot open for reading: " << path;
96 return false;
97 }
98
99 int current = max;
100 while (current >= min) {
101 // try to write out new value
102 std::string str_val = std::to_string(current);
103 std::ofstream of(path, std::fstream::out);
104 if (!of) {
105 LOG(ERROR) << "Cannot open for writing: " << path;
106 return false;
107 }
108 of << str_val << std::endl;
109 of.close();
110
111 // check to make sure it was recorded
112 inf.seekg(0);
113 std::string str_rec;
114 inf >> str_rec;
115 if (str_val.compare(str_rec) == 0) {
116 break;
117 }
118 current--;
119 }
120 inf.close();
121
122 if (current < min) {
123 LOG(ERROR) << "Unable to set minimum option value " << min << " in " << path;
124 return false;
125 }
126 return true;
127}
128
129#define MMAP_RND_PATH "/proc/sys/vm/mmap_rnd_bits"
130#define MMAP_RND_COMPAT_PATH "/proc/sys/vm/mmap_rnd_compat_bits"
131
Elliott Hughesf77f6f02020-02-21 13:25:54 -0800132static bool SetMmapRndBitsMin(int start, int min, bool compat) {
Tom Cherry0c8d6d22017-08-10 12:22:44 -0700133 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()
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700155Result<void> SetMmapRndBitsAction(const BuiltinArguments&) {
Tom Cherry0c8d6d22017-08-10 12:22:44 -0700156// values are arch-dependent
157#if defined(USER_MODE_LINUX)
158 // uml does not support mmap_rnd_bits
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700159 return {};
Tom Cherry0c8d6d22017-08-10 12:22:44 -0700160#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)) {
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700163 return {};
Tom Cherry0c8d6d22017-08-10 12:22:44 -0700164 }
165#elif defined(__x86_64__)
166 // x86_64 supports 28 - 32 bits
167 if (SetMmapRndBitsMin(32, 32, false) && SetMmapRndBitsMin(16, 16, true)) {
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700168 return {};
Tom Cherry0c8d6d22017-08-10 12:22:44 -0700169 }
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)) {
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700175 return {};
Tom Cherry0c8d6d22017-08-10 12:22:44 -0700176 }
Tom Cherry0c8d6d22017-08-10 12:22:44 -0700177#else
178 LOG(ERROR) << "Unknown architecture";
179#endif
180
Tom Cherryd8db7ab2017-08-17 17:28:30 -0700181 LOG(FATAL) << "Unable to set adequate mmap entropy value!";
Tom Cherry557946e2017-08-01 13:50:23 -0700182 return Error();
Tom Cherry0c8d6d22017-08-10 12:22:44 -0700183}
184
185#define KPTR_RESTRICT_PATH "/proc/sys/kernel/kptr_restrict"
186#define KPTR_RESTRICT_MINVALUE 2
187#define KPTR_RESTRICT_MAXVALUE 4
188
189// Set kptr_restrict to the highest available level.
190//
191// Aborts if unable to set this to an acceptable value.
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700192Result<void> SetKptrRestrictAction(const BuiltinArguments&) {
Tom Cherry0c8d6d22017-08-10 12:22:44 -0700193 std::string path = KPTR_RESTRICT_PATH;
194
195 if (!SetHighestAvailableOptionValue(path, KPTR_RESTRICT_MINVALUE, KPTR_RESTRICT_MAXVALUE)) {
Tom Cherryd8db7ab2017-08-17 17:28:30 -0700196 LOG(FATAL) << "Unable to set adequate kptr_restrict value!";
Tom Cherry557946e2017-08-01 13:50:23 -0700197 return Error();
Tom Cherry0c8d6d22017-08-10 12:22:44 -0700198 }
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700199 return {};
Tom Cherry0c8d6d22017-08-10 12:22:44 -0700200}
201
Ryan Savitskif0f7e702020-01-14 22:02:53 +0000202// Test for whether the kernel has SELinux hooks for the perf_event_open()
203// syscall. If the hooks are present, we can stop using the other permission
204// mechanism (perf_event_paranoid sysctl), and use only the SELinux policy to
205// control access to the syscall. The hooks are expected on all Android R
206// release kernels, but might be absent on devices that upgrade while keeping an
207// older kernel.
208//
209// There is no direct/synchronous way of finding out that a syscall failed due
210// to SELinux. Therefore we test for a combination of a success and a failure
211// that are explained by the platform's SELinux policy for the "init" domain:
212// * cpu-scoped perf_event is allowed
213// * ioctl() on the event fd is disallowed with EACCES
214//
215// Since init has CAP_SYS_ADMIN, these tests are not affected by the system-wide
216// perf_event_paranoid sysctl.
217//
218// If the SELinux hooks are detected, a special sysprop
219// (sys.init.perf_lsm_hooks) is set, which translates to a modification of
220// perf_event_paranoid (through init.rc sysprop actions).
221//
222// TODO(b/137092007): this entire test can be removed once the platform stops
223// supporting kernels that precede the perf_event_open hooks (Android common
224// kernels 4.4 and 4.9).
225Result<void> TestPerfEventSelinuxAction(const BuiltinArguments&) {
Ryan Savitskiea93f112020-10-28 18:01:35 +0000226 // Special case: for *development devices* that boot with permissive
227 // SELinux, treat the LSM hooks as present for the effect of lowering the
228 // perf_event_paranoid sysctl. The sysprop is reused for pragmatic reasons,
229 // as there no existing way for init rules to check for permissive boot at
230 // the time of writing.
231 if (ALLOW_PERMISSIVE_SELINUX) {
232 if (!security_getenforce()) {
233 LOG(INFO) << "Permissive SELinux boot, forcing sys.init.perf_lsm_hooks to 1.";
234 SetProperty("sys.init.perf_lsm_hooks", "1");
235 return {};
236 }
237 }
238
Ryan Savitskif0f7e702020-01-14 22:02:53 +0000239 // Use a trivial event that will be configured, but not started.
240 struct perf_event_attr pe = {
241 .type = PERF_TYPE_SOFTWARE,
242 .size = sizeof(struct perf_event_attr),
243 .config = PERF_COUNT_SW_TASK_CLOCK,
244 .disabled = 1,
245 .exclude_kernel = 1,
246 };
247
248 // Open the above event targeting cpu 0. (EINTR not possible.)
249 unique_fd fd(static_cast<int>(syscall(__NR_perf_event_open, &pe, /*pid=*/-1,
250 /*cpu=*/0,
251 /*group_fd=*/-1, /*flags=*/0)));
252 if (fd == -1) {
253 PLOG(ERROR) << "Unexpected perf_event_open error";
254 return {};
255 }
256
257 int ioctl_ret = ioctl(fd, PERF_EVENT_IOC_RESET);
258 if (ioctl_ret != -1) {
259 // Success implies that the kernel doesn't have the hooks.
260 return {};
261 } else if (errno != EACCES) {
262 PLOG(ERROR) << "Unexpected perf_event ioctl error";
263 return {};
264 }
265
266 // Conclude that the SELinux hooks are present.
267 SetProperty("sys.init.perf_lsm_hooks", "1");
268 return {};
269}
270
Tom Cherry0c8d6d22017-08-10 12:22:44 -0700271} // namespace init
272} // namespace android