1 /* Copyright (c) 2014, Google Inc.
2 *
3 * Permission to use, copy, modify, and/or distribute this software for any
4 * purpose with or without fee is hereby granted, provided that the above
5 * copyright notice and this permission notice appear in all copies.
6 *
7 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
8 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
9 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
10 * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
11 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
12 * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
13 * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
14
15 #if !defined(_GNU_SOURCE)
16 #define _GNU_SOURCE // needed for syscall() on Linux.
17 #endif
18
19 #include <openssl/rand.h>
20
21 #include "internal.h"
22
23 #if defined(OPENSSL_URANDOM)
24
25 #include <assert.h>
26 #include <errno.h>
27 #include <fcntl.h>
28 #include <stdio.h>
29 #include <string.h>
30 #include <unistd.h>
31
32 #if defined(OPENSSL_LINUX)
33 #if defined(BORINGSSL_FIPS)
34 #include <linux/random.h>
35 #include <sys/ioctl.h>
36 #endif
37 #include <sys/syscall.h>
38
39 #if defined(OPENSSL_ANDROID)
40 #include <sys/system_properties.h>
41 #endif
42
43 #if !defined(OPENSSL_ANDROID)
44 #define OPENSSL_HAS_GETAUXVAL
45 #endif
46 // glibc prior to 2.16 does not have getauxval and sys/auxv.h. Android has some
47 // host builds (i.e. not building for Android itself, so |OPENSSL_ANDROID| is
48 // unset) which are still using a 2.15 sysroot.
49 //
50 // TODO(davidben): Remove this once Android updates their sysroot.
51 #if defined(__GLIBC_PREREQ)
52 #if !__GLIBC_PREREQ(2, 16)
53 #undef OPENSSL_HAS_GETAUXVAL
54 #endif
55 #endif
56 #if defined(OPENSSL_HAS_GETAUXVAL)
57 #include <sys/auxv.h>
58 #endif
59 #endif // OPENSSL_LINUX
60
61 #if defined(OPENSSL_MACOS)
62 #include <sys/random.h>
63 #endif
64
65 #if defined(OPENSSL_FREEBSD)
66 #define URANDOM_BLOCKS_FOR_ENTROPY
67 #if __FreeBSD__ >= 12
68 // getrandom is supported in FreeBSD 12 and up.
69 #define FREEBSD_GETRANDOM
70 #include <sys/random.h>
71 #endif
72 #endif
73
74 #include <openssl/thread.h>
75 #include <openssl/mem.h>
76
77 #include "getrandom_fillin.h"
78 #include "../delocate.h"
79 #include "../../internal.h"
80
81
82 #if defined(USE_NR_getrandom)
83
84 #if defined(OPENSSL_MSAN)
85 void __msan_unpoison(void *, size_t);
86 #endif
87
boringssl_getrandom(void * buf,size_t buf_len,unsigned flags)88 static ssize_t boringssl_getrandom(void *buf, size_t buf_len, unsigned flags) {
89 ssize_t ret;
90 do {
91 ret = syscall(__NR_getrandom, buf, buf_len, flags);
92 } while (ret == -1 && errno == EINTR);
93
94 #if defined(OPENSSL_MSAN)
95 if (ret > 0) {
96 // MSAN doesn't recognise |syscall| and thus doesn't notice that we have
97 // initialised the output buffer.
98 __msan_unpoison(buf, ret);
99 }
100 #endif // OPENSSL_MSAN
101
102 return ret;
103 }
104
105 #endif // USE_NR_getrandom
106
107 // kHaveGetrandom in |urandom_fd| signals that |getrandom| or |getentropy| is
108 // available and should be used instead.
109 static const int kHaveGetrandom = -3;
110
111 // urandom_fd is a file descriptor to /dev/urandom. It's protected by |once|.
DEFINE_BSS_GET(int,urandom_fd)112 DEFINE_BSS_GET(int, urandom_fd)
113
114 #if defined(USE_NR_getrandom)
115
116 // getrandom_ready is one if |getrandom| had been initialized by the time
117 // |init_once| was called and zero otherwise.
118 DEFINE_BSS_GET(int, getrandom_ready)
119
120 // extra_getrandom_flags_for_seed contains a value that is ORed into the flags
121 // for getrandom() when reading entropy for a seed.
122 DEFINE_BSS_GET(int, extra_getrandom_flags_for_seed)
123
124 // On Android, check a system property to decide whether to set
125 // |extra_getrandom_flags_for_seed| otherwise they will default to zero. If
126 // ro.oem_boringcrypto_hwrand is true then |extra_getrandom_flags_for_seed| will
127 // be set to GRND_RANDOM, causing all random data to be drawn from the same
128 // source as /dev/random.
129 static void maybe_set_extra_getrandom_flags(void) {
130 #if defined(BORINGSSL_FIPS) && defined(OPENSSL_ANDROID)
131 char value[PROP_VALUE_MAX + 1];
132 int length = __system_property_get("ro.boringcrypto.hwrand", value);
133 if (length < 0 || length > PROP_VALUE_MAX) {
134 return;
135 }
136
137 value[length] = 0;
138 if (strcasecmp(value, "true") == 0) {
139 *extra_getrandom_flags_for_seed_bss_get() = GRND_RANDOM;
140 }
141 #endif
142 }
143
144 #endif // USE_NR_getrandom
145
DEFINE_STATIC_ONCE(rand_once)146 DEFINE_STATIC_ONCE(rand_once)
147
148 // init_once initializes the state of this module to values previously
149 // requested. This is the only function that modifies |urandom_fd|, which may be
150 // read safely after calling the once.
151 static void init_once(void) {
152 #if defined(USE_NR_getrandom)
153 int have_getrandom;
154 uint8_t dummy;
155 ssize_t getrandom_ret =
156 boringssl_getrandom(&dummy, sizeof(dummy), GRND_NONBLOCK);
157 if (getrandom_ret == 1) {
158 *getrandom_ready_bss_get() = 1;
159 have_getrandom = 1;
160 } else if (getrandom_ret == -1 && errno == EAGAIN) {
161 // We have getrandom, but the entropy pool has not been initialized yet.
162 have_getrandom = 1;
163 } else if (getrandom_ret == -1 && errno == ENOSYS) {
164 // Fallthrough to using /dev/urandom, below.
165 have_getrandom = 0;
166 } else {
167 // Other errors are fatal.
168 perror("getrandom");
169 abort();
170 }
171
172 if (have_getrandom) {
173 *urandom_fd_bss_get() = kHaveGetrandom;
174 maybe_set_extra_getrandom_flags();
175 return;
176 }
177 #endif // USE_NR_getrandom
178
179 #if defined(OPENSSL_MACOS)
180 // getentropy is available in macOS 10.12 and up. iOS 10 and up may also
181 // support it, but the header is missing. See https://crbug.com/boringssl/287.
182 if (__builtin_available(macos 10.12, *)) {
183 *urandom_fd_bss_get() = kHaveGetrandom;
184 return;
185 }
186 #endif
187
188 #if defined(FREEBSD_GETRANDOM)
189 *urandom_fd_bss_get() = kHaveGetrandom;
190 return;
191 #endif
192
193 // Android FIPS builds must support getrandom.
194 #if defined(BORINGSSL_FIPS) && defined(OPENSSL_ANDROID)
195 perror("getrandom not found");
196 abort();
197 #endif
198
199 int fd;
200 do {
201 fd = open("/dev/urandom", O_RDONLY);
202 } while (fd == -1 && errno == EINTR);
203
204 if (fd < 0) {
205 perror("failed to open /dev/urandom");
206 abort();
207 }
208
209 int flags = fcntl(fd, F_GETFD);
210 if (flags == -1) {
211 // Native Client doesn't implement |fcntl|.
212 if (errno != ENOSYS) {
213 perror("failed to get flags from urandom fd");
214 abort();
215 }
216 } else {
217 flags |= FD_CLOEXEC;
218 if (fcntl(fd, F_SETFD, flags) == -1) {
219 perror("failed to set FD_CLOEXEC on urandom fd");
220 abort();
221 }
222 }
223 *urandom_fd_bss_get() = fd;
224 }
225
DEFINE_STATIC_ONCE(wait_for_entropy_once)226 DEFINE_STATIC_ONCE(wait_for_entropy_once)
227
228 static void wait_for_entropy(void) {
229 int fd = *urandom_fd_bss_get();
230 if (fd == kHaveGetrandom) {
231 // |getrandom| and |getentropy| support blocking in |fill_with_entropy|
232 // directly. For |getrandom|, we first probe with a non-blocking call to aid
233 // debugging.
234 #if defined(USE_NR_getrandom)
235 if (*getrandom_ready_bss_get()) {
236 // The entropy pool was already initialized in |init_once|.
237 return;
238 }
239
240 uint8_t dummy;
241 ssize_t getrandom_ret =
242 boringssl_getrandom(&dummy, sizeof(dummy), GRND_NONBLOCK);
243 if (getrandom_ret == -1 && errno == EAGAIN) {
244 // Attempt to get the path of the current process to aid in debugging when
245 // something blocks.
246 const char *current_process = "<unknown>";
247 #if defined(OPENSSL_HAS_GETAUXVAL)
248 const unsigned long getauxval_ret = getauxval(AT_EXECFN);
249 if (getauxval_ret != 0) {
250 current_process = (const char *)getauxval_ret;
251 }
252 #endif
253
254 fprintf(
255 stderr,
256 "%s: getrandom indicates that the entropy pool has not been "
257 "initialized. Rather than continue with poor entropy, this process "
258 "will block until entropy is available.\n",
259 current_process);
260
261 getrandom_ret =
262 boringssl_getrandom(&dummy, sizeof(dummy), 0 /* no flags */);
263 }
264
265 if (getrandom_ret != 1) {
266 perror("getrandom");
267 abort();
268 }
269 #endif // USE_NR_getrandom
270 return;
271 }
272
273 #if defined(BORINGSSL_FIPS) && !defined(URANDOM_BLOCKS_FOR_ENTROPY)
274 // In FIPS mode on platforms where urandom doesn't block at startup, we ensure
275 // that the kernel has sufficient entropy before continuing. This is
276 // automatically handled by getrandom, which requires that the entropy pool
277 // has been initialised, but for urandom we have to poll.
278 for (;;) {
279 int entropy_bits;
280 if (ioctl(fd, RNDGETENTCNT, &entropy_bits)) {
281 fprintf(stderr,
282 "RNDGETENTCNT on /dev/urandom failed. We cannot continue in this "
283 "case when in FIPS mode.\n");
284 abort();
285 }
286
287 static const int kBitsNeeded = 256;
288 if (entropy_bits >= kBitsNeeded) {
289 break;
290 }
291
292 usleep(250000);
293 }
294 #endif // BORINGSSL_FIPS && !URANDOM_BLOCKS_FOR_ENTROPY
295 }
296
297 // fill_with_entropy writes |len| bytes of entropy into |out|. It returns one
298 // on success and zero on error. If |block| is one, this function will block
299 // until the entropy pool is initialized. Otherwise, this function may fail,
300 // setting |errno| to |EAGAIN| if the entropy pool has not yet been initialized.
301 // If |seed| is one, this function will OR in the value of
302 // |*extra_getrandom_flags_for_seed()| when using |getrandom|.
fill_with_entropy(uint8_t * out,size_t len,int block,int seed)303 static int fill_with_entropy(uint8_t *out, size_t len, int block, int seed) {
304 if (len == 0) {
305 return 1;
306 }
307
308 #if defined(USE_NR_getrandom) || defined(FREEBSD_GETRANDOM)
309 int getrandom_flags = 0;
310 if (!block) {
311 getrandom_flags |= GRND_NONBLOCK;
312 }
313 #endif
314
315 #if defined (USE_NR_getrandom)
316 if (seed) {
317 getrandom_flags |= *extra_getrandom_flags_for_seed_bss_get();
318 }
319 #endif
320
321 CRYPTO_init_sysrand();
322 if (block) {
323 CRYPTO_once(wait_for_entropy_once_bss_get(), wait_for_entropy);
324 }
325
326 // Clear |errno| so it has defined value if |read| or |getrandom|
327 // "successfully" returns zero.
328 errno = 0;
329 while (len > 0) {
330 ssize_t r;
331
332 if (*urandom_fd_bss_get() == kHaveGetrandom) {
333 #if defined(USE_NR_getrandom)
334 r = boringssl_getrandom(out, len, getrandom_flags);
335 #elif defined(FREEBSD_GETRANDOM)
336 r = getrandom(out, len, getrandom_flags);
337 #elif defined(OPENSSL_MACOS)
338 if (__builtin_available(macos 10.12, *)) {
339 // |getentropy| can only request 256 bytes at a time.
340 size_t todo = len <= 256 ? len : 256;
341 if (getentropy(out, todo) != 0) {
342 r = -1;
343 } else {
344 r = (ssize_t)todo;
345 }
346 } else {
347 fprintf(stderr, "urandom fd corrupt.\n");
348 abort();
349 }
350 #else // USE_NR_getrandom
351 fprintf(stderr, "urandom fd corrupt.\n");
352 abort();
353 #endif
354 } else {
355 do {
356 r = read(*urandom_fd_bss_get(), out, len);
357 } while (r == -1 && errno == EINTR);
358 }
359
360 if (r <= 0) {
361 return 0;
362 }
363 out += r;
364 len -= r;
365 }
366
367 return 1;
368 }
369
CRYPTO_init_sysrand(void)370 void CRYPTO_init_sysrand(void) {
371 CRYPTO_once(rand_once_bss_get(), init_once);
372 }
373
374 // CRYPTO_sysrand puts |requested| random bytes into |out|.
CRYPTO_sysrand(uint8_t * out,size_t requested)375 void CRYPTO_sysrand(uint8_t *out, size_t requested) {
376 if (!fill_with_entropy(out, requested, /*block=*/1, /*seed=*/0)) {
377 perror("entropy fill failed");
378 abort();
379 }
380 }
381
CRYPTO_sysrand_for_seed(uint8_t * out,size_t requested)382 void CRYPTO_sysrand_for_seed(uint8_t *out, size_t requested) {
383 if (!fill_with_entropy(out, requested, /*block=*/1, /*seed=*/1)) {
384 perror("entropy fill failed");
385 abort();
386 }
387 }
388
CRYPTO_sysrand_if_available(uint8_t * out,size_t requested)389 int CRYPTO_sysrand_if_available(uint8_t *out, size_t requested) {
390 if (fill_with_entropy(out, requested, /*block=*/0, /*seed=*/0)) {
391 return 1;
392 } else if (errno == EAGAIN) {
393 OPENSSL_memset(out, 0, requested);
394 return 0;
395 } else {
396 perror("opportunistic entropy fill failed");
397 abort();
398 }
399 }
400
401 #endif // OPENSSL_URANDOM
402