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