Additional error tests in evp_test.c
[openssl.git] / test / evp_test.c
1 /*
2  * Copyright 2015-2016 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the OpenSSL license (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9
10 #include <stdio.h>
11 #include <string.h>
12 #include <stdlib.h>
13 #include <ctype.h>
14 #include <openssl/evp.h>
15 #include <openssl/pem.h>
16 #include <openssl/err.h>
17 #include <openssl/x509v3.h>
18 #include <openssl/pkcs12.h>
19 #include <openssl/kdf.h>
20 #include "internal/numbers.h"
21
22 /* Remove spaces from beginning and end of a string */
23
24 static void remove_space(char **pval)
25 {
26     unsigned char *p = (unsigned char *)*pval;
27
28     while (isspace(*p))
29         p++;
30
31     *pval = (char *)p;
32
33     p = p + strlen(*pval) - 1;
34
35     /* Remove trailing space */
36     while (isspace(*p))
37         *p-- = 0;
38 }
39
40 /*
41  * Given a line of the form:
42  *      name = value # comment
43  * extract name and value. NB: modifies passed buffer.
44  */
45
46 static int parse_line(char **pkw, char **pval, char *linebuf)
47 {
48     char *p;
49
50     p = linebuf + strlen(linebuf) - 1;
51
52     if (*p != '\n') {
53         fprintf(stderr, "FATAL: missing EOL\n");
54         exit(1);
55     }
56
57     /* Look for # */
58
59     p = strchr(linebuf, '#');
60
61     if (p)
62         *p = '\0';
63
64     /* Look for = sign */
65     p = strchr(linebuf, '=');
66
67     /* If no '=' exit */
68     if (!p)
69         return 0;
70
71     *p++ = '\0';
72
73     *pkw = linebuf;
74     *pval = p;
75
76     /* Remove spaces from keyword and value */
77     remove_space(pkw);
78     remove_space(pval);
79
80     return 1;
81 }
82
83 /*
84  * Unescape some escape sequences in string literals.
85  * Return the result in a newly allocated buffer.
86  * Currently only supports '\n'.
87  * If the input length is 0, returns a valid 1-byte buffer, but sets
88  * the length to 0.
89  */
90 static unsigned char* unescape(const char *input, size_t input_len,
91                                size_t *out_len)
92 {
93     unsigned char *ret, *p;
94     size_t i;
95     if (input_len == 0) {
96         *out_len = 0;
97         return OPENSSL_zalloc(1);
98     }
99
100     /* Escaping is non-expanding; over-allocate original size for simplicity. */
101     ret = p = OPENSSL_malloc(input_len);
102     if (ret == NULL)
103         return NULL;
104
105     for (i = 0; i < input_len; i++) {
106         if (input[i] == '\\') {
107             if (i == input_len - 1 || input[i+1] != 'n')
108                 goto err;
109             *p++ = '\n';
110             i++;
111         } else {
112             *p++ = input[i];
113         }
114     }
115
116     *out_len = p - ret;
117     return ret;
118
119  err:
120     OPENSSL_free(ret);
121     return NULL;
122 }
123
124 /* For a hex string "value" convert to a binary allocated buffer */
125 static int test_bin(const char *value, unsigned char **buf, size_t *buflen)
126 {
127     long len;
128
129     *buflen = 0;
130     if (!*value) {
131         /*
132          * Don't return NULL for zero length buffer.
133          * This is needed for some tests with empty keys: HMAC_Init_ex() expects
134          * a non-NULL key buffer even if the key length is 0, in order to detect
135          * key reset.
136          */
137         *buf = OPENSSL_malloc(1);
138         if (!*buf)
139             return 0;
140         **buf = 0;
141         *buflen = 0;
142         return 1;
143     }
144     /* Check for string literal */
145     if (value[0] == '"') {
146         size_t vlen;
147         value++;
148         vlen = strlen(value);
149         if (value[vlen - 1] != '"')
150             return 0;
151         vlen--;
152         *buf = unescape(value, vlen, buflen);
153         if (*buf == NULL)
154             return 0;
155         return 1;
156     }
157
158     *buf = OPENSSL_hexstr2buf(value, &len);
159     if (!*buf) {
160         fprintf(stderr, "Value=%s\n", value);
161         ERR_print_errors_fp(stderr);
162         return -1;
163     }
164     /* Size of input buffer means we'll never overflow */
165     *buflen = len;
166     return 1;
167 }
168 #ifndef OPENSSL_NO_SCRYPT
169 /* Currently only used by scrypt tests */
170 /* Parse unsigned decimal 64 bit integer value */
171 static int test_uint64(const char *value, uint64_t *pr)
172 {
173     const char *p = value;
174     if (!*p) {
175         fprintf(stderr, "Invalid empty integer value\n");
176         return -1;
177     }
178     *pr = 0;
179     while (*p) {
180         if (*pr > UINT64_MAX/10) {
181             fprintf(stderr, "Integer string overflow value=%s\n", value);
182             return -1;
183         }
184         *pr *= 10;
185         if (*p < '0' || *p > '9') {
186             fprintf(stderr, "Invalid integer string value=%s\n", value);
187             return -1;
188         }
189         *pr += *p - '0';
190         p++;
191     }
192     return 1;
193 }
194 #endif
195
196 /* Structure holding test information */
197 struct evp_test {
198     /* file being read */
199     BIO *in;
200     /* List of public and private keys */
201     struct key_list *private;
202     struct key_list *public;
203     /* method for this test */
204     const struct evp_test_method *meth;
205     /* current line being processed */
206     unsigned int line;
207     /* start line of current test */
208     unsigned int start_line;
209     /* Error string for test */
210     const char *err, *aux_err;
211     /* Expected error value of test */
212     char *expected_err;
213     /* Number of tests */
214     int ntests;
215     /* Error count */
216     int errors;
217     /* Number of tests skipped */
218     int nskip;
219     /* If output mismatch expected and got value */
220     unsigned char *out_received;
221     size_t out_received_len;
222     unsigned char *out_expected;
223     size_t out_expected_len;
224     /* test specific data */
225     void *data;
226     /* Current test should be skipped */
227     int skip;
228 };
229
230 struct key_list {
231     char *name;
232     EVP_PKEY *key;
233     struct key_list *next;
234 };
235
236 /* Test method structure */
237 struct evp_test_method {
238     /* Name of test as it appears in file */
239     const char *name;
240     /* Initialise test for "alg" */
241     int (*init) (struct evp_test * t, const char *alg);
242     /* Clean up method */
243     void (*cleanup) (struct evp_test * t);
244     /* Test specific name value pair processing */
245     int (*parse) (struct evp_test * t, const char *name, const char *value);
246     /* Run the test itself */
247     int (*run_test) (struct evp_test * t);
248 };
249
250 static const struct evp_test_method digest_test_method, cipher_test_method;
251 static const struct evp_test_method mac_test_method;
252 static const struct evp_test_method psign_test_method, pverify_test_method;
253 static const struct evp_test_method pdecrypt_test_method;
254 static const struct evp_test_method pverify_recover_test_method;
255 static const struct evp_test_method pderive_test_method;
256 static const struct evp_test_method pbe_test_method;
257 static const struct evp_test_method encode_test_method;
258 static const struct evp_test_method kdf_test_method;
259
260 static const struct evp_test_method *evp_test_list[] = {
261     &digest_test_method,
262     &cipher_test_method,
263     &mac_test_method,
264     &psign_test_method,
265     &pverify_test_method,
266     &pdecrypt_test_method,
267     &pverify_recover_test_method,
268     &pderive_test_method,
269     &pbe_test_method,
270     &encode_test_method,
271     &kdf_test_method,
272     NULL
273 };
274
275 static const struct evp_test_method *evp_find_test(const char *name)
276 {
277     const struct evp_test_method **tt;
278
279     for (tt = evp_test_list; *tt; tt++) {
280         if (strcmp(name, (*tt)->name) == 0)
281             return *tt;
282     }
283     return NULL;
284 }
285
286 static void hex_print(const char *name, const unsigned char *buf, size_t len)
287 {
288     size_t i;
289     fprintf(stderr, "%s ", name);
290     for (i = 0; i < len; i++)
291         fprintf(stderr, "%02X", buf[i]);
292     fputs("\n", stderr);
293 }
294
295 static void free_expected(struct evp_test *t)
296 {
297     OPENSSL_free(t->expected_err);
298     t->expected_err = NULL;
299     OPENSSL_free(t->out_expected);
300     OPENSSL_free(t->out_received);
301     t->out_expected = NULL;
302     t->out_received = NULL;
303     t->out_expected_len = 0;
304     t->out_received_len = 0;
305     /* Literals. */
306     t->err = NULL;
307 }
308
309 static void print_expected(struct evp_test *t)
310 {
311     if (t->out_expected == NULL && t->out_received == NULL)
312         return;
313     hex_print("Expected:", t->out_expected, t->out_expected_len);
314     hex_print("Got:     ", t->out_received, t->out_received_len);
315     free_expected(t);
316 }
317
318 static int check_test_error(struct evp_test *t)
319 {
320     if (!t->err && !t->expected_err)
321         return 1;
322     if (t->err && !t->expected_err) {
323         if (t->aux_err != NULL) {
324             fprintf(stderr, "Test line %d(%s): unexpected error %s\n",
325                     t->start_line, t->aux_err, t->err);
326         } else {
327             fprintf(stderr, "Test line %d: unexpected error %s\n",
328                     t->start_line, t->err);
329         }
330         print_expected(t);
331         return 0;
332     }
333     if (!t->err && t->expected_err) {
334         fprintf(stderr, "Test line %d: succeeded expecting %s\n",
335                 t->start_line, t->expected_err);
336         return 0;
337     }
338     if (strcmp(t->err, t->expected_err) == 0)
339         return 1;
340
341     fprintf(stderr, "Test line %d: expecting %s got %s\n",
342             t->start_line, t->expected_err, t->err);
343     return 0;
344 }
345
346 /* Setup a new test, run any existing test */
347
348 static int setup_test(struct evp_test *t, const struct evp_test_method *tmeth)
349 {
350     /* If we already have a test set up run it */
351     if (t->meth) {
352         t->ntests++;
353         if (t->skip) {
354             t->nskip++;
355         } else {
356             /* run the test */
357             if (t->err == NULL && t->meth->run_test(t) != 1) {
358                 fprintf(stderr, "%s test error line %d\n",
359                         t->meth->name, t->start_line);
360                 return 0;
361             }
362             if (!check_test_error(t)) {
363                 if (t->err)
364                     ERR_print_errors_fp(stderr);
365                 t->errors++;
366             }
367         }
368         /* clean it up */
369         ERR_clear_error();
370         if (t->data != NULL) {
371             t->meth->cleanup(t);
372             OPENSSL_free(t->data);
373             t->data = NULL;
374         }
375         OPENSSL_free(t->expected_err);
376         t->expected_err = NULL;
377         free_expected(t);
378     }
379     t->meth = tmeth;
380     return 1;
381 }
382
383 static int find_key(EVP_PKEY **ppk, const char *name, struct key_list *lst)
384 {
385     for (; lst; lst = lst->next) {
386         if (strcmp(lst->name, name) == 0) {
387             if (ppk)
388                 *ppk = lst->key;
389             return 1;
390         }
391     }
392     return 0;
393 }
394
395 static void free_key_list(struct key_list *lst)
396 {
397     while (lst != NULL) {
398         struct key_list *ltmp;
399         EVP_PKEY_free(lst->key);
400         OPENSSL_free(lst->name);
401         ltmp = lst->next;
402         OPENSSL_free(lst);
403         lst = ltmp;
404     }
405 }
406
407 static int check_unsupported()
408 {
409     long err = ERR_peek_error();
410     if (ERR_GET_LIB(err) == ERR_LIB_EVP
411         && ERR_GET_REASON(err) == EVP_R_UNSUPPORTED_ALGORITHM) {
412         ERR_clear_error();
413         return 1;
414     }
415     return 0;
416 }
417
418 static int process_test(struct evp_test *t, char *buf, int verbose)
419 {
420     char *keyword = NULL, *value = NULL;
421     int rv = 0, add_key = 0;
422     long save_pos = 0;
423     struct key_list **lst = NULL, *key = NULL;
424     EVP_PKEY *pk = NULL;
425     const struct evp_test_method *tmeth = NULL;
426     if (verbose)
427         fputs(buf, stdout);
428     if (!parse_line(&keyword, &value, buf))
429         return 1;
430     if (strcmp(keyword, "PrivateKey") == 0) {
431         save_pos = BIO_tell(t->in);
432         pk = PEM_read_bio_PrivateKey(t->in, NULL, 0, NULL);
433         if (pk == NULL && !check_unsupported()) {
434             fprintf(stderr, "Error reading private key %s\n", value);
435             ERR_print_errors_fp(stderr);
436             return 0;
437         }
438         lst = &t->private;
439         add_key = 1;
440     }
441     if (strcmp(keyword, "PublicKey") == 0) {
442         save_pos = BIO_tell(t->in);
443         pk = PEM_read_bio_PUBKEY(t->in, NULL, 0, NULL);
444         if (pk == NULL && !check_unsupported()) {
445             fprintf(stderr, "Error reading public key %s\n", value);
446             ERR_print_errors_fp(stderr);
447             return 0;
448         }
449         lst = &t->public;
450         add_key = 1;
451     }
452     /* If we have a key add to list */
453     if (add_key) {
454         char tmpbuf[80];
455         if (find_key(NULL, value, *lst)) {
456             fprintf(stderr, "Duplicate key %s\n", value);
457             return 0;
458         }
459         key = OPENSSL_malloc(sizeof(*key));
460         if (!key)
461             return 0;
462         key->name = OPENSSL_strdup(value);
463         key->key = pk;
464         key->next = *lst;
465         *lst = key;
466         /* Rewind input, read to end and update line numbers */
467         (void)BIO_seek(t->in, save_pos);
468         while (BIO_gets(t->in,tmpbuf, sizeof(tmpbuf))) {
469             t->line++;
470             if (strncmp(tmpbuf, "-----END", 8) == 0)
471                 return 1;
472         }
473         fprintf(stderr, "Can't find key end\n");
474         return 0;
475     }
476
477     /* See if keyword corresponds to a test start */
478     tmeth = evp_find_test(keyword);
479     if (tmeth) {
480         if (!setup_test(t, tmeth))
481             return 0;
482         t->start_line = t->line;
483         t->skip = 0;
484         if (!tmeth->init(t, value)) {
485             fprintf(stderr, "Unknown %s: %s\n", keyword, value);
486             return 0;
487         }
488         return 1;
489     } else if (t->skip) {
490         return 1;
491     } else if (strcmp(keyword, "Result") == 0) {
492         if (t->expected_err) {
493             fprintf(stderr, "Line %d: multiple result lines\n", t->line);
494             return 0;
495         }
496         t->expected_err = OPENSSL_strdup(value);
497         if (!t->expected_err)
498             return 0;
499     } else {
500         /* Must be test specific line: try to parse it */
501         if (t->meth)
502             rv = t->meth->parse(t, keyword, value);
503
504         if (rv == 0)
505             fprintf(stderr, "line %d: unexpected keyword %s\n",
506                     t->line, keyword);
507
508         if (rv < 0)
509             fprintf(stderr, "line %d: error processing keyword %s\n",
510                     t->line, keyword);
511         if (rv <= 0)
512             return 0;
513     }
514     return 1;
515 }
516
517 static int check_var_length_output(struct evp_test *t,
518                                    const unsigned char *expected,
519                                    size_t expected_len,
520                                    const unsigned char *received,
521                                    size_t received_len)
522 {
523     if (expected_len == received_len &&
524         memcmp(expected, received, expected_len) == 0) {
525         return 0;
526     }
527
528     /* The result printing code expects a non-NULL buffer. */
529     t->out_expected = OPENSSL_memdup(expected, expected_len ? expected_len : 1);
530     t->out_expected_len = expected_len;
531     t->out_received = OPENSSL_memdup(received, received_len ? received_len : 1);
532     t->out_received_len = received_len;
533     if (t->out_expected == NULL || t->out_received == NULL) {
534         fprintf(stderr, "Memory allocation error!\n");
535         exit(1);
536     }
537     return 1;
538 }
539
540 static int check_output(struct evp_test *t,
541                         const unsigned char *expected,
542                         const unsigned char *received,
543                         size_t len)
544 {
545     return check_var_length_output(t, expected, len, received, len);
546 }
547
548 int main(int argc, char **argv)
549 {
550     BIO *in = NULL;
551     char buf[10240];
552     struct evp_test t;
553
554     if (argc != 2) {
555         fprintf(stderr, "usage: evp_test testfile.txt\n");
556         return 1;
557     }
558
559     CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON);
560
561     memset(&t, 0, sizeof(t));
562     t.start_line = -1;
563     in = BIO_new_file(argv[1], "r");
564     if (in == NULL) {
565         fprintf(stderr, "Can't open %s for reading\n", argv[1]);
566         return 1;
567     }
568     t.in = in;
569     t.err = NULL;
570     while (BIO_gets(in, buf, sizeof(buf))) {
571         t.line++;
572         if (!process_test(&t, buf, 0))
573             exit(1);
574     }
575     /* Run any final test we have */
576     if (!setup_test(&t, NULL))
577         exit(1);
578     fprintf(stderr, "%d tests completed with %d errors, %d skipped\n",
579             t.ntests, t.errors, t.nskip);
580     free_key_list(t.public);
581     free_key_list(t.private);
582     BIO_free(in);
583
584 #ifndef OPENSSL_NO_CRYPTO_MDEBUG
585     if (CRYPTO_mem_leaks_fp(stderr) <= 0)
586         return 1;
587 #endif
588     if (t.errors)
589         return 1;
590     return 0;
591 }
592
593 static void test_free(void *d)
594 {
595     OPENSSL_free(d);
596 }
597
598 /* Message digest tests */
599
600 struct digest_data {
601     /* Digest this test is for */
602     const EVP_MD *digest;
603     /* Input to digest */
604     unsigned char *input;
605     size_t input_len;
606     /* Repeat count for input */
607     size_t nrpt;
608     /* Expected output */
609     unsigned char *output;
610     size_t output_len;
611 };
612
613 static int digest_test_init(struct evp_test *t, const char *alg)
614 {
615     const EVP_MD *digest;
616     struct digest_data *mdat;
617     digest = EVP_get_digestbyname(alg);
618     if (!digest) {
619         /* If alg has an OID assume disabled algorithm */
620         if (OBJ_sn2nid(alg) != NID_undef || OBJ_ln2nid(alg) != NID_undef) {
621             t->skip = 1;
622             return 1;
623         }
624         return 0;
625     }
626     mdat = OPENSSL_malloc(sizeof(*mdat));
627     mdat->digest = digest;
628     mdat->input = NULL;
629     mdat->output = NULL;
630     mdat->nrpt = 1;
631     t->data = mdat;
632     return 1;
633 }
634
635 static void digest_test_cleanup(struct evp_test *t)
636 {
637     struct digest_data *mdat = t->data;
638     test_free(mdat->input);
639     test_free(mdat->output);
640 }
641
642 static int digest_test_parse(struct evp_test *t,
643                              const char *keyword, const char *value)
644 {
645     struct digest_data *mdata = t->data;
646     if (strcmp(keyword, "Input") == 0)
647         return test_bin(value, &mdata->input, &mdata->input_len);
648     if (strcmp(keyword, "Output") == 0)
649         return test_bin(value, &mdata->output, &mdata->output_len);
650     if (strcmp(keyword, "Count") == 0) {
651         long nrpt = atoi(value);
652         if (nrpt <= 0)
653             return 0;
654         mdata->nrpt = (size_t)nrpt;
655         return 1;
656     }
657     return 0;
658 }
659
660 static int digest_test_run(struct evp_test *t)
661 {
662     struct digest_data *mdata = t->data;
663     size_t i;
664     const char *err = "INTERNAL_ERROR";
665     EVP_MD_CTX *mctx;
666     unsigned char md[EVP_MAX_MD_SIZE];
667     unsigned int md_len;
668     mctx = EVP_MD_CTX_new();
669     if (!mctx)
670         goto err;
671     err = "DIGESTINIT_ERROR";
672     if (!EVP_DigestInit_ex(mctx, mdata->digest, NULL))
673         goto err;
674     err = "DIGESTUPDATE_ERROR";
675     for (i = 0; i < mdata->nrpt; i++) {
676         if (!EVP_DigestUpdate(mctx, mdata->input, mdata->input_len))
677             goto err;
678     }
679     err = "DIGESTFINAL_ERROR";
680     if (!EVP_DigestFinal(mctx, md, &md_len))
681         goto err;
682     err = "DIGEST_LENGTH_MISMATCH";
683     if (md_len != mdata->output_len)
684         goto err;
685     err = "DIGEST_MISMATCH";
686     if (check_output(t, mdata->output, md, md_len))
687         goto err;
688     err = NULL;
689  err:
690     EVP_MD_CTX_free(mctx);
691     t->err = err;
692     return 1;
693 }
694
695 static const struct evp_test_method digest_test_method = {
696     "Digest",
697     digest_test_init,
698     digest_test_cleanup,
699     digest_test_parse,
700     digest_test_run
701 };
702
703 /* Cipher tests */
704 struct cipher_data {
705     const EVP_CIPHER *cipher;
706     int enc;
707     /* EVP_CIPH_GCM_MODE, EVP_CIPH_CCM_MODE or EVP_CIPH_OCB_MODE if AEAD */
708     int aead;
709     unsigned char *key;
710     size_t key_len;
711     unsigned char *iv;
712     size_t iv_len;
713     unsigned char *plaintext;
714     size_t plaintext_len;
715     unsigned char *ciphertext;
716     size_t ciphertext_len;
717     /* GCM, CCM only */
718     unsigned char *aad;
719     size_t aad_len;
720     unsigned char *tag;
721     size_t tag_len;
722 };
723
724 static int cipher_test_init(struct evp_test *t, const char *alg)
725 {
726     const EVP_CIPHER *cipher;
727     struct cipher_data *cdat = t->data;
728     cipher = EVP_get_cipherbyname(alg);
729     if (!cipher) {
730         /* If alg has an OID assume disabled algorithm */
731         if (OBJ_sn2nid(alg) != NID_undef || OBJ_ln2nid(alg) != NID_undef) {
732             t->skip = 1;
733             return 1;
734         }
735         return 0;
736     }
737     cdat = OPENSSL_malloc(sizeof(*cdat));
738     cdat->cipher = cipher;
739     cdat->enc = -1;
740     cdat->key = NULL;
741     cdat->iv = NULL;
742     cdat->ciphertext = NULL;
743     cdat->plaintext = NULL;
744     cdat->aad = NULL;
745     cdat->tag = NULL;
746     t->data = cdat;
747     if (EVP_CIPHER_mode(cipher) == EVP_CIPH_GCM_MODE
748         || EVP_CIPHER_mode(cipher) == EVP_CIPH_OCB_MODE
749         || EVP_CIPHER_mode(cipher) == EVP_CIPH_CCM_MODE)
750         cdat->aead = EVP_CIPHER_mode(cipher);
751     else if (EVP_CIPHER_flags(cipher) & EVP_CIPH_FLAG_AEAD_CIPHER)
752         cdat->aead = -1;
753     else
754         cdat->aead = 0;
755
756     return 1;
757 }
758
759 static void cipher_test_cleanup(struct evp_test *t)
760 {
761     struct cipher_data *cdat = t->data;
762     test_free(cdat->key);
763     test_free(cdat->iv);
764     test_free(cdat->ciphertext);
765     test_free(cdat->plaintext);
766     test_free(cdat->aad);
767     test_free(cdat->tag);
768 }
769
770 static int cipher_test_parse(struct evp_test *t, const char *keyword,
771                              const char *value)
772 {
773     struct cipher_data *cdat = t->data;
774     if (strcmp(keyword, "Key") == 0)
775         return test_bin(value, &cdat->key, &cdat->key_len);
776     if (strcmp(keyword, "IV") == 0)
777         return test_bin(value, &cdat->iv, &cdat->iv_len);
778     if (strcmp(keyword, "Plaintext") == 0)
779         return test_bin(value, &cdat->plaintext, &cdat->plaintext_len);
780     if (strcmp(keyword, "Ciphertext") == 0)
781         return test_bin(value, &cdat->ciphertext, &cdat->ciphertext_len);
782     if (cdat->aead) {
783         if (strcmp(keyword, "AAD") == 0)
784             return test_bin(value, &cdat->aad, &cdat->aad_len);
785         if (strcmp(keyword, "Tag") == 0)
786             return test_bin(value, &cdat->tag, &cdat->tag_len);
787     }
788
789     if (strcmp(keyword, "Operation") == 0) {
790         if (strcmp(value, "ENCRYPT") == 0)
791             cdat->enc = 1;
792         else if (strcmp(value, "DECRYPT") == 0)
793             cdat->enc = 0;
794         else
795             return 0;
796         return 1;
797     }
798     return 0;
799 }
800
801 static int cipher_test_enc(struct evp_test *t, int enc,
802                            size_t out_misalign, size_t inp_misalign)
803 {
804     struct cipher_data *cdat = t->data;
805     unsigned char *in, *out, *tmp = NULL;
806     size_t in_len, out_len;
807     int tmplen, tmpflen;
808     EVP_CIPHER_CTX *ctx = NULL;
809     const char *err;
810     err = "INTERNAL_ERROR";
811     ctx = EVP_CIPHER_CTX_new();
812     if (!ctx)
813         goto err;
814     EVP_CIPHER_CTX_set_flags(ctx, EVP_CIPHER_CTX_FLAG_WRAP_ALLOW);
815     if (enc) {
816         in = cdat->plaintext;
817         in_len = cdat->plaintext_len;
818         out = cdat->ciphertext;
819         out_len = cdat->ciphertext_len;
820     } else {
821         in = cdat->ciphertext;
822         in_len = cdat->ciphertext_len;
823         out = cdat->plaintext;
824         out_len = cdat->plaintext_len;
825     }
826     if (inp_misalign == (size_t)-1) {
827         /*
828          * Exercise in-place encryption
829          */
830         tmp = OPENSSL_malloc(out_misalign + in_len + 2 * EVP_MAX_BLOCK_LENGTH);
831         if (!tmp)
832             goto err;
833         in = memcpy(tmp + out_misalign, in, in_len);
834     } else {
835         inp_misalign += 16 - ((out_misalign + in_len) & 15);
836         /*
837          * 'tmp' will store both output and copy of input. We make the copy
838          * of input to specifically aligned part of 'tmp'. So we just
839          * figured out how much padding would ensure the required alignment,
840          * now we allocate extended buffer and finally copy the input just
841          * past inp_misalign in expression below. Output will be written
842          * past out_misalign...
843          */
844         tmp = OPENSSL_malloc(out_misalign + in_len + 2 * EVP_MAX_BLOCK_LENGTH +
845                              inp_misalign + in_len);
846         if (!tmp)
847             goto err;
848         in = memcpy(tmp + out_misalign + in_len + 2 * EVP_MAX_BLOCK_LENGTH +
849                     inp_misalign, in, in_len);
850     }
851     err = "CIPHERINIT_ERROR";
852     if (!EVP_CipherInit_ex(ctx, cdat->cipher, NULL, NULL, NULL, enc))
853         goto err;
854     err = "INVALID_IV_LENGTH";
855     if (cdat->iv) {
856         if (cdat->aead) {
857             if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_IVLEN,
858                                      cdat->iv_len, 0))
859                 goto err;
860         } else if (cdat->iv_len != (size_t)EVP_CIPHER_CTX_iv_length(ctx))
861             goto err;
862     }
863     if (cdat->aead) {
864         unsigned char *tag;
865         /*
866          * If encrypting or OCB just set tag length initially, otherwise
867          * set tag length and value.
868          */
869         if (enc || cdat->aead == EVP_CIPH_OCB_MODE) {
870             err = "TAG_LENGTH_SET_ERROR";
871             tag = NULL;
872         } else {
873             err = "TAG_SET_ERROR";
874             tag = cdat->tag;
875         }
876         if (tag || cdat->aead != EVP_CIPH_GCM_MODE) {
877             if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_TAG,
878                                      cdat->tag_len, tag))
879                 goto err;
880         }
881     }
882
883     err = "INVALID_KEY_LENGTH";
884     if (!EVP_CIPHER_CTX_set_key_length(ctx, cdat->key_len))
885         goto err;
886     err = "KEY_SET_ERROR";
887     if (!EVP_CipherInit_ex(ctx, NULL, NULL, cdat->key, cdat->iv, -1))
888         goto err;
889
890     if (!enc && cdat->aead == EVP_CIPH_OCB_MODE) {
891         if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_TAG,
892                                  cdat->tag_len, cdat->tag)) {
893             err = "TAG_SET_ERROR";
894             goto err;
895         }
896     }
897
898     if (cdat->aead == EVP_CIPH_CCM_MODE) {
899         if (!EVP_CipherUpdate(ctx, NULL, &tmplen, NULL, out_len)) {
900             err = "CCM_PLAINTEXT_LENGTH_SET_ERROR";
901             goto err;
902         }
903     }
904     if (cdat->aad) {
905         if (!EVP_CipherUpdate(ctx, NULL, &tmplen, cdat->aad, cdat->aad_len)) {
906             err = "AAD_SET_ERROR";
907             goto err;
908         }
909     }
910     EVP_CIPHER_CTX_set_padding(ctx, 0);
911     err = "CIPHERUPDATE_ERROR";
912     if (!EVP_CipherUpdate(ctx, tmp + out_misalign, &tmplen, in, in_len))
913         goto err;
914     if (cdat->aead == EVP_CIPH_CCM_MODE)
915         tmpflen = 0;
916     else {
917         err = "CIPHERFINAL_ERROR";
918         if (!EVP_CipherFinal_ex(ctx, tmp + out_misalign + tmplen, &tmpflen))
919             goto err;
920     }
921     err = "LENGTH_MISMATCH";
922     if (out_len != (size_t)(tmplen + tmpflen))
923         goto err;
924     err = "VALUE_MISMATCH";
925     if (check_output(t, out, tmp + out_misalign, out_len))
926         goto err;
927     if (enc && cdat->aead) {
928         unsigned char rtag[16];
929         if (cdat->tag_len > sizeof(rtag)) {
930             err = "TAG_LENGTH_INTERNAL_ERROR";
931             goto err;
932         }
933         if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_GET_TAG,
934                                  cdat->tag_len, rtag)) {
935             err = "TAG_RETRIEVE_ERROR";
936             goto err;
937         }
938         if (check_output(t, cdat->tag, rtag, cdat->tag_len)) {
939             err = "TAG_VALUE_MISMATCH";
940             goto err;
941         }
942     }
943     err = NULL;
944  err:
945     OPENSSL_free(tmp);
946     EVP_CIPHER_CTX_free(ctx);
947     t->err = err;
948     return err ? 0 : 1;
949 }
950
951 static int cipher_test_run(struct evp_test *t)
952 {
953     struct cipher_data *cdat = t->data;
954     int rv;
955     size_t out_misalign, inp_misalign;
956
957     if (!cdat->key) {
958         t->err = "NO_KEY";
959         return 0;
960     }
961     if (!cdat->iv && EVP_CIPHER_iv_length(cdat->cipher)) {
962         /* IV is optional and usually omitted in wrap mode */
963         if (EVP_CIPHER_mode(cdat->cipher) != EVP_CIPH_WRAP_MODE) {
964             t->err = "NO_IV";
965             return 0;
966         }
967     }
968     if (cdat->aead && !cdat->tag) {
969         t->err = "NO_TAG";
970         return 0;
971     }
972     for (out_misalign = 0; out_misalign <= 1; out_misalign++) {
973         static char aux_err[64];
974         t->aux_err = aux_err;
975         for (inp_misalign = (size_t)-1; inp_misalign != 2; inp_misalign++) {
976             if (inp_misalign == (size_t)-1) {
977                 /* kludge: inp_misalign == -1 means "exercise in-place" */
978                 BIO_snprintf(aux_err, sizeof(aux_err), "%s in-place",
979                              out_misalign ? "misaligned" : "aligned");
980             } else {
981                 BIO_snprintf(aux_err, sizeof(aux_err), "%s output and %s input",
982                              out_misalign ? "misaligned" : "aligned",
983                              inp_misalign ? "misaligned" : "aligned");
984             }
985             if (cdat->enc) {
986                 rv = cipher_test_enc(t, 1, out_misalign, inp_misalign);
987                 /* Not fatal errors: return */
988                 if (rv != 1) {
989                     if (rv < 0)
990                         return 0;
991                     return 1;
992                 }
993             }
994             if (cdat->enc != 1) {
995                 rv = cipher_test_enc(t, 0, out_misalign, inp_misalign);
996                 /* Not fatal errors: return */
997                 if (rv != 1) {
998                     if (rv < 0)
999                         return 0;
1000                     return 1;
1001                 }
1002             }
1003         }
1004     }
1005     t->aux_err = NULL;
1006
1007     return 1;
1008 }
1009
1010 static const struct evp_test_method cipher_test_method = {
1011     "Cipher",
1012     cipher_test_init,
1013     cipher_test_cleanup,
1014     cipher_test_parse,
1015     cipher_test_run
1016 };
1017
1018 struct mac_data {
1019     /* MAC type */
1020     int type;
1021     /* Algorithm string for this MAC */
1022     char *alg;
1023     /* MAC key */
1024     unsigned char *key;
1025     size_t key_len;
1026     /* Input to MAC */
1027     unsigned char *input;
1028     size_t input_len;
1029     /* Expected output */
1030     unsigned char *output;
1031     size_t output_len;
1032 };
1033
1034 static int mac_test_init(struct evp_test *t, const char *alg)
1035 {
1036     int type;
1037     struct mac_data *mdat;
1038     if (strcmp(alg, "HMAC") == 0) {
1039         type = EVP_PKEY_HMAC;
1040     } else if (strcmp(alg, "CMAC") == 0) {
1041 #ifndef OPENSSL_NO_CMAC
1042         type = EVP_PKEY_CMAC;
1043 #else
1044         t->skip = 1;
1045         return 1;
1046 #endif
1047     } else
1048         return 0;
1049
1050     mdat = OPENSSL_malloc(sizeof(*mdat));
1051     mdat->type = type;
1052     mdat->alg = NULL;
1053     mdat->key = NULL;
1054     mdat->input = NULL;
1055     mdat->output = NULL;
1056     t->data = mdat;
1057     return 1;
1058 }
1059
1060 static void mac_test_cleanup(struct evp_test *t)
1061 {
1062     struct mac_data *mdat = t->data;
1063     test_free(mdat->alg);
1064     test_free(mdat->key);
1065     test_free(mdat->input);
1066     test_free(mdat->output);
1067 }
1068
1069 static int mac_test_parse(struct evp_test *t,
1070                           const char *keyword, const char *value)
1071 {
1072     struct mac_data *mdata = t->data;
1073     if (strcmp(keyword, "Key") == 0)
1074         return test_bin(value, &mdata->key, &mdata->key_len);
1075     if (strcmp(keyword, "Algorithm") == 0) {
1076         mdata->alg = OPENSSL_strdup(value);
1077         if (!mdata->alg)
1078             return 0;
1079         return 1;
1080     }
1081     if (strcmp(keyword, "Input") == 0)
1082         return test_bin(value, &mdata->input, &mdata->input_len);
1083     if (strcmp(keyword, "Output") == 0)
1084         return test_bin(value, &mdata->output, &mdata->output_len);
1085     return 0;
1086 }
1087
1088 static int mac_test_run(struct evp_test *t)
1089 {
1090     struct mac_data *mdata = t->data;
1091     const char *err = "INTERNAL_ERROR";
1092     EVP_MD_CTX *mctx = NULL;
1093     EVP_PKEY_CTX *pctx = NULL, *genctx = NULL;
1094     EVP_PKEY *key = NULL;
1095     const EVP_MD *md = NULL;
1096     unsigned char *mac = NULL;
1097     size_t mac_len;
1098
1099 #ifdef OPENSSL_NO_DES
1100     if (strstr(mdata->alg, "DES") != NULL) {
1101         /* Skip DES */
1102         err = NULL;
1103         goto err;
1104     }
1105 #endif
1106
1107     err = "MAC_PKEY_CTX_ERROR";
1108     genctx = EVP_PKEY_CTX_new_id(mdata->type, NULL);
1109     if (!genctx)
1110         goto err;
1111
1112     err = "MAC_KEYGEN_INIT_ERROR";
1113     if (EVP_PKEY_keygen_init(genctx) <= 0)
1114         goto err;
1115     if (mdata->type == EVP_PKEY_CMAC) {
1116         err = "MAC_ALGORITHM_SET_ERROR";
1117         if (EVP_PKEY_CTX_ctrl_str(genctx, "cipher", mdata->alg) <= 0)
1118             goto err;
1119     }
1120
1121     err = "MAC_KEY_SET_ERROR";
1122     if (EVP_PKEY_CTX_set_mac_key(genctx, mdata->key, mdata->key_len) <= 0)
1123         goto err;
1124
1125     err = "MAC_KEY_GENERATE_ERROR";
1126     if (EVP_PKEY_keygen(genctx, &key) <= 0)
1127         goto err;
1128     if (mdata->type == EVP_PKEY_HMAC) {
1129         err = "MAC_ALGORITHM_SET_ERROR";
1130         md = EVP_get_digestbyname(mdata->alg);
1131         if (!md)
1132             goto err;
1133     }
1134     mctx = EVP_MD_CTX_new();
1135     if (!mctx)
1136         goto err;
1137     err = "DIGESTSIGNINIT_ERROR";
1138     if (!EVP_DigestSignInit(mctx, &pctx, md, NULL, key))
1139         goto err;
1140
1141     err = "DIGESTSIGNUPDATE_ERROR";
1142     if (!EVP_DigestSignUpdate(mctx, mdata->input, mdata->input_len))
1143         goto err;
1144     err = "DIGESTSIGNFINAL_LENGTH_ERROR";
1145     if (!EVP_DigestSignFinal(mctx, NULL, &mac_len))
1146         goto err;
1147     mac = OPENSSL_malloc(mac_len);
1148     if (!mac) {
1149         fprintf(stderr, "Error allocating mac buffer!\n");
1150         exit(1);
1151     }
1152     if (!EVP_DigestSignFinal(mctx, mac, &mac_len))
1153         goto err;
1154     err = "MAC_LENGTH_MISMATCH";
1155     if (mac_len != mdata->output_len)
1156         goto err;
1157     err = "MAC_MISMATCH";
1158     if (check_output(t, mdata->output, mac, mac_len))
1159         goto err;
1160     err = NULL;
1161  err:
1162     EVP_MD_CTX_free(mctx);
1163     OPENSSL_free(mac);
1164     EVP_PKEY_CTX_free(genctx);
1165     EVP_PKEY_free(key);
1166     t->err = err;
1167     return 1;
1168 }
1169
1170 static const struct evp_test_method mac_test_method = {
1171     "MAC",
1172     mac_test_init,
1173     mac_test_cleanup,
1174     mac_test_parse,
1175     mac_test_run
1176 };
1177
1178 /*
1179  * Public key operations. These are all very similar and can share
1180  * a lot of common code.
1181  */
1182
1183 struct pkey_data {
1184     /* Context for this operation */
1185     EVP_PKEY_CTX *ctx;
1186     /* Key operation to perform */
1187     int (*keyop) (EVP_PKEY_CTX *ctx,
1188                   unsigned char *sig, size_t *siglen,
1189                   const unsigned char *tbs, size_t tbslen);
1190     /* Input to MAC */
1191     unsigned char *input;
1192     size_t input_len;
1193     /* Expected output */
1194     unsigned char *output;
1195     size_t output_len;
1196 };
1197
1198 /*
1199  * Perform public key operation setup: lookup key, allocated ctx and call
1200  * the appropriate initialisation function
1201  */
1202 static int pkey_test_init(struct evp_test *t, const char *name,
1203                           int use_public,
1204                           int (*keyopinit) (EVP_PKEY_CTX *ctx),
1205                           int (*keyop) (EVP_PKEY_CTX *ctx,
1206                                         unsigned char *sig, size_t *siglen,
1207                                         const unsigned char *tbs,
1208                                         size_t tbslen)
1209     )
1210 {
1211     struct pkey_data *kdata;
1212     EVP_PKEY *pkey = NULL;
1213     int rv = 0;
1214     if (use_public)
1215         rv = find_key(&pkey, name, t->public);
1216     if (!rv)
1217         rv = find_key(&pkey, name, t->private);
1218     if (!rv || pkey == NULL) {
1219         t->skip = 1;
1220         return 1;
1221     }
1222
1223     kdata = OPENSSL_malloc(sizeof(*kdata));
1224     if (!kdata) {
1225         EVP_PKEY_free(pkey);
1226         return 0;
1227     }
1228     kdata->ctx = NULL;
1229     kdata->input = NULL;
1230     kdata->output = NULL;
1231     kdata->keyop = keyop;
1232     t->data = kdata;
1233     kdata->ctx = EVP_PKEY_CTX_new(pkey, NULL);
1234     if (!kdata->ctx)
1235         return 0;
1236     if (keyopinit(kdata->ctx) <= 0)
1237         t->err = "KEYOP_INIT_ERROR";
1238     return 1;
1239 }
1240
1241 static void pkey_test_cleanup(struct evp_test *t)
1242 {
1243     struct pkey_data *kdata = t->data;
1244
1245     OPENSSL_free(kdata->input);
1246     OPENSSL_free(kdata->output);
1247     EVP_PKEY_CTX_free(kdata->ctx);
1248 }
1249
1250 static int pkey_test_ctrl(struct evp_test *t, EVP_PKEY_CTX *pctx,
1251                           const char *value)
1252 {
1253     int rv;
1254     char *p, *tmpval;
1255
1256     tmpval = OPENSSL_strdup(value);
1257     if (tmpval == NULL)
1258         return 0;
1259     p = strchr(tmpval, ':');
1260     if (p != NULL)
1261         *p++ = 0;
1262     rv = EVP_PKEY_CTX_ctrl_str(pctx, tmpval, p);
1263     if (rv == -2) {
1264         t->err = "PKEY_CTRL_INVALID";
1265         rv = 1;
1266     } else if (p != NULL && rv <= 0) {
1267         /* If p has an OID and lookup fails assume disabled algorithm */
1268         int nid = OBJ_sn2nid(p);
1269         if (nid == NID_undef)
1270              nid = OBJ_ln2nid(p);
1271         if ((nid != NID_undef) && EVP_get_digestbynid(nid) == NULL &&
1272             EVP_get_cipherbynid(nid) == NULL) {
1273             t->skip = 1;
1274             rv = 1;
1275         } else {
1276             t->err = "PKEY_CTRL_ERROR";
1277             rv = 1;
1278         }
1279     }
1280     OPENSSL_free(tmpval);
1281     return rv > 0;
1282 }
1283
1284 static int pkey_test_parse(struct evp_test *t,
1285                            const char *keyword, const char *value)
1286 {
1287     struct pkey_data *kdata = t->data;
1288     if (strcmp(keyword, "Input") == 0)
1289         return test_bin(value, &kdata->input, &kdata->input_len);
1290     if (strcmp(keyword, "Output") == 0)
1291         return test_bin(value, &kdata->output, &kdata->output_len);
1292     if (strcmp(keyword, "Ctrl") == 0)
1293         return pkey_test_ctrl(t, kdata->ctx, value);
1294     return 0;
1295 }
1296
1297 static int pkey_test_run(struct evp_test *t)
1298 {
1299     struct pkey_data *kdata = t->data;
1300     unsigned char *out = NULL;
1301     size_t out_len;
1302     const char *err = "KEYOP_LENGTH_ERROR";
1303     if (kdata->keyop(kdata->ctx, NULL, &out_len, kdata->input,
1304                      kdata->input_len) <= 0)
1305         goto err;
1306     out = OPENSSL_malloc(out_len);
1307     if (!out) {
1308         fprintf(stderr, "Error allocating output buffer!\n");
1309         exit(1);
1310     }
1311     err = "KEYOP_ERROR";
1312     if (kdata->keyop
1313         (kdata->ctx, out, &out_len, kdata->input, kdata->input_len) <= 0)
1314         goto err;
1315     err = "KEYOP_LENGTH_MISMATCH";
1316     if (out_len != kdata->output_len)
1317         goto err;
1318     err = "KEYOP_MISMATCH";
1319     if (check_output(t, kdata->output, out, out_len))
1320         goto err;
1321     err = NULL;
1322  err:
1323     OPENSSL_free(out);
1324     t->err = err;
1325     return 1;
1326 }
1327
1328 static int sign_test_init(struct evp_test *t, const char *name)
1329 {
1330     return pkey_test_init(t, name, 0, EVP_PKEY_sign_init, EVP_PKEY_sign);
1331 }
1332
1333 static const struct evp_test_method psign_test_method = {
1334     "Sign",
1335     sign_test_init,
1336     pkey_test_cleanup,
1337     pkey_test_parse,
1338     pkey_test_run
1339 };
1340
1341 static int verify_recover_test_init(struct evp_test *t, const char *name)
1342 {
1343     return pkey_test_init(t, name, 1, EVP_PKEY_verify_recover_init,
1344                           EVP_PKEY_verify_recover);
1345 }
1346
1347 static const struct evp_test_method pverify_recover_test_method = {
1348     "VerifyRecover",
1349     verify_recover_test_init,
1350     pkey_test_cleanup,
1351     pkey_test_parse,
1352     pkey_test_run
1353 };
1354
1355 static int decrypt_test_init(struct evp_test *t, const char *name)
1356 {
1357     return pkey_test_init(t, name, 0, EVP_PKEY_decrypt_init,
1358                           EVP_PKEY_decrypt);
1359 }
1360
1361 static const struct evp_test_method pdecrypt_test_method = {
1362     "Decrypt",
1363     decrypt_test_init,
1364     pkey_test_cleanup,
1365     pkey_test_parse,
1366     pkey_test_run
1367 };
1368
1369 static int verify_test_init(struct evp_test *t, const char *name)
1370 {
1371     return pkey_test_init(t, name, 1, EVP_PKEY_verify_init, 0);
1372 }
1373
1374 static int verify_test_run(struct evp_test *t)
1375 {
1376     struct pkey_data *kdata = t->data;
1377     if (EVP_PKEY_verify(kdata->ctx, kdata->output, kdata->output_len,
1378                         kdata->input, kdata->input_len) <= 0)
1379         t->err = "VERIFY_ERROR";
1380     return 1;
1381 }
1382
1383 static const struct evp_test_method pverify_test_method = {
1384     "Verify",
1385     verify_test_init,
1386     pkey_test_cleanup,
1387     pkey_test_parse,
1388     verify_test_run
1389 };
1390
1391
1392 static int pderive_test_init(struct evp_test *t, const char *name)
1393 {
1394     return pkey_test_init(t, name, 0, EVP_PKEY_derive_init, 0);
1395 }
1396
1397 static int pderive_test_parse(struct evp_test *t,
1398                               const char *keyword, const char *value)
1399 {
1400     struct pkey_data *kdata = t->data;
1401
1402     if (strcmp(keyword, "PeerKey") == 0) {
1403         EVP_PKEY *peer;
1404         if (find_key(&peer, value, t->public) == 0)
1405             return 0;
1406         if (EVP_PKEY_derive_set_peer(kdata->ctx, peer) <= 0)
1407             return 0;
1408         return 1;
1409     }
1410     if (strcmp(keyword, "SharedSecret") == 0)
1411         return test_bin(value, &kdata->output, &kdata->output_len);
1412     if (strcmp(keyword, "Ctrl") == 0)
1413         return pkey_test_ctrl(t, kdata->ctx, value);
1414     return 0;
1415 }
1416
1417 static int pderive_test_run(struct evp_test *t)
1418 {
1419     struct pkey_data *kdata = t->data;
1420     unsigned char *out = NULL;
1421     size_t out_len;
1422     const char *err = "INTERNAL_ERROR";
1423
1424     out_len = kdata->output_len;
1425     out = OPENSSL_malloc(out_len);
1426     if (!out) {
1427         fprintf(stderr, "Error allocating output buffer!\n");
1428         exit(1);
1429     }
1430     err = "DERIVE_ERROR";
1431     if (EVP_PKEY_derive(kdata->ctx, out, &out_len) <= 0)
1432         goto err;
1433     err = "SHARED_SECRET_LENGTH_MISMATCH";
1434     if (out_len != kdata->output_len)
1435         goto err;
1436     err = "SHARED_SECRET_MISMATCH";
1437     if (check_output(t, kdata->output, out, out_len))
1438         goto err;
1439     err = NULL;
1440  err:
1441     OPENSSL_free(out);
1442     t->err = err;
1443     return 1;
1444 }
1445
1446 static const struct evp_test_method pderive_test_method = {
1447     "Derive",
1448     pderive_test_init,
1449     pkey_test_cleanup,
1450     pderive_test_parse,
1451     pderive_test_run
1452 };
1453
1454 /* PBE tests */
1455
1456 #define PBE_TYPE_SCRYPT 1
1457 #define PBE_TYPE_PBKDF2 2
1458 #define PBE_TYPE_PKCS12 3
1459
1460 struct pbe_data {
1461
1462     int pbe_type;
1463
1464     /* scrypt parameters */
1465     uint64_t N, r, p, maxmem;
1466
1467     /* PKCS#12 parameters */
1468     int id, iter;
1469     const EVP_MD *md;
1470
1471     /* password */
1472     unsigned char *pass;
1473     size_t pass_len;
1474
1475     /* salt */
1476     unsigned char *salt;
1477     size_t salt_len;
1478
1479     /* Expected output */
1480     unsigned char *key;
1481     size_t key_len;
1482 };
1483
1484 #ifndef OPENSSL_NO_SCRYPT
1485 static int scrypt_test_parse(struct evp_test *t,
1486                              const char *keyword, const char *value)
1487 {
1488     struct pbe_data *pdata = t->data;
1489
1490     if (strcmp(keyword, "N") == 0)
1491         return test_uint64(value, &pdata->N);
1492     if (strcmp(keyword, "p") == 0)
1493         return test_uint64(value, &pdata->p);
1494     if (strcmp(keyword, "r") == 0)
1495         return test_uint64(value, &pdata->r);
1496     if (strcmp(keyword, "maxmem") == 0)
1497         return test_uint64(value, &pdata->maxmem);
1498     return 0;
1499 }
1500 #endif
1501
1502 static int pbkdf2_test_parse(struct evp_test *t,
1503                              const char *keyword, const char *value)
1504 {
1505     struct pbe_data *pdata = t->data;
1506
1507     if (strcmp(keyword, "iter") == 0) {
1508         pdata->iter = atoi(value);
1509         if (pdata->iter <= 0)
1510             return 0;
1511         return 1;
1512     }
1513     if (strcmp(keyword, "MD") == 0) {
1514         pdata->md = EVP_get_digestbyname(value);
1515         if (pdata->md == NULL)
1516             return 0;
1517         return 1;
1518     }
1519     return 0;
1520 }
1521
1522 static int pkcs12_test_parse(struct evp_test *t,
1523                              const char *keyword, const char *value)
1524 {
1525     struct pbe_data *pdata = t->data;
1526
1527     if (strcmp(keyword, "id") == 0) {
1528         pdata->id = atoi(value);
1529         if (pdata->id <= 0)
1530             return 0;
1531         return 1;
1532     }
1533     return pbkdf2_test_parse(t, keyword, value);
1534 }
1535
1536 static int pbe_test_init(struct evp_test *t, const char *alg)
1537 {
1538     struct pbe_data *pdat;
1539     int pbe_type = 0;
1540
1541     if (strcmp(alg, "scrypt") == 0) {
1542 #ifndef OPENSSL_NO_SCRYPT
1543         pbe_type = PBE_TYPE_SCRYPT;
1544 #else
1545         t->skip = 1;
1546         return 1;
1547 #endif
1548     } else if (strcmp(alg, "pbkdf2") == 0) {
1549         pbe_type = PBE_TYPE_PBKDF2;
1550     } else if (strcmp(alg, "pkcs12") == 0) {
1551         pbe_type = PBE_TYPE_PKCS12;
1552     } else {
1553         fprintf(stderr, "Unknown pbe algorithm %s\n", alg);
1554     }
1555     pdat = OPENSSL_malloc(sizeof(*pdat));
1556     pdat->pbe_type = pbe_type;
1557     pdat->pass = NULL;
1558     pdat->salt = NULL;
1559     pdat->N = 0;
1560     pdat->r = 0;
1561     pdat->p = 0;
1562     pdat->maxmem = 0;
1563     pdat->id = 0;
1564     pdat->iter = 0;
1565     pdat->md = NULL;
1566     t->data = pdat;
1567     return 1;
1568 }
1569
1570 static void pbe_test_cleanup(struct evp_test *t)
1571 {
1572     struct pbe_data *pdat = t->data;
1573     test_free(pdat->pass);
1574     test_free(pdat->salt);
1575     test_free(pdat->key);
1576 }
1577
1578 static int pbe_test_parse(struct evp_test *t,
1579                              const char *keyword, const char *value)
1580 {
1581     struct pbe_data *pdata = t->data;
1582
1583     if (strcmp(keyword, "Password") == 0)
1584         return test_bin(value, &pdata->pass, &pdata->pass_len);
1585     if (strcmp(keyword, "Salt") == 0)
1586         return test_bin(value, &pdata->salt, &pdata->salt_len);
1587     if (strcmp(keyword, "Key") == 0)
1588         return test_bin(value, &pdata->key, &pdata->key_len);
1589     if (pdata->pbe_type == PBE_TYPE_PBKDF2)
1590         return pbkdf2_test_parse(t, keyword, value);
1591     else if (pdata->pbe_type == PBE_TYPE_PKCS12)
1592         return pkcs12_test_parse(t, keyword, value);
1593 #ifndef OPENSSL_NO_SCRYPT
1594     else if (pdata->pbe_type == PBE_TYPE_SCRYPT)
1595         return scrypt_test_parse(t, keyword, value);
1596 #endif
1597     return 0;
1598 }
1599
1600 static int pbe_test_run(struct evp_test *t)
1601 {
1602     struct pbe_data *pdata = t->data;
1603     const char *err = "INTERNAL_ERROR";
1604     unsigned char *key;
1605
1606     key = OPENSSL_malloc(pdata->key_len);
1607     if (!key)
1608         goto err;
1609     if (pdata->pbe_type == PBE_TYPE_PBKDF2) {
1610         err = "PBKDF2_ERROR";
1611         if (PKCS5_PBKDF2_HMAC((char *)pdata->pass, pdata->pass_len,
1612                               pdata->salt, pdata->salt_len,
1613                               pdata->iter, pdata->md,
1614                               pdata->key_len, key) == 0)
1615             goto err;
1616 #ifndef OPENSSL_NO_SCRYPT
1617     } else if (pdata->pbe_type == PBE_TYPE_SCRYPT) {
1618         err = "SCRYPT_ERROR";
1619         if (EVP_PBE_scrypt((const char *)pdata->pass, pdata->pass_len,
1620                            pdata->salt, pdata->salt_len,
1621                            pdata->N, pdata->r, pdata->p, pdata->maxmem,
1622                            key, pdata->key_len) == 0)
1623             goto err;
1624 #endif
1625     } else if (pdata->pbe_type == PBE_TYPE_PKCS12) {
1626         err = "PKCS12_ERROR";
1627         if (PKCS12_key_gen_uni(pdata->pass, pdata->pass_len,
1628                                pdata->salt, pdata->salt_len,
1629                                pdata->id, pdata->iter, pdata->key_len,
1630                                key, pdata->md) == 0)
1631             goto err;
1632     }
1633     err = "KEY_MISMATCH";
1634     if (check_output(t, pdata->key, key, pdata->key_len))
1635         goto err;
1636     err = NULL;
1637     err:
1638     OPENSSL_free(key);
1639     t->err = err;
1640     return 1;
1641 }
1642
1643 static const struct evp_test_method pbe_test_method = {
1644     "PBE",
1645     pbe_test_init,
1646     pbe_test_cleanup,
1647     pbe_test_parse,
1648     pbe_test_run
1649 };
1650
1651 /* Base64 tests */
1652
1653 typedef enum {
1654     BASE64_CANONICAL_ENCODING = 0,
1655     BASE64_VALID_ENCODING = 1,
1656     BASE64_INVALID_ENCODING = 2
1657 } base64_encoding_type;
1658
1659 struct encode_data {
1660     /* Input to encoding */
1661     unsigned char *input;
1662     size_t input_len;
1663     /* Expected output */
1664     unsigned char *output;
1665     size_t output_len;
1666     base64_encoding_type encoding;
1667 };
1668
1669 static int encode_test_init(struct evp_test *t, const char *encoding)
1670 {
1671     struct encode_data *edata = OPENSSL_zalloc(sizeof(*edata));
1672
1673     if (strcmp(encoding, "canonical") == 0) {
1674         edata->encoding = BASE64_CANONICAL_ENCODING;
1675     } else if (strcmp(encoding, "valid") == 0) {
1676         edata->encoding = BASE64_VALID_ENCODING;
1677     } else if (strcmp(encoding, "invalid") == 0) {
1678         edata->encoding = BASE64_INVALID_ENCODING;
1679         t->expected_err = OPENSSL_strdup("DECODE_ERROR");
1680         if (t->expected_err == NULL)
1681             return 0;
1682     } else {
1683         fprintf(stderr, "Bad encoding: %s. Should be one of "
1684                 "{canonical, valid, invalid}\n", encoding);
1685         return 0;
1686     }
1687     t->data = edata;
1688     return 1;
1689 }
1690
1691 static void encode_test_cleanup(struct evp_test *t)
1692 {
1693     struct encode_data *edata = t->data;
1694     test_free(edata->input);
1695     test_free(edata->output);
1696     memset(edata, 0, sizeof(*edata));
1697 }
1698
1699 static int encode_test_parse(struct evp_test *t,
1700                              const char *keyword, const char *value)
1701 {
1702     struct encode_data *edata = t->data;
1703     if (strcmp(keyword, "Input") == 0)
1704         return test_bin(value, &edata->input, &edata->input_len);
1705     if (strcmp(keyword, "Output") == 0)
1706         return test_bin(value, &edata->output, &edata->output_len);
1707     return 0;
1708 }
1709
1710 static int encode_test_run(struct evp_test *t)
1711 {
1712     struct encode_data *edata = t->data;
1713     unsigned char *encode_out = NULL, *decode_out = NULL;
1714     int output_len, chunk_len;
1715     const char *err = "INTERNAL_ERROR";
1716     EVP_ENCODE_CTX *decode_ctx = EVP_ENCODE_CTX_new();
1717
1718     if (decode_ctx == NULL)
1719         goto err;
1720
1721     if (edata->encoding == BASE64_CANONICAL_ENCODING) {
1722         EVP_ENCODE_CTX *encode_ctx = EVP_ENCODE_CTX_new();
1723         if (encode_ctx == NULL)
1724             goto err;
1725         encode_out = OPENSSL_malloc(EVP_ENCODE_LENGTH(edata->input_len));
1726         if (encode_out == NULL)
1727             goto err;
1728
1729         EVP_EncodeInit(encode_ctx);
1730         EVP_EncodeUpdate(encode_ctx, encode_out, &chunk_len,
1731                          edata->input, edata->input_len);
1732         output_len = chunk_len;
1733
1734         EVP_EncodeFinal(encode_ctx, encode_out + chunk_len, &chunk_len);
1735         output_len += chunk_len;
1736
1737         EVP_ENCODE_CTX_free(encode_ctx);
1738
1739         if (check_var_length_output(t, edata->output, edata->output_len,
1740                                     encode_out, output_len)) {
1741             err = "BAD_ENCODING";
1742             goto err;
1743         }
1744     }
1745
1746     decode_out = OPENSSL_malloc(EVP_DECODE_LENGTH(edata->output_len));
1747     if (decode_out == NULL)
1748         goto err;
1749
1750     EVP_DecodeInit(decode_ctx);
1751     if (EVP_DecodeUpdate(decode_ctx, decode_out, &chunk_len, edata->output,
1752                          edata->output_len) < 0) {
1753         err = "DECODE_ERROR";
1754         goto err;
1755     }
1756     output_len = chunk_len;
1757
1758     if (EVP_DecodeFinal(decode_ctx, decode_out + chunk_len, &chunk_len) != 1) {
1759         err = "DECODE_ERROR";
1760         goto err;
1761     }
1762     output_len += chunk_len;
1763
1764     if (edata->encoding != BASE64_INVALID_ENCODING &&
1765         check_var_length_output(t, edata->input, edata->input_len,
1766                                 decode_out, output_len)) {
1767         err = "BAD_DECODING";
1768         goto err;
1769     }
1770
1771     err = NULL;
1772  err:
1773     t->err = err;
1774     OPENSSL_free(encode_out);
1775     OPENSSL_free(decode_out);
1776     EVP_ENCODE_CTX_free(decode_ctx);
1777     return 1;
1778 }
1779
1780 static const struct evp_test_method encode_test_method = {
1781     "Encoding",
1782     encode_test_init,
1783     encode_test_cleanup,
1784     encode_test_parse,
1785     encode_test_run,
1786 };
1787
1788 /* KDF operations */
1789
1790 struct kdf_data {
1791     /* Context for this operation */
1792     EVP_PKEY_CTX *ctx;
1793     /* Expected output */
1794     unsigned char *output;
1795     size_t output_len;
1796 };
1797
1798 /*
1799  * Perform public key operation setup: lookup key, allocated ctx and call
1800  * the appropriate initialisation function
1801  */
1802 static int kdf_test_init(struct evp_test *t, const char *name)
1803 {
1804     struct kdf_data *kdata;
1805
1806     kdata = OPENSSL_malloc(sizeof(*kdata));
1807     if (kdata == NULL)
1808         return 0;
1809     kdata->ctx = NULL;
1810     kdata->output = NULL;
1811     t->data = kdata;
1812     kdata->ctx = EVP_PKEY_CTX_new_id(OBJ_sn2nid(name), NULL);
1813     if (kdata->ctx == NULL)
1814         return 0;
1815     if (EVP_PKEY_derive_init(kdata->ctx) <= 0)
1816         return 0;
1817     return 1;
1818 }
1819
1820 static void kdf_test_cleanup(struct evp_test *t)
1821 {
1822     struct kdf_data *kdata = t->data;
1823     OPENSSL_free(kdata->output);
1824     EVP_PKEY_CTX_free(kdata->ctx);
1825 }
1826
1827 static int kdf_test_parse(struct evp_test *t,
1828                           const char *keyword, const char *value)
1829 {
1830     struct kdf_data *kdata = t->data;
1831     if (strcmp(keyword, "Output") == 0)
1832         return test_bin(value, &kdata->output, &kdata->output_len);
1833     if (strncmp(keyword, "Ctrl", 4) == 0)
1834         return pkey_test_ctrl(t, kdata->ctx, value);
1835     return 0;
1836 }
1837
1838 static int kdf_test_run(struct evp_test *t)
1839 {
1840     struct kdf_data *kdata = t->data;
1841     unsigned char *out = NULL;
1842     size_t out_len = kdata->output_len;
1843     const char *err = "INTERNAL_ERROR";
1844     out = OPENSSL_malloc(out_len);
1845     if (!out) {
1846         fprintf(stderr, "Error allocating output buffer!\n");
1847         exit(1);
1848     }
1849     err = "KDF_DERIVE_ERROR";
1850     if (EVP_PKEY_derive(kdata->ctx, out, &out_len) <= 0)
1851         goto err;
1852     err = "KDF_LENGTH_MISMATCH";
1853     if (out_len != kdata->output_len)
1854         goto err;
1855     err = "KDF_MISMATCH";
1856     if (check_output(t, kdata->output, out, out_len))
1857         goto err;
1858     err = NULL;
1859  err:
1860     OPENSSL_free(out);
1861     t->err = err;
1862     return 1;
1863 }
1864
1865 static const struct evp_test_method kdf_test_method = {
1866     "KDF",
1867     kdf_test_init,
1868     kdf_test_cleanup,
1869     kdf_test_parse,
1870     kdf_test_run
1871 };