Add Docs for EVP_CIPHER-*
[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) || defined(_AIX)
109 # pragma init(init)
110 # pragma fini(cleanup)
111
112 #elif defined(__hpux)
113 # pragma init "init"
114 # pragma fini "cleanup"
115
116 #elif defined(__GNUC__)
117 # undef DEP_INIT_ATTRIBUTE
118 # undef DEP_FINI_ATTRIBUTE
119 # define DEP_INIT_ATTRIBUTE static __attribute__((constructor))
120 # define DEP_FINI_ATTRIBUTE static __attribute__((destructor))
121
122 #elif defined(__TANDEM)
123 /* Method automatically called by the NonStop OS when the DLL loads */
124 void __INIT__init(void) {
125     init();
126 }
127
128 /* Method automatically called by the NonStop OS prior to unloading the DLL */
129 void __TERM__cleanup(void) {
130     cleanup();
131 }
132
133 #else
134 /*
135  * This build does not support any kind of DEP.
136  * We force the self-tests to run as part of the FIPS provider initialisation
137  * rather than being triggered by the DEP.
138  */
139 # undef DEP_INIT_ATTRIBUTE
140 # undef DEP_FINI_ATTRIBUTE
141 # undef DEP_INITIAL_STATE
142 # define DEP_INITIAL_STATE  FIPS_STATE_SELFTEST
143 #endif
144
145 static int FIPS_state = DEP_INITIAL_STATE;
146
147 #if defined(DEP_INIT_ATTRIBUTE)
148 DEP_INIT_ATTRIBUTE void init(void)
149 {
150     FIPS_state = FIPS_STATE_SELFTEST;
151 }
152 #endif
153
154 #if defined(DEP_FINI_ATTRIBUTE)
155 DEP_FINI_ATTRIBUTE void cleanup(void)
156 {
157     CRYPTO_THREAD_lock_free(self_test_lock);
158     CRYPTO_THREAD_lock_free(fips_state_lock);
159 }
160 #endif
161
162 /*
163  * Calculate the HMAC SHA256 of data read using a BIO and read_cb, and verify
164  * the result matches the expected value.
165  * Return 1 if verified, or 0 if it fails.
166  */
167 static int verify_integrity(OSSL_CORE_BIO *bio, OSSL_FUNC_BIO_read_ex_fn read_ex_cb,
168                             unsigned char *expected, size_t expected_len,
169                             OSSL_LIB_CTX *libctx, OSSL_SELF_TEST *ev,
170                             const char *event_type)
171 {
172     int ret = 0, status;
173     unsigned char out[MAX_MD_SIZE];
174     unsigned char buf[INTEGRITY_BUF_SIZE];
175     size_t bytes_read = 0, out_len = 0;
176     EVP_MAC *mac = NULL;
177     EVP_MAC_CTX *ctx = NULL;
178     OSSL_PARAM params[2], *p = params;
179
180     OSSL_SELF_TEST_onbegin(ev, event_type, OSSL_SELF_TEST_DESC_INTEGRITY_HMAC);
181
182     mac = EVP_MAC_fetch(libctx, MAC_NAME, NULL);
183     if (mac == NULL)
184         goto err;
185     ctx = EVP_MAC_CTX_new(mac);
186     if (ctx == NULL)
187         goto err;
188
189     *p++ = OSSL_PARAM_construct_utf8_string("digest", DIGEST_NAME, 0);
190     *p = OSSL_PARAM_construct_end();
191
192     if (!EVP_MAC_init(ctx, fixed_key, sizeof(fixed_key), params))
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     if (ossl_assert(CRYPTO_THREAD_write_lock(fips_state_lock) != 0)) {
220         FIPS_state = state;
221         CRYPTO_THREAD_unlock(fips_state_lock);
222     }
223 }
224
225 /* This API is triggered either on loading of the FIPS module or on demand */
226 int SELF_TEST_post(SELF_TEST_POST_PARAMS *st, int on_demand_test)
227 {
228     int ok = 0;
229     int kats_already_passed = 0;
230     long checksum_len;
231     OSSL_CORE_BIO *bio_module = NULL, *bio_indicator = NULL;
232     unsigned char *module_checksum = NULL;
233     unsigned char *indicator_checksum = NULL;
234     int loclstate;
235     OSSL_SELF_TEST *ev = NULL;
236
237     if (!RUN_ONCE(&fips_self_test_init, do_fips_self_test_init))
238         return 0;
239
240     if (!CRYPTO_THREAD_read_lock(fips_state_lock))
241         return 0;
242     loclstate = FIPS_state;
243     CRYPTO_THREAD_unlock(fips_state_lock);
244
245     if (loclstate == FIPS_STATE_RUNNING) {
246         if (!on_demand_test)
247             return 1;
248     } else if (loclstate != FIPS_STATE_SELFTEST) {
249         ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_STATE);
250         return 0;
251     }
252
253     if (!CRYPTO_THREAD_write_lock(self_test_lock))
254         return 0;
255     if (!CRYPTO_THREAD_read_lock(fips_state_lock)) {
256         CRYPTO_THREAD_unlock(self_test_lock);
257         return 0;
258     }
259     if (FIPS_state == FIPS_STATE_RUNNING) {
260         CRYPTO_THREAD_unlock(fips_state_lock);
261         if (!on_demand_test) {
262             CRYPTO_THREAD_unlock(self_test_lock);
263             return 1;
264         }
265         set_fips_state(FIPS_STATE_SELFTEST);
266     } else if (FIPS_state != FIPS_STATE_SELFTEST) {
267         CRYPTO_THREAD_unlock(fips_state_lock);
268         CRYPTO_THREAD_unlock(self_test_lock);
269         ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_STATE);
270         return 0;
271     } else {
272         CRYPTO_THREAD_unlock(fips_state_lock);
273     }
274
275     if (st == NULL
276             || st->module_checksum_data == NULL) {
277         ERR_raise(ERR_LIB_PROV, PROV_R_MISSING_CONFIG_DATA);
278         goto end;
279     }
280
281     ev = OSSL_SELF_TEST_new(st->cb, st->cb_arg);
282     if (ev == NULL)
283         goto end;
284
285     module_checksum = OPENSSL_hexstr2buf(st->module_checksum_data,
286                                          &checksum_len);
287     if (module_checksum == NULL) {
288         ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_CONFIG_DATA);
289         goto end;
290     }
291     bio_module = (*st->bio_new_file_cb)(st->module_filename, "rb");
292
293     /* Always check the integrity of the fips module */
294     if (bio_module == NULL
295             || !verify_integrity(bio_module, st->bio_read_ex_cb,
296                                  module_checksum, checksum_len, st->libctx,
297                                  ev, OSSL_SELF_TEST_TYPE_MODULE_INTEGRITY)) {
298         ERR_raise(ERR_LIB_PROV, PROV_R_MODULE_INTEGRITY_FAILURE);
299         goto end;
300     }
301
302     /* This will be NULL during installation - so the self test KATS will run */
303     if (st->indicator_data != NULL) {
304         /*
305          * If the kats have already passed indicator is set - then check the
306          * integrity of the indicator.
307          */
308         if (st->indicator_checksum_data == NULL) {
309             ERR_raise(ERR_LIB_PROV, PROV_R_MISSING_CONFIG_DATA);
310             goto end;
311         }
312         indicator_checksum = OPENSSL_hexstr2buf(st->indicator_checksum_data,
313                                                 &checksum_len);
314         if (indicator_checksum == NULL) {
315             ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_CONFIG_DATA);
316             goto end;
317         }
318
319         bio_indicator =
320             (*st->bio_new_buffer_cb)(st->indicator_data,
321                                      strlen(st->indicator_data));
322         if (bio_indicator == NULL
323                 || !verify_integrity(bio_indicator, st->bio_read_ex_cb,
324                                      indicator_checksum, checksum_len,
325                                      st->libctx, ev,
326                                      OSSL_SELF_TEST_TYPE_INSTALL_INTEGRITY)) {
327             ERR_raise(ERR_LIB_PROV, PROV_R_INDICATOR_INTEGRITY_FAILURE);
328             goto end;
329         } else {
330             kats_already_passed = 1;
331         }
332     }
333
334     /*
335      * Only runs the KAT's during installation OR on_demand().
336      * NOTE: If the installation option 'self_test_onload' is chosen then this
337      * path will always be run, since kats_already_passed will always be 0.
338      */
339     if (on_demand_test || kats_already_passed == 0) {
340         if (!SELF_TEST_kats(ev, st->libctx)) {
341             ERR_raise(ERR_LIB_PROV, PROV_R_SELF_TEST_KAT_FAILURE);
342             goto end;
343         }
344     }
345     ok = 1;
346 end:
347     OSSL_SELF_TEST_free(ev);
348     OPENSSL_free(module_checksum);
349     OPENSSL_free(indicator_checksum);
350
351     if (st != NULL) {
352         (*st->bio_free_cb)(bio_indicator);
353         (*st->bio_free_cb)(bio_module);
354     }
355     if (ok)
356         set_fips_state(FIPS_STATE_RUNNING);
357     else
358         ossl_set_error_state(OSSL_SELF_TEST_TYPE_NONE);
359     CRYPTO_THREAD_unlock(self_test_lock);
360
361     return ok;
362 }
363
364 void SELF_TEST_disable_conditional_error_state(void)
365 {
366     FIPS_conditional_error_check = 0;
367 }
368
369 void ossl_set_error_state(const char *type)
370 {
371     int cond_test = (type != NULL && strcmp(type, OSSL_SELF_TEST_TYPE_PCT) == 0);
372
373     if (!cond_test || (FIPS_conditional_error_check == 1)) {
374         set_fips_state(FIPS_STATE_ERROR);
375         ERR_raise(ERR_LIB_PROV, PROV_R_FIPS_MODULE_ENTERING_ERROR_STATE);
376     } else {
377         ERR_raise(ERR_LIB_PROV, PROV_R_FIPS_MODULE_CONDITIONAL_ERROR);
378     }
379 }
380
381 int ossl_prov_is_running(void)
382 {
383     int res;
384     static unsigned int rate_limit = 0;
385
386     if (!CRYPTO_THREAD_read_lock(fips_state_lock))
387         return 0;
388     res = FIPS_state == FIPS_STATE_RUNNING
389                         || FIPS_state == FIPS_STATE_SELFTEST;
390     if (FIPS_state == FIPS_STATE_ERROR) {
391         CRYPTO_THREAD_unlock(fips_state_lock);
392         if (!CRYPTO_THREAD_write_lock(fips_state_lock))
393             return 0;
394         if (rate_limit++ < FIPS_ERROR_REPORTING_RATE_LIMIT)
395             ERR_raise(ERR_LIB_PROV, PROV_R_FIPS_MODULE_IN_ERROR_STATE);
396     }
397     CRYPTO_THREAD_unlock(fips_state_lock);
398     return res;
399 }