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