xref: /src/crypto/openssl/crypto/rand/rand_pool.c (revision f25b8c9fb4f58cf61adb47d7570abe7caa6d385d)
1 /*
2  * Copyright 1995-2021 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 "crypto/rand.h"
15 #include <openssl/engine.h>
16 #include "internal/thread_once.h"
17 #include "crypto/rand_pool.h"
18 
19 /*
20  * Allocate memory and initialize a new random pool
21  */
ossl_rand_pool_new(int entropy_requested,int secure,size_t min_len,size_t max_len)22 RAND_POOL *ossl_rand_pool_new(int entropy_requested, int secure,
23     size_t min_len, size_t max_len)
24 {
25     RAND_POOL *pool = OPENSSL_zalloc(sizeof(*pool));
26     size_t min_alloc_size = RAND_POOL_MIN_ALLOCATION(secure);
27 
28     if (pool == NULL)
29         return NULL;
30 
31     pool->min_len = min_len;
32     pool->max_len = (max_len > RAND_POOL_MAX_LENGTH) ? RAND_POOL_MAX_LENGTH : max_len;
33     pool->alloc_len = min_len < min_alloc_size ? min_alloc_size : min_len;
34     if (pool->alloc_len > pool->max_len)
35         pool->alloc_len = pool->max_len;
36 
37     if (secure)
38         pool->buffer = OPENSSL_secure_zalloc(pool->alloc_len);
39     else
40         pool->buffer = OPENSSL_zalloc(pool->alloc_len);
41 
42     if (pool->buffer == NULL)
43         goto err;
44 
45     pool->entropy_requested = entropy_requested;
46     pool->secure = secure;
47     return pool;
48 
49 err:
50     OPENSSL_free(pool);
51     return NULL;
52 }
53 
54 /*
55  * Attach new random pool to the given buffer
56  *
57  * This function is intended to be used only for feeding random data
58  * provided by RAND_add() and RAND_seed() into the <master> DRBG.
59  */
ossl_rand_pool_attach(const unsigned char * buffer,size_t len,size_t entropy)60 RAND_POOL *ossl_rand_pool_attach(const unsigned char *buffer, size_t len,
61     size_t entropy)
62 {
63     RAND_POOL *pool = OPENSSL_zalloc(sizeof(*pool));
64 
65     if (pool == NULL)
66         return NULL;
67 
68     /*
69      * The const needs to be cast away, but attached buffers will not be
70      * modified (in contrary to allocated buffers which are zeroed and
71      * freed in the end).
72      */
73     pool->buffer = (unsigned char *)buffer;
74     pool->len = len;
75 
76     pool->attached = 1;
77 
78     pool->min_len = pool->max_len = pool->alloc_len = pool->len;
79     pool->entropy = entropy;
80 
81     return pool;
82 }
83 
84 /*
85  * Free |pool|, securely erasing its buffer.
86  */
ossl_rand_pool_free(RAND_POOL * pool)87 void ossl_rand_pool_free(RAND_POOL *pool)
88 {
89     if (pool == NULL)
90         return;
91 
92     /*
93      * Although it would be advisable from a cryptographical viewpoint,
94      * we are not allowed to clear attached buffers, since they are passed
95      * to ossl_rand_pool_attach() as `const unsigned char*`.
96      * (see corresponding comment in ossl_rand_pool_attach()).
97      */
98     if (!pool->attached) {
99         if (pool->secure)
100             OPENSSL_secure_clear_free(pool->buffer, pool->alloc_len);
101         else
102             OPENSSL_clear_free(pool->buffer, pool->alloc_len);
103     }
104 
105     OPENSSL_free(pool);
106 }
107 
108 /*
109  * Return the |pool|'s buffer to the caller (readonly).
110  */
ossl_rand_pool_buffer(RAND_POOL * pool)111 const unsigned char *ossl_rand_pool_buffer(RAND_POOL *pool)
112 {
113     return pool->buffer;
114 }
115 
116 /*
117  * Return the |pool|'s entropy to the caller.
118  */
ossl_rand_pool_entropy(RAND_POOL * pool)119 size_t ossl_rand_pool_entropy(RAND_POOL *pool)
120 {
121     return pool->entropy;
122 }
123 
124 /*
125  * Return the |pool|'s buffer length to the caller.
126  */
ossl_rand_pool_length(RAND_POOL * pool)127 size_t ossl_rand_pool_length(RAND_POOL *pool)
128 {
129     return pool->len;
130 }
131 
132 /*
133  * Detach the |pool| buffer and return it to the caller.
134  * It's the responsibility of the caller to free the buffer
135  * using OPENSSL_secure_clear_free() or to re-attach it
136  * again to the pool using ossl_rand_pool_reattach().
137  */
ossl_rand_pool_detach(RAND_POOL * pool)138 unsigned char *ossl_rand_pool_detach(RAND_POOL *pool)
139 {
140     unsigned char *ret = pool->buffer;
141     pool->buffer = NULL;
142     pool->entropy = 0;
143     return ret;
144 }
145 
146 /*
147  * Re-attach the |pool| buffer. It is only allowed to pass
148  * the |buffer| which was previously detached from the same pool.
149  */
ossl_rand_pool_reattach(RAND_POOL * pool,unsigned char * buffer)150 void ossl_rand_pool_reattach(RAND_POOL *pool, unsigned char *buffer)
151 {
152     pool->buffer = buffer;
153     OPENSSL_cleanse(pool->buffer, pool->len);
154     pool->len = 0;
155 }
156 
157 /*
158  * If |entropy_factor| bits contain 1 bit of entropy, how many bytes does one
159  * need to obtain at least |bits| bits of entropy?
160  */
161 #define ENTROPY_TO_BYTES(bits, entropy_factor) \
162     (((bits) * (entropy_factor) + 7) / 8)
163 
164 /*
165  * Checks whether the |pool|'s entropy is available to the caller.
166  * This is the case when entropy count and buffer length are high enough.
167  * Returns
168  *
169  *  |entropy|  if the entropy count and buffer size is large enough
170  *      0      otherwise
171  */
ossl_rand_pool_entropy_available(RAND_POOL * pool)172 size_t ossl_rand_pool_entropy_available(RAND_POOL *pool)
173 {
174     if (pool->entropy < pool->entropy_requested)
175         return 0;
176 
177     if (pool->len < pool->min_len)
178         return 0;
179 
180     return pool->entropy;
181 }
182 
183 /*
184  * Returns the (remaining) amount of entropy needed to fill
185  * the random pool.
186  */
187 
ossl_rand_pool_entropy_needed(RAND_POOL * pool)188 size_t ossl_rand_pool_entropy_needed(RAND_POOL *pool)
189 {
190     if (pool->entropy < pool->entropy_requested)
191         return pool->entropy_requested - pool->entropy;
192 
193     return 0;
194 }
195 
196 /* Increase the allocation size -- not usable for an attached pool */
rand_pool_grow(RAND_POOL * pool,size_t len)197 static int rand_pool_grow(RAND_POOL *pool, size_t len)
198 {
199     if (len > pool->alloc_len - pool->len) {
200         unsigned char *p;
201         const size_t limit = pool->max_len / 2;
202         size_t newlen = pool->alloc_len;
203 
204         if (pool->attached || len > pool->max_len - pool->len) {
205             ERR_raise(ERR_LIB_RAND, ERR_R_INTERNAL_ERROR);
206             return 0;
207         }
208 
209         do
210             newlen = newlen < limit ? newlen * 2 : pool->max_len;
211         while (len > newlen - pool->len);
212 
213         if (pool->secure)
214             p = OPENSSL_secure_zalloc(newlen);
215         else
216             p = OPENSSL_zalloc(newlen);
217         if (p == NULL)
218             return 0;
219         memcpy(p, pool->buffer, pool->len);
220         if (pool->secure)
221             OPENSSL_secure_clear_free(pool->buffer, pool->alloc_len);
222         else
223             OPENSSL_clear_free(pool->buffer, pool->alloc_len);
224         pool->buffer = p;
225         pool->alloc_len = newlen;
226     }
227     return 1;
228 }
229 
230 /*
231  * Returns the number of bytes needed to fill the pool, assuming
232  * the input has 1 / |entropy_factor| entropy bits per data bit.
233  * In case of an error, 0 is returned.
234  */
235 
ossl_rand_pool_bytes_needed(RAND_POOL * pool,unsigned int entropy_factor)236 size_t ossl_rand_pool_bytes_needed(RAND_POOL *pool, unsigned int entropy_factor)
237 {
238     size_t bytes_needed;
239     size_t entropy_needed = ossl_rand_pool_entropy_needed(pool);
240 
241     if (entropy_factor < 1) {
242         ERR_raise(ERR_LIB_RAND, RAND_R_ARGUMENT_OUT_OF_RANGE);
243         return 0;
244     }
245 
246     bytes_needed = ENTROPY_TO_BYTES(entropy_needed, entropy_factor);
247 
248     if (bytes_needed > pool->max_len - pool->len) {
249         /* not enough space left */
250         ERR_raise_data(ERR_LIB_RAND, RAND_R_RANDOM_POOL_OVERFLOW,
251             "entropy_factor=%u, entropy_needed=%zu, bytes_needed=%zu,"
252             "pool->max_len=%zu, pool->len=%zu",
253             entropy_factor, entropy_needed, bytes_needed,
254             pool->max_len, pool->len);
255         return 0;
256     }
257 
258     if (pool->len < pool->min_len && bytes_needed < pool->min_len - pool->len)
259         /* to meet the min_len requirement */
260         bytes_needed = pool->min_len - pool->len;
261 
262     /*
263      * Make sure the buffer is large enough for the requested amount
264      * of data. This guarantees that existing code patterns where
265      * ossl_rand_pool_add_begin, ossl_rand_pool_add_end or ossl_rand_pool_add
266      * are used to collect entropy data without any error handling
267      * whatsoever, continue to be valid.
268      * Furthermore if the allocation here fails once, make sure that
269      * we don't fall back to a less secure or even blocking random source,
270      * as that could happen by the existing code patterns.
271      * This is not a concern for additional data, therefore that
272      * is not needed if rand_pool_grow fails in other places.
273      */
274     if (!rand_pool_grow(pool, bytes_needed)) {
275         /* persistent error for this pool */
276         pool->max_len = pool->len = 0;
277         return 0;
278     }
279 
280     return bytes_needed;
281 }
282 
283 /* Returns the remaining number of bytes available */
ossl_rand_pool_bytes_remaining(RAND_POOL * pool)284 size_t ossl_rand_pool_bytes_remaining(RAND_POOL *pool)
285 {
286     return pool->max_len - pool->len;
287 }
288 
289 /*
290  * Add random bytes to the random pool.
291  *
292  * It is expected that the |buffer| contains |len| bytes of
293  * random input which contains at least |entropy| bits of
294  * randomness.
295  *
296  * Returns 1 if the added amount is adequate, otherwise 0
297  */
ossl_rand_pool_add(RAND_POOL * pool,const unsigned char * buffer,size_t len,size_t entropy)298 int ossl_rand_pool_add(RAND_POOL *pool,
299     const unsigned char *buffer, size_t len, size_t entropy)
300 {
301     if (len > pool->max_len - pool->len) {
302         ERR_raise(ERR_LIB_RAND, RAND_R_ENTROPY_INPUT_TOO_LONG);
303         return 0;
304     }
305 
306     if (pool->buffer == NULL) {
307         ERR_raise(ERR_LIB_RAND, ERR_R_INTERNAL_ERROR);
308         return 0;
309     }
310 
311     if (len > 0) {
312         /*
313          * This is to protect us from accidentally passing the buffer
314          * returned from ossl_rand_pool_add_begin.
315          * The check for alloc_len makes sure we do not compare the
316          * address of the end of the allocated memory to something
317          * different, since that comparison would have an
318          * indeterminate result.
319          */
320         if (pool->alloc_len > pool->len && pool->buffer + pool->len == buffer) {
321             ERR_raise(ERR_LIB_RAND, ERR_R_INTERNAL_ERROR);
322             return 0;
323         }
324         /*
325          * We have that only for cases when a pool is used to collect
326          * additional data.
327          * For entropy data, as long as the allocation request stays within
328          * the limits given by ossl_rand_pool_bytes_needed this rand_pool_grow
329          * below is guaranteed to succeed, thus no allocation happens.
330          */
331         if (!rand_pool_grow(pool, len))
332             return 0;
333         memcpy(pool->buffer + pool->len, buffer, len);
334         pool->len += len;
335         pool->entropy += entropy;
336     }
337 
338     return 1;
339 }
340 
341 /*
342  * Start to add random bytes to the random pool in-place.
343  *
344  * Reserves the next |len| bytes for adding random bytes in-place
345  * and returns a pointer to the buffer.
346  * The caller is allowed to copy up to |len| bytes into the buffer.
347  * If |len| == 0 this is considered a no-op and a NULL pointer
348  * is returned without producing an error message.
349  *
350  * After updating the buffer, ossl_rand_pool_add_end() needs to be called
351  * to finish the update operation (see next comment).
352  */
ossl_rand_pool_add_begin(RAND_POOL * pool,size_t len)353 unsigned char *ossl_rand_pool_add_begin(RAND_POOL *pool, size_t len)
354 {
355     if (len == 0)
356         return NULL;
357 
358     if (len > pool->max_len - pool->len) {
359         ERR_raise(ERR_LIB_RAND, RAND_R_RANDOM_POOL_OVERFLOW);
360         return NULL;
361     }
362 
363     if (pool->buffer == NULL) {
364         ERR_raise(ERR_LIB_RAND, ERR_R_INTERNAL_ERROR);
365         return NULL;
366     }
367 
368     /*
369      * As long as the allocation request stays within the limits given
370      * by ossl_rand_pool_bytes_needed this rand_pool_grow below is guaranteed
371      * to succeed, thus no allocation happens.
372      * We have that only for cases when a pool is used to collect
373      * additional data. Then the buffer might need to grow here,
374      * and of course the caller is responsible to check the return
375      * value of this function.
376      */
377     if (!rand_pool_grow(pool, len))
378         return NULL;
379 
380     return pool->buffer + pool->len;
381 }
382 
383 /*
384  * Finish to add random bytes to the random pool in-place.
385  *
386  * Finishes an in-place update of the random pool started by
387  * ossl_rand_pool_add_begin() (see previous comment).
388  * It is expected that |len| bytes of random input have been added
389  * to the buffer which contain at least |entropy| bits of randomness.
390  * It is allowed to add less bytes than originally reserved.
391  */
ossl_rand_pool_add_end(RAND_POOL * pool,size_t len,size_t entropy)392 int ossl_rand_pool_add_end(RAND_POOL *pool, size_t len, size_t entropy)
393 {
394     if (len > pool->alloc_len - pool->len) {
395         ERR_raise(ERR_LIB_RAND, RAND_R_RANDOM_POOL_OVERFLOW);
396         return 0;
397     }
398 
399     if (len > 0) {
400         pool->len += len;
401         pool->entropy += entropy;
402     }
403 
404     return 1;
405 }
406 
407 /**
408  * @brief Mix in the additional input into an existing entropy in the pool
409  *
410  * @param pool     A RAND_POOL to mix the additional input in
411  * @param adin     A buffer with the additional input
412  * @param adin_len A length of the additional input
413  *
414  * @return 1 if there is any existing entropy in the pool so the additional input
415  *         can be mixed in, 0 otherwise.
416  */
417 
ossl_rand_pool_adin_mix_in(RAND_POOL * pool,const unsigned char * adin,size_t adin_len)418 int ossl_rand_pool_adin_mix_in(RAND_POOL *pool, const unsigned char *adin,
419     size_t adin_len)
420 {
421     if (adin == NULL || adin_len == 0)
422         /* Nothing to mix in -> success */
423         return 1;
424 
425     if (pool->buffer == NULL) {
426         ERR_raise(ERR_LIB_RAND, ERR_R_INTERNAL_ERROR);
427         return 0;
428     }
429 
430     if (pool->len == 0) {
431         ERR_raise(ERR_LIB_RAND, RAND_R_RANDOM_POOL_IS_EMPTY);
432         return 0;
433     }
434 
435     if (adin != NULL && adin_len > 0) {
436         size_t i;
437 
438         /* xor the additional data into the pool */
439         for (i = 0; i < adin_len; ++i)
440             pool->buffer[i % pool->len] ^= adin[i];
441     }
442 
443     return 1;
444 }
445