Be careful when applying EXE_SHELL
[openssl.git] / test / evp_test.c
1 /*
2  * Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL
3  * project.
4  */
5 /* ====================================================================
6  * Copyright (c) 2015 The OpenSSL Project.  All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  *
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  *
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in
17  *    the documentation and/or other materials provided with the
18  *    distribution.
19  *
20  * 3. All advertising materials mentioning features or use of this
21  *    software must display the following acknowledgment:
22  *    "This product includes software developed by the OpenSSL Project
23  *    for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
24  *
25  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
26  *    endorse or promote products derived from this software without
27  *    prior written permission. For written permission, please contact
28  *    licensing@OpenSSL.org.
29  *
30  * 5. Products derived from this software may not be called "OpenSSL"
31  *    nor may "OpenSSL" appear in their names without prior written
32  *    permission of the OpenSSL Project.
33  *
34  * 6. Redistributions of any form whatsoever must retain the following
35  *    acknowledgment:
36  *    "This product includes software developed by the OpenSSL Project
37  *    for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
38  *
39  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
40  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
41  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
42  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
43  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
44  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
45  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
46  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
48  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
49  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
50  * OF THE POSSIBILITY OF SUCH DAMAGE.
51  * ====================================================================
52  */
53
54 #include <stdio.h>
55 #include <string.h>
56 #include <stdlib.h>
57 #include <ctype.h>
58 #include <openssl/evp.h>
59 #include <openssl/pem.h>
60 #include <openssl/err.h>
61 #include <openssl/x509v3.h>
62 #include <openssl/pkcs12.h>
63 #include <openssl/kdf.h>
64 #include "internal/numbers.h"
65
66 /* Remove spaces from beginning and end of a string */
67
68 static void remove_space(char **pval)
69 {
70     unsigned char *p = (unsigned char *)*pval;
71
72     while (isspace(*p))
73         p++;
74
75     *pval = (char *)p;
76
77     p = p + strlen(*pval) - 1;
78
79     /* Remove trailing space */
80     while (isspace(*p))
81         *p-- = 0;
82 }
83
84 /*
85  * Given a line of the form:
86  *      name = value # comment
87  * extract name and value. NB: modifies passed buffer.
88  */
89
90 static int parse_line(char **pkw, char **pval, char *linebuf)
91 {
92     char *p;
93
94     p = linebuf + strlen(linebuf) - 1;
95
96     if (*p != '\n') {
97         fprintf(stderr, "FATAL: missing EOL\n");
98         exit(1);
99     }
100
101     /* Look for # */
102
103     p = strchr(linebuf, '#');
104
105     if (p)
106         *p = '\0';
107
108     /* Look for = sign */
109     p = strchr(linebuf, '=');
110
111     /* If no '=' exit */
112     if (!p)
113         return 0;
114
115     *p++ = '\0';
116
117     *pkw = linebuf;
118     *pval = p;
119
120     /* Remove spaces from keyword and value */
121     remove_space(pkw);
122     remove_space(pval);
123
124     return 1;
125 }
126
127 /*
128  * Unescape some escape sequences in string literals.
129  * Return the result in a newly allocated buffer.
130  * Currently only supports '\n'.
131  * If the input length is 0, returns a valid 1-byte buffer, but sets
132  * the length to 0.
133  */
134 static unsigned char* unescape(const char *input, size_t input_len,
135                                size_t *out_len)
136 {
137     unsigned char *ret, *p;
138     size_t i;
139     if (input_len == 0) {
140         *out_len = 0;
141         return OPENSSL_zalloc(1);
142     }
143
144     /* Escaping is non-expanding; over-allocate original size for simplicity. */
145     ret = p = OPENSSL_malloc(input_len);
146     if (ret == NULL)
147         return NULL;
148
149     for (i = 0; i < input_len; i++) {
150         if (input[i] == '\\') {
151             if (i == input_len - 1 || input[i+1] != 'n')
152                 goto err;
153             *p++ = '\n';
154             i++;
155         } else {
156             *p++ = input[i];
157         }
158     }
159
160     *out_len = p - ret;
161     return ret;
162
163  err:
164     OPENSSL_free(ret);
165     return NULL;
166 }
167
168 /* For a hex string "value" convert to a binary allocated buffer */
169 static int test_bin(const char *value, unsigned char **buf, size_t *buflen)
170 {
171     long len;
172     if (!*value) {
173         /*
174          * Don't return NULL for zero length buffer.
175          * This is needed for some tests with empty keys: HMAC_Init_ex() expects
176          * a non-NULL key buffer even if the key length is 0, in order to detect
177          * key reset.
178          */
179         *buf = OPENSSL_malloc(1);
180         if (!*buf)
181             return 0;
182         **buf = 0;
183         *buflen = 0;
184         return 1;
185     }
186     /* Check for string literal */
187     if (value[0] == '"') {
188         size_t vlen;
189         value++;
190         vlen = strlen(value);
191         if (value[vlen - 1] != '"')
192             return 0;
193         vlen--;
194         *buf = unescape(value, vlen, buflen);
195         if (*buf == NULL)
196             return 0;
197         return 1;
198     }
199
200     *buf = string_to_hex(value, &len);
201     if (!*buf) {
202         fprintf(stderr, "Value=%s\n", value);
203         ERR_print_errors_fp(stderr);
204         return -1;
205     }
206     /* Size of input buffer means we'll never overflow */
207     *buflen = len;
208     return 1;
209 }
210 /* Parse unsigned decimal 64 bit integer value */
211 static int test_uint64(const char *value, uint64_t *pr)
212 {
213     const char *p = value;
214     if (!*p) {
215         fprintf(stderr, "Invalid empty integer value\n");
216         return -1;
217     }
218     *pr = 0;
219     while (*p) {
220         if (*pr > UINT64_MAX/10) {
221             fprintf(stderr, "Integer string overflow value=%s\n", value);
222             return -1;
223         }
224         *pr *= 10;
225         if (*p < '0' || *p > '9') {
226             fprintf(stderr, "Invalid integer string value=%s\n", value);
227             return -1;
228         }
229         *pr += *p - '0';
230         p++;
231     }
232     return 1;
233 }
234
235 /* Structure holding test information */
236 struct evp_test {
237     /* file being read */
238     FILE *in;
239     /* List of public and private keys */
240     struct key_list *private;
241     struct key_list *public;
242     /* method for this test */
243     const struct evp_test_method *meth;
244     /* current line being processed */
245     unsigned int line;
246     /* start line of current test */
247     unsigned int start_line;
248     /* Error string for test */
249     const char *err;
250     /* Expected error value of test */
251     char *expected_err;
252     /* Number of tests */
253     int ntests;
254     /* Error count */
255     int errors;
256     /* Number of tests skipped */
257     int nskip;
258     /* If output mismatch expected and got value */
259     unsigned char *out_received;
260     size_t out_received_len;
261     unsigned char *out_expected;
262     size_t out_expected_len;
263     /* test specific data */
264     void *data;
265     /* Current test should be skipped */
266     int skip;
267 };
268
269 struct key_list {
270     char *name;
271     EVP_PKEY *key;
272     struct key_list *next;
273 };
274
275 /* Test method structure */
276 struct evp_test_method {
277     /* Name of test as it appears in file */
278     const char *name;
279     /* Initialise test for "alg" */
280     int (*init) (struct evp_test * t, const char *alg);
281     /* Clean up method */
282     void (*cleanup) (struct evp_test * t);
283     /* Test specific name value pair processing */
284     int (*parse) (struct evp_test * t, const char *name, const char *value);
285     /* Run the test itself */
286     int (*run_test) (struct evp_test * t);
287 };
288
289 static const struct evp_test_method digest_test_method, cipher_test_method;
290 static const struct evp_test_method mac_test_method;
291 static const struct evp_test_method psign_test_method, pverify_test_method;
292 static const struct evp_test_method pdecrypt_test_method;
293 static const struct evp_test_method pverify_recover_test_method;
294 static const struct evp_test_method pbe_test_method;
295 static const struct evp_test_method encode_test_method;
296 static const struct evp_test_method kdf_test_method;
297
298 static const struct evp_test_method *evp_test_list[] = {
299     &digest_test_method,
300     &cipher_test_method,
301     &mac_test_method,
302     &psign_test_method,
303     &pverify_test_method,
304     &pdecrypt_test_method,
305     &pverify_recover_test_method,
306     &pbe_test_method,
307     &encode_test_method,
308     &kdf_test_method,
309     NULL
310 };
311
312 static const struct evp_test_method *evp_find_test(const char *name)
313 {
314     const struct evp_test_method **tt;
315
316     for (tt = evp_test_list; *tt; tt++) {
317         if (strcmp(name, (*tt)->name) == 0)
318             return *tt;
319     }
320     return NULL;
321 }
322
323 static void hex_print(const char *name, const unsigned char *buf, size_t len)
324 {
325     size_t i;
326     fprintf(stderr, "%s ", name);
327     for (i = 0; i < len; i++)
328         fprintf(stderr, "%02X", buf[i]);
329     fputs("\n", stderr);
330 }
331
332 static void free_expected(struct evp_test *t)
333 {
334     OPENSSL_free(t->expected_err);
335     t->expected_err = NULL;
336     OPENSSL_free(t->out_expected);
337     OPENSSL_free(t->out_received);
338     t->out_expected = NULL;
339     t->out_received = NULL;
340     t->out_expected_len = 0;
341     t->out_received_len = 0;
342     /* Literals. */
343     t->err = NULL;
344 }
345
346 static void print_expected(struct evp_test *t)
347 {
348     if (t->out_expected == NULL && t->out_received == NULL)
349         return;
350     hex_print("Expected:", t->out_expected, t->out_expected_len);
351     hex_print("Got:     ", t->out_received, t->out_received_len);
352     free_expected(t);
353 }
354
355 static int check_test_error(struct evp_test *t)
356 {
357     if (!t->err && !t->expected_err)
358         return 1;
359     if (t->err && !t->expected_err) {
360         fprintf(stderr, "Test line %d: unexpected error %s\n",
361                 t->start_line, t->err);
362         print_expected(t);
363         return 0;
364     }
365     if (!t->err && t->expected_err) {
366         fprintf(stderr, "Test line %d: succeeded expecting %s\n",
367                 t->start_line, t->expected_err);
368         return 0;
369     }
370     if (strcmp(t->err, t->expected_err) == 0)
371         return 1;
372
373     fprintf(stderr, "Test line %d: expecting %s got %s\n",
374             t->start_line, t->expected_err, t->err);
375     return 0;
376 }
377
378 /* Setup a new test, run any existing test */
379
380 static int setup_test(struct evp_test *t, const struct evp_test_method *tmeth)
381 {
382     /* If we already have a test set up run it */
383     if (t->meth) {
384         t->ntests++;
385         if (t->skip) {
386             t->meth = tmeth;
387             t->nskip++;
388             return 1;
389         }
390         t->err = NULL;
391         if (t->meth->run_test(t) != 1) {
392             fprintf(stderr, "%s test error line %d\n",
393                     t->meth->name, t->start_line);
394             return 0;
395         }
396         if (!check_test_error(t)) {
397             if (t->err)
398                 ERR_print_errors_fp(stderr);
399             t->errors++;
400         }
401         ERR_clear_error();
402         t->meth->cleanup(t);
403         OPENSSL_free(t->data);
404         t->data = NULL;
405         OPENSSL_free(t->expected_err);
406         t->expected_err = NULL;
407         free_expected(t);
408     }
409     t->meth = tmeth;
410     return 1;
411 }
412
413 static int find_key(EVP_PKEY **ppk, const char *name, struct key_list *lst)
414 {
415     for (; lst; lst = lst->next) {
416         if (strcmp(lst->name, name) == 0) {
417             if (ppk)
418                 *ppk = lst->key;
419             return 1;
420         }
421     }
422     return 0;
423 }
424
425 static void free_key_list(struct key_list *lst)
426 {
427     while (lst != NULL) {
428         struct key_list *ltmp;
429         EVP_PKEY_free(lst->key);
430         OPENSSL_free(lst->name);
431         ltmp = lst->next;
432         OPENSSL_free(lst);
433         lst = ltmp;
434     }
435 }
436
437 static int check_unsupported()
438 {
439     long err = ERR_peek_error();
440     if (ERR_GET_LIB(err) == ERR_LIB_EVP
441         && ERR_GET_REASON(err) == EVP_R_UNSUPPORTED_ALGORITHM) {
442         ERR_clear_error();
443         return 1;
444     }
445     return 0;
446 }
447
448 static int process_test(struct evp_test *t, char *buf, int verbose)
449 {
450     char *keyword = NULL, *value = NULL;
451     int rv = 0, add_key = 0;
452     long save_pos = 0;
453     struct key_list **lst = NULL, *key = NULL;
454     EVP_PKEY *pk = NULL;
455     const struct evp_test_method *tmeth = NULL;
456     if (verbose)
457         fputs(buf, stdout);
458     if (!parse_line(&keyword, &value, buf))
459         return 1;
460     if (strcmp(keyword, "PrivateKey") == 0) {
461         save_pos = ftell(t->in);
462         pk = PEM_read_PrivateKey(t->in, NULL, 0, NULL);
463         if (pk == NULL && !check_unsupported()) {
464             fprintf(stderr, "Error reading private key %s\n", value);
465             ERR_print_errors_fp(stderr);
466             return 0;
467         }
468         lst = &t->private;
469         add_key = 1;
470     }
471     if (strcmp(keyword, "PublicKey") == 0) {
472         save_pos = ftell(t->in);
473         pk = PEM_read_PUBKEY(t->in, NULL, 0, NULL);
474         if (pk == NULL && !check_unsupported()) {
475             fprintf(stderr, "Error reading public key %s\n", value);
476             ERR_print_errors_fp(stderr);
477             return 0;
478         }
479         lst = &t->public;
480         add_key = 1;
481     }
482     /* If we have a key add to list */
483     if (add_key) {
484         char tmpbuf[80];
485         if (find_key(NULL, value, *lst)) {
486             fprintf(stderr, "Duplicate key %s\n", value);
487             return 0;
488         }
489         key = OPENSSL_malloc(sizeof(*key));
490         if (!key)
491             return 0;
492         key->name = OPENSSL_strdup(value);
493         key->key = pk;
494         key->next = *lst;
495         *lst = key;
496         /* Rewind input, read to end and update line numbers */
497         fseek(t->in, save_pos, SEEK_SET);
498         while (fgets(tmpbuf, sizeof(tmpbuf), t->in)) {
499             t->line++;
500             if (strncmp(tmpbuf, "-----END", 8) == 0)
501                 return 1;
502         }
503         fprintf(stderr, "Can't find key end\n");
504         return 0;
505     }
506
507     /* See if keyword corresponds to a test start */
508     tmeth = evp_find_test(keyword);
509     if (tmeth) {
510         if (!setup_test(t, tmeth))
511             return 0;
512         t->start_line = t->line;
513         t->skip = 0;
514         if (!tmeth->init(t, value)) {
515             fprintf(stderr, "Unknown %s: %s\n", keyword, value);
516             return 0;
517         }
518         return 1;
519     } else if (t->skip) {
520         return 1;
521     } else if (strcmp(keyword, "Result") == 0) {
522         if (t->expected_err) {
523             fprintf(stderr, "Line %d: multiple result lines\n", t->line);
524             return 0;
525         }
526         t->expected_err = OPENSSL_strdup(value);
527         if (!t->expected_err)
528             return 0;
529     } else {
530         /* Must be test specific line: try to parse it */
531         if (t->meth)
532             rv = t->meth->parse(t, keyword, value);
533
534         if (rv == 0)
535             fprintf(stderr, "line %d: unexpected keyword %s\n",
536                     t->line, keyword);
537
538         if (rv < 0)
539             fprintf(stderr, "line %d: error processing keyword %s\n",
540                     t->line, keyword);
541         if (rv <= 0)
542             return 0;
543     }
544     return 1;
545 }
546
547 static int check_var_length_output(struct evp_test *t,
548                                    const unsigned char *expected,
549                                    size_t expected_len,
550                                    const unsigned char *received,
551                                    size_t received_len)
552 {
553     if (expected_len == received_len &&
554         memcmp(expected, received, expected_len) == 0) {
555         return 0;
556     }
557
558     /* The result printing code expects a non-NULL buffer. */
559     t->out_expected = OPENSSL_memdup(expected, expected_len ? expected_len : 1);
560     t->out_expected_len = expected_len;
561     t->out_received = OPENSSL_memdup(received, received_len ? received_len : 1);
562     t->out_received_len = received_len;
563     if (t->out_expected == NULL || t->out_received == NULL) {
564         fprintf(stderr, "Memory allocation error!\n");
565         exit(1);
566     }
567     return 1;
568 }
569
570 static int check_output(struct evp_test *t,
571                         const unsigned char *expected,
572                         const unsigned char *received,
573                         size_t len)
574 {
575     return check_var_length_output(t, expected, len, received, len);
576 }
577
578 int main(int argc, char **argv)
579 {
580     FILE *in = NULL;
581     char buf[10240];
582     struct evp_test t;
583
584     if (argc != 2) {
585         fprintf(stderr, "usage: evp_test testfile.txt\n");
586         return 1;
587     }
588
589     CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON);
590
591     ERR_load_crypto_strings();
592     OpenSSL_add_all_algorithms();
593
594     memset(&t, 0, sizeof(t));
595     t.start_line = -1;
596     in = fopen(argv[1], "r");
597     t.in = in;
598     while (fgets(buf, sizeof(buf), in)) {
599         t.line++;
600         if (!process_test(&t, buf, 0))
601             exit(1);
602     }
603     /* Run any final test we have */
604     if (!setup_test(&t, NULL))
605         exit(1);
606     fprintf(stderr, "%d tests completed with %d errors, %d skipped\n",
607             t.ntests, t.errors, t.nskip);
608     free_key_list(t.public);
609     free_key_list(t.private);
610     fclose(in);
611     EVP_cleanup();
612     CRYPTO_cleanup_all_ex_data();
613     ERR_remove_thread_state(NULL);
614     ERR_free_strings();
615 #ifndef OPENSSL_NO_CRYPTO_MDEBUG
616     CRYPTO_mem_leaks_fp(stderr);
617 #endif
618     if (t.errors)
619         return 1;
620     return 0;
621 }
622
623 static void test_free(void *d)
624 {
625     OPENSSL_free(d);
626 }
627
628 /* Message digest tests */
629
630 struct digest_data {
631     /* Digest this test is for */
632     const EVP_MD *digest;
633     /* Input to digest */
634     unsigned char *input;
635     size_t input_len;
636     /* Repeat count for input */
637     size_t nrpt;
638     /* Expected output */
639     unsigned char *output;
640     size_t output_len;
641 };
642
643 static int digest_test_init(struct evp_test *t, const char *alg)
644 {
645     const EVP_MD *digest;
646     struct digest_data *mdat;
647     digest = EVP_get_digestbyname(alg);
648     if (!digest) {
649         /* If alg has an OID assume disabled algorithm */
650         if (OBJ_sn2nid(alg) != NID_undef || OBJ_ln2nid(alg) != NID_undef) {
651             t->skip = 1;
652             return 1;
653         }
654         return 0;
655     }
656     mdat = OPENSSL_malloc(sizeof(*mdat));
657     mdat->digest = digest;
658     mdat->input = NULL;
659     mdat->output = NULL;
660     mdat->nrpt = 1;
661     t->data = mdat;
662     return 1;
663 }
664
665 static void digest_test_cleanup(struct evp_test *t)
666 {
667     struct digest_data *mdat = t->data;
668     test_free(mdat->input);
669     test_free(mdat->output);
670 }
671
672 static int digest_test_parse(struct evp_test *t,
673                              const char *keyword, const char *value)
674 {
675     struct digest_data *mdata = t->data;
676     if (strcmp(keyword, "Input") == 0)
677         return test_bin(value, &mdata->input, &mdata->input_len);
678     if (strcmp(keyword, "Output") == 0)
679         return test_bin(value, &mdata->output, &mdata->output_len);
680     if (strcmp(keyword, "Count") == 0) {
681         long nrpt = atoi(value);
682         if (nrpt <= 0)
683             return 0;
684         mdata->nrpt = (size_t)nrpt;
685         return 1;
686     }
687     return 0;
688 }
689
690 static int digest_test_run(struct evp_test *t)
691 {
692     struct digest_data *mdata = t->data;
693     size_t i;
694     const char *err = "INTERNAL_ERROR";
695     EVP_MD_CTX *mctx;
696     unsigned char md[EVP_MAX_MD_SIZE];
697     unsigned int md_len;
698     mctx = EVP_MD_CTX_new();
699     if (!mctx)
700         goto err;
701     err = "DIGESTINIT_ERROR";
702     if (!EVP_DigestInit_ex(mctx, mdata->digest, NULL))
703         goto err;
704     err = "DIGESTUPDATE_ERROR";
705     for (i = 0; i < mdata->nrpt; i++) {
706         if (!EVP_DigestUpdate(mctx, mdata->input, mdata->input_len))
707             goto err;
708     }
709     err = "DIGESTFINAL_ERROR";
710     if (!EVP_DigestFinal(mctx, md, &md_len))
711         goto err;
712     err = "DIGEST_LENGTH_MISMATCH";
713     if (md_len != mdata->output_len)
714         goto err;
715     err = "DIGEST_MISMATCH";
716     if (check_output(t, mdata->output, md, md_len))
717         goto err;
718     err = NULL;
719  err:
720     EVP_MD_CTX_free(mctx);
721     t->err = err;
722     return 1;
723 }
724
725 static const struct evp_test_method digest_test_method = {
726     "Digest",
727     digest_test_init,
728     digest_test_cleanup,
729     digest_test_parse,
730     digest_test_run
731 };
732
733 /* Cipher tests */
734 struct cipher_data {
735     const EVP_CIPHER *cipher;
736     int enc;
737     /* EVP_CIPH_GCM_MODE, EVP_CIPH_CCM_MODE or EVP_CIPH_OCB_MODE if AEAD */
738     int aead;
739     unsigned char *key;
740     size_t key_len;
741     unsigned char *iv;
742     size_t iv_len;
743     unsigned char *plaintext;
744     size_t plaintext_len;
745     unsigned char *ciphertext;
746     size_t ciphertext_len;
747     /* GCM, CCM only */
748     unsigned char *aad;
749     size_t aad_len;
750     unsigned char *tag;
751     size_t tag_len;
752 };
753
754 static int cipher_test_init(struct evp_test *t, const char *alg)
755 {
756     const EVP_CIPHER *cipher;
757     struct cipher_data *cdat = t->data;
758     cipher = EVP_get_cipherbyname(alg);
759     if (!cipher) {
760         /* If alg has an OID assume disabled algorithm */
761         if (OBJ_sn2nid(alg) != NID_undef || OBJ_ln2nid(alg) != NID_undef) {
762             t->skip = 1;
763             return 1;
764         }
765         return 0;
766     }
767     cdat = OPENSSL_malloc(sizeof(*cdat));
768     cdat->cipher = cipher;
769     cdat->enc = -1;
770     cdat->key = NULL;
771     cdat->iv = NULL;
772     cdat->ciphertext = NULL;
773     cdat->plaintext = NULL;
774     cdat->aad = NULL;
775     cdat->tag = NULL;
776     t->data = cdat;
777     if (EVP_CIPHER_mode(cipher) == EVP_CIPH_GCM_MODE
778         || EVP_CIPHER_mode(cipher) == EVP_CIPH_OCB_MODE
779         || EVP_CIPHER_mode(cipher) == EVP_CIPH_CCM_MODE)
780         cdat->aead = EVP_CIPHER_mode(cipher);
781     else if (EVP_CIPHER_flags(cipher) & EVP_CIPH_FLAG_AEAD_CIPHER)
782         cdat->aead = -1;
783     else
784         cdat->aead = 0;
785
786     return 1;
787 }
788
789 static void cipher_test_cleanup(struct evp_test *t)
790 {
791     struct cipher_data *cdat = t->data;
792     test_free(cdat->key);
793     test_free(cdat->iv);
794     test_free(cdat->ciphertext);
795     test_free(cdat->plaintext);
796     test_free(cdat->aad);
797     test_free(cdat->tag);
798 }
799
800 static int cipher_test_parse(struct evp_test *t, const char *keyword,
801                              const char *value)
802 {
803     struct cipher_data *cdat = t->data;
804     if (strcmp(keyword, "Key") == 0)
805         return test_bin(value, &cdat->key, &cdat->key_len);
806     if (strcmp(keyword, "IV") == 0)
807         return test_bin(value, &cdat->iv, &cdat->iv_len);
808     if (strcmp(keyword, "Plaintext") == 0)
809         return test_bin(value, &cdat->plaintext, &cdat->plaintext_len);
810     if (strcmp(keyword, "Ciphertext") == 0)
811         return test_bin(value, &cdat->ciphertext, &cdat->ciphertext_len);
812     if (cdat->aead) {
813         if (strcmp(keyword, "AAD") == 0)
814             return test_bin(value, &cdat->aad, &cdat->aad_len);
815         if (strcmp(keyword, "Tag") == 0)
816             return test_bin(value, &cdat->tag, &cdat->tag_len);
817     }
818
819     if (strcmp(keyword, "Operation") == 0) {
820         if (strcmp(value, "ENCRYPT") == 0)
821             cdat->enc = 1;
822         else if (strcmp(value, "DECRYPT") == 0)
823             cdat->enc = 0;
824         else
825             return 0;
826         return 1;
827     }
828     return 0;
829 }
830
831 static int cipher_test_enc(struct evp_test *t, int enc)
832 {
833     struct cipher_data *cdat = t->data;
834     unsigned char *in, *out, *tmp = NULL;
835     size_t in_len, out_len;
836     int tmplen, tmpflen;
837     EVP_CIPHER_CTX *ctx = NULL;
838     const char *err;
839     err = "INTERNAL_ERROR";
840     ctx = EVP_CIPHER_CTX_new();
841     if (!ctx)
842         goto err;
843     EVP_CIPHER_CTX_set_flags(ctx, EVP_CIPHER_CTX_FLAG_WRAP_ALLOW);
844     if (enc) {
845         in = cdat->plaintext;
846         in_len = cdat->plaintext_len;
847         out = cdat->ciphertext;
848         out_len = cdat->ciphertext_len;
849     } else {
850         in = cdat->ciphertext;
851         in_len = cdat->ciphertext_len;
852         out = cdat->plaintext;
853         out_len = cdat->plaintext_len;
854     }
855     tmp = OPENSSL_malloc(in_len + 2 * EVP_MAX_BLOCK_LENGTH);
856     if (!tmp)
857         goto err;
858     err = "CIPHERINIT_ERROR";
859     if (!EVP_CipherInit_ex(ctx, cdat->cipher, NULL, NULL, NULL, enc))
860         goto err;
861     err = "INVALID_IV_LENGTH";
862     if (cdat->iv) {
863         if (cdat->aead) {
864             if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_IVLEN,
865                                      cdat->iv_len, 0))
866                 goto err;
867         } else if (cdat->iv_len != (size_t)EVP_CIPHER_CTX_iv_length(ctx))
868             goto err;
869     }
870     if (cdat->aead) {
871         unsigned char *tag;
872         /*
873          * If encrypting or OCB just set tag length initially, otherwise
874          * set tag length and value.
875          */
876         if (enc || cdat->aead == EVP_CIPH_OCB_MODE) {
877             err = "TAG_LENGTH_SET_ERROR";
878             tag = NULL;
879         } else {
880             err = "TAG_SET_ERROR";
881             tag = cdat->tag;
882         }
883         if (tag || cdat->aead != EVP_CIPH_GCM_MODE) {
884             if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_TAG,
885                                      cdat->tag_len, tag))
886                 goto err;
887         }
888     }
889
890     err = "INVALID_KEY_LENGTH";
891     if (!EVP_CIPHER_CTX_set_key_length(ctx, cdat->key_len))
892         goto err;
893     err = "KEY_SET_ERROR";
894     if (!EVP_CipherInit_ex(ctx, NULL, NULL, cdat->key, cdat->iv, -1))
895         goto err;
896
897     if (!enc && cdat->aead == EVP_CIPH_OCB_MODE) {
898         if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_TAG,
899                                  cdat->tag_len, cdat->tag)) {
900             err = "TAG_SET_ERROR";
901             goto err;
902         }
903     }
904
905     if (cdat->aead == EVP_CIPH_CCM_MODE) {
906         if (!EVP_CipherUpdate(ctx, NULL, &tmplen, NULL, out_len)) {
907             err = "CCM_PLAINTEXT_LENGTH_SET_ERROR";
908             goto err;
909         }
910     }
911     if (cdat->aad) {
912         if (!EVP_CipherUpdate(ctx, NULL, &tmplen, cdat->aad, cdat->aad_len)) {
913             err = "AAD_SET_ERROR";
914             goto err;
915         }
916     }
917     EVP_CIPHER_CTX_set_padding(ctx, 0);
918     err = "CIPHERUPDATE_ERROR";
919     if (!EVP_CipherUpdate(ctx, tmp, &tmplen, in, in_len))
920         goto err;
921     if (cdat->aead == EVP_CIPH_CCM_MODE)
922         tmpflen = 0;
923     else {
924         err = "CIPHERFINAL_ERROR";
925         if (!EVP_CipherFinal_ex(ctx, tmp + tmplen, &tmpflen))
926             goto err;
927     }
928     err = "LENGTH_MISMATCH";
929     if (out_len != (size_t)(tmplen + tmpflen))
930         goto err;
931     err = "VALUE_MISMATCH";
932     if (check_output(t, out, tmp, out_len))
933         goto err;
934     if (enc && cdat->aead) {
935         unsigned char rtag[16];
936         if (cdat->tag_len > sizeof(rtag)) {
937             err = "TAG_LENGTH_INTERNAL_ERROR";
938             goto err;
939         }
940         if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_GET_TAG,
941                                  cdat->tag_len, rtag)) {
942             err = "TAG_RETRIEVE_ERROR";
943             goto err;
944         }
945         if (check_output(t, cdat->tag, rtag, cdat->tag_len)) {
946             err = "TAG_VALUE_MISMATCH";
947             goto err;
948         }
949     }
950     err = NULL;
951  err:
952     OPENSSL_free(tmp);
953     EVP_CIPHER_CTX_free(ctx);
954     t->err = err;
955     return err ? 0 : 1;
956 }
957
958 static int cipher_test_run(struct evp_test *t)
959 {
960     struct cipher_data *cdat = t->data;
961     int rv;
962     if (!cdat->key) {
963         t->err = "NO_KEY";
964         return 0;
965     }
966     if (!cdat->iv && EVP_CIPHER_iv_length(cdat->cipher)) {
967         /* IV is optional and usually omitted in wrap mode */
968         if (EVP_CIPHER_mode(cdat->cipher) != EVP_CIPH_WRAP_MODE) {
969             t->err = "NO_IV";
970             return 0;
971         }
972     }
973     if (cdat->aead && !cdat->tag) {
974         t->err = "NO_TAG";
975         return 0;
976     }
977     if (cdat->enc) {
978         rv = cipher_test_enc(t, 1);
979         /* Not fatal errors: return */
980         if (rv != 1) {
981             if (rv < 0)
982                 return 0;
983             return 1;
984         }
985     }
986     if (cdat->enc != 1) {
987         rv = cipher_test_enc(t, 0);
988         /* Not fatal errors: return */
989         if (rv != 1) {
990             if (rv < 0)
991                 return 0;
992             return 1;
993         }
994     }
995     return 1;
996 }
997
998 static const struct evp_test_method cipher_test_method = {
999     "Cipher",
1000     cipher_test_init,
1001     cipher_test_cleanup,
1002     cipher_test_parse,
1003     cipher_test_run
1004 };
1005
1006 struct mac_data {
1007     /* MAC type */
1008     int type;
1009     /* Algorithm string for this MAC */
1010     char *alg;
1011     /* MAC key */
1012     unsigned char *key;
1013     size_t key_len;
1014     /* Input to MAC */
1015     unsigned char *input;
1016     size_t input_len;
1017     /* Expected output */
1018     unsigned char *output;
1019     size_t output_len;
1020 };
1021
1022 static int mac_test_init(struct evp_test *t, const char *alg)
1023 {
1024     int type;
1025     struct mac_data *mdat;
1026     if (strcmp(alg, "HMAC") == 0)
1027         type = EVP_PKEY_HMAC;
1028     else if (strcmp(alg, "CMAC") == 0)
1029         type = EVP_PKEY_CMAC;
1030     else
1031         return 0;
1032
1033     mdat = OPENSSL_malloc(sizeof(*mdat));
1034     mdat->type = type;
1035     mdat->alg = NULL;
1036     mdat->key = NULL;
1037     mdat->input = NULL;
1038     mdat->output = NULL;
1039     t->data = mdat;
1040     return 1;
1041 }
1042
1043 static void mac_test_cleanup(struct evp_test *t)
1044 {
1045     struct mac_data *mdat = t->data;
1046     test_free(mdat->alg);
1047     test_free(mdat->key);
1048     test_free(mdat->input);
1049     test_free(mdat->output);
1050 }
1051
1052 static int mac_test_parse(struct evp_test *t,
1053                           const char *keyword, const char *value)
1054 {
1055     struct mac_data *mdata = t->data;
1056     if (strcmp(keyword, "Key") == 0)
1057         return test_bin(value, &mdata->key, &mdata->key_len);
1058     if (strcmp(keyword, "Algorithm") == 0) {
1059         mdata->alg = OPENSSL_strdup(value);
1060         if (!mdata->alg)
1061             return 0;
1062         return 1;
1063     }
1064     if (strcmp(keyword, "Input") == 0)
1065         return test_bin(value, &mdata->input, &mdata->input_len);
1066     if (strcmp(keyword, "Output") == 0)
1067         return test_bin(value, &mdata->output, &mdata->output_len);
1068     return 0;
1069 }
1070
1071 static int mac_test_run(struct evp_test *t)
1072 {
1073     struct mac_data *mdata = t->data;
1074     const char *err = "INTERNAL_ERROR";
1075     EVP_MD_CTX *mctx = NULL;
1076     EVP_PKEY_CTX *pctx = NULL, *genctx = NULL;
1077     EVP_PKEY *key = NULL;
1078     const EVP_MD *md = NULL;
1079     unsigned char *mac = NULL;
1080     size_t mac_len;
1081
1082     err = "MAC_PKEY_CTX_ERROR";
1083     genctx = EVP_PKEY_CTX_new_id(mdata->type, NULL);
1084     if (!genctx)
1085         goto err;
1086
1087     err = "MAC_KEYGEN_INIT_ERROR";
1088     if (EVP_PKEY_keygen_init(genctx) <= 0)
1089         goto err;
1090     if (mdata->type == EVP_PKEY_CMAC) {
1091         err = "MAC_ALGORITHM_SET_ERROR";
1092         if (EVP_PKEY_CTX_ctrl_str(genctx, "cipher", mdata->alg) <= 0)
1093             goto err;
1094     }
1095
1096     err = "MAC_KEY_SET_ERROR";
1097     if (EVP_PKEY_CTX_set_mac_key(genctx, mdata->key, mdata->key_len) <= 0)
1098         goto err;
1099
1100     err = "MAC_KEY_GENERATE_ERROR";
1101     if (EVP_PKEY_keygen(genctx, &key) <= 0)
1102         goto err;
1103     if (mdata->type == EVP_PKEY_HMAC) {
1104         err = "MAC_ALGORITHM_SET_ERROR";
1105         md = EVP_get_digestbyname(mdata->alg);
1106         if (!md)
1107             goto err;
1108     }
1109     mctx = EVP_MD_CTX_new();
1110     if (!mctx)
1111         goto err;
1112     err = "DIGESTSIGNINIT_ERROR";
1113     if (!EVP_DigestSignInit(mctx, &pctx, md, NULL, key))
1114         goto err;
1115
1116     err = "DIGESTSIGNUPDATE_ERROR";
1117     if (!EVP_DigestSignUpdate(mctx, mdata->input, mdata->input_len))
1118         goto err;
1119     err = "DIGESTSIGNFINAL_LENGTH_ERROR";
1120     if (!EVP_DigestSignFinal(mctx, NULL, &mac_len))
1121         goto err;
1122     mac = OPENSSL_malloc(mac_len);
1123     if (!mac) {
1124         fprintf(stderr, "Error allocating mac buffer!\n");
1125         exit(1);
1126     }
1127     if (!EVP_DigestSignFinal(mctx, mac, &mac_len))
1128         goto err;
1129     err = "MAC_LENGTH_MISMATCH";
1130     if (mac_len != mdata->output_len)
1131         goto err;
1132     err = "MAC_MISMATCH";
1133     if (check_output(t, mdata->output, mac, mac_len))
1134         goto err;
1135     err = NULL;
1136  err:
1137     EVP_MD_CTX_free(mctx);
1138     OPENSSL_free(mac);
1139     EVP_PKEY_CTX_free(genctx);
1140     EVP_PKEY_free(key);
1141     t->err = err;
1142     return 1;
1143 }
1144
1145 static const struct evp_test_method mac_test_method = {
1146     "MAC",
1147     mac_test_init,
1148     mac_test_cleanup,
1149     mac_test_parse,
1150     mac_test_run
1151 };
1152
1153 /*
1154  * Public key operations. These are all very similar and can share
1155  * a lot of common code.
1156  */
1157
1158 struct pkey_data {
1159     /* Context for this operation */
1160     EVP_PKEY_CTX *ctx;
1161     /* Key operation to perform */
1162     int (*keyop) (EVP_PKEY_CTX *ctx,
1163                   unsigned char *sig, size_t *siglen,
1164                   const unsigned char *tbs, size_t tbslen);
1165     /* Input to MAC */
1166     unsigned char *input;
1167     size_t input_len;
1168     /* Expected output */
1169     unsigned char *output;
1170     size_t output_len;
1171 };
1172
1173 /*
1174  * Perform public key operation setup: lookup key, allocated ctx and call
1175  * the appropriate initialisation function
1176  */
1177 static int pkey_test_init(struct evp_test *t, const char *name,
1178                           int use_public,
1179                           int (*keyopinit) (EVP_PKEY_CTX *ctx),
1180                           int (*keyop) (EVP_PKEY_CTX *ctx,
1181                                         unsigned char *sig, size_t *siglen,
1182                                         const unsigned char *tbs,
1183                                         size_t tbslen)
1184     )
1185 {
1186     struct pkey_data *kdata;
1187     EVP_PKEY *pkey = NULL;
1188     int rv = 0;
1189     if (use_public)
1190         rv = find_key(&pkey, name, t->public);
1191     if (!rv)
1192         rv = find_key(&pkey, name, t->private);
1193     if (!rv)
1194         return 0;
1195     if (!pkey) {
1196         t->skip = 1;
1197         return 1;
1198     }
1199
1200     kdata = OPENSSL_malloc(sizeof(*kdata));
1201     if (!kdata) {
1202         EVP_PKEY_free(pkey);
1203         return 0;
1204     }
1205     kdata->ctx = NULL;
1206     kdata->input = NULL;
1207     kdata->output = NULL;
1208     kdata->keyop = keyop;
1209     t->data = kdata;
1210     kdata->ctx = EVP_PKEY_CTX_new(pkey, NULL);
1211     if (!kdata->ctx)
1212         return 0;
1213     if (keyopinit(kdata->ctx) <= 0)
1214         return 0;
1215     return 1;
1216 }
1217
1218 static void pkey_test_cleanup(struct evp_test *t)
1219 {
1220     struct pkey_data *kdata = t->data;
1221
1222     OPENSSL_free(kdata->input);
1223     OPENSSL_free(kdata->output);
1224     EVP_PKEY_CTX_free(kdata->ctx);
1225 }
1226
1227 static int pkey_test_parse(struct evp_test *t,
1228                            const char *keyword, const char *value)
1229 {
1230     struct pkey_data *kdata = t->data;
1231     if (strcmp(keyword, "Input") == 0)
1232         return test_bin(value, &kdata->input, &kdata->input_len);
1233     if (strcmp(keyword, "Output") == 0)
1234         return test_bin(value, &kdata->output, &kdata->output_len);
1235     if (strcmp(keyword, "Ctrl") == 0) {
1236         char *p = strchr(value, ':');
1237         if (p)
1238             *p++ = 0;
1239         if (EVP_PKEY_CTX_ctrl_str(kdata->ctx, value, p) <= 0)
1240             return 0;
1241         return 1;
1242     }
1243     return 0;
1244 }
1245
1246 static int pkey_test_run(struct evp_test *t)
1247 {
1248     struct pkey_data *kdata = t->data;
1249     unsigned char *out = NULL;
1250     size_t out_len;
1251     const char *err = "KEYOP_LENGTH_ERROR";
1252     if (kdata->keyop(kdata->ctx, NULL, &out_len, kdata->input,
1253                      kdata->input_len) <= 0)
1254         goto err;
1255     out = OPENSSL_malloc(out_len);
1256     if (!out) {
1257         fprintf(stderr, "Error allocating output buffer!\n");
1258         exit(1);
1259     }
1260     err = "KEYOP_ERROR";
1261     if (kdata->keyop
1262         (kdata->ctx, out, &out_len, kdata->input, kdata->input_len) <= 0)
1263         goto err;
1264     err = "KEYOP_LENGTH_MISMATCH";
1265     if (out_len != kdata->output_len)
1266         goto err;
1267     err = "KEYOP_MISMATCH";
1268     if (check_output(t, kdata->output, out, out_len))
1269         goto err;
1270     err = NULL;
1271  err:
1272     OPENSSL_free(out);
1273     t->err = err;
1274     return 1;
1275 }
1276
1277 static int sign_test_init(struct evp_test *t, const char *name)
1278 {
1279     return pkey_test_init(t, name, 0, EVP_PKEY_sign_init, EVP_PKEY_sign);
1280 }
1281
1282 static const struct evp_test_method psign_test_method = {
1283     "Sign",
1284     sign_test_init,
1285     pkey_test_cleanup,
1286     pkey_test_parse,
1287     pkey_test_run
1288 };
1289
1290 static int verify_recover_test_init(struct evp_test *t, const char *name)
1291 {
1292     return pkey_test_init(t, name, 1, EVP_PKEY_verify_recover_init,
1293                           EVP_PKEY_verify_recover);
1294 }
1295
1296 static const struct evp_test_method pverify_recover_test_method = {
1297     "VerifyRecover",
1298     verify_recover_test_init,
1299     pkey_test_cleanup,
1300     pkey_test_parse,
1301     pkey_test_run
1302 };
1303
1304 static int decrypt_test_init(struct evp_test *t, const char *name)
1305 {
1306     return pkey_test_init(t, name, 0, EVP_PKEY_decrypt_init,
1307                           EVP_PKEY_decrypt);
1308 }
1309
1310 static const struct evp_test_method pdecrypt_test_method = {
1311     "Decrypt",
1312     decrypt_test_init,
1313     pkey_test_cleanup,
1314     pkey_test_parse,
1315     pkey_test_run
1316 };
1317
1318 static int verify_test_init(struct evp_test *t, const char *name)
1319 {
1320     return pkey_test_init(t, name, 1, EVP_PKEY_verify_init, 0);
1321 }
1322
1323 static int verify_test_run(struct evp_test *t)
1324 {
1325     struct pkey_data *kdata = t->data;
1326     if (EVP_PKEY_verify(kdata->ctx, kdata->output, kdata->output_len,
1327                         kdata->input, kdata->input_len) <= 0)
1328         t->err = "VERIFY_ERROR";
1329     return 1;
1330 }
1331
1332 static const struct evp_test_method pverify_test_method = {
1333     "Verify",
1334     verify_test_init,
1335     pkey_test_cleanup,
1336     pkey_test_parse,
1337     verify_test_run
1338 };
1339
1340 /* PBE tests */
1341
1342 #define PBE_TYPE_SCRYPT 1
1343 #define PBE_TYPE_PBKDF2 2
1344 #define PBE_TYPE_PKCS12 3
1345
1346 struct pbe_data {
1347
1348     int pbe_type;
1349
1350     /* scrypt parameters */
1351     uint64_t N, r, p, maxmem;
1352
1353     /* PKCS#12 parameters */
1354     int id, iter;
1355     const EVP_MD *md;
1356
1357     /* password */
1358     unsigned char *pass;
1359     size_t pass_len;
1360
1361     /* salt */
1362     unsigned char *salt;
1363     size_t salt_len;
1364
1365     /* Expected output */
1366     unsigned char *key;
1367     size_t key_len;
1368 };
1369
1370 #ifndef OPENSSL_NO_SCRYPT
1371 static int scrypt_test_parse(struct evp_test *t,
1372                              const char *keyword, const char *value)
1373 {
1374     struct pbe_data *pdata = t->data;
1375
1376     if (strcmp(keyword, "N") == 0)
1377         return test_uint64(value, &pdata->N);
1378     if (strcmp(keyword, "p") == 0)
1379         return test_uint64(value, &pdata->p);
1380     if (strcmp(keyword, "r") == 0)
1381         return test_uint64(value, &pdata->r);
1382     if (strcmp(keyword, "maxmem") == 0)
1383         return test_uint64(value, &pdata->maxmem);
1384     return 0;
1385 }
1386 #endif
1387
1388 static int pbkdf2_test_parse(struct evp_test *t,
1389                              const char *keyword, const char *value)
1390 {
1391     struct pbe_data *pdata = t->data;
1392
1393     if (strcmp(keyword, "iter") == 0) {
1394         pdata->iter = atoi(value);
1395         if (pdata->iter <= 0)
1396             return 0;
1397         return 1;
1398     }
1399     if (strcmp(keyword, "MD") == 0) {
1400         pdata->md = EVP_get_digestbyname(value);
1401         if (pdata->md == NULL)
1402             return 0;
1403         return 1;
1404     }
1405     return 0;
1406 }
1407
1408 static int pkcs12_test_parse(struct evp_test *t,
1409                              const char *keyword, const char *value)
1410 {
1411     struct pbe_data *pdata = t->data;
1412
1413     if (strcmp(keyword, "id") == 0) {
1414         pdata->id = atoi(value);
1415         if (pdata->id <= 0)
1416             return 0;
1417         return 1;
1418     }
1419     return pbkdf2_test_parse(t, keyword, value);
1420 }
1421
1422 static int pbe_test_init(struct evp_test *t, const char *alg)
1423 {
1424     struct pbe_data *pdat;
1425     int pbe_type = 0;
1426
1427 #ifndef OPENSSL_NO_SCRYPT
1428     if (strcmp(alg, "scrypt") == 0)
1429         pbe_type = PBE_TYPE_SCRYPT;
1430 #endif
1431     else if (strcmp(alg, "pbkdf2") == 0)
1432         pbe_type = PBE_TYPE_PBKDF2;
1433     else if (strcmp(alg, "pkcs12") == 0)
1434         pbe_type = PBE_TYPE_PKCS12;
1435     else
1436         fprintf(stderr, "Unknown pbe algorithm %s\n", alg);
1437     pdat = OPENSSL_malloc(sizeof(*pdat));
1438     pdat->pbe_type = pbe_type;
1439     pdat->pass = NULL;
1440     pdat->salt = NULL;
1441     pdat->N = 0;
1442     pdat->r = 0;
1443     pdat->p = 0;
1444     pdat->maxmem = 0;
1445     pdat->id = 0;
1446     pdat->iter = 0;
1447     pdat->md = NULL;
1448     t->data = pdat;
1449     return 1;
1450 }
1451
1452 static void pbe_test_cleanup(struct evp_test *t)
1453 {
1454     struct pbe_data *pdat = t->data;
1455     test_free(pdat->pass);
1456     test_free(pdat->salt);
1457     test_free(pdat->key);
1458 }
1459
1460 static int pbe_test_parse(struct evp_test *t,
1461                              const char *keyword, const char *value)
1462 {
1463     struct pbe_data *pdata = t->data;
1464
1465     if (strcmp(keyword, "Password") == 0)
1466         return test_bin(value, &pdata->pass, &pdata->pass_len);
1467     if (strcmp(keyword, "Salt") == 0)
1468         return test_bin(value, &pdata->salt, &pdata->salt_len);
1469     if (strcmp(keyword, "Key") == 0)
1470         return test_bin(value, &pdata->key, &pdata->key_len);
1471     if (pdata->pbe_type == PBE_TYPE_PBKDF2)
1472         return pbkdf2_test_parse(t, keyword, value);
1473     else if (pdata->pbe_type == PBE_TYPE_PKCS12)
1474         return pkcs12_test_parse(t, keyword, value);
1475 #ifndef OPENSSL_NO_SCRYPT
1476     else if (pdata->pbe_type == PBE_TYPE_SCRYPT)
1477         return scrypt_test_parse(t, keyword, value);
1478 #endif
1479     return 0;
1480 }
1481
1482 static int pbe_test_run(struct evp_test *t)
1483 {
1484     struct pbe_data *pdata = t->data;
1485     const char *err = "INTERNAL_ERROR";
1486     unsigned char *key;
1487
1488     key = OPENSSL_malloc(pdata->key_len);
1489     if (!key)
1490         goto err;
1491     if (pdata->pbe_type == PBE_TYPE_PBKDF2) {
1492         err = "PBKDF2_ERROR";
1493         if (PKCS5_PBKDF2_HMAC((char *)pdata->pass, pdata->pass_len,
1494                               pdata->salt, pdata->salt_len,
1495                               pdata->iter, pdata->md,
1496                               pdata->key_len, key) == 0)
1497             goto err;
1498 #ifndef OPENSSL_NO_SCRYPT
1499     } else if (pdata->pbe_type == PBE_TYPE_SCRYPT) {
1500         err = "SCRYPT_ERROR";
1501         if (EVP_PBE_scrypt((const char *)pdata->pass, pdata->pass_len,
1502                            pdata->salt, pdata->salt_len,
1503                            pdata->N, pdata->r, pdata->p, pdata->maxmem,
1504                            key, pdata->key_len) == 0)
1505             goto err;
1506 #endif
1507     } else if (pdata->pbe_type == PBE_TYPE_PKCS12) {
1508         err = "PKCS12_ERROR";
1509         if (PKCS12_key_gen_uni(pdata->pass, pdata->pass_len,
1510                                pdata->salt, pdata->salt_len,
1511                                pdata->id, pdata->iter, pdata->key_len,
1512                                key, pdata->md) == 0)
1513             goto err;
1514     }
1515     err = "KEY_MISMATCH";
1516     if (check_output(t, pdata->key, key, pdata->key_len))
1517         goto err;
1518     err = NULL;
1519     err:
1520     OPENSSL_free(key);
1521     t->err = err;
1522     return 1;
1523 }
1524
1525 static const struct evp_test_method pbe_test_method = {
1526     "PBE",
1527     pbe_test_init,
1528     pbe_test_cleanup,
1529     pbe_test_parse,
1530     pbe_test_run
1531 };
1532
1533 /* Base64 tests */
1534
1535 typedef enum {
1536     BASE64_CANONICAL_ENCODING = 0,
1537     BASE64_VALID_ENCODING = 1,
1538     BASE64_INVALID_ENCODING = 2
1539 } base64_encoding_type;
1540
1541 struct encode_data {
1542     /* Input to encoding */
1543     unsigned char *input;
1544     size_t input_len;
1545     /* Expected output */
1546     unsigned char *output;
1547     size_t output_len;
1548     base64_encoding_type encoding;
1549 };
1550
1551 static int encode_test_init(struct evp_test *t, const char *encoding)
1552 {
1553     struct encode_data *edata = OPENSSL_zalloc(sizeof(*edata));
1554
1555     if (strcmp(encoding, "canonical") == 0) {
1556         edata->encoding = BASE64_CANONICAL_ENCODING;
1557     } else if (strcmp(encoding, "valid") == 0) {
1558         edata->encoding = BASE64_VALID_ENCODING;
1559     } else if (strcmp(encoding, "invalid") == 0) {
1560         edata->encoding = BASE64_INVALID_ENCODING;
1561         t->expected_err = OPENSSL_strdup("DECODE_ERROR");
1562         if (t->expected_err == NULL)
1563             return 0;
1564     } else {
1565         fprintf(stderr, "Bad encoding: %s. Should be one of "
1566                 "{canonical, valid, invalid}\n", encoding);
1567         return 0;
1568     }
1569     t->data = edata;
1570     return 1;
1571 }
1572
1573 static void encode_test_cleanup(struct evp_test *t)
1574 {
1575     struct encode_data *edata = t->data;
1576     test_free(edata->input);
1577     test_free(edata->output);
1578     memset(edata, 0, sizeof(*edata));
1579 }
1580
1581 static int encode_test_parse(struct evp_test *t,
1582                              const char *keyword, const char *value)
1583 {
1584     struct encode_data *edata = t->data;
1585     if (strcmp(keyword, "Input") == 0)
1586         return test_bin(value, &edata->input, &edata->input_len);
1587     if (strcmp(keyword, "Output") == 0)
1588         return test_bin(value, &edata->output, &edata->output_len);
1589     return 0;
1590 }
1591
1592 static int encode_test_run(struct evp_test *t)
1593 {
1594     struct encode_data *edata = t->data;
1595     unsigned char *encode_out = NULL, *decode_out = NULL;
1596     int output_len, chunk_len;
1597     const char *err = "INTERNAL_ERROR";
1598     EVP_ENCODE_CTX *decode_ctx = EVP_ENCODE_CTX_new();
1599
1600     if (decode_ctx == NULL)
1601         goto err;
1602
1603     if (edata->encoding == BASE64_CANONICAL_ENCODING) {
1604         EVP_ENCODE_CTX *encode_ctx = EVP_ENCODE_CTX_new();
1605         if (encode_ctx == NULL)
1606             goto err;
1607         encode_out = OPENSSL_malloc(EVP_ENCODE_LENGTH(edata->input_len));
1608         if (encode_out == NULL)
1609             goto err;
1610
1611         EVP_EncodeInit(encode_ctx);
1612         EVP_EncodeUpdate(encode_ctx, encode_out, &chunk_len,
1613                          edata->input, edata->input_len);
1614         output_len = chunk_len;
1615
1616         EVP_EncodeFinal(encode_ctx, encode_out + chunk_len, &chunk_len);
1617         output_len += chunk_len;
1618
1619         EVP_ENCODE_CTX_free(encode_ctx);
1620
1621         if (check_var_length_output(t, edata->output, edata->output_len,
1622                                     encode_out, output_len)) {
1623             err = "BAD_ENCODING";
1624             goto err;
1625         }
1626     }
1627
1628     decode_out = OPENSSL_malloc(EVP_DECODE_LENGTH(edata->output_len));
1629     if (decode_out == NULL)
1630         goto err;
1631
1632     EVP_DecodeInit(decode_ctx);
1633     if (EVP_DecodeUpdate(decode_ctx, decode_out, &chunk_len, edata->output,
1634                          edata->output_len) < 0) {
1635         err = "DECODE_ERROR";
1636         goto err;
1637     }
1638     output_len = chunk_len;
1639
1640     if (EVP_DecodeFinal(decode_ctx, decode_out + chunk_len, &chunk_len) != 1) {
1641         err = "DECODE_ERROR";
1642         goto err;
1643     }
1644     output_len += chunk_len;
1645
1646     if (edata->encoding != BASE64_INVALID_ENCODING &&
1647         check_var_length_output(t, edata->input, edata->input_len,
1648                                 decode_out, output_len)) {
1649         err = "BAD_DECODING";
1650         goto err;
1651     }
1652
1653     err = NULL;
1654  err:
1655     t->err = err;
1656     OPENSSL_free(encode_out);
1657     OPENSSL_free(decode_out);
1658     EVP_ENCODE_CTX_free(decode_ctx);
1659     return 1;
1660 }
1661
1662 static const struct evp_test_method encode_test_method = {
1663     "Encoding",
1664     encode_test_init,
1665     encode_test_cleanup,
1666     encode_test_parse,
1667     encode_test_run,
1668 };
1669
1670 /*
1671  * KDF operations: initially just TLS1 PRF but can be adapted.
1672  */
1673
1674 struct kdf_data {
1675     /* Context for this operation */
1676     EVP_PKEY_CTX *ctx;
1677     /* Expected output */
1678     unsigned char *output;
1679     size_t output_len;
1680 };
1681
1682 /*
1683  * Perform public key operation setup: lookup key, allocated ctx and call
1684  * the appropriate initialisation function
1685  */
1686 static int kdf_test_init(struct evp_test *t, const char *name)
1687 {
1688     struct kdf_data *kdata;
1689
1690     kdata = OPENSSL_malloc(sizeof(*kdata));
1691     if (kdata == NULL)
1692         return 0;
1693     kdata->ctx = NULL;
1694     kdata->output = NULL;
1695     t->data = kdata;
1696     kdata->ctx = EVP_PKEY_CTX_new_id(OBJ_sn2nid(name), NULL);
1697     if (kdata->ctx == NULL)
1698         return 0;
1699     if (EVP_PKEY_derive_init(kdata->ctx) <= 0)
1700         return 0;
1701     return 1;
1702 }
1703
1704 static void kdf_test_cleanup(struct evp_test *t)
1705 {
1706     struct kdf_data *kdata = t->data;
1707     OPENSSL_free(kdata->output);
1708     EVP_PKEY_CTX_free(kdata->ctx);
1709 }
1710
1711 static int kdf_ctrl(EVP_PKEY_CTX *ctx, int op, const char *value)
1712 {
1713     unsigned char *buf = NULL;
1714     size_t buf_len;
1715     int rv = 0;
1716     if (test_bin(value, &buf, &buf_len) == 0)
1717         return 0;
1718     if (EVP_PKEY_CTX_ctrl(ctx, -1, -1, op, buf_len, buf) <= 0)
1719         goto err;
1720     rv = 1;
1721     err:
1722     OPENSSL_free(buf);
1723     return rv;
1724 }
1725
1726 static int kdf_test_parse(struct evp_test *t,
1727                           const char *keyword, const char *value)
1728 {
1729     struct kdf_data *kdata = t->data;
1730     if (strcmp(keyword, "Output") == 0)
1731         return test_bin(value, &kdata->output, &kdata->output_len);
1732     else if (strcmp(keyword, "MD") == 0) {
1733         const EVP_MD *md = EVP_get_digestbyname(value);
1734         if (md == NULL)
1735             return 0;
1736         if (EVP_PKEY_CTX_set_tls1_prf_md(kdata->ctx, md) <= 0)
1737             return 0;
1738         return 1;
1739     } else if (strcmp(keyword, "Secret") == 0) {
1740         return kdf_ctrl(kdata->ctx, EVP_PKEY_CTRL_TLS_SECRET, value);
1741     } else if (strncmp("Seed", keyword, 4) == 0) {
1742         return kdf_ctrl(kdata->ctx, EVP_PKEY_CTRL_TLS_SEED, value);
1743     }
1744     return 0;
1745 }
1746
1747 static int kdf_test_run(struct evp_test *t)
1748 {
1749     struct kdf_data *kdata = t->data;
1750     unsigned char *out = NULL;
1751     size_t out_len = kdata->output_len;
1752     const char *err = "INTERNAL_ERROR";
1753     out = OPENSSL_malloc(out_len);
1754     if (!out) {
1755         fprintf(stderr, "Error allocating output buffer!\n");
1756         exit(1);
1757     }
1758     err = "KDF_DERIVE_ERROR";
1759     if (EVP_PKEY_derive(kdata->ctx, out, &out_len) <= 0)
1760         goto err;
1761     err = "KDF_LENGTH_MISMATCH";
1762     if (out_len != kdata->output_len)
1763         goto err;
1764     err = "KDF_MISMATCH";
1765     if (check_output(t, kdata->output, out, out_len))
1766         goto err;
1767     err = NULL;
1768  err:
1769     OPENSSL_free(out);
1770     t->err = err;
1771     return 1;
1772 }
1773
1774 static const struct evp_test_method kdf_test_method = {
1775     "KDF",
1776     kdf_test_init,
1777     kdf_test_cleanup,
1778     kdf_test_parse,
1779     kdf_test_run
1780 };