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