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