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