CTR, HASH and HMAC DRBGs in provider
[openssl.git] / crypto / rand / drbg_lib.c
1 /*
2  * Copyright 2011-2020 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the Apache License 2.0 (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 <openssl/core_names.h>
15 #include "rand_local.h"
16 #include "internal/thread_once.h"
17 #include "crypto/rand.h"
18 #include "crypto/cryptlib.h"
19
20 /*
21  * Support framework for NIST SP 800-90A DRBG
22  *
23  * See manual page RAND_DRBG(7) for a general overview.
24  *
25  * The OpenSSL model is to have new and free functions, and that new
26  * does all initialization.  That is not the NIST model, which has
27  * instantiation and un-instantiate, and re-use within a new/free
28  * lifecycle.  (No doubt this comes from the desire to support hardware
29  * DRBG, where allocation of resources on something like an HSM is
30  * a much bigger deal than just re-setting an allocated resource.)
31  */
32
33
34 typedef struct drbg_global_st {
35     /*
36      * The three shared DRBG instances
37      *
38      * There are three shared DRBG instances: <master>, <public>, and <private>.
39      */
40     CRYPTO_RWLOCK *lock;
41
42     /*
43      * The <master> DRBG
44      *
45      * Not used directly by the application, only for reseeding the two other
46      * DRBGs. It reseeds itself by pulling either randomness from os entropy
47      * sources or by consuming randomness which was added by RAND_add().
48      *
49      * The <master> DRBG is a global instance which is accessed concurrently by
50      * all threads. The necessary locking is managed automatically by its child
51      * DRBG instances during reseeding.
52      */
53     RAND_DRBG *master_drbg;
54     /*
55      * The <public> DRBG
56      *
57      * Used by default for generating random bytes using RAND_bytes().
58      *
59      * The <public> DRBG is thread-local, i.e., there is one instance per
60      * thread.
61      */
62     CRYPTO_THREAD_LOCAL public_drbg;
63     /*
64      * The <private> DRBG
65      *
66      * Used by default for generating private keys using RAND_priv_bytes()
67      *
68      * The <private> DRBG is thread-local, i.e., there is one instance per
69      * thread.
70      */
71     CRYPTO_THREAD_LOCAL private_drbg;
72 } DRBG_GLOBAL;
73
74 #define RAND_DRBG_TYPE_FLAGS    ( \
75     RAND_DRBG_FLAG_MASTER | RAND_DRBG_FLAG_PUBLIC | RAND_DRBG_FLAG_PRIVATE )
76
77 #define RAND_DRBG_TYPE_MASTER                     0
78 #define RAND_DRBG_TYPE_PUBLIC                     1
79 #define RAND_DRBG_TYPE_PRIVATE                    2
80
81 /* Defaults */
82 static int rand_drbg_type[3] = {
83     RAND_DRBG_TYPE, /* Master */
84     RAND_DRBG_TYPE, /* Public */
85     RAND_DRBG_TYPE  /* Private */
86 };
87 static unsigned int rand_drbg_flags[3] = {
88     RAND_DRBG_FLAGS | RAND_DRBG_FLAG_MASTER, /* Master */
89     RAND_DRBG_FLAGS | RAND_DRBG_FLAG_PUBLIC, /* Public */
90     RAND_DRBG_FLAGS | RAND_DRBG_FLAG_PRIVATE /* Private */
91 };
92
93 static unsigned int master_reseed_interval = MASTER_RESEED_INTERVAL;
94 static unsigned int slave_reseed_interval  = SLAVE_RESEED_INTERVAL;
95
96 static time_t master_reseed_time_interval = MASTER_RESEED_TIME_INTERVAL;
97 static time_t slave_reseed_time_interval  = SLAVE_RESEED_TIME_INTERVAL;
98
99 /* A logical OR of all used DRBG flag bits (currently there is only one) */
100 static const unsigned int rand_drbg_used_flags =
101     RAND_DRBG_FLAG_CTR_NO_DF | RAND_DRBG_FLAG_HMAC | RAND_DRBG_TYPE_FLAGS;
102
103
104 static RAND_DRBG *drbg_setup(OPENSSL_CTX *ctx, RAND_DRBG *parent, int drbg_type);
105
106 static int get_drbg_params(int type, unsigned int flags, const char **name,
107                            OSSL_PARAM params[3])
108 {
109     OSSL_PARAM *p = params;
110
111     switch (type) {
112     case 0:
113         return 1;
114     default:
115         return 0;
116
117 #define CTR(v)                                                              \
118     *name = "CTR-DRBG";                                                     \
119     *p++ = OSSL_PARAM_construct_utf8_string(OSSL_DRBG_PARAM_CIPHER, v, 0)
120
121     case NID_aes_128_ctr:
122         CTR(SN_aes_128_ctr);
123         break;
124     case NID_aes_192_ctr:
125         CTR(SN_aes_192_ctr);
126         break;
127     case NID_aes_256_ctr:
128         CTR(SN_aes_256_ctr);
129         break;
130
131 #define DGST(v)                                                             \
132     *p++ = OSSL_PARAM_construct_utf8_string(OSSL_DRBG_PARAM_DIGEST, v, 0);  \
133     if ((flags & RAND_DRBG_FLAG_HMAC) == 0) {                               \
134         *name = "HASH-DRBG";                                                \
135     } else {                                                                \
136         *name = "HMAC-DRBG";                                                \
137         *p++ = OSSL_PARAM_construct_utf8_string(OSSL_DRBG_PARAM_MAC,        \
138                                                 SN_hmac, 0);                \
139     }
140
141     case NID_sha1:
142         DGST(SN_sha1);
143         break;
144     case NID_sha224:
145         DGST(SN_sha224);
146         break;
147     case NID_sha256:
148         DGST(SN_sha256);
149         break;
150     case NID_sha384:
151         DGST(SN_sha384);
152         break;
153     case NID_sha512:
154         DGST(SN_sha512);
155         break;
156     case NID_sha512_224:
157         DGST(SN_sha512_224);
158         break;
159     case NID_sha512_256:
160         DGST(SN_sha512_256);
161         break;
162     case NID_sha3_224:
163         DGST(SN_sha3_224);
164         break;
165     case NID_sha3_256:
166         DGST(SN_sha3_256);
167         break;
168     case NID_sha3_384:
169         DGST(SN_sha3_384);
170         break;
171     case NID_sha3_512:
172         DGST(SN_sha3_512);
173     }
174     *p = OSSL_PARAM_construct_end();
175     return 1;
176 }
177
178 /*
179  * Initialize the OPENSSL_CTX global DRBGs on first use.
180  * Returns the allocated global data on success or NULL on failure.
181  */
182 static void *drbg_ossl_ctx_new(OPENSSL_CTX *libctx)
183 {
184     DRBG_GLOBAL *dgbl = OPENSSL_zalloc(sizeof(*dgbl));
185
186     if (dgbl == NULL)
187         return NULL;
188
189 #ifndef FIPS_MODULE
190     /*
191      * We need to ensure that base libcrypto thread handling has been
192      * initialised.
193      */
194      OPENSSL_init_crypto(0, NULL);
195 #endif
196
197     dgbl->lock = CRYPTO_THREAD_lock_new();
198     if (dgbl->lock == NULL)
199         goto err0;
200
201     if (!CRYPTO_THREAD_init_local(&dgbl->private_drbg, NULL))
202         goto err1;
203
204     if (!CRYPTO_THREAD_init_local(&dgbl->public_drbg, NULL))
205         goto err2;
206
207     return dgbl;
208
209  err2:
210     CRYPTO_THREAD_cleanup_local(&dgbl->private_drbg);
211  err1:
212     CRYPTO_THREAD_lock_free(dgbl->lock);
213  err0:
214     OPENSSL_free(dgbl);
215     return NULL;
216 }
217
218 static void drbg_ossl_ctx_free(void *vdgbl)
219 {
220     DRBG_GLOBAL *dgbl = vdgbl;
221
222     if (dgbl == NULL)
223         return;
224
225     CRYPTO_THREAD_lock_free(dgbl->lock);
226     RAND_DRBG_free(dgbl->master_drbg);
227     CRYPTO_THREAD_cleanup_local(&dgbl->private_drbg);
228     CRYPTO_THREAD_cleanup_local(&dgbl->public_drbg);
229
230     OPENSSL_free(dgbl);
231 }
232
233 static const OPENSSL_CTX_METHOD drbg_ossl_ctx_method = {
234     drbg_ossl_ctx_new,
235     drbg_ossl_ctx_free,
236 };
237
238 static DRBG_GLOBAL *drbg_get_global(OPENSSL_CTX *libctx)
239 {
240     return openssl_ctx_get_data(libctx, OPENSSL_CTX_DRBG_INDEX,
241                                 &drbg_ossl_ctx_method);
242 }
243
244 /*
245  * Set the |drbg|'s callback data pointer for the entropy and nonce callbacks
246  *
247  * The ownership of the context data remains with the caller,
248  * i.e., it is the caller's responsibility to keep it available as long
249  * as it is need by the callbacks and free it after use.
250  *
251  * Setting the callback data is allowed only if the drbg has not been
252  * initialized yet. Otherwise, the operation will fail.
253  *
254  * Returns 1 on success, 0 on failure.
255  */
256 int RAND_DRBG_set_callback_data(RAND_DRBG *drbg, void *data)
257 {
258     if (EVP_RAND_state(drbg->rand) != EVP_RAND_STATE_UNINITIALISED
259             || drbg->parent != NULL)
260         return 0;
261
262     drbg->callback_data = data;
263     return 1;
264 }
265
266 /* Retrieve the callback data pointer */
267 void *RAND_DRBG_get_callback_data(RAND_DRBG *drbg)
268 {
269     return drbg->callback_data;
270 }
271
272 /*
273  * Set/initialize |drbg| to be of type |type|, with optional |flags|.
274  *
275  * If |type| and |flags| are zero, use the defaults
276  *
277  * Returns 1 on success, 0 on failure.
278  */
279 int RAND_DRBG_set(RAND_DRBG *drbg, int type, unsigned int flags)
280 {
281     OSSL_PARAM params[6], *p = params;
282     unsigned int reseed_interval;
283     time_t reseed_time_interval;
284     const char *name = NULL;
285     EVP_RAND *rand;
286     EVP_RAND_CTX *pctx;
287     int use_df;
288
289     if (type == 0 && flags == 0) {
290         type = rand_drbg_type[RAND_DRBG_TYPE_MASTER];
291         flags = rand_drbg_flags[RAND_DRBG_TYPE_MASTER];
292     }
293
294     if (drbg->parent == NULL) {
295         reseed_interval = master_reseed_interval;
296         reseed_time_interval = master_reseed_time_interval;
297     } else {
298         reseed_interval = slave_reseed_interval;
299         reseed_time_interval = slave_reseed_time_interval;
300     }
301     *p++ = OSSL_PARAM_construct_uint(OSSL_DRBG_PARAM_RESEED_REQUESTS,
302                                      &reseed_interval);
303     *p++ = OSSL_PARAM_construct_time_t(OSSL_DRBG_PARAM_RESEED_TIME_INTERVAL,
304                                        &reseed_time_interval);
305     use_df = (flags & RAND_DRBG_FLAG_CTR_NO_DF) == 0;
306     *p++ = OSSL_PARAM_construct_int(OSSL_DRBG_PARAM_USE_DF, &use_df);
307
308     if (!get_drbg_params(type, flags, &name, p)) {
309         RANDerr(0, RAND_R_UNSUPPORTED_DRBG_TYPE);
310         return 0;
311     }
312
313     rand = EVP_RAND_fetch(drbg->libctx, name, NULL);
314     if (rand == NULL) {
315         RANDerr(0, RAND_R_NO_DRBG_IMPLEMENTATION_SELECTED);
316         return 0;
317     }
318
319     EVP_RAND_CTX_free(drbg->rand);
320     drbg->rand = NULL;
321
322     drbg->flags = flags;
323     drbg->type = type;
324
325     pctx = drbg->parent != NULL ? drbg->parent->rand : NULL;
326     drbg->rand = EVP_RAND_CTX_new(rand, pctx);
327     EVP_RAND_free(rand);
328     if (drbg->rand == NULL) {
329         RANDerr(0, RAND_R_NO_DRBG_IMPLEMENTATION_SELECTED);
330         goto err;
331     }
332
333     if (!EVP_RAND_set_ctx_params(drbg->rand, params)) {
334         RANDerr(0, RAND_R_ERROR_INITIALISING_DRBG);
335         goto err;
336     }
337     return 1;
338 err:
339     EVP_RAND_CTX_free(drbg->rand);
340     drbg->rand = NULL;
341     drbg->type = 0;
342     drbg->flags = 0;
343     return 0;
344 }
345
346 /*
347  * Set/initialize default |type| and |flag| for new drbg instances.
348  *
349  * Returns 1 on success, 0 on failure.
350  */
351 int RAND_DRBG_set_defaults(int type, unsigned int flags)
352 {
353     int all;
354     const char *name;
355     OSSL_PARAM params[3];
356
357     if (!get_drbg_params(type, flags, &name, params)) {
358         RANDerr(RAND_F_RAND_DRBG_SET_DEFAULTS, RAND_R_UNSUPPORTED_DRBG_TYPE);
359         return 0;
360     }
361
362     if ((flags & ~rand_drbg_used_flags) != 0) {
363         RANDerr(RAND_F_RAND_DRBG_SET_DEFAULTS, RAND_R_UNSUPPORTED_DRBG_FLAGS);
364         return 0;
365     }
366
367     all = ((flags & RAND_DRBG_TYPE_FLAGS) == 0);
368     if (all || (flags & RAND_DRBG_FLAG_MASTER) != 0) {
369         rand_drbg_type[RAND_DRBG_TYPE_MASTER] = type;
370         rand_drbg_flags[RAND_DRBG_TYPE_MASTER] = flags | RAND_DRBG_FLAG_MASTER;
371     }
372     if (all || (flags & RAND_DRBG_FLAG_PUBLIC) != 0) {
373         rand_drbg_type[RAND_DRBG_TYPE_PUBLIC]  = type;
374         rand_drbg_flags[RAND_DRBG_TYPE_PUBLIC] = flags | RAND_DRBG_FLAG_PUBLIC;
375     }
376     if (all || (flags & RAND_DRBG_FLAG_PRIVATE) != 0) {
377         rand_drbg_type[RAND_DRBG_TYPE_PRIVATE] = type;
378         rand_drbg_flags[RAND_DRBG_TYPE_PRIVATE] = flags | RAND_DRBG_FLAG_PRIVATE;
379     }
380     return 1;
381 }
382
383
384 /*
385  * Allocate memory and initialize a new DRBG.
386  * The |parent|, if not NULL, will be used as random source for reseeding.
387  *
388  * Returns a pointer to the new DRBG instance on success, NULL on failure.
389  */
390 static RAND_DRBG *rand_drbg_new(OPENSSL_CTX *ctx,
391                                 int type,
392                                 unsigned int flags,
393                                 RAND_DRBG *parent)
394 {
395     RAND_DRBG *drbg = OPENSSL_zalloc(sizeof(*drbg));
396
397     if (drbg == NULL) {
398         RANDerr(RAND_F_RAND_DRBG_NEW, ERR_R_MALLOC_FAILURE);
399         return NULL;
400     }
401
402     drbg->libctx = ctx;
403     drbg->parent = parent;
404
405     if (RAND_DRBG_set(drbg, type, flags) == 0)
406         goto err;
407
408     return drbg;
409
410  err:
411     RAND_DRBG_free(drbg);
412
413     return NULL;
414 }
415
416 RAND_DRBG *RAND_DRBG_new_ex(OPENSSL_CTX *ctx, int type, unsigned int flags,
417                             RAND_DRBG *parent)
418 {
419     return rand_drbg_new(ctx, type, flags, parent);
420 }
421
422 RAND_DRBG *RAND_DRBG_new(int type, unsigned int flags, RAND_DRBG *parent)
423 {
424     return RAND_DRBG_new_ex(NULL, type, flags, parent);
425 }
426
427 /*
428  * Uninstantiate |drbg| and free all memory.
429  */
430 void RAND_DRBG_free(RAND_DRBG *drbg)
431 {
432     if (drbg == NULL)
433         return;
434
435     CRYPTO_free_ex_data(CRYPTO_EX_INDEX_RAND_DRBG, drbg, &drbg->ex_data);
436     OPENSSL_free(drbg);
437 }
438
439 /*
440  * Instantiate |drbg|, after it has been initialized.  Use |pers| and
441  * |perslen| as prediction-resistance input.
442  *
443  * Requires that drbg->lock is already locked for write, if non-null.
444  *
445  * Returns 1 on success, 0 on failure.
446  */
447 int RAND_DRBG_instantiate(RAND_DRBG *drbg,
448                           const unsigned char *pers, size_t perslen)
449 {
450     return EVP_RAND_instantiate(drbg->rand, EVP_RAND_strength(drbg->rand), 0,
451                                 pers, perslen);
452 }
453
454 /*
455  * Uninstantiate |drbg|. Must be instantiated before it can be used.
456  *
457  * Requires that drbg->lock is already locked for write, if non-null.
458  *
459  * Returns 1 on success, 0 on failure.
460  */
461 int RAND_DRBG_uninstantiate(RAND_DRBG *drbg)
462 {
463     int index = -1, type, flags;
464
465     if (!EVP_RAND_uninstantiate(drbg->rand))
466         return 0;
467
468     /* The reset uses the default values for type and flags */
469     if (drbg->flags & RAND_DRBG_FLAG_MASTER)
470         index = RAND_DRBG_TYPE_MASTER;
471     else if (drbg->flags & RAND_DRBG_FLAG_PRIVATE)
472         index = RAND_DRBG_TYPE_PRIVATE;
473     else if (drbg->flags & RAND_DRBG_FLAG_PUBLIC)
474         index = RAND_DRBG_TYPE_PUBLIC;
475
476     if (index != -1) {
477         flags = rand_drbg_flags[index];
478         type = rand_drbg_type[index];
479     } else {
480         flags = drbg->flags;
481         type = drbg->type;
482     }
483     return RAND_DRBG_set(drbg, type, flags);
484 }
485
486 /*
487  * Reseed |drbg|, mixing in the specified data
488  *
489  * Requires that drbg->lock is already locked for write, if non-null.
490  *
491  * Returns 1 on success, 0 on failure.
492  */
493 int RAND_DRBG_reseed(RAND_DRBG *drbg,
494                      const unsigned char *adin, size_t adinlen,
495                      int prediction_resistance)
496 {
497     return EVP_RAND_reseed(drbg->rand, prediction_resistance, NULL, 0,
498                            adin, adinlen);
499 }
500
501 /*
502  * Generate |outlen| bytes into the buffer at |out|.  Reseed if we need
503  * to or if |prediction_resistance| is set.  Additional input can be
504  * sent in |adin| and |adinlen|.
505  *
506  * Requires that drbg->lock is already locked for write, if non-null.
507  *
508  * Returns 1 on success, 0 on failure.
509  *
510  */
511 int RAND_DRBG_generate(RAND_DRBG *drbg, unsigned char *out, size_t outlen,
512                        int prediction_resistance,
513                        const unsigned char *adin, size_t adinlen)
514 {
515     return EVP_RAND_generate(drbg->rand, out, outlen, 0,
516                              prediction_resistance, adin, adinlen);
517 }
518
519 /*
520  * Generates |outlen| random bytes and stores them in |out|. It will
521  * using the given |drbg| to generate the bytes.
522  *
523  * Requires that drbg->lock is already locked for write, if non-null.
524  *
525  * Returns 1 on success 0 on failure.
526  */
527 int RAND_DRBG_bytes(RAND_DRBG *drbg, unsigned char *out, size_t outlen)
528 {
529     return EVP_RAND_generate(drbg->rand, out, outlen, 0, 0, NULL, 0);
530 }
531
532 /* DRBG call back shims */
533 static int rand_drbg_get_entroy_cb(const OSSL_PARAM *params, OSSL_PARAM *out,
534                                    void *vdrbg)
535 {
536     RAND_DRBG *drbg = (RAND_DRBG *)vdrbg;
537     int entropy = 0, prediction_resistance = 0;
538     size_t min_len = 0, max_len = 2048;
539     const OSSL_PARAM *p;
540     OSSL_PARAM *q;
541
542     if (drbg->get_entropy == NULL)
543         return 0;
544
545     p = OSSL_PARAM_locate_const(params, OSSL_DRBG_PARAM_ENTROPY_REQUIRED);
546     if (p == NULL || !OSSL_PARAM_get_int(p, &entropy))
547         return 0;
548
549     p = OSSL_PARAM_locate_const(params, OSSL_DRBG_PARAM_PREDICTION_RESISTANCE);
550     if (p == NULL || !OSSL_PARAM_get_int(p, &prediction_resistance))
551         return 0;
552
553     p = OSSL_PARAM_locate_const(params, OSSL_DRBG_PARAM_MAX_LENGTH);
554     if (p == NULL || !OSSL_PARAM_get_size_t(p, &max_len))
555         return 0;
556
557     p = OSSL_PARAM_locate_const(params, OSSL_DRBG_PARAM_MIN_LENGTH);
558     if (p == NULL || !OSSL_PARAM_get_size_t(p, &min_len))
559         return 0;
560
561     q = OSSL_PARAM_locate(out, OSSL_DRBG_PARAM_RANDOM_DATA);
562     if (q == NULL || q->data_type != OSSL_PARAM_OCTET_PTR || q->data == NULL)
563         return 0;
564
565     q->return_size = drbg->get_entropy(drbg, (unsigned char **)q->data, entropy,
566                                        min_len, max_len, prediction_resistance);
567     return 1;
568 }
569
570 static int rand_drbg_cleanup_entropy_cb(const OSSL_PARAM *params, void *vdrbg)
571 {
572     RAND_DRBG *drbg = (RAND_DRBG *)vdrbg;
573     const OSSL_PARAM *p;
574     size_t sz;
575
576     if (drbg->cleanup_entropy == NULL)
577         return 0;
578
579     p = OSSL_PARAM_locate_const(params, OSSL_DRBG_PARAM_SIZE);
580     if (p == NULL || !OSSL_PARAM_get_size_t(p, &sz))
581         return 0;
582
583     p = OSSL_PARAM_locate_const(params, OSSL_DRBG_PARAM_RANDOM_DATA);
584     if (p == NULL || p->data_type != OSSL_PARAM_OCTET_PTR)
585         return 0;
586
587     drbg->cleanup_entropy(drbg, p->data, sz);
588     return 1;
589 }
590
591 static int rand_drbg_get_nonce_cb(const OSSL_PARAM *params, OSSL_PARAM *out,
592                                   void *vdrbg)
593 {
594     RAND_DRBG *drbg = (RAND_DRBG *)vdrbg;
595     int entropy = 0;
596     size_t min_len = 0, max_len = 10240;
597     const OSSL_PARAM *p;
598     OSSL_PARAM *q;
599
600     if (drbg->get_nonce == NULL)
601         return 0;
602
603     p = OSSL_PARAM_locate_const(params, OSSL_DRBG_PARAM_ENTROPY_REQUIRED);
604     if (p == NULL || !OSSL_PARAM_get_int(p, &entropy))
605         return 0;
606
607     p = OSSL_PARAM_locate_const(params, OSSL_DRBG_PARAM_MAX_LENGTH);
608     if (p == NULL || !OSSL_PARAM_get_size_t(p, &max_len))
609         return 0;
610
611     p = OSSL_PARAM_locate_const(params, OSSL_DRBG_PARAM_MIN_LENGTH);
612     if (p == NULL || !OSSL_PARAM_get_size_t(p, &min_len))
613         return 0;
614
615     q = OSSL_PARAM_locate(out, OSSL_DRBG_PARAM_RANDOM_DATA);
616     if (q == NULL || q->data_type != OSSL_PARAM_OCTET_PTR || q->data == NULL)
617         return 0;
618
619     q->return_size = drbg->get_nonce(drbg, (unsigned char **)q->data, entropy,
620                                      min_len, max_len);
621     return 1;
622 }
623
624 static int rand_drbg_cleanup_nonce_cb(const OSSL_PARAM *params, void *vdrbg)
625 {
626     RAND_DRBG *drbg = (RAND_DRBG *)vdrbg;
627     const OSSL_PARAM *p;
628     size_t sz;
629
630     if (drbg->cleanup_nonce == NULL)
631         return 0;
632
633     p = OSSL_PARAM_locate_const(params, OSSL_DRBG_PARAM_SIZE);
634     if (p == NULL || !OSSL_PARAM_get_size_t(p, &sz))
635         return 0;
636
637     p = OSSL_PARAM_locate_const(params, OSSL_DRBG_PARAM_RANDOM_DATA);
638     if (p == NULL || p->data_type != OSSL_PARAM_OCTET_PTR)
639         return 0;
640
641     drbg->cleanup_nonce(drbg, p->data, sz);
642     return 1;
643 }
644
645 /*
646  * Set the RAND_DRBG callbacks for obtaining entropy and nonce.
647  *
648  * Setting the callbacks is allowed only if the drbg has not been
649  * initialized yet. Otherwise, the operation will fail.
650  *
651  * Returns 1 on success, 0 on failure.
652  */
653 int RAND_DRBG_set_callbacks(RAND_DRBG *drbg,
654                             RAND_DRBG_get_entropy_fn get_entropy,
655                             RAND_DRBG_cleanup_entropy_fn cleanup_entropy,
656                             RAND_DRBG_get_nonce_fn get_nonce,
657                             RAND_DRBG_cleanup_nonce_fn cleanup_nonce)
658 {
659     EVP_RAND_CTX *rand = drbg->rand;
660     OSSL_INOUT_CALLBACK *g_ent = NULL, *g_nonce = NULL;
661     OSSL_CALLBACK *c_ent = NULL, *c_nonce = NULL;
662
663     if (get_entropy != NULL) {
664         g_ent = &rand_drbg_get_entroy_cb;
665         c_ent = &rand_drbg_cleanup_entropy_cb;
666     }
667     if (get_nonce != NULL) {
668         g_nonce = rand_drbg_get_nonce_cb;
669         c_nonce = rand_drbg_cleanup_nonce_cb;
670     }
671     if (!EVP_RAND_set_callbacks(rand, g_ent, c_ent, g_nonce, c_nonce, drbg))
672         return 0;
673
674     drbg->get_entropy = g_ent != NULL ? get_entropy : NULL;
675     drbg->cleanup_entropy = c_ent != NULL ? cleanup_entropy : NULL;
676     drbg->get_nonce = g_nonce != NULL ? get_nonce : NULL;
677     drbg->cleanup_nonce = c_nonce != NULL ? cleanup_nonce : NULL;
678     return 1;
679 }
680
681 /*
682  * Set the reseed interval.
683  *
684  * The drbg will reseed automatically whenever the number of generate
685  * requests exceeds the given reseed interval. If the reseed interval
686  * is 0, then this feature is disabled.
687  *
688  * Returns 1 on success, 0 on failure.
689  */
690 int RAND_DRBG_set_reseed_interval(RAND_DRBG *drbg, unsigned int interval)
691 {
692     OSSL_PARAM params[2] = { OSSL_PARAM_END, OSSL_PARAM_END };
693
694     if (interval > MAX_RESEED_INTERVAL)
695         return 0;
696     params[0] = OSSL_PARAM_construct_uint(OSSL_DRBG_PARAM_RESEED_REQUESTS,
697                                           &interval);
698     return EVP_RAND_set_ctx_params(drbg->rand, params);
699 }
700
701 /*
702  * Set the reseed time interval.
703  *
704  * The drbg will reseed automatically whenever the time elapsed since
705  * the last reseeding exceeds the given reseed time interval. For safety,
706  * a reseeding will also occur if the clock has been reset to a smaller
707  * value.
708  *
709  * Returns 1 on success, 0 on failure.
710  */
711 int RAND_DRBG_set_reseed_time_interval(RAND_DRBG *drbg, time_t interval)
712 {
713     OSSL_PARAM params[2] = { OSSL_PARAM_END, OSSL_PARAM_END };
714
715     if (interval > MAX_RESEED_TIME_INTERVAL)
716         return 0;
717     params[0] =
718         OSSL_PARAM_construct_time_t(OSSL_DRBG_PARAM_RESEED_TIME_INTERVAL,
719                                     &interval);
720     return EVP_RAND_set_ctx_params(drbg->rand, params);
721 }
722
723 /*
724  * Set the default values for reseed (time) intervals of new DRBG instances
725  *
726  * The default values can be set independently for master DRBG instances
727  * (without a parent) and slave DRBG instances (with parent).
728  *
729  * Returns 1 on success, 0 on failure.
730  */
731
732 int RAND_DRBG_set_reseed_defaults(
733                                   unsigned int _master_reseed_interval,
734                                   unsigned int _slave_reseed_interval,
735                                   time_t _master_reseed_time_interval,
736                                   time_t _slave_reseed_time_interval
737                                   )
738 {
739     if (_master_reseed_interval > MAX_RESEED_INTERVAL
740         || _slave_reseed_interval > MAX_RESEED_INTERVAL)
741         return 0;
742
743     if (_master_reseed_time_interval > MAX_RESEED_TIME_INTERVAL
744         || _slave_reseed_time_interval > MAX_RESEED_TIME_INTERVAL)
745         return 0;
746
747     master_reseed_interval = _master_reseed_interval;
748     slave_reseed_interval = _slave_reseed_interval;
749
750     master_reseed_time_interval = _master_reseed_time_interval;
751     slave_reseed_time_interval = _slave_reseed_time_interval;
752
753     return 1;
754 }
755
756 /*
757  * Get and set the EXDATA
758  */
759 int RAND_DRBG_set_ex_data(RAND_DRBG *drbg, int idx, void *arg)
760 {
761     return CRYPTO_set_ex_data(&drbg->ex_data, idx, arg);
762 }
763
764 void *RAND_DRBG_get_ex_data(const RAND_DRBG *drbg, int idx)
765 {
766     return CRYPTO_get_ex_data(&drbg->ex_data, idx);
767 }
768
769 /*
770  * The following functions provide a RAND_METHOD that works on the
771  * global DRBG.  They lock.
772  */
773
774 /*
775  * Allocates a new global DRBG on the secure heap (if enabled) and
776  * initializes it with default settings.
777  *
778  * Returns a pointer to the new DRBG instance on success, NULL on failure.
779  */
780 static RAND_DRBG *drbg_setup(OPENSSL_CTX *ctx, RAND_DRBG *parent, int drbg_type)
781 {
782     RAND_DRBG *drbg;
783
784     drbg = RAND_DRBG_new_ex(ctx, rand_drbg_type[drbg_type],
785                             rand_drbg_flags[drbg_type], parent);
786     if (drbg == NULL)
787         return NULL;
788
789     /* Only the master DRBG needs to have a lock */
790     if (parent == NULL && EVP_RAND_enable_locking(drbg->rand) == 0)
791         goto err;
792
793     /*
794      * Ignore instantiation error to support just-in-time instantiation.
795      *
796      * The state of the drbg will be checked in RAND_DRBG_generate() and
797      * an automatic recovery is attempted.
798      */
799     (void)RAND_DRBG_instantiate(drbg, NULL, 0);
800     return drbg;
801
802 err:
803     RAND_DRBG_free(drbg);
804     return NULL;
805 }
806
807 static void drbg_delete_thread_state(void *arg)
808 {
809     OPENSSL_CTX *ctx = arg;
810     DRBG_GLOBAL *dgbl = drbg_get_global(ctx);
811     RAND_DRBG *drbg;
812
813     if (dgbl == NULL)
814         return;
815     drbg = CRYPTO_THREAD_get_local(&dgbl->public_drbg);
816     CRYPTO_THREAD_set_local(&dgbl->public_drbg, NULL);
817     RAND_DRBG_free(drbg);
818
819     drbg = CRYPTO_THREAD_get_local(&dgbl->private_drbg);
820     CRYPTO_THREAD_set_local(&dgbl->private_drbg, NULL);
821     RAND_DRBG_free(drbg);
822 }
823
824 /* Implements the default OpenSSL RAND_bytes() method */
825 static int drbg_bytes(unsigned char *out, int count)
826 {
827     int ret;
828     RAND_DRBG *drbg = RAND_DRBG_get0_public();
829
830     if (drbg == NULL)
831         return 0;
832
833     ret = RAND_DRBG_bytes(drbg, out, count);
834
835     return ret;
836 }
837
838 /* Implements the default OpenSSL RAND_add() method */
839 static int drbg_add(const void *buf, int num, double randomness)
840 {
841     RAND_DRBG *drbg = RAND_DRBG_get0_master();
842
843     if (drbg == NULL || num <= 0)
844         return 0;
845
846     return EVP_RAND_reseed(drbg->rand, 0, NULL, 0, buf, num);
847 }
848
849 /* Implements the default OpenSSL RAND_seed() method */
850 static int drbg_seed(const void *buf, int num)
851 {
852     return drbg_add(buf, num, num);
853 }
854
855 /* Implements the default OpenSSL RAND_status() method */
856 static int drbg_status(void)
857 {
858     int ret;
859     RAND_DRBG *drbg = RAND_DRBG_get0_master();
860
861     if (drbg == NULL)
862         return 0;
863
864     ret = EVP_RAND_state(drbg->rand) == EVP_RAND_STATE_READY ? 1 : 0;
865     return ret;
866 }
867
868 int RAND_DRBG_verify_zeroization(RAND_DRBG *drbg)
869 {
870     return EVP_RAND_verify_zeroization(drbg->rand);
871 }
872
873 /*
874  * Get the master DRBG.
875  * Returns pointer to the DRBG on success, NULL on failure.
876  *
877  */
878 RAND_DRBG *OPENSSL_CTX_get0_master_drbg(OPENSSL_CTX *ctx)
879 {
880     DRBG_GLOBAL *dgbl = drbg_get_global(ctx);
881
882     if (dgbl == NULL)
883         return NULL;
884
885     if (dgbl->master_drbg == NULL) {
886         if (!CRYPTO_THREAD_write_lock(dgbl->lock))
887             return NULL;
888         if (dgbl->master_drbg == NULL)
889             dgbl->master_drbg = drbg_setup(ctx, NULL, RAND_DRBG_TYPE_MASTER);
890         CRYPTO_THREAD_unlock(dgbl->lock);
891     }
892     return dgbl->master_drbg;
893 }
894
895 RAND_DRBG *RAND_DRBG_get0_master(void)
896 {
897     return OPENSSL_CTX_get0_master_drbg(NULL);
898 }
899
900 /*
901  * Get the public DRBG.
902  * Returns pointer to the DRBG on success, NULL on failure.
903  */
904 RAND_DRBG *OPENSSL_CTX_get0_public_drbg(OPENSSL_CTX *ctx)
905 {
906     DRBG_GLOBAL *dgbl = drbg_get_global(ctx);
907     RAND_DRBG *drbg, *master;
908
909     if (dgbl == NULL)
910         return NULL;
911
912     drbg = CRYPTO_THREAD_get_local(&dgbl->public_drbg);
913     if (drbg == NULL) {
914         master = OPENSSL_CTX_get0_master_drbg(ctx);
915         if (master == NULL)
916             return NULL;
917
918         ctx = openssl_ctx_get_concrete(ctx);
919         /*
920          * If the private_drbg is also NULL then this is the first time we've
921          * used this thread.
922          */
923         if (CRYPTO_THREAD_get_local(&dgbl->private_drbg) == NULL
924                 && !ossl_init_thread_start(NULL, ctx, drbg_delete_thread_state))
925             return NULL;
926         drbg = drbg_setup(ctx, master, RAND_DRBG_TYPE_PUBLIC);
927         CRYPTO_THREAD_set_local(&dgbl->public_drbg, drbg);
928     }
929     return drbg;
930 }
931
932 RAND_DRBG *RAND_DRBG_get0_public(void)
933 {
934     return OPENSSL_CTX_get0_public_drbg(NULL);
935 }
936
937 /*
938  * Get the private DRBG.
939  * Returns pointer to the DRBG on success, NULL on failure.
940  */
941 RAND_DRBG *OPENSSL_CTX_get0_private_drbg(OPENSSL_CTX *ctx)
942 {
943     DRBG_GLOBAL *dgbl = drbg_get_global(ctx);
944     RAND_DRBG *drbg, *master;
945
946     if (dgbl == NULL)
947         return NULL;
948
949     drbg = CRYPTO_THREAD_get_local(&dgbl->private_drbg);
950     if (drbg == NULL) {
951         master = OPENSSL_CTX_get0_master_drbg(ctx);
952         if (master == NULL)
953             return NULL;
954
955         ctx = openssl_ctx_get_concrete(ctx);
956         /*
957          * If the public_drbg is also NULL then this is the first time we've
958          * used this thread.
959          */
960         if (CRYPTO_THREAD_get_local(&dgbl->public_drbg) == NULL
961                 && !ossl_init_thread_start(NULL, ctx, drbg_delete_thread_state))
962             return NULL;
963         drbg = drbg_setup(ctx, master, RAND_DRBG_TYPE_PRIVATE);
964         CRYPTO_THREAD_set_local(&dgbl->private_drbg, drbg);
965     }
966     return drbg;
967 }
968
969 RAND_DRBG *RAND_DRBG_get0_private(void)
970 {
971     return OPENSSL_CTX_get0_private_drbg(NULL);
972 }
973
974 RAND_METHOD rand_meth = {
975     drbg_seed,
976     drbg_bytes,
977     NULL,
978     drbg_add,
979     drbg_bytes,
980     drbg_status
981 };
982
983 RAND_METHOD *RAND_OpenSSL(void)
984 {
985 #ifndef FIPS_MODULE
986     return &rand_meth;
987 #else
988     return NULL;
989 #endif
990 }