1 /*
2 * Copyright 2011-2022 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 if (drbg->get_entropy != NULL)
331 entropylen = drbg->get_entropy(drbg, &entropy, min_entropy,
332 min_entropylen, max_entropylen, 0);
333 if (entropylen < min_entropylen
334 || entropylen > max_entropylen) {
335 RANDerr(RAND_F_RAND_DRBG_INSTANTIATE, RAND_R_ERROR_RETRIEVING_ENTROPY);
336 goto end;
337 }
338
339 if (drbg->min_noncelen > 0 && drbg->get_nonce != NULL) {
340 noncelen = drbg->get_nonce(drbg, &nonce, drbg->strength / 2,
341 drbg->min_noncelen, drbg->max_noncelen);
342 if (noncelen < drbg->min_noncelen || noncelen > drbg->max_noncelen) {
343 RANDerr(RAND_F_RAND_DRBG_INSTANTIATE, RAND_R_ERROR_RETRIEVING_NONCE);
344 goto end;
345 }
346 }
347
348 if (!drbg->meth->instantiate(drbg, entropy, entropylen,
349 nonce, noncelen, pers, perslen)) {
350 RANDerr(RAND_F_RAND_DRBG_INSTANTIATE, RAND_R_ERROR_INSTANTIATING_DRBG);
351 goto end;
352 }
353
354 drbg->state = DRBG_READY;
355 drbg->generate_counter = 1;
356 drbg->reseed_time = time(NULL);
357 if (drbg->enable_reseed_propagation && drbg->parent == NULL)
358 tsan_counter(&drbg->reseed_counter);
359
360 end:
361 if (entropy != NULL && drbg->cleanup_entropy != NULL)
362 drbg->cleanup_entropy(drbg, entropy, entropylen);
363 if (nonce != NULL && drbg->cleanup_nonce != NULL)
364 drbg->cleanup_nonce(drbg, nonce, noncelen);
365 if (drbg->state == DRBG_READY)
366 return 1;
367 return 0;
368 }
369
370 /*
371 * Uninstantiate |drbg|. Must be instantiated before it can be used.
372 *
373 * Requires that drbg->lock is already locked for write, if non-null.
374 *
375 * Returns 1 on success, 0 on failure.
376 */
RAND_DRBG_uninstantiate(RAND_DRBG * drbg)377 int RAND_DRBG_uninstantiate(RAND_DRBG *drbg)
378 {
379 if (drbg->meth == NULL) {
380 drbg->state = DRBG_ERROR;
381 RANDerr(RAND_F_RAND_DRBG_UNINSTANTIATE,
382 RAND_R_NO_DRBG_IMPLEMENTATION_SELECTED);
383 return 0;
384 }
385
386 /* Clear the entire drbg->ctr struct, then reset some important
387 * members of the drbg->ctr struct (e.g. keysize, df_ks) to their
388 * initial values.
389 */
390 drbg->meth->uninstantiate(drbg);
391 return RAND_DRBG_set(drbg, drbg->type, drbg->flags);
392 }
393
394 /*
395 * Reseed |drbg|, mixing in the specified data
396 *
397 * Requires that drbg->lock is already locked for write, if non-null.
398 *
399 * Returns 1 on success, 0 on failure.
400 */
RAND_DRBG_reseed(RAND_DRBG * drbg,const unsigned char * adin,size_t adinlen,int prediction_resistance)401 int RAND_DRBG_reseed(RAND_DRBG *drbg,
402 const unsigned char *adin, size_t adinlen,
403 int prediction_resistance)
404 {
405 unsigned char *entropy = NULL;
406 size_t entropylen = 0;
407
408 if (drbg->state == DRBG_ERROR) {
409 RANDerr(RAND_F_RAND_DRBG_RESEED, RAND_R_IN_ERROR_STATE);
410 return 0;
411 }
412 if (drbg->state == DRBG_UNINITIALISED) {
413 RANDerr(RAND_F_RAND_DRBG_RESEED, RAND_R_NOT_INSTANTIATED);
414 return 0;
415 }
416
417 if (adin == NULL) {
418 adinlen = 0;
419 } else if (adinlen > drbg->max_adinlen) {
420 RANDerr(RAND_F_RAND_DRBG_RESEED, RAND_R_ADDITIONAL_INPUT_TOO_LONG);
421 return 0;
422 }
423
424 drbg->state = DRBG_ERROR;
425 if (drbg->get_entropy != NULL)
426 entropylen = drbg->get_entropy(drbg, &entropy, drbg->strength,
427 drbg->min_entropylen,
428 drbg->max_entropylen,
429 prediction_resistance);
430 if (entropylen < drbg->min_entropylen
431 || entropylen > drbg->max_entropylen) {
432 RANDerr(RAND_F_RAND_DRBG_RESEED, RAND_R_ERROR_RETRIEVING_ENTROPY);
433 goto end;
434 }
435
436 if (!drbg->meth->reseed(drbg, entropy, entropylen, adin, adinlen))
437 goto end;
438
439 drbg->state = DRBG_READY;
440 drbg->generate_counter = 1;
441 drbg->reseed_time = time(NULL);
442 if (drbg->enable_reseed_propagation && drbg->parent == NULL)
443 tsan_counter(&drbg->reseed_counter);
444
445 end:
446 if (entropy != NULL && drbg->cleanup_entropy != NULL)
447 drbg->cleanup_entropy(drbg, entropy, entropylen);
448 if (drbg->state == DRBG_READY)
449 return 1;
450 return 0;
451 }
452
453 /*
454 * Restart |drbg|, using the specified entropy or additional input
455 *
456 * Tries its best to get the drbg instantiated by all means,
457 * regardless of its current state.
458 *
459 * Optionally, a |buffer| of |len| random bytes can be passed,
460 * which is assumed to contain at least |entropy| bits of entropy.
461 *
462 * If |entropy| > 0, the buffer content is used as entropy input.
463 *
464 * If |entropy| == 0, the buffer content is used as additional input
465 *
466 * Returns 1 on success, 0 on failure.
467 *
468 * This function is used internally only.
469 */
rand_drbg_restart(RAND_DRBG * drbg,const unsigned char * buffer,size_t len,size_t entropy)470 int rand_drbg_restart(RAND_DRBG *drbg,
471 const unsigned char *buffer, size_t len, size_t entropy)
472 {
473 int reseeded = 0;
474 const unsigned char *adin = NULL;
475 size_t adinlen = 0;
476
477 if (drbg->seed_pool != NULL) {
478 RANDerr(RAND_F_RAND_DRBG_RESTART, ERR_R_INTERNAL_ERROR);
479 drbg->state = DRBG_ERROR;
480 rand_pool_free(drbg->seed_pool);
481 drbg->seed_pool = NULL;
482 return 0;
483 }
484
485 if (buffer != NULL) {
486 if (entropy > 0) {
487 if (drbg->max_entropylen < len) {
488 RANDerr(RAND_F_RAND_DRBG_RESTART,
489 RAND_R_ENTROPY_INPUT_TOO_LONG);
490 drbg->state = DRBG_ERROR;
491 return 0;
492 }
493
494 if (entropy > 8 * len) {
495 RANDerr(RAND_F_RAND_DRBG_RESTART, RAND_R_ENTROPY_OUT_OF_RANGE);
496 drbg->state = DRBG_ERROR;
497 return 0;
498 }
499
500 /* will be picked up by the rand_drbg_get_entropy() callback */
501 drbg->seed_pool = rand_pool_attach(buffer, len, entropy);
502 if (drbg->seed_pool == NULL)
503 return 0;
504 } else {
505 if (drbg->max_adinlen < len) {
506 RANDerr(RAND_F_RAND_DRBG_RESTART,
507 RAND_R_ADDITIONAL_INPUT_TOO_LONG);
508 drbg->state = DRBG_ERROR;
509 return 0;
510 }
511 adin = buffer;
512 adinlen = len;
513 }
514 }
515
516 /* repair error state */
517 if (drbg->state == DRBG_ERROR)
518 RAND_DRBG_uninstantiate(drbg);
519
520 /* repair uninitialized state */
521 if (drbg->state == DRBG_UNINITIALISED) {
522 /* reinstantiate drbg */
523 RAND_DRBG_instantiate(drbg,
524 (const unsigned char *) ossl_pers_string,
525 sizeof(ossl_pers_string) - 1);
526 /* already reseeded. prevent second reseeding below */
527 reseeded = (drbg->state == DRBG_READY);
528 }
529
530 /* refresh current state if entropy or additional input has been provided */
531 if (drbg->state == DRBG_READY) {
532 if (adin != NULL) {
533 /*
534 * mix in additional input without reseeding
535 *
536 * Similar to RAND_DRBG_reseed(), but the provided additional
537 * data |adin| is mixed into the current state without pulling
538 * entropy from the trusted entropy source using get_entropy().
539 * This is not a reseeding in the strict sense of NIST SP 800-90A.
540 */
541 drbg->meth->reseed(drbg, adin, adinlen, NULL, 0);
542 } else if (reseeded == 0) {
543 /* do a full reseeding if it has not been done yet above */
544 if (!RAND_DRBG_reseed(drbg, NULL, 0, 0)) {
545 RANDerr(RAND_F_RAND_DRBG_RESTART, RAND_R_RESEED_ERROR);
546 }
547 }
548 }
549
550 rand_pool_free(drbg->seed_pool);
551 drbg->seed_pool = NULL;
552
553 return drbg->state == DRBG_READY;
554 }
555
556 /*
557 * Generate |outlen| bytes into the buffer at |out|. Reseed if we need
558 * to or if |prediction_resistance| is set. Additional input can be
559 * sent in |adin| and |adinlen|.
560 *
561 * Requires that drbg->lock is already locked for write, if non-null.
562 *
563 * Returns 1 on success, 0 on failure.
564 *
565 */
RAND_DRBG_generate(RAND_DRBG * drbg,unsigned char * out,size_t outlen,int prediction_resistance,const unsigned char * adin,size_t adinlen)566 int RAND_DRBG_generate(RAND_DRBG *drbg, unsigned char *out, size_t outlen,
567 int prediction_resistance,
568 const unsigned char *adin, size_t adinlen)
569 {
570 int fork_id;
571 int reseed_required = 0;
572
573 if (drbg->state != DRBG_READY) {
574 /* try to recover from previous errors */
575 rand_drbg_restart(drbg, NULL, 0, 0);
576
577 if (drbg->state == DRBG_ERROR) {
578 RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_IN_ERROR_STATE);
579 return 0;
580 }
581 if (drbg->state == DRBG_UNINITIALISED) {
582 RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_NOT_INSTANTIATED);
583 return 0;
584 }
585 }
586
587 if (outlen > drbg->max_request) {
588 RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_REQUEST_TOO_LARGE_FOR_DRBG);
589 return 0;
590 }
591 if (adinlen > drbg->max_adinlen) {
592 RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_ADDITIONAL_INPUT_TOO_LONG);
593 return 0;
594 }
595
596 fork_id = openssl_get_fork_id();
597
598 if (drbg->fork_id != fork_id) {
599 drbg->fork_id = fork_id;
600 reseed_required = 1;
601 }
602
603 if (drbg->reseed_interval > 0) {
604 if (drbg->generate_counter >= drbg->reseed_interval)
605 reseed_required = 1;
606 }
607 if (drbg->reseed_time_interval > 0) {
608 time_t now = time(NULL);
609 if (now < drbg->reseed_time
610 || now - drbg->reseed_time >= drbg->reseed_time_interval)
611 reseed_required = 1;
612 }
613 if (drbg->enable_reseed_propagation && drbg->parent != NULL) {
614 if (drbg->reseed_counter != tsan_load(&drbg->parent->reseed_counter))
615 reseed_required = 1;
616 }
617
618 if (reseed_required || prediction_resistance) {
619 if (!RAND_DRBG_reseed(drbg, adin, adinlen, prediction_resistance)) {
620 RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_RESEED_ERROR);
621 return 0;
622 }
623 adin = NULL;
624 adinlen = 0;
625 }
626
627 if (!drbg->meth->generate(drbg, out, outlen, adin, adinlen)) {
628 drbg->state = DRBG_ERROR;
629 RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_GENERATE_ERROR);
630 return 0;
631 }
632
633 drbg->generate_counter++;
634
635 return 1;
636 }
637
638 /*
639 * Generates |outlen| random bytes and stores them in |out|. It will
640 * using the given |drbg| to generate the bytes.
641 *
642 * Requires that drbg->lock is already locked for write, if non-null.
643 *
644 * Returns 1 on success 0 on failure.
645 */
RAND_DRBG_bytes(RAND_DRBG * drbg,unsigned char * out,size_t outlen)646 int RAND_DRBG_bytes(RAND_DRBG *drbg, unsigned char *out, size_t outlen)
647 {
648 unsigned char *additional = NULL;
649 size_t additional_len;
650 size_t chunk;
651 size_t ret = 0;
652
653 if (drbg->adin_pool == NULL) {
654 if (drbg->type == 0)
655 goto err;
656 drbg->adin_pool = rand_pool_new(0, 0, 0, drbg->max_adinlen);
657 if (drbg->adin_pool == NULL)
658 goto err;
659 }
660
661 additional_len = rand_drbg_get_additional_data(drbg->adin_pool,
662 &additional);
663
664 for ( ; outlen > 0; outlen -= chunk, out += chunk) {
665 chunk = outlen;
666 if (chunk > drbg->max_request)
667 chunk = drbg->max_request;
668 ret = RAND_DRBG_generate(drbg, out, chunk, 0, additional, additional_len);
669 if (!ret)
670 goto err;
671 }
672 ret = 1;
673
674 err:
675 if (additional != NULL)
676 rand_drbg_cleanup_additional_data(drbg->adin_pool, additional);
677
678 return ret;
679 }
680
681 /*
682 * Set the RAND_DRBG callbacks for obtaining entropy and nonce.
683 *
684 * Setting the callbacks is allowed only if the drbg has not been
685 * initialized yet. Otherwise, the operation will fail.
686 *
687 * Returns 1 on success, 0 on failure.
688 */
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)689 int RAND_DRBG_set_callbacks(RAND_DRBG *drbg,
690 RAND_DRBG_get_entropy_fn get_entropy,
691 RAND_DRBG_cleanup_entropy_fn cleanup_entropy,
692 RAND_DRBG_get_nonce_fn get_nonce,
693 RAND_DRBG_cleanup_nonce_fn cleanup_nonce)
694 {
695 if (drbg->state != DRBG_UNINITIALISED)
696 return 0;
697 drbg->get_entropy = get_entropy;
698 drbg->cleanup_entropy = cleanup_entropy;
699 drbg->get_nonce = get_nonce;
700 drbg->cleanup_nonce = cleanup_nonce;
701 return 1;
702 }
703
704 /*
705 * Set the reseed interval.
706 *
707 * The drbg will reseed automatically whenever the number of generate
708 * requests exceeds the given reseed interval. If the reseed interval
709 * is 0, then this feature is disabled.
710 *
711 * Returns 1 on success, 0 on failure.
712 */
RAND_DRBG_set_reseed_interval(RAND_DRBG * drbg,unsigned int interval)713 int RAND_DRBG_set_reseed_interval(RAND_DRBG *drbg, unsigned int interval)
714 {
715 if (interval > MAX_RESEED_INTERVAL)
716 return 0;
717 drbg->reseed_interval = interval;
718 return 1;
719 }
720
721 /*
722 * Set the reseed time interval.
723 *
724 * The drbg will reseed automatically whenever the time elapsed since
725 * the last reseeding exceeds the given reseed time interval. For safety,
726 * a reseeding will also occur if the clock has been reset to a smaller
727 * value.
728 *
729 * Returns 1 on success, 0 on failure.
730 */
RAND_DRBG_set_reseed_time_interval(RAND_DRBG * drbg,time_t interval)731 int RAND_DRBG_set_reseed_time_interval(RAND_DRBG *drbg, time_t interval)
732 {
733 if (interval > MAX_RESEED_TIME_INTERVAL)
734 return 0;
735 drbg->reseed_time_interval = interval;
736 return 1;
737 }
738
739 /*
740 * Set the default values for reseed (time) intervals of new DRBG instances
741 *
742 * The default values can be set independently for master DRBG instances
743 * (without a parent) and slave DRBG instances (with parent).
744 *
745 * Returns 1 on success, 0 on failure.
746 */
747
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)748 int RAND_DRBG_set_reseed_defaults(
749 unsigned int _master_reseed_interval,
750 unsigned int _slave_reseed_interval,
751 time_t _master_reseed_time_interval,
752 time_t _slave_reseed_time_interval
753 )
754 {
755 if (_master_reseed_interval > MAX_RESEED_INTERVAL
756 || _slave_reseed_interval > MAX_RESEED_INTERVAL)
757 return 0;
758
759 if (_master_reseed_time_interval > MAX_RESEED_TIME_INTERVAL
760 || _slave_reseed_time_interval > MAX_RESEED_TIME_INTERVAL)
761 return 0;
762
763 master_reseed_interval = _master_reseed_interval;
764 slave_reseed_interval = _slave_reseed_interval;
765
766 master_reseed_time_interval = _master_reseed_time_interval;
767 slave_reseed_time_interval = _slave_reseed_time_interval;
768
769 return 1;
770 }
771
772 /*
773 * Locks the given drbg. Locking a drbg which does not have locking
774 * enabled is considered a successful no-op.
775 *
776 * Returns 1 on success, 0 on failure.
777 */
rand_drbg_lock(RAND_DRBG * drbg)778 int rand_drbg_lock(RAND_DRBG *drbg)
779 {
780 if (drbg->lock != NULL)
781 return CRYPTO_THREAD_write_lock(drbg->lock);
782
783 return 1;
784 }
785
786 /*
787 * Unlocks the given drbg. Unlocking a drbg which does not have locking
788 * enabled is considered a successful no-op.
789 *
790 * Returns 1 on success, 0 on failure.
791 */
rand_drbg_unlock(RAND_DRBG * drbg)792 int rand_drbg_unlock(RAND_DRBG *drbg)
793 {
794 if (drbg->lock != NULL)
795 return CRYPTO_THREAD_unlock(drbg->lock);
796
797 return 1;
798 }
799
800 /*
801 * Enables locking for the given drbg
802 *
803 * Locking can only be enabled if the random generator
804 * is in the uninitialized state.
805 *
806 * Returns 1 on success, 0 on failure.
807 */
rand_drbg_enable_locking(RAND_DRBG * drbg)808 int rand_drbg_enable_locking(RAND_DRBG *drbg)
809 {
810 if (drbg->state != DRBG_UNINITIALISED) {
811 RANDerr(RAND_F_RAND_DRBG_ENABLE_LOCKING,
812 RAND_R_DRBG_ALREADY_INITIALIZED);
813 return 0;
814 }
815
816 if (drbg->lock == NULL) {
817 if (drbg->parent != NULL && drbg->parent->lock == NULL) {
818 RANDerr(RAND_F_RAND_DRBG_ENABLE_LOCKING,
819 RAND_R_PARENT_LOCKING_NOT_ENABLED);
820 return 0;
821 }
822
823 drbg->lock = CRYPTO_THREAD_lock_new();
824 if (drbg->lock == NULL) {
825 RANDerr(RAND_F_RAND_DRBG_ENABLE_LOCKING,
826 RAND_R_FAILED_TO_CREATE_LOCK);
827 return 0;
828 }
829 }
830
831 return 1;
832 }
833
834 /*
835 * Get and set the EXDATA
836 */
RAND_DRBG_set_ex_data(RAND_DRBG * drbg,int idx,void * arg)837 int RAND_DRBG_set_ex_data(RAND_DRBG *drbg, int idx, void *arg)
838 {
839 return CRYPTO_set_ex_data(&drbg->ex_data, idx, arg);
840 }
841
RAND_DRBG_get_ex_data(const RAND_DRBG * drbg,int idx)842 void *RAND_DRBG_get_ex_data(const RAND_DRBG *drbg, int idx)
843 {
844 return CRYPTO_get_ex_data(&drbg->ex_data, idx);
845 }
846
847
848 /*
849 * The following functions provide a RAND_METHOD that works on the
850 * global DRBG. They lock.
851 */
852
853 /*
854 * Allocates a new global DRBG on the secure heap (if enabled) and
855 * initializes it with default settings.
856 *
857 * Returns a pointer to the new DRBG instance on success, NULL on failure.
858 */
drbg_setup(RAND_DRBG * parent)859 static RAND_DRBG *drbg_setup(RAND_DRBG *parent)
860 {
861 RAND_DRBG *drbg;
862
863 drbg = RAND_DRBG_secure_new(rand_drbg_type, rand_drbg_flags, parent);
864 if (drbg == NULL)
865 return NULL;
866
867 /* Only the master DRBG needs to have a lock */
868 if (parent == NULL && rand_drbg_enable_locking(drbg) == 0)
869 goto err;
870
871 /* enable reseed propagation */
872 drbg->enable_reseed_propagation = 1;
873 drbg->reseed_counter = 1;
874
875 /*
876 * Ignore instantiation error to support just-in-time instantiation.
877 *
878 * The state of the drbg will be checked in RAND_DRBG_generate() and
879 * an automatic recovery is attempted.
880 */
881 (void)RAND_DRBG_instantiate(drbg,
882 (const unsigned char *) ossl_pers_string,
883 sizeof(ossl_pers_string) - 1);
884 return drbg;
885
886 err:
887 RAND_DRBG_free(drbg);
888 return NULL;
889 }
890
891 /*
892 * Initialize the global DRBGs on first use.
893 * Returns 1 on success, 0 on failure.
894 */
DEFINE_RUN_ONCE_STATIC(do_rand_drbg_init)895 DEFINE_RUN_ONCE_STATIC(do_rand_drbg_init)
896 {
897 /*
898 * ensure that libcrypto is initialized, otherwise the
899 * DRBG locks are not cleaned up properly
900 */
901 if (!OPENSSL_init_crypto(0, NULL))
902 return 0;
903
904 if (!CRYPTO_THREAD_init_local(&private_drbg, NULL))
905 return 0;
906
907 if (!CRYPTO_THREAD_init_local(&public_drbg, NULL))
908 goto err1;
909
910 master_drbg = drbg_setup(NULL);
911 if (master_drbg == NULL)
912 goto err2;
913
914 return 1;
915
916 err2:
917 CRYPTO_THREAD_cleanup_local(&public_drbg);
918 err1:
919 CRYPTO_THREAD_cleanup_local(&private_drbg);
920 return 0;
921 }
922
923 /* Clean up the global DRBGs before exit */
rand_drbg_cleanup_int(void)924 void rand_drbg_cleanup_int(void)
925 {
926 if (master_drbg != NULL) {
927 RAND_DRBG_free(master_drbg);
928 master_drbg = NULL;
929
930 CRYPTO_THREAD_cleanup_local(&private_drbg);
931 CRYPTO_THREAD_cleanup_local(&public_drbg);
932 }
933 }
934
drbg_delete_thread_state(void)935 void drbg_delete_thread_state(void)
936 {
937 RAND_DRBG *drbg;
938
939 drbg = CRYPTO_THREAD_get_local(&public_drbg);
940 CRYPTO_THREAD_set_local(&public_drbg, NULL);
941 RAND_DRBG_free(drbg);
942
943 drbg = CRYPTO_THREAD_get_local(&private_drbg);
944 CRYPTO_THREAD_set_local(&private_drbg, NULL);
945 RAND_DRBG_free(drbg);
946 }
947
948 /* Implements the default OpenSSL RAND_bytes() method */
drbg_bytes(unsigned char * out,int count)949 static int drbg_bytes(unsigned char *out, int count)
950 {
951 int ret;
952 RAND_DRBG *drbg = RAND_DRBG_get0_public();
953
954 if (drbg == NULL)
955 return 0;
956
957 ret = RAND_DRBG_bytes(drbg, out, count);
958
959 return ret;
960 }
961
962 /*
963 * Calculates the minimum length of a full entropy buffer
964 * which is necessary to seed (i.e. instantiate) the DRBG
965 * successfully.
966 */
rand_drbg_seedlen(RAND_DRBG * drbg)967 size_t rand_drbg_seedlen(RAND_DRBG *drbg)
968 {
969 /*
970 * If no os entropy source is available then RAND_seed(buffer, bufsize)
971 * is expected to succeed if and only if the buffer length satisfies
972 * the following requirements, which follow from the calculations
973 * in RAND_DRBG_instantiate().
974 */
975 size_t min_entropy = drbg->strength;
976 size_t min_entropylen = drbg->min_entropylen;
977
978 /*
979 * Extra entropy for the random nonce in the absence of a
980 * get_nonce callback, see comment in RAND_DRBG_instantiate().
981 */
982 if (drbg->min_noncelen > 0 && drbg->get_nonce == NULL) {
983 min_entropy += drbg->strength / 2;
984 min_entropylen += drbg->min_noncelen;
985 }
986
987 /*
988 * Convert entropy requirement from bits to bytes
989 * (dividing by 8 without rounding upwards, because
990 * all entropy requirements are divisible by 8).
991 */
992 min_entropy >>= 3;
993
994 /* Return a value that satisfies both requirements */
995 return min_entropy > min_entropylen ? min_entropy : min_entropylen;
996 }
997
998 /* Implements the default OpenSSL RAND_add() method */
drbg_add(const void * buf,int num,double randomness)999 static int drbg_add(const void *buf, int num, double randomness)
1000 {
1001 int ret = 0;
1002 RAND_DRBG *drbg = RAND_DRBG_get0_master();
1003 size_t buflen;
1004 size_t seedlen;
1005
1006 if (drbg == NULL)
1007 return 0;
1008
1009 if (num < 0 || randomness < 0.0)
1010 return 0;
1011
1012 rand_drbg_lock(drbg);
1013 seedlen = rand_drbg_seedlen(drbg);
1014
1015 buflen = (size_t)num;
1016
1017 if (buflen < seedlen || randomness < (double) seedlen) {
1018 #if defined(OPENSSL_RAND_SEED_NONE)
1019 /*
1020 * If no os entropy source is available, a reseeding will fail
1021 * inevitably. So we use a trick to mix the buffer contents into
1022 * the DRBG state without forcing a reseeding: we generate a
1023 * dummy random byte, using the buffer content as additional data.
1024 * Note: This won't work with RAND_DRBG_FLAG_CTR_NO_DF.
1025 */
1026 unsigned char dummy[1];
1027
1028 ret = RAND_DRBG_generate(drbg, dummy, sizeof(dummy), 0, buf, buflen);
1029 rand_drbg_unlock(drbg);
1030 return ret;
1031 #else
1032 /*
1033 * If an os entropy source is available then we declare the buffer content
1034 * as additional data by setting randomness to zero and trigger a regular
1035 * reseeding.
1036 */
1037 randomness = 0.0;
1038 #endif
1039 }
1040
1041
1042 if (randomness > (double)seedlen) {
1043 /*
1044 * The purpose of this check is to bound |randomness| by a
1045 * relatively small value in order to prevent an integer
1046 * overflow when multiplying by 8 in the rand_drbg_restart()
1047 * call below. Note that randomness is measured in bytes,
1048 * not bits, so this value corresponds to eight times the
1049 * security strength.
1050 */
1051 randomness = (double)seedlen;
1052 }
1053
1054 ret = rand_drbg_restart(drbg, buf, buflen, (size_t)(8 * randomness));
1055 rand_drbg_unlock(drbg);
1056
1057 return ret;
1058 }
1059
1060 /* Implements the default OpenSSL RAND_seed() method */
drbg_seed(const void * buf,int num)1061 static int drbg_seed(const void *buf, int num)
1062 {
1063 return drbg_add(buf, num, num);
1064 }
1065
1066 /* Implements the default OpenSSL RAND_status() method */
drbg_status(void)1067 static int drbg_status(void)
1068 {
1069 int ret;
1070 RAND_DRBG *drbg = RAND_DRBG_get0_master();
1071
1072 if (drbg == NULL)
1073 return 0;
1074
1075 rand_drbg_lock(drbg);
1076 ret = drbg->state == DRBG_READY ? 1 : 0;
1077 rand_drbg_unlock(drbg);
1078 return ret;
1079 }
1080
1081 /*
1082 * Get the master DRBG.
1083 * Returns pointer to the DRBG on success, NULL on failure.
1084 *
1085 */
RAND_DRBG_get0_master(void)1086 RAND_DRBG *RAND_DRBG_get0_master(void)
1087 {
1088 if (!RUN_ONCE(&rand_drbg_init, do_rand_drbg_init))
1089 return NULL;
1090
1091 return master_drbg;
1092 }
1093
1094 /*
1095 * Get the public DRBG.
1096 * Returns pointer to the DRBG on success, NULL on failure.
1097 */
RAND_DRBG_get0_public(void)1098 RAND_DRBG *RAND_DRBG_get0_public(void)
1099 {
1100 RAND_DRBG *drbg;
1101
1102 if (!RUN_ONCE(&rand_drbg_init, do_rand_drbg_init))
1103 return NULL;
1104
1105 drbg = CRYPTO_THREAD_get_local(&public_drbg);
1106 if (drbg == NULL) {
1107 if (!ossl_init_thread_start(OPENSSL_INIT_THREAD_RAND))
1108 return NULL;
1109 drbg = drbg_setup(master_drbg);
1110 CRYPTO_THREAD_set_local(&public_drbg, drbg);
1111 }
1112 return drbg;
1113 }
1114
1115 /*
1116 * Get the private DRBG.
1117 * Returns pointer to the DRBG on success, NULL on failure.
1118 */
RAND_DRBG_get0_private(void)1119 RAND_DRBG *RAND_DRBG_get0_private(void)
1120 {
1121 RAND_DRBG *drbg;
1122
1123 if (!RUN_ONCE(&rand_drbg_init, do_rand_drbg_init))
1124 return NULL;
1125
1126 drbg = CRYPTO_THREAD_get_local(&private_drbg);
1127 if (drbg == NULL) {
1128 if (!ossl_init_thread_start(OPENSSL_INIT_THREAD_RAND))
1129 return NULL;
1130 drbg = drbg_setup(master_drbg);
1131 CRYPTO_THREAD_set_local(&private_drbg, drbg);
1132 }
1133 return drbg;
1134 }
1135
1136 RAND_METHOD rand_meth = {
1137 drbg_seed,
1138 drbg_bytes,
1139 NULL,
1140 drbg_add,
1141 drbg_bytes,
1142 drbg_status
1143 };
1144
RAND_OpenSSL(void)1145 RAND_METHOD *RAND_OpenSSL(void)
1146 {
1147 return &rand_meth;
1148 }
1149