xref: /openssl/test/evp_test.c (revision bb2be4f0)
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 <openssl/thread.h>
26 #include "internal/numbers.h"
27 #include "internal/nelem.h"
28 #include "internal/sizes.h"
29 #include "crypto/evp.h"
30 #include "testutil.h"
31 
32 typedef struct evp_test_buffer_st EVP_TEST_BUFFER;
33 DEFINE_STACK_OF(EVP_TEST_BUFFER)
34 
35 #define AAD_NUM 4
36 
37 typedef struct evp_test_method_st EVP_TEST_METHOD;
38 
39 /* Structure holding test information */
40 typedef struct evp_test_st {
41     STANZA s;                     /* Common test stanza */
42     char *name;
43     int skip;                     /* Current test should be skipped */
44     const EVP_TEST_METHOD *meth;  /* method for this test */
45     const char *err, *aux_err;    /* Error string for test */
46     char *expected_err;           /* Expected error value of test */
47     char *reason;                 /* Expected error reason string */
48     void *data;                   /* test specific data */
49     int expect_unapproved;
50 } EVP_TEST;
51 
52 /* Test method structure */
53 struct evp_test_method_st {
54     /* Name of test as it appears in file */
55     const char *name;
56     /* Initialise test for "alg" */
57     int (*init) (EVP_TEST *t, const char *alg);
58     /* Clean up method */
59     void (*cleanup) (EVP_TEST *t);
60     /* Test specific name value pair processing */
61     int (*parse) (EVP_TEST *t, const char *name, const char *value);
62     /* Run the test itself */
63     int (*run_test) (EVP_TEST *t);
64 };
65 
66 /* Linked list of named keys. */
67 typedef struct key_list_st {
68     char *name;
69     EVP_PKEY *key;
70     struct key_list_st *next;
71 } KEY_LIST;
72 
73 typedef enum OPTION_choice {
74     OPT_ERR = -1,
75     OPT_EOF = 0,
76     OPT_CONFIG_FILE,
77     OPT_IN_PLACE,
78     OPT_PROVIDER_NAME,
79     OPT_PROV_PROPQUERY,
80     OPT_DATA_CHUNK,
81     OPT_TEST_ENUM
82 } OPTION_CHOICE;
83 
84 static OSSL_PROVIDER *prov_null = NULL;
85 static OSSL_PROVIDER *libprov = NULL;
86 static OSSL_LIB_CTX *libctx = NULL;
87 static int fips_indicator_callback_unapproved_count = 0;
88 
89 /* List of public and private keys */
90 static KEY_LIST *private_keys;
91 static KEY_LIST *public_keys;
92 
93 static int find_key(EVP_PKEY **ppk, const char *name, KEY_LIST *lst);
94 static int parse_bin(const char *value, unsigned char **buf, size_t *buflen);
95 static int parse_bin_chunk(const char *value, size_t offset, size_t max,
96                            unsigned char **buf, size_t *buflen, size_t *out_offset);
97 static int is_digest_disabled(const char *name);
98 static int is_pkey_disabled(const char *name);
99 static int is_mac_disabled(const char *name);
100 static int is_cipher_disabled(const char *name);
101 static int is_kdf_disabled(const char *name);
102 
103 /* A callback that is triggered if fips unapproved mode is detected */
fips_indicator_cb(const char * type,const char * desc,const OSSL_PARAM params[])104 static int fips_indicator_cb(const char *type, const char *desc,
105                              const OSSL_PARAM params[])
106 {
107     fips_indicator_callback_unapproved_count++;
108     TEST_info("(Indicator Callback received %s : %s is not approved)", type, desc);
109     return 1;
110 }
111 
check_fips_approved(EVP_TEST * t,int approved)112 static int check_fips_approved(EVP_TEST *t, int approved)
113 {
114     /*
115      * If the expected result is approved
116      * then it is expected that approved will be 1
117      * and the fips indicator callback has not been triggered, otherwise
118      * approved should be 0 and the fips indicator callback should be triggered.
119      */
120     if (t->expect_unapproved) {
121         if (approved == 1 || fips_indicator_callback_unapproved_count == 0) {
122             TEST_error("Test is not expected to be FIPS approved");
123             return 0;
124         }
125     } else {
126         if (approved == 0 || fips_indicator_callback_unapproved_count > 0) {
127             TEST_error("Test is expected to be FIPS approved");
128             return 0;
129         }
130     }
131     return 1;
132 }
133 
mac_check_fips_approved(EVP_MAC_CTX * ctx,EVP_TEST * t)134 static int mac_check_fips_approved(EVP_MAC_CTX *ctx, EVP_TEST *t)
135 {
136     OSSL_PARAM params[2] = { OSSL_PARAM_END, OSSL_PARAM_END };
137     /*
138      * For any getters that do not handle the FIPS indicator assume a default
139      * value of approved.
140      */
141     int approved = 1;
142 
143     if (EVP_MAC_CTX_gettable_params(ctx) == NULL)
144         return 1;
145 
146     params[0] = OSSL_PARAM_construct_int(OSSL_MAC_PARAM_FIPS_APPROVED_INDICATOR,
147                                          &approved);
148     if (!EVP_MAC_CTX_get_params(ctx, params))
149         return 0;
150     return check_fips_approved(t, approved);
151 }
152 
pkey_check_fips_approved(EVP_PKEY_CTX * ctx,EVP_TEST * t)153 static int pkey_check_fips_approved(EVP_PKEY_CTX *ctx, EVP_TEST *t)
154 {
155     OSSL_PARAM params[2] = { OSSL_PARAM_END, OSSL_PARAM_END };
156     /*
157      * For any getters that do not handle the FIPS indicator assume a default
158      * value of approved.
159      */
160     int approved = 1;
161     const OSSL_PARAM *gettables = EVP_PKEY_CTX_gettable_params(ctx);
162 
163     if (gettables == NULL
164             || OSSL_PARAM_locate_const(gettables,
165                                        OSSL_ALG_PARAM_FIPS_APPROVED_INDICATOR)
166             == NULL)
167         return 1;
168 
169     /* Older providers dont have a gettable */
170     if (EVP_PKEY_CTX_gettable_params(ctx) == NULL)
171         return 1;
172 
173     params[0] = OSSL_PARAM_construct_int(OSSL_ALG_PARAM_FIPS_APPROVED_INDICATOR,
174                                          &approved);
175     if (!EVP_PKEY_CTX_get_params(ctx, params))
176         return 0;
177     return check_fips_approved(t, approved);
178 }
179 
rand_check_fips_approved(EVP_RAND_CTX * ctx,EVP_TEST * t)180 static int rand_check_fips_approved(EVP_RAND_CTX *ctx, EVP_TEST *t)
181 {
182     OSSL_PARAM params[2] = { OSSL_PARAM_END, OSSL_PARAM_END };
183     /*
184      * For any getters that do not handle the FIPS indicator assume a default
185      * value of approved.
186      */
187     int approved = 1;
188 
189     if (EVP_RAND_CTX_gettable_params(ctx) == NULL)
190         return 1;
191 
192     params[0] = OSSL_PARAM_construct_int(OSSL_DRBG_PARAM_FIPS_APPROVED_INDICATOR,
193                                          &approved);
194     if (!EVP_RAND_CTX_get_params(ctx, params))
195         return 0;
196     return check_fips_approved(t, approved);
197 }
198 
ctrladd(STACK_OF (OPENSSL_STRING)* controls,const char * value)199 static int ctrladd(STACK_OF(OPENSSL_STRING) *controls, const char *value)
200 {
201     char *data = OPENSSL_strdup(value);
202 
203     if (data == NULL)
204         return -1;
205     return sk_OPENSSL_STRING_push(controls, data) > 0;
206 }
207 
208 /* Because OPENSSL_free is a macro, it can't be passed as a function pointer */
openssl_free(char * m)209 static void openssl_free(char *m)
210 {
211     OPENSSL_free(m);
212 }
213 
ctrlfree(STACK_OF (OPENSSL_STRING)* controls)214 static void ctrlfree(STACK_OF(OPENSSL_STRING) *controls)
215 {
216     sk_OPENSSL_STRING_pop_free(controls, openssl_free);
217 }
218 
219 /*
220  * This is used if ctrl2params() passes settables as NULL.
221  * A default list of settable OSSL_PARAM that may be set during an operations
222  * init().
223  * Using the algorithms settable list is problematic since it requires that the
224  * init() has already run.
225  */
226 static const OSSL_PARAM settable_ctx_params[] = {
227     OSSL_PARAM_int("key-check", NULL),
228     OSSL_PARAM_int("digest-check", NULL),
229     OSSL_PARAM_int("ems_check", NULL),
230     OSSL_PARAM_int("sign-check", NULL),
231     OSSL_PARAM_int("encrypt-check", NULL),
232     OSSL_PARAM_int("rsa-pss-saltlen-check", NULL),
233     OSSL_PARAM_int("sign-x931-pad-check", NULL),
234     OSSL_PARAM_END
235 };
236 
ctrl2params(EVP_TEST * t,STACK_OF (OPENSSL_STRING)* controls,const OSSL_PARAM * settables,OSSL_PARAM params[],size_t params_sz,size_t * params_n)237 static int ctrl2params(EVP_TEST *t, STACK_OF(OPENSSL_STRING) *controls,
238                        const OSSL_PARAM *settables,
239                        OSSL_PARAM params[], size_t params_sz, size_t *params_n)
240 {
241     int i;
242 
243     if (settables == NULL)
244         settables = settable_ctx_params;
245     /* check bounds */
246     if (*params_n + sk_OPENSSL_STRING_num(controls) >= params_sz) {
247         t->err = "ERR_TOO_MANY_PARAMETERS";
248         goto err;
249     }
250     for (i = 0; i < sk_OPENSSL_STRING_num(controls); i++) {
251         char *tmpkey, *tmpval;
252         char *value = sk_OPENSSL_STRING_value(controls, i);
253 
254         if (!TEST_ptr(tmpkey = OPENSSL_strdup(value))) {
255             t->err = "ERR_PARAM_ERROR";
256             goto err;
257         }
258         tmpval = strchr(tmpkey, ':');
259         if (tmpval != NULL)
260             *tmpval++ = '\0';
261 
262         if (tmpval == NULL
263             || !OSSL_PARAM_allocate_from_text(&params[*params_n],
264                                               settables,
265                                               tmpkey, tmpval,
266                                               strlen(tmpval), NULL)) {
267             OPENSSL_free(tmpkey);
268             t->err = "ERR_PARAM_ERROR";
269             goto err;
270         }
271         *params_n += 1;
272         OPENSSL_free(tmpkey);
273     }
274     params[*params_n] = OSSL_PARAM_construct_end();
275     return 1;
276 err:
277     return 0;
278 }
279 
ctrl2params_free(OSSL_PARAM params[],size_t params_n,size_t params_n_allocstart)280 static void ctrl2params_free(OSSL_PARAM params[],
281                              size_t params_n, size_t params_n_allocstart)
282 {
283     while (params_n-- > params_n_allocstart) {
284         OPENSSL_free(params[params_n].data);
285     }
286 }
287 
kdf_check_fips_approved(EVP_KDF_CTX * ctx,EVP_TEST * t)288 static int kdf_check_fips_approved(EVP_KDF_CTX *ctx, EVP_TEST *t)
289 {
290     OSSL_PARAM params[2] = { OSSL_PARAM_END, OSSL_PARAM_END };
291     int approved = 1;
292 
293     params[0] = OSSL_PARAM_construct_int(OSSL_KDF_PARAM_FIPS_APPROVED_INDICATOR,
294                                          &approved);
295     if (!EVP_KDF_CTX_get_params(ctx, params))
296         return 0;
297     return check_fips_approved(t, approved);
298 }
299 
cipher_check_fips_approved(EVP_CIPHER_CTX * ctx,EVP_TEST * t)300 static int cipher_check_fips_approved(EVP_CIPHER_CTX *ctx, EVP_TEST *t)
301 {
302     OSSL_PARAM params[2] = { OSSL_PARAM_END, OSSL_PARAM_END };
303     int approved = 1;
304 
305     params[0] = OSSL_PARAM_construct_int(OSSL_CIPHER_PARAM_FIPS_APPROVED_INDICATOR,
306                                          &approved);
307     if (!EVP_CIPHER_CTX_get_params(ctx, params))
308         return 0;
309     return check_fips_approved(t, approved);
310 }
311 
312 /*
313  * Compare two memory regions for equality, returning zero if they differ.
314  * However, if there is expected to be an error and the actual error
315  * matches then the memory is expected to be different so handle this
316  * case without producing unnecessary test framework output.
317  */
memory_err_compare(EVP_TEST * t,const char * err,const void * expected,size_t expected_len,const void * got,size_t got_len)318 static int memory_err_compare(EVP_TEST *t, const char *err,
319                               const void *expected, size_t expected_len,
320                               const void *got, size_t got_len)
321 {
322     int r;
323 
324     if (t->expected_err != NULL && strcmp(t->expected_err, err) == 0)
325         r = !TEST_mem_ne(expected, expected_len, got, got_len);
326     else
327         r = TEST_mem_eq(expected, expected_len, got, got_len);
328     if (!r)
329         t->err = err;
330     return r;
331 }
332 
333 /* Option specific for evp test */
334 static int process_mode_in_place;
335 static const char *propquery = NULL;
336 static int data_chunk_size;
337 
evp_test_process_mode(char * mode)338 static int evp_test_process_mode(char *mode)
339 {
340     if (strcmp(mode, "in_place") == 0)
341         return 1;
342     else if (strcmp(mode, "both") == 0)
343         return 0;
344     return -1;
345 }
346 
347 /*
348  * Structure used to hold a list of blocks of memory to test
349  * calls to "update" like functions.
350  */
351 struct evp_test_buffer_st {
352     unsigned char *buf;
353     size_t buflen;
354     size_t count;
355     int count_set;
356 };
357 
evp_test_buffer_free(EVP_TEST_BUFFER * db)358 static void evp_test_buffer_free(EVP_TEST_BUFFER *db)
359 {
360     if (db != NULL) {
361         OPENSSL_free(db->buf);
362         OPENSSL_free(db);
363     }
364 }
365 
366 /* append buffer to a list */
evp_test_buffer_append(const char * value,size_t max_len,STACK_OF (EVP_TEST_BUFFER)** sk)367 static int evp_test_buffer_append(const char *value, size_t max_len,
368                                   STACK_OF(EVP_TEST_BUFFER) **sk)
369 {
370     EVP_TEST_BUFFER *db = NULL;
371     int rv = 0;
372     size_t offset = 0;
373 
374     if (*sk == NULL && !TEST_ptr(*sk = sk_EVP_TEST_BUFFER_new_null()))
375         goto err;
376 
377     do {
378         if (!TEST_ptr(db = OPENSSL_zalloc(sizeof(*db))))
379             goto err;
380         if (max_len == 0) {
381             /* parse all in one shot */
382             if ((rv = parse_bin(value, &db->buf, &db->buflen)) != 1)
383                 goto err;
384         } else {
385             /* parse in chunks */
386             size_t new_offset = 0;
387 
388             if ((rv = parse_bin_chunk(value, offset, max_len, &db->buf,
389                                       &db->buflen, &new_offset)) == -1)
390                 goto err;
391             offset = new_offset;
392         }
393 
394         db->count = 1;
395         db->count_set = 0;
396 
397         if (db->buf == NULL)
398             evp_test_buffer_free(db);
399         else if (db->buf != NULL && !sk_EVP_TEST_BUFFER_push(*sk, db))
400             goto err;
401         /* if processing by chunks, continue until the whole value is parsed */
402     } while (rv == 1 && max_len != 0);
403 
404     return 1;
405 
406 err:
407     evp_test_buffer_free(db);
408     return 0;
409 }
410 
411 /* replace last buffer in list with copies of itself */
evp_test_buffer_ncopy(const char * value,STACK_OF (EVP_TEST_BUFFER)* sk)412 static int evp_test_buffer_ncopy(const char *value,
413                                  STACK_OF(EVP_TEST_BUFFER) *sk)
414 {
415     EVP_TEST_BUFFER *db;
416     unsigned char *tbuf, *p;
417     size_t tbuflen;
418     int ncopy = atoi(value);
419     int i;
420 
421     if (ncopy <= 0)
422         return 0;
423     if (sk == NULL || sk_EVP_TEST_BUFFER_num(sk) == 0)
424         return 0;
425     db = sk_EVP_TEST_BUFFER_value(sk, sk_EVP_TEST_BUFFER_num(sk) - 1);
426 
427     tbuflen = db->buflen * ncopy;
428     if (!TEST_ptr(tbuf = OPENSSL_malloc(tbuflen)))
429         return 0;
430     for (i = 0, p = tbuf; i < ncopy; i++, p += db->buflen)
431         memcpy(p, db->buf, db->buflen);
432 
433     OPENSSL_free(db->buf);
434     db->buf = tbuf;
435     db->buflen = tbuflen;
436     return 1;
437 }
438 
439 /* set repeat count for last buffer in list */
evp_test_buffer_set_count(const char * value,STACK_OF (EVP_TEST_BUFFER)* sk)440 static int evp_test_buffer_set_count(const char *value,
441                                      STACK_OF(EVP_TEST_BUFFER) *sk)
442 {
443     EVP_TEST_BUFFER *db;
444     int count = atoi(value);
445 
446     if (count <= 0)
447         return 0;
448 
449     if (sk == NULL || sk_EVP_TEST_BUFFER_num(sk) == 0)
450         return 0;
451 
452     db = sk_EVP_TEST_BUFFER_value(sk, sk_EVP_TEST_BUFFER_num(sk) - 1);
453     if (db->count_set != 0)
454         return 0;
455 
456     db->count = (size_t)count;
457     db->count_set = 1;
458     return 1;
459 }
460 
461 /* call "fn" with each element of the list in turn */
evp_test_buffer_do(STACK_OF (EVP_TEST_BUFFER)* sk,int (* fn)(void * ctx,const unsigned char * buf,size_t buflen),void * ctx)462 static int evp_test_buffer_do(STACK_OF(EVP_TEST_BUFFER) *sk,
463                               int (*fn)(void *ctx,
464                                         const unsigned char *buf,
465                                         size_t buflen),
466                               void *ctx)
467 {
468     int i;
469 
470     for (i = 0; i < sk_EVP_TEST_BUFFER_num(sk); i++) {
471         EVP_TEST_BUFFER *tb = sk_EVP_TEST_BUFFER_value(sk, i);
472         size_t j;
473 
474         for (j = 0; j < tb->count; j++) {
475             if (fn(ctx, tb->buf, tb->buflen) <= 0)
476                 return 0;
477         }
478     }
479     return 1;
480 }
481 
482 /*
483  * Unescape some sequences in string literals (only \n for now).
484  * Return an allocated buffer, set |out_len|.  If |input_len|
485  * is zero, get an empty buffer but set length to zero.
486  */
unescape(const char * input,size_t input_len,size_t * out_len)487 static unsigned char* unescape(const char *input, size_t input_len,
488                                size_t *out_len)
489 {
490     unsigned char *ret, *p;
491     size_t i;
492 
493     if (input_len == 0) {
494         *out_len = 0;
495         return OPENSSL_zalloc(1);
496     }
497 
498     /* Escaping is non-expanding; over-allocate original size for simplicity. */
499     if (!TEST_ptr(ret = p = OPENSSL_malloc(input_len)))
500         return NULL;
501 
502     for (i = 0; i < input_len; i++) {
503         if (*input == '\\') {
504             if (i == input_len - 1 || *++input != 'n') {
505                 TEST_error("Bad escape sequence in file");
506                 goto err;
507             }
508             *p++ = '\n';
509             i++;
510             input++;
511         } else {
512             *p++ = *input++;
513         }
514     }
515 
516     *out_len = p - ret;
517     return ret;
518 
519  err:
520     OPENSSL_free(ret);
521     return NULL;
522 }
523 
524 /*
525  * For a hex string "value" convert to a binary allocated buffer.
526  * Return 1 on success or 0 on failure.
527  */
parse_bin(const char * value,unsigned char ** buf,size_t * buflen)528 static int parse_bin(const char *value, unsigned char **buf, size_t *buflen)
529 {
530     long len;
531 
532     /* Check for NULL literal */
533     if (strcmp(value, "NULL") == 0) {
534         *buf = NULL;
535         *buflen = 0;
536         return 1;
537     }
538 
539     /* Check for empty value */
540     if (*value == '\0') {
541         /*
542          * Don't return NULL for zero length buffer. This is needed for
543          * some tests with empty keys: HMAC_Init_ex() expects a non-NULL key
544          * buffer even if the key length is 0, in order to detect key reset.
545          */
546         *buf = OPENSSL_malloc(1);
547         if (*buf == NULL)
548             return 0;
549         **buf = 0;
550         *buflen = 0;
551         return 1;
552     }
553 
554     /* Check for string literal */
555     if (value[0] == '"') {
556         size_t vlen = strlen(++value);
557 
558         if (vlen == 0 || value[vlen - 1] != '"')
559             return 0;
560         vlen--;
561         *buf = unescape(value, vlen, buflen);
562         return *buf == NULL ? 0 : 1;
563     }
564 
565     /* Otherwise assume as hex literal and convert it to binary buffer */
566     if (!TEST_ptr(*buf = OPENSSL_hexstr2buf(value, &len))) {
567         TEST_info("Can't convert %s", value);
568         TEST_openssl_errors();
569         return -1;
570     }
571     /* Size of input buffer means we'll never overflow */
572     *buflen = len;
573     return 1;
574 }
575 
576 /*
577  * Convert at maximum "max" bytes to a binary allocated buffer.
578  * Return 1 on success, -1 on failure or 0 for end of value string.
579  */
parse_bin_chunk(const char * value,size_t offset,size_t max,unsigned char ** buf,size_t * buflen,size_t * out_offset)580 static int parse_bin_chunk(const char *value, size_t offset, size_t max,
581                            unsigned char **buf, size_t *buflen, size_t *out_offset)
582 {
583     size_t vlen;
584     size_t chunk_len;
585     const char *value_str = value[0] == '"' ? value + offset + 1 : value + offset;
586 
587     if (max < 1)
588         return -1;
589 
590     if (*value == '\0' || strcmp(value, "\"\"") == 0) {
591         *buf = OPENSSL_malloc(1);
592         if (*buf == NULL)
593             return 0;
594         **buf = 0;
595         *buflen = 0;
596         return 0;
597     }
598 
599     if (*value_str == '\0')
600         return 0;
601 
602     vlen = strlen(value_str);
603     if (value[0] == '"') {
604         /* Parse string literal */
605         if (vlen == 1 && value_str[0] != '"')
606             /* Missing ending quotation mark */
607             return -1;
608         if (vlen == 1 && value_str[0] == '"')
609             /* End of value */
610             return 0;
611         vlen--;
612         chunk_len = max > vlen ? vlen : max;
613         if ((*buf = unescape(value_str, chunk_len, buflen)) == NULL)
614             return -1;
615     } else {
616         /* Parse hex string chunk */
617         long len;
618         char *chunk = NULL;
619 
620         chunk_len = 2 * max > vlen ? vlen : 2 * max;
621         chunk = OPENSSL_strndup(value_str, chunk_len);
622         if (chunk == NULL)
623             return -1;
624         if (!TEST_ptr(*buf = OPENSSL_hexstr2buf(chunk, &len))) {
625             OPENSSL_free(chunk);
626             TEST_openssl_errors();
627             return -1;
628         }
629         OPENSSL_free(chunk);
630         *buflen = len;
631     }
632     *out_offset = value[0] == '"' ? offset + (*buflen) : offset + 2 * (*buflen);
633     return 1;
634 }
635 
636 /**
637  **  MESSAGE DIGEST TESTS
638  **/
639 
640 typedef struct digest_data_st {
641     /* Digest this test is for */
642     const EVP_MD *digest;
643     EVP_MD *fetched_digest;
644     /* Input to digest */
645     STACK_OF(EVP_TEST_BUFFER) *input;
646     /* Expected output */
647     unsigned char *output;
648     size_t output_len;
649     /* Padding type */
650     int pad_type;
651     /* XOF mode? */
652     int xof;
653     /* Size for variable output length but non-XOF */
654     size_t digest_size;
655 } DIGEST_DATA;
656 
digest_test_init(EVP_TEST * t,const char * alg)657 static int digest_test_init(EVP_TEST *t, const char *alg)
658 {
659     DIGEST_DATA *mdat;
660     const EVP_MD *digest;
661     EVP_MD *fetched_digest;
662 
663     if (is_digest_disabled(alg)) {
664         TEST_info("skipping, '%s' is disabled", alg);
665         t->skip = 1;
666         return 1;
667     }
668 
669     if ((digest = fetched_digest = EVP_MD_fetch(libctx, alg, propquery)) == NULL
670         && (digest = EVP_get_digestbyname(alg)) == NULL)
671         return 0;
672     if (!TEST_ptr(mdat = OPENSSL_zalloc(sizeof(*mdat))))
673         return 0;
674     t->data = mdat;
675     mdat->digest = digest;
676     mdat->fetched_digest = fetched_digest;
677     mdat->pad_type = 0;
678     mdat->xof = 0;
679     if (fetched_digest != NULL)
680         TEST_info("%s is fetched", alg);
681     return 1;
682 }
683 
digest_test_cleanup(EVP_TEST * t)684 static void digest_test_cleanup(EVP_TEST *t)
685 {
686     DIGEST_DATA *mdat = t->data;
687 
688     sk_EVP_TEST_BUFFER_pop_free(mdat->input, evp_test_buffer_free);
689     OPENSSL_free(mdat->output);
690     EVP_MD_free(mdat->fetched_digest);
691 }
692 
digest_test_parse(EVP_TEST * t,const char * keyword,const char * value)693 static int digest_test_parse(EVP_TEST *t,
694                              const char *keyword, const char *value)
695 {
696     DIGEST_DATA *mdata = t->data;
697 
698     if (strcmp(keyword, "Input") == 0)
699         return evp_test_buffer_append(value, data_chunk_size, &mdata->input);
700     if (strcmp(keyword, "Output") == 0)
701         return parse_bin(value, &mdata->output, &mdata->output_len);
702     if (strcmp(keyword, "Count") == 0)
703         return evp_test_buffer_set_count(value, mdata->input);
704     if (strcmp(keyword, "Ncopy") == 0)
705         return evp_test_buffer_ncopy(value, mdata->input);
706     if (strcmp(keyword, "Padding") == 0)
707         return (mdata->pad_type = atoi(value)) > 0;
708     if (strcmp(keyword, "XOF") == 0)
709         return (mdata->xof = atoi(value)) > 0;
710     if (strcmp(keyword, "OutputSize") == 0) {
711         int sz;
712 
713         sz = atoi(value);
714         if (sz < 0)
715             return -1;
716         mdata->digest_size = sz;
717         return 1;
718     }
719     return 0;
720 }
721 
digest_update_fn(void * ctx,const unsigned char * buf,size_t buflen)722 static int digest_update_fn(void *ctx, const unsigned char *buf, size_t buflen)
723 {
724     return EVP_DigestUpdate(ctx, buf, buflen);
725 }
726 
test_duplicate_md_ctx(EVP_TEST * t,EVP_MD_CTX * mctx)727 static int test_duplicate_md_ctx(EVP_TEST *t, EVP_MD_CTX *mctx)
728 {
729     char dont[] = "touch";
730 
731     if (!TEST_ptr(mctx))
732         return 0;
733     if (!EVP_DigestFinalXOF(mctx, (unsigned char *)dont, 0)) {
734         EVP_MD_CTX_free(mctx);
735         t->err = "DIGESTFINALXOF_ERROR";
736         return 0;
737     }
738     if (!TEST_str_eq(dont, "touch")) {
739         EVP_MD_CTX_free(mctx);
740         t->err = "DIGESTFINALXOF_ERROR";
741         return 0;
742     }
743     EVP_MD_CTX_free(mctx);
744     return 1;
745 }
746 
digest_test_run(EVP_TEST * t)747 static int digest_test_run(EVP_TEST *t)
748 {
749     DIGEST_DATA *expected = t->data;
750     EVP_TEST_BUFFER *inbuf;
751     EVP_MD_CTX *mctx;
752     unsigned char *got = NULL;
753     unsigned int got_len;
754     size_t size = 0;
755     int xof = 0;
756     OSSL_PARAM params[4], *p = &params[0];
757 
758     t->err = "TEST_FAILURE";
759     if (!TEST_ptr(mctx = EVP_MD_CTX_new()))
760         goto err;
761 
762     got = OPENSSL_malloc(expected->output_len > EVP_MAX_MD_SIZE ?
763                          expected->output_len : EVP_MAX_MD_SIZE);
764     if (!TEST_ptr(got))
765         goto err;
766 
767     if (expected->xof > 0) {
768         xof |= 1;
769         *p++ = OSSL_PARAM_construct_size_t(OSSL_DIGEST_PARAM_XOFLEN,
770                                            &expected->output_len);
771     }
772     if (expected->digest_size > 0) {
773         *p++ = OSSL_PARAM_construct_size_t(OSSL_DIGEST_PARAM_SIZE,
774                                            &expected->digest_size);
775     }
776     if (expected->pad_type > 0)
777         *p++ = OSSL_PARAM_construct_int(OSSL_DIGEST_PARAM_PAD_TYPE,
778                                         &expected->pad_type);
779     *p++ = OSSL_PARAM_construct_end();
780 
781     if (!EVP_DigestInit_ex2(mctx, expected->digest, params)) {
782         t->err = "DIGESTINIT_ERROR";
783         goto err;
784     }
785 
786     if (!evp_test_buffer_do(expected->input, digest_update_fn, mctx)) {
787         t->err = "DIGESTUPDATE_ERROR";
788         goto err;
789     }
790 
791     xof |= EVP_MD_xof(expected->digest);
792     if (xof) {
793         EVP_MD_CTX *mctx_cpy;
794 
795         if (!TEST_ptr(mctx_cpy = EVP_MD_CTX_new())) {
796             goto err;
797         }
798         if (!TEST_true(EVP_MD_CTX_copy(mctx_cpy, mctx))) {
799             EVP_MD_CTX_free(mctx_cpy);
800             goto err;
801         } else if (!test_duplicate_md_ctx(t, mctx_cpy)) {
802             goto err;
803         }
804 
805         if (!test_duplicate_md_ctx(t, EVP_MD_CTX_dup(mctx)))
806             goto err;
807 
808         got_len = expected->output_len;
809         if (!EVP_DigestFinalXOF(mctx, got, got_len)) {
810             t->err = "DIGESTFINALXOF_ERROR";
811             goto err;
812         }
813     } else {
814         if (!EVP_DigestFinal(mctx, got, &got_len)) {
815             t->err = "DIGESTFINAL_ERROR";
816             goto err;
817         }
818     }
819     if (!TEST_int_eq(expected->output_len, got_len)) {
820         t->err = "DIGEST_LENGTH_MISMATCH";
821         goto err;
822     }
823     if (!memory_err_compare(t, "DIGEST_MISMATCH",
824                             expected->output, expected->output_len,
825                             got, got_len))
826         goto err;
827 
828     t->err = NULL;
829 
830     /* Test the EVP_Q_digest interface as well */
831     if (sk_EVP_TEST_BUFFER_num(expected->input) == 1
832             && !xof
833             /* This should never fail but we need the returned pointer now */
834             && !TEST_ptr(inbuf = sk_EVP_TEST_BUFFER_value(expected->input, 0))
835             && !inbuf->count_set) {
836         OPENSSL_cleanse(got, got_len);
837         if (!TEST_true(EVP_Q_digest(libctx,
838                                     EVP_MD_get0_name(expected->fetched_digest),
839                                     NULL, inbuf->buf, inbuf->buflen,
840                                     got, &size))
841                 || !TEST_mem_eq(got, size,
842                                 expected->output, expected->output_len)) {
843             t->err = "EVP_Q_digest failed";
844             goto err;
845         }
846     }
847 
848  err:
849     OPENSSL_free(got);
850     EVP_MD_CTX_free(mctx);
851     return 1;
852 }
853 
854 static const EVP_TEST_METHOD digest_test_method = {
855     "Digest",
856     digest_test_init,
857     digest_test_cleanup,
858     digest_test_parse,
859     digest_test_run
860 };
861 
862 /**
863 ***  CIPHER TESTS
864 **/
865 
866 typedef struct cipher_data_st {
867     const EVP_CIPHER *cipher;
868     EVP_CIPHER *fetched_cipher;
869     int enc;
870     /* EVP_CIPH_GCM_MODE, EVP_CIPH_CCM_MODE or EVP_CIPH_OCB_MODE if AEAD */
871     int aead;
872     unsigned char *key;
873     size_t key_len;
874     size_t key_bits; /* Used by RC2 */
875     unsigned char *iv;
876     unsigned char *next_iv; /* Expected IV state after operation */
877     unsigned int rounds;
878     size_t iv_len;
879     unsigned char *plaintext;
880     size_t plaintext_len;
881     unsigned char *ciphertext;
882     size_t ciphertext_len;
883     /* AEAD ciphers only */
884     unsigned char *aad[AAD_NUM];
885     size_t aad_len[AAD_NUM];
886     int tls_aad;
887     int tls_version;
888     unsigned char *tag;
889     const char *cts_mode;
890     size_t tag_len;
891     int tag_late;
892     unsigned char *mac_key;
893     size_t mac_key_len;
894     const char *xts_standard;
895     STACK_OF(OPENSSL_STRING) *init_controls; /* collection of controls */
896 } CIPHER_DATA;
897 
898 
899 /*
900  * XTS, SIV, CCM, stitched ciphers and Wrap modes have special
901  * requirements about input lengths so we don't fragment for those
902  */
cipher_test_valid_fragmentation(CIPHER_DATA * cdat)903 static int cipher_test_valid_fragmentation(CIPHER_DATA *cdat)
904 {
905     return (cdat->aead == EVP_CIPH_CCM_MODE
906             || cdat->aead == EVP_CIPH_CBC_MODE
907             || (cdat->aead == -1
908                 && EVP_CIPHER_get_mode(cdat->cipher) == EVP_CIPH_STREAM_CIPHER)
909             || ((EVP_CIPHER_get_flags(cdat->cipher) & EVP_CIPH_FLAG_CTS) != 0)
910             || EVP_CIPHER_get_mode(cdat->cipher) == EVP_CIPH_SIV_MODE
911             || EVP_CIPHER_get_mode(cdat->cipher) == EVP_CIPH_GCM_SIV_MODE
912             || EVP_CIPHER_get_mode(cdat->cipher) == EVP_CIPH_XTS_MODE
913             || EVP_CIPHER_get_mode(cdat->cipher) == EVP_CIPH_WRAP_MODE) ? 0 : 1;
914 }
915 
cipher_test_init(EVP_TEST * t,const char * alg)916 static int cipher_test_init(EVP_TEST *t, const char *alg)
917 {
918     const EVP_CIPHER *cipher;
919     EVP_CIPHER *fetched_cipher;
920     CIPHER_DATA *cdat;
921     int m;
922 
923     if (is_cipher_disabled(alg)) {
924         t->skip = 1;
925         TEST_info("skipping, '%s' is disabled", alg);
926         return 1;
927     }
928 
929     ERR_set_mark();
930     if ((cipher = fetched_cipher = EVP_CIPHER_fetch(libctx, alg, propquery)) == NULL
931         && (cipher = EVP_get_cipherbyname(alg)) == NULL) {
932         /* a stitched cipher might not be available */
933         if (strstr(alg, "HMAC") != NULL) {
934             ERR_pop_to_mark();
935             t->skip = 1;
936             TEST_info("skipping, '%s' is not available", alg);
937             return 1;
938         }
939         ERR_clear_last_mark();
940         return 0;
941     }
942     ERR_clear_last_mark();
943 
944     if (!TEST_ptr(cdat = OPENSSL_zalloc(sizeof(*cdat))))
945         return 0;
946 
947     cdat->init_controls = sk_OPENSSL_STRING_new_null();
948     cdat->cipher = cipher;
949     cdat->fetched_cipher = fetched_cipher;
950     cdat->enc = -1;
951     m = EVP_CIPHER_get_mode(cipher);
952     if (EVP_CIPHER_get_flags(cipher) & EVP_CIPH_FLAG_AEAD_CIPHER)
953         cdat->aead = m != 0 ? m : -1;
954     else
955         cdat->aead = 0;
956 
957     if (data_chunk_size != 0 && !cipher_test_valid_fragmentation(cdat)) {
958         ERR_pop_to_mark();
959         EVP_CIPHER_free(fetched_cipher);
960         OPENSSL_free(cdat);
961         t->skip = 1;
962         TEST_info("skipping, '%s' does not support fragmentation", alg);
963         return 1;
964     }
965 
966     t->data = cdat;
967     if (fetched_cipher != NULL)
968         TEST_info("%s is fetched", alg);
969     return 1;
970 }
971 
cipher_test_cleanup(EVP_TEST * t)972 static void cipher_test_cleanup(EVP_TEST *t)
973 {
974     int i;
975     CIPHER_DATA *cdat = t->data;
976 
977     OPENSSL_free(cdat->key);
978     OPENSSL_free(cdat->iv);
979     OPENSSL_free(cdat->next_iv);
980     OPENSSL_free(cdat->ciphertext);
981     OPENSSL_free(cdat->plaintext);
982     for (i = 0; i < AAD_NUM; i++)
983         OPENSSL_free(cdat->aad[i]);
984     OPENSSL_free(cdat->tag);
985     OPENSSL_free(cdat->mac_key);
986     EVP_CIPHER_free(cdat->fetched_cipher);
987     ctrlfree(cdat->init_controls);
988 }
989 
cipher_test_parse(EVP_TEST * t,const char * keyword,const char * value)990 static int cipher_test_parse(EVP_TEST *t, const char *keyword,
991                              const char *value)
992 {
993     CIPHER_DATA *cdat = t->data;
994     int i;
995 
996     if (strcmp(keyword, "Key") == 0)
997         return parse_bin(value, &cdat->key, &cdat->key_len);
998     if (strcmp(keyword, "Rounds") == 0) {
999         i = atoi(value);
1000         if (i < 0)
1001             return -1;
1002         cdat->rounds = (unsigned int)i;
1003         return 1;
1004     }
1005     if (strcmp(keyword, "IV") == 0)
1006         return parse_bin(value, &cdat->iv, &cdat->iv_len);
1007     if (strcmp(keyword, "NextIV") == 0)
1008         return parse_bin(value, &cdat->next_iv, &cdat->iv_len);
1009     if (strcmp(keyword, "Plaintext") == 0)
1010         return parse_bin(value, &cdat->plaintext, &cdat->plaintext_len);
1011     if (strcmp(keyword, "Ciphertext") == 0)
1012         return parse_bin(value, &cdat->ciphertext, &cdat->ciphertext_len);
1013     if (strcmp(keyword, "KeyBits") == 0) {
1014         i = atoi(value);
1015         if (i < 0)
1016             return -1;
1017         cdat->key_bits = (size_t)i;
1018         return 1;
1019     }
1020     if (cdat->aead) {
1021         int tls_aad = 0;
1022 
1023         if (strcmp(keyword, "TLSAAD") == 0)
1024             cdat->tls_aad = tls_aad = 1;
1025         if (strcmp(keyword, "AAD") == 0 || tls_aad) {
1026             for (i = 0; i < AAD_NUM; i++) {
1027                 if (cdat->aad[i] == NULL)
1028                     return parse_bin(value, &cdat->aad[i], &cdat->aad_len[i]);
1029             }
1030             return -1;
1031         }
1032         if (strcmp(keyword, "Tag") == 0)
1033             return parse_bin(value, &cdat->tag, &cdat->tag_len);
1034         if (strcmp(keyword, "SetTagLate") == 0) {
1035             if (strcmp(value, "TRUE") == 0)
1036                 cdat->tag_late = 1;
1037             else if (strcmp(value, "FALSE") == 0)
1038                 cdat->tag_late = 0;
1039             else
1040                 return -1;
1041             return 1;
1042         }
1043         if (strcmp(keyword, "MACKey") == 0)
1044             return parse_bin(value, &cdat->mac_key, &cdat->mac_key_len);
1045         if (strcmp(keyword, "TLSVersion") == 0) {
1046             char *endptr;
1047 
1048             cdat->tls_version = (int)strtol(value, &endptr, 0);
1049             return value[0] != '\0' && endptr[0] == '\0';
1050         }
1051     }
1052 
1053     if (strcmp(keyword, "Operation") == 0) {
1054         if (strcmp(value, "ENCRYPT") == 0)
1055             cdat->enc = 1;
1056         else if (strcmp(value, "DECRYPT") == 0)
1057             cdat->enc = 0;
1058         else
1059             return -1;
1060         return 1;
1061     }
1062     if (strcmp(keyword, "CTSMode") == 0) {
1063         cdat->cts_mode = value;
1064         return 1;
1065     }
1066     if (strcmp(keyword, "XTSStandard") == 0) {
1067         cdat->xts_standard = value;
1068         return 1;
1069     }
1070     if (strcmp(keyword, "CtrlInit") == 0)
1071         return ctrladd(cdat->init_controls, value);
1072     return 0;
1073 }
1074 
cipher_test_enc(EVP_TEST * t,int enc,size_t out_misalign,size_t inp_misalign,int frag,int in_place,const OSSL_PARAM initparams[])1075 static int cipher_test_enc(EVP_TEST *t, int enc, size_t out_misalign,
1076                            size_t inp_misalign, int frag, int in_place,
1077                            const OSSL_PARAM initparams[])
1078 {
1079     CIPHER_DATA *expected = t->data;
1080     unsigned char *in, *expected_out, *tmp = NULL;
1081     size_t in_len, out_len, donelen = 0;
1082     int ok = 0, tmplen, chunklen, tmpflen, i;
1083     EVP_CIPHER_CTX *ctx_base = NULL;
1084     EVP_CIPHER_CTX *ctx = NULL, *duped;
1085     int fips_dupctx_supported = fips_provider_version_ge(libctx, 3, 2, 0);
1086 
1087     t->err = "TEST_FAILURE";
1088     if (!TEST_ptr(ctx_base = EVP_CIPHER_CTX_new()))
1089         goto err;
1090     if (!TEST_ptr(ctx = EVP_CIPHER_CTX_new()))
1091         goto err;
1092     EVP_CIPHER_CTX_set_flags(ctx_base, EVP_CIPHER_CTX_FLAG_WRAP_ALLOW);
1093     if (enc) {
1094         in = expected->plaintext;
1095         in_len = expected->plaintext_len;
1096         expected_out = expected->ciphertext;
1097         out_len = expected->ciphertext_len;
1098     } else {
1099         in = expected->ciphertext;
1100         in_len = expected->ciphertext_len;
1101         expected_out = expected->plaintext;
1102         out_len = expected->plaintext_len;
1103     }
1104     if (in_place == 1) {
1105         /* Exercise in-place encryption */
1106         tmp = OPENSSL_malloc(out_misalign + in_len + 2 * EVP_MAX_BLOCK_LENGTH);
1107         if (!tmp)
1108             goto err;
1109         in = memcpy(tmp + out_misalign, in, in_len);
1110     } else {
1111         inp_misalign += 16 - ((out_misalign + in_len) & 15);
1112         /*
1113          * 'tmp' will store both output and copy of input. We make the copy
1114          * of input to specifically aligned part of 'tmp'. So we just
1115          * figured out how much padding would ensure the required alignment,
1116          * now we allocate extended buffer and finally copy the input just
1117          * past inp_misalign in expression below. Output will be written
1118          * past out_misalign...
1119          */
1120         tmp = OPENSSL_malloc(out_misalign + in_len + 2 * EVP_MAX_BLOCK_LENGTH +
1121                              inp_misalign + in_len);
1122         if (!tmp)
1123             goto err;
1124         in = memcpy(tmp + out_misalign + in_len + 2 * EVP_MAX_BLOCK_LENGTH +
1125                     inp_misalign, in, in_len);
1126     }
1127     if (!EVP_CipherInit_ex2(ctx_base, expected->cipher, NULL, NULL, enc,
1128                             initparams)) {
1129         t->err = "CIPHERINIT_ERROR";
1130         goto err;
1131     }
1132     if (expected->cts_mode != NULL) {
1133         OSSL_PARAM params[2];
1134 
1135         params[0] = OSSL_PARAM_construct_utf8_string(OSSL_CIPHER_PARAM_CTS_MODE,
1136                                                      (char *)expected->cts_mode,
1137                                                      0);
1138         params[1] = OSSL_PARAM_construct_end();
1139         if (!EVP_CIPHER_CTX_set_params(ctx_base, params)) {
1140             t->err = "INVALID_CTS_MODE";
1141             goto err;
1142         }
1143     }
1144     if (expected->iv) {
1145         if (expected->aead) {
1146             if (EVP_CIPHER_CTX_ctrl(ctx_base, EVP_CTRL_AEAD_SET_IVLEN,
1147                                      expected->iv_len, 0) <= 0) {
1148                 t->err = "INVALID_IV_LENGTH";
1149                 goto err;
1150             }
1151         } else if (expected->iv_len != (size_t)EVP_CIPHER_CTX_get_iv_length(ctx_base)) {
1152             t->err = "INVALID_IV_LENGTH";
1153             goto err;
1154         }
1155     }
1156     if (expected->aead && !expected->tls_aad) {
1157         unsigned char *tag;
1158         /*
1159          * If encrypting or OCB just set tag length initially, otherwise
1160          * set tag length and value.
1161          */
1162         if (enc || expected->aead == EVP_CIPH_OCB_MODE || expected->tag_late) {
1163             t->err = "TAG_LENGTH_SET_ERROR";
1164             tag = NULL;
1165         } else {
1166             t->err = "TAG_SET_ERROR";
1167             tag = expected->tag;
1168         }
1169         if (tag || expected->aead != EVP_CIPH_GCM_MODE) {
1170             if (EVP_CIPHER_CTX_ctrl(ctx_base, EVP_CTRL_AEAD_SET_TAG,
1171                                      expected->tag_len, tag) <= 0)
1172                 goto err;
1173         }
1174     }
1175 
1176     if (expected->rounds > 0) {
1177         int  rounds = (int)expected->rounds;
1178 
1179         if (EVP_CIPHER_CTX_ctrl(ctx_base, EVP_CTRL_SET_RC5_ROUNDS, rounds, NULL) <= 0) {
1180             t->err = "INVALID_ROUNDS";
1181             goto err;
1182         }
1183     }
1184 
1185     if (!EVP_CIPHER_CTX_set_key_length(ctx_base, expected->key_len)) {
1186         t->err = "INVALID_KEY_LENGTH";
1187         goto err;
1188     }
1189     if (expected->key_bits > 0) {
1190         int bits = (int)expected->key_bits;
1191 
1192         if (EVP_CIPHER_CTX_ctrl(ctx_base, EVP_CTRL_SET_RC2_KEY_BITS, bits, NULL) <= 0) {
1193             t->err = "INVALID KEY BITS";
1194             goto err;
1195         }
1196     }
1197     if (!EVP_CipherInit_ex(ctx_base, NULL, NULL, expected->key, expected->iv, -1)) {
1198         t->err = "KEY_SET_ERROR";
1199         goto err;
1200     }
1201 
1202     /* Check that we get the same IV back */
1203     if (expected->iv != NULL) {
1204         /* Some (e.g., GCM) tests use IVs longer than EVP_MAX_IV_LENGTH. */
1205         unsigned char iv[128];
1206         if (!TEST_true(EVP_CIPHER_CTX_get_updated_iv(ctx_base, iv, sizeof(iv)))
1207             || ((EVP_CIPHER_get_flags(expected->cipher) & EVP_CIPH_CUSTOM_IV) == 0
1208                 && !TEST_mem_eq(expected->iv, expected->iv_len, iv,
1209                                 expected->iv_len))) {
1210             t->err = "INVALID_IV";
1211             goto err;
1212         }
1213     }
1214 
1215     /* Test that the cipher dup functions correctly if it is supported */
1216     ERR_set_mark();
1217     if (!EVP_CIPHER_CTX_copy(ctx, ctx_base)) {
1218         if (fips_dupctx_supported) {
1219             TEST_info("Doing a copy of Cipher %s Fails!\n",
1220                       EVP_CIPHER_get0_name(expected->cipher));
1221             ERR_print_errors_fp(stderr);
1222             goto err;
1223         } else {
1224             TEST_info("Allowing copy fail as an old fips provider is in use.");
1225         }
1226         EVP_CIPHER_CTX_free(ctx);
1227         ctx = ctx_base;
1228     } else {
1229         EVP_CIPHER_CTX_free(ctx_base);
1230         ctx_base = NULL;
1231     }
1232     /* Likewise for dup */
1233     duped = EVP_CIPHER_CTX_dup(ctx);
1234     if (duped != NULL) {
1235         EVP_CIPHER_CTX_free(ctx);
1236         ctx = duped;
1237     } else {
1238         if (fips_dupctx_supported) {
1239             TEST_info("Doing a dup of Cipher %s Fails!\n",
1240                       EVP_CIPHER_get0_name(expected->cipher));
1241             ERR_print_errors_fp(stderr);
1242             goto err;
1243         } else {
1244             TEST_info("Allowing dup fail as an old fips provider is in use.");
1245         }
1246     }
1247     ERR_pop_to_mark();
1248 
1249     if (expected->mac_key != NULL
1250         && EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_MAC_KEY,
1251                                 (int)expected->mac_key_len,
1252                                 (void *)expected->mac_key) <= 0) {
1253         t->err = "SET_MAC_KEY_ERROR";
1254         goto err;
1255     }
1256 
1257     if (expected->tls_version) {
1258         OSSL_PARAM params[2];
1259 
1260         params[0] = OSSL_PARAM_construct_int(OSSL_CIPHER_PARAM_TLS_VERSION,
1261                                              &expected->tls_version);
1262         params[1] = OSSL_PARAM_construct_end();
1263         if (!EVP_CIPHER_CTX_set_params(ctx, params)) {
1264             t->err = "SET_TLS_VERSION_ERROR";
1265             goto err;
1266         }
1267     }
1268 
1269     if (expected->aead == EVP_CIPH_CCM_MODE) {
1270         if (!EVP_CipherUpdate(ctx, NULL, &tmplen, NULL, out_len)) {
1271             t->err = "CCM_PLAINTEXT_LENGTH_SET_ERROR";
1272             goto err;
1273         }
1274     }
1275     if (expected->aad[0] != NULL && !expected->tls_aad) {
1276         t->err = "AAD_SET_ERROR";
1277         if (!frag) {
1278             /* Supply the data all in one go or according to data_chunk_size */
1279             for (i = 0; expected->aad[i] != NULL; i++) {
1280                 size_t aad_len = expected->aad_len[i];
1281                 donelen = 0;
1282 
1283                 do {
1284                     size_t current_aad_len = (size_t) data_chunk_size;
1285 
1286                     if (data_chunk_size == 0 || (size_t) data_chunk_size > aad_len)
1287                         current_aad_len = aad_len;
1288                     if (!EVP_CipherUpdate(ctx, NULL, &chunklen,
1289                                           expected->aad[i] + donelen,
1290                                           current_aad_len))
1291                         goto err;
1292                     donelen += current_aad_len;
1293                     aad_len -= current_aad_len;
1294                 } while (aad_len > 0);
1295             }
1296         } else {
1297             /* Supply the AAD in chunks less than the block size where possible */
1298             for (i = 0; expected->aad[i] != NULL; i++) {
1299                 if (expected->aad_len[i] > 0) {
1300                     if (!EVP_CipherUpdate(ctx, NULL, &chunklen, expected->aad[i], 1))
1301                         goto err;
1302                     donelen++;
1303                 }
1304                 if (expected->aad_len[i] > 2) {
1305                     if (!EVP_CipherUpdate(ctx, NULL, &chunklen,
1306                                           expected->aad[i] + donelen,
1307                                           expected->aad_len[i] - 2))
1308                         goto err;
1309                     donelen += expected->aad_len[i] - 2;
1310                 }
1311                 if (expected->aad_len[i] > 1
1312                     && !EVP_CipherUpdate(ctx, NULL, &chunklen,
1313                                          expected->aad[i] + donelen, 1))
1314                     goto err;
1315             }
1316         }
1317     }
1318 
1319     if (expected->tls_aad) {
1320         OSSL_PARAM params[2];
1321         char *tls_aad;
1322 
1323         /* duplicate the aad as the implementation might modify it */
1324         if ((tls_aad = OPENSSL_memdup(expected->aad[0],
1325                                       expected->aad_len[0])) == NULL)
1326             goto err;
1327         params[0] = OSSL_PARAM_construct_octet_string(OSSL_CIPHER_PARAM_AEAD_TLS1_AAD,
1328                                                       tls_aad,
1329                                                       expected->aad_len[0]);
1330         params[1] = OSSL_PARAM_construct_end();
1331         if (!EVP_CIPHER_CTX_set_params(ctx, params)) {
1332             OPENSSL_free(tls_aad);
1333             t->err = "TLS1_AAD_ERROR";
1334             goto err;
1335         }
1336         OPENSSL_free(tls_aad);
1337     } else if (!enc && (expected->aead == EVP_CIPH_OCB_MODE
1338                         || expected->tag_late)) {
1339         if (EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_TAG,
1340                                  expected->tag_len, expected->tag) <= 0) {
1341             t->err = "TAG_SET_ERROR";
1342             goto err;
1343         }
1344     }
1345     if (expected->xts_standard != NULL) {
1346         OSSL_PARAM params[2];
1347 
1348         params[0] =
1349             OSSL_PARAM_construct_utf8_string(OSSL_CIPHER_PARAM_XTS_STANDARD,
1350                                              (char *)expected->xts_standard, 0);
1351         params[1] = OSSL_PARAM_construct_end();
1352         if (!EVP_CIPHER_CTX_set_params(ctx, params)) {
1353             t->err = "SET_XTS_STANDARD_ERROR";
1354             goto err;
1355         }
1356     }
1357     EVP_CIPHER_CTX_set_padding(ctx, 0);
1358     t->err = "CIPHERUPDATE_ERROR";
1359     tmplen = 0;
1360     if (!frag) {
1361         do {
1362             /* Supply the data all in one go or according to data_chunk_size */
1363             size_t current_in_len = (size_t) data_chunk_size;
1364 
1365             if (data_chunk_size == 0 || (size_t) data_chunk_size > in_len)
1366                 current_in_len = in_len;
1367             if (!EVP_CipherUpdate(ctx, tmp + out_misalign + tmplen, &chunklen,
1368                                   in, current_in_len))
1369                 goto err;
1370             tmplen += chunklen;
1371             in += current_in_len;
1372             in_len -= current_in_len;
1373         } while (in_len > 0);
1374     } else {
1375         /* Supply the data in chunks less than the block size where possible */
1376         if (in_len > 0) {
1377             if (!EVP_CipherUpdate(ctx, tmp + out_misalign, &chunklen, in, 1))
1378                 goto err;
1379             tmplen += chunklen;
1380             in++;
1381             in_len--;
1382         }
1383         if (in_len > 1) {
1384             if (!EVP_CipherUpdate(ctx, tmp + out_misalign + tmplen, &chunklen,
1385                                   in, in_len - 1))
1386                 goto err;
1387             tmplen += chunklen;
1388             in += in_len - 1;
1389             in_len = 1;
1390         }
1391         if (in_len > 0) {
1392             if (!EVP_CipherUpdate(ctx, tmp + out_misalign + tmplen, &chunklen,
1393                                   in, 1))
1394                 goto err;
1395             tmplen += chunklen;
1396         }
1397     }
1398     if (!EVP_CipherFinal_ex(ctx, tmp + out_misalign + tmplen, &tmpflen)) {
1399         t->err = "CIPHERFINAL_ERROR";
1400         goto err;
1401     }
1402     if (!cipher_check_fips_approved(ctx, t)) {
1403         t->err = "FIPSAPPROVED_ERROR";
1404         goto err;
1405     }
1406 
1407     if (!enc && expected->tls_aad) {
1408         if (expected->tls_version >= TLS1_1_VERSION
1409             && (EVP_CIPHER_is_a(expected->cipher, "AES-128-CBC-HMAC-SHA1")
1410                 || EVP_CIPHER_is_a(expected->cipher, "AES-256-CBC-HMAC-SHA1"))) {
1411             tmplen -= expected->iv_len;
1412             expected_out += expected->iv_len;
1413             out_misalign += expected->iv_len;
1414         }
1415         if ((int)out_len > tmplen + tmpflen)
1416             out_len = tmplen + tmpflen;
1417     }
1418     if (!memory_err_compare(t, "VALUE_MISMATCH", expected_out, out_len,
1419                             tmp + out_misalign, tmplen + tmpflen))
1420         goto err;
1421     if (enc && expected->aead && !expected->tls_aad) {
1422         unsigned char rtag[48]; /* longest known for TLS_SHA384_SHA384 */
1423 
1424         if (!TEST_size_t_le(expected->tag_len, sizeof(rtag))) {
1425             t->err = "TAG_LENGTH_INTERNAL_ERROR";
1426             goto err;
1427         }
1428         if (EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_GET_TAG,
1429                                  expected->tag_len, rtag) <= 0) {
1430             t->err = "TAG_RETRIEVE_ERROR";
1431             goto err;
1432         }
1433         if (!memory_err_compare(t, "TAG_VALUE_MISMATCH",
1434                                 expected->tag, expected->tag_len,
1435                                 rtag, expected->tag_len))
1436             goto err;
1437     }
1438     /* Check the updated IV */
1439     if (expected->next_iv != NULL) {
1440         /* Some (e.g., GCM) tests use IVs longer than EVP_MAX_IV_LENGTH. */
1441         unsigned char iv[128];
1442         if (!TEST_true(EVP_CIPHER_CTX_get_updated_iv(ctx, iv, sizeof(iv)))
1443             || ((EVP_CIPHER_get_flags(expected->cipher) & EVP_CIPH_CUSTOM_IV) == 0
1444                 && !TEST_mem_eq(expected->next_iv, expected->iv_len, iv,
1445                                 expected->iv_len))) {
1446             t->err = "INVALID_NEXT_IV";
1447             goto err;
1448         }
1449     }
1450 
1451     t->err = NULL;
1452     ok = 1;
1453  err:
1454     OPENSSL_free(tmp);
1455     if (ctx != ctx_base)
1456         EVP_CIPHER_CTX_free(ctx_base);
1457     EVP_CIPHER_CTX_free(ctx);
1458     return ok;
1459 }
1460 
cipher_test_run(EVP_TEST * t)1461 static int cipher_test_run(EVP_TEST *t)
1462 {
1463     CIPHER_DATA *cdat = t->data;
1464     int rv, frag, fragmax, in_place;
1465     size_t out_misalign, inp_misalign;
1466     OSSL_PARAM initparams[2] = { OSSL_PARAM_END, OSSL_PARAM_END };
1467     size_t params_n = 0;
1468 
1469     TEST_info("RUNNING TEST FOR CIPHER %s\n", EVP_CIPHER_get0_name(cdat->cipher));
1470     if (!cdat->key) {
1471         t->err = "NO_KEY";
1472         return 0;
1473     }
1474     if (!cdat->iv && EVP_CIPHER_get_iv_length(cdat->cipher) > 0) {
1475         /* IV is optional and usually omitted in wrap mode */
1476         if (EVP_CIPHER_get_mode(cdat->cipher) != EVP_CIPH_WRAP_MODE) {
1477             t->err = "NO_IV";
1478             return 0;
1479         }
1480     }
1481     if (cdat->aead && cdat->tag == NULL && !cdat->tls_aad) {
1482         t->err = "NO_TAG";
1483         return 0;
1484     }
1485 
1486     if (sk_OPENSSL_STRING_num(cdat->init_controls) > 0) {
1487         if (!ctrl2params(t, cdat->init_controls, NULL,
1488                          initparams, OSSL_NELEM(initparams), &params_n))
1489             return 0;
1490     }
1491 
1492     fragmax = (cipher_test_valid_fragmentation(cdat) == 0) ? 0 : 1;
1493     for (in_place = 1; in_place >= 0; in_place--) {
1494         static char aux_err[64];
1495 
1496         t->aux_err = aux_err;
1497         /* Test only in-place data processing */
1498         if (process_mode_in_place == 1 && in_place == 0)
1499             break;
1500 
1501         for (frag = 0; frag <= fragmax; frag++) {
1502             if (frag == 1 && data_chunk_size != 0)
1503                 break;
1504             for (out_misalign = 0; out_misalign <= 1; out_misalign++) {
1505                 for (inp_misalign = 0; inp_misalign <= 1; inp_misalign++) {
1506                     /* Skip input misalign tests for in-place processing */
1507                     if (inp_misalign == 1 && in_place == 1)
1508                         break;
1509                     if (in_place == 1) {
1510                         BIO_snprintf(aux_err, sizeof(aux_err),
1511                                         "%s in-place, %sfragmented",
1512                                         out_misalign ? "misaligned" : "aligned",
1513                                         frag ? "" : "not ");
1514                     } else {
1515                         BIO_snprintf(aux_err, sizeof(aux_err),
1516                                         "%s output and %s input, %sfragmented",
1517                                         out_misalign ? "misaligned" : "aligned",
1518                                         inp_misalign ? "misaligned" : "aligned",
1519                                         frag ? "" : "not ");
1520                     }
1521                     if (cdat->enc) {
1522                         rv = cipher_test_enc(t, 1, out_misalign, inp_misalign,
1523                                              frag, in_place, initparams);
1524                         if (rv != 1)
1525                             goto end;
1526                     }
1527                     if (cdat->enc != 1) {
1528                         rv = cipher_test_enc(t, 0, out_misalign, inp_misalign,
1529                                              frag, in_place, initparams);
1530                         if (rv != 1)
1531                             goto end;
1532                     }
1533                 }
1534             }
1535         }
1536     }
1537     ctrl2params_free(initparams, params_n, 0);
1538     t->aux_err = NULL;
1539     return 1;
1540  end:
1541     ctrl2params_free(initparams, params_n, 0);
1542     return (rv < 0 ? 0 : 1);
1543 }
1544 
1545 static const EVP_TEST_METHOD cipher_test_method = {
1546     "Cipher",
1547     cipher_test_init,
1548     cipher_test_cleanup,
1549     cipher_test_parse,
1550     cipher_test_run
1551 };
1552 
1553 
1554 /**
1555  **  MAC TESTS
1556  **/
1557 
1558 typedef struct mac_data_st {
1559     /* MAC type in one form or another */
1560     char *mac_name;
1561     EVP_MAC *mac;                /* for mac_test_run_mac */
1562     int type;                    /* for mac_test_run_pkey */
1563     /* Algorithm string for this MAC */
1564     char *alg;
1565     /* MAC key */
1566     unsigned char *key;
1567     size_t key_len;
1568     /* MAC IV (GMAC) */
1569     unsigned char *iv;
1570     size_t iv_len;
1571     /* Input to MAC */
1572     unsigned char *input;
1573     size_t input_len;
1574     /* Expected output */
1575     unsigned char *output;
1576     size_t output_len;
1577     unsigned char *custom;
1578     size_t custom_len;
1579     /* MAC salt (blake2) */
1580     unsigned char *salt;
1581     size_t salt_len;
1582     /* XOF mode? */
1583     int xof;
1584     /* Reinitialization fails */
1585     int no_reinit;
1586     /* Collection of controls */
1587     STACK_OF(OPENSSL_STRING) *controls;
1588     /* Output size */
1589     int output_size;
1590     /* Block size */
1591     int block_size;
1592 } MAC_DATA;
1593 
mac_test_init(EVP_TEST * t,const char * alg)1594 static int mac_test_init(EVP_TEST *t, const char *alg)
1595 {
1596     EVP_MAC *mac = NULL;
1597     int type = NID_undef;
1598     MAC_DATA *mdat;
1599 
1600     if (is_mac_disabled(alg)) {
1601         TEST_info("skipping, '%s' is disabled", alg);
1602         t->skip = 1;
1603         return 1;
1604     }
1605     if ((mac = EVP_MAC_fetch(libctx, alg, propquery)) == NULL) {
1606         /*
1607          * Since we didn't find an EVP_MAC, we check for known EVP_PKEY methods
1608          * For debugging purposes, we allow 'NNNN by EVP_PKEY' to force running
1609          * the EVP_PKEY method.
1610          */
1611         size_t sz = strlen(alg);
1612         static const char epilogue[] = " by EVP_PKEY";
1613 
1614         if (sz >= sizeof(epilogue)
1615             && strcmp(alg + sz - (sizeof(epilogue) - 1), epilogue) == 0)
1616             sz -= sizeof(epilogue) - 1;
1617 
1618         if (strncmp(alg, "HMAC", sz) == 0)
1619             type = EVP_PKEY_HMAC;
1620         else if (strncmp(alg, "CMAC", sz) == 0)
1621             type = EVP_PKEY_CMAC;
1622         else if (strncmp(alg, "Poly1305", sz) == 0)
1623             type = EVP_PKEY_POLY1305;
1624         else if (strncmp(alg, "SipHash", sz) == 0)
1625             type = EVP_PKEY_SIPHASH;
1626         else
1627             return 0;
1628     }
1629 
1630     if (!TEST_ptr(mdat = OPENSSL_zalloc(sizeof(*mdat))))
1631         return 0;
1632 
1633     mdat->type = type;
1634     if (!TEST_ptr(mdat->mac_name = OPENSSL_strdup(alg))) {
1635         OPENSSL_free(mdat);
1636         return 0;
1637     }
1638 
1639     mdat->mac = mac;
1640     if (!TEST_ptr(mdat->controls = sk_OPENSSL_STRING_new_null())) {
1641         OPENSSL_free(mdat->mac_name);
1642         OPENSSL_free(mdat);
1643         return 0;
1644     }
1645 
1646     mdat->output_size = mdat->block_size = -1;
1647     t->data = mdat;
1648     return 1;
1649 }
1650 
mac_test_cleanup(EVP_TEST * t)1651 static void mac_test_cleanup(EVP_TEST *t)
1652 {
1653     MAC_DATA *mdat = t->data;
1654 
1655     EVP_MAC_free(mdat->mac);
1656     OPENSSL_free(mdat->mac_name);
1657     sk_OPENSSL_STRING_pop_free(mdat->controls, openssl_free);
1658     OPENSSL_free(mdat->alg);
1659     OPENSSL_free(mdat->key);
1660     OPENSSL_free(mdat->iv);
1661     OPENSSL_free(mdat->custom);
1662     OPENSSL_free(mdat->salt);
1663     OPENSSL_free(mdat->input);
1664     OPENSSL_free(mdat->output);
1665 }
1666 
mac_test_parse(EVP_TEST * t,const char * keyword,const char * value)1667 static int mac_test_parse(EVP_TEST *t,
1668                           const char *keyword, const char *value)
1669 {
1670     MAC_DATA *mdata = t->data;
1671 
1672     if (strcmp(keyword, "Key") == 0)
1673         return parse_bin(value, &mdata->key, &mdata->key_len);
1674     if (strcmp(keyword, "IV") == 0)
1675         return parse_bin(value, &mdata->iv, &mdata->iv_len);
1676     if (strcmp(keyword, "Custom") == 0)
1677         return parse_bin(value, &mdata->custom, &mdata->custom_len);
1678     if (strcmp(keyword, "Salt") == 0)
1679         return parse_bin(value, &mdata->salt, &mdata->salt_len);
1680     if (strcmp(keyword, "Algorithm") == 0) {
1681         mdata->alg = OPENSSL_strdup(value);
1682         if (mdata->alg == NULL)
1683             return -1;
1684         return 1;
1685     }
1686     if (strcmp(keyword, "Input") == 0)
1687         return parse_bin(value, &mdata->input, &mdata->input_len);
1688     if (strcmp(keyword, "Output") == 0)
1689         return parse_bin(value, &mdata->output, &mdata->output_len);
1690     if (strcmp(keyword, "XOF") == 0)
1691         return mdata->xof = 1;
1692     if (strcmp(keyword, "NoReinit") == 0)
1693         return mdata->no_reinit = 1;
1694     if (strcmp(keyword, "Ctrl") == 0)
1695         return ctrladd(mdata->controls, value);
1696     if (strcmp(keyword, "OutputSize") == 0) {
1697         mdata->output_size = atoi(value);
1698         if (mdata->output_size < 0)
1699             return -1;
1700         return 1;
1701     }
1702     if (strcmp(keyword, "BlockSize") == 0) {
1703         mdata->block_size = atoi(value);
1704         if (mdata->block_size < 0)
1705             return -1;
1706         return 1;
1707     }
1708     return 0;
1709 }
1710 
mac_test_ctrl_pkey(EVP_TEST * t,EVP_PKEY_CTX * pctx,const char * value)1711 static int mac_test_ctrl_pkey(EVP_TEST *t, EVP_PKEY_CTX *pctx,
1712                               const char *value)
1713 {
1714     int rv = 0;
1715     char *p, *tmpval;
1716 
1717     if (!TEST_ptr(tmpval = OPENSSL_strdup(value)))
1718         return 0;
1719     p = strchr(tmpval, ':');
1720     if (p != NULL) {
1721         *p++ = '\0';
1722         rv = EVP_PKEY_CTX_ctrl_str(pctx, tmpval, p);
1723     }
1724     if (rv == -2)
1725         t->err = "PKEY_CTRL_INVALID";
1726     else if (rv <= 0)
1727         t->err = "PKEY_CTRL_ERROR";
1728     else
1729         rv = 1;
1730     OPENSSL_free(tmpval);
1731     return rv > 0;
1732 }
1733 
mac_test_run_pkey(EVP_TEST * t)1734 static int mac_test_run_pkey(EVP_TEST *t)
1735 {
1736     MAC_DATA *expected = t->data;
1737     EVP_MD_CTX *mctx = NULL;
1738     EVP_PKEY_CTX *pctx = NULL, *genctx = NULL;
1739     EVP_PKEY *key = NULL;
1740     const char *mdname = NULL;
1741     EVP_CIPHER *cipher = NULL;
1742     unsigned char *got = NULL;
1743     size_t got_len;
1744     int i;
1745     size_t input_len, donelen;
1746 
1747     /* We don't do XOF mode via PKEY */
1748     if (expected->xof)
1749         return 1;
1750 
1751     if (expected->alg == NULL)
1752         TEST_info("Trying the EVP_PKEY %s test", OBJ_nid2sn(expected->type));
1753     else
1754         TEST_info("Trying the EVP_PKEY %s test with %s",
1755                   OBJ_nid2sn(expected->type), expected->alg);
1756 
1757     if (expected->type == EVP_PKEY_CMAC) {
1758 #ifdef OPENSSL_NO_DEPRECATED_3_0
1759         TEST_info("skipping, PKEY CMAC '%s' is disabled", expected->alg);
1760         t->skip = 1;
1761         t->err = NULL;
1762         goto err;
1763 #else
1764         OSSL_LIB_CTX *tmpctx;
1765 
1766         if (expected->alg != NULL && is_cipher_disabled(expected->alg)) {
1767             TEST_info("skipping, PKEY CMAC '%s' is disabled", expected->alg);
1768             t->skip = 1;
1769             t->err = NULL;
1770             goto err;
1771         }
1772         if (!TEST_ptr(cipher = EVP_CIPHER_fetch(libctx, expected->alg, propquery))) {
1773             t->err = "MAC_KEY_CREATE_ERROR";
1774             goto err;
1775         }
1776         tmpctx = OSSL_LIB_CTX_set0_default(libctx);
1777         key = EVP_PKEY_new_CMAC_key(NULL, expected->key, expected->key_len,
1778                                     cipher);
1779         OSSL_LIB_CTX_set0_default(tmpctx);
1780 #endif
1781     } else {
1782         key = EVP_PKEY_new_raw_private_key_ex(libctx,
1783                                               OBJ_nid2sn(expected->type), NULL,
1784                                               expected->key, expected->key_len);
1785     }
1786     if (key == NULL) {
1787         t->err = "MAC_KEY_CREATE_ERROR";
1788         goto err;
1789     }
1790 
1791     if (expected->type == EVP_PKEY_HMAC && expected->alg != NULL) {
1792         if (is_digest_disabled(expected->alg)) {
1793             TEST_info("skipping, HMAC '%s' is disabled", expected->alg);
1794             t->skip = 1;
1795             t->err = NULL;
1796             goto err;
1797         }
1798         mdname = expected->alg;
1799     }
1800     if (!TEST_ptr(mctx = EVP_MD_CTX_new())) {
1801         t->err = "INTERNAL_ERROR";
1802         goto err;
1803     }
1804     if (!EVP_DigestSignInit_ex(mctx, &pctx, mdname, libctx, NULL, key, NULL)) {
1805         t->err = "DIGESTSIGNINIT_ERROR";
1806         goto err;
1807     }
1808     for (i = 0; i < sk_OPENSSL_STRING_num(expected->controls); i++)
1809         if (!mac_test_ctrl_pkey(t, pctx,
1810                                 sk_OPENSSL_STRING_value(expected->controls,
1811                                                         i))) {
1812             t->err = "EVPPKEYCTXCTRL_ERROR";
1813             goto err;
1814         }
1815     input_len = expected->input_len;
1816     donelen = 0;
1817     do {
1818         size_t current_len = (size_t) data_chunk_size;
1819 
1820         if (data_chunk_size == 0 || (size_t) data_chunk_size > input_len)
1821             current_len = input_len;
1822         if (!EVP_DigestSignUpdate(mctx, expected->input + donelen, current_len)) {
1823             t->err = "DIGESTSIGNUPDATE_ERROR";
1824             goto err;
1825         }
1826         donelen += current_len;
1827         input_len -= current_len;
1828     } while (input_len > 0);
1829 
1830     if (!EVP_DigestSignFinal(mctx, NULL, &got_len)) {
1831         t->err = "DIGESTSIGNFINAL_LENGTH_ERROR";
1832         goto err;
1833     }
1834     if (!TEST_ptr(got = OPENSSL_malloc(got_len))) {
1835         t->err = "TEST_FAILURE";
1836         goto err;
1837     }
1838     if (!EVP_DigestSignFinal(mctx, got, &got_len)
1839             || !memory_err_compare(t, "TEST_MAC_ERR",
1840                                    expected->output, expected->output_len,
1841                                    got, got_len)) {
1842         t->err = "TEST_MAC_ERR";
1843         goto err;
1844     }
1845     t->err = NULL;
1846  err:
1847     EVP_CIPHER_free(cipher);
1848     EVP_MD_CTX_free(mctx);
1849     OPENSSL_free(got);
1850     EVP_PKEY_CTX_free(genctx);
1851     EVP_PKEY_free(key);
1852     return 1;
1853 }
1854 
mac_test_run_mac(EVP_TEST * t)1855 static int mac_test_run_mac(EVP_TEST *t)
1856 {
1857     MAC_DATA *expected = t->data;
1858     EVP_MAC_CTX *ctx = NULL;
1859     unsigned char *got = NULL;
1860     size_t got_len = 0, size = 0;
1861     size_t size_before_init = 0, size_after_init, size_val = 0;
1862     int block_size = -1, output_size = -1;
1863     OSSL_PARAM params[21], sizes[3], *psizes = sizes, *p;
1864     size_t params_n = 0;
1865     size_t params_n_allocstart = 0;
1866     const OSSL_PARAM *defined_params =
1867         EVP_MAC_settable_ctx_params(expected->mac);
1868     int xof;
1869     int reinit = 1;
1870     size_t input_len, donelen ;
1871 
1872     if (expected->alg == NULL)
1873         TEST_info("Trying the EVP_MAC %s test", expected->mac_name);
1874     else
1875         TEST_info("Trying the EVP_MAC %s test with %s",
1876                   expected->mac_name, expected->alg);
1877 
1878     if (expected->alg != NULL) {
1879         int skip = 0;
1880 
1881         /*
1882          * The underlying algorithm may be a cipher or a digest.
1883          * We don't know which it is, but we can ask the MAC what it
1884          * should be and bet on that.
1885          */
1886         if (OSSL_PARAM_locate_const(defined_params,
1887                                     OSSL_MAC_PARAM_CIPHER) != NULL) {
1888             if (is_cipher_disabled(expected->alg))
1889                 skip = 1;
1890             else
1891                 params[params_n++] =
1892                     OSSL_PARAM_construct_utf8_string(OSSL_MAC_PARAM_CIPHER,
1893                                                      expected->alg, 0);
1894         } else if (OSSL_PARAM_locate_const(defined_params,
1895                                            OSSL_MAC_PARAM_DIGEST) != NULL) {
1896             if (is_digest_disabled(expected->alg))
1897                 skip = 1;
1898             else
1899                 params[params_n++] =
1900                     OSSL_PARAM_construct_utf8_string(OSSL_MAC_PARAM_DIGEST,
1901                                                      expected->alg, 0);
1902         } else {
1903             t->err = "MAC_BAD_PARAMS";
1904             goto err;
1905         }
1906         if (skip) {
1907             TEST_info("skipping, algorithm '%s' is disabled", expected->alg);
1908             t->skip = 1;
1909             t->err = NULL;
1910             goto err;
1911         }
1912     }
1913     if (expected->custom != NULL)
1914         params[params_n++] =
1915             OSSL_PARAM_construct_octet_string(OSSL_MAC_PARAM_CUSTOM,
1916                                               expected->custom,
1917                                               expected->custom_len);
1918     if (expected->salt != NULL)
1919         params[params_n++] =
1920             OSSL_PARAM_construct_octet_string(OSSL_MAC_PARAM_SALT,
1921                                               expected->salt,
1922                                               expected->salt_len);
1923     if (expected->iv != NULL)
1924         params[params_n++] =
1925             OSSL_PARAM_construct_octet_string(OSSL_MAC_PARAM_IV,
1926                                               expected->iv,
1927                                               expected->iv_len);
1928 
1929     params_n_allocstart = params_n;
1930     if (!ctrl2params(t, expected->controls, defined_params,
1931                      params, OSSL_NELEM(params), &params_n))
1932         goto err;
1933 
1934     p = OSSL_PARAM_locate(params + params_n_allocstart, "size");
1935     if (p != NULL) {
1936         if (!OSSL_PARAM_get_size_t(p, &size_val))
1937             goto err;
1938     }
1939 
1940     if ((ctx = EVP_MAC_CTX_new(expected->mac)) == NULL) {
1941         t->err = "MAC_CREATE_ERROR";
1942         goto err;
1943     }
1944     if (fips_provider_version_gt(libctx, 3, 2, 0)) {
1945         /* HMAC will put an error on the stack here (digest is not set yet) */
1946         ERR_set_mark();
1947         size_before_init = EVP_MAC_CTX_get_mac_size(ctx);
1948         ERR_pop_to_mark();
1949     }
1950     if (!EVP_MAC_init(ctx, expected->key, expected->key_len, params)) {
1951         t->err = "MAC_INIT_ERROR";
1952         goto err;
1953     }
1954     size_after_init = EVP_MAC_CTX_get_mac_size(ctx);
1955     if (!TEST_false(size_before_init == 0 && size_after_init == 0)) {
1956         t->err = "MAC SIZE not set";
1957         goto err;
1958     }
1959     if (size_before_init != 0) {
1960         /* mac-size not modified by init params */
1961         if (size_val == 0 && !TEST_size_t_eq(size_before_init, size_after_init)) {
1962             t->err = "MAC SIZE check failed";
1963             goto err;
1964         }
1965         /* mac-size modified by init params */
1966         if (size_val != 0 && !TEST_size_t_eq(size_val, size_after_init)) {
1967             t->err = "MAC SIZE check failed";
1968             goto err;
1969         }
1970     }
1971     if (expected->output_size >= 0)
1972         *psizes++ = OSSL_PARAM_construct_int(OSSL_MAC_PARAM_SIZE,
1973                                              &output_size);
1974     if (expected->block_size >= 0)
1975         *psizes++ = OSSL_PARAM_construct_int(OSSL_MAC_PARAM_BLOCK_SIZE,
1976                                              &block_size);
1977     if (psizes != sizes) {
1978         *psizes = OSSL_PARAM_construct_end();
1979         if (!TEST_true(EVP_MAC_CTX_get_params(ctx, sizes))) {
1980             t->err = "INTERNAL_ERROR";
1981             goto err;
1982         }
1983         if (expected->output_size >= 0
1984                 && !TEST_int_eq(output_size, expected->output_size)) {
1985             t->err = "TEST_FAILURE";
1986             goto err;
1987         }
1988         if (expected->block_size >= 0
1989                 && !TEST_int_eq(block_size, expected->block_size)) {
1990             t->err = "TEST_FAILURE";
1991             goto err;
1992         }
1993     }
1994  retry:
1995     input_len = expected->input_len;
1996     donelen = 0;
1997     do {
1998         size_t current_len = (size_t) data_chunk_size;
1999 
2000         if (data_chunk_size == 0 || (size_t) data_chunk_size > input_len)
2001             current_len = input_len;
2002         if (!EVP_MAC_update(ctx, expected->input + donelen, current_len)) {
2003             t->err = "MAC_UPDATE_ERROR";
2004             goto err;
2005         }
2006         donelen += current_len;
2007         input_len -= current_len;
2008     } while (input_len > 0);
2009 
2010     xof = expected->xof;
2011     if (xof) {
2012         if (!TEST_ptr(got = OPENSSL_malloc(expected->output_len))) {
2013             t->err = "TEST_FAILURE";
2014             goto err;
2015         }
2016         if (!EVP_MAC_finalXOF(ctx, got, expected->output_len)
2017             || !memory_err_compare(t, "TEST_MAC_ERR",
2018                                    expected->output, expected->output_len,
2019                                    got, expected->output_len)) {
2020             t->err = "MAC_FINAL_ERROR";
2021             goto err;
2022         }
2023     } else {
2024         if (!EVP_MAC_final(ctx, NULL, &got_len, 0)) {
2025             t->err = "MAC_FINAL_LENGTH_ERROR";
2026             goto err;
2027         }
2028         if (!TEST_ptr(got = OPENSSL_malloc(got_len))) {
2029             t->err = "TEST_FAILURE";
2030             goto err;
2031         }
2032         if (!EVP_MAC_final(ctx, got, &got_len, got_len)
2033             || !memory_err_compare(t, "TEST_MAC_ERR",
2034                                    expected->output, expected->output_len,
2035                                    got, got_len)) {
2036             t->err = "TEST_MAC_ERR";
2037             goto err;
2038         }
2039         if (!mac_check_fips_approved(ctx, t))
2040             goto err;
2041     }
2042     /* FIPS(3.0.0): can't reinitialise MAC contexts #18100 */
2043     if (reinit-- && fips_provider_version_gt(libctx, 3, 0, 0)) {
2044         OSSL_PARAM ivparams[2] = { OSSL_PARAM_END, OSSL_PARAM_END };
2045         int ret;
2046 
2047         /* If the MAC uses IV, we have to set it again */
2048         if (expected->iv != NULL) {
2049             ivparams[0] =
2050                 OSSL_PARAM_construct_octet_string(OSSL_MAC_PARAM_IV,
2051                                                   expected->iv,
2052                                                   expected->iv_len);
2053             ivparams[1] = OSSL_PARAM_construct_end();
2054         }
2055         ERR_set_mark();
2056         ret = EVP_MAC_init(ctx, NULL, 0, ivparams);
2057         if (expected->no_reinit) {
2058             if (ret) {
2059                 ERR_clear_last_mark();
2060                 t->err = "MAC_REINIT_SHOULD_FAIL";
2061                 goto err;
2062             }
2063         } else if (ret) {
2064             ERR_clear_last_mark();
2065             OPENSSL_free(got);
2066             got = NULL;
2067             goto retry;
2068         } else {
2069             ERR_clear_last_mark();
2070             t->err = "MAC_REINIT_ERROR";
2071             goto err;
2072         }
2073         /* If reinitialization fails, it is unsupported by the algorithm */
2074         ERR_pop_to_mark();
2075     }
2076     t->err = NULL;
2077 
2078     /* Test the EVP_Q_mac interface as well */
2079     if (!xof) {
2080         OPENSSL_cleanse(got, got_len);
2081         if (!TEST_true(EVP_Q_mac(libctx, expected->mac_name, NULL,
2082                                  expected->alg, params,
2083                                  expected->key, expected->key_len,
2084                                  expected->input, expected->input_len,
2085                                  got, got_len, &size))
2086                 || !TEST_mem_eq(got, size,
2087                                 expected->output, expected->output_len)) {
2088             t->err = "EVP_Q_mac failed";
2089             goto err;
2090         }
2091     }
2092  err:
2093     ctrl2params_free(params, params_n, params_n_allocstart);
2094     EVP_MAC_CTX_free(ctx);
2095     OPENSSL_free(got);
2096     return 1;
2097 }
2098 
mac_test_run(EVP_TEST * t)2099 static int mac_test_run(EVP_TEST *t)
2100 {
2101     MAC_DATA *expected = t->data;
2102 
2103     if (expected->mac != NULL)
2104         return mac_test_run_mac(t);
2105     return mac_test_run_pkey(t);
2106 }
2107 
2108 static const EVP_TEST_METHOD mac_test_method = {
2109     "MAC",
2110     mac_test_init,
2111     mac_test_cleanup,
2112     mac_test_parse,
2113     mac_test_run
2114 };
2115 
2116 typedef struct kem_data_st {
2117     /* Context for this operation */
2118     EVP_PKEY_CTX *ctx;
2119     const char *op;
2120     /* Input to decapsulate */
2121     unsigned char *input;
2122     size_t inputlen;
2123     /* Expected secret */
2124     unsigned char *output;
2125     size_t outputlen;
2126     STACK_OF(OPENSSL_STRING) *init_ctrls;
2127 } KEM_DATA;
2128 
kem_test_init(EVP_TEST * t,const char * name)2129 static int kem_test_init(EVP_TEST *t, const char *name)
2130 {
2131     KEM_DATA *kdata = NULL;
2132     EVP_PKEY *pkey = NULL;
2133     int rv;
2134 
2135     rv = find_key(&pkey, name, private_keys);
2136     if (rv == 0 || pkey == NULL) {
2137         TEST_info("skipping, key '%s' is disabled", name);
2138         t->skip = 1;
2139         return 1;
2140     }
2141 
2142     if (!TEST_ptr(kdata = OPENSSL_zalloc(sizeof(*kdata))))
2143         goto err;
2144     if (!TEST_ptr(kdata->ctx = EVP_PKEY_CTX_new_from_pkey(libctx, pkey, propquery)))
2145         goto err;
2146 
2147     t->data = kdata;
2148     kdata->init_ctrls = sk_OPENSSL_STRING_new_null();
2149     return 1;
2150 err:
2151     EVP_PKEY_free(pkey);
2152     OPENSSL_free(kdata);
2153     return 0;
2154 }
2155 
kem_test_cleanup(EVP_TEST * t)2156 static void kem_test_cleanup(EVP_TEST *t)
2157 {
2158     KEM_DATA *kdata = t->data;
2159 
2160     ctrlfree(kdata->init_ctrls);
2161     OPENSSL_free(kdata->input);
2162     OPENSSL_free(kdata->output);
2163     EVP_PKEY_CTX_free(kdata->ctx);
2164 }
2165 
kem_test_parse(EVP_TEST * t,const char * keyword,const char * value)2166 static int kem_test_parse(EVP_TEST *t, const char *keyword, const char *value)
2167 {
2168     KEM_DATA *kdata = t->data;
2169 
2170     if (strcmp(keyword, "Op") == 0) {
2171         kdata->op = value;
2172         return 1;
2173     }
2174     if (strcmp(keyword, "CtrlInit") == 0)
2175         return ctrladd(kdata->init_ctrls, value);
2176     if (strcmp(keyword, "Input") == 0)
2177         return parse_bin(value, &kdata->input, &kdata->inputlen);
2178     if (strcmp(keyword, "Output") == 0)
2179         return parse_bin(value, &kdata->output, &kdata->outputlen);
2180     return 1;
2181 }
2182 
encapsulate(EVP_TEST * t,EVP_PKEY_CTX * ctx,const char * op,unsigned char ** outwrapped,size_t * outwrappedlen,unsigned char ** outsecret,size_t * outsecretlen)2183 static int encapsulate(EVP_TEST *t, EVP_PKEY_CTX *ctx, const char *op,
2184                        unsigned char **outwrapped, size_t *outwrappedlen,
2185                        unsigned char **outsecret, size_t *outsecretlen)
2186 {
2187     int ret = 1;
2188     KEM_DATA *kdata = t->data;
2189     unsigned char *wrapped = NULL, *secret = NULL;
2190     size_t wrappedlen = 0, secretlen = 0;
2191     OSSL_PARAM params[2] = { OSSL_PARAM_END, OSSL_PARAM_END };
2192     size_t params_n = 0, params_n_allocated = 0;
2193     OSSL_PARAM *p = NULL;
2194 
2195     if (sk_OPENSSL_STRING_num(kdata->init_ctrls) > 0) {
2196         if (ctrl2params(t, kdata->init_ctrls, NULL,
2197                         params, OSSL_NELEM(params), &params_n))
2198             goto err;
2199         p = params;
2200     }
2201     if (EVP_PKEY_encapsulate_init(ctx, p) <= 0) {
2202         t->err = "TEST_ENCAPSULATE_INIT_ERROR";
2203         goto err;
2204     }
2205 
2206     if (EVP_PKEY_CTX_set_kem_op(ctx, op) <= 0) {
2207         t->err = "TEST_SET_KEM_OP_ERROR";
2208         goto err;
2209     }
2210     if (EVP_PKEY_encapsulate(ctx, NULL, &wrappedlen, NULL, &secretlen) <= 0) {
2211         t->err = "TEST_ENCAPSULATE_LEN_ERROR";
2212         goto err;
2213     }
2214     wrapped = OPENSSL_malloc(wrappedlen);
2215     secret = OPENSSL_malloc(secretlen);
2216     if (!TEST_ptr(wrapped) || !TEST_ptr(secret)) {
2217         ret = 0;
2218         goto err;
2219     }
2220     if (EVP_PKEY_encapsulate(ctx, wrapped, &wrappedlen, secret, &secretlen) <= 0) {
2221         t->err = "TEST_ENCAPSULATE_ERROR";
2222         goto err;
2223     }
2224     ret = pkey_check_fips_approved(ctx, t);
2225     if (ret == 0)
2226         goto err;
2227 
2228     t->err = NULL;
2229     *outwrapped = wrapped;
2230     *outsecret = secret;
2231     *outwrappedlen = wrappedlen;
2232     *outsecretlen = secretlen;
2233     ret = 1;
2234     goto end;
2235 err:
2236     OPENSSL_free(wrapped);
2237     OPENSSL_free(secret);
2238 end:
2239     ctrl2params_free(params, params_n, params_n_allocated);
2240     return ret;
2241 }
2242 
decapsulate(EVP_TEST * t,EVP_PKEY_CTX * ctx,const char * op,const unsigned char * in,size_t inlen,const unsigned char * expected,size_t expectedlen)2243 static int decapsulate(EVP_TEST *t, EVP_PKEY_CTX *ctx, const char *op,
2244                        const unsigned char *in, size_t inlen,
2245                        const unsigned char *expected, size_t expectedlen)
2246 {
2247     int ret = 1;
2248     KEM_DATA *kdata = t->data;
2249     size_t outlen = 0;
2250     unsigned char *out = NULL;
2251     OSSL_PARAM params[2] = { OSSL_PARAM_END, OSSL_PARAM_END };
2252     OSSL_PARAM *p = NULL;
2253     size_t params_n = 0, params_n_allocated = 0;
2254 
2255     if (sk_OPENSSL_STRING_num(kdata->init_ctrls) > 0) {
2256         if (!ctrl2params(t, kdata->init_ctrls, NULL,
2257                         params, OSSL_NELEM(params), &params_n))
2258             goto err;
2259         p = params;
2260     }
2261     if (EVP_PKEY_decapsulate_init(ctx, p) <= 0) {
2262         t->err = "TEST_DECAPSULATE_INIT_ERROR";
2263         goto err;
2264     }
2265 
2266     if (EVP_PKEY_CTX_set_kem_op(ctx, op) <= 0) {
2267         t->err = "TEST_SET_KEM_OP_ERROR";
2268         goto err;
2269     }
2270     if (EVP_PKEY_decapsulate(ctx, NULL, &outlen, in, inlen) <= 0) {
2271         t->err = "TEST_DECAPSULATE_LEN_ERROR";
2272         goto err;
2273     }
2274     if (!TEST_ptr(out = OPENSSL_malloc(outlen))) {
2275         ret = 0;
2276         goto err;
2277     }
2278 
2279     if (EVP_PKEY_decapsulate(ctx, out, &outlen, in, inlen) <= 0) {
2280         t->err = "TEST_DECAPSULATE_ERROR";
2281         goto err;
2282     }
2283     if (!TEST_mem_eq(out, outlen, expected, expectedlen)) {
2284         t->err = "TEST_SECRET_MISMATCH";
2285         goto err;
2286     }
2287     t->err = NULL;
2288     ret = 1;
2289 err:
2290     OPENSSL_free(out);
2291     ctrl2params_free(params, params_n, params_n_allocated);
2292     return ret;
2293 }
2294 
kem_test_run(EVP_TEST * t)2295 static int kem_test_run(EVP_TEST *t)
2296 {
2297     int ret = 0;
2298     KEM_DATA *kdata = t->data;
2299     unsigned char *wrapped = NULL, *secret = NULL;
2300 
2301     if (kdata->input == NULL) {
2302         size_t wrappedlen = 0, secretlen = 0;
2303 
2304         ret = encapsulate(t, kdata->ctx, kdata->op, &wrapped, &wrappedlen,
2305                           &secret, &secretlen);
2306         if (ret == 0 || t->err != NULL)
2307             goto err;
2308         ret = decapsulate(t, kdata->ctx, kdata->op, wrapped, wrappedlen,
2309                           secret, secretlen);
2310     } else {
2311         ret = decapsulate(t, kdata->ctx, kdata->op, kdata->input, kdata->inputlen,
2312                           kdata->output, kdata->outputlen);
2313     }
2314 err:
2315     OPENSSL_free(wrapped);
2316     OPENSSL_free(secret);
2317     return ret;
2318 }
2319 
2320 static const EVP_TEST_METHOD pkey_kem_test_method = {
2321     "Kem",
2322     kem_test_init,
2323     kem_test_cleanup,
2324     kem_test_parse,
2325     kem_test_run
2326 };
2327 
2328 /**
2329  **  PUBLIC KEY TESTS
2330  **  These are all very similar and share much common code.
2331  **/
2332 
2333 typedef struct pkey_data_st {
2334     /* Context for this operation */
2335     EVP_PKEY_CTX *ctx;
2336     /* Signature algo for such operations */
2337     EVP_SIGNATURE *sigalgo;
2338     /* Key operation to perform */
2339     int (*keyopinit) (EVP_PKEY_CTX *ctx, const OSSL_PARAM params[]);
2340     int (*keyopinit_ex2) (EVP_PKEY_CTX *ctx, EVP_SIGNATURE *algo,
2341                           const OSSL_PARAM params[]);
2342     int (*keyop) (EVP_PKEY_CTX *ctx,
2343                   unsigned char *sig, size_t *siglen,
2344                   const unsigned char *tbs, size_t tbslen);
2345     /* Input to MAC */
2346     unsigned char *input;
2347     size_t input_len;
2348     /* Expected output */
2349     unsigned char *output;
2350     size_t output_len;
2351     STACK_OF(OPENSSL_STRING) *init_controls; /* collection of controls */
2352     STACK_OF(OPENSSL_STRING) *controls;      /* collection of controls */
2353     EVP_PKEY *peer;
2354     int validate;
2355 } PKEY_DATA;
2356 
2357 /*
2358  * Perform public key operation setup: lookup key, allocated ctx and call
2359  * the appropriate initialisation function
2360  */
pkey_test_init_keyctx(EVP_TEST * t,const char * keyname,int use_public)2361 static int pkey_test_init_keyctx(EVP_TEST *t, const char *keyname,
2362                                  int use_public)
2363 {
2364     PKEY_DATA *kdata;
2365     EVP_PKEY *pkey = NULL;
2366     int rv = 0;
2367 
2368     if (use_public)
2369         rv = find_key(&pkey, keyname, public_keys);
2370     if (rv == 0)
2371         rv = find_key(&pkey, keyname, private_keys);
2372     if (rv == 0 || pkey == NULL) {
2373         TEST_info("skipping, key '%s' is disabled", keyname);
2374         t->skip = 1;
2375         return 1;
2376     }
2377 
2378     if (!TEST_ptr(kdata = OPENSSL_zalloc(sizeof(*kdata)))) {
2379         EVP_PKEY_free(pkey);
2380         return 0;
2381     }
2382     if (!TEST_ptr(kdata->ctx = EVP_PKEY_CTX_new_from_pkey(libctx, pkey, propquery))) {
2383         EVP_PKEY_free(pkey);
2384         OPENSSL_free(kdata);
2385         return 0;
2386     }
2387     t->data = kdata;
2388     return 1;
2389 }
2390 
pkey_test_init(EVP_TEST * t,const char * name,int use_public,int (* keyopinit)(EVP_PKEY_CTX * ctx,const OSSL_PARAM params[]),int (* keyop)(EVP_PKEY_CTX * ctx,unsigned char * sig,size_t * siglen,const unsigned char * tbs,size_t tbslen))2391 static int pkey_test_init(EVP_TEST *t, const char *name,
2392                           int use_public,
2393                           int (*keyopinit) (EVP_PKEY_CTX *ctx,
2394                                             const OSSL_PARAM params[]),
2395                           int (*keyop)(EVP_PKEY_CTX *ctx,
2396                                        unsigned char *sig, size_t *siglen,
2397                                        const unsigned char *tbs,
2398                                        size_t tbslen))
2399 {
2400     PKEY_DATA *kdata = NULL;
2401     int rv = 0;
2402 
2403     rv = pkey_test_init_keyctx(t, name, use_public);
2404     if (t->skip || !rv)
2405         return rv;
2406     kdata = t->data;
2407     kdata->keyopinit = keyopinit;
2408     kdata->keyop = keyop;
2409     kdata->init_controls = sk_OPENSSL_STRING_new_null();
2410     kdata->controls = sk_OPENSSL_STRING_new_null();
2411     return 1;
2412 }
2413 
pkey_test_init_ex2(EVP_TEST * t,const char * name,int use_public,int (* keyopinit)(EVP_PKEY_CTX * ctx,EVP_SIGNATURE * algo,const OSSL_PARAM param[]),int (* keyop)(EVP_PKEY_CTX * ctx,unsigned char * sig,size_t * siglen,const unsigned char * tbs,size_t tbslen))2414 static int pkey_test_init_ex2(EVP_TEST *t, const char *name,
2415                               int use_public,
2416                               int (*keyopinit)(EVP_PKEY_CTX *ctx,
2417                                                EVP_SIGNATURE *algo,
2418                                                const OSSL_PARAM param[]),
2419                               int (*keyop)(EVP_PKEY_CTX *ctx,
2420                                            unsigned char *sig, size_t *siglen,
2421                                            const unsigned char *tbs,
2422                                            size_t tbslen))
2423 {
2424     PKEY_DATA *kdata = NULL;
2425     int rv = 0;
2426     char algoname[OSSL_MAX_NAME_SIZE + 1];
2427     const char *p;
2428 
2429     if ((p = strchr(name, ':')) == NULL
2430         || p == name || p[1] == '\0' || p - name > OSSL_MAX_NAME_SIZE) {
2431         TEST_info("Can't extract algorithm or key name from '%s'", name);
2432         return 0;
2433     }
2434     memcpy(algoname, name, p - name);
2435     algoname[p - name] = '\0';
2436 
2437     if (is_pkey_disabled(algoname)) {
2438         t->skip = 1;
2439         return 1;
2440     }
2441 
2442     rv = pkey_test_init_keyctx(t, /* keyname */ p + 1, use_public);
2443     if (t->skip || !rv)
2444         return rv;
2445     kdata = t->data;
2446     kdata->keyopinit_ex2 = keyopinit;
2447     kdata->keyop = keyop;
2448     if (!TEST_ptr(kdata->sigalgo
2449                   = EVP_SIGNATURE_fetch(libctx, algoname, propquery))) {
2450         TEST_info("algoname = '%s'", algoname);
2451         return 0;
2452     }
2453     kdata->init_controls = sk_OPENSSL_STRING_new_null();
2454     kdata->controls = sk_OPENSSL_STRING_new_null();
2455     return 1;
2456 }
2457 
pkey_test_cleanup(EVP_TEST * t)2458 static void pkey_test_cleanup(EVP_TEST *t)
2459 {
2460     PKEY_DATA *kdata = t->data;
2461 
2462     ctrlfree(kdata->init_controls);
2463     ctrlfree(kdata->controls);
2464     OPENSSL_free(kdata->input);
2465     OPENSSL_free(kdata->output);
2466     EVP_PKEY_CTX_free(kdata->ctx);
2467     EVP_SIGNATURE_free(kdata->sigalgo);
2468 }
2469 
pkey_test_ctrl(EVP_TEST * t,EVP_PKEY_CTX * pctx,const char * value)2470 static int pkey_test_ctrl(EVP_TEST *t, EVP_PKEY_CTX *pctx,
2471                           const char *value)
2472 {
2473     int rv = 0;
2474     char *p, *tmpval;
2475 
2476     if (!TEST_ptr(tmpval = OPENSSL_strdup(value)))
2477         return 0;
2478     p = strchr(tmpval, ':');
2479     if (p != NULL) {
2480         *p++ = '\0';
2481         rv = EVP_PKEY_CTX_ctrl_str(pctx, tmpval, p);
2482     }
2483     if (rv == -2) {
2484         t->err = "PKEY_CTRL_INVALID";
2485         rv = 1;
2486     } else if (p != NULL && rv <= 0) {
2487         if (is_digest_disabled(p) || is_cipher_disabled(p)) {
2488             TEST_info("skipping, '%s' is disabled", p);
2489             t->skip = 1;
2490             rv = 1;
2491         } else {
2492             t->err = "PKEY_CTRL_ERROR";
2493             rv = 1;
2494         }
2495     }
2496     OPENSSL_free(tmpval);
2497     return rv > 0;
2498 }
2499 
pkey_add_control(EVP_TEST * t,STACK_OF (OPENSSL_STRING)* controls,const char * value)2500 static int pkey_add_control(EVP_TEST *t, STACK_OF(OPENSSL_STRING) *controls,
2501                             const char *value)
2502 {
2503     char *p;
2504 
2505     if (controls == NULL)
2506         return 0;
2507 
2508     p = strchr(value, ':');
2509     if (p == NULL)
2510         return 0;
2511     p++;
2512     if (is_digest_disabled(p) || is_cipher_disabled(p)) {
2513         TEST_info("skipping, '%s' is disabled", p);
2514         t->skip = 1;
2515         return 1;
2516     }
2517 
2518     return ctrladd(controls, value) > 0;
2519 }
2520 
pkey_test_parse(EVP_TEST * t,const char * keyword,const char * value)2521 static int pkey_test_parse(EVP_TEST *t,
2522                            const char *keyword, const char *value)
2523 {
2524     PKEY_DATA *kdata = t->data;
2525     if (strcmp(keyword, "Input") == 0)
2526         return parse_bin(value, &kdata->input, &kdata->input_len);
2527     if (strcmp(keyword, "Output") == 0)
2528         return parse_bin(value, &kdata->output, &kdata->output_len);
2529     if (strcmp(keyword, "CtrlInit") == 0)
2530         return ctrladd(kdata->init_controls, value);
2531     if (strcmp(keyword, "Ctrl") == 0)
2532         return pkey_add_control(t, kdata->controls, value);
2533     return 0;
2534 }
2535 
pkey_test_run_init(EVP_TEST * t)2536 static int pkey_test_run_init(EVP_TEST *t)
2537 {
2538     PKEY_DATA *data = t->data;
2539     int i, ret = 0;
2540     OSSL_PARAM params[3] = { OSSL_PARAM_END, OSSL_PARAM_END, OSSL_PARAM_END };
2541     OSSL_PARAM *p = NULL;
2542     size_t params_n = 0, params_n_allocstart = 0;
2543 
2544     if (sk_OPENSSL_STRING_num(data->init_controls) > 0) {
2545         if (!ctrl2params(t, data->init_controls,
2546                          NULL,
2547                          params, OSSL_NELEM(params), &params_n))
2548             goto err;
2549         p = params;
2550     }
2551     if (data->keyopinit != NULL) {
2552         if (data->keyopinit(data->ctx, p) <= 0) {
2553             t->err = "KEYOP_INIT_ERROR";
2554             goto err;
2555         }
2556     } else if (data->keyopinit_ex2 != NULL) {
2557         if (data->keyopinit_ex2(data->ctx, data->sigalgo, p) <= 0) {
2558             t->err = "KEYOP_INIT_ERROR";
2559             goto err;
2560         }
2561     } else {
2562         t->err = "KEYOP_INIT_ERROR";
2563         goto err;
2564     }
2565 
2566     for (i = 0; i < sk_OPENSSL_STRING_num(data->controls); i++) {
2567         char *value = sk_OPENSSL_STRING_value(data->controls, i);
2568 
2569         if (!pkey_test_ctrl(t, data->ctx, value) || t->err != NULL)
2570             goto err;
2571     }
2572     ret = 1;
2573 err:
2574     ctrl2params_free(params, params_n, params_n_allocstart);
2575     return ret;
2576 }
2577 
pkey_test_run(EVP_TEST * t)2578 static int pkey_test_run(EVP_TEST *t)
2579 {
2580     PKEY_DATA *expected = t->data;
2581     unsigned char *got = NULL;
2582     size_t got_len;
2583     EVP_PKEY_CTX *copy = NULL;
2584 
2585     if (!pkey_test_run_init(t))
2586         goto err;
2587 
2588     /* Make a copy of the EVP_PKEY context, for repeat use further down */
2589     if (!TEST_ptr(copy = EVP_PKEY_CTX_dup(expected->ctx))) {
2590         t->err = "INTERNAL_ERROR";
2591         goto err;
2592     }
2593 
2594     if (expected->keyop(expected->ctx, NULL, &got_len,
2595                         expected->input, expected->input_len) <= 0
2596             || !TEST_ptr(got = OPENSSL_malloc(got_len))) {
2597         t->err = "KEYOP_LENGTH_ERROR";
2598         goto err;
2599     }
2600     if (expected->keyop(expected->ctx, got, &got_len,
2601                         expected->input, expected->input_len) <= 0) {
2602         t->err = "KEYOP_ERROR";
2603         goto err;
2604     }
2605     if (!memory_err_compare(t, "KEYOP_MISMATCH",
2606                             expected->output, expected->output_len,
2607                             got, got_len))
2608         goto err;
2609 
2610     t->err = NULL;
2611     OPENSSL_free(got);
2612     got = NULL;
2613 
2614     /* Repeat the test on the EVP_PKEY context copy. */
2615     if (expected->keyop(copy, NULL, &got_len, expected->input,
2616                         expected->input_len) <= 0
2617             || !TEST_ptr(got = OPENSSL_malloc(got_len))) {
2618         t->err = "KEYOP_LENGTH_ERROR";
2619         goto err;
2620     }
2621     if (expected->keyop(copy, got, &got_len, expected->input,
2622                         expected->input_len) <= 0) {
2623         t->err = "KEYOP_ERROR";
2624         goto err;
2625     }
2626     if (!memory_err_compare(t, "KEYOP_MISMATCH",
2627                             expected->output, expected->output_len,
2628                             got, got_len))
2629         goto err;
2630 
2631     if (pkey_check_fips_approved(expected->ctx, t) <= 0)
2632         goto err;
2633 
2634  err:
2635     OPENSSL_free(got);
2636     EVP_PKEY_CTX_free(copy);
2637     return 1;
2638 }
2639 
2640 /*
2641  * "Sign" implies EVP_PKEY_sign_init_ex2() if the argument is a colon-separated
2642  * pair, {algorithm}:{key}.  If not, it implies EVP_PKEY_sign_init_ex()
2643  */
sign_test_init(EVP_TEST * t,const char * name)2644 static int sign_test_init(EVP_TEST *t, const char *name)
2645 {
2646     if (strchr(name, ':') != NULL)
2647         return pkey_test_init_ex2(t, name, 0,
2648                                   EVP_PKEY_sign_init_ex2, EVP_PKEY_sign);
2649     return pkey_test_init(t, name, 0, EVP_PKEY_sign_init_ex, EVP_PKEY_sign);
2650 }
2651 
2652 static const EVP_TEST_METHOD psign_test_method = {
2653     "Sign",
2654     sign_test_init,
2655     pkey_test_cleanup,
2656     pkey_test_parse,
2657     pkey_test_run
2658 };
2659 
2660 /*
2661  * "Sign-Message" is like "Sign", but uses EVP_PKEY_sign_message_init()
2662  * The argument must be a colon separated pair, {algorithm}:{key}
2663  */
sign_test_message_init(EVP_TEST * t,const char * name)2664 static int sign_test_message_init(EVP_TEST *t, const char *name)
2665 {
2666     return pkey_test_init_ex2(t, name, 0,
2667                               EVP_PKEY_sign_message_init, EVP_PKEY_sign);
2668 }
2669 
2670 static const EVP_TEST_METHOD psign_message_test_method = {
2671     "Sign-Message",
2672     sign_test_message_init,
2673     pkey_test_cleanup,
2674     pkey_test_parse,
2675     pkey_test_run
2676 };
2677 
2678 /*
2679  * "VerifyRecover" implies EVP_PKEY_verify_recover_init_ex2() if the argument is a
2680  * colon-separated pair, {algorithm}:{key}.
2681  * If not, it implies EVP_PKEY_verify_recover_init_ex()
2682  */
verify_recover_test_init(EVP_TEST * t,const char * name)2683 static int verify_recover_test_init(EVP_TEST *t, const char *name)
2684 {
2685     if (strchr(name, ':') != NULL)
2686         return pkey_test_init_ex2(t, name, 1,
2687                                   EVP_PKEY_verify_recover_init_ex2,
2688                                   EVP_PKEY_verify_recover);
2689     return pkey_test_init(t, name, 1, EVP_PKEY_verify_recover_init_ex,
2690                           EVP_PKEY_verify_recover);
2691 }
2692 
2693 static const EVP_TEST_METHOD pverify_recover_test_method = {
2694     "VerifyRecover",
2695     verify_recover_test_init,
2696     pkey_test_cleanup,
2697     pkey_test_parse,
2698     pkey_test_run
2699 };
2700 
decrypt_test_init(EVP_TEST * t,const char * name)2701 static int decrypt_test_init(EVP_TEST *t, const char *name)
2702 {
2703     return pkey_test_init(t, name, 0, EVP_PKEY_decrypt_init_ex,
2704                           EVP_PKEY_decrypt);
2705 }
2706 
2707 static const EVP_TEST_METHOD pdecrypt_test_method = {
2708     "Decrypt",
2709     decrypt_test_init,
2710     pkey_test_cleanup,
2711     pkey_test_parse,
2712     pkey_test_run
2713 };
2714 
2715 /*
2716  * "Verify" implies EVP_PKEY_verify_init_ex2() if the argument is a
2717  * colon-separated pair, {algorithm}:{key}.
2718  * If not, it implies EVP_PKEY_verify_init_ex()
2719  */
verify_test_init(EVP_TEST * t,const char * name)2720 static int verify_test_init(EVP_TEST *t, const char *name)
2721 {
2722     if (strchr(name, ':') != NULL)
2723         return pkey_test_init_ex2(t, name, 1,
2724                                   EVP_PKEY_verify_init_ex2, NULL);
2725     return pkey_test_init(t, name, 1, EVP_PKEY_verify_init_ex, NULL);
2726 }
2727 
verify_test_run(EVP_TEST * t)2728 static int verify_test_run(EVP_TEST *t)
2729 {
2730     int ret = 1;
2731     PKEY_DATA *kdata = t->data;
2732 
2733     if (!pkey_test_run_init(t))
2734         goto err;
2735     if (EVP_PKEY_verify(kdata->ctx, kdata->output, kdata->output_len,
2736                         kdata->input, kdata->input_len) <= 0) {
2737         t->err = "VERIFY_ERROR";
2738         goto err;
2739     }
2740     if (!pkey_check_fips_approved(kdata->ctx, t))
2741         ret = 0;
2742 err:
2743     return ret;
2744 }
2745 
2746 static const EVP_TEST_METHOD pverify_test_method = {
2747     "Verify",
2748     verify_test_init,
2749     pkey_test_cleanup,
2750     pkey_test_parse,
2751     verify_test_run
2752 };
2753 
2754 /*
2755  * "Verify-Message" is like "Verify", but uses EVP_PKEY_verify_message_init()
2756  * The argument must be a colon separated pair, {algorithm}:{key}
2757  */
verify_message_test_init(EVP_TEST * t,const char * name)2758 static int verify_message_test_init(EVP_TEST *t, const char *name)
2759 {
2760     return pkey_test_init_ex2(t, name, 0,
2761                               EVP_PKEY_verify_message_init, NULL);
2762 }
2763 
2764 static const EVP_TEST_METHOD pverify_message_test_method = {
2765     "Verify-Message",
2766     verify_message_test_init,
2767     pkey_test_cleanup,
2768     pkey_test_parse,
2769     verify_test_run
2770 };
2771 
pderive_test_init(EVP_TEST * t,const char * name)2772 static int pderive_test_init(EVP_TEST *t, const char *name)
2773 {
2774     return pkey_test_init(t, name, 0, EVP_PKEY_derive_init_ex, 0);
2775 }
2776 
pderive_test_parse(EVP_TEST * t,const char * keyword,const char * value)2777 static int pderive_test_parse(EVP_TEST *t,
2778                               const char *keyword, const char *value)
2779 {
2780     PKEY_DATA *kdata = t->data;
2781     int validate = 0;
2782 
2783     if (strcmp(keyword, "PeerKeyValidate") == 0)
2784         validate = 1;
2785 
2786     if (validate || strcmp(keyword, "PeerKey") == 0) {
2787         EVP_PKEY *peer = NULL;
2788 
2789         kdata->validate = validate;
2790         if (find_key(&peer, value, public_keys) == 0)
2791             return -1;
2792         kdata->peer = peer;
2793         return 1;
2794     }
2795     if (strcmp(keyword, "SharedSecret") == 0)
2796         return parse_bin(value, &kdata->output, &kdata->output_len);
2797     if (strcmp(keyword, "Ctrl") == 0)
2798         return pkey_add_control(t, kdata->controls, value);
2799     if (strcmp(keyword, "CtrlInit") == 0)
2800         return ctrladd(kdata->init_controls, value);
2801     return 0;
2802 }
2803 
pderive_test_run(EVP_TEST * t)2804 static int pderive_test_run(EVP_TEST *t)
2805 {
2806     EVP_PKEY_CTX *dctx = NULL;
2807     PKEY_DATA *expected = t->data;
2808     unsigned char *got = NULL;
2809     size_t got_len;
2810     int ret = 1;
2811 
2812     if (!pkey_test_run_init(t))
2813         goto err;
2814 
2815     t->err = NULL;
2816     if (EVP_PKEY_derive_set_peer_ex(expected->ctx, expected->peer,
2817                                     expected->validate) <= 0) {
2818         t->err = "DERIVE_SET_PEER_ERROR";
2819         goto err;
2820     }
2821 
2822     if (!TEST_ptr(dctx = EVP_PKEY_CTX_dup(expected->ctx))) {
2823         t->err = "DERIVE_ERROR";
2824         goto err;
2825     }
2826 
2827     if (EVP_PKEY_derive(dctx, NULL, &got_len) <= 0
2828         || !TEST_size_t_ne(got_len, 0)) {
2829         t->err = "DERIVE_ERROR";
2830         goto err;
2831     }
2832     if (!TEST_ptr(got = OPENSSL_malloc(got_len))) {
2833         t->err = "DERIVE_ERROR";
2834         goto err;
2835     }
2836     if (EVP_PKEY_derive(dctx, got, &got_len) <= 0) {
2837         t->err = "DERIVE_ERROR";
2838         goto err;
2839     }
2840     if (!memory_err_compare(t, "SHARED_SECRET_MISMATCH",
2841                             expected->output, expected->output_len,
2842                             got, got_len))
2843         goto err;
2844 
2845     if (!pkey_check_fips_approved(dctx, t)) {
2846         ret = 0;
2847         goto err;
2848     }
2849     t->err = NULL;
2850  err:
2851     OPENSSL_free(got);
2852     EVP_PKEY_CTX_free(dctx);
2853     return ret;
2854 }
2855 
2856 static const EVP_TEST_METHOD pderive_test_method = {
2857     "Derive",
2858     pderive_test_init,
2859     pkey_test_cleanup,
2860     pderive_test_parse,
2861     pderive_test_run
2862 };
2863 
2864 /**
2865  **  PBE TESTS
2866  **/
2867 
2868 typedef enum pbe_type_enum {
2869     PBE_TYPE_INVALID = 0,
2870     PBE_TYPE_SCRYPT, PBE_TYPE_PBKDF2, PBE_TYPE_PKCS12
2871 } PBE_TYPE;
2872 
2873 typedef struct pbe_data_st {
2874     PBE_TYPE pbe_type;
2875         /* scrypt parameters */
2876     uint64_t N, r, p, maxmem;
2877         /* PKCS#12 parameters */
2878     int id, iter;
2879     const EVP_MD *md;
2880         /* password */
2881     unsigned char *pass;
2882     size_t pass_len;
2883         /* salt */
2884     unsigned char *salt;
2885     size_t salt_len;
2886         /* Expected output */
2887     unsigned char *key;
2888     size_t key_len;
2889 } PBE_DATA;
2890 
2891 #ifndef OPENSSL_NO_SCRYPT
2892 /* Parse unsigned decimal 64 bit integer value */
parse_uint64(const char * value,uint64_t * pr)2893 static int parse_uint64(const char *value, uint64_t *pr)
2894 {
2895     const char *p = value;
2896 
2897     if (!TEST_true(*p)) {
2898         TEST_info("Invalid empty integer value");
2899         return -1;
2900     }
2901     for (*pr = 0; *p; ) {
2902         if (*pr > UINT64_MAX / 10) {
2903             TEST_error("Integer overflow in string %s", value);
2904             return -1;
2905         }
2906         *pr *= 10;
2907         if (!TEST_true(isdigit((unsigned char)*p))) {
2908             TEST_error("Invalid character in string %s", value);
2909             return -1;
2910         }
2911         *pr += *p - '0';
2912         p++;
2913     }
2914     return 1;
2915 }
2916 
scrypt_test_parse(EVP_TEST * t,const char * keyword,const char * value)2917 static int scrypt_test_parse(EVP_TEST *t,
2918                              const char *keyword, const char *value)
2919 {
2920     PBE_DATA *pdata = t->data;
2921 
2922     if (strcmp(keyword, "N") == 0)
2923         return parse_uint64(value, &pdata->N);
2924     if (strcmp(keyword, "p") == 0)
2925         return parse_uint64(value, &pdata->p);
2926     if (strcmp(keyword, "r") == 0)
2927         return parse_uint64(value, &pdata->r);
2928     if (strcmp(keyword, "maxmem") == 0)
2929         return parse_uint64(value, &pdata->maxmem);
2930     return 0;
2931 }
2932 #endif
2933 
pbkdf2_test_parse(EVP_TEST * t,const char * keyword,const char * value)2934 static int pbkdf2_test_parse(EVP_TEST *t,
2935                              const char *keyword, const char *value)
2936 {
2937     PBE_DATA *pdata = t->data;
2938 
2939     if (strcmp(keyword, "iter") == 0) {
2940         pdata->iter = atoi(value);
2941         if (pdata->iter <= 0)
2942             return -1;
2943         return 1;
2944     }
2945     if (strcmp(keyword, "MD") == 0) {
2946         pdata->md = EVP_get_digestbyname(value);
2947         if (pdata->md == NULL)
2948             return -1;
2949         return 1;
2950     }
2951     return 0;
2952 }
2953 
pkcs12_test_parse(EVP_TEST * t,const char * keyword,const char * value)2954 static int pkcs12_test_parse(EVP_TEST *t,
2955                              const char *keyword, const char *value)
2956 {
2957     PBE_DATA *pdata = t->data;
2958 
2959     if (strcmp(keyword, "id") == 0) {
2960         pdata->id = atoi(value);
2961         if (pdata->id <= 0)
2962             return -1;
2963         return 1;
2964     }
2965     return pbkdf2_test_parse(t, keyword, value);
2966 }
2967 
pbe_test_init(EVP_TEST * t,const char * alg)2968 static int pbe_test_init(EVP_TEST *t, const char *alg)
2969 {
2970     PBE_DATA *pdat;
2971     PBE_TYPE pbe_type = PBE_TYPE_INVALID;
2972 
2973     if (is_kdf_disabled(alg)) {
2974         TEST_info("skipping, '%s' is disabled", alg);
2975         t->skip = 1;
2976         return 1;
2977     }
2978     if (strcmp(alg, "scrypt") == 0) {
2979         pbe_type = PBE_TYPE_SCRYPT;
2980     } else if (strcmp(alg, "pbkdf2") == 0) {
2981         pbe_type = PBE_TYPE_PBKDF2;
2982     } else if (strcmp(alg, "pkcs12") == 0) {
2983         pbe_type = PBE_TYPE_PKCS12;
2984     } else {
2985         TEST_error("Unknown pbe algorithm %s", alg);
2986         return 0;
2987     }
2988     if (!TEST_ptr(pdat = OPENSSL_zalloc(sizeof(*pdat))))
2989         return 0;
2990     pdat->pbe_type = pbe_type;
2991     t->data = pdat;
2992     return 1;
2993 }
2994 
pbe_test_cleanup(EVP_TEST * t)2995 static void pbe_test_cleanup(EVP_TEST *t)
2996 {
2997     PBE_DATA *pdat = t->data;
2998 
2999     OPENSSL_free(pdat->pass);
3000     OPENSSL_free(pdat->salt);
3001     OPENSSL_free(pdat->key);
3002 }
3003 
pbe_test_parse(EVP_TEST * t,const char * keyword,const char * value)3004 static int pbe_test_parse(EVP_TEST *t,
3005                           const char *keyword, const char *value)
3006 {
3007     PBE_DATA *pdata = t->data;
3008 
3009     if (strcmp(keyword, "Password") == 0)
3010         return parse_bin(value, &pdata->pass, &pdata->pass_len);
3011     if (strcmp(keyword, "Salt") == 0)
3012         return parse_bin(value, &pdata->salt, &pdata->salt_len);
3013     if (strcmp(keyword, "Key") == 0)
3014         return parse_bin(value, &pdata->key, &pdata->key_len);
3015     if (pdata->pbe_type == PBE_TYPE_PBKDF2)
3016         return pbkdf2_test_parse(t, keyword, value);
3017     else if (pdata->pbe_type == PBE_TYPE_PKCS12)
3018         return pkcs12_test_parse(t, keyword, value);
3019 #ifndef OPENSSL_NO_SCRYPT
3020     else if (pdata->pbe_type == PBE_TYPE_SCRYPT)
3021         return scrypt_test_parse(t, keyword, value);
3022 #endif
3023     return 0;
3024 }
3025 
pbe_test_run(EVP_TEST * t)3026 static int pbe_test_run(EVP_TEST *t)
3027 {
3028     PBE_DATA *expected = t->data;
3029     unsigned char *key;
3030     EVP_MD *fetched_digest = NULL;
3031     OSSL_LIB_CTX *save_libctx;
3032 
3033     save_libctx = OSSL_LIB_CTX_set0_default(libctx);
3034 
3035     if (!TEST_ptr(key = OPENSSL_malloc(expected->key_len))) {
3036         t->err = "INTERNAL_ERROR";
3037         goto err;
3038     }
3039     if (expected->pbe_type == PBE_TYPE_PBKDF2) {
3040         if (PKCS5_PBKDF2_HMAC((char *)expected->pass, expected->pass_len,
3041                               expected->salt, expected->salt_len,
3042                               expected->iter, expected->md,
3043                               expected->key_len, key) == 0) {
3044             t->err = "PBKDF2_ERROR";
3045             goto err;
3046         }
3047 #ifndef OPENSSL_NO_SCRYPT
3048     } else if (expected->pbe_type == PBE_TYPE_SCRYPT) {
3049         if (EVP_PBE_scrypt((const char *)expected->pass, expected->pass_len,
3050                             expected->salt, expected->salt_len,
3051                             expected->N, expected->r, expected->p,
3052                             expected->maxmem, key, expected->key_len) == 0) {
3053             t->err = "SCRYPT_ERROR";
3054             goto err;
3055         }
3056 #endif
3057     } else if (expected->pbe_type == PBE_TYPE_PKCS12) {
3058         fetched_digest = EVP_MD_fetch(libctx, EVP_MD_get0_name(expected->md),
3059                                       propquery);
3060         if (fetched_digest == NULL) {
3061             t->err = "PKCS12_ERROR";
3062             goto err;
3063         }
3064         if (PKCS12_key_gen_uni(expected->pass, expected->pass_len,
3065                                expected->salt, expected->salt_len,
3066                                expected->id, expected->iter, expected->key_len,
3067                                key, fetched_digest) == 0) {
3068             t->err = "PKCS12_ERROR";
3069             goto err;
3070         }
3071     }
3072     if (!memory_err_compare(t, "KEY_MISMATCH", expected->key, expected->key_len,
3073                             key, expected->key_len))
3074         goto err;
3075 
3076     t->err = NULL;
3077 err:
3078     EVP_MD_free(fetched_digest);
3079     OPENSSL_free(key);
3080     OSSL_LIB_CTX_set0_default(save_libctx);
3081     return 1;
3082 }
3083 
3084 static const EVP_TEST_METHOD pbe_test_method = {
3085     "PBE",
3086     pbe_test_init,
3087     pbe_test_cleanup,
3088     pbe_test_parse,
3089     pbe_test_run
3090 };
3091 
3092 
3093 /**
3094  **  BASE64 TESTS
3095  **/
3096 
3097 typedef enum {
3098     BASE64_CANONICAL_ENCODING = 0,
3099     BASE64_VALID_ENCODING = 1,
3100     BASE64_INVALID_ENCODING = 2
3101 } base64_encoding_type;
3102 
3103 typedef struct encode_data_st {
3104     /* Input to encoding */
3105     unsigned char *input;
3106     size_t input_len;
3107     /* Expected output */
3108     unsigned char *output;
3109     size_t output_len;
3110     base64_encoding_type encoding;
3111 } ENCODE_DATA;
3112 
encode_test_init(EVP_TEST * t,const char * encoding)3113 static int encode_test_init(EVP_TEST *t, const char *encoding)
3114 {
3115     ENCODE_DATA *edata;
3116 
3117     if (!TEST_ptr(edata = OPENSSL_zalloc(sizeof(*edata))))
3118         return 0;
3119     if (strcmp(encoding, "canonical") == 0) {
3120         edata->encoding = BASE64_CANONICAL_ENCODING;
3121     } else if (strcmp(encoding, "valid") == 0) {
3122         edata->encoding = BASE64_VALID_ENCODING;
3123     } else if (strcmp(encoding, "invalid") == 0) {
3124         edata->encoding = BASE64_INVALID_ENCODING;
3125         if (!TEST_ptr(t->expected_err = OPENSSL_strdup("DECODE_ERROR")))
3126             goto err;
3127     } else {
3128         TEST_error("Bad encoding: %s."
3129                    " Should be one of {canonical, valid, invalid}",
3130                    encoding);
3131         goto err;
3132     }
3133     t->data = edata;
3134     return 1;
3135 err:
3136     OPENSSL_free(edata);
3137     return 0;
3138 }
3139 
encode_test_cleanup(EVP_TEST * t)3140 static void encode_test_cleanup(EVP_TEST *t)
3141 {
3142     ENCODE_DATA *edata = t->data;
3143 
3144     OPENSSL_free(edata->input);
3145     OPENSSL_free(edata->output);
3146     memset(edata, 0, sizeof(*edata));
3147 }
3148 
encode_test_parse(EVP_TEST * t,const char * keyword,const char * value)3149 static int encode_test_parse(EVP_TEST *t,
3150                              const char *keyword, const char *value)
3151 {
3152     ENCODE_DATA *edata = t->data;
3153 
3154     if (strcmp(keyword, "Input") == 0)
3155         return parse_bin(value, &edata->input, &edata->input_len);
3156     if (strcmp(keyword, "Output") == 0)
3157         return parse_bin(value, &edata->output, &edata->output_len);
3158     return 0;
3159 }
3160 
encode_test_run(EVP_TEST * t)3161 static int encode_test_run(EVP_TEST *t)
3162 {
3163     ENCODE_DATA *expected = t->data;
3164     unsigned char *encode_out = NULL, *decode_out = NULL;
3165     int output_len, chunk_len;
3166     EVP_ENCODE_CTX *decode_ctx = NULL, *encode_ctx = NULL;
3167     size_t input_len, donelen;
3168 
3169     if (!TEST_ptr(decode_ctx = EVP_ENCODE_CTX_new())) {
3170         t->err = "INTERNAL_ERROR";
3171         goto err;
3172     }
3173 
3174     if (expected->encoding == BASE64_CANONICAL_ENCODING) {
3175 
3176         if (!TEST_ptr(encode_ctx = EVP_ENCODE_CTX_new())
3177                 || !TEST_ptr(encode_out =
3178                         OPENSSL_malloc(EVP_ENCODE_LENGTH(expected->input_len))))
3179             goto err;
3180 
3181         EVP_EncodeInit(encode_ctx);
3182 
3183         input_len = expected->input_len;
3184         donelen = 0;
3185         output_len = 0;
3186         do {
3187             size_t current_len = (size_t) data_chunk_size;
3188 
3189             if (data_chunk_size == 0 || (size_t) data_chunk_size > input_len)
3190                 current_len = input_len;
3191             if (!TEST_true(EVP_EncodeUpdate(encode_ctx, encode_out, &chunk_len,
3192                                             expected->input + donelen,
3193                                             current_len)))
3194                 goto err;
3195             donelen += current_len;
3196             input_len -= current_len;
3197             output_len += chunk_len;
3198         } while (input_len > 0);
3199 
3200         EVP_EncodeFinal(encode_ctx, encode_out + output_len, &chunk_len);
3201         output_len += chunk_len;
3202 
3203         if (!memory_err_compare(t, "BAD_ENCODING",
3204                                 expected->output, expected->output_len,
3205                                 encode_out, output_len))
3206             goto err;
3207     }
3208 
3209     if (!TEST_ptr(decode_out =
3210                 OPENSSL_malloc(EVP_DECODE_LENGTH(expected->output_len))))
3211         goto err;
3212 
3213     output_len = 0;
3214     EVP_DecodeInit(decode_ctx);
3215 
3216     input_len = expected->output_len;
3217     donelen = 0;
3218     do {
3219         size_t current_len = (size_t) data_chunk_size;
3220 
3221         if (data_chunk_size == 0 || (size_t) data_chunk_size > input_len)
3222             current_len = input_len;
3223         if (EVP_DecodeUpdate(decode_ctx, decode_out + output_len, &chunk_len,
3224                                 expected->output + donelen, current_len) < 0) {
3225             t->err = "DECODE_ERROR";
3226             goto err;
3227         }
3228         donelen += current_len;
3229         input_len -= current_len;
3230         output_len += chunk_len;
3231     } while (input_len > 0);
3232 
3233     if (EVP_DecodeFinal(decode_ctx, decode_out + output_len, &chunk_len) != 1) {
3234         t->err = "DECODE_ERROR";
3235         goto err;
3236     }
3237     output_len += chunk_len;
3238 
3239     if (expected->encoding != BASE64_INVALID_ENCODING
3240             && !memory_err_compare(t, "BAD_DECODING",
3241                                    expected->input, expected->input_len,
3242                                    decode_out, output_len)) {
3243         t->err = "BAD_DECODING";
3244         goto err;
3245     }
3246 
3247     t->err = NULL;
3248  err:
3249     OPENSSL_free(encode_out);
3250     OPENSSL_free(decode_out);
3251     EVP_ENCODE_CTX_free(decode_ctx);
3252     EVP_ENCODE_CTX_free(encode_ctx);
3253     return 1;
3254 }
3255 
3256 static const EVP_TEST_METHOD encode_test_method = {
3257     "Encoding",
3258     encode_test_init,
3259     encode_test_cleanup,
3260     encode_test_parse,
3261     encode_test_run,
3262 };
3263 
3264 
3265 /**
3266  **  RAND TESTS
3267  **/
3268 #define MAX_RAND_REPEATS    15
3269 
3270 typedef struct rand_data_pass_st {
3271     unsigned char *entropy;
3272     unsigned char *reseed_entropy;
3273     unsigned char *nonce;
3274     unsigned char *pers;
3275     unsigned char *reseed_addin;
3276     unsigned char *addinA;
3277     unsigned char *addinB;
3278     unsigned char *pr_entropyA;
3279     unsigned char *pr_entropyB;
3280     unsigned char *output;
3281     size_t entropy_len, nonce_len, pers_len, addinA_len, addinB_len,
3282            pr_entropyA_len, pr_entropyB_len, output_len, reseed_entropy_len,
3283            reseed_addin_len;
3284 } RAND_DATA_PASS;
3285 
3286 typedef struct rand_data_st {
3287     /* Context for this operation */
3288     EVP_RAND_CTX *ctx;
3289     EVP_RAND_CTX *parent;
3290     int n;
3291     int prediction_resistance;
3292     int use_df;
3293     unsigned int generate_bits;
3294     char *cipher;
3295     char *digest;
3296     STACK_OF(OPENSSL_STRING) *init_controls; /* collection of controls */
3297 
3298     /* Expected output */
3299     RAND_DATA_PASS data[MAX_RAND_REPEATS];
3300 } RAND_DATA;
3301 
rand_test_init(EVP_TEST * t,const char * name)3302 static int rand_test_init(EVP_TEST *t, const char *name)
3303 {
3304     RAND_DATA *rdata;
3305     EVP_RAND *rand;
3306     OSSL_PARAM params[2] = { OSSL_PARAM_END, OSSL_PARAM_END };
3307     unsigned int strength = 256;
3308 
3309     if (!TEST_ptr(rdata = OPENSSL_zalloc(sizeof(*rdata))))
3310         return 0;
3311 
3312     /* TEST-RAND is available in the FIPS provider but not with "fips=yes" */
3313     rand = EVP_RAND_fetch(libctx, "TEST-RAND", "-fips");
3314     if (rand == NULL)
3315         goto err;
3316     rdata->parent = EVP_RAND_CTX_new(rand, NULL);
3317     EVP_RAND_free(rand);
3318     if (rdata->parent == NULL)
3319         goto err;
3320 
3321     *params = OSSL_PARAM_construct_uint(OSSL_RAND_PARAM_STRENGTH, &strength);
3322     if (!EVP_RAND_CTX_set_params(rdata->parent, params))
3323         goto err;
3324 
3325     rand = EVP_RAND_fetch(libctx, name, propquery);
3326     if (rand == NULL)
3327         goto err;
3328     rdata->ctx = EVP_RAND_CTX_new(rand, rdata->parent);
3329     EVP_RAND_free(rand);
3330     if (rdata->ctx == NULL)
3331         goto err;
3332     rdata->init_controls = sk_OPENSSL_STRING_new_null();
3333 
3334     rdata->n = -1;
3335     t->data = rdata;
3336     return 1;
3337  err:
3338     EVP_RAND_CTX_free(rdata->parent);
3339     OPENSSL_free(rdata);
3340     return 0;
3341 }
3342 
rand_test_cleanup(EVP_TEST * t)3343 static void rand_test_cleanup(EVP_TEST *t)
3344 {
3345     RAND_DATA *rdata = t->data;
3346     int i;
3347 
3348     ctrlfree(rdata->init_controls);
3349     OPENSSL_free(rdata->cipher);
3350     OPENSSL_free(rdata->digest);
3351 
3352     for (i = 0; i <= rdata->n; i++) {
3353         OPENSSL_free(rdata->data[i].entropy);
3354         OPENSSL_free(rdata->data[i].reseed_entropy);
3355         OPENSSL_free(rdata->data[i].nonce);
3356         OPENSSL_free(rdata->data[i].pers);
3357         OPENSSL_free(rdata->data[i].reseed_addin);
3358         OPENSSL_free(rdata->data[i].addinA);
3359         OPENSSL_free(rdata->data[i].addinB);
3360         OPENSSL_free(rdata->data[i].pr_entropyA);
3361         OPENSSL_free(rdata->data[i].pr_entropyB);
3362         OPENSSL_free(rdata->data[i].output);
3363     }
3364     EVP_RAND_CTX_free(rdata->ctx);
3365     EVP_RAND_CTX_free(rdata->parent);
3366 }
3367 
rand_test_parse(EVP_TEST * t,const char * keyword,const char * value)3368 static int rand_test_parse(EVP_TEST *t,
3369                           const char *keyword, const char *value)
3370 {
3371     RAND_DATA *rdata = t->data;
3372     RAND_DATA_PASS *item;
3373     const char *p;
3374     int n;
3375 
3376     if ((p = strchr(keyword, '.')) != NULL) {
3377         n = atoi(++p);
3378         if (n >= MAX_RAND_REPEATS)
3379             return 0;
3380         if (n > rdata->n)
3381             rdata->n = n;
3382         item = rdata->data + n;
3383         if (HAS_PREFIX(keyword, "Entropy."))
3384             return parse_bin(value, &item->entropy, &item->entropy_len);
3385         if (HAS_PREFIX(keyword, "ReseedEntropy."))
3386             return parse_bin(value, &item->reseed_entropy,
3387                              &item->reseed_entropy_len);
3388         if (HAS_PREFIX(keyword, "Nonce."))
3389             return parse_bin(value, &item->nonce, &item->nonce_len);
3390         if (HAS_PREFIX(keyword, "PersonalisationString."))
3391             return parse_bin(value, &item->pers, &item->pers_len);
3392         if (HAS_PREFIX(keyword, "ReseedAdditionalInput."))
3393             return parse_bin(value, &item->reseed_addin,
3394                              &item->reseed_addin_len);
3395         if (HAS_PREFIX(keyword, "AdditionalInputA."))
3396             return parse_bin(value, &item->addinA, &item->addinA_len);
3397         if (HAS_PREFIX(keyword, "AdditionalInputB."))
3398             return parse_bin(value, &item->addinB, &item->addinB_len);
3399         if (HAS_PREFIX(keyword, "EntropyPredictionResistanceA."))
3400             return parse_bin(value, &item->pr_entropyA, &item->pr_entropyA_len);
3401         if (HAS_PREFIX(keyword, "EntropyPredictionResistanceB."))
3402             return parse_bin(value, &item->pr_entropyB, &item->pr_entropyB_len);
3403         if (HAS_PREFIX(keyword, "Output."))
3404             return parse_bin(value, &item->output, &item->output_len);
3405     } else {
3406         if (strcmp(keyword, "Cipher") == 0)
3407             return TEST_ptr(rdata->cipher = OPENSSL_strdup(value));
3408         if (strcmp(keyword, "Digest") == 0)
3409             return TEST_ptr(rdata->digest = OPENSSL_strdup(value));
3410         if (strcmp(keyword, "DerivationFunction") == 0) {
3411             rdata->use_df = atoi(value) != 0;
3412             return 1;
3413         }
3414         if (strcmp(keyword, "GenerateBits") == 0) {
3415             if ((n = atoi(value)) <= 0 || n % 8 != 0)
3416                 return 0;
3417             rdata->generate_bits = (unsigned int)n;
3418             return 1;
3419         }
3420         if (strcmp(keyword, "PredictionResistance") == 0) {
3421             rdata->prediction_resistance = atoi(value) != 0;
3422             return 1;
3423         }
3424         if (strcmp(keyword, "CtrlInit") == 0)
3425             return ctrladd(rdata->init_controls, value);
3426     }
3427     return 0;
3428 }
3429 
rand_test_run(EVP_TEST * t)3430 static int rand_test_run(EVP_TEST *t)
3431 {
3432     RAND_DATA *expected = t->data;
3433     RAND_DATA_PASS *item;
3434     unsigned char *got;
3435     size_t got_len = expected->generate_bits / 8;
3436     OSSL_PARAM params[8], *p = params;
3437     int i = -1, ret = 0;
3438     unsigned int strength;
3439     unsigned char *z;
3440     size_t params_n = 0, params_allocated_n = 0;
3441 
3442     if (!TEST_ptr(got = OPENSSL_malloc(got_len)))
3443         return 0;
3444 
3445     if (sk_OPENSSL_STRING_num(expected->init_controls) > 0) {
3446         if (!ctrl2params(t, expected->init_controls,
3447                          NULL,
3448                          params, OSSL_NELEM(params), &params_n))
3449             goto err;
3450     }
3451     p = params + params_n;
3452 
3453     *p++ = OSSL_PARAM_construct_int(OSSL_DRBG_PARAM_USE_DF, &expected->use_df);
3454     if (expected->cipher != NULL)
3455         *p++ = OSSL_PARAM_construct_utf8_string(OSSL_DRBG_PARAM_CIPHER,
3456                                                 expected->cipher, 0);
3457     if (expected->digest != NULL)
3458         *p++ = OSSL_PARAM_construct_utf8_string(OSSL_DRBG_PARAM_DIGEST,
3459                                                 expected->digest, 0);
3460     *p++ = OSSL_PARAM_construct_utf8_string(OSSL_DRBG_PARAM_MAC, "HMAC", 0);
3461     *p = OSSL_PARAM_construct_end();
3462     if (!EVP_RAND_CTX_set_params(expected->ctx, params)) {
3463         if (t->expect_unapproved == 0) {
3464             t->err = "EVP_RAND_CTX_set_params";
3465             ret = 1;
3466         }
3467         goto err;
3468     }
3469     ctrl2params_free(params, params_n, params_allocated_n);
3470     params_n = 0;
3471 
3472     strength = EVP_RAND_get_strength(expected->ctx);
3473     for (i = 0; i <= expected->n; i++) {
3474         item = expected->data + i;
3475 
3476         p = params;
3477         z = item->entropy != NULL ? item->entropy : (unsigned char *)"";
3478         *p++ = OSSL_PARAM_construct_octet_string(OSSL_RAND_PARAM_TEST_ENTROPY,
3479                                                  z, item->entropy_len);
3480         z = item->nonce != NULL ? item->nonce : (unsigned char *)"";
3481         *p++ = OSSL_PARAM_construct_octet_string(OSSL_RAND_PARAM_TEST_NONCE,
3482                                                  z, item->nonce_len);
3483         *p = OSSL_PARAM_construct_end();
3484         if (!TEST_true(EVP_RAND_instantiate(expected->parent, strength,
3485                                             0, NULL, 0, params)))
3486             goto err;
3487 
3488         z = item->pers != NULL ? item->pers : (unsigned char *)"";
3489         if (!TEST_true(EVP_RAND_instantiate
3490                            (expected->ctx, strength,
3491                             expected->prediction_resistance, z,
3492                             item->pers_len, NULL)))
3493             goto err;
3494 
3495         if (item->reseed_entropy != NULL) {
3496             params[0] = OSSL_PARAM_construct_octet_string
3497                            (OSSL_RAND_PARAM_TEST_ENTROPY, item->reseed_entropy,
3498                             item->reseed_entropy_len);
3499             params[1] = OSSL_PARAM_construct_end();
3500             if (!TEST_true(EVP_RAND_CTX_set_params(expected->parent, params)))
3501                 goto err;
3502 
3503             if (!TEST_true(EVP_RAND_reseed
3504                                (expected->ctx, expected->prediction_resistance,
3505                                 NULL, 0, item->reseed_addin,
3506                                 item->reseed_addin_len)))
3507                 goto err;
3508         }
3509         if (item->pr_entropyA != NULL) {
3510             params[0] = OSSL_PARAM_construct_octet_string
3511                            (OSSL_RAND_PARAM_TEST_ENTROPY, item->pr_entropyA,
3512                             item->pr_entropyA_len);
3513             params[1] = OSSL_PARAM_construct_end();
3514             if (!TEST_true(EVP_RAND_CTX_set_params(expected->parent, params)))
3515                 goto err;
3516         }
3517         if (!TEST_true(EVP_RAND_generate
3518                            (expected->ctx, got, got_len,
3519                             strength, expected->prediction_resistance,
3520                             item->addinA, item->addinA_len)))
3521             goto err;
3522 
3523         if (item->pr_entropyB != NULL) {
3524             params[0] = OSSL_PARAM_construct_octet_string
3525                            (OSSL_RAND_PARAM_TEST_ENTROPY, item->pr_entropyB,
3526                             item->pr_entropyB_len);
3527             params[1] = OSSL_PARAM_construct_end();
3528             if (!TEST_true(EVP_RAND_CTX_set_params(expected->parent, params)))
3529                 goto err;
3530         }
3531         if (!TEST_true(EVP_RAND_generate
3532                            (expected->ctx, got, got_len,
3533                             strength, expected->prediction_resistance,
3534                             item->addinB, item->addinB_len)))
3535             goto err;
3536         if (!TEST_mem_eq(got, got_len, item->output, item->output_len))
3537             goto err;
3538         if (!rand_check_fips_approved(expected->ctx, t))
3539             goto err;
3540         if (!TEST_true(EVP_RAND_uninstantiate(expected->ctx))
3541                 || !TEST_true(EVP_RAND_uninstantiate(expected->parent))
3542                 || !TEST_true(EVP_RAND_verify_zeroization(expected->ctx))
3543                 || !TEST_int_eq(EVP_RAND_get_state(expected->ctx),
3544                                 EVP_RAND_STATE_UNINITIALISED))
3545             goto err;
3546     }
3547     t->err = NULL;
3548     ret = 1;
3549 
3550  err:
3551     if (ret == 0 && i >= 0)
3552         TEST_info("Error in test case %d of %d\n", i, expected->n + 1);
3553     OPENSSL_free(got);
3554     ctrl2params_free(params, params_n, params_allocated_n);
3555     return ret;
3556 }
3557 
3558 static const EVP_TEST_METHOD rand_test_method = {
3559     "RAND",
3560     rand_test_init,
3561     rand_test_cleanup,
3562     rand_test_parse,
3563     rand_test_run
3564 };
3565 
3566 /**
3567  **  KDF TESTS
3568  **/
3569 typedef struct kdf_data_st {
3570     /* Context for this operation */
3571     EVP_KDF_CTX *ctx;
3572     /* Expected output */
3573     unsigned char *output;
3574     size_t output_len;
3575     OSSL_PARAM params[20];
3576     OSSL_PARAM *p;
3577     STACK_OF(OPENSSL_STRING) *init_controls; /* collection of controls */
3578 } KDF_DATA;
3579 
3580 /*
3581  * Perform public key operation setup: lookup key, allocated ctx and call
3582  * the appropriate initialisation function
3583  */
kdf_test_init(EVP_TEST * t,const char * name)3584 static int kdf_test_init(EVP_TEST *t, const char *name)
3585 {
3586     KDF_DATA *kdata;
3587     EVP_KDF *kdf;
3588 
3589     if (is_kdf_disabled(name)) {
3590         TEST_info("skipping, '%s' is disabled", name);
3591         t->skip = 1;
3592         return 1;
3593     }
3594 
3595     if (!TEST_ptr(kdata = OPENSSL_zalloc(sizeof(*kdata))))
3596         return 0;
3597     kdata->p = kdata->params;
3598     *kdata->p = OSSL_PARAM_construct_end();
3599 
3600     kdf = EVP_KDF_fetch(libctx, name, propquery);
3601     if (kdf == NULL) {
3602         OPENSSL_free(kdata);
3603         return 0;
3604     }
3605     kdata->ctx = EVP_KDF_CTX_new(kdf);
3606     EVP_KDF_free(kdf);
3607     if (kdata->ctx == NULL) {
3608         OPENSSL_free(kdata);
3609         return 0;
3610     }
3611     t->data = kdata;
3612     kdata->init_controls = sk_OPENSSL_STRING_new_null();
3613     return 1;
3614 }
3615 
kdf_test_cleanup(EVP_TEST * t)3616 static void kdf_test_cleanup(EVP_TEST *t)
3617 {
3618     KDF_DATA *kdata = t->data;
3619     OSSL_PARAM *p;
3620 
3621     ctrlfree(kdata->init_controls);
3622     for (p = kdata->params; p->key != NULL; p++)
3623         OPENSSL_free(p->data);
3624     OPENSSL_free(kdata->output);
3625     EVP_KDF_CTX_free(kdata->ctx);
3626 }
3627 
kdf_test_ctrl(EVP_TEST * t,EVP_KDF_CTX * kctx,const char * value)3628 static int kdf_test_ctrl(EVP_TEST *t, EVP_KDF_CTX *kctx,
3629                          const char *value)
3630 {
3631     KDF_DATA *kdata = t->data;
3632     int rv;
3633     char *p, *name;
3634     const OSSL_PARAM *defs = EVP_KDF_settable_ctx_params(EVP_KDF_CTX_kdf(kctx));
3635 
3636     if (!TEST_ptr(name = OPENSSL_strdup(value)))
3637         return 0;
3638     p = strchr(name, ':');
3639     if (p == NULL)
3640         p = "";
3641     else
3642         *p++ = '\0';
3643 
3644     if (strcmp(name, "r") == 0
3645         && OSSL_PARAM_locate_const(defs, name) == NULL) {
3646         TEST_info("skipping, setting 'r' is unsupported");
3647         t->skip = 1;
3648         goto end;
3649     }
3650 
3651     if (strcmp(name, "lanes") == 0
3652         && OSSL_PARAM_locate_const(defs, name) == NULL) {
3653         TEST_info("skipping, setting 'lanes' is unsupported");
3654         t->skip = 1;
3655         goto end;
3656     }
3657 
3658     if (strcmp(name, "iter") == 0
3659         && OSSL_PARAM_locate_const(defs, name) == NULL) {
3660         TEST_info("skipping, setting 'iter' is unsupported");
3661         t->skip = 1;
3662         goto end;
3663     }
3664 
3665     if (strcmp(name, "memcost") == 0
3666         && OSSL_PARAM_locate_const(defs, name) == NULL) {
3667         TEST_info("skipping, setting 'memcost' is unsupported");
3668         t->skip = 1;
3669         goto end;
3670     }
3671 
3672     if (strcmp(name, "secret") == 0
3673         && OSSL_PARAM_locate_const(defs, name) == NULL) {
3674         TEST_info("skipping, setting 'secret' is unsupported");
3675         t->skip = 1;
3676         goto end;
3677     }
3678 
3679     if (strcmp(name, "pass") == 0
3680         && OSSL_PARAM_locate_const(defs, name) == NULL) {
3681         TEST_info("skipping, setting 'pass' is unsupported");
3682         t->skip = 1;
3683         goto end;
3684     }
3685 
3686     if (strcmp(name, "ad") == 0
3687         && OSSL_PARAM_locate_const(defs, name) == NULL) {
3688         TEST_info("skipping, setting 'ad' is unsupported");
3689         t->skip = 1;
3690         goto end;
3691     }
3692 
3693     rv = OSSL_PARAM_allocate_from_text(kdata->p, defs, name, p,
3694                                        strlen(p), NULL);
3695     *++kdata->p = OSSL_PARAM_construct_end();
3696     if (!rv) {
3697         t->err = "KDF_PARAM_ERROR";
3698         OPENSSL_free(name);
3699         return 0;
3700     }
3701     if (strcmp(name, "digest") == 0) {
3702         if (is_digest_disabled(p)) {
3703             TEST_info("skipping, '%s' is disabled", p);
3704             t->skip = 1;
3705         }
3706         goto end;
3707     }
3708 
3709     if ((strcmp(name, "cipher") == 0
3710         || strcmp(name, "cekalg") == 0)
3711         && is_cipher_disabled(p)) {
3712         TEST_info("skipping, '%s' is disabled", p);
3713         t->skip = 1;
3714         goto end;
3715     }
3716     if ((strcmp(name, "mac") == 0)
3717         && is_mac_disabled(p)) {
3718         TEST_info("skipping, '%s' is disabled", p);
3719         t->skip = 1;
3720     }
3721  end:
3722     OPENSSL_free(name);
3723     return 1;
3724 }
3725 
kdf_test_parse(EVP_TEST * t,const char * keyword,const char * value)3726 static int kdf_test_parse(EVP_TEST *t,
3727                           const char *keyword, const char *value)
3728 {
3729     KDF_DATA *kdata = t->data;
3730 
3731     if (strcmp(keyword, "Output") == 0)
3732         return parse_bin(value, &kdata->output, &kdata->output_len);
3733     if (strcmp(keyword, "CtrlInit") == 0)
3734         return ctrladd(kdata->init_controls, value);
3735     if (HAS_PREFIX(keyword, "Ctrl"))
3736         return kdf_test_ctrl(t, kdata->ctx, value);
3737     return 0;
3738 }
3739 
kdf_test_run(EVP_TEST * t)3740 static int kdf_test_run(EVP_TEST *t)
3741 {
3742     int ret = 1;
3743     KDF_DATA *expected = t->data;
3744     unsigned char *got = NULL;
3745     size_t got_len = expected->output_len;
3746     EVP_KDF_CTX *ctx;
3747     OSSL_PARAM params[2] = { OSSL_PARAM_END, OSSL_PARAM_END };
3748     size_t params_n = 0, params_allocated_n = 0;
3749 
3750     if (sk_OPENSSL_STRING_num(expected->init_controls) > 0) {
3751         if (!ctrl2params(t, expected->init_controls,
3752                          NULL,
3753                          params, OSSL_NELEM(params), &params_n))
3754             goto err;
3755         if (!EVP_KDF_CTX_set_params(expected->ctx, params)) {
3756             t->err = "KDF_CTRL_ERROR";
3757             goto err;
3758         }
3759     }
3760 
3761     if (!EVP_KDF_CTX_set_params(expected->ctx, expected->params)) {
3762         t->err = "KDF_CTRL_ERROR";
3763         goto err;
3764     }
3765     if (!TEST_ptr(got = OPENSSL_malloc(got_len == 0 ? 1 : got_len))) {
3766         t->err = "INTERNAL_ERROR";
3767         goto err;
3768     }
3769     /* FIPS(3.0.0): can't dup KDF contexts #17572 */
3770     if (fips_provider_version_gt(libctx, 3, 0, 0)
3771             && (ctx = EVP_KDF_CTX_dup(expected->ctx)) != NULL) {
3772         EVP_KDF_CTX_free(expected->ctx);
3773         expected->ctx = ctx;
3774     }
3775     if (EVP_KDF_derive(expected->ctx, got, got_len, NULL) <= 0) {
3776         t->err = "KDF_DERIVE_ERROR";
3777         goto err;
3778     }
3779     if (!kdf_check_fips_approved(expected->ctx, t)) {
3780         ret = 0;
3781         goto err;
3782     }
3783     if (!memory_err_compare(t, "KDF_MISMATCH",
3784                             expected->output, expected->output_len,
3785                             got, got_len))
3786         goto err;
3787 
3788     t->err = NULL;
3789 
3790  err:
3791     ctrl2params_free(params, params_n, params_allocated_n);
3792     OPENSSL_free(got);
3793     return ret;
3794 }
3795 
3796 static const EVP_TEST_METHOD kdf_test_method = {
3797     "KDF",
3798     kdf_test_init,
3799     kdf_test_cleanup,
3800     kdf_test_parse,
3801     kdf_test_run
3802 };
3803 
3804 /**
3805  **  PKEY KDF TESTS
3806  **/
3807 
3808 typedef struct pkey_kdf_data_st {
3809     /* Context for this operation */
3810     EVP_PKEY_CTX *ctx;
3811     /* Expected output */
3812     unsigned char *output;
3813     size_t output_len;
3814 } PKEY_KDF_DATA;
3815 
3816 /*
3817  * Perform public key operation setup: lookup key, allocated ctx and call
3818  * the appropriate initialisation function
3819  */
pkey_kdf_test_init(EVP_TEST * t,const char * name)3820 static int pkey_kdf_test_init(EVP_TEST *t, const char *name)
3821 {
3822     PKEY_KDF_DATA *kdata = NULL;
3823 
3824     if (is_kdf_disabled(name)) {
3825         TEST_info("skipping, '%s' is disabled", name);
3826         t->skip = 1;
3827         return 1;
3828     }
3829 
3830     if (!TEST_ptr(kdata = OPENSSL_zalloc(sizeof(*kdata))))
3831         return 0;
3832 
3833     kdata->ctx = EVP_PKEY_CTX_new_from_name(libctx, name, propquery);
3834     if (kdata->ctx == NULL
3835         || EVP_PKEY_derive_init(kdata->ctx) <= 0)
3836         goto err;
3837 
3838     t->data = kdata;
3839     return 1;
3840 err:
3841     EVP_PKEY_CTX_free(kdata->ctx);
3842     OPENSSL_free(kdata);
3843     return 0;
3844 }
3845 
pkey_kdf_test_cleanup(EVP_TEST * t)3846 static void pkey_kdf_test_cleanup(EVP_TEST *t)
3847 {
3848     PKEY_KDF_DATA *kdata = t->data;
3849 
3850     OPENSSL_free(kdata->output);
3851     EVP_PKEY_CTX_free(kdata->ctx);
3852 }
3853 
pkey_kdf_test_parse(EVP_TEST * t,const char * keyword,const char * value)3854 static int pkey_kdf_test_parse(EVP_TEST *t,
3855                                const char *keyword, const char *value)
3856 {
3857     PKEY_KDF_DATA *kdata = t->data;
3858 
3859     if (strcmp(keyword, "Output") == 0)
3860         return parse_bin(value, &kdata->output, &kdata->output_len);
3861     if (HAS_PREFIX(keyword, "Ctrl"))
3862         return pkey_test_ctrl(t, kdata->ctx, value);
3863     return 0;
3864 }
3865 
pkey_kdf_test_run(EVP_TEST * t)3866 static int pkey_kdf_test_run(EVP_TEST *t)
3867 {
3868     int ret = 1;
3869     PKEY_KDF_DATA *expected = t->data;
3870     unsigned char *got = NULL;
3871     size_t got_len = 0;
3872 
3873     if (fips_provider_version_eq(libctx, 3, 0, 0)) {
3874         /* FIPS(3.0.0): can't deal with oversized output buffers #18533 */
3875         got_len = expected->output_len;
3876     } else {
3877         /* Find out the KDF output size */
3878         if (EVP_PKEY_derive(expected->ctx, NULL, &got_len) <= 0) {
3879             t->err = "INTERNAL_ERROR";
3880             goto err;
3881         }
3882 
3883         /*
3884          * We may get an absurd output size, which signals that anything goes.
3885          * If not, we specify a too big buffer for the output, to test that
3886          * EVP_PKEY_derive() can cope with it.
3887          */
3888         if (got_len == SIZE_MAX || got_len == 0)
3889             got_len = expected->output_len;
3890         else
3891             got_len = expected->output_len * 2;
3892     }
3893 
3894     if (!TEST_ptr(got = OPENSSL_malloc(got_len == 0 ? 1 : got_len))) {
3895         t->err = "INTERNAL_ERROR";
3896         goto err;
3897     }
3898     if (EVP_PKEY_derive(expected->ctx, got, &got_len) <= 0) {
3899         t->err = "KDF_DERIVE_ERROR";
3900         goto err;
3901     }
3902     if (!pkey_check_fips_approved(expected->ctx, t)) {
3903         ret = 0;
3904         goto err;
3905     }
3906     if (!TEST_mem_eq(expected->output, expected->output_len, got, got_len)) {
3907         t->err = "KDF_MISMATCH";
3908         goto err;
3909     }
3910     t->err = NULL;
3911 
3912  err:
3913     OPENSSL_free(got);
3914     return ret;
3915 }
3916 
3917 static const EVP_TEST_METHOD pkey_kdf_test_method = {
3918     "PKEYKDF",
3919     pkey_kdf_test_init,
3920     pkey_kdf_test_cleanup,
3921     pkey_kdf_test_parse,
3922     pkey_kdf_test_run
3923 };
3924 
3925 /**
3926  **  KEYPAIR TESTS
3927  **/
3928 
3929 typedef struct keypair_test_data_st {
3930     EVP_PKEY *privk;
3931     EVP_PKEY *pubk;
3932 } KEYPAIR_TEST_DATA;
3933 
keypair_test_init(EVP_TEST * t,const char * pair)3934 static int keypair_test_init(EVP_TEST *t, const char *pair)
3935 {
3936     KEYPAIR_TEST_DATA *data;
3937     int rv = 0;
3938     EVP_PKEY *pk = NULL, *pubk = NULL;
3939     char *pub, *priv = NULL;
3940 
3941     /* Split private and public names. */
3942     if (!TEST_ptr(priv = OPENSSL_strdup(pair))
3943             || !TEST_ptr(pub = strchr(priv, ':'))) {
3944         t->err = "PARSING_ERROR";
3945         goto end;
3946     }
3947     *pub++ = '\0';
3948 
3949     if (!TEST_true(find_key(&pk, priv, private_keys))) {
3950         TEST_info("Can't find private key: %s", priv);
3951         t->err = "MISSING_PRIVATE_KEY";
3952         goto end;
3953     }
3954     if (!TEST_true(find_key(&pubk, pub, public_keys))) {
3955         TEST_info("Can't find public key: %s", pub);
3956         t->err = "MISSING_PUBLIC_KEY";
3957         goto end;
3958     }
3959 
3960     if (pk == NULL && pubk == NULL) {
3961         /* Both keys are listed but unsupported: skip this test */
3962         t->skip = 1;
3963         rv = 1;
3964         goto end;
3965     }
3966 
3967     if (!TEST_ptr(data = OPENSSL_malloc(sizeof(*data))))
3968         goto end;
3969     data->privk = pk;
3970     data->pubk = pubk;
3971     t->data = data;
3972     rv = 1;
3973     t->err = NULL;
3974 
3975  end:
3976     OPENSSL_free(priv);
3977     return rv;
3978 }
3979 
keypair_test_cleanup(EVP_TEST * t)3980 static void keypair_test_cleanup(EVP_TEST *t)
3981 {
3982     OPENSSL_free(t->data);
3983     t->data = NULL;
3984 }
3985 
3986 /*
3987  * For tests that do not accept any custom keywords.
3988  */
void_test_parse(EVP_TEST * t,const char * keyword,const char * value)3989 static int void_test_parse(EVP_TEST *t, const char *keyword, const char *value)
3990 {
3991     return 0;
3992 }
3993 
keypair_test_run(EVP_TEST * t)3994 static int keypair_test_run(EVP_TEST *t)
3995 {
3996     int rv = 0;
3997     const KEYPAIR_TEST_DATA *pair = t->data;
3998 
3999     if (pair->privk == NULL || pair->pubk == NULL) {
4000         /*
4001          * this can only happen if only one of the keys is not set
4002          * which means that one of them was unsupported while the
4003          * other isn't: hence a key type mismatch.
4004          */
4005         t->err = "KEYPAIR_TYPE_MISMATCH";
4006         rv = 1;
4007         goto end;
4008     }
4009 
4010     if ((rv = EVP_PKEY_eq(pair->privk, pair->pubk)) != 1) {
4011         if (0 == rv) {
4012             t->err = "KEYPAIR_MISMATCH";
4013         } else if (-1 == rv) {
4014             t->err = "KEYPAIR_TYPE_MISMATCH";
4015         } else if (-2 == rv) {
4016             t->err = "UNSUPPORTED_KEY_COMPARISON";
4017         } else {
4018             TEST_error("Unexpected error in key comparison");
4019             rv = 0;
4020             goto end;
4021         }
4022         rv = 1;
4023         goto end;
4024     }
4025 
4026     rv = 1;
4027     t->err = NULL;
4028 
4029 end:
4030     return rv;
4031 }
4032 
4033 static const EVP_TEST_METHOD keypair_test_method = {
4034     "PrivPubKeyPair",
4035     keypair_test_init,
4036     keypair_test_cleanup,
4037     void_test_parse,
4038     keypair_test_run
4039 };
4040 
4041 /**
4042  **  KEYGEN TEST
4043  **/
4044 
4045 typedef struct keygen_test_data_st {
4046     char *keyname; /* Key name to store key or NULL */
4047     char *paramname;
4048     char *alg;
4049     STACK_OF(OPENSSL_STRING) *controls; /* Collection of controls */
4050 } KEYGEN_TEST_DATA;
4051 
keygen_test_init(EVP_TEST * t,const char * alg)4052 static int keygen_test_init(EVP_TEST *t, const char *alg)
4053 {
4054     KEYGEN_TEST_DATA *data;
4055 
4056     if (is_pkey_disabled(alg)) {
4057         t->skip = 1;
4058         return 1;
4059     }
4060 
4061     if (!TEST_ptr(data = OPENSSL_malloc(sizeof(*data))))
4062         return 0;
4063     data->keyname = NULL;
4064     data->paramname = NULL;
4065     data->controls = sk_OPENSSL_STRING_new_null();
4066     data->alg = OPENSSL_strdup(alg);
4067     t->data = data;
4068     t->err = NULL;
4069     return 1;
4070 }
4071 
keygen_test_cleanup(EVP_TEST * t)4072 static void keygen_test_cleanup(EVP_TEST *t)
4073 {
4074     KEYGEN_TEST_DATA *keygen = t->data;
4075 
4076     ctrlfree(keygen->controls);
4077     OPENSSL_free(keygen->alg);
4078     OPENSSL_free(keygen->keyname);
4079     OPENSSL_free(keygen->paramname);
4080     OPENSSL_free(t->data);
4081     t->data = NULL;
4082 }
4083 
keygen_test_parse(EVP_TEST * t,const char * keyword,const char * value)4084 static int keygen_test_parse(EVP_TEST *t,
4085                              const char *keyword, const char *value)
4086 {
4087     KEYGEN_TEST_DATA *keygen = t->data;
4088 
4089     if (strcmp(keyword, "KeyName") == 0)
4090         return TEST_ptr(keygen->keyname = OPENSSL_strdup(value));
4091     if (strcmp(keyword, "KeyParam") == 0)
4092         return TEST_ptr(keygen->paramname = OPENSSL_strdup(value));
4093     if (strcmp(keyword, "Ctrl") == 0)
4094         return ctrladd(keygen->controls, value);
4095     return 0;
4096 }
4097 
keygen_test_run(EVP_TEST * t)4098 static int keygen_test_run(EVP_TEST *t)
4099 {
4100     KEYGEN_TEST_DATA *keygen = t->data;
4101     EVP_PKEY *pkey = NULL, *keyparams = NULL;
4102     EVP_PKEY_CTX *genctx = NULL; /* Keygen context to use */
4103     int rv = 1;
4104     OSSL_PARAM params[4];
4105     size_t params_n = 0;
4106 
4107     if (keygen->paramname != NULL) {
4108         rv = find_key(&keyparams, keygen->paramname, public_keys);
4109         if (rv == 0 || keyparams == NULL) {
4110             TEST_info("skipping, key '%s' is disabled", keygen->paramname);
4111             t->skip = 1;
4112             return 1;
4113         }
4114         if (!TEST_ptr(genctx = EVP_PKEY_CTX_new_from_pkey(libctx, keyparams,
4115                                                           propquery)))
4116             goto err;
4117 
4118     } else {
4119         if (!TEST_ptr(genctx = EVP_PKEY_CTX_new_from_name(libctx, keygen->alg,
4120                                                           propquery)))
4121             goto err;
4122     }
4123 
4124     if (EVP_PKEY_keygen_init(genctx) <= 0) {
4125         t->err = "KEYGEN_INIT_ERROR";
4126         goto err;
4127     }
4128 
4129     if (sk_OPENSSL_STRING_num(keygen->controls) > 0) {
4130         if (!ctrl2params(t, keygen->controls,
4131                          EVP_PKEY_CTX_settable_params(genctx),
4132                          params, OSSL_NELEM(params), &params_n))
4133             goto err;
4134         if (!EVP_PKEY_CTX_set_params(genctx, params)) {
4135             t->err = "PKEY_CTRL_ERROR";
4136             goto err;
4137         }
4138     } else {
4139         params[0] = OSSL_PARAM_construct_end();
4140     }
4141 
4142     if (EVP_PKEY_keygen(genctx, &pkey) <= 0) {
4143         t->err = "KEYGEN_GENERATE_ERROR";
4144         goto err;
4145     }
4146     if (!pkey_check_fips_approved(genctx, t)) {
4147         rv = 0;
4148         goto err;
4149     }
4150 
4151     if (!evp_pkey_is_provided(pkey)) {
4152         TEST_info("Warning: legacy key generated %s", keygen->keyname);
4153         goto err;
4154     }
4155     if (keygen->keyname != NULL) {
4156         KEY_LIST *key;
4157 
4158         rv = 0;
4159         if (find_key(NULL, keygen->keyname, private_keys)) {
4160             TEST_info("Duplicate key %s", keygen->keyname);
4161             goto err;
4162         }
4163 
4164         if (!TEST_ptr(key = OPENSSL_malloc(sizeof(*key))))
4165             goto err;
4166         key->name = keygen->keyname;
4167         keygen->keyname = NULL;
4168         key->key = pkey;
4169         key->next = private_keys;
4170         private_keys = key;
4171         rv = 1;
4172     } else {
4173         EVP_PKEY_free(pkey);
4174     }
4175 
4176     t->err = NULL;
4177  err:
4178     ctrl2params_free(params, params_n, 0);
4179     EVP_PKEY_CTX_free(genctx);
4180     return rv;
4181 }
4182 
4183 static const EVP_TEST_METHOD keygen_test_method = {
4184     "KeyGen",
4185     keygen_test_init,
4186     keygen_test_cleanup,
4187     keygen_test_parse,
4188     keygen_test_run,
4189 };
4190 
4191 /**
4192  **  DIGEST SIGN+VERIFY TESTS
4193  **/
4194 
4195 typedef struct {
4196     int is_verify; /* Set to 1 if verifying */
4197     int is_oneshot; /* Set to 1 for one shot operation */
4198     const EVP_MD *md; /* Digest to use */
4199     EVP_MD_CTX *ctx; /* Digest context */
4200     EVP_PKEY_CTX *pctx;
4201     STACK_OF(EVP_TEST_BUFFER) *input; /* Input data: streaming */
4202     unsigned char *osin; /* Input data if one shot */
4203     size_t osin_len; /* Input length data if one shot */
4204     unsigned char *output; /* Expected output */
4205     size_t output_len; /* Expected output length */
4206     int deterministic_noncetype;
4207     EVP_PKEY *key;
4208     STACK_OF(OPENSSL_STRING) *init_controls; /* collection of controls */
4209     STACK_OF(OPENSSL_STRING) *controls; /* Collection of controls */
4210 } DIGESTSIGN_DATA;
4211 
digestsigver_test_init(EVP_TEST * t,const char * alg,int is_verify,int is_oneshot)4212 static int digestsigver_test_init(EVP_TEST *t, const char *alg, int is_verify,
4213                                   int is_oneshot)
4214 {
4215     const EVP_MD *md = NULL;
4216     DIGESTSIGN_DATA *mdat;
4217 
4218     if (strcmp(alg, "NULL") != 0) {
4219         if (is_digest_disabled(alg)) {
4220             t->skip = 1;
4221             return 1;
4222         }
4223         md = EVP_get_digestbyname(alg);
4224         if (md == NULL)
4225             return 0;
4226     }
4227     if (!TEST_ptr(mdat = OPENSSL_zalloc(sizeof(*mdat))))
4228         return 0;
4229     mdat->init_controls = sk_OPENSSL_STRING_new_null();
4230     mdat->controls = sk_OPENSSL_STRING_new_null();
4231     mdat->md = md;
4232     if (!TEST_ptr(mdat->ctx = EVP_MD_CTX_new())) {
4233         OPENSSL_free(mdat);
4234         return 0;
4235     }
4236     mdat->is_verify = is_verify;
4237     mdat->is_oneshot = is_oneshot;
4238     t->data = mdat;
4239     return 1;
4240 }
4241 
digestsign_test_init(EVP_TEST * t,const char * alg)4242 static int digestsign_test_init(EVP_TEST *t, const char *alg)
4243 {
4244     return digestsigver_test_init(t, alg, 0, 0);
4245 }
4246 
digestsigver_test_cleanup(EVP_TEST * t)4247 static void digestsigver_test_cleanup(EVP_TEST *t)
4248 {
4249     DIGESTSIGN_DATA *mdata = t->data;
4250 
4251     ctrlfree(mdata->init_controls);
4252     ctrlfree(mdata->controls);
4253     EVP_MD_CTX_free(mdata->ctx);
4254     sk_EVP_TEST_BUFFER_pop_free(mdata->input, evp_test_buffer_free);
4255     OPENSSL_free(mdata->osin);
4256     OPENSSL_free(mdata->output);
4257     OPENSSL_free(mdata);
4258     t->data = NULL;
4259 }
4260 
digestsigver_test_parse(EVP_TEST * t,const char * keyword,const char * value)4261 static int digestsigver_test_parse(EVP_TEST *t,
4262                                    const char *keyword, const char *value)
4263 {
4264     DIGESTSIGN_DATA *mdata = t->data;
4265 
4266     if (strcmp(keyword, "Key") == 0) {
4267         EVP_PKEY *pkey = NULL;
4268         int rv = 0;
4269 
4270         if (mdata->is_verify)
4271             rv = find_key(&pkey, value, public_keys);
4272         if (rv == 0)
4273             rv = find_key(&pkey, value, private_keys);
4274         if (rv == 0 || pkey == NULL) {
4275             t->skip = 1;
4276             return 1;
4277         }
4278         mdata->key = pkey;
4279         return 1;
4280     }
4281 
4282     if (strcmp(keyword, "Input") == 0) {
4283         if (mdata->is_oneshot)
4284             return parse_bin(value, &mdata->osin, &mdata->osin_len);
4285         return evp_test_buffer_append(value, data_chunk_size, &mdata->input);
4286     }
4287     if (strcmp(keyword, "Output") == 0)
4288         return parse_bin(value, &mdata->output, &mdata->output_len);
4289 
4290     if (!mdata->is_oneshot && data_chunk_size == 0) {
4291         if (strcmp(keyword, "Count") == 0)
4292             return evp_test_buffer_set_count(value, mdata->input);
4293         if (strcmp(keyword, "Ncopy") == 0)
4294             return evp_test_buffer_ncopy(value, mdata->input);
4295     }
4296     if (strcmp(keyword, "Ctrl") == 0)
4297         return pkey_add_control(t, mdata->controls, value);
4298     if (strcmp(keyword, "CtrlInit") == 0)
4299         return ctrladd(mdata->init_controls, value);
4300     if (strcmp(keyword, "NonceType") == 0) {
4301         if (strcmp(value, "deterministic") == 0)
4302             mdata->deterministic_noncetype = 1;
4303         return 1;
4304     }
4305     return 0;
4306 }
4307 
check_deterministic_noncetype(EVP_TEST * t,DIGESTSIGN_DATA * mdata)4308 static int check_deterministic_noncetype(EVP_TEST *t,
4309                                          DIGESTSIGN_DATA *mdata)
4310 {
4311     if (mdata->deterministic_noncetype == 1) {
4312         OSSL_PARAM params[2];
4313         unsigned int nonce_type = 1;
4314 
4315         params[0] =
4316             OSSL_PARAM_construct_uint(OSSL_SIGNATURE_PARAM_NONCE_TYPE,
4317                                       &nonce_type);
4318         params[1] = OSSL_PARAM_construct_end();
4319         if (!EVP_PKEY_CTX_set_params(mdata->pctx, params))
4320             t->err = "EVP_PKEY_CTX_set_params_ERROR";
4321         else if (!EVP_PKEY_CTX_get_params(mdata->pctx, params))
4322             t->err = "EVP_PKEY_CTX_get_params_ERROR";
4323         else if (!OSSL_PARAM_modified(&params[0]))
4324             t->err = "nonce_type_not_modified_ERROR";
4325         else if (nonce_type != 1)
4326             t->err = "nonce_type_value_ERROR";
4327     }
4328     return t->err == NULL;
4329 }
4330 
signverify_init(EVP_TEST * t,DIGESTSIGN_DATA * data)4331 static int signverify_init(EVP_TEST *t, DIGESTSIGN_DATA *data)
4332 {
4333     const char *name = data->md == NULL ? NULL : EVP_MD_get0_name(data->md);
4334     OSSL_PARAM params[5];
4335     OSSL_PARAM *p = NULL;
4336     int i, ret = 0;
4337     size_t params_n = 0, params_allocated_n = 0;
4338 
4339     if (sk_OPENSSL_STRING_num(data->init_controls) > 0) {
4340         if (!ctrl2params(t, data->init_controls,
4341                          NULL,
4342                          params, OSSL_NELEM(params), &params_n))
4343             goto err;
4344         p = params;
4345     }
4346 
4347     if (data->is_verify) {
4348         if (!EVP_DigestVerifyInit_ex(data->ctx, &data->pctx, name, libctx,
4349                                      NULL, data->key, p)) {
4350             t->err = "DIGESTVERIFYINIT_ERROR";
4351             goto err;
4352         }
4353     } else {
4354         if (!EVP_DigestSignInit_ex(data->ctx, &data->pctx, name, libctx, NULL,
4355                                    data->key, p)) {
4356             t->err = "DIGESTSIGNINIT_ERROR";
4357             goto err;
4358         }
4359     }
4360 
4361     for (i = 0; i < sk_OPENSSL_STRING_num(data->controls); i++) {
4362         char *value = sk_OPENSSL_STRING_value(data->controls, i);
4363 
4364         if (!pkey_test_ctrl(t, data->pctx, value) || t->err != NULL)
4365             goto err;
4366     }
4367     ret = 1;
4368 err:
4369     ctrl2params_free(params, params_n, params_allocated_n);
4370     return ret;
4371 }
4372 
digestsign_update_fn(void * ctx,const unsigned char * buf,size_t buflen)4373 static int digestsign_update_fn(void *ctx, const unsigned char *buf,
4374                                 size_t buflen)
4375 {
4376     return EVP_DigestSignUpdate(ctx, buf, buflen);
4377 }
4378 
digestsign_test_run(EVP_TEST * t)4379 static int digestsign_test_run(EVP_TEST *t)
4380 {
4381     int i;
4382     DIGESTSIGN_DATA *expected = t->data;
4383     unsigned char *got = NULL;
4384     size_t got_len;
4385 
4386     if (!signverify_init(t, expected))
4387         goto err;
4388     if (!check_deterministic_noncetype(t, expected))
4389         goto err;
4390 
4391     for (i = 0; i < sk_OPENSSL_STRING_num(expected->controls); i++) {
4392         char *value = sk_OPENSSL_STRING_value(expected->controls, i);
4393         if (!pkey_test_ctrl(t, expected->pctx, value) || t->err != NULL)
4394             return 0;
4395     }
4396 
4397     if (!evp_test_buffer_do(expected->input, digestsign_update_fn,
4398                             expected->ctx)) {
4399         t->err = "DIGESTUPDATE_ERROR";
4400         goto err;
4401     }
4402 
4403     if (!EVP_DigestSignFinal(expected->ctx, NULL, &got_len)) {
4404         t->err = "DIGESTSIGNFINAL_LENGTH_ERROR";
4405         goto err;
4406     }
4407     if (!TEST_ptr(got = OPENSSL_malloc(got_len))) {
4408         t->err = "MALLOC_FAILURE";
4409         goto err;
4410     }
4411     got_len *= 2;
4412     if (!EVP_DigestSignFinal(expected->ctx, got, &got_len)) {
4413         t->err = "DIGESTSIGNFINAL_ERROR";
4414         goto err;
4415     }
4416     if (!memory_err_compare(t, "SIGNATURE_MISMATCH",
4417                             expected->output, expected->output_len,
4418                             got, got_len))
4419         goto err;
4420 
4421     t->err = NULL;
4422  err:
4423     OPENSSL_free(got);
4424     return 1;
4425 }
4426 
4427 static const EVP_TEST_METHOD digestsign_test_method = {
4428     "DigestSign",
4429     digestsign_test_init,
4430     digestsigver_test_cleanup,
4431     digestsigver_test_parse,
4432     digestsign_test_run
4433 };
4434 
digestverify_test_init(EVP_TEST * t,const char * alg)4435 static int digestverify_test_init(EVP_TEST *t, const char *alg)
4436 {
4437     return digestsigver_test_init(t, alg, 1, 0);
4438 }
4439 
digestverify_update_fn(void * ctx,const unsigned char * buf,size_t buflen)4440 static int digestverify_update_fn(void *ctx, const unsigned char *buf,
4441                                   size_t buflen)
4442 {
4443     return EVP_DigestVerifyUpdate(ctx, buf, buflen);
4444 }
4445 
digestverify_test_run(EVP_TEST * t)4446 static int digestverify_test_run(EVP_TEST *t)
4447 {
4448     DIGESTSIGN_DATA *mdata = t->data;
4449 
4450     if (!signverify_init(t, mdata))
4451         return 1;
4452 
4453     if (!evp_test_buffer_do(mdata->input, digestverify_update_fn, mdata->ctx)) {
4454         t->err = "DIGESTUPDATE_ERROR";
4455         return 1;
4456     }
4457 
4458     if (EVP_DigestVerifyFinal(mdata->ctx, mdata->output,
4459                               mdata->output_len) <= 0)
4460         t->err = "VERIFY_ERROR";
4461     return 1;
4462 }
4463 
4464 static const EVP_TEST_METHOD digestverify_test_method = {
4465     "DigestVerify",
4466     digestverify_test_init,
4467     digestsigver_test_cleanup,
4468     digestsigver_test_parse,
4469     digestverify_test_run
4470 };
4471 
oneshot_digestsign_test_init(EVP_TEST * t,const char * alg)4472 static int oneshot_digestsign_test_init(EVP_TEST *t, const char *alg)
4473 {
4474     return digestsigver_test_init(t, alg, 0, 1);
4475 }
4476 
oneshot_digestsign_test_run(EVP_TEST * t)4477 static int oneshot_digestsign_test_run(EVP_TEST *t)
4478 {
4479     DIGESTSIGN_DATA *expected = t->data;
4480     unsigned char *got = NULL;
4481     size_t got_len;
4482 
4483     if (!signverify_init(t, expected))
4484         goto err;
4485 
4486     if (!EVP_DigestSign(expected->ctx, NULL, &got_len,
4487                         expected->osin, expected->osin_len)) {
4488         t->err = "DIGESTSIGN_LENGTH_ERROR";
4489         goto err;
4490     }
4491     if (!TEST_ptr(got = OPENSSL_malloc(got_len))) {
4492         t->err = "MALLOC_FAILURE";
4493         goto err;
4494     }
4495     got_len *= 2;
4496     if (!EVP_DigestSign(expected->ctx, got, &got_len,
4497                         expected->osin, expected->osin_len)) {
4498         t->err = "DIGESTSIGN_ERROR";
4499         goto err;
4500     }
4501     if (!memory_err_compare(t, "SIGNATURE_MISMATCH",
4502                             expected->output, expected->output_len,
4503                             got, got_len))
4504         goto err;
4505 
4506     t->err = NULL;
4507  err:
4508     OPENSSL_free(got);
4509     return 1;
4510 }
4511 
4512 static const EVP_TEST_METHOD oneshot_digestsign_test_method = {
4513     "OneShotDigestSign",
4514     oneshot_digestsign_test_init,
4515     digestsigver_test_cleanup,
4516     digestsigver_test_parse,
4517     oneshot_digestsign_test_run
4518 };
4519 
oneshot_digestverify_test_init(EVP_TEST * t,const char * alg)4520 static int oneshot_digestverify_test_init(EVP_TEST *t, const char *alg)
4521 {
4522     return digestsigver_test_init(t, alg, 1, 1);
4523 }
4524 
oneshot_digestverify_test_run(EVP_TEST * t)4525 static int oneshot_digestverify_test_run(EVP_TEST *t)
4526 {
4527     DIGESTSIGN_DATA *mdata = t->data;
4528 
4529     if (!signverify_init(t, mdata))
4530         return 1;
4531 
4532     if (EVP_DigestVerify(mdata->ctx, mdata->output, mdata->output_len,
4533                          mdata->osin, mdata->osin_len) <= 0)
4534         t->err = "VERIFY_ERROR";
4535     return 1;
4536 }
4537 
4538 static const EVP_TEST_METHOD oneshot_digestverify_test_method = {
4539     "OneShotDigestVerify",
4540     oneshot_digestverify_test_init,
4541     digestsigver_test_cleanup,
4542     digestsigver_test_parse,
4543     oneshot_digestverify_test_run
4544 };
4545 
4546 
4547 /**
4548  **  PARSING AND DISPATCH
4549  **/
4550 
4551 static const EVP_TEST_METHOD *evp_test_list[] = {
4552     &rand_test_method,
4553     &cipher_test_method,
4554     &digest_test_method,
4555     &digestsign_test_method,
4556     &digestverify_test_method,
4557     &encode_test_method,
4558     &kdf_test_method,
4559     &pkey_kdf_test_method,
4560     &keypair_test_method,
4561     &keygen_test_method,
4562     &mac_test_method,
4563     &oneshot_digestsign_test_method,
4564     &oneshot_digestverify_test_method,
4565     &pbe_test_method,
4566     &pdecrypt_test_method,
4567     &pderive_test_method,
4568     &psign_test_method,
4569     &psign_message_test_method,
4570     &pverify_recover_test_method,
4571     &pverify_test_method,
4572     &pverify_message_test_method,
4573     &pkey_kem_test_method,
4574     NULL
4575 };
4576 
find_test(const char * name)4577 static const EVP_TEST_METHOD *find_test(const char *name)
4578 {
4579     const EVP_TEST_METHOD **tt;
4580 
4581     for (tt = evp_test_list; *tt; tt++) {
4582         if (strcmp(name, (*tt)->name) == 0)
4583             return *tt;
4584     }
4585     return NULL;
4586 }
4587 
clear_test(EVP_TEST * t)4588 static void clear_test(EVP_TEST *t)
4589 {
4590     test_clearstanza(&t->s);
4591     ERR_clear_error();
4592     if (t->data != NULL) {
4593         if (t->meth != NULL)
4594             t->meth->cleanup(t);
4595         OPENSSL_free(t->data);
4596         t->data = NULL;
4597     }
4598     OPENSSL_free(t->expected_err);
4599     t->expected_err = NULL;
4600     OPENSSL_free(t->reason);
4601     t->reason = NULL;
4602 
4603     /* Text literal. */
4604     t->err = NULL;
4605     t->skip = 0;
4606     t->meth = NULL;
4607     t->expect_unapproved = 0;
4608 
4609 #if !defined(OPENSSL_NO_DEFAULT_THREAD_POOL)
4610     OSSL_set_max_threads(libctx, 0);
4611 #endif
4612 }
4613 
4614 /* Check for errors in the test structure; return 1 if okay, else 0. */
check_test_error(EVP_TEST * t)4615 static int check_test_error(EVP_TEST *t)
4616 {
4617     unsigned long err;
4618     const char *reason;
4619 
4620     if (t->err == NULL && t->expected_err == NULL)
4621         return 1;
4622     if (t->err != NULL && t->expected_err == NULL) {
4623         if (t->aux_err != NULL) {
4624             TEST_info("%s:%d: Source of above error (%s); unexpected error %s",
4625                       t->s.test_file, t->s.start, t->aux_err, t->err);
4626         } else {
4627             TEST_info("%s:%d: Source of above error; unexpected error %s",
4628                       t->s.test_file, t->s.start, t->err);
4629         }
4630         return 0;
4631     }
4632     if (t->err == NULL && t->expected_err != NULL) {
4633         TEST_info("%s:%d: Succeeded but was expecting %s",
4634                   t->s.test_file, t->s.start, t->expected_err);
4635         return 0;
4636     }
4637 
4638     if (strcmp(t->err, t->expected_err) != 0) {
4639         TEST_info("%s:%d: Expected %s got %s",
4640                   t->s.test_file, t->s.start, t->expected_err, t->err);
4641         return 0;
4642     }
4643 
4644     if (t->reason == NULL)
4645         return 1;
4646 
4647     if (t->reason == NULL) {
4648         TEST_info("%s:%d: Test is missing function or reason code",
4649                   t->s.test_file, t->s.start);
4650         return 0;
4651     }
4652 
4653     err = ERR_peek_error();
4654     if (err == 0) {
4655         TEST_info("%s:%d: Expected error \"%s\" not set",
4656                   t->s.test_file, t->s.start, t->reason);
4657         return 0;
4658     }
4659 
4660     reason = ERR_reason_error_string(err);
4661     if (reason == NULL) {
4662         TEST_info("%s:%d: Expected error \"%s\", no strings available."
4663                   " Assuming ok.",
4664                   t->s.test_file, t->s.start, t->reason);
4665         return 1;
4666     }
4667 
4668     if (strcmp(reason, t->reason) == 0)
4669         return 1;
4670 
4671     TEST_info("%s:%d: Expected error \"%s\", got \"%s\"",
4672               t->s.test_file, t->s.start, t->reason, reason);
4673 
4674     return 0;
4675 }
4676 
4677 /* Run a parsed test. Log a message and return 0 on error. */
run_test(EVP_TEST * t)4678 static int run_test(EVP_TEST *t)
4679 {
4680     if (t->meth == NULL)
4681         return 1;
4682     t->s.numtests++;
4683     if (t->skip) {
4684         t->s.numskip++;
4685     } else {
4686         /* run the test */
4687         if (t->err == NULL && t->meth->run_test(t) != 1) {
4688             TEST_info("%s:%d %s error",
4689                       t->s.test_file, t->s.start, t->meth->name);
4690             return 0;
4691         }
4692         if (!check_test_error(t)) {
4693             TEST_openssl_errors();
4694             t->s.errors++;
4695         }
4696     }
4697 
4698     /* clean it up */
4699     return 1;
4700 }
4701 
find_key(EVP_PKEY ** ppk,const char * name,KEY_LIST * lst)4702 static int find_key(EVP_PKEY **ppk, const char *name, KEY_LIST *lst)
4703 {
4704     for (; lst != NULL; lst = lst->next) {
4705         if (strcmp(lst->name, name) == 0) {
4706             if (ppk != NULL)
4707                 *ppk = lst->key;
4708             return 1;
4709         }
4710     }
4711     return 0;
4712 }
4713 
free_key_list(KEY_LIST * lst)4714 static void free_key_list(KEY_LIST *lst)
4715 {
4716     while (lst != NULL) {
4717         KEY_LIST *next = lst->next;
4718 
4719         EVP_PKEY_free(lst->key);
4720         OPENSSL_free(lst->name);
4721         OPENSSL_free(lst);
4722         lst = next;
4723     }
4724 }
4725 
4726 /*
4727  * Is the key type an unsupported algorithm?
4728  */
key_unsupported(void)4729 static int key_unsupported(void)
4730 {
4731     long err = ERR_peek_last_error();
4732     int lib = ERR_GET_LIB(err);
4733     long reason = ERR_GET_REASON(err);
4734 
4735     if ((lib == ERR_LIB_EVP && reason == EVP_R_UNSUPPORTED_ALGORITHM)
4736         || (lib == ERR_LIB_EVP && reason == EVP_R_DECODE_ERROR)
4737         || reason == ERR_R_UNSUPPORTED) {
4738         ERR_clear_error();
4739         return 1;
4740     }
4741 #ifndef OPENSSL_NO_EC
4742     /*
4743      * If EC support is enabled we should catch also EC_R_UNKNOWN_GROUP as an
4744      * hint to an unsupported algorithm/curve (e.g. if binary EC support is
4745      * disabled).
4746      */
4747     if (lib == ERR_LIB_EC
4748         && (reason == EC_R_UNKNOWN_GROUP
4749             || reason == EC_R_INVALID_CURVE)) {
4750         ERR_clear_error();
4751         return 1;
4752     }
4753 #endif /* OPENSSL_NO_EC */
4754     return 0;
4755 }
4756 
4757 /* NULL out the value from |pp| but return it.  This "steals" a pointer. */
take_value(PAIR * pp)4758 static char *take_value(PAIR *pp)
4759 {
4760     char *p = pp->value;
4761 
4762     pp->value = NULL;
4763     return p;
4764 }
4765 
4766 #if !defined(OPENSSL_NO_FIPS_SECURITYCHECKS)
securitycheck_enabled(void)4767 static int securitycheck_enabled(void)
4768 {
4769     static int enabled = -1;
4770 
4771     if (enabled == -1) {
4772         if (OSSL_PROVIDER_available(libctx, "fips")) {
4773             OSSL_PARAM params[2];
4774             OSSL_PROVIDER *prov = NULL;
4775             int check = 1;
4776 
4777             prov = OSSL_PROVIDER_load(libctx, "fips");
4778             if (prov != NULL) {
4779                 params[0] =
4780                     OSSL_PARAM_construct_int(OSSL_PROV_PARAM_SECURITY_CHECKS,
4781                                              &check);
4782                 params[1] = OSSL_PARAM_construct_end();
4783                 OSSL_PROVIDER_get_params(prov, params);
4784                 OSSL_PROVIDER_unload(prov);
4785             }
4786             enabled = check;
4787             return enabled;
4788         }
4789         enabled = 0;
4790     }
4791     return enabled;
4792 }
4793 #endif
4794 
4795 /*
4796  * Return 1 if one of the providers named in the string is available.
4797  * The provider names are separated with whitespace.
4798  * NOTE: destructive function, it inserts '\0' after each provider name.
4799  */
prov_available(char * providers)4800 static int prov_available(char *providers)
4801 {
4802     char *p;
4803     int more = 1;
4804 
4805     while (more) {
4806         for (; isspace((unsigned char)(*providers)); providers++)
4807             continue;
4808         if (*providers == '\0')
4809             break;               /* End of the road */
4810         for (p = providers; *p != '\0' && !isspace((unsigned char)(*p)); p++)
4811             continue;
4812         if (*p == '\0')
4813             more = 0;
4814         else
4815             *p = '\0';
4816         if (OSSL_PROVIDER_available(libctx, providers))
4817             return 1;            /* Found one */
4818     }
4819     return 0;
4820 }
4821 
4822 /* Read and parse one test.  Return 0 if failure, 1 if okay. */
parse(EVP_TEST * t)4823 static int parse(EVP_TEST *t)
4824 {
4825     KEY_LIST *key, **klist;
4826     EVP_PKEY *pkey;
4827     PAIR *pp;
4828     int i, j, skipped = 0;
4829 
4830     fips_indicator_callback_unapproved_count = 0;
4831 top:
4832     do {
4833         if (BIO_eof(t->s.fp))
4834             return EOF;
4835         clear_test(t);
4836         if (!test_readstanza(&t->s))
4837             return 0;
4838     } while (t->s.numpairs == 0);
4839     pp = &t->s.pairs[0];
4840 
4841     /* Are we adding a key? */
4842     klist = NULL;
4843     pkey = NULL;
4844 start:
4845     if (strcmp(pp->key, "PrivateKey") == 0) {
4846         pkey = PEM_read_bio_PrivateKey_ex(t->s.key, NULL, 0, NULL, libctx, NULL);
4847         if (pkey == NULL && !key_unsupported()) {
4848             EVP_PKEY_free(pkey);
4849             TEST_info("Can't read private key %s", pp->value);
4850             TEST_openssl_errors();
4851             return 0;
4852         }
4853         klist = &private_keys;
4854     } else if (strcmp(pp->key, "PublicKey") == 0) {
4855         pkey = PEM_read_bio_PUBKEY_ex(t->s.key, NULL, 0, NULL, libctx, NULL);
4856         if (pkey == NULL && !key_unsupported()) {
4857             EVP_PKEY_free(pkey);
4858             TEST_info("Can't read public key %s", pp->value);
4859             TEST_openssl_errors();
4860             return 0;
4861         }
4862         klist = &public_keys;
4863     } else if (strcmp(pp->key, "ParamKey") == 0) {
4864         pkey = PEM_read_bio_Parameters_ex(t->s.key, NULL, libctx, NULL);
4865         if (pkey == NULL && !key_unsupported()) {
4866             EVP_PKEY_free(pkey);
4867             TEST_info("Can't read params key %s", pp->value);
4868             TEST_openssl_errors();
4869             return 0;
4870         }
4871         klist = &public_keys;
4872     } else if (strcmp(pp->key, "PrivateKeyRaw") == 0
4873                || strcmp(pp->key, "PublicKeyRaw") == 0) {
4874         char *strnid = NULL, *keydata = NULL;
4875         unsigned char *keybin;
4876         size_t keylen;
4877         int nid;
4878 
4879         if (strcmp(pp->key, "PrivateKeyRaw") == 0)
4880             klist = &private_keys;
4881         else
4882             klist = &public_keys;
4883 
4884         strnid = strchr(pp->value, ':');
4885         if (strnid != NULL) {
4886             *strnid++ = '\0';
4887             keydata = strchr(strnid, ':');
4888             if (keydata != NULL)
4889                 *keydata++ = '\0';
4890         }
4891         if (keydata == NULL) {
4892             TEST_info("Failed to parse %s value", pp->key);
4893             return 0;
4894         }
4895 
4896         nid = OBJ_txt2nid(strnid);
4897         if (nid == NID_undef) {
4898             TEST_info("Unrecognised algorithm NID");
4899             return 0;
4900         }
4901         if (!parse_bin(keydata, &keybin, &keylen)) {
4902             TEST_info("Failed to create binary key");
4903             return 0;
4904         }
4905         if (klist == &private_keys)
4906             pkey = EVP_PKEY_new_raw_private_key_ex(libctx, strnid, NULL, keybin,
4907                                                    keylen);
4908         else
4909             pkey = EVP_PKEY_new_raw_public_key_ex(libctx, strnid, NULL, keybin,
4910                                                   keylen);
4911         if (pkey == NULL && !key_unsupported()) {
4912             TEST_info("Can't read %s data", pp->key);
4913             OPENSSL_free(keybin);
4914             TEST_openssl_errors();
4915             return 0;
4916         }
4917         OPENSSL_free(keybin);
4918     } else if (strcmp(pp->key, "Availablein") == 0) {
4919         if (!prov_available(pp->value)) {
4920             TEST_info("skipping, '%s' provider not available: %s:%d",
4921                       pp->value, t->s.test_file, t->s.start);
4922                 t->skip = 1;
4923                 return 0;
4924         }
4925         skipped++;
4926         pp++;
4927         goto start;
4928     } else if (strcmp(pp->key, "FIPSversion") == 0) {
4929         if (prov_available("fips")) {
4930             j = fips_provider_version_match(libctx, pp->value);
4931             if (j < 0) {
4932                 TEST_info("Line %d: error matching FIPS versions\n", t->s.curr);
4933                 return 0;
4934             } else if (j == 0) {
4935                 TEST_info("skipping, FIPS provider incompatible version: %s:%d",
4936                           t->s.test_file, t->s.start);
4937                     t->skip = 1;
4938                     return 0;
4939             }
4940         }
4941         skipped++;
4942         pp++;
4943         goto start;
4944     }
4945 
4946     /* If we have a key add to list */
4947     if (klist != NULL) {
4948         if (find_key(NULL, pp->value, *klist)) {
4949             TEST_info("Duplicate key %s", pp->value);
4950             return 0;
4951         }
4952         if (!TEST_ptr(key = OPENSSL_malloc(sizeof(*key))))
4953             return 0;
4954         key->name = take_value(pp);
4955         key->key = pkey;
4956         key->next = *klist;
4957         *klist = key;
4958 
4959         /* Go back and start a new stanza. */
4960         if ((t->s.numpairs - skipped) != 1)
4961             TEST_info("Line %d: missing blank line\n", t->s.curr);
4962         goto top;
4963     }
4964 
4965     /* Find the test, based on first keyword. */
4966     if (!TEST_ptr(t->meth = find_test(pp->key)))
4967         return 0;
4968     if (!t->meth->init(t, pp->value)) {
4969         TEST_error("unknown %s: %s\n", pp->key, pp->value);
4970         return 0;
4971     }
4972     if (t->skip == 1) {
4973         /* TEST_info("skipping %s %s", pp->key, pp->value); */
4974         return 0;
4975     }
4976 
4977     for (pp++, i = 1; i < (t->s.numpairs - skipped); pp++, i++) {
4978         if (strcmp(pp->key, "Securitycheck") == 0) {
4979 #if defined(OPENSSL_NO_FIPS_SECURITYCHECKS)
4980 #else
4981             if (!securitycheck_enabled())
4982 #endif
4983             {
4984                 TEST_info("skipping, Securitycheck is disabled: %s:%d",
4985                           t->s.test_file, t->s.start);
4986                 t->skip = 1;
4987                 return 0;
4988             }
4989         } else if (strcmp(pp->key, "Availablein") == 0) {
4990             TEST_info("Line %d: 'Availablein' should be the first option",
4991                       t->s.curr);
4992             return 0;
4993         } else if (strcmp(pp->key, "Result") == 0) {
4994             if (t->expected_err != NULL) {
4995                 TEST_info("Line %d: multiple result lines", t->s.curr);
4996                 return 0;
4997             }
4998             t->expected_err = take_value(pp);
4999         } else if (strcmp(pp->key, "Function") == 0) {
5000             /* Ignore old line. */
5001         } else if (strcmp(pp->key, "Reason") == 0) {
5002             if (t->reason != NULL) {
5003                 TEST_info("Line %d: multiple reason lines", t->s.curr);
5004                 return 0;
5005             }
5006             t->reason = take_value(pp);
5007         } else if (strcmp(pp->key, "Threads") == 0) {
5008             if (OSSL_set_max_threads(libctx, atoi(pp->value)) == 0) {
5009                 TEST_info("skipping, '%s' threads not available: %s:%d",
5010                           pp->value, t->s.test_file, t->s.start);
5011                 t->skip = 1;
5012             }
5013         } else if (strcmp(pp->key, "Unapproved") == 0) {
5014             t->expect_unapproved = 1;
5015         } else {
5016             /* Must be test specific line: try to parse it */
5017             int rv = t->meth->parse(t, pp->key, pp->value);
5018 
5019             if (rv == 0) {
5020                 TEST_info("Line %d: unknown keyword %s", t->s.curr, pp->key);
5021                 return 0;
5022             }
5023             if (rv < 0) {
5024                 TEST_info("Line %d: error processing keyword %s = %s\n",
5025                           t->s.curr, pp->key, pp->value);
5026                 return 0;
5027             }
5028             if (t->skip)
5029                 return 0;
5030         }
5031     }
5032 
5033     return 1;
5034 }
5035 
run_file_tests(int i)5036 static int run_file_tests(int i)
5037 {
5038     EVP_TEST *t;
5039     const char *testfile = test_get_argument(i);
5040     int c;
5041 
5042     if (!TEST_ptr(t = OPENSSL_zalloc(sizeof(*t))))
5043         return 0;
5044     if (!test_start_file(&t->s, testfile)) {
5045         OPENSSL_free(t);
5046         return 0;
5047     }
5048 
5049     OSSL_INDICATOR_set_callback(libctx, fips_indicator_cb);
5050     while (!BIO_eof(t->s.fp)) {
5051         c = parse(t);
5052         if (t->skip) {
5053             t->s.numskip++;
5054             continue;
5055         }
5056         if (c == 0 || !run_test(t)) {
5057             t->s.errors++;
5058             break;
5059         }
5060     }
5061     test_end_file(&t->s);
5062     clear_test(t);
5063 
5064     free_key_list(public_keys);
5065     free_key_list(private_keys);
5066     BIO_free(t->s.key);
5067     c = t->s.errors;
5068     OPENSSL_free(t);
5069     return c == 0;
5070 }
5071 
test_get_options(void)5072 const OPTIONS *test_get_options(void)
5073 {
5074     static const OPTIONS test_options[] = {
5075         OPT_TEST_OPTIONS_WITH_EXTRA_USAGE("[file...]\n"),
5076         { "config", OPT_CONFIG_FILE, '<',
5077           "The configuration file to use for the libctx" },
5078         { "process", OPT_IN_PLACE, 's',
5079           "Mode for data processing by cipher tests [in_place/both], both by default"},
5080         { "provider", OPT_PROVIDER_NAME, 's',
5081           "The provider to load (when no configuration file, the default value is 'default')" },
5082         { "propquery", OPT_PROV_PROPQUERY, 's',
5083           "Property query used when fetching algorithms" },
5084         { "chunk", OPT_DATA_CHUNK, 'N', "Size of data chunks to be processed, 0 for default size"},
5085         { OPT_HELP_STR, 1, '-', "file\tFile to run tests on.\n" },
5086         { NULL }
5087     };
5088     return test_options;
5089 }
5090 
setup_tests(void)5091 int setup_tests(void)
5092 {
5093     size_t n;
5094     char *config_file = NULL;
5095     char *provider_name = NULL;
5096 
5097     OPTION_CHOICE o;
5098 
5099     while ((o = opt_next()) != OPT_EOF) {
5100         switch (o) {
5101         case OPT_CONFIG_FILE:
5102             config_file = opt_arg();
5103             break;
5104         case OPT_IN_PLACE:
5105             if ((process_mode_in_place = evp_test_process_mode(opt_arg())) == -1)
5106         case OPT_DATA_CHUNK:
5107             if (!opt_int(opt_arg(), &data_chunk_size))
5108                 return 0;
5109             break;
5110         case OPT_PROVIDER_NAME:
5111             provider_name = opt_arg();
5112             break;
5113         case OPT_PROV_PROPQUERY:
5114             propquery = opt_arg();
5115             break;
5116         case OPT_TEST_CASES:
5117             break;
5118         default:
5119         case OPT_ERR:
5120             return 0;
5121         }
5122     }
5123 
5124     /*
5125      * Load the provider via configuration into the created library context.
5126      * Load the 'null' provider into the default library context to ensure that
5127      * the tests do not fallback to using the default provider.
5128      */
5129     if (config_file == NULL && provider_name == NULL)
5130         provider_name = "default";
5131     if (!test_get_libctx(&libctx, &prov_null, config_file, &libprov, provider_name))
5132         return 0;
5133 
5134     n = test_get_argument_count();
5135     if (n == 0)
5136         return 0;
5137 
5138     ADD_ALL_TESTS(run_file_tests, n);
5139     return 1;
5140 }
5141 
cleanup_tests(void)5142 void cleanup_tests(void)
5143 {
5144     OSSL_PROVIDER_unload(libprov);
5145     OSSL_PROVIDER_unload(prov_null);
5146     OSSL_LIB_CTX_free(libctx);
5147 }
5148 
is_digest_disabled(const char * name)5149 static int is_digest_disabled(const char *name)
5150 {
5151 #ifdef OPENSSL_NO_BLAKE2
5152     if (HAS_CASE_PREFIX(name, "BLAKE"))
5153         return 1;
5154 #endif
5155 #ifdef OPENSSL_NO_MD2
5156     if (OPENSSL_strcasecmp(name, "MD2") == 0)
5157         return 1;
5158 #endif
5159 #ifdef OPENSSL_NO_MDC2
5160     if (OPENSSL_strcasecmp(name, "MDC2") == 0)
5161         return 1;
5162 #endif
5163 #ifdef OPENSSL_NO_MD4
5164     if (OPENSSL_strcasecmp(name, "MD4") == 0)
5165         return 1;
5166 #endif
5167 #ifdef OPENSSL_NO_MD5
5168     if (OPENSSL_strcasecmp(name, "MD5") == 0)
5169         return 1;
5170 #endif
5171 #ifdef OPENSSL_NO_RMD160
5172     if (OPENSSL_strcasecmp(name, "RIPEMD160") == 0)
5173         return 1;
5174 #endif
5175 #ifdef OPENSSL_NO_SM3
5176     if (OPENSSL_strcasecmp(name, "SM3") == 0)
5177         return 1;
5178 #endif
5179 #ifdef OPENSSL_NO_WHIRLPOOL
5180     if (OPENSSL_strcasecmp(name, "WHIRLPOOL") == 0)
5181         return 1;
5182 #endif
5183     return 0;
5184 }
5185 
is_pkey_disabled(const char * name)5186 static int is_pkey_disabled(const char *name)
5187 {
5188 #ifdef OPENSSL_NO_EC
5189     if (HAS_CASE_PREFIX(name, "EC"))
5190         return 1;
5191 #endif
5192 #ifdef OPENSSL_NO_DH
5193     if (HAS_CASE_PREFIX(name, "DH"))
5194         return 1;
5195 #endif
5196 #ifdef OPENSSL_NO_DSA
5197     if (HAS_CASE_PREFIX(name, "DSA"))
5198         return 1;
5199 #endif
5200 #ifdef OPENSSL_NO_SM2
5201     if (HAS_CASE_PREFIX(name, "SM2"))
5202         return 1;
5203 #endif
5204 
5205     /* For sigalgs we use, we also check for digest suffixes */
5206 #ifdef OPENSSL_NO_RMD160
5207     if (HAS_CASE_SUFFIX(name, "-RIPEMD160"))
5208         return 1;
5209 #endif
5210 #ifdef OPENSSL_NO_SM3
5211     if (HAS_CASE_SUFFIX(name, "-SM3"))
5212         return 1;
5213 #endif
5214     return 0;
5215 }
5216 
is_mac_disabled(const char * name)5217 static int is_mac_disabled(const char *name)
5218 {
5219 #ifdef OPENSSL_NO_BLAKE2
5220     if (HAS_CASE_PREFIX(name, "BLAKE2BMAC")
5221         || HAS_CASE_PREFIX(name, "BLAKE2SMAC"))
5222         return 1;
5223 #endif
5224 #ifdef OPENSSL_NO_CMAC
5225     if (HAS_CASE_PREFIX(name, "CMAC"))
5226         return 1;
5227 #endif
5228 #ifdef OPENSSL_NO_POLY1305
5229     if (HAS_CASE_PREFIX(name, "Poly1305"))
5230         return 1;
5231 #endif
5232 #ifdef OPENSSL_NO_SIPHASH
5233     if (HAS_CASE_PREFIX(name, "SipHash"))
5234         return 1;
5235 #endif
5236     return 0;
5237 }
is_kdf_disabled(const char * name)5238 static int is_kdf_disabled(const char *name)
5239 {
5240 #ifdef OPENSSL_NO_SCRYPT
5241     if (HAS_CASE_SUFFIX(name, "SCRYPT"))
5242         return 1;
5243 #endif
5244 #ifdef OPENSSL_NO_ARGON2
5245     if (HAS_CASE_SUFFIX(name, "ARGON2"))
5246         return 1;
5247 #endif
5248     return 0;
5249 }
5250 
is_cipher_disabled(const char * name)5251 static int is_cipher_disabled(const char *name)
5252 {
5253 #ifdef OPENSSL_NO_ARIA
5254     if (HAS_CASE_PREFIX(name, "ARIA"))
5255         return 1;
5256 #endif
5257 #ifdef OPENSSL_NO_BF
5258     if (HAS_CASE_PREFIX(name, "BF"))
5259         return 1;
5260 #endif
5261 #ifdef OPENSSL_NO_CAMELLIA
5262     if (HAS_CASE_PREFIX(name, "CAMELLIA"))
5263         return 1;
5264 #endif
5265 #ifdef OPENSSL_NO_CAST
5266     if (HAS_CASE_PREFIX(name, "CAST"))
5267         return 1;
5268 #endif
5269 #ifdef OPENSSL_NO_CHACHA
5270     if (HAS_CASE_PREFIX(name, "CHACHA"))
5271         return 1;
5272 #endif
5273 #ifdef OPENSSL_NO_POLY1305
5274     if (HAS_CASE_SUFFIX(name, "Poly1305"))
5275         return 1;
5276 #endif
5277 #ifdef OPENSSL_NO_DES
5278     if (HAS_CASE_PREFIX(name, "DES"))
5279         return 1;
5280     if (HAS_CASE_SUFFIX(name, "3DESwrap"))
5281         return 1;
5282 #endif
5283 #ifdef OPENSSL_NO_OCB
5284     if (HAS_CASE_SUFFIX(name, "OCB"))
5285         return 1;
5286 #endif
5287 #ifdef OPENSSL_NO_IDEA
5288     if (HAS_CASE_PREFIX(name, "IDEA"))
5289         return 1;
5290 #endif
5291 #ifdef OPENSSL_NO_RC2
5292     if (HAS_CASE_PREFIX(name, "RC2"))
5293         return 1;
5294 #endif
5295 #ifdef OPENSSL_NO_RC4
5296     if (HAS_CASE_PREFIX(name, "RC4"))
5297         return 1;
5298 #endif
5299 #ifdef OPENSSL_NO_RC5
5300     if (HAS_CASE_PREFIX(name, "RC5"))
5301         return 1;
5302 #endif
5303 #ifdef OPENSSL_NO_SEED
5304     if (HAS_CASE_PREFIX(name, "SEED"))
5305         return 1;
5306 #endif
5307 #ifdef OPENSSL_NO_SIV
5308     if (HAS_CASE_SUFFIX(name, "SIV"))
5309         return 1;
5310 #endif
5311 #ifdef OPENSSL_NO_SM4
5312     if (HAS_CASE_PREFIX(name, "SM4"))
5313         return 1;
5314 #endif
5315     return 0;
5316 }
5317