Add OCB support and test vectors for evp_test.
[openssl.git] / crypto / evp / 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
64 /* Remove spaces from beginning and end of a string */
65
66 static void remove_space(char **pval)
67 {
68     unsigned char *p = (unsigned char *)*pval;
69
70     while (isspace(*p))
71         p++;
72
73     *pval = (char *)p;
74
75     p = p + strlen(*pval) - 1;
76
77     /* Remove trailing space */
78     while (isspace(*p))
79         *p-- = 0;
80 }
81
82 /*
83  * Given a line of the form:
84  *      name = value # comment
85  * extract name and value. NB: modifies passed buffer.
86  */
87
88 static int parse_line(char **pkw, char **pval, char *linebuf)
89 {
90     char *p;
91
92     p = linebuf + strlen(linebuf) - 1;
93
94     if (*p != '\n') {
95         fprintf(stderr, "FATAL: missing EOL\n");
96         exit(1);
97     }
98
99     /* Look for # */
100
101     p = strchr(linebuf, '#');
102
103     if (p)
104         *p = '\0';
105
106     /* Look for = sign */
107     p = strchr(linebuf, '=');
108
109     /* If no '=' exit */
110     if (!p)
111         return 0;
112
113     *p++ = '\0';
114
115     *pkw = linebuf;
116     *pval = p;
117
118     /* Remove spaces from keyword and value */
119     remove_space(pkw);
120     remove_space(pval);
121
122     return 1;
123 }
124
125 /* For a hex string "value" convert to a binary allocated buffer */
126 static int test_bin(const char *value, unsigned char **buf, size_t *buflen)
127 {
128     long len;
129     if (!*value) {
130         /* Don't return NULL for zero length buffer */
131         *buf = OPENSSL_malloc(1);
132         if (!*buf)
133             return 0;
134         **buf = 0;
135         *buflen = 0;
136         return 1;
137     }
138     /* Check for string literal */
139     if (value[0] == '"') {
140         size_t vlen;
141         value++;
142         vlen = strlen(value);
143         if (value[vlen - 1] != '"')
144             return 0;
145         vlen--;
146         *buf = BUF_memdup(value, vlen);
147         *buflen = vlen;
148         return 1;
149     }
150     *buf = string_to_hex(value, &len);
151     if (!*buf) {
152         fprintf(stderr, "Value=%s\n", value);
153         ERR_print_errors_fp(stderr);
154         return -1;
155     }
156     /* Size of input buffer means we'll never overflow */
157     *buflen = len;
158     return 1;
159 }
160
161 /* Structure holding test information */
162 struct evp_test {
163     /* file being read */
164     FILE *in;
165     /* List of public and private keys */
166     struct key_list *private;
167     struct key_list *public;
168     /* method for this test */
169     const struct evp_test_method *meth;
170     /* current line being processed */
171     unsigned int line;
172     /* start line of current test */
173     unsigned int start_line;
174     /* Error string for test */
175     const char *err;
176     /* Expected error value of test */
177     char *expected_err;
178     /* Number of tests */
179     int ntests;
180     /* Error count */
181     int errors;
182     /* Number of tests skipped */
183     int nskip;
184     /* If output mismatch expected and got value */
185     unsigned char *out_got;
186     unsigned char *out_expected;
187     size_t out_len;
188     /* test specific data */
189     void *data;
190     /* Current test should be skipped */
191     int skip;
192 };
193
194 struct key_list {
195     char *name;
196     EVP_PKEY *key;
197     struct key_list *next;
198 };
199
200 /* Test method structure */
201 struct evp_test_method {
202     /* Name of test as it appears in file */
203     const char *name;
204     /* Initialise test for "alg" */
205     int (*init) (struct evp_test * t, const char *alg);
206     /* Clean up method */
207     void (*cleanup) (struct evp_test * t);
208     /* Test specific name value pair processing */
209     int (*parse) (struct evp_test * t, const char *name, const char *value);
210     /* Run the test itself */
211     int (*run_test) (struct evp_test * t);
212 };
213
214 static const struct evp_test_method digest_test_method, cipher_test_method;
215 static const struct evp_test_method mac_test_method;
216 static const struct evp_test_method psign_test_method, pverify_test_method;
217 static const struct evp_test_method pdecrypt_test_method;
218 static const struct evp_test_method pverify_recover_test_method;
219
220 static const struct evp_test_method *evp_test_list[] = {
221     &digest_test_method,
222     &cipher_test_method,
223     &mac_test_method,
224     &psign_test_method,
225     &pverify_test_method,
226     &pdecrypt_test_method,
227     &pverify_recover_test_method,
228     NULL
229 };
230
231 static const struct evp_test_method *evp_find_test(const char *name)
232 {
233     const struct evp_test_method **tt;
234     for (tt = evp_test_list; *tt; tt++) {
235         if (!strcmp(name, (*tt)->name))
236             return *tt;
237     }
238     return NULL;
239 }
240
241 static void hex_print(const char *name, const unsigned char *buf, size_t len)
242 {
243     size_t i;
244     fprintf(stderr, "%s ", name);
245     for (i = 0; i < len; i++)
246         fprintf(stderr, "%02X", buf[i]);
247     fputs("\n", stderr);
248 }
249
250 static void print_expected(struct evp_test *t)
251 {
252     if (t->out_expected == NULL)
253         return;
254     hex_print("Expected:", t->out_expected, t->out_len);
255     hex_print("Got:     ", t->out_got, t->out_len);
256     OPENSSL_free(t->out_expected);
257     OPENSSL_free(t->out_got);
258     t->out_expected = NULL;
259     t->out_got = NULL;
260 }
261
262 static int check_test_error(struct evp_test *t)
263 {
264     if (!t->err && !t->expected_err)
265         return 1;
266     if (t->err && !t->expected_err) {
267         fprintf(stderr, "Test line %d: unexpected error %s\n",
268                 t->start_line, t->err);
269         print_expected(t);
270         return 0;
271     }
272     if (!t->err && t->expected_err) {
273         fprintf(stderr, "Test line %d: succeeded expecting %s\n",
274                 t->start_line, t->expected_err);
275         return 0;
276     }
277     if (!strcmp(t->err, t->expected_err))
278         return 1;
279
280     fprintf(stderr, "Test line %d: expecting %s got %s\n",
281             t->start_line, t->expected_err, t->err);
282     return 0;
283 }
284
285 /* Setup a new test, run any existing test */
286
287 static int setup_test(struct evp_test *t, const struct evp_test_method *tmeth)
288 {
289     /* If we already have a test set up run it */
290     if (t->meth) {
291         t->ntests++;
292         if (t->skip) {
293             t->meth = tmeth;
294             t->nskip++;
295             return 1;
296         }
297         t->err = NULL;
298         if (t->meth->run_test(t) != 1) {
299             fprintf(stderr, "%s test error line %d\n",
300                     t->meth->name, t->start_line);
301             return 0;
302         }
303         if (!check_test_error(t)) {
304             if (t->err)
305                 ERR_print_errors_fp(stderr);
306             t->errors++;
307         }
308         ERR_clear_error();
309         t->meth->cleanup(t);
310         OPENSSL_free(t->data);
311         t->data = NULL;
312         if (t->expected_err) {
313             OPENSSL_free(t->expected_err);
314             t->expected_err = NULL;
315         }
316     }
317     t->meth = tmeth;
318     return 1;
319 }
320
321 static int find_key(EVP_PKEY **ppk, const char *name, struct key_list *lst)
322 {
323     for (; lst; lst = lst->next) {
324         if (!strcmp(lst->name, name)) {
325             if (ppk)
326                 *ppk = lst->key;
327             return 1;
328         }
329     }
330     return 0;
331 }
332
333 static void free_key_list(struct key_list *lst)
334 {
335     while (lst != NULL) {
336         struct key_list *ltmp;
337         EVP_PKEY_free(lst->key);
338         OPENSSL_free(lst->name);
339         ltmp = lst->next;
340         OPENSSL_free(lst);
341         lst = ltmp;
342     }
343 }
344
345 static int check_unsupported()
346 {
347     long err = ERR_peek_error();
348     if (ERR_GET_LIB(err) == ERR_LIB_EVP
349          && ERR_GET_REASON(err) == EVP_R_UNSUPPORTED_ALGORITHM) {
350         ERR_clear_error();
351         return 1;
352     }
353     return 0;
354 }
355
356 static int process_test(struct evp_test *t, char *buf, int verbose)
357 {
358     char *keyword, *value;
359     int rv = 0, add_key = 0;
360     long save_pos;
361     struct key_list **lst, *key;
362     EVP_PKEY *pk = NULL;
363     const struct evp_test_method *tmeth;
364     if (verbose)
365         fputs(buf, stdout);
366     if (!parse_line(&keyword, &value, buf))
367         return 1;
368     if (!strcmp(keyword, "PrivateKey")) {
369         save_pos = ftell(t->in);
370         pk = PEM_read_PrivateKey(t->in, NULL, 0, NULL);
371         if (pk == NULL && !check_unsupported()) {
372             fprintf(stderr, "Error reading private key %s\n", value);
373             ERR_print_errors_fp(stderr);
374             return 0;
375         }
376         lst = &t->private;
377         add_key = 1;
378     }
379     if (!strcmp(keyword, "PublicKey")) {
380         save_pos = ftell(t->in);
381         pk = PEM_read_PUBKEY(t->in, NULL, 0, NULL);
382         if (pk == NULL && !check_unsupported()) {
383             fprintf(stderr, "Error reading public key %s\n", value);
384             ERR_print_errors_fp(stderr);
385             return 0;
386         }
387         lst = &t->public;
388         add_key = 1;
389     }
390     /* If we have a key add to list */
391     if (add_key) {
392         char tmpbuf[80];
393         if (find_key(NULL, value, *lst)) {
394             fprintf(stderr, "Duplicate key %s\n", value);
395             return 0;
396         }
397         key = OPENSSL_malloc(sizeof(struct key_list));
398         if (!key)
399             return 0;
400         key->name = BUF_strdup(value);
401         key->key = pk;
402         key->next = *lst;
403         *lst = key;
404         /* Rewind input, read to end and update line numbers */
405         fseek(t->in, save_pos, SEEK_SET);
406         while (fgets(tmpbuf, sizeof(tmpbuf), t->in)) {
407             t->line++;
408             if (!strncmp(tmpbuf, "-----END", 8))
409                 return 1;
410         }
411         fprintf(stderr, "Can't find key end\n");
412         return 0;
413     }
414
415     /* See if keyword corresponds to a test start */
416     tmeth = evp_find_test(keyword);
417     if (tmeth) {
418         if (!setup_test(t, tmeth))
419             return 0;
420         t->start_line = t->line;
421         t->skip = 0;
422         if (!tmeth->init(t, value)) {
423             fprintf(stderr, "Unknown %s: %s\n", keyword, value);
424             return 0;
425         }
426         return 1;
427     } else if (t->skip) {
428         return 1;
429     } else if (!strcmp(keyword, "Result")) {
430         if (t->expected_err) {
431             fprintf(stderr, "Line %d: multiple result lines\n", t->line);
432             return 0;
433         }
434         t->expected_err = BUF_strdup(value);
435         if (!t->expected_err)
436             return 0;
437     } else {
438         /* Must be test specific line: try to parse it */
439         if (t->meth)
440             rv = t->meth->parse(t, keyword, value);
441
442         if (rv == 0)
443             fprintf(stderr, "line %d: unexpected keyword %s\n",
444                     t->line, keyword);
445
446         if (rv < 0)
447             fprintf(stderr, "line %d: error processing keyword %s\n",
448                     t->line, keyword);
449         if (rv <= 0)
450             return 0;
451     }
452     return 1;
453 }
454
455 static int check_output(struct evp_test *t, const unsigned char *expected,
456                         const unsigned char *got, size_t len)
457 {
458     if (!memcmp(expected, got, len))
459         return 0;
460     t->out_expected = BUF_memdup(expected, len);
461     t->out_got = BUF_memdup(got, len);
462     t->out_len = len;
463     if (t->out_expected == NULL || t->out_got == NULL) {
464         fprintf(stderr, "Memory allocation error!\n");
465         exit(1);
466     }
467     return 1;
468 }
469
470 int main(int argc, char **argv)
471 {
472     FILE *in = NULL;
473     char buf[10240];
474     struct evp_test t;
475
476     if (argc != 2) {
477         fprintf(stderr, "usage: evp_test testfile.txt\n");
478         return 1;
479     }
480
481     CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON);
482
483     ERR_load_crypto_strings();
484     OpenSSL_add_all_algorithms();
485
486     memset(&t,0,sizeof(t));
487     t.meth = NULL;
488     t.public = NULL;
489     t.private = NULL;
490     t.err = NULL;
491     t.line = 0;
492     t.start_line = -1;
493     t.errors = 0;
494     t.ntests = 0;
495     t.out_expected = NULL;
496     t.out_got = NULL;
497     t.out_len = 0;
498     in = fopen(argv[1], "r");
499     t.in = in;
500     while (fgets(buf, sizeof(buf), in)) {
501         t.line++;
502         if (!process_test(&t, buf, 0))
503             exit(1);
504     }
505     /* Run any final test we have */
506     if (!setup_test(&t, NULL))
507         exit(1);
508     fprintf(stderr, "%d tests completed with %d errors, %d skipped\n",
509             t.ntests, t.errors, t.nskip);
510     free_key_list(t.public);
511     free_key_list(t.private);
512     fclose(in);
513     EVP_cleanup();
514     CRYPTO_cleanup_all_ex_data();
515     ERR_remove_thread_state(NULL);
516     ERR_free_strings();
517     CRYPTO_mem_leaks_fp(stderr);
518     if (t.errors)
519         return 1;
520     return 0;
521 }
522
523 static void test_free(void *d)
524 {
525     if (d)
526         OPENSSL_free(d);
527 }
528
529 /* Message digest tests */
530
531 struct digest_data {
532     /* Digest this test is for */
533     const EVP_MD *digest;
534     /* Input to digest */
535     unsigned char *input;
536     size_t input_len;
537     /* Expected output */
538     unsigned char *output;
539     size_t output_len;
540 };
541
542 static int digest_test_init(struct evp_test *t, const char *alg)
543 {
544     const EVP_MD *digest;
545     struct digest_data *mdat = t->data;
546     digest = EVP_get_digestbyname(alg);
547     if (!digest) {
548         /* If alg has an OID assume disabled algorithm */
549         if (OBJ_sn2nid(alg) != NID_undef || OBJ_ln2nid(alg) != NID_undef) {
550             t->skip = 1;
551             return 1;
552         }
553         return 0;
554     }
555     mdat = OPENSSL_malloc(sizeof(struct digest_data));
556     mdat->digest = digest;
557     mdat->input = NULL;
558     mdat->output = NULL;
559     t->data = mdat;
560     return 1;
561 }
562
563 static void digest_test_cleanup(struct evp_test *t)
564 {
565     struct digest_data *mdat = t->data;
566     test_free(mdat->input);
567     test_free(mdat->output);
568 }
569
570 static int digest_test_parse(struct evp_test *t,
571                              const char *keyword, const char *value)
572 {
573     struct digest_data *mdata = t->data;
574     if (!strcmp(keyword, "Input"))
575         return test_bin(value, &mdata->input, &mdata->input_len);
576     if (!strcmp(keyword, "Output"))
577         return test_bin(value, &mdata->output, &mdata->output_len);
578     return 0;
579 }
580
581 static int digest_test_run(struct evp_test *t)
582 {
583     struct digest_data *mdata = t->data;
584     const char *err = "INTERNAL_ERROR";
585     EVP_MD_CTX *mctx;
586     unsigned char md[EVP_MAX_MD_SIZE];
587     unsigned int md_len;
588     mctx = EVP_MD_CTX_create();
589     if (!mctx)
590         goto err;
591     err = "DIGESTINIT_ERROR";
592     if (!EVP_DigestInit_ex(mctx, mdata->digest, NULL))
593         goto err;
594     err = "DIGESTUPDATE_ERROR";
595     if (!EVP_DigestUpdate(mctx, mdata->input, mdata->input_len))
596         goto err;
597     err = "DIGESTFINAL_ERROR";
598     if (!EVP_DigestFinal(mctx, md, &md_len))
599         goto err;
600     err = "DIGEST_LENGTH_MISMATCH";
601     if (md_len != mdata->output_len)
602         goto err;
603     err = "DIGEST_MISMATCH";
604     if (check_output(t, mdata->output, md, md_len))
605         goto err;
606     err = NULL;
607  err:
608     if (mctx)
609         EVP_MD_CTX_destroy(mctx);
610     t->err = err;
611     return 1;
612 }
613
614 static const struct evp_test_method digest_test_method = {
615     "Digest",
616     digest_test_init,
617     digest_test_cleanup,
618     digest_test_parse,
619     digest_test_run
620 };
621
622 /* Cipher tests */
623 struct cipher_data {
624     const EVP_CIPHER *cipher;
625     int enc;
626     /* EVP_CIPH_GCM_MODE, EVP_CIPH_CCM_MODE or EVP_CIPH_OCB_MODE if AEAD */
627     int aead;
628     unsigned char *key;
629     size_t key_len;
630     unsigned char *iv;
631     size_t iv_len;
632     unsigned char *plaintext;
633     size_t plaintext_len;
634     unsigned char *ciphertext;
635     size_t ciphertext_len;
636     /* GCM, CCM only */
637     unsigned char *aad;
638     size_t aad_len;
639     unsigned char *tag;
640     size_t tag_len;
641 };
642
643 static int cipher_test_init(struct evp_test *t, const char *alg)
644 {
645     const EVP_CIPHER *cipher;
646     struct cipher_data *cdat = t->data;
647     cipher = EVP_get_cipherbyname(alg);
648     if (!cipher) {
649         /* If alg has an OID assume disabled algorithm */
650         if (OBJ_sn2nid(alg) != NID_undef || OBJ_ln2nid(alg) != NID_undef) {
651             t->skip = 1;
652             return 1;
653         }
654         return 0;
655     }
656     cdat = OPENSSL_malloc(sizeof(struct cipher_data));
657     cdat->cipher = cipher;
658     cdat->enc = -1;
659     cdat->key = NULL;
660     cdat->iv = NULL;
661     cdat->ciphertext = NULL;
662     cdat->plaintext = NULL;
663     cdat->aad = NULL;
664     cdat->tag = NULL;
665     t->data = cdat;
666     if (EVP_CIPHER_mode(cipher) == EVP_CIPH_GCM_MODE
667         || EVP_CIPHER_mode(cipher) == EVP_CIPH_OCB_MODE
668         || EVP_CIPHER_mode(cipher) == EVP_CIPH_CCM_MODE)
669         cdat->aead = EVP_CIPHER_mode(cipher);
670     else
671         cdat->aead = 0;
672
673     return 1;
674 }
675
676 static void cipher_test_cleanup(struct evp_test *t)
677 {
678     struct cipher_data *cdat = t->data;
679     test_free(cdat->key);
680     test_free(cdat->iv);
681     test_free(cdat->ciphertext);
682     test_free(cdat->plaintext);
683     test_free(cdat->aad);
684     test_free(cdat->tag);
685 }
686
687 static int cipher_test_parse(struct evp_test *t, const char *keyword,
688                              const char *value)
689 {
690     struct cipher_data *cdat = t->data;
691     if (!strcmp(keyword, "Key"))
692         return test_bin(value, &cdat->key, &cdat->key_len);
693     if (!strcmp(keyword, "IV"))
694         return test_bin(value, &cdat->iv, &cdat->iv_len);
695     if (!strcmp(keyword, "Plaintext"))
696         return test_bin(value, &cdat->plaintext, &cdat->plaintext_len);
697     if (!strcmp(keyword, "Ciphertext"))
698         return test_bin(value, &cdat->ciphertext, &cdat->ciphertext_len);
699     if (cdat->aead) {
700         if (!strcmp(keyword, "AAD"))
701             return test_bin(value, &cdat->aad, &cdat->aad_len);
702         if (!strcmp(keyword, "Tag"))
703             return test_bin(value, &cdat->tag, &cdat->tag_len);
704     }
705
706     if (!strcmp(keyword, "Operation")) {
707         if (!strcmp(value, "ENCRYPT"))
708             cdat->enc = 1;
709         else if (!strcmp(value, "DECRYPT"))
710             cdat->enc = 0;
711         else
712             return 0;
713         return 1;
714     }
715     return 0;
716 }
717
718 static int cipher_test_enc(struct evp_test *t, int enc)
719 {
720     struct cipher_data *cdat = t->data;
721     unsigned char *in, *out, *tmp = NULL;
722     size_t in_len, out_len;
723     int tmplen, tmpflen;
724     EVP_CIPHER_CTX *ctx = NULL;
725     const char *err;
726     err = "INTERNAL_ERROR";
727     ctx = EVP_CIPHER_CTX_new();
728     if (!ctx)
729         goto err;
730     EVP_CIPHER_CTX_set_flags(ctx, EVP_CIPHER_CTX_FLAG_WRAP_ALLOW);
731     if (enc) {
732         in = cdat->plaintext;
733         in_len = cdat->plaintext_len;
734         out = cdat->ciphertext;
735         out_len = cdat->ciphertext_len;
736     } else {
737         in = cdat->ciphertext;
738         in_len = cdat->ciphertext_len;
739         out = cdat->plaintext;
740         out_len = cdat->plaintext_len;
741     }
742     tmp = OPENSSL_malloc(in_len + 2 * EVP_MAX_BLOCK_LENGTH);
743     if (!tmp)
744         goto err;
745     err = "CIPHERINIT_ERROR";
746     if (!EVP_CipherInit_ex(ctx, cdat->cipher, NULL, NULL, NULL, enc))
747         goto err;
748     err = "INVALID_IV_LENGTH";
749     if (cdat->iv) {
750         if (cdat->aead) {
751             if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_IVLEN,
752                                      cdat->iv_len, 0))
753                 goto err;
754         } else if (cdat->iv_len != (size_t)EVP_CIPHER_CTX_iv_length(ctx))
755             goto err;
756     }
757     if (cdat->aead) {
758         unsigned char *tag;
759         /*
760          * If encrypting or OCB just set tag length initially, otherwise
761          * set tag length and value.
762          */
763         if (enc || cdat->aead == EVP_CIPH_OCB_MODE) {
764             err = "TAG_LENGTH_SET_ERROR";
765             tag = NULL;
766         } else {
767             err = "TAG_SET_ERROR";
768             tag = cdat->tag;
769         }
770         if (tag || cdat->aead != EVP_CIPH_GCM_MODE) {
771             if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_TAG,
772                                         cdat->tag_len, tag))
773                 goto err;
774         }
775     }
776
777     err = "INVALID_KEY_LENGTH";
778     if (!EVP_CIPHER_CTX_set_key_length(ctx, cdat->key_len))
779         goto err;
780     err = "KEY_SET_ERROR";
781     if (!EVP_CipherInit_ex(ctx, NULL, NULL, cdat->key, cdat->iv, -1))
782         goto err;
783
784     if (!enc && cdat->aead == EVP_CIPH_OCB_MODE) {
785         if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_TAG,
786                                  cdat->tag_len, cdat->tag)) {
787                 err = "TAG_SET_ERROR";
788                 goto err;
789         }
790     }
791
792     if (cdat->aead == EVP_CIPH_CCM_MODE) {
793         if (!EVP_CipherUpdate(ctx, NULL, &tmplen, NULL, out_len)) {
794             err = "CCM_PLAINTEXT_LENGTH_SET_ERROR";
795             goto err;
796         }
797     }
798     if (cdat->aad) {
799         if (!EVP_CipherUpdate(ctx, NULL, &tmplen, cdat->aad, cdat->aad_len)) {
800             err = "AAD_SET_ERROR";
801             goto err;
802         }
803     }
804     EVP_CIPHER_CTX_set_padding(ctx, 0);
805     err = "CIPHERUPDATE_ERROR";
806     if (!EVP_CipherUpdate(ctx, tmp, &tmplen, in, in_len))
807         goto err;
808     if (cdat->aead == EVP_CIPH_CCM_MODE)
809         tmpflen = 0;
810     else {
811         err = "CIPHERFINAL_ERROR";
812         if (!EVP_CipherFinal_ex(ctx, tmp + tmplen, &tmpflen))
813             goto err;
814     }
815     err = "LENGTH_MISMATCH";
816     if (out_len != (size_t)(tmplen + tmpflen))
817         goto err;
818     err = "VALUE_MISMATCH";
819     if (check_output(t, out, tmp, out_len))
820         goto err;
821     if (enc && cdat->aead) {
822         unsigned char rtag[16];
823         if (cdat->tag_len > sizeof(rtag)) {
824             err = "TAG_LENGTH_INTERNAL_ERROR";
825             goto err;
826         }
827         if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_GET_TAG,
828                                  cdat->tag_len, rtag)) {
829             err = "TAG_RETRIEVE_ERROR";
830             goto err;
831         }
832         if (check_output(t, cdat->tag, rtag, cdat->tag_len)) {
833             err = "TAG_VALUE_MISMATCH";
834             goto err;
835         }
836     }
837     err = NULL;
838  err:
839     if (tmp)
840         OPENSSL_free(tmp);
841     EVP_CIPHER_CTX_free(ctx);
842     t->err = err;
843     return err ? 0 : 1;
844 }
845
846 static int cipher_test_run(struct evp_test *t)
847 {
848     struct cipher_data *cdat = t->data;
849     int rv;
850     if (!cdat->key) {
851         t->err = "NO_KEY";
852         return 0;
853     }
854     if (!cdat->iv && EVP_CIPHER_iv_length(cdat->cipher)) {
855         /* IV is optional and usually omitted in wrap mode */
856         if (EVP_CIPHER_mode(cdat->cipher) != EVP_CIPH_WRAP_MODE) {
857             t->err = "NO_IV";
858             return 0;
859         }
860     }
861     if (cdat->aead && !cdat->tag) {
862         t->err = "NO_TAG";
863         return 0;
864     }
865     if (cdat->enc) {
866         rv = cipher_test_enc(t, 1);
867         /* Not fatal errors: return */
868         if (rv != 1) {
869             if (rv < 0)
870                 return 0;
871             return 1;
872         }
873     }
874     if (cdat->enc != 1) {
875         rv = cipher_test_enc(t, 0);
876         /* Not fatal errors: return */
877         if (rv != 1) {
878             if (rv < 0)
879                 return 0;
880             return 1;
881         }
882     }
883     return 1;
884 }
885
886 static const struct evp_test_method cipher_test_method = {
887     "Cipher",
888     cipher_test_init,
889     cipher_test_cleanup,
890     cipher_test_parse,
891     cipher_test_run
892 };
893
894 struct mac_data {
895     /* MAC type */
896     int type;
897     /* Algorithm string for this MAC */
898     char *alg;
899     /* MAC key */
900     unsigned char *key;
901     size_t key_len;
902     /* Input to MAC */
903     unsigned char *input;
904     size_t input_len;
905     /* Expected output */
906     unsigned char *output;
907     size_t output_len;
908 };
909
910 static int mac_test_init(struct evp_test *t, const char *alg)
911 {
912     int type;
913     struct mac_data *mdat;
914     if (!strcmp(alg, "HMAC"))
915         type = EVP_PKEY_HMAC;
916     else if (!strcmp(alg, "CMAC"))
917         type = EVP_PKEY_CMAC;
918     else
919         return 0;
920
921     mdat = OPENSSL_malloc(sizeof(struct mac_data));
922     mdat->type = type;
923     mdat->alg = NULL;
924     mdat->key = NULL;
925     mdat->input = NULL;
926     mdat->output = NULL;
927     t->data = mdat;
928     return 1;
929 }
930
931 static void mac_test_cleanup(struct evp_test *t)
932 {
933     struct mac_data *mdat = t->data;
934     test_free(mdat->alg);
935     test_free(mdat->key);
936     test_free(mdat->input);
937     test_free(mdat->output);
938 }
939
940 static int mac_test_parse(struct evp_test *t,
941                           const char *keyword, const char *value)
942 {
943     struct mac_data *mdata = t->data;
944     if (!strcmp(keyword, "Key"))
945         return test_bin(value, &mdata->key, &mdata->key_len);
946     if (!strcmp(keyword, "Algorithm")) {
947         mdata->alg = BUF_strdup(value);
948         if (!mdata->alg)
949             return 0;
950         return 1;
951     }
952     if (!strcmp(keyword, "Input"))
953         return test_bin(value, &mdata->input, &mdata->input_len);
954     if (!strcmp(keyword, "Output"))
955         return test_bin(value, &mdata->output, &mdata->output_len);
956     return 0;
957 }
958
959 static int mac_test_run(struct evp_test *t)
960 {
961     struct mac_data *mdata = t->data;
962     const char *err = "INTERNAL_ERROR";
963     EVP_MD_CTX *mctx = NULL;
964     EVP_PKEY_CTX *pctx = NULL, *genctx = NULL;
965     EVP_PKEY *key = NULL;
966     const EVP_MD *md = NULL;
967     unsigned char *mac = NULL;
968     size_t mac_len;
969
970     err = "MAC_PKEY_CTX_ERROR";
971     genctx = EVP_PKEY_CTX_new_id(mdata->type, NULL);
972     if (!genctx)
973         goto err;
974
975     err = "MAC_KEYGEN_INIT_ERROR";
976     if (EVP_PKEY_keygen_init(genctx) <= 0)
977         goto err;
978     if (mdata->type == EVP_PKEY_CMAC) {
979         err = "MAC_ALGORITHM_SET_ERROR";
980         if (EVP_PKEY_CTX_ctrl_str(genctx, "cipher", mdata->alg) <= 0)
981             goto err;
982     }
983
984     err = "MAC_KEY_SET_ERROR";
985     if (EVP_PKEY_CTX_set_mac_key(genctx, mdata->key, mdata->key_len) <= 0)
986         goto err;
987
988     err = "MAC_KEY_GENERATE_ERROR";
989     if (EVP_PKEY_keygen(genctx, &key) <= 0)
990         goto err;
991     if (mdata->type == EVP_PKEY_HMAC) {
992         err = "MAC_ALGORITHM_SET_ERROR";
993         md = EVP_get_digestbyname(mdata->alg);
994         if (!md)
995             goto err;
996     }
997     mctx = EVP_MD_CTX_create();
998     if (!mctx)
999         goto err;
1000     err = "DIGESTSIGNINIT_ERROR";
1001     if (!EVP_DigestSignInit(mctx, &pctx, md, NULL, key))
1002         goto err;
1003
1004     err = "DIGESTSIGNUPDATE_ERROR";
1005     if (!EVP_DigestSignUpdate(mctx, mdata->input, mdata->input_len))
1006         goto err;
1007     err = "DIGESTSIGNFINAL_LENGTH_ERROR";
1008     if (!EVP_DigestSignFinal(mctx, NULL, &mac_len))
1009         goto err;
1010     mac = OPENSSL_malloc(mac_len);
1011     if (!mac) {
1012         fprintf(stderr, "Error allocating mac buffer!\n");
1013         exit(1);
1014     }
1015     if (!EVP_DigestSignFinal(mctx, mac, &mac_len))
1016         goto err;
1017     err = "MAC_LENGTH_MISMATCH";
1018     if (mac_len != mdata->output_len)
1019         goto err;
1020     err = "MAC_MISMATCH";
1021     if (check_output(t, mdata->output, mac, mac_len))
1022         goto err;
1023     err = NULL;
1024  err:
1025     if (mctx)
1026         EVP_MD_CTX_destroy(mctx);
1027     if (mac)
1028         OPENSSL_free(mac);
1029     if (genctx)
1030         EVP_PKEY_CTX_free(genctx);
1031     if (key)
1032         EVP_PKEY_free(key);
1033     t->err = err;
1034     return 1;
1035 }
1036
1037 static const struct evp_test_method mac_test_method = {
1038     "MAC",
1039     mac_test_init,
1040     mac_test_cleanup,
1041     mac_test_parse,
1042     mac_test_run
1043 };
1044
1045 /*
1046  * Public key operations. These are all very similar and can share
1047  * a lot of common code.
1048  */
1049
1050 struct pkey_data {
1051     /* Context for this operation */
1052     EVP_PKEY_CTX *ctx;
1053     /* Key operation to perform */
1054     int (*keyop) (EVP_PKEY_CTX *ctx,
1055                   unsigned char *sig, size_t *siglen,
1056                   const unsigned char *tbs, size_t tbslen);
1057     /* Input to MAC */
1058     unsigned char *input;
1059     size_t input_len;
1060     /* Expected output */
1061     unsigned char *output;
1062     size_t output_len;
1063 };
1064
1065 /*
1066  * Perform public key operation setup: lookup key, allocated ctx and call
1067  * the appropriate initialisation function
1068  */
1069 static int pkey_test_init(struct evp_test *t, const char *name,
1070                           int use_public,
1071                           int (*keyopinit) (EVP_PKEY_CTX *ctx),
1072                           int (*keyop) (EVP_PKEY_CTX *ctx,
1073                                         unsigned char *sig, size_t *siglen,
1074                                         const unsigned char *tbs,
1075                                         size_t tbslen)
1076     )
1077 {
1078     struct pkey_data *kdata;
1079     EVP_PKEY *pkey = NULL;
1080     int rv = 0;
1081     if (use_public)
1082         rv = find_key(&pkey, name, t->public);
1083     if (!rv)
1084         rv = find_key(&pkey, name, t->private);
1085     if (!rv)
1086         return 0;
1087     if (!pkey) {
1088         t->skip = 1;
1089         return 1;
1090     }
1091
1092     kdata = OPENSSL_malloc(sizeof(struct pkey_data));
1093     if (!kdata) {
1094         EVP_PKEY_free(pkey);
1095         return 0;
1096     }
1097     kdata->ctx = NULL;
1098     kdata->input = NULL;
1099     kdata->output = NULL;
1100     kdata->keyop = keyop;
1101     t->data = kdata;
1102     kdata->ctx = EVP_PKEY_CTX_new(pkey, NULL);
1103     if (!kdata->ctx)
1104         return 0;
1105     if (keyopinit(kdata->ctx) <= 0)
1106         return 0;
1107     return 1;
1108 }
1109
1110 static void pkey_test_cleanup(struct evp_test *t)
1111 {
1112     struct pkey_data *kdata = t->data;
1113     if (kdata->input)
1114         OPENSSL_free(kdata->input);
1115     if (kdata->output)
1116         OPENSSL_free(kdata->output);
1117     if (kdata->ctx)
1118         EVP_PKEY_CTX_free(kdata->ctx);
1119 }
1120
1121 static int pkey_test_parse(struct evp_test *t,
1122                            const char *keyword, const char *value)
1123 {
1124     struct pkey_data *kdata = t->data;
1125     if (!strcmp(keyword, "Input"))
1126         return test_bin(value, &kdata->input, &kdata->input_len);
1127     if (!strcmp(keyword, "Output"))
1128         return test_bin(value, &kdata->output, &kdata->output_len);
1129     if (!strcmp(keyword, "Ctrl")) {
1130         char *p = strchr(value, ':');
1131         if (p)
1132             *p++ = 0;
1133         if (EVP_PKEY_CTX_ctrl_str(kdata->ctx, value, p) <= 0)
1134             return 0;
1135         return 1;
1136     }
1137     return 0;
1138 }
1139
1140 static int pkey_test_run(struct evp_test *t)
1141 {
1142     struct pkey_data *kdata = t->data;
1143     unsigned char *out = NULL;
1144     size_t out_len;
1145     const char *err = "KEYOP_LENGTH_ERROR";
1146     if (kdata->keyop(kdata->ctx, NULL, &out_len, kdata->input,
1147                      kdata->input_len) <= 0)
1148         goto err;
1149     out = OPENSSL_malloc(out_len);
1150     if (!out) {
1151         fprintf(stderr, "Error allocating output buffer!\n");
1152         exit(1);
1153     }
1154     err = "KEYOP_ERROR";
1155     if (kdata->keyop
1156         (kdata->ctx, out, &out_len, kdata->input, kdata->input_len) <= 0)
1157         goto err;
1158     err = "KEYOP_LENGTH_MISMATCH";
1159     if (out_len != kdata->output_len)
1160         goto err;
1161     err = "KEYOP_MISMATCH";
1162     if (check_output(t, kdata->output, out, out_len))
1163         goto err;
1164     err = NULL;
1165  err:
1166     if (out)
1167         OPENSSL_free(out);
1168     t->err = err;
1169     return 1;
1170 }
1171
1172 static int sign_test_init(struct evp_test *t, const char *name)
1173 {
1174     return pkey_test_init(t, name, 0, EVP_PKEY_sign_init, EVP_PKEY_sign);
1175 }
1176
1177 static const struct evp_test_method psign_test_method = {
1178     "Sign",
1179     sign_test_init,
1180     pkey_test_cleanup,
1181     pkey_test_parse,
1182     pkey_test_run
1183 };
1184
1185 static int verify_recover_test_init(struct evp_test *t, const char *name)
1186 {
1187     return pkey_test_init(t, name, 1, EVP_PKEY_verify_recover_init,
1188                           EVP_PKEY_verify_recover);
1189 }
1190
1191 static const struct evp_test_method pverify_recover_test_method = {
1192     "VerifyRecover",
1193     verify_recover_test_init,
1194     pkey_test_cleanup,
1195     pkey_test_parse,
1196     pkey_test_run
1197 };
1198
1199 static int decrypt_test_init(struct evp_test *t, const char *name)
1200 {
1201     return pkey_test_init(t, name, 0, EVP_PKEY_decrypt_init,
1202                           EVP_PKEY_decrypt);
1203 }
1204
1205 static const struct evp_test_method pdecrypt_test_method = {
1206     "Decrypt",
1207     decrypt_test_init,
1208     pkey_test_cleanup,
1209     pkey_test_parse,
1210     pkey_test_run
1211 };
1212
1213 static int verify_test_init(struct evp_test *t, const char *name)
1214 {
1215     return pkey_test_init(t, name, 1, EVP_PKEY_verify_init, 0);
1216 }
1217
1218 static int verify_test_run(struct evp_test *t)
1219 {
1220     struct pkey_data *kdata = t->data;
1221     if (EVP_PKEY_verify(kdata->ctx, kdata->output, kdata->output_len,
1222                         kdata->input, kdata->input_len) <= 0)
1223         t->err = "VERIFY_ERROR";
1224     return 1;
1225 }
1226
1227 static const struct evp_test_method pverify_test_method = {
1228     "Verify",
1229     verify_test_init,
1230     pkey_test_cleanup,
1231     pkey_test_parse,
1232     verify_test_run
1233 };