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