keygen: add FIPS error state management to conditional self tests
[openssl.git] / apps / fipsinstall.c
1 /*
2  * Copyright 2019-2020 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 <string.h>
11 #include <openssl/evp.h>
12 #include <openssl/err.h>
13 #include <openssl/provider.h>
14 #include <openssl/params.h>
15 #include <openssl/fips_names.h>
16 #include <openssl/core_names.h>
17 #include <openssl/self_test.h>
18 #include <openssl/fipskey.h>
19 #include "apps.h"
20 #include "progs.h"
21
22 DEFINE_STACK_OF_STRING()
23
24 #define BUFSIZE 4096
25
26 /* Configuration file values */
27 #define VERSION_KEY  "version"
28 #define VERSION_VAL  "1"
29 #define INSTALL_STATUS_VAL "INSTALL_SELF_TEST_KATS_RUN"
30
31 static OSSL_CALLBACK self_test_events;
32 static char *self_test_corrupt_desc = NULL;
33 static char *self_test_corrupt_type = NULL;
34 static int self_test_log = 1;
35 static int quiet = 0;
36
37 typedef enum OPTION_choice {
38     OPT_ERR = -1, OPT_EOF = 0, OPT_HELP,
39     OPT_IN, OPT_OUT, OPT_MODULE,
40     OPT_PROV_NAME, OPT_SECTION_NAME, OPT_MAC_NAME, OPT_MACOPT, OPT_VERIFY,
41     OPT_NO_LOG, OPT_CORRUPT_DESC, OPT_CORRUPT_TYPE, OPT_QUIET, OPT_CONFIG,
42     OPT_NO_CONDITIONAL_ERRORS
43 } OPTION_CHOICE;
44
45 const OPTIONS fipsinstall_options[] = {
46     OPT_SECTION("General"),
47     {"help", OPT_HELP, '-', "Display this summary"},
48     {"verify", OPT_VERIFY, '-',
49         "Verify a config file instead of generating one"},
50     {"module", OPT_MODULE, '<', "File name of the provider module"},
51     {"provider_name", OPT_PROV_NAME, 's', "FIPS provider name"},
52     {"section_name", OPT_SECTION_NAME, 's',
53      "FIPS Provider config section name (optional)"},
54      {"no_conditional_errors", OPT_NO_CONDITIONAL_ERRORS, '-',
55       "Disable the ability of the fips module to enter an error state if"
56       " any conditional self tests fail"},
57     OPT_SECTION("Input"),
58     {"in", OPT_IN, '<', "Input config file, used when verifying"},
59
60     OPT_SECTION("Output"),
61     {"out", OPT_OUT, '>', "Output config file, used when generating"},
62     {"mac_name", OPT_MAC_NAME, 's', "MAC name"},
63     {"macopt", OPT_MACOPT, 's', "MAC algorithm parameters in n:v form. "
64                                 "See 'PARAMETER NAMES' in the EVP_MAC_ docs"},
65     {"noout", OPT_NO_LOG, '-', "Disable logging of self test events"},
66     {"corrupt_desc", OPT_CORRUPT_DESC, 's', "Corrupt a self test by description"},
67     {"corrupt_type", OPT_CORRUPT_TYPE, 's', "Corrupt a self test by type"},
68     {"config", OPT_CONFIG, '<', "The parent config to verify"},
69     {"quiet", OPT_QUIET, '-', "No messages, just exit status"},
70     {NULL}
71 };
72
73 static int do_mac(EVP_MAC_CTX *ctx, unsigned char *tmp, BIO *in,
74                   unsigned char *out, size_t *out_len)
75 {
76     int ret = 0;
77     int i;
78     size_t outsz = *out_len;
79
80     if (!EVP_MAC_init(ctx))
81         goto err;
82     if (EVP_MAC_size(ctx) > outsz)
83         goto end;
84     while ((i = BIO_read(in, (char *)tmp, BUFSIZE)) != 0) {
85         if (i < 0 || !EVP_MAC_update(ctx, tmp, i))
86             goto err;
87     }
88 end:
89     if (!EVP_MAC_final(ctx, out, out_len, outsz))
90         goto err;
91     ret = 1;
92 err:
93     return ret;
94 }
95
96 static int load_fips_prov_and_run_self_test(const char *prov_name)
97 {
98     int ret = 0;
99     OSSL_PROVIDER *prov = NULL;
100
101     prov = OSSL_PROVIDER_load(NULL, prov_name);
102     if (prov == NULL) {
103         BIO_printf(bio_err, "Failed to load FIPS module\n");
104         goto end;
105     }
106     ret = 1;
107 end:
108     OSSL_PROVIDER_unload(prov);
109     return ret;
110 }
111
112 static int print_mac(BIO *bio, const char *label, const unsigned char *mac,
113                      size_t len)
114 {
115     int ret;
116     char *hexstr = NULL;
117
118     hexstr = OPENSSL_buf2hexstr(mac, (long)len);
119     if (hexstr == NULL)
120         return 0;
121     ret = BIO_printf(bio, "%s = %s\n", label, hexstr);
122     OPENSSL_free(hexstr);
123     return ret;
124 }
125
126 static int write_config_header(BIO *out, const char *prov_name,
127                                const char *section)
128 {
129     return BIO_printf(out, "openssl_conf = openssl_init\n\n")
130            && BIO_printf(out, "[openssl_init]\n")
131            && BIO_printf(out, "providers = provider_section\n\n")
132            && BIO_printf(out, "[provider_section]\n")
133            && BIO_printf(out, "%s = %s\n\n", prov_name, section);
134 }
135
136 /*
137  * Outputs a fips related config file that contains entries for the fips
138  * module checksum, installation indicator checksum and the option
139  * conditional_errors.
140  *
141  * Returns 1 if the config file is written otherwise it returns 0 on error.
142  */
143 static int write_config_fips_section(BIO *out, const char *section,
144                                      unsigned char *module_mac,
145                                      size_t module_mac_len,
146                                      int conditional_errors,
147                                      unsigned char *install_mac,
148                                      size_t install_mac_len)
149 {
150     int ret = 0;
151
152     if (BIO_printf(out, "[%s]\n", section) <= 0
153         || BIO_printf(out, "activate = 1\n") <= 0
154         || BIO_printf(out, "%s = %s\n", OSSL_PROV_FIPS_PARAM_INSTALL_VERSION,
155                       VERSION_VAL) <= 0
156         || BIO_printf(out, "%s = %s\n", OSSL_PROV_FIPS_PARAM_CONDITIONAL_ERRORS,
157                       conditional_errors ? "1" : "0") <= 0
158         || !print_mac(out, OSSL_PROV_FIPS_PARAM_MODULE_MAC, module_mac,
159                       module_mac_len))
160         goto end;
161
162     if (install_mac != NULL) {
163         if (!(print_mac(out, OSSL_PROV_FIPS_PARAM_INSTALL_MAC, install_mac,
164                       install_mac_len)
165               && BIO_printf(out, "%s = %s\n",
166                             OSSL_PROV_FIPS_PARAM_INSTALL_STATUS,
167                             INSTALL_STATUS_VAL) > 0))
168         goto end;
169     }
170     ret = 1;
171 end:
172     return ret;
173 }
174
175 static CONF *generate_config_and_load(const char *prov_name,
176                                       const char *section,
177                                       unsigned char *module_mac,
178                                       size_t module_mac_len,
179                                       int conditional_errors)
180 {
181     BIO *mem_bio = NULL;
182     CONF *conf = NULL;
183
184     mem_bio = BIO_new(BIO_s_mem());
185     if (mem_bio  == NULL)
186         return 0;
187     if (!write_config_header(mem_bio, prov_name, section)
188          || !write_config_fips_section(mem_bio, section,
189                                        module_mac, module_mac_len,
190                                        conditional_errors,
191                                        NULL, 0))
192         goto end;
193
194     conf = app_load_config_bio(mem_bio, NULL);
195     if (conf == NULL)
196         goto end;
197
198     if (CONF_modules_load(conf, NULL, 0) <= 0)
199         goto end;
200     BIO_free(mem_bio);
201     return conf;
202 end:
203     NCONF_free(conf);
204     BIO_free(mem_bio);
205     return NULL;
206 }
207
208 static void free_config_and_unload(CONF *conf)
209 {
210     if (conf != NULL) {
211         NCONF_free(conf);
212         CONF_modules_unload(1);
213     }
214 }
215
216 static int verify_module_load(const char *parent_config_file)
217 {
218     return OPENSSL_CTX_load_config(NULL, parent_config_file);
219 }
220
221 /*
222  * Returns 1 if the config file entries match the passed in module_mac and
223  * install_mac values, otherwise it returns 0.
224  */
225 static int verify_config(const char *infile, const char *section,
226                          unsigned char *module_mac, size_t module_mac_len,
227                          unsigned char *install_mac, size_t install_mac_len)
228 {
229     int ret = 0;
230     char *s = NULL;
231     unsigned char *buf1 = NULL, *buf2 = NULL;
232     long len;
233     CONF *conf = NULL;
234
235     /* read in the existing values and check they match the saved values */
236     conf = app_load_config(infile);
237     if (conf == NULL)
238         goto end;
239
240     s = NCONF_get_string(conf, section, OSSL_PROV_FIPS_PARAM_INSTALL_VERSION);
241     if (s == NULL || strcmp(s, VERSION_VAL) != 0) {
242         BIO_printf(bio_err, "version not found\n");
243         goto end;
244     }
245     s = NCONF_get_string(conf, section, OSSL_PROV_FIPS_PARAM_INSTALL_STATUS);
246     if (s == NULL || strcmp(s, INSTALL_STATUS_VAL) != 0) {
247         BIO_printf(bio_err, "install status not found\n");
248         goto end;
249     }
250     s = NCONF_get_string(conf, section, OSSL_PROV_FIPS_PARAM_MODULE_MAC);
251     if (s == NULL) {
252         BIO_printf(bio_err, "Module integrity MAC not found\n");
253         goto end;
254     }
255     buf1 = OPENSSL_hexstr2buf(s, &len);
256     if (buf1 == NULL
257             || (size_t)len != module_mac_len
258             || memcmp(module_mac, buf1, module_mac_len) != 0) {
259         BIO_printf(bio_err, "Module integrity mismatch\n");
260         goto end;
261     }
262     s = NCONF_get_string(conf, section, OSSL_PROV_FIPS_PARAM_INSTALL_MAC);
263     if (s == NULL) {
264         BIO_printf(bio_err, "Install indicator MAC not found\n");
265         goto end;
266     }
267     buf2 = OPENSSL_hexstr2buf(s, &len);
268     if (buf2 == NULL
269             || (size_t)len != install_mac_len
270             || memcmp(install_mac, buf2, install_mac_len) != 0) {
271         BIO_printf(bio_err, "Install indicator status mismatch\n");
272         goto end;
273     }
274     ret = 1;
275 end:
276     OPENSSL_free(buf1);
277     OPENSSL_free(buf2);
278     NCONF_free(conf);
279     return ret;
280 }
281
282 int fipsinstall_main(int argc, char **argv)
283 {
284     int ret = 1, verify = 0, gotkey = 0, gotdigest = 0;
285     int enable_conditional_errors = 1;
286     const char *section_name = "fips_sect";
287     const char *mac_name = "HMAC";
288     const char *prov_name = "fips";
289     BIO *module_bio = NULL, *mem_bio = NULL, *fout = NULL;
290     char *in_fname = NULL, *out_fname = NULL, *prog;
291     char *module_fname = NULL, *parent_config = NULL, *module_path = NULL;
292     const char *tail;
293     EVP_MAC_CTX *ctx = NULL, *ctx2 = NULL;
294     STACK_OF(OPENSSL_STRING) *opts = NULL;
295     OPTION_CHOICE o;
296     unsigned char *read_buffer = NULL;
297     unsigned char module_mac[EVP_MAX_MD_SIZE];
298     size_t module_mac_len = EVP_MAX_MD_SIZE;
299     unsigned char install_mac[EVP_MAX_MD_SIZE];
300     size_t install_mac_len = EVP_MAX_MD_SIZE;
301     EVP_MAC *mac = NULL;
302     CONF *conf = NULL;
303
304     if ((opts = sk_OPENSSL_STRING_new_null()) == NULL)
305         goto end;
306
307     prog = opt_init(argc, argv, fipsinstall_options);
308     while ((o = opt_next()) != OPT_EOF) {
309         switch (o) {
310         case OPT_EOF:
311         case OPT_ERR:
312 opthelp:
313             BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
314             goto cleanup;
315         case OPT_HELP:
316             opt_help(fipsinstall_options);
317             ret = 0;
318             goto end;
319         case OPT_IN:
320             in_fname = opt_arg();
321             break;
322         case OPT_OUT:
323             out_fname = opt_arg();
324             break;
325         case OPT_NO_CONDITIONAL_ERRORS:
326             enable_conditional_errors = 0;
327             break;
328         case OPT_QUIET:
329             quiet = 1;
330             /* FALLTHROUGH */
331         case OPT_NO_LOG:
332             self_test_log = 0;
333             break;
334         case OPT_CORRUPT_DESC:
335             self_test_corrupt_desc = opt_arg();
336             break;
337         case OPT_CORRUPT_TYPE:
338             self_test_corrupt_type = opt_arg();
339             break;
340         case OPT_PROV_NAME:
341             prov_name = opt_arg();
342             break;
343         case OPT_MODULE:
344             module_fname = opt_arg();
345             break;
346         case OPT_SECTION_NAME:
347             section_name = opt_arg();
348             break;
349         case OPT_MAC_NAME:
350             mac_name = opt_arg();
351             break;
352         case OPT_CONFIG:
353             parent_config = opt_arg();
354             break;
355         case OPT_MACOPT:
356             if (!sk_OPENSSL_STRING_push(opts, opt_arg()))
357                 goto opthelp;
358             if (strncmp(opt_arg(), "hexkey:", 7) == 0)
359                 gotkey = 1;
360             else if (strncmp(opt_arg(), "digest:", 7) == 0)
361                 gotdigest = 1;
362             break;
363         case OPT_VERIFY:
364             verify = 1;
365             break;
366         }
367     }
368     argc = opt_num_rest();
369
370     if (parent_config != NULL) {
371         /* Test that a parent config can load the module */
372         if (verify_module_load(parent_config)) {
373             ret = OSSL_PROVIDER_available(NULL, prov_name) ? 0 : 1;
374             if (!quiet)
375                 BIO_printf(bio_out, "FIPS provider is %s\n",
376                            ret == 0 ? "available" : " not available");
377         }
378         goto end;
379     }
380     if (module_fname == NULL
381         || (verify && in_fname == NULL)
382         || (!verify && out_fname == NULL)
383         || argc != 0)
384         goto opthelp;
385
386     tail = opt_path_end(module_fname);
387     if (tail != NULL) {
388         module_path = OPENSSL_strdup(module_fname);
389         if (module_path == NULL)
390             goto end;
391         module_path[tail - module_fname] = '\0';
392         if (!OSSL_PROVIDER_set_default_search_path(NULL, module_path))
393             goto end;
394     }
395
396     if (self_test_log
397             || self_test_corrupt_desc != NULL
398             || self_test_corrupt_type != NULL)
399         OSSL_SELF_TEST_set_callback(NULL, self_test_events, NULL);
400
401     /* Use the default FIPS HMAC digest and key if not specified. */
402     if (!gotdigest && !sk_OPENSSL_STRING_push(opts, "digest:SHA256"))
403         goto end;
404     if (!gotkey && !sk_OPENSSL_STRING_push(opts, "hexkey:" FIPS_KEY_STRING))
405         goto end;
406
407     module_bio = bio_open_default(module_fname, 'r', FORMAT_BINARY);
408     if (module_bio == NULL) {
409         BIO_printf(bio_err, "Failed to open module file\n");
410         goto end;
411     }
412
413     read_buffer = app_malloc(BUFSIZE, "I/O buffer");
414     if (read_buffer == NULL)
415         goto end;
416
417     mac = EVP_MAC_fetch(NULL, mac_name, NULL);
418     if (mac == NULL) {
419         BIO_printf(bio_err, "Unable to get MAC of type %s\n", mac_name);
420         goto end;
421     }
422
423     ctx = EVP_MAC_CTX_new(mac);
424     if (ctx == NULL) {
425         BIO_printf(bio_err, "Unable to create MAC CTX for module check\n");
426         goto end;
427     }
428
429     if (opts != NULL) {
430         int ok = 1;
431         OSSL_PARAM *params =
432             app_params_new_from_opts(opts, EVP_MAC_settable_ctx_params(mac));
433
434         if (params == NULL)
435             goto end;
436
437         if (!EVP_MAC_CTX_set_params(ctx, params)) {
438             BIO_printf(bio_err, "MAC parameter error\n");
439             ERR_print_errors(bio_err);
440             ok = 0;
441         }
442         app_params_free(params);
443         if (!ok)
444             goto end;
445     }
446
447     ctx2 = EVP_MAC_CTX_dup(ctx);
448     if (ctx2 == NULL) {
449         BIO_printf(bio_err, "Unable to create MAC CTX for install indicator\n");
450         goto end;
451     }
452
453     if (!do_mac(ctx, read_buffer, module_bio, module_mac, &module_mac_len))
454         goto end;
455
456     mem_bio = BIO_new_mem_buf((const void *)INSTALL_STATUS_VAL,
457                               strlen(INSTALL_STATUS_VAL));
458     if (mem_bio == NULL) {
459         BIO_printf(bio_err, "Unable to create memory BIO\n");
460         goto end;
461     }
462     if (!do_mac(ctx2, read_buffer, mem_bio, install_mac, &install_mac_len))
463         goto end;
464
465     if (verify) {
466         if (!verify_config(in_fname, section_name, module_mac, module_mac_len,
467                            install_mac, install_mac_len))
468             goto end;
469         if (!quiet)
470             BIO_printf(bio_out, "VERIFY PASSED\n");
471     } else {
472
473         conf = generate_config_and_load(prov_name, section_name, module_mac,
474                                         module_mac_len,
475                                         enable_conditional_errors);
476         if (conf == NULL)
477             goto end;
478         if (!load_fips_prov_and_run_self_test(prov_name))
479             goto end;
480
481         fout = bio_open_default(out_fname, 'w', FORMAT_TEXT);
482         if (fout == NULL) {
483             BIO_printf(bio_err, "Failed to open file\n");
484             goto end;
485         }
486         if (!write_config_fips_section(fout, section_name,
487                                        module_mac, module_mac_len,
488                                        enable_conditional_errors,
489                                        install_mac, install_mac_len))
490             goto end;
491         if (!quiet)
492             BIO_printf(bio_out, "INSTALL PASSED\n");
493     }
494
495     ret = 0;
496 end:
497     if (ret == 1) {
498         if (!quiet)
499             BIO_printf(bio_err, "%s FAILED\n", verify ? "VERIFY" : "INSTALL");
500         ERR_print_errors(bio_err);
501     }
502
503 cleanup:
504     OPENSSL_free(module_path);
505     BIO_free(fout);
506     BIO_free(mem_bio);
507     BIO_free(module_bio);
508     sk_OPENSSL_STRING_free(opts);
509     EVP_MAC_free(mac);
510     EVP_MAC_CTX_free(ctx2);
511     EVP_MAC_CTX_free(ctx);
512     OPENSSL_free(read_buffer);
513     free_config_and_unload(conf);
514     return ret;
515 }
516
517 static int self_test_events(const OSSL_PARAM params[], void *arg)
518 {
519     const OSSL_PARAM *p = NULL;
520     const char *phase = NULL, *type = NULL, *desc = NULL;
521     int ret = 0;
522
523     p = OSSL_PARAM_locate_const(params, OSSL_PROV_PARAM_SELF_TEST_PHASE);
524     if (p == NULL || p->data_type != OSSL_PARAM_UTF8_STRING)
525         goto err;
526     phase = (const char *)p->data;
527
528     p = OSSL_PARAM_locate_const(params, OSSL_PROV_PARAM_SELF_TEST_DESC);
529     if (p == NULL || p->data_type != OSSL_PARAM_UTF8_STRING)
530         goto err;
531     desc = (const char *)p->data;
532
533     p = OSSL_PARAM_locate_const(params, OSSL_PROV_PARAM_SELF_TEST_TYPE);
534     if (p == NULL || p->data_type != OSSL_PARAM_UTF8_STRING)
535         goto err;
536     type = (const char *)p->data;
537
538     if (self_test_log) {
539         if (strcmp(phase, OSSL_SELF_TEST_PHASE_START) == 0)
540             BIO_printf(bio_out, "%s : (%s) : ", desc, type);
541         else if (strcmp(phase, OSSL_SELF_TEST_PHASE_PASS) == 0
542                  || strcmp(phase, OSSL_SELF_TEST_PHASE_FAIL) == 0)
543             BIO_printf(bio_out, "%s\n", phase);
544     }
545     /*
546      * The self test code will internally corrupt the KAT test result if an
547      * error is returned during the corrupt phase.
548      */
549     if (strcmp(phase, OSSL_SELF_TEST_PHASE_CORRUPT) == 0
550             && (self_test_corrupt_desc != NULL
551                 || self_test_corrupt_type != NULL)) {
552         if (self_test_corrupt_desc != NULL
553                 && strcmp(self_test_corrupt_desc, desc) != 0)
554             goto end;
555         if (self_test_corrupt_type != NULL
556                 && strcmp(self_test_corrupt_type, type) != 0)
557             goto end;
558         BIO_printf(bio_out, "%s ", phase);
559         goto err;
560     }
561 end:
562     ret = 1;
563 err:
564     return ret;
565 }