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