xref: /freebsd/crypto/openssl/test/evp_test.c (revision f126890ac5386406dadf7c4cfa9566cbb56537c5)
1 /*
2  * Copyright 2015-2024 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 #define OPENSSL_SUPPRESS_DEPRECATED /* EVP_PKEY_new_CMAC_key */
11 #include <stdio.h>
12 #include <string.h>
13 #include <stdlib.h>
14 #include <ctype.h>
15 #include <openssl/evp.h>
16 #include <openssl/pem.h>
17 #include <openssl/err.h>
18 #include <openssl/provider.h>
19 #include <openssl/x509v3.h>
20 #include <openssl/pkcs12.h>
21 #include <openssl/kdf.h>
22 #include <openssl/params.h>
23 #include <openssl/core_names.h>
24 #include <openssl/fips_names.h>
25 #include "internal/numbers.h"
26 #include "internal/nelem.h"
27 #include "crypto/evp.h"
28 #include "testutil.h"
29 
30 typedef struct evp_test_buffer_st EVP_TEST_BUFFER;
31 DEFINE_STACK_OF(EVP_TEST_BUFFER)
32 
33 #define AAD_NUM 4
34 
35 typedef struct evp_test_method_st EVP_TEST_METHOD;
36 
37 /* Structure holding test information */
38 typedef struct evp_test_st {
39     STANZA s;                     /* Common test stanza */
40     char *name;
41     int skip;                     /* Current test should be skipped */
42     const EVP_TEST_METHOD *meth;  /* method for this test */
43     const char *err, *aux_err;    /* Error string for test */
44     char *expected_err;           /* Expected error value of test */
45     char *reason;                 /* Expected error reason string */
46     void *data;                   /* test specific data */
47 } EVP_TEST;
48 
49 /* Test method structure */
50 struct evp_test_method_st {
51     /* Name of test as it appears in file */
52     const char *name;
53     /* Initialise test for "alg" */
54     int (*init) (EVP_TEST * t, const char *alg);
55     /* Clean up method */
56     void (*cleanup) (EVP_TEST * t);
57     /* Test specific name value pair processing */
58     int (*parse) (EVP_TEST * t, const char *name, const char *value);
59     /* Run the test itself */
60     int (*run_test) (EVP_TEST * t);
61 };
62 
63 /* Linked list of named keys. */
64 typedef struct key_list_st {
65     char *name;
66     EVP_PKEY *key;
67     struct key_list_st *next;
68 } KEY_LIST;
69 
70 typedef enum OPTION_choice {
71     OPT_ERR = -1,
72     OPT_EOF = 0,
73     OPT_CONFIG_FILE,
74     OPT_TEST_ENUM
75 } OPTION_CHOICE;
76 
77 static OSSL_PROVIDER *prov_null = NULL;
78 static OSSL_LIB_CTX *libctx = NULL;
79 
80 /* List of public and private keys */
81 static KEY_LIST *private_keys;
82 static KEY_LIST *public_keys;
83 
84 static int find_key(EVP_PKEY **ppk, const char *name, KEY_LIST *lst);
85 static int parse_bin(const char *value, unsigned char **buf, size_t *buflen);
86 static int is_digest_disabled(const char *name);
87 static int is_pkey_disabled(const char *name);
88 static int is_mac_disabled(const char *name);
89 static int is_cipher_disabled(const char *name);
90 static int is_kdf_disabled(const char *name);
91 
92 /*
93  * Compare two memory regions for equality, returning zero if they differ.
94  * However, if there is expected to be an error and the actual error
95  * matches then the memory is expected to be different so handle this
96  * case without producing unnecessary test framework output.
97  */
98 static int memory_err_compare(EVP_TEST *t, const char *err,
99                               const void *expected, size_t expected_len,
100                               const void *got, size_t got_len)
101 {
102     int r;
103 
104     if (t->expected_err != NULL && strcmp(t->expected_err, err) == 0)
105         r = !TEST_mem_ne(expected, expected_len, got, got_len);
106     else
107         r = TEST_mem_eq(expected, expected_len, got, got_len);
108     if (!r)
109         t->err = err;
110     return r;
111 }
112 
113 /*
114  * Structure used to hold a list of blocks of memory to test
115  * calls to "update" like functions.
116  */
117 struct evp_test_buffer_st {
118     unsigned char *buf;
119     size_t buflen;
120     size_t count;
121     int count_set;
122 };
123 
124 static void evp_test_buffer_free(EVP_TEST_BUFFER *db)
125 {
126     if (db != NULL) {
127         OPENSSL_free(db->buf);
128         OPENSSL_free(db);
129     }
130 }
131 
132 /* append buffer to a list */
133 static int evp_test_buffer_append(const char *value,
134                                   STACK_OF(EVP_TEST_BUFFER) **sk)
135 {
136     EVP_TEST_BUFFER *db = NULL;
137 
138     if (!TEST_ptr(db = OPENSSL_malloc(sizeof(*db))))
139         goto err;
140 
141     if (!parse_bin(value, &db->buf, &db->buflen))
142         goto err;
143     db->count = 1;
144     db->count_set = 0;
145 
146     if (*sk == NULL && !TEST_ptr(*sk = sk_EVP_TEST_BUFFER_new_null()))
147         goto err;
148     if (!sk_EVP_TEST_BUFFER_push(*sk, db))
149         goto err;
150 
151     return 1;
152 
153 err:
154     evp_test_buffer_free(db);
155     return 0;
156 }
157 
158 /* replace last buffer in list with copies of itself */
159 static int evp_test_buffer_ncopy(const char *value,
160                                  STACK_OF(EVP_TEST_BUFFER) *sk)
161 {
162     EVP_TEST_BUFFER *db;
163     unsigned char *tbuf, *p;
164     size_t tbuflen;
165     int ncopy = atoi(value);
166     int i;
167 
168     if (ncopy <= 0)
169         return 0;
170     if (sk == NULL || sk_EVP_TEST_BUFFER_num(sk) == 0)
171         return 0;
172     db = sk_EVP_TEST_BUFFER_value(sk, sk_EVP_TEST_BUFFER_num(sk) - 1);
173 
174     tbuflen = db->buflen * ncopy;
175     if (!TEST_ptr(tbuf = OPENSSL_malloc(tbuflen)))
176         return 0;
177     for (i = 0, p = tbuf; i < ncopy; i++, p += db->buflen)
178         memcpy(p, db->buf, db->buflen);
179 
180     OPENSSL_free(db->buf);
181     db->buf = tbuf;
182     db->buflen = tbuflen;
183     return 1;
184 }
185 
186 /* set repeat count for last buffer in list */
187 static int evp_test_buffer_set_count(const char *value,
188                                      STACK_OF(EVP_TEST_BUFFER) *sk)
189 {
190     EVP_TEST_BUFFER *db;
191     int count = atoi(value);
192 
193     if (count <= 0)
194         return 0;
195 
196     if (sk == NULL || sk_EVP_TEST_BUFFER_num(sk) == 0)
197         return 0;
198 
199     db = sk_EVP_TEST_BUFFER_value(sk, sk_EVP_TEST_BUFFER_num(sk) - 1);
200     if (db->count_set != 0)
201         return 0;
202 
203     db->count = (size_t)count;
204     db->count_set = 1;
205     return 1;
206 }
207 
208 /* call "fn" with each element of the list in turn */
209 static int evp_test_buffer_do(STACK_OF(EVP_TEST_BUFFER) *sk,
210                               int (*fn)(void *ctx,
211                                         const unsigned char *buf,
212                                         size_t buflen),
213                               void *ctx)
214 {
215     int i;
216 
217     for (i = 0; i < sk_EVP_TEST_BUFFER_num(sk); i++) {
218         EVP_TEST_BUFFER *tb = sk_EVP_TEST_BUFFER_value(sk, i);
219         size_t j;
220 
221         for (j = 0; j < tb->count; j++) {
222             if (fn(ctx, tb->buf, tb->buflen) <= 0)
223                 return 0;
224         }
225     }
226     return 1;
227 }
228 
229 /*
230  * Unescape some sequences in string literals (only \n for now).
231  * Return an allocated buffer, set |out_len|.  If |input_len|
232  * is zero, get an empty buffer but set length to zero.
233  */
234 static unsigned char* unescape(const char *input, size_t input_len,
235                                size_t *out_len)
236 {
237     unsigned char *ret, *p;
238     size_t i;
239 
240     if (input_len == 0) {
241         *out_len = 0;
242         return OPENSSL_zalloc(1);
243     }
244 
245     /* Escaping is non-expanding; over-allocate original size for simplicity. */
246     if (!TEST_ptr(ret = p = OPENSSL_malloc(input_len)))
247         return NULL;
248 
249     for (i = 0; i < input_len; i++) {
250         if (*input == '\\') {
251             if (i == input_len - 1 || *++input != 'n') {
252                 TEST_error("Bad escape sequence in file");
253                 goto err;
254             }
255             *p++ = '\n';
256             i++;
257             input++;
258         } else {
259             *p++ = *input++;
260         }
261     }
262 
263     *out_len = p - ret;
264     return ret;
265 
266  err:
267     OPENSSL_free(ret);
268     return NULL;
269 }
270 
271 /*
272  * For a hex string "value" convert to a binary allocated buffer.
273  * Return 1 on success or 0 on failure.
274  */
275 static int parse_bin(const char *value, unsigned char **buf, size_t *buflen)
276 {
277     long len;
278 
279     /* Check for NULL literal */
280     if (strcmp(value, "NULL") == 0) {
281         *buf = NULL;
282         *buflen = 0;
283         return 1;
284     }
285 
286     /* Check for empty value */
287     if (*value == '\0') {
288         /*
289          * Don't return NULL for zero length buffer. This is needed for
290          * some tests with empty keys: HMAC_Init_ex() expects a non-NULL key
291          * buffer even if the key length is 0, in order to detect key reset.
292          */
293         *buf = OPENSSL_malloc(1);
294         if (*buf == NULL)
295             return 0;
296         **buf = 0;
297         *buflen = 0;
298         return 1;
299     }
300 
301     /* Check for string literal */
302     if (value[0] == '"') {
303         size_t vlen = strlen(++value);
304 
305         if (vlen == 0 || value[vlen - 1] != '"')
306             return 0;
307         vlen--;
308         *buf = unescape(value, vlen, buflen);
309         return *buf == NULL ? 0 : 1;
310     }
311 
312     /* Otherwise assume as hex literal and convert it to binary buffer */
313     if (!TEST_ptr(*buf = OPENSSL_hexstr2buf(value, &len))) {
314         TEST_info("Can't convert %s", value);
315         TEST_openssl_errors();
316         return -1;
317     }
318     /* Size of input buffer means we'll never overflow */
319     *buflen = len;
320     return 1;
321 }
322 
323 /**
324  **  MESSAGE DIGEST TESTS
325  **/
326 
327 typedef struct digest_data_st {
328     /* Digest this test is for */
329     const EVP_MD *digest;
330     EVP_MD *fetched_digest;
331     /* Input to digest */
332     STACK_OF(EVP_TEST_BUFFER) *input;
333     /* Expected output */
334     unsigned char *output;
335     size_t output_len;
336     /* Padding type */
337     int pad_type;
338 } DIGEST_DATA;
339 
340 static int digest_test_init(EVP_TEST *t, const char *alg)
341 {
342     DIGEST_DATA *mdat;
343     const EVP_MD *digest;
344     EVP_MD *fetched_digest;
345 
346     if (is_digest_disabled(alg)) {
347         TEST_info("skipping, '%s' is disabled", alg);
348         t->skip = 1;
349         return 1;
350     }
351 
352     if ((digest = fetched_digest = EVP_MD_fetch(libctx, alg, NULL)) == NULL
353         && (digest = EVP_get_digestbyname(alg)) == NULL)
354         return 0;
355     if (!TEST_ptr(mdat = OPENSSL_zalloc(sizeof(*mdat))))
356         return 0;
357     t->data = mdat;
358     mdat->digest = digest;
359     mdat->fetched_digest = fetched_digest;
360     mdat->pad_type = 0;
361     if (fetched_digest != NULL)
362         TEST_info("%s is fetched", alg);
363     return 1;
364 }
365 
366 static void digest_test_cleanup(EVP_TEST *t)
367 {
368     DIGEST_DATA *mdat = t->data;
369 
370     sk_EVP_TEST_BUFFER_pop_free(mdat->input, evp_test_buffer_free);
371     OPENSSL_free(mdat->output);
372     EVP_MD_free(mdat->fetched_digest);
373 }
374 
375 static int digest_test_parse(EVP_TEST *t,
376                              const char *keyword, const char *value)
377 {
378     DIGEST_DATA *mdata = t->data;
379 
380     if (strcmp(keyword, "Input") == 0)
381         return evp_test_buffer_append(value, &mdata->input);
382     if (strcmp(keyword, "Output") == 0)
383         return parse_bin(value, &mdata->output, &mdata->output_len);
384     if (strcmp(keyword, "Count") == 0)
385         return evp_test_buffer_set_count(value, mdata->input);
386     if (strcmp(keyword, "Ncopy") == 0)
387         return evp_test_buffer_ncopy(value, mdata->input);
388     if (strcmp(keyword, "Padding") == 0)
389         return (mdata->pad_type = atoi(value)) > 0;
390     return 0;
391 }
392 
393 static int digest_update_fn(void *ctx, const unsigned char *buf, size_t buflen)
394 {
395     return EVP_DigestUpdate(ctx, buf, buflen);
396 }
397 
398 static int digest_test_run(EVP_TEST *t)
399 {
400     DIGEST_DATA *expected = t->data;
401     EVP_TEST_BUFFER *inbuf;
402     EVP_MD_CTX *mctx;
403     unsigned char *got = NULL;
404     unsigned int got_len;
405     size_t size = 0;
406     int xof = 0;
407     OSSL_PARAM params[2];
408 
409     t->err = "TEST_FAILURE";
410     if (!TEST_ptr(mctx = EVP_MD_CTX_new()))
411         goto err;
412 
413     got = OPENSSL_malloc(expected->output_len > EVP_MAX_MD_SIZE ?
414                          expected->output_len : EVP_MAX_MD_SIZE);
415     if (!TEST_ptr(got))
416         goto err;
417 
418     if (!EVP_DigestInit_ex(mctx, expected->digest, NULL)) {
419         t->err = "DIGESTINIT_ERROR";
420         goto err;
421     }
422     if (expected->pad_type > 0) {
423         params[0] = OSSL_PARAM_construct_int(OSSL_DIGEST_PARAM_PAD_TYPE,
424                                               &expected->pad_type);
425         params[1] = OSSL_PARAM_construct_end();
426         if (!TEST_int_gt(EVP_MD_CTX_set_params(mctx, params), 0)) {
427             t->err = "PARAMS_ERROR";
428             goto err;
429         }
430     }
431     if (!evp_test_buffer_do(expected->input, digest_update_fn, mctx)) {
432         t->err = "DIGESTUPDATE_ERROR";
433         goto err;
434     }
435 
436     xof = (EVP_MD_get_flags(expected->digest) & EVP_MD_FLAG_XOF) != 0;
437     if (xof) {
438         EVP_MD_CTX *mctx_cpy;
439         char dont[] = "touch";
440 
441         if (!TEST_ptr(mctx_cpy = EVP_MD_CTX_new())) {
442             goto err;
443         }
444         if (!EVP_MD_CTX_copy(mctx_cpy, mctx)) {
445             EVP_MD_CTX_free(mctx_cpy);
446             goto err;
447         }
448         if (!EVP_DigestFinalXOF(mctx_cpy, (unsigned char *)dont, 0)) {
449             EVP_MD_CTX_free(mctx_cpy);
450             t->err = "DIGESTFINALXOF_ERROR";
451             goto err;
452         }
453         if (!TEST_str_eq(dont, "touch")) {
454             EVP_MD_CTX_free(mctx_cpy);
455             t->err = "DIGESTFINALXOF_ERROR";
456             goto err;
457         }
458         EVP_MD_CTX_free(mctx_cpy);
459 
460         got_len = expected->output_len;
461         if (!EVP_DigestFinalXOF(mctx, got, got_len)) {
462             t->err = "DIGESTFINALXOF_ERROR";
463             goto err;
464         }
465     } else {
466         if (!EVP_DigestFinal(mctx, got, &got_len)) {
467             t->err = "DIGESTFINAL_ERROR";
468             goto err;
469         }
470     }
471     if (!TEST_int_eq(expected->output_len, got_len)) {
472         t->err = "DIGEST_LENGTH_MISMATCH";
473         goto err;
474     }
475     if (!memory_err_compare(t, "DIGEST_MISMATCH",
476                             expected->output, expected->output_len,
477                             got, got_len))
478         goto err;
479 
480     t->err = NULL;
481 
482     /* Test the EVP_Q_digest interface as well */
483     if (sk_EVP_TEST_BUFFER_num(expected->input) == 1
484             && !xof
485             /* This should never fail but we need the returned pointer now */
486             && !TEST_ptr(inbuf = sk_EVP_TEST_BUFFER_value(expected->input, 0))
487             && !inbuf->count_set) {
488         OPENSSL_cleanse(got, got_len);
489         if (!TEST_true(EVP_Q_digest(libctx,
490                                     EVP_MD_get0_name(expected->fetched_digest),
491                                     NULL, inbuf->buf, inbuf->buflen,
492                                     got, &size))
493                 || !TEST_mem_eq(got, size,
494                                 expected->output, expected->output_len)) {
495             t->err = "EVP_Q_digest failed";
496             goto err;
497         }
498     }
499 
500  err:
501     OPENSSL_free(got);
502     EVP_MD_CTX_free(mctx);
503     return 1;
504 }
505 
506 static const EVP_TEST_METHOD digest_test_method = {
507     "Digest",
508     digest_test_init,
509     digest_test_cleanup,
510     digest_test_parse,
511     digest_test_run
512 };
513 
514 /**
515 ***  CIPHER TESTS
516 **/
517 
518 typedef struct cipher_data_st {
519     const EVP_CIPHER *cipher;
520     EVP_CIPHER *fetched_cipher;
521     int enc;
522     /* EVP_CIPH_GCM_MODE, EVP_CIPH_CCM_MODE or EVP_CIPH_OCB_MODE if AEAD */
523     int aead;
524     unsigned char *key;
525     size_t key_len;
526     size_t key_bits; /* Used by RC2 */
527     unsigned char *iv;
528     unsigned char *next_iv; /* Expected IV state after operation */
529     unsigned int rounds;
530     size_t iv_len;
531     unsigned char *plaintext;
532     size_t plaintext_len;
533     unsigned char *ciphertext;
534     size_t ciphertext_len;
535     /* AEAD ciphers only */
536     unsigned char *aad[AAD_NUM];
537     size_t aad_len[AAD_NUM];
538     int tls_aad;
539     int tls_version;
540     unsigned char *tag;
541     const char *cts_mode;
542     size_t tag_len;
543     int tag_late;
544     unsigned char *mac_key;
545     size_t mac_key_len;
546 } CIPHER_DATA;
547 
548 static int cipher_test_init(EVP_TEST *t, const char *alg)
549 {
550     const EVP_CIPHER *cipher;
551     EVP_CIPHER *fetched_cipher;
552     CIPHER_DATA *cdat;
553     int m;
554 
555     if (is_cipher_disabled(alg)) {
556         t->skip = 1;
557         TEST_info("skipping, '%s' is disabled", alg);
558         return 1;
559     }
560 
561     ERR_set_mark();
562     if ((cipher = fetched_cipher = EVP_CIPHER_fetch(libctx, alg, NULL)) == NULL
563         && (cipher = EVP_get_cipherbyname(alg)) == NULL) {
564         /* a stitched cipher might not be available */
565         if (strstr(alg, "HMAC") != NULL) {
566             ERR_pop_to_mark();
567             t->skip = 1;
568             TEST_info("skipping, '%s' is not available", alg);
569             return 1;
570         }
571         ERR_clear_last_mark();
572         return 0;
573     }
574     ERR_clear_last_mark();
575 
576     if (!TEST_ptr(cdat = OPENSSL_zalloc(sizeof(*cdat))))
577         return 0;
578 
579     cdat->cipher = cipher;
580     cdat->fetched_cipher = fetched_cipher;
581     cdat->enc = -1;
582     m = EVP_CIPHER_get_mode(cipher);
583     if (EVP_CIPHER_get_flags(cipher) & EVP_CIPH_FLAG_AEAD_CIPHER)
584         cdat->aead = m != 0 ? m : -1;
585     else
586         cdat->aead = 0;
587 
588     t->data = cdat;
589     if (fetched_cipher != NULL)
590         TEST_info("%s is fetched", alg);
591     return 1;
592 }
593 
594 static void cipher_test_cleanup(EVP_TEST *t)
595 {
596     int i;
597     CIPHER_DATA *cdat = t->data;
598 
599     OPENSSL_free(cdat->key);
600     OPENSSL_free(cdat->iv);
601     OPENSSL_free(cdat->next_iv);
602     OPENSSL_free(cdat->ciphertext);
603     OPENSSL_free(cdat->plaintext);
604     for (i = 0; i < AAD_NUM; i++)
605         OPENSSL_free(cdat->aad[i]);
606     OPENSSL_free(cdat->tag);
607     OPENSSL_free(cdat->mac_key);
608     EVP_CIPHER_free(cdat->fetched_cipher);
609 }
610 
611 static int cipher_test_parse(EVP_TEST *t, const char *keyword,
612                              const char *value)
613 {
614     CIPHER_DATA *cdat = t->data;
615     int i;
616 
617     if (strcmp(keyword, "Key") == 0)
618         return parse_bin(value, &cdat->key, &cdat->key_len);
619     if (strcmp(keyword, "Rounds") == 0) {
620         i = atoi(value);
621         if (i < 0)
622             return -1;
623         cdat->rounds = (unsigned int)i;
624         return 1;
625     }
626     if (strcmp(keyword, "IV") == 0)
627         return parse_bin(value, &cdat->iv, &cdat->iv_len);
628     if (strcmp(keyword, "NextIV") == 0)
629         return parse_bin(value, &cdat->next_iv, &cdat->iv_len);
630     if (strcmp(keyword, "Plaintext") == 0)
631         return parse_bin(value, &cdat->plaintext, &cdat->plaintext_len);
632     if (strcmp(keyword, "Ciphertext") == 0)
633         return parse_bin(value, &cdat->ciphertext, &cdat->ciphertext_len);
634     if (strcmp(keyword, "KeyBits") == 0) {
635         i = atoi(value);
636         if (i < 0)
637             return -1;
638         cdat->key_bits = (size_t)i;
639         return 1;
640     }
641     if (cdat->aead) {
642         int tls_aad = 0;
643 
644         if (strcmp(keyword, "TLSAAD") == 0)
645             cdat->tls_aad = tls_aad = 1;
646         if (strcmp(keyword, "AAD") == 0 || tls_aad) {
647             for (i = 0; i < AAD_NUM; i++) {
648                 if (cdat->aad[i] == NULL)
649                     return parse_bin(value, &cdat->aad[i], &cdat->aad_len[i]);
650             }
651             return -1;
652         }
653         if (strcmp(keyword, "Tag") == 0)
654             return parse_bin(value, &cdat->tag, &cdat->tag_len);
655         if (strcmp(keyword, "SetTagLate") == 0) {
656             if (strcmp(value, "TRUE") == 0)
657                 cdat->tag_late = 1;
658             else if (strcmp(value, "FALSE") == 0)
659                 cdat->tag_late = 0;
660             else
661                 return -1;
662             return 1;
663         }
664         if (strcmp(keyword, "MACKey") == 0)
665             return parse_bin(value, &cdat->mac_key, &cdat->mac_key_len);
666         if (strcmp(keyword, "TLSVersion") == 0) {
667             char *endptr;
668 
669             cdat->tls_version = (int)strtol(value, &endptr, 0);
670             return value[0] != '\0' && endptr[0] == '\0';
671         }
672     }
673 
674     if (strcmp(keyword, "Operation") == 0) {
675         if (strcmp(value, "ENCRYPT") == 0)
676             cdat->enc = 1;
677         else if (strcmp(value, "DECRYPT") == 0)
678             cdat->enc = 0;
679         else
680             return -1;
681         return 1;
682     }
683     if (strcmp(keyword, "CTSMode") == 0) {
684         cdat->cts_mode = value;
685         return 1;
686     }
687     return 0;
688 }
689 
690 static int cipher_test_enc(EVP_TEST *t, int enc,
691                            size_t out_misalign, size_t inp_misalign, int frag)
692 {
693     CIPHER_DATA *expected = t->data;
694     unsigned char *in, *expected_out, *tmp = NULL;
695     size_t in_len, out_len, donelen = 0;
696     int ok = 0, tmplen, chunklen, tmpflen, i;
697     EVP_CIPHER_CTX *ctx_base = NULL;
698     EVP_CIPHER_CTX *ctx = NULL;
699     int fips_dupctx_supported = (fips_provider_version_gt(libctx, 3, 0, 12)
700                                 && fips_provider_version_lt(libctx, 3, 1, 0))
701                                 || fips_provider_version_ge(libctx, 3, 1, 3);
702 
703     t->err = "TEST_FAILURE";
704     if (!TEST_ptr(ctx_base = EVP_CIPHER_CTX_new()))
705         goto err;
706     if (!TEST_ptr(ctx = EVP_CIPHER_CTX_new()))
707         goto err;
708     EVP_CIPHER_CTX_set_flags(ctx_base, EVP_CIPHER_CTX_FLAG_WRAP_ALLOW);
709     if (enc) {
710         in = expected->plaintext;
711         in_len = expected->plaintext_len;
712         expected_out = expected->ciphertext;
713         out_len = expected->ciphertext_len;
714     } else {
715         in = expected->ciphertext;
716         in_len = expected->ciphertext_len;
717         expected_out = expected->plaintext;
718         out_len = expected->plaintext_len;
719     }
720     if (inp_misalign == (size_t)-1) {
721         /* Exercise in-place encryption */
722         tmp = OPENSSL_malloc(out_misalign + in_len + 2 * EVP_MAX_BLOCK_LENGTH);
723         if (!tmp)
724             goto err;
725         in = memcpy(tmp + out_misalign, in, in_len);
726     } else {
727         inp_misalign += 16 - ((out_misalign + in_len) & 15);
728         /*
729          * 'tmp' will store both output and copy of input. We make the copy
730          * of input to specifically aligned part of 'tmp'. So we just
731          * figured out how much padding would ensure the required alignment,
732          * now we allocate extended buffer and finally copy the input just
733          * past inp_misalign in expression below. Output will be written
734          * past out_misalign...
735          */
736         tmp = OPENSSL_malloc(out_misalign + in_len + 2 * EVP_MAX_BLOCK_LENGTH +
737                              inp_misalign + in_len);
738         if (!tmp)
739             goto err;
740         in = memcpy(tmp + out_misalign + in_len + 2 * EVP_MAX_BLOCK_LENGTH +
741                     inp_misalign, in, in_len);
742     }
743     if (!EVP_CipherInit_ex(ctx_base, expected->cipher, NULL, NULL, NULL, enc)) {
744         t->err = "CIPHERINIT_ERROR";
745         goto err;
746     }
747     if (expected->cts_mode != NULL) {
748         OSSL_PARAM params[2];
749 
750         params[0] = OSSL_PARAM_construct_utf8_string(OSSL_CIPHER_PARAM_CTS_MODE,
751                                                      (char *)expected->cts_mode,
752                                                      0);
753         params[1] = OSSL_PARAM_construct_end();
754         if (!EVP_CIPHER_CTX_set_params(ctx_base, params)) {
755             t->err = "INVALID_CTS_MODE";
756             goto err;
757         }
758     }
759     if (expected->iv) {
760         if (expected->aead) {
761             if (EVP_CIPHER_CTX_ctrl(ctx_base, EVP_CTRL_AEAD_SET_IVLEN,
762                                      expected->iv_len, 0) <= 0) {
763                 t->err = "INVALID_IV_LENGTH";
764                 goto err;
765             }
766         } else if (expected->iv_len != (size_t)EVP_CIPHER_CTX_get_iv_length(ctx_base)) {
767             t->err = "INVALID_IV_LENGTH";
768             goto err;
769         }
770     }
771     if (expected->aead && !expected->tls_aad) {
772         unsigned char *tag;
773         /*
774          * If encrypting or OCB just set tag length initially, otherwise
775          * set tag length and value.
776          */
777         if (enc || expected->aead == EVP_CIPH_OCB_MODE || expected->tag_late) {
778             t->err = "TAG_LENGTH_SET_ERROR";
779             tag = NULL;
780         } else {
781             t->err = "TAG_SET_ERROR";
782             tag = expected->tag;
783         }
784         if (tag || expected->aead != EVP_CIPH_GCM_MODE) {
785             if (EVP_CIPHER_CTX_ctrl(ctx_base, EVP_CTRL_AEAD_SET_TAG,
786                                      expected->tag_len, tag) <= 0)
787                 goto err;
788         }
789     }
790 
791     if (expected->rounds > 0) {
792         int  rounds = (int)expected->rounds;
793 
794         if (EVP_CIPHER_CTX_ctrl(ctx_base, EVP_CTRL_SET_RC5_ROUNDS, rounds, NULL) <= 0) {
795             t->err = "INVALID_ROUNDS";
796             goto err;
797         }
798     }
799 
800     if (!EVP_CIPHER_CTX_set_key_length(ctx_base, expected->key_len)) {
801         t->err = "INVALID_KEY_LENGTH";
802         goto err;
803     }
804     if (expected->key_bits > 0) {
805         int bits = (int)expected->key_bits;
806 
807         if (EVP_CIPHER_CTX_ctrl(ctx_base, EVP_CTRL_SET_RC2_KEY_BITS, bits, NULL) <= 0) {
808             t->err = "INVALID KEY BITS";
809             goto err;
810         }
811     }
812     if (!EVP_CipherInit_ex(ctx_base, NULL, NULL, expected->key, expected->iv, -1)) {
813         t->err = "KEY_SET_ERROR";
814         goto err;
815     }
816 
817     /* Check that we get the same IV back */
818     if (expected->iv != NULL) {
819         /* Some (e.g., GCM) tests use IVs longer than EVP_MAX_IV_LENGTH. */
820         unsigned char iv[128];
821         if (!TEST_true(EVP_CIPHER_CTX_get_updated_iv(ctx_base, iv, sizeof(iv)))
822             || ((EVP_CIPHER_get_flags(expected->cipher) & EVP_CIPH_CUSTOM_IV) == 0
823                 && !TEST_mem_eq(expected->iv, expected->iv_len, iv,
824                                 expected->iv_len))) {
825             t->err = "INVALID_IV";
826             goto err;
827         }
828     }
829 
830     /* Test that the cipher dup functions correctly if it is supported */
831     ERR_set_mark();
832     if (!EVP_CIPHER_CTX_copy(ctx, ctx_base)) {
833         if (fips_dupctx_supported) {
834             TEST_info("Doing a copy of Cipher %s Fails!\n",
835                       EVP_CIPHER_get0_name(expected->cipher));
836             ERR_print_errors_fp(stderr);
837             goto err;
838         } else {
839             TEST_info("Allowing copy fail as an old fips provider is in use.");
840         }
841         EVP_CIPHER_CTX_free(ctx);
842         ctx = ctx_base;
843     } else {
844         EVP_CIPHER_CTX_free(ctx_base);
845         ctx_base = NULL;
846     }
847     ERR_pop_to_mark();
848 
849     if (expected->mac_key != NULL
850         && EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_MAC_KEY,
851                                 (int)expected->mac_key_len,
852                                 (void *)expected->mac_key) <= 0) {
853         t->err = "SET_MAC_KEY_ERROR";
854         goto err;
855     }
856 
857     if (expected->tls_version) {
858         OSSL_PARAM params[2];
859 
860         params[0] = OSSL_PARAM_construct_int(OSSL_CIPHER_PARAM_TLS_VERSION,
861                                              &expected->tls_version);
862         params[1] = OSSL_PARAM_construct_end();
863         if (!EVP_CIPHER_CTX_set_params(ctx, params)) {
864             t->err = "SET_TLS_VERSION_ERROR";
865             goto err;
866         }
867     }
868 
869     if (expected->aead == EVP_CIPH_CCM_MODE) {
870         if (!EVP_CipherUpdate(ctx, NULL, &tmplen, NULL, out_len)) {
871             t->err = "CCM_PLAINTEXT_LENGTH_SET_ERROR";
872             goto err;
873         }
874     }
875     if (expected->aad[0] != NULL && !expected->tls_aad) {
876         t->err = "AAD_SET_ERROR";
877         if (!frag) {
878             for (i = 0; expected->aad[i] != NULL; i++) {
879                 if (!EVP_CipherUpdate(ctx, NULL, &chunklen, expected->aad[i],
880                                       expected->aad_len[i]))
881                     goto err;
882             }
883         } else {
884             /*
885              * Supply the AAD in chunks less than the block size where possible
886              */
887             for (i = 0; expected->aad[i] != NULL; i++) {
888                 if (expected->aad_len[i] > 0) {
889                     if (!EVP_CipherUpdate(ctx, NULL, &chunklen, expected->aad[i], 1))
890                         goto err;
891                     donelen++;
892                 }
893                 if (expected->aad_len[i] > 2) {
894                     if (!EVP_CipherUpdate(ctx, NULL, &chunklen,
895                                           expected->aad[i] + donelen,
896                                           expected->aad_len[i] - 2))
897                         goto err;
898                     donelen += expected->aad_len[i] - 2;
899                 }
900                 if (expected->aad_len[i] > 1
901                     && !EVP_CipherUpdate(ctx, NULL, &chunklen,
902                                          expected->aad[i] + donelen, 1))
903                     goto err;
904             }
905         }
906     }
907 
908     if (expected->tls_aad) {
909         OSSL_PARAM params[2];
910         char *tls_aad;
911 
912         /* duplicate the aad as the implementation might modify it */
913         if ((tls_aad = OPENSSL_memdup(expected->aad[0],
914                                       expected->aad_len[0])) == NULL)
915             goto err;
916         params[0] = OSSL_PARAM_construct_octet_string(OSSL_CIPHER_PARAM_AEAD_TLS1_AAD,
917                                                       tls_aad,
918                                                       expected->aad_len[0]);
919         params[1] = OSSL_PARAM_construct_end();
920         if (!EVP_CIPHER_CTX_set_params(ctx, params)) {
921             OPENSSL_free(tls_aad);
922             t->err = "TLS1_AAD_ERROR";
923             goto err;
924         }
925         OPENSSL_free(tls_aad);
926     } else if (!enc && (expected->aead == EVP_CIPH_OCB_MODE
927                         || expected->tag_late)) {
928         if (EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_TAG,
929                                  expected->tag_len, expected->tag) <= 0) {
930             t->err = "TAG_SET_ERROR";
931             goto err;
932         }
933     }
934 
935     EVP_CIPHER_CTX_set_padding(ctx, 0);
936     t->err = "CIPHERUPDATE_ERROR";
937     tmplen = 0;
938     if (!frag) {
939         /* We supply the data all in one go */
940         if (!EVP_CipherUpdate(ctx, tmp + out_misalign, &tmplen, in, in_len))
941             goto err;
942     } else {
943         /* Supply the data in chunks less than the block size where possible */
944         if (in_len > 0) {
945             if (!EVP_CipherUpdate(ctx, tmp + out_misalign, &chunklen, in, 1))
946                 goto err;
947             tmplen += chunklen;
948             in++;
949             in_len--;
950         }
951         if (in_len > 1) {
952             if (!EVP_CipherUpdate(ctx, tmp + out_misalign + tmplen, &chunklen,
953                                   in, in_len - 1))
954                 goto err;
955             tmplen += chunklen;
956             in += in_len - 1;
957             in_len = 1;
958         }
959         if (in_len > 0 ) {
960             if (!EVP_CipherUpdate(ctx, tmp + out_misalign + tmplen, &chunklen,
961                                   in, 1))
962                 goto err;
963             tmplen += chunklen;
964         }
965     }
966     if (!EVP_CipherFinal_ex(ctx, tmp + out_misalign + tmplen, &tmpflen)) {
967         t->err = "CIPHERFINAL_ERROR";
968         goto err;
969     }
970     if (!enc && expected->tls_aad) {
971         if (expected->tls_version >= TLS1_1_VERSION
972             && (EVP_CIPHER_is_a(expected->cipher, "AES-128-CBC-HMAC-SHA1")
973                 || EVP_CIPHER_is_a(expected->cipher, "AES-256-CBC-HMAC-SHA1"))) {
974             tmplen -= expected->iv_len;
975             expected_out += expected->iv_len;
976             out_misalign += expected->iv_len;
977         }
978         if ((int)out_len > tmplen + tmpflen)
979             out_len = tmplen + tmpflen;
980     }
981     if (!memory_err_compare(t, "VALUE_MISMATCH", expected_out, out_len,
982                             tmp + out_misalign, tmplen + tmpflen))
983         goto err;
984     if (enc && expected->aead && !expected->tls_aad) {
985         unsigned char rtag[16];
986 
987         if (!TEST_size_t_le(expected->tag_len, sizeof(rtag))) {
988             t->err = "TAG_LENGTH_INTERNAL_ERROR";
989             goto err;
990         }
991         if (EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_GET_TAG,
992                                  expected->tag_len, rtag) <= 0) {
993             t->err = "TAG_RETRIEVE_ERROR";
994             goto err;
995         }
996         if (!memory_err_compare(t, "TAG_VALUE_MISMATCH",
997                                 expected->tag, expected->tag_len,
998                                 rtag, expected->tag_len))
999             goto err;
1000     }
1001     /* Check the updated IV */
1002     if (expected->next_iv != NULL) {
1003         /* Some (e.g., GCM) tests use IVs longer than EVP_MAX_IV_LENGTH. */
1004         unsigned char iv[128];
1005         if (!TEST_true(EVP_CIPHER_CTX_get_updated_iv(ctx, iv, sizeof(iv)))
1006             || ((EVP_CIPHER_get_flags(expected->cipher) & EVP_CIPH_CUSTOM_IV) == 0
1007                 && !TEST_mem_eq(expected->next_iv, expected->iv_len, iv,
1008                                 expected->iv_len))) {
1009             t->err = "INVALID_NEXT_IV";
1010             goto err;
1011         }
1012     }
1013 
1014     t->err = NULL;
1015     ok = 1;
1016  err:
1017     OPENSSL_free(tmp);
1018     if (ctx != ctx_base)
1019         EVP_CIPHER_CTX_free(ctx_base);
1020     EVP_CIPHER_CTX_free(ctx);
1021     return ok;
1022 }
1023 
1024 static int cipher_test_run(EVP_TEST *t)
1025 {
1026     CIPHER_DATA *cdat = t->data;
1027     int rv, frag = 0;
1028     size_t out_misalign, inp_misalign;
1029 
1030     TEST_info("RUNNING TEST FOR CIPHER %s\n", EVP_CIPHER_get0_name(cdat->cipher));
1031     if (!cdat->key) {
1032         t->err = "NO_KEY";
1033         return 0;
1034     }
1035     if (!cdat->iv && EVP_CIPHER_get_iv_length(cdat->cipher)) {
1036         /* IV is optional and usually omitted in wrap mode */
1037         if (EVP_CIPHER_get_mode(cdat->cipher) != EVP_CIPH_WRAP_MODE) {
1038             t->err = "NO_IV";
1039             return 0;
1040         }
1041     }
1042     if (cdat->aead && cdat->tag == NULL && !cdat->tls_aad) {
1043         t->err = "NO_TAG";
1044         return 0;
1045     }
1046     for (out_misalign = 0; out_misalign <= 1;) {
1047         static char aux_err[64];
1048         t->aux_err = aux_err;
1049         for (inp_misalign = (size_t)-1; inp_misalign != 2; inp_misalign++) {
1050             if (inp_misalign == (size_t)-1) {
1051                 /* kludge: inp_misalign == -1 means "exercise in-place" */
1052                 BIO_snprintf(aux_err, sizeof(aux_err),
1053                              "%s in-place, %sfragmented",
1054                              out_misalign ? "misaligned" : "aligned",
1055                              frag ? "" : "not ");
1056             } else {
1057                 BIO_snprintf(aux_err, sizeof(aux_err),
1058                              "%s output and %s input, %sfragmented",
1059                              out_misalign ? "misaligned" : "aligned",
1060                              inp_misalign ? "misaligned" : "aligned",
1061                              frag ? "" : "not ");
1062             }
1063             if (cdat->enc) {
1064                 rv = cipher_test_enc(t, 1, out_misalign, inp_misalign, frag);
1065                 /* Not fatal errors: return */
1066                 if (rv != 1) {
1067                     if (rv < 0)
1068                         return 0;
1069                     return 1;
1070                 }
1071             }
1072             if (cdat->enc != 1) {
1073                 rv = cipher_test_enc(t, 0, out_misalign, inp_misalign, frag);
1074                 /* Not fatal errors: return */
1075                 if (rv != 1) {
1076                     if (rv < 0)
1077                         return 0;
1078                     return 1;
1079                 }
1080             }
1081         }
1082 
1083         if (out_misalign == 1 && frag == 0) {
1084             /*
1085              * XTS, SIV, CCM, stitched ciphers and Wrap modes have special
1086              * requirements about input lengths so we don't fragment for those
1087              */
1088             if (cdat->aead == EVP_CIPH_CCM_MODE
1089                 || cdat->aead == EVP_CIPH_CBC_MODE
1090                 || (cdat->aead == -1
1091                     && EVP_CIPHER_get_mode(cdat->cipher) == EVP_CIPH_STREAM_CIPHER)
1092                 || ((EVP_CIPHER_get_flags(cdat->cipher) & EVP_CIPH_FLAG_CTS) != 0)
1093                 || EVP_CIPHER_get_mode(cdat->cipher) == EVP_CIPH_SIV_MODE
1094                 || EVP_CIPHER_get_mode(cdat->cipher) == EVP_CIPH_XTS_MODE
1095                 || EVP_CIPHER_get_mode(cdat->cipher) == EVP_CIPH_WRAP_MODE)
1096                 break;
1097             out_misalign = 0;
1098             frag++;
1099         } else {
1100             out_misalign++;
1101         }
1102     }
1103     t->aux_err = NULL;
1104 
1105     return 1;
1106 }
1107 
1108 static const EVP_TEST_METHOD cipher_test_method = {
1109     "Cipher",
1110     cipher_test_init,
1111     cipher_test_cleanup,
1112     cipher_test_parse,
1113     cipher_test_run
1114 };
1115 
1116 
1117 /**
1118  **  MAC TESTS
1119  **/
1120 
1121 typedef struct mac_data_st {
1122     /* MAC type in one form or another */
1123     char *mac_name;
1124     EVP_MAC *mac;                /* for mac_test_run_mac */
1125     int type;                    /* for mac_test_run_pkey */
1126     /* Algorithm string for this MAC */
1127     char *alg;
1128     /* MAC key */
1129     unsigned char *key;
1130     size_t key_len;
1131     /* MAC IV (GMAC) */
1132     unsigned char *iv;
1133     size_t iv_len;
1134     /* Input to MAC */
1135     unsigned char *input;
1136     size_t input_len;
1137     /* Expected output */
1138     unsigned char *output;
1139     size_t output_len;
1140     unsigned char *custom;
1141     size_t custom_len;
1142     /* MAC salt (blake2) */
1143     unsigned char *salt;
1144     size_t salt_len;
1145     /* XOF mode? */
1146     int xof;
1147     /* Reinitialization fails */
1148     int no_reinit;
1149     /* Collection of controls */
1150     STACK_OF(OPENSSL_STRING) *controls;
1151     /* Output size */
1152     int output_size;
1153     /* Block size */
1154     int block_size;
1155 } MAC_DATA;
1156 
1157 static int mac_test_init(EVP_TEST *t, const char *alg)
1158 {
1159     EVP_MAC *mac = NULL;
1160     int type = NID_undef;
1161     MAC_DATA *mdat;
1162 
1163     if (is_mac_disabled(alg)) {
1164         TEST_info("skipping, '%s' is disabled", alg);
1165         t->skip = 1;
1166         return 1;
1167     }
1168     if ((mac = EVP_MAC_fetch(libctx, alg, NULL)) == NULL) {
1169         /*
1170          * Since we didn't find an EVP_MAC, we check for known EVP_PKEY methods
1171          * For debugging purposes, we allow 'NNNN by EVP_PKEY' to force running
1172          * the EVP_PKEY method.
1173          */
1174         size_t sz = strlen(alg);
1175         static const char epilogue[] = " by EVP_PKEY";
1176 
1177         if (sz >= sizeof(epilogue)
1178             && strcmp(alg + sz - (sizeof(epilogue) - 1), epilogue) == 0)
1179             sz -= sizeof(epilogue) - 1;
1180 
1181         if (strncmp(alg, "HMAC", sz) == 0)
1182             type = EVP_PKEY_HMAC;
1183         else if (strncmp(alg, "CMAC", sz) == 0)
1184             type = EVP_PKEY_CMAC;
1185         else if (strncmp(alg, "Poly1305", sz) == 0)
1186             type = EVP_PKEY_POLY1305;
1187         else if (strncmp(alg, "SipHash", sz) == 0)
1188             type = EVP_PKEY_SIPHASH;
1189         else
1190             return 0;
1191     }
1192 
1193     if (!TEST_ptr(mdat = OPENSSL_zalloc(sizeof(*mdat))))
1194         return 0;
1195 
1196     mdat->type = type;
1197     if (!TEST_ptr(mdat->mac_name = OPENSSL_strdup(alg))) {
1198         OPENSSL_free(mdat);
1199         return 0;
1200     }
1201 
1202     mdat->mac = mac;
1203     if (!TEST_ptr(mdat->controls = sk_OPENSSL_STRING_new_null())) {
1204         OPENSSL_free(mdat->mac_name);
1205         OPENSSL_free(mdat);
1206         return 0;
1207     }
1208 
1209     mdat->output_size = mdat->block_size = -1;
1210     t->data = mdat;
1211     return 1;
1212 }
1213 
1214 /* Because OPENSSL_free is a macro, it can't be passed as a function pointer */
1215 static void openssl_free(char *m)
1216 {
1217     OPENSSL_free(m);
1218 }
1219 
1220 static void mac_test_cleanup(EVP_TEST *t)
1221 {
1222     MAC_DATA *mdat = t->data;
1223 
1224     EVP_MAC_free(mdat->mac);
1225     OPENSSL_free(mdat->mac_name);
1226     sk_OPENSSL_STRING_pop_free(mdat->controls, openssl_free);
1227     OPENSSL_free(mdat->alg);
1228     OPENSSL_free(mdat->key);
1229     OPENSSL_free(mdat->iv);
1230     OPENSSL_free(mdat->custom);
1231     OPENSSL_free(mdat->salt);
1232     OPENSSL_free(mdat->input);
1233     OPENSSL_free(mdat->output);
1234 }
1235 
1236 static int mac_test_parse(EVP_TEST *t,
1237                           const char *keyword, const char *value)
1238 {
1239     MAC_DATA *mdata = t->data;
1240 
1241     if (strcmp(keyword, "Key") == 0)
1242         return parse_bin(value, &mdata->key, &mdata->key_len);
1243     if (strcmp(keyword, "IV") == 0)
1244         return parse_bin(value, &mdata->iv, &mdata->iv_len);
1245     if (strcmp(keyword, "Custom") == 0)
1246         return parse_bin(value, &mdata->custom, &mdata->custom_len);
1247     if (strcmp(keyword, "Salt") == 0)
1248         return parse_bin(value, &mdata->salt, &mdata->salt_len);
1249     if (strcmp(keyword, "Algorithm") == 0) {
1250         mdata->alg = OPENSSL_strdup(value);
1251         if (mdata->alg == NULL)
1252             return -1;
1253         return 1;
1254     }
1255     if (strcmp(keyword, "Input") == 0)
1256         return parse_bin(value, &mdata->input, &mdata->input_len);
1257     if (strcmp(keyword, "Output") == 0)
1258         return parse_bin(value, &mdata->output, &mdata->output_len);
1259     if (strcmp(keyword, "XOF") == 0)
1260         return mdata->xof = 1;
1261     if (strcmp(keyword, "NoReinit") == 0)
1262         return mdata->no_reinit = 1;
1263     if (strcmp(keyword, "Ctrl") == 0) {
1264         char *data = OPENSSL_strdup(value);
1265 
1266         if (data == NULL)
1267             return -1;
1268         return sk_OPENSSL_STRING_push(mdata->controls, data) != 0;
1269     }
1270     if (strcmp(keyword, "OutputSize") == 0) {
1271         mdata->output_size = atoi(value);
1272         if (mdata->output_size < 0)
1273             return -1;
1274         return 1;
1275     }
1276     if (strcmp(keyword, "BlockSize") == 0) {
1277         mdata->block_size = atoi(value);
1278         if (mdata->block_size < 0)
1279             return -1;
1280         return 1;
1281     }
1282     return 0;
1283 }
1284 
1285 static int mac_test_ctrl_pkey(EVP_TEST *t, EVP_PKEY_CTX *pctx,
1286                               const char *value)
1287 {
1288     int rv = 0;
1289     char *p, *tmpval;
1290 
1291     if (!TEST_ptr(tmpval = OPENSSL_strdup(value)))
1292         return 0;
1293     p = strchr(tmpval, ':');
1294     if (p != NULL) {
1295         *p++ = '\0';
1296         rv = EVP_PKEY_CTX_ctrl_str(pctx, tmpval, p);
1297     }
1298     if (rv == -2)
1299         t->err = "PKEY_CTRL_INVALID";
1300     else if (rv <= 0)
1301         t->err = "PKEY_CTRL_ERROR";
1302     else
1303         rv = 1;
1304     OPENSSL_free(tmpval);
1305     return rv > 0;
1306 }
1307 
1308 static int mac_test_run_pkey(EVP_TEST *t)
1309 {
1310     MAC_DATA *expected = t->data;
1311     EVP_MD_CTX *mctx = NULL;
1312     EVP_PKEY_CTX *pctx = NULL, *genctx = NULL;
1313     EVP_PKEY *key = NULL;
1314     const char *mdname = NULL;
1315     EVP_CIPHER *cipher = NULL;
1316     unsigned char *got = NULL;
1317     size_t got_len;
1318     int i;
1319 
1320     /* We don't do XOF mode via PKEY */
1321     if (expected->xof)
1322         return 1;
1323 
1324     if (expected->alg == NULL)
1325         TEST_info("Trying the EVP_PKEY %s test", OBJ_nid2sn(expected->type));
1326     else
1327         TEST_info("Trying the EVP_PKEY %s test with %s",
1328                   OBJ_nid2sn(expected->type), expected->alg);
1329 
1330     if (expected->type == EVP_PKEY_CMAC) {
1331 #ifdef OPENSSL_NO_DEPRECATED_3_0
1332         TEST_info("skipping, PKEY CMAC '%s' is disabled", expected->alg);
1333         t->skip = 1;
1334         t->err = NULL;
1335         goto err;
1336 #else
1337         OSSL_LIB_CTX *tmpctx;
1338 
1339         if (expected->alg != NULL && is_cipher_disabled(expected->alg)) {
1340             TEST_info("skipping, PKEY CMAC '%s' is disabled", expected->alg);
1341             t->skip = 1;
1342             t->err = NULL;
1343             goto err;
1344         }
1345         if (!TEST_ptr(cipher = EVP_CIPHER_fetch(libctx, expected->alg, NULL))) {
1346             t->err = "MAC_KEY_CREATE_ERROR";
1347             goto err;
1348         }
1349         tmpctx = OSSL_LIB_CTX_set0_default(libctx);
1350         key = EVP_PKEY_new_CMAC_key(NULL, expected->key, expected->key_len,
1351                                     cipher);
1352         OSSL_LIB_CTX_set0_default(tmpctx);
1353 #endif
1354     } else {
1355         key = EVP_PKEY_new_raw_private_key_ex(libctx,
1356                                               OBJ_nid2sn(expected->type), NULL,
1357                                               expected->key, expected->key_len);
1358     }
1359     if (key == NULL) {
1360         t->err = "MAC_KEY_CREATE_ERROR";
1361         goto err;
1362     }
1363 
1364     if (expected->type == EVP_PKEY_HMAC && expected->alg != NULL) {
1365         if (is_digest_disabled(expected->alg)) {
1366             TEST_info("skipping, HMAC '%s' is disabled", expected->alg);
1367             t->skip = 1;
1368             t->err = NULL;
1369             goto err;
1370         }
1371         mdname = expected->alg;
1372     }
1373     if (!TEST_ptr(mctx = EVP_MD_CTX_new())) {
1374         t->err = "INTERNAL_ERROR";
1375         goto err;
1376     }
1377     if (!EVP_DigestSignInit_ex(mctx, &pctx, mdname, libctx, NULL, key, NULL)) {
1378         t->err = "DIGESTSIGNINIT_ERROR";
1379         goto err;
1380     }
1381     for (i = 0; i < sk_OPENSSL_STRING_num(expected->controls); i++)
1382         if (!mac_test_ctrl_pkey(t, pctx,
1383                                 sk_OPENSSL_STRING_value(expected->controls,
1384                                                         i))) {
1385             t->err = "EVPPKEYCTXCTRL_ERROR";
1386             goto err;
1387         }
1388     if (!EVP_DigestSignUpdate(mctx, expected->input, expected->input_len)) {
1389         t->err = "DIGESTSIGNUPDATE_ERROR";
1390         goto err;
1391     }
1392     if (!EVP_DigestSignFinal(mctx, NULL, &got_len)) {
1393         t->err = "DIGESTSIGNFINAL_LENGTH_ERROR";
1394         goto err;
1395     }
1396     if (!TEST_ptr(got = OPENSSL_malloc(got_len))) {
1397         t->err = "TEST_FAILURE";
1398         goto err;
1399     }
1400     if (!EVP_DigestSignFinal(mctx, got, &got_len)
1401             || !memory_err_compare(t, "TEST_MAC_ERR",
1402                                    expected->output, expected->output_len,
1403                                    got, got_len)) {
1404         t->err = "TEST_MAC_ERR";
1405         goto err;
1406     }
1407     t->err = NULL;
1408  err:
1409     EVP_CIPHER_free(cipher);
1410     EVP_MD_CTX_free(mctx);
1411     OPENSSL_free(got);
1412     EVP_PKEY_CTX_free(genctx);
1413     EVP_PKEY_free(key);
1414     return 1;
1415 }
1416 
1417 static int mac_test_run_mac(EVP_TEST *t)
1418 {
1419     MAC_DATA *expected = t->data;
1420     EVP_MAC_CTX *ctx = NULL;
1421     unsigned char *got = NULL;
1422     size_t got_len = 0, size = 0;
1423     size_t size_before_init = 0, size_after_init, size_val = 0;
1424     int i, block_size = -1, output_size = -1;
1425     OSSL_PARAM params[21], sizes[3], *psizes = sizes;
1426     size_t params_n = 0;
1427     size_t params_n_allocstart = 0;
1428     const OSSL_PARAM *defined_params =
1429         EVP_MAC_settable_ctx_params(expected->mac);
1430     int xof;
1431     int reinit = 1;
1432 
1433     if (expected->alg == NULL)
1434         TEST_info("Trying the EVP_MAC %s test", expected->mac_name);
1435     else
1436         TEST_info("Trying the EVP_MAC %s test with %s",
1437                   expected->mac_name, expected->alg);
1438 
1439     if (expected->alg != NULL) {
1440         int skip = 0;
1441 
1442         /*
1443          * The underlying algorithm may be a cipher or a digest.
1444          * We don't know which it is, but we can ask the MAC what it
1445          * should be and bet on that.
1446          */
1447         if (OSSL_PARAM_locate_const(defined_params,
1448                                     OSSL_MAC_PARAM_CIPHER) != NULL) {
1449             if (is_cipher_disabled(expected->alg))
1450                 skip = 1;
1451             else
1452                 params[params_n++] =
1453                     OSSL_PARAM_construct_utf8_string(OSSL_MAC_PARAM_CIPHER,
1454                                                      expected->alg, 0);
1455         } else if (OSSL_PARAM_locate_const(defined_params,
1456                                            OSSL_MAC_PARAM_DIGEST) != NULL) {
1457             if (is_digest_disabled(expected->alg))
1458                 skip = 1;
1459             else
1460                 params[params_n++] =
1461                     OSSL_PARAM_construct_utf8_string(OSSL_MAC_PARAM_DIGEST,
1462                                                      expected->alg, 0);
1463         } else {
1464             t->err = "MAC_BAD_PARAMS";
1465             goto err;
1466         }
1467         if (skip) {
1468             TEST_info("skipping, algorithm '%s' is disabled", expected->alg);
1469             t->skip = 1;
1470             t->err = NULL;
1471             goto err;
1472         }
1473     }
1474     if (expected->custom != NULL)
1475         params[params_n++] =
1476             OSSL_PARAM_construct_octet_string(OSSL_MAC_PARAM_CUSTOM,
1477                                               expected->custom,
1478                                               expected->custom_len);
1479     if (expected->salt != NULL)
1480         params[params_n++] =
1481             OSSL_PARAM_construct_octet_string(OSSL_MAC_PARAM_SALT,
1482                                               expected->salt,
1483                                               expected->salt_len);
1484     if (expected->iv != NULL)
1485         params[params_n++] =
1486             OSSL_PARAM_construct_octet_string(OSSL_MAC_PARAM_IV,
1487                                               expected->iv,
1488                                               expected->iv_len);
1489 
1490     /* Unknown controls.  They must match parameters that the MAC recognizes */
1491     if (params_n + sk_OPENSSL_STRING_num(expected->controls)
1492         >= OSSL_NELEM(params)) {
1493         t->err = "MAC_TOO_MANY_PARAMETERS";
1494         goto err;
1495     }
1496     params_n_allocstart = params_n;
1497     for (i = 0; i < sk_OPENSSL_STRING_num(expected->controls); i++) {
1498         char *tmpkey, *tmpval;
1499         char *value = sk_OPENSSL_STRING_value(expected->controls, i);
1500 
1501         if (!TEST_ptr(tmpkey = OPENSSL_strdup(value))) {
1502             t->err = "MAC_PARAM_ERROR";
1503             goto err;
1504         }
1505         tmpval = strchr(tmpkey, ':');
1506         if (tmpval != NULL)
1507             *tmpval++ = '\0';
1508 
1509         if (tmpval == NULL
1510             || !OSSL_PARAM_allocate_from_text(&params[params_n],
1511                                               defined_params,
1512                                               tmpkey, tmpval,
1513                                               strlen(tmpval), NULL)) {
1514             OPENSSL_free(tmpkey);
1515             t->err = "MAC_PARAM_ERROR";
1516             goto err;
1517         }
1518         params_n++;
1519 
1520         if (strcmp(tmpkey, "size") == 0)
1521             size_val = (size_t)strtoul(tmpval, NULL, 0);
1522 
1523         OPENSSL_free(tmpkey);
1524     }
1525     params[params_n] = OSSL_PARAM_construct_end();
1526 
1527     if ((ctx = EVP_MAC_CTX_new(expected->mac)) == NULL) {
1528         t->err = "MAC_CREATE_ERROR";
1529         goto err;
1530     }
1531     if (fips_provider_version_gt(libctx, 3, 1, 4)
1532         || (fips_provider_version_lt(libctx, 3, 1, 0)
1533             && fips_provider_version_gt(libctx, 3, 0, 12)))
1534         size_before_init = EVP_MAC_CTX_get_mac_size(ctx);
1535     if (!EVP_MAC_init(ctx, expected->key, expected->key_len, params)) {
1536         t->err = "MAC_INIT_ERROR";
1537         goto err;
1538     }
1539     size_after_init = EVP_MAC_CTX_get_mac_size(ctx);
1540     if (!TEST_false(size_before_init == 0 && size_after_init == 0)) {
1541         t->err = "MAC SIZE not set";
1542         goto err;
1543     }
1544     if (size_before_init != 0) {
1545         /* mac-size not modified by init params */
1546         if (size_val == 0 && !TEST_size_t_eq(size_before_init, size_after_init)) {
1547             t->err = "MAC SIZE check failed";
1548             goto err;
1549         }
1550         /* mac-size modified by init params */
1551         if (size_val != 0 && !TEST_size_t_eq(size_val, size_after_init)) {
1552             t->err = "MAC SIZE check failed";
1553             goto err;
1554         }
1555     }
1556     if (expected->output_size >= 0)
1557         *psizes++ = OSSL_PARAM_construct_int(OSSL_MAC_PARAM_SIZE,
1558                                              &output_size);
1559     if (expected->block_size >= 0)
1560         *psizes++ = OSSL_PARAM_construct_int(OSSL_MAC_PARAM_BLOCK_SIZE,
1561                                              &block_size);
1562     if (psizes != sizes) {
1563         *psizes = OSSL_PARAM_construct_end();
1564         if (!TEST_true(EVP_MAC_CTX_get_params(ctx, sizes))) {
1565             t->err = "INTERNAL_ERROR";
1566             goto err;
1567         }
1568         if (expected->output_size >= 0
1569                 && !TEST_int_eq(output_size, expected->output_size)) {
1570             t->err = "TEST_FAILURE";
1571             goto err;
1572         }
1573         if (expected->block_size >= 0
1574                 && !TEST_int_eq(block_size, expected->block_size)) {
1575             t->err = "TEST_FAILURE";
1576             goto err;
1577         }
1578     }
1579  retry:
1580     if (!EVP_MAC_update(ctx, expected->input, expected->input_len)) {
1581         t->err = "MAC_UPDATE_ERROR";
1582         goto err;
1583     }
1584     xof = expected->xof;
1585     if (xof) {
1586         if (!TEST_ptr(got = OPENSSL_malloc(expected->output_len))) {
1587             t->err = "TEST_FAILURE";
1588             goto err;
1589         }
1590         if (!EVP_MAC_finalXOF(ctx, got, expected->output_len)
1591             || !memory_err_compare(t, "TEST_MAC_ERR",
1592                                    expected->output, expected->output_len,
1593                                    got, expected->output_len)) {
1594             t->err = "MAC_FINAL_ERROR";
1595             goto err;
1596         }
1597     } else {
1598         if (!EVP_MAC_final(ctx, NULL, &got_len, 0)) {
1599             t->err = "MAC_FINAL_LENGTH_ERROR";
1600             goto err;
1601         }
1602         if (!TEST_ptr(got = OPENSSL_malloc(got_len))) {
1603             t->err = "TEST_FAILURE";
1604             goto err;
1605         }
1606         if (!EVP_MAC_final(ctx, got, &got_len, got_len)
1607             || !memory_err_compare(t, "TEST_MAC_ERR",
1608                                    expected->output, expected->output_len,
1609                                    got, got_len)) {
1610             t->err = "TEST_MAC_ERR";
1611             goto err;
1612         }
1613     }
1614     /* FIPS(3.0.0): can't reinitialise MAC contexts #18100 */
1615     if (reinit-- && fips_provider_version_gt(libctx, 3, 0, 0)) {
1616         OSSL_PARAM ivparams[2] = { OSSL_PARAM_END, OSSL_PARAM_END };
1617         int ret;
1618 
1619         /* If the MAC uses IV, we have to set it again */
1620         if (expected->iv != NULL) {
1621             ivparams[0] =
1622                 OSSL_PARAM_construct_octet_string(OSSL_MAC_PARAM_IV,
1623                                                   expected->iv,
1624                                                   expected->iv_len);
1625             ivparams[1] = OSSL_PARAM_construct_end();
1626         }
1627         ERR_set_mark();
1628         ret = EVP_MAC_init(ctx, NULL, 0, ivparams);
1629         if (expected->no_reinit) {
1630             if (ret) {
1631                 ERR_clear_last_mark();
1632                 t->err = "MAC_REINIT_SHOULD_FAIL";
1633                 goto err;
1634             }
1635         } else if (ret) {
1636             ERR_clear_last_mark();
1637             OPENSSL_free(got);
1638             got = NULL;
1639             goto retry;
1640         } else {
1641             ERR_clear_last_mark();
1642             t->err = "MAC_REINIT_ERROR";
1643             goto err;
1644         }
1645         /* If reinitialization fails, it is unsupported by the algorithm */
1646         ERR_pop_to_mark();
1647     }
1648     t->err = NULL;
1649 
1650     /* Test the EVP_Q_mac interface as well */
1651     if (!xof) {
1652         OPENSSL_cleanse(got, got_len);
1653         if (!TEST_true(EVP_Q_mac(libctx, expected->mac_name, NULL,
1654                                  expected->alg, params,
1655                                  expected->key, expected->key_len,
1656                                  expected->input, expected->input_len,
1657                                  got, got_len, &size))
1658                 || !TEST_mem_eq(got, size,
1659                                 expected->output, expected->output_len)) {
1660             t->err = "EVP_Q_mac failed";
1661             goto err;
1662         }
1663     }
1664  err:
1665     while (params_n-- > params_n_allocstart) {
1666         OPENSSL_free(params[params_n].data);
1667     }
1668     EVP_MAC_CTX_free(ctx);
1669     OPENSSL_free(got);
1670     return 1;
1671 }
1672 
1673 static int mac_test_run(EVP_TEST *t)
1674 {
1675     MAC_DATA *expected = t->data;
1676 
1677     if (expected->mac != NULL)
1678         return mac_test_run_mac(t);
1679     return mac_test_run_pkey(t);
1680 }
1681 
1682 static const EVP_TEST_METHOD mac_test_method = {
1683     "MAC",
1684     mac_test_init,
1685     mac_test_cleanup,
1686     mac_test_parse,
1687     mac_test_run
1688 };
1689 
1690 
1691 /**
1692  **  PUBLIC KEY TESTS
1693  **  These are all very similar and share much common code.
1694  **/
1695 
1696 typedef struct pkey_data_st {
1697     /* Context for this operation */
1698     EVP_PKEY_CTX *ctx;
1699     /* Key operation to perform */
1700     int (*keyop) (EVP_PKEY_CTX *ctx,
1701                   unsigned char *sig, size_t *siglen,
1702                   const unsigned char *tbs, size_t tbslen);
1703     /* Input to MAC */
1704     unsigned char *input;
1705     size_t input_len;
1706     /* Expected output */
1707     unsigned char *output;
1708     size_t output_len;
1709 } PKEY_DATA;
1710 
1711 /*
1712  * Perform public key operation setup: lookup key, allocated ctx and call
1713  * the appropriate initialisation function
1714  */
1715 static int pkey_test_init(EVP_TEST *t, const char *name,
1716                           int use_public,
1717                           int (*keyopinit) (EVP_PKEY_CTX *ctx),
1718                           int (*keyop)(EVP_PKEY_CTX *ctx,
1719                                        unsigned char *sig, size_t *siglen,
1720                                        const unsigned char *tbs,
1721                                        size_t tbslen))
1722 {
1723     PKEY_DATA *kdata;
1724     EVP_PKEY *pkey = NULL;
1725     int rv = 0;
1726 
1727     if (use_public)
1728         rv = find_key(&pkey, name, public_keys);
1729     if (rv == 0)
1730         rv = find_key(&pkey, name, private_keys);
1731     if (rv == 0 || pkey == NULL) {
1732         TEST_info("skipping, key '%s' is disabled", name);
1733         t->skip = 1;
1734         return 1;
1735     }
1736 
1737     if (!TEST_ptr(kdata = OPENSSL_zalloc(sizeof(*kdata)))) {
1738         EVP_PKEY_free(pkey);
1739         return 0;
1740     }
1741     kdata->keyop = keyop;
1742     if (!TEST_ptr(kdata->ctx = EVP_PKEY_CTX_new_from_pkey(libctx, pkey, NULL))) {
1743         EVP_PKEY_free(pkey);
1744         OPENSSL_free(kdata);
1745         return 0;
1746     }
1747     if (keyopinit(kdata->ctx) <= 0)
1748         t->err = "KEYOP_INIT_ERROR";
1749     t->data = kdata;
1750     return 1;
1751 }
1752 
1753 static void pkey_test_cleanup(EVP_TEST *t)
1754 {
1755     PKEY_DATA *kdata = t->data;
1756 
1757     OPENSSL_free(kdata->input);
1758     OPENSSL_free(kdata->output);
1759     EVP_PKEY_CTX_free(kdata->ctx);
1760 }
1761 
1762 static int pkey_test_ctrl(EVP_TEST *t, EVP_PKEY_CTX *pctx,
1763                           const char *value)
1764 {
1765     int rv = 0;
1766     char *p, *tmpval;
1767 
1768     if (!TEST_ptr(tmpval = OPENSSL_strdup(value)))
1769         return 0;
1770     p = strchr(tmpval, ':');
1771     if (p != NULL) {
1772         *p++ = '\0';
1773         rv = EVP_PKEY_CTX_ctrl_str(pctx, tmpval, p);
1774     }
1775     if (rv == -2) {
1776         t->err = "PKEY_CTRL_INVALID";
1777         rv = 1;
1778     } else if (p != NULL && rv <= 0) {
1779         if (is_digest_disabled(p) || is_cipher_disabled(p)) {
1780             TEST_info("skipping, '%s' is disabled", p);
1781             t->skip = 1;
1782             rv = 1;
1783         } else {
1784             t->err = "PKEY_CTRL_ERROR";
1785             rv = 1;
1786         }
1787     }
1788     OPENSSL_free(tmpval);
1789     return rv > 0;
1790 }
1791 
1792 static int pkey_test_parse(EVP_TEST *t,
1793                            const char *keyword, const char *value)
1794 {
1795     PKEY_DATA *kdata = t->data;
1796     if (strcmp(keyword, "Input") == 0)
1797         return parse_bin(value, &kdata->input, &kdata->input_len);
1798     if (strcmp(keyword, "Output") == 0)
1799         return parse_bin(value, &kdata->output, &kdata->output_len);
1800     if (strcmp(keyword, "Ctrl") == 0)
1801         return pkey_test_ctrl(t, kdata->ctx, value);
1802     return 0;
1803 }
1804 
1805 static int pkey_test_run(EVP_TEST *t)
1806 {
1807     PKEY_DATA *expected = t->data;
1808     unsigned char *got = NULL;
1809     size_t got_len;
1810     EVP_PKEY_CTX *copy = NULL;
1811 
1812     if (expected->keyop(expected->ctx, NULL, &got_len,
1813                         expected->input, expected->input_len) <= 0
1814             || !TEST_ptr(got = OPENSSL_malloc(got_len))) {
1815         t->err = "KEYOP_LENGTH_ERROR";
1816         goto err;
1817     }
1818     if (expected->keyop(expected->ctx, got, &got_len,
1819                         expected->input, expected->input_len) <= 0) {
1820         t->err = "KEYOP_ERROR";
1821         goto err;
1822     }
1823     if (!memory_err_compare(t, "KEYOP_MISMATCH",
1824                             expected->output, expected->output_len,
1825                             got, got_len))
1826         goto err;
1827 
1828     t->err = NULL;
1829     OPENSSL_free(got);
1830     got = NULL;
1831 
1832     /* Repeat the test on a copy. */
1833     if (!TEST_ptr(copy = EVP_PKEY_CTX_dup(expected->ctx))) {
1834         t->err = "INTERNAL_ERROR";
1835         goto err;
1836     }
1837     if (expected->keyop(copy, NULL, &got_len, expected->input,
1838                         expected->input_len) <= 0
1839             || !TEST_ptr(got = OPENSSL_malloc(got_len))) {
1840         t->err = "KEYOP_LENGTH_ERROR";
1841         goto err;
1842     }
1843     if (expected->keyop(copy, got, &got_len, expected->input,
1844                         expected->input_len) <= 0) {
1845         t->err = "KEYOP_ERROR";
1846         goto err;
1847     }
1848     if (!memory_err_compare(t, "KEYOP_MISMATCH",
1849                             expected->output, expected->output_len,
1850                             got, got_len))
1851         goto err;
1852 
1853  err:
1854     OPENSSL_free(got);
1855     EVP_PKEY_CTX_free(copy);
1856     return 1;
1857 }
1858 
1859 static int sign_test_init(EVP_TEST *t, const char *name)
1860 {
1861     return pkey_test_init(t, name, 0, EVP_PKEY_sign_init, EVP_PKEY_sign);
1862 }
1863 
1864 static const EVP_TEST_METHOD psign_test_method = {
1865     "Sign",
1866     sign_test_init,
1867     pkey_test_cleanup,
1868     pkey_test_parse,
1869     pkey_test_run
1870 };
1871 
1872 static int verify_recover_test_init(EVP_TEST *t, const char *name)
1873 {
1874     return pkey_test_init(t, name, 1, EVP_PKEY_verify_recover_init,
1875                           EVP_PKEY_verify_recover);
1876 }
1877 
1878 static const EVP_TEST_METHOD pverify_recover_test_method = {
1879     "VerifyRecover",
1880     verify_recover_test_init,
1881     pkey_test_cleanup,
1882     pkey_test_parse,
1883     pkey_test_run
1884 };
1885 
1886 static int decrypt_test_init(EVP_TEST *t, const char *name)
1887 {
1888     return pkey_test_init(t, name, 0, EVP_PKEY_decrypt_init,
1889                           EVP_PKEY_decrypt);
1890 }
1891 
1892 static const EVP_TEST_METHOD pdecrypt_test_method = {
1893     "Decrypt",
1894     decrypt_test_init,
1895     pkey_test_cleanup,
1896     pkey_test_parse,
1897     pkey_test_run
1898 };
1899 
1900 static int verify_test_init(EVP_TEST *t, const char *name)
1901 {
1902     return pkey_test_init(t, name, 1, EVP_PKEY_verify_init, 0);
1903 }
1904 
1905 static int verify_test_run(EVP_TEST *t)
1906 {
1907     PKEY_DATA *kdata = t->data;
1908 
1909     if (EVP_PKEY_verify(kdata->ctx, kdata->output, kdata->output_len,
1910                         kdata->input, kdata->input_len) <= 0)
1911         t->err = "VERIFY_ERROR";
1912     return 1;
1913 }
1914 
1915 static const EVP_TEST_METHOD pverify_test_method = {
1916     "Verify",
1917     verify_test_init,
1918     pkey_test_cleanup,
1919     pkey_test_parse,
1920     verify_test_run
1921 };
1922 
1923 static int pderive_test_init(EVP_TEST *t, const char *name)
1924 {
1925     return pkey_test_init(t, name, 0, EVP_PKEY_derive_init, 0);
1926 }
1927 
1928 static int pderive_test_parse(EVP_TEST *t,
1929                               const char *keyword, const char *value)
1930 {
1931     PKEY_DATA *kdata = t->data;
1932     int validate = 0;
1933 
1934     if (strcmp(keyword, "PeerKeyValidate") == 0)
1935         validate = 1;
1936 
1937     if (validate || strcmp(keyword, "PeerKey") == 0) {
1938         EVP_PKEY *peer;
1939         if (find_key(&peer, value, public_keys) == 0)
1940             return -1;
1941         if (EVP_PKEY_derive_set_peer_ex(kdata->ctx, peer, validate) <= 0) {
1942             t->err = "DERIVE_SET_PEER_ERROR";
1943             return 1;
1944         }
1945         t->err = NULL;
1946         return 1;
1947     }
1948     if (strcmp(keyword, "SharedSecret") == 0)
1949         return parse_bin(value, &kdata->output, &kdata->output_len);
1950     if (strcmp(keyword, "Ctrl") == 0)
1951         return pkey_test_ctrl(t, kdata->ctx, value);
1952     if (strcmp(keyword, "KDFType") == 0) {
1953         OSSL_PARAM params[2];
1954 
1955         params[0] = OSSL_PARAM_construct_utf8_string(OSSL_EXCHANGE_PARAM_KDF_TYPE,
1956                                                      (char *)value, 0);
1957         params[1] = OSSL_PARAM_construct_end();
1958         if (EVP_PKEY_CTX_set_params(kdata->ctx, params) == 0)
1959             return -1;
1960         return 1;
1961     }
1962     if (strcmp(keyword, "KDFDigest") == 0) {
1963         OSSL_PARAM params[2];
1964 
1965         params[0] = OSSL_PARAM_construct_utf8_string(OSSL_EXCHANGE_PARAM_KDF_DIGEST,
1966                                                      (char *)value, 0);
1967         params[1] = OSSL_PARAM_construct_end();
1968         if (EVP_PKEY_CTX_set_params(kdata->ctx, params) == 0)
1969             return -1;
1970         return 1;
1971     }
1972     if (strcmp(keyword, "CEKAlg") == 0) {
1973         OSSL_PARAM params[2];
1974 
1975         params[0] = OSSL_PARAM_construct_utf8_string(OSSL_KDF_PARAM_CEK_ALG,
1976                                                      (char *)value, 0);
1977         params[1] = OSSL_PARAM_construct_end();
1978         if (EVP_PKEY_CTX_set_params(kdata->ctx, params) == 0)
1979             return -1;
1980         return 1;
1981     }
1982     if (strcmp(keyword, "KDFOutlen") == 0) {
1983         OSSL_PARAM params[2];
1984         char *endptr;
1985         size_t outlen = (size_t)strtoul(value, &endptr, 0);
1986 
1987         if (endptr[0] != '\0')
1988             return -1;
1989 
1990         params[0] = OSSL_PARAM_construct_size_t(OSSL_EXCHANGE_PARAM_KDF_OUTLEN,
1991                                                 &outlen);
1992         params[1] = OSSL_PARAM_construct_end();
1993         if (EVP_PKEY_CTX_set_params(kdata->ctx, params) == 0)
1994             return -1;
1995         return 1;
1996     }
1997     return 0;
1998 }
1999 
2000 static int pderive_test_run(EVP_TEST *t)
2001 {
2002     EVP_PKEY_CTX *dctx = NULL;
2003     PKEY_DATA *expected = t->data;
2004     unsigned char *got = NULL;
2005     size_t got_len;
2006 
2007     if (!TEST_ptr(dctx = EVP_PKEY_CTX_dup(expected->ctx))) {
2008         t->err = "DERIVE_ERROR";
2009         goto err;
2010     }
2011 
2012     if (EVP_PKEY_derive(dctx, NULL, &got_len) <= 0
2013         || !TEST_size_t_ne(got_len, 0)) {
2014         t->err = "DERIVE_ERROR";
2015         goto err;
2016     }
2017     if (!TEST_ptr(got = OPENSSL_malloc(got_len))) {
2018         t->err = "DERIVE_ERROR";
2019         goto err;
2020     }
2021     if (EVP_PKEY_derive(dctx, got, &got_len) <= 0) {
2022         t->err = "DERIVE_ERROR";
2023         goto err;
2024     }
2025     if (!memory_err_compare(t, "SHARED_SECRET_MISMATCH",
2026                             expected->output, expected->output_len,
2027                             got, got_len))
2028         goto err;
2029 
2030     t->err = NULL;
2031  err:
2032     OPENSSL_free(got);
2033     EVP_PKEY_CTX_free(dctx);
2034     return 1;
2035 }
2036 
2037 static const EVP_TEST_METHOD pderive_test_method = {
2038     "Derive",
2039     pderive_test_init,
2040     pkey_test_cleanup,
2041     pderive_test_parse,
2042     pderive_test_run
2043 };
2044 
2045 
2046 /**
2047  **  PBE TESTS
2048  **/
2049 
2050 typedef enum pbe_type_enum {
2051     PBE_TYPE_INVALID = 0,
2052     PBE_TYPE_SCRYPT, PBE_TYPE_PBKDF2, PBE_TYPE_PKCS12
2053 } PBE_TYPE;
2054 
2055 typedef struct pbe_data_st {
2056     PBE_TYPE pbe_type;
2057         /* scrypt parameters */
2058     uint64_t N, r, p, maxmem;
2059         /* PKCS#12 parameters */
2060     int id, iter;
2061     const EVP_MD *md;
2062         /* password */
2063     unsigned char *pass;
2064     size_t pass_len;
2065         /* salt */
2066     unsigned char *salt;
2067     size_t salt_len;
2068         /* Expected output */
2069     unsigned char *key;
2070     size_t key_len;
2071 } PBE_DATA;
2072 
2073 #ifndef OPENSSL_NO_SCRYPT
2074 /* Parse unsigned decimal 64 bit integer value */
2075 static int parse_uint64(const char *value, uint64_t *pr)
2076 {
2077     const char *p = value;
2078 
2079     if (!TEST_true(*p)) {
2080         TEST_info("Invalid empty integer value");
2081         return -1;
2082     }
2083     for (*pr = 0; *p; ) {
2084         if (*pr > UINT64_MAX / 10) {
2085             TEST_error("Integer overflow in string %s", value);
2086             return -1;
2087         }
2088         *pr *= 10;
2089         if (!TEST_true(isdigit((unsigned char)*p))) {
2090             TEST_error("Invalid character in string %s", value);
2091             return -1;
2092         }
2093         *pr += *p - '0';
2094         p++;
2095     }
2096     return 1;
2097 }
2098 
2099 static int scrypt_test_parse(EVP_TEST *t,
2100                              const char *keyword, const char *value)
2101 {
2102     PBE_DATA *pdata = t->data;
2103 
2104     if (strcmp(keyword, "N") == 0)
2105         return parse_uint64(value, &pdata->N);
2106     if (strcmp(keyword, "p") == 0)
2107         return parse_uint64(value, &pdata->p);
2108     if (strcmp(keyword, "r") == 0)
2109         return parse_uint64(value, &pdata->r);
2110     if (strcmp(keyword, "maxmem") == 0)
2111         return parse_uint64(value, &pdata->maxmem);
2112     return 0;
2113 }
2114 #endif
2115 
2116 static int pbkdf2_test_parse(EVP_TEST *t,
2117                              const char *keyword, const char *value)
2118 {
2119     PBE_DATA *pdata = t->data;
2120 
2121     if (strcmp(keyword, "iter") == 0) {
2122         pdata->iter = atoi(value);
2123         if (pdata->iter <= 0)
2124             return -1;
2125         return 1;
2126     }
2127     if (strcmp(keyword, "MD") == 0) {
2128         pdata->md = EVP_get_digestbyname(value);
2129         if (pdata->md == NULL)
2130             return -1;
2131         return 1;
2132     }
2133     return 0;
2134 }
2135 
2136 static int pkcs12_test_parse(EVP_TEST *t,
2137                              const char *keyword, const char *value)
2138 {
2139     PBE_DATA *pdata = t->data;
2140 
2141     if (strcmp(keyword, "id") == 0) {
2142         pdata->id = atoi(value);
2143         if (pdata->id <= 0)
2144             return -1;
2145         return 1;
2146     }
2147     return pbkdf2_test_parse(t, keyword, value);
2148 }
2149 
2150 static int pbe_test_init(EVP_TEST *t, const char *alg)
2151 {
2152     PBE_DATA *pdat;
2153     PBE_TYPE pbe_type = PBE_TYPE_INVALID;
2154 
2155     if (is_kdf_disabled(alg)) {
2156         TEST_info("skipping, '%s' is disabled", alg);
2157         t->skip = 1;
2158         return 1;
2159     }
2160     if (strcmp(alg, "scrypt") == 0) {
2161         pbe_type = PBE_TYPE_SCRYPT;
2162     } else if (strcmp(alg, "pbkdf2") == 0) {
2163         pbe_type = PBE_TYPE_PBKDF2;
2164     } else if (strcmp(alg, "pkcs12") == 0) {
2165         pbe_type = PBE_TYPE_PKCS12;
2166     } else {
2167         TEST_error("Unknown pbe algorithm %s", alg);
2168         return 0;
2169     }
2170     if (!TEST_ptr(pdat = OPENSSL_zalloc(sizeof(*pdat))))
2171         return 0;
2172     pdat->pbe_type = pbe_type;
2173     t->data = pdat;
2174     return 1;
2175 }
2176 
2177 static void pbe_test_cleanup(EVP_TEST *t)
2178 {
2179     PBE_DATA *pdat = t->data;
2180 
2181     OPENSSL_free(pdat->pass);
2182     OPENSSL_free(pdat->salt);
2183     OPENSSL_free(pdat->key);
2184 }
2185 
2186 static int pbe_test_parse(EVP_TEST *t,
2187                           const char *keyword, const char *value)
2188 {
2189     PBE_DATA *pdata = t->data;
2190 
2191     if (strcmp(keyword, "Password") == 0)
2192         return parse_bin(value, &pdata->pass, &pdata->pass_len);
2193     if (strcmp(keyword, "Salt") == 0)
2194         return parse_bin(value, &pdata->salt, &pdata->salt_len);
2195     if (strcmp(keyword, "Key") == 0)
2196         return parse_bin(value, &pdata->key, &pdata->key_len);
2197     if (pdata->pbe_type == PBE_TYPE_PBKDF2)
2198         return pbkdf2_test_parse(t, keyword, value);
2199     else if (pdata->pbe_type == PBE_TYPE_PKCS12)
2200         return pkcs12_test_parse(t, keyword, value);
2201 #ifndef OPENSSL_NO_SCRYPT
2202     else if (pdata->pbe_type == PBE_TYPE_SCRYPT)
2203         return scrypt_test_parse(t, keyword, value);
2204 #endif
2205     return 0;
2206 }
2207 
2208 static int pbe_test_run(EVP_TEST *t)
2209 {
2210     PBE_DATA *expected = t->data;
2211     unsigned char *key;
2212     EVP_MD *fetched_digest = NULL;
2213     OSSL_LIB_CTX *save_libctx;
2214 
2215     save_libctx = OSSL_LIB_CTX_set0_default(libctx);
2216 
2217     if (!TEST_ptr(key = OPENSSL_malloc(expected->key_len))) {
2218         t->err = "INTERNAL_ERROR";
2219         goto err;
2220     }
2221     if (expected->pbe_type == PBE_TYPE_PBKDF2) {
2222         if (PKCS5_PBKDF2_HMAC((char *)expected->pass, expected->pass_len,
2223                               expected->salt, expected->salt_len,
2224                               expected->iter, expected->md,
2225                               expected->key_len, key) == 0) {
2226             t->err = "PBKDF2_ERROR";
2227             goto err;
2228         }
2229 #ifndef OPENSSL_NO_SCRYPT
2230     } else if (expected->pbe_type == PBE_TYPE_SCRYPT) {
2231         if (EVP_PBE_scrypt((const char *)expected->pass, expected->pass_len,
2232                             expected->salt, expected->salt_len,
2233                             expected->N, expected->r, expected->p,
2234                             expected->maxmem, key, expected->key_len) == 0) {
2235             t->err = "SCRYPT_ERROR";
2236             goto err;
2237         }
2238 #endif
2239     } else if (expected->pbe_type == PBE_TYPE_PKCS12) {
2240         fetched_digest = EVP_MD_fetch(libctx, EVP_MD_get0_name(expected->md),
2241                                       NULL);
2242         if (fetched_digest == NULL) {
2243             t->err = "PKCS12_ERROR";
2244             goto err;
2245         }
2246         if (PKCS12_key_gen_uni(expected->pass, expected->pass_len,
2247                                expected->salt, expected->salt_len,
2248                                expected->id, expected->iter, expected->key_len,
2249                                key, fetched_digest) == 0) {
2250             t->err = "PKCS12_ERROR";
2251             goto err;
2252         }
2253     }
2254     if (!memory_err_compare(t, "KEY_MISMATCH", expected->key, expected->key_len,
2255                             key, expected->key_len))
2256         goto err;
2257 
2258     t->err = NULL;
2259 err:
2260     EVP_MD_free(fetched_digest);
2261     OPENSSL_free(key);
2262     OSSL_LIB_CTX_set0_default(save_libctx);
2263     return 1;
2264 }
2265 
2266 static const EVP_TEST_METHOD pbe_test_method = {
2267     "PBE",
2268     pbe_test_init,
2269     pbe_test_cleanup,
2270     pbe_test_parse,
2271     pbe_test_run
2272 };
2273 
2274 
2275 /**
2276  **  BASE64 TESTS
2277  **/
2278 
2279 typedef enum {
2280     BASE64_CANONICAL_ENCODING = 0,
2281     BASE64_VALID_ENCODING = 1,
2282     BASE64_INVALID_ENCODING = 2
2283 } base64_encoding_type;
2284 
2285 typedef struct encode_data_st {
2286     /* Input to encoding */
2287     unsigned char *input;
2288     size_t input_len;
2289     /* Expected output */
2290     unsigned char *output;
2291     size_t output_len;
2292     base64_encoding_type encoding;
2293 } ENCODE_DATA;
2294 
2295 static int encode_test_init(EVP_TEST *t, const char *encoding)
2296 {
2297     ENCODE_DATA *edata;
2298 
2299     if (!TEST_ptr(edata = OPENSSL_zalloc(sizeof(*edata))))
2300         return 0;
2301     if (strcmp(encoding, "canonical") == 0) {
2302         edata->encoding = BASE64_CANONICAL_ENCODING;
2303     } else if (strcmp(encoding, "valid") == 0) {
2304         edata->encoding = BASE64_VALID_ENCODING;
2305     } else if (strcmp(encoding, "invalid") == 0) {
2306         edata->encoding = BASE64_INVALID_ENCODING;
2307         if (!TEST_ptr(t->expected_err = OPENSSL_strdup("DECODE_ERROR")))
2308             goto err;
2309     } else {
2310         TEST_error("Bad encoding: %s."
2311                    " Should be one of {canonical, valid, invalid}",
2312                    encoding);
2313         goto err;
2314     }
2315     t->data = edata;
2316     return 1;
2317 err:
2318     OPENSSL_free(edata);
2319     return 0;
2320 }
2321 
2322 static void encode_test_cleanup(EVP_TEST *t)
2323 {
2324     ENCODE_DATA *edata = t->data;
2325 
2326     OPENSSL_free(edata->input);
2327     OPENSSL_free(edata->output);
2328     memset(edata, 0, sizeof(*edata));
2329 }
2330 
2331 static int encode_test_parse(EVP_TEST *t,
2332                              const char *keyword, const char *value)
2333 {
2334     ENCODE_DATA *edata = t->data;
2335 
2336     if (strcmp(keyword, "Input") == 0)
2337         return parse_bin(value, &edata->input, &edata->input_len);
2338     if (strcmp(keyword, "Output") == 0)
2339         return parse_bin(value, &edata->output, &edata->output_len);
2340     return 0;
2341 }
2342 
2343 static int encode_test_run(EVP_TEST *t)
2344 {
2345     ENCODE_DATA *expected = t->data;
2346     unsigned char *encode_out = NULL, *decode_out = NULL;
2347     int output_len, chunk_len;
2348     EVP_ENCODE_CTX *decode_ctx = NULL, *encode_ctx = NULL;
2349 
2350     if (!TEST_ptr(decode_ctx = EVP_ENCODE_CTX_new())) {
2351         t->err = "INTERNAL_ERROR";
2352         goto err;
2353     }
2354 
2355     if (expected->encoding == BASE64_CANONICAL_ENCODING) {
2356 
2357         if (!TEST_ptr(encode_ctx = EVP_ENCODE_CTX_new())
2358                 || !TEST_ptr(encode_out =
2359                         OPENSSL_malloc(EVP_ENCODE_LENGTH(expected->input_len))))
2360             goto err;
2361 
2362         EVP_EncodeInit(encode_ctx);
2363         if (!TEST_true(EVP_EncodeUpdate(encode_ctx, encode_out, &chunk_len,
2364                                         expected->input, expected->input_len)))
2365             goto err;
2366 
2367         output_len = chunk_len;
2368 
2369         EVP_EncodeFinal(encode_ctx, encode_out + chunk_len, &chunk_len);
2370         output_len += chunk_len;
2371 
2372         if (!memory_err_compare(t, "BAD_ENCODING",
2373                                 expected->output, expected->output_len,
2374                                 encode_out, output_len))
2375             goto err;
2376     }
2377 
2378     if (!TEST_ptr(decode_out =
2379                 OPENSSL_malloc(EVP_DECODE_LENGTH(expected->output_len))))
2380         goto err;
2381 
2382     EVP_DecodeInit(decode_ctx);
2383     if (EVP_DecodeUpdate(decode_ctx, decode_out, &chunk_len, expected->output,
2384                          expected->output_len) < 0) {
2385         t->err = "DECODE_ERROR";
2386         goto err;
2387     }
2388     output_len = chunk_len;
2389 
2390     if (EVP_DecodeFinal(decode_ctx, decode_out + chunk_len, &chunk_len) != 1) {
2391         t->err = "DECODE_ERROR";
2392         goto err;
2393     }
2394     output_len += chunk_len;
2395 
2396     if (expected->encoding != BASE64_INVALID_ENCODING
2397             && !memory_err_compare(t, "BAD_DECODING",
2398                                    expected->input, expected->input_len,
2399                                    decode_out, output_len)) {
2400         t->err = "BAD_DECODING";
2401         goto err;
2402     }
2403 
2404     t->err = NULL;
2405  err:
2406     OPENSSL_free(encode_out);
2407     OPENSSL_free(decode_out);
2408     EVP_ENCODE_CTX_free(decode_ctx);
2409     EVP_ENCODE_CTX_free(encode_ctx);
2410     return 1;
2411 }
2412 
2413 static const EVP_TEST_METHOD encode_test_method = {
2414     "Encoding",
2415     encode_test_init,
2416     encode_test_cleanup,
2417     encode_test_parse,
2418     encode_test_run,
2419 };
2420 
2421 
2422 /**
2423  **  RAND TESTS
2424  **/
2425 #define MAX_RAND_REPEATS    15
2426 
2427 typedef struct rand_data_pass_st {
2428     unsigned char *entropy;
2429     unsigned char *reseed_entropy;
2430     unsigned char *nonce;
2431     unsigned char *pers;
2432     unsigned char *reseed_addin;
2433     unsigned char *addinA;
2434     unsigned char *addinB;
2435     unsigned char *pr_entropyA;
2436     unsigned char *pr_entropyB;
2437     unsigned char *output;
2438     size_t entropy_len, nonce_len, pers_len, addinA_len, addinB_len,
2439            pr_entropyA_len, pr_entropyB_len, output_len, reseed_entropy_len,
2440            reseed_addin_len;
2441 } RAND_DATA_PASS;
2442 
2443 typedef struct rand_data_st {
2444     /* Context for this operation */
2445     EVP_RAND_CTX *ctx;
2446     EVP_RAND_CTX *parent;
2447     int n;
2448     int prediction_resistance;
2449     int use_df;
2450     unsigned int generate_bits;
2451     char *cipher;
2452     char *digest;
2453 
2454     /* Expected output */
2455     RAND_DATA_PASS data[MAX_RAND_REPEATS];
2456 } RAND_DATA;
2457 
2458 static int rand_test_init(EVP_TEST *t, const char *name)
2459 {
2460     RAND_DATA *rdata;
2461     EVP_RAND *rand;
2462     OSSL_PARAM params[2] = { OSSL_PARAM_END, OSSL_PARAM_END };
2463     unsigned int strength = 256;
2464 
2465     if (!TEST_ptr(rdata = OPENSSL_zalloc(sizeof(*rdata))))
2466         return 0;
2467 
2468     /* TEST-RAND is available in the FIPS provider but not with "fips=yes" */
2469     rand = EVP_RAND_fetch(libctx, "TEST-RAND", "-fips");
2470     if (rand == NULL)
2471         goto err;
2472     rdata->parent = EVP_RAND_CTX_new(rand, NULL);
2473     EVP_RAND_free(rand);
2474     if (rdata->parent == NULL)
2475         goto err;
2476 
2477     *params = OSSL_PARAM_construct_uint(OSSL_RAND_PARAM_STRENGTH, &strength);
2478     if (!EVP_RAND_CTX_set_params(rdata->parent, params))
2479         goto err;
2480 
2481     rand = EVP_RAND_fetch(libctx, name, NULL);
2482     if (rand == NULL)
2483         goto err;
2484     rdata->ctx = EVP_RAND_CTX_new(rand, rdata->parent);
2485     EVP_RAND_free(rand);
2486     if (rdata->ctx == NULL)
2487         goto err;
2488 
2489     rdata->n = -1;
2490     t->data = rdata;
2491     return 1;
2492  err:
2493     EVP_RAND_CTX_free(rdata->parent);
2494     OPENSSL_free(rdata);
2495     return 0;
2496 }
2497 
2498 static void rand_test_cleanup(EVP_TEST *t)
2499 {
2500     RAND_DATA *rdata = t->data;
2501     int i;
2502 
2503     OPENSSL_free(rdata->cipher);
2504     OPENSSL_free(rdata->digest);
2505 
2506     for (i = 0; i <= rdata->n; i++) {
2507         OPENSSL_free(rdata->data[i].entropy);
2508         OPENSSL_free(rdata->data[i].reseed_entropy);
2509         OPENSSL_free(rdata->data[i].nonce);
2510         OPENSSL_free(rdata->data[i].pers);
2511         OPENSSL_free(rdata->data[i].reseed_addin);
2512         OPENSSL_free(rdata->data[i].addinA);
2513         OPENSSL_free(rdata->data[i].addinB);
2514         OPENSSL_free(rdata->data[i].pr_entropyA);
2515         OPENSSL_free(rdata->data[i].pr_entropyB);
2516         OPENSSL_free(rdata->data[i].output);
2517     }
2518     EVP_RAND_CTX_free(rdata->ctx);
2519     EVP_RAND_CTX_free(rdata->parent);
2520 }
2521 
2522 static int rand_test_parse(EVP_TEST *t,
2523                           const char *keyword, const char *value)
2524 {
2525     RAND_DATA *rdata = t->data;
2526     RAND_DATA_PASS *item;
2527     const char *p;
2528     int n;
2529 
2530     if ((p = strchr(keyword, '.')) != NULL) {
2531         n = atoi(++p);
2532         if (n >= MAX_RAND_REPEATS)
2533             return 0;
2534         if (n > rdata->n)
2535             rdata->n = n;
2536         item = rdata->data + n;
2537         if (strncmp(keyword, "Entropy.", sizeof("Entropy")) == 0)
2538             return parse_bin(value, &item->entropy, &item->entropy_len);
2539         if (strncmp(keyword, "ReseedEntropy.", sizeof("ReseedEntropy")) == 0)
2540             return parse_bin(value, &item->reseed_entropy,
2541                              &item->reseed_entropy_len);
2542         if (strncmp(keyword, "Nonce.", sizeof("Nonce")) == 0)
2543             return parse_bin(value, &item->nonce, &item->nonce_len);
2544         if (strncmp(keyword, "PersonalisationString.",
2545                     sizeof("PersonalisationString")) == 0)
2546             return parse_bin(value, &item->pers, &item->pers_len);
2547         if (strncmp(keyword, "ReseedAdditionalInput.",
2548                     sizeof("ReseedAdditionalInput")) == 0)
2549             return parse_bin(value, &item->reseed_addin,
2550                              &item->reseed_addin_len);
2551         if (strncmp(keyword, "AdditionalInputA.",
2552                     sizeof("AdditionalInputA")) == 0)
2553             return parse_bin(value, &item->addinA, &item->addinA_len);
2554         if (strncmp(keyword, "AdditionalInputB.",
2555                     sizeof("AdditionalInputB")) == 0)
2556             return parse_bin(value, &item->addinB, &item->addinB_len);
2557         if (strncmp(keyword, "EntropyPredictionResistanceA.",
2558                     sizeof("EntropyPredictionResistanceA")) == 0)
2559             return parse_bin(value, &item->pr_entropyA, &item->pr_entropyA_len);
2560         if (strncmp(keyword, "EntropyPredictionResistanceB.",
2561                     sizeof("EntropyPredictionResistanceB")) == 0)
2562             return parse_bin(value, &item->pr_entropyB, &item->pr_entropyB_len);
2563         if (strncmp(keyword, "Output.", sizeof("Output")) == 0)
2564             return parse_bin(value, &item->output, &item->output_len);
2565     } else {
2566         if (strcmp(keyword, "Cipher") == 0)
2567             return TEST_ptr(rdata->cipher = OPENSSL_strdup(value));
2568         if (strcmp(keyword, "Digest") == 0)
2569             return TEST_ptr(rdata->digest = OPENSSL_strdup(value));
2570         if (strcmp(keyword, "DerivationFunction") == 0) {
2571             rdata->use_df = atoi(value) != 0;
2572             return 1;
2573         }
2574         if (strcmp(keyword, "GenerateBits") == 0) {
2575             if ((n = atoi(value)) <= 0 || n % 8 != 0)
2576                 return 0;
2577             rdata->generate_bits = (unsigned int)n;
2578             return 1;
2579         }
2580         if (strcmp(keyword, "PredictionResistance") == 0) {
2581             rdata->prediction_resistance = atoi(value) != 0;
2582             return 1;
2583         }
2584     }
2585     return 0;
2586 }
2587 
2588 static int rand_test_run(EVP_TEST *t)
2589 {
2590     RAND_DATA *expected = t->data;
2591     RAND_DATA_PASS *item;
2592     unsigned char *got;
2593     size_t got_len = expected->generate_bits / 8;
2594     OSSL_PARAM params[5], *p = params;
2595     int i = -1, ret = 0;
2596     unsigned int strength;
2597     unsigned char *z;
2598 
2599     if (!TEST_ptr(got = OPENSSL_malloc(got_len)))
2600         return 0;
2601 
2602     *p++ = OSSL_PARAM_construct_int(OSSL_DRBG_PARAM_USE_DF, &expected->use_df);
2603     if (expected->cipher != NULL)
2604         *p++ = OSSL_PARAM_construct_utf8_string(OSSL_DRBG_PARAM_CIPHER,
2605                                                 expected->cipher, 0);
2606     if (expected->digest != NULL)
2607         *p++ = OSSL_PARAM_construct_utf8_string(OSSL_DRBG_PARAM_DIGEST,
2608                                                 expected->digest, 0);
2609     *p++ = OSSL_PARAM_construct_utf8_string(OSSL_DRBG_PARAM_MAC, "HMAC", 0);
2610     *p = OSSL_PARAM_construct_end();
2611     if (!TEST_true(EVP_RAND_CTX_set_params(expected->ctx, params)))
2612         goto err;
2613 
2614     strength = EVP_RAND_get_strength(expected->ctx);
2615     for (i = 0; i <= expected->n; i++) {
2616         item = expected->data + i;
2617 
2618         p = params;
2619         z = item->entropy != NULL ? item->entropy : (unsigned char *)"";
2620         *p++ = OSSL_PARAM_construct_octet_string(OSSL_RAND_PARAM_TEST_ENTROPY,
2621                                                  z, item->entropy_len);
2622         z = item->nonce != NULL ? item->nonce : (unsigned char *)"";
2623         *p++ = OSSL_PARAM_construct_octet_string(OSSL_RAND_PARAM_TEST_NONCE,
2624                                                  z, item->nonce_len);
2625         *p = OSSL_PARAM_construct_end();
2626         if (!TEST_true(EVP_RAND_instantiate(expected->parent, strength,
2627                                             0, NULL, 0, params)))
2628             goto err;
2629 
2630         z = item->pers != NULL ? item->pers : (unsigned char *)"";
2631         if (!TEST_true(EVP_RAND_instantiate
2632                            (expected->ctx, strength,
2633                             expected->prediction_resistance, z,
2634                             item->pers_len, NULL)))
2635             goto err;
2636 
2637         if (item->reseed_entropy != NULL) {
2638             params[0] = OSSL_PARAM_construct_octet_string
2639                            (OSSL_RAND_PARAM_TEST_ENTROPY, item->reseed_entropy,
2640                             item->reseed_entropy_len);
2641             params[1] = OSSL_PARAM_construct_end();
2642             if (!TEST_true(EVP_RAND_CTX_set_params(expected->parent, params)))
2643                 goto err;
2644 
2645             if (!TEST_true(EVP_RAND_reseed
2646                                (expected->ctx, expected->prediction_resistance,
2647                                 NULL, 0, item->reseed_addin,
2648                                 item->reseed_addin_len)))
2649                 goto err;
2650         }
2651         if (item->pr_entropyA != NULL) {
2652             params[0] = OSSL_PARAM_construct_octet_string
2653                            (OSSL_RAND_PARAM_TEST_ENTROPY, item->pr_entropyA,
2654                             item->pr_entropyA_len);
2655             params[1] = OSSL_PARAM_construct_end();
2656             if (!TEST_true(EVP_RAND_CTX_set_params(expected->parent, params)))
2657                 goto err;
2658         }
2659         if (!TEST_true(EVP_RAND_generate
2660                            (expected->ctx, got, got_len,
2661                             strength, expected->prediction_resistance,
2662                             item->addinA, item->addinA_len)))
2663             goto err;
2664 
2665         if (item->pr_entropyB != NULL) {
2666             params[0] = OSSL_PARAM_construct_octet_string
2667                            (OSSL_RAND_PARAM_TEST_ENTROPY, item->pr_entropyB,
2668                             item->pr_entropyB_len);
2669             params[1] = OSSL_PARAM_construct_end();
2670             if (!TEST_true(EVP_RAND_CTX_set_params(expected->parent, params)))
2671                 goto err;
2672         }
2673         if (!TEST_true(EVP_RAND_generate
2674                            (expected->ctx, got, got_len,
2675                             strength, expected->prediction_resistance,
2676                             item->addinB, item->addinB_len)))
2677             goto err;
2678         if (!TEST_mem_eq(got, got_len, item->output, item->output_len))
2679             goto err;
2680         if (!TEST_true(EVP_RAND_uninstantiate(expected->ctx))
2681                 || !TEST_true(EVP_RAND_uninstantiate(expected->parent))
2682                 || !TEST_true(EVP_RAND_verify_zeroization(expected->ctx))
2683                 || !TEST_int_eq(EVP_RAND_get_state(expected->ctx),
2684                                 EVP_RAND_STATE_UNINITIALISED))
2685             goto err;
2686     }
2687     t->err = NULL;
2688     ret = 1;
2689 
2690  err:
2691     if (ret == 0 && i >= 0)
2692         TEST_info("Error in test case %d of %d\n", i, expected->n + 1);
2693     OPENSSL_free(got);
2694     return ret;
2695 }
2696 
2697 static const EVP_TEST_METHOD rand_test_method = {
2698     "RAND",
2699     rand_test_init,
2700     rand_test_cleanup,
2701     rand_test_parse,
2702     rand_test_run
2703 };
2704 
2705 
2706 /**
2707  **  KDF TESTS
2708  **/
2709 typedef struct kdf_data_st {
2710     /* Context for this operation */
2711     EVP_KDF_CTX *ctx;
2712     /* Expected output */
2713     unsigned char *output;
2714     size_t output_len;
2715     OSSL_PARAM params[20];
2716     OSSL_PARAM *p;
2717 } KDF_DATA;
2718 
2719 /*
2720  * Perform public key operation setup: lookup key, allocated ctx and call
2721  * the appropriate initialisation function
2722  */
2723 static int kdf_test_init(EVP_TEST *t, const char *name)
2724 {
2725     KDF_DATA *kdata;
2726     EVP_KDF *kdf;
2727 
2728     if (is_kdf_disabled(name)) {
2729         TEST_info("skipping, '%s' is disabled", name);
2730         t->skip = 1;
2731         return 1;
2732     }
2733 
2734     if (!TEST_ptr(kdata = OPENSSL_zalloc(sizeof(*kdata))))
2735         return 0;
2736     kdata->p = kdata->params;
2737     *kdata->p = OSSL_PARAM_construct_end();
2738 
2739     kdf = EVP_KDF_fetch(libctx, name, NULL);
2740     if (kdf == NULL) {
2741         OPENSSL_free(kdata);
2742         return 0;
2743     }
2744     kdata->ctx = EVP_KDF_CTX_new(kdf);
2745     EVP_KDF_free(kdf);
2746     if (kdata->ctx == NULL) {
2747         OPENSSL_free(kdata);
2748         return 0;
2749     }
2750     t->data = kdata;
2751     return 1;
2752 }
2753 
2754 static void kdf_test_cleanup(EVP_TEST *t)
2755 {
2756     KDF_DATA *kdata = t->data;
2757     OSSL_PARAM *p;
2758 
2759     for (p = kdata->params; p->key != NULL; p++)
2760         OPENSSL_free(p->data);
2761     OPENSSL_free(kdata->output);
2762     EVP_KDF_CTX_free(kdata->ctx);
2763 }
2764 
2765 static int kdf_test_ctrl(EVP_TEST *t, EVP_KDF_CTX *kctx,
2766                          const char *value)
2767 {
2768     KDF_DATA *kdata = t->data;
2769     int rv;
2770     char *p, *name;
2771     const OSSL_PARAM *defs = EVP_KDF_settable_ctx_params(EVP_KDF_CTX_kdf(kctx));
2772 
2773     if (!TEST_ptr(name = OPENSSL_strdup(value)))
2774         return 0;
2775     p = strchr(name, ':');
2776     if (p != NULL)
2777         *p++ = '\0';
2778 
2779     rv = OSSL_PARAM_allocate_from_text(kdata->p, defs, name, p,
2780                                        p != NULL ? strlen(p) : 0, NULL);
2781     *++kdata->p = OSSL_PARAM_construct_end();
2782     if (!rv) {
2783         t->err = "KDF_PARAM_ERROR";
2784         OPENSSL_free(name);
2785         return 0;
2786     }
2787     if (p != NULL && strcmp(name, "digest") == 0) {
2788         if (is_digest_disabled(p)) {
2789             TEST_info("skipping, '%s' is disabled", p);
2790             t->skip = 1;
2791         }
2792     }
2793     if (p != NULL
2794         && (strcmp(name, "cipher") == 0
2795             || strcmp(name, "cekalg") == 0)
2796         && is_cipher_disabled(p)) {
2797         TEST_info("skipping, '%s' is disabled", p);
2798         t->skip = 1;
2799     }
2800     OPENSSL_free(name);
2801     return 1;
2802 }
2803 
2804 static int kdf_test_parse(EVP_TEST *t,
2805                           const char *keyword, const char *value)
2806 {
2807     KDF_DATA *kdata = t->data;
2808 
2809     if (strcmp(keyword, "Output") == 0)
2810         return parse_bin(value, &kdata->output, &kdata->output_len);
2811     if (strncmp(keyword, "Ctrl", 4) == 0)
2812         return kdf_test_ctrl(t, kdata->ctx, value);
2813     return 0;
2814 }
2815 
2816 static int kdf_test_run(EVP_TEST *t)
2817 {
2818     KDF_DATA *expected = t->data;
2819     unsigned char *got = NULL;
2820     size_t got_len = expected->output_len;
2821 
2822     if (!EVP_KDF_CTX_set_params(expected->ctx, expected->params)) {
2823         t->err = "KDF_CTRL_ERROR";
2824         return 1;
2825     }
2826     if (!TEST_ptr(got = OPENSSL_malloc(got_len == 0 ? 1 : got_len))) {
2827         t->err = "INTERNAL_ERROR";
2828         goto err;
2829     }
2830     if (EVP_KDF_derive(expected->ctx, got, got_len, NULL) <= 0) {
2831         t->err = "KDF_DERIVE_ERROR";
2832         goto err;
2833     }
2834     if (!memory_err_compare(t, "KDF_MISMATCH",
2835                             expected->output, expected->output_len,
2836                             got, got_len))
2837         goto err;
2838 
2839     t->err = NULL;
2840 
2841  err:
2842     OPENSSL_free(got);
2843     return 1;
2844 }
2845 
2846 static const EVP_TEST_METHOD kdf_test_method = {
2847     "KDF",
2848     kdf_test_init,
2849     kdf_test_cleanup,
2850     kdf_test_parse,
2851     kdf_test_run
2852 };
2853 
2854 /**
2855  **  PKEY KDF TESTS
2856  **/
2857 
2858 typedef struct pkey_kdf_data_st {
2859     /* Context for this operation */
2860     EVP_PKEY_CTX *ctx;
2861     /* Expected output */
2862     unsigned char *output;
2863     size_t output_len;
2864 } PKEY_KDF_DATA;
2865 
2866 /*
2867  * Perform public key operation setup: lookup key, allocated ctx and call
2868  * the appropriate initialisation function
2869  */
2870 static int pkey_kdf_test_init(EVP_TEST *t, const char *name)
2871 {
2872     PKEY_KDF_DATA *kdata = NULL;
2873 
2874     if (is_kdf_disabled(name)) {
2875         TEST_info("skipping, '%s' is disabled", name);
2876         t->skip = 1;
2877         return 1;
2878     }
2879 
2880     if (!TEST_ptr(kdata = OPENSSL_zalloc(sizeof(*kdata))))
2881         return 0;
2882 
2883     kdata->ctx = EVP_PKEY_CTX_new_from_name(libctx, name, NULL);
2884     if (kdata->ctx == NULL
2885         || EVP_PKEY_derive_init(kdata->ctx) <= 0)
2886         goto err;
2887 
2888     t->data = kdata;
2889     return 1;
2890 err:
2891     EVP_PKEY_CTX_free(kdata->ctx);
2892     OPENSSL_free(kdata);
2893     return 0;
2894 }
2895 
2896 static void pkey_kdf_test_cleanup(EVP_TEST *t)
2897 {
2898     PKEY_KDF_DATA *kdata = t->data;
2899 
2900     OPENSSL_free(kdata->output);
2901     EVP_PKEY_CTX_free(kdata->ctx);
2902 }
2903 
2904 static int pkey_kdf_test_parse(EVP_TEST *t,
2905                                const char *keyword, const char *value)
2906 {
2907     PKEY_KDF_DATA *kdata = t->data;
2908 
2909     if (strcmp(keyword, "Output") == 0)
2910         return parse_bin(value, &kdata->output, &kdata->output_len);
2911     if (strncmp(keyword, "Ctrl", 4) == 0)
2912         return pkey_test_ctrl(t, kdata->ctx, value);
2913     return 0;
2914 }
2915 
2916 static int pkey_kdf_test_run(EVP_TEST *t)
2917 {
2918     PKEY_KDF_DATA *expected = t->data;
2919     unsigned char *got = NULL;
2920     size_t got_len = 0;
2921 
2922     if (fips_provider_version_eq(libctx, 3, 0, 0)) {
2923         /* FIPS(3.0.0): can't deal with oversized output buffers #18533 */
2924         got_len = expected->output_len;
2925     } else {
2926         /* Find out the KDF output size */
2927         if (EVP_PKEY_derive(expected->ctx, NULL, &got_len) <= 0) {
2928             t->err = "INTERNAL_ERROR";
2929             goto err;
2930         }
2931 
2932         /*
2933          * We may get an absurd output size, which signals that anything goes.
2934          * If not, we specify a too big buffer for the output, to test that
2935          * EVP_PKEY_derive() can cope with it.
2936          */
2937         if (got_len == SIZE_MAX || got_len == 0)
2938             got_len = expected->output_len;
2939         else
2940             got_len = expected->output_len * 2;
2941     }
2942 
2943     if (!TEST_ptr(got = OPENSSL_malloc(got_len == 0 ? 1 : got_len))) {
2944         t->err = "INTERNAL_ERROR";
2945         goto err;
2946     }
2947     if (EVP_PKEY_derive(expected->ctx, got, &got_len) <= 0) {
2948         t->err = "KDF_DERIVE_ERROR";
2949         goto err;
2950     }
2951     if (!TEST_mem_eq(expected->output, expected->output_len, got, got_len)) {
2952         t->err = "KDF_MISMATCH";
2953         goto err;
2954     }
2955     t->err = NULL;
2956 
2957  err:
2958     OPENSSL_free(got);
2959     return 1;
2960 }
2961 
2962 static const EVP_TEST_METHOD pkey_kdf_test_method = {
2963     "PKEYKDF",
2964     pkey_kdf_test_init,
2965     pkey_kdf_test_cleanup,
2966     pkey_kdf_test_parse,
2967     pkey_kdf_test_run
2968 };
2969 
2970 /**
2971  **  KEYPAIR TESTS
2972  **/
2973 
2974 typedef struct keypair_test_data_st {
2975     EVP_PKEY *privk;
2976     EVP_PKEY *pubk;
2977 } KEYPAIR_TEST_DATA;
2978 
2979 static int keypair_test_init(EVP_TEST *t, const char *pair)
2980 {
2981     KEYPAIR_TEST_DATA *data;
2982     int rv = 0;
2983     EVP_PKEY *pk = NULL, *pubk = NULL;
2984     char *pub, *priv = NULL;
2985 
2986     /* Split private and public names. */
2987     if (!TEST_ptr(priv = OPENSSL_strdup(pair))
2988             || !TEST_ptr(pub = strchr(priv, ':'))) {
2989         t->err = "PARSING_ERROR";
2990         goto end;
2991     }
2992     *pub++ = '\0';
2993 
2994     if (!TEST_true(find_key(&pk, priv, private_keys))) {
2995         TEST_info("Can't find private key: %s", priv);
2996         t->err = "MISSING_PRIVATE_KEY";
2997         goto end;
2998     }
2999     if (!TEST_true(find_key(&pubk, pub, public_keys))) {
3000         TEST_info("Can't find public key: %s", pub);
3001         t->err = "MISSING_PUBLIC_KEY";
3002         goto end;
3003     }
3004 
3005     if (pk == NULL && pubk == NULL) {
3006         /* Both keys are listed but unsupported: skip this test */
3007         t->skip = 1;
3008         rv = 1;
3009         goto end;
3010     }
3011 
3012     if (!TEST_ptr(data = OPENSSL_malloc(sizeof(*data))))
3013         goto end;
3014     data->privk = pk;
3015     data->pubk = pubk;
3016     t->data = data;
3017     rv = 1;
3018     t->err = NULL;
3019 
3020 end:
3021     OPENSSL_free(priv);
3022     return rv;
3023 }
3024 
3025 static void keypair_test_cleanup(EVP_TEST *t)
3026 {
3027     OPENSSL_free(t->data);
3028     t->data = NULL;
3029 }
3030 
3031 /*
3032  * For tests that do not accept any custom keywords.
3033  */
3034 static int void_test_parse(EVP_TEST *t, const char *keyword, const char *value)
3035 {
3036     return 0;
3037 }
3038 
3039 static int keypair_test_run(EVP_TEST *t)
3040 {
3041     int rv = 0;
3042     const KEYPAIR_TEST_DATA *pair = t->data;
3043 
3044     if (pair->privk == NULL || pair->pubk == NULL) {
3045         /*
3046          * this can only happen if only one of the keys is not set
3047          * which means that one of them was unsupported while the
3048          * other isn't: hence a key type mismatch.
3049          */
3050         t->err = "KEYPAIR_TYPE_MISMATCH";
3051         rv = 1;
3052         goto end;
3053     }
3054 
3055     if ((rv = EVP_PKEY_eq(pair->privk, pair->pubk)) != 1 ) {
3056         if ( 0 == rv ) {
3057             t->err = "KEYPAIR_MISMATCH";
3058         } else if ( -1 == rv ) {
3059             t->err = "KEYPAIR_TYPE_MISMATCH";
3060         } else if ( -2 == rv ) {
3061             t->err = "UNSUPPORTED_KEY_COMPARISON";
3062         } else {
3063             TEST_error("Unexpected error in key comparison");
3064             rv = 0;
3065             goto end;
3066         }
3067         rv = 1;
3068         goto end;
3069     }
3070 
3071     rv = 1;
3072     t->err = NULL;
3073 
3074 end:
3075     return rv;
3076 }
3077 
3078 static const EVP_TEST_METHOD keypair_test_method = {
3079     "PrivPubKeyPair",
3080     keypair_test_init,
3081     keypair_test_cleanup,
3082     void_test_parse,
3083     keypair_test_run
3084 };
3085 
3086 /**
3087  **  KEYGEN TEST
3088  **/
3089 
3090 typedef struct keygen_test_data_st {
3091     EVP_PKEY_CTX *genctx; /* Keygen context to use */
3092     char *keyname; /* Key name to store key or NULL */
3093 } KEYGEN_TEST_DATA;
3094 
3095 static int keygen_test_init(EVP_TEST *t, const char *alg)
3096 {
3097     KEYGEN_TEST_DATA *data;
3098     EVP_PKEY_CTX *genctx;
3099     int nid = OBJ_sn2nid(alg);
3100 
3101     if (nid == NID_undef) {
3102         nid = OBJ_ln2nid(alg);
3103         if (nid == NID_undef)
3104             return 0;
3105     }
3106 
3107     if (is_pkey_disabled(alg)) {
3108         t->skip = 1;
3109         return 1;
3110     }
3111     if (!TEST_ptr(genctx = EVP_PKEY_CTX_new_from_name(libctx, alg, NULL)))
3112         goto err;
3113 
3114     if (EVP_PKEY_keygen_init(genctx) <= 0) {
3115         t->err = "KEYGEN_INIT_ERROR";
3116         goto err;
3117     }
3118 
3119     if (!TEST_ptr(data = OPENSSL_malloc(sizeof(*data))))
3120         goto err;
3121     data->genctx = genctx;
3122     data->keyname = NULL;
3123     t->data = data;
3124     t->err = NULL;
3125     return 1;
3126 
3127 err:
3128     EVP_PKEY_CTX_free(genctx);
3129     return 0;
3130 }
3131 
3132 static void keygen_test_cleanup(EVP_TEST *t)
3133 {
3134     KEYGEN_TEST_DATA *keygen = t->data;
3135 
3136     EVP_PKEY_CTX_free(keygen->genctx);
3137     OPENSSL_free(keygen->keyname);
3138     OPENSSL_free(t->data);
3139     t->data = NULL;
3140 }
3141 
3142 static int keygen_test_parse(EVP_TEST *t,
3143                              const char *keyword, const char *value)
3144 {
3145     KEYGEN_TEST_DATA *keygen = t->data;
3146 
3147     if (strcmp(keyword, "KeyName") == 0)
3148         return TEST_ptr(keygen->keyname = OPENSSL_strdup(value));
3149     if (strcmp(keyword, "Ctrl") == 0)
3150         return pkey_test_ctrl(t, keygen->genctx, value);
3151     return 0;
3152 }
3153 
3154 static int keygen_test_run(EVP_TEST *t)
3155 {
3156     KEYGEN_TEST_DATA *keygen = t->data;
3157     EVP_PKEY *pkey = NULL;
3158     int rv = 1;
3159 
3160     if (EVP_PKEY_keygen(keygen->genctx, &pkey) <= 0) {
3161         t->err = "KEYGEN_GENERATE_ERROR";
3162         goto err;
3163     }
3164 
3165     if (!evp_pkey_is_provided(pkey)) {
3166         TEST_info("Warning: legacy key generated %s", keygen->keyname);
3167         goto err;
3168     }
3169     if (keygen->keyname != NULL) {
3170         KEY_LIST *key;
3171 
3172         rv = 0;
3173         if (find_key(NULL, keygen->keyname, private_keys)) {
3174             TEST_info("Duplicate key %s", keygen->keyname);
3175             goto err;
3176         }
3177 
3178         if (!TEST_ptr(key = OPENSSL_malloc(sizeof(*key))))
3179             goto err;
3180         key->name = keygen->keyname;
3181         keygen->keyname = NULL;
3182         key->key = pkey;
3183         key->next = private_keys;
3184         private_keys = key;
3185         rv = 1;
3186     } else {
3187         EVP_PKEY_free(pkey);
3188     }
3189 
3190     t->err = NULL;
3191 
3192 err:
3193     return rv;
3194 }
3195 
3196 static const EVP_TEST_METHOD keygen_test_method = {
3197     "KeyGen",
3198     keygen_test_init,
3199     keygen_test_cleanup,
3200     keygen_test_parse,
3201     keygen_test_run,
3202 };
3203 
3204 /**
3205  **  DIGEST SIGN+VERIFY TESTS
3206  **/
3207 
3208 typedef struct {
3209     int is_verify; /* Set to 1 if verifying */
3210     int is_oneshot; /* Set to 1 for one shot operation */
3211     const EVP_MD *md; /* Digest to use */
3212     EVP_MD_CTX *ctx; /* Digest context */
3213     EVP_PKEY_CTX *pctx;
3214     STACK_OF(EVP_TEST_BUFFER) *input; /* Input data: streaming */
3215     unsigned char *osin; /* Input data if one shot */
3216     size_t osin_len; /* Input length data if one shot */
3217     unsigned char *output; /* Expected output */
3218     size_t output_len; /* Expected output length */
3219 } DIGESTSIGN_DATA;
3220 
3221 static int digestsigver_test_init(EVP_TEST *t, const char *alg, int is_verify,
3222                                   int is_oneshot)
3223 {
3224     const EVP_MD *md = NULL;
3225     DIGESTSIGN_DATA *mdat;
3226 
3227     if (strcmp(alg, "NULL") != 0) {
3228         if (is_digest_disabled(alg)) {
3229             t->skip = 1;
3230             return 1;
3231         }
3232         md = EVP_get_digestbyname(alg);
3233         if (md == NULL)
3234             return 0;
3235     }
3236     if (!TEST_ptr(mdat = OPENSSL_zalloc(sizeof(*mdat))))
3237         return 0;
3238     mdat->md = md;
3239     if (!TEST_ptr(mdat->ctx = EVP_MD_CTX_new())) {
3240         OPENSSL_free(mdat);
3241         return 0;
3242     }
3243     mdat->is_verify = is_verify;
3244     mdat->is_oneshot = is_oneshot;
3245     t->data = mdat;
3246     return 1;
3247 }
3248 
3249 static int digestsign_test_init(EVP_TEST *t, const char *alg)
3250 {
3251     return digestsigver_test_init(t, alg, 0, 0);
3252 }
3253 
3254 static void digestsigver_test_cleanup(EVP_TEST *t)
3255 {
3256     DIGESTSIGN_DATA *mdata = t->data;
3257 
3258     EVP_MD_CTX_free(mdata->ctx);
3259     sk_EVP_TEST_BUFFER_pop_free(mdata->input, evp_test_buffer_free);
3260     OPENSSL_free(mdata->osin);
3261     OPENSSL_free(mdata->output);
3262     OPENSSL_free(mdata);
3263     t->data = NULL;
3264 }
3265 
3266 static int digestsigver_test_parse(EVP_TEST *t,
3267                                    const char *keyword, const char *value)
3268 {
3269     DIGESTSIGN_DATA *mdata = t->data;
3270 
3271     if (strcmp(keyword, "Key") == 0) {
3272         EVP_PKEY *pkey = NULL;
3273         int rv = 0;
3274         const char *name = mdata->md == NULL ? NULL : EVP_MD_get0_name(mdata->md);
3275 
3276         if (mdata->is_verify)
3277             rv = find_key(&pkey, value, public_keys);
3278         if (rv == 0)
3279             rv = find_key(&pkey, value, private_keys);
3280         if (rv == 0 || pkey == NULL) {
3281             t->skip = 1;
3282             return 1;
3283         }
3284         if (mdata->is_verify) {
3285             if (!EVP_DigestVerifyInit_ex(mdata->ctx, &mdata->pctx, name, libctx,
3286                                          NULL, pkey, NULL))
3287                 t->err = "DIGESTVERIFYINIT_ERROR";
3288             return 1;
3289         }
3290         if (!EVP_DigestSignInit_ex(mdata->ctx, &mdata->pctx, name, libctx, NULL,
3291                                    pkey, NULL))
3292             t->err = "DIGESTSIGNINIT_ERROR";
3293         return 1;
3294     }
3295 
3296     if (strcmp(keyword, "Input") == 0) {
3297         if (mdata->is_oneshot)
3298             return parse_bin(value, &mdata->osin, &mdata->osin_len);
3299         return evp_test_buffer_append(value, &mdata->input);
3300     }
3301     if (strcmp(keyword, "Output") == 0)
3302         return parse_bin(value, &mdata->output, &mdata->output_len);
3303 
3304     if (!mdata->is_oneshot) {
3305         if (strcmp(keyword, "Count") == 0)
3306             return evp_test_buffer_set_count(value, mdata->input);
3307         if (strcmp(keyword, "Ncopy") == 0)
3308             return evp_test_buffer_ncopy(value, mdata->input);
3309     }
3310     if (strcmp(keyword, "Ctrl") == 0) {
3311         if (mdata->pctx == NULL)
3312             return -1;
3313         return pkey_test_ctrl(t, mdata->pctx, value);
3314     }
3315     return 0;
3316 }
3317 
3318 static int digestsign_update_fn(void *ctx, const unsigned char *buf,
3319                                 size_t buflen)
3320 {
3321     return EVP_DigestSignUpdate(ctx, buf, buflen);
3322 }
3323 
3324 static int digestsign_test_run(EVP_TEST *t)
3325 {
3326     DIGESTSIGN_DATA *expected = t->data;
3327     unsigned char *got = NULL;
3328     size_t got_len;
3329 
3330     if (!evp_test_buffer_do(expected->input, digestsign_update_fn,
3331                             expected->ctx)) {
3332         t->err = "DIGESTUPDATE_ERROR";
3333         goto err;
3334     }
3335 
3336     if (!EVP_DigestSignFinal(expected->ctx, NULL, &got_len)) {
3337         t->err = "DIGESTSIGNFINAL_LENGTH_ERROR";
3338         goto err;
3339     }
3340     if (!TEST_ptr(got = OPENSSL_malloc(got_len))) {
3341         t->err = "MALLOC_FAILURE";
3342         goto err;
3343     }
3344     got_len *= 2;
3345     if (!EVP_DigestSignFinal(expected->ctx, got, &got_len)) {
3346         t->err = "DIGESTSIGNFINAL_ERROR";
3347         goto err;
3348     }
3349     if (!memory_err_compare(t, "SIGNATURE_MISMATCH",
3350                             expected->output, expected->output_len,
3351                             got, got_len))
3352         goto err;
3353 
3354     t->err = NULL;
3355  err:
3356     OPENSSL_free(got);
3357     return 1;
3358 }
3359 
3360 static const EVP_TEST_METHOD digestsign_test_method = {
3361     "DigestSign",
3362     digestsign_test_init,
3363     digestsigver_test_cleanup,
3364     digestsigver_test_parse,
3365     digestsign_test_run
3366 };
3367 
3368 static int digestverify_test_init(EVP_TEST *t, const char *alg)
3369 {
3370     return digestsigver_test_init(t, alg, 1, 0);
3371 }
3372 
3373 static int digestverify_update_fn(void *ctx, const unsigned char *buf,
3374                                   size_t buflen)
3375 {
3376     return EVP_DigestVerifyUpdate(ctx, buf, buflen);
3377 }
3378 
3379 static int digestverify_test_run(EVP_TEST *t)
3380 {
3381     DIGESTSIGN_DATA *mdata = t->data;
3382 
3383     if (!evp_test_buffer_do(mdata->input, digestverify_update_fn, mdata->ctx)) {
3384         t->err = "DIGESTUPDATE_ERROR";
3385         return 1;
3386     }
3387 
3388     if (EVP_DigestVerifyFinal(mdata->ctx, mdata->output,
3389                               mdata->output_len) <= 0)
3390         t->err = "VERIFY_ERROR";
3391     return 1;
3392 }
3393 
3394 static const EVP_TEST_METHOD digestverify_test_method = {
3395     "DigestVerify",
3396     digestverify_test_init,
3397     digestsigver_test_cleanup,
3398     digestsigver_test_parse,
3399     digestverify_test_run
3400 };
3401 
3402 static int oneshot_digestsign_test_init(EVP_TEST *t, const char *alg)
3403 {
3404     return digestsigver_test_init(t, alg, 0, 1);
3405 }
3406 
3407 static int oneshot_digestsign_test_run(EVP_TEST *t)
3408 {
3409     DIGESTSIGN_DATA *expected = t->data;
3410     unsigned char *got = NULL;
3411     size_t got_len;
3412 
3413     if (!EVP_DigestSign(expected->ctx, NULL, &got_len,
3414                         expected->osin, expected->osin_len)) {
3415         t->err = "DIGESTSIGN_LENGTH_ERROR";
3416         goto err;
3417     }
3418     if (!TEST_ptr(got = OPENSSL_malloc(got_len))) {
3419         t->err = "MALLOC_FAILURE";
3420         goto err;
3421     }
3422     got_len *= 2;
3423     if (!EVP_DigestSign(expected->ctx, got, &got_len,
3424                         expected->osin, expected->osin_len)) {
3425         t->err = "DIGESTSIGN_ERROR";
3426         goto err;
3427     }
3428     if (!memory_err_compare(t, "SIGNATURE_MISMATCH",
3429                             expected->output, expected->output_len,
3430                             got, got_len))
3431         goto err;
3432 
3433     t->err = NULL;
3434  err:
3435     OPENSSL_free(got);
3436     return 1;
3437 }
3438 
3439 static const EVP_TEST_METHOD oneshot_digestsign_test_method = {
3440     "OneShotDigestSign",
3441     oneshot_digestsign_test_init,
3442     digestsigver_test_cleanup,
3443     digestsigver_test_parse,
3444     oneshot_digestsign_test_run
3445 };
3446 
3447 static int oneshot_digestverify_test_init(EVP_TEST *t, const char *alg)
3448 {
3449     return digestsigver_test_init(t, alg, 1, 1);
3450 }
3451 
3452 static int oneshot_digestverify_test_run(EVP_TEST *t)
3453 {
3454     DIGESTSIGN_DATA *mdata = t->data;
3455 
3456     if (EVP_DigestVerify(mdata->ctx, mdata->output, mdata->output_len,
3457                          mdata->osin, mdata->osin_len) <= 0)
3458         t->err = "VERIFY_ERROR";
3459     return 1;
3460 }
3461 
3462 static const EVP_TEST_METHOD oneshot_digestverify_test_method = {
3463     "OneShotDigestVerify",
3464     oneshot_digestverify_test_init,
3465     digestsigver_test_cleanup,
3466     digestsigver_test_parse,
3467     oneshot_digestverify_test_run
3468 };
3469 
3470 
3471 /**
3472  **  PARSING AND DISPATCH
3473  **/
3474 
3475 static const EVP_TEST_METHOD *evp_test_list[] = {
3476     &rand_test_method,
3477     &cipher_test_method,
3478     &digest_test_method,
3479     &digestsign_test_method,
3480     &digestverify_test_method,
3481     &encode_test_method,
3482     &kdf_test_method,
3483     &pkey_kdf_test_method,
3484     &keypair_test_method,
3485     &keygen_test_method,
3486     &mac_test_method,
3487     &oneshot_digestsign_test_method,
3488     &oneshot_digestverify_test_method,
3489     &pbe_test_method,
3490     &pdecrypt_test_method,
3491     &pderive_test_method,
3492     &psign_test_method,
3493     &pverify_recover_test_method,
3494     &pverify_test_method,
3495     NULL
3496 };
3497 
3498 static const EVP_TEST_METHOD *find_test(const char *name)
3499 {
3500     const EVP_TEST_METHOD **tt;
3501 
3502     for (tt = evp_test_list; *tt; tt++) {
3503         if (strcmp(name, (*tt)->name) == 0)
3504             return *tt;
3505     }
3506     return NULL;
3507 }
3508 
3509 static void clear_test(EVP_TEST *t)
3510 {
3511     test_clearstanza(&t->s);
3512     ERR_clear_error();
3513     if (t->data != NULL) {
3514         if (t->meth != NULL)
3515             t->meth->cleanup(t);
3516         OPENSSL_free(t->data);
3517         t->data = NULL;
3518     }
3519     OPENSSL_free(t->expected_err);
3520     t->expected_err = NULL;
3521     OPENSSL_free(t->reason);
3522     t->reason = NULL;
3523 
3524     /* Text literal. */
3525     t->err = NULL;
3526     t->skip = 0;
3527     t->meth = NULL;
3528 }
3529 
3530 /* Check for errors in the test structure; return 1 if okay, else 0. */
3531 static int check_test_error(EVP_TEST *t)
3532 {
3533     unsigned long err;
3534     const char *reason;
3535 
3536     if (t->err == NULL && t->expected_err == NULL)
3537         return 1;
3538     if (t->err != NULL && t->expected_err == NULL) {
3539         if (t->aux_err != NULL) {
3540             TEST_info("%s:%d: Source of above error (%s); unexpected error %s",
3541                       t->s.test_file, t->s.start, t->aux_err, t->err);
3542         } else {
3543             TEST_info("%s:%d: Source of above error; unexpected error %s",
3544                       t->s.test_file, t->s.start, t->err);
3545         }
3546         return 0;
3547     }
3548     if (t->err == NULL && t->expected_err != NULL) {
3549         TEST_info("%s:%d: Succeeded but was expecting %s",
3550                   t->s.test_file, t->s.start, t->expected_err);
3551         return 0;
3552     }
3553 
3554     if (strcmp(t->err, t->expected_err) != 0) {
3555         TEST_info("%s:%d: Expected %s got %s",
3556                   t->s.test_file, t->s.start, t->expected_err, t->err);
3557         return 0;
3558     }
3559 
3560     if (t->reason == NULL)
3561         return 1;
3562 
3563     if (t->reason == NULL) {
3564         TEST_info("%s:%d: Test is missing function or reason code",
3565                   t->s.test_file, t->s.start);
3566         return 0;
3567     }
3568 
3569     err = ERR_peek_error();
3570     if (err == 0) {
3571         TEST_info("%s:%d: Expected error \"%s\" not set",
3572                   t->s.test_file, t->s.start, t->reason);
3573         return 0;
3574     }
3575 
3576     reason = ERR_reason_error_string(err);
3577     if (reason == NULL) {
3578         TEST_info("%s:%d: Expected error \"%s\", no strings available."
3579                   " Assuming ok.",
3580                   t->s.test_file, t->s.start, t->reason);
3581         return 1;
3582     }
3583 
3584     if (strcmp(reason, t->reason) == 0)
3585         return 1;
3586 
3587     TEST_info("%s:%d: Expected error \"%s\", got \"%s\"",
3588               t->s.test_file, t->s.start, t->reason, reason);
3589 
3590     return 0;
3591 }
3592 
3593 /* Run a parsed test. Log a message and return 0 on error. */
3594 static int run_test(EVP_TEST *t)
3595 {
3596     if (t->meth == NULL)
3597         return 1;
3598     t->s.numtests++;
3599     if (t->skip) {
3600         t->s.numskip++;
3601     } else {
3602         /* run the test */
3603         if (t->err == NULL && t->meth->run_test(t) != 1) {
3604             TEST_info("%s:%d %s error",
3605                       t->s.test_file, t->s.start, t->meth->name);
3606             return 0;
3607         }
3608         if (!check_test_error(t)) {
3609             TEST_openssl_errors();
3610             t->s.errors++;
3611         }
3612     }
3613 
3614     /* clean it up */
3615     return 1;
3616 }
3617 
3618 static int find_key(EVP_PKEY **ppk, const char *name, KEY_LIST *lst)
3619 {
3620     for (; lst != NULL; lst = lst->next) {
3621         if (strcmp(lst->name, name) == 0) {
3622             if (ppk != NULL)
3623                 *ppk = lst->key;
3624             return 1;
3625         }
3626     }
3627     return 0;
3628 }
3629 
3630 static void free_key_list(KEY_LIST *lst)
3631 {
3632     while (lst != NULL) {
3633         KEY_LIST *next = lst->next;
3634 
3635         EVP_PKEY_free(lst->key);
3636         OPENSSL_free(lst->name);
3637         OPENSSL_free(lst);
3638         lst = next;
3639     }
3640 }
3641 
3642 /*
3643  * Is the key type an unsupported algorithm?
3644  */
3645 static int key_unsupported(void)
3646 {
3647     long err = ERR_peek_last_error();
3648     int lib = ERR_GET_LIB(err);
3649     long reason = ERR_GET_REASON(err);
3650 
3651     if ((lib == ERR_LIB_EVP && reason == EVP_R_UNSUPPORTED_ALGORITHM)
3652         || (lib == ERR_LIB_EVP && reason == EVP_R_DECODE_ERROR)
3653         || reason == ERR_R_UNSUPPORTED) {
3654         ERR_clear_error();
3655         return 1;
3656     }
3657 #ifndef OPENSSL_NO_EC
3658     /*
3659      * If EC support is enabled we should catch also EC_R_UNKNOWN_GROUP as an
3660      * hint to an unsupported algorithm/curve (e.g. if binary EC support is
3661      * disabled).
3662      */
3663     if (lib == ERR_LIB_EC
3664         && (reason == EC_R_UNKNOWN_GROUP
3665             || reason == EC_R_INVALID_CURVE)) {
3666         ERR_clear_error();
3667         return 1;
3668     }
3669 #endif /* OPENSSL_NO_EC */
3670     return 0;
3671 }
3672 
3673 /* NULL out the value from |pp| but return it.  This "steals" a pointer. */
3674 static char *take_value(PAIR *pp)
3675 {
3676     char *p = pp->value;
3677 
3678     pp->value = NULL;
3679     return p;
3680 }
3681 
3682 #if !defined(OPENSSL_NO_FIPS_SECURITYCHECKS)
3683 static int securitycheck_enabled(void)
3684 {
3685     static int enabled = -1;
3686 
3687     if (enabled == -1) {
3688         if (OSSL_PROVIDER_available(libctx, "fips")) {
3689             OSSL_PARAM params[2];
3690             OSSL_PROVIDER *prov = NULL;
3691             int check = 1;
3692 
3693             prov = OSSL_PROVIDER_load(libctx, "fips");
3694             if (prov != NULL) {
3695                 params[0] =
3696                     OSSL_PARAM_construct_int(OSSL_PROV_PARAM_SECURITY_CHECKS,
3697                                              &check);
3698                 params[1] = OSSL_PARAM_construct_end();
3699                 OSSL_PROVIDER_get_params(prov, params);
3700                 OSSL_PROVIDER_unload(prov);
3701             }
3702             enabled = check;
3703             return enabled;
3704         }
3705         enabled = 0;
3706     }
3707     return enabled;
3708 }
3709 #endif
3710 
3711 /*
3712  * Return 1 if one of the providers named in the string is available.
3713  * The provider names are separated with whitespace.
3714  * NOTE: destructive function, it inserts '\0' after each provider name.
3715  */
3716 static int prov_available(char *providers)
3717 {
3718     char *p;
3719     int more = 1;
3720 
3721     while (more) {
3722         for (; isspace((unsigned char)(*providers)); providers++)
3723             continue;
3724         if (*providers == '\0')
3725             break;               /* End of the road */
3726         for (p = providers; *p != '\0' && !isspace((unsigned char)(*p)); p++)
3727             continue;
3728         if (*p == '\0')
3729             more = 0;
3730         else
3731             *p = '\0';
3732         if (OSSL_PROVIDER_available(libctx, providers))
3733             return 1;            /* Found one */
3734     }
3735     return 0;
3736 }
3737 
3738 /* Read and parse one test.  Return 0 if failure, 1 if okay. */
3739 static int parse(EVP_TEST *t)
3740 {
3741     KEY_LIST *key, **klist;
3742     EVP_PKEY *pkey;
3743     PAIR *pp;
3744     int i, j, skipped = 0;
3745 
3746 top:
3747     do {
3748         if (BIO_eof(t->s.fp))
3749             return EOF;
3750         clear_test(t);
3751         if (!test_readstanza(&t->s))
3752             return 0;
3753     } while (t->s.numpairs == 0);
3754     pp = &t->s.pairs[0];
3755 
3756     /* Are we adding a key? */
3757     klist = NULL;
3758     pkey = NULL;
3759 start:
3760     if (strcmp(pp->key, "PrivateKey") == 0) {
3761         pkey = PEM_read_bio_PrivateKey_ex(t->s.key, NULL, 0, NULL, libctx, NULL);
3762         if (pkey == NULL && !key_unsupported()) {
3763             EVP_PKEY_free(pkey);
3764             TEST_info("Can't read private key %s", pp->value);
3765             TEST_openssl_errors();
3766             return 0;
3767         }
3768         klist = &private_keys;
3769     } else if (strcmp(pp->key, "PublicKey") == 0) {
3770         pkey = PEM_read_bio_PUBKEY_ex(t->s.key, NULL, 0, NULL, libctx, NULL);
3771         if (pkey == NULL && !key_unsupported()) {
3772             EVP_PKEY_free(pkey);
3773             TEST_info("Can't read public key %s", pp->value);
3774             TEST_openssl_errors();
3775             return 0;
3776         }
3777         klist = &public_keys;
3778     } else if (strcmp(pp->key, "PrivateKeyRaw") == 0
3779                || strcmp(pp->key, "PublicKeyRaw") == 0 ) {
3780         char *strnid = NULL, *keydata = NULL;
3781         unsigned char *keybin;
3782         size_t keylen;
3783         int nid;
3784 
3785         if (strcmp(pp->key, "PrivateKeyRaw") == 0)
3786             klist = &private_keys;
3787         else
3788             klist = &public_keys;
3789 
3790         strnid = strchr(pp->value, ':');
3791         if (strnid != NULL) {
3792             *strnid++ = '\0';
3793             keydata = strchr(strnid, ':');
3794             if (keydata != NULL)
3795                 *keydata++ = '\0';
3796         }
3797         if (keydata == NULL) {
3798             TEST_info("Failed to parse %s value", pp->key);
3799             return 0;
3800         }
3801 
3802         nid = OBJ_txt2nid(strnid);
3803         if (nid == NID_undef) {
3804             TEST_info("Unrecognised algorithm NID");
3805             return 0;
3806         }
3807         if (!parse_bin(keydata, &keybin, &keylen)) {
3808             TEST_info("Failed to create binary key");
3809             return 0;
3810         }
3811         if (klist == &private_keys)
3812             pkey = EVP_PKEY_new_raw_private_key_ex(libctx, strnid, NULL, keybin,
3813                                                    keylen);
3814         else
3815             pkey = EVP_PKEY_new_raw_public_key_ex(libctx, strnid, NULL, keybin,
3816                                                   keylen);
3817         if (pkey == NULL && !key_unsupported()) {
3818             TEST_info("Can't read %s data", pp->key);
3819             OPENSSL_free(keybin);
3820             TEST_openssl_errors();
3821             return 0;
3822         }
3823         OPENSSL_free(keybin);
3824     } else if (strcmp(pp->key, "Availablein") == 0) {
3825         if (!prov_available(pp->value)) {
3826             TEST_info("skipping, '%s' provider not available: %s:%d",
3827                       pp->value, t->s.test_file, t->s.start);
3828                 t->skip = 1;
3829                 return 0;
3830         }
3831         skipped++;
3832         pp++;
3833         goto start;
3834     } else if (strcmp(pp->key, "FIPSversion") == 0) {
3835         if (prov_available("fips")) {
3836             j = fips_provider_version_match(libctx, pp->value);
3837             if (j < 0) {
3838                 TEST_info("Line %d: error matching FIPS versions\n", t->s.curr);
3839                 return 0;
3840             } else if (j == 0) {
3841                 TEST_info("skipping, FIPS provider incompatible version: %s:%d",
3842                           t->s.test_file, t->s.start);
3843                     t->skip = 1;
3844                     return 0;
3845             }
3846         }
3847         skipped++;
3848         pp++;
3849         goto start;
3850     }
3851 
3852     /* If we have a key add to list */
3853     if (klist != NULL) {
3854         if (find_key(NULL, pp->value, *klist)) {
3855             TEST_info("Duplicate key %s", pp->value);
3856             return 0;
3857         }
3858         if (!TEST_ptr(key = OPENSSL_malloc(sizeof(*key))))
3859             return 0;
3860         key->name = take_value(pp);
3861         key->key = pkey;
3862         key->next = *klist;
3863         *klist = key;
3864 
3865         /* Go back and start a new stanza. */
3866         if ((t->s.numpairs - skipped) != 1)
3867             TEST_info("Line %d: missing blank line\n", t->s.curr);
3868         goto top;
3869     }
3870 
3871     /* Find the test, based on first keyword. */
3872     if (!TEST_ptr(t->meth = find_test(pp->key)))
3873         return 0;
3874     if (!t->meth->init(t, pp->value)) {
3875         TEST_error("unknown %s: %s\n", pp->key, pp->value);
3876         return 0;
3877     }
3878     if (t->skip == 1) {
3879         /* TEST_info("skipping %s %s", pp->key, pp->value); */
3880         return 0;
3881     }
3882 
3883     for (pp++, i = 1; i < (t->s.numpairs - skipped); pp++, i++) {
3884         if (strcmp(pp->key, "Securitycheck") == 0) {
3885 #if defined(OPENSSL_NO_FIPS_SECURITYCHECKS)
3886 #else
3887             if (!securitycheck_enabled())
3888 #endif
3889             {
3890                 TEST_info("skipping, Securitycheck is disabled: %s:%d",
3891                           t->s.test_file, t->s.start);
3892                 t->skip = 1;
3893                 return 0;
3894             }
3895         } else if (strcmp(pp->key, "Availablein") == 0) {
3896             TEST_info("Line %d: 'Availablein' should be the first option",
3897                       t->s.curr);
3898             return 0;
3899         } else if (strcmp(pp->key, "Result") == 0) {
3900             if (t->expected_err != NULL) {
3901                 TEST_info("Line %d: multiple result lines", t->s.curr);
3902                 return 0;
3903             }
3904             t->expected_err = take_value(pp);
3905         } else if (strcmp(pp->key, "Function") == 0) {
3906             /* Ignore old line. */
3907         } else if (strcmp(pp->key, "Reason") == 0) {
3908             if (t->reason != NULL) {
3909                 TEST_info("Line %d: multiple reason lines", t->s.curr);
3910                 return 0;
3911             }
3912             t->reason = take_value(pp);
3913         } else {
3914             /* Must be test specific line: try to parse it */
3915             int rv = t->meth->parse(t, pp->key, pp->value);
3916 
3917             if (rv == 0) {
3918                 TEST_info("Line %d: unknown keyword %s", t->s.curr, pp->key);
3919                 return 0;
3920             }
3921             if (rv < 0) {
3922                 TEST_info("Line %d: error processing keyword %s = %s\n",
3923                           t->s.curr, pp->key, pp->value);
3924                 return 0;
3925             }
3926         }
3927     }
3928 
3929     return 1;
3930 }
3931 
3932 static int run_file_tests(int i)
3933 {
3934     EVP_TEST *t;
3935     const char *testfile = test_get_argument(i);
3936     int c;
3937 
3938     if (!TEST_ptr(t = OPENSSL_zalloc(sizeof(*t))))
3939         return 0;
3940     if (!test_start_file(&t->s, testfile)) {
3941         OPENSSL_free(t);
3942         return 0;
3943     }
3944 
3945     while (!BIO_eof(t->s.fp)) {
3946         c = parse(t);
3947         if (t->skip) {
3948             t->s.numskip++;
3949             continue;
3950         }
3951         if (c == 0 || !run_test(t)) {
3952             t->s.errors++;
3953             break;
3954         }
3955     }
3956     test_end_file(&t->s);
3957     clear_test(t);
3958 
3959     free_key_list(public_keys);
3960     free_key_list(private_keys);
3961     BIO_free(t->s.key);
3962     c = t->s.errors;
3963     OPENSSL_free(t);
3964     return c == 0;
3965 }
3966 
3967 const OPTIONS *test_get_options(void)
3968 {
3969     static const OPTIONS test_options[] = {
3970         OPT_TEST_OPTIONS_WITH_EXTRA_USAGE("[file...]\n"),
3971         { "config", OPT_CONFIG_FILE, '<',
3972           "The configuration file to use for the libctx" },
3973         { OPT_HELP_STR, 1, '-', "file\tFile to run tests on.\n" },
3974         { NULL }
3975     };
3976     return test_options;
3977 }
3978 
3979 int setup_tests(void)
3980 {
3981     size_t n;
3982     char *config_file = NULL;
3983 
3984     OPTION_CHOICE o;
3985 
3986     while ((o = opt_next()) != OPT_EOF) {
3987         switch (o) {
3988         case OPT_CONFIG_FILE:
3989             config_file = opt_arg();
3990             break;
3991         case OPT_TEST_CASES:
3992            break;
3993         default:
3994         case OPT_ERR:
3995             return 0;
3996         }
3997     }
3998 
3999     /*
4000      * Load the provider via configuration into the created library context.
4001      * Load the 'null' provider into the default library context to ensure that
4002      * the tests do not fallback to using the default provider.
4003      */
4004     if (!test_get_libctx(&libctx, &prov_null, config_file, NULL, NULL))
4005         return 0;
4006 
4007     n = test_get_argument_count();
4008     if (n == 0)
4009         return 0;
4010 
4011     ADD_ALL_TESTS(run_file_tests, n);
4012     return 1;
4013 }
4014 
4015 void cleanup_tests(void)
4016 {
4017     OSSL_PROVIDER_unload(prov_null);
4018     OSSL_LIB_CTX_free(libctx);
4019 }
4020 
4021 #define STR_STARTS_WITH(str, pre) OPENSSL_strncasecmp(pre, str, strlen(pre)) == 0
4022 #define STR_ENDS_WITH(str, pre)                                                \
4023 strlen(str) < strlen(pre) ? 0 : (OPENSSL_strcasecmp(pre, str + strlen(str) - strlen(pre)) == 0)
4024 
4025 static int is_digest_disabled(const char *name)
4026 {
4027 #ifdef OPENSSL_NO_BLAKE2
4028     if (STR_STARTS_WITH(name, "BLAKE"))
4029         return 1;
4030 #endif
4031 #ifdef OPENSSL_NO_MD2
4032     if (OPENSSL_strcasecmp(name, "MD2") == 0)
4033         return 1;
4034 #endif
4035 #ifdef OPENSSL_NO_MDC2
4036     if (OPENSSL_strcasecmp(name, "MDC2") == 0)
4037         return 1;
4038 #endif
4039 #ifdef OPENSSL_NO_MD4
4040     if (OPENSSL_strcasecmp(name, "MD4") == 0)
4041         return 1;
4042 #endif
4043 #ifdef OPENSSL_NO_MD5
4044     if (OPENSSL_strcasecmp(name, "MD5") == 0)
4045         return 1;
4046 #endif
4047 #ifdef OPENSSL_NO_RMD160
4048     if (OPENSSL_strcasecmp(name, "RIPEMD160") == 0)
4049         return 1;
4050 #endif
4051 #ifdef OPENSSL_NO_SM3
4052     if (OPENSSL_strcasecmp(name, "SM3") == 0)
4053         return 1;
4054 #endif
4055 #ifdef OPENSSL_NO_WHIRLPOOL
4056     if (OPENSSL_strcasecmp(name, "WHIRLPOOL") == 0)
4057         return 1;
4058 #endif
4059     return 0;
4060 }
4061 
4062 static int is_pkey_disabled(const char *name)
4063 {
4064 #ifdef OPENSSL_NO_EC
4065     if (STR_STARTS_WITH(name, "EC"))
4066         return 1;
4067 #endif
4068 #ifdef OPENSSL_NO_DH
4069     if (STR_STARTS_WITH(name, "DH"))
4070         return 1;
4071 #endif
4072 #ifdef OPENSSL_NO_DSA
4073     if (STR_STARTS_WITH(name, "DSA"))
4074         return 1;
4075 #endif
4076     return 0;
4077 }
4078 
4079 static int is_mac_disabled(const char *name)
4080 {
4081 #ifdef OPENSSL_NO_BLAKE2
4082     if (STR_STARTS_WITH(name, "BLAKE2BMAC")
4083         || STR_STARTS_WITH(name, "BLAKE2SMAC"))
4084         return 1;
4085 #endif
4086 #ifdef OPENSSL_NO_CMAC
4087     if (STR_STARTS_WITH(name, "CMAC"))
4088         return 1;
4089 #endif
4090 #ifdef OPENSSL_NO_POLY1305
4091     if (STR_STARTS_WITH(name, "Poly1305"))
4092         return 1;
4093 #endif
4094 #ifdef OPENSSL_NO_SIPHASH
4095     if (STR_STARTS_WITH(name, "SipHash"))
4096         return 1;
4097 #endif
4098     return 0;
4099 }
4100 static int is_kdf_disabled(const char *name)
4101 {
4102 #ifdef OPENSSL_NO_SCRYPT
4103     if (STR_ENDS_WITH(name, "SCRYPT"))
4104         return 1;
4105 #endif
4106     return 0;
4107 }
4108 
4109 static int is_cipher_disabled(const char *name)
4110 {
4111 #ifdef OPENSSL_NO_ARIA
4112     if (STR_STARTS_WITH(name, "ARIA"))
4113         return 1;
4114 #endif
4115 #ifdef OPENSSL_NO_BF
4116     if (STR_STARTS_WITH(name, "BF"))
4117         return 1;
4118 #endif
4119 #ifdef OPENSSL_NO_CAMELLIA
4120     if (STR_STARTS_WITH(name, "CAMELLIA"))
4121         return 1;
4122 #endif
4123 #ifdef OPENSSL_NO_CAST
4124     if (STR_STARTS_WITH(name, "CAST"))
4125         return 1;
4126 #endif
4127 #ifdef OPENSSL_NO_CHACHA
4128     if (STR_STARTS_WITH(name, "CHACHA"))
4129         return 1;
4130 #endif
4131 #ifdef OPENSSL_NO_POLY1305
4132     if (STR_ENDS_WITH(name, "Poly1305"))
4133         return 1;
4134 #endif
4135 #ifdef OPENSSL_NO_DES
4136     if (STR_STARTS_WITH(name, "DES"))
4137         return 1;
4138     if (STR_ENDS_WITH(name, "3DESwrap"))
4139         return 1;
4140 #endif
4141 #ifdef OPENSSL_NO_OCB
4142     if (STR_ENDS_WITH(name, "OCB"))
4143         return 1;
4144 #endif
4145 #ifdef OPENSSL_NO_IDEA
4146     if (STR_STARTS_WITH(name, "IDEA"))
4147         return 1;
4148 #endif
4149 #ifdef OPENSSL_NO_RC2
4150     if (STR_STARTS_WITH(name, "RC2"))
4151         return 1;
4152 #endif
4153 #ifdef OPENSSL_NO_RC4
4154     if (STR_STARTS_WITH(name, "RC4"))
4155         return 1;
4156 #endif
4157 #ifdef OPENSSL_NO_RC5
4158     if (STR_STARTS_WITH(name, "RC5"))
4159         return 1;
4160 #endif
4161 #ifdef OPENSSL_NO_SEED
4162     if (STR_STARTS_WITH(name, "SEED"))
4163         return 1;
4164 #endif
4165 #ifdef OPENSSL_NO_SIV
4166     if (STR_ENDS_WITH(name, "SIV"))
4167         return 1;
4168 #endif
4169 #ifdef OPENSSL_NO_SM4
4170     if (STR_STARTS_WITH(name, "SM4"))
4171         return 1;
4172 #endif
4173     return 0;
4174 }
4175