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 #include <openssl/thread.h>
66 #include <openssl/mem.h>
67
68 #include "../delocate.h"
69 #include "../../internal.h"
70
71
72 #if defined(OPENSSL_LINUX)
73
74 #if defined(OPENSSL_X86_64)
75 #define EXPECTED_NR_getrandom 318
76 #elif defined(OPENSSL_X86)
77 #define EXPECTED_NR_getrandom 355
78 #elif defined(OPENSSL_AARCH64)
79 #define EXPECTED_NR_getrandom 278
80 #elif defined(OPENSSL_ARM)
81 #define EXPECTED_NR_getrandom 384
82 #elif defined(OPENSSL_PPC64LE)
83 #define EXPECTED_NR_getrandom 359
84 #endif
85
86 #if defined(EXPECTED_NR_getrandom)
87 #define USE_NR_getrandom
88
89 #if defined(__NR_getrandom)
90
91 #if __NR_getrandom != EXPECTED_NR_getrandom
92 #error "system call number for getrandom is not the expected value"
93 #endif
94
95 #else // __NR_getrandom
96
97 #define __NR_getrandom EXPECTED_NR_getrandom
98
99 #endif // __NR_getrandom
100
101 #if defined(OPENSSL_MSAN)
102 void __msan_unpoison(void *, size_t);
103 #endif
104
boringssl_getrandom(void * buf,size_t buf_len,unsigned flags)105 static ssize_t boringssl_getrandom(void *buf, size_t buf_len, unsigned flags) {
106 ssize_t ret;
107 do {
108 ret = syscall(__NR_getrandom, buf, buf_len, flags);
109 } while (ret == -1 && errno == EINTR);
110
111 #if defined(OPENSSL_MSAN)
112 if (ret > 0) {
113 // MSAN doesn't recognise |syscall| and thus doesn't notice that we have
114 // initialised the output buffer.
115 __msan_unpoison(buf, ret);
116 }
117 #endif // OPENSSL_MSAN
118
119 return ret;
120 }
121
122 #endif // EXPECTED_NR_getrandom
123
124 #if !defined(GRND_NONBLOCK)
125 #define GRND_NONBLOCK 1
126 #endif
127 #if !defined(GRND_RANDOM)
128 #define GRND_RANDOM 2
129 #endif
130
131 #endif // OPENSSL_LINUX
132
133 // rand_lock is used to protect the |*_requested| variables.
134 DEFINE_STATIC_MUTEX(rand_lock)
135
136 // The following constants are magic values of |urandom_fd|.
137 static const int kUnset = 0;
138 static const int kHaveGetrandom = -3;
139
140 // urandom_fd_requested is set by |RAND_set_urandom_fd|. It's protected by
141 // |rand_lock|.
DEFINE_BSS_GET(int,urandom_fd_requested)142 DEFINE_BSS_GET(int, urandom_fd_requested)
143
144 // urandom_fd is a file descriptor to /dev/urandom. It's protected by |once|.
145 DEFINE_BSS_GET(int, urandom_fd)
146
147 #if defined(USE_NR_getrandom)
148
149 // getrandom_ready is one if |getrandom| had been initialized by the time
150 // |init_once| was called and zero otherwise.
151 DEFINE_BSS_GET(int, getrandom_ready)
152
153 // extra_getrandom_flags_for_seed contains a value that is ORed into the flags
154 // for getrandom() when reading entropy for a seed.
155 DEFINE_BSS_GET(int, extra_getrandom_flags_for_seed)
156
157 // On Android, check a system property to decide whether to set
158 // |extra_getrandom_flags_for_seed| otherwise they will default to zero. If
159 // ro.oem_boringcrypto_hwrand is true then |extra_getrandom_flags_for_seed| will
160 // be set to GRND_RANDOM, causing all random data to be drawn from the same
161 // source as /dev/random.
162 static void maybe_set_extra_getrandom_flags(void) {
163 #if defined(BORINGSSL_FIPS) && defined(OPENSSL_ANDROID)
164 char value[PROP_VALUE_MAX + 1];
165 int length = __system_property_get("ro.boringcrypto.hwrand", value);
166 if (length < 0 || length > PROP_VALUE_MAX) {
167 return;
168 }
169
170 value[length] = 0;
171 if (strcasecmp(value, "true") == 0) {
172 *extra_getrandom_flags_for_seed_bss_get() = GRND_RANDOM;
173 }
174 #endif
175 }
176
177 #endif // USE_NR_getrandom
178
DEFINE_STATIC_ONCE(rand_once)179 DEFINE_STATIC_ONCE(rand_once)
180
181 // init_once initializes the state of this module to values previously
182 // requested. This is the only function that modifies |urandom_fd| and
183 // |urandom_buffering|, whose values may be read safely after calling the
184 // once.
185 static void init_once(void) {
186 CRYPTO_STATIC_MUTEX_lock_read(rand_lock_bss_get());
187 int fd = *urandom_fd_requested_bss_get();
188 CRYPTO_STATIC_MUTEX_unlock_read(rand_lock_bss_get());
189
190 #if defined(USE_NR_getrandom)
191 int have_getrandom;
192 uint8_t dummy;
193 ssize_t getrandom_ret =
194 boringssl_getrandom(&dummy, sizeof(dummy), GRND_NONBLOCK);
195 if (getrandom_ret == 1) {
196 *getrandom_ready_bss_get() = 1;
197 have_getrandom = 1;
198 } else if (getrandom_ret == -1 && errno == EAGAIN) {
199 // We have getrandom, but the entropy pool has not been initialized yet.
200 have_getrandom = 1;
201 } else if (getrandom_ret == -1 && errno == ENOSYS) {
202 // Fallthrough to using /dev/urandom, below.
203 have_getrandom = 0;
204 } else {
205 // Other errors are fatal.
206 perror("getrandom");
207 abort();
208 }
209
210 if (have_getrandom) {
211 *urandom_fd_bss_get() = kHaveGetrandom;
212 maybe_set_extra_getrandom_flags();
213 return;
214 }
215 #endif // USE_NR_getrandom
216
217 #if defined(OPENSSL_MACOS)
218 // getentropy is available in macOS 10.12 and up. iOS 10 and up may also
219 // support it, but the header is missing. See https://crbug.com/boringssl/287.
220 if (__builtin_available(macos 10.12, *)) {
221 *urandom_fd_bss_get() = kHaveGetrandom;
222 return;
223 }
224 #endif
225
226 // Android FIPS builds must support getrandom.
227 #if defined(BORINGSSL_FIPS) && defined(OPENSSL_ANDROID)
228 perror("getrandom not found");
229 abort();
230 #endif
231
232 if (fd == kUnset) {
233 do {
234 fd = open("/dev/urandom", O_RDONLY);
235 } while (fd == -1 && errno == EINTR);
236 }
237
238 if (fd < 0) {
239 perror("failed to open /dev/urandom");
240 abort();
241 }
242
243 assert(kUnset == 0);
244 if (fd == kUnset) {
245 // Because we want to keep |urandom_fd| in the BSS, we have to initialise
246 // it to zero. But zero is a valid file descriptor too. Thus if open
247 // returns zero for /dev/urandom, we dup it to get a non-zero number.
248 fd = dup(fd);
249 close(kUnset);
250
251 if (fd <= 0) {
252 perror("failed to dup /dev/urandom fd");
253 abort();
254 }
255 }
256
257 int flags = fcntl(fd, F_GETFD);
258 if (flags == -1) {
259 // Native Client doesn't implement |fcntl|.
260 if (errno != ENOSYS) {
261 perror("failed to get flags from urandom fd");
262 abort();
263 }
264 } else {
265 flags |= FD_CLOEXEC;
266 if (fcntl(fd, F_SETFD, flags) == -1) {
267 perror("failed to set FD_CLOEXEC on urandom fd");
268 abort();
269 }
270 }
271 *urandom_fd_bss_get() = fd;
272 }
273
DEFINE_STATIC_ONCE(wait_for_entropy_once)274 DEFINE_STATIC_ONCE(wait_for_entropy_once)
275
276 static void wait_for_entropy(void) {
277 int fd = *urandom_fd_bss_get();
278 if (fd == kHaveGetrandom) {
279 // |getrandom| and |getentropy| support blocking in |fill_with_entropy|
280 // directly. For |getrandom|, we first probe with a non-blocking call to aid
281 // debugging.
282 #if defined(USE_NR_getrandom)
283 if (*getrandom_ready_bss_get()) {
284 // The entropy pool was already initialized in |init_once|.
285 return;
286 }
287
288 uint8_t dummy;
289 ssize_t getrandom_ret =
290 boringssl_getrandom(&dummy, sizeof(dummy), GRND_NONBLOCK);
291 if (getrandom_ret == -1 && errno == EAGAIN) {
292 // Attempt to get the path of the current process to aid in debugging when
293 // something blocks.
294 const char *current_process = "<unknown>";
295 #if defined(OPENSSL_HAS_GETAUXVAL)
296 const unsigned long getauxval_ret = getauxval(AT_EXECFN);
297 if (getauxval_ret != 0) {
298 current_process = (const char *)getauxval_ret;
299 }
300 #endif
301
302 fprintf(
303 stderr,
304 "%s: getrandom indicates that the entropy pool has not been "
305 "initialized. Rather than continue with poor entropy, this process "
306 "will block until entropy is available.\n",
307 current_process);
308
309 getrandom_ret =
310 boringssl_getrandom(&dummy, sizeof(dummy), 0 /* no flags */);
311 }
312
313 if (getrandom_ret != 1) {
314 perror("getrandom");
315 abort();
316 }
317 #endif // USE_NR_getrandom
318 return;
319 }
320
321 #if defined(BORINGSSL_FIPS)
322 // In FIPS mode we ensure that the kernel has sufficient entropy before
323 // continuing. This is automatically handled by getrandom, which requires
324 // that the entropy pool has been initialised, but for urandom we have to
325 // poll.
326 for (;;) {
327 int entropy_bits;
328 if (ioctl(fd, RNDGETENTCNT, &entropy_bits)) {
329 fprintf(stderr,
330 "RNDGETENTCNT on /dev/urandom failed. We cannot continue in this "
331 "case when in FIPS mode.\n");
332 abort();
333 }
334
335 static const int kBitsNeeded = 256;
336 if (entropy_bits >= kBitsNeeded) {
337 break;
338 }
339
340 usleep(250000);
341 }
342 #endif // BORINGSSL_FIPS
343 }
344
RAND_set_urandom_fd(int fd)345 void RAND_set_urandom_fd(int fd) {
346 fd = dup(fd);
347 if (fd < 0) {
348 perror("failed to dup supplied urandom fd");
349 abort();
350 }
351
352 assert(kUnset == 0);
353 if (fd == kUnset) {
354 // Because we want to keep |urandom_fd| in the BSS, we have to initialise
355 // it to zero. But zero is a valid file descriptor too. Thus if dup
356 // returned zero we dup it again to get a non-zero number.
357 fd = dup(fd);
358 close(kUnset);
359
360 if (fd <= 0) {
361 perror("failed to dup supplied urandom fd");
362 abort();
363 }
364 }
365
366 CRYPTO_STATIC_MUTEX_lock_write(rand_lock_bss_get());
367 *urandom_fd_requested_bss_get() = fd;
368 CRYPTO_STATIC_MUTEX_unlock_write(rand_lock_bss_get());
369
370 CRYPTO_once(rand_once_bss_get(), init_once);
371 if (*urandom_fd_bss_get() == kHaveGetrandom) {
372 close(fd);
373 } else if (*urandom_fd_bss_get() != fd) {
374 fprintf(stderr, "RAND_set_urandom_fd called after initialisation.\n");
375 abort();
376 }
377 }
378
379 // fill_with_entropy writes |len| bytes of entropy into |out|. It returns one
380 // on success and zero on error. If |block| is one, this function will block
381 // until the entropy pool is initialized. Otherwise, this function may fail,
382 // setting |errno| to |EAGAIN| if the entropy pool has not yet been initialized.
383 // If |seed| is one, this function will OR in the value of
384 // |*extra_getrandom_flags_for_seed()| when using |getrandom|.
fill_with_entropy(uint8_t * out,size_t len,int block,int seed)385 static int fill_with_entropy(uint8_t *out, size_t len, int block, int seed) {
386 if (len == 0) {
387 return 1;
388 }
389
390 #if defined(USE_NR_getrandom)
391 int getrandom_flags = 0;
392 if (!block) {
393 getrandom_flags |= GRND_NONBLOCK;
394 }
395 if (seed) {
396 getrandom_flags |= *extra_getrandom_flags_for_seed_bss_get();
397 }
398 #endif
399
400 CRYPTO_once(rand_once_bss_get(), init_once);
401 if (block) {
402 CRYPTO_once(wait_for_entropy_once_bss_get(), wait_for_entropy);
403 }
404
405 // Clear |errno| so it has defined value if |read| or |getrandom|
406 // "successfully" returns zero.
407 errno = 0;
408 while (len > 0) {
409 ssize_t r;
410
411 if (*urandom_fd_bss_get() == kHaveGetrandom) {
412 #if defined(USE_NR_getrandom)
413 r = boringssl_getrandom(out, len, getrandom_flags);
414 #elif defined(OPENSSL_MACOS)
415 if (__builtin_available(macos 10.12, *)) {
416 // |getentropy| can only request 256 bytes at a time.
417 size_t todo = len <= 256 ? len : 256;
418 if (getentropy(out, todo) != 0) {
419 r = -1;
420 } else {
421 r = (ssize_t)todo;
422 }
423 } else {
424 fprintf(stderr, "urandom fd corrupt.\n");
425 abort();
426 }
427 #else // USE_NR_getrandom
428 fprintf(stderr, "urandom fd corrupt.\n");
429 abort();
430 #endif
431 } else {
432 do {
433 r = read(*urandom_fd_bss_get(), out, len);
434 } while (r == -1 && errno == EINTR);
435 }
436
437 if (r <= 0) {
438 return 0;
439 }
440 out += r;
441 len -= r;
442 }
443
444 return 1;
445 }
446
447 // CRYPTO_sysrand puts |requested| random bytes into |out|.
CRYPTO_sysrand(uint8_t * out,size_t requested)448 void CRYPTO_sysrand(uint8_t *out, size_t requested) {
449 if (!fill_with_entropy(out, requested, /*block=*/1, /*seed=*/0)) {
450 perror("entropy fill failed");
451 abort();
452 }
453 }
454
455 #if defined(BORINGSSL_FIPS)
CRYPTO_sysrand_for_seed(uint8_t * out,size_t requested)456 void CRYPTO_sysrand_for_seed(uint8_t *out, size_t requested) {
457 if (!fill_with_entropy(out, requested, /*block=*/1, /*seed=*/1)) {
458 perror("entropy fill failed");
459 abort();
460 }
461
462 #if defined(BORINGSSL_FIPS_BREAK_CRNG)
463 // This breaks the "continuous random number generator test" defined in FIPS
464 // 140-2, section 4.9.2, and implemented in rand_get_seed().
465 OPENSSL_memset(out, 0, requested);
466 #endif
467 }
468
CRYPTO_sysrand_if_available(uint8_t * out,size_t requested)469 void CRYPTO_sysrand_if_available(uint8_t *out, size_t requested) {
470 // Return all zeros if |fill_with_entropy| fails.
471 OPENSSL_memset(out, 0, requested);
472
473 if (!fill_with_entropy(out, requested, /*block=*/0, /*seed=*/0) &&
474 errno != EAGAIN) {
475 perror("opportunistic entropy fill failed");
476 abort();
477 }
478 }
479 #endif // BORINGSSL_FIPS
480
481 #endif // OPENSSL_URANDOM
482