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