Debian Codegraph @

debian/rust-vendor/aws-lc-sys/aws-lc/crypto/fipsmodule/rand/rand.c

raw
1 // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
2 // SPDX-License-Identifier: Apache-2.0 OR ISC
3
4 #include <openssl/rand.h>
5 #include <openssl/mem.h>
6 #include <openssl/ctrdrbg.h>
7 #include <openssl/type_check.h>
8
9 #include "entropy/internal.h"
10 #include "internal.h"
11 #include "../../internal.h"
12 #include "../../ube/internal.h"
13 #include "../delocate.h"
14 #include "../service_indicator/internal.h"
15
16 // rand_thread_state contains the per-thread state for the RNG.
17 struct rand_thread_local_state {
18 // Thread-local CTR-DRBG state. UBE unique state.
19 CTR_DRBG_STATE drbg;
20
21 // generate_calls_since_seed is the number of generate calls made on |drbg|
22 // since it was last (re)seeded. Must be bounded by |kCtrDrbgReseedInterval|.
23 uint64_t generate_calls_since_seed;
24
25 // reseed_calls_since_initialization is the number of reseed calls made on
26 // |drbg| since its initialization.
27 // We assume 2^64 - 1 is an upper bound on the number of reseeds. Type must
28 // support that.
29 uint64_t reseed_calls_since_initialization;
30
31 // generation_number caches the UBE generation number.
32 uint64_t generation_number;
33
34 // Entropy source. UBE unique state.
35 struct entropy_source_t *entropy_source;
36
37 // Backward and forward references to nodes in a doubly-linked list.
38 struct rand_thread_local_state *next;
39 struct rand_thread_local_state *previous;
40
41 // Lock used when globally clearing (zeroising) all thread-local states at
42 // process exit.
43 CRYPTO_MUTEX state_clear_lock;
44 };
45 OPENSSL_STATIC_ASSERT((sizeof((struct rand_thread_local_state*)0)->generate_calls_since_seed) * 8 >= 48, value_can_overflow)
46
47 DEFINE_BSS_GET(struct rand_thread_local_state *, thread_states_list_head)
48 DEFINE_STATIC_MUTEX(thread_local_states_list_lock)
49
50 // thread_local_drbg_shutdown_started is set to a non-zero value during process
51 // exit by |rand_thread_local_state_clear_all|, while the linked-list lock is
52 // held. All reads and writes occur under |thread_local_states_list_lock|, so
53 // no atomic accessors are needed; doing the check under the lock also avoids
54 // the otherwise-racy window where a TLS destructor could observe the flag as
55 // unset, then block on the lock while shutdown zeroization runs, and then
56 // free a state whose |state_clear_lock| has been intentionally write-locked
57 // forever.
58 DEFINE_BSS_GET(int, thread_local_drbg_shutdown_started)
59
60 #if defined(_MSC_VER)
61 #pragma section(".CRT$XCU", read)
62 static void rand_thread_local_state_clear_all(void);
63 static void windows_install_rand_thread_local_state_clear_all(void) {
64 atexit(&rand_thread_local_state_clear_all);
65 }
66 __declspec(allocate(".CRT$XCU")) void(*rand_fips_library_destructor)(void) =
67 windows_install_rand_thread_local_state_clear_all;
68 #else
69 static void rand_thread_local_state_clear_all(void) __attribute__ ((destructor));
70 #endif
71
72 // At process exit not all threads will be scheduled and proper exited. To
73 // ensure no secret state is left, globally clear all thread-local states. This
74 // is a FIPS-derived requirement, see ISO/IEC 19790-2012 7.9.7.
75 //
76 // This is problematic because a thread might be scheduled and return
77 // randomness from a non-valid state. The linked application should obviously
78 // arrange that all threads are gracefully exited before exiting the process.
79 // Yet, in cases where such graceful exit does not happen we ensure that no
80 // output can be returned by locking each thread-local state's
81 // |state_clear_lock| and deliberately not releasing it. A synchronization step
82 // in the core randomness generation routine |RAND_bytes_core| then ensures
83 // that no randomness generation can occur after a thread-local state has been
84 // locked.
85 //
86 // We additionally set |thread_local_drbg_shutdown_started| under the
87 // linked-list lock so that any thread which has not yet registered a
88 // thread-local state cannot do so after this routine has begun zeroization;
89 // without this, a fresh thread could allocate a state and bypass zeroization.
90 // The linked-list lock itself is released at the end of this function. If we
91 // instead held it forever, |thread_local_list_delete_node| (called from a
92 // thread's TLS destructor in |rand_thread_local_state_free|) would block
93 // indefinitely. On Windows, TLS destructors run under the loader lock, so
94 // blocking there causes |ExitProcess| to hang waiting for the loader lock.
95 // See https://github.com/aws/aws-lc/issues/3197.
96 //
97 // When a thread-local DRBG is gated from returning output, we can invoke the
98 // entropy source zeroization from |state->entropy_source|. The entropy source
99 // implementation can assume that any returned seed is never used to generate
100 // any randomness that is later returned to a consumer.
101 static void rand_thread_local_state_clear_all(void) {
102 CRYPTO_STATIC_MUTEX_lock_write(thread_local_states_list_lock_bss_get());
103
104 // Idempotency guard. Under normal operation this routine runs exactly once
105 // (via |atexit|), but it is also exposed for testing via
106 // |rand_thread_local_state_clear_all_FOR_TESTING|, and re-running would
107 // attempt to write-lock per-state |state_clear_lock|s that are already held
108 // write-locked by the first invocation -- which is UB for a non-recursive
109 // rwlock.
110 if (*thread_local_drbg_shutdown_started_bss_get() != 0) {
111 CRYPTO_STATIC_MUTEX_unlock_write(thread_local_states_list_lock_bss_get());
112 return;
113 }
114 *thread_local_drbg_shutdown_started_bss_get() = 1;
115
116 for (struct rand_thread_local_state *state = *thread_states_list_head_bss_get();
117 state != NULL; state = state->next) {
118 CRYPTO_MUTEX_lock_write(&state->state_clear_lock);
119 CTR_DRBG_clear(&state->drbg);
120 }
121
122 for (struct rand_thread_local_state *state = *thread_states_list_head_bss_get();
123 state != NULL; state = state->next) {
124 state->entropy_source->methods->zeroize_thread(state->entropy_source);
125 }
126
127 CRYPTO_STATIC_MUTEX_unlock_write(thread_local_states_list_lock_bss_get());
128 }
129
130 void rand_thread_local_state_clear_all_FOR_TESTING(void) {
131 rand_thread_local_state_clear_all();
132 }
133
134 // thread_local_list_delete_node removes |node_delete| from the global
135 // linked list and returns 1. If process-wide shutdown zeroization has already
136 // begun, the node is left in place and 0 is returned -- the caller must not
137 // free the node in that case because |rand_thread_local_state_clear_all| has
138 // write-locked its |state_clear_lock| and intentionally never releases it.
139 static int thread_local_list_delete_node(
140 struct rand_thread_local_state *node_delete) {
141
142 // Mutating the global linked list. Need to synchronize over all threads.
143 CRYPTO_STATIC_MUTEX_lock_write(thread_local_states_list_lock_bss_get());
144
145 // Re-check the shutdown flag under the lock. This makes the
146 // "free vs. shutdown-zeroize" decision atomic with respect to
147 // |rand_thread_local_state_clear_all|: either we delete and free before
148 // shutdown begins, or shutdown wins and we leak the node deliberately.
149 if (*thread_local_drbg_shutdown_started_bss_get() != 0) {
150 CRYPTO_STATIC_MUTEX_unlock_write(thread_local_states_list_lock_bss_get());
151 return 0;
152 }
153
154 struct rand_thread_local_state *node_head = *thread_states_list_head_bss_get();
155
156 // We have [node_delete->previous] <--> [node_delete] <--> [node_delete->next]
157 // and must end up with [node_delete->previous] <--> [node_delete->next]
158 if (node_head == node_delete) {
159 // If node node_delete is the head, we know that the backwards reference
160 // does not exist but we need to update the head pointer.
161 *thread_states_list_head_bss_get() = node_delete->next;
162 } else {
163 // On the other hand, if node_delete is not the head, then we need to update
164 // the node node_delete->previous to point to the node node_delete->next.
165 // But only if node_delete->previous actually exists.
166 if (node_delete->previous != NULL) {
167 (node_delete->previous)->next = node_delete->next;
168 }
169 }
170
171 // Now [node_delete->previous] --> [node_delete->next]
172 // |
173 // [node_delete] <--|
174 // Final thing to do is to update the backwards reference for the node
175 // node_delete->next, if it exists.
176 if (node_delete->next != NULL) {
177 // If node_delete is the head, then node_delete->previous is NULL. But that
178 // is OK because node_delete->next is the new head and should therefore have
179 // a backwards reference that is NULL.
180 (node_delete->next)->previous = node_delete->previous;
181 }
182
183 CRYPTO_STATIC_MUTEX_unlock_write(thread_local_states_list_lock_bss_get());
184 return 1;
185 }
186
187 // thread_local_list_add adds the state |node_add| to the linked list. Note that
188 // |node_add| is not added at the tail of the linked list, but is replacing the
189 // current head to keep the add operation at low time-complexity.
190 static void thread_local_list_add_node(
191 struct rand_thread_local_state *node_add) {
192
193 // node_add will be the new head and will not have a backwards reference.
194 node_add->previous = NULL;
195
196 // Mutating the global linked list. Need to synchronize over all threads.
197 CRYPTO_STATIC_MUTEX_lock_write(thread_local_states_list_lock_bss_get());
198
199 // If process-wide zeroization has already started, do not add a new state to
200 // the list -- it would not have been zeroized by
201 // |rand_thread_local_state_clear_all|. Instead, write-lock the state's
202 // |state_clear_lock| and never release it. This causes any subsequent
203 // |RAND_bytes_core| call on this thread to block forever on the read lock,
204 // matching the FIPS-derived guarantee that no output is returned after
205 // shutdown zeroization.
206 if (*thread_local_drbg_shutdown_started_bss_get() != 0) {
207 CRYPTO_MUTEX_lock_write(&node_add->state_clear_lock);
208 CRYPTO_STATIC_MUTEX_unlock_write(thread_local_states_list_lock_bss_get());
209 return;
210 }
211
212 // First get a reference to the pointer of the head of the linked list.
213 // That is, the pointer to the head node node_head is *thread_states_head.
214 struct rand_thread_local_state **thread_states_head = thread_states_list_head_bss_get();
215
216 // We have [node_head] <--> [node_head->next] and must end up with
217 // [node_add] <--> [node_head] <--> [node_head->next]
218 // First make the forward reference
219 node_add->next = *thread_states_head;
220
221 // Only add a backwards reference if a head already existed (this might be
222 // the first add).
223 if (*thread_states_head != NULL) {
224 (*thread_states_head)->previous = node_add;
225 }
226
227 // The last thing is to assign the new head.
228 *thread_states_head = node_add;
229
230 CRYPTO_STATIC_MUTEX_unlock_write(thread_local_states_list_lock_bss_get());
231 }
232
233 // rand_thread_local_state frees a |rand_thread_local_state|. This is called
234 // when a thread exits.
235 static void rand_thread_local_state_free(void *state_in) {
236
237 struct rand_thread_local_state *state = state_in;
238 if (state_in == NULL) {
239 return;
240 }
241
242 // If process-wide shutdown zeroization has begun, the per-state
243 // |state_clear_lock| has been write-locked and is intentionally never
244 // released (so any in-flight |RAND_bytes| call cannot return output from a
245 // zeroized state). |thread_local_list_delete_node| therefore detects this
246 // case under the linked-list lock and refuses to delete; we must then leak
247 // the node, since freeing it would destroy a held mutex. The OS reclaims
248 // the memory at process exit. See issue #3197.
249 if (thread_local_list_delete_node(state) == 0) {
250 return;
251 }
252
253 // Potentially, something could kill the thread before an entropy source has
254 // been associated to the thread-local randomness generator object.
255 if (state->entropy_source != NULL) {
256 state->entropy_source->methods->free_thread(state->entropy_source);
257 }
258
259 OPENSSL_free(state->entropy_source);
260 OPENSSL_free(state);
261 }
262
263 // rand_ensure_valid_state determines whether |state| is in a valid state. The
264 // reasons are documented with inline comments in the function.
265 //
266 // Returns 1 if |state| is in a valid state and 0 otherwise.
267 static int rand_ensure_valid_state(const struct rand_thread_local_state *state) {
268
269 // Currently, the Go based test runner cannot execute a unit test stanza with
270 // guaranteed sequential execution. VM UBE testing is using a global file
271 // that all unit tests will read if ever taking a path to |RAND_bytes|. The
272 // validation below will have a high likelihood of triggering. Disable the
273 // validation for VM UBE testing, until Go test runner can guarantee
274 // sequential execution.
275
276 #if !defined(AWSLC_VM_UBE_TESTING)
277 // We do not allow the UBE generation number to change while executing AWS-LC
278 // randomness generation code e.g. while |RAND_bytes| executes. One way to hit
279 // this error is if snapshotting the address space while executing
280 // |RAND_bytes| and while VM UBE is active.
281 uint64_t current_generation_number = 0;
282 if (CRYPTO_get_ube_generation_number(&current_generation_number) == 1 &&
283 current_generation_number != state->generation_number) {
284 return 0;
285 }
286 #endif
287
288 return 1;
289 }
290
291 // rand_check_ctr_drbg_uniqueness computes whether |state| must be randomized
292 // to ensure uniqueness.
293 //
294 // Note: If |rand_check_ctr_drbg_uniqueness| returns 0 it does not necessarily
295 // imply that an UBE occurred. It can also mean that no UBE detection is
296 // supported or that UBE detection failed. In these cases, |state| must also be
297 // randomized to ensure uniqueness. Any special future cases can be handled in
298 // this function.
299 //
300 // Return 0 if |state| must be randomized. 1 otherwise.
301 static int rand_check_ctr_drbg_uniqueness(struct rand_thread_local_state *state) {
302
303 uint64_t current_generation_number = 0;
304 if (CRYPTO_get_ube_generation_number(&current_generation_number) != 1) {
305 return 0;
306 }
307
308 if (current_generation_number != state->generation_number) {
309 state->generation_number = current_generation_number;
310 return 0;
311 }
312
313 return 1;
314 }
315
316 // rand_maybe_get_ctr_drbg_pred_resistance maybe fills |pred_resistance| with
317 // |RAND_PRED_RESISTANCE_LEN| bytes. The bytes are sourced from the prediction
318 // resistance source from the entropy source in |state|, if such a source has
319 // been configured.
320 //
321 // |*pred_resistance_len| is set to 0 if no prediction resistance source is
322 // available and |RAND_PRED_RESISTANCE_LEN| otherwise.
323 static void rand_maybe_get_ctr_drbg_pred_resistance(
324 const struct entropy_source_t *entropy_source,
325 uint8_t pred_resistance[RAND_PRED_RESISTANCE_LEN],
326 size_t *pred_resistance_len) {
327
328 GUARD_PTR_ABORT(entropy_source);
329 GUARD_PTR_ABORT(pred_resistance_len);
330
331 *pred_resistance_len = 0;
332
333 if (entropy_source->methods->get_prediction_resistance != NULL) {
334 if (entropy_source->methods->get_prediction_resistance(
335 entropy_source, pred_resistance) != 1) {
336 abort();
337 }
338 *pred_resistance_len = RAND_PRED_RESISTANCE_LEN;
339 }
340 }
341
342 // rand_get_ctr_drbg_seed_entropy source entropy for seeding and reseeding the
343 // CTR-DRBG state. Firstly, |seed| is filled with |CTR_DRBG_ENTROPY_LEN| bytes
344 // from the seed source configured in |entropy_source|. Secondly, if available,
345 // |CTR_DRBG_ENTROPY_LEN| bytes is filled into |extra_entropy| sourced
346 // from the extra entropy source configured in |entropy_source|.
347 //
348 // |*extra_entropy_len| is set to 0 if no extra entropy source
349 // is available and |CTR_DRBG_ENTROPY_LEN| otherwise.
350 static void rand_get_ctr_drbg_seed_entropy(
351 const struct entropy_source_t *entropy_source,
352 uint8_t seed[CTR_DRBG_ENTROPY_LEN],
353 uint8_t extra_entropy[CTR_DRBG_ENTROPY_LEN],
354 size_t *extra_entropy_len) {
355
356 GUARD_PTR_ABORT(entropy_source);
357 GUARD_PTR_ABORT(extra_entropy_len);
358
359 *extra_entropy_len = 0;
360
361 // If the seed source is missing it is impossible to source any entropy.
362 if (entropy_source->methods->get_seed(entropy_source, seed) != 1) {
363 abort();
364 }
365
366 // Not all entropy source configurations will have a personalization string
367 // source. Hence, it's optional. But use it if configured.
368 if (entropy_source->methods->get_extra_entropy != NULL) {
369 if(entropy_source->methods->get_extra_entropy(
370 entropy_source, extra_entropy) != 1) {
371 abort();
372 }
373 *extra_entropy_len = CTR_DRBG_ENTROPY_LEN;
374 }
375 }
376
377 // rand_ctr_drbg_reseed reseeds the CTR-DRBG state in |state|.
378 static void rand_ctr_drbg_reseed(struct rand_thread_local_state *state,
379 const uint8_t seed[CTR_DRBG_ENTROPY_LEN],
380 const uint8_t additional_data[CTR_DRBG_ENTROPY_LEN],
381 size_t additional_data_len) {
382
383 GUARD_PTR_ABORT(state);
384
385 if (CTR_DRBG_reseed(&(state->drbg), seed, additional_data,
386 additional_data_len) != 1) {
387 abort();
388 }
389
390 state->reseed_calls_since_initialization++;
391 state->generate_calls_since_seed = 0;
392 }
393
394 // rand_state_initialize initializes the thread-local state |state|. In
395 // particular initializes the CTR-DRBG state with the initial seed material.
396 static void rand_state_initialize(struct rand_thread_local_state *state) {
397
398 GUARD_PTR_ABORT(state);
399
400 state->entropy_source = get_entropy_source();
401 if (state->entropy_source == NULL) {
402 abort();
403 }
404
405 uint8_t seed[CTR_DRBG_ENTROPY_LEN];
406 uint8_t personalization_string[CTR_DRBG_ENTROPY_LEN];
407 size_t personalization_string_len = 0;
408 rand_get_ctr_drbg_seed_entropy(state->entropy_source, seed,
409 personalization_string, &personalization_string_len);
410
411 assert(personalization_string_len == 0 ||
412 personalization_string_len == CTR_DRBG_ENTROPY_LEN);
413
414 if (!CTR_DRBG_init(&(state->drbg), seed, personalization_string,
415 personalization_string_len)) {
416 abort();
417 }
418
419 state->reseed_calls_since_initialization = 0;
420 state->generate_calls_since_seed = 0;
421 uint64_t current_generation_number = 0;
422 if (CRYPTO_get_ube_generation_number(&current_generation_number) != 1) {
423 state->generation_number = 0;
424 } else {
425 state->generation_number = current_generation_number;
426 }
427 CRYPTO_MUTEX_init(&state->state_clear_lock);
428
429 OPENSSL_cleanse(seed, CTR_DRBG_ENTROPY_LEN);
430 OPENSSL_cleanse(personalization_string, CTR_DRBG_ENTROPY_LEN);
431 }
432
433 // RAND_bytes_core generates |out_len| bytes of randomness and puts them in
434 // |out|. The CTR-DRBG state in |state| is managed to ensure uniqueness and
435 // usage requirements are met.
436 //
437 // The argument |use_user_pred_resistance| must be either
438 // |RAND_USE_USER_PRED_RESISTANCE| or |RAND_NO_USER_PRED_RESISTANCE|. The former
439 // cause the content of |user_pred_resistance| to be mixed in as prediction
440 // resistance. The latter ensures that |user_pred_resistance| is not used.
441 //
442 // If the state has just been initialized, then |ctr_drbg_state_is_fresh| is 1.
443 // Otherwise, 0.
444 static void rand_bytes_core(
445 struct rand_thread_local_state *state,
446 uint8_t *out, size_t out_len,
447 const uint8_t user_pred_resistance[RAND_PRED_RESISTANCE_LEN],
448 int use_user_pred_resistance, int ctr_drbg_state_is_fresh) {
449
450 GUARD_PTR_ABORT(state);
451 GUARD_PTR_ABORT(out);
452
453 // must_reseed_before_generate is 1 if we must reseed before invoking the
454 // CTR-DRBG generate function CTR_DRBG_generate().
455 int must_reseed_before_generate = 0;
456
457 // Ensure that the CTR-DRBG state is unique. If the state is fresh then
458 // uniqueness is guaranteed.
459 if (rand_check_ctr_drbg_uniqueness(state) != 1 &&
460 ctr_drbg_state_is_fresh != 1) {
461 must_reseed_before_generate = 1;
462 }
463
464 // If a prediction resistance source is available, use it.
465 // Prediction resistance is only used on first invocation of the CTR-DRBG,
466 // ensuring that its state is randomized before generating output.
467 size_t first_pred_resistance_len = 0;
468 uint8_t pred_resistance[RAND_PRED_RESISTANCE_LEN] = {0};
469 rand_maybe_get_ctr_drbg_pred_resistance(state->entropy_source,
470 pred_resistance, &first_pred_resistance_len);
471
472 // If caller input user-controlled prediction resistance, use it.
473 if (use_user_pred_resistance == RAND_USE_USER_PRED_RESISTANCE) {
474 for (size_t i = 0; i < RAND_PRED_RESISTANCE_LEN; i++) {
475 pred_resistance[i] ^= user_pred_resistance[i];
476 }
477 first_pred_resistance_len = RAND_PRED_RESISTANCE_LEN;
478 }
479
480 assert(first_pred_resistance_len == 0 ||
481 first_pred_resistance_len == RAND_PRED_RESISTANCE_LEN);
482
483 // Synchronize with |rand_thread_local_state_clear_all|. In case a
484 // thread-local state has been zeroized, thread execution will block here
485 // because there is no secure way to generate randomness from that state.
486 // Note that this lock is thread-local and therefore not contended except at
487 // process exit.
488 CRYPTO_MUTEX_lock_read(&state->state_clear_lock);
489
490 // Iterate CTR-DRBG generate until |out_len| bytes of randomness have been
491 // generated. CTR_DRBG_generate can maximally generate
492 // |CTR_DRBG_MAX_GENERATE_LENGTH| bytes per usage of its state see
493 // SP800-90A Rev 1 Table 3. If user requests more, we must generate output in
494 // chunks and concatenate.
495 while (out_len > 0) {
496 size_t todo = out_len;
497
498 if (todo > CTR_DRBG_MAX_GENERATE_LENGTH) {
499 todo = CTR_DRBG_MAX_GENERATE_LENGTH;
500 }
501
502 if (must_reseed_before_generate == 1 ||
503 (state->generate_calls_since_seed + 1) > kCtrDrbgReseedInterval) {
504
505 // An unlock-lock cycle is located here to not acquire any locks while we
506 // might perform system calls (e.g. when sourcing OS entropy). This
507 // shields against known bugs. For example, glibc can implement locks
508 // using memory transactions on powerpc that has been observed to break
509 // when reaching |getrandom| through |syscall|. For this, see
510 // https://github.com/google/boringssl/commit/17ce286e0792fc2855fb7e34a968bed17ae914af
511 // https://www.kernel.org/doc/Documentation/powerpc/transactional_memory.txt
512 //
513 // Even though the unlock-lock cycle is under the loop iteration,
514 // practically a request size (i.e. the value of |out_len|), will
515 // almost-always be strictly less than |CTR_DRBG_MAX_GENERATE_LENGTH|.
516 // Hence, practically, only one lock-unlock rotation will be required.
517 CRYPTO_MUTEX_unlock_read(&state->state_clear_lock);
518 uint8_t seed[CTR_DRBG_ENTROPY_LEN];
519 uint8_t additional_data[CTR_DRBG_ENTROPY_LEN];
520 size_t additional_data_len = 0;
521 rand_get_ctr_drbg_seed_entropy(state->entropy_source, seed,
522 additional_data, &additional_data_len);
523 CRYPTO_MUTEX_lock_read(&state->state_clear_lock);
524
525 rand_ctr_drbg_reseed(state, seed, additional_data,
526 additional_data_len);
527 must_reseed_before_generate = 0;
528
529 OPENSSL_cleanse(seed, CTR_DRBG_ENTROPY_LEN);
530 OPENSSL_cleanse(additional_data, CTR_DRBG_ENTROPY_LEN);
531 }
532
533 if (!CTR_DRBG_generate(&(state->drbg), out, todo, pred_resistance,
534 first_pred_resistance_len)) {
535 abort();
536 }
537
538 out += todo;
539 out_len -= todo;
540 state->generate_calls_since_seed++;
541 first_pred_resistance_len = 0;
542 }
543
544 OPENSSL_cleanse(pred_resistance, RAND_PRED_RESISTANCE_LEN);
545
546 if (rand_ensure_valid_state(state) != 1) {
547 abort();
548 }
549
550 CRYPTO_MUTEX_unlock_read(&state->state_clear_lock);
551 }
552
553 static void rand_bytes_impl(thread_local_data_t tls_key, uint8_t *out,
554 size_t out_len, const uint8_t user_pred_resistance[RAND_PRED_RESISTANCE_LEN],
555 int use_user_pred_resistance) {
556
557 if (out_len == 0) {
558 return;
559 }
560
561 // Lock state here because CTR-DRBG-generate can be invoked multiple times
562 // and every successful invocation increments the service indicator.
563 FIPS_service_indicator_lock_state();
564
565 struct rand_thread_local_state *state =
566 CRYPTO_get_thread_local(tls_key);
567
568 int ctr_drbg_state_is_fresh = 0;
569
570 if (state == NULL) {
571 state = OPENSSL_zalloc(sizeof(struct rand_thread_local_state));
572 if (state == NULL ||
573 CRYPTO_set_thread_local(tls_key, state,
574 rand_thread_local_state_free) != 1) {
575 abort();
576 }
577
578 rand_state_initialize(state);
579 thread_local_list_add_node(state);
580
581 ctr_drbg_state_is_fresh = 1;
582 }
583
584 rand_bytes_core(state, out, out_len, user_pred_resistance,
585 use_user_pred_resistance, ctr_drbg_state_is_fresh);
586
587 FIPS_service_indicator_unlock_state();
588 FIPS_service_indicator_update_state();
589 }
590
591 int RAND_bytes_with_user_prediction_resistance(uint8_t *out, size_t out_len,
592 const uint8_t user_pred_resistance[RAND_PRED_RESISTANCE_LEN]) {
593
594 GUARD_PTR_ABORT(user_pred_resistance);
595
596 rand_bytes_impl(OPENSSL_THREAD_LOCAL_PRIVATE_RAND, out, out_len,
597 user_pred_resistance, RAND_USE_USER_PRED_RESISTANCE);
598 return 1;
599 }
600
601 int RAND_bytes(uint8_t *out, size_t out_len) {
602
603 static const uint8_t kZeroPredResistance[RAND_PRED_RESISTANCE_LEN] = {0};
604 rand_bytes_impl(OPENSSL_THREAD_LOCAL_PRIVATE_RAND, out, out_len,
605 kZeroPredResistance, RAND_NO_USER_PRED_RESISTANCE);
606 return 1;
607 }
608
609 int RAND_priv_bytes(uint8_t *out, size_t out_len) {
610 return RAND_bytes(out, out_len);
611 }
612
613 int RAND_public_bytes(uint8_t *out, size_t out_len) {
614 static const uint8_t kZeroPredResistance[RAND_PRED_RESISTANCE_LEN] = {0};
615 rand_bytes_impl(OPENSSL_THREAD_LOCAL_PUBLIC_RAND, out, out_len,
616 kZeroPredResistance, RAND_NO_USER_PRED_RESISTANCE);
617 return 1;
618 }
619
620 int RAND_pseudo_bytes(uint8_t *out, size_t out_len) {
621 return RAND_bytes(out, out_len);
622 }
623
624 // Returns the number of generate calls made on the private thread-local state
625 // since last seed/reseed. Returns 0 if private thread-local state has not been
626 // initialized.
627 uint64_t get_private_thread_generate_calls_since_seed(void) {
628
629 struct rand_thread_local_state *state =
630 CRYPTO_get_thread_local(OPENSSL_THREAD_LOCAL_PRIVATE_RAND);
631 if (state == NULL) {
632 return 0;
633 }
634
635 return state->generate_calls_since_seed;
636 }
637
638 // Returns the number of reseed calls made on the private thread-local state
639 // since initialization. Returns 0 if private thread-local state has not been
640 // initialized.
641 uint64_t get_private_thread_reseed_calls_since_initialization(void) {
642
643 struct rand_thread_local_state *state =
644 CRYPTO_get_thread_local(OPENSSL_THREAD_LOCAL_PRIVATE_RAND);
645 if (state == NULL) {
646 return 0;
647 }
648
649 return state->reseed_calls_since_initialization;
650 }
651
652 // Returns the number of generate calls made on the public thread-local state
653 // since last seed/reseed. Returns 0 if public thread-local state has not been
654 // initialized.
655 uint64_t get_public_thread_generate_calls_since_seed(void) {
656
657 struct rand_thread_local_state *state =
658 CRYPTO_get_thread_local(OPENSSL_THREAD_LOCAL_PUBLIC_RAND);
659 if (state == NULL) {
660 return 0;
661 }
662
663 return state->generate_calls_since_seed;
664 }
665
666 // Returns the number of reseed calls made on the public thread-local state
667 // since initialization. Returns 0 if public thread-local state has not been
668 // initialized.
669 uint64_t get_public_thread_reseed_calls_since_initialization(void) {
670
671 struct rand_thread_local_state *state =
672 CRYPTO_get_thread_local(OPENSSL_THREAD_LOCAL_PUBLIC_RAND);
673 if (state == NULL) {
674 return 0;
675 }
676
677 return state->reseed_calls_since_initialization;
678 }