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