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