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