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