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