Remove ambiguity in rand_pool_add[_end] return value
[openssl.git] / crypto / rand / rand_lib.c
1 /*
2  * Copyright 1995-2018 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 #ifdef OPENSSL_SYS_UNIX
19 # include <sys/types.h>
20 # include <unistd.h>
21 # include <sys/time.h>
22 #endif
23 #include "e_os.h"
24
25 /* Macro to convert two thirty two bit values into a sixty four bit one */
26 #define TWO32TO64(a, b) ((((uint64_t)(a)) << 32) + (b))
27
28 /*
29  * Check for the existence and support of POSIX timers.  The standard
30  * says that the _POSIX_TIMERS macro will have a positive value if they
31  * are available.
32  *
33  * However, we want an additional constraint: that the timer support does
34  * not require an extra library dependency.  Early versions of glibc
35  * require -lrt to be specified on the link line to access the timers,
36  * so this needs to be checked for.
37  *
38  * It is worse because some libraries define __GLIBC__ but don't
39  * support the version testing macro (e.g. uClibc).  This means
40  * an extra check is needed.
41  *
42  * The final condition is:
43  *      "have posix timers and either not glibc or glibc without -lrt"
44  *
45  * The nested #if sequences are required to avoid using a parameterised
46  * macro that might be undefined.
47  */
48 #undef OSSL_POSIX_TIMER_OKAY
49 #if defined(_POSIX_TIMERS) && _POSIX_TIMERS > 0
50 # if defined(__GLIBC__)
51 #  if defined(__GLIBC_PREREQ)
52 #   if __GLIBC_PREREQ(2, 17)
53 #    define OSSL_POSIX_TIMER_OKAY
54 #   endif
55 #  endif
56 # else
57 #  define OSSL_POSIX_TIMER_OKAY
58 # endif
59 #endif
60
61 #ifndef OPENSSL_NO_ENGINE
62 /* non-NULL if default_RAND_meth is ENGINE-provided */
63 static ENGINE *funct_ref;
64 static CRYPTO_RWLOCK *rand_engine_lock;
65 #endif
66 static CRYPTO_RWLOCK *rand_meth_lock;
67 static const RAND_METHOD *default_RAND_meth;
68 static CRYPTO_ONCE rand_init = CRYPTO_ONCE_STATIC_INIT;
69
70 int rand_fork_count;
71
72 #ifdef OPENSSL_RAND_SEED_RDTSC
73 /*
74  * IMPORTANT NOTE:  It is not currently possible to use this code
75  * because we are not sure about the amount of randomness it provides.
76  * Some SP900 tests have been run, but there is internal skepticism.
77  * So for now this code is not used.
78  */
79 # error "RDTSC enabled?  Should not be possible!"
80
81 /*
82  * Acquire entropy from high-speed clock
83  *
84  * Since we get some randomness from the low-order bits of the
85  * high-speed clock, it can help.
86  *
87  * Returns the total entropy count, if it exceeds the requested
88  * entropy count. Otherwise, returns an entropy count of 0.
89  */
90 size_t rand_acquire_entropy_from_tsc(RAND_POOL *pool)
91 {
92     unsigned char c;
93     int i;
94
95     if ((OPENSSL_ia32cap_P[0] & (1 << 4)) != 0) {
96         for (i = 0; i < TSC_READ_COUNT; i++) {
97             c = (unsigned char)(OPENSSL_rdtsc() & 0xFF);
98             rand_pool_add(pool, &c, 1, 4);
99         }
100     }
101     return rand_pool_entropy_available(pool);
102 }
103 #endif
104
105 #ifdef OPENSSL_RAND_SEED_RDCPU
106 size_t OPENSSL_ia32_rdseed_bytes(unsigned char *buf, size_t len);
107 size_t OPENSSL_ia32_rdrand_bytes(unsigned char *buf, size_t len);
108
109 extern unsigned int OPENSSL_ia32cap_P[];
110
111 /*
112  * Acquire entropy using Intel-specific cpu instructions
113  *
114  * Uses the RDSEED instruction if available, otherwise uses
115  * RDRAND if available.
116  *
117  * For the differences between RDSEED and RDRAND, and why RDSEED
118  * is the preferred choice, see https://goo.gl/oK3KcN
119  *
120  * Returns the total entropy count, if it exceeds the requested
121  * entropy count. Otherwise, returns an entropy count of 0.
122  */
123 size_t rand_acquire_entropy_from_cpu(RAND_POOL *pool)
124 {
125     size_t bytes_needed;
126     unsigned char *buffer;
127
128     bytes_needed = rand_pool_bytes_needed(pool, 8 /*entropy_per_byte*/);
129     if (bytes_needed > 0) {
130         buffer = rand_pool_add_begin(pool, bytes_needed);
131
132         if (buffer != NULL) {
133             /* Whichever comes first, use RDSEED, RDRAND or nothing */
134             if ((OPENSSL_ia32cap_P[2] & (1 << 18)) != 0) {
135                 if (OPENSSL_ia32_rdseed_bytes(buffer, bytes_needed)
136                     == bytes_needed) {
137                     rand_pool_add_end(pool, bytes_needed, 8 * bytes_needed);
138                 }
139             } else if ((OPENSSL_ia32cap_P[1] & (1 << (62 - 32))) != 0) {
140                 if (OPENSSL_ia32_rdrand_bytes(buffer, bytes_needed)
141                     == bytes_needed) {
142                     rand_pool_add_end(pool, bytes_needed, 8 * bytes_needed);
143                 }
144             } else {
145                 rand_pool_add_end(pool, 0, 0);
146             }
147         }
148     }
149
150     return rand_pool_entropy_available(pool);
151 }
152 #endif
153
154
155 /*
156  * Implements the get_entropy() callback (see RAND_DRBG_set_callbacks())
157  *
158  * If the DRBG has a parent, then the required amount of entropy input
159  * is fetched using the parent's RAND_DRBG_generate().
160  *
161  * Otherwise, the entropy is polled from the system entropy sources
162  * using rand_pool_acquire_entropy().
163  *
164  * If a random pool has been added to the DRBG using RAND_add(), then
165  * its entropy will be used up first.
166  */
167 size_t rand_drbg_get_entropy(RAND_DRBG *drbg,
168                              unsigned char **pout,
169                              int entropy, size_t min_len, size_t max_len,
170                              int prediction_resistance)
171 {
172     size_t ret = 0;
173     size_t entropy_available = 0;
174     RAND_POOL *pool;
175
176     if (drbg->parent && drbg->strength > drbg->parent->strength) {
177         /*
178          * We currently don't support the algorithm from NIST SP 800-90C
179          * 10.1.2 to use a weaker DRBG as source
180          */
181         RANDerr(RAND_F_RAND_DRBG_GET_ENTROPY, RAND_R_PARENT_STRENGTH_TOO_WEAK);
182         return 0;
183     }
184
185     pool = rand_pool_new(entropy, min_len, max_len);
186     if (pool == NULL)
187         return 0;
188
189     if (drbg->pool) {
190         rand_pool_add(pool,
191                       rand_pool_buffer(drbg->pool),
192                       rand_pool_length(drbg->pool),
193                       rand_pool_entropy(drbg->pool));
194         rand_pool_free(drbg->pool);
195         drbg->pool = NULL;
196     }
197
198     if (drbg->parent) {
199         size_t bytes_needed = rand_pool_bytes_needed(pool, 8);
200         unsigned char *buffer = rand_pool_add_begin(pool, bytes_needed);
201
202         if (buffer != NULL) {
203             size_t bytes = 0;
204
205             /*
206              * Get random from parent, include our state as additional input.
207              * Our lock is already held, but we need to lock our parent before
208              * generating bits from it. (Note: taking the lock will be a no-op
209              * if locking if drbg->parent->lock == NULL.)
210              */
211             rand_drbg_lock(drbg->parent);
212             if (RAND_DRBG_generate(drbg->parent,
213                                    buffer, bytes_needed,
214                                    prediction_resistance,
215                                    (unsigned char *)drbg, sizeof(*drbg)) != 0)
216                 bytes = bytes_needed;
217             rand_drbg_unlock(drbg->parent);
218
219             rand_pool_add_end(pool, bytes, 8 * bytes);
220             entropy_available = rand_pool_entropy_available(pool);
221         }
222
223     } else {
224         if (prediction_resistance) {
225             /*
226              * We don't have any entropy sources that comply with the NIST
227              * standard to provide prediction resistance (see NIST SP 800-90C,
228              * Section 5.4).
229              */
230             RANDerr(RAND_F_RAND_DRBG_GET_ENTROPY,
231                     RAND_R_PREDICTION_RESISTANCE_NOT_SUPPORTED);
232             return 0;
233         }
234
235         /* Get entropy by polling system entropy sources. */
236         entropy_available = rand_pool_acquire_entropy(pool);
237     }
238
239     if (entropy_available > 0) {
240         ret   = rand_pool_length(pool);
241         *pout = rand_pool_detach(pool);
242     }
243
244     rand_pool_free(pool);
245     return ret;
246 }
247
248 /*
249  * Find a suitable source of time.  Start with the highest resolution source
250  * and work down to the slower ones.  This is added as additional data and
251  * isn't counted as randomness, so any result is acceptable.
252  *
253  * Returns 0 when we weren't able to find any time source
254  */
255 static uint64_t get_timer_bits(void)
256 {
257     uint64_t res = OPENSSL_rdtsc();
258
259     if (res != 0)
260         return res;
261 #if defined(_WIN32)
262     {
263         LARGE_INTEGER t;
264         FILETIME ft;
265
266         if (QueryPerformanceCounter(&t) != 0)
267             return t.QuadPart;
268         GetSystemTimeAsFileTime(&ft);
269         return TWO32TO64(ft.dwHighDateTime, ft.dwLowDateTime);
270     }
271 #elif defined(__sun) || defined(__hpux)
272     return gethrtime();
273 #elif defined(_AIX)
274     {
275         timebasestruct_t t;
276
277         read_wall_time(&t, TIMEBASE_SZ);
278         return TWO32TO64(t.tb_high, t.tb_low);
279     }
280 #else
281
282 # if defined(OSSL_POSIX_TIMER_OKAY)
283     {
284         struct timespec ts;
285         clockid_t cid;
286
287 #  ifdef CLOCK_BOOTTIME
288         cid = CLOCK_BOOTTIME;
289 #  elif defined(_POSIX_MONOTONIC_CLOCK)
290         cid = CLOCK_MONOTONIC;
291 #  else
292         cid = CLOCK_REALTIME;
293 #  endif
294
295         if (clock_gettime(cid, &ts) == 0)
296             return TWO32TO64(ts.tv_sec, ts.tv_nsec);
297     }
298 # endif
299 # if defined(__unix__) \
300      || (defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 200112L)
301     {
302         struct timeval tv;
303
304         if (gettimeofday(&tv, NULL) == 0)
305             return TWO32TO64(tv.tv_sec, tv.tv_usec);
306     }
307 # endif
308     {
309         time_t t = time(NULL);
310         if (t == (time_t)-1)
311             return 0;
312         return t;
313     }
314 #endif
315 }
316
317 /*
318  * Generate additional data that can be used for the drbg. The data does
319  * not need to contain entropy, but it's useful if it contains at least
320  * some bits that are unpredictable.
321  *
322  * Returns 0 on failure.
323  *
324  * On success it allocates a buffer at |*pout| and returns the length of
325  * the data. The buffer should get freed using OPENSSL_secure_clear_free().
326  */
327 size_t rand_drbg_get_additional_data(unsigned char **pout, size_t max_len)
328 {
329     RAND_POOL *pool;
330     CRYPTO_THREAD_ID thread_id;
331     size_t len;
332 #ifdef OPENSSL_SYS_UNIX
333     pid_t pid;
334 #elif defined(OPENSSL_SYS_WIN32)
335     DWORD pid;
336 #endif
337     uint64_t tbits;
338
339     pool = rand_pool_new(0, 0, max_len);
340     if (pool == NULL)
341         return 0;
342
343 #ifdef OPENSSL_SYS_UNIX
344     pid = getpid();
345     rand_pool_add(pool, (unsigned char *)&pid, sizeof(pid), 0);
346 #elif defined(OPENSSL_SYS_WIN32)
347     pid = GetCurrentProcessId();
348     rand_pool_add(pool, (unsigned char *)&pid, sizeof(pid), 0);
349 #endif
350
351     thread_id = CRYPTO_THREAD_get_current_id();
352     if (thread_id != 0)
353         rand_pool_add(pool, (unsigned char *)&thread_id, sizeof(thread_id), 0);
354
355     tbits = get_timer_bits();
356     if (tbits != 0)
357         rand_pool_add(pool, (unsigned char *)&tbits, sizeof(tbits), 0);
358
359     /* TODO: Use RDSEED? */
360
361     len = rand_pool_length(pool);
362     if (len != 0)
363         *pout = rand_pool_detach(pool);
364     rand_pool_free(pool);
365
366     return len;
367 }
368
369 /*
370  * Implements the cleanup_entropy() callback (see RAND_DRBG_set_callbacks())
371  *
372  */
373 void rand_drbg_cleanup_entropy(RAND_DRBG *drbg,
374                                unsigned char *out, size_t outlen)
375 {
376     OPENSSL_secure_clear_free(out, outlen);
377 }
378
379 void rand_fork()
380 {
381     rand_fork_count++;
382 }
383
384 DEFINE_RUN_ONCE_STATIC(do_rand_init)
385 {
386     int ret = 1;
387
388 #ifndef OPENSSL_NO_ENGINE
389     rand_engine_lock = CRYPTO_THREAD_lock_new();
390     ret &= rand_engine_lock != NULL;
391 #endif
392     rand_meth_lock = CRYPTO_THREAD_lock_new();
393     ret &= rand_meth_lock != NULL;
394
395     return ret;
396 }
397
398 void rand_cleanup_int(void)
399 {
400     const RAND_METHOD *meth = default_RAND_meth;
401
402     if (meth != NULL && meth->cleanup != NULL)
403         meth->cleanup();
404     RAND_set_rand_method(NULL);
405 #ifndef OPENSSL_NO_ENGINE
406     CRYPTO_THREAD_lock_free(rand_engine_lock);
407 #endif
408     CRYPTO_THREAD_lock_free(rand_meth_lock);
409 }
410
411 /*
412  * RAND_poll() reseeds the default RNG using random input
413  *
414  * The random input is obtained from polling various entropy
415  * sources which depend on the operating system and are
416  * configurable via the --with-rand-seed configure option.
417  */
418 int RAND_poll(void)
419 {
420     int ret = 0;
421
422     RAND_POOL *pool = NULL;
423
424     const RAND_METHOD *meth = RAND_get_rand_method();
425
426     if (meth == RAND_OpenSSL()) {
427         /* fill random pool and seed the master DRBG */
428         RAND_DRBG *drbg = RAND_DRBG_get0_master();
429
430         if (drbg == NULL)
431             return 0;
432
433         rand_drbg_lock(drbg);
434         ret = rand_drbg_restart(drbg, NULL, 0, 0);
435         rand_drbg_unlock(drbg);
436
437         return ret;
438
439     } else {
440         /* fill random pool and seed the current legacy RNG */
441         pool = rand_pool_new(RAND_DRBG_STRENGTH,
442                              RAND_DRBG_STRENGTH / 8,
443                              DRBG_MINMAX_FACTOR * (RAND_DRBG_STRENGTH / 8));
444         if (pool == NULL)
445             return 0;
446
447         if (rand_pool_acquire_entropy(pool) == 0)
448             goto err;
449
450         if (meth->add == NULL
451             || meth->add(rand_pool_buffer(pool),
452                          rand_pool_length(pool),
453                          (rand_pool_entropy(pool) / 8.0)) == 0)
454             goto err;
455
456         ret = 1;
457     }
458
459 err:
460     rand_pool_free(pool);
461     return ret;
462 }
463
464 /*
465  * Allocate memory and initialize a new random pool
466  */
467
468 RAND_POOL *rand_pool_new(int entropy, size_t min_len, size_t max_len)
469 {
470     RAND_POOL *pool = OPENSSL_zalloc(sizeof(*pool));
471
472     if (pool == NULL) {
473         RANDerr(RAND_F_RAND_POOL_NEW, ERR_R_MALLOC_FAILURE);
474         goto err;
475     }
476
477     pool->min_len = min_len;
478     pool->max_len = max_len;
479
480     pool->buffer = OPENSSL_secure_zalloc(pool->max_len);
481     if (pool->buffer == NULL) {
482         RANDerr(RAND_F_RAND_POOL_NEW, ERR_R_MALLOC_FAILURE);
483         goto err;
484     }
485
486     pool->requested_entropy = entropy;
487
488     return pool;
489
490 err:
491     OPENSSL_free(pool);
492     return NULL;
493 }
494
495 /*
496  * Free |pool|, securely erasing its buffer.
497  */
498 void rand_pool_free(RAND_POOL *pool)
499 {
500     if (pool == NULL)
501         return;
502
503     OPENSSL_secure_clear_free(pool->buffer, pool->max_len);
504     OPENSSL_free(pool);
505 }
506
507 /*
508  * Return the |pool|'s buffer to the caller (readonly).
509  */
510 const unsigned char *rand_pool_buffer(RAND_POOL *pool)
511 {
512     return pool->buffer;
513 }
514
515 /*
516  * Return the |pool|'s entropy to the caller.
517  */
518 size_t rand_pool_entropy(RAND_POOL *pool)
519 {
520     return pool->entropy;
521 }
522
523 /*
524  * Return the |pool|'s buffer length to the caller.
525  */
526 size_t rand_pool_length(RAND_POOL *pool)
527 {
528     return pool->len;
529 }
530
531 /*
532  * Detach the |pool| buffer and return it to the caller.
533  * It's the responsibility of the caller to free the buffer
534  * using OPENSSL_secure_clear_free().
535  */
536 unsigned char *rand_pool_detach(RAND_POOL *pool)
537 {
538     unsigned char *ret = pool->buffer;
539     pool->buffer = NULL;
540     return ret;
541 }
542
543
544 /*
545  * If every byte of the input contains |entropy_per_bytes| bits of entropy,
546  * how many bytes does one need to obtain at least |bits| bits of entropy?
547  */
548 #define ENTROPY_TO_BYTES(bits, entropy_per_bytes) \
549     (((bits) + ((entropy_per_bytes) - 1))/(entropy_per_bytes))
550
551
552 /*
553  * Checks whether the |pool|'s entropy is available to the caller.
554  * This is the case when entropy count and buffer length are high enough.
555  * Returns
556  *
557  *  |entropy|  if the entropy count and buffer size is large enough
558  *      0      otherwise
559  */
560 size_t rand_pool_entropy_available(RAND_POOL *pool)
561 {
562     if (pool->entropy < pool->requested_entropy)
563         return 0;
564
565     if (pool->len < pool->min_len)
566         return 0;
567
568     return pool->entropy;
569 }
570
571 /*
572  * Returns the (remaining) amount of entropy needed to fill
573  * the random pool.
574  */
575
576 size_t rand_pool_entropy_needed(RAND_POOL *pool)
577 {
578     if (pool->entropy < pool->requested_entropy)
579         return pool->requested_entropy - pool->entropy;
580
581     return 0;
582 }
583
584 /*
585  * Returns the number of bytes needed to fill the pool, assuming
586  * the input has 'entropy_per_byte' entropy bits per byte.
587  * In case of an error, 0 is returned.
588  */
589
590 size_t rand_pool_bytes_needed(RAND_POOL *pool, unsigned int entropy_per_byte)
591 {
592     size_t bytes_needed;
593     size_t entropy_needed = rand_pool_entropy_needed(pool);
594
595     if (entropy_per_byte < 1 || entropy_per_byte > 8) {
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_per_byte);
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     return bytes_needed;
614 }
615
616 /* Returns the remaining number of bytes available */
617 size_t rand_pool_bytes_remaining(RAND_POOL *pool)
618 {
619     return pool->max_len - pool->len;
620 }
621
622 /*
623  * Add random bytes to the random pool.
624  *
625  * It is expected that the |buffer| contains |len| bytes of
626  * random input which contains at least |entropy| bits of
627  * randomness.
628  *
629  * Returns 1 if the added amount is adequate, otherwise 0
630  */
631 int rand_pool_add(RAND_POOL *pool,
632                   const unsigned char *buffer, size_t len, size_t entropy)
633 {
634     if (len > pool->max_len - pool->len) {
635         RANDerr(RAND_F_RAND_POOL_ADD, RAND_R_ENTROPY_INPUT_TOO_LONG);
636         return 0;
637     }
638
639     if (len > 0) {
640         memcpy(pool->buffer + pool->len, buffer, len);
641         pool->len += len;
642         pool->entropy += entropy;
643     }
644
645     return 1;
646 }
647
648 /*
649  * Start to add random bytes to the random pool in-place.
650  *
651  * Reserves the next |len| bytes for adding random bytes in-place
652  * and returns a pointer to the buffer.
653  * The caller is allowed to copy up to |len| bytes into the buffer.
654  * If |len| == 0 this is considered a no-op and a NULL pointer
655  * is returned without producing an error message.
656  *
657  * After updating the buffer, rand_pool_add_end() needs to be called
658  * to finish the udpate operation (see next comment).
659  */
660 unsigned char *rand_pool_add_begin(RAND_POOL *pool, size_t len)
661 {
662     if (len == 0)
663         return NULL;
664
665     if (len > pool->max_len - pool->len) {
666         RANDerr(RAND_F_RAND_POOL_ADD_BEGIN, RAND_R_RANDOM_POOL_OVERFLOW);
667         return NULL;
668     }
669
670     return pool->buffer + pool->len;
671 }
672
673 /*
674  * Finish to add random bytes to the random pool in-place.
675  *
676  * Finishes an in-place update of the random pool started by
677  * rand_pool_add_begin() (see previous comment).
678  * It is expected that |len| bytes of random input have been added
679  * to the buffer which contain at least |entropy| bits of randomness.
680  * It is allowed to add less bytes than originally reserved.
681  */
682 int rand_pool_add_end(RAND_POOL *pool, size_t len, size_t entropy)
683 {
684     if (len > pool->max_len - pool->len) {
685         RANDerr(RAND_F_RAND_POOL_ADD_END, RAND_R_RANDOM_POOL_OVERFLOW);
686         return 0;
687     }
688
689     if (len > 0) {
690         pool->len += len;
691         pool->entropy += entropy;
692     }
693
694     return 1;
695 }
696
697 int RAND_set_rand_method(const RAND_METHOD *meth)
698 {
699     if (!RUN_ONCE(&rand_init, do_rand_init))
700         return 0;
701
702     CRYPTO_THREAD_write_lock(rand_meth_lock);
703 #ifndef OPENSSL_NO_ENGINE
704     ENGINE_finish(funct_ref);
705     funct_ref = NULL;
706 #endif
707     default_RAND_meth = meth;
708     CRYPTO_THREAD_unlock(rand_meth_lock);
709     return 1;
710 }
711
712 const RAND_METHOD *RAND_get_rand_method(void)
713 {
714     const RAND_METHOD *tmp_meth = NULL;
715
716     if (!RUN_ONCE(&rand_init, do_rand_init))
717         return NULL;
718
719     CRYPTO_THREAD_write_lock(rand_meth_lock);
720     if (default_RAND_meth == NULL) {
721 #ifndef OPENSSL_NO_ENGINE
722         ENGINE *e;
723
724         /* If we have an engine that can do RAND, use it. */
725         if ((e = ENGINE_get_default_RAND()) != NULL
726                 && (tmp_meth = ENGINE_get_RAND(e)) != NULL) {
727             funct_ref = e;
728             default_RAND_meth = tmp_meth;
729         } else {
730             ENGINE_finish(e);
731             default_RAND_meth = &rand_meth;
732         }
733 #else
734         default_RAND_meth = &rand_meth;
735 #endif
736     }
737     tmp_meth = default_RAND_meth;
738     CRYPTO_THREAD_unlock(rand_meth_lock);
739     return tmp_meth;
740 }
741
742 #ifndef OPENSSL_NO_ENGINE
743 int RAND_set_rand_engine(ENGINE *engine)
744 {
745     const RAND_METHOD *tmp_meth = NULL;
746
747     if (!RUN_ONCE(&rand_init, do_rand_init))
748         return 0;
749
750     if (engine != NULL) {
751         if (!ENGINE_init(engine))
752             return 0;
753         tmp_meth = ENGINE_get_RAND(engine);
754         if (tmp_meth == NULL) {
755             ENGINE_finish(engine);
756             return 0;
757         }
758     }
759     CRYPTO_THREAD_write_lock(rand_engine_lock);
760     /* This function releases any prior ENGINE so call it first */
761     RAND_set_rand_method(tmp_meth);
762     funct_ref = engine;
763     CRYPTO_THREAD_unlock(rand_engine_lock);
764     return 1;
765 }
766 #endif
767
768 void RAND_seed(const void *buf, int num)
769 {
770     const RAND_METHOD *meth = RAND_get_rand_method();
771
772     if (meth->seed != NULL)
773         meth->seed(buf, num);
774 }
775
776 void RAND_add(const void *buf, int num, double randomness)
777 {
778     const RAND_METHOD *meth = RAND_get_rand_method();
779
780     if (meth->add != NULL)
781         meth->add(buf, num, randomness);
782 }
783
784 /*
785  * This function is not part of RAND_METHOD, so if we're not using
786  * the default method, then just call RAND_bytes().  Otherwise make
787  * sure we're instantiated and use the private DRBG.
788  */
789 int RAND_priv_bytes(unsigned char *buf, int num)
790 {
791     const RAND_METHOD *meth = RAND_get_rand_method();
792     RAND_DRBG *drbg;
793     int ret;
794
795     if (meth != RAND_OpenSSL())
796         return RAND_bytes(buf, num);
797
798     drbg = RAND_DRBG_get0_private();
799     if (drbg == NULL)
800         return 0;
801
802     ret = RAND_DRBG_bytes(drbg, buf, num);
803     return ret;
804 }
805
806 int RAND_bytes(unsigned char *buf, int num)
807 {
808     const RAND_METHOD *meth = RAND_get_rand_method();
809
810     if (meth->bytes != NULL)
811         return meth->bytes(buf, num);
812     RANDerr(RAND_F_RAND_BYTES, RAND_R_FUNC_NOT_IMPLEMENTED);
813     return -1;
814 }
815
816 #if OPENSSL_API_COMPAT < 0x10100000L
817 int RAND_pseudo_bytes(unsigned char *buf, int num)
818 {
819     const RAND_METHOD *meth = RAND_get_rand_method();
820
821     if (meth->pseudorand != NULL)
822         return meth->pseudorand(buf, num);
823     return -1;
824 }
825 #endif
826
827 int RAND_status(void)
828 {
829     const RAND_METHOD *meth = RAND_get_rand_method();
830
831     if (meth->status != NULL)
832         return meth->status();
833     return 0;
834 }