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