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