1 /* Copyright (c) 2023, 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(_DEFAULT_SOURCE)
16 #define _DEFAULT_SOURCE // Needed for getentropy on musl and glibc
17 #endif
18
19 #include <openssl/rand.h>
20
21 #include "../fipsmodule/rand/internal.h"
22
23 #if defined(OPENSSL_RAND_GETENTROPY)
24
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <unistd.h>
28
29 #if defined(OPENSSL_MACOS) || defined(OPENSSL_FUCHSIA)
30 #include <sys/random.h>
31 #endif
32
33 // CRYPTO_sysrand puts |requested| random bytes into |out|.
CRYPTO_sysrand(uint8_t * out,size_t requested)34 void CRYPTO_sysrand(uint8_t *out, size_t requested) {
35 while (requested > 0) {
36 // |getentropy| can only request 256 bytes at a time.
37 size_t todo = requested <= 256 ? requested : 256;
38 if (getentropy(out, todo) != 0) {
39 perror("getentropy() failed");
40 abort();
41 }
42
43 out += todo;
44 requested -= todo;
45 }
46 }
47
CRYPTO_sysrand_for_seed(uint8_t * out,size_t requested)48 void CRYPTO_sysrand_for_seed(uint8_t *out, size_t requested) {
49 CRYPTO_sysrand(out, requested);
50 }
51
52 #endif // OPENSSL_RAND_GETENTROPY
53