xref: /freebsd/crypto/openssl/test/evp_test.c (revision e9ac41698b2f322d55ccf9da50a3596edb2c1800)
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 = "";
2778     else
2779         *p++ = '\0';
2780 
2781     rv = OSSL_PARAM_allocate_from_text(kdata->p, defs, name, p,
2782                                        strlen(p), NULL);
2783     *++kdata->p = OSSL_PARAM_construct_end();
2784     if (!rv) {
2785         t->err = "KDF_PARAM_ERROR";
2786         OPENSSL_free(name);
2787         return 0;
2788     }
2789     if (strcmp(name, "digest") == 0) {
2790         if (is_digest_disabled(p)) {
2791             TEST_info("skipping, '%s' is disabled", p);
2792             t->skip = 1;
2793         }
2794     }
2795 
2796     if ((strcmp(name, "cipher") == 0
2797         || strcmp(name, "cekalg") == 0)
2798         && is_cipher_disabled(p)) {
2799         TEST_info("skipping, '%s' is disabled", p);
2800         t->skip = 1;
2801     }
2802 
2803     OPENSSL_free(name);
2804     return 1;
2805 }
2806 
2807 static int kdf_test_parse(EVP_TEST *t,
2808                           const char *keyword, const char *value)
2809 {
2810     KDF_DATA *kdata = t->data;
2811 
2812     if (strcmp(keyword, "Output") == 0)
2813         return parse_bin(value, &kdata->output, &kdata->output_len);
2814     if (strncmp(keyword, "Ctrl", 4) == 0)
2815         return kdf_test_ctrl(t, kdata->ctx, value);
2816     return 0;
2817 }
2818 
2819 static int kdf_test_run(EVP_TEST *t)
2820 {
2821     KDF_DATA *expected = t->data;
2822     unsigned char *got = NULL;
2823     size_t got_len = expected->output_len;
2824 
2825     if (!EVP_KDF_CTX_set_params(expected->ctx, expected->params)) {
2826         t->err = "KDF_CTRL_ERROR";
2827         return 1;
2828     }
2829     if (!TEST_ptr(got = OPENSSL_malloc(got_len == 0 ? 1 : got_len))) {
2830         t->err = "INTERNAL_ERROR";
2831         goto err;
2832     }
2833     if (EVP_KDF_derive(expected->ctx, got, got_len, NULL) <= 0) {
2834         t->err = "KDF_DERIVE_ERROR";
2835         goto err;
2836     }
2837     if (!memory_err_compare(t, "KDF_MISMATCH",
2838                             expected->output, expected->output_len,
2839                             got, got_len))
2840         goto err;
2841 
2842     t->err = NULL;
2843 
2844  err:
2845     OPENSSL_free(got);
2846     return 1;
2847 }
2848 
2849 static const EVP_TEST_METHOD kdf_test_method = {
2850     "KDF",
2851     kdf_test_init,
2852     kdf_test_cleanup,
2853     kdf_test_parse,
2854     kdf_test_run
2855 };
2856 
2857 /**
2858  **  PKEY KDF TESTS
2859  **/
2860 
2861 typedef struct pkey_kdf_data_st {
2862     /* Context for this operation */
2863     EVP_PKEY_CTX *ctx;
2864     /* Expected output */
2865     unsigned char *output;
2866     size_t output_len;
2867 } PKEY_KDF_DATA;
2868 
2869 /*
2870  * Perform public key operation setup: lookup key, allocated ctx and call
2871  * the appropriate initialisation function
2872  */
2873 static int pkey_kdf_test_init(EVP_TEST *t, const char *name)
2874 {
2875     PKEY_KDF_DATA *kdata = NULL;
2876 
2877     if (is_kdf_disabled(name)) {
2878         TEST_info("skipping, '%s' is disabled", name);
2879         t->skip = 1;
2880         return 1;
2881     }
2882 
2883     if (!TEST_ptr(kdata = OPENSSL_zalloc(sizeof(*kdata))))
2884         return 0;
2885 
2886     kdata->ctx = EVP_PKEY_CTX_new_from_name(libctx, name, NULL);
2887     if (kdata->ctx == NULL
2888         || EVP_PKEY_derive_init(kdata->ctx) <= 0)
2889         goto err;
2890 
2891     t->data = kdata;
2892     return 1;
2893 err:
2894     EVP_PKEY_CTX_free(kdata->ctx);
2895     OPENSSL_free(kdata);
2896     return 0;
2897 }
2898 
2899 static void pkey_kdf_test_cleanup(EVP_TEST *t)
2900 {
2901     PKEY_KDF_DATA *kdata = t->data;
2902 
2903     OPENSSL_free(kdata->output);
2904     EVP_PKEY_CTX_free(kdata->ctx);
2905 }
2906 
2907 static int pkey_kdf_test_parse(EVP_TEST *t,
2908                                const char *keyword, const char *value)
2909 {
2910     PKEY_KDF_DATA *kdata = t->data;
2911 
2912     if (strcmp(keyword, "Output") == 0)
2913         return parse_bin(value, &kdata->output, &kdata->output_len);
2914     if (strncmp(keyword, "Ctrl", 4) == 0)
2915         return pkey_test_ctrl(t, kdata->ctx, value);
2916     return 0;
2917 }
2918 
2919 static int pkey_kdf_test_run(EVP_TEST *t)
2920 {
2921     PKEY_KDF_DATA *expected = t->data;
2922     unsigned char *got = NULL;
2923     size_t got_len = 0;
2924 
2925     if (fips_provider_version_eq(libctx, 3, 0, 0)) {
2926         /* FIPS(3.0.0): can't deal with oversized output buffers #18533 */
2927         got_len = expected->output_len;
2928     } else {
2929         /* Find out the KDF output size */
2930         if (EVP_PKEY_derive(expected->ctx, NULL, &got_len) <= 0) {
2931             t->err = "INTERNAL_ERROR";
2932             goto err;
2933         }
2934 
2935         /*
2936          * We may get an absurd output size, which signals that anything goes.
2937          * If not, we specify a too big buffer for the output, to test that
2938          * EVP_PKEY_derive() can cope with it.
2939          */
2940         if (got_len == SIZE_MAX || got_len == 0)
2941             got_len = expected->output_len;
2942         else
2943             got_len = expected->output_len * 2;
2944     }
2945 
2946     if (!TEST_ptr(got = OPENSSL_malloc(got_len == 0 ? 1 : got_len))) {
2947         t->err = "INTERNAL_ERROR";
2948         goto err;
2949     }
2950     if (EVP_PKEY_derive(expected->ctx, got, &got_len) <= 0) {
2951         t->err = "KDF_DERIVE_ERROR";
2952         goto err;
2953     }
2954     if (!TEST_mem_eq(expected->output, expected->output_len, got, got_len)) {
2955         t->err = "KDF_MISMATCH";
2956         goto err;
2957     }
2958     t->err = NULL;
2959 
2960  err:
2961     OPENSSL_free(got);
2962     return 1;
2963 }
2964 
2965 static const EVP_TEST_METHOD pkey_kdf_test_method = {
2966     "PKEYKDF",
2967     pkey_kdf_test_init,
2968     pkey_kdf_test_cleanup,
2969     pkey_kdf_test_parse,
2970     pkey_kdf_test_run
2971 };
2972 
2973 /**
2974  **  KEYPAIR TESTS
2975  **/
2976 
2977 typedef struct keypair_test_data_st {
2978     EVP_PKEY *privk;
2979     EVP_PKEY *pubk;
2980 } KEYPAIR_TEST_DATA;
2981 
2982 static int keypair_test_init(EVP_TEST *t, const char *pair)
2983 {
2984     KEYPAIR_TEST_DATA *data;
2985     int rv = 0;
2986     EVP_PKEY *pk = NULL, *pubk = NULL;
2987     char *pub, *priv = NULL;
2988 
2989     /* Split private and public names. */
2990     if (!TEST_ptr(priv = OPENSSL_strdup(pair))
2991             || !TEST_ptr(pub = strchr(priv, ':'))) {
2992         t->err = "PARSING_ERROR";
2993         goto end;
2994     }
2995     *pub++ = '\0';
2996 
2997     if (!TEST_true(find_key(&pk, priv, private_keys))) {
2998         TEST_info("Can't find private key: %s", priv);
2999         t->err = "MISSING_PRIVATE_KEY";
3000         goto end;
3001     }
3002     if (!TEST_true(find_key(&pubk, pub, public_keys))) {
3003         TEST_info("Can't find public key: %s", pub);
3004         t->err = "MISSING_PUBLIC_KEY";
3005         goto end;
3006     }
3007 
3008     if (pk == NULL && pubk == NULL) {
3009         /* Both keys are listed but unsupported: skip this test */
3010         t->skip = 1;
3011         rv = 1;
3012         goto end;
3013     }
3014 
3015     if (!TEST_ptr(data = OPENSSL_malloc(sizeof(*data))))
3016         goto end;
3017     data->privk = pk;
3018     data->pubk = pubk;
3019     t->data = data;
3020     rv = 1;
3021     t->err = NULL;
3022 
3023 end:
3024     OPENSSL_free(priv);
3025     return rv;
3026 }
3027 
3028 static void keypair_test_cleanup(EVP_TEST *t)
3029 {
3030     OPENSSL_free(t->data);
3031     t->data = NULL;
3032 }
3033 
3034 /*
3035  * For tests that do not accept any custom keywords.
3036  */
3037 static int void_test_parse(EVP_TEST *t, const char *keyword, const char *value)
3038 {
3039     return 0;
3040 }
3041 
3042 static int keypair_test_run(EVP_TEST *t)
3043 {
3044     int rv = 0;
3045     const KEYPAIR_TEST_DATA *pair = t->data;
3046 
3047     if (pair->privk == NULL || pair->pubk == NULL) {
3048         /*
3049          * this can only happen if only one of the keys is not set
3050          * which means that one of them was unsupported while the
3051          * other isn't: hence a key type mismatch.
3052          */
3053         t->err = "KEYPAIR_TYPE_MISMATCH";
3054         rv = 1;
3055         goto end;
3056     }
3057 
3058     if ((rv = EVP_PKEY_eq(pair->privk, pair->pubk)) != 1 ) {
3059         if ( 0 == rv ) {
3060             t->err = "KEYPAIR_MISMATCH";
3061         } else if ( -1 == rv ) {
3062             t->err = "KEYPAIR_TYPE_MISMATCH";
3063         } else if ( -2 == rv ) {
3064             t->err = "UNSUPPORTED_KEY_COMPARISON";
3065         } else {
3066             TEST_error("Unexpected error in key comparison");
3067             rv = 0;
3068             goto end;
3069         }
3070         rv = 1;
3071         goto end;
3072     }
3073 
3074     rv = 1;
3075     t->err = NULL;
3076 
3077 end:
3078     return rv;
3079 }
3080 
3081 static const EVP_TEST_METHOD keypair_test_method = {
3082     "PrivPubKeyPair",
3083     keypair_test_init,
3084     keypair_test_cleanup,
3085     void_test_parse,
3086     keypair_test_run
3087 };
3088 
3089 /**
3090  **  KEYGEN TEST
3091  **/
3092 
3093 typedef struct keygen_test_data_st {
3094     EVP_PKEY_CTX *genctx; /* Keygen context to use */
3095     char *keyname; /* Key name to store key or NULL */
3096 } KEYGEN_TEST_DATA;
3097 
3098 static int keygen_test_init(EVP_TEST *t, const char *alg)
3099 {
3100     KEYGEN_TEST_DATA *data;
3101     EVP_PKEY_CTX *genctx;
3102     int nid = OBJ_sn2nid(alg);
3103 
3104     if (nid == NID_undef) {
3105         nid = OBJ_ln2nid(alg);
3106         if (nid == NID_undef)
3107             return 0;
3108     }
3109 
3110     if (is_pkey_disabled(alg)) {
3111         t->skip = 1;
3112         return 1;
3113     }
3114     if (!TEST_ptr(genctx = EVP_PKEY_CTX_new_from_name(libctx, alg, NULL)))
3115         goto err;
3116 
3117     if (EVP_PKEY_keygen_init(genctx) <= 0) {
3118         t->err = "KEYGEN_INIT_ERROR";
3119         goto err;
3120     }
3121 
3122     if (!TEST_ptr(data = OPENSSL_malloc(sizeof(*data))))
3123         goto err;
3124     data->genctx = genctx;
3125     data->keyname = NULL;
3126     t->data = data;
3127     t->err = NULL;
3128     return 1;
3129 
3130 err:
3131     EVP_PKEY_CTX_free(genctx);
3132     return 0;
3133 }
3134 
3135 static void keygen_test_cleanup(EVP_TEST *t)
3136 {
3137     KEYGEN_TEST_DATA *keygen = t->data;
3138 
3139     EVP_PKEY_CTX_free(keygen->genctx);
3140     OPENSSL_free(keygen->keyname);
3141     OPENSSL_free(t->data);
3142     t->data = NULL;
3143 }
3144 
3145 static int keygen_test_parse(EVP_TEST *t,
3146                              const char *keyword, const char *value)
3147 {
3148     KEYGEN_TEST_DATA *keygen = t->data;
3149 
3150     if (strcmp(keyword, "KeyName") == 0)
3151         return TEST_ptr(keygen->keyname = OPENSSL_strdup(value));
3152     if (strcmp(keyword, "Ctrl") == 0)
3153         return pkey_test_ctrl(t, keygen->genctx, value);
3154     return 0;
3155 }
3156 
3157 static int keygen_test_run(EVP_TEST *t)
3158 {
3159     KEYGEN_TEST_DATA *keygen = t->data;
3160     EVP_PKEY *pkey = NULL;
3161     int rv = 1;
3162 
3163     if (EVP_PKEY_keygen(keygen->genctx, &pkey) <= 0) {
3164         t->err = "KEYGEN_GENERATE_ERROR";
3165         goto err;
3166     }
3167 
3168     if (!evp_pkey_is_provided(pkey)) {
3169         TEST_info("Warning: legacy key generated %s", keygen->keyname);
3170         goto err;
3171     }
3172     if (keygen->keyname != NULL) {
3173         KEY_LIST *key;
3174 
3175         rv = 0;
3176         if (find_key(NULL, keygen->keyname, private_keys)) {
3177             TEST_info("Duplicate key %s", keygen->keyname);
3178             goto err;
3179         }
3180 
3181         if (!TEST_ptr(key = OPENSSL_malloc(sizeof(*key))))
3182             goto err;
3183         key->name = keygen->keyname;
3184         keygen->keyname = NULL;
3185         key->key = pkey;
3186         key->next = private_keys;
3187         private_keys = key;
3188         rv = 1;
3189     } else {
3190         EVP_PKEY_free(pkey);
3191     }
3192 
3193     t->err = NULL;
3194 
3195 err:
3196     return rv;
3197 }
3198 
3199 static const EVP_TEST_METHOD keygen_test_method = {
3200     "KeyGen",
3201     keygen_test_init,
3202     keygen_test_cleanup,
3203     keygen_test_parse,
3204     keygen_test_run,
3205 };
3206 
3207 /**
3208  **  DIGEST SIGN+VERIFY TESTS
3209  **/
3210 
3211 typedef struct {
3212     int is_verify; /* Set to 1 if verifying */
3213     int is_oneshot; /* Set to 1 for one shot operation */
3214     const EVP_MD *md; /* Digest to use */
3215     EVP_MD_CTX *ctx; /* Digest context */
3216     EVP_PKEY_CTX *pctx;
3217     STACK_OF(EVP_TEST_BUFFER) *input; /* Input data: streaming */
3218     unsigned char *osin; /* Input data if one shot */
3219     size_t osin_len; /* Input length data if one shot */
3220     unsigned char *output; /* Expected output */
3221     size_t output_len; /* Expected output length */
3222 } DIGESTSIGN_DATA;
3223 
3224 static int digestsigver_test_init(EVP_TEST *t, const char *alg, int is_verify,
3225                                   int is_oneshot)
3226 {
3227     const EVP_MD *md = NULL;
3228     DIGESTSIGN_DATA *mdat;
3229 
3230     if (strcmp(alg, "NULL") != 0) {
3231         if (is_digest_disabled(alg)) {
3232             t->skip = 1;
3233             return 1;
3234         }
3235         md = EVP_get_digestbyname(alg);
3236         if (md == NULL)
3237             return 0;
3238     }
3239     if (!TEST_ptr(mdat = OPENSSL_zalloc(sizeof(*mdat))))
3240         return 0;
3241     mdat->md = md;
3242     if (!TEST_ptr(mdat->ctx = EVP_MD_CTX_new())) {
3243         OPENSSL_free(mdat);
3244         return 0;
3245     }
3246     mdat->is_verify = is_verify;
3247     mdat->is_oneshot = is_oneshot;
3248     t->data = mdat;
3249     return 1;
3250 }
3251 
3252 static int digestsign_test_init(EVP_TEST *t, const char *alg)
3253 {
3254     return digestsigver_test_init(t, alg, 0, 0);
3255 }
3256 
3257 static void digestsigver_test_cleanup(EVP_TEST *t)
3258 {
3259     DIGESTSIGN_DATA *mdata = t->data;
3260 
3261     EVP_MD_CTX_free(mdata->ctx);
3262     sk_EVP_TEST_BUFFER_pop_free(mdata->input, evp_test_buffer_free);
3263     OPENSSL_free(mdata->osin);
3264     OPENSSL_free(mdata->output);
3265     OPENSSL_free(mdata);
3266     t->data = NULL;
3267 }
3268 
3269 static int digestsigver_test_parse(EVP_TEST *t,
3270                                    const char *keyword, const char *value)
3271 {
3272     DIGESTSIGN_DATA *mdata = t->data;
3273 
3274     if (strcmp(keyword, "Key") == 0) {
3275         EVP_PKEY *pkey = NULL;
3276         int rv = 0;
3277         const char *name = mdata->md == NULL ? NULL : EVP_MD_get0_name(mdata->md);
3278 
3279         if (mdata->is_verify)
3280             rv = find_key(&pkey, value, public_keys);
3281         if (rv == 0)
3282             rv = find_key(&pkey, value, private_keys);
3283         if (rv == 0 || pkey == NULL) {
3284             t->skip = 1;
3285             return 1;
3286         }
3287         if (mdata->is_verify) {
3288             if (!EVP_DigestVerifyInit_ex(mdata->ctx, &mdata->pctx, name, libctx,
3289                                          NULL, pkey, NULL))
3290                 t->err = "DIGESTVERIFYINIT_ERROR";
3291             return 1;
3292         }
3293         if (!EVP_DigestSignInit_ex(mdata->ctx, &mdata->pctx, name, libctx, NULL,
3294                                    pkey, NULL))
3295             t->err = "DIGESTSIGNINIT_ERROR";
3296         return 1;
3297     }
3298 
3299     if (strcmp(keyword, "Input") == 0) {
3300         if (mdata->is_oneshot)
3301             return parse_bin(value, &mdata->osin, &mdata->osin_len);
3302         return evp_test_buffer_append(value, &mdata->input);
3303     }
3304     if (strcmp(keyword, "Output") == 0)
3305         return parse_bin(value, &mdata->output, &mdata->output_len);
3306 
3307     if (!mdata->is_oneshot) {
3308         if (strcmp(keyword, "Count") == 0)
3309             return evp_test_buffer_set_count(value, mdata->input);
3310         if (strcmp(keyword, "Ncopy") == 0)
3311             return evp_test_buffer_ncopy(value, mdata->input);
3312     }
3313     if (strcmp(keyword, "Ctrl") == 0) {
3314         if (mdata->pctx == NULL)
3315             return -1;
3316         return pkey_test_ctrl(t, mdata->pctx, value);
3317     }
3318     return 0;
3319 }
3320 
3321 static int digestsign_update_fn(void *ctx, const unsigned char *buf,
3322                                 size_t buflen)
3323 {
3324     return EVP_DigestSignUpdate(ctx, buf, buflen);
3325 }
3326 
3327 static int digestsign_test_run(EVP_TEST *t)
3328 {
3329     DIGESTSIGN_DATA *expected = t->data;
3330     unsigned char *got = NULL;
3331     size_t got_len;
3332 
3333     if (!evp_test_buffer_do(expected->input, digestsign_update_fn,
3334                             expected->ctx)) {
3335         t->err = "DIGESTUPDATE_ERROR";
3336         goto err;
3337     }
3338 
3339     if (!EVP_DigestSignFinal(expected->ctx, NULL, &got_len)) {
3340         t->err = "DIGESTSIGNFINAL_LENGTH_ERROR";
3341         goto err;
3342     }
3343     if (!TEST_ptr(got = OPENSSL_malloc(got_len))) {
3344         t->err = "MALLOC_FAILURE";
3345         goto err;
3346     }
3347     got_len *= 2;
3348     if (!EVP_DigestSignFinal(expected->ctx, got, &got_len)) {
3349         t->err = "DIGESTSIGNFINAL_ERROR";
3350         goto err;
3351     }
3352     if (!memory_err_compare(t, "SIGNATURE_MISMATCH",
3353                             expected->output, expected->output_len,
3354                             got, got_len))
3355         goto err;
3356 
3357     t->err = NULL;
3358  err:
3359     OPENSSL_free(got);
3360     return 1;
3361 }
3362 
3363 static const EVP_TEST_METHOD digestsign_test_method = {
3364     "DigestSign",
3365     digestsign_test_init,
3366     digestsigver_test_cleanup,
3367     digestsigver_test_parse,
3368     digestsign_test_run
3369 };
3370 
3371 static int digestverify_test_init(EVP_TEST *t, const char *alg)
3372 {
3373     return digestsigver_test_init(t, alg, 1, 0);
3374 }
3375 
3376 static int digestverify_update_fn(void *ctx, const unsigned char *buf,
3377                                   size_t buflen)
3378 {
3379     return EVP_DigestVerifyUpdate(ctx, buf, buflen);
3380 }
3381 
3382 static int digestverify_test_run(EVP_TEST *t)
3383 {
3384     DIGESTSIGN_DATA *mdata = t->data;
3385 
3386     if (!evp_test_buffer_do(mdata->input, digestverify_update_fn, mdata->ctx)) {
3387         t->err = "DIGESTUPDATE_ERROR";
3388         return 1;
3389     }
3390 
3391     if (EVP_DigestVerifyFinal(mdata->ctx, mdata->output,
3392                               mdata->output_len) <= 0)
3393         t->err = "VERIFY_ERROR";
3394     return 1;
3395 }
3396 
3397 static const EVP_TEST_METHOD digestverify_test_method = {
3398     "DigestVerify",
3399     digestverify_test_init,
3400     digestsigver_test_cleanup,
3401     digestsigver_test_parse,
3402     digestverify_test_run
3403 };
3404 
3405 static int oneshot_digestsign_test_init(EVP_TEST *t, const char *alg)
3406 {
3407     return digestsigver_test_init(t, alg, 0, 1);
3408 }
3409 
3410 static int oneshot_digestsign_test_run(EVP_TEST *t)
3411 {
3412     DIGESTSIGN_DATA *expected = t->data;
3413     unsigned char *got = NULL;
3414     size_t got_len;
3415 
3416     if (!EVP_DigestSign(expected->ctx, NULL, &got_len,
3417                         expected->osin, expected->osin_len)) {
3418         t->err = "DIGESTSIGN_LENGTH_ERROR";
3419         goto err;
3420     }
3421     if (!TEST_ptr(got = OPENSSL_malloc(got_len))) {
3422         t->err = "MALLOC_FAILURE";
3423         goto err;
3424     }
3425     got_len *= 2;
3426     if (!EVP_DigestSign(expected->ctx, got, &got_len,
3427                         expected->osin, expected->osin_len)) {
3428         t->err = "DIGESTSIGN_ERROR";
3429         goto err;
3430     }
3431     if (!memory_err_compare(t, "SIGNATURE_MISMATCH",
3432                             expected->output, expected->output_len,
3433                             got, got_len))
3434         goto err;
3435 
3436     t->err = NULL;
3437  err:
3438     OPENSSL_free(got);
3439     return 1;
3440 }
3441 
3442 static const EVP_TEST_METHOD oneshot_digestsign_test_method = {
3443     "OneShotDigestSign",
3444     oneshot_digestsign_test_init,
3445     digestsigver_test_cleanup,
3446     digestsigver_test_parse,
3447     oneshot_digestsign_test_run
3448 };
3449 
3450 static int oneshot_digestverify_test_init(EVP_TEST *t, const char *alg)
3451 {
3452     return digestsigver_test_init(t, alg, 1, 1);
3453 }
3454 
3455 static int oneshot_digestverify_test_run(EVP_TEST *t)
3456 {
3457     DIGESTSIGN_DATA *mdata = t->data;
3458 
3459     if (EVP_DigestVerify(mdata->ctx, mdata->output, mdata->output_len,
3460                          mdata->osin, mdata->osin_len) <= 0)
3461         t->err = "VERIFY_ERROR";
3462     return 1;
3463 }
3464 
3465 static const EVP_TEST_METHOD oneshot_digestverify_test_method = {
3466     "OneShotDigestVerify",
3467     oneshot_digestverify_test_init,
3468     digestsigver_test_cleanup,
3469     digestsigver_test_parse,
3470     oneshot_digestverify_test_run
3471 };
3472 
3473 
3474 /**
3475  **  PARSING AND DISPATCH
3476  **/
3477 
3478 static const EVP_TEST_METHOD *evp_test_list[] = {
3479     &rand_test_method,
3480     &cipher_test_method,
3481     &digest_test_method,
3482     &digestsign_test_method,
3483     &digestverify_test_method,
3484     &encode_test_method,
3485     &kdf_test_method,
3486     &pkey_kdf_test_method,
3487     &keypair_test_method,
3488     &keygen_test_method,
3489     &mac_test_method,
3490     &oneshot_digestsign_test_method,
3491     &oneshot_digestverify_test_method,
3492     &pbe_test_method,
3493     &pdecrypt_test_method,
3494     &pderive_test_method,
3495     &psign_test_method,
3496     &pverify_recover_test_method,
3497     &pverify_test_method,
3498     NULL
3499 };
3500 
3501 static const EVP_TEST_METHOD *find_test(const char *name)
3502 {
3503     const EVP_TEST_METHOD **tt;
3504 
3505     for (tt = evp_test_list; *tt; tt++) {
3506         if (strcmp(name, (*tt)->name) == 0)
3507             return *tt;
3508     }
3509     return NULL;
3510 }
3511 
3512 static void clear_test(EVP_TEST *t)
3513 {
3514     test_clearstanza(&t->s);
3515     ERR_clear_error();
3516     if (t->data != NULL) {
3517         if (t->meth != NULL)
3518             t->meth->cleanup(t);
3519         OPENSSL_free(t->data);
3520         t->data = NULL;
3521     }
3522     OPENSSL_free(t->expected_err);
3523     t->expected_err = NULL;
3524     OPENSSL_free(t->reason);
3525     t->reason = NULL;
3526 
3527     /* Text literal. */
3528     t->err = NULL;
3529     t->skip = 0;
3530     t->meth = NULL;
3531 }
3532 
3533 /* Check for errors in the test structure; return 1 if okay, else 0. */
3534 static int check_test_error(EVP_TEST *t)
3535 {
3536     unsigned long err;
3537     const char *reason;
3538 
3539     if (t->err == NULL && t->expected_err == NULL)
3540         return 1;
3541     if (t->err != NULL && t->expected_err == NULL) {
3542         if (t->aux_err != NULL) {
3543             TEST_info("%s:%d: Source of above error (%s); unexpected error %s",
3544                       t->s.test_file, t->s.start, t->aux_err, t->err);
3545         } else {
3546             TEST_info("%s:%d: Source of above error; unexpected error %s",
3547                       t->s.test_file, t->s.start, t->err);
3548         }
3549         return 0;
3550     }
3551     if (t->err == NULL && t->expected_err != NULL) {
3552         TEST_info("%s:%d: Succeeded but was expecting %s",
3553                   t->s.test_file, t->s.start, t->expected_err);
3554         return 0;
3555     }
3556 
3557     if (strcmp(t->err, t->expected_err) != 0) {
3558         TEST_info("%s:%d: Expected %s got %s",
3559                   t->s.test_file, t->s.start, t->expected_err, t->err);
3560         return 0;
3561     }
3562 
3563     if (t->reason == NULL)
3564         return 1;
3565 
3566     if (t->reason == NULL) {
3567         TEST_info("%s:%d: Test is missing function or reason code",
3568                   t->s.test_file, t->s.start);
3569         return 0;
3570     }
3571 
3572     err = ERR_peek_error();
3573     if (err == 0) {
3574         TEST_info("%s:%d: Expected error \"%s\" not set",
3575                   t->s.test_file, t->s.start, t->reason);
3576         return 0;
3577     }
3578 
3579     reason = ERR_reason_error_string(err);
3580     if (reason == NULL) {
3581         TEST_info("%s:%d: Expected error \"%s\", no strings available."
3582                   " Assuming ok.",
3583                   t->s.test_file, t->s.start, t->reason);
3584         return 1;
3585     }
3586 
3587     if (strcmp(reason, t->reason) == 0)
3588         return 1;
3589 
3590     TEST_info("%s:%d: Expected error \"%s\", got \"%s\"",
3591               t->s.test_file, t->s.start, t->reason, reason);
3592 
3593     return 0;
3594 }
3595 
3596 /* Run a parsed test. Log a message and return 0 on error. */
3597 static int run_test(EVP_TEST *t)
3598 {
3599     if (t->meth == NULL)
3600         return 1;
3601     t->s.numtests++;
3602     if (t->skip) {
3603         t->s.numskip++;
3604     } else {
3605         /* run the test */
3606         if (t->err == NULL && t->meth->run_test(t) != 1) {
3607             TEST_info("%s:%d %s error",
3608                       t->s.test_file, t->s.start, t->meth->name);
3609             return 0;
3610         }
3611         if (!check_test_error(t)) {
3612             TEST_openssl_errors();
3613             t->s.errors++;
3614         }
3615     }
3616 
3617     /* clean it up */
3618     return 1;
3619 }
3620 
3621 static int find_key(EVP_PKEY **ppk, const char *name, KEY_LIST *lst)
3622 {
3623     for (; lst != NULL; lst = lst->next) {
3624         if (strcmp(lst->name, name) == 0) {
3625             if (ppk != NULL)
3626                 *ppk = lst->key;
3627             return 1;
3628         }
3629     }
3630     return 0;
3631 }
3632 
3633 static void free_key_list(KEY_LIST *lst)
3634 {
3635     while (lst != NULL) {
3636         KEY_LIST *next = lst->next;
3637 
3638         EVP_PKEY_free(lst->key);
3639         OPENSSL_free(lst->name);
3640         OPENSSL_free(lst);
3641         lst = next;
3642     }
3643 }
3644 
3645 /*
3646  * Is the key type an unsupported algorithm?
3647  */
3648 static int key_unsupported(void)
3649 {
3650     long err = ERR_peek_last_error();
3651     int lib = ERR_GET_LIB(err);
3652     long reason = ERR_GET_REASON(err);
3653 
3654     if ((lib == ERR_LIB_EVP && reason == EVP_R_UNSUPPORTED_ALGORITHM)
3655         || (lib == ERR_LIB_EVP && reason == EVP_R_DECODE_ERROR)
3656         || reason == ERR_R_UNSUPPORTED) {
3657         ERR_clear_error();
3658         return 1;
3659     }
3660 #ifndef OPENSSL_NO_EC
3661     /*
3662      * If EC support is enabled we should catch also EC_R_UNKNOWN_GROUP as an
3663      * hint to an unsupported algorithm/curve (e.g. if binary EC support is
3664      * disabled).
3665      */
3666     if (lib == ERR_LIB_EC
3667         && (reason == EC_R_UNKNOWN_GROUP
3668             || reason == EC_R_INVALID_CURVE)) {
3669         ERR_clear_error();
3670         return 1;
3671     }
3672 #endif /* OPENSSL_NO_EC */
3673     return 0;
3674 }
3675 
3676 /* NULL out the value from |pp| but return it.  This "steals" a pointer. */
3677 static char *take_value(PAIR *pp)
3678 {
3679     char *p = pp->value;
3680 
3681     pp->value = NULL;
3682     return p;
3683 }
3684 
3685 #if !defined(OPENSSL_NO_FIPS_SECURITYCHECKS)
3686 static int securitycheck_enabled(void)
3687 {
3688     static int enabled = -1;
3689 
3690     if (enabled == -1) {
3691         if (OSSL_PROVIDER_available(libctx, "fips")) {
3692             OSSL_PARAM params[2];
3693             OSSL_PROVIDER *prov = NULL;
3694             int check = 1;
3695 
3696             prov = OSSL_PROVIDER_load(libctx, "fips");
3697             if (prov != NULL) {
3698                 params[0] =
3699                     OSSL_PARAM_construct_int(OSSL_PROV_PARAM_SECURITY_CHECKS,
3700                                              &check);
3701                 params[1] = OSSL_PARAM_construct_end();
3702                 OSSL_PROVIDER_get_params(prov, params);
3703                 OSSL_PROVIDER_unload(prov);
3704             }
3705             enabled = check;
3706             return enabled;
3707         }
3708         enabled = 0;
3709     }
3710     return enabled;
3711 }
3712 #endif
3713 
3714 /*
3715  * Return 1 if one of the providers named in the string is available.
3716  * The provider names are separated with whitespace.
3717  * NOTE: destructive function, it inserts '\0' after each provider name.
3718  */
3719 static int prov_available(char *providers)
3720 {
3721     char *p;
3722     int more = 1;
3723 
3724     while (more) {
3725         for (; isspace((unsigned char)(*providers)); providers++)
3726             continue;
3727         if (*providers == '\0')
3728             break;               /* End of the road */
3729         for (p = providers; *p != '\0' && !isspace((unsigned char)(*p)); p++)
3730             continue;
3731         if (*p == '\0')
3732             more = 0;
3733         else
3734             *p = '\0';
3735         if (OSSL_PROVIDER_available(libctx, providers))
3736             return 1;            /* Found one */
3737     }
3738     return 0;
3739 }
3740 
3741 /* Read and parse one test.  Return 0 if failure, 1 if okay. */
3742 static int parse(EVP_TEST *t)
3743 {
3744     KEY_LIST *key, **klist;
3745     EVP_PKEY *pkey;
3746     PAIR *pp;
3747     int i, j, skipped = 0;
3748 
3749 top:
3750     do {
3751         if (BIO_eof(t->s.fp))
3752             return EOF;
3753         clear_test(t);
3754         if (!test_readstanza(&t->s))
3755             return 0;
3756     } while (t->s.numpairs == 0);
3757     pp = &t->s.pairs[0];
3758 
3759     /* Are we adding a key? */
3760     klist = NULL;
3761     pkey = NULL;
3762 start:
3763     if (strcmp(pp->key, "PrivateKey") == 0) {
3764         pkey = PEM_read_bio_PrivateKey_ex(t->s.key, NULL, 0, NULL, libctx, NULL);
3765         if (pkey == NULL && !key_unsupported()) {
3766             EVP_PKEY_free(pkey);
3767             TEST_info("Can't read private key %s", pp->value);
3768             TEST_openssl_errors();
3769             return 0;
3770         }
3771         klist = &private_keys;
3772     } else if (strcmp(pp->key, "PublicKey") == 0) {
3773         pkey = PEM_read_bio_PUBKEY_ex(t->s.key, NULL, 0, NULL, libctx, NULL);
3774         if (pkey == NULL && !key_unsupported()) {
3775             EVP_PKEY_free(pkey);
3776             TEST_info("Can't read public key %s", pp->value);
3777             TEST_openssl_errors();
3778             return 0;
3779         }
3780         klist = &public_keys;
3781     } else if (strcmp(pp->key, "PrivateKeyRaw") == 0
3782                || strcmp(pp->key, "PublicKeyRaw") == 0 ) {
3783         char *strnid = NULL, *keydata = NULL;
3784         unsigned char *keybin;
3785         size_t keylen;
3786         int nid;
3787 
3788         if (strcmp(pp->key, "PrivateKeyRaw") == 0)
3789             klist = &private_keys;
3790         else
3791             klist = &public_keys;
3792 
3793         strnid = strchr(pp->value, ':');
3794         if (strnid != NULL) {
3795             *strnid++ = '\0';
3796             keydata = strchr(strnid, ':');
3797             if (keydata != NULL)
3798                 *keydata++ = '\0';
3799         }
3800         if (keydata == NULL) {
3801             TEST_info("Failed to parse %s value", pp->key);
3802             return 0;
3803         }
3804 
3805         nid = OBJ_txt2nid(strnid);
3806         if (nid == NID_undef) {
3807             TEST_info("Unrecognised algorithm NID");
3808             return 0;
3809         }
3810         if (!parse_bin(keydata, &keybin, &keylen)) {
3811             TEST_info("Failed to create binary key");
3812             return 0;
3813         }
3814         if (klist == &private_keys)
3815             pkey = EVP_PKEY_new_raw_private_key_ex(libctx, strnid, NULL, keybin,
3816                                                    keylen);
3817         else
3818             pkey = EVP_PKEY_new_raw_public_key_ex(libctx, strnid, NULL, keybin,
3819                                                   keylen);
3820         if (pkey == NULL && !key_unsupported()) {
3821             TEST_info("Can't read %s data", pp->key);
3822             OPENSSL_free(keybin);
3823             TEST_openssl_errors();
3824             return 0;
3825         }
3826         OPENSSL_free(keybin);
3827     } else if (strcmp(pp->key, "Availablein") == 0) {
3828         if (!prov_available(pp->value)) {
3829             TEST_info("skipping, '%s' provider not available: %s:%d",
3830                       pp->value, t->s.test_file, t->s.start);
3831                 t->skip = 1;
3832                 return 0;
3833         }
3834         skipped++;
3835         pp++;
3836         goto start;
3837     } else if (strcmp(pp->key, "FIPSversion") == 0) {
3838         if (prov_available("fips")) {
3839             j = fips_provider_version_match(libctx, pp->value);
3840             if (j < 0) {
3841                 TEST_info("Line %d: error matching FIPS versions\n", t->s.curr);
3842                 return 0;
3843             } else if (j == 0) {
3844                 TEST_info("skipping, FIPS provider incompatible version: %s:%d",
3845                           t->s.test_file, t->s.start);
3846                     t->skip = 1;
3847                     return 0;
3848             }
3849         }
3850         skipped++;
3851         pp++;
3852         goto start;
3853     }
3854 
3855     /* If we have a key add to list */
3856     if (klist != NULL) {
3857         if (find_key(NULL, pp->value, *klist)) {
3858             TEST_info("Duplicate key %s", pp->value);
3859             return 0;
3860         }
3861         if (!TEST_ptr(key = OPENSSL_malloc(sizeof(*key))))
3862             return 0;
3863         key->name = take_value(pp);
3864         key->key = pkey;
3865         key->next = *klist;
3866         *klist = key;
3867 
3868         /* Go back and start a new stanza. */
3869         if ((t->s.numpairs - skipped) != 1)
3870             TEST_info("Line %d: missing blank line\n", t->s.curr);
3871         goto top;
3872     }
3873 
3874     /* Find the test, based on first keyword. */
3875     if (!TEST_ptr(t->meth = find_test(pp->key)))
3876         return 0;
3877     if (!t->meth->init(t, pp->value)) {
3878         TEST_error("unknown %s: %s\n", pp->key, pp->value);
3879         return 0;
3880     }
3881     if (t->skip == 1) {
3882         /* TEST_info("skipping %s %s", pp->key, pp->value); */
3883         return 0;
3884     }
3885 
3886     for (pp++, i = 1; i < (t->s.numpairs - skipped); pp++, i++) {
3887         if (strcmp(pp->key, "Securitycheck") == 0) {
3888 #if defined(OPENSSL_NO_FIPS_SECURITYCHECKS)
3889 #else
3890             if (!securitycheck_enabled())
3891 #endif
3892             {
3893                 TEST_info("skipping, Securitycheck is disabled: %s:%d",
3894                           t->s.test_file, t->s.start);
3895                 t->skip = 1;
3896                 return 0;
3897             }
3898         } else if (strcmp(pp->key, "Availablein") == 0) {
3899             TEST_info("Line %d: 'Availablein' should be the first option",
3900                       t->s.curr);
3901             return 0;
3902         } else if (strcmp(pp->key, "Result") == 0) {
3903             if (t->expected_err != NULL) {
3904                 TEST_info("Line %d: multiple result lines", t->s.curr);
3905                 return 0;
3906             }
3907             t->expected_err = take_value(pp);
3908         } else if (strcmp(pp->key, "Function") == 0) {
3909             /* Ignore old line. */
3910         } else if (strcmp(pp->key, "Reason") == 0) {
3911             if (t->reason != NULL) {
3912                 TEST_info("Line %d: multiple reason lines", t->s.curr);
3913                 return 0;
3914             }
3915             t->reason = take_value(pp);
3916         } else {
3917             /* Must be test specific line: try to parse it */
3918             int rv = t->meth->parse(t, pp->key, pp->value);
3919 
3920             if (rv == 0) {
3921                 TEST_info("Line %d: unknown keyword %s", t->s.curr, pp->key);
3922                 return 0;
3923             }
3924             if (rv < 0) {
3925                 TEST_info("Line %d: error processing keyword %s = %s\n",
3926                           t->s.curr, pp->key, pp->value);
3927                 return 0;
3928             }
3929         }
3930     }
3931 
3932     return 1;
3933 }
3934 
3935 static int run_file_tests(int i)
3936 {
3937     EVP_TEST *t;
3938     const char *testfile = test_get_argument(i);
3939     int c;
3940 
3941     if (!TEST_ptr(t = OPENSSL_zalloc(sizeof(*t))))
3942         return 0;
3943     if (!test_start_file(&t->s, testfile)) {
3944         OPENSSL_free(t);
3945         return 0;
3946     }
3947 
3948     while (!BIO_eof(t->s.fp)) {
3949         c = parse(t);
3950         if (t->skip) {
3951             t->s.numskip++;
3952             continue;
3953         }
3954         if (c == 0 || !run_test(t)) {
3955             t->s.errors++;
3956             break;
3957         }
3958     }
3959     test_end_file(&t->s);
3960     clear_test(t);
3961 
3962     free_key_list(public_keys);
3963     free_key_list(private_keys);
3964     BIO_free(t->s.key);
3965     c = t->s.errors;
3966     OPENSSL_free(t);
3967     return c == 0;
3968 }
3969 
3970 const OPTIONS *test_get_options(void)
3971 {
3972     static const OPTIONS test_options[] = {
3973         OPT_TEST_OPTIONS_WITH_EXTRA_USAGE("[file...]\n"),
3974         { "config", OPT_CONFIG_FILE, '<',
3975           "The configuration file to use for the libctx" },
3976         { OPT_HELP_STR, 1, '-', "file\tFile to run tests on.\n" },
3977         { NULL }
3978     };
3979     return test_options;
3980 }
3981 
3982 int setup_tests(void)
3983 {
3984     size_t n;
3985     char *config_file = NULL;
3986 
3987     OPTION_CHOICE o;
3988 
3989     while ((o = opt_next()) != OPT_EOF) {
3990         switch (o) {
3991         case OPT_CONFIG_FILE:
3992             config_file = opt_arg();
3993             break;
3994         case OPT_TEST_CASES:
3995            break;
3996         default:
3997         case OPT_ERR:
3998             return 0;
3999         }
4000     }
4001 
4002     /*
4003      * Load the provider via configuration into the created library context.
4004      * Load the 'null' provider into the default library context to ensure that
4005      * the tests do not fallback to using the default provider.
4006      */
4007     if (!test_get_libctx(&libctx, &prov_null, config_file, NULL, NULL))
4008         return 0;
4009 
4010     n = test_get_argument_count();
4011     if (n == 0)
4012         return 0;
4013 
4014     ADD_ALL_TESTS(run_file_tests, n);
4015     return 1;
4016 }
4017 
4018 void cleanup_tests(void)
4019 {
4020     OSSL_PROVIDER_unload(prov_null);
4021     OSSL_LIB_CTX_free(libctx);
4022 }
4023 
4024 #define STR_STARTS_WITH(str, pre) OPENSSL_strncasecmp(pre, str, strlen(pre)) == 0
4025 #define STR_ENDS_WITH(str, pre)                                                \
4026 strlen(str) < strlen(pre) ? 0 : (OPENSSL_strcasecmp(pre, str + strlen(str) - strlen(pre)) == 0)
4027 
4028 static int is_digest_disabled(const char *name)
4029 {
4030 #ifdef OPENSSL_NO_BLAKE2
4031     if (STR_STARTS_WITH(name, "BLAKE"))
4032         return 1;
4033 #endif
4034 #ifdef OPENSSL_NO_MD2
4035     if (OPENSSL_strcasecmp(name, "MD2") == 0)
4036         return 1;
4037 #endif
4038 #ifdef OPENSSL_NO_MDC2
4039     if (OPENSSL_strcasecmp(name, "MDC2") == 0)
4040         return 1;
4041 #endif
4042 #ifdef OPENSSL_NO_MD4
4043     if (OPENSSL_strcasecmp(name, "MD4") == 0)
4044         return 1;
4045 #endif
4046 #ifdef OPENSSL_NO_MD5
4047     if (OPENSSL_strcasecmp(name, "MD5") == 0)
4048         return 1;
4049 #endif
4050 #ifdef OPENSSL_NO_RMD160
4051     if (OPENSSL_strcasecmp(name, "RIPEMD160") == 0)
4052         return 1;
4053 #endif
4054 #ifdef OPENSSL_NO_SM3
4055     if (OPENSSL_strcasecmp(name, "SM3") == 0)
4056         return 1;
4057 #endif
4058 #ifdef OPENSSL_NO_WHIRLPOOL
4059     if (OPENSSL_strcasecmp(name, "WHIRLPOOL") == 0)
4060         return 1;
4061 #endif
4062     return 0;
4063 }
4064 
4065 static int is_pkey_disabled(const char *name)
4066 {
4067 #ifdef OPENSSL_NO_EC
4068     if (STR_STARTS_WITH(name, "EC"))
4069         return 1;
4070 #endif
4071 #ifdef OPENSSL_NO_DH
4072     if (STR_STARTS_WITH(name, "DH"))
4073         return 1;
4074 #endif
4075 #ifdef OPENSSL_NO_DSA
4076     if (STR_STARTS_WITH(name, "DSA"))
4077         return 1;
4078 #endif
4079     return 0;
4080 }
4081 
4082 static int is_mac_disabled(const char *name)
4083 {
4084 #ifdef OPENSSL_NO_BLAKE2
4085     if (STR_STARTS_WITH(name, "BLAKE2BMAC")
4086         || STR_STARTS_WITH(name, "BLAKE2SMAC"))
4087         return 1;
4088 #endif
4089 #ifdef OPENSSL_NO_CMAC
4090     if (STR_STARTS_WITH(name, "CMAC"))
4091         return 1;
4092 #endif
4093 #ifdef OPENSSL_NO_POLY1305
4094     if (STR_STARTS_WITH(name, "Poly1305"))
4095         return 1;
4096 #endif
4097 #ifdef OPENSSL_NO_SIPHASH
4098     if (STR_STARTS_WITH(name, "SipHash"))
4099         return 1;
4100 #endif
4101     return 0;
4102 }
4103 static int is_kdf_disabled(const char *name)
4104 {
4105 #ifdef OPENSSL_NO_SCRYPT
4106     if (STR_ENDS_WITH(name, "SCRYPT"))
4107         return 1;
4108 #endif
4109     return 0;
4110 }
4111 
4112 static int is_cipher_disabled(const char *name)
4113 {
4114 #ifdef OPENSSL_NO_ARIA
4115     if (STR_STARTS_WITH(name, "ARIA"))
4116         return 1;
4117 #endif
4118 #ifdef OPENSSL_NO_BF
4119     if (STR_STARTS_WITH(name, "BF"))
4120         return 1;
4121 #endif
4122 #ifdef OPENSSL_NO_CAMELLIA
4123     if (STR_STARTS_WITH(name, "CAMELLIA"))
4124         return 1;
4125 #endif
4126 #ifdef OPENSSL_NO_CAST
4127     if (STR_STARTS_WITH(name, "CAST"))
4128         return 1;
4129 #endif
4130 #ifdef OPENSSL_NO_CHACHA
4131     if (STR_STARTS_WITH(name, "CHACHA"))
4132         return 1;
4133 #endif
4134 #ifdef OPENSSL_NO_POLY1305
4135     if (STR_ENDS_WITH(name, "Poly1305"))
4136         return 1;
4137 #endif
4138 #ifdef OPENSSL_NO_DES
4139     if (STR_STARTS_WITH(name, "DES"))
4140         return 1;
4141     if (STR_ENDS_WITH(name, "3DESwrap"))
4142         return 1;
4143 #endif
4144 #ifdef OPENSSL_NO_OCB
4145     if (STR_ENDS_WITH(name, "OCB"))
4146         return 1;
4147 #endif
4148 #ifdef OPENSSL_NO_IDEA
4149     if (STR_STARTS_WITH(name, "IDEA"))
4150         return 1;
4151 #endif
4152 #ifdef OPENSSL_NO_RC2
4153     if (STR_STARTS_WITH(name, "RC2"))
4154         return 1;
4155 #endif
4156 #ifdef OPENSSL_NO_RC4
4157     if (STR_STARTS_WITH(name, "RC4"))
4158         return 1;
4159 #endif
4160 #ifdef OPENSSL_NO_RC5
4161     if (STR_STARTS_WITH(name, "RC5"))
4162         return 1;
4163 #endif
4164 #ifdef OPENSSL_NO_SEED
4165     if (STR_STARTS_WITH(name, "SEED"))
4166         return 1;
4167 #endif
4168 #ifdef OPENSSL_NO_SIV
4169     if (STR_ENDS_WITH(name, "SIV"))
4170         return 1;
4171 #endif
4172 #ifdef OPENSSL_NO_SM4
4173     if (STR_STARTS_WITH(name, "SM4"))
4174         return 1;
4175 #endif
4176     return 0;
4177 }
4178