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