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