ec key validation checks updated
[openssl.git] / crypto / rand / rand_lib.c
1 /*
2  * Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the Apache License 2.0 (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_inited = 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 != NULL && 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->seed_pool != NULL) {
150         pool = drbg->seed_pool;
151         pool->entropy_requested = entropy;
152     } else {
153         pool = rand_pool_new(entropy, min_len, max_len);
154         if (pool == NULL)
155             return 0;
156     }
157
158     if (drbg->parent != NULL) {
159         size_t bytes_needed = rand_pool_bytes_needed(pool, 1 /*entropy_factor*/);
160         unsigned char *buffer = rand_pool_add_begin(pool, bytes_needed);
161
162         if (buffer != NULL) {
163             size_t bytes = 0;
164
165             /*
166              * Get random from parent, include our state as additional input.
167              * Our lock is already held, but we need to lock our parent before
168              * generating bits from it. (Note: taking the lock will be a no-op
169              * if locking if drbg->parent->lock == NULL.)
170              */
171             rand_drbg_lock(drbg->parent);
172             if (RAND_DRBG_generate(drbg->parent,
173                                    buffer, bytes_needed,
174                                    prediction_resistance,
175                                    NULL, 0) != 0)
176                 bytes = bytes_needed;
177             drbg->reseed_next_counter
178                 = tsan_load(&drbg->parent->reseed_prop_counter);
179             rand_drbg_unlock(drbg->parent);
180
181             rand_pool_add_end(pool, bytes, 8 * bytes);
182             entropy_available = rand_pool_entropy_available(pool);
183         }
184
185     } else {
186         if (prediction_resistance) {
187             /*
188              * We don't have any entropy sources that comply with the NIST
189              * standard to provide prediction resistance (see NIST SP 800-90C,
190              * Section 5.4).
191              */
192             RANDerr(RAND_F_RAND_DRBG_GET_ENTROPY,
193                     RAND_R_PREDICTION_RESISTANCE_NOT_SUPPORTED);
194             goto err;
195         }
196
197         /* Get entropy by polling system entropy sources. */
198         entropy_available = rand_pool_acquire_entropy(pool);
199     }
200
201     if (entropy_available > 0) {
202         ret   = rand_pool_length(pool);
203         *pout = rand_pool_detach(pool);
204     }
205
206  err:
207     if (drbg->seed_pool == NULL)
208         rand_pool_free(pool);
209     return ret;
210 }
211
212 /*
213  * Implements the cleanup_entropy() callback (see RAND_DRBG_set_callbacks())
214  *
215  */
216 void rand_drbg_cleanup_entropy(RAND_DRBG *drbg,
217                                unsigned char *out, size_t outlen)
218 {
219     if (drbg->seed_pool == NULL)
220         OPENSSL_secure_clear_free(out, outlen);
221 }
222
223
224 /*
225  * Implements the get_nonce() callback (see RAND_DRBG_set_callbacks())
226  *
227  */
228 size_t rand_drbg_get_nonce(RAND_DRBG *drbg,
229                            unsigned char **pout,
230                            int entropy, size_t min_len, size_t max_len)
231 {
232     size_t ret = 0;
233     RAND_POOL *pool;
234
235     struct {
236         void * instance;
237         int count;
238     } data;
239
240     memset(&data, 0, sizeof(data));
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(RAND_POOL *pool, unsigned char **pout)
284 {
285     size_t ret = 0;
286
287     if (rand_pool_add_additional_data(pool) == 0)
288         goto err;
289
290     ret = rand_pool_length(pool);
291     *pout = rand_pool_detach(pool);
292
293  err:
294     return ret;
295 }
296
297 void rand_drbg_cleanup_additional_data(RAND_POOL *pool, unsigned char *out)
298 {
299     rand_pool_reattach(pool, out);
300 }
301
302 void rand_fork(void)
303 {
304     rand_fork_count++;
305 }
306
307 DEFINE_RUN_ONCE_STATIC(do_rand_init)
308 {
309 #ifndef OPENSSL_NO_ENGINE
310     rand_engine_lock = CRYPTO_THREAD_lock_new();
311     if (rand_engine_lock == NULL)
312         return 0;
313 #endif
314
315     rand_meth_lock = CRYPTO_THREAD_lock_new();
316     if (rand_meth_lock == NULL)
317         goto err1;
318
319     rand_nonce_lock = CRYPTO_THREAD_lock_new();
320     if (rand_nonce_lock == NULL)
321         goto err2;
322
323     if (!rand_pool_init())
324         goto err3;
325
326     rand_inited = 1;
327     return 1;
328
329 err3:
330     CRYPTO_THREAD_lock_free(rand_nonce_lock);
331     rand_nonce_lock = NULL;
332 err2:
333     CRYPTO_THREAD_lock_free(rand_meth_lock);
334     rand_meth_lock = NULL;
335 err1:
336 #ifndef OPENSSL_NO_ENGINE
337     CRYPTO_THREAD_lock_free(rand_engine_lock);
338     rand_engine_lock = NULL;
339 #endif
340     return 0;
341 }
342
343 void rand_cleanup_int(void)
344 {
345     const RAND_METHOD *meth = default_RAND_meth;
346
347     if (!rand_inited)
348         return;
349
350     if (meth != NULL && meth->cleanup != NULL)
351         meth->cleanup();
352     RAND_set_rand_method(NULL);
353     rand_pool_cleanup();
354 #ifndef OPENSSL_NO_ENGINE
355     CRYPTO_THREAD_lock_free(rand_engine_lock);
356     rand_engine_lock = NULL;
357 #endif
358     CRYPTO_THREAD_lock_free(rand_meth_lock);
359     rand_meth_lock = NULL;
360     CRYPTO_THREAD_lock_free(rand_nonce_lock);
361     rand_nonce_lock = NULL;
362     rand_inited = 0;
363 }
364
365 /*
366  * RAND_close_seed_files() ensures that any seed file decriptors are
367  * closed after use.
368  */
369 void RAND_keep_random_devices_open(int keep)
370 {
371     if (RUN_ONCE(&rand_init, do_rand_init))
372         rand_pool_keep_random_devices_open(keep);
373 }
374
375 /*
376  * RAND_poll() reseeds the default RNG using random input
377  *
378  * The random input is obtained from polling various entropy
379  * sources which depend on the operating system and are
380  * configurable via the --with-rand-seed configure option.
381  */
382 int RAND_poll(void)
383 {
384     int ret = 0;
385
386     RAND_POOL *pool = NULL;
387
388     const RAND_METHOD *meth = RAND_get_rand_method();
389
390     if (meth == RAND_OpenSSL()) {
391         /* fill random pool and seed the master DRBG */
392         RAND_DRBG *drbg = RAND_DRBG_get0_master();
393
394         if (drbg == NULL)
395             return 0;
396
397         rand_drbg_lock(drbg);
398         ret = rand_drbg_restart(drbg, NULL, 0, 0);
399         rand_drbg_unlock(drbg);
400
401         return ret;
402
403     } else {
404         /* fill random pool and seed the current legacy RNG */
405         pool = rand_pool_new(RAND_DRBG_STRENGTH,
406                              (RAND_DRBG_STRENGTH + 7) / 8,
407                              RAND_POOL_MAX_LENGTH);
408         if (pool == NULL)
409             return 0;
410
411         if (rand_pool_acquire_entropy(pool) == 0)
412             goto err;
413
414         if (meth->add == NULL
415             || meth->add(rand_pool_buffer(pool),
416                          rand_pool_length(pool),
417                          (rand_pool_entropy(pool) / 8.0)) == 0)
418             goto err;
419
420         ret = 1;
421     }
422
423 err:
424     rand_pool_free(pool);
425     return ret;
426 }
427
428 /*
429  * Allocate memory and initialize a new random pool
430  */
431
432 RAND_POOL *rand_pool_new(int entropy_requested, size_t min_len, size_t max_len)
433 {
434     RAND_POOL *pool = OPENSSL_zalloc(sizeof(*pool));
435
436     if (pool == NULL) {
437         RANDerr(RAND_F_RAND_POOL_NEW, ERR_R_MALLOC_FAILURE);
438         return NULL;
439     }
440
441     pool->min_len = min_len;
442     pool->max_len = (max_len > RAND_POOL_MAX_LENGTH) ?
443         RAND_POOL_MAX_LENGTH : max_len;
444
445     pool->buffer = OPENSSL_secure_zalloc(pool->max_len);
446     if (pool->buffer == NULL) {
447         RANDerr(RAND_F_RAND_POOL_NEW, ERR_R_MALLOC_FAILURE);
448         goto err;
449     }
450
451     pool->entropy_requested = entropy_requested;
452
453     return pool;
454
455 err:
456     OPENSSL_free(pool);
457     return NULL;
458 }
459
460 /*
461  * Attach new random pool to the given buffer
462  *
463  * This function is intended to be used only for feeding random data
464  * provided by RAND_add() and RAND_seed() into the <master> DRBG.
465  */
466 RAND_POOL *rand_pool_attach(const unsigned char *buffer, size_t len,
467                             size_t entropy)
468 {
469     RAND_POOL *pool = OPENSSL_zalloc(sizeof(*pool));
470
471     if (pool == NULL) {
472         RANDerr(RAND_F_RAND_POOL_ATTACH, ERR_R_MALLOC_FAILURE);
473         return NULL;
474     }
475
476     /*
477      * The const needs to be cast away, but attached buffers will not be
478      * modified (in contrary to allocated buffers which are zeroed and
479      * freed in the end).
480      */
481     pool->buffer = (unsigned char *) buffer;
482     pool->len = len;
483
484     pool->attached = 1;
485
486     pool->min_len = pool->max_len = pool->len;
487     pool->entropy = entropy;
488
489     return pool;
490 }
491
492 /*
493  * Free |pool|, securely erasing its buffer.
494  */
495 void rand_pool_free(RAND_POOL *pool)
496 {
497     if (pool == NULL)
498         return;
499
500     /*
501      * Although it would be advisable from a cryptographical viewpoint,
502      * we are not allowed to clear attached buffers, since they are passed
503      * to rand_pool_attach() as `const unsigned char*`.
504      * (see corresponding comment in rand_pool_attach()).
505      */
506     if (!pool->attached)
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() or to re-attach it
539  * again to the pool using rand_pool_reattach().
540  */
541 unsigned char *rand_pool_detach(RAND_POOL *pool)
542 {
543     unsigned char *ret = pool->buffer;
544     pool->buffer = NULL;
545     pool->entropy = 0;
546     return ret;
547 }
548
549 /*
550  * Re-attach the |pool| buffer. It is only allowed to pass
551  * the |buffer| which was previously detached from the same pool.
552  */
553 void rand_pool_reattach(RAND_POOL *pool, unsigned char *buffer)
554 {
555     pool->buffer = buffer;
556     OPENSSL_cleanse(pool->buffer, pool->len);
557     pool->len = 0;
558 }
559
560 /*
561  * If |entropy_factor| bits contain 1 bit of entropy, how many bytes does one
562  * need to obtain at least |bits| bits of entropy?
563  */
564 #define ENTROPY_TO_BYTES(bits, entropy_factor) \
565     (((bits) * (entropy_factor) + 7) / 8)
566
567
568 /*
569  * Checks whether the |pool|'s entropy is available to the caller.
570  * This is the case when entropy count and buffer length are high enough.
571  * Returns
572  *
573  *  |entropy|  if the entropy count and buffer size is large enough
574  *      0      otherwise
575  */
576 size_t rand_pool_entropy_available(RAND_POOL *pool)
577 {
578     if (pool->entropy < pool->entropy_requested)
579         return 0;
580
581     if (pool->len < pool->min_len)
582         return 0;
583
584     return pool->entropy;
585 }
586
587 /*
588  * Returns the (remaining) amount of entropy needed to fill
589  * the random pool.
590  */
591
592 size_t rand_pool_entropy_needed(RAND_POOL *pool)
593 {
594     if (pool->entropy < pool->entropy_requested)
595         return pool->entropy_requested - pool->entropy;
596
597     return 0;
598 }
599
600 /*
601  * Returns the number of bytes needed to fill the pool, assuming
602  * the input has 1 / |entropy_factor| entropy bits per data bit.
603  * In case of an error, 0 is returned.
604  */
605
606 size_t rand_pool_bytes_needed(RAND_POOL *pool, unsigned int entropy_factor)
607 {
608     size_t bytes_needed;
609     size_t entropy_needed = rand_pool_entropy_needed(pool);
610
611     if (entropy_factor < 1) {
612         RANDerr(RAND_F_RAND_POOL_BYTES_NEEDED, RAND_R_ARGUMENT_OUT_OF_RANGE);
613         return 0;
614     }
615
616     bytes_needed = ENTROPY_TO_BYTES(entropy_needed, entropy_factor);
617
618     if (bytes_needed > pool->max_len - pool->len) {
619         /* not enough space left */
620         RANDerr(RAND_F_RAND_POOL_BYTES_NEEDED, RAND_R_RANDOM_POOL_OVERFLOW);
621         return 0;
622     }
623
624     if (pool->len < pool->min_len &&
625         bytes_needed < pool->min_len - pool->len)
626         /* to meet the min_len requirement */
627         bytes_needed = pool->min_len - pool->len;
628
629     return bytes_needed;
630 }
631
632 /* Returns the remaining number of bytes available */
633 size_t rand_pool_bytes_remaining(RAND_POOL *pool)
634 {
635     return pool->max_len - pool->len;
636 }
637
638 /*
639  * Add random bytes to the random pool.
640  *
641  * It is expected that the |buffer| contains |len| bytes of
642  * random input which contains at least |entropy| bits of
643  * randomness.
644  *
645  * Returns 1 if the added amount is adequate, otherwise 0
646  */
647 int 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 (pool->buffer == NULL) {
656         RANDerr(RAND_F_RAND_POOL_ADD, ERR_R_INTERNAL_ERROR);
657         return 0;
658     }
659
660     if (len > 0) {
661         memcpy(pool->buffer + pool->len, buffer, len);
662         pool->len += len;
663         pool->entropy += entropy;
664     }
665
666     return 1;
667 }
668
669 /*
670  * Start to add random bytes to the random pool in-place.
671  *
672  * Reserves the next |len| bytes for adding random bytes in-place
673  * and returns a pointer to the buffer.
674  * The caller is allowed to copy up to |len| bytes into the buffer.
675  * If |len| == 0 this is considered a no-op and a NULL pointer
676  * is returned without producing an error message.
677  *
678  * After updating the buffer, rand_pool_add_end() needs to be called
679  * to finish the udpate operation (see next comment).
680  */
681 unsigned char *rand_pool_add_begin(RAND_POOL *pool, size_t len)
682 {
683     if (len == 0)
684         return NULL;
685
686     if (len > pool->max_len - pool->len) {
687         RANDerr(RAND_F_RAND_POOL_ADD_BEGIN, RAND_R_RANDOM_POOL_OVERFLOW);
688         return NULL;
689     }
690
691     if (pool->buffer == NULL) {
692         RANDerr(RAND_F_RAND_POOL_ADD_BEGIN, ERR_R_INTERNAL_ERROR);
693         return NULL;
694     }
695
696     return pool->buffer + pool->len;
697 }
698
699 /*
700  * Finish to add random bytes to the random pool in-place.
701  *
702  * Finishes an in-place update of the random pool started by
703  * rand_pool_add_begin() (see previous comment).
704  * It is expected that |len| bytes of random input have been added
705  * to the buffer which contain at least |entropy| bits of randomness.
706  * It is allowed to add less bytes than originally reserved.
707  */
708 int rand_pool_add_end(RAND_POOL *pool, size_t len, size_t entropy)
709 {
710     if (len > pool->max_len - pool->len) {
711         RANDerr(RAND_F_RAND_POOL_ADD_END, RAND_R_RANDOM_POOL_OVERFLOW);
712         return 0;
713     }
714
715     if (len > 0) {
716         pool->len += len;
717         pool->entropy += entropy;
718     }
719
720     return 1;
721 }
722
723 int RAND_set_rand_method(const RAND_METHOD *meth)
724 {
725     if (!RUN_ONCE(&rand_init, do_rand_init))
726         return 0;
727
728     CRYPTO_THREAD_write_lock(rand_meth_lock);
729 #ifndef OPENSSL_NO_ENGINE
730     ENGINE_finish(funct_ref);
731     funct_ref = NULL;
732 #endif
733     default_RAND_meth = meth;
734     CRYPTO_THREAD_unlock(rand_meth_lock);
735     return 1;
736 }
737
738 const RAND_METHOD *RAND_get_rand_method(void)
739 {
740     const RAND_METHOD *tmp_meth = NULL;
741
742     if (!RUN_ONCE(&rand_init, do_rand_init))
743         return NULL;
744
745     CRYPTO_THREAD_write_lock(rand_meth_lock);
746     if (default_RAND_meth == NULL) {
747 #ifndef OPENSSL_NO_ENGINE
748         ENGINE *e;
749
750         /* If we have an engine that can do RAND, use it. */
751         if ((e = ENGINE_get_default_RAND()) != NULL
752                 && (tmp_meth = ENGINE_get_RAND(e)) != NULL) {
753             funct_ref = e;
754             default_RAND_meth = tmp_meth;
755         } else {
756             ENGINE_finish(e);
757             default_RAND_meth = &rand_meth;
758         }
759 #else
760         default_RAND_meth = &rand_meth;
761 #endif
762     }
763     tmp_meth = default_RAND_meth;
764     CRYPTO_THREAD_unlock(rand_meth_lock);
765     return tmp_meth;
766 }
767
768 #ifndef OPENSSL_NO_ENGINE
769 int RAND_set_rand_engine(ENGINE *engine)
770 {
771     const RAND_METHOD *tmp_meth = NULL;
772
773     if (!RUN_ONCE(&rand_init, do_rand_init))
774         return 0;
775
776     if (engine != NULL) {
777         if (!ENGINE_init(engine))
778             return 0;
779         tmp_meth = ENGINE_get_RAND(engine);
780         if (tmp_meth == NULL) {
781             ENGINE_finish(engine);
782             return 0;
783         }
784     }
785     CRYPTO_THREAD_write_lock(rand_engine_lock);
786     /* This function releases any prior ENGINE so call it first */
787     RAND_set_rand_method(tmp_meth);
788     funct_ref = engine;
789     CRYPTO_THREAD_unlock(rand_engine_lock);
790     return 1;
791 }
792 #endif
793
794 void RAND_seed(const void *buf, int num)
795 {
796     const RAND_METHOD *meth = RAND_get_rand_method();
797
798     if (meth->seed != NULL)
799         meth->seed(buf, num);
800 }
801
802 void RAND_add(const void *buf, int num, double randomness)
803 {
804     const RAND_METHOD *meth = RAND_get_rand_method();
805
806     if (meth->add != NULL)
807         meth->add(buf, num, randomness);
808 }
809
810 /*
811  * This function is not part of RAND_METHOD, so if we're not using
812  * the default method, then just call RAND_bytes().  Otherwise make
813  * sure we're instantiated and use the private DRBG.
814  */
815 int RAND_priv_bytes(unsigned char *buf, int num)
816 {
817     const RAND_METHOD *meth = RAND_get_rand_method();
818     RAND_DRBG *drbg;
819     int ret;
820
821     if (meth != RAND_OpenSSL())
822         return RAND_bytes(buf, num);
823
824     drbg = RAND_DRBG_get0_private();
825     if (drbg == NULL)
826         return 0;
827
828     ret = RAND_DRBG_bytes(drbg, buf, num);
829     return ret;
830 }
831
832 int RAND_bytes(unsigned char *buf, int num)
833 {
834     const RAND_METHOD *meth = RAND_get_rand_method();
835
836     if (meth->bytes != NULL)
837         return meth->bytes(buf, num);
838     RANDerr(RAND_F_RAND_BYTES, RAND_R_FUNC_NOT_IMPLEMENTED);
839     return -1;
840 }
841
842 #if !OPENSSL_API_1_1_0
843 int RAND_pseudo_bytes(unsigned char *buf, int num)
844 {
845     const RAND_METHOD *meth = RAND_get_rand_method();
846
847     if (meth->pseudorand != NULL)
848         return meth->pseudorand(buf, num);
849     return -1;
850 }
851 #endif
852
853 int RAND_status(void)
854 {
855     const RAND_METHOD *meth = RAND_get_rand_method();
856
857     if (meth->status != NULL)
858         return meth->status();
859     return 0;
860 }