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