c0c0b91cfd72a25b4b6c2259c1bdbe2bc53c08c8
[openssl.git] / crypto / rand / drbg_lib.c
1 /*
2  * Copyright 2011-2018 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_lcl.h"
15 #include "internal/thread_once.h"
16 #include "internal/rand_int.h"
17
18 /*
19  * Support framework for NIST SP 800-90A DRBG, AES-CTR mode.
20  * The RAND_DRBG is OpenSSL's pointer to an instance of the DRBG.
21  *
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.)
28  */
29
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  */
42 static RAND_DRBG *drbg_master;
43 /*
44  * THE PUBLIC DRBG
45  *
46  * Used by default for generating random bytes using RAND_bytes().
47  */
48 static RAND_DRBG *drbg_public;
49 /*
50  * THE PRIVATE DRBG
51  *
52  * Used by default for generating private keys using RAND_priv_bytes()
53  */
54 static RAND_DRBG *drbg_private;
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  *
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.
85  *
86  * MANUAL RESEEDING
87  *
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
90  * |randomness| argument). This will immediately reseed the <master> DRBG.
91  * The <public> and <private> DRBG will detect this on their next generate
92  * call and reseed, pulling randomness from <master>.
93  */
94
95
96 /* NIST SP 800-90A DRBG recommends the use of a personalization string. */
97 static const char ossl_pers_string[] = "OpenSSL NIST SP 800-90A DRBG";
98
99 static CRYPTO_ONCE rand_drbg_init = CRYPTO_ONCE_STATIC_INIT;
100
101 static RAND_DRBG *drbg_setup(RAND_DRBG *parent);
102 static void drbg_cleanup(RAND_DRBG *drbg);
103
104 /*
105  * Set/initialize |drbg| to be of type |nid|, with optional |flags|.
106  *
107  * Returns 1 on success, 0 on failure.
108  */
109 int RAND_DRBG_set(RAND_DRBG *drbg, int nid, unsigned int flags)
110 {
111     int ret = 1;
112
113     drbg->state = DRBG_UNINITIALISED;
114     drbg->flags = flags;
115     drbg->nid = nid;
116
117     switch (nid) {
118     default:
119         RANDerr(RAND_F_RAND_DRBG_SET, RAND_R_UNSUPPORTED_DRBG_TYPE);
120         return 0;
121     case 0:
122         /* Uninitialized; that's okay. */
123         return 1;
124     case NID_aes_128_ctr:
125     case NID_aes_192_ctr:
126     case NID_aes_256_ctr:
127         ret = drbg_ctr_init(drbg);
128         break;
129     }
130
131     if (ret == 0)
132         RANDerr(RAND_F_RAND_DRBG_SET, RAND_R_ERROR_INITIALISING_DRBG);
133     return ret;
134 }
135
136 /*
137  * Allocate memory and initialize a new DRBG.  The |parent|, if not
138  * NULL, will be used to auto-seed this RAND_DRBG as needed.
139  *
140  * Returns a pointer to the new DRBG instance on success, NULL on failure.
141  */
142 RAND_DRBG *RAND_DRBG_new(int type, unsigned int flags, RAND_DRBG *parent)
143 {
144     RAND_DRBG *drbg = OPENSSL_zalloc(sizeof(*drbg));
145
146     if (drbg == NULL) {
147         RANDerr(RAND_F_RAND_DRBG_NEW, ERR_R_MALLOC_FAILURE);
148         goto err;
149     }
150     drbg->fork_count = rand_fork_count;
151     drbg->parent = parent;
152     if (RAND_DRBG_set(drbg, type, flags) == 0)
153         goto err;
154
155     if (!RAND_DRBG_set_callbacks(drbg, rand_drbg_get_entropy,
156                                  rand_drbg_cleanup_entropy,
157                                  NULL, NULL))
158         goto err;
159
160     return drbg;
161
162 err:
163     OPENSSL_free(drbg);
164     return NULL;
165 }
166
167 /*
168  * Uninstantiate |drbg| and free all memory.
169  */
170 void RAND_DRBG_free(RAND_DRBG *drbg)
171 {
172     if (drbg == NULL)
173         return;
174
175     if (drbg->meth != NULL)
176         drbg->meth->uninstantiate(drbg);
177     CRYPTO_free_ex_data(CRYPTO_EX_INDEX_DRBG, drbg, &drbg->ex_data);
178     OPENSSL_clear_free(drbg, sizeof(*drbg));
179 }
180
181 /*
182  * Instantiate |drbg|, after it has been initialized.  Use |pers| and
183  * |perslen| as prediction-resistance input.
184  *
185  * Requires that drbg->lock is already locked for write, if non-null.
186  *
187  * Returns 1 on success, 0 on failure.
188  */
189 int RAND_DRBG_instantiate(RAND_DRBG *drbg,
190                           const unsigned char *pers, size_t perslen)
191 {
192     unsigned char *nonce = NULL, *entropy = NULL;
193     size_t noncelen = 0, entropylen = 0;
194
195     if (perslen > drbg->max_perslen) {
196         RANDerr(RAND_F_RAND_DRBG_INSTANTIATE,
197                 RAND_R_PERSONALISATION_STRING_TOO_LONG);
198         goto end;
199     }
200
201     if (drbg->meth == NULL)
202     {
203         RANDerr(RAND_F_RAND_DRBG_INSTANTIATE,
204                 RAND_R_NO_DRBG_IMPLEMENTATION_SELECTED);
205         goto end;
206     }
207
208     if (drbg->state != DRBG_UNINITIALISED) {
209         RANDerr(RAND_F_RAND_DRBG_INSTANTIATE,
210                 drbg->state == DRBG_ERROR ? RAND_R_IN_ERROR_STATE
211                                           : RAND_R_ALREADY_INSTANTIATED);
212         goto end;
213     }
214
215     drbg->state = DRBG_ERROR;
216     if (drbg->get_entropy != NULL)
217         entropylen = drbg->get_entropy(drbg, &entropy, drbg->strength,
218                                    drbg->min_entropylen, drbg->max_entropylen);
219     if (entropylen < drbg->min_entropylen
220         || entropylen > drbg->max_entropylen) {
221         RANDerr(RAND_F_RAND_DRBG_INSTANTIATE, RAND_R_ERROR_RETRIEVING_ENTROPY);
222         goto end;
223     }
224
225     if (drbg->max_noncelen > 0 && drbg->get_nonce != NULL) {
226         noncelen = drbg->get_nonce(drbg, &nonce, drbg->strength / 2,
227                                    drbg->min_noncelen, drbg->max_noncelen);
228         if (noncelen < drbg->min_noncelen || noncelen > drbg->max_noncelen) {
229             RANDerr(RAND_F_RAND_DRBG_INSTANTIATE,
230                     RAND_R_ERROR_RETRIEVING_NONCE);
231             goto end;
232         }
233     }
234
235     if (!drbg->meth->instantiate(drbg, entropy, entropylen,
236                          nonce, noncelen, pers, perslen)) {
237         RANDerr(RAND_F_RAND_DRBG_INSTANTIATE, RAND_R_ERROR_INSTANTIATING_DRBG);
238         goto end;
239     }
240
241     drbg->state = DRBG_READY;
242     drbg->generate_counter = 0;
243     drbg->reseed_time = time(NULL);
244     if (drbg->reseed_counter > 0) {
245         if (drbg->parent == NULL)
246             drbg->reseed_counter++;
247         else
248             drbg->reseed_counter = drbg->parent->reseed_counter;
249     }
250
251 end:
252     if (entropy != NULL && drbg->cleanup_entropy != NULL)
253         drbg->cleanup_entropy(drbg, entropy, entropylen);
254     if (nonce != NULL && drbg->cleanup_nonce!= NULL )
255         drbg->cleanup_nonce(drbg, nonce, noncelen);
256     if (drbg->pool != NULL) {
257         if (drbg->state == DRBG_READY) {
258             RANDerr(RAND_F_RAND_DRBG_INSTANTIATE,
259                     RAND_R_ERROR_ENTROPY_POOL_WAS_IGNORED);
260             drbg->state = DRBG_ERROR;
261         }
262         RAND_POOL_free(drbg->pool);
263         drbg->pool = NULL;
264     }
265     if (drbg->state == DRBG_READY)
266         return 1;
267     return 0;
268 }
269
270 /*
271  * Uninstantiate |drbg|. Must be instantiated before it can be used.
272  *
273  * Requires that drbg->lock is already locked for write, if non-null.
274  *
275  * Returns 1 on success, 0 on failure.
276  */
277 int RAND_DRBG_uninstantiate(RAND_DRBG *drbg)
278 {
279     if (drbg->meth == NULL)
280     {
281         RANDerr(RAND_F_RAND_DRBG_UNINSTANTIATE,
282                 RAND_R_NO_DRBG_IMPLEMENTATION_SELECTED);
283         return 0;
284     }
285
286     /* Clear the entire drbg->ctr struct, then reset some important
287      * members of the drbg->ctr struct (e.g. keysize, df_ks) to their
288      * initial values.
289      */
290     drbg->meth->uninstantiate(drbg);
291     return RAND_DRBG_set(drbg, drbg->nid, drbg->flags);
292 }
293
294 /*
295  * Reseed |drbg|, mixing in the specified data
296  *
297  * Requires that drbg->lock is already locked for write, if non-null.
298  *
299  * Returns 1 on success, 0 on failure.
300  */
301 int RAND_DRBG_reseed(RAND_DRBG *drbg,
302                      const unsigned char *adin, size_t adinlen)
303 {
304     unsigned char *entropy = NULL;
305     size_t entropylen = 0;
306
307     if (drbg->state == DRBG_ERROR) {
308         RANDerr(RAND_F_RAND_DRBG_RESEED, RAND_R_IN_ERROR_STATE);
309         return 0;
310     }
311     if (drbg->state == DRBG_UNINITIALISED) {
312         RANDerr(RAND_F_RAND_DRBG_RESEED, RAND_R_NOT_INSTANTIATED);
313         return 0;
314     }
315
316     if (adin == NULL)
317         adinlen = 0;
318     else if (adinlen > drbg->max_adinlen) {
319         RANDerr(RAND_F_RAND_DRBG_RESEED, RAND_R_ADDITIONAL_INPUT_TOO_LONG);
320         return 0;
321     }
322
323     drbg->state = DRBG_ERROR;
324     if (drbg->get_entropy != NULL)
325         entropylen = drbg->get_entropy(drbg, &entropy, drbg->strength,
326                                    drbg->min_entropylen, drbg->max_entropylen);
327     if (entropylen < drbg->min_entropylen
328         || entropylen > drbg->max_entropylen) {
329         RANDerr(RAND_F_RAND_DRBG_RESEED, RAND_R_ERROR_RETRIEVING_ENTROPY);
330         goto end;
331     }
332
333     if (!drbg->meth->reseed(drbg, entropy, entropylen, adin, adinlen))
334         goto end;
335
336     drbg->state = DRBG_READY;
337     drbg->generate_counter = 0;
338     drbg->reseed_time = time(NULL);
339     if (drbg->reseed_counter > 0) {
340         if (drbg->parent == NULL)
341             drbg->reseed_counter++;
342         else
343             drbg->reseed_counter = drbg->parent->reseed_counter;
344     }
345
346 end:
347     if (entropy != NULL && drbg->cleanup_entropy != NULL)
348         drbg->cleanup_entropy(drbg, entropy, entropylen);
349     if (drbg->state == DRBG_READY)
350         return 1;
351     return 0;
352 }
353
354 /*
355  * Restart |drbg|, using the specified entropy or additional input
356  *
357  * Tries its best to get the drbg instantiated by all means,
358  * regardless of its current state.
359  *
360  * Optionally, a |buffer| of |len| random bytes can be passed,
361  * which is assumed to contain at least |entropy| bits of entropy.
362  *
363  * If |entropy| > 0, the buffer content is used as entropy input.
364  *
365  * If |entropy| == 0, the buffer content is used as additional input
366  *
367  * Returns 1 on success, 0 on failure.
368  *
369  * This function is used internally only.
370  */
371 int rand_drbg_restart(RAND_DRBG *drbg,
372                       const unsigned char *buffer, size_t len, size_t entropy)
373 {
374     int reseeded = 0;
375     const unsigned char *adin = NULL;
376     size_t adinlen = 0;
377
378     if (drbg->pool != NULL) {
379         RANDerr(RAND_F_RAND_DRBG_RESTART, ERR_R_INTERNAL_ERROR);
380         RAND_POOL_free(drbg->pool);
381         drbg->pool = NULL;
382     }
383
384     if (buffer != NULL) {
385         if (entropy > 0) {
386             if (drbg->max_entropylen < len) {
387                 RANDerr(RAND_F_RAND_DRBG_RESTART,
388                     RAND_R_ENTROPY_INPUT_TOO_LONG);
389                 return 0;
390             }
391
392             if (entropy > 8 * len) {
393                 RANDerr(RAND_F_RAND_DRBG_RESTART, RAND_R_ENTROPY_OUT_OF_RANGE);
394                 return 0;
395             }
396
397             /* will be picked up by the rand_drbg_get_entropy() callback */
398             drbg->pool = RAND_POOL_new(entropy, len, len);
399             if (drbg->pool == NULL)
400                 return 0;
401
402             RAND_POOL_add(drbg->pool, buffer, len, entropy);
403         } else {
404             if (drbg->max_adinlen < len) {
405                 RANDerr(RAND_F_RAND_DRBG_RESTART,
406                         RAND_R_ADDITIONAL_INPUT_TOO_LONG);
407                 return 0;
408             }
409             adin = buffer;
410             adinlen = len;
411         }
412     }
413
414     /* repair error state */
415     if (drbg->state == DRBG_ERROR)
416         RAND_DRBG_uninstantiate(drbg);
417
418     /* repair uninitialized state */
419     if (drbg->state == DRBG_UNINITIALISED) {
420         /* reinstantiate drbg */
421         RAND_DRBG_instantiate(drbg,
422                               (const unsigned char *) ossl_pers_string,
423                               sizeof(ossl_pers_string) - 1);
424         /* already reseeded. prevent second reseeding below */
425         reseeded = (drbg->state == DRBG_READY);
426     }
427
428     /* refresh current state if entropy or additional input has been provided */
429     if (drbg->state == DRBG_READY) {
430         if (adin != NULL) {
431             /*
432              * mix in additional input without reseeding
433              *
434              * Similar to RAND_DRBG_reseed(), but the provided additional
435              * data |adin| is mixed into the current state without pulling
436              * entropy from the trusted entropy source using get_entropy().
437              * This is not a reseeding in the strict sense of NIST SP 800-90A.
438              */
439             drbg->meth->reseed(drbg, adin, adinlen, NULL, 0);
440         } else if (reseeded == 0) {
441             /* do a full reseeding if it has not been done yet above */
442             RAND_DRBG_reseed(drbg, NULL, 0);
443         }
444     }
445
446     /* check whether a given entropy pool was cleared properly during reseed */
447     if (drbg->pool != NULL) {
448         drbg->state = DRBG_ERROR;
449         RANDerr(RAND_F_RAND_DRBG_RESTART, ERR_R_INTERNAL_ERROR);
450         RAND_POOL_free(drbg->pool);
451         drbg->pool = NULL;
452         return 0;
453     }
454
455     return drbg->state == DRBG_READY;
456 }
457
458 /*
459  * Generate |outlen| bytes into the buffer at |out|.  Reseed if we need
460  * to or if |prediction_resistance| is set.  Additional input can be
461  * sent in |adin| and |adinlen|.
462  *
463  * Requires that drbg->lock is already locked for write, if non-null.
464  *
465  * Returns 1 on success, 0 on failure.
466  *
467  */
468 int RAND_DRBG_generate(RAND_DRBG *drbg, unsigned char *out, size_t outlen,
469                        int prediction_resistance,
470                        const unsigned char *adin, size_t adinlen)
471 {
472     int reseed_required = 0;
473
474     if (drbg->state != DRBG_READY) {
475         /* try to recover from previous errors */
476         rand_drbg_restart(drbg, NULL, 0, 0);
477
478         if (drbg->state == DRBG_ERROR) {
479             RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_IN_ERROR_STATE);
480             return 0;
481         }
482         if (drbg->state == DRBG_UNINITIALISED) {
483             RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_NOT_INSTANTIATED);
484             return 0;
485         }
486     }
487
488     if (outlen > drbg->max_request) {
489         RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_REQUEST_TOO_LARGE_FOR_DRBG);
490         return 0;
491     }
492     if (adinlen > drbg->max_adinlen) {
493         RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_ADDITIONAL_INPUT_TOO_LONG);
494         return 0;
495     }
496
497     if (drbg->fork_count != rand_fork_count) {
498         drbg->fork_count = rand_fork_count;
499         reseed_required = 1;
500     }
501
502     if (drbg->reseed_interval > 0) {
503         if (drbg->generate_counter >= drbg->reseed_interval)
504             reseed_required = 1;
505     }
506     if (drbg->reseed_time_interval > 0) {
507         time_t now = time(NULL);
508         if (now < drbg->reseed_time
509             || now - drbg->reseed_time >= drbg->reseed_time_interval)
510             reseed_required = 1;
511     }
512     if (drbg->reseed_counter > 0 && drbg->parent != NULL) {
513         if (drbg->reseed_counter != drbg->parent->reseed_counter)
514             reseed_required = 1;
515     }
516
517     if (reseed_required || prediction_resistance) {
518         if (!RAND_DRBG_reseed(drbg, adin, adinlen)) {
519             RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_RESEED_ERROR);
520             return 0;
521         }
522         adin = NULL;
523         adinlen = 0;
524     }
525
526     if (!drbg->meth->generate(drbg, out, outlen, adin, adinlen)) {
527         drbg->state = DRBG_ERROR;
528         RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_GENERATE_ERROR);
529         return 0;
530     }
531
532     drbg->generate_counter++;
533
534     return 1;
535 }
536
537 /*
538  * Generates |outlen| random bytes and stores them in |out|. It will
539  * using the given |drbg| to generate the bytes.
540  *
541  * Requires that drbg->lock is already locked for write, if non-null.
542  *
543  * Returns 1 on success 0 on failure.
544  */
545 int RAND_DRBG_bytes(RAND_DRBG *drbg, unsigned char *out, size_t outlen)
546 {
547     unsigned char *additional = NULL;
548     size_t additional_len;
549     size_t chunk;
550     size_t ret;
551
552     additional_len = rand_drbg_get_additional_data(&additional, drbg->max_adinlen);
553
554     for ( ; outlen > 0; outlen -= chunk, out += chunk) {
555         chunk = outlen;
556         if (chunk > drbg->max_request)
557             chunk = drbg->max_request;
558         ret = RAND_DRBG_generate(drbg, out, chunk, 0, additional, additional_len);
559         if (!ret)
560             goto err;
561     }
562     ret = 1;
563
564 err:
565     if (additional_len != 0)
566         OPENSSL_secure_clear_free(additional, additional_len);
567
568     return ret;
569 }
570
571 /*
572  * Set the RAND_DRBG callbacks for obtaining entropy and nonce.
573  *
574  * In the following, the signature and the semantics of the
575  * get_entropy() and cleanup_entropy() callbacks are explained.
576  *
577  * GET_ENTROPY
578  *
579  *     size_t get_entropy(RAND_DRBG *ctx,
580  *                        unsigned char **pout,
581  *                        int entropy,
582  *                        size_t min_len, size_t max_len);
583  *
584  * This is a request to allocate and fill a buffer of size
585  * |min_len| <= size <= |max_len| (in bytes) which contains
586  * at least |entropy| bits of randomness. The buffer's address is
587  * to be returned in |*pout| and the number of collected
588  * randomness bytes (which may be less than the allocated size
589  * of the buffer) as return value.
590  *
591  * If the callback fails to acquire at least |entropy| bits of
592  * randomness, it shall return a buffer length of 0.
593  *
594  * CLEANUP_ENTROPY
595  *
596  *     void cleanup_entropy(RAND_DRBG *ctx,
597  *                          unsigned char *out, size_t outlen);
598  *
599  * A request to clear and free the buffer allocated by get_entropy().
600  * The values |out| and |outlen| are expected to be the random buffer's
601  * address and length, as returned by the get_entropy() callback.
602  *
603  * GET_NONCE, CLEANUP_NONCE
604  *
605  * Signature and semantics of the get_nonce() and cleanup_nonce()
606  * callbacks are analogous to get_entropy() and cleanup_entropy().
607  * Currently, the nonce is used only for the known answer tests.
608  */
609 int RAND_DRBG_set_callbacks(RAND_DRBG *drbg,
610                             RAND_DRBG_get_entropy_fn get_entropy,
611                             RAND_DRBG_cleanup_entropy_fn cleanup_entropy,
612                             RAND_DRBG_get_nonce_fn get_nonce,
613                             RAND_DRBG_cleanup_nonce_fn cleanup_nonce)
614 {
615     if (drbg->state != DRBG_UNINITIALISED)
616         return 0;
617     drbg->get_entropy = get_entropy;
618     drbg->cleanup_entropy = cleanup_entropy;
619     drbg->get_nonce = get_nonce;
620     drbg->cleanup_nonce = cleanup_nonce;
621     return 1;
622 }
623
624 /*
625  * Set the reseed interval.
626  *
627  * The drbg will reseed automatically whenever the number of generate
628  * requests exceeds the given reseed interval. If the reseed interval
629  * is 0, then this feature is disabled.
630  *
631  * Returns 1 on success, 0 on failure.
632  */
633 int RAND_DRBG_set_reseed_interval(RAND_DRBG *drbg, unsigned int interval)
634 {
635     if (interval > MAX_RESEED_INTERVAL)
636         return 0;
637     drbg->reseed_interval = interval;
638     return 1;
639 }
640
641 /*
642  * Set the reseed time interval.
643  *
644  * The drbg will reseed automatically whenever the time elapsed since
645  * the last reseeding exceeds the given reseed time interval. For safety,
646  * a reseeding will also occur if the clock has been reset to a smaller
647  * value.
648  *
649  * Returns 1 on success, 0 on failure.
650  */
651 int RAND_DRBG_set_reseed_time_interval(RAND_DRBG *drbg, time_t interval)
652 {
653     if (interval > MAX_RESEED_TIME_INTERVAL)
654         return 0;
655     drbg->reseed_time_interval = interval;
656     return 1;
657 }
658
659 /*
660  * Get and set the EXDATA
661  */
662 int RAND_DRBG_set_ex_data(RAND_DRBG *drbg, int idx, void *arg)
663 {
664     return CRYPTO_set_ex_data(&drbg->ex_data, idx, arg);
665 }
666
667 void *RAND_DRBG_get_ex_data(const RAND_DRBG *drbg, int idx)
668 {
669     return CRYPTO_get_ex_data(&drbg->ex_data, idx);
670 }
671
672
673 /*
674  * The following functions provide a RAND_METHOD that works on the
675  * global DRBG.  They lock.
676  */
677
678 /*
679  * Allocates a new global DRBG on the secure heap (if enabled) and
680  * initializes it with default settings.
681  *
682  * Returns a pointer to the new DRBG instance on success, NULL on failure.
683  */
684 static RAND_DRBG *drbg_setup(RAND_DRBG *parent)
685 {
686     RAND_DRBG *drbg;
687
688     drbg = OPENSSL_secure_zalloc(sizeof(RAND_DRBG));
689     if (drbg == NULL)
690         return NULL;
691
692     drbg->lock = CRYPTO_THREAD_lock_new();
693     if (drbg->lock == NULL) {
694         RANDerr(RAND_F_DRBG_SETUP, RAND_R_FAILED_TO_CREATE_LOCK);
695         goto err;
696     }
697
698     if (RAND_DRBG_set(drbg,
699                       RAND_DRBG_NID, RAND_DRBG_FLAG_CTR_USE_DF) != 1)
700         goto err;
701     if (RAND_DRBG_set_callbacks(drbg, rand_drbg_get_entropy,
702                                 rand_drbg_cleanup_entropy, NULL, NULL) != 1)
703         goto err;
704
705     if (parent == NULL) {
706         drbg->reseed_interval = MASTER_RESEED_INTERVAL;
707         drbg->reseed_time_interval = MASTER_RESEED_TIME_INTERVAL;
708     } else {
709         drbg->parent = parent;
710         drbg->reseed_interval = SLAVE_RESEED_INTERVAL;
711         drbg->reseed_time_interval = SLAVE_RESEED_TIME_INTERVAL;
712     }
713
714     /* enable seed propagation */
715     drbg->reseed_counter = 1;
716
717     /*
718      * Ignore instantiation error so support just-in-time instantiation.
719      *
720      * The state of the drbg will be checked in RAND_DRBG_generate() and
721      * an automatic recovery is attempted.
722      */
723     RAND_DRBG_instantiate(drbg,
724                           (const unsigned char *) ossl_pers_string,
725                           sizeof(ossl_pers_string) - 1);
726     return drbg;
727
728 err:
729     drbg_cleanup(drbg);
730     return NULL;
731 }
732
733 /*
734  * Initialize the global DRBGs on first use.
735  * Returns 1 on success, 0 on failure.
736  */
737 DEFINE_RUN_ONCE_STATIC(do_rand_drbg_init)
738 {
739     /*
740      * ensure that libcrypto is initialized, otherwise the
741      * DRBG locks are not cleaned up properly
742      */
743     if (!OPENSSL_init_crypto(0, NULL))
744         return 0;
745
746     drbg_master = drbg_setup(NULL);
747     drbg_public = drbg_setup(drbg_master);
748     drbg_private = drbg_setup(drbg_master);
749
750     if (drbg_master == NULL || drbg_public == NULL || drbg_private == NULL)
751         return 0;
752
753     return 1;
754 }
755
756 /* Cleans up the given global DRBG  */
757 static void drbg_cleanup(RAND_DRBG *drbg)
758 {
759     if (drbg != NULL) {
760         RAND_DRBG_uninstantiate(drbg);
761         CRYPTO_THREAD_lock_free(drbg->lock);
762         OPENSSL_secure_clear_free(drbg, sizeof(RAND_DRBG));
763     }
764 }
765
766 /* Clean up the global DRBGs before exit */
767 void rand_drbg_cleanup_int(void)
768 {
769     drbg_cleanup(drbg_private);
770     drbg_cleanup(drbg_public);
771     drbg_cleanup(drbg_master);
772
773     drbg_private = drbg_public = drbg_master = NULL;
774 }
775
776 /* Implements the default OpenSSL RAND_bytes() method */
777 static int drbg_bytes(unsigned char *out, int count)
778 {
779     int ret = 0;
780     size_t chunk;
781     RAND_DRBG *drbg = RAND_DRBG_get0_public();
782
783     if (drbg == NULL)
784         return 0;
785
786     CRYPTO_THREAD_write_lock(drbg->lock);
787     for ( ; count > 0; count -= chunk, out += chunk) {
788         chunk = count;
789         if (chunk > drbg->max_request)
790             chunk = drbg->max_request;
791         ret = RAND_DRBG_generate(drbg, out, chunk, 0, NULL, 0);
792         if (!ret)
793             goto err;
794     }
795     ret = 1;
796
797 err:
798     CRYPTO_THREAD_unlock(drbg->lock);
799     return ret;
800 }
801
802 /* Implements the default OpenSSL RAND_add() method */
803 static int drbg_add(const void *buf, int num, double randomness)
804 {
805     int ret = 0;
806     RAND_DRBG *drbg = RAND_DRBG_get0_master();
807
808     if (drbg == NULL)
809         return 0;
810
811     if (num < 0 || randomness < 0.0)
812         return 0;
813
814     if (randomness > (double)drbg->max_entropylen) {
815         /*
816          * The purpose of this check is to bound |randomness| by a
817          * relatively small value in order to prevent an integer
818          * overflow when multiplying by 8 in the rand_drbg_restart()
819          * call below.
820          */
821         return 0;
822     }
823
824     CRYPTO_THREAD_write_lock(drbg->lock);
825     ret = rand_drbg_restart(drbg, buf,
826                             (size_t)(unsigned int)num,
827                             (size_t)(8*randomness));
828     CRYPTO_THREAD_unlock(drbg->lock);
829
830     return ret;
831 }
832
833 /* Implements the default OpenSSL RAND_seed() method */
834 static int drbg_seed(const void *buf, int num)
835 {
836     return drbg_add(buf, num, num);
837 }
838
839 /* Implements the default OpenSSL RAND_status() method */
840 static int drbg_status(void)
841 {
842     int ret;
843     RAND_DRBG *drbg = RAND_DRBG_get0_master();
844
845     if (drbg == NULL)
846         return 0;
847
848     CRYPTO_THREAD_write_lock(drbg->lock);
849     ret = drbg->state == DRBG_READY ? 1 : 0;
850     CRYPTO_THREAD_unlock(drbg->lock);
851     return ret;
852 }
853
854 /*
855  * Get the master DRBG.
856  * Returns pointer to the DRBG on success, NULL on failure.
857  *
858  */
859 RAND_DRBG *RAND_DRBG_get0_master(void)
860 {
861     if (!RUN_ONCE(&rand_drbg_init, do_rand_drbg_init))
862         return NULL;
863
864     return drbg_master;
865 }
866
867 /*
868  * Get the public DRBG.
869  * Returns pointer to the DRBG on success, NULL on failure.
870  */
871 RAND_DRBG *RAND_DRBG_get0_public(void)
872 {
873     if (!RUN_ONCE(&rand_drbg_init, do_rand_drbg_init))
874         return NULL;
875
876     return drbg_public;
877 }
878
879 /*
880  * Get the private DRBG.
881  * Returns pointer to the DRBG on success, NULL on failure.
882  */
883 RAND_DRBG *RAND_DRBG_get0_private(void)
884 {
885     if (!RUN_ONCE(&rand_drbg_init, do_rand_drbg_init))
886         return NULL;
887
888     return drbg_private;
889 }
890
891 RAND_METHOD rand_meth = {
892     drbg_seed,
893     drbg_bytes,
894     NULL,
895     drbg_add,
896     drbg_bytes,
897     drbg_status
898 };
899
900 RAND_METHOD *RAND_OpenSSL(void)
901 {
902     return &rand_meth;
903 }