b7f7e4c3412e1cc3989227e4c24fc6bf30eda79d
[openssl.git] / crypto / rand / drbg_lib.c
1 /*
2  * Copyright 2011-2017 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 static RAND_DRBG rand_drbg; /* The default global DRBG. */
19 static RAND_DRBG priv_drbg; /* The global private-key DRBG. */
20
21 /*
22  * Support framework for NIST SP 800-90A DRBG, AES-CTR mode.
23  * The RAND_DRBG is OpenSSL's pointer to an instance of the DRBG.
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 static CRYPTO_ONCE rand_init_drbg = CRYPTO_ONCE_STATIC_INIT;
34
35 /*
36  * Set/initialize |drbg| to be of type |nid|, with optional |flags|.
37  * Return -2 if the type is not supported, 1 on success and -1 on
38  * failure.
39  */
40 int RAND_DRBG_set(RAND_DRBG *drbg, int nid, unsigned int flags)
41 {
42     int ret = 1;
43
44     drbg->state = DRBG_UNINITIALISED;
45     drbg->flags = flags;
46     drbg->nid = nid;
47
48     switch (nid) {
49     default:
50         RANDerr(RAND_F_RAND_DRBG_SET, RAND_R_UNSUPPORTED_DRBG_TYPE);
51         return -2;
52     case 0:
53         /* Uninitialized; that's okay. */
54         return 1;
55     case NID_aes_128_ctr:
56     case NID_aes_192_ctr:
57     case NID_aes_256_ctr:
58         ret = ctr_init(drbg);
59         break;
60     }
61
62     if (ret < 0)
63         RANDerr(RAND_F_RAND_DRBG_SET, RAND_R_ERROR_INITIALISING_DRBG);
64     return ret;
65 }
66
67 /*
68  * Allocate memory and initialize a new DRBG.  The |parent|, if not
69  * NULL, will be used to auto-seed this RAND_DRBG as needed.
70  */
71 RAND_DRBG *RAND_DRBG_new(int type, unsigned int flags, RAND_DRBG *parent)
72 {
73     RAND_DRBG *drbg = OPENSSL_zalloc(sizeof(*drbg));
74
75     if (drbg == NULL) {
76         RANDerr(RAND_F_RAND_DRBG_NEW, ERR_R_MALLOC_FAILURE);
77         goto err;
78     }
79     drbg->size = RANDOMNESS_NEEDED;
80     drbg->fork_count = rand_fork_count;
81     drbg->parent = parent;
82     if (RAND_DRBG_set(drbg, type, flags) < 0)
83         goto err;
84
85     if (parent != NULL) {
86         if (!RAND_DRBG_set_callbacks(drbg, drbg_entropy_from_parent,
87                                      drbg_release_entropy,
88                                      NULL, NULL))
89             goto err;
90     }
91
92     return drbg;
93
94 err:
95     OPENSSL_free(drbg);
96     return NULL;
97 }
98
99 /*
100  * Uninstantiate |drbg| and free all memory.
101  */
102 void RAND_DRBG_free(RAND_DRBG *drbg)
103 {
104     /* The global DRBG is free'd by rand_cleanup_drbg_int() */
105     if (drbg == NULL || drbg == &rand_drbg)
106         return;
107
108     ctr_uninstantiate(drbg);
109     CRYPTO_free_ex_data(CRYPTO_EX_INDEX_DRBG, drbg, &drbg->ex_data);
110     OPENSSL_clear_free(drbg, sizeof(*drbg));
111 }
112
113 /*
114  * Instantiate |drbg|, after it has been initialized.  Use |pers| and
115  * |perslen| as prediction-resistance input.
116  */
117 int RAND_DRBG_instantiate(RAND_DRBG *drbg,
118                           const unsigned char *pers, size_t perslen)
119 {
120     unsigned char *nonce = NULL, *entropy = NULL;
121     size_t noncelen = 0, entropylen = 0;
122
123     if (perslen > drbg->max_perslen) {
124         RANDerr(RAND_F_RAND_DRBG_INSTANTIATE,
125                 RAND_R_PERSONALISATION_STRING_TOO_LONG);
126         goto end;
127     }
128     if (drbg->state != DRBG_UNINITIALISED) {
129         RANDerr(RAND_F_RAND_DRBG_INSTANTIATE,
130                 drbg->state == DRBG_ERROR ? RAND_R_IN_ERROR_STATE
131                                           : RAND_R_ALREADY_INSTANTIATED);
132         goto end;
133     }
134
135     drbg->state = DRBG_ERROR;
136     if (drbg->get_entropy != NULL)
137         entropylen = drbg->get_entropy(drbg, &entropy, drbg->strength,
138                                    drbg->min_entropylen, drbg->max_entropylen);
139     if (entropylen < drbg->min_entropylen || entropylen > drbg->max_entropylen) {
140         RANDerr(RAND_F_RAND_DRBG_INSTANTIATE, RAND_R_ERROR_RETRIEVING_ENTROPY);
141         goto end;
142     }
143
144     if (drbg->max_noncelen > 0 && drbg->get_nonce != NULL) {
145         noncelen = drbg->get_nonce(drbg, &nonce, drbg->strength / 2,
146                                    drbg->min_noncelen, drbg->max_noncelen);
147         if (noncelen < drbg->min_noncelen || noncelen > drbg->max_noncelen) {
148             RANDerr(RAND_F_RAND_DRBG_INSTANTIATE, RAND_R_ERROR_RETRIEVING_NONCE);
149             goto end;
150         }
151     }
152
153     if (!ctr_instantiate(drbg, entropy, entropylen,
154                          nonce, noncelen, pers, perslen)) {
155         RANDerr(RAND_F_RAND_DRBG_INSTANTIATE, RAND_R_ERROR_INSTANTIATING_DRBG);
156         goto end;
157     }
158
159     drbg->state = DRBG_READY;
160     drbg->reseed_counter = 1;
161
162 end:
163     if (entropy != NULL && drbg->cleanup_entropy != NULL)
164         drbg->cleanup_entropy(drbg, entropy, entropylen);
165     if (nonce != NULL && drbg->cleanup_nonce!= NULL )
166         drbg->cleanup_nonce(drbg, nonce, noncelen);
167     if (drbg->state == DRBG_READY)
168         return 1;
169     return 0;
170 }
171
172 /*
173  * Uninstantiate |drbg|. Must be instantiated before it can be used.
174  */
175 int RAND_DRBG_uninstantiate(RAND_DRBG *drbg)
176 {
177     int ret = ctr_uninstantiate(drbg);
178
179     OPENSSL_cleanse(&drbg->ctr, sizeof(drbg->ctr));
180     drbg->state = DRBG_UNINITIALISED;
181     return ret;
182 }
183
184 /*
185  * Mix in the specified data to reseed |drbg|.
186  */
187 int RAND_DRBG_reseed(RAND_DRBG *drbg,
188                      const unsigned char *adin, size_t adinlen)
189 {
190     unsigned char *entropy = NULL;
191     size_t entropylen = 0;
192
193     if (drbg->state == DRBG_ERROR) {
194         RANDerr(RAND_F_RAND_DRBG_RESEED, RAND_R_IN_ERROR_STATE);
195         return 0;
196     }
197     if (drbg->state == DRBG_UNINITIALISED) {
198         RANDerr(RAND_F_RAND_DRBG_RESEED, RAND_R_NOT_INSTANTIATED);
199         return 0;
200     }
201
202     if (adin == NULL)
203         adinlen = 0;
204     else if (adinlen > drbg->max_adinlen) {
205         RANDerr(RAND_F_RAND_DRBG_RESEED, RAND_R_ADDITIONAL_INPUT_TOO_LONG);
206         return 0;
207     }
208
209     drbg->state = DRBG_ERROR;
210     if (drbg->get_entropy != NULL)
211         entropylen = drbg->get_entropy(drbg, &entropy, drbg->strength,
212                                    drbg->min_entropylen, drbg->max_entropylen);
213     if (entropylen < drbg->min_entropylen || entropylen > drbg->max_entropylen) {
214         RANDerr(RAND_F_RAND_DRBG_RESEED, RAND_R_ERROR_RETRIEVING_ENTROPY);
215         goto end;
216     }
217
218     if (!ctr_reseed(drbg, entropy, entropylen, adin, adinlen))
219         goto end;
220     drbg->state = DRBG_READY;
221     drbg->reseed_counter = 1;
222
223 end:
224     if (entropy != NULL && drbg->cleanup_entropy != NULL)
225         drbg->cleanup_entropy(drbg, entropy, entropylen);
226     if (drbg->state == DRBG_READY)
227         return 1;
228     return 0;
229 }
230
231 /*
232  * Generate |outlen| bytes into the buffer at |out|.  Reseed if we need
233  * to or if |prediction_resistance| is set.  Additional input can be
234  * sent in |adin| and |adinlen|.
235  */
236 int RAND_DRBG_generate(RAND_DRBG *drbg, unsigned char *out, size_t outlen,
237                        int prediction_resistance,
238                        const unsigned char *adin, size_t adinlen)
239 {
240     if (drbg->state == DRBG_ERROR) {
241         RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_IN_ERROR_STATE);
242         return 0;
243     }
244     if (drbg->state == DRBG_UNINITIALISED) {
245         RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_NOT_INSTANTIATED);
246         return 0;
247     }
248     if (outlen > drbg->max_request) {
249         RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_REQUEST_TOO_LARGE_FOR_DRBG);
250         return 0;
251     }
252     if (adinlen > drbg->max_adinlen) {
253         RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_ADDITIONAL_INPUT_TOO_LONG);
254         return 0;
255     }
256
257     if (drbg->fork_count != rand_fork_count) {
258         drbg->fork_count = rand_fork_count;
259         drbg->state = DRBG_RESEED;
260     }
261
262     if (drbg->reseed_counter >= drbg->reseed_interval)
263         drbg->state = DRBG_RESEED;
264
265     if (drbg->state == DRBG_RESEED || prediction_resistance) {
266         if (!RAND_DRBG_reseed(drbg, adin, adinlen)) {
267             RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_RESEED_ERROR);
268             return 0;
269         }
270         adin = NULL;
271         adinlen = 0;
272     }
273
274     if (!ctr_generate(drbg, out, outlen, adin, adinlen)) {
275         drbg->state = DRBG_ERROR;
276         RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_GENERATE_ERROR);
277         return 0;
278     }
279
280     if (drbg->reseed_counter >= drbg->reseed_interval)
281         drbg->state = DRBG_RESEED;
282     else
283         drbg->reseed_counter++;
284     return 1;
285 }
286
287 /*
288  * Set the callbacks for entropy and nonce.  We currently don't use
289  * the nonce; that's mainly for the KATs
290  */
291 int RAND_DRBG_set_callbacks(RAND_DRBG *drbg,
292                             RAND_DRBG_get_entropy_fn cb_get_entropy,
293                             RAND_DRBG_cleanup_entropy_fn cb_cleanup_entropy,
294                             RAND_DRBG_get_nonce_fn cb_get_nonce,
295                             RAND_DRBG_cleanup_nonce_fn cb_cleanup_nonce)
296 {
297     if (drbg->state != DRBG_UNINITIALISED)
298         return 0;
299     drbg->get_entropy = cb_get_entropy;
300     drbg->cleanup_entropy = cb_cleanup_entropy;
301     drbg->get_nonce = cb_get_nonce;
302     drbg->cleanup_nonce = cb_cleanup_nonce;
303     return 1;
304 }
305
306 /*
307  * Set the reseed interval.
308  */
309 int RAND_DRBG_set_reseed_interval(RAND_DRBG *drbg, int interval)
310 {
311     if (interval < 0 || interval > MAX_RESEED)
312         return 0;
313     drbg->reseed_interval = interval;
314     return 1;
315 }
316
317 /*
318  * Get and set the EXDATA
319  */
320 int RAND_DRBG_set_ex_data(RAND_DRBG *drbg, int idx, void *arg)
321 {
322     return CRYPTO_set_ex_data(&drbg->ex_data, idx, arg);
323 }
324
325 void *RAND_DRBG_get_ex_data(const RAND_DRBG *drbg, int idx)
326 {
327     return CRYPTO_get_ex_data(&drbg->ex_data, idx);
328 }
329
330
331 /*
332  * The following functions provide a RAND_METHOD that works on the
333  * global DRBG.  They lock.
334  */
335
336 /*
337  * Creates a global DRBG with default settings.
338  * Returns 1 on success, 0 on failure
339  */
340 static int setup_drbg(RAND_DRBG *drbg, const char *name)
341 {
342     int ret = 1;
343
344     drbg->lock = CRYPTO_THREAD_glock_new(name);
345     ret &= drbg->lock != NULL;
346     drbg->size = RANDOMNESS_NEEDED;
347     drbg->secure = CRYPTO_secure_malloc_initialized();
348     /* If you change these parameters, see RANDOMNESS_NEEDED */
349     ret &= RAND_DRBG_set(drbg,
350                          NID_aes_128_ctr, RAND_DRBG_FLAG_CTR_USE_DF) == 1;
351     ret &= RAND_DRBG_set_callbacks(drbg, drbg_entropy_from_system,
352                                    drbg_release_entropy, NULL, NULL) == 1;
353     ret &= RAND_DRBG_instantiate(drbg, NULL, 0) == 1;
354     return ret;
355 }
356
357 /*
358  * Initialize the global DRBGs on first use.
359  * Returns 1 on success, 0 on failure.
360  */
361 DEFINE_RUN_ONCE_STATIC(do_rand_init_drbg)
362 {
363     int ret = 1;
364
365     ret &= setup_drbg(&rand_drbg, "rand_drbg");
366     ret &= setup_drbg(&priv_drbg, "priv_drbg");
367
368     return ret;
369 }
370
371 /* Clean up a DRBG and free it */
372 static void free_drbg(RAND_DRBG *drbg)
373 {
374     CRYPTO_THREAD_lock_free(drbg->lock);
375     RAND_DRBG_uninstantiate(drbg);
376 }
377
378 /* Clean up the global DRBGs before exit */
379 void rand_cleanup_drbg_int(void)
380 {
381     free_drbg(&rand_drbg);
382     free_drbg(&priv_drbg);
383 }
384
385 static int drbg_bytes(unsigned char *out, int count)
386 {
387     int ret = 0;
388     size_t chunk;
389     RAND_DRBG *drbg = RAND_DRBG_get0_global();
390
391     if (drbg == NULL)
392         return 0;
393
394     CRYPTO_THREAD_write_lock(drbg->lock);
395     if (drbg->state == DRBG_UNINITIALISED)
396         goto err;
397
398     for ( ; count > 0; count -= chunk, out += chunk) {
399         chunk = count;
400         if (chunk > drbg->max_request)
401             chunk = drbg->max_request;
402         ret = RAND_DRBG_generate(drbg, out, chunk, 0, NULL, 0);
403         if (!ret)
404             goto err;
405     }
406     ret = 1;
407
408 err:
409     CRYPTO_THREAD_unlock(drbg->lock);
410     return ret;
411 }
412
413 static int drbg_add(const void *buf, int num, double randomness)
414 {
415     unsigned char *in = (unsigned char *)buf;
416     unsigned char *out, *end;
417
418     CRYPTO_THREAD_write_lock(rand_bytes.lock);
419     out = &rand_bytes.buff[rand_bytes.curr];
420     end = &rand_bytes.buff[rand_bytes.size];
421
422     /* Copy whatever fits into the end of the buffer. */
423     for ( ; --num >= 0 && out < end; rand_bytes.curr++)
424         *out++ = *in++;
425
426     /* XOR any the leftover. */
427     while (num > 0) {
428         for (out = rand_bytes.buff; --num >= 0 && out < end; )
429             *out++ ^= *in++;
430     }
431
432     CRYPTO_THREAD_unlock(rand_bytes.lock);
433     return 1;
434 }
435
436 static int drbg_seed(const void *buf, int num)
437 {
438     return drbg_add(buf, num, num);
439 }
440
441 static int drbg_status(void)
442 {
443     int ret;
444     RAND_DRBG *drbg = RAND_DRBG_get0_global();
445
446     if (drbg == NULL)
447         return 0;
448
449     CRYPTO_THREAD_write_lock(drbg->lock);
450     ret = drbg->state == DRBG_READY ? 1 : 0;
451     CRYPTO_THREAD_unlock(drbg->lock);
452     return ret;
453 }
454
455 /*
456  * Get the global public DRBG.
457  * Returns pointer to the DRBG on success, NULL on failure.
458  */
459 RAND_DRBG *RAND_DRBG_get0_global(void)
460 {
461     if (!RUN_ONCE(&rand_init_drbg, do_rand_init_drbg))
462         return NULL;
463
464     return &rand_drbg;
465 }
466
467 /*
468  * Get the global private DRBG.
469  * Returns pointer to the DRBG on success, NULL on failure.
470  */
471 RAND_DRBG *RAND_DRBG_get0_priv_global(void)
472 {
473     if (!RUN_ONCE(&rand_init_drbg, do_rand_init_drbg))
474         return NULL;
475
476     return &priv_drbg;
477 }
478
479 RAND_METHOD rand_meth = {
480     drbg_seed,
481     drbg_bytes,
482     NULL,
483     drbg_add,
484     drbg_bytes,
485     drbg_status
486 };
487
488 RAND_METHOD *RAND_OpenSSL(void)
489 {
490     return &rand_meth;
491 }