blob: 2450d654b3f326b2bf1077a9bc7c110c7ba5014a [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
Elliott Hughesf77f6f02020-02-21 13:25:54 -0800131static bool SetMmapRndBitsMin(int start, int min, bool compat) {
Tom Cherry0c8d6d22017-08-10 12:22:44 -0700132 std::string path;
133 if (compat) {
134 path = MMAP_RND_COMPAT_PATH;
135 } else {
136 path = MMAP_RND_PATH;
137 }
138
139 return SetHighestAvailableOptionValue(path, min, start);
140}
141
142// Set /proc/sys/vm/mmap_rnd_bits and potentially
143// /proc/sys/vm/mmap_rnd_compat_bits to the maximum supported values.
144// Returns -1 if unable to set these to an acceptable value.
145//
146// To support this sysctl, the following upstream commits are needed:
147//
148// d07e22597d1d mm: mmap: add new /proc tunable for mmap_base ASLR
149// e0c25d958f78 arm: mm: support ARCH_MMAP_RND_BITS
150// 8f0d3aa9de57 arm64: mm: support ARCH_MMAP_RND_BITS
151// 9e08f57d684a x86: mm: support ARCH_MMAP_RND_BITS
152// ec9ee4acd97c drivers: char: random: add get_random_long()
153// 5ef11c35ce86 mm: ASLR: use get_random_long()
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700154Result<void> SetMmapRndBitsAction(const BuiltinArguments&) {
Tom Cherry0c8d6d22017-08-10 12:22:44 -0700155// values are arch-dependent
156#if defined(USER_MODE_LINUX)
157 // uml does not support mmap_rnd_bits
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700158 return {};
Tom Cherry0c8d6d22017-08-10 12:22:44 -0700159#elif defined(__aarch64__)
160 // arm64 supports 18 - 33 bits depending on pagesize and VA_SIZE
161 if (SetMmapRndBitsMin(33, 24, false) && SetMmapRndBitsMin(16, 16, true)) {
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700162 return {};
Tom Cherry0c8d6d22017-08-10 12:22:44 -0700163 }
164#elif defined(__x86_64__)
165 // x86_64 supports 28 - 32 bits
166 if (SetMmapRndBitsMin(32, 32, false) && SetMmapRndBitsMin(16, 16, true)) {
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700167 return {};
Tom Cherry0c8d6d22017-08-10 12:22:44 -0700168 }
169#elif defined(__arm__) || defined(__i386__)
170 // check to see if we're running on 64-bit kernel
171 bool h64 = !access(MMAP_RND_COMPAT_PATH, F_OK);
172 // supported 32-bit architecture must have 16 bits set
173 if (SetMmapRndBitsMin(16, 16, h64)) {
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700174 return {};
Tom Cherry0c8d6d22017-08-10 12:22:44 -0700175 }
Tom Cherry0c8d6d22017-08-10 12:22:44 -0700176#else
177 LOG(ERROR) << "Unknown architecture";
178#endif
179
Tom Cherryd8db7ab2017-08-17 17:28:30 -0700180 LOG(FATAL) << "Unable to set adequate mmap entropy value!";
Tom Cherry557946e2017-08-01 13:50:23 -0700181 return Error();
Tom Cherry0c8d6d22017-08-10 12:22:44 -0700182}
183
184#define KPTR_RESTRICT_PATH "/proc/sys/kernel/kptr_restrict"
185#define KPTR_RESTRICT_MINVALUE 2
186#define KPTR_RESTRICT_MAXVALUE 4
187
188// Set kptr_restrict to the highest available level.
189//
190// Aborts if unable to set this to an acceptable value.
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700191Result<void> SetKptrRestrictAction(const BuiltinArguments&) {
Tom Cherry0c8d6d22017-08-10 12:22:44 -0700192 std::string path = KPTR_RESTRICT_PATH;
193
194 if (!SetHighestAvailableOptionValue(path, KPTR_RESTRICT_MINVALUE, KPTR_RESTRICT_MAXVALUE)) {
Tom Cherryd8db7ab2017-08-17 17:28:30 -0700195 LOG(FATAL) << "Unable to set adequate kptr_restrict value!";
Tom Cherry557946e2017-08-01 13:50:23 -0700196 return Error();
Tom Cherry0c8d6d22017-08-10 12:22:44 -0700197 }
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700198 return {};
Tom Cherry0c8d6d22017-08-10 12:22:44 -0700199}
200
Ryan Savitskif0f7e702020-01-14 22:02:53 +0000201// Test for whether the kernel has SELinux hooks for the perf_event_open()
202// syscall. If the hooks are present, we can stop using the other permission
203// mechanism (perf_event_paranoid sysctl), and use only the SELinux policy to
204// control access to the syscall. The hooks are expected on all Android R
205// release kernels, but might be absent on devices that upgrade while keeping an
206// older kernel.
207//
208// There is no direct/synchronous way of finding out that a syscall failed due
209// to SELinux. Therefore we test for a combination of a success and a failure
210// that are explained by the platform's SELinux policy for the "init" domain:
211// * cpu-scoped perf_event is allowed
212// * ioctl() on the event fd is disallowed with EACCES
213//
214// Since init has CAP_SYS_ADMIN, these tests are not affected by the system-wide
215// perf_event_paranoid sysctl.
216//
217// If the SELinux hooks are detected, a special sysprop
218// (sys.init.perf_lsm_hooks) is set, which translates to a modification of
219// perf_event_paranoid (through init.rc sysprop actions).
220//
221// TODO(b/137092007): this entire test can be removed once the platform stops
222// supporting kernels that precede the perf_event_open hooks (Android common
223// kernels 4.4 and 4.9).
224Result<void> TestPerfEventSelinuxAction(const BuiltinArguments&) {
225 // Use a trivial event that will be configured, but not started.
226 struct perf_event_attr pe = {
227 .type = PERF_TYPE_SOFTWARE,
228 .size = sizeof(struct perf_event_attr),
229 .config = PERF_COUNT_SW_TASK_CLOCK,
230 .disabled = 1,
231 .exclude_kernel = 1,
232 };
233
234 // Open the above event targeting cpu 0. (EINTR not possible.)
235 unique_fd fd(static_cast<int>(syscall(__NR_perf_event_open, &pe, /*pid=*/-1,
236 /*cpu=*/0,
237 /*group_fd=*/-1, /*flags=*/0)));
238 if (fd == -1) {
239 PLOG(ERROR) << "Unexpected perf_event_open error";
240 return {};
241 }
242
243 int ioctl_ret = ioctl(fd, PERF_EVENT_IOC_RESET);
244 if (ioctl_ret != -1) {
245 // Success implies that the kernel doesn't have the hooks.
246 return {};
247 } else if (errno != EACCES) {
248 PLOG(ERROR) << "Unexpected perf_event ioctl error";
249 return {};
250 }
251
252 // Conclude that the SELinux hooks are present.
253 SetProperty("sys.init.perf_lsm_hooks", "1");
254 return {};
255}
256
Tom Cherry0c8d6d22017-08-10 12:22:44 -0700257} // namespace init
258} // namespace android