Make sure we only run the self tests once
[oweals/openssl.git] / providers / fips / selftest.c
1 /*
2  * Copyright 2019 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the OpenSSL license (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 "e_os.h"
15 /*
16  * We're cheating here. Normally we don't allow RUN_ONCE usage inside the FIPS
17  * module because all such initialisation should be associated with an
18  * individual OPENSSL_CTX. That doesn't work with the self test though because
19  * it should be run once regardless of the number of OPENSSL_CTXs we have.
20  */
21 #define ALLOW_RUN_ONCE_IN_FIPS
22 #include <internal/thread_once.h>
23 #include "selftest.h"
24
25 #define FIPS_STATE_INIT     0
26 #define FIPS_STATE_SELFTEST 1
27 #define FIPS_STATE_RUNNING  2
28 #define FIPS_STATE_ERROR    3
29
30 /* The size of a temp buffer used to read in data */
31 #define INTEGRITY_BUF_SIZE (4096)
32 #define MAX_MD_SIZE 64
33 #define MAC_NAME    "HMAC"
34 #define DIGEST_NAME "SHA256"
35
36 static int FIPS_state = FIPS_STATE_INIT;
37 static CRYPTO_RWLOCK *self_test_lock = NULL;
38 static unsigned char fixed_key[32] = { 0 };
39
40 static CRYPTO_ONCE fips_self_test_init = CRYPTO_ONCE_STATIC_INIT;
41 DEFINE_RUN_ONCE_STATIC(do_fips_self_test_init)
42 {
43     self_test_lock = CRYPTO_THREAD_lock_new();
44
45     return self_test_lock != NULL;
46 }
47
48 /*
49  * This is the Default Entry Point (DEP) code. Every platform must have a DEP.
50  * See FIPS 140-2 IG 9.10
51  *
52  * If we're run on a platform where we don't know how to define the DEP then
53  * the self-tests will never get triggered (FIPS_state never moves to
54  * FIPS_STATE_SELFTEST). This will be detected as an error when SELF_TEST_post()
55  * is called from OSSL_provider_init(), and so the fips module will be unusable
56  * on those platforms.
57  */
58 #if defined(_WIN32) || defined(__CYGWIN__)
59 # ifdef __CYGWIN__
60 /* pick DLL_[PROCESS|THREAD]_[ATTACH|DETACH] definitions */
61 #  include <windows.h>
62 /*
63  * this has side-effect of _WIN32 getting defined, which otherwise is
64  * mutually exclusive with __CYGWIN__...
65  */
66 # endif
67
68 BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved);
69 BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
70 {
71     switch (fdwReason) {
72     case DLL_PROCESS_ATTACH:
73         FIPS_state = FIPS_STATE_SELFTEST;
74         break;
75     case DLL_PROCESS_DETACH:
76         CRYPTO_THREAD_lock_free(self_test_lock);
77         break;
78     default:
79         break;
80     }
81     return TRUE;
82 }
83 #elif defined(__GNUC__)
84
85 static __attribute__((constructor)) void init(void)
86 {
87     FIPS_state = FIPS_STATE_SELFTEST;
88 }
89
90
91 static __attribute__((destructor)) void cleanup(void)
92 {
93     CRYPTO_THREAD_lock_free(self_test_lock);
94 }
95
96 #endif
97
98 /*
99  * Calculate the HMAC SHA256 of data read using a BIO and read_cb, and verify
100  * the result matches the expected value.
101  * Return 1 if verified, or 0 if it fails.
102  */
103 static int verify_integrity(BIO *bio, OSSL_BIO_read_ex_fn read_ex_cb,
104                             unsigned char *expected, size_t expected_len,
105                             OPENSSL_CTX *libctx)
106 {
107     int ret = 0, status;
108     unsigned char out[MAX_MD_SIZE];
109     unsigned char buf[INTEGRITY_BUF_SIZE];
110     size_t bytes_read = 0, out_len = 0;
111     EVP_MAC *mac = NULL;
112     EVP_MAC_CTX *ctx = NULL;
113     OSSL_PARAM params[3], *p = params;
114
115     mac = EVP_MAC_fetch(libctx, MAC_NAME, NULL);
116     ctx = EVP_MAC_CTX_new(mac);
117     if (mac == NULL || ctx == NULL)
118         goto err;
119
120     *p++ = OSSL_PARAM_construct_utf8_string("digest", DIGEST_NAME,
121                                             strlen(DIGEST_NAME) + 1);
122     *p++ = OSSL_PARAM_construct_octet_string("key", fixed_key,
123                                              sizeof(fixed_key));
124     *p = OSSL_PARAM_construct_end();
125
126     if (EVP_MAC_CTX_set_params(ctx, params) <= 0
127         || !EVP_MAC_init(ctx))
128         goto err;
129
130     while (1) {
131         status = read_ex_cb(bio, buf, sizeof(buf), &bytes_read);
132         if (status != 1)
133             break;
134         if (!EVP_MAC_update(ctx, buf, bytes_read))
135             goto err;
136     }
137     if (!EVP_MAC_final(ctx, out, &out_len, sizeof(out)))
138         goto err;
139
140     if (expected_len != out_len
141             || memcmp(expected, out, out_len) != 0)
142         goto err;
143     ret = 1;
144 err:
145     EVP_MAC_CTX_free(ctx);
146     EVP_MAC_free(mac);
147     return ret;
148 }
149
150 /* This API is triggered either on loading of the FIPS module or on demand */
151 int SELF_TEST_post(SELF_TEST_POST_PARAMS *st, int on_demand_test)
152 {
153     int ok = 0;
154     int kats_already_passed = 0;
155     long checksum_len;
156     BIO *bio_module = NULL, *bio_indicator = NULL;
157     unsigned char *module_checksum = NULL;
158     unsigned char *indicator_checksum = NULL;
159     int loclstate;
160
161     if (!RUN_ONCE(&fips_self_test_init, do_fips_self_test_init))
162         return 0;
163
164     CRYPTO_THREAD_read_lock(self_test_lock);
165     loclstate = FIPS_state;
166     CRYPTO_THREAD_unlock(self_test_lock);
167
168     if (loclstate == FIPS_STATE_RUNNING) {
169         if (!on_demand_test)
170             return 1;
171     } else if (loclstate != FIPS_STATE_SELFTEST) {
172         return 0;
173     }
174
175     CRYPTO_THREAD_write_lock(self_test_lock);
176     if (FIPS_state == FIPS_STATE_RUNNING) {
177         if (!on_demand_test) {
178             CRYPTO_THREAD_unlock(self_test_lock);
179             return 1;
180         }
181         FIPS_state = FIPS_STATE_SELFTEST;
182     } else if (FIPS_state != FIPS_STATE_SELFTEST) {
183         CRYPTO_THREAD_unlock(self_test_lock);
184         return 0;
185     }
186     if (st == NULL
187             || st->module_checksum_data == NULL)
188         goto end;
189
190     module_checksum = OPENSSL_hexstr2buf(st->module_checksum_data,
191                                          &checksum_len);
192     if (module_checksum == NULL)
193         goto end;
194     bio_module = (*st->bio_new_file_cb)(st->module_filename, "rb");
195
196     /* Always check the integrity of the fips module */
197     if (bio_module == NULL
198             || !verify_integrity(bio_module, st->bio_read_ex_cb,
199                                  module_checksum, checksum_len, st->libctx))
200         goto end;
201
202     /* This will be NULL during installation - so the self test KATS will run */
203     if (st->indicator_data != NULL) {
204         /*
205          * If the kats have already passed indicator is set - then check the
206          * integrity of the indicator.
207          */
208         if (st->indicator_checksum_data == NULL)
209             goto end;
210         indicator_checksum = OPENSSL_hexstr2buf(st->indicator_checksum_data,
211                                                 &checksum_len);
212         if (indicator_checksum == NULL)
213             goto end;
214
215         bio_indicator =
216             (*st->bio_new_buffer_cb)(st->indicator_data,
217                                      strlen(st->indicator_data));
218         if (bio_indicator == NULL
219                 || !verify_integrity(bio_indicator, st->bio_read_ex_cb,
220                                      indicator_checksum, checksum_len,
221                                      st->libctx))
222             goto end;
223         else
224             kats_already_passed = 1;
225     }
226
227     /* Only runs the KAT's during installation OR on_demand() */
228     if (on_demand_test || kats_already_passed == 0) {
229         /*TODO (3.0) Add self test KATS */
230     }
231     ok = 1;
232 end:
233     OPENSSL_free(module_checksum);
234     OPENSSL_free(indicator_checksum);
235
236     if (st != NULL) {
237         (*st->bio_free_cb)(bio_indicator);
238         (*st->bio_free_cb)(bio_module);
239     }
240     FIPS_state = ok ? FIPS_STATE_RUNNING : FIPS_STATE_ERROR;
241     CRYPTO_THREAD_unlock(self_test_lock);
242
243     return ok;
244 }