c86d3bea30383f6be4037c6c5354dd165d920347
[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 static const EVP_TEST_METHOD digestsign_test_method;
408 static const EVP_TEST_METHOD digestverify_test_method;
409 static const EVP_TEST_METHOD oneshot_digestsign_test_method;
410 static const EVP_TEST_METHOD oneshot_digestverify_test_method;
411
412 static const EVP_TEST_METHOD *evp_test_list[] = {
413     &digest_test_method,
414     &cipher_test_method,
415     &mac_test_method,
416     &psign_test_method,
417     &pverify_test_method,
418     &pdecrypt_test_method,
419     &pverify_recover_test_method,
420     &pderive_test_method,
421     &pbe_test_method,
422     &encode_test_method,
423     &kdf_test_method,
424     &keypair_test_method,
425     &digestsign_test_method,
426     &digestverify_test_method,
427     &oneshot_digestsign_test_method,
428     &oneshot_digestverify_test_method,
429     NULL
430 };
431
432 static const EVP_TEST_METHOD *evp_find_test(const char *name)
433 {
434     const EVP_TEST_METHOD **tt;
435
436     for (tt = evp_test_list; *tt; tt++) {
437         if (strcmp(name, (*tt)->name) == 0)
438             return *tt;
439     }
440     return NULL;
441 }
442
443 static void clear_test(EVP_TEST *t)
444 {
445     OPENSSL_free(t->expected_err);
446     t->expected_err = NULL;
447     OPENSSL_free(t->func);
448     t->func = NULL;
449     OPENSSL_free(t->reason);
450     t->reason = NULL;
451     /* Text literal. */
452     t->err = NULL;
453 }
454
455 /*
456  * Check for errors in the test structure; return 1 if okay, else 0.
457  */
458 static int check_test_error(EVP_TEST *t)
459 {
460     unsigned long err;
461     const char *func;
462     const char *reason;
463
464     if (t->err == NULL && t->expected_err == NULL)
465         return 1;
466     if (t->err != NULL && t->expected_err == NULL) {
467         if (t->aux_err != NULL) {
468             TEST_info("Above error from the test at %s:%d "
469                       "(%s) unexpected error %s",
470                       current_test_file, t->start_line, t->aux_err, t->err);
471         } else {
472             TEST_info("Above error from the test at %s:%d "
473                       "unexpected error %s",
474                       current_test_file, t->start_line, t->err);
475         }
476         clear_test(t);
477         return 0;
478     }
479     if (t->err == NULL && t->expected_err != NULL) {
480         TEST_info("Test line %d: succeeded expecting %s",
481                   t->start_line, t->expected_err);
482         return 0;
483     }
484
485     if (strcmp(t->err, t->expected_err) != 0) {
486         TEST_info("Test line %d: expecting %s got %s",
487                   t->start_line, t->expected_err, t->err);
488         return 0;
489     }
490
491     if (t->func == NULL && t->reason == NULL)
492         return 1;
493
494     if (t->func == NULL || t->reason == NULL) {
495         TEST_info("Test line %d: missing function or reason code",
496                   t->start_line);
497         return 0;
498     }
499
500     err = ERR_peek_error();
501     if (err == 0) {
502         TEST_info("Test line %d, expected error \"%s:%s\" not set",
503                   t->start_line, t->func, t->reason);
504         return 0;
505     }
506
507     func = ERR_func_error_string(err);
508     reason = ERR_reason_error_string(err);
509     if (func == NULL && reason == NULL) {
510         TEST_info("Test line %d: expected error \"%s:%s\","
511                   " no strings available.  Skipping...\n",
512                   t->start_line, t->func, t->reason);
513         return 1;
514     }
515
516     if (strcmp(func, t->func) == 0 && strcmp(reason, t->reason) == 0)
517         return 1;
518
519     TEST_info("Test line %d: expected error \"%s:%s\", got \"%s:%s\"",
520               t->start_line, t->func, t->reason, func, reason);
521
522     return 0;
523 }
524
525 /*
526  * Setup a new test, run any existing test. Log a message and return 0
527  * on error.
528  */
529 static int run_and_get_next(EVP_TEST *t, const EVP_TEST_METHOD *tmeth)
530 {
531     /* If we already have a test set up run it */
532     if (t->meth) {
533         t->ntests++;
534         if (t->skip) {
535             /*TEST_info("Line %d skipped %s test", t->start_line, t->meth->name);
536              */
537             t->nskip++;
538         } else {
539             /* run the test */
540             if (t->err == NULL && t->meth->run_test(t) != 1) {
541                 TEST_info("Line %d error %s", t->start_line, t->meth->name);
542                 return 0;
543             }
544             if (!check_test_error(t)) {
545                 test_openssl_errors();
546                 t->errors++;
547             }
548         }
549         /* clean it up */
550         ERR_clear_error();
551         if (t->data != NULL) {
552             t->meth->cleanup(t);
553             OPENSSL_free(t->data);
554             t->data = NULL;
555         }
556         clear_test(t);
557     }
558     t->meth = tmeth;
559     return 1;
560 }
561
562 static int find_key(EVP_PKEY **ppk, const char *name, KEY_LIST *lst)
563 {
564     for (; lst; lst = lst->next) {
565         if (strcmp(lst->name, name) == 0) {
566             if (ppk)
567                 *ppk = lst->key;
568             return 1;
569         }
570     }
571     return 0;
572 }
573
574 static void free_key_list(KEY_LIST *lst)
575 {
576     while (lst != NULL) {
577         KEY_LIST *ltmp;
578
579         EVP_PKEY_free(lst->key);
580         OPENSSL_free(lst->name);
581         ltmp = lst->next;
582         OPENSSL_free(lst);
583         lst = ltmp;
584     }
585 }
586
587 static int check_unsupported()
588 {
589     long err = ERR_peek_error();
590
591     if (ERR_GET_LIB(err) == ERR_LIB_EVP
592             && ERR_GET_REASON(err) == EVP_R_UNSUPPORTED_ALGORITHM) {
593         ERR_clear_error();
594         return 1;
595     }
596 #ifndef OPENSSL_NO_EC
597     /*
598      * If EC support is enabled we should catch also EC_R_UNKNOWN_GROUP as an
599      * hint to an unsupported algorithm/curve (e.g. if binary EC support is
600      * disabled).
601      */
602     if (ERR_GET_LIB(err) == ERR_LIB_EC
603         && ERR_GET_REASON(err) == EC_R_UNKNOWN_GROUP) {
604         ERR_clear_error();
605         return 1;
606     }
607 #endif /* OPENSSL_NO_EC */
608     return 0;
609 }
610
611
612 static int read_key(EVP_TEST *t)
613 {
614     char tmpbuf[80];
615
616     if (t->key == NULL) {
617         if (!TEST_ptr(t->key = BIO_new(BIO_s_mem())))
618             return 0;
619     } else if (!TEST_int_gt(BIO_reset(t->key), 0)) {
620         return 0;
621     }
622
623     /* Read to PEM end line and place content in memory BIO */
624     while (BIO_gets(t->in, tmpbuf, sizeof(tmpbuf))) {
625         t->line++;
626         if (!TEST_int_gt(BIO_puts(t->key, tmpbuf), 0))
627             return 0;
628         if (strncmp(tmpbuf, "-----END", 8) == 0)
629             return 1;
630     }
631     TEST_error("Can't find key end");
632     return 0;
633 }
634
635 /*
636  * Parse a line into the current test |t|.  Return 0 on error.
637  */
638 static int parse_test_line(EVP_TEST *t, char *buf)
639 {
640     char *keyword = NULL, *value = NULL;
641     int add_key = 0;
642     KEY_LIST **lst = NULL, *key = NULL;
643     EVP_PKEY *pk = NULL;
644     const EVP_TEST_METHOD *tmeth = NULL;
645
646     if (!parse_line(&keyword, &value, buf))
647         return 1;
648     if (strcmp(keyword, "PrivateKey") == 0) {
649         if (!read_key(t))
650             return 0;
651         pk = PEM_read_bio_PrivateKey(t->key, NULL, 0, NULL);
652         if (pk == NULL && !check_unsupported()) {
653             TEST_info("Error reading private key %s", value);
654             ERR_print_errors_fp(stderr);
655             return 0;
656         }
657         lst = &private_keys;
658         add_key = 1;
659     }
660     if (strcmp(keyword, "PublicKey") == 0) {
661         if (!read_key(t))
662             return 0;
663         pk = PEM_read_bio_PUBKEY(t->key, NULL, 0, NULL);
664         if (pk == NULL && !check_unsupported()) {
665             TEST_info("Error reading public key %s", value);
666             ERR_print_errors_fp(stderr);
667             return 0;
668         }
669         lst = &public_keys;
670         add_key = 1;
671     }
672     /* If we have a key add to list */
673     if (add_key) {
674         if (find_key(NULL, value, *lst)) {
675             TEST_info("Duplicate key %s", value);
676             return 0;
677         }
678         if (!TEST_ptr(key = OPENSSL_malloc(sizeof(*key)))
679                 || !TEST_ptr(key->name = OPENSSL_strdup(value)))
680             return 0;
681         key->key = pk;
682         key->next = *lst;
683         *lst = key;
684         return 1;
685     }
686
687     /* See if keyword corresponds to a test start */
688     if ((tmeth = evp_find_test(keyword)) != NULL) {
689         if (!run_and_get_next(t, tmeth))
690             return 0;
691         t->start_line = t->line;
692         t->skip = 0;
693         if (!tmeth->init(t, value)) {
694             TEST_info("Unknown %s: %s", keyword, value);
695             return 0;
696         }
697         return 1;
698     }
699     if (t->skip)
700         return 1;
701     if (strcmp(keyword, "Title") == 0) {
702         TEST_info("Starting %s tests", value);
703         set_test_title(value);
704     } else if (strcmp(keyword, "Result") == 0) {
705         if (t->expected_err != NULL) {
706             TEST_info("Line %d: multiple result lines", t->line);
707             return 0;
708         }
709         if (!TEST_ptr(t->expected_err = OPENSSL_strdup(value)))
710             return 0;
711     } else if (strcmp(keyword, "Function") == 0) {
712         if (t->func != NULL) {
713             TEST_info("Line %d: multiple function lines\n", t->line);
714             return 0;
715         }
716         if (!TEST_ptr(t->func = OPENSSL_strdup(value)))
717             return 0;
718     } else if (strcmp(keyword, "Reason") == 0) {
719         if (t->reason != NULL) {
720             TEST_info("Line %d: multiple reason lines", t->line);
721             return 0;
722         }
723         if (!TEST_ptr(t->reason = OPENSSL_strdup(value)))
724             return 0;
725     } else {
726         /* Must be test specific line: try to parse it */
727         int rv = t->meth == NULL ? 0 : t->meth->parse(t, keyword, value);
728
729         if (rv == 0) {
730             TEST_info("Line %d: unknown keyword %s", t->line, keyword);
731             return 0;
732         }
733         if (rv < 0) {
734             TEST_info("Line %d: error processing keyword %s\n",
735                       t->line, keyword);
736             return 0;
737         }
738     }
739     return 1;
740 }
741
742 /* Message digest tests */
743
744 typedef struct digest_data_st {
745     /* Digest this test is for */
746     const EVP_MD *digest;
747     /* Input to digest */
748     STACK_OF(EVP_TEST_BUFFER) *input;
749     /* Expected output */
750     unsigned char *output;
751     size_t output_len;
752 } DIGEST_DATA;
753
754 static int digest_test_init(EVP_TEST *t, const char *alg)
755 {
756     const EVP_MD *digest;
757     DIGEST_DATA *mdat;
758
759     digest = EVP_get_digestbyname(alg);
760     if (!digest) {
761         /* If alg has an OID assume disabled algorithm */
762         if (OBJ_sn2nid(alg) != NID_undef || OBJ_ln2nid(alg) != NID_undef) {
763             t->skip = 1;
764             return 1;
765         }
766         return 0;
767     }
768     mdat = OPENSSL_zalloc(sizeof(*mdat));
769     mdat->digest = digest;
770     t->data = mdat;
771     return 1;
772 }
773
774 static void digest_test_cleanup(EVP_TEST *t)
775 {
776     DIGEST_DATA *mdat = t->data;
777
778     sk_EVP_TEST_BUFFER_pop_free(mdat->input, evp_test_buffer_free);
779     OPENSSL_free(mdat->output);
780 }
781
782 static int digest_test_parse(EVP_TEST *t,
783                              const char *keyword, const char *value)
784 {
785     DIGEST_DATA *mdata = t->data;
786
787     if (strcmp(keyword, "Input") == 0)
788         return evp_test_buffer_append(value, &mdata->input);
789     if (strcmp(keyword, "Output") == 0)
790         return test_bin(value, &mdata->output, &mdata->output_len);
791     if (strcmp(keyword, "Count") == 0)
792         return evp_test_buffer_set_count(value, mdata->input);
793     if (strcmp(keyword, "Ncopy") == 0)
794         return evp_test_buffer_ncopy(value, mdata->input);
795     return 0;
796 }
797
798 static int digest_update_fn(void *ctx, const unsigned char *buf, size_t buflen)
799 {
800     return EVP_DigestUpdate(ctx, buf, buflen);
801 }
802
803 static int digest_test_run(EVP_TEST *t)
804 {
805     DIGEST_DATA *mdata = t->data;
806     EVP_MD_CTX *mctx;
807     unsigned char md[EVP_MAX_MD_SIZE];
808     unsigned int md_len;
809
810     t->err = "TEST_FAILURE";
811     if (!TEST_ptr(mctx = EVP_MD_CTX_new()))
812         goto err;
813
814     if (!EVP_DigestInit_ex(mctx, mdata->digest, NULL)) {
815         t->err = "DIGESTINIT_ERROR";
816         goto err;
817     }
818     if (!evp_test_buffer_do(mdata->input, digest_update_fn, mctx)) {
819         t->err = "DIGESTUPDATE_ERROR";
820         goto err;
821     }
822
823     if (!EVP_DigestFinal(mctx, md, &md_len)) {
824         t->err = "DIGESTFINAL_ERROR";
825         goto err;
826     }
827     if (md_len != mdata->output_len) {
828         t->err = "DIGEST_LENGTH_MISMATCH";
829         goto err;
830     }
831     if (!compare_mem(mdata->output, mdata->output_len, md, md_len)) {
832         t->err = "DIGEST_MISMATCH";
833         goto err;
834     }
835     t->err = NULL;
836
837  err:
838     EVP_MD_CTX_free(mctx);
839     return 1;
840 }
841
842 static const EVP_TEST_METHOD digest_test_method = {
843     "Digest",
844     digest_test_init,
845     digest_test_cleanup,
846     digest_test_parse,
847     digest_test_run
848 };
849
850 /* Cipher tests */
851 typedef struct cipher_data_st {
852     const EVP_CIPHER *cipher;
853     int enc;
854     /* EVP_CIPH_GCM_MODE, EVP_CIPH_CCM_MODE or EVP_CIPH_OCB_MODE if AEAD */
855     int aead;
856     unsigned char *key;
857     size_t key_len;
858     unsigned char *iv;
859     size_t iv_len;
860     unsigned char *plaintext;
861     size_t plaintext_len;
862     unsigned char *ciphertext;
863     size_t ciphertext_len;
864     /* GCM, CCM only */
865     unsigned char *aad;
866     size_t aad_len;
867     unsigned char *tag;
868     size_t tag_len;
869 } CIPHER_DATA;
870
871 static int cipher_test_init(EVP_TEST *t, const char *alg)
872 {
873     const EVP_CIPHER *cipher;
874     CIPHER_DATA *cdat = t->data;
875
876     cipher = EVP_get_cipherbyname(alg);
877     if (!cipher) {
878         /* If alg has an OID assume disabled algorithm */
879         if (OBJ_sn2nid(alg) != NID_undef || OBJ_ln2nid(alg) != NID_undef) {
880             t->skip = 1;
881             return 1;
882         }
883         return 0;
884     }
885     cdat = OPENSSL_malloc(sizeof(*cdat));
886     cdat->cipher = cipher;
887     cdat->enc = -1;
888     cdat->key = NULL;
889     cdat->iv = NULL;
890     cdat->ciphertext = NULL;
891     cdat->plaintext = NULL;
892     cdat->aad = NULL;
893     cdat->tag = NULL;
894     t->data = cdat;
895     if (EVP_CIPHER_mode(cipher) == EVP_CIPH_GCM_MODE
896         || EVP_CIPHER_mode(cipher) == EVP_CIPH_OCB_MODE
897         || EVP_CIPHER_mode(cipher) == EVP_CIPH_CCM_MODE)
898         cdat->aead = EVP_CIPHER_mode(cipher);
899     else if (EVP_CIPHER_flags(cipher) & EVP_CIPH_FLAG_AEAD_CIPHER)
900         cdat->aead = -1;
901     else
902         cdat->aead = 0;
903
904     return 1;
905 }
906
907 static void cipher_test_cleanup(EVP_TEST *t)
908 {
909     CIPHER_DATA *cdat = t->data;
910
911     OPENSSL_free(cdat->key);
912     OPENSSL_free(cdat->iv);
913     OPENSSL_free(cdat->ciphertext);
914     OPENSSL_free(cdat->plaintext);
915     OPENSSL_free(cdat->aad);
916     OPENSSL_free(cdat->tag);
917 }
918
919 static int cipher_test_parse(EVP_TEST *t, const char *keyword,
920                              const char *value)
921 {
922     CIPHER_DATA *cdat = t->data;
923
924     if (strcmp(keyword, "Key") == 0)
925         return test_bin(value, &cdat->key, &cdat->key_len);
926     if (strcmp(keyword, "IV") == 0)
927         return test_bin(value, &cdat->iv, &cdat->iv_len);
928     if (strcmp(keyword, "Plaintext") == 0)
929         return test_bin(value, &cdat->plaintext, &cdat->plaintext_len);
930     if (strcmp(keyword, "Ciphertext") == 0)
931         return test_bin(value, &cdat->ciphertext, &cdat->ciphertext_len);
932     if (cdat->aead) {
933         if (strcmp(keyword, "AAD") == 0)
934             return test_bin(value, &cdat->aad, &cdat->aad_len);
935         if (strcmp(keyword, "Tag") == 0)
936             return test_bin(value, &cdat->tag, &cdat->tag_len);
937     }
938
939     if (strcmp(keyword, "Operation") == 0) {
940         if (strcmp(value, "ENCRYPT") == 0)
941             cdat->enc = 1;
942         else if (strcmp(value, "DECRYPT") == 0)
943             cdat->enc = 0;
944         else
945             return 0;
946         return 1;
947     }
948     return 0;
949 }
950
951 static int cipher_test_enc(EVP_TEST *t, int enc,
952                            size_t out_misalign, size_t inp_misalign, int frag)
953 {
954     CIPHER_DATA *cdat = t->data;
955     unsigned char *in, *out, *tmp = NULL;
956     size_t in_len, out_len, donelen = 0;
957     int ok = 0, tmplen, chunklen, tmpflen;
958     EVP_CIPHER_CTX *ctx = NULL;
959
960     t->err = "TEST_FAILURE";
961     if (!TEST_ptr(ctx = EVP_CIPHER_CTX_new()))
962         goto err;
963     EVP_CIPHER_CTX_set_flags(ctx, EVP_CIPHER_CTX_FLAG_WRAP_ALLOW);
964     if (enc) {
965         in = cdat->plaintext;
966         in_len = cdat->plaintext_len;
967         out = cdat->ciphertext;
968         out_len = cdat->ciphertext_len;
969     } else {
970         in = cdat->ciphertext;
971         in_len = cdat->ciphertext_len;
972         out = cdat->plaintext;
973         out_len = cdat->plaintext_len;
974     }
975     if (inp_misalign == (size_t)-1) {
976         /*
977          * Exercise in-place encryption
978          */
979         tmp = OPENSSL_malloc(out_misalign + in_len + 2 * EVP_MAX_BLOCK_LENGTH);
980         if (!tmp)
981             goto err;
982         in = memcpy(tmp + out_misalign, in, in_len);
983     } else {
984         inp_misalign += 16 - ((out_misalign + in_len) & 15);
985         /*
986          * 'tmp' will store both output and copy of input. We make the copy
987          * of input to specifically aligned part of 'tmp'. So we just
988          * figured out how much padding would ensure the required alignment,
989          * now we allocate extended buffer and finally copy the input just
990          * past inp_misalign in expression below. Output will be written
991          * past out_misalign...
992          */
993         tmp = OPENSSL_malloc(out_misalign + in_len + 2 * EVP_MAX_BLOCK_LENGTH +
994                              inp_misalign + in_len);
995         if (!tmp)
996             goto err;
997         in = memcpy(tmp + out_misalign + in_len + 2 * EVP_MAX_BLOCK_LENGTH +
998                     inp_misalign, in, in_len);
999     }
1000     if (!EVP_CipherInit_ex(ctx, cdat->cipher, NULL, NULL, NULL, enc)) {
1001         t->err = "CIPHERINIT_ERROR";
1002         goto err;
1003     }
1004     if (cdat->iv) {
1005         if (cdat->aead) {
1006             if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_IVLEN,
1007                                      cdat->iv_len, 0)) {
1008                 t->err = "INVALID_IV_LENGTH";
1009                 goto err;
1010             }
1011         } else if (cdat->iv_len != (size_t)EVP_CIPHER_CTX_iv_length(ctx)) {
1012             t->err = "INVALID_IV_LENGTH";
1013             goto err;
1014         }
1015     }
1016     if (cdat->aead) {
1017         unsigned char *tag;
1018         /*
1019          * If encrypting or OCB just set tag length initially, otherwise
1020          * set tag length and value.
1021          */
1022         if (enc || cdat->aead == EVP_CIPH_OCB_MODE) {
1023             t->err = "TAG_LENGTH_SET_ERROR";
1024             tag = NULL;
1025         } else {
1026             t->err = "TAG_SET_ERROR";
1027             tag = cdat->tag;
1028         }
1029         if (tag || cdat->aead != EVP_CIPH_GCM_MODE) {
1030             if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_TAG,
1031                                      cdat->tag_len, tag))
1032                 goto err;
1033         }
1034     }
1035
1036     if (!EVP_CIPHER_CTX_set_key_length(ctx, cdat->key_len)) {
1037         t->err = "INVALID_KEY_LENGTH";
1038         goto err;
1039     }
1040     if (!EVP_CipherInit_ex(ctx, NULL, NULL, cdat->key, cdat->iv, -1)) {
1041         t->err = "KEY_SET_ERROR";
1042         goto err;
1043     }
1044
1045     if (!enc && cdat->aead == EVP_CIPH_OCB_MODE) {
1046         if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_TAG,
1047                                  cdat->tag_len, cdat->tag)) {
1048             t->err = "TAG_SET_ERROR";
1049             goto err;
1050         }
1051     }
1052
1053     if (cdat->aead == EVP_CIPH_CCM_MODE) {
1054         if (!EVP_CipherUpdate(ctx, NULL, &tmplen, NULL, out_len)) {
1055             t->err = "CCM_PLAINTEXT_LENGTH_SET_ERROR";
1056             goto err;
1057         }
1058     }
1059     if (cdat->aad) {
1060         t->err = "AAD_SET_ERROR";
1061         if (!frag) {
1062             if (!EVP_CipherUpdate(ctx, NULL, &chunklen, cdat->aad,
1063                                   cdat->aad_len))
1064                 goto err;
1065         } else {
1066             /*
1067              * Supply the AAD in chunks less than the block size where possible
1068              */
1069             if (cdat->aad_len > 0) {
1070                 if (!EVP_CipherUpdate(ctx, NULL, &chunklen, cdat->aad, 1))
1071                     goto err;
1072                 donelen++;
1073             }
1074             if (cdat->aad_len > 2) {
1075                 if (!EVP_CipherUpdate(ctx, NULL, &chunklen, cdat->aad + donelen,
1076                                       cdat->aad_len - 2))
1077                     goto err;
1078                 donelen += cdat->aad_len - 2;
1079             }
1080             if (cdat->aad_len > 1
1081                     && !EVP_CipherUpdate(ctx, NULL, &chunklen,
1082                                          cdat->aad + donelen, 1))
1083                 goto err;
1084         }
1085     }
1086     EVP_CIPHER_CTX_set_padding(ctx, 0);
1087     t->err = "CIPHERUPDATE_ERROR";
1088     tmplen = 0;
1089     if (!frag) {
1090         /* We supply the data all in one go */
1091         if (!EVP_CipherUpdate(ctx, tmp + out_misalign, &tmplen, in, in_len))
1092             goto err;
1093     } else {
1094         /* Supply the data in chunks less than the block size where possible */
1095         if (in_len > 0) {
1096             if (!EVP_CipherUpdate(ctx, tmp + out_misalign, &chunklen, in, 1))
1097                 goto err;
1098             tmplen += chunklen;
1099             in++;
1100             in_len--;
1101         }
1102         if (in_len > 1) {
1103             if (!EVP_CipherUpdate(ctx, tmp + out_misalign + tmplen, &chunklen,
1104                                   in, in_len - 1))
1105                 goto err;
1106             tmplen += chunklen;
1107             in += in_len - 1;
1108             in_len = 1;
1109         }
1110         if (in_len > 0 ) {
1111             if (!EVP_CipherUpdate(ctx, tmp + out_misalign + tmplen, &chunklen,
1112                                   in, 1))
1113                 goto err;
1114             tmplen += chunklen;
1115         }
1116     }
1117     if (!EVP_CipherFinal_ex(ctx, tmp + out_misalign + tmplen, &tmpflen)) {
1118         t->err = "CIPHERFINAL_ERROR";
1119         goto err;
1120     }
1121     if (!compare_mem(out, out_len, tmp + out_misalign, tmplen + tmpflen)) {
1122         t->err = "VALUE_MISMATCH";
1123         goto err;
1124     }
1125     if (enc && cdat->aead) {
1126         unsigned char rtag[16];
1127
1128         if (cdat->tag_len > sizeof(rtag)) {
1129             t->err = "TAG_LENGTH_INTERNAL_ERROR";
1130             goto err;
1131         }
1132         if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_GET_TAG,
1133                                  cdat->tag_len, rtag)) {
1134             t->err = "TAG_RETRIEVE_ERROR";
1135             goto err;
1136         }
1137         if (!compare_mem(cdat->tag, cdat->tag_len, rtag, cdat->tag_len)) {
1138             t->err = "TAG_VALUE_MISMATCH";
1139             goto err;
1140         }
1141     }
1142     t->err = NULL;
1143     ok = 1;
1144  err:
1145     OPENSSL_free(tmp);
1146     EVP_CIPHER_CTX_free(ctx);
1147     return ok;
1148 }
1149
1150 static int cipher_test_run(EVP_TEST *t)
1151 {
1152     CIPHER_DATA *cdat = t->data;
1153     int rv, frag = 0;
1154     size_t out_misalign, inp_misalign;
1155
1156     if (!cdat->key) {
1157         t->err = "NO_KEY";
1158         return 0;
1159     }
1160     if (!cdat->iv && EVP_CIPHER_iv_length(cdat->cipher)) {
1161         /* IV is optional and usually omitted in wrap mode */
1162         if (EVP_CIPHER_mode(cdat->cipher) != EVP_CIPH_WRAP_MODE) {
1163             t->err = "NO_IV";
1164             return 0;
1165         }
1166     }
1167     if (cdat->aead && !cdat->tag) {
1168         t->err = "NO_TAG";
1169         return 0;
1170     }
1171     for (out_misalign = 0; out_misalign <= 1;) {
1172         static char aux_err[64];
1173         t->aux_err = aux_err;
1174         for (inp_misalign = (size_t)-1; inp_misalign != 2; inp_misalign++) {
1175             if (inp_misalign == (size_t)-1) {
1176                 /* kludge: inp_misalign == -1 means "exercise in-place" */
1177                 BIO_snprintf(aux_err, sizeof(aux_err),
1178                              "%s in-place, %sfragmented",
1179                              out_misalign ? "misaligned" : "aligned",
1180                              frag ? "" : "not ");
1181             } else {
1182                 BIO_snprintf(aux_err, sizeof(aux_err),
1183                              "%s output and %s input, %sfragmented",
1184                              out_misalign ? "misaligned" : "aligned",
1185                              inp_misalign ? "misaligned" : "aligned",
1186                              frag ? "" : "not ");
1187             }
1188             if (cdat->enc) {
1189                 rv = cipher_test_enc(t, 1, out_misalign, inp_misalign, frag);
1190                 /* Not fatal errors: return */
1191                 if (rv != 1) {
1192                     if (rv < 0)
1193                         return 0;
1194                     return 1;
1195                 }
1196             }
1197             if (cdat->enc != 1) {
1198                 rv = cipher_test_enc(t, 0, out_misalign, inp_misalign, frag);
1199                 /* Not fatal errors: return */
1200                 if (rv != 1) {
1201                     if (rv < 0)
1202                         return 0;
1203                     return 1;
1204                 }
1205             }
1206         }
1207
1208         if (out_misalign == 1 && frag == 0) {
1209             /*
1210              * XTS, CCM and Wrap modes have special requirements about input
1211              * lengths so we don't fragment for those
1212              */
1213             if (cdat->aead == EVP_CIPH_CCM_MODE
1214                     || EVP_CIPHER_mode(cdat->cipher) == EVP_CIPH_XTS_MODE
1215                      || EVP_CIPHER_mode(cdat->cipher) == EVP_CIPH_WRAP_MODE)
1216                 break;
1217             out_misalign = 0;
1218             frag++;
1219         } else {
1220             out_misalign++;
1221         }
1222     }
1223     t->aux_err = NULL;
1224
1225     return 1;
1226 }
1227
1228 static const EVP_TEST_METHOD cipher_test_method = {
1229     "Cipher",
1230     cipher_test_init,
1231     cipher_test_cleanup,
1232     cipher_test_parse,
1233     cipher_test_run
1234 };
1235
1236 typedef struct mac_data_st {
1237     /* MAC type */
1238     int type;
1239     /* Algorithm string for this MAC */
1240     char *alg;
1241     /* MAC key */
1242     unsigned char *key;
1243     size_t key_len;
1244     /* Input to MAC */
1245     unsigned char *input;
1246     size_t input_len;
1247     /* Expected output */
1248     unsigned char *output;
1249     size_t output_len;
1250 } MAC_DATA;
1251
1252 static int mac_test_init(EVP_TEST *t, const char *alg)
1253 {
1254     int type;
1255     MAC_DATA *mdat;
1256
1257     if (strcmp(alg, "HMAC") == 0) {
1258         type = EVP_PKEY_HMAC;
1259     } else if (strcmp(alg, "CMAC") == 0) {
1260 #ifndef OPENSSL_NO_CMAC
1261         type = EVP_PKEY_CMAC;
1262 #else
1263         t->skip = 1;
1264         return 1;
1265 #endif
1266     } else if (strcmp(alg, "Poly1305") == 0) {
1267 #ifndef OPENSSL_NO_POLY1305
1268         type = EVP_PKEY_POLY1305;
1269 #else
1270         t->skip = 1;
1271         return 1;
1272 #endif
1273     } else if (strcmp(alg, "SipHash") == 0) {
1274 #ifndef OPENSSL_NO_SIPHASH
1275         type = EVP_PKEY_SIPHASH;
1276 #else
1277         t->skip = 1;
1278         return 1;
1279 #endif
1280     } else
1281         return 0;
1282
1283     mdat = OPENSSL_zalloc(sizeof(*mdat));
1284     mdat->type = type;
1285     t->data = mdat;
1286     return 1;
1287 }
1288
1289 static void mac_test_cleanup(EVP_TEST *t)
1290 {
1291     MAC_DATA *mdat = t->data;
1292
1293     OPENSSL_free(mdat->alg);
1294     OPENSSL_free(mdat->key);
1295     OPENSSL_free(mdat->input);
1296     OPENSSL_free(mdat->output);
1297 }
1298
1299 static int mac_test_parse(EVP_TEST *t,
1300                           const char *keyword, const char *value)
1301 {
1302     MAC_DATA *mdata = t->data;
1303
1304     if (strcmp(keyword, "Key") == 0)
1305         return test_bin(value, &mdata->key, &mdata->key_len);
1306     if (strcmp(keyword, "Algorithm") == 0) {
1307         mdata->alg = OPENSSL_strdup(value);
1308         if (!mdata->alg)
1309             return 0;
1310         return 1;
1311     }
1312     if (strcmp(keyword, "Input") == 0)
1313         return test_bin(value, &mdata->input, &mdata->input_len);
1314     if (strcmp(keyword, "Output") == 0)
1315         return test_bin(value, &mdata->output, &mdata->output_len);
1316     return 0;
1317 }
1318
1319 static int mac_test_run(EVP_TEST *t)
1320 {
1321     MAC_DATA *mdata = t->data;
1322     EVP_MD_CTX *mctx = NULL;
1323     EVP_PKEY_CTX *pctx = NULL, *genctx = NULL;
1324     EVP_PKEY *key = NULL;
1325     const EVP_MD *md = NULL;
1326     unsigned char *mac = NULL;
1327     size_t mac_len;
1328
1329 #ifdef OPENSSL_NO_DES
1330     if (mdata->alg != NULL && strstr(mdata->alg, "DES") != NULL) {
1331         /* Skip DES */
1332         t->err = NULL;
1333         goto err;
1334     }
1335 #endif
1336
1337     if (!TEST_ptr(genctx = EVP_PKEY_CTX_new_id(mdata->type, NULL))) {
1338         t->err = "MAC_PKEY_CTX_ERROR";
1339         goto err;
1340     }
1341
1342     if (EVP_PKEY_keygen_init(genctx) <= 0) {
1343         t->err = "MAC_KEYGEN_INIT_ERROR";
1344         goto err;
1345     }
1346     if (mdata->type == EVP_PKEY_CMAC
1347              && EVP_PKEY_CTX_ctrl_str(genctx, "cipher", mdata->alg) <= 0) {
1348         t->err = "MAC_ALGORITHM_SET_ERROR";
1349         goto err;
1350     }
1351
1352     if (EVP_PKEY_CTX_set_mac_key(genctx, mdata->key, mdata->key_len) <= 0) {
1353         t->err = "MAC_KEY_SET_ERROR";
1354         goto err;
1355     }
1356
1357     if (EVP_PKEY_keygen(genctx, &key) <= 0) {
1358         t->err = "MAC_KEY_GENERATE_ERROR";
1359         goto err;
1360     }
1361     if (mdata->type == EVP_PKEY_HMAC) {
1362         if (!TEST_ptr(md = EVP_get_digestbyname(mdata->alg))) {
1363             t->err = "MAC_ALGORITHM_SET_ERROR";
1364             goto err;
1365         }
1366     }
1367     if (!TEST_ptr(mctx = EVP_MD_CTX_new())) {
1368         t->err = "INTERNAL_ERROR";
1369         goto err;
1370     }
1371     if (!EVP_DigestSignInit(mctx, &pctx, md, NULL, key)) {
1372         t->err = "DIGESTSIGNINIT_ERROR";
1373         goto err;
1374     }
1375
1376     if (!EVP_DigestSignUpdate(mctx, mdata->input, mdata->input_len)) {
1377         t->err = "DIGESTSIGNUPDATE_ERROR";
1378         goto err;
1379     }
1380     if (!EVP_DigestSignFinal(mctx, NULL, &mac_len)) {
1381         t->err = "DIGESTSIGNFINAL_LENGTH_ERROR";
1382         goto err;
1383     }
1384     if (!TEST_ptr(mac = OPENSSL_malloc(mac_len))) {
1385         t->err = "TEST_FAILURE";
1386         goto err;
1387     }
1388     if (!EVP_DigestSignFinal(mctx, mac, &mac_len)
1389             || !compare_mem(mdata->output, mdata->output_len, mac, mac_len)) {
1390         t->err = "TEST_MAC_ERR";
1391         goto err;
1392     }
1393     t->err = NULL;
1394  err:
1395     EVP_MD_CTX_free(mctx);
1396     OPENSSL_free(mac);
1397     EVP_PKEY_CTX_free(genctx);
1398     EVP_PKEY_free(key);
1399     return 1;
1400 }
1401
1402 static const EVP_TEST_METHOD mac_test_method = {
1403     "MAC",
1404     mac_test_init,
1405     mac_test_cleanup,
1406     mac_test_parse,
1407     mac_test_run
1408 };
1409
1410 /*
1411  * Public key operations. These are all very similar and can share
1412  * a lot of common code.
1413  */
1414
1415 typedef struct pkey_data_st {
1416     /* Context for this operation */
1417     EVP_PKEY_CTX *ctx;
1418     /* Key operation to perform */
1419     int (*keyop) (EVP_PKEY_CTX *ctx,
1420                   unsigned char *sig, size_t *siglen,
1421                   const unsigned char *tbs, size_t tbslen);
1422     /* Input to MAC */
1423     unsigned char *input;
1424     size_t input_len;
1425     /* Expected output */
1426     unsigned char *output;
1427     size_t output_len;
1428 } PKEY_DATA;
1429
1430 /*
1431  * Perform public key operation setup: lookup key, allocated ctx and call
1432  * the appropriate initialisation function
1433  */
1434 static int pkey_test_init(EVP_TEST *t, const char *name,
1435                           int use_public,
1436                           int (*keyopinit) (EVP_PKEY_CTX *ctx),
1437                           int (*keyop) (EVP_PKEY_CTX *ctx,
1438                                         unsigned char *sig, size_t *siglen,
1439                                         const unsigned char *tbs,
1440                                         size_t tbslen)
1441     )
1442 {
1443     PKEY_DATA *kdata;
1444     EVP_PKEY *pkey = NULL;
1445     int rv = 0;
1446
1447     if (use_public)
1448         rv = find_key(&pkey, name, public_keys);
1449     if (rv == 0)
1450         rv = find_key(&pkey, name, private_keys);
1451     if (rv == 0 || pkey == NULL) {
1452         t->skip = 1;
1453         return 1;
1454     }
1455
1456     if (!TEST_ptr(kdata = OPENSSL_malloc(sizeof(*kdata)))) {
1457         EVP_PKEY_free(pkey);
1458         return 0;
1459     }
1460     kdata->ctx = NULL;
1461     kdata->input = NULL;
1462     kdata->output = NULL;
1463     kdata->keyop = keyop;
1464     t->data = kdata;
1465     if (!TEST_ptr(kdata->ctx = EVP_PKEY_CTX_new(pkey, NULL)))
1466         return 0;
1467     if (keyopinit(kdata->ctx) <= 0)
1468         t->err = "KEYOP_INIT_ERROR";
1469     return 1;
1470 }
1471
1472 static void pkey_test_cleanup(EVP_TEST *t)
1473 {
1474     PKEY_DATA *kdata = t->data;
1475
1476     OPENSSL_free(kdata->input);
1477     OPENSSL_free(kdata->output);
1478     EVP_PKEY_CTX_free(kdata->ctx);
1479 }
1480
1481 static int pkey_test_ctrl(EVP_TEST *t, EVP_PKEY_CTX *pctx,
1482                           const char *value)
1483 {
1484     int rv;
1485     char *p, *tmpval;
1486
1487     if (!TEST_ptr(tmpval = OPENSSL_strdup(value)))
1488         return 0;
1489     p = strchr(tmpval, ':');
1490     if (p != NULL)
1491         *p++ = 0;
1492     rv = EVP_PKEY_CTX_ctrl_str(pctx, tmpval, p);
1493     if (rv == -2) {
1494         t->err = "PKEY_CTRL_INVALID";
1495         rv = 1;
1496     } else if (p != NULL && rv <= 0) {
1497         /* If p has an OID and lookup fails assume disabled algorithm */
1498         int nid = OBJ_sn2nid(p);
1499
1500         if (nid == NID_undef)
1501              nid = OBJ_ln2nid(p);
1502         if ((nid != NID_undef) && EVP_get_digestbynid(nid) == NULL &&
1503             EVP_get_cipherbynid(nid) == NULL) {
1504             t->skip = 1;
1505             rv = 1;
1506         } else {
1507             t->err = "PKEY_CTRL_ERROR";
1508             rv = 1;
1509         }
1510     }
1511     OPENSSL_free(tmpval);
1512     return rv > 0;
1513 }
1514
1515 static int pkey_test_parse(EVP_TEST *t,
1516                            const char *keyword, const char *value)
1517 {
1518     PKEY_DATA *kdata = t->data;
1519     if (strcmp(keyword, "Input") == 0)
1520         return test_bin(value, &kdata->input, &kdata->input_len);
1521     if (strcmp(keyword, "Output") == 0)
1522         return test_bin(value, &kdata->output, &kdata->output_len);
1523     if (strcmp(keyword, "Ctrl") == 0)
1524         return pkey_test_ctrl(t, kdata->ctx, value);
1525     return 0;
1526 }
1527
1528 static int pkey_test_run(EVP_TEST *t)
1529 {
1530     PKEY_DATA *kdata = t->data;
1531     unsigned char *out = NULL;
1532     size_t out_len;
1533
1534     if (kdata->keyop(kdata->ctx, NULL, &out_len, kdata->input,
1535                      kdata->input_len) <= 0
1536             || !TEST_ptr(out = OPENSSL_malloc(out_len))) {
1537         t->err = "KEYOP_LENGTH_ERROR";
1538         goto err;
1539     }
1540     if (kdata->keyop(kdata->ctx, out,
1541                      &out_len, kdata->input, kdata->input_len) <= 0) {
1542         t->err = "KEYOP_ERROR";
1543         goto err;
1544     }
1545     if (!compare_mem(kdata->output, kdata->output_len, out, out_len)) {
1546         t->err = "KEYOP_MISMATCH";
1547         goto err;
1548     }
1549     t->err = NULL;
1550  err:
1551     OPENSSL_free(out);
1552     return 1;
1553 }
1554
1555 static int sign_test_init(EVP_TEST *t, const char *name)
1556 {
1557     return pkey_test_init(t, name, 0, EVP_PKEY_sign_init, EVP_PKEY_sign);
1558 }
1559
1560 static const EVP_TEST_METHOD psign_test_method = {
1561     "Sign",
1562     sign_test_init,
1563     pkey_test_cleanup,
1564     pkey_test_parse,
1565     pkey_test_run
1566 };
1567
1568 static int verify_recover_test_init(EVP_TEST *t, const char *name)
1569 {
1570     return pkey_test_init(t, name, 1, EVP_PKEY_verify_recover_init,
1571                           EVP_PKEY_verify_recover);
1572 }
1573
1574 static const EVP_TEST_METHOD pverify_recover_test_method = {
1575     "VerifyRecover",
1576     verify_recover_test_init,
1577     pkey_test_cleanup,
1578     pkey_test_parse,
1579     pkey_test_run
1580 };
1581
1582 static int decrypt_test_init(EVP_TEST *t, const char *name)
1583 {
1584     return pkey_test_init(t, name, 0, EVP_PKEY_decrypt_init,
1585                           EVP_PKEY_decrypt);
1586 }
1587
1588 static const EVP_TEST_METHOD pdecrypt_test_method = {
1589     "Decrypt",
1590     decrypt_test_init,
1591     pkey_test_cleanup,
1592     pkey_test_parse,
1593     pkey_test_run
1594 };
1595
1596 static int verify_test_init(EVP_TEST *t, const char *name)
1597 {
1598     return pkey_test_init(t, name, 1, EVP_PKEY_verify_init, 0);
1599 }
1600
1601 static int verify_test_run(EVP_TEST *t)
1602 {
1603     PKEY_DATA *kdata = t->data;
1604
1605     if (EVP_PKEY_verify(kdata->ctx, kdata->output, kdata->output_len,
1606                         kdata->input, kdata->input_len) <= 0)
1607         t->err = "VERIFY_ERROR";
1608     return 1;
1609 }
1610
1611 static const EVP_TEST_METHOD pverify_test_method = {
1612     "Verify",
1613     verify_test_init,
1614     pkey_test_cleanup,
1615     pkey_test_parse,
1616     verify_test_run
1617 };
1618
1619
1620 static int pderive_test_init(EVP_TEST *t, const char *name)
1621 {
1622     return pkey_test_init(t, name, 0, EVP_PKEY_derive_init, 0);
1623 }
1624
1625 static int pderive_test_parse(EVP_TEST *t,
1626                               const char *keyword, const char *value)
1627 {
1628     PKEY_DATA *kdata = t->data;
1629
1630     if (strcmp(keyword, "PeerKey") == 0) {
1631         EVP_PKEY *peer;
1632         if (find_key(&peer, value, public_keys) == 0)
1633             return 0;
1634         if (EVP_PKEY_derive_set_peer(kdata->ctx, peer) <= 0)
1635             return 0;
1636         return 1;
1637     }
1638     if (strcmp(keyword, "SharedSecret") == 0)
1639         return test_bin(value, &kdata->output, &kdata->output_len);
1640     if (strcmp(keyword, "Ctrl") == 0)
1641         return pkey_test_ctrl(t, kdata->ctx, value);
1642     return 0;
1643 }
1644
1645 static int pderive_test_run(EVP_TEST *t)
1646 {
1647     PKEY_DATA *kdata = t->data;
1648     unsigned char *out = NULL;
1649     size_t out_len;
1650
1651     out_len = kdata->output_len;
1652     if (!TEST_ptr(out = OPENSSL_malloc(out_len))) {
1653         t->err = "DERIVE_ERROR";
1654         goto err;
1655     }
1656     if (EVP_PKEY_derive(kdata->ctx, out, &out_len) <= 0) {
1657         t->err = "DERIVE_ERROR";
1658         goto err;
1659     }
1660     if (!compare_mem(kdata->output, kdata->output_len, out, out_len)) {
1661         t->err = "SHARED_SECRET_MISMATCH";
1662         goto err;
1663     }
1664
1665     t->err = NULL;
1666  err:
1667     OPENSSL_free(out);
1668     return 1;
1669 }
1670
1671 static const EVP_TEST_METHOD pderive_test_method = {
1672     "Derive",
1673     pderive_test_init,
1674     pkey_test_cleanup,
1675     pderive_test_parse,
1676     pderive_test_run
1677 };
1678
1679 /* PBE tests */
1680
1681 #define PBE_TYPE_SCRYPT 1
1682 #define PBE_TYPE_PBKDF2 2
1683 #define PBE_TYPE_PKCS12 3
1684
1685 typedef struct pbe_data_st {
1686     int pbe_type;
1687         /* scrypt parameters */
1688     uint64_t N, r, p, maxmem;
1689         /* PKCS#12 parameters */
1690     int id, iter;
1691     const EVP_MD *md;
1692         /* password */
1693     unsigned char *pass;
1694     size_t pass_len;
1695         /* salt */
1696     unsigned char *salt;
1697     size_t salt_len;
1698         /* Expected output */
1699     unsigned char *key;
1700     size_t key_len;
1701 } PBE_DATA;
1702
1703 #ifndef OPENSSL_NO_SCRYPT
1704 static int scrypt_test_parse(EVP_TEST *t,
1705                              const char *keyword, const char *value)
1706 {
1707     PBE_DATA *pdata = t->data;
1708
1709     if (strcmp(keyword, "N") == 0)
1710         return test_uint64(value, &pdata->N);
1711     if (strcmp(keyword, "p") == 0)
1712         return test_uint64(value, &pdata->p);
1713     if (strcmp(keyword, "r") == 0)
1714         return test_uint64(value, &pdata->r);
1715     if (strcmp(keyword, "maxmem") == 0)
1716         return test_uint64(value, &pdata->maxmem);
1717     return 0;
1718 }
1719 #endif
1720
1721 static int pbkdf2_test_parse(EVP_TEST *t,
1722                              const char *keyword, const char *value)
1723 {
1724     PBE_DATA *pdata = t->data;
1725
1726     if (strcmp(keyword, "iter") == 0) {
1727         pdata->iter = atoi(value);
1728         if (pdata->iter <= 0)
1729             return 0;
1730         return 1;
1731     }
1732     if (strcmp(keyword, "MD") == 0) {
1733         pdata->md = EVP_get_digestbyname(value);
1734         if (pdata->md == NULL)
1735             return 0;
1736         return 1;
1737     }
1738     return 0;
1739 }
1740
1741 static int pkcs12_test_parse(EVP_TEST *t,
1742                              const char *keyword, const char *value)
1743 {
1744     PBE_DATA *pdata = t->data;
1745
1746     if (strcmp(keyword, "id") == 0) {
1747         pdata->id = atoi(value);
1748         if (pdata->id <= 0)
1749             return 0;
1750         return 1;
1751     }
1752     return pbkdf2_test_parse(t, keyword, value);
1753 }
1754
1755 static int pbe_test_init(EVP_TEST *t, const char *alg)
1756 {
1757     PBE_DATA *pdat;
1758     int pbe_type = 0;
1759
1760     if (strcmp(alg, "scrypt") == 0) {
1761 #ifndef OPENSSL_NO_SCRYPT
1762         pbe_type = PBE_TYPE_SCRYPT;
1763 #else
1764         t->skip = 1;
1765         return 1;
1766 #endif
1767     } else if (strcmp(alg, "pbkdf2") == 0) {
1768         pbe_type = PBE_TYPE_PBKDF2;
1769     } else if (strcmp(alg, "pkcs12") == 0) {
1770         pbe_type = PBE_TYPE_PKCS12;
1771     } else {
1772         TEST_error("Unknown pbe algorithm %s", alg);
1773     }
1774     pdat = OPENSSL_malloc(sizeof(*pdat));
1775     pdat->pbe_type = pbe_type;
1776     pdat->pass = NULL;
1777     pdat->salt = NULL;
1778     pdat->N = 0;
1779     pdat->r = 0;
1780     pdat->p = 0;
1781     pdat->maxmem = 0;
1782     pdat->id = 0;
1783     pdat->iter = 0;
1784     pdat->md = NULL;
1785     t->data = pdat;
1786     return 1;
1787 }
1788
1789 static void pbe_test_cleanup(EVP_TEST *t)
1790 {
1791     PBE_DATA *pdat = t->data;
1792
1793     OPENSSL_free(pdat->pass);
1794     OPENSSL_free(pdat->salt);
1795     OPENSSL_free(pdat->key);
1796 }
1797
1798 static int pbe_test_parse(EVP_TEST *t,
1799                           const char *keyword, const char *value)
1800 {
1801     PBE_DATA *pdata = t->data;
1802
1803     if (strcmp(keyword, "Password") == 0)
1804         return test_bin(value, &pdata->pass, &pdata->pass_len);
1805     if (strcmp(keyword, "Salt") == 0)
1806         return test_bin(value, &pdata->salt, &pdata->salt_len);
1807     if (strcmp(keyword, "Key") == 0)
1808         return test_bin(value, &pdata->key, &pdata->key_len);
1809     if (pdata->pbe_type == PBE_TYPE_PBKDF2)
1810         return pbkdf2_test_parse(t, keyword, value);
1811     else if (pdata->pbe_type == PBE_TYPE_PKCS12)
1812         return pkcs12_test_parse(t, keyword, value);
1813 #ifndef OPENSSL_NO_SCRYPT
1814     else if (pdata->pbe_type == PBE_TYPE_SCRYPT)
1815         return scrypt_test_parse(t, keyword, value);
1816 #endif
1817     return 0;
1818 }
1819
1820 static int pbe_test_run(EVP_TEST *t)
1821 {
1822     PBE_DATA *pdata = t->data;
1823     unsigned char *key;
1824
1825     if (!TEST_ptr(key = OPENSSL_malloc(pdata->key_len))) {
1826         t->err = "INTERNAL_ERROR";
1827         goto err;
1828     }
1829     if (pdata->pbe_type == PBE_TYPE_PBKDF2) {
1830         if (PKCS5_PBKDF2_HMAC((char *)pdata->pass, pdata->pass_len,
1831                               pdata->salt, pdata->salt_len,
1832                               pdata->iter, pdata->md,
1833                               pdata->key_len, key) == 0) {
1834             t->err = "PBKDF2_ERROR";
1835             goto err;
1836         }
1837 #ifndef OPENSSL_NO_SCRYPT
1838     } else if (pdata->pbe_type == PBE_TYPE_SCRYPT) {
1839         if (EVP_PBE_scrypt((const char *)pdata->pass, pdata->pass_len,
1840                            pdata->salt, pdata->salt_len,
1841                            pdata->N, pdata->r, pdata->p, pdata->maxmem,
1842                            key, pdata->key_len) == 0) {
1843             t->err = "SCRYPT_ERROR";
1844             goto err;
1845         }
1846 #endif
1847     } else if (pdata->pbe_type == PBE_TYPE_PKCS12) {
1848         if (PKCS12_key_gen_uni(pdata->pass, pdata->pass_len,
1849                                pdata->salt, pdata->salt_len,
1850                                pdata->id, pdata->iter, pdata->key_len,
1851                                key, pdata->md) == 0) {
1852             t->err = "PKCS12_ERROR";
1853             goto err;
1854         }
1855     }
1856     if (!compare_mem(pdata->key, pdata->key_len, key, pdata->key_len)) {
1857         t->err = "KEY_MISMATCH";
1858         goto err;
1859     }
1860     t->err = NULL;
1861 err:
1862     OPENSSL_free(key);
1863     return 1;
1864 }
1865
1866 static const EVP_TEST_METHOD pbe_test_method = {
1867     "PBE",
1868     pbe_test_init,
1869     pbe_test_cleanup,
1870     pbe_test_parse,
1871     pbe_test_run
1872 };
1873
1874 /* Base64 tests */
1875
1876 typedef enum {
1877     BASE64_CANONICAL_ENCODING = 0,
1878     BASE64_VALID_ENCODING = 1,
1879     BASE64_INVALID_ENCODING = 2
1880 } base64_encoding_type;
1881
1882 typedef struct encode_data_st {
1883     /* Input to encoding */
1884     unsigned char *input;
1885     size_t input_len;
1886     /* Expected output */
1887     unsigned char *output;
1888     size_t output_len;
1889     base64_encoding_type encoding;
1890 } ENCODE_DATA;
1891
1892 static int encode_test_init(EVP_TEST *t, const char *encoding)
1893 {
1894     ENCODE_DATA *edata = OPENSSL_zalloc(sizeof(*edata));
1895
1896     if (strcmp(encoding, "canonical") == 0) {
1897         edata->encoding = BASE64_CANONICAL_ENCODING;
1898     } else if (strcmp(encoding, "valid") == 0) {
1899         edata->encoding = BASE64_VALID_ENCODING;
1900     } else if (strcmp(encoding, "invalid") == 0) {
1901         edata->encoding = BASE64_INVALID_ENCODING;
1902         t->expected_err = OPENSSL_strdup("DECODE_ERROR");
1903         if (t->expected_err == NULL)
1904             return 0;
1905     } else {
1906         TEST_info("Bad encoding: %s. Should be one of "
1907                   "{canonical, valid, invalid}", encoding);
1908         return 0;
1909     }
1910     t->data = edata;
1911     return 1;
1912 }
1913
1914 static void encode_test_cleanup(EVP_TEST *t)
1915 {
1916     ENCODE_DATA *edata = t->data;
1917
1918     OPENSSL_free(edata->input);
1919     OPENSSL_free(edata->output);
1920     memset(edata, 0, sizeof(*edata));
1921 }
1922
1923 static int encode_test_parse(EVP_TEST *t,
1924                              const char *keyword, const char *value)
1925 {
1926     ENCODE_DATA *edata = t->data;
1927     if (strcmp(keyword, "Input") == 0)
1928         return test_bin(value, &edata->input, &edata->input_len);
1929     if (strcmp(keyword, "Output") == 0)
1930         return test_bin(value, &edata->output, &edata->output_len);
1931     return 0;
1932 }
1933
1934 static int encode_test_run(EVP_TEST *t)
1935 {
1936     ENCODE_DATA *edata = t->data;
1937     unsigned char *encode_out = NULL, *decode_out = NULL;
1938     int output_len, chunk_len;
1939     EVP_ENCODE_CTX *decode_ctx;
1940
1941     if (!TEST_ptr(decode_ctx = EVP_ENCODE_CTX_new())) {
1942         t->err = "INTERNAL_ERROR";
1943         goto err;
1944     }
1945
1946     if (edata->encoding == BASE64_CANONICAL_ENCODING) {
1947         EVP_ENCODE_CTX *encode_ctx;
1948
1949         if (!TEST_ptr(encode_ctx = EVP_ENCODE_CTX_new())
1950                 || !TEST_ptr(encode_out =
1951                         OPENSSL_malloc(EVP_ENCODE_LENGTH(edata->input_len))))
1952             goto err;
1953
1954         EVP_EncodeInit(encode_ctx);
1955         EVP_EncodeUpdate(encode_ctx, encode_out, &chunk_len,
1956                          edata->input, edata->input_len);
1957         output_len = chunk_len;
1958
1959         EVP_EncodeFinal(encode_ctx, encode_out + chunk_len, &chunk_len);
1960         output_len += chunk_len;
1961
1962         EVP_ENCODE_CTX_free(encode_ctx);
1963
1964         if (!compare_mem(edata->output, edata->output_len,
1965                          encode_out, output_len)) {
1966             t->err = "BAD_ENCODING";
1967             goto err;
1968         }
1969     }
1970
1971     if (!TEST_ptr(decode_out =
1972                 OPENSSL_malloc(EVP_DECODE_LENGTH(edata->output_len))))
1973         goto err;
1974
1975     EVP_DecodeInit(decode_ctx);
1976     if (EVP_DecodeUpdate(decode_ctx, decode_out, &chunk_len, edata->output,
1977                          edata->output_len) < 0) {
1978         t->err = "DECODE_ERROR";
1979         goto err;
1980     }
1981     output_len = chunk_len;
1982
1983     if (EVP_DecodeFinal(decode_ctx, decode_out + chunk_len, &chunk_len) != 1) {
1984         t->err = "DECODE_ERROR";
1985         goto err;
1986     }
1987     output_len += chunk_len;
1988
1989     if (edata->encoding != BASE64_INVALID_ENCODING
1990             && !compare_mem(edata->input, edata->input_len,
1991                             decode_out, output_len)) {
1992         t->err = "BAD_DECODING";
1993         goto err;
1994     }
1995
1996     t->err = NULL;
1997  err:
1998     OPENSSL_free(encode_out);
1999     OPENSSL_free(decode_out);
2000     EVP_ENCODE_CTX_free(decode_ctx);
2001     return 1;
2002 }
2003
2004 static const EVP_TEST_METHOD encode_test_method = {
2005     "Encoding",
2006     encode_test_init,
2007     encode_test_cleanup,
2008     encode_test_parse,
2009     encode_test_run,
2010 };
2011
2012 /* KDF operations */
2013
2014 typedef struct kdf_data_st {
2015     /* Context for this operation */
2016     EVP_PKEY_CTX *ctx;
2017     /* Expected output */
2018     unsigned char *output;
2019     size_t output_len;
2020 } KDF_DATA;
2021
2022 /*
2023  * Perform public key operation setup: lookup key, allocated ctx and call
2024  * the appropriate initialisation function
2025  */
2026 static int kdf_test_init(EVP_TEST *t, const char *name)
2027 {
2028     KDF_DATA *kdata;
2029
2030     kdata = OPENSSL_malloc(sizeof(*kdata));
2031     if (kdata == NULL)
2032         return 0;
2033     kdata->ctx = NULL;
2034     kdata->output = NULL;
2035     t->data = kdata;
2036     kdata->ctx = EVP_PKEY_CTX_new_id(OBJ_sn2nid(name), NULL);
2037     if (kdata->ctx == NULL)
2038         return 0;
2039     if (EVP_PKEY_derive_init(kdata->ctx) <= 0)
2040         return 0;
2041     return 1;
2042 }
2043
2044 static void kdf_test_cleanup(EVP_TEST *t)
2045 {
2046     KDF_DATA *kdata = t->data;
2047     OPENSSL_free(kdata->output);
2048     EVP_PKEY_CTX_free(kdata->ctx);
2049 }
2050
2051 static int kdf_test_parse(EVP_TEST *t,
2052                           const char *keyword, const char *value)
2053 {
2054     KDF_DATA *kdata = t->data;
2055
2056     if (strcmp(keyword, "Output") == 0)
2057         return test_bin(value, &kdata->output, &kdata->output_len);
2058     if (strncmp(keyword, "Ctrl", 4) == 0)
2059         return pkey_test_ctrl(t, kdata->ctx, value);
2060     return 0;
2061 }
2062
2063 static int kdf_test_run(EVP_TEST *t)
2064 {
2065     KDF_DATA *kdata = t->data;
2066     unsigned char *out = NULL;
2067     size_t out_len = kdata->output_len;
2068
2069     if (!TEST_ptr(out = OPENSSL_malloc(out_len))) {
2070         t->err = "INTERNAL_ERROR";
2071         goto err;
2072     }
2073     if (EVP_PKEY_derive(kdata->ctx, out, &out_len) <= 0) {
2074         t->err = "KDF_DERIVE_ERROR";
2075         goto err;
2076     }
2077     if (!compare_mem(kdata->output, kdata->output_len, out, out_len)) {
2078         t->err = "KDF_MISMATCH";
2079         goto err;
2080     }
2081     t->err = NULL;
2082
2083  err:
2084     OPENSSL_free(out);
2085     return 1;
2086 }
2087
2088 static const EVP_TEST_METHOD kdf_test_method = {
2089     "KDF",
2090     kdf_test_init,
2091     kdf_test_cleanup,
2092     kdf_test_parse,
2093     kdf_test_run
2094 };
2095
2096 typedef struct keypair_test_buffer_st {
2097     EVP_PKEY *privk;
2098     EVP_PKEY *pubk;
2099 } KEYPAIR_TEST_DATA;
2100
2101 static int keypair_test_init(EVP_TEST *t, const char *pair)
2102 {
2103     int rv = 0;
2104     EVP_PKEY *pk = NULL, *pubk = NULL;
2105     char *pub, *priv = NULL;
2106     KEYPAIR_TEST_DATA *data;
2107
2108     if (!TEST_ptr(priv = OPENSSL_strdup(pair))
2109             || !TEST_ptr(pub = strchr(priv, ':'))) {
2110         t->err = "PARSING_ERROR";
2111         goto end;
2112     }
2113     *pub++ = 0; /* split priv and pub strings */
2114
2115     if (!TEST_true(find_key(&pk, priv, private_keys))) {
2116         TEST_info("Cannot find private key: %s", priv);
2117         t->err = "MISSING_PRIVATE_KEY";
2118         goto end;
2119     }
2120     if (!TEST_true(find_key(&pubk, pub, public_keys))) {
2121         TEST_info("Cannot find public key: %s", pub);
2122         t->err = "MISSING_PUBLIC_KEY";
2123         goto end;
2124     }
2125
2126     if (pk == NULL && pubk == NULL) {
2127         /* Both keys are listed but unsupported: skip this test */
2128         t->skip = 1;
2129         rv = 1;
2130         goto end;
2131     }
2132
2133     if (!TEST_ptr(data = OPENSSL_malloc(sizeof(*data))))
2134         goto end;
2135
2136     data->privk = pk;
2137     data->pubk = pubk;
2138     t->data = data;
2139     rv = 1;
2140     t->err = NULL;
2141
2142 end:
2143     OPENSSL_free(priv);
2144     return rv;
2145 }
2146
2147 static void keypair_test_cleanup(EVP_TEST *t)
2148 {
2149     OPENSSL_free(t->data);
2150     t->data = NULL;
2151 }
2152
2153 /* For test that do not accept any custom keyword:
2154  *      return 0 if called
2155  */
2156 static int void_test_parse(EVP_TEST *t, const char *keyword, const char *value)
2157 {
2158     return 0;
2159 }
2160
2161 static int keypair_test_run(EVP_TEST *t)
2162 {
2163     int rv = 0;
2164     const KEYPAIR_TEST_DATA *pair = t->data;
2165
2166     if (pair->privk == NULL || pair->pubk == NULL) {
2167         /*
2168          * this can only happen if only one of the keys is not set
2169          * which means that one of them was unsupported while the
2170          * other isn't: hence a key type mismatch.
2171          */
2172         t->err = "KEYPAIR_TYPE_MISMATCH";
2173         rv = 1;
2174         goto end;
2175     }
2176
2177     if ((rv = EVP_PKEY_cmp(pair->privk, pair->pubk)) != 1 ) {
2178         if ( 0 == rv ) {
2179             t->err = "KEYPAIR_MISMATCH";
2180         } else if ( -1 == rv ) {
2181             t->err = "KEYPAIR_TYPE_MISMATCH";
2182         } else if ( -2 == rv ) {
2183             t->err = "UNSUPPORTED_KEY_COMPARISON";
2184         } else {
2185             TEST_error("Unexpected error in key comparison");
2186             rv = 0;
2187             goto end;
2188         }
2189         rv = 1;
2190         goto end;
2191     }
2192
2193     rv = 1;
2194     t->err = NULL;
2195
2196 end:
2197     return rv;
2198 }
2199
2200 static const EVP_TEST_METHOD keypair_test_method = {
2201     "PrivPubKeyPair",
2202     keypair_test_init,
2203     keypair_test_cleanup,
2204     void_test_parse,
2205     keypair_test_run
2206 };
2207
2208 typedef struct {
2209     /* Set to 1 if verifying */
2210     int is_verify;
2211     /* Set to 1 for one shot operation */
2212     int is_oneshot;
2213     /* Digest to use */
2214     const EVP_MD *md;
2215     /* Digest context */
2216     EVP_MD_CTX *ctx;
2217     EVP_PKEY_CTX *pctx;
2218     /* Input data: streaming */
2219     STACK_OF(EVP_TEST_BUFFER) *input;
2220     /* Input data if one shot */
2221     unsigned char *osin;
2222     size_t osin_len;
2223     /* Expected output */
2224     unsigned char *output;
2225     size_t output_len;
2226 } DIGESTSIGN_DATA;
2227
2228 static int digestsigver_test_init(EVP_TEST *t, const char *alg, int is_verify,
2229                                   int is_oneshot)
2230 {
2231     const EVP_MD *md = NULL;
2232     DIGESTSIGN_DATA *mdat;
2233
2234     if (strcmp(alg, "NULL") != 0) {
2235         if ((md = EVP_get_digestbyname(alg)) == NULL) {
2236             /* If alg has an OID assume disabled algorithm */
2237             if (OBJ_sn2nid(alg) != NID_undef || OBJ_ln2nid(alg) != NID_undef) {
2238                 t->skip = 1;
2239                 return 1;
2240             }
2241             return 0;
2242         }
2243     }
2244     if (!TEST_ptr(mdat = OPENSSL_zalloc(sizeof(*mdat))))
2245         return 0;
2246     mdat->md = md;
2247     if (!TEST_ptr(mdat->ctx = EVP_MD_CTX_new())) {
2248         OPENSSL_free(mdat);
2249         return 0;
2250     }
2251     mdat->is_verify = is_verify;
2252     mdat->is_oneshot = is_oneshot;
2253     t->data = mdat;
2254     return 1;
2255 }
2256
2257 static int digestsign_test_init(EVP_TEST *t, const char *alg)
2258 {
2259     return digestsigver_test_init(t, alg, 0, 0);
2260 }
2261
2262 static void digestsigver_test_cleanup(EVP_TEST *t)
2263 {
2264     DIGESTSIGN_DATA *mdata = t->data;
2265
2266     EVP_MD_CTX_free(mdata->ctx);
2267     sk_EVP_TEST_BUFFER_pop_free(mdata->input, evp_test_buffer_free);
2268     OPENSSL_free(mdata->osin);
2269     OPENSSL_free(mdata->output);
2270     OPENSSL_free(mdata);
2271     t->data = NULL;
2272 }
2273
2274 static int digestsigver_test_parse(EVP_TEST *t,
2275                                    const char *keyword, const char *value)
2276 {
2277     DIGESTSIGN_DATA *mdata = t->data;
2278
2279     if (strcmp(keyword, "Key") == 0) {
2280         EVP_PKEY *pkey = NULL;
2281         int rv = 0;
2282
2283         if (mdata->is_verify)
2284             rv = find_key(&pkey, value, public_keys);
2285         if (rv == 0)
2286             rv = find_key(&pkey, value, private_keys);
2287         if (rv == 0 || pkey == NULL) {
2288             t->skip = 1;
2289             return 1;
2290         }
2291         if (mdata->is_verify) {
2292             if (!EVP_DigestVerifyInit(mdata->ctx, &mdata->pctx, mdata->md,
2293                                       NULL, pkey))
2294                 t->err = "DIGESTVERIFYINIT_ERROR";
2295             return 1;
2296         }
2297         if (!EVP_DigestSignInit(mdata->ctx, &mdata->pctx, mdata->md, NULL,
2298                                 pkey))
2299             t->err = "DIGESTSIGNINIT_ERROR";
2300         return 1;
2301     }
2302
2303     if (strcmp(keyword, "Input") == 0) {
2304         if (mdata->is_oneshot)
2305             return test_bin(value, &mdata->osin, &mdata->osin_len);
2306         return evp_test_buffer_append(value, &mdata->input);
2307     }
2308     if (strcmp(keyword, "Output") == 0)
2309         return test_bin(value, &mdata->output, &mdata->output_len);
2310
2311     if (!mdata->is_oneshot) {
2312         if (strcmp(keyword, "Count") == 0)
2313             return evp_test_buffer_set_count(value, mdata->input);
2314         if (strcmp(keyword, "Ncopy") == 0)
2315             return evp_test_buffer_ncopy(value, mdata->input);
2316     }
2317     if (strcmp(keyword, "Ctrl") == 0) {
2318         if (mdata->pctx == NULL)
2319             return 0;
2320         return pkey_test_ctrl(t, mdata->pctx, value);
2321     }
2322     return 0;
2323 }
2324
2325 static int digestsign_update_fn(void *ctx, const unsigned char *buf,
2326                                 size_t buflen)
2327 {
2328     return EVP_DigestSignUpdate(ctx, buf, buflen);
2329 }
2330
2331 static int digestsign_test_run(EVP_TEST *t)
2332 {
2333     DIGESTSIGN_DATA *mdata = t->data;
2334     unsigned char *buf = NULL;
2335     size_t buflen;
2336
2337     if (!evp_test_buffer_do(mdata->input, digestsign_update_fn, mdata->ctx)) {
2338         t->err = "DIGESTUPDATE_ERROR";
2339         goto err;
2340     }
2341
2342     if (!EVP_DigestSignFinal(mdata->ctx, NULL, &buflen)) {
2343         t->err = "DIGESTSIGNFINAL_LENGTH_ERROR";
2344         goto err;
2345     }
2346     if (!TEST_ptr(buf = OPENSSL_malloc(buflen))) {
2347         t->err = "MALLOC_FAILURE";
2348         goto err;
2349     }
2350     if (!EVP_DigestSignFinal(mdata->ctx, buf, &buflen)) {
2351         t->err = "DIGESTSIGNFINAL_ERROR";
2352         goto err;
2353     }
2354     if (!compare_mem(mdata->output, mdata->output_len, buf, buflen)) {
2355         t->err = "SIGNATURE_MISMATCH";
2356         goto err;
2357     }
2358
2359  err:
2360     OPENSSL_free(buf);
2361     return 1;
2362 }
2363
2364 static const EVP_TEST_METHOD digestsign_test_method = {
2365     "DigestSign",
2366     digestsign_test_init,
2367     digestsigver_test_cleanup,
2368     digestsigver_test_parse,
2369     digestsign_test_run
2370 };
2371
2372 static int digestverify_test_init(EVP_TEST *t, const char *alg)
2373 {
2374     return digestsigver_test_init(t, alg, 1, 0);
2375 }
2376
2377 static int digestverify_update_fn(void *ctx, const unsigned char *buf,
2378                                   size_t buflen)
2379 {
2380     return EVP_DigestVerifyUpdate(ctx, buf, buflen);
2381 }
2382
2383 static int digestverify_test_run(EVP_TEST *t)
2384 {
2385     DIGESTSIGN_DATA *mdata = t->data;
2386
2387     if (!evp_test_buffer_do(mdata->input, digestverify_update_fn, mdata->ctx)) {
2388         t->err = "DIGESTUPDATE_ERROR";
2389         return 1;
2390     }
2391
2392     if (EVP_DigestVerifyFinal(mdata->ctx, mdata->output,
2393                               mdata->output_len) <= 0)
2394         t->err = "VERIFY_ERROR";
2395     return 1;
2396 }
2397
2398 static const EVP_TEST_METHOD digestverify_test_method = {
2399     "DigestVerify",
2400     digestverify_test_init,
2401     digestsigver_test_cleanup,
2402     digestsigver_test_parse,
2403     digestverify_test_run
2404 };
2405
2406 static int oneshot_digestsign_test_init(EVP_TEST *t, const char *alg)
2407 {
2408     return digestsigver_test_init(t, alg, 0, 1);
2409 }
2410
2411 static int oneshot_digestsign_test_run(EVP_TEST *t)
2412 {
2413     DIGESTSIGN_DATA *mdata = t->data;
2414     unsigned char *buf = NULL;
2415     size_t buflen;
2416
2417     if (!EVP_DigestSign(mdata->ctx, NULL, &buflen, mdata->osin,
2418                         mdata->osin_len)) {
2419         t->err = "DIGESTSIGN_LENGTH_ERROR";
2420         goto err;
2421     }
2422     if (!TEST_ptr(buf = OPENSSL_malloc(buflen))) {
2423         t->err = "MALLOC_FAILURE";
2424         goto err;
2425     }
2426     if (!EVP_DigestSign(mdata->ctx, buf, &buflen, mdata->osin,
2427                         mdata->osin_len)) {
2428         t->err = "DIGESTSIGN_ERROR";
2429         goto err;
2430     }
2431     if (!compare_mem(mdata->output, mdata->output_len, buf, buflen)) {
2432         t->err = "SIGNATURE_MISMATCH";
2433         goto err;
2434     }
2435
2436  err:
2437     OPENSSL_free(buf);
2438     return 1;
2439 }
2440
2441 static const EVP_TEST_METHOD oneshot_digestsign_test_method = {
2442     "OneShotDigestSign",
2443     oneshot_digestsign_test_init,
2444     digestsigver_test_cleanup,
2445     digestsigver_test_parse,
2446     oneshot_digestsign_test_run
2447 };
2448
2449 static int oneshot_digestverify_test_init(EVP_TEST *t, const char *alg)
2450 {
2451     return digestsigver_test_init(t, alg, 1, 1);
2452 }
2453
2454 static int oneshot_digestverify_test_run(EVP_TEST *t)
2455 {
2456     DIGESTSIGN_DATA *mdata = t->data;
2457
2458     if (EVP_DigestVerify(mdata->ctx, mdata->output, mdata->output_len,
2459                          mdata->osin, mdata->osin_len) <= 0)
2460         t->err = "VERIFY_ERROR";
2461     return 1;
2462 }
2463
2464 static const EVP_TEST_METHOD oneshot_digestverify_test_method = {
2465     "OneShotDigestVerify",
2466     oneshot_digestverify_test_init,
2467     digestsigver_test_cleanup,
2468     digestsigver_test_parse,
2469     oneshot_digestverify_test_run
2470 };
2471
2472 static int do_test_file(const char *testfile)
2473 {
2474     BIO *in;
2475     char buf[10240];
2476     EVP_TEST t;
2477
2478     set_test_title(testfile);
2479     current_test_file = testfile;
2480     if (!TEST_ptr(in = BIO_new_file(testfile, "rb")))
2481         return 0;
2482     memset(&t, 0, sizeof(t));
2483     t.start_line = -1;
2484     t.in = in;
2485     t.err = NULL;
2486     while (BIO_gets(in, buf, sizeof(buf))) {
2487         t.line++;
2488         if (!TEST_true(parse_test_line(&t, buf)))
2489             return 0;
2490     }
2491     /* Run any final test we have */
2492     if (!run_and_get_next(&t, NULL))
2493         return 0;
2494
2495     TEST_info("Completed %d tests with %d errors and %d skipped",
2496               t.ntests, t.errors, t.nskip);
2497     free_key_list(public_keys);
2498     free_key_list(private_keys);
2499     BIO_free(t.key);
2500     BIO_free(in);
2501     return t.errors == 0;
2502 }
2503
2504 static char * const *testfiles;
2505
2506 static int run_file_tests(int i)
2507 {
2508     return do_test_file(testfiles[i]);
2509 }
2510
2511 int test_main(int argc, char *argv[])
2512 {
2513     if (argc < 2) {
2514         TEST_error("Usage: %s file...", argv[0]);
2515         return 0;
2516     }
2517     testfiles = &argv[1];
2518
2519     ADD_ALL_TESTS(run_file_tests, argc - 1);
2520
2521     return run_tests(argv[0]);
2522 }