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