e6813e292da8dd8529464714dcca3b9848bdb28c
[openssl.git] / providers / fips / self_test.c
1 /*
2  * Copyright 2019-2021 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/params.h>
13 #include <openssl/crypto.h>
14 #include "internal/cryptlib.h"
15 #include <openssl/fipskey.h>
16 #include <openssl/err.h>
17 #include <openssl/proverr.h>
18 #include "e_os.h"
19 #include "prov/providercommon.h"
20
21 /*
22  * We're cheating here. Normally we don't allow RUN_ONCE usage inside the FIPS
23  * module because all such initialisation should be associated with an
24  * individual OSSL_LIB_CTX. That doesn't work with the self test though because
25  * it should be run once regardless of the number of OSSL_LIB_CTXs we have.
26  */
27 #define ALLOW_RUN_ONCE_IN_FIPS
28 #include "internal/thread_once.h"
29 #include "self_test.h"
30
31 #define FIPS_STATE_INIT     0
32 #define FIPS_STATE_SELFTEST 1
33 #define FIPS_STATE_RUNNING  2
34 #define FIPS_STATE_ERROR    3
35
36 /*
37  * The number of times the module will report it is in the error state
38  * before going quiet.
39  */
40 #define FIPS_ERROR_REPORTING_RATE_LIMIT     10
41
42 /* The size of a temp buffer used to read in data */
43 #define INTEGRITY_BUF_SIZE (4096)
44 #define MAX_MD_SIZE 64
45 #define MAC_NAME    "HMAC"
46 #define DIGEST_NAME "SHA256"
47
48 static int FIPS_conditional_error_check = 1;
49 static CRYPTO_RWLOCK *self_test_lock = NULL;
50 static CRYPTO_RWLOCK *fips_state_lock = NULL;
51 static unsigned char fixed_key[32] = { FIPS_KEY_ELEMENTS };
52
53 static CRYPTO_ONCE fips_self_test_init = CRYPTO_ONCE_STATIC_INIT;
54 DEFINE_RUN_ONCE_STATIC(do_fips_self_test_init)
55 {
56     /*
57      * These locks get freed in platform specific ways that may occur after we
58      * do mem leak checking. If we don't know how to free it for a particular
59      * platform then we just leak it deliberately.
60      */
61     self_test_lock = CRYPTO_THREAD_lock_new();
62     fips_state_lock = CRYPTO_THREAD_lock_new();
63     return self_test_lock != NULL;
64 }
65
66 /*
67  * Declarations for the DEP entry/exit points.
68  * Ones not required or incorrect need to be undefined or redefined respectively.
69  */
70 #define DEP_INITIAL_STATE   FIPS_STATE_INIT
71 #define DEP_INIT_ATTRIBUTE  static
72 #define DEP_FINI_ATTRIBUTE  static
73
74 #if !defined(__GNUC__)
75 static void init(void);
76 static void cleanup(void);
77 #endif
78
79 /*
80  * This is the Default Entry Point (DEP) code.
81  * See FIPS 140-2 IG 9.10
82  */
83 #if defined(_WIN32) || defined(__CYGWIN__)
84 # ifdef __CYGWIN__
85 /* pick DLL_[PROCESS|THREAD]_[ATTACH|DETACH] definitions */
86 #  include <windows.h>
87 /*
88  * this has side-effect of _WIN32 getting defined, which otherwise is
89  * mutually exclusive with __CYGWIN__...
90  */
91 # endif
92
93 BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved);
94 BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
95 {
96     switch (fdwReason) {
97     case DLL_PROCESS_ATTACH:
98         init();
99         break;
100     case DLL_PROCESS_DETACH:
101         cleanup();
102         break;
103     default:
104         break;
105     }
106     return TRUE;
107 }
108 #elif defined(__sun)
109 # pragma init(init)
110 # pragma fini(cleanup)
111
112 #elif defined(_AIX)
113 void _init(void);
114 void _cleanup(void);
115 # pragma init(_init)
116 # pragma fini(_cleanup)
117 void _init(void)
118 {
119     init();
120 }
121 void _cleanup(void)
122 {
123     cleanup();
124 }
125
126 #elif defined(__hpux)
127 # pragma init "init"
128 # pragma fini "cleanup"
129
130 #elif defined(__GNUC__)
131 # undef DEP_INIT_ATTRIBUTE
132 # undef DEP_FINI_ATTRIBUTE
133 # define DEP_INIT_ATTRIBUTE static __attribute__((constructor))
134 # define DEP_FINI_ATTRIBUTE static __attribute__((destructor))
135
136 #elif defined(__TANDEM)
137 /* Method automatically called by the NonStop OS when the DLL loads */
138 void __INIT__init(void) {
139     init();
140 }
141
142 /* Method automatically called by the NonStop OS prior to unloading the DLL */
143 void __TERM__cleanup(void) {
144     cleanup();
145 }
146
147 #else
148 /*
149  * This build does not support any kind of DEP.
150  * We force the self-tests to run as part of the FIPS provider initialisation
151  * rather than being triggered by the DEP.
152  */
153 # undef DEP_INIT_ATTRIBUTE
154 # undef DEP_FINI_ATTRIBUTE
155 # undef DEP_INITIAL_STATE
156 # define DEP_INITIAL_STATE  FIPS_STATE_SELFTEST
157 #endif
158
159 static int FIPS_state = DEP_INITIAL_STATE;
160
161 #if defined(DEP_INIT_ATTRIBUTE)
162 DEP_INIT_ATTRIBUTE void init(void)
163 {
164     FIPS_state = FIPS_STATE_SELFTEST;
165 }
166 #endif
167
168 #if defined(DEP_FINI_ATTRIBUTE)
169 DEP_FINI_ATTRIBUTE void cleanup(void)
170 {
171     CRYPTO_THREAD_lock_free(self_test_lock);
172     CRYPTO_THREAD_lock_free(fips_state_lock);
173 }
174 #endif
175
176 /*
177  * Calculate the HMAC SHA256 of data read using a BIO and read_cb, and verify
178  * the result matches the expected value.
179  * Return 1 if verified, or 0 if it fails.
180  */
181 static int verify_integrity(OSSL_CORE_BIO *bio, OSSL_FUNC_BIO_read_ex_fn read_ex_cb,
182                             unsigned char *expected, size_t expected_len,
183                             OSSL_LIB_CTX *libctx, OSSL_SELF_TEST *ev,
184                             const char *event_type)
185 {
186     int ret = 0, status;
187     unsigned char out[MAX_MD_SIZE];
188     unsigned char buf[INTEGRITY_BUF_SIZE];
189     size_t bytes_read = 0, out_len = 0;
190     EVP_MAC *mac = NULL;
191     EVP_MAC_CTX *ctx = NULL;
192     OSSL_PARAM params[2], *p = params;
193
194     OSSL_SELF_TEST_onbegin(ev, event_type, OSSL_SELF_TEST_DESC_INTEGRITY_HMAC);
195
196     mac = EVP_MAC_fetch(libctx, MAC_NAME, NULL);
197     if (mac == NULL)
198         goto err;
199     ctx = EVP_MAC_CTX_new(mac);
200     if (ctx == NULL)
201         goto err;
202
203     *p++ = OSSL_PARAM_construct_utf8_string("digest", DIGEST_NAME, 0);
204     *p = OSSL_PARAM_construct_end();
205
206     if (!EVP_MAC_init(ctx, fixed_key, sizeof(fixed_key), params))
207         goto err;
208
209     while (1) {
210         status = read_ex_cb(bio, buf, sizeof(buf), &bytes_read);
211         if (status != 1)
212             break;
213         if (!EVP_MAC_update(ctx, buf, bytes_read))
214             goto err;
215     }
216     if (!EVP_MAC_final(ctx, out, &out_len, sizeof(out)))
217         goto err;
218
219     OSSL_SELF_TEST_oncorrupt_byte(ev, out);
220     if (expected_len != out_len
221             || memcmp(expected, out, out_len) != 0)
222         goto err;
223     ret = 1;
224 err:
225     OSSL_SELF_TEST_onend(ev, ret);
226     EVP_MAC_CTX_free(ctx);
227     EVP_MAC_free(mac);
228     return ret;
229 }
230
231 static void set_fips_state(int state)
232 {
233     if (ossl_assert(CRYPTO_THREAD_write_lock(fips_state_lock) != 0)) {
234         FIPS_state = state;
235         CRYPTO_THREAD_unlock(fips_state_lock);
236     }
237 }
238
239 /* This API is triggered either on loading of the FIPS module or on demand */
240 int SELF_TEST_post(SELF_TEST_POST_PARAMS *st, int on_demand_test)
241 {
242     int ok = 0;
243     int kats_already_passed = 0;
244     long checksum_len;
245     OSSL_CORE_BIO *bio_module = NULL, *bio_indicator = NULL;
246     unsigned char *module_checksum = NULL;
247     unsigned char *indicator_checksum = NULL;
248     int loclstate;
249     OSSL_SELF_TEST *ev = NULL;
250
251     if (!RUN_ONCE(&fips_self_test_init, do_fips_self_test_init))
252         return 0;
253
254     if (!CRYPTO_THREAD_read_lock(fips_state_lock))
255         return 0;
256     loclstate = FIPS_state;
257     CRYPTO_THREAD_unlock(fips_state_lock);
258
259     if (loclstate == FIPS_STATE_RUNNING) {
260         if (!on_demand_test)
261             return 1;
262     } else if (loclstate != FIPS_STATE_SELFTEST) {
263         ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_STATE);
264         return 0;
265     }
266
267     if (!CRYPTO_THREAD_write_lock(self_test_lock))
268         return 0;
269     if (!CRYPTO_THREAD_read_lock(fips_state_lock)) {
270         CRYPTO_THREAD_unlock(self_test_lock);
271         return 0;
272     }
273     if (FIPS_state == FIPS_STATE_RUNNING) {
274         CRYPTO_THREAD_unlock(fips_state_lock);
275         if (!on_demand_test) {
276             CRYPTO_THREAD_unlock(self_test_lock);
277             return 1;
278         }
279         set_fips_state(FIPS_STATE_SELFTEST);
280     } else if (FIPS_state != FIPS_STATE_SELFTEST) {
281         CRYPTO_THREAD_unlock(fips_state_lock);
282         CRYPTO_THREAD_unlock(self_test_lock);
283         ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_STATE);
284         return 0;
285     } else {
286         CRYPTO_THREAD_unlock(fips_state_lock);
287     }
288
289     if (st == NULL
290             || st->module_checksum_data == NULL) {
291         ERR_raise(ERR_LIB_PROV, PROV_R_MISSING_CONFIG_DATA);
292         goto end;
293     }
294
295     ev = OSSL_SELF_TEST_new(st->cb, st->cb_arg);
296     if (ev == NULL)
297         goto end;
298
299     module_checksum = OPENSSL_hexstr2buf(st->module_checksum_data,
300                                          &checksum_len);
301     if (module_checksum == NULL) {
302         ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_CONFIG_DATA);
303         goto end;
304     }
305     bio_module = (*st->bio_new_file_cb)(st->module_filename, "rb");
306
307     /* Always check the integrity of the fips module */
308     if (bio_module == NULL
309             || !verify_integrity(bio_module, st->bio_read_ex_cb,
310                                  module_checksum, checksum_len, st->libctx,
311                                  ev, OSSL_SELF_TEST_TYPE_MODULE_INTEGRITY)) {
312         ERR_raise(ERR_LIB_PROV, PROV_R_MODULE_INTEGRITY_FAILURE);
313         goto end;
314     }
315
316     /* This will be NULL during installation - so the self test KATS will run */
317     if (st->indicator_data != NULL) {
318         /*
319          * If the kats have already passed indicator is set - then check the
320          * integrity of the indicator.
321          */
322         if (st->indicator_checksum_data == NULL) {
323             ERR_raise(ERR_LIB_PROV, PROV_R_MISSING_CONFIG_DATA);
324             goto end;
325         }
326         indicator_checksum = OPENSSL_hexstr2buf(st->indicator_checksum_data,
327                                                 &checksum_len);
328         if (indicator_checksum == NULL) {
329             ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_CONFIG_DATA);
330             goto end;
331         }
332
333         bio_indicator =
334             (*st->bio_new_buffer_cb)(st->indicator_data,
335                                      strlen(st->indicator_data));
336         if (bio_indicator == NULL
337                 || !verify_integrity(bio_indicator, st->bio_read_ex_cb,
338                                      indicator_checksum, checksum_len,
339                                      st->libctx, ev,
340                                      OSSL_SELF_TEST_TYPE_INSTALL_INTEGRITY)) {
341             ERR_raise(ERR_LIB_PROV, PROV_R_INDICATOR_INTEGRITY_FAILURE);
342             goto end;
343         } else {
344             kats_already_passed = 1;
345         }
346     }
347
348     /*
349      * Only runs the KAT's during installation OR on_demand().
350      * NOTE: If the installation option 'self_test_onload' is chosen then this
351      * path will always be run, since kats_already_passed will always be 0.
352      */
353     if (on_demand_test || kats_already_passed == 0) {
354         if (!SELF_TEST_kats(ev, st->libctx)) {
355             ERR_raise(ERR_LIB_PROV, PROV_R_SELF_TEST_KAT_FAILURE);
356             goto end;
357         }
358     }
359     ok = 1;
360 end:
361     OSSL_SELF_TEST_free(ev);
362     OPENSSL_free(module_checksum);
363     OPENSSL_free(indicator_checksum);
364
365     if (st != NULL) {
366         (*st->bio_free_cb)(bio_indicator);
367         (*st->bio_free_cb)(bio_module);
368     }
369     if (ok)
370         set_fips_state(FIPS_STATE_RUNNING);
371     else
372         ossl_set_error_state(OSSL_SELF_TEST_TYPE_NONE);
373     CRYPTO_THREAD_unlock(self_test_lock);
374
375     return ok;
376 }
377
378 void SELF_TEST_disable_conditional_error_state(void)
379 {
380     FIPS_conditional_error_check = 0;
381 }
382
383 void ossl_set_error_state(const char *type)
384 {
385     int cond_test = (type != NULL && strcmp(type, OSSL_SELF_TEST_TYPE_PCT) == 0);
386
387     if (!cond_test || (FIPS_conditional_error_check == 1)) {
388         set_fips_state(FIPS_STATE_ERROR);
389         ERR_raise(ERR_LIB_PROV, PROV_R_FIPS_MODULE_ENTERING_ERROR_STATE);
390     } else {
391         ERR_raise(ERR_LIB_PROV, PROV_R_FIPS_MODULE_CONDITIONAL_ERROR);
392     }
393 }
394
395 int ossl_prov_is_running(void)
396 {
397     int res;
398     static unsigned int rate_limit = 0;
399
400     if (!CRYPTO_THREAD_read_lock(fips_state_lock))
401         return 0;
402     res = FIPS_state == FIPS_STATE_RUNNING
403                         || FIPS_state == FIPS_STATE_SELFTEST;
404     if (FIPS_state == FIPS_STATE_ERROR) {
405         CRYPTO_THREAD_unlock(fips_state_lock);
406         if (!CRYPTO_THREAD_write_lock(fips_state_lock))
407             return 0;
408         if (rate_limit++ < FIPS_ERROR_REPORTING_RATE_LIMIT)
409             ERR_raise(ERR_LIB_PROV, PROV_R_FIPS_MODULE_IN_ERROR_STATE);
410     }
411     CRYPTO_THREAD_unlock(fips_state_lock);
412     return res;
413 }