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