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