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