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