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