2 * Copyright 2011-2017 The OpenSSL Project Authors. All Rights Reserved.
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
11 #include <openssl/crypto.h>
12 #include <openssl/err.h>
13 #include <openssl/rand.h>
15 #include "internal/thread_once.h"
16 #include "internal/rand_int.h"
18 static RAND_DRBG rand_drbg; /* The default global DRBG. */
19 static RAND_DRBG priv_drbg; /* The global private-key DRBG. */
21 /* NIST SP 800-90A DRBG recommends the use of a personalization string. */
22 static const char ossl_pers_string[] = "OpenSSL NIST SP 800-90A DRBG";
25 * Support framework for NIST SP 800-90A DRBG, AES-CTR mode.
26 * The RAND_DRBG is OpenSSL's pointer to an instance of the DRBG.
28 * The OpenSSL model is to have new and free functions, and that new
29 * does all initialization. That is not the NIST model, which has
30 * instantiation and un-instantiate, and re-use within a new/free
31 * lifecycle. (No doubt this comes from the desire to support hardware
32 * DRBG, where allocation of resources on something like an HSM is
33 * a much bigger deal than just re-setting an allocated resource.)
36 static CRYPTO_ONCE rand_drbg_init = CRYPTO_ONCE_STATIC_INIT;
38 static int drbg_setup(RAND_DRBG *drbg, const char *name);
41 * Set/initialize |drbg| to be of type |nid|, with optional |flags|.
42 * Return -2 if the type is not supported, 1 on success and -1 on
45 int RAND_DRBG_set(RAND_DRBG *drbg, int nid, unsigned int flags)
49 drbg->state = DRBG_UNINITIALISED;
55 RANDerr(RAND_F_RAND_DRBG_SET, RAND_R_UNSUPPORTED_DRBG_TYPE);
58 /* Uninitialized; that's okay. */
68 RANDerr(RAND_F_RAND_DRBG_SET, RAND_R_ERROR_INITIALISING_DRBG);
73 * Allocate memory and initialize a new DRBG. The |parent|, if not
74 * NULL, will be used to auto-seed this RAND_DRBG as needed.
76 RAND_DRBG *RAND_DRBG_new(int type, unsigned int flags, RAND_DRBG *parent)
78 RAND_DRBG *drbg = OPENSSL_zalloc(sizeof(*drbg));
81 RANDerr(RAND_F_RAND_DRBG_NEW, ERR_R_MALLOC_FAILURE);
84 drbg->fork_count = rand_fork_count;
85 drbg->parent = parent;
86 if (RAND_DRBG_set(drbg, type, flags) < 0)
90 if (!RAND_DRBG_set_callbacks(drbg, rand_drbg_get_entropy,
91 rand_drbg_cleanup_entropy,
104 * Uninstantiate |drbg| and free all memory.
106 void RAND_DRBG_free(RAND_DRBG *drbg)
111 ctr_uninstantiate(drbg);
112 CRYPTO_free_ex_data(CRYPTO_EX_INDEX_DRBG, drbg, &drbg->ex_data);
113 OPENSSL_clear_free(drbg, sizeof(*drbg));
117 * Instantiate |drbg|, after it has been initialized. Use |pers| and
118 * |perslen| as prediction-resistance input.
120 * Requires that drbg->lock is already locked for write, if non-null.
122 int RAND_DRBG_instantiate(RAND_DRBG *drbg,
123 const unsigned char *pers, size_t perslen)
125 unsigned char *nonce = NULL, *entropy = NULL;
126 size_t noncelen = 0, entropylen = 0;
128 if (perslen > drbg->max_perslen) {
129 RANDerr(RAND_F_RAND_DRBG_INSTANTIATE,
130 RAND_R_PERSONALISATION_STRING_TOO_LONG);
133 if (drbg->state != DRBG_UNINITIALISED) {
134 RANDerr(RAND_F_RAND_DRBG_INSTANTIATE,
135 drbg->state == DRBG_ERROR ? RAND_R_IN_ERROR_STATE
136 : RAND_R_ALREADY_INSTANTIATED);
140 drbg->state = DRBG_ERROR;
141 if (drbg->get_entropy != NULL)
142 entropylen = drbg->get_entropy(drbg, &entropy, drbg->strength,
143 drbg->min_entropylen, drbg->max_entropylen);
144 if (entropylen < drbg->min_entropylen
145 || entropylen > drbg->max_entropylen) {
146 RANDerr(RAND_F_RAND_DRBG_INSTANTIATE, RAND_R_ERROR_RETRIEVING_ENTROPY);
150 if (drbg->max_noncelen > 0 && drbg->get_nonce != NULL) {
151 noncelen = drbg->get_nonce(drbg, &nonce, drbg->strength / 2,
152 drbg->min_noncelen, drbg->max_noncelen);
153 if (noncelen < drbg->min_noncelen || noncelen > drbg->max_noncelen) {
154 RANDerr(RAND_F_RAND_DRBG_INSTANTIATE,
155 RAND_R_ERROR_RETRIEVING_NONCE);
160 if (!ctr_instantiate(drbg, entropy, entropylen,
161 nonce, noncelen, pers, perslen)) {
162 RANDerr(RAND_F_RAND_DRBG_INSTANTIATE, RAND_R_ERROR_INSTANTIATING_DRBG);
166 drbg->state = DRBG_READY;
167 drbg->reseed_counter = 1;
170 if (entropy != NULL && drbg->cleanup_entropy != NULL)
171 drbg->cleanup_entropy(drbg, entropy, entropylen);
172 if (nonce != NULL && drbg->cleanup_nonce!= NULL )
173 drbg->cleanup_nonce(drbg, nonce, noncelen);
174 if (drbg->pool != NULL) {
175 if (drbg->state == DRBG_READY) {
176 RANDerr(RAND_F_RAND_DRBG_INSTANTIATE,
177 RAND_R_ERROR_ENTROPY_POOL_WAS_IGNORED);
178 drbg->state = DRBG_ERROR;
180 RAND_POOL_free(drbg->pool);
183 if (drbg->state == DRBG_READY)
189 * Uninstantiate |drbg|. Must be instantiated before it can be used.
191 * Requires that drbg->lock is already locked for write, if non-null.
193 int RAND_DRBG_uninstantiate(RAND_DRBG *drbg)
195 int ret = ctr_uninstantiate(drbg);
197 OPENSSL_cleanse(&drbg->ctr, sizeof(drbg->ctr));
198 drbg->state = DRBG_UNINITIALISED;
203 * Reseed |drbg|, mixing in the specified data
205 * Requires that drbg->lock is already locked for write, if non-null.
207 int RAND_DRBG_reseed(RAND_DRBG *drbg,
208 const unsigned char *adin, size_t adinlen)
210 unsigned char *entropy = NULL;
211 size_t entropylen = 0;
213 if (drbg->state == DRBG_ERROR) {
214 RANDerr(RAND_F_RAND_DRBG_RESEED, RAND_R_IN_ERROR_STATE);
217 if (drbg->state == DRBG_UNINITIALISED) {
218 RANDerr(RAND_F_RAND_DRBG_RESEED, RAND_R_NOT_INSTANTIATED);
224 else if (adinlen > drbg->max_adinlen) {
225 RANDerr(RAND_F_RAND_DRBG_RESEED, RAND_R_ADDITIONAL_INPUT_TOO_LONG);
229 drbg->state = DRBG_ERROR;
230 if (drbg->get_entropy != NULL)
231 entropylen = drbg->get_entropy(drbg, &entropy, drbg->strength,
232 drbg->min_entropylen, drbg->max_entropylen);
233 if (entropylen < drbg->min_entropylen
234 || entropylen > drbg->max_entropylen) {
235 RANDerr(RAND_F_RAND_DRBG_RESEED, RAND_R_ERROR_RETRIEVING_ENTROPY);
239 if (!ctr_reseed(drbg, entropy, entropylen, adin, adinlen))
241 drbg->state = DRBG_READY;
242 drbg->reseed_counter = 1;
245 if (entropy != NULL && drbg->cleanup_entropy != NULL)
246 drbg->cleanup_entropy(drbg, entropy, entropylen);
247 if (drbg->state == DRBG_READY)
253 * Restart |drbg|, using the specified entropy or additional input
255 * Tries its best to get the drbg instantiated by all means,
256 * regardless of its current state.
258 * Optionally, a |buffer| of |len| random bytes can be passed,
259 * which is assumed to contain at least |entropy| bits of entropy.
261 * If |entropy| > 0, the buffer content is used as entropy input.
263 * If |entropy| == 0, the buffer content is used as additional input
265 * Returns 1 on success, 0 on failure.
267 * This function is used internally only.
269 int rand_drbg_restart(RAND_DRBG *drbg,
270 const unsigned char *buffer, size_t len, size_t entropy)
273 const unsigned char *adin = NULL;
276 if (drbg->pool != NULL) {
277 RANDerr(RAND_F_RAND_DRBG_RESTART, ERR_R_INTERNAL_ERROR);
278 RAND_POOL_free(drbg->pool);
282 if (buffer != NULL) {
284 if (drbg->max_entropylen < len) {
285 RANDerr(RAND_F_RAND_DRBG_RESTART,
286 RAND_R_ENTROPY_INPUT_TOO_LONG);
290 if (entropy > 8 * len) {
291 RANDerr(RAND_F_RAND_DRBG_RESTART, RAND_R_ENTROPY_OUT_OF_RANGE);
295 /* will be picked up by the rand_drbg_get_entropy() callback */
296 drbg->pool = RAND_POOL_new(entropy, len, len);
297 if (drbg->pool == NULL)
300 RAND_POOL_add(drbg->pool, buffer, len, entropy);
302 if (drbg->max_adinlen < len) {
303 RANDerr(RAND_F_RAND_DRBG_RESTART,
304 RAND_R_ADDITIONAL_INPUT_TOO_LONG);
312 /* repair error state */
313 if (drbg->state == DRBG_ERROR)
314 RAND_DRBG_uninstantiate(drbg);
316 /* repair uninitialized state */
317 if (drbg->state == DRBG_UNINITIALISED) {
318 drbg_setup(drbg, NULL);
319 /* already reseeded. prevent second reseeding below */
320 reseeded = (drbg->state == DRBG_READY);
323 /* refresh current state if entropy or additional input has been provided */
324 if (drbg->state == DRBG_READY) {
327 * mix in additional input without reseeding
329 * Similar to RAND_DRBG_reseed(), but the provided additional
330 * data |adin| is mixed into the current state without pulling
331 * entropy from the trusted entropy source using get_entropy().
332 * This is not a reseeding in the strict sense of NIST SP 800-90A.
334 ctr_reseed(drbg, adin, adinlen, NULL, 0);
335 } else if (reseeded == 0) {
336 /* do a full reseeding if it has not been done yet above */
337 RAND_DRBG_reseed(drbg, NULL, 0);
341 /* check whether a given entropy pool was cleared properly during reseed */
342 if (drbg->pool != NULL) {
343 drbg->state = DRBG_ERROR;
344 RANDerr(RAND_F_RAND_DRBG_RESTART, ERR_R_INTERNAL_ERROR);
345 RAND_POOL_free(drbg->pool);
350 return drbg->state == DRBG_READY;
354 * Generate |outlen| bytes into the buffer at |out|. Reseed if we need
355 * to or if |prediction_resistance| is set. Additional input can be
356 * sent in |adin| and |adinlen|.
358 * Requires that drbg->lock is already locked for write, if non-null.
360 * Returns 1 on success, 0 on failure.
363 int RAND_DRBG_generate(RAND_DRBG *drbg, unsigned char *out, size_t outlen,
364 int prediction_resistance,
365 const unsigned char *adin, size_t adinlen)
367 int reseed_required = 0;
369 if (drbg->state != DRBG_READY) {
370 /* try to recover from previous errors */
371 rand_drbg_restart(drbg, NULL, 0, 0);
373 if (drbg->state == DRBG_ERROR) {
374 RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_IN_ERROR_STATE);
377 if (drbg->state == DRBG_UNINITIALISED) {
378 RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_NOT_INSTANTIATED);
383 if (outlen > drbg->max_request) {
384 RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_REQUEST_TOO_LARGE_FOR_DRBG);
387 if (adinlen > drbg->max_adinlen) {
388 RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_ADDITIONAL_INPUT_TOO_LONG);
392 if (drbg->fork_count != rand_fork_count) {
393 drbg->fork_count = rand_fork_count;
397 if (drbg->reseed_counter >= drbg->reseed_interval)
400 if (reseed_required || prediction_resistance) {
401 if (!RAND_DRBG_reseed(drbg, adin, adinlen)) {
402 RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_RESEED_ERROR);
409 if (!ctr_generate(drbg, out, outlen, adin, adinlen)) {
410 drbg->state = DRBG_ERROR;
411 RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_GENERATE_ERROR);
415 drbg->reseed_counter++;
421 * Set the RAND_DRBG callbacks for obtaining entropy and nonce.
423 * In the following, the signature and the semantics of the
424 * get_entropy() and cleanup_entropy() callbacks are explained.
428 * size_t get_entropy(RAND_DRBG *ctx,
429 * unsigned char **pout,
431 * size_t min_len, size_t max_len);
433 * This is a request to allocate and fill a buffer of size
434 * |min_len| <= size <= |max_len| (in bytes) which contains
435 * at least |entropy| bits of randomness. The buffer's address is
436 * to be returned in |*pout| and the number of collected
437 * randomness bytes (which may be less than the allocated size
438 * of the buffer) as return value.
440 * If the callback fails to acquire at least |entropy| bits of
441 * randomness, it shall return a buffer length of 0.
445 * void cleanup_entropy(RAND_DRBG *ctx,
446 * unsigned char *out, size_t outlen);
448 * A request to clear and free the buffer allocated by get_entropy().
449 * The values |out| and |outlen| are expected to be the random buffer's
450 * address and length, as returned by the get_entropy() callback.
452 * GET_NONCE, CLEANUP_NONCE
454 * Signature and semantics of the get_nonce() and cleanup_nonce()
455 * callbacks are analogous to get_entropy() and cleanup_entropy().
456 * Currently, the nonce is used only for the known answer tests.
458 int RAND_DRBG_set_callbacks(RAND_DRBG *drbg,
459 RAND_DRBG_get_entropy_fn get_entropy,
460 RAND_DRBG_cleanup_entropy_fn cleanup_entropy,
461 RAND_DRBG_get_nonce_fn get_nonce,
462 RAND_DRBG_cleanup_nonce_fn cleanup_nonce)
464 if (drbg->state != DRBG_UNINITIALISED)
466 drbg->get_entropy = get_entropy;
467 drbg->cleanup_entropy = cleanup_entropy;
468 drbg->get_nonce = get_nonce;
469 drbg->cleanup_nonce = cleanup_nonce;
474 * Set the reseed interval.
476 int RAND_DRBG_set_reseed_interval(RAND_DRBG *drbg, int interval)
478 if (interval < 0 || interval > MAX_RESEED)
480 drbg->reseed_interval = interval;
485 * Get and set the EXDATA
487 int RAND_DRBG_set_ex_data(RAND_DRBG *drbg, int idx, void *arg)
489 return CRYPTO_set_ex_data(&drbg->ex_data, idx, arg);
492 void *RAND_DRBG_get_ex_data(const RAND_DRBG *drbg, int idx)
494 return CRYPTO_get_ex_data(&drbg->ex_data, idx);
499 * The following functions provide a RAND_METHOD that works on the
500 * global DRBG. They lock.
504 * Initializes the DRBG with default settings.
505 * For global DRBGs a global lock is created with the given name
506 * Returns 1 on success, 0 on failure
508 static int drbg_setup(RAND_DRBG *drbg, const char *name)
513 if (drbg->lock != NULL) {
514 RANDerr(RAND_F_DRBG_SETUP, ERR_R_INTERNAL_ERROR);
518 drbg->lock = CRYPTO_THREAD_glock_new(name);
519 if (drbg->lock == NULL) {
520 RANDerr(RAND_F_DRBG_SETUP, RAND_R_FAILED_TO_CREATE_LOCK);
525 ret &= RAND_DRBG_set(drbg,
526 RAND_DRBG_NID, RAND_DRBG_FLAG_CTR_USE_DF) == 1;
527 ret &= RAND_DRBG_set_callbacks(drbg, rand_drbg_get_entropy,
528 rand_drbg_cleanup_entropy, NULL, NULL) == 1;
530 * Ignore instantiation error so support just-in-time instantiation.
532 * The state of the drbg will be checked in RAND_DRBG_generate() and
533 * an automatic recovery is attempted.
535 RAND_DRBG_instantiate(drbg,
536 (const unsigned char *) ossl_pers_string,
537 sizeof(ossl_pers_string) - 1);
542 * Initialize the global DRBGs on first use.
543 * Returns 1 on success, 0 on failure.
545 DEFINE_RUN_ONCE_STATIC(do_rand_drbg_init)
549 ret &= drbg_setup(&rand_drbg, "rand_drbg");
550 ret &= drbg_setup(&priv_drbg, "priv_drbg");
555 /* Cleans up the given global DRBG */
556 static void drbg_cleanup(RAND_DRBG *drbg)
558 CRYPTO_THREAD_lock_free(drbg->lock);
559 RAND_DRBG_uninstantiate(drbg);
562 /* Clean up the global DRBGs before exit */
563 void rand_drbg_cleanup_int(void)
565 drbg_cleanup(&rand_drbg);
566 drbg_cleanup(&priv_drbg);
569 /* Implements the default OpenSSL RAND_bytes() method */
570 static int drbg_bytes(unsigned char *out, int count)
574 RAND_DRBG *drbg = RAND_DRBG_get0_global();
579 CRYPTO_THREAD_write_lock(drbg->lock);
580 if (drbg->state == DRBG_UNINITIALISED)
583 for ( ; count > 0; count -= chunk, out += chunk) {
585 if (chunk > drbg->max_request)
586 chunk = drbg->max_request;
587 ret = RAND_DRBG_generate(drbg, out, chunk, 0, NULL, 0);
594 CRYPTO_THREAD_unlock(drbg->lock);
598 /* Implements the default OpenSSL RAND_add() method */
599 static int drbg_add(const void *buf, int num, double randomness)
602 RAND_DRBG *drbg = RAND_DRBG_get0_global();
607 if (num < 0 || randomness < 0.0)
610 if (randomness > (double)drbg->max_entropylen) {
612 * The purpose of this check is to bound |randomness| by a
613 * relatively small value in order to prevent an integer
614 * overflow when multiplying by 8 in the rand_drbg_restart()
620 CRYPTO_THREAD_write_lock(drbg->lock);
621 ret = rand_drbg_restart(drbg, buf,
622 (size_t)(unsigned int)num,
623 (size_t)(8*randomness));
624 CRYPTO_THREAD_unlock(drbg->lock);
629 /* Implements the default OpenSSL RAND_seed() method */
630 static int drbg_seed(const void *buf, int num)
632 return drbg_add(buf, num, num);
635 /* Implements the default OpenSSL RAND_status() method */
636 static int drbg_status(void)
639 RAND_DRBG *drbg = RAND_DRBG_get0_global();
644 CRYPTO_THREAD_write_lock(drbg->lock);
645 ret = drbg->state == DRBG_READY ? 1 : 0;
646 CRYPTO_THREAD_unlock(drbg->lock);
651 * Get the global public DRBG.
652 * Returns pointer to the DRBG on success, NULL on failure.
654 RAND_DRBG *RAND_DRBG_get0_global(void)
656 if (!RUN_ONCE(&rand_drbg_init, do_rand_drbg_init))
663 * Get the global private DRBG.
664 * Returns pointer to the DRBG on success, NULL on failure.
666 RAND_DRBG *RAND_DRBG_get0_priv_global(void)
668 if (!RUN_ONCE(&rand_drbg_init, do_rand_drbg_init))
674 RAND_METHOD rand_meth = {
683 RAND_METHOD *RAND_OpenSSL(void)