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