Update source files for pre-3.0 deprecation
[openssl.git] / crypto / rand / rand_lib.c
1 /*
2  * Copyright 1995-2018 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_MODE
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_MODE */
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
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
241 #ifndef FIPS_MODE
242 DEFINE_RUN_ONCE_STATIC(do_rand_init)
243 {
244 # ifndef OPENSSL_NO_ENGINE
245     rand_engine_lock = CRYPTO_THREAD_lock_new();
246     if (rand_engine_lock == NULL)
247         return 0;
248 # endif
249
250     rand_meth_lock = CRYPTO_THREAD_lock_new();
251     if (rand_meth_lock == NULL)
252         goto err;
253
254     if (!rand_pool_init())
255         goto err;
256
257     rand_inited = 1;
258     return 1;
259
260  err:
261     CRYPTO_THREAD_lock_free(rand_meth_lock);
262     rand_meth_lock = NULL;
263 # ifndef OPENSSL_NO_ENGINE
264     CRYPTO_THREAD_lock_free(rand_engine_lock);
265     rand_engine_lock = NULL;
266 # endif
267     return 0;
268 }
269
270 void rand_cleanup_int(void)
271 {
272     const RAND_METHOD *meth = default_RAND_meth;
273
274     if (!rand_inited)
275         return;
276
277     if (meth != NULL && meth->cleanup != NULL)
278         meth->cleanup();
279     RAND_set_rand_method(NULL);
280     rand_pool_cleanup();
281 # ifndef OPENSSL_NO_ENGINE
282     CRYPTO_THREAD_lock_free(rand_engine_lock);
283     rand_engine_lock = NULL;
284 # endif
285     CRYPTO_THREAD_lock_free(rand_meth_lock);
286     rand_meth_lock = NULL;
287     rand_inited = 0;
288 }
289
290 /* TODO(3.0): Do we need to handle this somehow in the FIPS module? */
291 /*
292  * RAND_close_seed_files() ensures that any seed file descriptors are
293  * closed after use.
294  */
295 void RAND_keep_random_devices_open(int keep)
296 {
297     if (RUN_ONCE(&rand_init, do_rand_init))
298         rand_pool_keep_random_devices_open(keep);
299 }
300
301 /*
302  * RAND_poll() reseeds the default RNG using random input
303  *
304  * The random input is obtained from polling various entropy
305  * sources which depend on the operating system and are
306  * configurable via the --with-rand-seed configure option.
307  */
308 int RAND_poll(void)
309 {
310     int ret = 0;
311
312     const RAND_METHOD *meth = RAND_get_rand_method();
313
314     if (meth == RAND_OpenSSL()) {
315         /* fill random pool and seed the master DRBG */
316         RAND_DRBG *drbg = RAND_DRBG_get0_master();
317
318         if (drbg == NULL)
319             return 0;
320
321         rand_drbg_lock(drbg);
322         ret = rand_drbg_restart(drbg, NULL, 0, 0);
323         rand_drbg_unlock(drbg);
324
325         return ret;
326
327     } else {
328         RAND_POOL *pool = NULL;
329
330         /* fill random pool and seed the current legacy RNG */
331         pool = rand_pool_new(RAND_DRBG_STRENGTH, 1,
332                              (RAND_DRBG_STRENGTH + 7) / 8,
333                              RAND_POOL_MAX_LENGTH);
334         if (pool == NULL)
335             return 0;
336
337         if (rand_pool_acquire_entropy(pool) == 0)
338             goto err;
339
340         if (meth->add == NULL
341             || meth->add(rand_pool_buffer(pool),
342                          rand_pool_length(pool),
343                          (rand_pool_entropy(pool) / 8.0)) == 0)
344             goto err;
345
346         ret = 1;
347
348      err:
349         rand_pool_free(pool);
350     }
351
352     return ret;
353 }
354 #endif /* FIPS_MODE */
355
356 /*
357  * Allocate memory and initialize a new random pool
358  */
359
360 RAND_POOL *rand_pool_new(int entropy_requested, int secure,
361                          size_t min_len, size_t max_len)
362 {
363     RAND_POOL *pool = OPENSSL_zalloc(sizeof(*pool));
364     size_t min_alloc_size = RAND_POOL_MIN_ALLOCATION(secure);
365
366     if (pool == NULL) {
367         RANDerr(RAND_F_RAND_POOL_NEW, ERR_R_MALLOC_FAILURE);
368         return NULL;
369     }
370
371     pool->min_len = min_len;
372     pool->max_len = (max_len > RAND_POOL_MAX_LENGTH) ?
373         RAND_POOL_MAX_LENGTH : max_len;
374     pool->alloc_len = min_len < min_alloc_size ? min_alloc_size : min_len;
375     if (pool->alloc_len > pool->max_len)
376         pool->alloc_len = pool->max_len;
377
378     if (secure)
379         pool->buffer = OPENSSL_secure_zalloc(pool->alloc_len);
380     else
381         pool->buffer = OPENSSL_zalloc(pool->alloc_len);
382
383     if (pool->buffer == NULL) {
384         RANDerr(RAND_F_RAND_POOL_NEW, ERR_R_MALLOC_FAILURE);
385         goto err;
386     }
387
388     pool->entropy_requested = entropy_requested;
389     pool->secure = secure;
390
391     return pool;
392
393 err:
394     OPENSSL_free(pool);
395     return NULL;
396 }
397
398 /*
399  * Attach new random pool to the given buffer
400  *
401  * This function is intended to be used only for feeding random data
402  * provided by RAND_add() and RAND_seed() into the <master> DRBG.
403  */
404 RAND_POOL *rand_pool_attach(const unsigned char *buffer, size_t len,
405                             size_t entropy)
406 {
407     RAND_POOL *pool = OPENSSL_zalloc(sizeof(*pool));
408
409     if (pool == NULL) {
410         RANDerr(RAND_F_RAND_POOL_ATTACH, ERR_R_MALLOC_FAILURE);
411         return NULL;
412     }
413
414     /*
415      * The const needs to be cast away, but attached buffers will not be
416      * modified (in contrary to allocated buffers which are zeroed and
417      * freed in the end).
418      */
419     pool->buffer = (unsigned char *) buffer;
420     pool->len = len;
421
422     pool->attached = 1;
423
424     pool->min_len = pool->max_len = pool->alloc_len = pool->len;
425     pool->entropy = entropy;
426
427     return pool;
428 }
429
430 /*
431  * Free |pool|, securely erasing its buffer.
432  */
433 void rand_pool_free(RAND_POOL *pool)
434 {
435     if (pool == NULL)
436         return;
437
438     /*
439      * Although it would be advisable from a cryptographical viewpoint,
440      * we are not allowed to clear attached buffers, since they are passed
441      * to rand_pool_attach() as `const unsigned char*`.
442      * (see corresponding comment in rand_pool_attach()).
443      */
444     if (!pool->attached) {
445         if (pool->secure)
446             OPENSSL_secure_clear_free(pool->buffer, pool->alloc_len);
447         else
448             OPENSSL_clear_free(pool->buffer, pool->alloc_len);
449     }
450
451     OPENSSL_free(pool);
452 }
453
454 /*
455  * Return the |pool|'s buffer to the caller (readonly).
456  */
457 const unsigned char *rand_pool_buffer(RAND_POOL *pool)
458 {
459     return pool->buffer;
460 }
461
462 /*
463  * Return the |pool|'s entropy to the caller.
464  */
465 size_t rand_pool_entropy(RAND_POOL *pool)
466 {
467     return pool->entropy;
468 }
469
470 /*
471  * Return the |pool|'s buffer length to the caller.
472  */
473 size_t rand_pool_length(RAND_POOL *pool)
474 {
475     return pool->len;
476 }
477
478 /*
479  * Detach the |pool| buffer and return it to the caller.
480  * It's the responsibility of the caller to free the buffer
481  * using OPENSSL_secure_clear_free() or to re-attach it
482  * again to the pool using rand_pool_reattach().
483  */
484 unsigned char *rand_pool_detach(RAND_POOL *pool)
485 {
486     unsigned char *ret = pool->buffer;
487     pool->buffer = NULL;
488     pool->entropy = 0;
489     return ret;
490 }
491
492 /*
493  * Re-attach the |pool| buffer. It is only allowed to pass
494  * the |buffer| which was previously detached from the same pool.
495  */
496 void rand_pool_reattach(RAND_POOL *pool, unsigned char *buffer)
497 {
498     pool->buffer = buffer;
499     OPENSSL_cleanse(pool->buffer, pool->len);
500     pool->len = 0;
501 }
502
503 /*
504  * If |entropy_factor| bits contain 1 bit of entropy, how many bytes does one
505  * need to obtain at least |bits| bits of entropy?
506  */
507 #define ENTROPY_TO_BYTES(bits, entropy_factor) \
508     (((bits) * (entropy_factor) + 7) / 8)
509
510
511 /*
512  * Checks whether the |pool|'s entropy is available to the caller.
513  * This is the case when entropy count and buffer length are high enough.
514  * Returns
515  *
516  *  |entropy|  if the entropy count and buffer size is large enough
517  *      0      otherwise
518  */
519 size_t rand_pool_entropy_available(RAND_POOL *pool)
520 {
521     if (pool->entropy < pool->entropy_requested)
522         return 0;
523
524     if (pool->len < pool->min_len)
525         return 0;
526
527     return pool->entropy;
528 }
529
530 /*
531  * Returns the (remaining) amount of entropy needed to fill
532  * the random pool.
533  */
534
535 size_t rand_pool_entropy_needed(RAND_POOL *pool)
536 {
537     if (pool->entropy < pool->entropy_requested)
538         return pool->entropy_requested - pool->entropy;
539
540     return 0;
541 }
542
543 /* Increase the allocation size -- not usable for an attached pool */
544 static int rand_pool_grow(RAND_POOL *pool, size_t len)
545 {
546     if (len > pool->alloc_len - pool->len) {
547         unsigned char *p;
548         const size_t limit = pool->max_len / 2;
549         size_t newlen = pool->alloc_len;
550
551         if (pool->attached || len > pool->max_len - pool->len) {
552             RANDerr(RAND_F_RAND_POOL_GROW, ERR_R_INTERNAL_ERROR);
553             return 0;
554         }
555
556         do
557             newlen = newlen < limit ? newlen * 2 : pool->max_len;
558         while (len > newlen - pool->len);
559
560         if (pool->secure)
561             p = OPENSSL_secure_zalloc(newlen);
562         else
563             p = OPENSSL_zalloc(newlen);
564         if (p == NULL) {
565             RANDerr(RAND_F_RAND_POOL_GROW, ERR_R_MALLOC_FAILURE);
566             return 0;
567         }
568         memcpy(p, pool->buffer, pool->len);
569         if (pool->secure)
570             OPENSSL_secure_clear_free(pool->buffer, pool->alloc_len);
571         else
572             OPENSSL_clear_free(pool->buffer, pool->alloc_len);
573         pool->buffer = p;
574         pool->alloc_len = newlen;
575     }
576     return 1;
577 }
578
579 /*
580  * Returns the number of bytes needed to fill the pool, assuming
581  * the input has 1 / |entropy_factor| entropy bits per data bit.
582  * In case of an error, 0 is returned.
583  */
584
585 size_t rand_pool_bytes_needed(RAND_POOL *pool, unsigned int entropy_factor)
586 {
587     size_t bytes_needed;
588     size_t entropy_needed = rand_pool_entropy_needed(pool);
589
590     if (entropy_factor < 1) {
591         RANDerr(RAND_F_RAND_POOL_BYTES_NEEDED, RAND_R_ARGUMENT_OUT_OF_RANGE);
592         return 0;
593     }
594
595     bytes_needed = ENTROPY_TO_BYTES(entropy_needed, entropy_factor);
596
597     if (bytes_needed > pool->max_len - pool->len) {
598         /* not enough space left */
599         RANDerr(RAND_F_RAND_POOL_BYTES_NEEDED, RAND_R_RANDOM_POOL_OVERFLOW);
600         return 0;
601     }
602
603     if (pool->len < pool->min_len &&
604         bytes_needed < pool->min_len - pool->len)
605         /* to meet the min_len requirement */
606         bytes_needed = pool->min_len - pool->len;
607
608     /*
609      * Make sure the buffer is large enough for the requested amount
610      * of data. This guarantees that existing code patterns where
611      * rand_pool_add_begin, rand_pool_add_end or rand_pool_add
612      * are used to collect entropy data without any error handling
613      * whatsoever, continue to be valid.
614      * Furthermore if the allocation here fails once, make sure that
615      * we don't fall back to a less secure or even blocking random source,
616      * as that could happen by the existing code patterns.
617      * This is not a concern for additional data, therefore that
618      * is not needed if rand_pool_grow fails in other places.
619      */
620     if (!rand_pool_grow(pool, bytes_needed)) {
621         /* persistent error for this pool */
622         pool->max_len = pool->len = 0;
623         return 0;
624     }
625
626     return bytes_needed;
627 }
628
629 /* Returns the remaining number of bytes available */
630 size_t rand_pool_bytes_remaining(RAND_POOL *pool)
631 {
632     return pool->max_len - pool->len;
633 }
634
635 /*
636  * Add random bytes to the random pool.
637  *
638  * It is expected that the |buffer| contains |len| bytes of
639  * random input which contains at least |entropy| bits of
640  * randomness.
641  *
642  * Returns 1 if the added amount is adequate, otherwise 0
643  */
644 int rand_pool_add(RAND_POOL *pool,
645                   const unsigned char *buffer, size_t len, size_t entropy)
646 {
647     if (len > pool->max_len - pool->len) {
648         RANDerr(RAND_F_RAND_POOL_ADD, RAND_R_ENTROPY_INPUT_TOO_LONG);
649         return 0;
650     }
651
652     if (pool->buffer == NULL) {
653         RANDerr(RAND_F_RAND_POOL_ADD, ERR_R_INTERNAL_ERROR);
654         return 0;
655     }
656
657     if (len > 0) {
658         /*
659          * This is to protect us from accidentally passing the buffer
660          * returned from rand_pool_add_begin.
661          * The check for alloc_len makes sure we do not compare the
662          * address of the end of the allocated memory to something
663          * different, since that comparison would have an
664          * indeterminate result.
665          */
666         if (pool->alloc_len > pool->len && pool->buffer + pool->len == buffer) {
667             RANDerr(RAND_F_RAND_POOL_ADD, ERR_R_INTERNAL_ERROR);
668             return 0;
669         }
670         /*
671          * We have that only for cases when a pool is used to collect
672          * additional data.
673          * For entropy data, as long as the allocation request stays within
674          * the limits given by rand_pool_bytes_needed this rand_pool_grow
675          * below is guaranteed to succeed, thus no allocation happens.
676          */
677         if (!rand_pool_grow(pool, len))
678             return 0;
679         memcpy(pool->buffer + pool->len, buffer, len);
680         pool->len += len;
681         pool->entropy += entropy;
682     }
683
684     return 1;
685 }
686
687 /*
688  * Start to add random bytes to the random pool in-place.
689  *
690  * Reserves the next |len| bytes for adding random bytes in-place
691  * and returns a pointer to the buffer.
692  * The caller is allowed to copy up to |len| bytes into the buffer.
693  * If |len| == 0 this is considered a no-op and a NULL pointer
694  * is returned without producing an error message.
695  *
696  * After updating the buffer, rand_pool_add_end() needs to be called
697  * to finish the udpate operation (see next comment).
698  */
699 unsigned char *rand_pool_add_begin(RAND_POOL *pool, size_t len)
700 {
701     if (len == 0)
702         return NULL;
703
704     if (len > pool->max_len - pool->len) {
705         RANDerr(RAND_F_RAND_POOL_ADD_BEGIN, RAND_R_RANDOM_POOL_OVERFLOW);
706         return NULL;
707     }
708
709     if (pool->buffer == NULL) {
710         RANDerr(RAND_F_RAND_POOL_ADD_BEGIN, ERR_R_INTERNAL_ERROR);
711         return NULL;
712     }
713
714     /*
715      * As long as the allocation request stays within the limits given
716      * by rand_pool_bytes_needed this rand_pool_grow below is guaranteed
717      * to succeed, thus no allocation happens.
718      * We have that only for cases when a pool is used to collect
719      * additional data. Then the buffer might need to grow here,
720      * and of course the caller is responsible to check the return
721      * value of this function.
722      */
723     if (!rand_pool_grow(pool, len))
724         return NULL;
725
726     return pool->buffer + pool->len;
727 }
728
729 /*
730  * Finish to add random bytes to the random pool in-place.
731  *
732  * Finishes an in-place update of the random pool started by
733  * rand_pool_add_begin() (see previous comment).
734  * It is expected that |len| bytes of random input have been added
735  * to the buffer which contain at least |entropy| bits of randomness.
736  * It is allowed to add less bytes than originally reserved.
737  */
738 int rand_pool_add_end(RAND_POOL *pool, size_t len, size_t entropy)
739 {
740     if (len > pool->alloc_len - pool->len) {
741         RANDerr(RAND_F_RAND_POOL_ADD_END, RAND_R_RANDOM_POOL_OVERFLOW);
742         return 0;
743     }
744
745     if (len > 0) {
746         pool->len += len;
747         pool->entropy += entropy;
748     }
749
750     return 1;
751 }
752
753 #ifndef FIPS_MODE
754 int RAND_set_rand_method(const RAND_METHOD *meth)
755 {
756     if (!RUN_ONCE(&rand_init, do_rand_init))
757         return 0;
758
759     CRYPTO_THREAD_write_lock(rand_meth_lock);
760 # ifndef OPENSSL_NO_ENGINE
761     ENGINE_finish(funct_ref);
762     funct_ref = NULL;
763 # endif
764     default_RAND_meth = meth;
765     CRYPTO_THREAD_unlock(rand_meth_lock);
766     return 1;
767 }
768 #endif
769
770 const RAND_METHOD *RAND_get_rand_method(void)
771 {
772 #ifdef FIPS_MODE
773     return NULL;
774 #else
775     const RAND_METHOD *tmp_meth = NULL;
776
777     if (!RUN_ONCE(&rand_init, do_rand_init))
778         return NULL;
779
780     CRYPTO_THREAD_write_lock(rand_meth_lock);
781     if (default_RAND_meth == NULL) {
782 # ifndef OPENSSL_NO_ENGINE
783         ENGINE *e;
784
785         /* If we have an engine that can do RAND, use it. */
786         if ((e = ENGINE_get_default_RAND()) != NULL
787                 && (tmp_meth = ENGINE_get_RAND(e)) != NULL) {
788             funct_ref = e;
789             default_RAND_meth = tmp_meth;
790         } else {
791             ENGINE_finish(e);
792             default_RAND_meth = &rand_meth;
793         }
794 # else
795         default_RAND_meth = &rand_meth;
796 # endif
797     }
798     tmp_meth = default_RAND_meth;
799     CRYPTO_THREAD_unlock(rand_meth_lock);
800     return tmp_meth;
801 #endif
802 }
803
804 #if !defined(OPENSSL_NO_ENGINE) && !defined(FIPS_MODE)
805 int RAND_set_rand_engine(ENGINE *engine)
806 {
807     const RAND_METHOD *tmp_meth = NULL;
808
809     if (!RUN_ONCE(&rand_init, do_rand_init))
810         return 0;
811
812     if (engine != NULL) {
813         if (!ENGINE_init(engine))
814             return 0;
815         tmp_meth = ENGINE_get_RAND(engine);
816         if (tmp_meth == NULL) {
817             ENGINE_finish(engine);
818             return 0;
819         }
820     }
821     CRYPTO_THREAD_write_lock(rand_engine_lock);
822     /* This function releases any prior ENGINE so call it first */
823     RAND_set_rand_method(tmp_meth);
824     funct_ref = engine;
825     CRYPTO_THREAD_unlock(rand_engine_lock);
826     return 1;
827 }
828 #endif
829
830 void RAND_seed(const void *buf, int num)
831 {
832     const RAND_METHOD *meth = RAND_get_rand_method();
833
834     if (meth->seed != NULL)
835         meth->seed(buf, num);
836 }
837
838 void RAND_add(const void *buf, int num, double randomness)
839 {
840     const RAND_METHOD *meth = RAND_get_rand_method();
841
842     if (meth->add != NULL)
843         meth->add(buf, num, randomness);
844 }
845
846 /*
847  * This function is not part of RAND_METHOD, so if we're not using
848  * the default method, then just call RAND_bytes().  Otherwise make
849  * sure we're instantiated and use the private DRBG.
850  */
851 int rand_priv_bytes_ex(OPENSSL_CTX *ctx, unsigned char *buf, int num)
852 {
853     RAND_DRBG *drbg;
854     int ret;
855     const RAND_METHOD *meth = RAND_get_rand_method();
856
857     if (meth != RAND_OpenSSL())
858         return meth->bytes(buf, num);
859
860     drbg = OPENSSL_CTX_get0_private_drbg(ctx);
861     if (drbg == NULL)
862         return 0;
863
864     ret = RAND_DRBG_bytes(drbg, buf, num);
865     return ret;
866 }
867
868 int RAND_priv_bytes(unsigned char *buf, int num)
869 {
870     return rand_priv_bytes_ex(NULL, buf, num);
871 }
872
873 int rand_bytes_ex(OPENSSL_CTX *ctx, unsigned char *buf, int num)
874 {
875     RAND_DRBG *drbg;
876     int ret;
877     const RAND_METHOD *meth = RAND_get_rand_method();
878
879     if (meth != RAND_OpenSSL()) {
880         if (meth->bytes != NULL)
881             return meth->bytes(buf, num);
882         RANDerr(RAND_F_RAND_BYTES_EX, RAND_R_FUNC_NOT_IMPLEMENTED);
883         return -1;
884     }
885
886     drbg = OPENSSL_CTX_get0_public_drbg(ctx);
887     if (drbg == NULL)
888         return 0;
889
890     ret = RAND_DRBG_bytes(drbg, buf, num);
891     return ret;
892 }
893
894 int RAND_bytes(unsigned char *buf, int num)
895 {
896     return rand_bytes_ex(NULL, buf, num);
897 }
898
899 #if !defined(OPENSSL_NO_DEPRECATED_1_1_0) && !defined(FIPS_MODE)
900 int RAND_pseudo_bytes(unsigned char *buf, int num)
901 {
902     const RAND_METHOD *meth = RAND_get_rand_method();
903
904     if (meth->pseudorand != NULL)
905         return meth->pseudorand(buf, num);
906     return -1;
907 }
908 #endif
909
910 int RAND_status(void)
911 {
912     const RAND_METHOD *meth = RAND_get_rand_method();
913
914     if (meth->status != NULL)
915         return meth->status();
916     return 0;
917 }