• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 <selinux/selinux.h>
24 #include <sys/ioctl.h>
25 #include <sys/syscall.h>
26 #include <unistd.h>
27 
28 #include <fstream>
29 
30 #include <android-base/logging.h>
31 #include <android-base/properties.h>
32 #include <android-base/unique_fd.h>
33 
34 using android::base::unique_fd;
35 using android::base::SetProperty;
36 
37 namespace android {
38 namespace init {
39 
SetHighestAvailableOptionValue(const std::string & path,int min,int max)40 static bool SetHighestAvailableOptionValue(const std::string& path, int min, int max) {
41     std::ifstream inf(path, std::fstream::in);
42     if (!inf) {
43         LOG(ERROR) << "Cannot open for reading: " << path;
44         return false;
45     }
46 
47     int current = max;
48     while (current >= min) {
49         // try to write out new value
50         std::string str_val = std::to_string(current);
51         std::ofstream of(path, std::fstream::out);
52         if (!of) {
53             LOG(ERROR) << "Cannot open for writing: " << path;
54             return false;
55         }
56         of << str_val << std::endl;
57         of.close();
58 
59         // check to make sure it was recorded
60         inf.seekg(0);
61         std::string str_rec;
62         inf >> str_rec;
63         if (str_val.compare(str_rec) == 0) {
64             break;
65         }
66         current--;
67     }
68     inf.close();
69 
70     if (current < min) {
71         LOG(ERROR) << "Unable to set minimum option value " << min << " in " << path;
72         return false;
73     }
74     return true;
75 }
76 
77 #define MMAP_RND_PATH "/proc/sys/vm/mmap_rnd_bits"
78 #define MMAP_RND_COMPAT_PATH "/proc/sys/vm/mmap_rnd_compat_bits"
79 
SetMmapRndBitsMin(int start,int min,bool compat)80 static bool SetMmapRndBitsMin(int start, int min, bool compat) {
81     std::string path;
82     if (compat) {
83         path = MMAP_RND_COMPAT_PATH;
84     } else {
85         path = MMAP_RND_PATH;
86     }
87 
88     return SetHighestAvailableOptionValue(path, min, start);
89 }
90 
91 // Set /proc/sys/vm/mmap_rnd_bits and potentially
92 // /proc/sys/vm/mmap_rnd_compat_bits to the maximum supported values.
93 // Returns an error if unable to set these to an acceptable value.
94 //
95 // To support this sysctl, the following upstream commits are needed:
96 //
97 // d07e22597d1d mm: mmap: add new /proc tunable for mmap_base ASLR
98 // e0c25d958f78 arm: mm: support ARCH_MMAP_RND_BITS
99 // 8f0d3aa9de57 arm64: mm: support ARCH_MMAP_RND_BITS
100 // 9e08f57d684a x86: mm: support ARCH_MMAP_RND_BITS
101 // ec9ee4acd97c drivers: char: random: add get_random_long()
102 // 5ef11c35ce86 mm: ASLR: use get_random_long()
SetMmapRndBitsAction(const BuiltinArguments &)103 Result<void> SetMmapRndBitsAction(const BuiltinArguments&) {
104 // values are arch-dependent
105 #if defined(USER_MODE_LINUX)
106     // uml does not support mmap_rnd_bits
107     return {};
108 #elif defined(__aarch64__)
109     // arm64 architecture supports 18 - 33 rnd bits depending on pagesize and
110     // VA_SIZE. However the kernel might have been compiled with a narrower
111     // range using CONFIG_ARCH_MMAP_RND_BITS_MIN/MAX. To use the maximum
112     // supported number of bits, we start from the theoretical maximum of 33
113     // bits and try smaller values until we reach 24 bits which is the
114     // Android-specific minimum. Don't go lower even if the configured maximum
115     // is smaller than 24.
116     if (SetMmapRndBitsMin(33, 24, false) && (!Has32BitAbi() || SetMmapRndBitsMin(16, 16, true))) {
117         return {};
118     }
119 #elif defined(__riscv)
120     // TODO: sv48 and sv57 were both added to the kernel this year, so we
121     // probably just need some kernel fixes to enable higher ASLR randomization,
122     // but for now 24 is the maximum that the kernel supports.
123     if (SetMmapRndBitsMin(24, 18, false)) {
124         return {};
125     }
126 #elif defined(__x86_64__)
127     // x86_64 supports 28 - 32 rnd bits, but Android wants to ensure that the
128     // theoretical maximum of 32 bits is always supported and used.
129     if (SetMmapRndBitsMin(32, 32, false) && (!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