a4c9e694726e749f7ce981364f192f0086d85b17
[openssl.git] / crypto / rand / rand_lib.c
1 /*
2  * Copyright 1995-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 <stdio.h>
11 #include <time.h>
12 #include "internal/cryptlib.h"
13 #include <openssl/opensslconf.h>
14 #include "crypto/rand.h"
15 #include <openssl/engine.h>
16 #include "internal/thread_once.h"
17 #include "rand_local.h"
18 #include "e_os.h"
19
20 #ifndef FIPS_MODULE
21 # ifndef OPENSSL_NO_ENGINE
22 /* non-NULL if default_RAND_meth is ENGINE-provided */
23 static ENGINE *funct_ref;
24 static CRYPTO_RWLOCK *rand_engine_lock;
25 # endif
26 static CRYPTO_RWLOCK *rand_meth_lock;
27 static const RAND_METHOD *default_RAND_meth;
28 static CRYPTO_ONCE rand_init = CRYPTO_ONCE_STATIC_INIT;
29
30 static int rand_inited = 0;
31 #endif /* FIPS_MODULE */
32
33 #ifdef OPENSSL_RAND_SEED_RDTSC
34 /*
35  * IMPORTANT NOTE:  It is not currently possible to use this code
36  * because we are not sure about the amount of randomness it provides.
37  * Some SP900 tests have been run, but there is internal skepticism.
38  * So for now this code is not used.
39  */
40 # error "RDTSC enabled?  Should not be possible!"
41
42 /*
43  * Acquire entropy from high-speed clock
44  *
45  * Since we get some randomness from the low-order bits of the
46  * high-speed clock, it can help.
47  *
48  * Returns the total entropy count, if it exceeds the requested
49  * entropy count. Otherwise, returns an entropy count of 0.
50  */
51 size_t rand_acquire_entropy_from_tsc(RAND_POOL *pool)
52 {
53     unsigned char c;
54     int i;
55
56     if ((OPENSSL_ia32cap_P[0] & (1 << 4)) != 0) {
57         for (i = 0; i < TSC_READ_COUNT; i++) {
58             c = (unsigned char)(OPENSSL_rdtsc() & 0xFF);
59             rand_pool_add(pool, &c, 1, 4);
60         }
61     }
62     return rand_pool_entropy_available(pool);
63 }
64 #endif
65
66 #ifdef OPENSSL_RAND_SEED_RDCPU
67 size_t OPENSSL_ia32_rdseed_bytes(unsigned char *buf, size_t len);
68 size_t OPENSSL_ia32_rdrand_bytes(unsigned char *buf, size_t len);
69
70 /*
71  * Acquire entropy using Intel-specific cpu instructions
72  *
73  * Uses the RDSEED instruction if available, otherwise uses
74  * RDRAND if available.
75  *
76  * For the differences between RDSEED and RDRAND, and why RDSEED
77  * is the preferred choice, see https://goo.gl/oK3KcN
78  *
79  * Returns the total entropy count, if it exceeds the requested
80  * entropy count. Otherwise, returns an entropy count of 0.
81  */
82 size_t rand_acquire_entropy_from_cpu(RAND_POOL *pool)
83 {
84     size_t bytes_needed;
85     unsigned char *buffer;
86
87     bytes_needed = rand_pool_bytes_needed(pool, 1 /*entropy_factor*/);
88     if (bytes_needed > 0) {
89         buffer = rand_pool_add_begin(pool, bytes_needed);
90
91         if (buffer != NULL) {
92             /* Whichever comes first, use RDSEED, RDRAND or nothing */
93             if ((OPENSSL_ia32cap_P[2] & (1 << 18)) != 0) {
94                 if (OPENSSL_ia32_rdseed_bytes(buffer, bytes_needed)
95                     == bytes_needed) {
96                     rand_pool_add_end(pool, bytes_needed, 8 * bytes_needed);
97                 }
98             } else if ((OPENSSL_ia32cap_P[1] & (1 << (62 - 32))) != 0) {
99                 if (OPENSSL_ia32_rdrand_bytes(buffer, bytes_needed)
100                     == bytes_needed) {
101                     rand_pool_add_end(pool, bytes_needed, 8 * bytes_needed);
102                 }
103             } else {
104                 rand_pool_add_end(pool, 0, 0);
105             }
106         }
107     }
108
109     return rand_pool_entropy_available(pool);
110 }
111 #endif
112
113 #if 0
114 /*
115  * Implements the get_entropy() callback (see RAND_DRBG_set_callbacks())
116  *
117  * If the DRBG has a parent, then the required amount of entropy input
118  * is fetched using the parent's RAND_DRBG_generate().
119  *
120  * Otherwise, the entropy is polled from the system entropy sources
121  * using rand_pool_acquire_entropy().
122  *
123  * If a random pool has been added to the DRBG using RAND_add(), then
124  * its entropy will be used up first.
125  */
126 size_t rand_drbg_get_entropy(RAND_DRBG *drbg,
127                              unsigned char **pout,
128                              int entropy, size_t min_len, size_t max_len,
129                              int prediction_resistance)
130 {
131     size_t ret = 0;
132     size_t entropy_available = 0;
133     RAND_POOL *pool;
134
135     if (drbg->parent != NULL && drbg->strength > drbg->parent->strength) {
136         /*
137          * We currently don't support the algorithm from NIST SP 800-90C
138          * 10.1.2 to use a weaker DRBG as source
139          */
140         RANDerr(RAND_F_RAND_DRBG_GET_ENTROPY, RAND_R_PARENT_STRENGTH_TOO_WEAK);
141         return 0;
142     }
143
144     if (drbg->seed_pool != NULL) {
145         pool = drbg->seed_pool;
146         pool->entropy_requested = entropy;
147     } else {
148         pool = rand_pool_new(entropy, drbg->secure, min_len, max_len);
149         if (pool == NULL)
150             return 0;
151     }
152
153     if (drbg->parent != NULL) {
154         size_t bytes_needed = rand_pool_bytes_needed(pool, 1 /*entropy_factor*/);
155         unsigned char *buffer = rand_pool_add_begin(pool, bytes_needed);
156
157         if (buffer != NULL) {
158             size_t bytes = 0;
159
160             /*
161              * Get random data from parent. Include our address as additional input,
162              * in order to provide some additional distinction between different
163              * DRBG child instances.
164              * Our lock is already held, but we need to lock our parent before
165              * generating bits from it. (Note: taking the lock will be a no-op
166              * if locking if drbg->parent->lock == NULL.)
167              */
168             rand_drbg_lock(drbg->parent);
169             if (RAND_DRBG_generate(drbg->parent,
170                                    buffer, bytes_needed,
171                                    prediction_resistance,
172                                    (unsigned char *)&drbg, sizeof(drbg)) != 0)
173                 bytes = bytes_needed;
174             drbg->reseed_next_counter
175                 = tsan_load(&drbg->parent->reseed_prop_counter);
176             rand_drbg_unlock(drbg->parent);
177
178             rand_pool_add_end(pool, bytes, 8 * bytes);
179             entropy_available = rand_pool_entropy_available(pool);
180         }
181
182     } else {
183         /* Get entropy by polling system entropy sources. */
184         entropy_available = rand_pool_acquire_entropy(pool);
185     }
186
187     if (entropy_available > 0) {
188         ret   = rand_pool_length(pool);
189         *pout = rand_pool_detach(pool);
190     }
191
192     if (drbg->seed_pool == NULL)
193         rand_pool_free(pool);
194     return ret;
195 }
196
197 /*
198  * Implements the cleanup_entropy() callback (see RAND_DRBG_set_callbacks())
199  *
200  */
201 void rand_drbg_cleanup_entropy(RAND_DRBG *drbg,
202                                unsigned char *out, size_t outlen)
203 {
204     if (drbg->seed_pool == NULL) {
205         if (drbg->secure)
206             OPENSSL_secure_clear_free(out, outlen);
207         else
208             OPENSSL_clear_free(out, outlen);
209     }
210 }
211
212 /*
213  * Generate additional data that can be used for the drbg. The data does
214  * not need to contain entropy, but it's useful if it contains at least
215  * some bits that are unpredictable.
216  *
217  * Returns 0 on failure.
218  *
219  * On success it allocates a buffer at |*pout| and returns the length of
220  * the data. The buffer should get freed using OPENSSL_secure_clear_free().
221  */
222 size_t rand_drbg_get_additional_data(RAND_POOL *pool, unsigned char **pout)
223 {
224     size_t ret = 0;
225
226     if (rand_pool_add_additional_data(pool) == 0)
227         goto err;
228
229     ret = rand_pool_length(pool);
230     *pout = rand_pool_detach(pool);
231
232  err:
233     return ret;
234 }
235
236 void rand_drbg_cleanup_additional_data(RAND_POOL *pool, unsigned char *out)
237 {
238     rand_pool_reattach(pool, out);
239 }
240 #endif
241
242 #ifndef FIPS_MODULE
243 DEFINE_RUN_ONCE_STATIC(do_rand_init)
244 {
245 # ifndef OPENSSL_NO_ENGINE
246     rand_engine_lock = CRYPTO_THREAD_lock_new();
247     if (rand_engine_lock == NULL)
248         return 0;
249 # endif
250
251     rand_meth_lock = CRYPTO_THREAD_lock_new();
252     if (rand_meth_lock == NULL)
253         goto err;
254
255     if (!rand_pool_init())
256         goto err;
257
258     rand_inited = 1;
259     return 1;
260
261  err:
262     CRYPTO_THREAD_lock_free(rand_meth_lock);
263     rand_meth_lock = NULL;
264 # ifndef OPENSSL_NO_ENGINE
265     CRYPTO_THREAD_lock_free(rand_engine_lock);
266     rand_engine_lock = NULL;
267 # endif
268     return 0;
269 }
270
271 void rand_cleanup_int(void)
272 {
273     const RAND_METHOD *meth = default_RAND_meth;
274
275     if (!rand_inited)
276         return;
277
278     if (meth != NULL && meth->cleanup != NULL)
279         meth->cleanup();
280     RAND_set_rand_method(NULL);
281     rand_pool_cleanup();
282 # ifndef OPENSSL_NO_ENGINE
283     CRYPTO_THREAD_lock_free(rand_engine_lock);
284     rand_engine_lock = NULL;
285 # endif
286     CRYPTO_THREAD_lock_free(rand_meth_lock);
287     rand_meth_lock = NULL;
288     rand_inited = 0;
289 }
290
291 /* TODO(3.0): Do we need to handle this somehow in the FIPS module? */
292 /*
293  * RAND_close_seed_files() ensures that any seed file descriptors are
294  * closed after use.
295  */
296 void RAND_keep_random_devices_open(int keep)
297 {
298     if (RUN_ONCE(&rand_init, do_rand_init))
299         rand_pool_keep_random_devices_open(keep);
300 }
301
302 /*
303  * RAND_poll() reseeds the default RNG using random input
304  *
305  * The random input is obtained from polling various entropy
306  * sources which depend on the operating system and are
307  * configurable via the --with-rand-seed configure option.
308  */
309 int RAND_poll(void)
310 {
311     int ret = 0;
312
313     const RAND_METHOD *meth = RAND_get_rand_method();
314
315     if (meth == NULL)
316         return 0;
317
318     if (meth == RAND_OpenSSL()) {
319         /* fill random pool and seed the master DRBG */
320         RAND_DRBG *drbg = RAND_DRBG_get0_master();
321
322         if (drbg == NULL)
323             return 0;
324
325 #if 0
326         ret = rand_drbg_restart(drbg, NULL, 0, 0);
327 #endif
328
329         return ret;
330
331     } else {
332         RAND_POOL *pool = NULL;
333
334         /* fill random pool and seed the current legacy RNG */
335         pool = rand_pool_new(RAND_DRBG_STRENGTH, 1,
336                              (RAND_DRBG_STRENGTH + 7) / 8,
337                              RAND_POOL_MAX_LENGTH);
338         if (pool == NULL)
339             return 0;
340 #if 0
341         if (rand_pool_acquire_entropy(pool) == 0)
342             goto err;
343 #endif
344         if (meth->add == NULL
345             || meth->add(rand_pool_buffer(pool),
346                          rand_pool_length(pool),
347                          (rand_pool_entropy(pool) / 8.0)) == 0)
348             goto err;
349
350         ret = 1;
351
352      err:
353         rand_pool_free(pool);
354     }
355
356     return ret;
357 }
358
359 int RAND_set_rand_method(const RAND_METHOD *meth)
360 {
361     if (!RUN_ONCE(&rand_init, do_rand_init))
362         return 0;
363
364     CRYPTO_THREAD_write_lock(rand_meth_lock);
365 # ifndef OPENSSL_NO_ENGINE
366     ENGINE_finish(funct_ref);
367     funct_ref = NULL;
368 # endif
369     default_RAND_meth = meth;
370     CRYPTO_THREAD_unlock(rand_meth_lock);
371     return 1;
372 }
373 #endif /* FIPS_MODULE */
374
375 const RAND_METHOD *RAND_get_rand_method(void)
376 {
377 #ifdef FIPS_MODULE
378     return NULL;
379 #else
380     const RAND_METHOD *tmp_meth = NULL;
381
382     if (!RUN_ONCE(&rand_init, do_rand_init))
383         return NULL;
384
385     CRYPTO_THREAD_write_lock(rand_meth_lock);
386     if (default_RAND_meth == NULL) {
387 # ifndef OPENSSL_NO_ENGINE
388         ENGINE *e;
389
390         /* If we have an engine that can do RAND, use it. */
391         if ((e = ENGINE_get_default_RAND()) != NULL
392                 && (tmp_meth = ENGINE_get_RAND(e)) != NULL) {
393             funct_ref = e;
394             default_RAND_meth = tmp_meth;
395         } else {
396             ENGINE_finish(e);
397             default_RAND_meth = &rand_meth;
398         }
399 # else
400         default_RAND_meth = &rand_meth;
401 # endif
402     }
403     tmp_meth = default_RAND_meth;
404     CRYPTO_THREAD_unlock(rand_meth_lock);
405     return tmp_meth;
406 #endif
407 }
408
409 #if !defined(OPENSSL_NO_ENGINE) && !defined(FIPS_MODULE)
410 int RAND_set_rand_engine(ENGINE *engine)
411 {
412     const RAND_METHOD *tmp_meth = NULL;
413
414     if (!RUN_ONCE(&rand_init, do_rand_init))
415         return 0;
416
417     if (engine != NULL) {
418         if (!ENGINE_init(engine))
419             return 0;
420         tmp_meth = ENGINE_get_RAND(engine);
421         if (tmp_meth == NULL) {
422             ENGINE_finish(engine);
423             return 0;
424         }
425     }
426     CRYPTO_THREAD_write_lock(rand_engine_lock);
427     /* This function releases any prior ENGINE so call it first */
428     RAND_set_rand_method(tmp_meth);
429     funct_ref = engine;
430     CRYPTO_THREAD_unlock(rand_engine_lock);
431     return 1;
432 }
433 #endif
434
435 void RAND_seed(const void *buf, int num)
436 {
437     const RAND_METHOD *meth = RAND_get_rand_method();
438
439     if (meth != NULL && meth->seed != NULL)
440         meth->seed(buf, num);
441 }
442
443 void RAND_add(const void *buf, int num, double randomness)
444 {
445     const RAND_METHOD *meth = RAND_get_rand_method();
446
447     if (meth != NULL && meth->add != NULL)
448         meth->add(buf, num, randomness);
449 }
450
451 /*
452  * This function is not part of RAND_METHOD, so if we're not using
453  * the default method, then just call RAND_bytes().  Otherwise make
454  * sure we're instantiated and use the private DRBG.
455  */
456 int RAND_priv_bytes_ex(OPENSSL_CTX *ctx, unsigned char *buf, int num)
457 {
458     RAND_DRBG *drbg;
459     const RAND_METHOD *meth = RAND_get_rand_method();
460
461     if (meth != NULL && meth != RAND_OpenSSL()) {
462         if (meth->bytes != NULL)
463             return meth->bytes(buf, num);
464         RANDerr(RAND_F_RAND_PRIV_BYTES_EX, RAND_R_FUNC_NOT_IMPLEMENTED);
465         return -1;
466     }
467
468     drbg = OPENSSL_CTX_get0_private_drbg(ctx);
469     if (drbg != NULL)
470         return RAND_DRBG_bytes(drbg, buf, num);
471
472     return 0;
473 }
474
475 int RAND_priv_bytes(unsigned char *buf, int num)
476 {
477     return RAND_priv_bytes_ex(NULL, buf, num);
478 }
479
480 int RAND_bytes_ex(OPENSSL_CTX *ctx, unsigned char *buf, int num)
481 {
482     RAND_DRBG *drbg;
483     const RAND_METHOD *meth = RAND_get_rand_method();
484
485     if (meth != NULL && meth != RAND_OpenSSL()) {
486         if (meth->bytes != NULL)
487             return meth->bytes(buf, num);
488         RANDerr(RAND_F_RAND_BYTES_EX, RAND_R_FUNC_NOT_IMPLEMENTED);
489         return -1;
490     }
491
492     drbg = OPENSSL_CTX_get0_public_drbg(ctx);
493     if (drbg != NULL)
494         return RAND_DRBG_bytes(drbg, buf, num);
495
496     return 0;
497 }
498
499 int RAND_bytes(unsigned char *buf, int num)
500 {
501     return RAND_bytes_ex(NULL, buf, num);
502 }
503
504 #if !defined(OPENSSL_NO_DEPRECATED_1_1_0) && !defined(FIPS_MODULE)
505 int RAND_pseudo_bytes(unsigned char *buf, int num)
506 {
507     const RAND_METHOD *meth = RAND_get_rand_method();
508
509     if (meth != NULL && meth->pseudorand != NULL)
510         return meth->pseudorand(buf, num);
511     RANDerr(RAND_F_RAND_PSEUDO_BYTES, RAND_R_FUNC_NOT_IMPLEMENTED);
512     return -1;
513 }
514 #endif
515
516 int RAND_status(void)
517 {
518     const RAND_METHOD *meth = RAND_get_rand_method();
519
520     if (meth != NULL && meth->status != NULL)
521         return meth->status();
522     return 0;
523 }