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