1 /* Copyright (c) 2016, 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 #include <openssl/rand.h>
16 
17 #if defined(BORINGSSL_UNSAFE_DETERMINISTIC_MODE)
18 
19 #include <string.h>
20 
21 #include <openssl/chacha.h>
22 
23 #include "../internal.h"
24 #include "../fipsmodule/rand/internal.h"
25 
26 
27 // g_num_calls is the number of calls to |CRYPTO_sysrand| that have occurred.
28 //
29 // This is intentionally not thread-safe. If the fuzzer mode is ever used in a
30 // multi-threaded program, replace this with a thread-local. (A mutex would not
31 // be deterministic.)
32 static uint64_t g_num_calls = 0;
33 static struct CRYPTO_STATIC_MUTEX g_num_calls_lock = CRYPTO_STATIC_MUTEX_INIT;
34 
RAND_reset_for_fuzzing(void)35 void RAND_reset_for_fuzzing(void) { g_num_calls = 0; }
36 
CRYPTO_sysrand(uint8_t * out,size_t requested)37 void CRYPTO_sysrand(uint8_t *out, size_t requested) {
38   static const uint8_t kZeroKey[32];
39 
40   CRYPTO_STATIC_MUTEX_lock_write(&g_num_calls_lock);
41   uint64_t num_calls = g_num_calls++;
42   CRYPTO_STATIC_MUTEX_unlock_write(&g_num_calls_lock);
43 
44   uint8_t nonce[12];
45   OPENSSL_memset(nonce, 0, sizeof(nonce));
46   OPENSSL_memcpy(nonce, &num_calls, sizeof(num_calls));
47 
48   OPENSSL_memset(out, 0, requested);
49   CRYPTO_chacha_20(out, out, requested, kZeroKey, nonce, 0);
50 }
51 
52 #endif  // BORINGSSL_UNSAFE_DETERMINISTIC_MODE
53