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