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