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 <unistd.h>
22
23 #include <fstream>
24
25 #include <android-base/logging.h>
26 #include <android-base/unique_fd.h>
27
28 using android::base::unique_fd;
29
30 namespace android {
31 namespace init {
32
33 // Writes 512 bytes of output from Hardware RNG (/dev/hw_random, backed
34 // by Linux kernel's hw_random framework) into Linux RNG's via /dev/urandom.
35 // Does nothing if Hardware RNG is not present.
36 //
37 // Since we don't yet trust the quality of Hardware RNG, these bytes are not
38 // mixed into the primary pool of Linux RNG and the entropy estimate is left
39 // unmodified.
40 //
41 // If the HW RNG device /dev/hw_random is present, we require that at least
42 // 512 bytes read from it are written into Linux RNG. QA is expected to catch
43 // devices/configurations where these I/O operations are blocking for a long
44 // time. We do not reboot or halt on failures, as this is a best-effort
45 // attempt.
MixHwrngIntoLinuxRngAction(const BuiltinArguments &)46 Result<Success> MixHwrngIntoLinuxRngAction(const BuiltinArguments&) {
47 unique_fd hwrandom_fd(
48 TEMP_FAILURE_RETRY(open("/dev/hw_random", O_RDONLY | O_NOFOLLOW | O_CLOEXEC)));
49 if (hwrandom_fd == -1) {
50 if (errno == ENOENT) {
51 LOG(INFO) << "/dev/hw_random not found";
52 // It's not an error to not have a Hardware RNG.
53 return Success();
54 }
55 return ErrnoError() << "Failed to open /dev/hw_random";
56 }
57
58 unique_fd urandom_fd(
59 TEMP_FAILURE_RETRY(open("/dev/urandom", O_WRONLY | O_NOFOLLOW | O_CLOEXEC)));
60 if (urandom_fd == -1) {
61 return ErrnoError() << "Failed to open /dev/urandom";
62 }
63
64 char buf[512];
65 size_t total_bytes_written = 0;
66 while (total_bytes_written < sizeof(buf)) {
67 ssize_t chunk_size =
68 TEMP_FAILURE_RETRY(read(hwrandom_fd, buf, sizeof(buf) - total_bytes_written));
69 if (chunk_size == -1) {
70 return ErrnoError() << "Failed to read from /dev/hw_random";
71 } else if (chunk_size == 0) {
72 return Error() << "Failed to read from /dev/hw_random: EOF";
73 }
74
75 chunk_size = TEMP_FAILURE_RETRY(write(urandom_fd, buf, chunk_size));
76 if (chunk_size == -1) {
77 return ErrnoError() << "Failed to write to /dev/urandom";
78 }
79 total_bytes_written += chunk_size;
80 }
81
82 LOG(INFO) << "Mixed " << total_bytes_written << " bytes from /dev/hw_random into /dev/urandom";
83 return Success();
84 }
85
SetHighestAvailableOptionValue(std::string path,int min,int max)86 static bool SetHighestAvailableOptionValue(std::string path, int min, int max) {
87 std::ifstream inf(path, std::fstream::in);
88 if (!inf) {
89 LOG(ERROR) << "Cannot open for reading: " << path;
90 return false;
91 }
92
93 int current = max;
94 while (current >= min) {
95 // try to write out new value
96 std::string str_val = std::to_string(current);
97 std::ofstream of(path, std::fstream::out);
98 if (!of) {
99 LOG(ERROR) << "Cannot open for writing: " << path;
100 return false;
101 }
102 of << str_val << std::endl;
103 of.close();
104
105 // check to make sure it was recorded
106 inf.seekg(0);
107 std::string str_rec;
108 inf >> str_rec;
109 if (str_val.compare(str_rec) == 0) {
110 break;
111 }
112 current--;
113 }
114 inf.close();
115
116 if (current < min) {
117 LOG(ERROR) << "Unable to set minimum option value " << min << " in " << path;
118 return false;
119 }
120 return true;
121 }
122
123 #define MMAP_RND_PATH "/proc/sys/vm/mmap_rnd_bits"
124 #define MMAP_RND_COMPAT_PATH "/proc/sys/vm/mmap_rnd_compat_bits"
125
126 // __attribute__((unused)) due to lack of mips support: see mips block in SetMmapRndBitsAction
SetMmapRndBitsMin(int start,int min,bool compat)127 static bool __attribute__((unused)) SetMmapRndBitsMin(int start, int min, bool compat) {
128 std::string path;
129 if (compat) {
130 path = MMAP_RND_COMPAT_PATH;
131 } else {
132 path = MMAP_RND_PATH;
133 }
134
135 return SetHighestAvailableOptionValue(path, min, start);
136 }
137
138 // Set /proc/sys/vm/mmap_rnd_bits and potentially
139 // /proc/sys/vm/mmap_rnd_compat_bits to the maximum supported values.
140 // Returns -1 if unable to set these to an acceptable value.
141 //
142 // To support this sysctl, the following upstream commits are needed:
143 //
144 // d07e22597d1d mm: mmap: add new /proc tunable for mmap_base ASLR
145 // e0c25d958f78 arm: mm: support ARCH_MMAP_RND_BITS
146 // 8f0d3aa9de57 arm64: mm: support ARCH_MMAP_RND_BITS
147 // 9e08f57d684a x86: mm: support ARCH_MMAP_RND_BITS
148 // ec9ee4acd97c drivers: char: random: add get_random_long()
149 // 5ef11c35ce86 mm: ASLR: use get_random_long()
SetMmapRndBitsAction(const BuiltinArguments &)150 Result<Success> SetMmapRndBitsAction(const BuiltinArguments&) {
151 // values are arch-dependent
152 #if defined(USER_MODE_LINUX)
153 // uml does not support mmap_rnd_bits
154 return Success();
155 #elif defined(__aarch64__)
156 // arm64 supports 18 - 33 bits depending on pagesize and VA_SIZE
157 if (SetMmapRndBitsMin(33, 24, false) && SetMmapRndBitsMin(16, 16, true)) {
158 return Success();
159 }
160 #elif defined(__x86_64__)
161 // x86_64 supports 28 - 32 bits
162 if (SetMmapRndBitsMin(32, 32, false) && SetMmapRndBitsMin(16, 16, true)) {
163 return Success();
164 }
165 #elif defined(__arm__) || defined(__i386__)
166 // check to see if we're running on 64-bit kernel
167 bool h64 = !access(MMAP_RND_COMPAT_PATH, F_OK);
168 // supported 32-bit architecture must have 16 bits set
169 if (SetMmapRndBitsMin(16, 16, h64)) {
170 return Success();
171 }
172 #elif defined(__mips__) || defined(__mips64__)
173 // TODO: add mips support b/27788820
174 return Success();
175 #else
176 LOG(ERROR) << "Unknown architecture";
177 #endif
178
179 LOG(FATAL) << "Unable to set adequate mmap entropy value!";
180 return Error();
181 }
182
183 #define KPTR_RESTRICT_PATH "/proc/sys/kernel/kptr_restrict"
184 #define KPTR_RESTRICT_MINVALUE 2
185 #define KPTR_RESTRICT_MAXVALUE 4
186
187 // Set kptr_restrict to the highest available level.
188 //
189 // Aborts if unable to set this to an acceptable value.
SetKptrRestrictAction(const BuiltinArguments &)190 Result<Success> SetKptrRestrictAction(const BuiltinArguments&) {
191 std::string path = KPTR_RESTRICT_PATH;
192
193 if (!SetHighestAvailableOptionValue(path, KPTR_RESTRICT_MINVALUE, KPTR_RESTRICT_MAXVALUE)) {
194 LOG(FATAL) << "Unable to set adequate kptr_restrict value!";
195 return Error();
196 }
197 return Success();
198 }
199
200 } // namespace init
201 } // namespace android
202