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