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