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