1 /*
2 * Copyright 2011-2020 The OpenSSL Project Authors. All Rights Reserved.
3 *
4 * Licensed under the OpenSSL license (the "License"). You may not use
5 * this file except in compliance with the License. You can obtain a copy
6 * in the file LICENSE in the source distribution or at
7 * https://www.openssl.org/source/license.html
8 */
9
10 #include <string.h>
11 #include <openssl/crypto.h>
12 #include <openssl/err.h>
13 #include <openssl/rand.h>
14 #include "rand_local.h"
15 #include "internal/thread_once.h"
16 #include "crypto/rand.h"
17 #include "crypto/cryptlib.h"
18
19 /*
20 * Support framework for NIST SP 800-90A DRBG
21 *
22 * See manual page RAND_DRBG(7) for a general overview.
23 *
24 * The OpenSSL model is to have new and free functions, and that new
25 * does all initialization. That is not the NIST model, which has
26 * instantiation and un-instantiate, and re-use within a new/free
27 * lifecycle. (No doubt this comes from the desire to support hardware
28 * DRBG, where allocation of resources on something like an HSM is
29 * a much bigger deal than just re-setting an allocated resource.)
30 */
31
32 /*
33 * The three shared DRBG instances
34 *
35 * There are three shared DRBG instances: <master>, <public>, and <private>.
36 */
37
38 /*
39 * The <master> DRBG
40 *
41 * Not used directly by the application, only for reseeding the two other
42 * DRBGs. It reseeds itself by pulling either randomness from os entropy
43 * sources or by consuming randomness which was added by RAND_add().
44 *
45 * The <master> DRBG is a global instance which is accessed concurrently by
46 * all threads. The necessary locking is managed automatically by its child
47 * DRBG instances during reseeding.
48 */
49 static RAND_DRBG *master_drbg;
50 /*
51 * The <public> DRBG
52 *
53 * Used by default for generating random bytes using RAND_bytes().
54 *
55 * The <public> DRBG is thread-local, i.e., there is one instance per thread.
56 */
57 static CRYPTO_THREAD_LOCAL public_drbg;
58 /*
59 * The <private> DRBG
60 *
61 * Used by default for generating private keys using RAND_priv_bytes()
62 *
63 * The <private> DRBG is thread-local, i.e., there is one instance per thread.
64 */
65 static CRYPTO_THREAD_LOCAL private_drbg;
66
67
68
69 /* NIST SP 800-90A DRBG recommends the use of a personalization string. */
70 static const char ossl_pers_string[] = "OpenSSL NIST SP 800-90A DRBG";
71
72 static CRYPTO_ONCE rand_drbg_init = CRYPTO_ONCE_STATIC_INIT;
73
74
75
76 static int rand_drbg_type = RAND_DRBG_TYPE;
77 static unsigned int rand_drbg_flags = RAND_DRBG_FLAGS;
78
79 static unsigned int master_reseed_interval = MASTER_RESEED_INTERVAL;
80 static unsigned int slave_reseed_interval = SLAVE_RESEED_INTERVAL;
81
82 static time_t master_reseed_time_interval = MASTER_RESEED_TIME_INTERVAL;
83 static time_t slave_reseed_time_interval = SLAVE_RESEED_TIME_INTERVAL;
84
85 /* A logical OR of all used DRBG flag bits (currently there is only one) */
86 static const unsigned int rand_drbg_used_flags =
87 RAND_DRBG_FLAG_CTR_NO_DF;
88
89 static RAND_DRBG *drbg_setup(RAND_DRBG *parent);
90
91 static RAND_DRBG *rand_drbg_new(int secure,
92 int type,
93 unsigned int flags,
94 RAND_DRBG *parent);
95
96 /*
97 * Set/initialize |drbg| to be of type |type|, with optional |flags|.
98 *
99 * If |type| and |flags| are zero, use the defaults
100 *
101 * Returns 1 on success, 0 on failure.
102 */
RAND_DRBG_set(RAND_DRBG * drbg,int type,unsigned int flags)103 int RAND_DRBG_set(RAND_DRBG *drbg, int type, unsigned int flags)
104 {
105 int ret = 1;
106
107 if (type == 0 && flags == 0) {
108 type = rand_drbg_type;
109 flags = rand_drbg_flags;
110 }
111
112 /* If set is called multiple times - clear the old one */
113 if (drbg->type != 0 && (type != drbg->type || flags != drbg->flags)) {
114 drbg->meth->uninstantiate(drbg);
115 rand_pool_free(drbg->adin_pool);
116 drbg->adin_pool = NULL;
117 }
118
119 drbg->state = DRBG_UNINITIALISED;
120 drbg->flags = flags;
121 drbg->type = type;
122
123 switch (type) {
124 default:
125 drbg->type = 0;
126 drbg->flags = 0;
127 drbg->meth = NULL;
128 RANDerr(RAND_F_RAND_DRBG_SET, RAND_R_UNSUPPORTED_DRBG_TYPE);
129 return 0;
130 case 0:
131 /* Uninitialized; that's okay. */
132 drbg->meth = NULL;
133 return 1;
134 case NID_aes_128_ctr:
135 case NID_aes_192_ctr:
136 case NID_aes_256_ctr:
137 ret = drbg_ctr_init(drbg);
138 break;
139 }
140
141 if (ret == 0) {
142 drbg->state = DRBG_ERROR;
143 RANDerr(RAND_F_RAND_DRBG_SET, RAND_R_ERROR_INITIALISING_DRBG);
144 }
145 return ret;
146 }
147
148 /*
149 * Set/initialize default |type| and |flag| for new drbg instances.
150 *
151 * Returns 1 on success, 0 on failure.
152 */
RAND_DRBG_set_defaults(int type,unsigned int flags)153 int RAND_DRBG_set_defaults(int type, unsigned int flags)
154 {
155 int ret = 1;
156
157 switch (type) {
158 default:
159 RANDerr(RAND_F_RAND_DRBG_SET_DEFAULTS, RAND_R_UNSUPPORTED_DRBG_TYPE);
160 return 0;
161 case NID_aes_128_ctr:
162 case NID_aes_192_ctr:
163 case NID_aes_256_ctr:
164 break;
165 }
166
167 if ((flags & ~rand_drbg_used_flags) != 0) {
168 RANDerr(RAND_F_RAND_DRBG_SET_DEFAULTS, RAND_R_UNSUPPORTED_DRBG_FLAGS);
169 return 0;
170 }
171
172 rand_drbg_type = type;
173 rand_drbg_flags = flags;
174
175 return ret;
176 }
177
178
179 /*
180 * Allocate memory and initialize a new DRBG. The DRBG is allocated on
181 * the secure heap if |secure| is nonzero and the secure heap is enabled.
182 * The |parent|, if not NULL, will be used as random source for reseeding.
183 *
184 * Returns a pointer to the new DRBG instance on success, NULL on failure.
185 */
rand_drbg_new(int secure,int type,unsigned int flags,RAND_DRBG * parent)186 static RAND_DRBG *rand_drbg_new(int secure,
187 int type,
188 unsigned int flags,
189 RAND_DRBG *parent)
190 {
191 RAND_DRBG *drbg = secure ? OPENSSL_secure_zalloc(sizeof(*drbg))
192 : OPENSSL_zalloc(sizeof(*drbg));
193
194 if (drbg == NULL) {
195 RANDerr(RAND_F_RAND_DRBG_NEW, ERR_R_MALLOC_FAILURE);
196 return NULL;
197 }
198
199 drbg->secure = secure && CRYPTO_secure_allocated(drbg);
200 drbg->fork_id = openssl_get_fork_id();
201 drbg->parent = parent;
202
203 if (parent == NULL) {
204 drbg->get_entropy = rand_drbg_get_entropy;
205 drbg->cleanup_entropy = rand_drbg_cleanup_entropy;
206 #ifndef RAND_DRBG_GET_RANDOM_NONCE
207 drbg->get_nonce = rand_drbg_get_nonce;
208 drbg->cleanup_nonce = rand_drbg_cleanup_nonce;
209 #endif
210
211 drbg->reseed_interval = master_reseed_interval;
212 drbg->reseed_time_interval = master_reseed_time_interval;
213 } else {
214 drbg->get_entropy = rand_drbg_get_entropy;
215 drbg->cleanup_entropy = rand_drbg_cleanup_entropy;
216 /*
217 * Do not provide nonce callbacks, the child DRBGs will
218 * obtain their nonce using random bits from the parent.
219 */
220
221 drbg->reseed_interval = slave_reseed_interval;
222 drbg->reseed_time_interval = slave_reseed_time_interval;
223 }
224
225 if (RAND_DRBG_set(drbg, type, flags) == 0)
226 goto err;
227
228 if (parent != NULL) {
229 rand_drbg_lock(parent);
230 if (drbg->strength > parent->strength) {
231 /*
232 * We currently don't support the algorithm from NIST SP 800-90C
233 * 10.1.2 to use a weaker DRBG as source
234 */
235 rand_drbg_unlock(parent);
236 RANDerr(RAND_F_RAND_DRBG_NEW, RAND_R_PARENT_STRENGTH_TOO_WEAK);
237 goto err;
238 }
239 rand_drbg_unlock(parent);
240 }
241
242 return drbg;
243
244 err:
245 RAND_DRBG_free(drbg);
246
247 return NULL;
248 }
249
RAND_DRBG_new(int type,unsigned int flags,RAND_DRBG * parent)250 RAND_DRBG *RAND_DRBG_new(int type, unsigned int flags, RAND_DRBG *parent)
251 {
252 return rand_drbg_new(0, type, flags, parent);
253 }
254
RAND_DRBG_secure_new(int type,unsigned int flags,RAND_DRBG * parent)255 RAND_DRBG *RAND_DRBG_secure_new(int type, unsigned int flags, RAND_DRBG *parent)
256 {
257 return rand_drbg_new(1, type, flags, parent);
258 }
259
260 /*
261 * Uninstantiate |drbg| and free all memory.
262 */
RAND_DRBG_free(RAND_DRBG * drbg)263 void RAND_DRBG_free(RAND_DRBG *drbg)
264 {
265 if (drbg == NULL)
266 return;
267
268 if (drbg->meth != NULL)
269 drbg->meth->uninstantiate(drbg);
270 rand_pool_free(drbg->adin_pool);
271 CRYPTO_THREAD_lock_free(drbg->lock);
272 CRYPTO_free_ex_data(CRYPTO_EX_INDEX_DRBG, drbg, &drbg->ex_data);
273
274 if (drbg->secure)
275 OPENSSL_secure_clear_free(drbg, sizeof(*drbg));
276 else
277 OPENSSL_clear_free(drbg, sizeof(*drbg));
278 }
279
280 /*
281 * Instantiate |drbg|, after it has been initialized. Use |pers| and
282 * |perslen| as prediction-resistance input.
283 *
284 * Requires that drbg->lock is already locked for write, if non-null.
285 *
286 * Returns 1 on success, 0 on failure.
287 */
RAND_DRBG_instantiate(RAND_DRBG * drbg,const unsigned char * pers,size_t perslen)288 int RAND_DRBG_instantiate(RAND_DRBG *drbg,
289 const unsigned char *pers, size_t perslen)
290 {
291 unsigned char *nonce = NULL, *entropy = NULL;
292 size_t noncelen = 0, entropylen = 0;
293 size_t min_entropy = drbg->strength;
294 size_t min_entropylen = drbg->min_entropylen;
295 size_t max_entropylen = drbg->max_entropylen;
296
297 if (perslen > drbg->max_perslen) {
298 RANDerr(RAND_F_RAND_DRBG_INSTANTIATE,
299 RAND_R_PERSONALISATION_STRING_TOO_LONG);
300 goto end;
301 }
302
303 if (drbg->meth == NULL) {
304 RANDerr(RAND_F_RAND_DRBG_INSTANTIATE,
305 RAND_R_NO_DRBG_IMPLEMENTATION_SELECTED);
306 goto end;
307 }
308
309 if (drbg->state != DRBG_UNINITIALISED) {
310 RANDerr(RAND_F_RAND_DRBG_INSTANTIATE,
311 drbg->state == DRBG_ERROR ? RAND_R_IN_ERROR_STATE
312 : RAND_R_ALREADY_INSTANTIATED);
313 goto end;
314 }
315
316 drbg->state = DRBG_ERROR;
317
318 /*
319 * NIST SP800-90Ar1 section 9.1 says you can combine getting the entropy
320 * and nonce in 1 call by increasing the entropy with 50% and increasing
321 * the minimum length to accommodate the length of the nonce.
322 * We do this in case a nonce is require and get_nonce is NULL.
323 */
324 if (drbg->min_noncelen > 0 && drbg->get_nonce == NULL) {
325 min_entropy += drbg->strength / 2;
326 min_entropylen += drbg->min_noncelen;
327 max_entropylen += drbg->max_noncelen;
328 }
329
330 drbg->reseed_next_counter = tsan_load(&drbg->reseed_prop_counter);
331 if (drbg->reseed_next_counter) {
332 drbg->reseed_next_counter++;
333 if(!drbg->reseed_next_counter)
334 drbg->reseed_next_counter = 1;
335 }
336
337 if (drbg->get_entropy != NULL)
338 entropylen = drbg->get_entropy(drbg, &entropy, min_entropy,
339 min_entropylen, max_entropylen, 0);
340 if (entropylen < min_entropylen
341 || entropylen > max_entropylen) {
342 RANDerr(RAND_F_RAND_DRBG_INSTANTIATE, RAND_R_ERROR_RETRIEVING_ENTROPY);
343 goto end;
344 }
345
346 if (drbg->min_noncelen > 0 && drbg->get_nonce != NULL) {
347 noncelen = drbg->get_nonce(drbg, &nonce, drbg->strength / 2,
348 drbg->min_noncelen, drbg->max_noncelen);
349 if (noncelen < drbg->min_noncelen || noncelen > drbg->max_noncelen) {
350 RANDerr(RAND_F_RAND_DRBG_INSTANTIATE, RAND_R_ERROR_RETRIEVING_NONCE);
351 goto end;
352 }
353 }
354
355 if (!drbg->meth->instantiate(drbg, entropy, entropylen,
356 nonce, noncelen, pers, perslen)) {
357 RANDerr(RAND_F_RAND_DRBG_INSTANTIATE, RAND_R_ERROR_INSTANTIATING_DRBG);
358 goto end;
359 }
360
361 drbg->state = DRBG_READY;
362 drbg->reseed_gen_counter = 1;
363 drbg->reseed_time = time(NULL);
364 tsan_store(&drbg->reseed_prop_counter, drbg->reseed_next_counter);
365
366 end:
367 if (entropy != NULL && drbg->cleanup_entropy != NULL)
368 drbg->cleanup_entropy(drbg, entropy, entropylen);
369 if (nonce != NULL && drbg->cleanup_nonce != NULL)
370 drbg->cleanup_nonce(drbg, nonce, noncelen);
371 if (drbg->state == DRBG_READY)
372 return 1;
373 return 0;
374 }
375
376 /*
377 * Uninstantiate |drbg|. Must be instantiated before it can be used.
378 *
379 * Requires that drbg->lock is already locked for write, if non-null.
380 *
381 * Returns 1 on success, 0 on failure.
382 */
RAND_DRBG_uninstantiate(RAND_DRBG * drbg)383 int RAND_DRBG_uninstantiate(RAND_DRBG *drbg)
384 {
385 if (drbg->meth == NULL) {
386 drbg->state = DRBG_ERROR;
387 RANDerr(RAND_F_RAND_DRBG_UNINSTANTIATE,
388 RAND_R_NO_DRBG_IMPLEMENTATION_SELECTED);
389 return 0;
390 }
391
392 /* Clear the entire drbg->ctr struct, then reset some important
393 * members of the drbg->ctr struct (e.g. keysize, df_ks) to their
394 * initial values.
395 */
396 drbg->meth->uninstantiate(drbg);
397 return RAND_DRBG_set(drbg, drbg->type, drbg->flags);
398 }
399
400 /*
401 * Reseed |drbg|, mixing in the specified data
402 *
403 * Requires that drbg->lock is already locked for write, if non-null.
404 *
405 * Returns 1 on success, 0 on failure.
406 */
RAND_DRBG_reseed(RAND_DRBG * drbg,const unsigned char * adin,size_t adinlen,int prediction_resistance)407 int RAND_DRBG_reseed(RAND_DRBG *drbg,
408 const unsigned char *adin, size_t adinlen,
409 int prediction_resistance)
410 {
411 unsigned char *entropy = NULL;
412 size_t entropylen = 0;
413
414 if (drbg->state == DRBG_ERROR) {
415 RANDerr(RAND_F_RAND_DRBG_RESEED, RAND_R_IN_ERROR_STATE);
416 return 0;
417 }
418 if (drbg->state == DRBG_UNINITIALISED) {
419 RANDerr(RAND_F_RAND_DRBG_RESEED, RAND_R_NOT_INSTANTIATED);
420 return 0;
421 }
422
423 if (adin == NULL) {
424 adinlen = 0;
425 } else if (adinlen > drbg->max_adinlen) {
426 RANDerr(RAND_F_RAND_DRBG_RESEED, RAND_R_ADDITIONAL_INPUT_TOO_LONG);
427 return 0;
428 }
429
430 drbg->state = DRBG_ERROR;
431
432 drbg->reseed_next_counter = tsan_load(&drbg->reseed_prop_counter);
433 if (drbg->reseed_next_counter) {
434 drbg->reseed_next_counter++;
435 if(!drbg->reseed_next_counter)
436 drbg->reseed_next_counter = 1;
437 }
438
439 if (drbg->get_entropy != NULL)
440 entropylen = drbg->get_entropy(drbg, &entropy, drbg->strength,
441 drbg->min_entropylen,
442 drbg->max_entropylen,
443 prediction_resistance);
444 if (entropylen < drbg->min_entropylen
445 || entropylen > drbg->max_entropylen) {
446 RANDerr(RAND_F_RAND_DRBG_RESEED, RAND_R_ERROR_RETRIEVING_ENTROPY);
447 goto end;
448 }
449
450 if (!drbg->meth->reseed(drbg, entropy, entropylen, adin, adinlen))
451 goto end;
452
453 drbg->state = DRBG_READY;
454 drbg->reseed_gen_counter = 1;
455 drbg->reseed_time = time(NULL);
456 tsan_store(&drbg->reseed_prop_counter, drbg->reseed_next_counter);
457
458 end:
459 if (entropy != NULL && drbg->cleanup_entropy != NULL)
460 drbg->cleanup_entropy(drbg, entropy, entropylen);
461 if (drbg->state == DRBG_READY)
462 return 1;
463 return 0;
464 }
465
466 /*
467 * Restart |drbg|, using the specified entropy or additional input
468 *
469 * Tries its best to get the drbg instantiated by all means,
470 * regardless of its current state.
471 *
472 * Optionally, a |buffer| of |len| random bytes can be passed,
473 * which is assumed to contain at least |entropy| bits of entropy.
474 *
475 * If |entropy| > 0, the buffer content is used as entropy input.
476 *
477 * If |entropy| == 0, the buffer content is used as additional input
478 *
479 * Returns 1 on success, 0 on failure.
480 *
481 * This function is used internally only.
482 */
rand_drbg_restart(RAND_DRBG * drbg,const unsigned char * buffer,size_t len,size_t entropy)483 int rand_drbg_restart(RAND_DRBG *drbg,
484 const unsigned char *buffer, size_t len, size_t entropy)
485 {
486 int reseeded = 0;
487 const unsigned char *adin = NULL;
488 size_t adinlen = 0;
489
490 if (drbg->seed_pool != NULL) {
491 RANDerr(RAND_F_RAND_DRBG_RESTART, ERR_R_INTERNAL_ERROR);
492 drbg->state = DRBG_ERROR;
493 rand_pool_free(drbg->seed_pool);
494 drbg->seed_pool = NULL;
495 return 0;
496 }
497
498 if (buffer != NULL) {
499 if (entropy > 0) {
500 if (drbg->max_entropylen < len) {
501 RANDerr(RAND_F_RAND_DRBG_RESTART,
502 RAND_R_ENTROPY_INPUT_TOO_LONG);
503 drbg->state = DRBG_ERROR;
504 return 0;
505 }
506
507 if (entropy > 8 * len) {
508 RANDerr(RAND_F_RAND_DRBG_RESTART, RAND_R_ENTROPY_OUT_OF_RANGE);
509 drbg->state = DRBG_ERROR;
510 return 0;
511 }
512
513 /* will be picked up by the rand_drbg_get_entropy() callback */
514 drbg->seed_pool = rand_pool_attach(buffer, len, entropy);
515 if (drbg->seed_pool == NULL)
516 return 0;
517 } else {
518 if (drbg->max_adinlen < len) {
519 RANDerr(RAND_F_RAND_DRBG_RESTART,
520 RAND_R_ADDITIONAL_INPUT_TOO_LONG);
521 drbg->state = DRBG_ERROR;
522 return 0;
523 }
524 adin = buffer;
525 adinlen = len;
526 }
527 }
528
529 /* repair error state */
530 if (drbg->state == DRBG_ERROR)
531 RAND_DRBG_uninstantiate(drbg);
532
533 /* repair uninitialized state */
534 if (drbg->state == DRBG_UNINITIALISED) {
535 /* reinstantiate drbg */
536 RAND_DRBG_instantiate(drbg,
537 (const unsigned char *) ossl_pers_string,
538 sizeof(ossl_pers_string) - 1);
539 /* already reseeded. prevent second reseeding below */
540 reseeded = (drbg->state == DRBG_READY);
541 }
542
543 /* refresh current state if entropy or additional input has been provided */
544 if (drbg->state == DRBG_READY) {
545 if (adin != NULL) {
546 /*
547 * mix in additional input without reseeding
548 *
549 * Similar to RAND_DRBG_reseed(), but the provided additional
550 * data |adin| is mixed into the current state without pulling
551 * entropy from the trusted entropy source using get_entropy().
552 * This is not a reseeding in the strict sense of NIST SP 800-90A.
553 */
554 drbg->meth->reseed(drbg, adin, adinlen, NULL, 0);
555 } else if (reseeded == 0) {
556 /* do a full reseeding if it has not been done yet above */
557 RAND_DRBG_reseed(drbg, NULL, 0, 0);
558 }
559 }
560
561 rand_pool_free(drbg->seed_pool);
562 drbg->seed_pool = NULL;
563
564 return drbg->state == DRBG_READY;
565 }
566
567 /*
568 * Generate |outlen| bytes into the buffer at |out|. Reseed if we need
569 * to or if |prediction_resistance| is set. Additional input can be
570 * sent in |adin| and |adinlen|.
571 *
572 * Requires that drbg->lock is already locked for write, if non-null.
573 *
574 * Returns 1 on success, 0 on failure.
575 *
576 */
RAND_DRBG_generate(RAND_DRBG * drbg,unsigned char * out,size_t outlen,int prediction_resistance,const unsigned char * adin,size_t adinlen)577 int RAND_DRBG_generate(RAND_DRBG *drbg, unsigned char *out, size_t outlen,
578 int prediction_resistance,
579 const unsigned char *adin, size_t adinlen)
580 {
581 int fork_id;
582 int reseed_required = 0;
583
584 if (drbg->state != DRBG_READY) {
585 /* try to recover from previous errors */
586 rand_drbg_restart(drbg, NULL, 0, 0);
587
588 if (drbg->state == DRBG_ERROR) {
589 RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_IN_ERROR_STATE);
590 return 0;
591 }
592 if (drbg->state == DRBG_UNINITIALISED) {
593 RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_NOT_INSTANTIATED);
594 return 0;
595 }
596 }
597
598 if (outlen > drbg->max_request) {
599 RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_REQUEST_TOO_LARGE_FOR_DRBG);
600 return 0;
601 }
602 if (adinlen > drbg->max_adinlen) {
603 RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_ADDITIONAL_INPUT_TOO_LONG);
604 return 0;
605 }
606
607 fork_id = openssl_get_fork_id();
608
609 if (drbg->fork_id != fork_id) {
610 drbg->fork_id = fork_id;
611 reseed_required = 1;
612 }
613
614 if (drbg->reseed_interval > 0) {
615 if (drbg->reseed_gen_counter >= drbg->reseed_interval)
616 reseed_required = 1;
617 }
618 if (drbg->reseed_time_interval > 0) {
619 time_t now = time(NULL);
620 if (now < drbg->reseed_time
621 || now - drbg->reseed_time >= drbg->reseed_time_interval)
622 reseed_required = 1;
623 }
624 if (drbg->parent != NULL) {
625 unsigned int reseed_counter = tsan_load(&drbg->reseed_prop_counter);
626 if (reseed_counter > 0
627 && tsan_load(&drbg->parent->reseed_prop_counter)
628 != reseed_counter)
629 reseed_required = 1;
630 }
631
632 if (reseed_required || prediction_resistance) {
633 if (!RAND_DRBG_reseed(drbg, adin, adinlen, prediction_resistance)) {
634 RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_RESEED_ERROR);
635 return 0;
636 }
637 adin = NULL;
638 adinlen = 0;
639 }
640
641 if (!drbg->meth->generate(drbg, out, outlen, adin, adinlen)) {
642 drbg->state = DRBG_ERROR;
643 RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_GENERATE_ERROR);
644 return 0;
645 }
646
647 drbg->reseed_gen_counter++;
648
649 return 1;
650 }
651
652 /*
653 * Generates |outlen| random bytes and stores them in |out|. It will
654 * using the given |drbg| to generate the bytes.
655 *
656 * Requires that drbg->lock is already locked for write, if non-null.
657 *
658 * Returns 1 on success 0 on failure.
659 */
RAND_DRBG_bytes(RAND_DRBG * drbg,unsigned char * out,size_t outlen)660 int RAND_DRBG_bytes(RAND_DRBG *drbg, unsigned char *out, size_t outlen)
661 {
662 unsigned char *additional = NULL;
663 size_t additional_len;
664 size_t chunk;
665 size_t ret = 0;
666
667 if (drbg->adin_pool == NULL) {
668 if (drbg->type == 0)
669 goto err;
670 drbg->adin_pool = rand_pool_new(0, 0, 0, drbg->max_adinlen);
671 if (drbg->adin_pool == NULL)
672 goto err;
673 }
674
675 additional_len = rand_drbg_get_additional_data(drbg->adin_pool,
676 &additional);
677
678 for ( ; outlen > 0; outlen -= chunk, out += chunk) {
679 chunk = outlen;
680 if (chunk > drbg->max_request)
681 chunk = drbg->max_request;
682 ret = RAND_DRBG_generate(drbg, out, chunk, 0, additional, additional_len);
683 if (!ret)
684 goto err;
685 }
686 ret = 1;
687
688 err:
689 if (additional != NULL)
690 rand_drbg_cleanup_additional_data(drbg->adin_pool, additional);
691
692 return ret;
693 }
694
695 /*
696 * Set the RAND_DRBG callbacks for obtaining entropy and nonce.
697 *
698 * Setting the callbacks is allowed only if the drbg has not been
699 * initialized yet. Otherwise, the operation will fail.
700 *
701 * Returns 1 on success, 0 on failure.
702 */
RAND_DRBG_set_callbacks(RAND_DRBG * drbg,RAND_DRBG_get_entropy_fn get_entropy,RAND_DRBG_cleanup_entropy_fn cleanup_entropy,RAND_DRBG_get_nonce_fn get_nonce,RAND_DRBG_cleanup_nonce_fn cleanup_nonce)703 int RAND_DRBG_set_callbacks(RAND_DRBG *drbg,
704 RAND_DRBG_get_entropy_fn get_entropy,
705 RAND_DRBG_cleanup_entropy_fn cleanup_entropy,
706 RAND_DRBG_get_nonce_fn get_nonce,
707 RAND_DRBG_cleanup_nonce_fn cleanup_nonce)
708 {
709 if (drbg->state != DRBG_UNINITIALISED
710 || drbg->parent != NULL)
711 return 0;
712 drbg->get_entropy = get_entropy;
713 drbg->cleanup_entropy = cleanup_entropy;
714 drbg->get_nonce = get_nonce;
715 drbg->cleanup_nonce = cleanup_nonce;
716 return 1;
717 }
718
719 /*
720 * Set the reseed interval.
721 *
722 * The drbg will reseed automatically whenever the number of generate
723 * requests exceeds the given reseed interval. If the reseed interval
724 * is 0, then this feature is disabled.
725 *
726 * Returns 1 on success, 0 on failure.
727 */
RAND_DRBG_set_reseed_interval(RAND_DRBG * drbg,unsigned int interval)728 int RAND_DRBG_set_reseed_interval(RAND_DRBG *drbg, unsigned int interval)
729 {
730 if (interval > MAX_RESEED_INTERVAL)
731 return 0;
732 drbg->reseed_interval = interval;
733 return 1;
734 }
735
736 /*
737 * Set the reseed time interval.
738 *
739 * The drbg will reseed automatically whenever the time elapsed since
740 * the last reseeding exceeds the given reseed time interval. For safety,
741 * a reseeding will also occur if the clock has been reset to a smaller
742 * value.
743 *
744 * Returns 1 on success, 0 on failure.
745 */
RAND_DRBG_set_reseed_time_interval(RAND_DRBG * drbg,time_t interval)746 int RAND_DRBG_set_reseed_time_interval(RAND_DRBG *drbg, time_t interval)
747 {
748 if (interval > MAX_RESEED_TIME_INTERVAL)
749 return 0;
750 drbg->reseed_time_interval = interval;
751 return 1;
752 }
753
754 /*
755 * Set the default values for reseed (time) intervals of new DRBG instances
756 *
757 * The default values can be set independently for master DRBG instances
758 * (without a parent) and slave DRBG instances (with parent).
759 *
760 * Returns 1 on success, 0 on failure.
761 */
762
RAND_DRBG_set_reseed_defaults(unsigned int _master_reseed_interval,unsigned int _slave_reseed_interval,time_t _master_reseed_time_interval,time_t _slave_reseed_time_interval)763 int RAND_DRBG_set_reseed_defaults(
764 unsigned int _master_reseed_interval,
765 unsigned int _slave_reseed_interval,
766 time_t _master_reseed_time_interval,
767 time_t _slave_reseed_time_interval
768 )
769 {
770 if (_master_reseed_interval > MAX_RESEED_INTERVAL
771 || _slave_reseed_interval > MAX_RESEED_INTERVAL)
772 return 0;
773
774 if (_master_reseed_time_interval > MAX_RESEED_TIME_INTERVAL
775 || _slave_reseed_time_interval > MAX_RESEED_TIME_INTERVAL)
776 return 0;
777
778 master_reseed_interval = _master_reseed_interval;
779 slave_reseed_interval = _slave_reseed_interval;
780
781 master_reseed_time_interval = _master_reseed_time_interval;
782 slave_reseed_time_interval = _slave_reseed_time_interval;
783
784 return 1;
785 }
786
787 /*
788 * Locks the given drbg. Locking a drbg which does not have locking
789 * enabled is considered a successful no-op.
790 *
791 * Returns 1 on success, 0 on failure.
792 */
rand_drbg_lock(RAND_DRBG * drbg)793 int rand_drbg_lock(RAND_DRBG *drbg)
794 {
795 if (drbg->lock != NULL)
796 return CRYPTO_THREAD_write_lock(drbg->lock);
797
798 return 1;
799 }
800
801 /*
802 * Unlocks the given drbg. Unlocking a drbg which does not have locking
803 * enabled is considered a successful no-op.
804 *
805 * Returns 1 on success, 0 on failure.
806 */
rand_drbg_unlock(RAND_DRBG * drbg)807 int rand_drbg_unlock(RAND_DRBG *drbg)
808 {
809 if (drbg->lock != NULL)
810 return CRYPTO_THREAD_unlock(drbg->lock);
811
812 return 1;
813 }
814
815 /*
816 * Enables locking for the given drbg
817 *
818 * Locking can only be enabled if the random generator
819 * is in the uninitialized state.
820 *
821 * Returns 1 on success, 0 on failure.
822 */
rand_drbg_enable_locking(RAND_DRBG * drbg)823 int rand_drbg_enable_locking(RAND_DRBG *drbg)
824 {
825 if (drbg->state != DRBG_UNINITIALISED) {
826 RANDerr(RAND_F_RAND_DRBG_ENABLE_LOCKING,
827 RAND_R_DRBG_ALREADY_INITIALIZED);
828 return 0;
829 }
830
831 if (drbg->lock == NULL) {
832 if (drbg->parent != NULL && drbg->parent->lock == NULL) {
833 RANDerr(RAND_F_RAND_DRBG_ENABLE_LOCKING,
834 RAND_R_PARENT_LOCKING_NOT_ENABLED);
835 return 0;
836 }
837
838 drbg->lock = CRYPTO_THREAD_lock_new();
839 if (drbg->lock == NULL) {
840 RANDerr(RAND_F_RAND_DRBG_ENABLE_LOCKING,
841 RAND_R_FAILED_TO_CREATE_LOCK);
842 return 0;
843 }
844 }
845
846 return 1;
847 }
848
849 /*
850 * Get and set the EXDATA
851 */
RAND_DRBG_set_ex_data(RAND_DRBG * drbg,int idx,void * arg)852 int RAND_DRBG_set_ex_data(RAND_DRBG *drbg, int idx, void *arg)
853 {
854 return CRYPTO_set_ex_data(&drbg->ex_data, idx, arg);
855 }
856
RAND_DRBG_get_ex_data(const RAND_DRBG * drbg,int idx)857 void *RAND_DRBG_get_ex_data(const RAND_DRBG *drbg, int idx)
858 {
859 return CRYPTO_get_ex_data(&drbg->ex_data, idx);
860 }
861
862
863 /*
864 * The following functions provide a RAND_METHOD that works on the
865 * global DRBG. They lock.
866 */
867
868 /*
869 * Allocates a new global DRBG on the secure heap (if enabled) and
870 * initializes it with default settings.
871 *
872 * Returns a pointer to the new DRBG instance on success, NULL on failure.
873 */
drbg_setup(RAND_DRBG * parent)874 static RAND_DRBG *drbg_setup(RAND_DRBG *parent)
875 {
876 RAND_DRBG *drbg;
877
878 drbg = RAND_DRBG_secure_new(rand_drbg_type, rand_drbg_flags, parent);
879 if (drbg == NULL)
880 return NULL;
881
882 /* Only the master DRBG needs to have a lock */
883 if (parent == NULL && rand_drbg_enable_locking(drbg) == 0)
884 goto err;
885
886 /* enable seed propagation */
887 tsan_store(&drbg->reseed_prop_counter, 1);
888
889 /*
890 * Ignore instantiation error to support just-in-time instantiation.
891 *
892 * The state of the drbg will be checked in RAND_DRBG_generate() and
893 * an automatic recovery is attempted.
894 */
895 (void)RAND_DRBG_instantiate(drbg,
896 (const unsigned char *) ossl_pers_string,
897 sizeof(ossl_pers_string) - 1);
898 return drbg;
899
900 err:
901 RAND_DRBG_free(drbg);
902 return NULL;
903 }
904
905 /*
906 * Initialize the global DRBGs on first use.
907 * Returns 1 on success, 0 on failure.
908 */
DEFINE_RUN_ONCE_STATIC(do_rand_drbg_init)909 DEFINE_RUN_ONCE_STATIC(do_rand_drbg_init)
910 {
911 /*
912 * ensure that libcrypto is initialized, otherwise the
913 * DRBG locks are not cleaned up properly
914 */
915 if (!OPENSSL_init_crypto(0, NULL))
916 return 0;
917
918 if (!CRYPTO_THREAD_init_local(&private_drbg, NULL))
919 return 0;
920
921 if (!CRYPTO_THREAD_init_local(&public_drbg, NULL))
922 goto err1;
923
924 master_drbg = drbg_setup(NULL);
925 if (master_drbg == NULL)
926 goto err2;
927
928 return 1;
929
930 err2:
931 CRYPTO_THREAD_cleanup_local(&public_drbg);
932 err1:
933 CRYPTO_THREAD_cleanup_local(&private_drbg);
934 return 0;
935 }
936
937 /* Clean up the global DRBGs before exit */
rand_drbg_cleanup_int(void)938 void rand_drbg_cleanup_int(void)
939 {
940 if (master_drbg != NULL) {
941 RAND_DRBG_free(master_drbg);
942 master_drbg = NULL;
943
944 CRYPTO_THREAD_cleanup_local(&private_drbg);
945 CRYPTO_THREAD_cleanup_local(&public_drbg);
946 }
947 }
948
drbg_delete_thread_state(void)949 void drbg_delete_thread_state(void)
950 {
951 RAND_DRBG *drbg;
952
953 drbg = CRYPTO_THREAD_get_local(&public_drbg);
954 CRYPTO_THREAD_set_local(&public_drbg, NULL);
955 RAND_DRBG_free(drbg);
956
957 drbg = CRYPTO_THREAD_get_local(&private_drbg);
958 CRYPTO_THREAD_set_local(&private_drbg, NULL);
959 RAND_DRBG_free(drbg);
960 }
961
962 /* Implements the default OpenSSL RAND_bytes() method */
drbg_bytes(unsigned char * out,int count)963 static int drbg_bytes(unsigned char *out, int count)
964 {
965 int ret;
966 RAND_DRBG *drbg = RAND_DRBG_get0_public();
967
968 if (drbg == NULL)
969 return 0;
970
971 ret = RAND_DRBG_bytes(drbg, out, count);
972
973 return ret;
974 }
975
976 /*
977 * Calculates the minimum length of a full entropy buffer
978 * which is necessary to seed (i.e. instantiate) the DRBG
979 * successfully.
980 */
rand_drbg_seedlen(RAND_DRBG * drbg)981 size_t rand_drbg_seedlen(RAND_DRBG *drbg)
982 {
983 /*
984 * If no os entropy source is available then RAND_seed(buffer, bufsize)
985 * is expected to succeed if and only if the buffer length satisfies
986 * the following requirements, which follow from the calculations
987 * in RAND_DRBG_instantiate().
988 */
989 size_t min_entropy = drbg->strength;
990 size_t min_entropylen = drbg->min_entropylen;
991
992 /*
993 * Extra entropy for the random nonce in the absence of a
994 * get_nonce callback, see comment in RAND_DRBG_instantiate().
995 */
996 if (drbg->min_noncelen > 0 && drbg->get_nonce == NULL) {
997 min_entropy += drbg->strength / 2;
998 min_entropylen += drbg->min_noncelen;
999 }
1000
1001 /*
1002 * Convert entropy requirement from bits to bytes
1003 * (dividing by 8 without rounding upwards, because
1004 * all entropy requirements are divisible by 8).
1005 */
1006 min_entropy >>= 3;
1007
1008 /* Return a value that satisfies both requirements */
1009 return min_entropy > min_entropylen ? min_entropy : min_entropylen;
1010 }
1011
1012 /* Implements the default OpenSSL RAND_add() method */
drbg_add(const void * buf,int num,double randomness)1013 static int drbg_add(const void *buf, int num, double randomness)
1014 {
1015 int ret = 0;
1016 RAND_DRBG *drbg = RAND_DRBG_get0_master();
1017 size_t buflen;
1018 size_t seedlen;
1019
1020 if (drbg == NULL)
1021 return 0;
1022
1023 if (num < 0 || randomness < 0.0)
1024 return 0;
1025
1026 rand_drbg_lock(drbg);
1027 seedlen = rand_drbg_seedlen(drbg);
1028
1029 buflen = (size_t)num;
1030
1031 if (buflen < seedlen || randomness < (double) seedlen) {
1032 #if defined(OPENSSL_RAND_SEED_NONE)
1033 /*
1034 * If no os entropy source is available, a reseeding will fail
1035 * inevitably. So we use a trick to mix the buffer contents into
1036 * the DRBG state without forcing a reseeding: we generate a
1037 * dummy random byte, using the buffer content as additional data.
1038 * Note: This won't work with RAND_DRBG_FLAG_CTR_NO_DF.
1039 */
1040 unsigned char dummy[1];
1041
1042 ret = RAND_DRBG_generate(drbg, dummy, sizeof(dummy), 0, buf, buflen);
1043 rand_drbg_unlock(drbg);
1044 return ret;
1045 #else
1046 /*
1047 * If an os entropy source is available then we declare the buffer content
1048 * as additional data by setting randomness to zero and trigger a regular
1049 * reseeding.
1050 */
1051 randomness = 0.0;
1052 #endif
1053 }
1054
1055
1056 if (randomness > (double)seedlen) {
1057 /*
1058 * The purpose of this check is to bound |randomness| by a
1059 * relatively small value in order to prevent an integer
1060 * overflow when multiplying by 8 in the rand_drbg_restart()
1061 * call below. Note that randomness is measured in bytes,
1062 * not bits, so this value corresponds to eight times the
1063 * security strength.
1064 */
1065 randomness = (double)seedlen;
1066 }
1067
1068 ret = rand_drbg_restart(drbg, buf, buflen, (size_t)(8 * randomness));
1069 rand_drbg_unlock(drbg);
1070
1071 return ret;
1072 }
1073
1074 /* Implements the default OpenSSL RAND_seed() method */
drbg_seed(const void * buf,int num)1075 static int drbg_seed(const void *buf, int num)
1076 {
1077 return drbg_add(buf, num, num);
1078 }
1079
1080 /* Implements the default OpenSSL RAND_status() method */
drbg_status(void)1081 static int drbg_status(void)
1082 {
1083 int ret;
1084 RAND_DRBG *drbg = RAND_DRBG_get0_master();
1085
1086 if (drbg == NULL)
1087 return 0;
1088
1089 rand_drbg_lock(drbg);
1090 ret = drbg->state == DRBG_READY ? 1 : 0;
1091 rand_drbg_unlock(drbg);
1092 return ret;
1093 }
1094
1095 /*
1096 * Get the master DRBG.
1097 * Returns pointer to the DRBG on success, NULL on failure.
1098 *
1099 */
RAND_DRBG_get0_master(void)1100 RAND_DRBG *RAND_DRBG_get0_master(void)
1101 {
1102 if (!RUN_ONCE(&rand_drbg_init, do_rand_drbg_init))
1103 return NULL;
1104
1105 return master_drbg;
1106 }
1107
1108 /*
1109 * Get the public DRBG.
1110 * Returns pointer to the DRBG on success, NULL on failure.
1111 */
RAND_DRBG_get0_public(void)1112 RAND_DRBG *RAND_DRBG_get0_public(void)
1113 {
1114 RAND_DRBG *drbg;
1115
1116 if (!RUN_ONCE(&rand_drbg_init, do_rand_drbg_init))
1117 return NULL;
1118
1119 drbg = CRYPTO_THREAD_get_local(&public_drbg);
1120 if (drbg == NULL) {
1121 if (!ossl_init_thread_start(OPENSSL_INIT_THREAD_RAND))
1122 return NULL;
1123 drbg = drbg_setup(master_drbg);
1124 CRYPTO_THREAD_set_local(&public_drbg, drbg);
1125 }
1126 return drbg;
1127 }
1128
1129 /*
1130 * Get the private DRBG.
1131 * Returns pointer to the DRBG on success, NULL on failure.
1132 */
RAND_DRBG_get0_private(void)1133 RAND_DRBG *RAND_DRBG_get0_private(void)
1134 {
1135 RAND_DRBG *drbg;
1136
1137 if (!RUN_ONCE(&rand_drbg_init, do_rand_drbg_init))
1138 return NULL;
1139
1140 drbg = CRYPTO_THREAD_get_local(&private_drbg);
1141 if (drbg == NULL) {
1142 if (!ossl_init_thread_start(OPENSSL_INIT_THREAD_RAND))
1143 return NULL;
1144 drbg = drbg_setup(master_drbg);
1145 CRYPTO_THREAD_set_local(&private_drbg, drbg);
1146 }
1147 return drbg;
1148 }
1149
1150 RAND_METHOD rand_meth = {
1151 drbg_seed,
1152 drbg_bytes,
1153 NULL,
1154 drbg_add,
1155 drbg_bytes,
1156 drbg_status
1157 };
1158
RAND_OpenSSL(void)1159 RAND_METHOD *RAND_OpenSSL(void)
1160 {
1161 return &rand_meth;
1162 }
1163