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
SetMmapRndBitsMin(int start,int min,bool compat)131 static bool SetMmapRndBitsMin(int start, int min, bool compat) {
132 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()
SetMmapRndBitsAction(const BuiltinArguments &)154 Result<void> SetMmapRndBitsAction(const BuiltinArguments&) {
155 // values are arch-dependent
156 #if defined(USER_MODE_LINUX)
157 // uml does not support mmap_rnd_bits
158 return {};
159 #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)) {
162 return {};
163 }
164 #elif defined(__x86_64__)
165 // x86_64 supports 28 - 32 bits
166 if (SetMmapRndBitsMin(32, 32, false) && SetMmapRndBitsMin(16, 16, true)) {
167 return {};
168 }
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)) {
174 return {};
175 }
176 #else
177 LOG(ERROR) << "Unknown architecture";
178 #endif
179
180 LOG(FATAL) << "Unable to set adequate mmap entropy value!";
181 return Error();
182 }
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.
SetKptrRestrictAction(const BuiltinArguments &)191 Result<void> SetKptrRestrictAction(const BuiltinArguments&) {
192 std::string path = KPTR_RESTRICT_PATH;
193
194 if (!SetHighestAvailableOptionValue(path, KPTR_RESTRICT_MINVALUE, KPTR_RESTRICT_MAXVALUE)) {
195 LOG(FATAL) << "Unable to set adequate kptr_restrict value!";
196 return Error();
197 }
198 return {};
199 }
200
201 // 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).
TestPerfEventSelinuxAction(const BuiltinArguments &)224 Result<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
257 } // namespace init
258 } // namespace android
259