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