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