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