2 * Crypto-quality random number functions
4 * Author: Harlan Stenn, 2014
6 * This file is Copyright (c) 2014 by Network Time Foundation.
7 * BSD terms apply: see the file COPYRIGHT in the distribution root for details.
11 #include <sys/types.h>
18 #include <ntp_random.h>
21 #ifdef USE_OPENSSL_CRYPTO_RAND
22 #include <openssl/err.h>
23 #include <openssl/rand.h>
25 int crypto_rand_init = 0;
28 # ifndef HAVE_ARC4RANDOM_BUF
30 arc4random_buf(void *buf, size_t nbytes);
33 evutil_secure_rng_get_bytes(void *buf, size_t nbytes);
36 arc4random_buf(void *buf, size_t nbytes)
38 evutil_secure_rng_get_bytes(buf, nbytes);
45 * As of late 2014, here's how we plan to provide cryptographic-quality
48 * - If we are building with OpenSSL, use RAND_poll() and RAND_bytes().
49 * - Otherwise, use arc4random().
51 * Use of arc4random() can be forced using configure --disable-openssl-random
53 * We can count on arc4random existing, thru the OS or thru libevent.
54 * The quality of arc4random depends on the implementor.
56 * RAND_poll() doesn't show up until XXX. If it's not present, we
57 * need to either provide our own or use arc4random().
63 * Initialize the random number generator, if needed by the underlying
64 * crypto random number generation mechanism.
72 #ifdef USE_OPENSSL_CRYPTO_RAND
73 if (!crypto_rand_init) {
78 /* No initialization needed for arc4random() */
84 * ntp_crypto_random_buf:
86 * Returns 0 on success, -1 on error.
89 ntp_crypto_random_buf(
94 #ifdef USE_OPENSSL_CRYPTO_RAND
97 rc = RAND_bytes(buf, size2int_chk(nbytes));
102 err = ERR_get_error();
103 err_str = ERR_error_string(err, NULL);
104 /* XXX: Log the error */
111 arc4random_buf(buf, nbytes);