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