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