EVP_Digest*: enable SHA3 pre-hashing for DSA
[openssl.git] / test / evp_test.c
1 /*
2  * Copyright 2015-2019 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the Apache License 2.0 (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9
10 #include <stdio.h>
11 #include <string.h>
12 #include <stdlib.h>
13 #include <ctype.h>
14 #include <openssl/evp.h>
15 #include <openssl/pem.h>
16 #include <openssl/err.h>
17 #include <openssl/x509v3.h>
18 #include <openssl/pkcs12.h>
19 #include <openssl/kdf.h>
20 #include "internal/numbers.h"
21 #include "testutil.h"
22 #include "evp_test.h"
23
24 #define AAD_NUM 4
25
26 typedef struct evp_test_method_st EVP_TEST_METHOD;
27
28 /*
29  * Structure holding test information
30  */
31 typedef struct evp_test_st {
32     STANZA s;                     /* Common test stanza */
33     char *name;
34     int skip;                     /* Current test should be skipped */
35     const EVP_TEST_METHOD *meth;  /* method for this test */
36     const char *err, *aux_err;    /* Error string for test */
37     char *expected_err;           /* Expected error value of test */
38     char *func;                   /* Expected error function string */
39     char *reason;                 /* Expected error reason string */
40     void *data;                   /* test specific data */
41 } EVP_TEST;
42
43 /*
44  * Test method structure
45  */
46 struct evp_test_method_st {
47     /* Name of test as it appears in file */
48     const char *name;
49     /* Initialise test for "alg" */
50     int (*init) (EVP_TEST * t, const char *alg);
51     /* Clean up method */
52     void (*cleanup) (EVP_TEST * t);
53     /* Test specific name value pair processing */
54     int (*parse) (EVP_TEST * t, const char *name, const char *value);
55     /* Run the test itself */
56     int (*run_test) (EVP_TEST * t);
57 };
58
59
60 /*
61  * Linked list of named keys.
62  */
63 typedef struct key_list_st {
64     char *name;
65     EVP_PKEY *key;
66     struct key_list_st *next;
67 } KEY_LIST;
68
69 /*
70  * List of public and private keys
71  */
72 static KEY_LIST *private_keys;
73 static KEY_LIST *public_keys;
74 static int find_key(EVP_PKEY **ppk, const char *name, KEY_LIST *lst);
75
76 static int parse_bin(const char *value, unsigned char **buf, size_t *buflen);
77
78 /*
79  * Compare two memory regions for equality, returning zero if they differ.
80  * However, if there is expected to be an error and the actual error
81  * matches then the memory is expected to be different so handle this
82  * case without producing unnecessary test framework output.
83  */
84 static int memory_err_compare(EVP_TEST *t, const char *err,
85                               const void *expected, size_t expected_len,
86                               const void *got, size_t got_len)
87 {
88     int r;
89
90     if (t->expected_err != NULL && strcmp(t->expected_err, err) == 0)
91         r = !TEST_mem_ne(expected, expected_len, got, got_len);
92     else
93         r = TEST_mem_eq(expected, expected_len, got, got_len);
94     if (!r)
95         t->err = err;
96     return r;
97 }
98
99 /*
100  * Structure used to hold a list of blocks of memory to test
101  * calls to "update" like functions.
102  */
103 struct evp_test_buffer_st {
104     unsigned char *buf;
105     size_t buflen;
106     size_t count;
107     int count_set;
108 };
109
110 static void evp_test_buffer_free(EVP_TEST_BUFFER *db)
111 {
112     if (db != NULL) {
113         OPENSSL_free(db->buf);
114         OPENSSL_free(db);
115     }
116 }
117
118 /*
119  * append buffer to a list
120  */
121 static int evp_test_buffer_append(const char *value,
122                                   STACK_OF(EVP_TEST_BUFFER) **sk)
123 {
124     EVP_TEST_BUFFER *db = NULL;
125
126     if (!TEST_ptr(db = OPENSSL_malloc(sizeof(*db))))
127         goto err;
128
129     if (!parse_bin(value, &db->buf, &db->buflen))
130         goto err;
131     db->count = 1;
132     db->count_set = 0;
133
134     if (*sk == NULL && !TEST_ptr(*sk = sk_EVP_TEST_BUFFER_new_null()))
135         goto err;
136     if (!sk_EVP_TEST_BUFFER_push(*sk, db))
137         goto err;
138
139     return 1;
140
141 err:
142     evp_test_buffer_free(db);
143     return 0;
144 }
145
146 /*
147  * replace last buffer in list with copies of itself
148  */
149 static int evp_test_buffer_ncopy(const char *value,
150                                  STACK_OF(EVP_TEST_BUFFER) *sk)
151 {
152     EVP_TEST_BUFFER *db;
153     unsigned char *tbuf, *p;
154     size_t tbuflen;
155     int ncopy = atoi(value);
156     int i;
157
158     if (ncopy <= 0)
159         return 0;
160     if (sk == NULL || sk_EVP_TEST_BUFFER_num(sk) == 0)
161         return 0;
162     db = sk_EVP_TEST_BUFFER_value(sk, sk_EVP_TEST_BUFFER_num(sk) - 1);
163
164     tbuflen = db->buflen * ncopy;
165     if (!TEST_ptr(tbuf = OPENSSL_malloc(tbuflen)))
166         return 0;
167     for (i = 0, p = tbuf; i < ncopy; i++, p += db->buflen)
168         memcpy(p, db->buf, db->buflen);
169
170     OPENSSL_free(db->buf);
171     db->buf = tbuf;
172     db->buflen = tbuflen;
173     return 1;
174 }
175
176 /*
177  * set repeat count for last buffer in list
178  */
179 static int evp_test_buffer_set_count(const char *value,
180                                      STACK_OF(EVP_TEST_BUFFER) *sk)
181 {
182     EVP_TEST_BUFFER *db;
183     int count = atoi(value);
184
185     if (count <= 0)
186         return 0;
187
188     if (sk == NULL || sk_EVP_TEST_BUFFER_num(sk) == 0)
189         return 0;
190
191     db = sk_EVP_TEST_BUFFER_value(sk, sk_EVP_TEST_BUFFER_num(sk) - 1);
192     if (db->count_set != 0)
193         return 0;
194
195     db->count = (size_t)count;
196     db->count_set = 1;
197     return 1;
198 }
199
200 /*
201  * call "fn" with each element of the list in turn
202  */
203 static int evp_test_buffer_do(STACK_OF(EVP_TEST_BUFFER) *sk,
204                               int (*fn)(void *ctx,
205                                         const unsigned char *buf,
206                                         size_t buflen),
207                               void *ctx)
208 {
209     int i;
210
211     for (i = 0; i < sk_EVP_TEST_BUFFER_num(sk); i++) {
212         EVP_TEST_BUFFER *tb = sk_EVP_TEST_BUFFER_value(sk, i);
213         size_t j;
214
215         for (j = 0; j < tb->count; j++) {
216             if (fn(ctx, tb->buf, tb->buflen) <= 0)
217                 return 0;
218         }
219     }
220     return 1;
221 }
222
223 /*
224  * Unescape some sequences in string literals (only \n for now).
225  * Return an allocated buffer, set |out_len|.  If |input_len|
226  * is zero, get an empty buffer but set length to zero.
227  */
228 static unsigned char* unescape(const char *input, size_t input_len,
229                                size_t *out_len)
230 {
231     unsigned char *ret, *p;
232     size_t i;
233
234     if (input_len == 0) {
235         *out_len = 0;
236         return OPENSSL_zalloc(1);
237     }
238
239     /* Escaping is non-expanding; over-allocate original size for simplicity. */
240     if (!TEST_ptr(ret = p = OPENSSL_malloc(input_len)))
241         return NULL;
242
243     for (i = 0; i < input_len; i++) {
244         if (*input == '\\') {
245             if (i == input_len - 1 || *++input != 'n') {
246                 TEST_error("Bad escape sequence in file");
247                 goto err;
248             }
249             *p++ = '\n';
250             i++;
251             input++;
252         } else {
253             *p++ = *input++;
254         }
255     }
256
257     *out_len = p - ret;
258     return ret;
259
260  err:
261     OPENSSL_free(ret);
262     return NULL;
263 }
264
265 /*
266  * For a hex string "value" convert to a binary allocated buffer.
267  * Return 1 on success or 0 on failure.
268  */
269 static int parse_bin(const char *value, unsigned char **buf, size_t *buflen)
270 {
271     long len;
272
273     /* Check for NULL literal */
274     if (strcmp(value, "NULL") == 0) {
275         *buf = NULL;
276         *buflen = 0;
277         return 1;
278     }
279
280     /* Check for empty value */
281     if (*value == '\0') {
282         /*
283          * Don't return NULL for zero length buffer. This is needed for
284          * some tests with empty keys: HMAC_Init_ex() expects a non-NULL key
285          * buffer even if the key length is 0, in order to detect key reset.
286          */
287         *buf = OPENSSL_malloc(1);
288         if (*buf == NULL)
289             return 0;
290         **buf = 0;
291         *buflen = 0;
292         return 1;
293     }
294
295     /* Check for string literal */
296     if (value[0] == '"') {
297         size_t vlen = strlen(++value);
298
299         if (vlen == 0 || value[vlen - 1] != '"')
300             return 0;
301         vlen--;
302         *buf = unescape(value, vlen, buflen);
303         return *buf == NULL ? 0 : 1;
304     }
305
306     /* Otherwise assume as hex literal and convert it to binary buffer */
307     if (!TEST_ptr(*buf = OPENSSL_hexstr2buf(value, &len))) {
308         TEST_info("Can't convert %s", value);
309         TEST_openssl_errors();
310         return -1;
311     }
312     /* Size of input buffer means we'll never overflow */
313     *buflen = len;
314     return 1;
315 }
316
317
318 /**
319 ***  MESSAGE DIGEST TESTS
320 **/
321
322 typedef struct digest_data_st {
323     /* Digest this test is for */
324     const EVP_MD *digest;
325     /* Input to digest */
326     STACK_OF(EVP_TEST_BUFFER) *input;
327     /* Expected output */
328     unsigned char *output;
329     size_t output_len;
330 } DIGEST_DATA;
331
332 static int digest_test_init(EVP_TEST *t, const char *alg)
333 {
334     DIGEST_DATA *mdat;
335     const EVP_MD *digest;
336
337     if ((digest = EVP_get_digestbyname(alg)) == NULL) {
338         /* If alg has an OID assume disabled algorithm */
339         if (OBJ_sn2nid(alg) != NID_undef || OBJ_ln2nid(alg) != NID_undef) {
340             t->skip = 1;
341             return 1;
342         }
343         return 0;
344     }
345     if (!TEST_ptr(mdat = OPENSSL_zalloc(sizeof(*mdat))))
346         return 0;
347     t->data = mdat;
348     mdat->digest = digest;
349     return 1;
350 }
351
352 static void digest_test_cleanup(EVP_TEST *t)
353 {
354     DIGEST_DATA *mdat = t->data;
355
356     sk_EVP_TEST_BUFFER_pop_free(mdat->input, evp_test_buffer_free);
357     OPENSSL_free(mdat->output);
358 }
359
360 static int digest_test_parse(EVP_TEST *t,
361                              const char *keyword, const char *value)
362 {
363     DIGEST_DATA *mdata = t->data;
364
365     if (strcmp(keyword, "Input") == 0)
366         return evp_test_buffer_append(value, &mdata->input);
367     if (strcmp(keyword, "Output") == 0)
368         return parse_bin(value, &mdata->output, &mdata->output_len);
369     if (strcmp(keyword, "Count") == 0)
370         return evp_test_buffer_set_count(value, mdata->input);
371     if (strcmp(keyword, "Ncopy") == 0)
372         return evp_test_buffer_ncopy(value, mdata->input);
373     return 0;
374 }
375
376 static int digest_update_fn(void *ctx, const unsigned char *buf, size_t buflen)
377 {
378     return EVP_DigestUpdate(ctx, buf, buflen);
379 }
380
381 static int digest_test_run(EVP_TEST *t)
382 {
383     DIGEST_DATA *expected = t->data;
384     EVP_MD_CTX *mctx;
385     unsigned char *got = NULL;
386     unsigned int got_len;
387
388     t->err = "TEST_FAILURE";
389     if (!TEST_ptr(mctx = EVP_MD_CTX_new()))
390         goto err;
391
392     got = OPENSSL_malloc(expected->output_len > EVP_MAX_MD_SIZE ?
393                          expected->output_len : EVP_MAX_MD_SIZE);
394     if (!TEST_ptr(got))
395         goto err;
396
397     if (!EVP_DigestInit_ex(mctx, expected->digest, NULL)) {
398         t->err = "DIGESTINIT_ERROR";
399         goto err;
400     }
401     if (!evp_test_buffer_do(expected->input, digest_update_fn, mctx)) {
402         t->err = "DIGESTUPDATE_ERROR";
403         goto err;
404     }
405
406     if (EVP_MD_flags(expected->digest) & EVP_MD_FLAG_XOF) {
407         got_len = expected->output_len;
408         if (!EVP_DigestFinalXOF(mctx, got, got_len)) {
409             t->err = "DIGESTFINALXOF_ERROR";
410             goto err;
411         }
412     } else {
413         if (!EVP_DigestFinal(mctx, got, &got_len)) {
414             t->err = "DIGESTFINAL_ERROR";
415             goto err;
416         }
417     }
418     if (!TEST_int_eq(expected->output_len, got_len)) {
419         t->err = "DIGEST_LENGTH_MISMATCH";
420         goto err;
421     }
422     if (!memory_err_compare(t, "DIGEST_MISMATCH",
423                             expected->output, expected->output_len,
424                             got, got_len))
425         goto err;
426
427     t->err = NULL;
428
429  err:
430     OPENSSL_free(got);
431     EVP_MD_CTX_free(mctx);
432     return 1;
433 }
434
435 static const EVP_TEST_METHOD digest_test_method = {
436     "Digest",
437     digest_test_init,
438     digest_test_cleanup,
439     digest_test_parse,
440     digest_test_run
441 };
442
443
444 /**
445 ***  CIPHER TESTS
446 **/
447
448 typedef struct cipher_data_st {
449     const EVP_CIPHER *cipher;
450     int enc;
451     /* EVP_CIPH_GCM_MODE, EVP_CIPH_CCM_MODE or EVP_CIPH_OCB_MODE if AEAD */
452     int aead;
453     unsigned char *key;
454     size_t key_len;
455     unsigned char *iv;
456     size_t iv_len;
457     unsigned char *plaintext;
458     size_t plaintext_len;
459     unsigned char *ciphertext;
460     size_t ciphertext_len;
461     /* GCM, CCM, OCB and SIV only */
462     unsigned char *aad[AAD_NUM];
463     size_t aad_len[AAD_NUM];
464     unsigned char *tag;
465     size_t tag_len;
466     int tag_late;
467 } CIPHER_DATA;
468
469 static int cipher_test_init(EVP_TEST *t, const char *alg)
470 {
471     const EVP_CIPHER *cipher;
472     CIPHER_DATA *cdat;
473     int m;
474
475     if ((cipher = EVP_get_cipherbyname(alg)) == NULL) {
476         /* If alg has an OID assume disabled algorithm */
477         if (OBJ_sn2nid(alg) != NID_undef || OBJ_ln2nid(alg) != NID_undef) {
478             t->skip = 1;
479             return 1;
480         }
481         return 0;
482     }
483     cdat = OPENSSL_zalloc(sizeof(*cdat));
484     cdat->cipher = cipher;
485     cdat->enc = -1;
486     m = EVP_CIPHER_mode(cipher);
487     if (m == EVP_CIPH_GCM_MODE
488             || m == EVP_CIPH_OCB_MODE
489             || m == EVP_CIPH_SIV_MODE
490             || m == EVP_CIPH_CCM_MODE)
491         cdat->aead = m;
492     else if (EVP_CIPHER_flags(cipher) & EVP_CIPH_FLAG_AEAD_CIPHER)
493         cdat->aead = -1;
494     else
495         cdat->aead = 0;
496
497     t->data = cdat;
498     return 1;
499 }
500
501 static void cipher_test_cleanup(EVP_TEST *t)
502 {
503     int i;
504     CIPHER_DATA *cdat = t->data;
505
506     OPENSSL_free(cdat->key);
507     OPENSSL_free(cdat->iv);
508     OPENSSL_free(cdat->ciphertext);
509     OPENSSL_free(cdat->plaintext);
510     for (i = 0; i < AAD_NUM; i++)
511         OPENSSL_free(cdat->aad[i]);
512     OPENSSL_free(cdat->tag);
513 }
514
515 static int cipher_test_parse(EVP_TEST *t, const char *keyword,
516                              const char *value)
517 {
518     CIPHER_DATA *cdat = t->data;
519     int i;
520
521     if (strcmp(keyword, "Key") == 0)
522         return parse_bin(value, &cdat->key, &cdat->key_len);
523     if (strcmp(keyword, "IV") == 0)
524         return parse_bin(value, &cdat->iv, &cdat->iv_len);
525     if (strcmp(keyword, "Plaintext") == 0)
526         return parse_bin(value, &cdat->plaintext, &cdat->plaintext_len);
527     if (strcmp(keyword, "Ciphertext") == 0)
528         return parse_bin(value, &cdat->ciphertext, &cdat->ciphertext_len);
529     if (cdat->aead) {
530         if (strcmp(keyword, "AAD") == 0) {
531             for (i = 0; i < AAD_NUM; i++) {
532                 if (cdat->aad[i] == NULL)
533                     return parse_bin(value, &cdat->aad[i], &cdat->aad_len[i]);
534             }
535             return 0;
536         }
537         if (strcmp(keyword, "Tag") == 0)
538             return parse_bin(value, &cdat->tag, &cdat->tag_len);
539         if (strcmp(keyword, "SetTagLate") == 0) {
540             if (strcmp(value, "TRUE") == 0)
541                 cdat->tag_late = 1;
542             else if (strcmp(value, "FALSE") == 0)
543                 cdat->tag_late = 0;
544             else
545                 return 0;
546             return 1;
547         }
548     }
549
550     if (strcmp(keyword, "Operation") == 0) {
551         if (strcmp(value, "ENCRYPT") == 0)
552             cdat->enc = 1;
553         else if (strcmp(value, "DECRYPT") == 0)
554             cdat->enc = 0;
555         else
556             return 0;
557         return 1;
558     }
559     return 0;
560 }
561
562 static int cipher_test_enc(EVP_TEST *t, int enc,
563                            size_t out_misalign, size_t inp_misalign, int frag)
564 {
565     CIPHER_DATA *expected = t->data;
566     unsigned char *in, *expected_out, *tmp = NULL;
567     size_t in_len, out_len, donelen = 0;
568     int ok = 0, tmplen, chunklen, tmpflen, i;
569     EVP_CIPHER_CTX *ctx = NULL;
570
571     t->err = "TEST_FAILURE";
572     if (!TEST_ptr(ctx = EVP_CIPHER_CTX_new()))
573         goto err;
574     EVP_CIPHER_CTX_set_flags(ctx, EVP_CIPHER_CTX_FLAG_WRAP_ALLOW);
575     if (enc) {
576         in = expected->plaintext;
577         in_len = expected->plaintext_len;
578         expected_out = expected->ciphertext;
579         out_len = expected->ciphertext_len;
580     } else {
581         in = expected->ciphertext;
582         in_len = expected->ciphertext_len;
583         expected_out = expected->plaintext;
584         out_len = expected->plaintext_len;
585     }
586     if (inp_misalign == (size_t)-1) {
587         /*
588          * Exercise in-place encryption
589          */
590         tmp = OPENSSL_malloc(out_misalign + in_len + 2 * EVP_MAX_BLOCK_LENGTH);
591         if (!tmp)
592             goto err;
593         in = memcpy(tmp + out_misalign, in, in_len);
594     } else {
595         inp_misalign += 16 - ((out_misalign + in_len) & 15);
596         /*
597          * 'tmp' will store both output and copy of input. We make the copy
598          * of input to specifically aligned part of 'tmp'. So we just
599          * figured out how much padding would ensure the required alignment,
600          * now we allocate extended buffer and finally copy the input just
601          * past inp_misalign in expression below. Output will be written
602          * past out_misalign...
603          */
604         tmp = OPENSSL_malloc(out_misalign + in_len + 2 * EVP_MAX_BLOCK_LENGTH +
605                              inp_misalign + in_len);
606         if (!tmp)
607             goto err;
608         in = memcpy(tmp + out_misalign + in_len + 2 * EVP_MAX_BLOCK_LENGTH +
609                     inp_misalign, in, in_len);
610     }
611     if (!EVP_CipherInit_ex(ctx, expected->cipher, NULL, NULL, NULL, enc)) {
612         t->err = "CIPHERINIT_ERROR";
613         goto err;
614     }
615     if (expected->iv) {
616         if (expected->aead) {
617             if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_IVLEN,
618                                      expected->iv_len, 0)) {
619                 t->err = "INVALID_IV_LENGTH";
620                 goto err;
621             }
622         } else if (expected->iv_len != (size_t)EVP_CIPHER_CTX_iv_length(ctx)) {
623             t->err = "INVALID_IV_LENGTH";
624             goto err;
625         }
626     }
627     if (expected->aead) {
628         unsigned char *tag;
629         /*
630          * If encrypting or OCB just set tag length initially, otherwise
631          * set tag length and value.
632          */
633         if (enc || expected->aead == EVP_CIPH_OCB_MODE || expected->tag_late) {
634             t->err = "TAG_LENGTH_SET_ERROR";
635             tag = NULL;
636         } else {
637             t->err = "TAG_SET_ERROR";
638             tag = expected->tag;
639         }
640         if (tag || expected->aead != EVP_CIPH_GCM_MODE) {
641             if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_TAG,
642                                      expected->tag_len, tag))
643                 goto err;
644         }
645     }
646
647     if (!EVP_CIPHER_CTX_set_key_length(ctx, expected->key_len)) {
648         t->err = "INVALID_KEY_LENGTH";
649         goto err;
650     }
651     if (!EVP_CipherInit_ex(ctx, NULL, NULL, expected->key, expected->iv, -1)) {
652         t->err = "KEY_SET_ERROR";
653         goto err;
654     }
655
656     if (expected->aead == EVP_CIPH_CCM_MODE) {
657         if (!EVP_CipherUpdate(ctx, NULL, &tmplen, NULL, out_len)) {
658             t->err = "CCM_PLAINTEXT_LENGTH_SET_ERROR";
659             goto err;
660         }
661     }
662     if (expected->aad[0] != NULL) {
663         t->err = "AAD_SET_ERROR";
664         if (!frag) {
665             for (i = 0; expected->aad[i] != NULL; i++) {
666                 if (!EVP_CipherUpdate(ctx, NULL, &chunklen, expected->aad[i],
667                                       expected->aad_len[i]))
668                     goto err;
669             }
670         } else {
671             /*
672              * Supply the AAD in chunks less than the block size where possible
673              */
674             for (i = 0; expected->aad[i] != NULL; i++) {
675                 if (expected->aad_len[i] > 0) {
676                     if (!EVP_CipherUpdate(ctx, NULL, &chunklen, expected->aad[i], 1))
677                         goto err;
678                     donelen++;
679                 }
680                 if (expected->aad_len[i] > 2) {
681                     if (!EVP_CipherUpdate(ctx, NULL, &chunklen,
682                                           expected->aad[i] + donelen,
683                                           expected->aad_len[i] - 2))
684                         goto err;
685                     donelen += expected->aad_len[i] - 2;
686                 }
687                 if (expected->aad_len[i] > 1
688                     && !EVP_CipherUpdate(ctx, NULL, &chunklen,
689                                          expected->aad[i] + donelen, 1))
690                     goto err;
691             }
692         }
693     }
694
695     if (!enc && (expected->aead == EVP_CIPH_OCB_MODE || expected->tag_late)) {
696         if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_TAG,
697                                  expected->tag_len, expected->tag)) {
698             t->err = "TAG_SET_ERROR";
699             goto err;
700         }
701     }
702
703     EVP_CIPHER_CTX_set_padding(ctx, 0);
704     t->err = "CIPHERUPDATE_ERROR";
705     tmplen = 0;
706     if (!frag) {
707         /* We supply the data all in one go */
708         if (!EVP_CipherUpdate(ctx, tmp + out_misalign, &tmplen, in, in_len))
709             goto err;
710     } else {
711         /* Supply the data in chunks less than the block size where possible */
712         if (in_len > 0) {
713             if (!EVP_CipherUpdate(ctx, tmp + out_misalign, &chunklen, in, 1))
714                 goto err;
715             tmplen += chunklen;
716             in++;
717             in_len--;
718         }
719         if (in_len > 1) {
720             if (!EVP_CipherUpdate(ctx, tmp + out_misalign + tmplen, &chunklen,
721                                   in, in_len - 1))
722                 goto err;
723             tmplen += chunklen;
724             in += in_len - 1;
725             in_len = 1;
726         }
727         if (in_len > 0 ) {
728             if (!EVP_CipherUpdate(ctx, tmp + out_misalign + tmplen, &chunklen,
729                                   in, 1))
730                 goto err;
731             tmplen += chunklen;
732         }
733     }
734     if (!EVP_CipherFinal_ex(ctx, tmp + out_misalign + tmplen, &tmpflen)) {
735         t->err = "CIPHERFINAL_ERROR";
736         goto err;
737     }
738     if (!memory_err_compare(t, "VALUE_MISMATCH", expected_out, out_len,
739                             tmp + out_misalign, tmplen + tmpflen))
740         goto err;
741     if (enc && expected->aead) {
742         unsigned char rtag[16];
743
744         if (!TEST_size_t_le(expected->tag_len, sizeof(rtag))) {
745             t->err = "TAG_LENGTH_INTERNAL_ERROR";
746             goto err;
747         }
748         if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_GET_TAG,
749                                  expected->tag_len, rtag)) {
750             t->err = "TAG_RETRIEVE_ERROR";
751             goto err;
752         }
753         if (!memory_err_compare(t, "TAG_VALUE_MISMATCH",
754                                 expected->tag, expected->tag_len,
755                                 rtag, expected->tag_len))
756             goto err;
757     }
758     t->err = NULL;
759     ok = 1;
760  err:
761     OPENSSL_free(tmp);
762     EVP_CIPHER_CTX_free(ctx);
763     return ok;
764 }
765
766 static int cipher_test_run(EVP_TEST *t)
767 {
768     CIPHER_DATA *cdat = t->data;
769     int rv, frag = 0;
770     size_t out_misalign, inp_misalign;
771
772     if (!cdat->key) {
773         t->err = "NO_KEY";
774         return 0;
775     }
776     if (!cdat->iv && EVP_CIPHER_iv_length(cdat->cipher)) {
777         /* IV is optional and usually omitted in wrap mode */
778         if (EVP_CIPHER_mode(cdat->cipher) != EVP_CIPH_WRAP_MODE) {
779             t->err = "NO_IV";
780             return 0;
781         }
782     }
783     if (cdat->aead && !cdat->tag) {
784         t->err = "NO_TAG";
785         return 0;
786     }
787     for (out_misalign = 0; out_misalign <= 1;) {
788         static char aux_err[64];
789         t->aux_err = aux_err;
790         for (inp_misalign = (size_t)-1; inp_misalign != 2; inp_misalign++) {
791             if (inp_misalign == (size_t)-1) {
792                 /* kludge: inp_misalign == -1 means "exercise in-place" */
793                 BIO_snprintf(aux_err, sizeof(aux_err),
794                              "%s in-place, %sfragmented",
795                              out_misalign ? "misaligned" : "aligned",
796                              frag ? "" : "not ");
797             } else {
798                 BIO_snprintf(aux_err, sizeof(aux_err),
799                              "%s output and %s input, %sfragmented",
800                              out_misalign ? "misaligned" : "aligned",
801                              inp_misalign ? "misaligned" : "aligned",
802                              frag ? "" : "not ");
803             }
804             if (cdat->enc) {
805                 rv = cipher_test_enc(t, 1, out_misalign, inp_misalign, frag);
806                 /* Not fatal errors: return */
807                 if (rv != 1) {
808                     if (rv < 0)
809                         return 0;
810                     return 1;
811                 }
812             }
813             if (cdat->enc != 1) {
814                 rv = cipher_test_enc(t, 0, out_misalign, inp_misalign, frag);
815                 /* Not fatal errors: return */
816                 if (rv != 1) {
817                     if (rv < 0)
818                         return 0;
819                     return 1;
820                 }
821             }
822         }
823
824         if (out_misalign == 1 && frag == 0) {
825             /*
826              * XTS, SIV, CCM and Wrap modes have special requirements about input
827              * lengths so we don't fragment for those
828              */
829             if (cdat->aead == EVP_CIPH_CCM_MODE
830                     || EVP_CIPHER_mode(cdat->cipher) == EVP_CIPH_SIV_MODE
831                     || EVP_CIPHER_mode(cdat->cipher) == EVP_CIPH_XTS_MODE
832                     || EVP_CIPHER_mode(cdat->cipher) == EVP_CIPH_WRAP_MODE)
833                 break;
834             out_misalign = 0;
835             frag++;
836         } else {
837             out_misalign++;
838         }
839     }
840     t->aux_err = NULL;
841
842     return 1;
843 }
844
845 static const EVP_TEST_METHOD cipher_test_method = {
846     "Cipher",
847     cipher_test_init,
848     cipher_test_cleanup,
849     cipher_test_parse,
850     cipher_test_run
851 };
852
853
854 /**
855 ***  MAC TESTS
856 **/
857
858 typedef struct mac_data_st {
859     /* MAC type in one form or another */
860     const EVP_MAC *mac;          /* for mac_test_run_mac */
861     int type;                    /* for mac_test_run_pkey */
862     /* Algorithm string for this MAC */
863     char *alg;
864     /* MAC key */
865     unsigned char *key;
866     size_t key_len;
867     /* MAC IV (GMAC) */
868     unsigned char *iv;
869     size_t iv_len;
870     /* Input to MAC */
871     unsigned char *input;
872     size_t input_len;
873     /* Expected output */
874     unsigned char *output;
875     size_t output_len;
876     unsigned char *custom;
877     size_t custom_len;
878     /* MAC salt (blake2) */
879     unsigned char *salt;
880     size_t salt_len;
881     /* Collection of controls */
882     STACK_OF(OPENSSL_STRING) *controls;
883 } MAC_DATA;
884
885 static int mac_test_init(EVP_TEST *t, const char *alg)
886 {
887     const EVP_MAC *mac = NULL;
888     int type = NID_undef;
889     MAC_DATA *mdat;
890
891     if ((mac = EVP_get_macbyname(alg)) == NULL) {
892         /*
893          * Since we didn't find an EVP_MAC, we check for known EVP_PKEY methods
894          * For debugging purposes, we allow 'NNNN by EVP_PKEY' to force running
895          * the EVP_PKEY method.
896          */
897         size_t sz = strlen(alg);
898         static const char epilogue[] = " by EVP_PKEY";
899
900         if (sz >= sizeof(epilogue)
901             && strcmp(alg + sz - (sizeof(epilogue) - 1), epilogue) == 0)
902             sz -= sizeof(epilogue) - 1;
903
904         if (strncmp(alg, "HMAC", sz) == 0) {
905             type = EVP_PKEY_HMAC;
906         } else if (strncmp(alg, "CMAC", sz) == 0) {
907 #ifndef OPENSSL_NO_CMAC
908             type = EVP_PKEY_CMAC;
909 #else
910             t->skip = 1;
911             return 1;
912 #endif
913         } else if (strncmp(alg, "Poly1305", sz) == 0) {
914 #ifndef OPENSSL_NO_POLY1305
915             type = EVP_PKEY_POLY1305;
916 #else
917             t->skip = 1;
918             return 1;
919 #endif
920         } else if (strncmp(alg, "SipHash", sz) == 0) {
921 #ifndef OPENSSL_NO_SIPHASH
922             type = EVP_PKEY_SIPHASH;
923 #else
924             t->skip = 1;
925             return 1;
926 #endif
927         } else {
928             /*
929              * Not a known EVP_PKEY method either.  If it's a known OID, then
930              * assume it's been disabled.
931              */
932             if (OBJ_sn2nid(alg) != NID_undef || OBJ_ln2nid(alg) != NID_undef) {
933                 t->skip = 1;
934                 return 1;
935             }
936
937             return 0;
938         }
939     }
940
941     mdat = OPENSSL_zalloc(sizeof(*mdat));
942     mdat->type = type;
943     mdat->mac = mac;
944     mdat->controls = sk_OPENSSL_STRING_new_null();
945     t->data = mdat;
946     return 1;
947 }
948
949 /* Because OPENSSL_free is a macro, it can't be passed as a function pointer */
950 static void openssl_free(char *m)
951 {
952     OPENSSL_free(m);
953 }
954
955 static void mac_test_cleanup(EVP_TEST *t)
956 {
957     MAC_DATA *mdat = t->data;
958
959     sk_OPENSSL_STRING_pop_free(mdat->controls, openssl_free);
960     OPENSSL_free(mdat->alg);
961     OPENSSL_free(mdat->key);
962     OPENSSL_free(mdat->iv);
963     OPENSSL_free(mdat->custom);
964     OPENSSL_free(mdat->salt);
965     OPENSSL_free(mdat->input);
966     OPENSSL_free(mdat->output);
967 }
968
969 static int mac_test_parse(EVP_TEST *t,
970                           const char *keyword, const char *value)
971 {
972     MAC_DATA *mdata = t->data;
973
974     if (strcmp(keyword, "Key") == 0)
975         return parse_bin(value, &mdata->key, &mdata->key_len);
976     if (strcmp(keyword, "IV") == 0)
977         return parse_bin(value, &mdata->iv, &mdata->iv_len);
978     if (strcmp(keyword, "Custom") == 0)
979         return parse_bin(value, &mdata->custom, &mdata->custom_len);
980     if (strcmp(keyword, "Salt") == 0)
981         return parse_bin(value, &mdata->salt, &mdata->salt_len);
982     if (strcmp(keyword, "Algorithm") == 0) {
983         mdata->alg = OPENSSL_strdup(value);
984         if (!mdata->alg)
985             return 0;
986         return 1;
987     }
988     if (strcmp(keyword, "Input") == 0)
989         return parse_bin(value, &mdata->input, &mdata->input_len);
990     if (strcmp(keyword, "Output") == 0)
991         return parse_bin(value, &mdata->output, &mdata->output_len);
992     if (strcmp(keyword, "Ctrl") == 0)
993         return sk_OPENSSL_STRING_push(mdata->controls,
994                                       OPENSSL_strdup(value)) != 0;
995     return 0;
996 }
997
998 static int mac_test_ctrl_pkey(EVP_TEST *t, EVP_PKEY_CTX *pctx,
999                               const char *value)
1000 {
1001     int rv;
1002     char *p, *tmpval;
1003
1004     if (!TEST_ptr(tmpval = OPENSSL_strdup(value)))
1005         return 0;
1006     p = strchr(tmpval, ':');
1007     if (p != NULL)
1008         *p++ = '\0';
1009     rv = EVP_PKEY_CTX_ctrl_str(pctx, tmpval, p);
1010     if (rv == -2)
1011         t->err = "PKEY_CTRL_INVALID";
1012     else if (rv <= 0)
1013         t->err = "PKEY_CTRL_ERROR";
1014     else
1015         rv = 1;
1016     OPENSSL_free(tmpval);
1017     return rv > 0;
1018 }
1019
1020 static int mac_test_run_pkey(EVP_TEST *t)
1021 {
1022     MAC_DATA *expected = t->data;
1023     EVP_MD_CTX *mctx = NULL;
1024     EVP_PKEY_CTX *pctx = NULL, *genctx = NULL;
1025     EVP_PKEY *key = NULL;
1026     const EVP_MD *md = NULL;
1027     unsigned char *got = NULL;
1028     size_t got_len;
1029     int i;
1030
1031     if (expected->alg == NULL)
1032         TEST_info("Trying the EVP_PKEY %s test", OBJ_nid2sn(expected->type));
1033     else
1034         TEST_info("Trying the EVP_PKEY %s test with %s",
1035                   OBJ_nid2sn(expected->type), expected->alg);
1036
1037 #ifdef OPENSSL_NO_DES
1038     if (expected->alg != NULL && strstr(expected->alg, "DES") != NULL) {
1039         /* Skip DES */
1040         t->err = NULL;
1041         goto err;
1042     }
1043 #endif
1044
1045     if (expected->type == EVP_PKEY_CMAC)
1046         key = EVP_PKEY_new_CMAC_key(NULL, expected->key, expected->key_len,
1047                                     EVP_get_cipherbyname(expected->alg));
1048     else
1049         key = EVP_PKEY_new_raw_private_key(expected->type, NULL, expected->key,
1050                                            expected->key_len);
1051     if (key == NULL) {
1052         t->err = "MAC_KEY_CREATE_ERROR";
1053         goto err;
1054     }
1055
1056     if (expected->type == EVP_PKEY_HMAC) {
1057         if (!TEST_ptr(md = EVP_get_digestbyname(expected->alg))) {
1058             t->err = "MAC_ALGORITHM_SET_ERROR";
1059             goto err;
1060         }
1061     }
1062     if (!TEST_ptr(mctx = EVP_MD_CTX_new())) {
1063         t->err = "INTERNAL_ERROR";
1064         goto err;
1065     }
1066     if (!EVP_DigestSignInit(mctx, &pctx, md, NULL, key)) {
1067         t->err = "DIGESTSIGNINIT_ERROR";
1068         goto err;
1069     }
1070     for (i = 0; i < sk_OPENSSL_STRING_num(expected->controls); i++)
1071         if (!mac_test_ctrl_pkey(t, pctx,
1072                                 sk_OPENSSL_STRING_value(expected->controls,
1073                                                         i))) {
1074             t->err = "EVPPKEYCTXCTRL_ERROR";
1075             goto err;
1076         }
1077     if (!EVP_DigestSignUpdate(mctx, expected->input, expected->input_len)) {
1078         t->err = "DIGESTSIGNUPDATE_ERROR";
1079         goto err;
1080     }
1081     if (!EVP_DigestSignFinal(mctx, NULL, &got_len)) {
1082         t->err = "DIGESTSIGNFINAL_LENGTH_ERROR";
1083         goto err;
1084     }
1085     if (!TEST_ptr(got = OPENSSL_malloc(got_len))) {
1086         t->err = "TEST_FAILURE";
1087         goto err;
1088     }
1089     if (!EVP_DigestSignFinal(mctx, got, &got_len)
1090             || !memory_err_compare(t, "TEST_MAC_ERR",
1091                                    expected->output, expected->output_len,
1092                                    got, got_len)) {
1093         t->err = "TEST_MAC_ERR";
1094         goto err;
1095     }
1096     t->err = NULL;
1097  err:
1098     EVP_MD_CTX_free(mctx);
1099     OPENSSL_free(got);
1100     EVP_PKEY_CTX_free(genctx);
1101     EVP_PKEY_free(key);
1102     return 1;
1103 }
1104
1105 static int mac_test_run_mac(EVP_TEST *t)
1106 {
1107     MAC_DATA *expected = t->data;
1108     EVP_MAC_CTX *ctx = NULL;
1109     const void *algo = NULL;
1110     int algo_ctrl = 0;
1111     unsigned char *got = NULL;
1112     size_t got_len;
1113     int rv, i;
1114
1115     if (expected->alg == NULL)
1116         TEST_info("Trying the EVP_MAC %s test", EVP_MAC_name(expected->mac));
1117     else
1118         TEST_info("Trying the EVP_MAC %s test with %s",
1119                   EVP_MAC_name(expected->mac), expected->alg);
1120
1121 #ifdef OPENSSL_NO_DES
1122     if (expected->alg != NULL && strstr(expected->alg, "DES") != NULL) {
1123         /* Skip DES */
1124         t->err = NULL;
1125         goto err;
1126     }
1127 #endif
1128
1129     if ((ctx = EVP_MAC_CTX_new(expected->mac)) == NULL) {
1130         t->err = "MAC_CREATE_ERROR";
1131         goto err;
1132     }
1133
1134     if (expected->alg != NULL
1135         && ((algo_ctrl = EVP_MAC_CTRL_SET_CIPHER,
1136              algo = EVP_get_cipherbyname(expected->alg)) == NULL
1137             && (algo_ctrl = EVP_MAC_CTRL_SET_MD,
1138                 algo = EVP_get_digestbyname(expected->alg)) == NULL)) {
1139         t->err = "MAC_BAD_ALGORITHM";
1140         goto err;
1141     }
1142
1143
1144     if (algo_ctrl != 0) {
1145         rv = EVP_MAC_ctrl(ctx, algo_ctrl, algo);
1146         if (rv == -2) {
1147             t->err = "MAC_CTRL_INVALID";
1148             goto err;
1149         } else if (rv <= 0) {
1150             t->err = "MAC_CTRL_ERROR";
1151             goto err;
1152         }
1153     }
1154
1155     rv = EVP_MAC_ctrl(ctx, EVP_MAC_CTRL_SET_KEY,
1156                       expected->key, expected->key_len);
1157     if (rv == -2) {
1158         t->err = "MAC_CTRL_INVALID";
1159         goto err;
1160     } else if (rv <= 0) {
1161         t->err = "MAC_CTRL_ERROR";
1162         goto err;
1163     }
1164     if (expected->custom != NULL) {
1165         rv = EVP_MAC_ctrl(ctx, EVP_MAC_CTRL_SET_CUSTOM,
1166                           expected->custom, expected->custom_len);
1167         if (rv == -2) {
1168             t->err = "MAC_CTRL_INVALID";
1169             goto err;
1170         } else if (rv <= 0) {
1171             t->err = "MAC_CTRL_ERROR";
1172             goto err;
1173         }
1174     }
1175
1176     if (expected->salt != NULL) {
1177         rv = EVP_MAC_ctrl(ctx, EVP_MAC_CTRL_SET_SALT,
1178                           expected->salt, expected->salt_len);
1179         if (rv == -2) {
1180             t->err = "MAC_CTRL_INVALID";
1181             goto err;
1182         } else if (rv <= 0) {
1183             t->err = "MAC_CTRL_ERROR";
1184             goto err;
1185         }
1186     }
1187
1188     if (expected->iv != NULL) {
1189         rv = EVP_MAC_ctrl(ctx, EVP_MAC_CTRL_SET_IV,
1190                           expected->iv, expected->iv_len);
1191         if (rv == -2) {
1192             t->err = "MAC_CTRL_INVALID";
1193             goto err;
1194         } else if (rv <= 0) {
1195             t->err = "MAC_CTRL_ERROR";
1196             goto err;
1197         }
1198     }
1199
1200     for (i = 0; i < sk_OPENSSL_STRING_num(expected->controls); i++) {
1201         char *p, *tmpval;
1202         char *value = sk_OPENSSL_STRING_value(expected->controls, i);
1203
1204         if (!TEST_ptr(tmpval = OPENSSL_strdup(value))) {
1205             t->err = "MAC_CTRL_ERROR";
1206             goto err;
1207         }
1208         p = strchr(tmpval, ':');
1209         if (p != NULL)
1210             *p++ = '\0';
1211         rv = EVP_MAC_ctrl_str(ctx, tmpval, p);
1212         OPENSSL_free(tmpval);
1213         if (rv == -2) {
1214             t->err = "MAC_CTRL_INVALID";
1215             goto err;
1216         } else if (rv <= 0) {
1217             t->err = "MAC_CTRL_ERROR";
1218             goto err;
1219         }
1220     }
1221     if (!EVP_MAC_init(ctx)) {
1222         t->err = "MAC_INIT_ERROR";
1223         goto err;
1224     }
1225     if (!EVP_MAC_update(ctx, expected->input, expected->input_len)) {
1226         t->err = "MAC_UPDATE_ERROR";
1227         goto err;
1228     }
1229     if (!EVP_MAC_final(ctx, NULL, &got_len)) {
1230         t->err = "MAC_FINAL_LENGTH_ERROR";
1231         goto err;
1232     }
1233     if (!TEST_ptr(got = OPENSSL_malloc(got_len))) {
1234         t->err = "TEST_FAILURE";
1235         goto err;
1236     }
1237     if (!EVP_MAC_final(ctx, got, &got_len)
1238         || !memory_err_compare(t, "TEST_MAC_ERR",
1239                                expected->output, expected->output_len,
1240                                got, got_len)) {
1241         t->err = "TEST_MAC_ERR";
1242         goto err;
1243     }
1244     t->err = NULL;
1245  err:
1246     EVP_MAC_CTX_free(ctx);
1247     OPENSSL_free(got);
1248     return 1;
1249 }
1250
1251 static int mac_test_run(EVP_TEST *t)
1252 {
1253     MAC_DATA *expected = t->data;
1254
1255     if (expected->mac != NULL)
1256         return mac_test_run_mac(t);
1257     return mac_test_run_pkey(t);
1258 }
1259
1260 static const EVP_TEST_METHOD mac_test_method = {
1261     "MAC",
1262     mac_test_init,
1263     mac_test_cleanup,
1264     mac_test_parse,
1265     mac_test_run
1266 };
1267
1268
1269 /**
1270 ***  PUBLIC KEY TESTS
1271 ***  These are all very similar and share much common code.
1272 **/
1273
1274 typedef struct pkey_data_st {
1275     /* Context for this operation */
1276     EVP_PKEY_CTX *ctx;
1277     /* Key operation to perform */
1278     int (*keyop) (EVP_PKEY_CTX *ctx,
1279                   unsigned char *sig, size_t *siglen,
1280                   const unsigned char *tbs, size_t tbslen);
1281     /* Input to MAC */
1282     unsigned char *input;
1283     size_t input_len;
1284     /* Expected output */
1285     unsigned char *output;
1286     size_t output_len;
1287 } PKEY_DATA;
1288
1289 /*
1290  * Perform public key operation setup: lookup key, allocated ctx and call
1291  * the appropriate initialisation function
1292  */
1293 static int pkey_test_init(EVP_TEST *t, const char *name,
1294                           int use_public,
1295                           int (*keyopinit) (EVP_PKEY_CTX *ctx),
1296                           int (*keyop)(EVP_PKEY_CTX *ctx,
1297                                        unsigned char *sig, size_t *siglen,
1298                                        const unsigned char *tbs,
1299                                        size_t tbslen))
1300 {
1301     PKEY_DATA *kdata;
1302     EVP_PKEY *pkey = NULL;
1303     int rv = 0;
1304
1305     if (use_public)
1306         rv = find_key(&pkey, name, public_keys);
1307     if (rv == 0)
1308         rv = find_key(&pkey, name, private_keys);
1309     if (rv == 0 || pkey == NULL) {
1310         t->skip = 1;
1311         return 1;
1312     }
1313
1314     if (!TEST_ptr(kdata = OPENSSL_zalloc(sizeof(*kdata)))) {
1315         EVP_PKEY_free(pkey);
1316         return 0;
1317     }
1318     kdata->keyop = keyop;
1319     if (!TEST_ptr(kdata->ctx = EVP_PKEY_CTX_new(pkey, NULL))) {
1320         EVP_PKEY_free(pkey);
1321         OPENSSL_free(kdata);
1322         return 0;
1323     }
1324     if (keyopinit(kdata->ctx) <= 0)
1325         t->err = "KEYOP_INIT_ERROR";
1326     t->data = kdata;
1327     return 1;
1328 }
1329
1330 static void pkey_test_cleanup(EVP_TEST *t)
1331 {
1332     PKEY_DATA *kdata = t->data;
1333
1334     OPENSSL_free(kdata->input);
1335     OPENSSL_free(kdata->output);
1336     EVP_PKEY_CTX_free(kdata->ctx);
1337 }
1338
1339 static int pkey_test_ctrl(EVP_TEST *t, EVP_PKEY_CTX *pctx,
1340                           const char *value)
1341 {
1342     int rv;
1343     char *p, *tmpval;
1344
1345     if (!TEST_ptr(tmpval = OPENSSL_strdup(value)))
1346         return 0;
1347     p = strchr(tmpval, ':');
1348     if (p != NULL)
1349         *p++ = '\0';
1350     rv = EVP_PKEY_CTX_ctrl_str(pctx, tmpval, p);
1351     if (rv == -2) {
1352         t->err = "PKEY_CTRL_INVALID";
1353         rv = 1;
1354     } else if (p != NULL && rv <= 0) {
1355         /* If p has an OID and lookup fails assume disabled algorithm */
1356         int nid = OBJ_sn2nid(p);
1357
1358         if (nid == NID_undef)
1359              nid = OBJ_ln2nid(p);
1360         if (nid != NID_undef
1361                 && EVP_get_digestbynid(nid) == NULL
1362                 && EVP_get_cipherbynid(nid) == NULL) {
1363             t->skip = 1;
1364             rv = 1;
1365         } else {
1366             t->err = "PKEY_CTRL_ERROR";
1367             rv = 1;
1368         }
1369     }
1370     OPENSSL_free(tmpval);
1371     return rv > 0;
1372 }
1373
1374 static int pkey_test_parse(EVP_TEST *t,
1375                            const char *keyword, const char *value)
1376 {
1377     PKEY_DATA *kdata = t->data;
1378     if (strcmp(keyword, "Input") == 0)
1379         return parse_bin(value, &kdata->input, &kdata->input_len);
1380     if (strcmp(keyword, "Output") == 0)
1381         return parse_bin(value, &kdata->output, &kdata->output_len);
1382     if (strcmp(keyword, "Ctrl") == 0)
1383         return pkey_test_ctrl(t, kdata->ctx, value);
1384     return 0;
1385 }
1386
1387 static int pkey_test_run(EVP_TEST *t)
1388 {
1389     PKEY_DATA *expected = t->data;
1390     unsigned char *got = NULL;
1391     size_t got_len;
1392     EVP_PKEY_CTX *copy = NULL;
1393
1394     if (expected->keyop(expected->ctx, NULL, &got_len,
1395                         expected->input, expected->input_len) <= 0
1396             || !TEST_ptr(got = OPENSSL_malloc(got_len))) {
1397         t->err = "KEYOP_LENGTH_ERROR";
1398         goto err;
1399     }
1400     if (expected->keyop(expected->ctx, got, &got_len,
1401                         expected->input, expected->input_len) <= 0) {
1402         t->err = "KEYOP_ERROR";
1403         goto err;
1404     }
1405     if (!memory_err_compare(t, "KEYOP_MISMATCH",
1406                             expected->output, expected->output_len,
1407                             got, got_len))
1408         goto err;
1409
1410     t->err = NULL;
1411     OPENSSL_free(got);
1412     got = NULL;
1413
1414     /* Repeat the test on a copy. */
1415     if (!TEST_ptr(copy = EVP_PKEY_CTX_dup(expected->ctx))) {
1416         t->err = "INTERNAL_ERROR";
1417         goto err;
1418     }
1419     if (expected->keyop(copy, NULL, &got_len, expected->input,
1420                         expected->input_len) <= 0
1421             || !TEST_ptr(got = OPENSSL_malloc(got_len))) {
1422         t->err = "KEYOP_LENGTH_ERROR";
1423         goto err;
1424     }
1425     if (expected->keyop(copy, got, &got_len, expected->input,
1426                         expected->input_len) <= 0) {
1427         t->err = "KEYOP_ERROR";
1428         goto err;
1429     }
1430     if (!memory_err_compare(t, "KEYOP_MISMATCH",
1431                             expected->output, expected->output_len,
1432                             got, got_len))
1433         goto err;
1434
1435  err:
1436     OPENSSL_free(got);
1437     EVP_PKEY_CTX_free(copy);
1438     return 1;
1439 }
1440
1441 static int sign_test_init(EVP_TEST *t, const char *name)
1442 {
1443     return pkey_test_init(t, name, 0, EVP_PKEY_sign_init, EVP_PKEY_sign);
1444 }
1445
1446 static const EVP_TEST_METHOD psign_test_method = {
1447     "Sign",
1448     sign_test_init,
1449     pkey_test_cleanup,
1450     pkey_test_parse,
1451     pkey_test_run
1452 };
1453
1454 static int verify_recover_test_init(EVP_TEST *t, const char *name)
1455 {
1456     return pkey_test_init(t, name, 1, EVP_PKEY_verify_recover_init,
1457                           EVP_PKEY_verify_recover);
1458 }
1459
1460 static const EVP_TEST_METHOD pverify_recover_test_method = {
1461     "VerifyRecover",
1462     verify_recover_test_init,
1463     pkey_test_cleanup,
1464     pkey_test_parse,
1465     pkey_test_run
1466 };
1467
1468 static int decrypt_test_init(EVP_TEST *t, const char *name)
1469 {
1470     return pkey_test_init(t, name, 0, EVP_PKEY_decrypt_init,
1471                           EVP_PKEY_decrypt);
1472 }
1473
1474 static const EVP_TEST_METHOD pdecrypt_test_method = {
1475     "Decrypt",
1476     decrypt_test_init,
1477     pkey_test_cleanup,
1478     pkey_test_parse,
1479     pkey_test_run
1480 };
1481
1482 static int verify_test_init(EVP_TEST *t, const char *name)
1483 {
1484     return pkey_test_init(t, name, 1, EVP_PKEY_verify_init, 0);
1485 }
1486
1487 static int verify_test_run(EVP_TEST *t)
1488 {
1489     PKEY_DATA *kdata = t->data;
1490
1491     if (EVP_PKEY_verify(kdata->ctx, kdata->output, kdata->output_len,
1492                         kdata->input, kdata->input_len) <= 0)
1493         t->err = "VERIFY_ERROR";
1494     return 1;
1495 }
1496
1497 static const EVP_TEST_METHOD pverify_test_method = {
1498     "Verify",
1499     verify_test_init,
1500     pkey_test_cleanup,
1501     pkey_test_parse,
1502     verify_test_run
1503 };
1504
1505
1506 static int pderive_test_init(EVP_TEST *t, const char *name)
1507 {
1508     return pkey_test_init(t, name, 0, EVP_PKEY_derive_init, 0);
1509 }
1510
1511 static int pderive_test_parse(EVP_TEST *t,
1512                               const char *keyword, const char *value)
1513 {
1514     PKEY_DATA *kdata = t->data;
1515
1516     if (strcmp(keyword, "PeerKey") == 0) {
1517         EVP_PKEY *peer;
1518         if (find_key(&peer, value, public_keys) == 0)
1519             return 0;
1520         if (EVP_PKEY_derive_set_peer(kdata->ctx, peer) <= 0)
1521             return 0;
1522         return 1;
1523     }
1524     if (strcmp(keyword, "SharedSecret") == 0)
1525         return parse_bin(value, &kdata->output, &kdata->output_len);
1526     if (strcmp(keyword, "Ctrl") == 0)
1527         return pkey_test_ctrl(t, kdata->ctx, value);
1528     return 0;
1529 }
1530
1531 static int pderive_test_run(EVP_TEST *t)
1532 {
1533     PKEY_DATA *expected = t->data;
1534     unsigned char *got = NULL;
1535     size_t got_len;
1536
1537     if (EVP_PKEY_derive(expected->ctx, NULL, &got_len) <= 0) {
1538         t->err = "DERIVE_ERROR";
1539         goto err;
1540     }
1541     if (!TEST_ptr(got = OPENSSL_malloc(got_len))) {
1542         t->err = "DERIVE_ERROR";
1543         goto err;
1544     }
1545     if (EVP_PKEY_derive(expected->ctx, got, &got_len) <= 0) {
1546         t->err = "DERIVE_ERROR";
1547         goto err;
1548     }
1549     if (!memory_err_compare(t, "SHARED_SECRET_MISMATCH",
1550                             expected->output, expected->output_len,
1551                             got, got_len))
1552         goto err;
1553
1554     t->err = NULL;
1555  err:
1556     OPENSSL_free(got);
1557     return 1;
1558 }
1559
1560 static const EVP_TEST_METHOD pderive_test_method = {
1561     "Derive",
1562     pderive_test_init,
1563     pkey_test_cleanup,
1564     pderive_test_parse,
1565     pderive_test_run
1566 };
1567
1568
1569 /**
1570 ***  PBE TESTS
1571 **/
1572
1573 typedef enum pbe_type_enum {
1574     PBE_TYPE_INVALID = 0,
1575     PBE_TYPE_SCRYPT, PBE_TYPE_PBKDF2, PBE_TYPE_PKCS12
1576 } PBE_TYPE;
1577
1578 typedef struct pbe_data_st {
1579     PBE_TYPE pbe_type;
1580         /* scrypt parameters */
1581     uint64_t N, r, p, maxmem;
1582         /* PKCS#12 parameters */
1583     int id, iter;
1584     const EVP_MD *md;
1585         /* password */
1586     unsigned char *pass;
1587     size_t pass_len;
1588         /* salt */
1589     unsigned char *salt;
1590     size_t salt_len;
1591         /* Expected output */
1592     unsigned char *key;
1593     size_t key_len;
1594 } PBE_DATA;
1595
1596 #ifndef OPENSSL_NO_SCRYPT
1597 /*
1598  * Parse unsigned decimal 64 bit integer value
1599  */
1600 static int parse_uint64(const char *value, uint64_t *pr)
1601 {
1602     const char *p = value;
1603
1604     if (!TEST_true(*p)) {
1605         TEST_info("Invalid empty integer value");
1606         return -1;
1607     }
1608     for (*pr = 0; *p; ) {
1609         if (*pr > UINT64_MAX / 10) {
1610             TEST_error("Integer overflow in string %s", value);
1611             return -1;
1612         }
1613         *pr *= 10;
1614         if (!TEST_true(isdigit((unsigned char)*p))) {
1615             TEST_error("Invalid character in string %s", value);
1616             return -1;
1617         }
1618         *pr += *p - '0';
1619         p++;
1620     }
1621     return 1;
1622 }
1623
1624 static int scrypt_test_parse(EVP_TEST *t,
1625                              const char *keyword, const char *value)
1626 {
1627     PBE_DATA *pdata = t->data;
1628
1629     if (strcmp(keyword, "N") == 0)
1630         return parse_uint64(value, &pdata->N);
1631     if (strcmp(keyword, "p") == 0)
1632         return parse_uint64(value, &pdata->p);
1633     if (strcmp(keyword, "r") == 0)
1634         return parse_uint64(value, &pdata->r);
1635     if (strcmp(keyword, "maxmem") == 0)
1636         return parse_uint64(value, &pdata->maxmem);
1637     return 0;
1638 }
1639 #endif
1640
1641 static int pbkdf2_test_parse(EVP_TEST *t,
1642                              const char *keyword, const char *value)
1643 {
1644     PBE_DATA *pdata = t->data;
1645
1646     if (strcmp(keyword, "iter") == 0) {
1647         pdata->iter = atoi(value);
1648         if (pdata->iter <= 0)
1649             return -1;
1650         return 1;
1651     }
1652     if (strcmp(keyword, "MD") == 0) {
1653         pdata->md = EVP_get_digestbyname(value);
1654         if (pdata->md == NULL)
1655             return -1;
1656         return 1;
1657     }
1658     return 0;
1659 }
1660
1661 static int pkcs12_test_parse(EVP_TEST *t,
1662                              const char *keyword, const char *value)
1663 {
1664     PBE_DATA *pdata = t->data;
1665
1666     if (strcmp(keyword, "id") == 0) {
1667         pdata->id = atoi(value);
1668         if (pdata->id <= 0)
1669             return -1;
1670         return 1;
1671     }
1672     return pbkdf2_test_parse(t, keyword, value);
1673 }
1674
1675 static int pbe_test_init(EVP_TEST *t, const char *alg)
1676 {
1677     PBE_DATA *pdat;
1678     PBE_TYPE pbe_type = PBE_TYPE_INVALID;
1679
1680     if (strcmp(alg, "scrypt") == 0) {
1681 #ifndef OPENSSL_NO_SCRYPT
1682         pbe_type = PBE_TYPE_SCRYPT;
1683 #else
1684         t->skip = 1;
1685         return 1;
1686 #endif
1687     } else if (strcmp(alg, "pbkdf2") == 0) {
1688         pbe_type = PBE_TYPE_PBKDF2;
1689     } else if (strcmp(alg, "pkcs12") == 0) {
1690         pbe_type = PBE_TYPE_PKCS12;
1691     } else {
1692         TEST_error("Unknown pbe algorithm %s", alg);
1693     }
1694     pdat = OPENSSL_zalloc(sizeof(*pdat));
1695     pdat->pbe_type = pbe_type;
1696     t->data = pdat;
1697     return 1;
1698 }
1699
1700 static void pbe_test_cleanup(EVP_TEST *t)
1701 {
1702     PBE_DATA *pdat = t->data;
1703
1704     OPENSSL_free(pdat->pass);
1705     OPENSSL_free(pdat->salt);
1706     OPENSSL_free(pdat->key);
1707 }
1708
1709 static int pbe_test_parse(EVP_TEST *t,
1710                           const char *keyword, const char *value)
1711 {
1712     PBE_DATA *pdata = t->data;
1713
1714     if (strcmp(keyword, "Password") == 0)
1715         return parse_bin(value, &pdata->pass, &pdata->pass_len);
1716     if (strcmp(keyword, "Salt") == 0)
1717         return parse_bin(value, &pdata->salt, &pdata->salt_len);
1718     if (strcmp(keyword, "Key") == 0)
1719         return parse_bin(value, &pdata->key, &pdata->key_len);
1720     if (pdata->pbe_type == PBE_TYPE_PBKDF2)
1721         return pbkdf2_test_parse(t, keyword, value);
1722     else if (pdata->pbe_type == PBE_TYPE_PKCS12)
1723         return pkcs12_test_parse(t, keyword, value);
1724 #ifndef OPENSSL_NO_SCRYPT
1725     else if (pdata->pbe_type == PBE_TYPE_SCRYPT)
1726         return scrypt_test_parse(t, keyword, value);
1727 #endif
1728     return 0;
1729 }
1730
1731 static int pbe_test_run(EVP_TEST *t)
1732 {
1733     PBE_DATA *expected = t->data;
1734     unsigned char *key;
1735
1736     if (!TEST_ptr(key = OPENSSL_malloc(expected->key_len))) {
1737         t->err = "INTERNAL_ERROR";
1738         goto err;
1739     }
1740     if (expected->pbe_type == PBE_TYPE_PBKDF2) {
1741         if (PKCS5_PBKDF2_HMAC((char *)expected->pass, expected->pass_len,
1742                               expected->salt, expected->salt_len,
1743                               expected->iter, expected->md,
1744                               expected->key_len, key) == 0) {
1745             t->err = "PBKDF2_ERROR";
1746             goto err;
1747         }
1748 #ifndef OPENSSL_NO_SCRYPT
1749     } else if (expected->pbe_type == PBE_TYPE_SCRYPT) {
1750         if (EVP_PBE_scrypt((const char *)expected->pass, expected->pass_len,
1751                            expected->salt, expected->salt_len, expected->N,
1752                            expected->r, expected->p, expected->maxmem,
1753                            key, expected->key_len) == 0) {
1754             t->err = "SCRYPT_ERROR";
1755             goto err;
1756         }
1757 #endif
1758     } else if (expected->pbe_type == PBE_TYPE_PKCS12) {
1759         if (PKCS12_key_gen_uni(expected->pass, expected->pass_len,
1760                                expected->salt, expected->salt_len,
1761                                expected->id, expected->iter, expected->key_len,
1762                                key, expected->md) == 0) {
1763             t->err = "PKCS12_ERROR";
1764             goto err;
1765         }
1766     }
1767     if (!memory_err_compare(t, "KEY_MISMATCH", expected->key, expected->key_len,
1768                             key, expected->key_len))
1769         goto err;
1770
1771     t->err = NULL;
1772 err:
1773     OPENSSL_free(key);
1774     return 1;
1775 }
1776
1777 static const EVP_TEST_METHOD pbe_test_method = {
1778     "PBE",
1779     pbe_test_init,
1780     pbe_test_cleanup,
1781     pbe_test_parse,
1782     pbe_test_run
1783 };
1784
1785
1786 /**
1787 ***  BASE64 TESTS
1788 **/
1789
1790 typedef enum {
1791     BASE64_CANONICAL_ENCODING = 0,
1792     BASE64_VALID_ENCODING = 1,
1793     BASE64_INVALID_ENCODING = 2
1794 } base64_encoding_type;
1795
1796 typedef struct encode_data_st {
1797     /* Input to encoding */
1798     unsigned char *input;
1799     size_t input_len;
1800     /* Expected output */
1801     unsigned char *output;
1802     size_t output_len;
1803     base64_encoding_type encoding;
1804 } ENCODE_DATA;
1805
1806 static int encode_test_init(EVP_TEST *t, const char *encoding)
1807 {
1808     ENCODE_DATA *edata;
1809
1810     if (!TEST_ptr(edata = OPENSSL_zalloc(sizeof(*edata))))
1811         return 0;
1812     if (strcmp(encoding, "canonical") == 0) {
1813         edata->encoding = BASE64_CANONICAL_ENCODING;
1814     } else if (strcmp(encoding, "valid") == 0) {
1815         edata->encoding = BASE64_VALID_ENCODING;
1816     } else if (strcmp(encoding, "invalid") == 0) {
1817         edata->encoding = BASE64_INVALID_ENCODING;
1818         if (!TEST_ptr(t->expected_err = OPENSSL_strdup("DECODE_ERROR")))
1819             goto err;
1820     } else {
1821         TEST_error("Bad encoding: %s."
1822                    " Should be one of {canonical, valid, invalid}",
1823                    encoding);
1824         goto err;
1825     }
1826     t->data = edata;
1827     return 1;
1828 err:
1829     OPENSSL_free(edata);
1830     return 0;
1831 }
1832
1833 static void encode_test_cleanup(EVP_TEST *t)
1834 {
1835     ENCODE_DATA *edata = t->data;
1836
1837     OPENSSL_free(edata->input);
1838     OPENSSL_free(edata->output);
1839     memset(edata, 0, sizeof(*edata));
1840 }
1841
1842 static int encode_test_parse(EVP_TEST *t,
1843                              const char *keyword, const char *value)
1844 {
1845     ENCODE_DATA *edata = t->data;
1846
1847     if (strcmp(keyword, "Input") == 0)
1848         return parse_bin(value, &edata->input, &edata->input_len);
1849     if (strcmp(keyword, "Output") == 0)
1850         return parse_bin(value, &edata->output, &edata->output_len);
1851     return 0;
1852 }
1853
1854 static int encode_test_run(EVP_TEST *t)
1855 {
1856     ENCODE_DATA *expected = t->data;
1857     unsigned char *encode_out = NULL, *decode_out = NULL;
1858     int output_len, chunk_len;
1859     EVP_ENCODE_CTX *decode_ctx = NULL, *encode_ctx = NULL;
1860
1861     if (!TEST_ptr(decode_ctx = EVP_ENCODE_CTX_new())) {
1862         t->err = "INTERNAL_ERROR";
1863         goto err;
1864     }
1865
1866     if (expected->encoding == BASE64_CANONICAL_ENCODING) {
1867
1868         if (!TEST_ptr(encode_ctx = EVP_ENCODE_CTX_new())
1869                 || !TEST_ptr(encode_out =
1870                         OPENSSL_malloc(EVP_ENCODE_LENGTH(expected->input_len))))
1871             goto err;
1872
1873         EVP_EncodeInit(encode_ctx);
1874         if (!TEST_true(EVP_EncodeUpdate(encode_ctx, encode_out, &chunk_len,
1875                                         expected->input, expected->input_len)))
1876             goto err;
1877
1878         output_len = chunk_len;
1879
1880         EVP_EncodeFinal(encode_ctx, encode_out + chunk_len, &chunk_len);
1881         output_len += chunk_len;
1882
1883         if (!memory_err_compare(t, "BAD_ENCODING",
1884                                 expected->output, expected->output_len,
1885                                 encode_out, output_len))
1886             goto err;
1887     }
1888
1889     if (!TEST_ptr(decode_out =
1890                 OPENSSL_malloc(EVP_DECODE_LENGTH(expected->output_len))))
1891         goto err;
1892
1893     EVP_DecodeInit(decode_ctx);
1894     if (EVP_DecodeUpdate(decode_ctx, decode_out, &chunk_len, expected->output,
1895                          expected->output_len) < 0) {
1896         t->err = "DECODE_ERROR";
1897         goto err;
1898     }
1899     output_len = chunk_len;
1900
1901     if (EVP_DecodeFinal(decode_ctx, decode_out + chunk_len, &chunk_len) != 1) {
1902         t->err = "DECODE_ERROR";
1903         goto err;
1904     }
1905     output_len += chunk_len;
1906
1907     if (expected->encoding != BASE64_INVALID_ENCODING
1908             && !memory_err_compare(t, "BAD_DECODING",
1909                                    expected->input, expected->input_len,
1910                                    decode_out, output_len)) {
1911         t->err = "BAD_DECODING";
1912         goto err;
1913     }
1914
1915     t->err = NULL;
1916  err:
1917     OPENSSL_free(encode_out);
1918     OPENSSL_free(decode_out);
1919     EVP_ENCODE_CTX_free(decode_ctx);
1920     EVP_ENCODE_CTX_free(encode_ctx);
1921     return 1;
1922 }
1923
1924 static const EVP_TEST_METHOD encode_test_method = {
1925     "Encoding",
1926     encode_test_init,
1927     encode_test_cleanup,
1928     encode_test_parse,
1929     encode_test_run,
1930 };
1931
1932
1933 /**
1934 ***  KDF TESTS
1935 **/
1936
1937 typedef struct kdf_data_st {
1938     /* Context for this operation */
1939     EVP_KDF_CTX *ctx;
1940     /* Expected output */
1941     unsigned char *output;
1942     size_t output_len;
1943 } KDF_DATA;
1944
1945 /*
1946  * Perform public key operation setup: lookup key, allocated ctx and call
1947  * the appropriate initialisation function
1948  */
1949 static int kdf_test_init(EVP_TEST *t, const char *name)
1950 {
1951     KDF_DATA *kdata;
1952     const EVP_KDF *kdf;
1953
1954 #ifdef OPENSSL_NO_SCRYPT
1955     if (strcmp(name, "scrypt") == 0) {
1956         t->skip = 1;
1957         return 1;
1958     }
1959 #endif
1960
1961     kdf = EVP_get_kdfbyname(name);
1962     if (kdf == NULL)
1963         return 0;
1964
1965     if (!TEST_ptr(kdata = OPENSSL_zalloc(sizeof(*kdata))))
1966         return 0;
1967     kdata->ctx = EVP_KDF_CTX_new(kdf);
1968     if (kdata->ctx == NULL) {
1969         OPENSSL_free(kdata);
1970         return 0;
1971     }
1972     t->data = kdata;
1973     return 1;
1974 }
1975
1976 static void kdf_test_cleanup(EVP_TEST *t)
1977 {
1978     KDF_DATA *kdata = t->data;
1979     OPENSSL_free(kdata->output);
1980     EVP_KDF_CTX_free(kdata->ctx);
1981 }
1982
1983 static int kdf_test_ctrl(EVP_TEST *t, EVP_KDF_CTX *kctx,
1984                          const char *value)
1985 {
1986     int rv;
1987     char *p, *tmpval;
1988
1989     if (!TEST_ptr(tmpval = OPENSSL_strdup(value)))
1990         return 0;
1991     p = strchr(tmpval, ':');
1992     if (p != NULL)
1993         *p++ = '\0';
1994     rv = EVP_KDF_ctrl_str(kctx, tmpval, p);
1995     if (rv == -2) {
1996         t->err = "KDF_CTRL_INVALID";
1997         rv = 1;
1998     } else if (p != NULL && rv <= 0) {
1999         /* If p has an OID and lookup fails assume disabled algorithm */
2000         int nid = OBJ_sn2nid(p);
2001
2002         if (nid == NID_undef)
2003              nid = OBJ_ln2nid(p);
2004         if (nid != NID_undef
2005                 && EVP_get_digestbynid(nid) == NULL
2006                 && EVP_get_cipherbynid(nid) == NULL) {
2007             t->skip = 1;
2008             rv = 1;
2009         } else {
2010             t->err = "KDF_CTRL_ERROR";
2011             rv = 1;
2012         }
2013     }
2014     OPENSSL_free(tmpval);
2015     return rv > 0;
2016 }
2017
2018 static int kdf_test_parse(EVP_TEST *t,
2019                           const char *keyword, const char *value)
2020 {
2021     KDF_DATA *kdata = t->data;
2022
2023     if (strcmp(keyword, "Output") == 0)
2024         return parse_bin(value, &kdata->output, &kdata->output_len);
2025     if (strncmp(keyword, "Ctrl", 4) == 0)
2026         return kdf_test_ctrl(t, kdata->ctx, value);
2027     return 0;
2028 }
2029
2030 static int kdf_test_run(EVP_TEST *t)
2031 {
2032     KDF_DATA *expected = t->data;
2033     unsigned char *got = NULL;
2034     size_t got_len = expected->output_len;
2035
2036     if (!TEST_ptr(got = OPENSSL_malloc(got_len))) {
2037         t->err = "INTERNAL_ERROR";
2038         goto err;
2039     }
2040     if (EVP_KDF_derive(expected->ctx, got, got_len) <= 0) {
2041         t->err = "KDF_DERIVE_ERROR";
2042         goto err;
2043     }
2044     if (!memory_err_compare(t, "KDF_MISMATCH",
2045                             expected->output, expected->output_len,
2046                             got, got_len))
2047         goto err;
2048
2049     t->err = NULL;
2050
2051  err:
2052     OPENSSL_free(got);
2053     return 1;
2054 }
2055
2056 static const EVP_TEST_METHOD kdf_test_method = {
2057     "KDF",
2058     kdf_test_init,
2059     kdf_test_cleanup,
2060     kdf_test_parse,
2061     kdf_test_run
2062 };
2063
2064
2065 /**
2066 ***  PKEY KDF TESTS
2067 **/
2068
2069 typedef struct pkey_kdf_data_st {
2070     /* Context for this operation */
2071     EVP_PKEY_CTX *ctx;
2072     /* Expected output */
2073     unsigned char *output;
2074     size_t output_len;
2075 } PKEY_KDF_DATA;
2076
2077 /*
2078  * Perform public key operation setup: lookup key, allocated ctx and call
2079  * the appropriate initialisation function
2080  */
2081 static int pkey_kdf_test_init(EVP_TEST *t, const char *name)
2082 {
2083     PKEY_KDF_DATA *kdata;
2084     int kdf_nid = OBJ_sn2nid(name);
2085
2086 #ifdef OPENSSL_NO_SCRYPT
2087     if (strcmp(name, "scrypt") == 0) {
2088         t->skip = 1;
2089         return 1;
2090     }
2091 #endif
2092
2093     if (kdf_nid == NID_undef)
2094         kdf_nid = OBJ_ln2nid(name);
2095
2096     if (!TEST_ptr(kdata = OPENSSL_zalloc(sizeof(*kdata))))
2097         return 0;
2098     kdata->ctx = EVP_PKEY_CTX_new_id(kdf_nid, NULL);
2099     if (kdata->ctx == NULL) {
2100         OPENSSL_free(kdata);
2101         return 0;
2102     }
2103     if (EVP_PKEY_derive_init(kdata->ctx) <= 0) {
2104         EVP_PKEY_CTX_free(kdata->ctx);
2105         OPENSSL_free(kdata);
2106         return 0;
2107     }
2108     t->data = kdata;
2109     return 1;
2110 }
2111
2112 static void pkey_kdf_test_cleanup(EVP_TEST *t)
2113 {
2114     PKEY_KDF_DATA *kdata = t->data;
2115     OPENSSL_free(kdata->output);
2116     EVP_PKEY_CTX_free(kdata->ctx);
2117 }
2118
2119 static int pkey_kdf_test_parse(EVP_TEST *t,
2120                                const char *keyword, const char *value)
2121 {
2122     PKEY_KDF_DATA *kdata = t->data;
2123
2124     if (strcmp(keyword, "Output") == 0)
2125         return parse_bin(value, &kdata->output, &kdata->output_len);
2126     if (strncmp(keyword, "Ctrl", 4) == 0)
2127         return pkey_test_ctrl(t, kdata->ctx, value);
2128     return 0;
2129 }
2130
2131 static int pkey_kdf_test_run(EVP_TEST *t)
2132 {
2133     PKEY_KDF_DATA *expected = t->data;
2134     unsigned char *got = NULL;
2135     size_t got_len = expected->output_len;
2136
2137     if (!TEST_ptr(got = OPENSSL_malloc(got_len))) {
2138         t->err = "INTERNAL_ERROR";
2139         goto err;
2140     }
2141     if (EVP_PKEY_derive(expected->ctx, got, &got_len) <= 0) {
2142         t->err = "KDF_DERIVE_ERROR";
2143         goto err;
2144     }
2145     if (!TEST_mem_eq(expected->output, expected->output_len, got, got_len)) {
2146         t->err = "KDF_MISMATCH";
2147         goto err;
2148     }
2149     t->err = NULL;
2150
2151  err:
2152     OPENSSL_free(got);
2153     return 1;
2154 }
2155
2156 static const EVP_TEST_METHOD pkey_kdf_test_method = {
2157     "PKEYKDF",
2158     pkey_kdf_test_init,
2159     pkey_kdf_test_cleanup,
2160     pkey_kdf_test_parse,
2161     pkey_kdf_test_run
2162 };
2163
2164
2165 /**
2166 ***  KEYPAIR TESTS
2167 **/
2168
2169 typedef struct keypair_test_data_st {
2170     EVP_PKEY *privk;
2171     EVP_PKEY *pubk;
2172 } KEYPAIR_TEST_DATA;
2173
2174 static int keypair_test_init(EVP_TEST *t, const char *pair)
2175 {
2176     KEYPAIR_TEST_DATA *data;
2177     int rv = 0;
2178     EVP_PKEY *pk = NULL, *pubk = NULL;
2179     char *pub, *priv = NULL;
2180
2181     /* Split private and public names. */
2182     if (!TEST_ptr(priv = OPENSSL_strdup(pair))
2183             || !TEST_ptr(pub = strchr(priv, ':'))) {
2184         t->err = "PARSING_ERROR";
2185         goto end;
2186     }
2187     *pub++ = '\0';
2188
2189     if (!TEST_true(find_key(&pk, priv, private_keys))) {
2190         TEST_info("Can't find private key: %s", priv);
2191         t->err = "MISSING_PRIVATE_KEY";
2192         goto end;
2193     }
2194     if (!TEST_true(find_key(&pubk, pub, public_keys))) {
2195         TEST_info("Can't find public key: %s", pub);
2196         t->err = "MISSING_PUBLIC_KEY";
2197         goto end;
2198     }
2199
2200     if (pk == NULL && pubk == NULL) {
2201         /* Both keys are listed but unsupported: skip this test */
2202         t->skip = 1;
2203         rv = 1;
2204         goto end;
2205     }
2206
2207     if (!TEST_ptr(data = OPENSSL_malloc(sizeof(*data))))
2208         goto end;
2209     data->privk = pk;
2210     data->pubk = pubk;
2211     t->data = data;
2212     rv = 1;
2213     t->err = NULL;
2214
2215 end:
2216     OPENSSL_free(priv);
2217     return rv;
2218 }
2219
2220 static void keypair_test_cleanup(EVP_TEST *t)
2221 {
2222     OPENSSL_free(t->data);
2223     t->data = NULL;
2224 }
2225
2226 /*
2227  * For tests that do not accept any custom keywords.
2228  */
2229 static int void_test_parse(EVP_TEST *t, const char *keyword, const char *value)
2230 {
2231     return 0;
2232 }
2233
2234 static int keypair_test_run(EVP_TEST *t)
2235 {
2236     int rv = 0;
2237     const KEYPAIR_TEST_DATA *pair = t->data;
2238
2239     if (pair->privk == NULL || pair->pubk == NULL) {
2240         /*
2241          * this can only happen if only one of the keys is not set
2242          * which means that one of them was unsupported while the
2243          * other isn't: hence a key type mismatch.
2244          */
2245         t->err = "KEYPAIR_TYPE_MISMATCH";
2246         rv = 1;
2247         goto end;
2248     }
2249
2250     if ((rv = EVP_PKEY_cmp(pair->privk, pair->pubk)) != 1 ) {
2251         if ( 0 == rv ) {
2252             t->err = "KEYPAIR_MISMATCH";
2253         } else if ( -1 == rv ) {
2254             t->err = "KEYPAIR_TYPE_MISMATCH";
2255         } else if ( -2 == rv ) {
2256             t->err = "UNSUPPORTED_KEY_COMPARISON";
2257         } else {
2258             TEST_error("Unexpected error in key comparison");
2259             rv = 0;
2260             goto end;
2261         }
2262         rv = 1;
2263         goto end;
2264     }
2265
2266     rv = 1;
2267     t->err = NULL;
2268
2269 end:
2270     return rv;
2271 }
2272
2273 static const EVP_TEST_METHOD keypair_test_method = {
2274     "PrivPubKeyPair",
2275     keypair_test_init,
2276     keypair_test_cleanup,
2277     void_test_parse,
2278     keypair_test_run
2279 };
2280
2281 /**
2282 ***  KEYGEN TEST
2283 **/
2284
2285 typedef struct keygen_test_data_st {
2286     EVP_PKEY_CTX *genctx; /* Keygen context to use */
2287     char *keyname; /* Key name to store key or NULL */
2288 } KEYGEN_TEST_DATA;
2289
2290 static int keygen_test_init(EVP_TEST *t, const char *alg)
2291 {
2292     KEYGEN_TEST_DATA *data;
2293     EVP_PKEY_CTX *genctx;
2294     int nid = OBJ_sn2nid(alg);
2295
2296     if (nid == NID_undef) {
2297         nid = OBJ_ln2nid(alg);
2298         if (nid == NID_undef)
2299             return 0;
2300     }
2301
2302     if (!TEST_ptr(genctx = EVP_PKEY_CTX_new_id(nid, NULL))) {
2303         /* assume algorithm disabled */
2304         t->skip = 1;
2305         return 1;
2306     }
2307
2308     if (EVP_PKEY_keygen_init(genctx) <= 0) {
2309         t->err = "KEYGEN_INIT_ERROR";
2310         goto err;
2311     }
2312
2313     if (!TEST_ptr(data = OPENSSL_malloc(sizeof(*data))))
2314         goto err;
2315     data->genctx = genctx;
2316     data->keyname = NULL;
2317     t->data = data;
2318     t->err = NULL;
2319     return 1;
2320
2321 err:
2322     EVP_PKEY_CTX_free(genctx);
2323     return 0;
2324 }
2325
2326 static void keygen_test_cleanup(EVP_TEST *t)
2327 {
2328     KEYGEN_TEST_DATA *keygen = t->data;
2329
2330     EVP_PKEY_CTX_free(keygen->genctx);
2331     OPENSSL_free(keygen->keyname);
2332     OPENSSL_free(t->data);
2333     t->data = NULL;
2334 }
2335
2336 static int keygen_test_parse(EVP_TEST *t,
2337                              const char *keyword, const char *value)
2338 {
2339     KEYGEN_TEST_DATA *keygen = t->data;
2340
2341     if (strcmp(keyword, "KeyName") == 0)
2342         return TEST_ptr(keygen->keyname = OPENSSL_strdup(value));
2343     if (strcmp(keyword, "Ctrl") == 0)
2344         return pkey_test_ctrl(t, keygen->genctx, value);
2345     return 0;
2346 }
2347
2348 static int keygen_test_run(EVP_TEST *t)
2349 {
2350     KEYGEN_TEST_DATA *keygen = t->data;
2351     EVP_PKEY *pkey = NULL;
2352
2353     t->err = NULL;
2354     if (EVP_PKEY_keygen(keygen->genctx, &pkey) <= 0) {
2355         t->err = "KEYGEN_GENERATE_ERROR";
2356         goto err;
2357     }
2358
2359     if (keygen->keyname != NULL) {
2360         KEY_LIST *key;
2361
2362         if (find_key(NULL, keygen->keyname, private_keys)) {
2363             TEST_info("Duplicate key %s", keygen->keyname);
2364             goto err;
2365         }
2366
2367         if (!TEST_ptr(key = OPENSSL_malloc(sizeof(*key))))
2368             goto err;
2369         key->name = keygen->keyname;
2370         keygen->keyname = NULL;
2371         key->key = pkey;
2372         key->next = private_keys;
2373         private_keys = key;
2374     } else {
2375         EVP_PKEY_free(pkey);
2376     }
2377
2378     return 1;
2379
2380 err:
2381     EVP_PKEY_free(pkey);
2382     return 0;
2383 }
2384
2385 static const EVP_TEST_METHOD keygen_test_method = {
2386     "KeyGen",
2387     keygen_test_init,
2388     keygen_test_cleanup,
2389     keygen_test_parse,
2390     keygen_test_run,
2391 };
2392
2393 /**
2394 ***  DIGEST SIGN+VERIFY TESTS
2395 **/
2396
2397 typedef struct {
2398     int is_verify; /* Set to 1 if verifying */
2399     int is_oneshot; /* Set to 1 for one shot operation */
2400     const EVP_MD *md; /* Digest to use */
2401     EVP_MD_CTX *ctx; /* Digest context */
2402     EVP_PKEY_CTX *pctx;
2403     STACK_OF(EVP_TEST_BUFFER) *input; /* Input data: streaming */
2404     unsigned char *osin; /* Input data if one shot */
2405     size_t osin_len; /* Input length data if one shot */
2406     unsigned char *output; /* Expected output */
2407     size_t output_len; /* Expected output length */
2408 } DIGESTSIGN_DATA;
2409
2410 static int digestsigver_test_init(EVP_TEST *t, const char *alg, int is_verify,
2411                                   int is_oneshot)
2412 {
2413     const EVP_MD *md = NULL;
2414     DIGESTSIGN_DATA *mdat;
2415
2416     if (strcmp(alg, "NULL") != 0) {
2417         if ((md = EVP_get_digestbyname(alg)) == NULL) {
2418             /* If alg has an OID assume disabled algorithm */
2419             if (OBJ_sn2nid(alg) != NID_undef || OBJ_ln2nid(alg) != NID_undef) {
2420                 t->skip = 1;
2421                 return 1;
2422             }
2423             return 0;
2424         }
2425     }
2426     if (!TEST_ptr(mdat = OPENSSL_zalloc(sizeof(*mdat))))
2427         return 0;
2428     mdat->md = md;
2429     if (!TEST_ptr(mdat->ctx = EVP_MD_CTX_new())) {
2430         OPENSSL_free(mdat);
2431         return 0;
2432     }
2433     mdat->is_verify = is_verify;
2434     mdat->is_oneshot = is_oneshot;
2435     t->data = mdat;
2436     return 1;
2437 }
2438
2439 static int digestsign_test_init(EVP_TEST *t, const char *alg)
2440 {
2441     return digestsigver_test_init(t, alg, 0, 0);
2442 }
2443
2444 static void digestsigver_test_cleanup(EVP_TEST *t)
2445 {
2446     DIGESTSIGN_DATA *mdata = t->data;
2447
2448     EVP_MD_CTX_free(mdata->ctx);
2449     sk_EVP_TEST_BUFFER_pop_free(mdata->input, evp_test_buffer_free);
2450     OPENSSL_free(mdata->osin);
2451     OPENSSL_free(mdata->output);
2452     OPENSSL_free(mdata);
2453     t->data = NULL;
2454 }
2455
2456 static int digestsigver_test_parse(EVP_TEST *t,
2457                                    const char *keyword, const char *value)
2458 {
2459     DIGESTSIGN_DATA *mdata = t->data;
2460
2461     if (strcmp(keyword, "Key") == 0) {
2462         EVP_PKEY *pkey = NULL;
2463         int rv = 0;
2464
2465         if (mdata->is_verify)
2466             rv = find_key(&pkey, value, public_keys);
2467         if (rv == 0)
2468             rv = find_key(&pkey, value, private_keys);
2469         if (rv == 0 || pkey == NULL) {
2470             t->skip = 1;
2471             return 1;
2472         }
2473         if (mdata->is_verify) {
2474             if (!EVP_DigestVerifyInit(mdata->ctx, &mdata->pctx, mdata->md,
2475                                       NULL, pkey))
2476                 t->err = "DIGESTVERIFYINIT_ERROR";
2477             return 1;
2478         }
2479         if (!EVP_DigestSignInit(mdata->ctx, &mdata->pctx, mdata->md, NULL,
2480                                 pkey))
2481             t->err = "DIGESTSIGNINIT_ERROR";
2482         return 1;
2483     }
2484
2485     if (strcmp(keyword, "Input") == 0) {
2486         if (mdata->is_oneshot)
2487             return parse_bin(value, &mdata->osin, &mdata->osin_len);
2488         return evp_test_buffer_append(value, &mdata->input);
2489     }
2490     if (strcmp(keyword, "Output") == 0)
2491         return parse_bin(value, &mdata->output, &mdata->output_len);
2492
2493     if (!mdata->is_oneshot) {
2494         if (strcmp(keyword, "Count") == 0)
2495             return evp_test_buffer_set_count(value, mdata->input);
2496         if (strcmp(keyword, "Ncopy") == 0)
2497             return evp_test_buffer_ncopy(value, mdata->input);
2498     }
2499     if (strcmp(keyword, "Ctrl") == 0) {
2500         if (mdata->pctx == NULL)
2501             return 0;
2502         return pkey_test_ctrl(t, mdata->pctx, value);
2503     }
2504     return 0;
2505 }
2506
2507 static int digestsign_update_fn(void *ctx, const unsigned char *buf,
2508                                 size_t buflen)
2509 {
2510     return EVP_DigestSignUpdate(ctx, buf, buflen);
2511 }
2512
2513 static int digestsign_test_run(EVP_TEST *t)
2514 {
2515     DIGESTSIGN_DATA *expected = t->data;
2516     unsigned char *got = NULL;
2517     size_t got_len;
2518
2519     if (!evp_test_buffer_do(expected->input, digestsign_update_fn,
2520                             expected->ctx)) {
2521         t->err = "DIGESTUPDATE_ERROR";
2522         goto err;
2523     }
2524
2525     if (!EVP_DigestSignFinal(expected->ctx, NULL, &got_len)) {
2526         t->err = "DIGESTSIGNFINAL_LENGTH_ERROR";
2527         goto err;
2528     }
2529     if (!TEST_ptr(got = OPENSSL_malloc(got_len))) {
2530         t->err = "MALLOC_FAILURE";
2531         goto err;
2532     }
2533     if (!EVP_DigestSignFinal(expected->ctx, got, &got_len)) {
2534         t->err = "DIGESTSIGNFINAL_ERROR";
2535         goto err;
2536     }
2537     if (!memory_err_compare(t, "SIGNATURE_MISMATCH",
2538                             expected->output, expected->output_len,
2539                             got, got_len))
2540         goto err;
2541
2542     t->err = NULL;
2543  err:
2544     OPENSSL_free(got);
2545     return 1;
2546 }
2547
2548 static const EVP_TEST_METHOD digestsign_test_method = {
2549     "DigestSign",
2550     digestsign_test_init,
2551     digestsigver_test_cleanup,
2552     digestsigver_test_parse,
2553     digestsign_test_run
2554 };
2555
2556 static int digestverify_test_init(EVP_TEST *t, const char *alg)
2557 {
2558     return digestsigver_test_init(t, alg, 1, 0);
2559 }
2560
2561 static int digestverify_update_fn(void *ctx, const unsigned char *buf,
2562                                   size_t buflen)
2563 {
2564     return EVP_DigestVerifyUpdate(ctx, buf, buflen);
2565 }
2566
2567 static int digestverify_test_run(EVP_TEST *t)
2568 {
2569     DIGESTSIGN_DATA *mdata = t->data;
2570
2571     if (!evp_test_buffer_do(mdata->input, digestverify_update_fn, mdata->ctx)) {
2572         t->err = "DIGESTUPDATE_ERROR";
2573         return 1;
2574     }
2575
2576     if (EVP_DigestVerifyFinal(mdata->ctx, mdata->output,
2577                               mdata->output_len) <= 0)
2578         t->err = "VERIFY_ERROR";
2579     return 1;
2580 }
2581
2582 static const EVP_TEST_METHOD digestverify_test_method = {
2583     "DigestVerify",
2584     digestverify_test_init,
2585     digestsigver_test_cleanup,
2586     digestsigver_test_parse,
2587     digestverify_test_run
2588 };
2589
2590 static int oneshot_digestsign_test_init(EVP_TEST *t, const char *alg)
2591 {
2592     return digestsigver_test_init(t, alg, 0, 1);
2593 }
2594
2595 static int oneshot_digestsign_test_run(EVP_TEST *t)
2596 {
2597     DIGESTSIGN_DATA *expected = t->data;
2598     unsigned char *got = NULL;
2599     size_t got_len;
2600
2601     if (!EVP_DigestSign(expected->ctx, NULL, &got_len,
2602                         expected->osin, expected->osin_len)) {
2603         t->err = "DIGESTSIGN_LENGTH_ERROR";
2604         goto err;
2605     }
2606     if (!TEST_ptr(got = OPENSSL_malloc(got_len))) {
2607         t->err = "MALLOC_FAILURE";
2608         goto err;
2609     }
2610     if (!EVP_DigestSign(expected->ctx, got, &got_len,
2611                         expected->osin, expected->osin_len)) {
2612         t->err = "DIGESTSIGN_ERROR";
2613         goto err;
2614     }
2615     if (!memory_err_compare(t, "SIGNATURE_MISMATCH",
2616                             expected->output, expected->output_len,
2617                             got, got_len))
2618         goto err;
2619
2620     t->err = NULL;
2621  err:
2622     OPENSSL_free(got);
2623     return 1;
2624 }
2625
2626 static const EVP_TEST_METHOD oneshot_digestsign_test_method = {
2627     "OneShotDigestSign",
2628     oneshot_digestsign_test_init,
2629     digestsigver_test_cleanup,
2630     digestsigver_test_parse,
2631     oneshot_digestsign_test_run
2632 };
2633
2634 static int oneshot_digestverify_test_init(EVP_TEST *t, const char *alg)
2635 {
2636     return digestsigver_test_init(t, alg, 1, 1);
2637 }
2638
2639 static int oneshot_digestverify_test_run(EVP_TEST *t)
2640 {
2641     DIGESTSIGN_DATA *mdata = t->data;
2642
2643     if (EVP_DigestVerify(mdata->ctx, mdata->output, mdata->output_len,
2644                          mdata->osin, mdata->osin_len) <= 0)
2645         t->err = "VERIFY_ERROR";
2646     return 1;
2647 }
2648
2649 static const EVP_TEST_METHOD oneshot_digestverify_test_method = {
2650     "OneShotDigestVerify",
2651     oneshot_digestverify_test_init,
2652     digestsigver_test_cleanup,
2653     digestsigver_test_parse,
2654     oneshot_digestverify_test_run
2655 };
2656
2657
2658 /**
2659 ***  PARSING AND DISPATCH
2660 **/
2661
2662 static const EVP_TEST_METHOD *evp_test_list[] = {
2663     &cipher_test_method,
2664     &digest_test_method,
2665     &digestsign_test_method,
2666     &digestverify_test_method,
2667     &encode_test_method,
2668     &kdf_test_method,
2669     &pkey_kdf_test_method,
2670     &keypair_test_method,
2671     &keygen_test_method,
2672     &mac_test_method,
2673     &oneshot_digestsign_test_method,
2674     &oneshot_digestverify_test_method,
2675     &pbe_test_method,
2676     &pdecrypt_test_method,
2677     &pderive_test_method,
2678     &psign_test_method,
2679     &pverify_recover_test_method,
2680     &pverify_test_method,
2681     NULL
2682 };
2683
2684 static const EVP_TEST_METHOD *find_test(const char *name)
2685 {
2686     const EVP_TEST_METHOD **tt;
2687
2688     for (tt = evp_test_list; *tt; tt++) {
2689         if (strcmp(name, (*tt)->name) == 0)
2690             return *tt;
2691     }
2692     return NULL;
2693 }
2694
2695 static void clear_test(EVP_TEST *t)
2696 {
2697     test_clearstanza(&t->s);
2698     ERR_clear_error();
2699     if (t->data != NULL) {
2700         if (t->meth != NULL)
2701             t->meth->cleanup(t);
2702         OPENSSL_free(t->data);
2703         t->data = NULL;
2704     }
2705     OPENSSL_free(t->expected_err);
2706     t->expected_err = NULL;
2707     OPENSSL_free(t->func);
2708     t->func = NULL;
2709     OPENSSL_free(t->reason);
2710     t->reason = NULL;
2711
2712     /* Text literal. */
2713     t->err = NULL;
2714     t->skip = 0;
2715     t->meth = NULL;
2716 }
2717
2718 /*
2719  * Check for errors in the test structure; return 1 if okay, else 0.
2720  */
2721 static int check_test_error(EVP_TEST *t)
2722 {
2723     unsigned long err;
2724     const char *func;
2725     const char *reason;
2726
2727     if (t->err == NULL && t->expected_err == NULL)
2728         return 1;
2729     if (t->err != NULL && t->expected_err == NULL) {
2730         if (t->aux_err != NULL) {
2731             TEST_info("%s:%d: Source of above error (%s); unexpected error %s",
2732                       t->s.test_file, t->s.start, t->aux_err, t->err);
2733         } else {
2734             TEST_info("%s:%d: Source of above error; unexpected error %s",
2735                       t->s.test_file, t->s.start, t->err);
2736         }
2737         return 0;
2738     }
2739     if (t->err == NULL && t->expected_err != NULL) {
2740         TEST_info("%s:%d: Succeeded but was expecting %s",
2741                   t->s.test_file, t->s.start, t->expected_err);
2742         return 0;
2743     }
2744
2745     if (strcmp(t->err, t->expected_err) != 0) {
2746         TEST_info("%s:%d: Expected %s got %s",
2747                   t->s.test_file, t->s.start, t->expected_err, t->err);
2748         return 0;
2749     }
2750
2751     if (t->func == NULL && t->reason == NULL)
2752         return 1;
2753
2754     if (t->func == NULL || t->reason == NULL) {
2755         TEST_info("%s:%d: Test is missing function or reason code",
2756                   t->s.test_file, t->s.start);
2757         return 0;
2758     }
2759
2760     err = ERR_peek_error();
2761     if (err == 0) {
2762         TEST_info("%s:%d: Expected error \"%s:%s\" not set",
2763                   t->s.test_file, t->s.start, t->func, t->reason);
2764         return 0;
2765     }
2766
2767     func = ERR_func_error_string(err);
2768     reason = ERR_reason_error_string(err);
2769     if (func == NULL && reason == NULL) {
2770         TEST_info("%s:%d: Expected error \"%s:%s\", no strings available."
2771                   " Assuming ok.",
2772                   t->s.test_file, t->s.start, t->func, t->reason);
2773         return 1;
2774     }
2775
2776     if (strcmp(func, t->func) == 0 && strcmp(reason, t->reason) == 0)
2777         return 1;
2778
2779     TEST_info("%s:%d: Expected error \"%s:%s\", got \"%s:%s\"",
2780               t->s.test_file, t->s.start, t->func, t->reason, func, reason);
2781
2782     return 0;
2783 }
2784
2785 /*
2786  * Run a parsed test. Log a message and return 0 on error.
2787  */
2788 static int run_test(EVP_TEST *t)
2789 {
2790     if (t->meth == NULL)
2791         return 1;
2792     t->s.numtests++;
2793     if (t->skip) {
2794         t->s.numskip++;
2795     } else {
2796         /* run the test */
2797         if (t->err == NULL && t->meth->run_test(t) != 1) {
2798             TEST_info("%s:%d %s error",
2799                       t->s.test_file, t->s.start, t->meth->name);
2800             return 0;
2801         }
2802         if (!check_test_error(t)) {
2803             TEST_openssl_errors();
2804             t->s.errors++;
2805         }
2806     }
2807
2808     /* clean it up */
2809     return 1;
2810 }
2811
2812 static int find_key(EVP_PKEY **ppk, const char *name, KEY_LIST *lst)
2813 {
2814     for (; lst != NULL; lst = lst->next) {
2815         if (strcmp(lst->name, name) == 0) {
2816             if (ppk != NULL)
2817                 *ppk = lst->key;
2818             return 1;
2819         }
2820     }
2821     return 0;
2822 }
2823
2824 static void free_key_list(KEY_LIST *lst)
2825 {
2826     while (lst != NULL) {
2827         KEY_LIST *next = lst->next;
2828
2829         EVP_PKEY_free(lst->key);
2830         OPENSSL_free(lst->name);
2831         OPENSSL_free(lst);
2832         lst = next;
2833     }
2834 }
2835
2836 /*
2837  * Is the key type an unsupported algorithm?
2838  */
2839 static int key_unsupported(void)
2840 {
2841     long err = ERR_peek_error();
2842
2843     if (ERR_GET_LIB(err) == ERR_LIB_EVP
2844             && ERR_GET_REASON(err) == EVP_R_UNSUPPORTED_ALGORITHM) {
2845         ERR_clear_error();
2846         return 1;
2847     }
2848 #ifndef OPENSSL_NO_EC
2849     /*
2850      * If EC support is enabled we should catch also EC_R_UNKNOWN_GROUP as an
2851      * hint to an unsupported algorithm/curve (e.g. if binary EC support is
2852      * disabled).
2853      */
2854     if (ERR_GET_LIB(err) == ERR_LIB_EC
2855         && ERR_GET_REASON(err) == EC_R_UNKNOWN_GROUP) {
2856         ERR_clear_error();
2857         return 1;
2858     }
2859 #endif /* OPENSSL_NO_EC */
2860     return 0;
2861 }
2862
2863 /*
2864  * NULL out the value from |pp| but return it.  This "steals" a pointer.
2865  */
2866 static char *take_value(PAIR *pp)
2867 {
2868     char *p = pp->value;
2869
2870     pp->value = NULL;
2871     return p;
2872 }
2873
2874 /*
2875  * Read and parse one test.  Return 0 if failure, 1 if okay.
2876  */
2877 static int parse(EVP_TEST *t)
2878 {
2879     KEY_LIST *key, **klist;
2880     EVP_PKEY *pkey;
2881     PAIR *pp;
2882     int i;
2883
2884 top:
2885     do {
2886         if (BIO_eof(t->s.fp))
2887             return EOF;
2888         clear_test(t);
2889         if (!test_readstanza(&t->s))
2890             return 0;
2891     } while (t->s.numpairs == 0);
2892     pp = &t->s.pairs[0];
2893
2894     /* Are we adding a key? */
2895     klist = NULL;
2896     pkey = NULL;
2897     if (strcmp(pp->key, "PrivateKey") == 0) {
2898         pkey = PEM_read_bio_PrivateKey(t->s.key, NULL, 0, NULL);
2899         if (pkey == NULL && !key_unsupported()) {
2900             EVP_PKEY_free(pkey);
2901             TEST_info("Can't read private key %s", pp->value);
2902             TEST_openssl_errors();
2903             return 0;
2904         }
2905         klist = &private_keys;
2906     } else if (strcmp(pp->key, "PublicKey") == 0) {
2907         pkey = PEM_read_bio_PUBKEY(t->s.key, NULL, 0, NULL);
2908         if (pkey == NULL && !key_unsupported()) {
2909             EVP_PKEY_free(pkey);
2910             TEST_info("Can't read public key %s", pp->value);
2911             TEST_openssl_errors();
2912             return 0;
2913         }
2914         klist = &public_keys;
2915     } else if (strcmp(pp->key, "PrivateKeyRaw") == 0
2916                || strcmp(pp->key, "PublicKeyRaw") == 0 ) {
2917         char *strnid = NULL, *keydata = NULL;
2918         unsigned char *keybin;
2919         size_t keylen;
2920         int nid;
2921
2922         if (strcmp(pp->key, "PrivateKeyRaw") == 0)
2923             klist = &private_keys;
2924         else
2925             klist = &public_keys;
2926
2927         strnid = strchr(pp->value, ':');
2928         if (strnid != NULL) {
2929             *strnid++ = '\0';
2930             keydata = strchr(strnid, ':');
2931             if (keydata != NULL)
2932                 *keydata++ = '\0';
2933         }
2934         if (keydata == NULL) {
2935             TEST_info("Failed to parse %s value", pp->key);
2936             return 0;
2937         }
2938
2939         nid = OBJ_txt2nid(strnid);
2940         if (nid == NID_undef) {
2941             TEST_info("Uncrecognised algorithm NID");
2942             return 0;
2943         }
2944         if (!parse_bin(keydata, &keybin, &keylen)) {
2945             TEST_info("Failed to create binary key");
2946             return 0;
2947         }
2948         if (klist == &private_keys)
2949             pkey = EVP_PKEY_new_raw_private_key(nid, NULL, keybin, keylen);
2950         else
2951             pkey = EVP_PKEY_new_raw_public_key(nid, NULL, keybin, keylen);
2952         if (pkey == NULL && !key_unsupported()) {
2953             TEST_info("Can't read %s data", pp->key);
2954             OPENSSL_free(keybin);
2955             TEST_openssl_errors();
2956             return 0;
2957         }
2958         OPENSSL_free(keybin);
2959     }
2960
2961     /* If we have a key add to list */
2962     if (klist != NULL) {
2963         if (find_key(NULL, pp->value, *klist)) {
2964             TEST_info("Duplicate key %s", pp->value);
2965             return 0;
2966         }
2967         if (!TEST_ptr(key = OPENSSL_malloc(sizeof(*key))))
2968             return 0;
2969         key->name = take_value(pp);
2970
2971         /* Hack to detect SM2 keys */
2972         if(pkey != NULL && strstr(key->name, "SM2") != NULL) {
2973 #ifdef OPENSSL_NO_SM2
2974             EVP_PKEY_free(pkey);
2975             pkey = NULL;
2976 #else
2977             EVP_PKEY_set_alias_type(pkey, EVP_PKEY_SM2);
2978 #endif
2979         }
2980
2981         key->key = pkey;
2982         key->next = *klist;
2983         *klist = key;
2984
2985         /* Go back and start a new stanza. */
2986         if (t->s.numpairs != 1)
2987             TEST_info("Line %d: missing blank line\n", t->s.curr);
2988         goto top;
2989     }
2990
2991     /* Find the test, based on first keyword. */
2992     if (!TEST_ptr(t->meth = find_test(pp->key)))
2993         return 0;
2994     if (!t->meth->init(t, pp->value)) {
2995         TEST_error("unknown %s: %s\n", pp->key, pp->value);
2996         return 0;
2997     }
2998     if (t->skip == 1) {
2999         /* TEST_info("skipping %s %s", pp->key, pp->value); */
3000         return 0;
3001     }
3002
3003     for (pp++, i = 1; i < t->s.numpairs; pp++, i++) {
3004         if (strcmp(pp->key, "Result") == 0) {
3005             if (t->expected_err != NULL) {
3006                 TEST_info("Line %d: multiple result lines", t->s.curr);
3007                 return 0;
3008             }
3009             t->expected_err = take_value(pp);
3010         } else if (strcmp(pp->key, "Function") == 0) {
3011             if (t->func != NULL) {
3012                 TEST_info("Line %d: multiple function lines\n", t->s.curr);
3013                 return 0;
3014             }
3015             t->func = take_value(pp);
3016         } else if (strcmp(pp->key, "Reason") == 0) {
3017             if (t->reason != NULL) {
3018                 TEST_info("Line %d: multiple reason lines", t->s.curr);
3019                 return 0;
3020             }
3021             t->reason = take_value(pp);
3022         } else {
3023             /* Must be test specific line: try to parse it */
3024             int rv = t->meth->parse(t, pp->key, pp->value);
3025
3026             if (rv == 0) {
3027                 TEST_info("Line %d: unknown keyword %s", t->s.curr, pp->key);
3028                 return 0;
3029             }
3030             if (rv < 0) {
3031                 TEST_info("Line %d: error processing keyword %s = %s\n",
3032                           t->s.curr, pp->key, pp->value);
3033                 return 0;
3034             }
3035         }
3036     }
3037
3038     return 1;
3039 }
3040
3041 static int run_file_tests(int i)
3042 {
3043     EVP_TEST *t;
3044     const char *testfile = test_get_argument(i);
3045     int c;
3046
3047     if (!TEST_ptr(t = OPENSSL_zalloc(sizeof(*t))))
3048         return 0;
3049     if (!test_start_file(&t->s, testfile)) {
3050         OPENSSL_free(t);
3051         return 0;
3052     }
3053
3054     while (!BIO_eof(t->s.fp)) {
3055         c = parse(t);
3056         if (t->skip)
3057             continue;
3058         if (c == 0 || !run_test(t)) {
3059             t->s.errors++;
3060             break;
3061         }
3062     }
3063     test_end_file(&t->s);
3064     clear_test(t);
3065
3066     free_key_list(public_keys);
3067     free_key_list(private_keys);
3068     BIO_free(t->s.key);
3069     c = t->s.errors;
3070     OPENSSL_free(t);
3071     return c == 0;
3072 }
3073
3074 OPT_TEST_DECLARE_USAGE("file...\n")
3075
3076 int setup_tests(void)
3077 {
3078     size_t n = test_get_argument_count();
3079
3080     if (n == 0)
3081         return 0;
3082
3083     ADD_ALL_TESTS(run_file_tests, n);
3084     return 1;
3085 }