Check return codes properly.
[openssl.git] / fips / rand / fips_drbg_ec.c
1 /* fips/rand/fips_drbg_ec.c */
2 /* Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL
3  * project.
4  */
5 /* ====================================================================
6  * Copyright (c) 2011 The OpenSSL Project.  All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  *
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer. 
14  *
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in
17  *    the documentation and/or other materials provided with the
18  *    distribution.
19  *
20  * 3. All advertising materials mentioning features or use of this
21  *    software must display the following acknowledgment:
22  *    "This product includes software developed by the OpenSSL Project
23  *    for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
24  *
25  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
26  *    endorse or promote products derived from this software without
27  *    prior written permission. For written permission, please contact
28  *    licensing@OpenSSL.org.
29  *
30  * 5. Products derived from this software may not be called "OpenSSL"
31  *    nor may "OpenSSL" appear in their names without prior written
32  *    permission of the OpenSSL Project.
33  *
34  * 6. Redistributions of any form whatsoever must retain the following
35  *    acknowledgment:
36  *    "This product includes software developed by the OpenSSL Project
37  *    for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
38  *
39  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
40  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
41  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
42  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
43  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
44  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
45  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
46  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
48  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
49  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
50  * OF THE POSSIBILITY OF SUCH DAMAGE.
51  * ====================================================================
52  */
53
54 #define OPENSSL_FIPSAPI
55
56 #include <stdlib.h>
57 #include <string.h>
58 #include <openssl/crypto.h>
59 #include <openssl/fips.h>
60 #include <openssl/fips_rand.h>
61 #include <openssl/bn.h>
62 #include "fips_rand_lcl.h"
63
64 /*#define EC_DRBG_TRACE*/
65
66 #ifdef EC_DRBG_TRACE
67 static void hexprint(FILE *out, const unsigned char *buf, int buflen)
68         {
69         int i;
70         fprintf(out, "\t");
71         for (i = 0; i < buflen; i++)
72                 fprintf(out, "%02X", buf[i]);
73         fprintf(out, "\n");
74         }
75 static void bnprint(FILE *out, const char *name, const BIGNUM *b)
76         {
77         unsigned char *tmp;
78         int len;
79         len = BN_num_bytes(b);
80         tmp = OPENSSL_malloc(len);
81         BN_bn2bin(b, tmp);
82         fprintf(out, "%s\n", name);
83         hexprint(out, tmp, len);
84         OPENSSL_free(tmp);
85         }
86 #if 0
87 static void ecprint(FILE *out, EC_GROUP *grp, EC_POINT *pt)
88         {
89         BIGNUM *x, *y;
90         x = BN_new();
91         y = BN_new();
92         EC_POINT_get_affine_coordinates_GFp(grp, pt, x, y, NULL);
93         bnprint(out, "\tPoint X: ", x);
94         bnprint(out, "\tPoint Y: ", y);
95         BN_free(x);
96         BN_free(y);
97         }
98 #endif
99 #endif
100
101 /* This is Hash_df from SP 800-90 10.4.1 */
102
103 static int hash_df(DRBG_CTX *dctx, unsigned char *out,
104                         const unsigned char *in1, size_t in1len,
105                         const unsigned char *in2, size_t in2len,
106                         const unsigned char *in3, size_t in3len)
107         {
108         DRBG_EC_CTX *ectx = &dctx->d.ec;
109         EVP_MD_CTX *mctx = &ectx->mctx;
110         unsigned char *vtmp = ectx->vtmp;
111         unsigned char tmp[6];
112         size_t mdlen = M_EVP_MD_size(ectx->md);
113         /* Standard only ever needs seedlen bytes which is always less than
114          * maximum permitted so no need to check length.
115          */
116         size_t outlen = dctx->seedlen;
117         size_t nbits = (outlen << 3) - ectx->exbits;
118         tmp[0] = 1;
119         tmp[1] = (nbits >> 24) & 0xff;
120         tmp[2] = (nbits >> 16) & 0xff;
121         tmp[3] = (nbits >> 8) & 0xff;
122         tmp[4] = nbits & 0xff;
123         if (!in1)
124                 {
125                 tmp[5] = (unsigned char)in1len;
126                 in1 = tmp + 5;
127                 in1len = 1;
128                 }
129         for (;;)
130                 {
131                 if (!FIPS_digestinit(mctx, ectx->md))
132                         return 0;
133                 if (!FIPS_digestupdate(mctx, tmp, 5))
134                         return 0;
135                 if (in1 && !FIPS_digestupdate(mctx, in1, in1len))
136                         return 0;
137                 if (in2 && !FIPS_digestupdate(mctx, in2, in2len))
138                         return 0;
139                 if (in3 && !FIPS_digestupdate(mctx, in3, in3len))
140                         return 0;
141                 if (outlen < mdlen)
142                         {
143                         if (!FIPS_digestfinal(mctx, vtmp, NULL))
144                                 return 0;
145                         memcpy(out, vtmp, outlen);
146                         OPENSSL_cleanse(vtmp, mdlen);
147                         return 1;
148                         }
149                 else if(!FIPS_digestfinal(mctx, out, NULL))
150                         return 0;
151
152                 outlen -= mdlen;
153                 if (outlen == 0)
154                         return 1;
155                 tmp[0]++;
156                 out += mdlen;
157                 }
158         }
159
160 static int bn2binpad(unsigned char *to, size_t tolen, BIGNUM *b)
161         {
162         size_t blen;
163         blen = BN_num_bytes(b);
164         /* If BIGNUM length greater than buffer, mask to get rightmost
165          * bytes. NB: modifies b but this doesn't matter for our purposes.
166          */
167         if (blen > tolen)
168                 {
169                 BN_mask_bits(b, tolen << 3);
170                 /* Update length because mask operation might create leading
171                  * zeroes.
172                  */
173                 blen = BN_num_bytes(b);
174                 }
175         /* If b length smaller than buffer pad with zeroes */
176         if (blen < tolen)
177                 {
178                 memset(to, 0, tolen - blen);
179                 to += tolen - blen;
180                 }
181
182         /* This call cannot fail */
183         BN_bn2bin(b, to);
184         return 1;
185         }
186 /* Convert buffer to a BIGNUM discarding extra bits if necessary */
187 static int bin2bnbits(DRBG_CTX *dctx, BIGNUM *r, const unsigned char *buf)
188         {
189         DRBG_EC_CTX *ectx = &dctx->d.ec;
190         if (!BN_bin2bn(buf, dctx->seedlen, r))
191                 return 0;
192         /* If we have extra bits right shift off the end of r */
193         if (ectx->exbits)
194                 {
195                 if (!BN_rshift(r, r, ectx->exbits))
196                         return 0;
197                 }
198         return 1;
199         }
200
201 /* Calculate r = phi(s * P) or r= phi(s * Q) */
202
203 static int drbg_ec_mul(DRBG_EC_CTX *ectx, BIGNUM *r, const BIGNUM *s, int use_q)
204         {
205         if (use_q)
206                 {
207                 if (!EC_POINT_mul(ectx->curve, ectx->ptmp,
208                                                 NULL, ectx->Q, s, ectx->bctx))
209                         return 0;
210                 }
211         else
212                 {
213                 if (!EC_POINT_mul(ectx->curve, ectx->ptmp,
214                                                 s, NULL, NULL, ectx->bctx))
215                         return 0;
216                 }
217         /* Get x coordinate of result */
218         if (!EC_POINT_get_affine_coordinates_GFp(ectx->curve, ectx->ptmp, r,
219                                                         NULL, ectx->bctx))
220                 return 0;
221         return 1;
222         }
223
224 static int drbg_ec_instantiate(DRBG_CTX *dctx,
225                                 const unsigned char *ent, size_t ent_len,
226                                 const unsigned char *nonce, size_t nonce_len,
227                                 const unsigned char *pstr, size_t pstr_len)
228         {
229         DRBG_EC_CTX *ectx = &dctx->d.ec;
230         if (!hash_df(dctx, ectx->sbuf, 
231                         ent, ent_len, nonce, nonce_len, pstr, pstr_len))
232                 return 0;
233         if (!bin2bnbits(dctx, ectx->s, ectx->sbuf))
234                 return 0;
235         return 1;
236         }
237
238         
239 static int drbg_ec_reseed(DRBG_CTX *dctx,
240                                 const unsigned char *ent, size_t ent_len,
241                                 const unsigned char *adin, size_t adin_len)
242         {
243         DRBG_EC_CTX *ectx = &dctx->d.ec;
244         /* Check if we have a deferred s = s * P */
245         if (ectx->sp_defer)
246                 {
247                 if (!drbg_ec_mul(ectx, ectx->s, ectx->s, 0))
248                         return 0;
249                 ectx->sp_defer = 0;
250                 }
251         /* Convert s value to a binary buffer. Save it to tbuf as we are
252          * about to overwrite it.
253          */
254         if (ectx->exbits)
255                 BN_lshift(ectx->s, ectx->s, ectx->exbits);
256         bn2binpad(ectx->tbuf, dctx->seedlen, ectx->s);
257         if (!hash_df(dctx, ectx->sbuf, ectx->tbuf, dctx->seedlen, 
258                         ent, ent_len, adin, adin_len))
259                 return 0;
260         if (!bin2bnbits(dctx, ectx->s, ectx->sbuf))
261                 return 0;
262         dctx->reseed_counter = 0;
263         return 1;
264         }
265
266 static int drbg_ec_generate(DRBG_CTX *dctx,
267                                 unsigned char *out, size_t outlen,
268                                 const unsigned char *adin, size_t adin_len)
269         {
270         DRBG_EC_CTX *ectx = &dctx->d.ec;
271         BIGNUM *t, *r;
272         BIGNUM *s = ectx->s;
273         /* special case: check reseed interval */
274         if (out == NULL)
275                 {
276                 size_t nb = (outlen + dctx->blocklength - 1)/dctx->blocklength;
277                 if (dctx->reseed_counter + nb > dctx->reseed_interval)
278                         dctx->status = DRBG_STATUS_RESEED;
279                 return 1;
280                 }
281         /* Check if we have a deferred s = s * P */
282         if (ectx->sp_defer)
283                 {
284                 if (!drbg_ec_mul(ectx, s, s, 0))
285                         goto err;
286                 ectx->sp_defer = 0;
287                 }
288
289         BN_CTX_start(ectx->bctx);
290         r = BN_CTX_get(ectx->bctx);
291         if (!r)
292                 goto err;
293         if (adin && adin_len)
294                 {
295                 size_t i;
296                 t = BN_CTX_get(ectx->bctx);
297                 if (!t)
298                         goto err;
299                 /* Convert s to buffer */
300                 if (ectx->exbits)
301                         BN_lshift(s, s, ectx->exbits);
302                 bn2binpad(ectx->sbuf, dctx->seedlen, s);
303                 /* Step 2 */
304                 if (!hash_df(dctx, ectx->tbuf, adin, adin_len,
305                                 NULL, 0, NULL, 0))
306                         goto err;
307                 /* Step 5 */
308                 for (i = 0; i < dctx->seedlen; i++)
309                         ectx->tbuf[i] ^= ectx->sbuf[i];
310                 if (!bin2bnbits(dctx, t, ectx->tbuf))
311                         return 0;
312                 }
313         else
314                 /* Note if no additional input the algorithm never
315                  * needs separate values for t and s.
316                  */
317                 t = s;
318
319 #ifdef EC_DRBG_TRACE
320         bnprint(stderr, "s at start of generate: ", s);
321 #endif
322
323         for (;;)
324                 {
325                 /* Step #6, calculate s = t * P */
326                 if (!drbg_ec_mul(ectx, s, t, 0))
327                         goto err;
328 #ifdef EC_DRBG_TRACE
329                 bnprint(stderr, "s in generate: ", ectx->s);
330 #endif
331                 /* Step #7, calculate r = s * Q */
332                 if (!drbg_ec_mul(ectx, r, s, 1))
333                         goto err;
334 #ifdef EC_DRBG_TRACE
335         bnprint(stderr, "r in generate is: ", r);
336 #endif
337                 dctx->reseed_counter++;
338                 /* Get rightmost bits of r to output buffer */
339
340                 if (!(dctx->xflags & DRBG_FLAG_TEST) && !dctx->lb_valid)
341                         {
342                         if (!bn2binpad(dctx->lb, dctx->blocklength, r))
343                                 goto err;
344                         dctx->lb_valid = 1;
345                         continue;
346                         }
347                 if (outlen < dctx->blocklength)
348                         {
349                         if (!bn2binpad(ectx->vtmp, dctx->blocklength, r))
350                                 goto err;
351                         if (!fips_drbg_cprng_test(dctx, ectx->vtmp))
352                                 goto err;
353                         memcpy(out, ectx->vtmp, outlen);
354                         break;
355                         }
356                 else
357                         {
358                         if (!bn2binpad(out, dctx->blocklength, r))
359                                 goto err;
360                         if (!fips_drbg_cprng_test(dctx, out))
361                                 goto err;
362                         }       
363                 outlen -= dctx->blocklength;
364                 if (!outlen)
365                         break;
366                 out += dctx->blocklength;
367                 /* Step #5 after first pass */
368                 t = s;
369 #ifdef EC_DRBG_TRACE
370                 fprintf(stderr, "Random bits written:\n");
371                 hexprint(stderr, out, dctx->blocklength);
372 #endif
373                 }
374         /* Defer s = s * P until we need it */
375         ectx->sp_defer = 1;
376 #ifdef EC_DRBG_TRACE
377         bnprint(stderr, "s after generate is: ", s);
378 #endif
379         BN_CTX_end(ectx->bctx);
380         return 1;
381         err:
382         BN_CTX_end(ectx->bctx);
383         return 0;
384         }
385
386 static int drbg_ec_uninstantiate(DRBG_CTX *dctx)
387         {
388         DRBG_EC_CTX *ectx = &dctx->d.ec;
389         EVP_MD_CTX_cleanup(&ectx->mctx);
390         EC_GROUP_free(ectx->curve);
391         EC_POINT_free(ectx->Q);
392         EC_POINT_free(ectx->ptmp);
393         BN_clear_free(ectx->s);
394         BN_CTX_free(ectx->bctx);
395         OPENSSL_cleanse(&dctx->d.ec, sizeof(DRBG_EC_CTX));
396         return 1;
397         }
398
399 /* Q points from SP 800-90 A.1, P is generator */
400
401 __fips_constseg
402 static const unsigned char p_256_qx[] = {
403         0xc9,0x74,0x45,0xf4,0x5c,0xde,0xf9,0xf0,0xd3,0xe0,0x5e,0x1e,
404         0x58,0x5f,0xc2,0x97,0x23,0x5b,0x82,0xb5,0xbe,0x8f,0xf3,0xef,
405         0xca,0x67,0xc5,0x98,0x52,0x01,0x81,0x92
406 };
407 __fips_constseg
408 static const unsigned char p_256_qy[] = {
409         0xb2,0x8e,0xf5,0x57,0xba,0x31,0xdf,0xcb,0xdd,0x21,0xac,0x46,
410         0xe2,0xa9,0x1e,0x3c,0x30,0x4f,0x44,0xcb,0x87,0x05,0x8a,0xda,
411         0x2c,0xb8,0x15,0x15,0x1e,0x61,0x00,0x46
412 };
413
414 __fips_constseg
415 static const unsigned char p_384_qx[] = {
416         0x8e,0x72,0x2d,0xe3,0x12,0x5b,0xdd,0xb0,0x55,0x80,0x16,0x4b,
417         0xfe,0x20,0xb8,0xb4,0x32,0x21,0x6a,0x62,0x92,0x6c,0x57,0x50,
418         0x2c,0xee,0xde,0x31,0xc4,0x78,0x16,0xed,0xd1,0xe8,0x97,0x69,
419         0x12,0x41,0x79,0xd0,0xb6,0x95,0x10,0x64,0x28,0x81,0x50,0x65
420 };
421 __fips_constseg
422 static const unsigned char p_384_qy[] = {
423         0x02,0x3b,0x16,0x60,0xdd,0x70,0x1d,0x08,0x39,0xfd,0x45,0xee,
424         0xc3,0x6f,0x9e,0xe7,0xb3,0x2e,0x13,0xb3,0x15,0xdc,0x02,0x61,
425         0x0a,0xa1,0xb6,0x36,0xe3,0x46,0xdf,0x67,0x1f,0x79,0x0f,0x84,
426         0xc5,0xe0,0x9b,0x05,0x67,0x4d,0xbb,0x7e,0x45,0xc8,0x03,0xdd
427 };
428
429 __fips_constseg
430 static const unsigned char p_521_qx[] = {
431         0x01,0xb9,0xfa,0x3e,0x51,0x8d,0x68,0x3c,0x6b,0x65,0x76,0x36,
432         0x94,0xac,0x8e,0xfb,0xae,0xc6,0xfa,0xb4,0x4f,0x22,0x76,0x17,
433         0x1a,0x42,0x72,0x65,0x07,0xdd,0x08,0xad,0xd4,0xc3,0xb3,0xf4,
434         0xc1,0xeb,0xc5,0xb1,0x22,0x2d,0xdb,0xa0,0x77,0xf7,0x22,0x94,
435         0x3b,0x24,0xc3,0xed,0xfa,0x0f,0x85,0xfe,0x24,0xd0,0xc8,0xc0,
436         0x15,0x91,0xf0,0xbe,0x6f,0x63
437 };
438 __fips_constseg
439 static const unsigned char p_521_qy[] = {
440         0x01,0xf3,0xbd,0xba,0x58,0x52,0x95,0xd9,0xa1,0x11,0x0d,0x1d,
441         0xf1,0xf9,0x43,0x0e,0xf8,0x44,0x2c,0x50,0x18,0x97,0x6f,0xf3,
442         0x43,0x7e,0xf9,0x1b,0x81,0xdc,0x0b,0x81,0x32,0xc8,0xd5,0xc3,
443         0x9c,0x32,0xd0,0xe0,0x04,0xa3,0x09,0x2b,0x7d,0x32,0x7c,0x0e,
444         0x7a,0x4d,0x26,0xd2,0xc7,0xb6,0x9b,0x58,0xf9,0x06,0x66,0x52,
445         0x91,0x1e,0x45,0x77,0x79,0xde
446 };
447
448 int fips_drbg_ec_init(DRBG_CTX *dctx)
449         {
450         const EVP_MD *md;
451         const unsigned char *Q_x, *Q_y;
452         BIGNUM *x, *y;
453         size_t ptlen;
454         int md_nid = dctx->type & 0xffff;
455         int curve_nid = dctx->type >> 16;
456         DRBG_EC_CTX *ectx = &dctx->d.ec;
457         md = FIPS_get_digestbynid(md_nid);
458         if (!md)
459                 return -2;
460
461         /* These are taken from SP 800-90 10.3.1 table 4 */
462         switch (curve_nid)
463                 {
464                 case NID_X9_62_prime256v1:
465                 dctx->strength = 128;
466                 dctx->seedlen = 32;
467                 dctx->blocklength = 30;
468                 ectx->exbits = 0;
469                 Q_x = p_256_qx;
470                 Q_y = p_256_qy;
471                 ptlen = sizeof(p_256_qx);
472                 break;
473
474                 case NID_secp384r1:
475                 if (md_nid == NID_sha1)
476                         return -2;
477                 dctx->strength = 192;
478                 dctx->seedlen = 48;
479                 dctx->blocklength = 46;
480                 ectx->exbits = 0;
481                 Q_x = p_384_qx;
482                 Q_y = p_384_qy;
483                 ptlen = sizeof(p_384_qx);
484                 break;
485
486                 case NID_secp521r1:
487                 if (md_nid == NID_sha1 || md_nid == NID_sha224)
488                         return -2;
489                 dctx->strength = 256;
490                 dctx->seedlen = 66;
491                 dctx->blocklength = 63;
492                 ectx->exbits = 7;
493                 Q_x = p_521_qx;
494                 Q_y = p_521_qy;
495                 ptlen = sizeof(p_521_qx);
496                 break;
497
498                 default:
499                 return -2;
500                 }
501
502         dctx->iflags |= DRBG_CUSTOM_RESEED;
503         dctx->reseed_counter = 0;
504         dctx->instantiate = drbg_ec_instantiate;
505         dctx->reseed = drbg_ec_reseed;
506         dctx->generate = drbg_ec_generate;
507         dctx->uninstantiate = drbg_ec_uninstantiate;
508
509         ectx->md = md;
510         EVP_MD_CTX_init(&ectx->mctx);
511
512         dctx->min_entropy = dctx->strength / 8;
513         dctx->max_entropy = 2 << 10;
514
515         dctx->min_nonce = dctx->min_entropy / 2;
516         dctx->max_nonce = 2 << 10;
517
518         dctx->max_pers = 2 << 10;
519         dctx->max_adin = 2 << 10;
520
521         dctx->reseed_interval = 1<<24;
522         dctx->max_request = dctx->reseed_interval * dctx->blocklength;
523
524         /* Setup internal structures */
525         ectx->bctx = BN_CTX_new();
526         if (!ectx->bctx)
527                 return 0;
528         BN_CTX_start(ectx->bctx);
529
530         ectx->s = BN_new();
531
532         ectx->curve = EC_GROUP_new_by_curve_name(curve_nid);
533
534         ectx->Q = EC_POINT_new(ectx->curve);
535         ectx->ptmp = EC_POINT_new(ectx->curve);
536
537         ectx->sp_defer = 0;
538
539         x = BN_CTX_get(ectx->bctx);
540         y = BN_CTX_get(ectx->bctx);
541
542         if (!ectx->s || !ectx->curve || !ectx->Q || !y)
543                 goto err;
544
545         if (!BN_bin2bn(Q_x, ptlen, x) || !BN_bin2bn(Q_y, ptlen, y))
546                 goto err;
547         if (!EC_POINT_set_affine_coordinates_GFp(ectx->curve, ectx->Q,
548                                                         x, y, ectx->bctx))
549                 goto err;
550
551         BN_CTX_end(ectx->bctx);
552
553         return 1;
554         err:
555         BN_CTX_end(ectx->bctx);
556         drbg_ec_uninstantiate(dctx);
557         return 0;
558         }