Check the parent DRBG's strength
[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  * LOCKING
95  *
96  * The three shared DRBGs are intended to be used concurrently, so they
97  * support locking. The RAND methods take the locks automatically, so using
98  * the RAND api (in particular RAND_bytes() and RAND_priv_bytes()) is
99  * thread-safe. Note however that accessing the shared DRBGs directly via
100  * the RAND_DRBG interface is *not* thread-safe.
101  *
102  * All other DRBG instances don't support locking, because they are
103  * intendended to be used by a single thread. Instead of accessing a single
104  * DRBG instance concurrently from different threads, it is recommended to
105  * instantiate a separate DRBG instance per thread. Using the same shared
106  * DRBG (preferrably the public DRBG) as parent of DRBG instances on
107  * different threads is safe.
108  */
109
110
111 /* NIST SP 800-90A DRBG recommends the use of a personalization string. */
112 static const char ossl_pers_string[] = "OpenSSL NIST SP 800-90A DRBG";
113
114 static CRYPTO_ONCE rand_drbg_init = CRYPTO_ONCE_STATIC_INIT;
115
116 static RAND_DRBG *drbg_setup(RAND_DRBG *parent);
117
118 static RAND_DRBG *rand_drbg_new(int secure,
119                                 int type,
120                                 unsigned int flags,
121                                 RAND_DRBG *parent);
122
123 /*
124  * Set/initialize |drbg| to be of type |nid|, with optional |flags|.
125  *
126  * Returns 1 on success, 0 on failure.
127  */
128 int RAND_DRBG_set(RAND_DRBG *drbg, int nid, unsigned int flags)
129 {
130     int ret = 1;
131
132     drbg->state = DRBG_UNINITIALISED;
133     drbg->flags = flags;
134     drbg->nid = nid;
135
136     switch (nid) {
137     default:
138         RANDerr(RAND_F_RAND_DRBG_SET, RAND_R_UNSUPPORTED_DRBG_TYPE);
139         return 0;
140     case 0:
141         /* Uninitialized; that's okay. */
142         return 1;
143     case NID_aes_128_ctr:
144     case NID_aes_192_ctr:
145     case NID_aes_256_ctr:
146         ret = drbg_ctr_init(drbg);
147         break;
148     }
149
150     if (ret == 0)
151         RANDerr(RAND_F_RAND_DRBG_SET, RAND_R_ERROR_INITIALISING_DRBG);
152     return ret;
153 }
154
155 /*
156  * Allocate memory and initialize a new DRBG. The DRBG is allocated on
157  * the secure heap if |secure| is nonzero and the secure heap is enabled.
158  * The |parent|, if not NULL, will be used as random source for reseeding.
159  *
160  * Returns a pointer to the new DRBG instance on success, NULL on failure.
161  */
162 static RAND_DRBG *rand_drbg_new(int secure,
163                                 int type,
164                                 unsigned int flags,
165                                 RAND_DRBG *parent)
166 {
167     RAND_DRBG *drbg = secure ?
168         OPENSSL_secure_zalloc(sizeof(*drbg)) : OPENSSL_zalloc(sizeof(*drbg));
169
170     if (drbg == NULL) {
171         RANDerr(RAND_F_RAND_DRBG_NEW, ERR_R_MALLOC_FAILURE);
172         goto err;
173     }
174
175     drbg->secure = secure && CRYPTO_secure_allocated(drbg);
176     drbg->fork_count = rand_fork_count;
177     drbg->parent = parent;
178     if (RAND_DRBG_set(drbg, type, flags) == 0)
179         goto err;
180
181     if (parent != NULL && drbg->strength > parent->strength) {
182         /*
183          * We currently don't support the algorithm from NIST SP 800-90C
184          * 10.1.2 to use a weaker DRBG as source
185          */
186         RANDerr(RAND_F_RAND_DRBG_NEW, RAND_R_PARENT_STRENGTH_TOO_WEAK);
187         goto err;
188     }
189
190     if (!RAND_DRBG_set_callbacks(drbg, rand_drbg_get_entropy,
191                                  rand_drbg_cleanup_entropy,
192                                  NULL, NULL))
193         goto err;
194
195     return drbg;
196
197 err:
198     if (drbg->secure)
199         OPENSSL_secure_free(drbg);
200     else
201         OPENSSL_free(drbg);
202
203     return NULL;
204 }
205
206 RAND_DRBG *RAND_DRBG_new(int type, unsigned int flags, RAND_DRBG *parent)
207 {
208     return rand_drbg_new(0, type, flags, parent);
209 }
210
211 RAND_DRBG *RAND_DRBG_secure_new(int type, unsigned int flags, RAND_DRBG *parent)
212 {
213     return rand_drbg_new(1, type, flags, parent);
214 }
215
216 /*
217  * Uninstantiate |drbg| and free all memory.
218  */
219 void RAND_DRBG_free(RAND_DRBG *drbg)
220 {
221     if (drbg == NULL)
222         return;
223
224     if (drbg->meth != NULL)
225         drbg->meth->uninstantiate(drbg);
226     CRYPTO_THREAD_lock_free(drbg->lock);
227     CRYPTO_free_ex_data(CRYPTO_EX_INDEX_DRBG, drbg, &drbg->ex_data);
228
229     if (drbg->secure)
230         OPENSSL_secure_clear_free(drbg, sizeof(*drbg));
231     else
232         OPENSSL_clear_free(drbg, sizeof(*drbg));
233 }
234
235 /*
236  * Instantiate |drbg|, after it has been initialized.  Use |pers| and
237  * |perslen| as prediction-resistance input.
238  *
239  * Requires that drbg->lock is already locked for write, if non-null.
240  *
241  * Returns 1 on success, 0 on failure.
242  */
243 int RAND_DRBG_instantiate(RAND_DRBG *drbg,
244                           const unsigned char *pers, size_t perslen)
245 {
246     unsigned char *nonce = NULL, *entropy = NULL;
247     size_t noncelen = 0, entropylen = 0;
248
249     if (perslen > drbg->max_perslen) {
250         RANDerr(RAND_F_RAND_DRBG_INSTANTIATE,
251                 RAND_R_PERSONALISATION_STRING_TOO_LONG);
252         goto end;
253     }
254
255     if (drbg->meth == NULL)
256     {
257         RANDerr(RAND_F_RAND_DRBG_INSTANTIATE,
258                 RAND_R_NO_DRBG_IMPLEMENTATION_SELECTED);
259         goto end;
260     }
261
262     if (drbg->state != DRBG_UNINITIALISED) {
263         RANDerr(RAND_F_RAND_DRBG_INSTANTIATE,
264                 drbg->state == DRBG_ERROR ? RAND_R_IN_ERROR_STATE
265                                           : RAND_R_ALREADY_INSTANTIATED);
266         goto end;
267     }
268
269     drbg->state = DRBG_ERROR;
270     if (drbg->get_entropy != NULL)
271         entropylen = drbg->get_entropy(drbg, &entropy, drbg->strength,
272                                    drbg->min_entropylen, drbg->max_entropylen);
273     if (entropylen < drbg->min_entropylen
274         || entropylen > drbg->max_entropylen) {
275         RANDerr(RAND_F_RAND_DRBG_INSTANTIATE, RAND_R_ERROR_RETRIEVING_ENTROPY);
276         goto end;
277     }
278
279     if (drbg->max_noncelen > 0 && drbg->get_nonce != NULL) {
280         noncelen = drbg->get_nonce(drbg, &nonce, drbg->strength / 2,
281                                    drbg->min_noncelen, drbg->max_noncelen);
282         if (noncelen < drbg->min_noncelen || noncelen > drbg->max_noncelen) {
283             RANDerr(RAND_F_RAND_DRBG_INSTANTIATE,
284                     RAND_R_ERROR_RETRIEVING_NONCE);
285             goto end;
286         }
287     }
288
289     if (!drbg->meth->instantiate(drbg, entropy, entropylen,
290                          nonce, noncelen, pers, perslen)) {
291         RANDerr(RAND_F_RAND_DRBG_INSTANTIATE, RAND_R_ERROR_INSTANTIATING_DRBG);
292         goto end;
293     }
294
295     drbg->state = DRBG_READY;
296     drbg->generate_counter = 0;
297     drbg->reseed_time = time(NULL);
298     if (drbg->reseed_counter > 0) {
299         if (drbg->parent == NULL)
300             drbg->reseed_counter++;
301         else
302             drbg->reseed_counter = drbg->parent->reseed_counter;
303     }
304
305 end:
306     if (entropy != NULL && drbg->cleanup_entropy != NULL)
307         drbg->cleanup_entropy(drbg, entropy, entropylen);
308     if (nonce != NULL && drbg->cleanup_nonce!= NULL )
309         drbg->cleanup_nonce(drbg, nonce, noncelen);
310     if (drbg->pool != NULL) {
311         if (drbg->state == DRBG_READY) {
312             RANDerr(RAND_F_RAND_DRBG_INSTANTIATE,
313                     RAND_R_ERROR_ENTROPY_POOL_WAS_IGNORED);
314             drbg->state = DRBG_ERROR;
315         }
316         RAND_POOL_free(drbg->pool);
317         drbg->pool = NULL;
318     }
319     if (drbg->state == DRBG_READY)
320         return 1;
321     return 0;
322 }
323
324 /*
325  * Uninstantiate |drbg|. Must be instantiated before it can be used.
326  *
327  * Requires that drbg->lock is already locked for write, if non-null.
328  *
329  * Returns 1 on success, 0 on failure.
330  */
331 int RAND_DRBG_uninstantiate(RAND_DRBG *drbg)
332 {
333     if (drbg->meth == NULL)
334     {
335         RANDerr(RAND_F_RAND_DRBG_UNINSTANTIATE,
336                 RAND_R_NO_DRBG_IMPLEMENTATION_SELECTED);
337         return 0;
338     }
339
340     /* Clear the entire drbg->ctr struct, then reset some important
341      * members of the drbg->ctr struct (e.g. keysize, df_ks) to their
342      * initial values.
343      */
344     drbg->meth->uninstantiate(drbg);
345     return RAND_DRBG_set(drbg, drbg->nid, drbg->flags);
346 }
347
348 /*
349  * Reseed |drbg|, mixing in the specified data
350  *
351  * Requires that drbg->lock is already locked for write, if non-null.
352  *
353  * Returns 1 on success, 0 on failure.
354  */
355 int RAND_DRBG_reseed(RAND_DRBG *drbg,
356                      const unsigned char *adin, size_t adinlen)
357 {
358     unsigned char *entropy = NULL;
359     size_t entropylen = 0;
360
361     if (drbg->state == DRBG_ERROR) {
362         RANDerr(RAND_F_RAND_DRBG_RESEED, RAND_R_IN_ERROR_STATE);
363         return 0;
364     }
365     if (drbg->state == DRBG_UNINITIALISED) {
366         RANDerr(RAND_F_RAND_DRBG_RESEED, RAND_R_NOT_INSTANTIATED);
367         return 0;
368     }
369
370     if (adin == NULL)
371         adinlen = 0;
372     else if (adinlen > drbg->max_adinlen) {
373         RANDerr(RAND_F_RAND_DRBG_RESEED, RAND_R_ADDITIONAL_INPUT_TOO_LONG);
374         return 0;
375     }
376
377     drbg->state = DRBG_ERROR;
378     if (drbg->get_entropy != NULL)
379         entropylen = drbg->get_entropy(drbg, &entropy, drbg->strength,
380                                    drbg->min_entropylen, drbg->max_entropylen);
381     if (entropylen < drbg->min_entropylen
382         || entropylen > drbg->max_entropylen) {
383         RANDerr(RAND_F_RAND_DRBG_RESEED, RAND_R_ERROR_RETRIEVING_ENTROPY);
384         goto end;
385     }
386
387     if (!drbg->meth->reseed(drbg, entropy, entropylen, adin, adinlen))
388         goto end;
389
390     drbg->state = DRBG_READY;
391     drbg->generate_counter = 0;
392     drbg->reseed_time = time(NULL);
393     if (drbg->reseed_counter > 0) {
394         if (drbg->parent == NULL)
395             drbg->reseed_counter++;
396         else
397             drbg->reseed_counter = drbg->parent->reseed_counter;
398     }
399
400 end:
401     if (entropy != NULL && drbg->cleanup_entropy != NULL)
402         drbg->cleanup_entropy(drbg, entropy, entropylen);
403     if (drbg->state == DRBG_READY)
404         return 1;
405     return 0;
406 }
407
408 /*
409  * Restart |drbg|, using the specified entropy or additional input
410  *
411  * Tries its best to get the drbg instantiated by all means,
412  * regardless of its current state.
413  *
414  * Optionally, a |buffer| of |len| random bytes can be passed,
415  * which is assumed to contain at least |entropy| bits of entropy.
416  *
417  * If |entropy| > 0, the buffer content is used as entropy input.
418  *
419  * If |entropy| == 0, the buffer content is used as additional input
420  *
421  * Returns 1 on success, 0 on failure.
422  *
423  * This function is used internally only.
424  */
425 int rand_drbg_restart(RAND_DRBG *drbg,
426                       const unsigned char *buffer, size_t len, size_t entropy)
427 {
428     int reseeded = 0;
429     const unsigned char *adin = NULL;
430     size_t adinlen = 0;
431
432     if (drbg->pool != NULL) {
433         RANDerr(RAND_F_RAND_DRBG_RESTART, ERR_R_INTERNAL_ERROR);
434         RAND_POOL_free(drbg->pool);
435         drbg->pool = NULL;
436     }
437
438     if (buffer != NULL) {
439         if (entropy > 0) {
440             if (drbg->max_entropylen < len) {
441                 RANDerr(RAND_F_RAND_DRBG_RESTART,
442                     RAND_R_ENTROPY_INPUT_TOO_LONG);
443                 return 0;
444             }
445
446             if (entropy > 8 * len) {
447                 RANDerr(RAND_F_RAND_DRBG_RESTART, RAND_R_ENTROPY_OUT_OF_RANGE);
448                 return 0;
449             }
450
451             /* will be picked up by the rand_drbg_get_entropy() callback */
452             drbg->pool = RAND_POOL_new(entropy, len, len);
453             if (drbg->pool == NULL)
454                 return 0;
455
456             RAND_POOL_add(drbg->pool, buffer, len, entropy);
457         } else {
458             if (drbg->max_adinlen < len) {
459                 RANDerr(RAND_F_RAND_DRBG_RESTART,
460                         RAND_R_ADDITIONAL_INPUT_TOO_LONG);
461                 return 0;
462             }
463             adin = buffer;
464             adinlen = len;
465         }
466     }
467
468     /* repair error state */
469     if (drbg->state == DRBG_ERROR)
470         RAND_DRBG_uninstantiate(drbg);
471
472     /* repair uninitialized state */
473     if (drbg->state == DRBG_UNINITIALISED) {
474         /* reinstantiate drbg */
475         RAND_DRBG_instantiate(drbg,
476                               (const unsigned char *) ossl_pers_string,
477                               sizeof(ossl_pers_string) - 1);
478         /* already reseeded. prevent second reseeding below */
479         reseeded = (drbg->state == DRBG_READY);
480     }
481
482     /* refresh current state if entropy or additional input has been provided */
483     if (drbg->state == DRBG_READY) {
484         if (adin != NULL) {
485             /*
486              * mix in additional input without reseeding
487              *
488              * Similar to RAND_DRBG_reseed(), but the provided additional
489              * data |adin| is mixed into the current state without pulling
490              * entropy from the trusted entropy source using get_entropy().
491              * This is not a reseeding in the strict sense of NIST SP 800-90A.
492              */
493             drbg->meth->reseed(drbg, adin, adinlen, NULL, 0);
494         } else if (reseeded == 0) {
495             /* do a full reseeding if it has not been done yet above */
496             RAND_DRBG_reseed(drbg, NULL, 0);
497         }
498     }
499
500     /* check whether a given entropy pool was cleared properly during reseed */
501     if (drbg->pool != NULL) {
502         drbg->state = DRBG_ERROR;
503         RANDerr(RAND_F_RAND_DRBG_RESTART, ERR_R_INTERNAL_ERROR);
504         RAND_POOL_free(drbg->pool);
505         drbg->pool = NULL;
506         return 0;
507     }
508
509     return drbg->state == DRBG_READY;
510 }
511
512 /*
513  * Generate |outlen| bytes into the buffer at |out|.  Reseed if we need
514  * to or if |prediction_resistance| is set.  Additional input can be
515  * sent in |adin| and |adinlen|.
516  *
517  * Requires that drbg->lock is already locked for write, if non-null.
518  *
519  * Returns 1 on success, 0 on failure.
520  *
521  */
522 int RAND_DRBG_generate(RAND_DRBG *drbg, unsigned char *out, size_t outlen,
523                        int prediction_resistance,
524                        const unsigned char *adin, size_t adinlen)
525 {
526     int reseed_required = 0;
527
528     if (drbg->state != DRBG_READY) {
529         /* try to recover from previous errors */
530         rand_drbg_restart(drbg, NULL, 0, 0);
531
532         if (drbg->state == DRBG_ERROR) {
533             RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_IN_ERROR_STATE);
534             return 0;
535         }
536         if (drbg->state == DRBG_UNINITIALISED) {
537             RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_NOT_INSTANTIATED);
538             return 0;
539         }
540     }
541
542     if (outlen > drbg->max_request) {
543         RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_REQUEST_TOO_LARGE_FOR_DRBG);
544         return 0;
545     }
546     if (adinlen > drbg->max_adinlen) {
547         RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_ADDITIONAL_INPUT_TOO_LONG);
548         return 0;
549     }
550
551     if (drbg->fork_count != rand_fork_count) {
552         drbg->fork_count = rand_fork_count;
553         reseed_required = 1;
554     }
555
556     if (drbg->reseed_interval > 0) {
557         if (drbg->generate_counter >= drbg->reseed_interval)
558             reseed_required = 1;
559     }
560     if (drbg->reseed_time_interval > 0) {
561         time_t now = time(NULL);
562         if (now < drbg->reseed_time
563             || now - drbg->reseed_time >= drbg->reseed_time_interval)
564             reseed_required = 1;
565     }
566     if (drbg->reseed_counter > 0 && drbg->parent != NULL) {
567         if (drbg->reseed_counter != drbg->parent->reseed_counter)
568             reseed_required = 1;
569     }
570
571     if (reseed_required || prediction_resistance) {
572         if (!RAND_DRBG_reseed(drbg, adin, adinlen)) {
573             RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_RESEED_ERROR);
574             return 0;
575         }
576         adin = NULL;
577         adinlen = 0;
578     }
579
580     if (!drbg->meth->generate(drbg, out, outlen, adin, adinlen)) {
581         drbg->state = DRBG_ERROR;
582         RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_GENERATE_ERROR);
583         return 0;
584     }
585
586     drbg->generate_counter++;
587
588     return 1;
589 }
590
591 /*
592  * Generates |outlen| random bytes and stores them in |out|. It will
593  * using the given |drbg| to generate the bytes.
594  *
595  * Requires that drbg->lock is already locked for write, if non-null.
596  *
597  * Returns 1 on success 0 on failure.
598  */
599 int RAND_DRBG_bytes(RAND_DRBG *drbg, unsigned char *out, size_t outlen)
600 {
601     unsigned char *additional = NULL;
602     size_t additional_len;
603     size_t chunk;
604     size_t ret;
605
606     additional_len = rand_drbg_get_additional_data(&additional, drbg->max_adinlen);
607
608     for ( ; outlen > 0; outlen -= chunk, out += chunk) {
609         chunk = outlen;
610         if (chunk > drbg->max_request)
611             chunk = drbg->max_request;
612         ret = RAND_DRBG_generate(drbg, out, chunk, 0, additional, additional_len);
613         if (!ret)
614             goto err;
615     }
616     ret = 1;
617
618 err:
619     if (additional_len != 0)
620         OPENSSL_secure_clear_free(additional, additional_len);
621
622     return ret;
623 }
624
625 /*
626  * Set the RAND_DRBG callbacks for obtaining entropy and nonce.
627  *
628  * In the following, the signature and the semantics of the
629  * get_entropy() and cleanup_entropy() callbacks are explained.
630  *
631  * GET_ENTROPY
632  *
633  *     size_t get_entropy(RAND_DRBG *ctx,
634  *                        unsigned char **pout,
635  *                        int entropy,
636  *                        size_t min_len, size_t max_len);
637  *
638  * This is a request to allocate and fill a buffer of size
639  * |min_len| <= size <= |max_len| (in bytes) which contains
640  * at least |entropy| bits of randomness. The buffer's address is
641  * to be returned in |*pout| and the number of collected
642  * randomness bytes (which may be less than the allocated size
643  * of the buffer) as return value.
644  *
645  * If the callback fails to acquire at least |entropy| bits of
646  * randomness, it shall return a buffer length of 0.
647  *
648  * CLEANUP_ENTROPY
649  *
650  *     void cleanup_entropy(RAND_DRBG *ctx,
651  *                          unsigned char *out, size_t outlen);
652  *
653  * A request to clear and free the buffer allocated by get_entropy().
654  * The values |out| and |outlen| are expected to be the random buffer's
655  * address and length, as returned by the get_entropy() callback.
656  *
657  * GET_NONCE, CLEANUP_NONCE
658  *
659  * Signature and semantics of the get_nonce() and cleanup_nonce()
660  * callbacks are analogous to get_entropy() and cleanup_entropy().
661  * Currently, the nonce is used only for the known answer tests.
662  */
663 int RAND_DRBG_set_callbacks(RAND_DRBG *drbg,
664                             RAND_DRBG_get_entropy_fn get_entropy,
665                             RAND_DRBG_cleanup_entropy_fn cleanup_entropy,
666                             RAND_DRBG_get_nonce_fn get_nonce,
667                             RAND_DRBG_cleanup_nonce_fn cleanup_nonce)
668 {
669     if (drbg->state != DRBG_UNINITIALISED)
670         return 0;
671     drbg->get_entropy = get_entropy;
672     drbg->cleanup_entropy = cleanup_entropy;
673     drbg->get_nonce = get_nonce;
674     drbg->cleanup_nonce = cleanup_nonce;
675     return 1;
676 }
677
678 /*
679  * Set the reseed interval.
680  *
681  * The drbg will reseed automatically whenever the number of generate
682  * requests exceeds the given reseed interval. If the reseed interval
683  * is 0, then this feature is disabled.
684  *
685  * Returns 1 on success, 0 on failure.
686  */
687 int RAND_DRBG_set_reseed_interval(RAND_DRBG *drbg, unsigned int interval)
688 {
689     if (interval > MAX_RESEED_INTERVAL)
690         return 0;
691     drbg->reseed_interval = interval;
692     return 1;
693 }
694
695 /*
696  * Set the reseed time interval.
697  *
698  * The drbg will reseed automatically whenever the time elapsed since
699  * the last reseeding exceeds the given reseed time interval. For safety,
700  * a reseeding will also occur if the clock has been reset to a smaller
701  * value.
702  *
703  * Returns 1 on success, 0 on failure.
704  */
705 int RAND_DRBG_set_reseed_time_interval(RAND_DRBG *drbg, time_t interval)
706 {
707     if (interval > MAX_RESEED_TIME_INTERVAL)
708         return 0;
709     drbg->reseed_time_interval = interval;
710     return 1;
711 }
712
713
714 /*
715  * Locks the given drbg. Locking a drbg which does not have locking
716  * enabled is considered a successful no-op.
717  *
718  * Returns 1 on success, 0 on failure.
719  */
720 int rand_drbg_lock(RAND_DRBG *drbg)
721 {
722     if (drbg->lock != NULL)
723         return CRYPTO_THREAD_write_lock(drbg->lock);
724
725     return 1;
726 }
727
728 /*
729  * Unlocks the given drbg. Unlocking a drbg which does not have locking
730  * enabled is considered a successful no-op.
731  *
732  * Returns 1 on success, 0 on failure.
733  */
734 int rand_drbg_unlock(RAND_DRBG *drbg)
735 {
736     if (drbg->lock != NULL)
737         return CRYPTO_THREAD_unlock(drbg->lock);
738
739     return 1;
740 }
741
742 /*
743  * Enables locking for the given drbg
744  *
745  * Locking can only be enabled if the random generator
746  * is in the uninitialized state.
747  *
748  * Returns 1 on success, 0 on failure.
749  */
750 int rand_drbg_enable_locking(RAND_DRBG *drbg)
751 {
752     if (drbg->state != DRBG_UNINITIALISED) {
753         RANDerr(RAND_F_RAND_DRBG_ENABLE_LOCKING,
754                 RAND_R_DRBG_ALREADY_INITIALIZED);
755         return 0;
756     }
757
758     if (drbg->lock == NULL) {
759         if (drbg->parent != NULL && drbg->parent->lock == NULL) {
760             RANDerr(RAND_F_RAND_DRBG_ENABLE_LOCKING,
761                     RAND_R_PARENT_LOCKING_NOT_ENABLED);
762             return 0;
763         }
764
765         drbg->lock = CRYPTO_THREAD_lock_new();
766         if (drbg->lock == NULL) {
767             RANDerr(RAND_F_RAND_DRBG_ENABLE_LOCKING,
768                     RAND_R_FAILED_TO_CREATE_LOCK);
769             return 0;
770         }
771     }
772
773     return 1;
774 }
775
776 /*
777  * Get and set the EXDATA
778  */
779 int RAND_DRBG_set_ex_data(RAND_DRBG *drbg, int idx, void *arg)
780 {
781     return CRYPTO_set_ex_data(&drbg->ex_data, idx, arg);
782 }
783
784 void *RAND_DRBG_get_ex_data(const RAND_DRBG *drbg, int idx)
785 {
786     return CRYPTO_get_ex_data(&drbg->ex_data, idx);
787 }
788
789
790 /*
791  * The following functions provide a RAND_METHOD that works on the
792  * global DRBG.  They lock.
793  */
794
795 /*
796  * Allocates a new global DRBG on the secure heap (if enabled) and
797  * initializes it with default settings.
798  *
799  * Returns a pointer to the new DRBG instance on success, NULL on failure.
800  */
801 static RAND_DRBG *drbg_setup(RAND_DRBG *parent)
802 {
803     RAND_DRBG *drbg;
804
805     drbg = RAND_DRBG_secure_new(RAND_DRBG_NID, 0, parent);
806     if (drbg == NULL)
807         return NULL;
808
809     if (rand_drbg_enable_locking(drbg) == 0)
810         goto err;
811
812     if (parent == NULL) {
813         drbg->reseed_interval = MASTER_RESEED_INTERVAL;
814         drbg->reseed_time_interval = MASTER_RESEED_TIME_INTERVAL;
815     } else {
816         drbg->reseed_interval = SLAVE_RESEED_INTERVAL;
817         drbg->reseed_time_interval = SLAVE_RESEED_TIME_INTERVAL;
818     }
819
820     /* enable seed propagation */
821     drbg->reseed_counter = 1;
822
823     /*
824      * Ignore instantiation error so support just-in-time instantiation.
825      *
826      * The state of the drbg will be checked in RAND_DRBG_generate() and
827      * an automatic recovery is attempted.
828      */
829     RAND_DRBG_instantiate(drbg,
830                           (const unsigned char *) ossl_pers_string,
831                           sizeof(ossl_pers_string) - 1);
832     return drbg;
833
834 err:
835     RAND_DRBG_free(drbg);
836     return NULL;
837 }
838
839 /*
840  * Initialize the global DRBGs on first use.
841  * Returns 1 on success, 0 on failure.
842  */
843 DEFINE_RUN_ONCE_STATIC(do_rand_drbg_init)
844 {
845     /*
846      * ensure that libcrypto is initialized, otherwise the
847      * DRBG locks are not cleaned up properly
848      */
849     if (!OPENSSL_init_crypto(0, NULL))
850         return 0;
851
852     drbg_master = drbg_setup(NULL);
853     drbg_public = drbg_setup(drbg_master);
854     drbg_private = drbg_setup(drbg_master);
855
856     if (drbg_master == NULL || drbg_public == NULL || drbg_private == NULL)
857         return 0;
858
859     return 1;
860 }
861
862 /* Clean up the global DRBGs before exit */
863 void rand_drbg_cleanup_int(void)
864 {
865     RAND_DRBG_free(drbg_private);
866     RAND_DRBG_free(drbg_public);
867     RAND_DRBG_free(drbg_master);
868
869     drbg_private = drbg_public = drbg_master = NULL;
870 }
871
872 /* Implements the default OpenSSL RAND_bytes() method */
873 static int drbg_bytes(unsigned char *out, int count)
874 {
875     int ret;
876     RAND_DRBG *drbg = RAND_DRBG_get0_public();
877
878     if (drbg == NULL)
879         return 0;
880
881     rand_drbg_lock(drbg);
882     ret = RAND_DRBG_bytes(drbg, out, count);
883     rand_drbg_unlock(drbg);
884
885     return ret;
886 }
887
888 /* Implements the default OpenSSL RAND_add() method */
889 static int drbg_add(const void *buf, int num, double randomness)
890 {
891     int ret = 0;
892     RAND_DRBG *drbg = RAND_DRBG_get0_master();
893
894     if (drbg == NULL)
895         return 0;
896
897     if (num < 0 || randomness < 0.0)
898         return 0;
899
900     if (randomness > (double)drbg->max_entropylen) {
901         /*
902          * The purpose of this check is to bound |randomness| by a
903          * relatively small value in order to prevent an integer
904          * overflow when multiplying by 8 in the rand_drbg_restart()
905          * call below.
906          */
907         return 0;
908     }
909
910     rand_drbg_lock(drbg);
911     ret = rand_drbg_restart(drbg, buf,
912                             (size_t)(unsigned int)num,
913                             (size_t)(8*randomness));
914     rand_drbg_unlock(drbg);
915
916     return ret;
917 }
918
919 /* Implements the default OpenSSL RAND_seed() method */
920 static int drbg_seed(const void *buf, int num)
921 {
922     return drbg_add(buf, num, num);
923 }
924
925 /* Implements the default OpenSSL RAND_status() method */
926 static int drbg_status(void)
927 {
928     int ret;
929     RAND_DRBG *drbg = RAND_DRBG_get0_master();
930
931     if (drbg == NULL)
932         return 0;
933
934     rand_drbg_lock(drbg);
935     ret = drbg->state == DRBG_READY ? 1 : 0;
936     rand_drbg_unlock(drbg);
937     return ret;
938 }
939
940 /*
941  * Get the master DRBG.
942  * Returns pointer to the DRBG on success, NULL on failure.
943  *
944  */
945 RAND_DRBG *RAND_DRBG_get0_master(void)
946 {
947     if (!RUN_ONCE(&rand_drbg_init, do_rand_drbg_init))
948         return NULL;
949
950     return drbg_master;
951 }
952
953 /*
954  * Get the public DRBG.
955  * Returns pointer to the DRBG on success, NULL on failure.
956  */
957 RAND_DRBG *RAND_DRBG_get0_public(void)
958 {
959     if (!RUN_ONCE(&rand_drbg_init, do_rand_drbg_init))
960         return NULL;
961
962     return drbg_public;
963 }
964
965 /*
966  * Get the private DRBG.
967  * Returns pointer to the DRBG on success, NULL on failure.
968  */
969 RAND_DRBG *RAND_DRBG_get0_private(void)
970 {
971     if (!RUN_ONCE(&rand_drbg_init, do_rand_drbg_init))
972         return NULL;
973
974     return drbg_private;
975 }
976
977 RAND_METHOD rand_meth = {
978     drbg_seed,
979     drbg_bytes,
980     NULL,
981     drbg_add,
982     drbg_bytes,
983     drbg_status
984 };
985
986 RAND_METHOD *RAND_OpenSSL(void)
987 {
988     return &rand_meth;
989 }