Add continuous RNG test to entropy source. Entropy callbacks now need
[openssl.git] / fips / fips_utl.h
1 /* ====================================================================
2  * Copyright (c) 2007 The OpenSSL Project.  All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  *
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer. 
10  *
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in
13  *    the documentation and/or other materials provided with the
14  *    distribution.
15  *
16  * 3. All advertising materials mentioning features or use of this
17  *    software must display the following acknowledgment:
18  *    "This product includes software developed by the OpenSSL Project
19  *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
20  *
21  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
22  *    endorse or promote products derived from this software without
23  *    prior written permission. For written permission, please contact
24  *    openssl-core@openssl.org.
25  *
26  * 5. Products derived from this software may not be called "OpenSSL"
27  *    nor may "OpenSSL" appear in their names without prior written
28  *    permission of the OpenSSL Project.
29  *
30  * 6. Redistributions of any form whatsoever must retain the following
31  *    acknowledgment:
32  *    "This product includes software developed by the OpenSSL Project
33  *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
34  *
35  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
36  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
37  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
38  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
39  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
40  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
41  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
42  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
43  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
44  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
45  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
46  * OF THE POSSIBILITY OF SUCH DAMAGE.
47  *
48  */
49
50 #define OPENSSL_FIPSAPI
51
52 #include <openssl/fips_rand.h>
53 #include <openssl/objects.h>
54
55 int hex2bin(const char *in, unsigned char *out);
56 unsigned char *hex2bin_m(const char *in, long *plen);
57 int do_hex2bn(BIGNUM **pr, const char *in);
58 int do_bn_print(FILE *out, const BIGNUM *bn);
59 int do_bn_print_name(FILE *out, const char *name, const BIGNUM *bn);
60 int parse_line(char **pkw, char **pval, char *linebuf, char *olinebuf);
61 BIGNUM *hex2bn(const char *in);
62 int bin2hex(const unsigned char *in,int len,char *out);
63 void pv(const char *tag,const unsigned char *val,int len);
64 int tidy_line(char *linebuf, char *olinebuf);
65 int bint2bin(const char *in, int len, unsigned char *out);
66 int bin2bint(const unsigned char *in,int len,char *out);
67 void PrintValue(char *tag, unsigned char *val, int len);
68 void OutputValue(char *tag, unsigned char *val, int len, FILE *rfp,int bitmode);
69 void fips_algtest_init(void);
70 void do_entropy_stick(void);
71
72 static int no_err;
73
74 static void put_err_cb(int lib, int func,int reason,const char *file,int line)
75         {
76                 if (no_err)
77                         return;
78                 fprintf(stderr, "ERROR:%08lX:lib=%d,func=%d,reason=%d"
79                                 ":file=%s:line=%d\n",
80                         ERR_PACK(lib, func, reason),
81                         lib, func, reason, file, line);
82         }
83
84 static void add_err_cb(int num, va_list args)
85         {
86         int i;
87         char *str;
88         if (no_err)
89                 return;
90         fputs("\t", stderr);
91         for (i = 0; i < num; i++)
92                 {
93                 str = va_arg(args, char *);
94                 if (str)
95                         fputs(str, stderr);
96                 }
97         fputs("\n", stderr);
98         }
99
100 /* Dummy Entropy to keep DRBG happy. WARNING: THIS IS TOTALLY BOGUS
101  * HAS ZERO SECURITY AND MUST NOT BE USED IN REAL APPLICATIONS.
102  */
103
104 static unsigned char dummy_entropy[1024];
105
106 static size_t dummy_cb(DRBG_CTX *ctx, unsigned char **pout,
107                                 int entropy, size_t min_len, size_t max_len)
108         {
109         *pout = dummy_entropy;
110         return min_len;
111         }
112
113 static int entropy_stick = 0;
114
115 static void fips_algtest_init_nofips(void)
116         {
117         DRBG_CTX *ctx;
118         size_t i;
119         FIPS_set_error_callbacks(put_err_cb, add_err_cb);
120         for (i = 0; i < sizeof(dummy_entropy); i++)
121                 dummy_entropy[i] = i & 0xff;
122         if (entropy_stick)
123                 memcpy(dummy_entropy + 32, dummy_entropy + 16, 16);
124         ctx = FIPS_get_default_drbg();
125         FIPS_drbg_init(ctx, NID_aes_256_ctr, DRBG_FLAG_CTR_USE_DF);
126         FIPS_drbg_set_callbacks(ctx, dummy_cb, 0, 16, dummy_cb, 0);
127         FIPS_drbg_instantiate(ctx, dummy_entropy, 10);
128         FIPS_rand_set_method(FIPS_drbg_method());
129         }
130
131 void do_entropy_stick(void)
132         {
133         entropy_stick = 1;
134         }
135
136 void fips_algtest_init(void)
137         {
138         fips_algtest_init_nofips();
139         if (!FIPS_mode_set(1))
140                 {
141                 fprintf(stderr, "Error entering FIPS mode\n");
142                 exit(1);
143                 }
144         }
145
146 int hex2bin(const char *in, unsigned char *out)
147     {
148     int n1, n2, isodd = 0;
149     unsigned char ch;
150
151     n1 = strlen(in);
152     if (in[n1 - 1] == '\n')
153         n1--;
154
155     if (n1 & 1)
156         isodd = 1;
157
158     for (n1=0,n2=0 ; in[n1] && in[n1] != '\n' ; )
159         { /* first byte */
160         if ((in[n1] >= '0') && (in[n1] <= '9'))
161             ch = in[n1++] - '0';
162         else if ((in[n1] >= 'A') && (in[n1] <= 'F'))
163             ch = in[n1++] - 'A' + 10;
164         else if ((in[n1] >= 'a') && (in[n1] <= 'f'))
165             ch = in[n1++] - 'a' + 10;
166         else
167             return -1;
168         if(!in[n1])
169             {
170             out[n2++]=ch;
171             break;
172             }
173         /* If input is odd length first digit is least significant: assumes
174          * all digits valid hex and null terminated which is true for the
175          * strings we pass.
176          */
177         if (n1 == 1 && isodd)
178                 {
179                 out[n2++] = ch;
180                 continue;
181                 }
182         out[n2] = ch << 4;
183         /* second byte */
184         if ((in[n1] >= '0') && (in[n1] <= '9'))
185             ch = in[n1++] - '0';
186         else if ((in[n1] >= 'A') && (in[n1] <= 'F'))
187             ch = in[n1++] - 'A' + 10;
188         else if ((in[n1] >= 'a') && (in[n1] <= 'f'))
189             ch = in[n1++] - 'a' + 10;
190         else
191             return -1;
192         out[n2++] |= ch;
193         }
194     return n2;
195     }
196
197 unsigned char *hex2bin_m(const char *in, long *plen)
198         {
199         unsigned char *p;
200         if (strlen(in) == 0)
201                 {
202                 *plen = 0;
203                 return OPENSSL_malloc(1);
204                 }
205         p = OPENSSL_malloc((strlen(in) + 1)/2);
206         *plen = hex2bin(in, p);
207         return p;
208         }
209
210 int do_hex2bn(BIGNUM **pr, const char *in)
211         {
212         unsigned char *p;
213         long plen;
214         int r = 0;
215         p = hex2bin_m(in, &plen);
216         if (!p)
217                 return 0;
218         if (!*pr)
219                 *pr = BN_new();
220         if (!*pr)
221                 return 0;
222         if (BN_bin2bn(p, plen, *pr))
223                 r = 1;
224         OPENSSL_free(p);
225         return r;
226         }
227
228 int do_bn_print(FILE *out, const BIGNUM *bn)
229         {
230         int len, i;
231         unsigned char *tmp;
232         len = BN_num_bytes(bn);
233         if (len == 0)
234                 {
235                 fputs("00", out);
236                 return 1;
237                 }
238
239         tmp = OPENSSL_malloc(len);
240         if (!tmp)
241                 {
242                 fprintf(stderr, "Memory allocation error\n");
243                 return 0;
244                 }
245         BN_bn2bin(bn, tmp);
246         for (i = 0; i < len; i++)
247                 fprintf(out, "%02x", tmp[i]);
248         OPENSSL_free(tmp);
249         return 1;
250         }
251
252 int do_bn_print_name(FILE *out, const char *name, const BIGNUM *bn)
253         {
254         int r;
255         fprintf(out, "%s = ", name);
256         r = do_bn_print(out, bn);
257         if (!r)
258                 return 0;
259         fputs("\n", out);
260         return 1;
261         }
262
263 int parse_line(char **pkw, char **pval, char *linebuf, char *olinebuf)
264         {
265         char *keyword, *value, *p, *q;
266         strcpy(linebuf, olinebuf);
267         keyword = linebuf;
268         /* Skip leading space */
269         while (isspace((unsigned char)*keyword))
270                 keyword++;
271
272         /* Look for = sign */
273         p = strchr(linebuf, '=');
274
275         /* If no '=' exit */
276         if (!p)
277                 return 0;
278
279         q = p - 1;
280
281         /* Remove trailing space */
282         while (isspace((unsigned char)*q))
283                 *q-- = 0;
284
285         *p = 0;
286         value = p + 1;
287
288         /* Remove leading space from value */
289         while (isspace((unsigned char)*value))
290                 value++;
291
292         /* Remove trailing space from value */
293         p = value + strlen(value) - 1;
294
295         if (*p != '\n')
296                 fprintf(stderr, "Warning: missing EOL\n");
297
298         while (*p == '\n' || isspace((unsigned char)*p))
299                 *p-- = 0;
300
301         *pkw = keyword;
302         *pval = value;
303         return 1;
304         }
305
306 BIGNUM *hex2bn(const char *in)
307     {
308     BIGNUM *p=NULL;
309
310     if (!do_hex2bn(&p, in))
311         return NULL;
312
313     return p;
314     }
315
316 int bin2hex(const unsigned char *in,int len,char *out)
317     {
318     int n1, n2;
319     unsigned char ch;
320
321     for (n1=0,n2=0 ; n1 < len ; ++n1)
322         {
323         ch=in[n1] >> 4;
324         if (ch <= 0x09)
325             out[n2++]=ch+'0';
326         else
327             out[n2++]=ch-10+'a';
328         ch=in[n1] & 0x0f;
329         if(ch <= 0x09)
330             out[n2++]=ch+'0';
331         else
332             out[n2++]=ch-10+'a';
333         }
334     out[n2]='\0';
335     return n2;
336     }
337
338 void pv(const char *tag,const unsigned char *val,int len)
339     {
340     char obuf[2048];
341
342     bin2hex(val,len,obuf);
343     printf("%s = %s\n",tag,obuf);
344     }
345
346 /* To avoid extensive changes to test program at this stage just convert
347  * the input line into an acceptable form. Keyword lines converted to form
348  * "keyword = value\n" no matter what white space present, all other lines
349  * just have leading and trailing space removed.
350  */
351
352 int tidy_line(char *linebuf, char *olinebuf)
353         {
354         char *keyword, *value, *p, *q;
355         strcpy(linebuf, olinebuf);
356         keyword = linebuf;
357         /* Skip leading space */
358         while (isspace((unsigned char)*keyword))
359                 keyword++;
360         /* Look for = sign */
361         p = strchr(linebuf, '=');
362
363         /* If no '=' just chop leading, trailing ws */
364         if (!p)
365                 {
366                 p = keyword + strlen(keyword) - 1;
367                 while (*p == '\n' || isspace((unsigned char)*p))
368                         *p-- = 0;
369                 strcpy(olinebuf, keyword);
370                 strcat(olinebuf, "\n");
371                 return 1;
372                 }
373
374         q = p - 1;
375
376         /* Remove trailing space */
377         while (isspace((unsigned char)*q))
378                 *q-- = 0;
379
380         *p = 0;
381         value = p + 1;
382
383         /* Remove leading space from value */
384         while (isspace((unsigned char)*value))
385                 value++;
386
387         /* Remove trailing space from value */
388         p = value + strlen(value) - 1;
389
390         while (*p == '\n' || isspace((unsigned char)*p))
391                 *p-- = 0;
392
393         strcpy(olinebuf, keyword);
394         strcat(olinebuf, " = ");
395         strcat(olinebuf, value);
396         strcat(olinebuf, "\n");
397
398         return 1;
399         }
400
401 /* NB: this return the number of _bits_ read */
402 int bint2bin(const char *in, int len, unsigned char *out)
403     {
404     int n;
405
406     memset(out,0,len);
407     for(n=0 ; n < len ; ++n)
408         if(in[n] == '1')
409             out[n/8]|=(0x80 >> (n%8));
410     return len;
411     }
412
413 int bin2bint(const unsigned char *in,int len,char *out)
414     {
415     int n;
416
417     for(n=0 ; n < len ; ++n)
418         out[n]=(in[n/8]&(0x80 >> (n%8))) ? '1' : '0';
419     return n;
420     }
421
422 /*-----------------------------------------------*/
423
424 void PrintValue(char *tag, unsigned char *val, int len)
425 {
426 #if VERBOSE
427   char obuf[2048];
428   int olen;
429   olen = bin2hex(val, len, obuf);
430   printf("%s = %.*s\n", tag, olen, obuf);
431 #endif
432 }
433
434 void OutputValue(char *tag, unsigned char *val, int len, FILE *rfp,int bitmode)
435     {
436     char obuf[2048];
437     int olen;
438
439     if(bitmode)
440         olen=bin2bint(val,len,obuf);
441     else
442         olen=bin2hex(val,len,obuf);
443
444     fprintf(rfp, "%s = %.*s\n", tag, olen, obuf);
445 #if VERBOSE
446     printf("%s = %.*s\n", tag, olen, obuf);
447 #endif
448     }
449