Make rand_pool buffers more dynamic in their sizing.
[openssl.git] / crypto / rand / rand_lcl.h
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 #ifndef HEADER_RAND_LCL_H
11 # define HEADER_RAND_LCL_H
12
13 # include <openssl/aes.h>
14 # include <openssl/evp.h>
15 # include <openssl/sha.h>
16 # include <openssl/hmac.h>
17 # include <openssl/ec.h>
18 # include <openssl/rand_drbg.h>
19 # include "internal/tsan_assist.h"
20 # include "internal/rand_int.h"
21
22 # include "internal/numbers.h"
23
24 /* How many times to read the TSC as a randomness source. */
25 # define TSC_READ_COUNT                 4
26
27 /* Maximum reseed intervals */
28 # define MAX_RESEED_INTERVAL                     (1 << 24)
29 # define MAX_RESEED_TIME_INTERVAL                (1 << 20) /* approx. 12 days */
30
31 /* Default reseed intervals */
32 # define MASTER_RESEED_INTERVAL                  (1 << 8)
33 # define SLAVE_RESEED_INTERVAL                   (1 << 16)
34 # define MASTER_RESEED_TIME_INTERVAL             (60*60)   /* 1 hour */
35 # define SLAVE_RESEED_TIME_INTERVAL              (7*60)    /* 7 minutes */
36
37 /*
38  * The number of bytes that constitutes an atomic lump of entropy with respect
39  * to the FIPS 140-2 section 4.9.2 Conditional Tests.  The size is somewhat
40  * arbitrary, the smaller the value, the less entropy is consumed on first
41  * read but the higher the probability of the test failing by accident.
42  *
43  * The value is in bytes.
44  */
45 #define CRNGT_BUFSIZ    16
46
47 /*
48  * Maximum input size for the DRBG (entropy, nonce, personalization string)
49  *
50  * NIST SP800 90Ar1 allows a maximum of (1 << 35) bits i.e., (1 << 32) bytes.
51  *
52  * We lower it to 'only' INT32_MAX bytes, which is equivalent to 2 gigabytes.
53  */
54 # define DRBG_MAX_LENGTH                         INT32_MAX
55
56 /* The default nonce */
57 # define DRBG_DEFAULT_PERS_STRING                "OpenSSL NIST SP 800-90A DRBG"
58
59 /*
60  * Maximum allocation size for RANDOM_POOL buffers
61  *
62  * The max_len value for the buffer provided to the rand_drbg_get_entropy()
63  * callback is currently 2^31 bytes (2 gigabytes), if a derivation function
64  * is used. Since this is much too large to be allocated, the rand_pool_new()
65  * function chooses more modest values as default pool length, bounded
66  * by RAND_POOL_MIN_LENGTH and RAND_POOL_MAX_LENGTH
67  *
68  * The choice of the RAND_POOL_FACTOR is large enough such that the
69  * RAND_POOL can store a random input which has a lousy entropy rate of
70  * 8/256 (= 0.03125) bits per byte. This input will be sent through the
71  * derivation function which 'compresses' the low quality input into a
72  * high quality output.
73  *
74  * The factor 1.5 below is the pessimistic estimate for the extra amount
75  * of entropy required when no get_nonce() callback is defined.
76  */
77 # define RAND_POOL_FACTOR        256
78 # define RAND_POOL_MAX_LENGTH    (RAND_POOL_FACTOR * \
79                                   3 * (RAND_DRBG_STRENGTH / 16))
80 /*
81  *                             = (RAND_POOL_FACTOR * \
82  *                                1.5 * (RAND_DRBG_STRENGTH / 8))
83  */
84
85 /*
86  * Initial allocation minimum.
87  *
88  * There is a distinction between the secure and normal allocation minimums.
89  * Ideally, the secure allocation size should be a power of two.  The normal
90  * allocation size doesn't have any such restriction.
91  *
92  * The secure value is based on 128 bits of secure material, which is 16 bytes.
93  * Typically, the DRBGs will set a minimum larger than this so optimal
94  * allocation ought to take place (for full quality seed material).
95  *
96  * The normal value has been chosed by noticing that the rand_drbg_get_nonce
97  * function is usually the largest of the built in allocation (twenty four
98  * bytes and then appending another sixteen bytes).  This means the buffer ends
99  * with 40 bytes.  The value of forty eight is comfortably above this which
100  * allows some slack in the platform specific values used.
101  */
102 # define RAND_POOL_MIN_ALLOCATION(secure) ((secure) ? 16 : 48)
103
104 /* DRBG status values */
105 typedef enum drbg_status_e {
106     DRBG_UNINITIALISED,
107     DRBG_READY,
108     DRBG_ERROR
109 } DRBG_STATUS;
110
111
112 /* instantiate */
113 typedef int (*RAND_DRBG_instantiate_fn)(RAND_DRBG *ctx,
114                                         const unsigned char *ent,
115                                         size_t entlen,
116                                         const unsigned char *nonce,
117                                         size_t noncelen,
118                                         const unsigned char *pers,
119                                         size_t perslen);
120 /* reseed */
121 typedef int (*RAND_DRBG_reseed_fn)(RAND_DRBG *ctx,
122                                    const unsigned char *ent,
123                                    size_t entlen,
124                                    const unsigned char *adin,
125                                    size_t adinlen);
126 /* generate output */
127 typedef int (*RAND_DRBG_generate_fn)(RAND_DRBG *ctx,
128                                      unsigned char *out,
129                                      size_t outlen,
130                                      const unsigned char *adin,
131                                      size_t adinlen);
132 /* uninstantiate */
133 typedef int (*RAND_DRBG_uninstantiate_fn)(RAND_DRBG *ctx);
134
135
136 /*
137  * The DRBG methods
138  */
139
140 typedef struct rand_drbg_method_st {
141     RAND_DRBG_instantiate_fn instantiate;
142     RAND_DRBG_reseed_fn reseed;
143     RAND_DRBG_generate_fn generate;
144     RAND_DRBG_uninstantiate_fn uninstantiate;
145 } RAND_DRBG_METHOD;
146
147 /* 888 bits from SP800-90Ar1 10.1 table 2 */
148 #define HASH_PRNG_MAX_SEEDLEN    (888/8)
149
150 typedef struct rand_drbg_hash_st {
151     EVP_MD *md;
152     EVP_MD_CTX *ctx;
153     size_t blocklen;
154     unsigned char V[HASH_PRNG_MAX_SEEDLEN];
155     unsigned char C[HASH_PRNG_MAX_SEEDLEN];
156     /* Temporary value storage: should always exceed max digest length */
157     unsigned char vtmp[HASH_PRNG_MAX_SEEDLEN];
158 } RAND_DRBG_HASH;
159
160 typedef struct rand_drbg_hmac_st {
161     EVP_MD *md;
162     HMAC_CTX *ctx;
163     size_t blocklen;
164     unsigned char K[EVP_MAX_MD_SIZE];
165     unsigned char V[EVP_MAX_MD_SIZE];
166 } RAND_DRBG_HMAC;
167
168 /*
169  * The state of a DRBG AES-CTR.
170  */
171 typedef struct rand_drbg_ctr_st {
172     EVP_CIPHER_CTX *ctx;
173     EVP_CIPHER_CTX *ctx_df;
174     EVP_CIPHER *cipher;
175     size_t keylen;
176     unsigned char K[32];
177     unsigned char V[16];
178     /* Temporary block storage used by ctr_df */
179     unsigned char bltmp[16];
180     size_t bltmp_pos;
181     unsigned char KX[48];
182 } RAND_DRBG_CTR;
183
184
185 /*
186  * The 'random pool' acts as a dumb container for collecting random
187  * input from various entropy sources. The pool has no knowledge about
188  * whether its randomness is fed into a legacy RAND_METHOD via RAND_add()
189  * or into a new style RAND_DRBG. It is the callers duty to 1) initialize the
190  * random pool, 2) pass it to the polling callbacks, 3) seed the RNG, and
191  * 4) cleanup the random pool again.
192  *
193  * The random pool contains no locking mechanism because its scope and
194  * lifetime is intended to be restricted to a single stack frame.
195  */
196 struct rand_pool_st {
197     unsigned char *buffer;  /* points to the beginning of the random pool */
198     size_t len; /* current number of random bytes contained in the pool */
199
200     int attached;  /* true pool was attached to existing buffer */
201     int secure;    /* 1: allocated on the secure heap, 0: otherwise */
202
203     size_t min_len; /* minimum number of random bytes requested */
204     size_t max_len; /* maximum number of random bytes (allocated buffer size) */
205     size_t alloc_len; /* current number of bytes allocated */
206     size_t entropy; /* current entropy count in bits */
207     size_t entropy_requested; /* requested entropy count in bits */
208 };
209
210 /*
211  * The state of all types of DRBGs, even though we only have CTR mode
212  * right now.
213  */
214 struct rand_drbg_st {
215     CRYPTO_RWLOCK *lock;
216     /* The library context this DRBG is associated with, if any */
217     OPENSSL_CTX *libctx;
218     RAND_DRBG *parent;
219     int secure; /* 1: allocated on the secure heap, 0: otherwise */
220     int type; /* the nid of the underlying algorithm */
221     /*
222      * Stores the value of the rand_fork_count global as of when we last
223      * reseeded.  The DRBG reseeds automatically whenever drbg->fork_count !=
224      * rand_fork_count.  Used to provide fork-safety and reseed this DRBG in
225      * the child process.
226      */
227     int fork_count;
228     unsigned short flags; /* various external flags */
229
230     /*
231      * The random_data is used by RAND_add()/drbg_add() to attach random
232      * data to the global drbg, such that the rand_drbg_get_entropy() callback
233      * can pull it during instantiation and reseeding. This is necessary to
234      * reconcile the different philosophies of the RAND and the RAND_DRBG
235      * with respect to how randomness is added to the RNG during reseeding
236      * (see PR #4328).
237      */
238     struct rand_pool_st *seed_pool;
239
240     /*
241      * Auxiliary pool for additional data.
242      */
243     struct rand_pool_st *adin_pool;
244
245     /*
246      * The following parameters are setup by the per-type "init" function.
247      *
248      * The supported types and their init functions are:
249      *    (1) CTR_DRBG:  drbg_ctr_init().
250      *    (2) HMAC_DRBG: drbg_hmac_init().
251      *    (3) HASH_DRBG: drbg_hash_init().
252      *
253      * The parameters are closely related to the ones described in
254      * section '10.2.1 CTR_DRBG' of [NIST SP 800-90Ar1], with one
255      * crucial difference: In the NIST standard, all counts are given
256      * in bits, whereas in OpenSSL entropy counts are given in bits
257      * and buffer lengths are given in bytes.
258      *
259      * Since this difference has lead to some confusion in the past,
260      * (see [GitHub Issue #2443], formerly [rt.openssl.org #4055])
261      * the 'len' suffix has been added to all buffer sizes for
262      * clarification.
263      */
264
265     int strength;
266     size_t max_request;
267     size_t min_entropylen, max_entropylen;
268     size_t min_noncelen, max_noncelen;
269     size_t max_perslen, max_adinlen;
270
271     /*
272      * Counts the number of generate requests since the last reseed
273      * (Starts at 1). This value is the reseed_counter as defined in
274      * NIST SP 800-90Ar1
275      */
276     unsigned int reseed_gen_counter;
277     /*
278      * Maximum number of generate requests until a reseed is required.
279      * This value is ignored if it is zero.
280      */
281     unsigned int reseed_interval;
282     /* Stores the time when the last reseeding occurred */
283     time_t reseed_time;
284     /*
285      * Specifies the maximum time interval (in seconds) between reseeds.
286      * This value is ignored if it is zero.
287      */
288     time_t reseed_time_interval;
289     /*
290      * Counts the number of reseeds since instantiation.
291      * This value is ignored if it is zero.
292      *
293      * This counter is used only for seed propagation from the <master> DRBG
294      * to its two children, the <public> and <private> DRBG. This feature is
295      * very special and its sole purpose is to ensure that any randomness which
296      * is added by RAND_add() or RAND_seed() will have an immediate effect on
297      * the output of RAND_bytes() resp. RAND_priv_bytes().
298      */
299     TSAN_QUALIFIER unsigned int reseed_prop_counter;
300     unsigned int reseed_next_counter;
301
302     size_t seedlen;
303     DRBG_STATUS state;
304
305     /* Application data, mainly used in the KATs. */
306     CRYPTO_EX_DATA ex_data;
307
308     /* Implementation specific data */
309     union {
310         RAND_DRBG_CTR ctr;
311         RAND_DRBG_HASH hash;
312         RAND_DRBG_HMAC hmac;
313     } data;
314
315     /* Implementation specific methods */
316     RAND_DRBG_METHOD *meth;
317
318     /* Callback functions.  See comments in rand_lib.c */
319     RAND_DRBG_get_entropy_fn get_entropy;
320     RAND_DRBG_cleanup_entropy_fn cleanup_entropy;
321     RAND_DRBG_get_nonce_fn get_nonce;
322     RAND_DRBG_cleanup_nonce_fn cleanup_nonce;
323 };
324
325 /* The global RAND method, and the global buffer and DRBG instance. */
326 extern RAND_METHOD rand_meth;
327
328 /*
329  * A "generation count" of forks.  Incremented in the child process after a
330  * fork.  Since rand_fork_count is increment-only, and only ever written to in
331  * the child process of the fork, which is guaranteed to be single-threaded, no
332  * locking is needed for normal (read) accesses; the rest of pthread fork
333  * processing is assumed to introduce the necessary memory barriers.  Sibling
334  * children of a given parent will produce duplicate values, but this is not
335  * problematic because the reseeding process pulls input from the system CSPRNG
336  * and/or other global sources, so the siblings will end up generating
337  * different output streams.
338  */
339 extern int rand_fork_count;
340
341 /* DRBG helpers */
342 int rand_drbg_restart(RAND_DRBG *drbg,
343                       const unsigned char *buffer, size_t len, size_t entropy);
344 size_t rand_drbg_seedlen(RAND_DRBG *drbg);
345 /* locking api */
346 int rand_drbg_lock(RAND_DRBG *drbg);
347 int rand_drbg_unlock(RAND_DRBG *drbg);
348 int rand_drbg_enable_locking(RAND_DRBG *drbg);
349
350
351 /* initializes the DRBG implementation */
352 int drbg_ctr_init(RAND_DRBG *drbg);
353 int drbg_hash_init(RAND_DRBG *drbg);
354 int drbg_hmac_init(RAND_DRBG *drbg);
355
356 /*
357  * Entropy call back for the FIPS 140-2 section 4.9.2 Conditional Tests.
358  * These need to be exposed for the unit tests.
359  */
360 int rand_crngt_get_entropy_cb(OPENSSL_CTX *ctx, RAND_POOL *pool,
361                               unsigned char *buf, unsigned char *md,
362                               unsigned int *md_size);
363 extern int (*crngt_get_entropy)(OPENSSL_CTX *ctx, RAND_POOL *pool,
364                                 unsigned char *buf, unsigned char *md,
365                                 unsigned int *md_size);
366
367 #endif