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