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