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