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