cae567beb438bf1bb1127a67918bf6921e8b9f22
[openssl.git] / crypto / rand / drbg_hash.c
1 /*
2  * Copyright 2011-2018 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 <assert.h>
11 #include <stdlib.h>
12 #include <string.h>
13 #include <openssl/crypto.h>
14 #include <openssl/err.h>
15 #include <openssl/rand.h>
16 #include "internal/thread_once.h"
17 #include "rand_lcl.h"
18
19 /* 440 bits from SP800-90Ar1 10.1 table 2 */
20 #define HASH_PRNG_SMALL_SEEDLEN   (440/8)
21 /* Determine what seedlen to use based on the block length */
22 #define MAX_BLOCKLEN_USING_SMALL_SEEDLEN (256/8)
23 #define INBYTE_IGNORE ((unsigned char)0xFF)
24
25
26 /*
27  * SP800-90Ar1 10.3.1 Derivation function using a Hash Function (Hash_df).
28  * The input string used is composed of:
29  *    inbyte - An optional leading byte (ignore if equal to INBYTE_IGNORE)
30  *    in - input string 1 (A Non NULL value).
31  *    in2 - optional input string (Can be NULL).
32  *    in3 - optional input string (Can be NULL).
33  *    These are concatenated as part of the DigestUpdate process.
34  */
35 static int hash_df(RAND_DRBG *drbg, unsigned char *out,
36                    const unsigned char inbyte,
37                    const unsigned char *in, size_t inlen,
38                    const unsigned char *in2, size_t in2len,
39                    const unsigned char *in3, size_t in3len)
40 {
41     RAND_DRBG_HASH *hash = &drbg->data.hash;
42     EVP_MD_CTX *ctx = hash->ctx;
43     unsigned char *vtmp = hash->vtmp;
44     /* tmp = counter || num_bits_returned || [inbyte] */
45     unsigned char tmp[1 + 4 + 1];
46     int tmp_sz = 0;
47     size_t outlen = drbg->seedlen;
48     size_t num_bits_returned = outlen * 8;
49     /*
50      * No need to check outlen size here, as the standard only ever needs
51      * seedlen bytes which is always less than the maximum permitted.
52      */
53
54     /* (Step 3) counter = 1 (tmp[0] is the 8 bit counter) */
55     tmp[tmp_sz++] = 1;
56     /* tmp[1..4] is the fixed 32 bit no_of_bits_to_return */
57     tmp[tmp_sz++] = (unsigned char)((num_bits_returned >> 24) & 0xff);
58     tmp[tmp_sz++] = (unsigned char)((num_bits_returned >> 16) & 0xff);
59     tmp[tmp_sz++] = (unsigned char)((num_bits_returned >> 8) & 0xff);
60     tmp[tmp_sz++] = (unsigned char)(num_bits_returned & 0xff);
61     /* Tack the additional input byte onto the end of tmp if it exists */
62     if (inbyte != INBYTE_IGNORE)
63         tmp[tmp_sz++] = inbyte;
64
65     /* (Step 4) */
66     for (;;) {
67         /*
68          * (Step 4.1) out = out || Hash(tmp || in || [in2] || [in3])
69          *            (where tmp = counter || num_bits_returned || [inbyte])
70          */
71         if (!(EVP_DigestInit_ex(ctx, hash->md, NULL)
72                 && EVP_DigestUpdate(ctx, tmp, tmp_sz)
73                 && EVP_DigestUpdate(ctx, in, inlen)
74                 && (in2 == NULL || EVP_DigestUpdate(ctx, in2, in2len))
75                 && (in3 == NULL || EVP_DigestUpdate(ctx, in3, in3len))))
76             return 0;
77
78         if (outlen < hash->blocklen) {
79             if (!EVP_DigestFinal(ctx, vtmp, NULL))
80                 return 0;
81             memcpy(out, vtmp, outlen);
82             OPENSSL_cleanse(vtmp, hash->blocklen);
83             break;
84         } else if(!EVP_DigestFinal(ctx, out, NULL)) {
85             return 0;
86         }
87
88         outlen -= hash->blocklen;
89         if (outlen == 0)
90             break;
91         /* (Step 4.2) counter++ */
92         tmp[0]++;
93         out += hash->blocklen;
94     }
95     return 1;
96 }
97
98 /* Helper function that just passes 2 input parameters to hash_df() */
99 static int hash_df1(RAND_DRBG *drbg, unsigned char *out,
100                     const unsigned char in_byte,
101                     const unsigned char *in1, size_t in1len)
102 {
103     return hash_df(drbg, out, in_byte, in1, in1len, NULL, 0, NULL, 0);
104 }
105
106 /*
107  * Add 2 byte buffers together. The first elements in each buffer are the top
108  * most bytes. The result is stored in the dst buffer.
109  * The final carry is ignored i.e: dst =  (dst + in) mod (2^seedlen_bits).
110  * where dst size is drbg->seedlen, and inlen <= drbg->seedlen.
111  */
112 static int add_bytes(RAND_DRBG *drbg, unsigned char *dst,
113                      unsigned char *in, size_t inlen)
114 {
115     size_t i;
116     int result;
117     const unsigned char *add;
118     unsigned char carry = 0, *d;
119
120     assert(drbg->seedlen >= 1 && inlen >= 1 && inlen <= drbg->seedlen);
121
122     d = &dst[drbg->seedlen - 1];
123     add = &in[inlen - 1];
124
125     for (i = inlen; i > 0; i--, d--, add--) {
126         result = *d + *add + carry;
127         carry = (unsigned char)(result >> 8);
128         *d = (unsigned char)(result & 0xff);
129     }
130
131     if (carry != 0) {
132         /* Add the carry to the top of the dst if inlen is not the same size */
133         for (i = drbg->seedlen - inlen; i > 0; --i, d--) {
134             *d += 1;     /* Carry can only be 1 */
135             if (*d != 0) /* exit if carry doesnt propagate to the next byte */
136                 break;
137         }
138     }
139     return 1;
140 }
141
142 /* V = (V + Hash(inbyte || V  || [additional_input]) mod (2^seedlen) */
143 static int add_hash_to_v(RAND_DRBG *drbg, unsigned char inbyte,
144                          const unsigned char *adin, size_t adinlen)
145 {
146     RAND_DRBG_HASH *hash = &drbg->data.hash;
147     EVP_MD_CTX *ctx = hash->ctx;
148
149     return EVP_DigestInit_ex(ctx, hash->md, NULL)
150            && EVP_DigestUpdate(ctx, &inbyte, 1)
151            && EVP_DigestUpdate(ctx, hash->V, drbg->seedlen)
152            && (adin == NULL || EVP_DigestUpdate(ctx, adin, adinlen))
153            && EVP_DigestFinal(ctx, hash->vtmp, NULL)
154            && add_bytes(drbg, hash->V, hash->vtmp, hash->blocklen);
155 }
156
157 /*
158  * The Hashgen() as listed in SP800-90Ar1 10.1.1.4 Hash_DRBG_Generate_Process.
159  *
160  * drbg contains the current value of V.
161  * outlen is the requested number of bytes.
162  * out is a buffer to return the generated bits.
163  *
164  * The algorithm to generate the bits is:
165  *     data = V
166  *     w = NULL
167  *     for (i = 1 to m) {
168  *        W = W || Hash(data)
169  *        data = (data + 1) mod (2^seedlen)
170  *     }
171  *     out = Leftmost(W, outlen)
172  *
173  * Returns zero if an error occurs otherwise it returns 1.
174  */
175 static int hash_gen(RAND_DRBG *drbg, unsigned char *out, size_t outlen)
176 {
177     RAND_DRBG_HASH *hash = &drbg->data.hash;
178     unsigned char one = 1;
179
180     if (outlen == 0)
181         return 1;
182     memcpy(hash->vtmp, hash->V, drbg->seedlen);
183     for(;;) {
184         if (!EVP_DigestInit_ex(hash->ctx, hash->md, NULL)
185                 || !EVP_DigestUpdate(hash->ctx, hash->vtmp, drbg->seedlen))
186             return 0;
187
188         if (outlen < hash->blocklen) {
189             if (!EVP_DigestFinal(hash->ctx, hash->vtmp, NULL))
190                 return 0;
191             memcpy(out, hash->vtmp, outlen);
192             return 1;
193         } else {
194             if (!EVP_DigestFinal(hash->ctx, out, NULL))
195                 return 0;
196             outlen -= hash->blocklen;
197             if (outlen == 0)
198                 break;
199             out += hash->blocklen;
200         }
201         add_bytes(drbg, hash->vtmp, &one, 1);
202     }
203     return 1;
204 }
205
206 /*
207  * SP800-90Ar1 10.1.1.2 Hash_DRBG_Instantiate_Process:
208  *
209  * ent is entropy input obtained from a randomness source of length ent_len.
210  * nonce is a string of bytes of length nonce_len.
211  * pstr is a personalization string received from an application. May be NULL.
212  *
213  * Returns zero if an error occurs otherwise it returns 1.
214  */
215 static int drbg_hash_instantiate(RAND_DRBG *drbg,
216                                  const unsigned char *ent, size_t ent_len,
217                                  const unsigned char *nonce, size_t nonce_len,
218                                  const unsigned char *pstr, size_t pstr_len)
219 {
220     RAND_DRBG_HASH *hash = &drbg->data.hash;
221
222     /* (Step 1-3) V = Hash_df(entropy||nonce||pers, seedlen) */
223     return hash_df(drbg, hash->V, INBYTE_IGNORE,
224                    ent, ent_len, nonce, nonce_len, pstr, pstr_len)
225            /* (Step 4) C = Hash_df(0x00||V, seedlen) */
226            && hash_df1(drbg, hash->C, 0x00, hash->V, drbg->seedlen);
227 }
228
229 /*
230  * SP800-90Ar1 10.1.1.3 Hash_DRBG_Reseed_Process:
231  *
232  * ent is entropy input bytes obtained from a randomness source.
233  * addin is additional input received from an application. May be NULL.
234  *
235  * Returns zero if an error occurs otherwise it returns 1.
236  */
237 static int drbg_hash_reseed(RAND_DRBG *drbg,
238                             const unsigned char *ent, size_t ent_len,
239                             const unsigned char *adin, size_t adin_len)
240 {
241     RAND_DRBG_HASH *hash = &drbg->data.hash;
242
243     /* (Step 1-2) V = Hash_df(0x01 || V || entropy_input || additional_input)*/
244     /* V about to be updated so use C as output instead */
245     if (!hash_df(drbg, hash->C, 0x01, hash->V, drbg->seedlen, ent, ent_len,
246                  adin, adin_len))
247         return 0;
248     memcpy(hash->V, hash->C, drbg->seedlen);
249     /* (Step 4) C = Hash_df(0x00||V, seedlen) */
250     return hash_df1(drbg, hash->C, 0x00, hash->V, drbg->seedlen);
251 }
252
253 /*
254  * SP800-90Ar1 10.1.1.4 Hash_DRBG_Generate_Process:
255  *
256  * Generates pseudo random bytes using the drbg.
257  * out is a buffer to fill with outlen bytes of pseudo random data.
258  * addin is additional input received from an application. May be NULL.
259  *
260  * Returns zero if an error occurs otherwise it returns 1.
261  */
262 static int drbg_hash_generate(RAND_DRBG *drbg,
263                               unsigned char *out, size_t outlen,
264                               const unsigned char *adin, size_t adin_len)
265 {
266     RAND_DRBG_HASH *hash = &drbg->data.hash;
267     unsigned char counter[4];
268     int reseed_counter = drbg->reseed_gen_counter;
269
270     counter[0] = (unsigned char)((reseed_counter >> 24) & 0xff);
271     counter[1] = (unsigned char)((reseed_counter >> 16) & 0xff);
272     counter[2] = (unsigned char)((reseed_counter >> 8) & 0xff);
273     counter[3] = (unsigned char)(reseed_counter & 0xff);
274
275     return (adin == NULL
276            /* (Step 2) if adin != NULL then V = V + Hash(0x02||V||adin) */
277                 || adin_len == 0
278                 || add_hash_to_v(drbg, 0x02, adin, adin_len))
279            /* (Step 3) Hashgen(outlen, V) */
280            && hash_gen(drbg, out, outlen)
281            /* (Step 4/5) H = V = (V + Hash(0x03||V) mod (2^seedlen_bits) */
282            && add_hash_to_v(drbg, 0x03, NULL, 0)
283            /* (Step 5) V = (V + H + C + reseed_counter) mod (2^seedlen_bits) */
284            /* V = (V + C) mod (2^seedlen_bits) */
285            && add_bytes(drbg, hash->V, hash->C, drbg->seedlen)
286            /* V = (V + reseed_counter) mod (2^seedlen_bits) */
287            && add_bytes(drbg, hash->V, counter, 4);
288 }
289
290 static int drbg_hash_uninstantiate(RAND_DRBG *drbg)
291 {
292     EVP_MD_CTX_free(drbg->data.hash.ctx);
293     OPENSSL_cleanse(&drbg->data.hash, sizeof(drbg->data.hash));
294     return 1;
295 }
296
297 static RAND_DRBG_METHOD drbg_hash_meth = {
298     drbg_hash_instantiate,
299     drbg_hash_reseed,
300     drbg_hash_generate,
301     drbg_hash_uninstantiate
302 };
303
304 int drbg_hash_init(RAND_DRBG *drbg)
305 {
306     const EVP_MD *md;
307     RAND_DRBG_HASH *hash = &drbg->data.hash;
308
309     /* Any approved digest is allowed */
310     md = EVP_get_digestbynid(drbg->type);
311     if (md == NULL)
312         return 0;
313
314     drbg->meth = &drbg_hash_meth;
315     hash->md = md;
316
317     if (hash->ctx == NULL) {
318         hash->ctx = EVP_MD_CTX_new();
319         if (hash->ctx == NULL)
320             return 0;
321     }
322
323     /* These are taken from SP 800-90 10.1 Table 2 */
324     hash->blocklen = EVP_MD_size(md);
325     /* See SP800-57 Part1 Rev4 5.6.1 Table 3 */
326     drbg->strength = 64 * (hash->blocklen >> 3);
327     if (drbg->strength > 256)
328         drbg->strength = 256;
329     if (hash->blocklen > MAX_BLOCKLEN_USING_SMALL_SEEDLEN)
330         drbg->seedlen = HASH_PRNG_MAX_SEEDLEN;
331     else
332         drbg->seedlen = HASH_PRNG_SMALL_SEEDLEN;
333
334     drbg->min_entropylen = drbg->strength / 8;
335     drbg->max_entropylen = DRBG_MAX_LENGTH;
336
337     drbg->min_noncelen = drbg->min_entropylen / 2;
338     drbg->max_noncelen = DRBG_MAX_LENGTH;
339
340     drbg->max_perslen = DRBG_MAX_LENGTH;
341     drbg->max_adinlen = DRBG_MAX_LENGTH;
342
343     /* Maximum number of bits per request = 2^19  = 2^16 bytes */
344     drbg->max_request = 1 << 16;
345
346     return 1;
347 }