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