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