xref: /aosp_15_r20/external/boringssl/src/crypto/rand_extra/deterministic.c (revision 8fb009dc861624b67b6cdb62ea21f0f22d0c584b)
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 #include "../fipsmodule/rand/internal.h"
18 
19 #if defined(OPENSSL_RAND_DETERMINISTIC)
20 
21 #include <string.h>
22 
23 #include <openssl/chacha.h>
24 
25 #include "../internal.h"
26 
27 
28 // g_num_calls is the number of calls to |CRYPTO_sysrand| that have occurred.
29 //
30 // This is intentionally not thread-safe. If the fuzzer mode is ever used in a
31 // multi-threaded program, replace this with a thread-local. (A mutex would not
32 // be deterministic.)
33 static uint64_t g_num_calls = 0;
34 static CRYPTO_MUTEX g_num_calls_lock = CRYPTO_MUTEX_INIT;
35 
RAND_reset_for_fuzzing(void)36 void RAND_reset_for_fuzzing(void) { g_num_calls = 0; }
37 
CRYPTO_sysrand(uint8_t * out,size_t requested)38 void CRYPTO_sysrand(uint8_t *out, size_t requested) {
39   static const uint8_t kZeroKey[32];
40 
41   CRYPTO_MUTEX_lock_write(&g_num_calls_lock);
42   uint64_t num_calls = g_num_calls++;
43   CRYPTO_MUTEX_unlock_write(&g_num_calls_lock);
44 
45   uint8_t nonce[12];
46   OPENSSL_memset(nonce, 0, sizeof(nonce));
47   OPENSSL_memcpy(nonce, &num_calls, sizeof(num_calls));
48 
49   OPENSSL_memset(out, 0, requested);
50   CRYPTO_chacha_20(out, out, requested, kZeroKey, nonce, 0);
51 }
52 
CRYPTO_sysrand_for_seed(uint8_t * out,size_t requested)53 void CRYPTO_sysrand_for_seed(uint8_t *out, size_t requested) {
54   CRYPTO_sysrand(out, requested);
55 }
56 
57 #endif  // OPENSSL_RAND_DETERMINISTIC
58