• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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) && __FreeBSD__ >= 12
66 // getrandom is supported in FreeBSD 12 and up.
67 #define FREEBSD_GETRANDOM
68 #include <sys/random.h>
69 #endif
70 
71 #include <openssl/thread.h>
72 #include <openssl/mem.h>
73 
74 #include "getrandom_fillin.h"
75 #include "../delocate.h"
76 #include "../../internal.h"
77 
78 
79 #if defined(USE_NR_getrandom)
80 
81 #if defined(OPENSSL_MSAN)
82 void __msan_unpoison(void *, size_t);
83 #endif
84 
boringssl_getrandom(void * buf,size_t buf_len,unsigned flags)85 static ssize_t boringssl_getrandom(void *buf, size_t buf_len, unsigned flags) {
86   ssize_t ret;
87   do {
88     ret = syscall(__NR_getrandom, buf, buf_len, flags);
89   } while (ret == -1 && errno == EINTR);
90 
91 #if defined(OPENSSL_MSAN)
92   if (ret > 0) {
93     // MSAN doesn't recognise |syscall| and thus doesn't notice that we have
94     // initialised the output buffer.
95     __msan_unpoison(buf, ret);
96   }
97 #endif  // OPENSSL_MSAN
98 
99   return ret;
100 }
101 
102 #endif  // USE_NR_getrandom
103 
104 // kHaveGetrandom in |urandom_fd| signals that |getrandom| or |getentropy| is
105 // available and should be used instead.
106 static const int kHaveGetrandom = -3;
107 
108 // urandom_fd is a file descriptor to /dev/urandom. It's protected by |once|.
DEFINE_BSS_GET(int,urandom_fd)109 DEFINE_BSS_GET(int, urandom_fd)
110 
111 #if defined(USE_NR_getrandom)
112 
113 // getrandom_ready is one if |getrandom| had been initialized by the time
114 // |init_once| was called and zero otherwise.
115 DEFINE_BSS_GET(int, getrandom_ready)
116 
117 // extra_getrandom_flags_for_seed contains a value that is ORed into the flags
118 // for getrandom() when reading entropy for a seed.
119 DEFINE_BSS_GET(int, extra_getrandom_flags_for_seed)
120 
121 // On Android, check a system property to decide whether to set
122 // |extra_getrandom_flags_for_seed| otherwise they will default to zero.  If
123 // ro.oem_boringcrypto_hwrand is true then |extra_getrandom_flags_for_seed| will
124 // be set to GRND_RANDOM, causing all random data to be drawn from the same
125 // source as /dev/random.
126 static void maybe_set_extra_getrandom_flags(void) {
127 #if defined(BORINGSSL_FIPS) && defined(OPENSSL_ANDROID)
128   char value[PROP_VALUE_MAX + 1];
129   int length = __system_property_get("ro.boringcrypto.hwrand", value);
130   if (length < 0 || length > PROP_VALUE_MAX) {
131     return;
132   }
133 
134   value[length] = 0;
135   if (OPENSSL_strcasecmp(value, "true") == 0) {
136     *extra_getrandom_flags_for_seed_bss_get() = GRND_RANDOM;
137   }
138 #endif
139 }
140 
141 #endif  // USE_NR_getrandom
142 
DEFINE_STATIC_ONCE(rand_once)143 DEFINE_STATIC_ONCE(rand_once)
144 
145 // init_once initializes the state of this module to values previously
146 // requested. This is the only function that modifies |urandom_fd|, which may be
147 // read safely after calling the once.
148 static void init_once(void) {
149 #if defined(USE_NR_getrandom)
150   int have_getrandom;
151   uint8_t dummy;
152   ssize_t getrandom_ret =
153       boringssl_getrandom(&dummy, sizeof(dummy), GRND_NONBLOCK);
154   if (getrandom_ret == 1) {
155     *getrandom_ready_bss_get() = 1;
156     have_getrandom = 1;
157   } else if (getrandom_ret == -1 && errno == EAGAIN) {
158     // We have getrandom, but the entropy pool has not been initialized yet.
159     have_getrandom = 1;
160   } else if (getrandom_ret == -1 && errno == ENOSYS) {
161     // Fallthrough to using /dev/urandom, below.
162     have_getrandom = 0;
163   } else {
164     // Other errors are fatal.
165     perror("getrandom");
166     abort();
167   }
168 
169   if (have_getrandom) {
170     *urandom_fd_bss_get() = kHaveGetrandom;
171     maybe_set_extra_getrandom_flags();
172     return;
173   }
174 #endif  // USE_NR_getrandom
175 
176 #if defined(OPENSSL_MACOS)
177   // getentropy is available in macOS 10.12 and up. iOS 10 and up may also
178   // support it, but the header is missing. See https://crbug.com/boringssl/287.
179   if (__builtin_available(macos 10.12, *)) {
180     *urandom_fd_bss_get() = kHaveGetrandom;
181     return;
182   }
183 #endif
184 
185 #if defined(FREEBSD_GETRANDOM)
186   *urandom_fd_bss_get() = kHaveGetrandom;
187   return;
188 #endif
189 
190   // FIPS builds must support getrandom.
191   //
192   // Historically, only Android FIPS builds required getrandom, while Linux FIPS
193   // builds had a /dev/urandom fallback which used RNDGETENTCNT as a poor
194   // approximation for getrandom's blocking behavior. This is now removed, but
195   // avoid making assumptions on this removal until March 2023, in case it needs
196   // to be restored. This comment can be deleted after March 2023.
197 #if defined(BORINGSSL_FIPS)
198   perror("getrandom not found");
199   abort();
200 #endif
201 
202   int fd;
203   do {
204     fd = open("/dev/urandom", O_RDONLY | O_CLOEXEC);
205   } while (fd == -1 && errno == EINTR);
206 
207   if (fd < 0) {
208     perror("failed to open /dev/urandom");
209     abort();
210   }
211 
212   *urandom_fd_bss_get() = fd;
213 }
214 
DEFINE_STATIC_ONCE(wait_for_entropy_once)215 DEFINE_STATIC_ONCE(wait_for_entropy_once)
216 
217 static void wait_for_entropy(void) {
218   int fd = *urandom_fd_bss_get();
219   if (fd == kHaveGetrandom) {
220     // |getrandom| and |getentropy| support blocking in |fill_with_entropy|
221     // directly. For |getrandom|, we first probe with a non-blocking call to aid
222     // debugging.
223 #if defined(USE_NR_getrandom)
224     if (*getrandom_ready_bss_get()) {
225       // The entropy pool was already initialized in |init_once|.
226       return;
227     }
228 
229     uint8_t dummy;
230     ssize_t getrandom_ret =
231         boringssl_getrandom(&dummy, sizeof(dummy), GRND_NONBLOCK);
232     if (getrandom_ret == -1 && errno == EAGAIN) {
233       // Attempt to get the path of the current process to aid in debugging when
234       // something blocks.
235       const char *current_process = "<unknown>";
236 #if defined(OPENSSL_HAS_GETAUXVAL)
237       const unsigned long getauxval_ret = getauxval(AT_EXECFN);
238       if (getauxval_ret != 0) {
239         current_process = (const char *)getauxval_ret;
240       }
241 #endif
242 
243       fprintf(
244           stderr,
245           "%s: getrandom indicates that the entropy pool has not been "
246           "initialized. Rather than continue with poor entropy, this process "
247           "will block until entropy is available.\n",
248           current_process);
249 
250       getrandom_ret =
251           boringssl_getrandom(&dummy, sizeof(dummy), 0 /* no flags */);
252     }
253 
254     if (getrandom_ret != 1) {
255       perror("getrandom");
256       abort();
257     }
258 #endif  // USE_NR_getrandom
259     return;
260   }
261 }
262 
263 // fill_with_entropy writes |len| bytes of entropy into |out|. It returns one
264 // on success and zero on error. If |block| is one, this function will block
265 // until the entropy pool is initialized. Otherwise, this function may fail,
266 // setting |errno| to |EAGAIN| if the entropy pool has not yet been initialized.
267 // If |seed| is one, this function will OR in the value of
268 // |*extra_getrandom_flags_for_seed()| when using |getrandom|.
fill_with_entropy(uint8_t * out,size_t len,int block,int seed)269 static int fill_with_entropy(uint8_t *out, size_t len, int block, int seed) {
270   if (len == 0) {
271     return 1;
272   }
273 
274 #if defined(USE_NR_getrandom) || defined(FREEBSD_GETRANDOM)
275   int getrandom_flags = 0;
276   if (!block) {
277     getrandom_flags |= GRND_NONBLOCK;
278   }
279 #endif
280 
281 #if defined (USE_NR_getrandom)
282   if (seed) {
283     getrandom_flags |= *extra_getrandom_flags_for_seed_bss_get();
284   }
285 #endif
286 
287   CRYPTO_init_sysrand();
288   if (block) {
289     CRYPTO_once(wait_for_entropy_once_bss_get(), wait_for_entropy);
290   }
291 
292   // Clear |errno| so it has defined value if |read| or |getrandom|
293   // "successfully" returns zero.
294   errno = 0;
295   while (len > 0) {
296     ssize_t r;
297 
298     if (*urandom_fd_bss_get() == kHaveGetrandom) {
299 #if defined(USE_NR_getrandom)
300       r = boringssl_getrandom(out, len, getrandom_flags);
301 #elif defined(FREEBSD_GETRANDOM)
302       r = getrandom(out, len, getrandom_flags);
303 #elif defined(OPENSSL_MACOS)
304       if (__builtin_available(macos 10.12, *)) {
305         // |getentropy| can only request 256 bytes at a time.
306         size_t todo = len <= 256 ? len : 256;
307         if (getentropy(out, todo) != 0) {
308           r = -1;
309         } else {
310           r = (ssize_t)todo;
311         }
312       } else {
313         fprintf(stderr, "urandom fd corrupt.\n");
314         abort();
315       }
316 #else  // USE_NR_getrandom
317       fprintf(stderr, "urandom fd corrupt.\n");
318       abort();
319 #endif
320     } else {
321       do {
322         r = read(*urandom_fd_bss_get(), out, len);
323       } while (r == -1 && errno == EINTR);
324     }
325 
326     if (r <= 0) {
327       return 0;
328     }
329     out += r;
330     len -= r;
331   }
332 
333   return 1;
334 }
335 
CRYPTO_init_sysrand(void)336 void CRYPTO_init_sysrand(void) {
337   CRYPTO_once(rand_once_bss_get(), init_once);
338 }
339 
340 // CRYPTO_sysrand puts |requested| random bytes into |out|.
CRYPTO_sysrand(uint8_t * out,size_t requested)341 void CRYPTO_sysrand(uint8_t *out, size_t requested) {
342   if (!fill_with_entropy(out, requested, /*block=*/1, /*seed=*/0)) {
343     perror("entropy fill failed");
344     abort();
345   }
346 }
347 
CRYPTO_sysrand_for_seed(uint8_t * out,size_t requested)348 void CRYPTO_sysrand_for_seed(uint8_t *out, size_t requested) {
349   if (!fill_with_entropy(out, requested, /*block=*/1, /*seed=*/1)) {
350     perror("entropy fill failed");
351     abort();
352   }
353 }
354 
CRYPTO_sysrand_if_available(uint8_t * out,size_t requested)355 int CRYPTO_sysrand_if_available(uint8_t *out, size_t requested) {
356   if (fill_with_entropy(out, requested, /*block=*/0, /*seed=*/0)) {
357     return 1;
358   } else if (errno == EAGAIN) {
359     OPENSSL_memset(out, 0, requested);
360     return 0;
361   } else {
362     perror("opportunistic entropy fill failed");
363     abort();
364   }
365 }
366 
367 #endif  // OPENSSL_URANDOM
368