]> git.ipfire.org Git - thirdparty/openssl.git/blob - crypto/rand/rand_lib.c
Add missing RAND_DRBG locking
[thirdparty/openssl.git] / crypto / rand / rand_lib.c
1 /*
2 * Copyright 1995-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 <stdio.h>
11 #include <time.h>
12 #include "internal/cryptlib.h"
13 #include <openssl/opensslconf.h>
14 #include "internal/rand_int.h"
15 #include <openssl/engine.h>
16 #include "internal/thread_once.h"
17 #include "rand_lcl.h"
18
19 #ifndef OPENSSL_NO_ENGINE
20 /* non-NULL if default_RAND_meth is ENGINE-provided */
21 static ENGINE *funct_ref;
22 static CRYPTO_RWLOCK *rand_engine_lock;
23 #endif
24 static CRYPTO_RWLOCK *rand_meth_lock;
25 static const RAND_METHOD *default_RAND_meth;
26 static CRYPTO_ONCE rand_init = CRYPTO_ONCE_STATIC_INIT;
27
28 int rand_fork_count;
29
30 #ifdef OPENSSL_RAND_SEED_RDTSC
31 /*
32 * IMPORTANT NOTE: It is not currently possible to use this code
33 * because we are not sure about the amount of randomness it provides.
34 * Some SP900 tests have been run, but there is internal skepticism.
35 * So for now this code is not used.
36 */
37 # error "RDTSC enabled? Should not be possible!"
38
39 /*
40 * Acquire entropy from high-speed clock
41 *
42 * Since we get some randomness from the low-order bits of the
43 * high-speed clock, it can help.
44 *
45 * Returns the total entropy count, if it exceeds the requested
46 * entropy count. Otherwise, returns an entropy count of 0.
47 */
48 size_t rand_acquire_entropy_from_tsc(RAND_POOL *pool)
49 {
50 unsigned char c;
51 int i;
52
53 if ((OPENSSL_ia32cap_P[0] & (1 << 4)) != 0) {
54 for (i = 0; i < TSC_READ_COUNT; i++) {
55 c = (unsigned char)(OPENSSL_rdtsc() & 0xFF);
56 RAND_POOL_add(pool, &c, 1, 4);
57 }
58 }
59 return RAND_POOL_entropy_available(pool);
60 }
61 #endif
62
63 #ifdef OPENSSL_RAND_SEED_RDCPU
64 size_t OPENSSL_ia32_rdseed_bytes(unsigned char *buf, size_t len);
65 size_t OPENSSL_ia32_rdrand_bytes(unsigned char *buf, size_t len);
66
67 extern unsigned int OPENSSL_ia32cap_P[];
68
69 /*
70 * Acquire entropy using Intel-specific cpu instructions
71 *
72 * Uses the RDSEED instruction if available, otherwise uses
73 * RDRAND if available.
74 *
75 * For the differences between RDSEED and RDRAND, and why RDSEED
76 * is the preferred choice, see https://goo.gl/oK3KcN
77 *
78 * Returns the total entropy count, if it exceeds the requested
79 * entropy count. Otherwise, returns an entropy count of 0.
80 */
81 size_t rand_acquire_entropy_from_cpu(RAND_POOL *pool)
82 {
83 size_t bytes_needed;
84 unsigned char *buffer;
85
86 bytes_needed = RAND_POOL_bytes_needed(pool, 8 /*entropy_per_byte*/);
87 if (bytes_needed > 0) {
88 buffer = RAND_POOL_add_begin(pool, bytes_needed);
89
90 if (buffer != NULL) {
91
92 /* If RDSEED is available, use that. */
93 if ((OPENSSL_ia32cap_P[2] & (1 << 18)) != 0) {
94 if (OPENSSL_ia32_rdseed_bytes(buffer, bytes_needed)
95 == bytes_needed)
96 return RAND_POOL_add_end(pool,
97 bytes_needed,
98 8 * bytes_needed);
99 }
100
101 /* Second choice is RDRAND. */
102 if ((OPENSSL_ia32cap_P[1] & (1 << (62 - 32))) != 0) {
103 if (OPENSSL_ia32_rdrand_bytes(buffer, bytes_needed)
104 == bytes_needed)
105 return RAND_POOL_add_end(pool,
106 bytes_needed,
107 8 * bytes_needed);
108 }
109
110 return RAND_POOL_add_end(pool, 0, 0);
111 }
112 }
113
114 return RAND_POOL_entropy_available(pool);
115 }
116 #endif
117
118
119 /*
120 * Implements the get_entropy() callback (see RAND_DRBG_set_callbacks())
121 *
122 * If the DRBG has a parent, then the required amount of entropy input
123 * is fetched using the parent's RAND_DRBG_generate().
124 *
125 * Otherwise, the entropy is polled from the system entropy sources
126 * using RAND_POOL_acquire_entropy().
127 *
128 * If a random pool has been added to the DRBG using RAND_add(), then
129 * its entropy will be used up first.
130 */
131 size_t rand_drbg_get_entropy(RAND_DRBG *drbg,
132 unsigned char **pout,
133 int entropy, size_t min_len, size_t max_len)
134 {
135 size_t ret = 0;
136 size_t entropy_available = 0;
137 RAND_POOL *pool = RAND_POOL_new(entropy, min_len, max_len);
138
139 if (pool == NULL)
140 return 0;
141
142 if (drbg->pool) {
143 RAND_POOL_add(pool,
144 RAND_POOL_buffer(drbg->pool),
145 RAND_POOL_length(drbg->pool),
146 RAND_POOL_entropy(drbg->pool));
147 RAND_POOL_free(drbg->pool);
148 drbg->pool = NULL;
149 }
150
151 if (drbg->parent) {
152 size_t bytes_needed = RAND_POOL_bytes_needed(pool, 8);
153 unsigned char *buffer = RAND_POOL_add_begin(pool, bytes_needed);
154
155 if (buffer != NULL) {
156 size_t bytes = 0;
157
158 /*
159 * Get random from parent, include our state as additional input.
160 * Our lock is already held, but we need to lock our parent before
161 * generating bits from it.
162 */
163 if (drbg->parent->lock)
164 CRYPTO_THREAD_write_lock(drbg->parent->lock);
165 if (RAND_DRBG_generate(drbg->parent,
166 buffer, bytes_needed,
167 0,
168 (unsigned char *)drbg, sizeof(*drbg)) != 0)
169 bytes = bytes_needed;
170 if (drbg->parent->lock)
171 CRYPTO_THREAD_unlock(drbg->parent->lock);
172
173 entropy_available = RAND_POOL_add_end(pool, bytes, 8 * bytes);
174 }
175
176 } else {
177 /* Get entropy by polling system entropy sources. */
178 entropy_available = RAND_POOL_acquire_entropy(pool);
179 }
180
181 if (entropy_available > 0) {
182 ret = RAND_POOL_length(pool);
183 *pout = RAND_POOL_detach(pool);
184 }
185
186 RAND_POOL_free(pool);
187 return ret;
188 }
189
190
191 /*
192 * Implements the cleanup_entropy() callback (see RAND_DRBG_set_callbacks())
193 *
194 */
195 void rand_drbg_cleanup_entropy(RAND_DRBG *drbg,
196 unsigned char *out, size_t outlen)
197 {
198 OPENSSL_secure_clear_free(out, outlen);
199 }
200
201 void rand_fork()
202 {
203 rand_fork_count++;
204 }
205
206 DEFINE_RUN_ONCE_STATIC(do_rand_init)
207 {
208 int ret = 1;
209
210 #ifndef OPENSSL_NO_ENGINE
211 rand_engine_lock = CRYPTO_THREAD_glock_new("rand_engine");
212 ret &= rand_engine_lock != NULL;
213 #endif
214 rand_meth_lock = CRYPTO_THREAD_glock_new("rand_meth");
215 ret &= rand_meth_lock != NULL;
216
217 return ret;
218 }
219
220 void rand_cleanup_int(void)
221 {
222 const RAND_METHOD *meth = default_RAND_meth;
223
224 if (meth != NULL && meth->cleanup != NULL)
225 meth->cleanup();
226 RAND_set_rand_method(NULL);
227 #ifndef OPENSSL_NO_ENGINE
228 CRYPTO_THREAD_lock_free(rand_engine_lock);
229 #endif
230 CRYPTO_THREAD_lock_free(rand_meth_lock);
231 }
232
233 /*
234 * RAND_poll() reseeds the default RNG using random input
235 *
236 * The random input is obtained from polling various entropy
237 * sources which depend on the operating system and are
238 * configurable via the --with-rand-seed configure option.
239 */
240 int RAND_poll(void)
241 {
242 int ret = 0;
243
244 RAND_POOL *pool = NULL;
245
246 const RAND_METHOD *meth = RAND_get_rand_method();
247
248 if (meth == RAND_OpenSSL()) {
249 /* fill random pool and seed the default DRBG */
250 RAND_DRBG *drbg = RAND_DRBG_get0_global();
251
252 if (drbg == NULL)
253 return 0;
254
255 CRYPTO_THREAD_write_lock(drbg->lock);
256 ret = rand_drbg_restart(drbg, NULL, 0, 0);
257 CRYPTO_THREAD_unlock(drbg->lock);
258
259 return ret;
260
261 } else {
262 /* fill random pool and seed the current legacy RNG */
263 pool = RAND_POOL_new(RAND_DRBG_STRENGTH,
264 RAND_DRBG_STRENGTH / 8,
265 DRBG_MINMAX_FACTOR * (RAND_DRBG_STRENGTH / 8));
266 if (pool == NULL)
267 return 0;
268
269 if (RAND_POOL_acquire_entropy(pool) == 0)
270 goto err;
271
272 if (meth->add == NULL
273 || meth->add(RAND_POOL_buffer(pool),
274 RAND_POOL_length(pool),
275 (RAND_POOL_entropy(pool) / 8.0)) == 0)
276 goto err;
277
278 ret = 1;
279 }
280
281 err:
282 RAND_POOL_free(pool);
283 return ret;
284 }
285
286 /*
287 * The 'random pool' acts as a dumb container for collecting random
288 * input from various entropy sources. The pool has no knowledge about
289 * whether its randomness is fed into a legacy RAND_METHOD via RAND_add()
290 * or into a new style RAND_DRBG. It is the callers duty to 1) initialize the
291 * random pool, 2) pass it to the polling callbacks, 3) seed the RNG, and
292 * 4) cleanup the random pool again.
293 *
294 * The random pool contains no locking mechanism because its scope and
295 * lifetime is intended to be restricted to a single stack frame.
296 */
297 struct rand_pool_st {
298 unsigned char *buffer; /* points to the beginning of the random pool */
299 size_t len; /* current number of random bytes contained in the pool */
300
301 size_t min_len; /* minimum number of random bytes requested */
302 size_t max_len; /* maximum number of random bytes (allocated buffer size) */
303 size_t entropy; /* current entropy count in bits */
304 size_t requested_entropy; /* requested entropy count in bits */
305 };
306
307 /*
308 * Allocate memory and initialize a new random pool
309 */
310
311 RAND_POOL *RAND_POOL_new(int entropy, size_t min_len, size_t max_len)
312 {
313 RAND_POOL *pool = OPENSSL_zalloc(sizeof(*pool));
314
315 if (pool == NULL) {
316 RANDerr(RAND_F_RAND_POOL_NEW, ERR_R_MALLOC_FAILURE);
317 goto err;
318 }
319
320 pool->min_len = min_len;
321 pool->max_len = max_len;
322
323 pool->buffer = OPENSSL_secure_zalloc(pool->max_len);
324 if (pool->buffer == NULL) {
325 RANDerr(RAND_F_RAND_POOL_NEW, ERR_R_MALLOC_FAILURE);
326 goto err;
327 }
328
329 pool->requested_entropy = entropy;
330
331 return pool;
332
333 err:
334 OPENSSL_free(pool);
335 return NULL;
336 }
337
338 /*
339 * Free |pool|, securely erasing its buffer.
340 */
341 void RAND_POOL_free(RAND_POOL *pool)
342 {
343 if (pool == NULL)
344 return;
345
346 OPENSSL_secure_clear_free(pool->buffer, pool->max_len);
347 OPENSSL_free(pool);
348 }
349
350 /*
351 * Return the |pool|'s buffer to the caller (readonly).
352 */
353 const unsigned char *RAND_POOL_buffer(RAND_POOL *pool)
354 {
355 return pool->buffer;
356 }
357
358 /*
359 * Return the |pool|'s entropy to the caller.
360 */
361 size_t RAND_POOL_entropy(RAND_POOL *pool)
362 {
363 return pool->entropy;
364 }
365
366 /*
367 * Return the |pool|'s buffer length to the caller.
368 */
369 size_t RAND_POOL_length(RAND_POOL *pool)
370 {
371 return pool->len;
372 }
373
374 /*
375 * Detach the |pool| buffer and return it to the caller.
376 * It's the responsibility of the caller to free the buffer
377 * using OPENSSL_secure_clear_free().
378 */
379 unsigned char *RAND_POOL_detach(RAND_POOL *pool)
380 {
381 unsigned char *ret = pool->buffer;
382 pool->buffer = NULL;
383 return ret;
384 }
385
386
387 /*
388 * If every byte of the input contains |entropy_per_bytes| bits of entropy,
389 * how many bytes does one need to obtain at least |bits| bits of entropy?
390 */
391 #define ENTROPY_TO_BYTES(bits, entropy_per_bytes) \
392 (((bits) + ((entropy_per_bytes) - 1))/(entropy_per_bytes))
393
394
395 /*
396 * Checks whether the |pool|'s entropy is available to the caller.
397 * This is the case when entropy count and buffer length are high enough.
398 * Returns
399 *
400 * |entropy| if the entropy count and buffer size is large enough
401 * 0 otherwise
402 */
403 size_t RAND_POOL_entropy_available(RAND_POOL *pool)
404 {
405 if (pool->entropy < pool->requested_entropy)
406 return 0;
407
408 if (pool->len < pool->min_len)
409 return 0;
410
411 return pool->entropy;
412 }
413
414 /*
415 * Returns the (remaining) amount of entropy needed to fill
416 * the random pool.
417 */
418
419 size_t RAND_POOL_entropy_needed(RAND_POOL *pool)
420 {
421 if (pool->entropy < pool->requested_entropy)
422 return pool->requested_entropy - pool->entropy;
423
424 return 0;
425 }
426
427 /*
428 * Returns the number of bytes needed to fill the pool, assuming
429 * the input has 'entropy_per_byte' entropy bits per byte.
430 * In case of an error, 0 is returned.
431 */
432
433 size_t RAND_POOL_bytes_needed(RAND_POOL *pool, unsigned int entropy_per_byte)
434 {
435 size_t bytes_needed;
436 size_t entropy_needed = RAND_POOL_entropy_needed(pool);
437
438 if (entropy_per_byte < 1 || entropy_per_byte > 8) {
439 RANDerr(RAND_F_RAND_POOL_BYTES_NEEDED, RAND_R_ARGUMENT_OUT_OF_RANGE);
440 return 0;
441 }
442
443 bytes_needed = ENTROPY_TO_BYTES(entropy_needed, entropy_per_byte);
444
445 if (bytes_needed > pool->max_len - pool->len) {
446 /* not enough space left */
447 RANDerr(RAND_F_RAND_POOL_BYTES_NEEDED, RAND_R_RANDOM_POOL_OVERFLOW);
448 return 0;
449 }
450
451 if (pool->len < pool->min_len &&
452 bytes_needed < pool->min_len - pool->len)
453 /* to meet the min_len requirement */
454 bytes_needed = pool->min_len - pool->len;
455
456 return bytes_needed;
457 }
458
459 /* Returns the remaining number of bytes available */
460 size_t RAND_POOL_bytes_remaining(RAND_POOL *pool)
461 {
462 return pool->max_len - pool->len;
463 }
464
465 /*
466 * Add random bytes to the random pool.
467 *
468 * It is expected that the |buffer| contains |len| bytes of
469 * random input which contains at least |entropy| bits of
470 * randomness.
471 *
472 * Return available amount of entropy after this operation.
473 * (see RAND_POOL_entropy_available(pool))
474 */
475 size_t RAND_POOL_add(RAND_POOL *pool,
476 const unsigned char *buffer, size_t len, size_t entropy)
477 {
478 if (len > pool->max_len - pool->len) {
479 RANDerr(RAND_F_RAND_POOL_ADD, RAND_R_ENTROPY_INPUT_TOO_LONG);
480 return 0;
481 }
482
483 if (len > 0) {
484 memcpy(pool->buffer + pool->len, buffer, len);
485 pool->len += len;
486 pool->entropy += entropy;
487 }
488
489 return RAND_POOL_entropy_available(pool);
490 }
491
492 /*
493 * Start to add random bytes to the random pool in-place.
494 *
495 * Reserves the next |len| bytes for adding random bytes in-place
496 * and returns a pointer to the buffer.
497 * The caller is allowed to copy up to |len| bytes into the buffer.
498 * If |len| == 0 this is considered a no-op and a NULL pointer
499 * is returned without producing an error message.
500 *
501 * After updating the buffer, RAND_POOL_add_end() needs to be called
502 * to finish the udpate operation (see next comment).
503 */
504 unsigned char *RAND_POOL_add_begin(RAND_POOL *pool, size_t len)
505 {
506 if (len == 0)
507 return NULL;
508
509 if (len > pool->max_len - pool->len) {
510 RANDerr(RAND_F_RAND_POOL_ADD_BEGIN, RAND_R_RANDOM_POOL_OVERFLOW);
511 return NULL;
512 }
513
514 return pool->buffer + pool->len;
515 }
516
517 /*
518 * Finish to add random bytes to the random pool in-place.
519 *
520 * Finishes an in-place update of the random pool started by
521 * RAND_POOL_add_begin() (see previous comment).
522 * It is expected that |len| bytes of random input have been added
523 * to the buffer which contain at least |entropy| bits of randomness.
524 * It is allowed to add less bytes than originally reserved.
525 */
526 size_t RAND_POOL_add_end(RAND_POOL *pool, size_t len, size_t entropy)
527 {
528 if (len > pool->max_len - pool->len) {
529 RANDerr(RAND_F_RAND_POOL_ADD_END, RAND_R_RANDOM_POOL_OVERFLOW);
530 return 0;
531 }
532
533 if (len > 0) {
534 pool->len += len;
535 pool->entropy += entropy;
536 }
537
538 return RAND_POOL_entropy_available(pool);
539 }
540
541 int RAND_set_rand_method(const RAND_METHOD *meth)
542 {
543 if (!RUN_ONCE(&rand_init, do_rand_init))
544 return 0;
545
546 CRYPTO_THREAD_write_lock(rand_meth_lock);
547 #ifndef OPENSSL_NO_ENGINE
548 ENGINE_finish(funct_ref);
549 funct_ref = NULL;
550 #endif
551 default_RAND_meth = meth;
552 CRYPTO_THREAD_unlock(rand_meth_lock);
553 return 1;
554 }
555
556 const RAND_METHOD *RAND_get_rand_method(void)
557 {
558 const RAND_METHOD *tmp_meth = NULL;
559
560 if (!RUN_ONCE(&rand_init, do_rand_init))
561 return NULL;
562
563 CRYPTO_THREAD_write_lock(rand_meth_lock);
564 if (default_RAND_meth == NULL) {
565 #ifndef OPENSSL_NO_ENGINE
566 ENGINE *e;
567
568 /* If we have an engine that can do RAND, use it. */
569 if ((e = ENGINE_get_default_RAND()) != NULL
570 && (tmp_meth = ENGINE_get_RAND(e)) != NULL) {
571 funct_ref = e;
572 default_RAND_meth = tmp_meth;
573 } else {
574 ENGINE_finish(e);
575 default_RAND_meth = &rand_meth;
576 }
577 #else
578 default_RAND_meth = &rand_meth;
579 #endif
580 }
581 tmp_meth = default_RAND_meth;
582 CRYPTO_THREAD_unlock(rand_meth_lock);
583 return tmp_meth;
584 }
585
586 #ifndef OPENSSL_NO_ENGINE
587 int RAND_set_rand_engine(ENGINE *engine)
588 {
589 const RAND_METHOD *tmp_meth = NULL;
590
591 if (!RUN_ONCE(&rand_init, do_rand_init))
592 return 0;
593
594 if (engine != NULL) {
595 if (!ENGINE_init(engine))
596 return 0;
597 tmp_meth = ENGINE_get_RAND(engine);
598 if (tmp_meth == NULL) {
599 ENGINE_finish(engine);
600 return 0;
601 }
602 }
603 CRYPTO_THREAD_write_lock(rand_engine_lock);
604 /* This function releases any prior ENGINE so call it first */
605 RAND_set_rand_method(tmp_meth);
606 funct_ref = engine;
607 CRYPTO_THREAD_unlock(rand_engine_lock);
608 return 1;
609 }
610 #endif
611
612 void RAND_seed(const void *buf, int num)
613 {
614 const RAND_METHOD *meth = RAND_get_rand_method();
615
616 if (meth->seed != NULL)
617 meth->seed(buf, num);
618 }
619
620 void RAND_add(const void *buf, int num, double randomness)
621 {
622 const RAND_METHOD *meth = RAND_get_rand_method();
623
624 if (meth->add != NULL)
625 meth->add(buf, num, randomness);
626 }
627
628 /*
629 * This function is not part of RAND_METHOD, so if we're not using
630 * the default method, then just call RAND_bytes(). Otherwise make
631 * sure we're instantiated and use the private DRBG.
632 */
633 int RAND_priv_bytes(unsigned char *buf, int num)
634 {
635 const RAND_METHOD *meth = RAND_get_rand_method();
636 RAND_DRBG *drbg;
637 int ret;
638
639 if (meth != RAND_OpenSSL())
640 return RAND_bytes(buf, num);
641
642 drbg = RAND_DRBG_get0_priv_global();
643 if (drbg == NULL)
644 return 0;
645
646 /* We have to lock the DRBG before generating bits from it. */
647 CRYPTO_THREAD_write_lock(drbg->lock);
648 ret = RAND_DRBG_generate(drbg, buf, num, 0, NULL, 0);
649 CRYPTO_THREAD_unlock(drbg->lock);
650 return ret;
651 }
652
653 int RAND_bytes(unsigned char *buf, int num)
654 {
655 const RAND_METHOD *meth = RAND_get_rand_method();
656
657 if (meth->bytes != NULL)
658 return meth->bytes(buf, num);
659 RANDerr(RAND_F_RAND_BYTES, RAND_R_FUNC_NOT_IMPLEMENTED);
660 return -1;
661 }
662
663 #if OPENSSL_API_COMPAT < 0x10100000L
664 int RAND_pseudo_bytes(unsigned char *buf, int num)
665 {
666 const RAND_METHOD *meth = RAND_get_rand_method();
667
668 if (meth->pseudorand != NULL)
669 return meth->pseudorand(buf, num);
670 return -1;
671 }
672 #endif
673
674 int RAND_status(void)
675 {
676 const RAND_METHOD *meth = RAND_get_rand_method();
677
678 if (meth->status != NULL)
679 return meth->status();
680 return 0;
681 }