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