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