blob: a0d63bca83ffa4e45778d75e617f810c0db496a5 [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"
Jiyong Park11d7bc52022-07-15 13:44:14 +090018#include "util.h"
Tom Cherry0c8d6d22017-08-10 12:22:44 -070019
20#include <errno.h>
21#include <fcntl.h>
Ryan Savitskif0f7e702020-01-14 22:02:53 +000022#include <linux/perf_event.h>
Kalesh Singh24a47ec2023-07-14 14:29:42 -070023#include <math.h>
Ryan Savitskiea93f112020-10-28 18:01:35 +000024#include <selinux/selinux.h>
Ryan Savitskif0f7e702020-01-14 22:02:53 +000025#include <sys/ioctl.h>
26#include <sys/syscall.h>
Tom Cherry0c8d6d22017-08-10 12:22:44 -070027#include <unistd.h>
28
29#include <fstream>
30
31#include <android-base/logging.h>
Ryan Savitskif0f7e702020-01-14 22:02:53 +000032#include <android-base/properties.h>
Tom Cherry0c8d6d22017-08-10 12:22:44 -070033#include <android-base/unique_fd.h>
34
Tom Cherry0c8d6d22017-08-10 12:22:44 -070035using android::base::unique_fd;
Ryan Savitskif0f7e702020-01-14 22:02:53 +000036using android::base::SetProperty;
Tom Cherry0c8d6d22017-08-10 12:22:44 -070037
38namespace android {
39namespace init {
40
Tom Cherry7c1d87e2019-07-10 11:18:24 -070041static bool SetHighestAvailableOptionValue(const std::string& path, int min, int max) {
Tom Cherry0c8d6d22017-08-10 12:22:44 -070042 std::ifstream inf(path, std::fstream::in);
43 if (!inf) {
44 LOG(ERROR) << "Cannot open for reading: " << path;
45 return false;
46 }
47
48 int current = max;
49 while (current >= min) {
50 // try to write out new value
51 std::string str_val = std::to_string(current);
52 std::ofstream of(path, std::fstream::out);
53 if (!of) {
54 LOG(ERROR) << "Cannot open for writing: " << path;
55 return false;
56 }
57 of << str_val << std::endl;
58 of.close();
59
60 // check to make sure it was recorded
61 inf.seekg(0);
62 std::string str_rec;
63 inf >> str_rec;
64 if (str_val.compare(str_rec) == 0) {
65 break;
66 }
67 current--;
68 }
69 inf.close();
70
71 if (current < min) {
72 LOG(ERROR) << "Unable to set minimum option value " << min << " in " << path;
73 return false;
74 }
75 return true;
76}
77
78#define MMAP_RND_PATH "/proc/sys/vm/mmap_rnd_bits"
79#define MMAP_RND_COMPAT_PATH "/proc/sys/vm/mmap_rnd_compat_bits"
80
Elliott Hughesf77f6f02020-02-21 13:25:54 -080081static bool SetMmapRndBitsMin(int start, int min, bool compat) {
Tom Cherry0c8d6d22017-08-10 12:22:44 -070082 std::string path;
83 if (compat) {
84 path = MMAP_RND_COMPAT_PATH;
85 } else {
86 path = MMAP_RND_PATH;
87 }
88
89 return SetHighestAvailableOptionValue(path, min, start);
90}
91
92// Set /proc/sys/vm/mmap_rnd_bits and potentially
93// /proc/sys/vm/mmap_rnd_compat_bits to the maximum supported values.
Jiyong Park5b16ccb2022-07-18 09:17:39 +090094// Returns an error if unable to set these to an acceptable value.
Tom Cherry0c8d6d22017-08-10 12:22:44 -070095//
96// To support this sysctl, the following upstream commits are needed:
97//
98// d07e22597d1d mm: mmap: add new /proc tunable for mmap_base ASLR
99// e0c25d958f78 arm: mm: support ARCH_MMAP_RND_BITS
100// 8f0d3aa9de57 arm64: mm: support ARCH_MMAP_RND_BITS
101// 9e08f57d684a x86: mm: support ARCH_MMAP_RND_BITS
102// ec9ee4acd97c drivers: char: random: add get_random_long()
103// 5ef11c35ce86 mm: ASLR: use get_random_long()
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700104Result<void> SetMmapRndBitsAction(const BuiltinArguments&) {
Tom Cherry0c8d6d22017-08-10 12:22:44 -0700105// values are arch-dependent
106#if defined(USER_MODE_LINUX)
107 // uml does not support mmap_rnd_bits
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700108 return {};
Tom Cherry0c8d6d22017-08-10 12:22:44 -0700109#elif defined(__aarch64__)
Elliott Hughes6bc53ff2023-09-19 18:40:03 +0000110 // arm64 supports 14 - 33 rnd bits depending on page size and ARM64_VA_BITS.
111 // The kernel (6.5) still defaults to 39 va bits for 4KiB pages, so shipping
112 // devices are only getting 24 bits of randomness in practice.
Jiyong Park11d7bc52022-07-15 13:44:14 +0900113 if (SetMmapRndBitsMin(33, 24, false) && (!Has32BitAbi() || SetMmapRndBitsMin(16, 16, true))) {
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700114 return {};
Tom Cherry0c8d6d22017-08-10 12:22:44 -0700115 }
Mao Hanc09eee02022-10-12 22:25:06 +0800116#elif defined(__riscv)
Sami Tolvanenb87b2552024-05-21 17:27:39 +0000117 // riscv64 supports 24 rnd bits with Sv39, and starting with the 6.9 kernel,
118 // 33 bits with Sv48 and Sv57.
119 if (SetMmapRndBitsMin(33, 24, false)) {
Mao Hanc09eee02022-10-12 22:25:06 +0800120 return {};
121 }
Tom Cherry0c8d6d22017-08-10 12:22:44 -0700122#elif defined(__x86_64__)
Jiyong Park5b16ccb2022-07-18 09:17:39 +0900123 // x86_64 supports 28 - 32 rnd bits, but Android wants to ensure that the
Kalesh Singh24a47ec2023-07-14 14:29:42 -0700124 // theoretical maximum of 32 bits is always supported and used; except in
125 // the case of the x86 page size emulator which supports a maximum
126 // of 30 bits for 16k page size, or 28 bits for 64k page size.
127 int max_bits = 32 - (static_cast<int>(log2(getpagesize())) - 12);
128 if (SetMmapRndBitsMin(max_bits, max_bits, false) &&
129 (!Has32BitAbi() || SetMmapRndBitsMin(16, 16, true))) {
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700130 return {};
Tom Cherry0c8d6d22017-08-10 12:22:44 -0700131 }
132#elif defined(__arm__) || defined(__i386__)
133 // check to see if we're running on 64-bit kernel
134 bool h64 = !access(MMAP_RND_COMPAT_PATH, F_OK);
135 // supported 32-bit architecture must have 16 bits set
136 if (SetMmapRndBitsMin(16, 16, h64)) {
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700137 return {};
Tom Cherry0c8d6d22017-08-10 12:22:44 -0700138 }
Tom Cherry0c8d6d22017-08-10 12:22:44 -0700139#else
140 LOG(ERROR) << "Unknown architecture";
141#endif
142
Tom Cherryd8db7ab2017-08-17 17:28:30 -0700143 LOG(FATAL) << "Unable to set adequate mmap entropy value!";
Tom Cherry557946e2017-08-01 13:50:23 -0700144 return Error();
Tom Cherry0c8d6d22017-08-10 12:22:44 -0700145}
146
147#define KPTR_RESTRICT_PATH "/proc/sys/kernel/kptr_restrict"
148#define KPTR_RESTRICT_MINVALUE 2
149#define KPTR_RESTRICT_MAXVALUE 4
150
151// Set kptr_restrict to the highest available level.
152//
153// Aborts if unable to set this to an acceptable value.
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700154Result<void> SetKptrRestrictAction(const BuiltinArguments&) {
Tom Cherry0c8d6d22017-08-10 12:22:44 -0700155 std::string path = KPTR_RESTRICT_PATH;
156
157 if (!SetHighestAvailableOptionValue(path, KPTR_RESTRICT_MINVALUE, KPTR_RESTRICT_MAXVALUE)) {
Tom Cherryd8db7ab2017-08-17 17:28:30 -0700158 LOG(FATAL) << "Unable to set adequate kptr_restrict value!";
Tom Cherry557946e2017-08-01 13:50:23 -0700159 return Error();
Tom Cherry0c8d6d22017-08-10 12:22:44 -0700160 }
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700161 return {};
Tom Cherry0c8d6d22017-08-10 12:22:44 -0700162}
163
Ryan Savitskif0f7e702020-01-14 22:02:53 +0000164// Test for whether the kernel has SELinux hooks for the perf_event_open()
165// syscall. If the hooks are present, we can stop using the other permission
166// mechanism (perf_event_paranoid sysctl), and use only the SELinux policy to
167// control access to the syscall. The hooks are expected on all Android R
168// release kernels, but might be absent on devices that upgrade while keeping an
169// older kernel.
170//
171// There is no direct/synchronous way of finding out that a syscall failed due
172// to SELinux. Therefore we test for a combination of a success and a failure
173// that are explained by the platform's SELinux policy for the "init" domain:
174// * cpu-scoped perf_event is allowed
175// * ioctl() on the event fd is disallowed with EACCES
176//
177// Since init has CAP_SYS_ADMIN, these tests are not affected by the system-wide
178// perf_event_paranoid sysctl.
179//
180// If the SELinux hooks are detected, a special sysprop
181// (sys.init.perf_lsm_hooks) is set, which translates to a modification of
182// perf_event_paranoid (through init.rc sysprop actions).
183//
184// TODO(b/137092007): this entire test can be removed once the platform stops
185// supporting kernels that precede the perf_event_open hooks (Android common
186// kernels 4.4 and 4.9).
187Result<void> TestPerfEventSelinuxAction(const BuiltinArguments&) {
Ryan Savitskiea93f112020-10-28 18:01:35 +0000188 // Special case: for *development devices* that boot with permissive
189 // SELinux, treat the LSM hooks as present for the effect of lowering the
190 // perf_event_paranoid sysctl. The sysprop is reused for pragmatic reasons,
191 // as there no existing way for init rules to check for permissive boot at
192 // the time of writing.
193 if (ALLOW_PERMISSIVE_SELINUX) {
194 if (!security_getenforce()) {
195 LOG(INFO) << "Permissive SELinux boot, forcing sys.init.perf_lsm_hooks to 1.";
196 SetProperty("sys.init.perf_lsm_hooks", "1");
197 return {};
198 }
199 }
200
Ryan Savitskif0f7e702020-01-14 22:02:53 +0000201 // Use a trivial event that will be configured, but not started.
202 struct perf_event_attr pe = {
203 .type = PERF_TYPE_SOFTWARE,
204 .size = sizeof(struct perf_event_attr),
205 .config = PERF_COUNT_SW_TASK_CLOCK,
206 .disabled = 1,
207 .exclude_kernel = 1,
208 };
209
210 // Open the above event targeting cpu 0. (EINTR not possible.)
211 unique_fd fd(static_cast<int>(syscall(__NR_perf_event_open, &pe, /*pid=*/-1,
212 /*cpu=*/0,
213 /*group_fd=*/-1, /*flags=*/0)));
214 if (fd == -1) {
215 PLOG(ERROR) << "Unexpected perf_event_open error";
216 return {};
217 }
218
Bart Van Asscheaee2ec82022-12-02 18:48:15 -0800219 int ioctl_ret = ioctl(fd.get(), PERF_EVENT_IOC_RESET);
Ryan Savitskif0f7e702020-01-14 22:02:53 +0000220 if (ioctl_ret != -1) {
221 // Success implies that the kernel doesn't have the hooks.
222 return {};
223 } else if (errno != EACCES) {
224 PLOG(ERROR) << "Unexpected perf_event ioctl error";
225 return {};
226 }
227
228 // Conclude that the SELinux hooks are present.
229 SetProperty("sys.init.perf_lsm_hooks", "1");
230 return {};
231}
232
Tom Cherry0c8d6d22017-08-10 12:22:44 -0700233} // namespace init
234} // namespace android