blob: 6cbe642c081b13c12d7d951b0620d2dcf52e4b89 [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>
22#include <sys/ioctl.h>
23#include <sys/syscall.h>
Tom Cherry0c8d6d22017-08-10 12:22:44 -070024#include <unistd.h>
25
26#include <fstream>
27
28#include <android-base/logging.h>
Ryan Savitskif0f7e702020-01-14 22:02:53 +000029#include <android-base/properties.h>
Tom Cherry0c8d6d22017-08-10 12:22:44 -070030#include <android-base/unique_fd.h>
31
Tom Cherry0c8d6d22017-08-10 12:22:44 -070032using android::base::unique_fd;
Ryan Savitskif0f7e702020-01-14 22:02:53 +000033using android::base::SetProperty;
Tom Cherry0c8d6d22017-08-10 12:22:44 -070034
35namespace android {
36namespace 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.
Tom Cherrybbcbc2f2019-06-10 11:08:01 -070051Result<void> MixHwrngIntoLinuxRngAction(const BuiltinArguments&) {
Tom Cherry0c8d6d22017-08-10 12:22:44 -070052 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.
Tom Cherrybbcbc2f2019-06-10 11:08:01 -070058 return {};
Tom Cherry0c8d6d22017-08-10 12:22:44 -070059 }
Tom Cherry557946e2017-08-01 13:50:23 -070060 return ErrnoError() << "Failed to open /dev/hw_random";
Tom Cherry0c8d6d22017-08-10 12:22:44 -070061 }
62
63 unique_fd urandom_fd(
64 TEMP_FAILURE_RETRY(open("/dev/urandom", O_WRONLY | O_NOFOLLOW | O_CLOEXEC)));
65 if (urandom_fd == -1) {
Tom Cherry557946e2017-08-01 13:50:23 -070066 return ErrnoError() << "Failed to open /dev/urandom";
Tom Cherry0c8d6d22017-08-10 12:22:44 -070067 }
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) {
Tom Cherry557946e2017-08-01 13:50:23 -070075 return ErrnoError() << "Failed to read from /dev/hw_random";
Tom Cherry0c8d6d22017-08-10 12:22:44 -070076 } else if (chunk_size == 0) {
Tom Cherry557946e2017-08-01 13:50:23 -070077 return Error() << "Failed to read from /dev/hw_random: EOF";
Tom Cherry0c8d6d22017-08-10 12:22:44 -070078 }
79
80 chunk_size = TEMP_FAILURE_RETRY(write(urandom_fd, buf, chunk_size));
81 if (chunk_size == -1) {
Tom Cherry557946e2017-08-01 13:50:23 -070082 return ErrnoError() << "Failed to write to /dev/urandom";
Tom Cherry0c8d6d22017-08-10 12:22:44 -070083 }
84 total_bytes_written += chunk_size;
85 }
86
87 LOG(INFO) << "Mixed " << total_bytes_written << " bytes from /dev/hw_random into /dev/urandom";
Tom Cherrybbcbc2f2019-06-10 11:08:01 -070088 return {};
Tom Cherry0c8d6d22017-08-10 12:22:44 -070089}
90
Tom Cherry7c1d87e2019-07-10 11:18:24 -070091static bool SetHighestAvailableOptionValue(const std::string& path, int min, int max) {
Tom Cherry0c8d6d22017-08-10 12:22:44 -070092 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
132static 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()
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 }
177#elif defined(__mips__) || defined(__mips64__)
178 // TODO: add mips support b/27788820
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700179 return {};
Tom Cherry0c8d6d22017-08-10 12:22:44 -0700180#else
181 LOG(ERROR) << "Unknown architecture";
182#endif
183
Tom Cherryd8db7ab2017-08-17 17:28:30 -0700184 LOG(FATAL) << "Unable to set adequate mmap entropy value!";
Tom Cherry557946e2017-08-01 13:50:23 -0700185 return Error();
Tom Cherry0c8d6d22017-08-10 12:22:44 -0700186}
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.
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700195Result<void> SetKptrRestrictAction(const BuiltinArguments&) {
Tom Cherry0c8d6d22017-08-10 12:22:44 -0700196 std::string path = KPTR_RESTRICT_PATH;
197
198 if (!SetHighestAvailableOptionValue(path, KPTR_RESTRICT_MINVALUE, KPTR_RESTRICT_MAXVALUE)) {
Tom Cherryd8db7ab2017-08-17 17:28:30 -0700199 LOG(FATAL) << "Unable to set adequate kptr_restrict value!";
Tom Cherry557946e2017-08-01 13:50:23 -0700200 return Error();
Tom Cherry0c8d6d22017-08-10 12:22:44 -0700201 }
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700202 return {};
Tom Cherry0c8d6d22017-08-10 12:22:44 -0700203}
204
Ryan Savitskif0f7e702020-01-14 22:02:53 +0000205// 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).
228Result<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
Tom Cherry0c8d6d22017-08-10 12:22:44 -0700261} // namespace init
262} // namespace android