Rewrite OutputValue to avoid use of buffer when printing out hex values.
[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 tidy_line(char *linebuf, char *olinebuf);
63 int bint2bin(const char *in, int len, unsigned char *out);
64 int bin2bint(const unsigned char *in,int len,char *out);
65 void PrintValue(char *tag, unsigned char *val, int len);
66 void OutputValue(char *tag, unsigned char *val, int len, FILE *rfp,int bitmode);
67 void fips_algtest_init(void);
68 void do_entropy_stick(void);
69
70 static int no_err;
71
72 static void put_err_cb(int lib, int func,int reason,const char *file,int line)
73         {
74                 if (no_err)
75                         return;
76                 fprintf(stderr, "ERROR:%08lX:lib=%d,func=%d,reason=%d"
77                                 ":file=%s:line=%d\n",
78                         ERR_PACK(lib, func, reason),
79                         lib, func, reason, file, line);
80         }
81
82 static void add_err_cb(int num, va_list args)
83         {
84         int i;
85         char *str;
86         if (no_err)
87                 return;
88         fputs("\t", stderr);
89         for (i = 0; i < num; i++)
90                 {
91                 str = va_arg(args, char *);
92                 if (str)
93                         fputs(str, stderr);
94                 }
95         fputs("\n", stderr);
96         }
97
98 /* Dummy Entropy to keep DRBG happy. WARNING: THIS IS TOTALLY BOGUS
99  * HAS ZERO SECURITY AND MUST NOT BE USED IN REAL APPLICATIONS.
100  */
101
102 static unsigned char dummy_entropy[1024];
103
104 static size_t dummy_cb(DRBG_CTX *ctx, unsigned char **pout,
105                                 int entropy, size_t min_len, size_t max_len)
106         {
107         *pout = dummy_entropy;
108         return min_len;
109         }
110
111 static int entropy_stick = 0;
112
113 static void fips_algtest_init_nofips(void)
114         {
115         DRBG_CTX *ctx;
116         size_t i;
117         FIPS_set_error_callbacks(put_err_cb, add_err_cb);
118         for (i = 0; i < sizeof(dummy_entropy); i++)
119                 dummy_entropy[i] = i & 0xff;
120         if (entropy_stick)
121                 memcpy(dummy_entropy + 32, dummy_entropy + 16, 16);
122         ctx = FIPS_get_default_drbg();
123         FIPS_drbg_init(ctx, NID_aes_256_ctr, DRBG_FLAG_CTR_USE_DF);
124         FIPS_drbg_set_callbacks(ctx, dummy_cb, 0, 16, dummy_cb, 0);
125         FIPS_drbg_instantiate(ctx, dummy_entropy, 10);
126         FIPS_rand_set_method(FIPS_drbg_method());
127         }
128
129 void do_entropy_stick(void)
130         {
131         entropy_stick = 1;
132         }
133
134 void fips_algtest_init(void)
135         {
136         fips_algtest_init_nofips();
137         if (!FIPS_mode_set(1))
138                 {
139                 fprintf(stderr, "Error entering FIPS mode\n");
140                 exit(1);
141                 }
142         }
143
144 int hex2bin(const char *in, unsigned char *out)
145     {
146     int n1, n2, isodd = 0;
147     unsigned char ch;
148
149     n1 = strlen(in);
150     if (in[n1 - 1] == '\n')
151         n1--;
152
153     if (n1 & 1)
154         isodd = 1;
155
156     for (n1=0,n2=0 ; in[n1] && in[n1] != '\n' ; )
157         { /* first byte */
158         if ((in[n1] >= '0') && (in[n1] <= '9'))
159             ch = in[n1++] - '0';
160         else if ((in[n1] >= 'A') && (in[n1] <= 'F'))
161             ch = in[n1++] - 'A' + 10;
162         else if ((in[n1] >= 'a') && (in[n1] <= 'f'))
163             ch = in[n1++] - 'a' + 10;
164         else
165             return -1;
166         if(!in[n1])
167             {
168             out[n2++]=ch;
169             break;
170             }
171         /* If input is odd length first digit is least significant: assumes
172          * all digits valid hex and null terminated which is true for the
173          * strings we pass.
174          */
175         if (n1 == 1 && isodd)
176                 {
177                 out[n2++] = ch;
178                 continue;
179                 }
180         out[n2] = ch << 4;
181         /* second byte */
182         if ((in[n1] >= '0') && (in[n1] <= '9'))
183             ch = in[n1++] - '0';
184         else if ((in[n1] >= 'A') && (in[n1] <= 'F'))
185             ch = in[n1++] - 'A' + 10;
186         else if ((in[n1] >= 'a') && (in[n1] <= 'f'))
187             ch = in[n1++] - 'a' + 10;
188         else
189             return -1;
190         out[n2++] |= ch;
191         }
192     return n2;
193     }
194
195 unsigned char *hex2bin_m(const char *in, long *plen)
196         {
197         unsigned char *p;
198         if (strlen(in) == 0)
199                 {
200                 *plen = 0;
201                 return OPENSSL_malloc(1);
202                 }
203         p = OPENSSL_malloc((strlen(in) + 1)/2);
204         *plen = hex2bin(in, p);
205         return p;
206         }
207
208 int do_hex2bn(BIGNUM **pr, const char *in)
209         {
210         unsigned char *p;
211         long plen;
212         int r = 0;
213         p = hex2bin_m(in, &plen);
214         if (!p)
215                 return 0;
216         if (!*pr)
217                 *pr = BN_new();
218         if (!*pr)
219                 return 0;
220         if (BN_bin2bn(p, plen, *pr))
221                 r = 1;
222         OPENSSL_free(p);
223         return r;
224         }
225
226 int do_bn_print(FILE *out, const BIGNUM *bn)
227         {
228         int len, i;
229         unsigned char *tmp;
230         len = BN_num_bytes(bn);
231         if (len == 0)
232                 {
233                 fputs("00", out);
234                 return 1;
235                 }
236
237         tmp = OPENSSL_malloc(len);
238         if (!tmp)
239                 {
240                 fprintf(stderr, "Memory allocation error\n");
241                 return 0;
242                 }
243         BN_bn2bin(bn, tmp);
244         for (i = 0; i < len; i++)
245                 fprintf(out, "%02x", tmp[i]);
246         OPENSSL_free(tmp);
247         return 1;
248         }
249
250 int do_bn_print_name(FILE *out, const char *name, const BIGNUM *bn)
251         {
252         int r;
253         fprintf(out, "%s = ", name);
254         r = do_bn_print(out, bn);
255         if (!r)
256                 return 0;
257         fputs("\n", out);
258         return 1;
259         }
260
261 int parse_line(char **pkw, char **pval, char *linebuf, char *olinebuf)
262         {
263         char *keyword, *value, *p, *q;
264         strcpy(linebuf, olinebuf);
265         keyword = linebuf;
266         /* Skip leading space */
267         while (isspace((unsigned char)*keyword))
268                 keyword++;
269
270         /* Look for = sign */
271         p = strchr(linebuf, '=');
272
273         /* If no '=' exit */
274         if (!p)
275                 return 0;
276
277         q = p - 1;
278
279         /* Remove trailing space */
280         while (isspace((unsigned char)*q))
281                 *q-- = 0;
282
283         *p = 0;
284         value = p + 1;
285
286         /* Remove leading space from value */
287         while (isspace((unsigned char)*value))
288                 value++;
289
290         /* Remove trailing space from value */
291         p = value + strlen(value) - 1;
292
293         if (*p != '\n')
294                 fprintf(stderr, "Warning: missing EOL\n");
295
296         while (*p == '\n' || isspace((unsigned char)*p))
297                 *p-- = 0;
298
299         *pkw = keyword;
300         *pval = value;
301         return 1;
302         }
303
304 BIGNUM *hex2bn(const char *in)
305     {
306     BIGNUM *p=NULL;
307
308     if (!do_hex2bn(&p, in))
309         return NULL;
310
311     return p;
312     }
313
314 /* To avoid extensive changes to test program at this stage just convert
315  * the input line into an acceptable form. Keyword lines converted to form
316  * "keyword = value\n" no matter what white space present, all other lines
317  * just have leading and trailing space removed.
318  */
319
320 int tidy_line(char *linebuf, char *olinebuf)
321         {
322         char *keyword, *value, *p, *q;
323         strcpy(linebuf, olinebuf);
324         keyword = linebuf;
325         /* Skip leading space */
326         while (isspace((unsigned char)*keyword))
327                 keyword++;
328         /* Look for = sign */
329         p = strchr(linebuf, '=');
330
331         /* If no '=' just chop leading, trailing ws */
332         if (!p)
333                 {
334                 p = keyword + strlen(keyword) - 1;
335                 while (*p == '\n' || isspace((unsigned char)*p))
336                         *p-- = 0;
337                 strcpy(olinebuf, keyword);
338                 strcat(olinebuf, "\n");
339                 return 1;
340                 }
341
342         q = p - 1;
343
344         /* Remove trailing space */
345         while (isspace((unsigned char)*q))
346                 *q-- = 0;
347
348         *p = 0;
349         value = p + 1;
350
351         /* Remove leading space from value */
352         while (isspace((unsigned char)*value))
353                 value++;
354
355         /* Remove trailing space from value */
356         p = value + strlen(value) - 1;
357
358         while (*p == '\n' || isspace((unsigned char)*p))
359                 *p-- = 0;
360
361         strcpy(olinebuf, keyword);
362         strcat(olinebuf, " = ");
363         strcat(olinebuf, value);
364         strcat(olinebuf, "\n");
365
366         return 1;
367         }
368
369 /* NB: this return the number of _bits_ read */
370 int bint2bin(const char *in, int len, unsigned char *out)
371     {
372     int n;
373
374     memset(out,0,len);
375     for(n=0 ; n < len ; ++n)
376         if(in[n] == '1')
377             out[n/8]|=(0x80 >> (n%8));
378     return len;
379     }
380
381 int bin2bint(const unsigned char *in,int len,char *out)
382     {
383     int n;
384
385     for(n=0 ; n < len ; ++n)
386         out[n]=(in[n/8]&(0x80 >> (n%8))) ? '1' : '0';
387     return n;
388     }
389
390 /*-----------------------------------------------*/
391
392 void PrintValue(char *tag, unsigned char *val, int len)
393 {
394 #ifdef VERBOSE
395         OutputValue(tag, val, len, stdout, 0);
396 #endif
397 }
398
399 void OutputValue(char *tag, unsigned char *val, int len, FILE *rfp,int bitmode)
400     {
401     char obuf[2048];
402     int olen;
403
404     if(bitmode)
405         {
406         olen=bin2bint(val,len,obuf);
407         fprintf(rfp, "%s = %.*s\n", tag, olen, obuf);
408         }
409     else
410         {
411         int i;
412         fprintf(rfp, "%s = ", tag);
413         for (i = 0; i < len; i++)
414                 fprintf(rfp, "%02x", val[i]);
415         fputs("\n", rfp);
416         }
417
418 #if VERBOSE
419     printf("%s = %.*s\n", tag, olen, obuf);
420 #endif
421     }
422