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