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