1 /*
2 * Copyright 1995-2019 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 #include "e_os.h"
19
20 #ifndef OPENSSL_NO_ENGINE
21 /* non-NULL if default_RAND_meth is ENGINE-provided */
22 static ENGINE *funct_ref;
23 static CRYPTO_RWLOCK *rand_engine_lock;
24 #endif
25 static CRYPTO_RWLOCK *rand_meth_lock;
26 static const RAND_METHOD *default_RAND_meth;
27 static CRYPTO_ONCE rand_init = CRYPTO_ONCE_STATIC_INIT;
28
29 static CRYPTO_RWLOCK *rand_nonce_lock;
30 static int rand_nonce_count;
31
32 static int rand_inited = 0;
33
34 #ifdef OPENSSL_RAND_SEED_RDTSC
35 /*
36 * IMPORTANT NOTE: It is not currently possible to use this code
37 * because we are not sure about the amount of randomness it provides.
38 * Some SP900 tests have been run, but there is internal skepticism.
39 * So for now this code is not used.
40 */
41 # error "RDTSC enabled? Should not be possible!"
42
43 /*
44 * Acquire entropy from high-speed clock
45 *
46 * Since we get some randomness from the low-order bits of the
47 * high-speed clock, it can help.
48 *
49 * Returns the total entropy count, if it exceeds the requested
50 * entropy count. Otherwise, returns an entropy count of 0.
51 */
rand_acquire_entropy_from_tsc(RAND_POOL * pool)52 size_t rand_acquire_entropy_from_tsc(RAND_POOL *pool)
53 {
54 unsigned char c;
55 int i;
56
57 if ((OPENSSL_ia32cap_P[0] & (1 << 4)) != 0) {
58 for (i = 0; i < TSC_READ_COUNT; i++) {
59 c = (unsigned char)(OPENSSL_rdtsc() & 0xFF);
60 rand_pool_add(pool, &c, 1, 4);
61 }
62 }
63 return rand_pool_entropy_available(pool);
64 }
65 #endif
66
67 #ifdef OPENSSL_RAND_SEED_RDCPU
68 size_t OPENSSL_ia32_rdseed_bytes(unsigned char *buf, size_t len);
69 size_t OPENSSL_ia32_rdrand_bytes(unsigned char *buf, size_t len);
70
71 extern unsigned int OPENSSL_ia32cap_P[];
72
73 /*
74 * Acquire entropy using Intel-specific cpu instructions
75 *
76 * Uses the RDSEED instruction if available, otherwise uses
77 * RDRAND if available.
78 *
79 * For the differences between RDSEED and RDRAND, and why RDSEED
80 * is the preferred choice, see https://goo.gl/oK3KcN
81 *
82 * Returns the total entropy count, if it exceeds the requested
83 * entropy count. Otherwise, returns an entropy count of 0.
84 */
rand_acquire_entropy_from_cpu(RAND_POOL * pool)85 size_t rand_acquire_entropy_from_cpu(RAND_POOL *pool)
86 {
87 size_t bytes_needed;
88 unsigned char *buffer;
89
90 bytes_needed = rand_pool_bytes_needed(pool, 1 /*entropy_factor*/);
91 if (bytes_needed > 0) {
92 buffer = rand_pool_add_begin(pool, bytes_needed);
93
94 if (buffer != NULL) {
95 /* Whichever comes first, use RDSEED, RDRAND or nothing */
96 if ((OPENSSL_ia32cap_P[2] & (1 << 18)) != 0) {
97 if (OPENSSL_ia32_rdseed_bytes(buffer, bytes_needed)
98 == bytes_needed) {
99 rand_pool_add_end(pool, bytes_needed, 8 * bytes_needed);
100 }
101 } else if ((OPENSSL_ia32cap_P[1] & (1 << (62 - 32))) != 0) {
102 if (OPENSSL_ia32_rdrand_bytes(buffer, bytes_needed)
103 == bytes_needed) {
104 rand_pool_add_end(pool, bytes_needed, 8 * bytes_needed);
105 }
106 } else {
107 rand_pool_add_end(pool, 0, 0);
108 }
109 }
110 }
111
112 return rand_pool_entropy_available(pool);
113 }
114 #endif
115
116
117 /*
118 * Implements the get_entropy() callback (see RAND_DRBG_set_callbacks())
119 *
120 * If the DRBG has a parent, then the required amount of entropy input
121 * is fetched using the parent's RAND_DRBG_generate().
122 *
123 * Otherwise, the entropy is polled from the system entropy sources
124 * using rand_pool_acquire_entropy().
125 *
126 * If a random pool has been added to the DRBG using RAND_add(), then
127 * its entropy will be used up first.
128 */
rand_drbg_get_entropy(RAND_DRBG * drbg,unsigned char ** pout,int entropy,size_t min_len,size_t max_len,int prediction_resistance)129 size_t rand_drbg_get_entropy(RAND_DRBG *drbg,
130 unsigned char **pout,
131 int entropy, size_t min_len, size_t max_len,
132 int prediction_resistance)
133 {
134 size_t ret = 0;
135 size_t entropy_available = 0;
136 RAND_POOL *pool;
137
138 if (drbg->parent != NULL && drbg->strength > drbg->parent->strength) {
139 /*
140 * We currently don't support the algorithm from NIST SP 800-90C
141 * 10.1.2 to use a weaker DRBG as source
142 */
143 RANDerr(RAND_F_RAND_DRBG_GET_ENTROPY, RAND_R_PARENT_STRENGTH_TOO_WEAK);
144 return 0;
145 }
146
147 if (drbg->seed_pool != NULL) {
148 pool = drbg->seed_pool;
149 pool->entropy_requested = entropy;
150 } else {
151 pool = rand_pool_new(entropy, drbg->secure, min_len, max_len);
152 if (pool == NULL)
153 return 0;
154 }
155
156 if (drbg->parent != NULL) {
157 size_t bytes_needed = rand_pool_bytes_needed(pool, 1 /*entropy_factor*/);
158 unsigned char *buffer = rand_pool_add_begin(pool, bytes_needed);
159
160 if (buffer != NULL) {
161 size_t bytes = 0;
162
163 /*
164 * Get random data from parent. Include our address as additional input,
165 * in order to provide some additional distinction between different
166 * DRBG child instances.
167 * Our lock is already held, but we need to lock our parent before
168 * generating bits from it. (Note: taking the lock will be a no-op
169 * if locking if drbg->parent->lock == NULL.)
170 */
171 rand_drbg_lock(drbg->parent);
172 if (RAND_DRBG_generate(drbg->parent,
173 buffer, bytes_needed,
174 prediction_resistance,
175 (unsigned char *)&drbg, sizeof(drbg)) != 0)
176 bytes = bytes_needed;
177 drbg->reseed_next_counter
178 = tsan_load(&drbg->parent->reseed_prop_counter);
179 rand_drbg_unlock(drbg->parent);
180
181 rand_pool_add_end(pool, bytes, 8 * bytes);
182 entropy_available = rand_pool_entropy_available(pool);
183 }
184
185 } else {
186 if (prediction_resistance) {
187 /*
188 * We don't have any entropy sources that comply with the NIST
189 * standard to provide prediction resistance (see NIST SP 800-90C,
190 * Section 5.4).
191 */
192 RANDerr(RAND_F_RAND_DRBG_GET_ENTROPY,
193 RAND_R_PREDICTION_RESISTANCE_NOT_SUPPORTED);
194 goto err;
195 }
196
197 /* Get entropy by polling system entropy sources. */
198 entropy_available = rand_pool_acquire_entropy(pool);
199 }
200
201 if (entropy_available > 0) {
202 ret = rand_pool_length(pool);
203 *pout = rand_pool_detach(pool);
204 }
205
206 err:
207 if (drbg->seed_pool == NULL)
208 rand_pool_free(pool);
209 return ret;
210 }
211
212 /*
213 * Implements the cleanup_entropy() callback (see RAND_DRBG_set_callbacks())
214 *
215 */
rand_drbg_cleanup_entropy(RAND_DRBG * drbg,unsigned char * out,size_t outlen)216 void rand_drbg_cleanup_entropy(RAND_DRBG *drbg,
217 unsigned char *out, size_t outlen)
218 {
219 if (drbg->seed_pool == NULL) {
220 if (drbg->secure)
221 OPENSSL_secure_clear_free(out, outlen);
222 else
223 OPENSSL_clear_free(out, outlen);
224 }
225 }
226
227
228 /*
229 * Implements the get_nonce() callback (see RAND_DRBG_set_callbacks())
230 *
231 */
rand_drbg_get_nonce(RAND_DRBG * drbg,unsigned char ** pout,int entropy,size_t min_len,size_t max_len)232 size_t rand_drbg_get_nonce(RAND_DRBG *drbg,
233 unsigned char **pout,
234 int entropy, size_t min_len, size_t max_len)
235 {
236 size_t ret = 0;
237 RAND_POOL *pool;
238
239 struct {
240 void * instance;
241 int count;
242 } data;
243
244 memset(&data, 0, sizeof(data));
245 pool = rand_pool_new(0, 0, min_len, max_len);
246 if (pool == NULL)
247 return 0;
248
249 if (rand_pool_add_nonce_data(pool) == 0)
250 goto err;
251
252 data.instance = drbg;
253 CRYPTO_atomic_add(&rand_nonce_count, 1, &data.count, rand_nonce_lock);
254
255 if (rand_pool_add(pool, (unsigned char *)&data, sizeof(data), 0) == 0)
256 goto err;
257
258 ret = rand_pool_length(pool);
259 *pout = rand_pool_detach(pool);
260
261 err:
262 rand_pool_free(pool);
263
264 return ret;
265 }
266
267 /*
268 * Implements the cleanup_nonce() callback (see RAND_DRBG_set_callbacks())
269 *
270 */
rand_drbg_cleanup_nonce(RAND_DRBG * drbg,unsigned char * out,size_t outlen)271 void rand_drbg_cleanup_nonce(RAND_DRBG *drbg,
272 unsigned char *out, size_t outlen)
273 {
274 OPENSSL_clear_free(out, outlen);
275 }
276
277 /*
278 * Generate additional data that can be used for the drbg. The data does
279 * not need to contain entropy, but it's useful if it contains at least
280 * some bits that are unpredictable.
281 *
282 * Returns 0 on failure.
283 *
284 * On success it allocates a buffer at |*pout| and returns the length of
285 * the data. The buffer should get freed using OPENSSL_secure_clear_free().
286 */
rand_drbg_get_additional_data(RAND_POOL * pool,unsigned char ** pout)287 size_t rand_drbg_get_additional_data(RAND_POOL *pool, unsigned char **pout)
288 {
289 size_t ret = 0;
290
291 if (rand_pool_add_additional_data(pool) == 0)
292 goto err;
293
294 ret = rand_pool_length(pool);
295 *pout = rand_pool_detach(pool);
296
297 err:
298 return ret;
299 }
300
rand_drbg_cleanup_additional_data(RAND_POOL * pool,unsigned char * out)301 void rand_drbg_cleanup_additional_data(RAND_POOL *pool, unsigned char *out)
302 {
303 rand_pool_reattach(pool, out);
304 }
305
DEFINE_RUN_ONCE_STATIC(do_rand_init)306 DEFINE_RUN_ONCE_STATIC(do_rand_init)
307 {
308 #ifndef OPENSSL_NO_ENGINE
309 rand_engine_lock = CRYPTO_THREAD_lock_new();
310 if (rand_engine_lock == NULL)
311 return 0;
312 #endif
313
314 rand_meth_lock = CRYPTO_THREAD_lock_new();
315 if (rand_meth_lock == NULL)
316 goto err1;
317
318 rand_nonce_lock = CRYPTO_THREAD_lock_new();
319 if (rand_nonce_lock == NULL)
320 goto err2;
321
322 if (!rand_pool_init())
323 goto err3;
324
325 rand_inited = 1;
326 return 1;
327
328 err3:
329 CRYPTO_THREAD_lock_free(rand_nonce_lock);
330 rand_nonce_lock = NULL;
331 err2:
332 CRYPTO_THREAD_lock_free(rand_meth_lock);
333 rand_meth_lock = NULL;
334 err1:
335 #ifndef OPENSSL_NO_ENGINE
336 CRYPTO_THREAD_lock_free(rand_engine_lock);
337 rand_engine_lock = NULL;
338 #endif
339 return 0;
340 }
341
rand_cleanup_int(void)342 void rand_cleanup_int(void)
343 {
344 const RAND_METHOD *meth = default_RAND_meth;
345
346 if (!rand_inited)
347 return;
348
349 if (meth != NULL && meth->cleanup != NULL)
350 meth->cleanup();
351 RAND_set_rand_method(NULL);
352 rand_pool_cleanup();
353 #ifndef OPENSSL_NO_ENGINE
354 CRYPTO_THREAD_lock_free(rand_engine_lock);
355 rand_engine_lock = NULL;
356 #endif
357 CRYPTO_THREAD_lock_free(rand_meth_lock);
358 rand_meth_lock = NULL;
359 CRYPTO_THREAD_lock_free(rand_nonce_lock);
360 rand_nonce_lock = NULL;
361 rand_inited = 0;
362 }
363
364 /*
365 * RAND_close_seed_files() ensures that any seed file descriptors are
366 * closed after use.
367 */
RAND_keep_random_devices_open(int keep)368 void RAND_keep_random_devices_open(int keep)
369 {
370 if (RUN_ONCE(&rand_init, do_rand_init))
371 rand_pool_keep_random_devices_open(keep);
372 }
373
374 /*
375 * RAND_poll() reseeds the default RNG using random input
376 *
377 * The random input is obtained from polling various entropy
378 * sources which depend on the operating system and are
379 * configurable via the --with-rand-seed configure option.
380 */
RAND_poll(void)381 int RAND_poll(void)
382 {
383 int ret = 0;
384
385 RAND_POOL *pool = NULL;
386
387 const RAND_METHOD *meth = RAND_get_rand_method();
388
389 if (meth == RAND_OpenSSL()) {
390 /* fill random pool and seed the master DRBG */
391 RAND_DRBG *drbg = RAND_DRBG_get0_master();
392
393 if (drbg == NULL)
394 return 0;
395
396 rand_drbg_lock(drbg);
397 ret = rand_drbg_restart(drbg, NULL, 0, 0);
398 rand_drbg_unlock(drbg);
399
400 return ret;
401
402 } else {
403 /* fill random pool and seed the current legacy RNG */
404 pool = rand_pool_new(RAND_DRBG_STRENGTH, 1,
405 (RAND_DRBG_STRENGTH + 7) / 8,
406 RAND_POOL_MAX_LENGTH);
407 if (pool == NULL)
408 return 0;
409
410 if (rand_pool_acquire_entropy(pool) == 0)
411 goto err;
412
413 if (meth->add == NULL
414 || meth->add(rand_pool_buffer(pool),
415 rand_pool_length(pool),
416 (rand_pool_entropy(pool) / 8.0)) == 0)
417 goto err;
418
419 ret = 1;
420 }
421
422 err:
423 rand_pool_free(pool);
424 return ret;
425 }
426
427 /*
428 * Allocate memory and initialize a new random pool
429 */
430
rand_pool_new(int entropy_requested,int secure,size_t min_len,size_t max_len)431 RAND_POOL *rand_pool_new(int entropy_requested, int secure,
432 size_t min_len, size_t max_len)
433 {
434 RAND_POOL *pool = OPENSSL_zalloc(sizeof(*pool));
435 size_t min_alloc_size = RAND_POOL_MIN_ALLOCATION(secure);
436
437 if (pool == NULL) {
438 RANDerr(RAND_F_RAND_POOL_NEW, ERR_R_MALLOC_FAILURE);
439 return NULL;
440 }
441
442 pool->min_len = min_len;
443 pool->max_len = (max_len > RAND_POOL_MAX_LENGTH) ?
444 RAND_POOL_MAX_LENGTH : max_len;
445 pool->alloc_len = min_len < min_alloc_size ? min_alloc_size : min_len;
446 if (pool->alloc_len > pool->max_len)
447 pool->alloc_len = pool->max_len;
448
449 if (secure)
450 pool->buffer = OPENSSL_secure_zalloc(pool->alloc_len);
451 else
452 pool->buffer = OPENSSL_zalloc(pool->alloc_len);
453
454 if (pool->buffer == NULL) {
455 RANDerr(RAND_F_RAND_POOL_NEW, ERR_R_MALLOC_FAILURE);
456 goto err;
457 }
458
459 pool->entropy_requested = entropy_requested;
460 pool->secure = secure;
461
462 return pool;
463
464 err:
465 OPENSSL_free(pool);
466 return NULL;
467 }
468
469 /*
470 * Attach new random pool to the given buffer
471 *
472 * This function is intended to be used only for feeding random data
473 * provided by RAND_add() and RAND_seed() into the <master> DRBG.
474 */
rand_pool_attach(const unsigned char * buffer,size_t len,size_t entropy)475 RAND_POOL *rand_pool_attach(const unsigned char *buffer, size_t len,
476 size_t entropy)
477 {
478 RAND_POOL *pool = OPENSSL_zalloc(sizeof(*pool));
479
480 if (pool == NULL) {
481 RANDerr(RAND_F_RAND_POOL_ATTACH, ERR_R_MALLOC_FAILURE);
482 return NULL;
483 }
484
485 /*
486 * The const needs to be cast away, but attached buffers will not be
487 * modified (in contrary to allocated buffers which are zeroed and
488 * freed in the end).
489 */
490 pool->buffer = (unsigned char *) buffer;
491 pool->len = len;
492
493 pool->attached = 1;
494
495 pool->min_len = pool->max_len = pool->alloc_len = pool->len;
496 pool->entropy = entropy;
497
498 return pool;
499 }
500
501 /*
502 * Free |pool|, securely erasing its buffer.
503 */
rand_pool_free(RAND_POOL * pool)504 void rand_pool_free(RAND_POOL *pool)
505 {
506 if (pool == NULL)
507 return;
508
509 /*
510 * Although it would be advisable from a cryptographical viewpoint,
511 * we are not allowed to clear attached buffers, since they are passed
512 * to rand_pool_attach() as `const unsigned char*`.
513 * (see corresponding comment in rand_pool_attach()).
514 */
515 if (!pool->attached) {
516 if (pool->secure)
517 OPENSSL_secure_clear_free(pool->buffer, pool->alloc_len);
518 else
519 OPENSSL_clear_free(pool->buffer, pool->alloc_len);
520 }
521
522 OPENSSL_free(pool);
523 }
524
525 /*
526 * Return the |pool|'s buffer to the caller (readonly).
527 */
rand_pool_buffer(RAND_POOL * pool)528 const unsigned char *rand_pool_buffer(RAND_POOL *pool)
529 {
530 return pool->buffer;
531 }
532
533 /*
534 * Return the |pool|'s entropy to the caller.
535 */
rand_pool_entropy(RAND_POOL * pool)536 size_t rand_pool_entropy(RAND_POOL *pool)
537 {
538 return pool->entropy;
539 }
540
541 /*
542 * Return the |pool|'s buffer length to the caller.
543 */
rand_pool_length(RAND_POOL * pool)544 size_t rand_pool_length(RAND_POOL *pool)
545 {
546 return pool->len;
547 }
548
549 /*
550 * Detach the |pool| buffer and return it to the caller.
551 * It's the responsibility of the caller to free the buffer
552 * using OPENSSL_secure_clear_free() or to re-attach it
553 * again to the pool using rand_pool_reattach().
554 */
rand_pool_detach(RAND_POOL * pool)555 unsigned char *rand_pool_detach(RAND_POOL *pool)
556 {
557 unsigned char *ret = pool->buffer;
558 pool->buffer = NULL;
559 pool->entropy = 0;
560 return ret;
561 }
562
563 /*
564 * Re-attach the |pool| buffer. It is only allowed to pass
565 * the |buffer| which was previously detached from the same pool.
566 */
rand_pool_reattach(RAND_POOL * pool,unsigned char * buffer)567 void rand_pool_reattach(RAND_POOL *pool, unsigned char *buffer)
568 {
569 pool->buffer = buffer;
570 OPENSSL_cleanse(pool->buffer, pool->len);
571 pool->len = 0;
572 }
573
574 /*
575 * If |entropy_factor| bits contain 1 bit of entropy, how many bytes does one
576 * need to obtain at least |bits| bits of entropy?
577 */
578 #define ENTROPY_TO_BYTES(bits, entropy_factor) \
579 (((bits) * (entropy_factor) + 7) / 8)
580
581
582 /*
583 * Checks whether the |pool|'s entropy is available to the caller.
584 * This is the case when entropy count and buffer length are high enough.
585 * Returns
586 *
587 * |entropy| if the entropy count and buffer size is large enough
588 * 0 otherwise
589 */
rand_pool_entropy_available(RAND_POOL * pool)590 size_t rand_pool_entropy_available(RAND_POOL *pool)
591 {
592 if (pool->entropy < pool->entropy_requested)
593 return 0;
594
595 if (pool->len < pool->min_len)
596 return 0;
597
598 return pool->entropy;
599 }
600
601 /*
602 * Returns the (remaining) amount of entropy needed to fill
603 * the random pool.
604 */
605
rand_pool_entropy_needed(RAND_POOL * pool)606 size_t rand_pool_entropy_needed(RAND_POOL *pool)
607 {
608 if (pool->entropy < pool->entropy_requested)
609 return pool->entropy_requested - pool->entropy;
610
611 return 0;
612 }
613
614 /* Increase the allocation size -- not usable for an attached pool */
rand_pool_grow(RAND_POOL * pool,size_t len)615 static int rand_pool_grow(RAND_POOL *pool, size_t len)
616 {
617 if (len > pool->alloc_len - pool->len) {
618 unsigned char *p;
619 const size_t limit = pool->max_len / 2;
620 size_t newlen = pool->alloc_len;
621
622 if (pool->attached || len > pool->max_len - pool->len) {
623 RANDerr(RAND_F_RAND_POOL_GROW, ERR_R_INTERNAL_ERROR);
624 return 0;
625 }
626
627 do
628 newlen = newlen < limit ? newlen * 2 : pool->max_len;
629 while (len > newlen - pool->len);
630
631 if (pool->secure)
632 p = OPENSSL_secure_zalloc(newlen);
633 else
634 p = OPENSSL_zalloc(newlen);
635 if (p == NULL) {
636 RANDerr(RAND_F_RAND_POOL_GROW, ERR_R_MALLOC_FAILURE);
637 return 0;
638 }
639 memcpy(p, pool->buffer, pool->len);
640 if (pool->secure)
641 OPENSSL_secure_clear_free(pool->buffer, pool->alloc_len);
642 else
643 OPENSSL_clear_free(pool->buffer, pool->alloc_len);
644 pool->buffer = p;
645 pool->alloc_len = newlen;
646 }
647 return 1;
648 }
649
650 /*
651 * Returns the number of bytes needed to fill the pool, assuming
652 * the input has 1 / |entropy_factor| entropy bits per data bit.
653 * In case of an error, 0 is returned.
654 */
655
rand_pool_bytes_needed(RAND_POOL * pool,unsigned int entropy_factor)656 size_t rand_pool_bytes_needed(RAND_POOL *pool, unsigned int entropy_factor)
657 {
658 size_t bytes_needed;
659 size_t entropy_needed = rand_pool_entropy_needed(pool);
660
661 if (entropy_factor < 1) {
662 RANDerr(RAND_F_RAND_POOL_BYTES_NEEDED, RAND_R_ARGUMENT_OUT_OF_RANGE);
663 return 0;
664 }
665
666 bytes_needed = ENTROPY_TO_BYTES(entropy_needed, entropy_factor);
667
668 if (bytes_needed > pool->max_len - pool->len) {
669 /* not enough space left */
670 RANDerr(RAND_F_RAND_POOL_BYTES_NEEDED, RAND_R_RANDOM_POOL_OVERFLOW);
671 return 0;
672 }
673
674 if (pool->len < pool->min_len &&
675 bytes_needed < pool->min_len - pool->len)
676 /* to meet the min_len requirement */
677 bytes_needed = pool->min_len - pool->len;
678
679 /*
680 * Make sure the buffer is large enough for the requested amount
681 * of data. This guarantees that existing code patterns where
682 * rand_pool_add_begin, rand_pool_add_end or rand_pool_add
683 * are used to collect entropy data without any error handling
684 * whatsoever, continue to be valid.
685 * Furthermore if the allocation here fails once, make sure that
686 * we don't fall back to a less secure or even blocking random source,
687 * as that could happen by the existing code patterns.
688 * This is not a concern for additional data, therefore that
689 * is not needed if rand_pool_grow fails in other places.
690 */
691 if (!rand_pool_grow(pool, bytes_needed)) {
692 /* persistent error for this pool */
693 pool->max_len = pool->len = 0;
694 return 0;
695 }
696
697 return bytes_needed;
698 }
699
700 /* Returns the remaining number of bytes available */
rand_pool_bytes_remaining(RAND_POOL * pool)701 size_t rand_pool_bytes_remaining(RAND_POOL *pool)
702 {
703 return pool->max_len - pool->len;
704 }
705
706 /*
707 * Add random bytes to the random pool.
708 *
709 * It is expected that the |buffer| contains |len| bytes of
710 * random input which contains at least |entropy| bits of
711 * randomness.
712 *
713 * Returns 1 if the added amount is adequate, otherwise 0
714 */
rand_pool_add(RAND_POOL * pool,const unsigned char * buffer,size_t len,size_t entropy)715 int rand_pool_add(RAND_POOL *pool,
716 const unsigned char *buffer, size_t len, size_t entropy)
717 {
718 if (len > pool->max_len - pool->len) {
719 RANDerr(RAND_F_RAND_POOL_ADD, RAND_R_ENTROPY_INPUT_TOO_LONG);
720 return 0;
721 }
722
723 if (pool->buffer == NULL) {
724 RANDerr(RAND_F_RAND_POOL_ADD, ERR_R_INTERNAL_ERROR);
725 return 0;
726 }
727
728 if (len > 0) {
729 /*
730 * This is to protect us from accidentally passing the buffer
731 * returned from rand_pool_add_begin.
732 * The check for alloc_len makes sure we do not compare the
733 * address of the end of the allocated memory to something
734 * different, since that comparison would have an
735 * indeterminate result.
736 */
737 if (pool->alloc_len > pool->len && pool->buffer + pool->len == buffer) {
738 RANDerr(RAND_F_RAND_POOL_ADD, ERR_R_INTERNAL_ERROR);
739 return 0;
740 }
741 /*
742 * We have that only for cases when a pool is used to collect
743 * additional data.
744 * For entropy data, as long as the allocation request stays within
745 * the limits given by rand_pool_bytes_needed this rand_pool_grow
746 * below is guaranteed to succeed, thus no allocation happens.
747 */
748 if (!rand_pool_grow(pool, len))
749 return 0;
750 memcpy(pool->buffer + pool->len, buffer, len);
751 pool->len += len;
752 pool->entropy += entropy;
753 }
754
755 return 1;
756 }
757
758 /*
759 * Start to add random bytes to the random pool in-place.
760 *
761 * Reserves the next |len| bytes for adding random bytes in-place
762 * and returns a pointer to the buffer.
763 * The caller is allowed to copy up to |len| bytes into the buffer.
764 * If |len| == 0 this is considered a no-op and a NULL pointer
765 * is returned without producing an error message.
766 *
767 * After updating the buffer, rand_pool_add_end() needs to be called
768 * to finish the udpate operation (see next comment).
769 */
rand_pool_add_begin(RAND_POOL * pool,size_t len)770 unsigned char *rand_pool_add_begin(RAND_POOL *pool, size_t len)
771 {
772 if (len == 0)
773 return NULL;
774
775 if (len > pool->max_len - pool->len) {
776 RANDerr(RAND_F_RAND_POOL_ADD_BEGIN, RAND_R_RANDOM_POOL_OVERFLOW);
777 return NULL;
778 }
779
780 if (pool->buffer == NULL) {
781 RANDerr(RAND_F_RAND_POOL_ADD_BEGIN, ERR_R_INTERNAL_ERROR);
782 return NULL;
783 }
784
785 /*
786 * As long as the allocation request stays within the limits given
787 * by rand_pool_bytes_needed this rand_pool_grow below is guaranteed
788 * to succeed, thus no allocation happens.
789 * We have that only for cases when a pool is used to collect
790 * additional data. Then the buffer might need to grow here,
791 * and of course the caller is responsible to check the return
792 * value of this function.
793 */
794 if (!rand_pool_grow(pool, len))
795 return NULL;
796
797 return pool->buffer + pool->len;
798 }
799
800 /*
801 * Finish to add random bytes to the random pool in-place.
802 *
803 * Finishes an in-place update of the random pool started by
804 * rand_pool_add_begin() (see previous comment).
805 * It is expected that |len| bytes of random input have been added
806 * to the buffer which contain at least |entropy| bits of randomness.
807 * It is allowed to add less bytes than originally reserved.
808 */
rand_pool_add_end(RAND_POOL * pool,size_t len,size_t entropy)809 int rand_pool_add_end(RAND_POOL *pool, size_t len, size_t entropy)
810 {
811 if (len > pool->alloc_len - pool->len) {
812 RANDerr(RAND_F_RAND_POOL_ADD_END, RAND_R_RANDOM_POOL_OVERFLOW);
813 return 0;
814 }
815
816 if (len > 0) {
817 pool->len += len;
818 pool->entropy += entropy;
819 }
820
821 return 1;
822 }
823
RAND_set_rand_method(const RAND_METHOD * meth)824 int RAND_set_rand_method(const RAND_METHOD *meth)
825 {
826 if (!RUN_ONCE(&rand_init, do_rand_init))
827 return 0;
828
829 CRYPTO_THREAD_write_lock(rand_meth_lock);
830 #ifndef OPENSSL_NO_ENGINE
831 ENGINE_finish(funct_ref);
832 funct_ref = NULL;
833 #endif
834 default_RAND_meth = meth;
835 CRYPTO_THREAD_unlock(rand_meth_lock);
836 return 1;
837 }
838
RAND_get_rand_method(void)839 const RAND_METHOD *RAND_get_rand_method(void)
840 {
841 const RAND_METHOD *tmp_meth = NULL;
842
843 if (!RUN_ONCE(&rand_init, do_rand_init))
844 return NULL;
845
846 CRYPTO_THREAD_write_lock(rand_meth_lock);
847 if (default_RAND_meth == NULL) {
848 #ifndef OPENSSL_NO_ENGINE
849 ENGINE *e;
850
851 /* If we have an engine that can do RAND, use it. */
852 if ((e = ENGINE_get_default_RAND()) != NULL
853 && (tmp_meth = ENGINE_get_RAND(e)) != NULL) {
854 funct_ref = e;
855 default_RAND_meth = tmp_meth;
856 } else {
857 ENGINE_finish(e);
858 default_RAND_meth = &rand_meth;
859 }
860 #else
861 default_RAND_meth = &rand_meth;
862 #endif
863 }
864 tmp_meth = default_RAND_meth;
865 CRYPTO_THREAD_unlock(rand_meth_lock);
866 return tmp_meth;
867 }
868
869 #ifndef OPENSSL_NO_ENGINE
RAND_set_rand_engine(ENGINE * engine)870 int RAND_set_rand_engine(ENGINE *engine)
871 {
872 const RAND_METHOD *tmp_meth = NULL;
873
874 if (!RUN_ONCE(&rand_init, do_rand_init))
875 return 0;
876
877 if (engine != NULL) {
878 if (!ENGINE_init(engine))
879 return 0;
880 tmp_meth = ENGINE_get_RAND(engine);
881 if (tmp_meth == NULL) {
882 ENGINE_finish(engine);
883 return 0;
884 }
885 }
886 CRYPTO_THREAD_write_lock(rand_engine_lock);
887 /* This function releases any prior ENGINE so call it first */
888 RAND_set_rand_method(tmp_meth);
889 funct_ref = engine;
890 CRYPTO_THREAD_unlock(rand_engine_lock);
891 return 1;
892 }
893 #endif
894
RAND_seed(const void * buf,int num)895 void RAND_seed(const void *buf, int num)
896 {
897 const RAND_METHOD *meth = RAND_get_rand_method();
898
899 if (meth->seed != NULL)
900 meth->seed(buf, num);
901 }
902
RAND_add(const void * buf,int num,double randomness)903 void RAND_add(const void *buf, int num, double randomness)
904 {
905 const RAND_METHOD *meth = RAND_get_rand_method();
906
907 if (meth->add != NULL)
908 meth->add(buf, num, randomness);
909 }
910
911 /*
912 * This function is not part of RAND_METHOD, so if we're not using
913 * the default method, then just call RAND_bytes(). Otherwise make
914 * sure we're instantiated and use the private DRBG.
915 */
RAND_priv_bytes(unsigned char * buf,int num)916 int RAND_priv_bytes(unsigned char *buf, int num)
917 {
918 const RAND_METHOD *meth = RAND_get_rand_method();
919 RAND_DRBG *drbg;
920 int ret;
921
922 if (meth != RAND_OpenSSL())
923 return RAND_bytes(buf, num);
924
925 drbg = RAND_DRBG_get0_private();
926 if (drbg == NULL)
927 return 0;
928
929 ret = RAND_DRBG_bytes(drbg, buf, num);
930 return ret;
931 }
932
RAND_bytes(unsigned char * buf,int num)933 int RAND_bytes(unsigned char *buf, int num)
934 {
935 const RAND_METHOD *meth = RAND_get_rand_method();
936
937 if (meth->bytes != NULL)
938 return meth->bytes(buf, num);
939 RANDerr(RAND_F_RAND_BYTES, RAND_R_FUNC_NOT_IMPLEMENTED);
940 return -1;
941 }
942
943 #if OPENSSL_API_COMPAT < 0x10100000L
RAND_pseudo_bytes(unsigned char * buf,int num)944 int RAND_pseudo_bytes(unsigned char *buf, int num)
945 {
946 const RAND_METHOD *meth = RAND_get_rand_method();
947
948 if (meth->pseudorand != NULL)
949 return meth->pseudorand(buf, num);
950 return -1;
951 }
952 #endif
953
RAND_status(void)954 int RAND_status(void)
955 {
956 const RAND_METHOD *meth = RAND_get_rand_method();
957
958 if (meth->status != NULL)
959 return meth->status();
960 return 0;
961 }
962