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