bdf599aaada4188a9b8482b4cef1ea382e691dd1
[openssl.git] / providers / fips / self_test_kats.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/kdf.h>
13 #include <openssl/core_names.h>
14 #include <openssl/param_build.h>
15 #include <openssl/rand.h>
16 #include "internal/cryptlib.h"
17 #include "internal/nelem.h"
18 #include "self_test.h"
19 #include "self_test_data.inc"
20
21 static int set_kat_drbg(OSSL_LIB_CTX *ctx,
22                         const unsigned char *entropy, size_t entropy_len,
23                         const unsigned char *nonce, size_t nonce_len,
24                         const unsigned char *persstr, size_t persstr_len);
25 static int reset_original_drbg(OSSL_LIB_CTX *ctx);
26
27 static int self_test_digest(const ST_KAT_DIGEST *t, OSSL_SELF_TEST *st,
28                             OSSL_LIB_CTX *libctx)
29 {
30     int ok = 0;
31     unsigned char out[EVP_MAX_MD_SIZE];
32     unsigned int out_len = 0;
33     EVP_MD_CTX *ctx = EVP_MD_CTX_new();
34     EVP_MD *md = EVP_MD_fetch(libctx, t->algorithm, NULL);
35
36     OSSL_SELF_TEST_onbegin(st, OSSL_SELF_TEST_TYPE_KAT_DIGEST, t->desc);
37
38     if (ctx == NULL
39             || md == NULL
40             || !EVP_DigestInit_ex(ctx, md, NULL)
41             || !EVP_DigestUpdate(ctx, t->pt, t->pt_len)
42             || !EVP_DigestFinal(ctx, out, &out_len))
43         goto err;
44
45     /* Optional corruption */
46     OSSL_SELF_TEST_oncorrupt_byte(st, out);
47
48     if (out_len != t->expected_len
49             || memcmp(out, t->expected, out_len) != 0)
50         goto err;
51     ok = 1;
52 err:
53     EVP_MD_free(md);
54     EVP_MD_CTX_free(ctx);
55     OSSL_SELF_TEST_onend(st, ok);
56     return ok;
57 }
58
59 /*
60  * Helper function to setup a EVP_CipherInit
61  * Used to hide the complexity of Authenticated ciphers.
62  */
63 static int cipher_init(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher,
64                        const ST_KAT_CIPHER *t, int enc)
65 {
66     unsigned char *in_tag = NULL;
67     int pad = 0, tmp;
68
69     /* Flag required for Key wrapping */
70     EVP_CIPHER_CTX_set_flags(ctx, EVP_CIPHER_CTX_FLAG_WRAP_ALLOW);
71     if (t->tag == NULL) {
72         /* Use a normal cipher init */
73         return EVP_CipherInit_ex(ctx, cipher, NULL, t->key, t->iv, enc)
74                && EVP_CIPHER_CTX_set_padding(ctx, pad);
75     }
76
77     /* The authenticated cipher init */
78     if (!enc)
79         in_tag = (unsigned char *)t->tag;
80
81     return EVP_CipherInit_ex(ctx, cipher, NULL, NULL, NULL, enc)
82            && (EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_IVLEN, t->iv_len, NULL) > 0)
83            && (in_tag == NULL
84                || EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_TAG, t->tag_len,
85                                       in_tag) > 0)
86            && EVP_CipherInit_ex(ctx, NULL, NULL, t->key, t->iv, enc)
87            && EVP_CIPHER_CTX_set_padding(ctx, pad)
88            && EVP_CipherUpdate(ctx, NULL, &tmp, t->aad, t->aad_len);
89 }
90
91 /* Test a single KAT for encrypt/decrypt */
92 static int self_test_cipher(const ST_KAT_CIPHER *t, OSSL_SELF_TEST *st,
93                             OSSL_LIB_CTX *libctx)
94 {
95     int ret = 0, encrypt = 1, len = 0, ct_len = 0, pt_len = 0;
96     EVP_CIPHER_CTX *ctx = NULL;
97     EVP_CIPHER *cipher = NULL;
98     unsigned char ct_buf[256] = { 0 };
99     unsigned char pt_buf[256] = { 0 };
100
101     OSSL_SELF_TEST_onbegin(st, OSSL_SELF_TEST_TYPE_KAT_CIPHER, t->base.desc);
102
103     ctx = EVP_CIPHER_CTX_new();
104     if (ctx == NULL)
105         goto err;
106     cipher = EVP_CIPHER_fetch(libctx, t->base.algorithm, NULL);
107     if (cipher == NULL)
108         goto err;
109
110     /* Encrypt plain text message */
111     if ((t->mode & CIPHER_MODE_ENCRYPT) != 0) {
112         if (!cipher_init(ctx, cipher, t, encrypt)
113                 || !EVP_CipherUpdate(ctx, ct_buf, &len, t->base.pt,
114                                      t->base.pt_len)
115                 || !EVP_CipherFinal_ex(ctx, ct_buf + len, &ct_len))
116             goto err;
117
118         OSSL_SELF_TEST_oncorrupt_byte(st, ct_buf);
119         ct_len += len;
120         if (ct_len != (int)t->base.expected_len
121             || memcmp(t->base.expected, ct_buf, ct_len) != 0)
122             goto err;
123
124         if (t->tag != NULL) {
125             unsigned char tag[16] = { 0 };
126
127             if (EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_GET_TAG, t->tag_len,
128                                      tag) <= 0
129                 || memcmp(tag, t->tag, t->tag_len) != 0)
130                 goto err;
131         }
132     }
133
134     /* Decrypt cipher text */
135     if ((t->mode & CIPHER_MODE_DECRYPT) != 0) {
136         if (!(cipher_init(ctx, cipher, t, !encrypt)
137               && EVP_CipherUpdate(ctx, pt_buf, &len,
138                                   t->base.expected, t->base.expected_len)
139               && EVP_CipherFinal_ex(ctx, pt_buf + len, &pt_len)))
140             goto err;
141         OSSL_SELF_TEST_oncorrupt_byte(st, pt_buf);
142         pt_len += len;
143         if (pt_len != (int)t->base.pt_len
144                 || memcmp(pt_buf, t->base.pt, pt_len) != 0)
145             goto err;
146     }
147
148     ret = 1;
149 err:
150     EVP_CIPHER_free(cipher);
151     EVP_CIPHER_CTX_free(ctx);
152     OSSL_SELF_TEST_onend(st, ret);
153     return ret;
154 }
155
156 static int add_params(OSSL_PARAM_BLD *bld, const ST_KAT_PARAM *params,
157                       BN_CTX *ctx)
158 {
159     int ret = 0;
160     const ST_KAT_PARAM *p;
161
162     if (params == NULL)
163         return 1;
164     for (p = params; p->data != NULL; ++p)
165     {
166         switch (p->type) {
167         case OSSL_PARAM_UNSIGNED_INTEGER: {
168             BIGNUM *bn = BN_CTX_get(ctx);
169
170             if (bn == NULL
171                 || (BN_bin2bn(p->data, p->data_len, bn) == NULL)
172                 || !OSSL_PARAM_BLD_push_BN(bld, p->name, bn))
173                 goto err;
174             break;
175         }
176         case OSSL_PARAM_UTF8_STRING: {
177             if (!OSSL_PARAM_BLD_push_utf8_string(bld, p->name, p->data,
178                                                  p->data_len))
179                 goto err;
180             break;
181         }
182         case OSSL_PARAM_OCTET_STRING: {
183             if (!OSSL_PARAM_BLD_push_octet_string(bld, p->name, p->data,
184                                                   p->data_len))
185                 goto err;
186             break;
187         }
188         case OSSL_PARAM_INTEGER: {
189             if (!OSSL_PARAM_BLD_push_int(bld, p->name, *(int *)p->data))
190                 goto err;
191             break;
192         }
193         default:
194             break;
195         }
196     }
197     ret = 1;
198 err:
199     return ret;
200 }
201
202 static int self_test_kdf(const ST_KAT_KDF *t, OSSL_SELF_TEST *st,
203                          OSSL_LIB_CTX *libctx)
204 {
205     int ret = 0;
206     unsigned char out[128];
207     EVP_KDF *kdf = NULL;
208     EVP_KDF_CTX *ctx = NULL;
209     BN_CTX *bnctx = NULL;
210     OSSL_PARAM *params  = NULL;
211     OSSL_PARAM_BLD *bld = NULL;
212
213     OSSL_SELF_TEST_onbegin(st, OSSL_SELF_TEST_TYPE_KAT_KDF, t->desc);
214
215     bld = OSSL_PARAM_BLD_new();
216     if (bld == NULL)
217         goto err;
218
219     kdf = EVP_KDF_fetch(libctx, t->algorithm, "");
220     if (kdf == NULL)
221         goto err;
222
223     ctx = EVP_KDF_CTX_new(kdf);
224     if (ctx == NULL)
225         goto err;
226
227     bnctx = BN_CTX_new_ex(libctx);
228     if (bnctx == NULL)
229         goto err;
230     if (!add_params(bld, t->params, bnctx))
231         goto err;
232     params = OSSL_PARAM_BLD_to_param(bld);
233     if (params == NULL)
234         goto err;
235
236     if (t->expected_len > sizeof(out))
237         goto err;
238     if (EVP_KDF_derive(ctx, out, t->expected_len, params) <= 0)
239         goto err;
240
241     OSSL_SELF_TEST_oncorrupt_byte(st, out);
242
243     if (memcmp(out, t->expected,  t->expected_len) != 0)
244         goto err;
245
246     ret = 1;
247 err:
248     EVP_KDF_free(kdf);
249     EVP_KDF_CTX_free(ctx);
250     BN_CTX_free(bnctx);
251     OSSL_PARAM_free(params);
252     OSSL_PARAM_BLD_free(bld);
253     OSSL_SELF_TEST_onend(st, ret);
254     return ret;
255 }
256
257 static int self_test_drbg(const ST_KAT_DRBG *t, OSSL_SELF_TEST *st,
258                           OSSL_LIB_CTX *libctx)
259 {
260     int ret = 0;
261     unsigned char out[256];
262     EVP_RAND *rand;
263     EVP_RAND_CTX *test = NULL, *drbg = NULL;
264     unsigned int strength = 256;
265     int prediction_resistance = 1; /* Causes a reseed */
266     OSSL_PARAM drbg_params[3] = {
267         OSSL_PARAM_END, OSSL_PARAM_END, OSSL_PARAM_END
268     };
269
270     OSSL_SELF_TEST_onbegin(st, OSSL_SELF_TEST_TYPE_DRBG, t->desc);
271
272     rand = EVP_RAND_fetch(libctx, "TEST-RAND", NULL);
273     if (rand == NULL)
274         goto err;
275
276     test = EVP_RAND_CTX_new(rand, NULL);
277     EVP_RAND_free(rand);
278     if (test == NULL)
279         goto err;
280
281     drbg_params[0] = OSSL_PARAM_construct_uint(OSSL_RAND_PARAM_STRENGTH,
282                                                &strength);
283     if (!EVP_RAND_CTX_set_params(test, drbg_params))
284         goto err;
285
286     rand = EVP_RAND_fetch(libctx, t->algorithm, NULL);
287     if (rand == NULL)
288         goto err;
289
290     drbg = EVP_RAND_CTX_new(rand, test);
291     EVP_RAND_free(rand);
292     if (drbg == NULL)
293         goto err;
294
295     strength = EVP_RAND_get_strength(drbg);
296
297     drbg_params[0] = OSSL_PARAM_construct_utf8_string(t->param_name,
298                                                       t->param_value, 0);
299     /* This is only used by HMAC-DRBG but it is ignored by the others */
300     drbg_params[1] =
301         OSSL_PARAM_construct_utf8_string(OSSL_DRBG_PARAM_MAC, "HMAC", 0);
302     if (!EVP_RAND_CTX_set_params(drbg, drbg_params))
303         goto err;
304
305     drbg_params[0] =
306         OSSL_PARAM_construct_octet_string(OSSL_RAND_PARAM_TEST_ENTROPY,
307                                           (void *)t->entropyin,
308                                           t->entropyinlen);
309     drbg_params[1] =
310         OSSL_PARAM_construct_octet_string(OSSL_RAND_PARAM_TEST_NONCE,
311                                           (void *)t->nonce, t->noncelen);
312     if (!EVP_RAND_instantiate(test, strength, 0, NULL, 0, drbg_params))
313         goto err;
314     if (!EVP_RAND_instantiate(drbg, strength, 0, t->persstr, t->persstrlen,
315                               NULL))
316         goto err;
317
318     drbg_params[0] =
319         OSSL_PARAM_construct_octet_string(OSSL_RAND_PARAM_TEST_ENTROPY,
320                                           (void *)t->entropyinpr1,
321                                           t->entropyinpr1len);
322     if (!EVP_RAND_CTX_set_params(test, drbg_params))
323         goto err;
324
325     if (!EVP_RAND_generate(drbg, out, t->expectedlen, strength,
326                            prediction_resistance,
327                            t->entropyaddin1, t->entropyaddin1len))
328         goto err;
329
330     drbg_params[0] =
331         OSSL_PARAM_construct_octet_string(OSSL_RAND_PARAM_TEST_ENTROPY,
332                                          (void *)t->entropyinpr2,
333                                          t->entropyinpr2len);
334     if (!EVP_RAND_CTX_set_params(test, drbg_params))
335         goto err;
336
337     /*
338      * This calls ossl_prov_drbg_reseed() internally when
339      * prediction_resistance = 1
340      */
341     if (!EVP_RAND_generate(drbg, out, t->expectedlen, strength,
342                            prediction_resistance,
343                            t->entropyaddin2, t->entropyaddin2len))
344         goto err;
345
346     OSSL_SELF_TEST_oncorrupt_byte(st, out);
347
348     if (memcmp(out, t->expected, t->expectedlen) != 0)
349         goto err;
350
351     if (!EVP_RAND_uninstantiate(drbg))
352         goto err;
353     /*
354      * Check that the DRBG data has been zeroized after
355      * ossl_prov_drbg_uninstantiate.
356      */
357     if (!EVP_RAND_verify_zeroization(drbg))
358         goto err;
359
360     ret = 1;
361 err:
362     EVP_RAND_CTX_free(drbg);
363     EVP_RAND_CTX_free(test);
364     OSSL_SELF_TEST_onend(st, ret);
365     return ret;
366 }
367
368 #if !defined(OPENSSL_NO_DH) || !defined(OPENSSL_NO_EC)
369 static int self_test_ka(const ST_KAT_KAS *t,
370                         OSSL_SELF_TEST *st, OSSL_LIB_CTX *libctx)
371 {
372     int ret = 0;
373     EVP_PKEY_CTX *kactx = NULL, *dctx = NULL;
374     EVP_PKEY *pkey = NULL, *peerkey = NULL;
375     OSSL_PARAM *params = NULL;
376     OSSL_PARAM *params_peer = NULL;
377     unsigned char secret[256];
378     size_t secret_len = sizeof(secret);
379     OSSL_PARAM_BLD *bld = NULL;
380     BN_CTX *bnctx = NULL;
381
382     OSSL_SELF_TEST_onbegin(st, OSSL_SELF_TEST_TYPE_KAT_KA, t->desc);
383
384     bnctx = BN_CTX_new_ex(libctx);
385     if (bnctx == NULL)
386         goto err;
387
388     bld = OSSL_PARAM_BLD_new();
389     if (bld == NULL)
390         goto err;
391
392     if (!add_params(bld, t->key_group, bnctx)
393         || !add_params(bld, t->key_host_data, bnctx))
394         goto err;
395     params = OSSL_PARAM_BLD_to_param(bld);
396
397     if (!add_params(bld, t->key_group, bnctx)
398         || !add_params(bld, t->key_peer_data, bnctx))
399         goto err;
400
401     params_peer = OSSL_PARAM_BLD_to_param(bld);
402     if (params == NULL || params_peer == NULL)
403         goto err;
404
405     /* Create a EVP_PKEY_CTX to load the DH keys into */
406     kactx = EVP_PKEY_CTX_new_from_name(libctx, t->algorithm, "");
407     if (kactx == NULL)
408         goto err;
409     if (EVP_PKEY_fromdata_init(kactx) <= 0
410         || EVP_PKEY_fromdata(kactx, &pkey, EVP_PKEY_KEYPAIR, params) <= 0)
411         goto err;
412     if (EVP_PKEY_fromdata_init(kactx) <= 0
413         || EVP_PKEY_fromdata(kactx, &peerkey, EVP_PKEY_KEYPAIR, params_peer) <= 0)
414         goto err;
415
416     /* Create a EVP_PKEY_CTX to perform key derivation */
417     dctx = EVP_PKEY_CTX_new_from_pkey(libctx, pkey, NULL);
418     if (dctx == NULL)
419         goto err;
420
421     if (EVP_PKEY_derive_init(dctx) <= 0
422         || EVP_PKEY_derive_set_peer(dctx, peerkey) <= 0
423         || EVP_PKEY_derive(dctx, secret, &secret_len) <= 0)
424         goto err;
425
426     OSSL_SELF_TEST_oncorrupt_byte(st, secret);
427
428     if (secret_len != t->expected_len
429         || memcmp(secret, t->expected, t->expected_len) != 0)
430         goto err;
431     ret = 1;
432 err:
433     BN_CTX_free(bnctx);
434     EVP_PKEY_free(pkey);
435     EVP_PKEY_free(peerkey);
436     EVP_PKEY_CTX_free(kactx);
437     EVP_PKEY_CTX_free(dctx);
438     OSSL_PARAM_free(params_peer);
439     OSSL_PARAM_free(params);
440     OSSL_PARAM_BLD_free(bld);
441     OSSL_SELF_TEST_onend(st, ret);
442     return ret;
443 }
444 #endif /* !defined(OPENSSL_NO_DH) || !defined(OPENSSL_NO_EC) */
445
446 static int self_test_sign(const ST_KAT_SIGN *t,
447                           OSSL_SELF_TEST *st, OSSL_LIB_CTX *libctx)
448 {
449     int ret = 0;
450     OSSL_PARAM *params = NULL, *params_sig = NULL;
451     OSSL_PARAM_BLD *bld = NULL;
452     EVP_PKEY_CTX *sctx = NULL, *kctx = NULL;
453     EVP_PKEY *pkey = NULL;
454     unsigned char sig[256];
455     BN_CTX *bnctx = NULL;
456     size_t siglen = sizeof(sig);
457     static const unsigned char dgst[] = {
458         0x7f, 0x83, 0xb1, 0x65, 0x7f, 0xf1, 0xfc, 0x53, 0xb9, 0x2d, 0xc1, 0x81,
459         0x48, 0xa1, 0xd6, 0x5d, 0xfc, 0x2d, 0x4b, 0x1f, 0xa3, 0xd6, 0x77, 0x28,
460         0x4a, 0xdd, 0xd2, 0x00, 0x12, 0x6d, 0x90, 0x69
461     };
462     const char *typ = OSSL_SELF_TEST_TYPE_KAT_SIGNATURE;
463
464     if (t->sig_expected == NULL)
465         typ = OSSL_SELF_TEST_TYPE_PCT_SIGNATURE;
466
467     OSSL_SELF_TEST_onbegin(st, typ, t->desc);
468
469     bnctx = BN_CTX_new_ex(libctx);
470     if (bnctx == NULL)
471         goto err;
472
473     bld = OSSL_PARAM_BLD_new();
474     if (bld == NULL)
475         goto err;
476
477     if (!add_params(bld, t->key, bnctx))
478         goto err;
479     params = OSSL_PARAM_BLD_to_param(bld);
480
481     /* Create a EVP_PKEY_CTX to load the DSA key into */
482     kctx = EVP_PKEY_CTX_new_from_name(libctx, t->algorithm, "");
483     if (kctx == NULL || params == NULL)
484         goto err;
485     if (EVP_PKEY_fromdata_init(kctx) <= 0
486         || EVP_PKEY_fromdata(kctx, &pkey, EVP_PKEY_KEYPAIR, params) <= 0)
487         goto err;
488
489     /* Create a EVP_PKEY_CTX to use for the signing operation */
490     sctx = EVP_PKEY_CTX_new_from_pkey(libctx, pkey, NULL);
491     if (sctx == NULL
492         || EVP_PKEY_sign_init(sctx) <= 0)
493         goto err;
494
495     /* set signature parameters */
496     if (!OSSL_PARAM_BLD_push_utf8_string(bld, OSSL_SIGNATURE_PARAM_DIGEST,
497                                          t->mdalgorithm,
498                                          strlen(t->mdalgorithm) + 1))
499         goto err;
500     params_sig = OSSL_PARAM_BLD_to_param(bld);
501     if (EVP_PKEY_CTX_set_params(sctx, params_sig) <= 0)
502         goto err;
503
504     if (EVP_PKEY_sign(sctx, sig, &siglen, dgst, sizeof(dgst)) <= 0
505         || EVP_PKEY_verify_init(sctx) <= 0
506         || EVP_PKEY_CTX_set_params(sctx, params_sig) <= 0)
507         goto err;
508
509     if (t->sig_expected != NULL
510         && (siglen != t->sig_expected_len
511             || memcmp(sig, t->sig_expected, t->sig_expected_len) != 0))
512         goto err;
513
514     OSSL_SELF_TEST_oncorrupt_byte(st, sig);
515     if (EVP_PKEY_verify(sctx, sig, siglen, dgst, sizeof(dgst)) <= 0)
516         goto err;
517     ret = 1;
518 err:
519     BN_CTX_free(bnctx);
520     EVP_PKEY_free(pkey);
521     EVP_PKEY_CTX_free(kctx);
522     EVP_PKEY_CTX_free(sctx);
523     OSSL_PARAM_free(params);
524     OSSL_PARAM_free(params_sig);
525     OSSL_PARAM_BLD_free(bld);
526     OSSL_SELF_TEST_onend(st, ret);
527     return ret;
528 }
529
530 /*
531  * Test an encrypt or decrypt KAT..
532  *
533  * FIPS 140-2 IG D.9 states that separate KAT tests are needed for encrypt
534  * and decrypt..
535  */
536 static int self_test_asym_cipher(const ST_KAT_ASYM_CIPHER *t, OSSL_SELF_TEST *st,
537                                  OSSL_LIB_CTX *libctx)
538 {
539     int ret = 0;
540     OSSL_PARAM *keyparams = NULL, *initparams = NULL;
541     OSSL_PARAM_BLD *keybld = NULL, *initbld = NULL;
542     EVP_PKEY_CTX *encctx = NULL, *keyctx = NULL;
543     EVP_PKEY *key = NULL;
544     BN_CTX *bnctx = NULL;
545     unsigned char out[256];
546     size_t outlen = sizeof(out);
547
548     OSSL_SELF_TEST_onbegin(st, OSSL_SELF_TEST_TYPE_KAT_ASYM_CIPHER, t->desc);
549
550     bnctx = BN_CTX_new_ex(libctx);
551     if (bnctx == NULL)
552         goto err;
553
554     /* Load a public or private key from data */
555     keybld = OSSL_PARAM_BLD_new();
556     if (keybld == NULL
557         || !add_params(keybld, t->key, bnctx))
558         goto err;
559     keyparams = OSSL_PARAM_BLD_to_param(keybld);
560     keyctx = EVP_PKEY_CTX_new_from_name(libctx, t->algorithm, NULL);
561     if (keyctx == NULL || keyparams == NULL)
562         goto err;
563     if (EVP_PKEY_fromdata_init(keyctx) <= 0
564         || EVP_PKEY_fromdata(keyctx, &key, EVP_PKEY_KEYPAIR, keyparams) <= 0)
565         goto err;
566
567     /* Create a EVP_PKEY_CTX to use for the encrypt or decrypt operation */
568     encctx = EVP_PKEY_CTX_new_from_pkey(libctx, key, NULL);
569     if (encctx == NULL
570         || (t->encrypt && EVP_PKEY_encrypt_init(encctx) <= 0)
571         || (!t->encrypt && EVP_PKEY_decrypt_init(encctx) <= 0))
572         goto err;
573
574     /* Add any additional parameters such as padding */
575     if (t->postinit != NULL) {
576         initbld = OSSL_PARAM_BLD_new();
577         if (initbld == NULL)
578             goto err;
579         if (!add_params(initbld, t->postinit, bnctx))
580             goto err;
581         initparams = OSSL_PARAM_BLD_to_param(initbld);
582         if (initparams == NULL)
583             goto err;
584         if (EVP_PKEY_CTX_set_params(encctx, initparams) <= 0)
585             goto err;
586     }
587
588     if (t->encrypt) {
589         if (EVP_PKEY_encrypt(encctx, out, &outlen,
590                              t->in, t->in_len) <= 0)
591             goto err;
592     } else {
593         if (EVP_PKEY_decrypt(encctx, out, &outlen,
594                              t->in, t->in_len) <= 0)
595             goto err;
596     }
597     /* Check the KAT */
598     OSSL_SELF_TEST_oncorrupt_byte(st, out);
599     if (outlen != t->expected_len
600         || memcmp(out, t->expected, t->expected_len) != 0)
601         goto err;
602
603     ret = 1;
604 err:
605     BN_CTX_free(bnctx);
606     EVP_PKEY_free(key);
607     EVP_PKEY_CTX_free(encctx);
608     EVP_PKEY_CTX_free(keyctx);
609     OSSL_PARAM_free(keyparams);
610     OSSL_PARAM_BLD_free(keybld);
611     OSSL_PARAM_free(initparams);
612     OSSL_PARAM_BLD_free(initbld);
613     OSSL_SELF_TEST_onend(st, ret);
614     return ret;
615 }
616
617 /*
618  * Test a data driven list of KAT's for digest algorithms.
619  * All tests are run regardless of if they fail or not.
620  * Return 0 if any test fails.
621  */
622 static int self_test_digests(OSSL_SELF_TEST *st, OSSL_LIB_CTX *libctx)
623 {
624     int i, ret = 1;
625
626     for (i = 0; i < (int)OSSL_NELEM(st_kat_digest_tests); ++i) {
627         if (!self_test_digest(&st_kat_digest_tests[i], st, libctx))
628             ret = 0;
629     }
630     return ret;
631 }
632
633 static int self_test_ciphers(OSSL_SELF_TEST *st, OSSL_LIB_CTX *libctx)
634 {
635     int i, ret = 1;
636
637     for (i = 0; i < (int)OSSL_NELEM(st_kat_cipher_tests); ++i) {
638         if (!self_test_cipher(&st_kat_cipher_tests[i], st, libctx))
639             ret = 0;
640     }
641     return ret;
642 }
643
644 static int self_test_asym_ciphers(OSSL_SELF_TEST *st, OSSL_LIB_CTX *libctx)
645 {
646     int i, ret = 1;
647
648     for (i = 0; i < (int)OSSL_NELEM(st_kat_asym_cipher_tests); ++i) {
649         if (!self_test_asym_cipher(&st_kat_asym_cipher_tests[i], st, libctx))
650             ret = 0;
651     }
652     return ret;
653 }
654
655 static int self_test_kdfs(OSSL_SELF_TEST *st, OSSL_LIB_CTX *libctx)
656 {
657     int i, ret = 1;
658
659     for (i = 0; i < (int)OSSL_NELEM(st_kat_kdf_tests); ++i) {
660         if (!self_test_kdf(&st_kat_kdf_tests[i], st, libctx))
661             ret = 0;
662     }
663     return ret;
664 }
665
666 static int self_test_drbgs(OSSL_SELF_TEST *st, OSSL_LIB_CTX *libctx)
667 {
668     int i, ret = 1;
669
670     for (i = 0; i < (int)OSSL_NELEM(st_kat_drbg_tests); ++i) {
671         if (!self_test_drbg(&st_kat_drbg_tests[i], st, libctx))
672             ret = 0;
673     }
674     return ret;
675 }
676
677 static int self_test_kas(OSSL_SELF_TEST *st, OSSL_LIB_CTX *libctx)
678 {
679     int ret = 1;
680 #if !defined(OPENSSL_NO_DH) || !defined(OPENSSL_NO_EC)
681     int i;
682
683     for (i = 0; i < (int)OSSL_NELEM(st_kat_kas_tests); ++i) {
684         if (!self_test_ka(&st_kat_kas_tests[i], st, libctx))
685             ret = 0;
686     }
687 #endif
688
689     return ret;
690 }
691
692 static int self_test_signatures(OSSL_SELF_TEST *st, OSSL_LIB_CTX *libctx)
693 {
694     int i, ret = 1;
695     const ST_KAT_SIGN *t;
696
697     for (i = 0; ret && i < (int)OSSL_NELEM(st_kat_sign_tests); ++i) {
698         t = st_kat_sign_tests + i;
699         if (!set_kat_drbg(libctx, t->entropy, t->entropy_len,
700                           t->nonce, t->nonce_len, t->persstr, t->persstr_len))
701             return 0;
702         if (!self_test_sign(t, st, libctx))
703             ret = 0;
704         if (!reset_original_drbg(libctx))
705             ret = 0;
706     }
707     return ret;
708 }
709
710 /*
711  * Run the algorithm KAT's.
712  * Return 1 is successful, otherwise return 0.
713  * This runs all the tests regardless of if any fail.
714  */
715 int SELF_TEST_kats(OSSL_SELF_TEST *st, OSSL_LIB_CTX *libctx)
716 {
717     int ret = 1;
718
719     if (!self_test_digests(st, libctx))
720         ret = 0;
721     if (!self_test_ciphers(st, libctx))
722         ret = 0;
723     if (!self_test_signatures(st, libctx))
724         ret = 0;
725     if (!self_test_kdfs(st, libctx))
726         ret = 0;
727     if (!self_test_drbgs(st, libctx))
728         ret = 0;
729     if (!self_test_kas(st, libctx))
730         ret = 0;
731     if (!self_test_asym_ciphers(st, libctx))
732         ret = 0;
733
734     return ret;
735 }
736
737 /*
738  * Swap the library context DRBG for KAT testing
739  *
740  * In FIPS 140-3, the asymmetric POST must be a KAT, not a PCT.  For DSA and ECDSA,
741  * the sign operation includes the random value 'k'.  For a KAT to work, we
742  * have to have control of the DRBG to make sure it is in a "test" state, where
743  * its output is truly deterministic.
744  *
745  */
746
747 /*
748  * The default private DRBG of the library context, saved for the duration
749  * of KAT testing.
750  */
751 static EVP_RAND_CTX *saved_rand = NULL;
752
753 /* Replacement "random" source */
754 static EVP_RAND_CTX *kat_rand = NULL;
755
756 static int set_kat_drbg(OSSL_LIB_CTX *ctx,
757                         const unsigned char *entropy, size_t entropy_len,
758                         const unsigned char *nonce, size_t nonce_len,
759                         const unsigned char *persstr, size_t persstr_len) {
760     EVP_RAND *rand;
761     unsigned int strength = 256;
762     EVP_RAND_CTX *parent_rand = NULL;
763     OSSL_PARAM drbg_params[3] = {
764         OSSL_PARAM_END, OSSL_PARAM_END, OSSL_PARAM_END
765     };
766
767     /* If not NULL, we didn't cleanup from last call: BAD */
768     if (kat_rand != NULL || saved_rand != NULL)
769         return 0;
770
771     rand = EVP_RAND_fetch(ctx, "TEST-RAND", NULL);
772     if (rand == NULL)
773         return 0;
774
775     parent_rand = EVP_RAND_CTX_new(rand, NULL);
776     EVP_RAND_free(rand);
777     if (parent_rand == NULL)
778         goto err;
779
780     drbg_params[0] = OSSL_PARAM_construct_uint(OSSL_RAND_PARAM_STRENGTH, &strength);
781     if (!EVP_RAND_CTX_set_params(parent_rand, drbg_params))
782         goto err;
783
784     rand = EVP_RAND_fetch(ctx, "HASH-DRBG", NULL);
785     if (rand == NULL)
786         goto err;
787
788     kat_rand = EVP_RAND_CTX_new(rand, parent_rand);
789     EVP_RAND_free(rand);
790     if (kat_rand == NULL)
791         goto err;
792
793     drbg_params[0] = OSSL_PARAM_construct_utf8_string("digest", "SHA256", 0);
794     if (!EVP_RAND_CTX_set_params(kat_rand, drbg_params))
795         goto err;
796
797     /* Instantiate the RNGs */
798     drbg_params[0] =
799         OSSL_PARAM_construct_octet_string(OSSL_RAND_PARAM_TEST_ENTROPY,
800                                           (void *)entropy, entropy_len);
801     drbg_params[1] =
802         OSSL_PARAM_construct_octet_string(OSSL_RAND_PARAM_TEST_NONCE,
803                                           (void *)nonce, nonce_len);
804     if (!EVP_RAND_instantiate(parent_rand, strength, 0, NULL, 0, drbg_params))
805         goto err;
806
807     EVP_RAND_CTX_free(parent_rand);
808     parent_rand = NULL;
809
810     if (!EVP_RAND_instantiate(kat_rand, strength, 0, persstr, persstr_len, NULL))
811         goto err;
812
813     /* Update the library context DRBG */
814     if ((saved_rand = RAND_get0_private(ctx)) != NULL)
815         /* Avoid freeing this since we replace it */
816         if (!EVP_RAND_CTX_up_ref(saved_rand)) {
817             saved_rand = NULL;
818             goto err;
819         }
820     if (RAND_set0_private(ctx, kat_rand) > 0) {
821         /* Keeping a copy to verify zeroization */
822         if (EVP_RAND_CTX_up_ref(kat_rand))
823             return 1;
824         if (saved_rand != NULL)
825             RAND_set0_private(ctx, saved_rand);
826     }
827
828  err:
829     EVP_RAND_CTX_free(parent_rand);
830     EVP_RAND_CTX_free(saved_rand);
831     EVP_RAND_CTX_free(kat_rand);
832     kat_rand = saved_rand = NULL;
833     return 0;
834 }
835
836 static int reset_original_drbg(OSSL_LIB_CTX *ctx) {
837     int ret = 1;
838
839     if (saved_rand != NULL) {
840         if (!RAND_set0_private(ctx, saved_rand))
841             ret = 0;
842         saved_rand = NULL;
843     }
844     if (kat_rand != NULL) {
845         if (!EVP_RAND_uninstantiate(kat_rand)
846                 || !EVP_RAND_verify_zeroization(kat_rand))
847             ret = 0;
848         EVP_RAND_CTX_free(kat_rand);
849         kat_rand = NULL;
850     }
851     return ret;
852 }
853