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