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