ff7f6546d7944040203bfd37dfd001617518947a
[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(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  *
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  * Set the RAND_DRBG callbacks for obtaining entropy and nonce.
539  *
540  * In the following, the signature and the semantics of the
541  * get_entropy() and cleanup_entropy() callbacks are explained.
542  *
543  * GET_ENTROPY
544  *
545  *     size_t get_entropy(RAND_DRBG *ctx,
546  *                        unsigned char **pout,
547  *                        int entropy,
548  *                        size_t min_len, size_t max_len);
549  *
550  * This is a request to allocate and fill a buffer of size
551  * |min_len| <= size <= |max_len| (in bytes) which contains
552  * at least |entropy| bits of randomness. The buffer's address is
553  * to be returned in |*pout| and the number of collected
554  * randomness bytes (which may be less than the allocated size
555  * of the buffer) as return value.
556  *
557  * If the callback fails to acquire at least |entropy| bits of
558  * randomness, it shall return a buffer length of 0.
559  *
560  * CLEANUP_ENTROPY
561  *
562  *     void cleanup_entropy(RAND_DRBG *ctx,
563  *                          unsigned char *out, size_t outlen);
564  *
565  * A request to clear and free the buffer allocated by get_entropy().
566  * The values |out| and |outlen| are expected to be the random buffer's
567  * address and length, as returned by the get_entropy() callback.
568  *
569  * GET_NONCE, CLEANUP_NONCE
570  *
571  * Signature and semantics of the get_nonce() and cleanup_nonce()
572  * callbacks are analogous to get_entropy() and cleanup_entropy().
573  * Currently, the nonce is used only for the known answer tests.
574  */
575 int RAND_DRBG_set_callbacks(RAND_DRBG *drbg,
576                             RAND_DRBG_get_entropy_fn get_entropy,
577                             RAND_DRBG_cleanup_entropy_fn cleanup_entropy,
578                             RAND_DRBG_get_nonce_fn get_nonce,
579                             RAND_DRBG_cleanup_nonce_fn cleanup_nonce)
580 {
581     if (drbg->state != DRBG_UNINITIALISED)
582         return 0;
583     drbg->get_entropy = get_entropy;
584     drbg->cleanup_entropy = cleanup_entropy;
585     drbg->get_nonce = get_nonce;
586     drbg->cleanup_nonce = cleanup_nonce;
587     return 1;
588 }
589
590 /*
591  * Set the reseed interval.
592  *
593  * The drbg will reseed automatically whenever the number of generate
594  * requests exceeds the given reseed interval. If the reseed interval
595  * is 0, then this feature is disabled.
596  *
597  * Returns 1 on success, 0 on failure.
598  */
599 int RAND_DRBG_set_reseed_interval(RAND_DRBG *drbg, unsigned int interval)
600 {
601     if (interval > MAX_RESEED_INTERVAL)
602         return 0;
603     drbg->reseed_interval = interval;
604     return 1;
605 }
606
607 /*
608  * Set the reseed time interval.
609  *
610  * The drbg will reseed automatically whenever the time elapsed since
611  * the last reseeding exceeds the given reseed time interval. For safety,
612  * a reseeding will also occur if the clock has been reset to a smaller
613  * value.
614  *
615  * Returns 1 on success, 0 on failure.
616  */
617 int RAND_DRBG_set_reseed_time_interval(RAND_DRBG *drbg, time_t interval)
618 {
619     if (interval > MAX_RESEED_TIME_INTERVAL)
620         return 0;
621     drbg->reseed_time_interval = interval;
622     return 1;
623 }
624
625 /*
626  * Get and set the EXDATA
627  */
628 int RAND_DRBG_set_ex_data(RAND_DRBG *drbg, int idx, void *arg)
629 {
630     return CRYPTO_set_ex_data(&drbg->ex_data, idx, arg);
631 }
632
633 void *RAND_DRBG_get_ex_data(const RAND_DRBG *drbg, int idx)
634 {
635     return CRYPTO_get_ex_data(&drbg->ex_data, idx);
636 }
637
638
639 /*
640  * The following functions provide a RAND_METHOD that works on the
641  * global DRBG.  They lock.
642  */
643
644 /*
645  * Allocates a new global DRBG on the secure heap (if enabled) and
646  * initializes it with default settings.
647  * A global lock for the DRBG is created with the given name.
648  *
649  * Returns a pointer to the new DRBG instance on success, NULL on failure.
650  */
651 static RAND_DRBG *drbg_setup(const char *name, RAND_DRBG *parent)
652 {
653     RAND_DRBG *drbg;
654
655     if (name == NULL) {
656         RANDerr(RAND_F_DRBG_SETUP, ERR_R_INTERNAL_ERROR);
657         return NULL;
658     }
659
660     drbg = OPENSSL_secure_zalloc(sizeof(RAND_DRBG));
661     if (drbg == NULL)
662         return NULL;
663
664     drbg->lock = CRYPTO_THREAD_glock_new(name);
665     if (drbg->lock == NULL) {
666         RANDerr(RAND_F_DRBG_SETUP, RAND_R_FAILED_TO_CREATE_LOCK);
667         goto err;
668     }
669
670     if (RAND_DRBG_set(drbg,
671                       RAND_DRBG_NID, RAND_DRBG_FLAG_CTR_USE_DF) != 1)
672         goto err;
673     if (RAND_DRBG_set_callbacks(drbg, rand_drbg_get_entropy,
674                                 rand_drbg_cleanup_entropy, NULL, NULL) != 1)
675         goto err;
676
677     if (parent == NULL) {
678         drbg->reseed_interval = MASTER_RESEED_INTERVAL;
679         drbg->reseed_time_interval = MASTER_RESEED_TIME_INTERVAL;
680     } else {
681         drbg->parent = parent;
682         drbg->reseed_interval = SLAVE_RESEED_INTERVAL;
683         drbg->reseed_time_interval = SLAVE_RESEED_TIME_INTERVAL;
684     }
685
686     /* enable seed propagation */
687     drbg->reseed_counter = 1;
688
689     /*
690      * Ignore instantiation error so support just-in-time instantiation.
691      *
692      * The state of the drbg will be checked in RAND_DRBG_generate() and
693      * an automatic recovery is attempted.
694      */
695     RAND_DRBG_instantiate(drbg,
696                           (const unsigned char *) ossl_pers_string,
697                           sizeof(ossl_pers_string) - 1);
698     return drbg;
699
700 err:
701     drbg_cleanup(drbg);
702     return NULL;
703 }
704
705 /*
706  * Initialize the global DRBGs on first use.
707  * Returns 1 on success, 0 on failure.
708  */
709 DEFINE_RUN_ONCE_STATIC(do_rand_drbg_init)
710 {
711     drbg_master = drbg_setup("drbg_master", NULL);
712     drbg_public = drbg_setup("drbg_public", drbg_master);
713     drbg_private = drbg_setup("drbg_private", drbg_master);
714
715     if (drbg_master == NULL || drbg_public == NULL || drbg_private == NULL)
716         return 0;
717
718     return 1;
719 }
720
721 /* Cleans up the given global DRBG  */
722 static void drbg_cleanup(RAND_DRBG *drbg)
723 {
724     if (drbg != NULL) {
725         RAND_DRBG_uninstantiate(drbg);
726         CRYPTO_THREAD_lock_free(drbg->lock);
727         OPENSSL_secure_clear_free(drbg, sizeof(RAND_DRBG));
728     }
729 }
730
731 /* Clean up the global DRBGs before exit */
732 void rand_drbg_cleanup_int(void)
733 {
734     drbg_cleanup(drbg_private);
735     drbg_cleanup(drbg_public);
736     drbg_cleanup(drbg_master);
737
738     drbg_private = drbg_public = drbg_master = NULL;
739 }
740
741 /* Implements the default OpenSSL RAND_bytes() method */
742 static int drbg_bytes(unsigned char *out, int count)
743 {
744     int ret = 0;
745     size_t chunk;
746     RAND_DRBG *drbg = RAND_DRBG_get0_public();
747
748     if (drbg == NULL)
749         return 0;
750
751     CRYPTO_THREAD_write_lock(drbg->lock);
752     if (drbg->state == DRBG_UNINITIALISED)
753         goto err;
754
755     for ( ; count > 0; count -= chunk, out += chunk) {
756         chunk = count;
757         if (chunk > drbg->max_request)
758             chunk = drbg->max_request;
759         ret = RAND_DRBG_generate(drbg, out, chunk, 0, NULL, 0);
760         if (!ret)
761             goto err;
762     }
763     ret = 1;
764
765 err:
766     CRYPTO_THREAD_unlock(drbg->lock);
767     return ret;
768 }
769
770 /* Implements the default OpenSSL RAND_add() method */
771 static int drbg_add(const void *buf, int num, double randomness)
772 {
773     int ret = 0;
774     RAND_DRBG *drbg = RAND_DRBG_get0_master();
775
776     if (drbg == NULL)
777         return 0;
778
779     if (num < 0 || randomness < 0.0)
780         return 0;
781
782     if (randomness > (double)drbg->max_entropylen) {
783         /*
784          * The purpose of this check is to bound |randomness| by a
785          * relatively small value in order to prevent an integer
786          * overflow when multiplying by 8 in the rand_drbg_restart()
787          * call below.
788          */
789         return 0;
790     }
791
792     CRYPTO_THREAD_write_lock(drbg->lock);
793     ret = rand_drbg_restart(drbg, buf,
794                             (size_t)(unsigned int)num,
795                             (size_t)(8*randomness));
796     CRYPTO_THREAD_unlock(drbg->lock);
797
798     return ret;
799 }
800
801 /* Implements the default OpenSSL RAND_seed() method */
802 static int drbg_seed(const void *buf, int num)
803 {
804     return drbg_add(buf, num, num);
805 }
806
807 /* Implements the default OpenSSL RAND_status() method */
808 static int drbg_status(void)
809 {
810     int ret;
811     RAND_DRBG *drbg = RAND_DRBG_get0_master();
812
813     if (drbg == NULL)
814         return 0;
815
816     CRYPTO_THREAD_write_lock(drbg->lock);
817     ret = drbg->state == DRBG_READY ? 1 : 0;
818     CRYPTO_THREAD_unlock(drbg->lock);
819     return ret;
820 }
821
822 /*
823  * Get the master DRBG.
824  * Returns pointer to the DRBG on success, NULL on failure.
825  *
826  */
827 RAND_DRBG *RAND_DRBG_get0_master(void)
828 {
829     if (!RUN_ONCE(&rand_drbg_init, do_rand_drbg_init))
830         return NULL;
831
832     return drbg_master;
833 }
834
835 /*
836  * Get the public DRBG.
837  * Returns pointer to the DRBG on success, NULL on failure.
838  */
839 RAND_DRBG *RAND_DRBG_get0_public(void)
840 {
841     if (!RUN_ONCE(&rand_drbg_init, do_rand_drbg_init))
842         return NULL;
843
844     return drbg_public;
845 }
846
847 /*
848  * Get the private DRBG.
849  * Returns pointer to the DRBG on success, NULL on failure.
850  */
851 RAND_DRBG *RAND_DRBG_get0_private(void)
852 {
853     if (!RUN_ONCE(&rand_drbg_init, do_rand_drbg_init))
854         return NULL;
855
856     return drbg_private;
857 }
858
859 RAND_METHOD rand_meth = {
860     drbg_seed,
861     drbg_bytes,
862     NULL,
863     drbg_add,
864     drbg_bytes,
865     drbg_status
866 };
867
868 RAND_METHOD *RAND_OpenSSL(void)
869 {
870     return &rand_meth;
871 }