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