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