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