Make RAND_DRBG fork-safe
[openssl.git] / crypto / rand / rand_lib.c
1 /*
2  * Copyright 1995-2016 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
19 #ifndef OPENSSL_NO_ENGINE
20 /* non-NULL if default_RAND_meth is ENGINE-provided */
21 static ENGINE *funct_ref;
22 static CRYPTO_RWLOCK *rand_engine_lock;
23 #endif
24 static CRYPTO_RWLOCK *rand_meth_lock;
25 static const RAND_METHOD *default_RAND_meth;
26 static CRYPTO_ONCE rand_init = CRYPTO_ONCE_STATIC_INIT;
27 RAND_BYTES_BUFFER rand_bytes;
28 int rand_fork_count;
29
30 #ifdef OPENSSL_RAND_SEED_RDTSC
31 /*
32  * IMPORTANT NOTE:  It is not currently possible to use this code
33  * because we are not sure about the amount of randomness.  Some
34  * SP900 tests have been run, but there is internal skepticism.
35  * So for now this code is not used.
36  */
37 # error "RDTSC enabled?  Should not be possible!"
38
39 /*
40  * Since we get some randomness from the low-order bits of the
41  * high-speec clock, it can help.  But don't return a status since
42  * it's not sufficient to indicate whether or not the seeding was
43  * done.
44  */
45 void rand_read_tsc(RAND_poll_fn cb, void *arg)
46 {
47     unsigned char c;
48     int i;
49
50     for (i = 0; i < 10; i++) {
51         c = (unsigned char)(OPENSSL_rdtsc() & 0xFF);
52         cb(arg, &c, 1, 0.5);
53     }
54 }
55 #endif
56
57 #ifdef OPENSSL_RAND_SEED_RDCPU
58 size_t OPENSSL_ia32_rdseed(void);
59 size_t OPENSSL_ia32_rdrand(void);
60
61 extern unsigned int OPENSSL_ia32cap_P[];
62
63 int rand_read_cpu(RAND_poll_fn cb, void *arg)
64 {
65     size_t i, s;
66
67     /* If RDSEED is available, use that. */
68     if ((OPENSSL_ia32cap_P[1] & (1 << 18)) != 0) {
69         for (i = 0; i < RANDOMNESS_NEEDED; i += sizeof(s)) {
70             s = OPENSSL_ia32_rdseed();
71             if (s == 0)
72                 break;
73             cb(arg, &s, (int)sizeof(s), sizeof(s));
74         }
75         if (i >= RANDOMNESS_NEEDED)
76             return 1;
77     }
78
79     /* Second choice is RDRAND. */
80     if ((OPENSSL_ia32cap_P[1] & (1 << (62 - 32))) != 0) {
81         for (i = 0; i < RANDOMNESS_NEEDED; i += sizeof(s)) {
82             s = OPENSSL_ia32_rdrand();
83             if (s == 0)
84                 break;
85             cb(arg, &s, (int)sizeof(s), sizeof(s));
86         }
87         if (i >= RANDOMNESS_NEEDED)
88             return 1;
89     }
90
91     return 0;
92 }
93 #endif
94
95
96 /*
97  * DRBG has two sets of callbacks; we only discuss the "entropy" one
98  * here.  When the DRBG needs additional randomness bits (called entropy
99  * in the NIST document), it calls the get_entropy callback which fills in
100  * a pointer and returns the number of bytes. When the DRBG is finished with
101  * the buffer, it calls the cleanup_entropy callback, with the value of
102  * the buffer that the get_entropy callback filled in.
103  *
104  * Get entropy from the system, via RAND_poll if needed.  The |entropy|
105  * is the bits of randomness required, and is expected to fit into a buffer
106  * of |min_len|..|max__len| size.  We assume we're getting high-quality
107  * randomness from the system, and that |min_len| bytes will do.
108  */
109 size_t drbg_entropy_from_system(RAND_DRBG *drbg,
110                                 unsigned char **pout,
111                                 int entropy, size_t min_len, size_t max_len)
112 {
113     int i;
114
115
116     if (min_len > (size_t)drbg->size) {
117         /* Should not happen.  See comment near RANDOMNESS_NEEDED. */
118         min_len = drbg->size;
119     }
120
121     if (drbg->filled) {
122         /* Re-use what we have. */
123         *pout = drbg->randomness;
124         return drbg->size;
125     }
126
127     /* If we don't have enough, try to get more. */
128     CRYPTO_THREAD_write_lock(rand_bytes.lock);
129     for (i = RAND_POLL_RETRIES; rand_bytes.curr < min_len && --i >= 0; ) {
130         CRYPTO_THREAD_unlock(rand_bytes.lock);
131         RAND_poll();
132         CRYPTO_THREAD_write_lock(rand_bytes.lock);
133     }
134
135     /* Get desired amount, but no more than we have. */
136     if (min_len > rand_bytes.curr)
137         min_len = rand_bytes.curr;
138     if (min_len != 0) {
139         memcpy(drbg->randomness, rand_bytes.buff, min_len);
140         drbg->filled = 1;
141         /* Update amount left and shift it down. */
142         rand_bytes.curr -= min_len;
143         if (rand_bytes.curr != 0)
144             memmove(rand_bytes.buff, &rand_bytes.buff[min_len], rand_bytes.curr);
145     }
146     CRYPTO_THREAD_unlock(rand_bytes.lock);
147     *pout = drbg->randomness;
148     return min_len;
149 }
150
151 size_t drbg_entropy_from_parent(RAND_DRBG *drbg,
152                                 unsigned char **pout,
153                                 int entropy, size_t min_len, size_t max_len)
154 {
155     int st;
156
157     if (min_len > (size_t)drbg->size) {
158         /* Should not happen.  See comment near RANDOMNESS_NEEDED. */
159         min_len = drbg->size;
160     }
161
162     /* Get random from parent, include our state as additional input. */
163     st = RAND_DRBG_generate(drbg->parent, drbg->randomness, min_len, 0,
164                             (unsigned char *)drbg, sizeof(*drbg));
165     if (st == 0)
166         return 0;
167     drbg->filled = 1;
168     *pout = drbg->randomness;
169     return min_len;
170 }
171
172 void drbg_release_entropy(RAND_DRBG *drbg, unsigned char *out)
173 {
174     drbg->filled = 0;
175     OPENSSL_cleanse(drbg->randomness, drbg->size);
176 }
177
178
179 /*
180  * Set up a global DRBG.
181  */
182 static int setup_drbg(RAND_DRBG *drbg)
183 {
184     int ret = 1;
185
186     drbg->lock = CRYPTO_THREAD_lock_new();
187     ret &= drbg->lock != NULL;
188     drbg->size = RANDOMNESS_NEEDED;
189     drbg->randomness = OPENSSL_malloc(drbg->size);
190     ret &= drbg->randomness != NULL;
191     /* If you change these parameters, see RANDOMNESS_NEEDED */
192     ret &= RAND_DRBG_set(drbg,
193                          NID_aes_128_ctr, RAND_DRBG_FLAG_CTR_USE_DF) == 1;
194     ret &= RAND_DRBG_set_callbacks(drbg, drbg_entropy_from_system,
195                                    drbg_release_entropy, NULL, NULL) == 1;
196     return ret;
197 }
198
199 static void free_drbg(RAND_DRBG *drbg)
200 {
201     CRYPTO_THREAD_lock_free(drbg->lock);
202     OPENSSL_clear_free(drbg->randomness, drbg->size);
203     RAND_DRBG_uninstantiate(drbg);
204 }
205
206 void rand_fork()
207 {
208     rand_fork_count++;
209 }
210
211 DEFINE_RUN_ONCE_STATIC(do_rand_init)
212 {
213     int ret = 1;
214
215 #ifndef OPENSSL_NO_ENGINE
216     rand_engine_lock = CRYPTO_THREAD_lock_new();
217     ret &= rand_engine_lock != NULL;
218 #endif
219     rand_meth_lock = CRYPTO_THREAD_lock_new();
220     ret &= rand_meth_lock != NULL;
221
222     rand_bytes.lock = CRYPTO_THREAD_lock_new();
223     ret &= rand_bytes.lock != NULL;
224     rand_bytes.curr = 0;
225     rand_bytes.size = MAX_RANDOMNESS_HELD;
226     /* TODO: Should this be secure malloc? */
227     rand_bytes.buff = malloc(rand_bytes.size);
228
229     ret &= rand_bytes.buff != NULL;
230     ret &= setup_drbg(&rand_drbg);
231     ret &= setup_drbg(&priv_drbg);
232     return ret;
233 }
234
235 void rand_cleanup_int(void)
236 {
237     const RAND_METHOD *meth = default_RAND_meth;
238
239     if (meth != NULL && meth->cleanup != NULL)
240         meth->cleanup();
241     RAND_set_rand_method(NULL);
242 #ifndef OPENSSL_NO_ENGINE
243     CRYPTO_THREAD_lock_free(rand_engine_lock);
244 #endif
245     CRYPTO_THREAD_lock_free(rand_meth_lock);
246     CRYPTO_THREAD_lock_free(rand_bytes.lock);
247     OPENSSL_clear_free(rand_bytes.buff, rand_bytes.size);
248     free_drbg(&rand_drbg);
249     free_drbg(&priv_drbg);
250 }
251
252 /*
253  * RAND_poll_ex() gets a function pointer to call when it has random bytes.
254  * RAND_poll() sets the function pointer to be a wrapper that calls RAND_add().
255  */
256 static void call_rand_add(void* arg, const void *buf, int num, double r)
257 {
258     RAND_add(buf, num, r);
259 }
260
261 int RAND_poll(void)
262 {
263     return RAND_poll_ex(call_rand_add, NULL);
264 }
265
266 int RAND_set_rand_method(const RAND_METHOD *meth)
267 {
268     if (!RUN_ONCE(&rand_init, do_rand_init))
269         return 0;
270
271     CRYPTO_THREAD_write_lock(rand_meth_lock);
272 #ifndef OPENSSL_NO_ENGINE
273     ENGINE_finish(funct_ref);
274     funct_ref = NULL;
275 #endif
276     default_RAND_meth = meth;
277     CRYPTO_THREAD_unlock(rand_meth_lock);
278     return 1;
279 }
280
281 const RAND_METHOD *RAND_get_rand_method(void)
282 {
283     const RAND_METHOD *tmp_meth = NULL;
284
285     if (!RUN_ONCE(&rand_init, do_rand_init))
286         return NULL;
287
288     CRYPTO_THREAD_write_lock(rand_meth_lock);
289     if (default_RAND_meth == NULL) {
290 #ifndef OPENSSL_NO_ENGINE
291         ENGINE *e;
292
293         /* If we have an engine that can do RAND, use it. */
294         if ((e = ENGINE_get_default_RAND()) != NULL
295                 && (tmp_meth = ENGINE_get_RAND(e)) != NULL) {
296             funct_ref = e;
297             default_RAND_meth = tmp_meth;
298         } else {
299             ENGINE_finish(e);
300             default_RAND_meth = &rand_meth;
301         }
302 #else
303         default_RAND_meth = &rand_meth;
304 #endif
305     }
306     tmp_meth = default_RAND_meth;
307     CRYPTO_THREAD_unlock(rand_meth_lock);
308     return tmp_meth;
309 }
310
311 #ifndef OPENSSL_NO_ENGINE
312 int RAND_set_rand_engine(ENGINE *engine)
313 {
314     const RAND_METHOD *tmp_meth = NULL;
315
316     if (!RUN_ONCE(&rand_init, do_rand_init))
317         return 0;
318
319     if (engine != NULL) {
320         if (!ENGINE_init(engine))
321             return 0;
322         tmp_meth = ENGINE_get_RAND(engine);
323         if (tmp_meth == NULL) {
324             ENGINE_finish(engine);
325             return 0;
326         }
327     }
328     CRYPTO_THREAD_write_lock(rand_engine_lock);
329     /* This function releases any prior ENGINE so call it first */
330     RAND_set_rand_method(tmp_meth);
331     funct_ref = engine;
332     CRYPTO_THREAD_unlock(rand_engine_lock);
333     return 1;
334 }
335 #endif
336
337 void RAND_seed(const void *buf, int num)
338 {
339     const RAND_METHOD *meth = RAND_get_rand_method();
340
341     if (meth->seed != NULL)
342         meth->seed(buf, num);
343 }
344
345 void RAND_add(const void *buf, int num, double randomness)
346 {
347     const RAND_METHOD *meth = RAND_get_rand_method();
348
349     if (meth->add != NULL)
350         meth->add(buf, num, randomness);
351 }
352
353 /*
354  * This function is not part of RAND_METHOD, so if we're not using
355  * the default method, then just call RAND_bytes().  Otherwise make
356  * sure we're instantiated and use the private DRBG.
357  */
358 int RAND_priv_bytes(unsigned char *buf, int num)
359 {
360     const RAND_METHOD *meth = RAND_get_rand_method();
361
362     if (meth != RAND_OpenSSL())
363         return RAND_bytes(buf, num);
364
365     if (priv_drbg.state == DRBG_UNINITIALISED
366             && RAND_DRBG_instantiate(&priv_drbg, NULL, 0) == 0)
367         return 0;
368     return RAND_DRBG_generate(&priv_drbg, buf, num, 0, NULL, 0);
369
370 }
371
372 int RAND_bytes(unsigned char *buf, int num)
373 {
374     const RAND_METHOD *meth = RAND_get_rand_method();
375
376     if (meth->bytes != NULL)
377         return meth->bytes(buf, num);
378     RANDerr(RAND_F_RAND_BYTES, RAND_R_FUNC_NOT_IMPLEMENTED);
379     return -1;
380 }
381
382 #if OPENSSL_API_COMPAT < 0x10100000L
383 int RAND_pseudo_bytes(unsigned char *buf, int num)
384 {
385     const RAND_METHOD *meth = RAND_get_rand_method();
386
387     if (meth->pseudorand != NULL)
388         return meth->pseudorand(buf, num);
389     return -1;
390 }
391 #endif
392
393 int RAND_status(void)
394 {
395     const RAND_METHOD *meth = RAND_get_rand_method();
396
397     if (meth->status != NULL)
398         return meth->status();
399     return 0;
400 }