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