8902510b44cf856a3093326e167b5595dbb7a959
[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 /*
19  * We're cheating here. Normally we don't allow RUN_ONCE usage inside the FIPS
20  * module because all such initialisation should be associated with an
21  * individual OPENSSL_CTX. That doesn't work with the self test though because
22  * it should be run once regardless of the number of OPENSSL_CTXs we have.
23  */
24 #define ALLOW_RUN_ONCE_IN_FIPS
25 #include <internal/thread_once.h>
26 #include "self_test.h"
27
28 #define FIPS_STATE_INIT     0
29 #define FIPS_STATE_SELFTEST 1
30 #define FIPS_STATE_RUNNING  2
31 #define FIPS_STATE_ERROR    3
32
33 /* The size of a temp buffer used to read in data */
34 #define INTEGRITY_BUF_SIZE (4096)
35 #define MAX_MD_SIZE 64
36 #define MAC_NAME    "HMAC"
37 #define DIGEST_NAME "SHA256"
38
39 static int FIPS_state = FIPS_STATE_INIT;
40 static CRYPTO_RWLOCK *self_test_lock = NULL;
41 static unsigned char fixed_key[32] = { FIPS_KEY_ELEMENTS };
42
43 static CRYPTO_ONCE fips_self_test_init = CRYPTO_ONCE_STATIC_INIT;
44 DEFINE_RUN_ONCE_STATIC(do_fips_self_test_init)
45 {
46     /*
47      * This lock gets freed in platform specific ways that may occur after we
48      * do mem leak checking. If we don't know how to free it for a particular
49      * platform then we just leak it deliberately. So we temporarily disable the
50      * mem leak checking while we allocate this.
51      */
52     self_test_lock = CRYPTO_THREAD_lock_new();
53     return self_test_lock != NULL;
54 }
55
56 #define DEP_DECLARE()                                                          \
57 void init(void);                                                               \
58 void cleanup(void);
59
60 /*
61  * This is the Default Entry Point (DEP) code. Every platform must have a DEP.
62  * See FIPS 140-2 IG 9.10
63  *
64  * If we're run on a platform where we don't know how to define the DEP then
65  * the self-tests will never get triggered (FIPS_state never moves to
66  * FIPS_STATE_SELFTEST). This will be detected as an error when SELF_TEST_post()
67  * is called from OSSL_provider_init(), and so the fips module will be unusable
68  * on those platforms.
69  */
70 #if defined(_WIN32) || defined(__CYGWIN__)
71 # ifdef __CYGWIN__
72 /* pick DLL_[PROCESS|THREAD]_[ATTACH|DETACH] definitions */
73 #  include <windows.h>
74 /*
75  * this has side-effect of _WIN32 getting defined, which otherwise is
76  * mutually exclusive with __CYGWIN__...
77  */
78 # endif
79
80 DEP_DECLARE()
81 # define DEP_INIT_ATTRIBUTE
82 # define DEP_FINI_ATTRIBUTE
83 BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved);
84 BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
85 {
86     switch (fdwReason) {
87     case DLL_PROCESS_ATTACH:
88         init();
89         break;
90     case DLL_PROCESS_DETACH:
91         cleanup();
92         break;
93     default:
94         break;
95     }
96     return TRUE;
97 }
98 #elif defined(__sun) || defined(_AIX)
99
100 DEP_DECLARE() /* must be declared before pragma */
101 # define DEP_INIT_ATTRIBUTE
102 # define DEP_FINI_ATTRIBUTE
103 # pragma init(init)
104 # pragma fini(cleanup)
105
106 #elif defined(__hpux)
107
108 DEP_DECLARE()
109 # define DEP_INIT_ATTRIBUTE
110 # define DEP_FINI_ATTRIBUTE
111 # pragma init "init"
112 # pragma fini "cleanup"
113
114 #elif defined(__GNUC__)
115 # define DEP_INIT_ATTRIBUTE static __attribute__((constructor))
116 # define DEP_FINI_ATTRIBUTE static __attribute__((destructor))
117 #endif
118
119 #if defined(DEP_INIT_ATTRIBUTE) && defined(DEP_FINI_ATTRIBUTE)
120 DEP_INIT_ATTRIBUTE void init(void)
121 {
122     FIPS_state = FIPS_STATE_SELFTEST;
123 }
124
125 DEP_FINI_ATTRIBUTE void cleanup(void)
126 {
127     CRYPTO_THREAD_lock_free(self_test_lock);
128 }
129 #endif
130
131 /*
132  * Calculate the HMAC SHA256 of data read using a BIO and read_cb, and verify
133  * the result matches the expected value.
134  * Return 1 if verified, or 0 if it fails.
135  */
136 static int verify_integrity(OSSL_CORE_BIO *bio, OSSL_FUNC_BIO_read_ex_fn read_ex_cb,
137                             unsigned char *expected, size_t expected_len,
138                             OPENSSL_CTX *libctx, OSSL_SELF_TEST *ev,
139                             const char *event_type)
140 {
141     int ret = 0, status;
142     unsigned char out[MAX_MD_SIZE];
143     unsigned char buf[INTEGRITY_BUF_SIZE];
144     size_t bytes_read = 0, out_len = 0;
145     EVP_MAC *mac = NULL;
146     EVP_MAC_CTX *ctx = NULL;
147     OSSL_PARAM params[3], *p = params;
148
149     OSSL_SELF_TEST_onbegin(ev, event_type, OSSL_SELF_TEST_DESC_INTEGRITY_HMAC);
150
151     mac = EVP_MAC_fetch(libctx, MAC_NAME, NULL);
152     ctx = EVP_MAC_CTX_new(mac);
153     if (mac == NULL || ctx == NULL)
154         goto err;
155
156     *p++ = OSSL_PARAM_construct_utf8_string("digest", DIGEST_NAME,
157                                             strlen(DIGEST_NAME) + 1);
158     *p++ = OSSL_PARAM_construct_octet_string("key", fixed_key,
159                                              sizeof(fixed_key));
160     *p = OSSL_PARAM_construct_end();
161
162     if (EVP_MAC_CTX_set_params(ctx, params) <= 0
163         || !EVP_MAC_init(ctx))
164         goto err;
165
166     while (1) {
167         status = read_ex_cb(bio, buf, sizeof(buf), &bytes_read);
168         if (status != 1)
169             break;
170         if (!EVP_MAC_update(ctx, buf, bytes_read))
171             goto err;
172     }
173     if (!EVP_MAC_final(ctx, out, &out_len, sizeof(out)))
174         goto err;
175
176     OSSL_SELF_TEST_oncorrupt_byte(ev, out);
177     if (expected_len != out_len
178             || memcmp(expected, out, out_len) != 0)
179         goto err;
180     ret = 1;
181 err:
182     OSSL_SELF_TEST_onend(ev, ret);
183     EVP_MAC_CTX_free(ctx);
184     EVP_MAC_free(mac);
185     return ret;
186 }
187
188 /* This API is triggered either on loading of the FIPS module or on demand */
189 int SELF_TEST_post(SELF_TEST_POST_PARAMS *st, int on_demand_test)
190 {
191     int ok = 0;
192     int kats_already_passed = 0;
193     long checksum_len;
194     OSSL_CORE_BIO *bio_module = NULL, *bio_indicator = NULL;
195     unsigned char *module_checksum = NULL;
196     unsigned char *indicator_checksum = NULL;
197     int loclstate;
198     OSSL_SELF_TEST *ev = NULL;
199
200     if (!RUN_ONCE(&fips_self_test_init, do_fips_self_test_init))
201         return 0;
202
203     CRYPTO_THREAD_read_lock(self_test_lock);
204     loclstate = FIPS_state;
205     CRYPTO_THREAD_unlock(self_test_lock);
206
207     if (loclstate == FIPS_STATE_RUNNING) {
208         if (!on_demand_test)
209             return 1;
210     } else if (loclstate != FIPS_STATE_SELFTEST) {
211         ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_STATE);
212         return 0;
213     }
214
215     CRYPTO_THREAD_write_lock(self_test_lock);
216     if (FIPS_state == FIPS_STATE_RUNNING) {
217         if (!on_demand_test) {
218             CRYPTO_THREAD_unlock(self_test_lock);
219             return 1;
220         }
221         FIPS_state = FIPS_STATE_SELFTEST;
222     } else if (FIPS_state != FIPS_STATE_SELFTEST) {
223         CRYPTO_THREAD_unlock(self_test_lock);
224         ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_STATE);
225         return 0;
226     }
227     if (st == NULL
228             || st->module_checksum_data == NULL) {
229         ERR_raise(ERR_LIB_PROV, PROV_R_MISSING_CONFIG_DATA);
230         goto end;
231     }
232
233     ev = OSSL_SELF_TEST_new(st->cb, st->cb_arg);
234     if (ev == NULL)
235         goto end;
236
237     module_checksum = OPENSSL_hexstr2buf(st->module_checksum_data,
238                                          &checksum_len);
239     if (module_checksum == NULL) {
240         ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_CONFIG_DATA);
241         goto end;
242     }
243     bio_module = (*st->bio_new_file_cb)(st->module_filename, "rb");
244
245     /* Always check the integrity of the fips module */
246     if (bio_module == NULL
247             || !verify_integrity(bio_module, st->bio_read_ex_cb,
248                                  module_checksum, checksum_len, st->libctx,
249                                  ev, OSSL_SELF_TEST_TYPE_MODULE_INTEGRITY)) {
250         ERR_raise(ERR_LIB_PROV, PROV_R_MODULE_INTEGRITY_FAILURE);
251         goto end;
252     }
253
254     /* This will be NULL during installation - so the self test KATS will run */
255     if (st->indicator_data != NULL) {
256         /*
257          * If the kats have already passed indicator is set - then check the
258          * integrity of the indicator.
259          */
260         if (st->indicator_checksum_data == NULL) {
261             ERR_raise(ERR_LIB_PROV, PROV_R_MISSING_CONFIG_DATA);
262             goto end;
263         }
264         indicator_checksum = OPENSSL_hexstr2buf(st->indicator_checksum_data,
265                                                 &checksum_len);
266         if (indicator_checksum == NULL) {
267             ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_CONFIG_DATA);
268             goto end;
269         }
270
271         bio_indicator =
272             (*st->bio_new_buffer_cb)(st->indicator_data,
273                                      strlen(st->indicator_data));
274         if (bio_indicator == NULL
275                 || !verify_integrity(bio_indicator, st->bio_read_ex_cb,
276                                      indicator_checksum, checksum_len,
277                                      st->libctx, ev,
278                                      OSSL_SELF_TEST_TYPE_INSTALL_INTEGRITY)) {
279             ERR_raise(ERR_LIB_PROV, PROV_R_INDICATOR_INTEGRITY_FAILURE);
280             goto end;
281         } else {
282             kats_already_passed = 1;
283         }
284     }
285
286     /* Only runs the KAT's during installation OR on_demand() */
287     if (on_demand_test || kats_already_passed == 0) {
288         if (!SELF_TEST_kats(ev, st->libctx)) {
289             ERR_raise(ERR_LIB_PROV, PROV_R_SELF_TEST_KAT_FAILURE);
290             goto end;
291         }
292     }
293     ok = 1;
294 end:
295     OSSL_SELF_TEST_free(ev);
296     OPENSSL_free(module_checksum);
297     OPENSSL_free(indicator_checksum);
298
299     if (st != NULL) {
300         (*st->bio_free_cb)(bio_indicator);
301         (*st->bio_free_cb)(bio_module);
302     }
303     FIPS_state = ok ? FIPS_STATE_RUNNING : FIPS_STATE_ERROR;
304     CRYPTO_THREAD_unlock(self_test_lock);
305
306     return ok;
307 }