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