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