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 #include "util.h"
19 
20 #include <errno.h>
21 #include <fcntl.h>
22 #include <linux/perf_event.h>
23 #include <math.h>
24 #include <selinux/selinux.h>
25 #include <sys/ioctl.h>
26 #include <sys/syscall.h>
27 #include <unistd.h>
28 
29 #include <fstream>
30 
31 #include <android-base/logging.h>
32 #include <android-base/properties.h>
33 #include <android-base/unique_fd.h>
34 
35 using android::base::unique_fd;
36 using android::base::SetProperty;
37 
38 namespace android {
39 namespace init {
40 
SetHighestAvailableOptionValue(const std::string & path,int min,int max)41 static bool SetHighestAvailableOptionValue(const std::string& path, int min, int max) {
42     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 
SetMmapRndBitsMin(int start,int min,bool compat)81 static bool SetMmapRndBitsMin(int start, int min, bool compat) {
82     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.
94 // Returns an error if unable to set these to an acceptable value.
95 //
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()
SetMmapRndBitsAction(const BuiltinArguments &)104 Result<void> SetMmapRndBitsAction(const BuiltinArguments&) {
105 // values are arch-dependent
106 #if defined(USER_MODE_LINUX)
107     // uml does not support mmap_rnd_bits
108     return {};
109 #elif defined(__aarch64__)
110     // 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.
113     if (SetMmapRndBitsMin(33, 24, false) && (!Has32BitAbi() || SetMmapRndBitsMin(16, 16, true))) {
114         return {};
115     }
116 #elif defined(__riscv)
117     // 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)) {
120         return {};
121     }
122 #elif defined(__x86_64__)
123     // x86_64 supports 28 - 32 rnd bits, but Android wants to ensure that the
124     // 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))) {
130         return {};
131     }
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)) {
137         return {};
138     }
139 #else
140     LOG(ERROR) << "Unknown architecture";
141 #endif
142 
143     LOG(FATAL) << "Unable to set adequate mmap entropy value!";
144     return Error();
145 }
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.
SetKptrRestrictAction(const BuiltinArguments &)154 Result<void> SetKptrRestrictAction(const BuiltinArguments&) {
155     std::string path = KPTR_RESTRICT_PATH;
156 
157     if (!SetHighestAvailableOptionValue(path, KPTR_RESTRICT_MINVALUE, KPTR_RESTRICT_MAXVALUE)) {
158         LOG(FATAL) << "Unable to set adequate kptr_restrict value!";
159         return Error();
160     }
161     return {};
162 }
163 
164 // 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).
TestPerfEventSelinuxAction(const BuiltinArguments &)187 Result<void> TestPerfEventSelinuxAction(const BuiltinArguments&) {
188     // 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 
201     // 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 
219     int ioctl_ret = ioctl(fd.get(), PERF_EVENT_IOC_RESET);
220     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 
233 }  // namespace init
234 }  // namespace android
235