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