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