1227825Stheraven/*
2227825Stheraven * Copyright 2015-2021 The OpenSSL Project Authors. All Rights Reserved.
3227825Stheraven *
4227825Stheraven * Licensed under the OpenSSL license (the "License").  You may not use
5227825Stheraven * this file except in compliance with the License.  You can obtain a copy
6227825Stheraven * in the file LICENSE in the source distribution or at
7227825Stheraven * https://www.openssl.org/source/license.html
8227825Stheraven */
9227825Stheraven
10227825Stheraven#include <stdio.h>
11227825Stheraven#include <string.h>
12227825Stheraven#include <stdlib.h>
13227825Stheraven#include <ctype.h>
14227825Stheraven#include <openssl/evp.h>
15227825Stheraven#include <openssl/pem.h>
16227825Stheraven#include <openssl/err.h>
17227825Stheraven#include <openssl/x509v3.h>
18227825Stheraven#include <openssl/pkcs12.h>
19227825Stheraven#include <openssl/kdf.h>
20227825Stheraven#include "internal/numbers.h"
21227825Stheraven#include "testutil.h"
22227825Stheraven#include "evp_test.h"
23227825Stheraven
24227825Stheraven
25227825Stheraventypedef struct evp_test_method_st EVP_TEST_METHOD;
26227825Stheraven
27227825Stheraven/*
28227825Stheraven * Structure holding test information
29227825Stheraven */
30227825Stheraventypedef struct evp_test_st {
31227825Stheraven    STANZA s;                     /* Common test stanza */
32227825Stheraven    char *name;
33227825Stheraven    int skip;                     /* Current test should be skipped */
34227825Stheraven    const EVP_TEST_METHOD *meth;  /* method for this test */
35227825Stheraven    const char *err, *aux_err;    /* Error string for test */
36227825Stheraven    char *expected_err;           /* Expected error value of test */
37227825Stheraven    char *func;                   /* Expected error function string */
38227825Stheraven    char *reason;                 /* Expected error reason string */
39227825Stheraven    void *data;                   /* test specific data */
40227825Stheraven} EVP_TEST;
41227825Stheraven
42227825Stheraven/*
43227825Stheraven * Test method structure
44227825Stheraven */
45227825Stheravenstruct evp_test_method_st {
46227825Stheraven    /* Name of test as it appears in file */
47227825Stheraven    const char *name;
48227825Stheraven    /* Initialise test for "alg" */
49227825Stheraven    int (*init) (EVP_TEST * t, const char *alg);
50227825Stheraven    /* Clean up method */
51227825Stheraven    void (*cleanup) (EVP_TEST * t);
52227825Stheraven    /* Test specific name value pair processing */
53227825Stheraven    int (*parse) (EVP_TEST * t, const char *name, const char *value);
54227825Stheraven    /* Run the test itself */
55227825Stheraven    int (*run_test) (EVP_TEST * t);
56227825Stheraven};
57227825Stheraven
58227825Stheraven
59227825Stheraven/*
60227825Stheraven * Linked list of named keys.
61227825Stheraven */
62227825Stheraventypedef struct key_list_st {
63227825Stheraven    char *name;
64227825Stheraven    EVP_PKEY *key;
65227825Stheraven    struct key_list_st *next;
66227825Stheraven} KEY_LIST;
67227825Stheraven
68227825Stheraven/*
69227825Stheraven * List of public and private keys
70227825Stheraven */
71227825Stheravenstatic KEY_LIST *private_keys;
72227825Stheravenstatic KEY_LIST *public_keys;
73227825Stheravenstatic int find_key(EVP_PKEY **ppk, const char *name, KEY_LIST *lst);
74227825Stheraven
75227825Stheravenstatic int parse_bin(const char *value, unsigned char **buf, size_t *buflen);
76227825Stheraven
77227825Stheraven/*
78227825Stheraven * Compare two memory regions for equality, returning zero if they differ.
79227825Stheraven * However, if there is expected to be an error and the actual error
80227825Stheraven * matches then the memory is expected to be different so handle this
81227825Stheraven * case without producing unnecessary test framework output.
82227825Stheraven */
83227825Stheravenstatic int memory_err_compare(EVP_TEST *t, const char *err,
84227825Stheraven                              const void *expected, size_t expected_len,
85227825Stheraven                              const void *got, size_t got_len)
86227825Stheraven{
87227825Stheraven    int r;
88227825Stheraven
89227825Stheraven    if (t->expected_err != NULL && strcmp(t->expected_err, err) == 0)
90227825Stheraven        r = !TEST_mem_ne(expected, expected_len, got, got_len);
91227825Stheraven    else
92227825Stheraven        r = TEST_mem_eq(expected, expected_len, got, got_len);
93227825Stheraven    if (!r)
94227825Stheraven        t->err = err;
95227825Stheraven    return r;
96227825Stheraven}
97227825Stheraven
98227825Stheraven/*
99227825Stheraven * Structure used to hold a list of blocks of memory to test
100227825Stheraven * calls to "update" like functions.
101227825Stheraven */
102227825Stheravenstruct evp_test_buffer_st {
103227825Stheraven    unsigned char *buf;
104227825Stheraven    size_t buflen;
105227825Stheraven    size_t count;
106227825Stheraven    int count_set;
107227825Stheraven};
108227825Stheraven
109227825Stheravenstatic void evp_test_buffer_free(EVP_TEST_BUFFER *db)
110227825Stheraven{
111227825Stheraven    if (db != NULL) {
112227825Stheraven        OPENSSL_free(db->buf);
113227825Stheraven        OPENSSL_free(db);
114227825Stheraven    }
115227825Stheraven}
116227825Stheraven
117227825Stheraven/*
118227825Stheraven * append buffer to a list
119227825Stheraven */
120227825Stheravenstatic int evp_test_buffer_append(const char *value,
121227825Stheraven                                  STACK_OF(EVP_TEST_BUFFER) **sk)
122227825Stheraven{
123227825Stheraven    EVP_TEST_BUFFER *db = NULL;
124227825Stheraven
125227825Stheraven    if (!TEST_ptr(db = OPENSSL_malloc(sizeof(*db))))
126227825Stheraven        goto err;
127227825Stheraven
128227825Stheraven    if (!parse_bin(value, &db->buf, &db->buflen))
129227825Stheraven        goto err;
130227825Stheraven    db->count = 1;
131227825Stheraven    db->count_set = 0;
132227825Stheraven
133227825Stheraven    if (*sk == NULL && !TEST_ptr(*sk = sk_EVP_TEST_BUFFER_new_null()))
134227825Stheraven        goto err;
135227825Stheraven    if (!sk_EVP_TEST_BUFFER_push(*sk, db))
136227825Stheraven        goto err;
137227825Stheraven
138227825Stheraven    return 1;
139227825Stheraven
140227825Stheravenerr:
141227825Stheraven    evp_test_buffer_free(db);
142227825Stheraven    return 0;
143227825Stheraven}
144227825Stheraven
145227825Stheraven/*
146227825Stheraven * replace last buffer in list with copies of itself
147227825Stheraven */
148227825Stheravenstatic int evp_test_buffer_ncopy(const char *value,
149227825Stheraven                                 STACK_OF(EVP_TEST_BUFFER) *sk)
150227825Stheraven{
151227825Stheraven    EVP_TEST_BUFFER *db;
152227825Stheraven    unsigned char *tbuf, *p;
153227825Stheraven    size_t tbuflen;
154227825Stheraven    int ncopy = atoi(value);
155227825Stheraven    int i;
156227825Stheraven
157227825Stheraven    if (ncopy <= 0)
158227825Stheraven        return 0;
159227825Stheraven    if (sk == NULL || sk_EVP_TEST_BUFFER_num(sk) == 0)
160227825Stheraven        return 0;
161227825Stheraven    db = sk_EVP_TEST_BUFFER_value(sk, sk_EVP_TEST_BUFFER_num(sk) - 1);
162227825Stheraven
163227825Stheraven    tbuflen = db->buflen * ncopy;
164227825Stheraven    if (!TEST_ptr(tbuf = OPENSSL_malloc(tbuflen)))
165227825Stheraven        return 0;
166227825Stheraven    for (i = 0, p = tbuf; i < ncopy; i++, p += db->buflen)
167227825Stheraven        memcpy(p, db->buf, db->buflen);
168227825Stheraven
169227825Stheraven    OPENSSL_free(db->buf);
170227825Stheraven    db->buf = tbuf;
171227825Stheraven    db->buflen = tbuflen;
172227825Stheraven    return 1;
173227825Stheraven}
174227825Stheraven
175227825Stheraven/*
176227825Stheraven * set repeat count for last buffer in list
177227825Stheraven */
178227825Stheravenstatic int evp_test_buffer_set_count(const char *value,
179227825Stheraven                                     STACK_OF(EVP_TEST_BUFFER) *sk)
180249998Sdim{
181227825Stheraven    EVP_TEST_BUFFER *db;
182227825Stheraven    int count = atoi(value);
183241903Sdim
184227825Stheraven    if (count <= 0)
185227825Stheraven        return 0;
186227825Stheraven
187227825Stheraven    if (sk == NULL || sk_EVP_TEST_BUFFER_num(sk) == 0)
188241903Sdim        return 0;
189227825Stheraven
190227825Stheraven    db = sk_EVP_TEST_BUFFER_value(sk, sk_EVP_TEST_BUFFER_num(sk) - 1);
191227825Stheraven    if (db->count_set != 0)
192227825Stheraven        return 0;
193249998Sdim
194227825Stheraven    db->count = (size_t)count;
195227825Stheraven    db->count_set = 1;
196227825Stheraven    return 1;
197227825Stheraven}
198227825Stheraven
199227825Stheraven/*
200227825Stheraven * call "fn" with each element of the list in turn
201227825Stheraven */
202227825Stheravenstatic int evp_test_buffer_do(STACK_OF(EVP_TEST_BUFFER) *sk,
203227825Stheraven                              int (*fn)(void *ctx,
204227825Stheraven                                        const unsigned char *buf,
205227825Stheraven                                        size_t buflen),
206227825Stheraven                              void *ctx)
207227825Stheraven{
208227825Stheraven    int i;
209227825Stheraven
210227825Stheraven    for (i = 0; i < sk_EVP_TEST_BUFFER_num(sk); i++) {
211227825Stheraven        EVP_TEST_BUFFER *tb = sk_EVP_TEST_BUFFER_value(sk, i);
212227825Stheraven        size_t j;
213227825Stheraven
214227825Stheraven        for (j = 0; j < tb->count; j++) {
215227825Stheraven            if (fn(ctx, tb->buf, tb->buflen) <= 0)
216227825Stheraven                return 0;
217227825Stheraven        }
218227825Stheraven    }
219227825Stheraven    return 1;
220227825Stheraven}
221227825Stheraven
222227825Stheraven/*
223227825Stheraven * Unescape some sequences in string literals (only \n for now).
224227825Stheraven * Return an allocated buffer, set |out_len|.  If |input_len|
225227825Stheraven * is zero, get an empty buffer but set length to zero.
226227825Stheraven */
227227825Stheravenstatic unsigned char* unescape(const char *input, size_t input_len,
228227825Stheraven                               size_t *out_len)
229227825Stheraven{
230227825Stheraven    unsigned char *ret, *p;
231227825Stheraven    size_t i;
232227825Stheraven
233227825Stheraven    if (input_len == 0) {
234227825Stheraven        *out_len = 0;
235227825Stheraven        return OPENSSL_zalloc(1);
236227825Stheraven    }
237227825Stheraven
238227825Stheraven    /* Escaping is non-expanding; over-allocate original size for simplicity. */
239227825Stheraven    if (!TEST_ptr(ret = p = OPENSSL_malloc(input_len)))
240227825Stheraven        return NULL;
241227825Stheraven
242227825Stheraven    for (i = 0; i < input_len; i++) {
243227825Stheraven        if (*input == '\\') {
244227825Stheraven            if (i == input_len - 1 || *++input != 'n') {
245227825Stheraven                TEST_error("Bad escape sequence in file");
246227825Stheraven                goto err;
247227825Stheraven            }
248227825Stheraven            *p++ = '\n';
249227825Stheraven            i++;
250227825Stheraven            input++;
251227825Stheraven        } else {
252227825Stheraven            *p++ = *input++;
253227825Stheraven        }
254227825Stheraven    }
255227825Stheraven
256227825Stheraven    *out_len = p - ret;
257227825Stheraven    return ret;
258227825Stheraven
259227825Stheraven err:
260227825Stheraven    OPENSSL_free(ret);
261227825Stheraven    return NULL;
262227825Stheraven}
263227825Stheraven
264227825Stheraven/*
265227825Stheraven * For a hex string "value" convert to a binary allocated buffer.
266227825Stheraven * Return 1 on success or 0 on failure.
267227825Stheraven */
268227825Stheravenstatic int parse_bin(const char *value, unsigned char **buf, size_t *buflen)
269227825Stheraven{
270227825Stheraven    long len;
271227825Stheraven
272227825Stheraven    /* Check for NULL literal */
273227825Stheraven    if (strcmp(value, "NULL") == 0) {
274227825Stheraven        *buf = NULL;
275227825Stheraven        *buflen = 0;
276227825Stheraven        return 1;
277227825Stheraven    }
278227825Stheraven
279227825Stheraven    /* Check for empty value */
280227825Stheraven    if (*value == '\0') {
281227825Stheraven        /*
282227825Stheraven         * Don't return NULL for zero length buffer. This is needed for
283227825Stheraven         * some tests with empty keys: HMAC_Init_ex() expects a non-NULL key
284227825Stheraven         * buffer even if the key length is 0, in order to detect key reset.
285227825Stheraven         */
286227825Stheraven        *buf = OPENSSL_malloc(1);
287227825Stheraven        if (*buf == NULL)
288227825Stheraven            return 0;
289227825Stheraven        **buf = 0;
290227825Stheraven        *buflen = 0;
291227825Stheraven        return 1;
292227825Stheraven    }
293227825Stheraven
294227825Stheraven    /* Check for string literal */
295227825Stheraven    if (value[0] == '"') {
296227825Stheraven        size_t vlen = strlen(++value);
297227825Stheraven
298227825Stheraven        if (vlen == 0 || value[vlen - 1] != '"')
299227825Stheraven            return 0;
300227825Stheraven        vlen--;
301227825Stheraven        *buf = unescape(value, vlen, buflen);
302227825Stheraven        return *buf == NULL ? 0 : 1;
303227825Stheraven    }
304227825Stheraven
305227825Stheraven    /* Otherwise assume as hex literal and convert it to binary buffer */
306227825Stheraven    if (!TEST_ptr(*buf = OPENSSL_hexstr2buf(value, &len))) {
307227825Stheraven        TEST_info("Can't convert %s", value);
308227825Stheraven        TEST_openssl_errors();
309227825Stheraven        return -1;
310227825Stheraven    }
311227825Stheraven    /* Size of input buffer means we'll never overflow */
312227825Stheraven    *buflen = len;
313227825Stheraven    return 1;
314227825Stheraven}
315227825Stheraven
316227825Stheraven
317227825Stheraven/**
318227825Stheraven***  MESSAGE DIGEST TESTS
319227825Stheraven**/
320227825Stheraven
321227825Stheraventypedef struct digest_data_st {
322227825Stheraven    /* Digest this test is for */
323227825Stheraven    const EVP_MD *digest;
324227825Stheraven    /* Input to digest */
325227825Stheraven    STACK_OF(EVP_TEST_BUFFER) *input;
326227825Stheraven    /* Expected output */
327227825Stheraven    unsigned char *output;
328227825Stheraven    size_t output_len;
329227825Stheraven} DIGEST_DATA;
330227825Stheraven
331227825Stheravenstatic int digest_test_init(EVP_TEST *t, const char *alg)
332227825Stheraven{
333227825Stheraven    DIGEST_DATA *mdat;
334227825Stheraven    const EVP_MD *digest;
335227825Stheraven
336227825Stheraven    if ((digest = EVP_get_digestbyname(alg)) == NULL) {
337227825Stheraven        /* If alg has an OID assume disabled algorithm */
338227825Stheraven        if (OBJ_sn2nid(alg) != NID_undef || OBJ_ln2nid(alg) != NID_undef) {
339227825Stheraven            t->skip = 1;
340227825Stheraven            return 1;
341227825Stheraven        }
342227825Stheraven        return 0;
343227825Stheraven    }
344227825Stheraven    if (!TEST_ptr(mdat = OPENSSL_zalloc(sizeof(*mdat))))
345227825Stheraven        return 0;
346227825Stheraven    t->data = mdat;
347227825Stheraven    mdat->digest = digest;
348227825Stheraven    return 1;
349227825Stheraven}
350227825Stheraven
351227825Stheravenstatic void digest_test_cleanup(EVP_TEST *t)
352227825Stheraven{
353227825Stheraven    DIGEST_DATA *mdat = t->data;
354227825Stheraven
355227825Stheraven    sk_EVP_TEST_BUFFER_pop_free(mdat->input, evp_test_buffer_free);
356227825Stheraven    OPENSSL_free(mdat->output);
357227825Stheraven}
358227825Stheraven
359227825Stheravenstatic int digest_test_parse(EVP_TEST *t,
360227825Stheraven                             const char *keyword, const char *value)
361227825Stheraven{
362227825Stheraven    DIGEST_DATA *mdata = t->data;
363227825Stheraven
364227825Stheraven    if (strcmp(keyword, "Input") == 0)
365227825Stheraven        return evp_test_buffer_append(value, &mdata->input);
366227825Stheraven    if (strcmp(keyword, "Output") == 0)
367227825Stheraven        return parse_bin(value, &mdata->output, &mdata->output_len);
368227825Stheraven    if (strcmp(keyword, "Count") == 0)
369227825Stheraven        return evp_test_buffer_set_count(value, mdata->input);
370227825Stheraven    if (strcmp(keyword, "Ncopy") == 0)
371227825Stheraven        return evp_test_buffer_ncopy(value, mdata->input);
372227825Stheraven    return 0;
373227825Stheraven}
374227825Stheraven
375227825Stheravenstatic int digest_update_fn(void *ctx, const unsigned char *buf, size_t buflen)
376227825Stheraven{
377227825Stheraven    return EVP_DigestUpdate(ctx, buf, buflen);
378227825Stheraven}
379249998Sdim
380227825Stheravenstatic int digest_test_run(EVP_TEST *t)
381227825Stheraven{
382227825Stheraven    DIGEST_DATA *expected = t->data;
383227825Stheraven    EVP_MD_CTX *mctx;
384227825Stheraven    unsigned char *got = NULL;
385227825Stheraven    unsigned int got_len;
386249998Sdim
387227825Stheraven    t->err = "TEST_FAILURE";
388227825Stheraven    if (!TEST_ptr(mctx = EVP_MD_CTX_new()))
389227825Stheraven        goto err;
390227825Stheraven
391227825Stheraven    got = OPENSSL_malloc(expected->output_len > EVP_MAX_MD_SIZE ?
392227825Stheraven                         expected->output_len : EVP_MAX_MD_SIZE);
393227825Stheraven    if (!TEST_ptr(got))
394227825Stheraven        goto err;
395227825Stheraven
396227825Stheraven    if (!EVP_DigestInit_ex(mctx, expected->digest, NULL)) {
397227825Stheraven        t->err = "DIGESTINIT_ERROR";
398227825Stheraven        goto err;
399227825Stheraven    }
400227825Stheraven    if (!evp_test_buffer_do(expected->input, digest_update_fn, mctx)) {
401227825Stheraven        t->err = "DIGESTUPDATE_ERROR";
402227825Stheraven        goto err;
403227825Stheraven    }
404227825Stheraven
405227825Stheraven    if (EVP_MD_flags(expected->digest) & EVP_MD_FLAG_XOF) {
406227825Stheraven        EVP_MD_CTX *mctx_cpy;
407227825Stheraven        char dont[] = "touch";
408227825Stheraven
409227825Stheraven        if (!TEST_ptr(mctx_cpy = EVP_MD_CTX_new())) {
410227825Stheraven            goto err;
411227825Stheraven        }
412227825Stheraven        if (!EVP_MD_CTX_copy(mctx_cpy, mctx)) {
413227825Stheraven            EVP_MD_CTX_free(mctx_cpy);
414227825Stheraven            goto err;
415227825Stheraven        }
416227825Stheraven        if (!EVP_DigestFinalXOF(mctx_cpy, (unsigned char *)dont, 0)) {
417227825Stheraven            EVP_MD_CTX_free(mctx_cpy);
418227825Stheraven            t->err = "DIGESTFINALXOF_ERROR";
419227825Stheraven            goto err;
420227825Stheraven        }
421227825Stheraven        if (!TEST_str_eq(dont, "touch")) {
422227825Stheraven            EVP_MD_CTX_free(mctx_cpy);
423227825Stheraven            t->err = "DIGESTFINALXOF_ERROR";
424227825Stheraven            goto err;
425227825Stheraven        }
426227825Stheraven        EVP_MD_CTX_free(mctx_cpy);
427227825Stheraven
428227825Stheraven        got_len = expected->output_len;
429227825Stheraven        if (!EVP_DigestFinalXOF(mctx, got, got_len)) {
430227825Stheraven            t->err = "DIGESTFINALXOF_ERROR";
431227825Stheraven            goto err;
432227825Stheraven        }
433227825Stheraven    } else {
434227825Stheraven        if (!EVP_DigestFinal(mctx, got, &got_len)) {
435227825Stheraven            t->err = "DIGESTFINAL_ERROR";
436227825Stheraven            goto err;
437227825Stheraven        }
438227825Stheraven    }
439227825Stheraven    if (!TEST_int_eq(expected->output_len, got_len)) {
440227825Stheraven        t->err = "DIGEST_LENGTH_MISMATCH";
441227825Stheraven        goto err;
442227825Stheraven    }
443227825Stheraven    if (!memory_err_compare(t, "DIGEST_MISMATCH",
444227825Stheraven                            expected->output, expected->output_len,
445227825Stheraven                            got, got_len))
446227825Stheraven        goto err;
447227825Stheraven
448227825Stheraven    t->err = NULL;
449227825Stheraven
450227825Stheraven err:
451227825Stheraven    OPENSSL_free(got);
452227825Stheraven    EVP_MD_CTX_free(mctx);
453227825Stheraven    return 1;
454227825Stheraven}
455227825Stheraven
456227825Stheravenstatic const EVP_TEST_METHOD digest_test_method = {
457227825Stheraven    "Digest",
458227825Stheraven    digest_test_init,
459227825Stheraven    digest_test_cleanup,
460227825Stheraven    digest_test_parse,
461227825Stheraven    digest_test_run
462227825Stheraven};
463227825Stheraven
464227825Stheraven
465227825Stheraven/**
466227825Stheraven***  CIPHER TESTS
467227825Stheraven**/
468227825Stheraven
469227825Stheraventypedef struct cipher_data_st {
470227825Stheraven    const EVP_CIPHER *cipher;
471227825Stheraven    int enc;
472227825Stheraven    /* EVP_CIPH_GCM_MODE, EVP_CIPH_CCM_MODE or EVP_CIPH_OCB_MODE if AEAD */
473227825Stheraven    int aead;
474227825Stheraven    unsigned char *key;
475227825Stheraven    size_t key_len;
476227825Stheraven    unsigned char *iv;
477227825Stheraven    size_t iv_len;
478227825Stheraven    unsigned char *plaintext;
479227825Stheraven    size_t plaintext_len;
480227825Stheraven    unsigned char *ciphertext;
481227825Stheraven    size_t ciphertext_len;
482227825Stheraven    /* GCM, CCM and OCB only */
483227825Stheraven    unsigned char *aad;
484227825Stheraven    size_t aad_len;
485227825Stheraven    unsigned char *tag;
486227825Stheraven    size_t tag_len;
487227825Stheraven    int tag_late;
488227825Stheraven} CIPHER_DATA;
489227825Stheraven
490227825Stheravenstatic int cipher_test_init(EVP_TEST *t, const char *alg)
491227825Stheraven{
492227825Stheraven    const EVP_CIPHER *cipher;
493227825Stheraven    CIPHER_DATA *cdat;
494227825Stheraven    int m;
495227825Stheraven
496227825Stheraven    if ((cipher = EVP_get_cipherbyname(alg)) == NULL) {
497227825Stheraven        /* If alg has an OID assume disabled algorithm */
498227825Stheraven        if (OBJ_sn2nid(alg) != NID_undef || OBJ_ln2nid(alg) != NID_undef) {
499227825Stheraven            t->skip = 1;
500227825Stheraven            return 1;
501227825Stheraven        }
502227825Stheraven        return 0;
503227825Stheraven    }
504227825Stheraven    cdat = OPENSSL_zalloc(sizeof(*cdat));
505227825Stheraven    cdat->cipher = cipher;
506227825Stheraven    cdat->enc = -1;
507227825Stheraven    m = EVP_CIPHER_mode(cipher);
508227825Stheraven    if (m == EVP_CIPH_GCM_MODE
509227825Stheraven            || m == EVP_CIPH_OCB_MODE
510227825Stheraven            || m == EVP_CIPH_CCM_MODE)
511227825Stheraven        cdat->aead = m;
512227825Stheraven    else if (EVP_CIPHER_flags(cipher) & EVP_CIPH_FLAG_AEAD_CIPHER)
513227825Stheraven        cdat->aead = -1;
514227825Stheraven    else
515227825Stheraven        cdat->aead = 0;
516227825Stheraven
517227825Stheraven    t->data = cdat;
518227825Stheraven    return 1;
519227825Stheraven}
520227825Stheraven
521227825Stheravenstatic void cipher_test_cleanup(EVP_TEST *t)
522227825Stheraven{
523227825Stheraven    CIPHER_DATA *cdat = t->data;
524227825Stheraven
525227825Stheraven    OPENSSL_free(cdat->key);
526227825Stheraven    OPENSSL_free(cdat->iv);
527227825Stheraven    OPENSSL_free(cdat->ciphertext);
528227825Stheraven    OPENSSL_free(cdat->plaintext);
529227825Stheraven    OPENSSL_free(cdat->aad);
530227825Stheraven    OPENSSL_free(cdat->tag);
531227825Stheraven}
532227825Stheraven
533227825Stheravenstatic int cipher_test_parse(EVP_TEST *t, const char *keyword,
534227825Stheraven                             const char *value)
535227825Stheraven{
536227825Stheraven    CIPHER_DATA *cdat = t->data;
537227825Stheraven
538227825Stheraven    if (strcmp(keyword, "Key") == 0)
539227825Stheraven        return parse_bin(value, &cdat->key, &cdat->key_len);
540227825Stheraven    if (strcmp(keyword, "IV") == 0)
541227825Stheraven        return parse_bin(value, &cdat->iv, &cdat->iv_len);
542227825Stheraven    if (strcmp(keyword, "Plaintext") == 0)
543227825Stheraven        return parse_bin(value, &cdat->plaintext, &cdat->plaintext_len);
544227825Stheraven    if (strcmp(keyword, "Ciphertext") == 0)
545227825Stheraven        return parse_bin(value, &cdat->ciphertext, &cdat->ciphertext_len);
546227825Stheraven    if (cdat->aead) {
547227825Stheraven        if (strcmp(keyword, "AAD") == 0)
548227825Stheraven            return parse_bin(value, &cdat->aad, &cdat->aad_len);
549227825Stheraven        if (strcmp(keyword, "Tag") == 0)
550227825Stheraven            return parse_bin(value, &cdat->tag, &cdat->tag_len);
551227825Stheraven        if (strcmp(keyword, "SetTagLate") == 0) {
552227825Stheraven            if (strcmp(value, "TRUE") == 0)
553227825Stheraven                cdat->tag_late = 1;
554227825Stheraven            else if (strcmp(value, "FALSE") == 0)
555227825Stheraven                cdat->tag_late = 0;
556227825Stheraven            else
557227825Stheraven                return -1;
558227825Stheraven            return 1;
559227825Stheraven        }
560227825Stheraven    }
561227825Stheraven
562227825Stheraven    if (strcmp(keyword, "Operation") == 0) {
563227825Stheraven        if (strcmp(value, "ENCRYPT") == 0)
564227825Stheraven            cdat->enc = 1;
565227825Stheraven        else if (strcmp(value, "DECRYPT") == 0)
566227825Stheraven            cdat->enc = 0;
567227825Stheraven        else
568227825Stheraven            return -1;
569227825Stheraven        return 1;
570227825Stheraven    }
571227825Stheraven    return 0;
572227825Stheraven}
573227825Stheraven
574227825Stheravenstatic int cipher_test_enc(EVP_TEST *t, int enc,
575227825Stheraven                           size_t out_misalign, size_t inp_misalign, int frag)
576227825Stheraven{
577227825Stheraven    CIPHER_DATA *expected = t->data;
578227825Stheraven    unsigned char *in, *expected_out, *tmp = NULL;
579227825Stheraven    size_t in_len, out_len, donelen = 0;
580227825Stheraven    int ok = 0, tmplen, chunklen, tmpflen;
581227825Stheraven    EVP_CIPHER_CTX *ctx = NULL;
582227825Stheraven
583227825Stheraven    t->err = "TEST_FAILURE";
584227825Stheraven    if (!TEST_ptr(ctx = EVP_CIPHER_CTX_new()))
585227825Stheraven        goto err;
586227825Stheraven    EVP_CIPHER_CTX_set_flags(ctx, EVP_CIPHER_CTX_FLAG_WRAP_ALLOW);
587227825Stheraven    if (enc) {
588227825Stheraven        in = expected->plaintext;
589227825Stheraven        in_len = expected->plaintext_len;
590227825Stheraven        expected_out = expected->ciphertext;
591227825Stheraven        out_len = expected->ciphertext_len;
592227825Stheraven    } else {
593227825Stheraven        in = expected->ciphertext;
594227825Stheraven        in_len = expected->ciphertext_len;
595227825Stheraven        expected_out = expected->plaintext;
596227825Stheraven        out_len = expected->plaintext_len;
597227825Stheraven    }
598227825Stheraven    if (inp_misalign == (size_t)-1) {
599227825Stheraven        /*
600227825Stheraven         * Exercise in-place encryption
601227825Stheraven         */
602227825Stheraven        tmp = OPENSSL_malloc(out_misalign + in_len + 2 * EVP_MAX_BLOCK_LENGTH);
603227825Stheraven        if (!tmp)
604227825Stheraven            goto err;
605227825Stheraven        in = memcpy(tmp + out_misalign, in, in_len);
606227825Stheraven    } else {
607227825Stheraven        inp_misalign += 16 - ((out_misalign + in_len) & 15);
608227825Stheraven        /*
609227825Stheraven         * 'tmp' will store both output and copy of input. We make the copy
610227825Stheraven         * of input to specifically aligned part of 'tmp'. So we just
611227825Stheraven         * figured out how much padding would ensure the required alignment,
612227825Stheraven         * now we allocate extended buffer and finally copy the input just
613227825Stheraven         * past inp_misalign in expression below. Output will be written
614227825Stheraven         * past out_misalign...
615227825Stheraven         */
616227825Stheraven        tmp = OPENSSL_malloc(out_misalign + in_len + 2 * EVP_MAX_BLOCK_LENGTH +
617227825Stheraven                             inp_misalign + in_len);
618227825Stheraven        if (!tmp)
619227825Stheraven            goto err;
620227825Stheraven        in = memcpy(tmp + out_misalign + in_len + 2 * EVP_MAX_BLOCK_LENGTH +
621227825Stheraven                    inp_misalign, in, in_len);
622227825Stheraven    }
623227825Stheraven    if (!EVP_CipherInit_ex(ctx, expected->cipher, NULL, NULL, NULL, enc)) {
624227825Stheraven        t->err = "CIPHERINIT_ERROR";
625227825Stheraven        goto err;
626227825Stheraven    }
627227825Stheraven    if (expected->iv) {
628227825Stheraven        if (expected->aead) {
629227825Stheraven            if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_IVLEN,
630227825Stheraven                                     expected->iv_len, 0)) {
631227825Stheraven                t->err = "INVALID_IV_LENGTH";
632227825Stheraven                goto err;
633227825Stheraven            }
634227825Stheraven        } else if (expected->iv_len != (size_t)EVP_CIPHER_CTX_iv_length(ctx)) {
635227825Stheraven            t->err = "INVALID_IV_LENGTH";
636227825Stheraven            goto err;
637227825Stheraven        }
638227825Stheraven    }
639227825Stheraven    if (expected->aead) {
640227825Stheraven        unsigned char *tag;
641227825Stheraven        /*
642227825Stheraven         * If encrypting or OCB just set tag length initially, otherwise
643227825Stheraven         * set tag length and value.
644227825Stheraven         */
645227825Stheraven        if (enc || expected->aead == EVP_CIPH_OCB_MODE || expected->tag_late) {
646227825Stheraven            t->err = "TAG_LENGTH_SET_ERROR";
647227825Stheraven            tag = NULL;
648227825Stheraven        } else {
649227825Stheraven            t->err = "TAG_SET_ERROR";
650227825Stheraven            tag = expected->tag;
651227825Stheraven        }
652227825Stheraven        if (tag || expected->aead != EVP_CIPH_GCM_MODE) {
653227825Stheraven            if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_TAG,
654227825Stheraven                                     expected->tag_len, tag))
655227825Stheraven                goto err;
656227825Stheraven        }
657227825Stheraven    }
658227825Stheraven
659227825Stheraven    if (!EVP_CIPHER_CTX_set_key_length(ctx, expected->key_len)) {
660227825Stheraven        t->err = "INVALID_KEY_LENGTH";
661227825Stheraven        goto err;
662227825Stheraven    }
663227825Stheraven    if (!EVP_CipherInit_ex(ctx, NULL, NULL, expected->key, expected->iv, -1)) {
664227825Stheraven        t->err = "KEY_SET_ERROR";
665227825Stheraven        goto err;
666227825Stheraven    }
667227825Stheraven
668227825Stheraven    if (expected->aead == EVP_CIPH_CCM_MODE) {
669227825Stheraven        if (!EVP_CipherUpdate(ctx, NULL, &tmplen, NULL, out_len)) {
670227825Stheraven            t->err = "CCM_PLAINTEXT_LENGTH_SET_ERROR";
671227825Stheraven            goto err;
672227825Stheraven        }
673227825Stheraven    }
674227825Stheraven    if (expected->aad) {
675227825Stheraven        t->err = "AAD_SET_ERROR";
676227825Stheraven        if (!frag) {
677227825Stheraven            if (!EVP_CipherUpdate(ctx, NULL, &chunklen, expected->aad,
678227825Stheraven                                  expected->aad_len))
679227825Stheraven                goto err;
680227825Stheraven        } else {
681227825Stheraven            /*
682227825Stheraven             * Supply the AAD in chunks less than the block size where possible
683227825Stheraven             */
684227825Stheraven            if (expected->aad_len > 0) {
685227825Stheraven                if (!EVP_CipherUpdate(ctx, NULL, &chunklen, expected->aad, 1))
686227825Stheraven                    goto err;
687227825Stheraven                donelen++;
688227825Stheraven            }
689227825Stheraven            if (expected->aad_len > 2) {
690227825Stheraven                if (!EVP_CipherUpdate(ctx, NULL, &chunklen,
691227825Stheraven                                      expected->aad + donelen,
692227825Stheraven                                      expected->aad_len - 2))
693227825Stheraven                    goto err;
694227825Stheraven                donelen += expected->aad_len - 2;
695227825Stheraven            }
696227825Stheraven            if (expected->aad_len > 1
697227825Stheraven                    && !EVP_CipherUpdate(ctx, NULL, &chunklen,
698227825Stheraven                                         expected->aad + donelen, 1))
699227825Stheraven                goto err;
700227825Stheraven        }
701227825Stheraven    }
702227825Stheraven
703227825Stheraven    if (!enc && (expected->aead == EVP_CIPH_OCB_MODE || expected->tag_late)) {
704227825Stheraven        if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_TAG,
705227825Stheraven                                 expected->tag_len, expected->tag)) {
706227825Stheraven            t->err = "TAG_SET_ERROR";
707227825Stheraven            goto err;
708227825Stheraven        }
709227825Stheraven    }
710249998Sdim
711227825Stheraven    EVP_CIPHER_CTX_set_padding(ctx, 0);
712227825Stheraven    t->err = "CIPHERUPDATE_ERROR";
713227825Stheraven    tmplen = 0;
714227825Stheraven    if (!frag) {
715227825Stheraven        /* We supply the data all in one go */
716227825Stheraven        if (!EVP_CipherUpdate(ctx, tmp + out_misalign, &tmplen, in, in_len))
717227825Stheraven            goto err;
718    } else {
719        /* Supply the data in chunks less than the block size where possible */
720        if (in_len > 0) {
721            if (!EVP_CipherUpdate(ctx, tmp + out_misalign, &chunklen, in, 1))
722                goto err;
723            tmplen += chunklen;
724            in++;
725            in_len--;
726        }
727        if (in_len > 1) {
728            if (!EVP_CipherUpdate(ctx, tmp + out_misalign + tmplen, &chunklen,
729                                  in, in_len - 1))
730                goto err;
731            tmplen += chunklen;
732            in += in_len - 1;
733            in_len = 1;
734        }
735        if (in_len > 0 ) {
736            if (!EVP_CipherUpdate(ctx, tmp + out_misalign + tmplen, &chunklen,
737                                  in, 1))
738                goto err;
739            tmplen += chunklen;
740        }
741    }
742    if (!EVP_CipherFinal_ex(ctx, tmp + out_misalign + tmplen, &tmpflen)) {
743        t->err = "CIPHERFINAL_ERROR";
744        goto err;
745    }
746    if (!memory_err_compare(t, "VALUE_MISMATCH", expected_out, out_len,
747                            tmp + out_misalign, tmplen + tmpflen))
748        goto err;
749    if (enc && expected->aead) {
750        unsigned char rtag[16];
751
752        if (!TEST_size_t_le(expected->tag_len, sizeof(rtag))) {
753            t->err = "TAG_LENGTH_INTERNAL_ERROR";
754            goto err;
755        }
756        if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_GET_TAG,
757                                 expected->tag_len, rtag)) {
758            t->err = "TAG_RETRIEVE_ERROR";
759            goto err;
760        }
761        if (!memory_err_compare(t, "TAG_VALUE_MISMATCH",
762                                expected->tag, expected->tag_len,
763                                rtag, expected->tag_len))
764            goto err;
765    }
766    t->err = NULL;
767    ok = 1;
768 err:
769    OPENSSL_free(tmp);
770    EVP_CIPHER_CTX_free(ctx);
771    return ok;
772}
773
774static int cipher_test_run(EVP_TEST *t)
775{
776    CIPHER_DATA *cdat = t->data;
777    int rv, frag = 0;
778    size_t out_misalign, inp_misalign;
779
780    if (!cdat->key) {
781        t->err = "NO_KEY";
782        return 0;
783    }
784    if (!cdat->iv && EVP_CIPHER_iv_length(cdat->cipher)) {
785        /* IV is optional and usually omitted in wrap mode */
786        if (EVP_CIPHER_mode(cdat->cipher) != EVP_CIPH_WRAP_MODE) {
787            t->err = "NO_IV";
788            return 0;
789        }
790    }
791    if (cdat->aead && !cdat->tag) {
792        t->err = "NO_TAG";
793        return 0;
794    }
795    for (out_misalign = 0; out_misalign <= 1;) {
796        static char aux_err[64];
797        t->aux_err = aux_err;
798        for (inp_misalign = (size_t)-1; inp_misalign != 2; inp_misalign++) {
799            if (inp_misalign == (size_t)-1) {
800                /* kludge: inp_misalign == -1 means "exercise in-place" */
801                BIO_snprintf(aux_err, sizeof(aux_err),
802                             "%s in-place, %sfragmented",
803                             out_misalign ? "misaligned" : "aligned",
804                             frag ? "" : "not ");
805            } else {
806                BIO_snprintf(aux_err, sizeof(aux_err),
807                             "%s output and %s input, %sfragmented",
808                             out_misalign ? "misaligned" : "aligned",
809                             inp_misalign ? "misaligned" : "aligned",
810                             frag ? "" : "not ");
811            }
812            if (cdat->enc) {
813                rv = cipher_test_enc(t, 1, out_misalign, inp_misalign, frag);
814                /* Not fatal errors: return */
815                if (rv != 1) {
816                    if (rv < 0)
817                        return 0;
818                    return 1;
819                }
820            }
821            if (cdat->enc != 1) {
822                rv = cipher_test_enc(t, 0, out_misalign, inp_misalign, frag);
823                /* Not fatal errors: return */
824                if (rv != 1) {
825                    if (rv < 0)
826                        return 0;
827                    return 1;
828                }
829            }
830        }
831
832        if (out_misalign == 1 && frag == 0) {
833            /*
834             * XTS, CCM and Wrap modes have special requirements about input
835             * lengths so we don't fragment for those
836             */
837            if (cdat->aead == EVP_CIPH_CCM_MODE
838                    || EVP_CIPHER_mode(cdat->cipher) == EVP_CIPH_XTS_MODE
839                    || EVP_CIPHER_mode(cdat->cipher) == EVP_CIPH_WRAP_MODE)
840                break;
841            out_misalign = 0;
842            frag++;
843        } else {
844            out_misalign++;
845        }
846    }
847    t->aux_err = NULL;
848
849    return 1;
850}
851
852static const EVP_TEST_METHOD cipher_test_method = {
853    "Cipher",
854    cipher_test_init,
855    cipher_test_cleanup,
856    cipher_test_parse,
857    cipher_test_run
858};
859
860
861/**
862***  MAC TESTS
863**/
864
865typedef struct mac_data_st {
866    /* MAC type */
867    int type;
868    /* Algorithm string for this MAC */
869    char *alg;
870    /* MAC key */
871    unsigned char *key;
872    size_t key_len;
873    /* Input to MAC */
874    unsigned char *input;
875    size_t input_len;
876    /* Expected output */
877    unsigned char *output;
878    size_t output_len;
879    /* Collection of controls */
880    STACK_OF(OPENSSL_STRING) *controls;
881} MAC_DATA;
882
883static int mac_test_init(EVP_TEST *t, const char *alg)
884{
885    int type;
886    MAC_DATA *mdat;
887
888    if (strcmp(alg, "HMAC") == 0) {
889        type = EVP_PKEY_HMAC;
890    } else if (strcmp(alg, "CMAC") == 0) {
891#ifndef OPENSSL_NO_CMAC
892        type = EVP_PKEY_CMAC;
893#else
894        t->skip = 1;
895        return 1;
896#endif
897    } else if (strcmp(alg, "Poly1305") == 0) {
898#ifndef OPENSSL_NO_POLY1305
899        type = EVP_PKEY_POLY1305;
900#else
901        t->skip = 1;
902        return 1;
903#endif
904    } else if (strcmp(alg, "SipHash") == 0) {
905#ifndef OPENSSL_NO_SIPHASH
906        type = EVP_PKEY_SIPHASH;
907#else
908        t->skip = 1;
909        return 1;
910#endif
911    } else
912        return 0;
913
914    mdat = OPENSSL_zalloc(sizeof(*mdat));
915    mdat->type = type;
916    mdat->controls = sk_OPENSSL_STRING_new_null();
917    t->data = mdat;
918    return 1;
919}
920
921/* Because OPENSSL_free is a macro, it can't be passed as a function pointer */
922static void openssl_free(char *m)
923{
924    OPENSSL_free(m);
925}
926
927static void mac_test_cleanup(EVP_TEST *t)
928{
929    MAC_DATA *mdat = t->data;
930
931    sk_OPENSSL_STRING_pop_free(mdat->controls, openssl_free);
932    OPENSSL_free(mdat->alg);
933    OPENSSL_free(mdat->key);
934    OPENSSL_free(mdat->input);
935    OPENSSL_free(mdat->output);
936}
937
938static int mac_test_parse(EVP_TEST *t,
939                          const char *keyword, const char *value)
940{
941    MAC_DATA *mdata = t->data;
942
943    if (strcmp(keyword, "Key") == 0)
944        return parse_bin(value, &mdata->key, &mdata->key_len);
945    if (strcmp(keyword, "Algorithm") == 0) {
946        mdata->alg = OPENSSL_strdup(value);
947        if (!mdata->alg)
948            return -1;
949        return 1;
950    }
951    if (strcmp(keyword, "Input") == 0)
952        return parse_bin(value, &mdata->input, &mdata->input_len);
953    if (strcmp(keyword, "Output") == 0)
954        return parse_bin(value, &mdata->output, &mdata->output_len);
955    if (strcmp(keyword, "Ctrl") == 0)
956        return sk_OPENSSL_STRING_push(mdata->controls,
957                                      OPENSSL_strdup(value)) != 0;
958    return 0;
959}
960
961static int mac_test_ctrl_pkey(EVP_TEST *t, EVP_PKEY_CTX *pctx,
962                              const char *value)
963{
964    int rv;
965    char *p, *tmpval;
966
967    if (!TEST_ptr(tmpval = OPENSSL_strdup(value)))
968        return 0;
969    p = strchr(tmpval, ':');
970    if (p != NULL)
971        *p++ = '\0';
972    rv = EVP_PKEY_CTX_ctrl_str(pctx, tmpval, p);
973    if (rv == -2)
974        t->err = "PKEY_CTRL_INVALID";
975    else if (rv <= 0)
976        t->err = "PKEY_CTRL_ERROR";
977    else
978        rv = 1;
979    OPENSSL_free(tmpval);
980    return rv > 0;
981}
982
983static int mac_test_run(EVP_TEST *t)
984{
985    MAC_DATA *expected = t->data;
986    EVP_MD_CTX *mctx = NULL;
987    EVP_PKEY_CTX *pctx = NULL, *genctx = NULL;
988    EVP_PKEY *key = NULL;
989    const EVP_MD *md = NULL;
990    unsigned char *got = NULL;
991    size_t got_len;
992    int i;
993
994#ifdef OPENSSL_NO_DES
995    if (expected->alg != NULL && strstr(expected->alg, "DES") != NULL) {
996        /* Skip DES */
997        t->err = NULL;
998        goto err;
999    }
1000#endif
1001
1002    if (expected->type == EVP_PKEY_CMAC)
1003        key = EVP_PKEY_new_CMAC_key(NULL, expected->key, expected->key_len,
1004                                    EVP_get_cipherbyname(expected->alg));
1005    else
1006        key = EVP_PKEY_new_raw_private_key(expected->type, NULL, expected->key,
1007                                           expected->key_len);
1008    if (key == NULL) {
1009        t->err = "MAC_KEY_CREATE_ERROR";
1010        goto err;
1011    }
1012
1013    if (expected->type == EVP_PKEY_HMAC) {
1014        if (!TEST_ptr(md = EVP_get_digestbyname(expected->alg))) {
1015            t->err = "MAC_ALGORITHM_SET_ERROR";
1016            goto err;
1017        }
1018    }
1019    if (!TEST_ptr(mctx = EVP_MD_CTX_new())) {
1020        t->err = "INTERNAL_ERROR";
1021        goto err;
1022    }
1023    if (!EVP_DigestSignInit(mctx, &pctx, md, NULL, key)) {
1024        t->err = "DIGESTSIGNINIT_ERROR";
1025        goto err;
1026    }
1027    for (i = 0; i < sk_OPENSSL_STRING_num(expected->controls); i++)
1028        if (!mac_test_ctrl_pkey(t, pctx,
1029                                sk_OPENSSL_STRING_value(expected->controls,
1030                                                        i))) {
1031            t->err = "EVPPKEYCTXCTRL_ERROR";
1032            goto err;
1033        }
1034    if (!EVP_DigestSignUpdate(mctx, expected->input, expected->input_len)) {
1035        t->err = "DIGESTSIGNUPDATE_ERROR";
1036        goto err;
1037    }
1038    if (!EVP_DigestSignFinal(mctx, NULL, &got_len)) {
1039        t->err = "DIGESTSIGNFINAL_LENGTH_ERROR";
1040        goto err;
1041    }
1042    if (!TEST_ptr(got = OPENSSL_malloc(got_len))) {
1043        t->err = "TEST_FAILURE";
1044        goto err;
1045    }
1046    if (!EVP_DigestSignFinal(mctx, got, &got_len)
1047            || !memory_err_compare(t, "TEST_MAC_ERR",
1048                                   expected->output, expected->output_len,
1049                                   got, got_len)) {
1050        t->err = "TEST_MAC_ERR";
1051        goto err;
1052    }
1053    t->err = NULL;
1054 err:
1055    EVP_MD_CTX_free(mctx);
1056    OPENSSL_free(got);
1057    EVP_PKEY_CTX_free(genctx);
1058    EVP_PKEY_free(key);
1059    return 1;
1060}
1061
1062static const EVP_TEST_METHOD mac_test_method = {
1063    "MAC",
1064    mac_test_init,
1065    mac_test_cleanup,
1066    mac_test_parse,
1067    mac_test_run
1068};
1069
1070
1071/**
1072***  PUBLIC KEY TESTS
1073***  These are all very similar and share much common code.
1074**/
1075
1076typedef struct pkey_data_st {
1077    /* Context for this operation */
1078    EVP_PKEY_CTX *ctx;
1079    /* Key operation to perform */
1080    int (*keyop) (EVP_PKEY_CTX *ctx,
1081                  unsigned char *sig, size_t *siglen,
1082                  const unsigned char *tbs, size_t tbslen);
1083    /* Input to MAC */
1084    unsigned char *input;
1085    size_t input_len;
1086    /* Expected output */
1087    unsigned char *output;
1088    size_t output_len;
1089} PKEY_DATA;
1090
1091/*
1092 * Perform public key operation setup: lookup key, allocated ctx and call
1093 * the appropriate initialisation function
1094 */
1095static int pkey_test_init(EVP_TEST *t, const char *name,
1096                          int use_public,
1097                          int (*keyopinit) (EVP_PKEY_CTX *ctx),
1098                          int (*keyop)(EVP_PKEY_CTX *ctx,
1099                                       unsigned char *sig, size_t *siglen,
1100                                       const unsigned char *tbs,
1101                                       size_t tbslen))
1102{
1103    PKEY_DATA *kdata;
1104    EVP_PKEY *pkey = NULL;
1105    int rv = 0;
1106
1107    if (use_public)
1108        rv = find_key(&pkey, name, public_keys);
1109    if (rv == 0)
1110        rv = find_key(&pkey, name, private_keys);
1111    if (rv == 0 || pkey == NULL) {
1112        t->skip = 1;
1113        return 1;
1114    }
1115
1116    if (!TEST_ptr(kdata = OPENSSL_zalloc(sizeof(*kdata)))) {
1117        EVP_PKEY_free(pkey);
1118        return 0;
1119    }
1120    kdata->keyop = keyop;
1121    if (!TEST_ptr(kdata->ctx = EVP_PKEY_CTX_new(pkey, NULL))) {
1122        EVP_PKEY_free(pkey);
1123        OPENSSL_free(kdata);
1124        return 0;
1125    }
1126    if (keyopinit(kdata->ctx) <= 0)
1127        t->err = "KEYOP_INIT_ERROR";
1128    t->data = kdata;
1129    return 1;
1130}
1131
1132static void pkey_test_cleanup(EVP_TEST *t)
1133{
1134    PKEY_DATA *kdata = t->data;
1135
1136    OPENSSL_free(kdata->input);
1137    OPENSSL_free(kdata->output);
1138    EVP_PKEY_CTX_free(kdata->ctx);
1139}
1140
1141static int pkey_test_ctrl(EVP_TEST *t, EVP_PKEY_CTX *pctx,
1142                          const char *value)
1143{
1144    int rv;
1145    char *p, *tmpval;
1146
1147    if (!TEST_ptr(tmpval = OPENSSL_strdup(value)))
1148        return 0;
1149    p = strchr(tmpval, ':');
1150    if (p != NULL)
1151        *p++ = '\0';
1152    rv = EVP_PKEY_CTX_ctrl_str(pctx, tmpval, p);
1153    if (rv == -2) {
1154        t->err = "PKEY_CTRL_INVALID";
1155        rv = 1;
1156    } else if (p != NULL && rv <= 0) {
1157        /* If p has an OID and lookup fails assume disabled algorithm */
1158        int nid = OBJ_sn2nid(p);
1159
1160        if (nid == NID_undef)
1161             nid = OBJ_ln2nid(p);
1162        if (nid != NID_undef
1163                && EVP_get_digestbynid(nid) == NULL
1164                && EVP_get_cipherbynid(nid) == NULL) {
1165            t->skip = 1;
1166            rv = 1;
1167        } else {
1168            t->err = "PKEY_CTRL_ERROR";
1169            rv = 1;
1170        }
1171    }
1172    OPENSSL_free(tmpval);
1173    return rv > 0;
1174}
1175
1176static int pkey_test_parse(EVP_TEST *t,
1177                           const char *keyword, const char *value)
1178{
1179    PKEY_DATA *kdata = t->data;
1180    if (strcmp(keyword, "Input") == 0)
1181        return parse_bin(value, &kdata->input, &kdata->input_len);
1182    if (strcmp(keyword, "Output") == 0)
1183        return parse_bin(value, &kdata->output, &kdata->output_len);
1184    if (strcmp(keyword, "Ctrl") == 0)
1185        return pkey_test_ctrl(t, kdata->ctx, value);
1186    return 0;
1187}
1188
1189static int pkey_test_run(EVP_TEST *t)
1190{
1191    PKEY_DATA *expected = t->data;
1192    unsigned char *got = NULL;
1193    size_t got_len;
1194
1195    if (expected->keyop(expected->ctx, NULL, &got_len,
1196                        expected->input, expected->input_len) <= 0
1197            || !TEST_ptr(got = OPENSSL_malloc(got_len))) {
1198        t->err = "KEYOP_LENGTH_ERROR";
1199        goto err;
1200    }
1201    if (expected->keyop(expected->ctx, got, &got_len,
1202                        expected->input, expected->input_len) <= 0) {
1203        t->err = "KEYOP_ERROR";
1204        goto err;
1205    }
1206    if (!memory_err_compare(t, "KEYOP_MISMATCH",
1207                            expected->output, expected->output_len,
1208                            got, got_len))
1209        goto err;
1210
1211    t->err = NULL;
1212 err:
1213    OPENSSL_free(got);
1214    return 1;
1215}
1216
1217static int sign_test_init(EVP_TEST *t, const char *name)
1218{
1219    return pkey_test_init(t, name, 0, EVP_PKEY_sign_init, EVP_PKEY_sign);
1220}
1221
1222static const EVP_TEST_METHOD psign_test_method = {
1223    "Sign",
1224    sign_test_init,
1225    pkey_test_cleanup,
1226    pkey_test_parse,
1227    pkey_test_run
1228};
1229
1230static int verify_recover_test_init(EVP_TEST *t, const char *name)
1231{
1232    return pkey_test_init(t, name, 1, EVP_PKEY_verify_recover_init,
1233                          EVP_PKEY_verify_recover);
1234}
1235
1236static const EVP_TEST_METHOD pverify_recover_test_method = {
1237    "VerifyRecover",
1238    verify_recover_test_init,
1239    pkey_test_cleanup,
1240    pkey_test_parse,
1241    pkey_test_run
1242};
1243
1244static int decrypt_test_init(EVP_TEST *t, const char *name)
1245{
1246    return pkey_test_init(t, name, 0, EVP_PKEY_decrypt_init,
1247                          EVP_PKEY_decrypt);
1248}
1249
1250static const EVP_TEST_METHOD pdecrypt_test_method = {
1251    "Decrypt",
1252    decrypt_test_init,
1253    pkey_test_cleanup,
1254    pkey_test_parse,
1255    pkey_test_run
1256};
1257
1258static int verify_test_init(EVP_TEST *t, const char *name)
1259{
1260    return pkey_test_init(t, name, 1, EVP_PKEY_verify_init, 0);
1261}
1262
1263static int verify_test_run(EVP_TEST *t)
1264{
1265    PKEY_DATA *kdata = t->data;
1266
1267    if (EVP_PKEY_verify(kdata->ctx, kdata->output, kdata->output_len,
1268                        kdata->input, kdata->input_len) <= 0)
1269        t->err = "VERIFY_ERROR";
1270    return 1;
1271}
1272
1273static const EVP_TEST_METHOD pverify_test_method = {
1274    "Verify",
1275    verify_test_init,
1276    pkey_test_cleanup,
1277    pkey_test_parse,
1278    verify_test_run
1279};
1280
1281
1282static int pderive_test_init(EVP_TEST *t, const char *name)
1283{
1284    return pkey_test_init(t, name, 0, EVP_PKEY_derive_init, 0);
1285}
1286
1287static int pderive_test_parse(EVP_TEST *t,
1288                              const char *keyword, const char *value)
1289{
1290    PKEY_DATA *kdata = t->data;
1291
1292    if (strcmp(keyword, "PeerKey") == 0) {
1293        EVP_PKEY *peer;
1294        if (find_key(&peer, value, public_keys) == 0)
1295            return -1;
1296        if (EVP_PKEY_derive_set_peer(kdata->ctx, peer) <= 0)
1297            return -1;
1298        return 1;
1299    }
1300    if (strcmp(keyword, "SharedSecret") == 0)
1301        return parse_bin(value, &kdata->output, &kdata->output_len);
1302    if (strcmp(keyword, "Ctrl") == 0)
1303        return pkey_test_ctrl(t, kdata->ctx, value);
1304    return 0;
1305}
1306
1307static int pderive_test_run(EVP_TEST *t)
1308{
1309    PKEY_DATA *expected = t->data;
1310    unsigned char *got = NULL;
1311    size_t got_len;
1312
1313    if (EVP_PKEY_derive(expected->ctx, NULL, &got_len) <= 0) {
1314        t->err = "DERIVE_ERROR";
1315        goto err;
1316    }
1317    if (!TEST_ptr(got = OPENSSL_malloc(got_len))) {
1318        t->err = "DERIVE_ERROR";
1319        goto err;
1320    }
1321    if (EVP_PKEY_derive(expected->ctx, got, &got_len) <= 0) {
1322        t->err = "DERIVE_ERROR";
1323        goto err;
1324    }
1325    if (!memory_err_compare(t, "SHARED_SECRET_MISMATCH",
1326                            expected->output, expected->output_len,
1327                            got, got_len))
1328        goto err;
1329
1330    t->err = NULL;
1331 err:
1332    OPENSSL_free(got);
1333    return 1;
1334}
1335
1336static const EVP_TEST_METHOD pderive_test_method = {
1337    "Derive",
1338    pderive_test_init,
1339    pkey_test_cleanup,
1340    pderive_test_parse,
1341    pderive_test_run
1342};
1343
1344
1345/**
1346***  PBE TESTS
1347**/
1348
1349typedef enum pbe_type_enum {
1350    PBE_TYPE_INVALID = 0,
1351    PBE_TYPE_SCRYPT, PBE_TYPE_PBKDF2, PBE_TYPE_PKCS12
1352} PBE_TYPE;
1353
1354typedef struct pbe_data_st {
1355    PBE_TYPE pbe_type;
1356        /* scrypt parameters */
1357    uint64_t N, r, p, maxmem;
1358        /* PKCS#12 parameters */
1359    int id, iter;
1360    const EVP_MD *md;
1361        /* password */
1362    unsigned char *pass;
1363    size_t pass_len;
1364        /* salt */
1365    unsigned char *salt;
1366    size_t salt_len;
1367        /* Expected output */
1368    unsigned char *key;
1369    size_t key_len;
1370} PBE_DATA;
1371
1372#ifndef OPENSSL_NO_SCRYPT
1373/*
1374 * Parse unsigned decimal 64 bit integer value
1375 */
1376static int parse_uint64(const char *value, uint64_t *pr)
1377{
1378    const char *p = value;
1379
1380    if (!TEST_true(*p)) {
1381        TEST_info("Invalid empty integer value");
1382        return -1;
1383    }
1384    for (*pr = 0; *p; ) {
1385        if (*pr > UINT64_MAX / 10) {
1386            TEST_error("Integer overflow in string %s", value);
1387            return -1;
1388        }
1389        *pr *= 10;
1390        if (!TEST_true(isdigit((unsigned char)*p))) {
1391            TEST_error("Invalid character in string %s", value);
1392            return -1;
1393        }
1394        *pr += *p - '0';
1395        p++;
1396    }
1397    return 1;
1398}
1399
1400static int scrypt_test_parse(EVP_TEST *t,
1401                             const char *keyword, const char *value)
1402{
1403    PBE_DATA *pdata = t->data;
1404
1405    if (strcmp(keyword, "N") == 0)
1406        return parse_uint64(value, &pdata->N);
1407    if (strcmp(keyword, "p") == 0)
1408        return parse_uint64(value, &pdata->p);
1409    if (strcmp(keyword, "r") == 0)
1410        return parse_uint64(value, &pdata->r);
1411    if (strcmp(keyword, "maxmem") == 0)
1412        return parse_uint64(value, &pdata->maxmem);
1413    return 0;
1414}
1415#endif
1416
1417static int pbkdf2_test_parse(EVP_TEST *t,
1418                             const char *keyword, const char *value)
1419{
1420    PBE_DATA *pdata = t->data;
1421
1422    if (strcmp(keyword, "iter") == 0) {
1423        pdata->iter = atoi(value);
1424        if (pdata->iter <= 0)
1425            return -1;
1426        return 1;
1427    }
1428    if (strcmp(keyword, "MD") == 0) {
1429        pdata->md = EVP_get_digestbyname(value);
1430        if (pdata->md == NULL)
1431            return -1;
1432        return 1;
1433    }
1434    return 0;
1435}
1436
1437static int pkcs12_test_parse(EVP_TEST *t,
1438                             const char *keyword, const char *value)
1439{
1440    PBE_DATA *pdata = t->data;
1441
1442    if (strcmp(keyword, "id") == 0) {
1443        pdata->id = atoi(value);
1444        if (pdata->id <= 0)
1445            return -1;
1446        return 1;
1447    }
1448    return pbkdf2_test_parse(t, keyword, value);
1449}
1450
1451static int pbe_test_init(EVP_TEST *t, const char *alg)
1452{
1453    PBE_DATA *pdat;
1454    PBE_TYPE pbe_type = PBE_TYPE_INVALID;
1455
1456    if (strcmp(alg, "scrypt") == 0) {
1457#ifndef OPENSSL_NO_SCRYPT
1458        pbe_type = PBE_TYPE_SCRYPT;
1459#else
1460        t->skip = 1;
1461        return 1;
1462#endif
1463    } else if (strcmp(alg, "pbkdf2") == 0) {
1464        pbe_type = PBE_TYPE_PBKDF2;
1465    } else if (strcmp(alg, "pkcs12") == 0) {
1466        pbe_type = PBE_TYPE_PKCS12;
1467    } else {
1468        TEST_error("Unknown pbe algorithm %s", alg);
1469    }
1470    pdat = OPENSSL_zalloc(sizeof(*pdat));
1471    pdat->pbe_type = pbe_type;
1472    t->data = pdat;
1473    return 1;
1474}
1475
1476static void pbe_test_cleanup(EVP_TEST *t)
1477{
1478    PBE_DATA *pdat = t->data;
1479
1480    OPENSSL_free(pdat->pass);
1481    OPENSSL_free(pdat->salt);
1482    OPENSSL_free(pdat->key);
1483}
1484
1485static int pbe_test_parse(EVP_TEST *t,
1486                          const char *keyword, const char *value)
1487{
1488    PBE_DATA *pdata = t->data;
1489
1490    if (strcmp(keyword, "Password") == 0)
1491        return parse_bin(value, &pdata->pass, &pdata->pass_len);
1492    if (strcmp(keyword, "Salt") == 0)
1493        return parse_bin(value, &pdata->salt, &pdata->salt_len);
1494    if (strcmp(keyword, "Key") == 0)
1495        return parse_bin(value, &pdata->key, &pdata->key_len);
1496    if (pdata->pbe_type == PBE_TYPE_PBKDF2)
1497        return pbkdf2_test_parse(t, keyword, value);
1498    else if (pdata->pbe_type == PBE_TYPE_PKCS12)
1499        return pkcs12_test_parse(t, keyword, value);
1500#ifndef OPENSSL_NO_SCRYPT
1501    else if (pdata->pbe_type == PBE_TYPE_SCRYPT)
1502        return scrypt_test_parse(t, keyword, value);
1503#endif
1504    return 0;
1505}
1506
1507static int pbe_test_run(EVP_TEST *t)
1508{
1509    PBE_DATA *expected = t->data;
1510    unsigned char *key;
1511
1512    if (!TEST_ptr(key = OPENSSL_malloc(expected->key_len))) {
1513        t->err = "INTERNAL_ERROR";
1514        goto err;
1515    }
1516    if (expected->pbe_type == PBE_TYPE_PBKDF2) {
1517        if (PKCS5_PBKDF2_HMAC((char *)expected->pass, expected->pass_len,
1518                              expected->salt, expected->salt_len,
1519                              expected->iter, expected->md,
1520                              expected->key_len, key) == 0) {
1521            t->err = "PBKDF2_ERROR";
1522            goto err;
1523        }
1524#ifndef OPENSSL_NO_SCRYPT
1525    } else if (expected->pbe_type == PBE_TYPE_SCRYPT) {
1526        if (EVP_PBE_scrypt((const char *)expected->pass, expected->pass_len,
1527                           expected->salt, expected->salt_len, expected->N,
1528                           expected->r, expected->p, expected->maxmem,
1529                           key, expected->key_len) == 0) {
1530            t->err = "SCRYPT_ERROR";
1531            goto err;
1532        }
1533#endif
1534    } else if (expected->pbe_type == PBE_TYPE_PKCS12) {
1535        if (PKCS12_key_gen_uni(expected->pass, expected->pass_len,
1536                               expected->salt, expected->salt_len,
1537                               expected->id, expected->iter, expected->key_len,
1538                               key, expected->md) == 0) {
1539            t->err = "PKCS12_ERROR";
1540            goto err;
1541        }
1542    }
1543    if (!memory_err_compare(t, "KEY_MISMATCH", expected->key, expected->key_len,
1544                            key, expected->key_len))
1545        goto err;
1546
1547    t->err = NULL;
1548err:
1549    OPENSSL_free(key);
1550    return 1;
1551}
1552
1553static const EVP_TEST_METHOD pbe_test_method = {
1554    "PBE",
1555    pbe_test_init,
1556    pbe_test_cleanup,
1557    pbe_test_parse,
1558    pbe_test_run
1559};
1560
1561
1562/**
1563***  BASE64 TESTS
1564**/
1565
1566typedef enum {
1567    BASE64_CANONICAL_ENCODING = 0,
1568    BASE64_VALID_ENCODING = 1,
1569    BASE64_INVALID_ENCODING = 2
1570} base64_encoding_type;
1571
1572typedef struct encode_data_st {
1573    /* Input to encoding */
1574    unsigned char *input;
1575    size_t input_len;
1576    /* Expected output */
1577    unsigned char *output;
1578    size_t output_len;
1579    base64_encoding_type encoding;
1580} ENCODE_DATA;
1581
1582static int encode_test_init(EVP_TEST *t, const char *encoding)
1583{
1584    ENCODE_DATA *edata;
1585
1586    if (!TEST_ptr(edata = OPENSSL_zalloc(sizeof(*edata))))
1587        return 0;
1588    if (strcmp(encoding, "canonical") == 0) {
1589        edata->encoding = BASE64_CANONICAL_ENCODING;
1590    } else if (strcmp(encoding, "valid") == 0) {
1591        edata->encoding = BASE64_VALID_ENCODING;
1592    } else if (strcmp(encoding, "invalid") == 0) {
1593        edata->encoding = BASE64_INVALID_ENCODING;
1594        if (!TEST_ptr(t->expected_err = OPENSSL_strdup("DECODE_ERROR")))
1595            goto err;
1596    } else {
1597        TEST_error("Bad encoding: %s."
1598                   " Should be one of {canonical, valid, invalid}",
1599                   encoding);
1600        goto err;
1601    }
1602    t->data = edata;
1603    return 1;
1604err:
1605    OPENSSL_free(edata);
1606    return 0;
1607}
1608
1609static void encode_test_cleanup(EVP_TEST *t)
1610{
1611    ENCODE_DATA *edata = t->data;
1612
1613    OPENSSL_free(edata->input);
1614    OPENSSL_free(edata->output);
1615    memset(edata, 0, sizeof(*edata));
1616}
1617
1618static int encode_test_parse(EVP_TEST *t,
1619                             const char *keyword, const char *value)
1620{
1621    ENCODE_DATA *edata = t->data;
1622
1623    if (strcmp(keyword, "Input") == 0)
1624        return parse_bin(value, &edata->input, &edata->input_len);
1625    if (strcmp(keyword, "Output") == 0)
1626        return parse_bin(value, &edata->output, &edata->output_len);
1627    return 0;
1628}
1629
1630static int encode_test_run(EVP_TEST *t)
1631{
1632    ENCODE_DATA *expected = t->data;
1633    unsigned char *encode_out = NULL, *decode_out = NULL;
1634    int output_len, chunk_len;
1635    EVP_ENCODE_CTX *decode_ctx = NULL, *encode_ctx = NULL;
1636
1637    if (!TEST_ptr(decode_ctx = EVP_ENCODE_CTX_new())) {
1638        t->err = "INTERNAL_ERROR";
1639        goto err;
1640    }
1641
1642    if (expected->encoding == BASE64_CANONICAL_ENCODING) {
1643
1644        if (!TEST_ptr(encode_ctx = EVP_ENCODE_CTX_new())
1645                || !TEST_ptr(encode_out =
1646                        OPENSSL_malloc(EVP_ENCODE_LENGTH(expected->input_len))))
1647            goto err;
1648
1649        EVP_EncodeInit(encode_ctx);
1650        if (!TEST_true(EVP_EncodeUpdate(encode_ctx, encode_out, &chunk_len,
1651                                        expected->input, expected->input_len)))
1652            goto err;
1653
1654        output_len = chunk_len;
1655
1656        EVP_EncodeFinal(encode_ctx, encode_out + chunk_len, &chunk_len);
1657        output_len += chunk_len;
1658
1659        if (!memory_err_compare(t, "BAD_ENCODING",
1660                                expected->output, expected->output_len,
1661                                encode_out, output_len))
1662            goto err;
1663    }
1664
1665    if (!TEST_ptr(decode_out =
1666                OPENSSL_malloc(EVP_DECODE_LENGTH(expected->output_len))))
1667        goto err;
1668
1669    EVP_DecodeInit(decode_ctx);
1670    if (EVP_DecodeUpdate(decode_ctx, decode_out, &chunk_len, expected->output,
1671                         expected->output_len) < 0) {
1672        t->err = "DECODE_ERROR";
1673        goto err;
1674    }
1675    output_len = chunk_len;
1676
1677    if (EVP_DecodeFinal(decode_ctx, decode_out + chunk_len, &chunk_len) != 1) {
1678        t->err = "DECODE_ERROR";
1679        goto err;
1680    }
1681    output_len += chunk_len;
1682
1683    if (expected->encoding != BASE64_INVALID_ENCODING
1684            && !memory_err_compare(t, "BAD_DECODING",
1685                                   expected->input, expected->input_len,
1686                                   decode_out, output_len)) {
1687        t->err = "BAD_DECODING";
1688        goto err;
1689    }
1690
1691    t->err = NULL;
1692 err:
1693    OPENSSL_free(encode_out);
1694    OPENSSL_free(decode_out);
1695    EVP_ENCODE_CTX_free(decode_ctx);
1696    EVP_ENCODE_CTX_free(encode_ctx);
1697    return 1;
1698}
1699
1700static const EVP_TEST_METHOD encode_test_method = {
1701    "Encoding",
1702    encode_test_init,
1703    encode_test_cleanup,
1704    encode_test_parse,
1705    encode_test_run,
1706};
1707
1708/**
1709***  KDF TESTS
1710**/
1711
1712typedef struct kdf_data_st {
1713    /* Context for this operation */
1714    EVP_PKEY_CTX *ctx;
1715    /* Expected output */
1716    unsigned char *output;
1717    size_t output_len;
1718} KDF_DATA;
1719
1720/*
1721 * Perform public key operation setup: lookup key, allocated ctx and call
1722 * the appropriate initialisation function
1723 */
1724static int kdf_test_init(EVP_TEST *t, const char *name)
1725{
1726    KDF_DATA *kdata;
1727    int kdf_nid = OBJ_sn2nid(name);
1728
1729#ifdef OPENSSL_NO_SCRYPT
1730    if (strcmp(name, "scrypt") == 0) {
1731        t->skip = 1;
1732        return 1;
1733    }
1734#endif
1735
1736    if (kdf_nid == NID_undef)
1737        kdf_nid = OBJ_ln2nid(name);
1738
1739    if (!TEST_ptr(kdata = OPENSSL_zalloc(sizeof(*kdata))))
1740        return 0;
1741    kdata->ctx = EVP_PKEY_CTX_new_id(kdf_nid, NULL);
1742    if (kdata->ctx == NULL) {
1743        OPENSSL_free(kdata);
1744        return 0;
1745    }
1746    if (EVP_PKEY_derive_init(kdata->ctx) <= 0) {
1747        EVP_PKEY_CTX_free(kdata->ctx);
1748        OPENSSL_free(kdata);
1749        return 0;
1750    }
1751    t->data = kdata;
1752    return 1;
1753}
1754
1755static void kdf_test_cleanup(EVP_TEST *t)
1756{
1757    KDF_DATA *kdata = t->data;
1758    OPENSSL_free(kdata->output);
1759    EVP_PKEY_CTX_free(kdata->ctx);
1760}
1761
1762static int kdf_test_parse(EVP_TEST *t,
1763                          const char *keyword, const char *value)
1764{
1765    KDF_DATA *kdata = t->data;
1766
1767    if (strcmp(keyword, "Output") == 0)
1768        return parse_bin(value, &kdata->output, &kdata->output_len);
1769    if (strncmp(keyword, "Ctrl", 4) == 0)
1770        return pkey_test_ctrl(t, kdata->ctx, value);
1771    return 0;
1772}
1773
1774static int kdf_test_run(EVP_TEST *t)
1775{
1776    KDF_DATA *expected = t->data;
1777    unsigned char *got = NULL;
1778    size_t got_len = expected->output_len;
1779
1780    if (!TEST_ptr(got = OPENSSL_malloc(got_len == 0 ? 1 : got_len))) {
1781        t->err = "INTERNAL_ERROR";
1782        goto err;
1783    }
1784    if (EVP_PKEY_derive(expected->ctx, got, &got_len) <= 0) {
1785        t->err = "KDF_DERIVE_ERROR";
1786        goto err;
1787    }
1788    if (!memory_err_compare(t, "KDF_MISMATCH",
1789                            expected->output, expected->output_len,
1790                            got, got_len))
1791        goto err;
1792
1793    t->err = NULL;
1794
1795 err:
1796    OPENSSL_free(got);
1797    return 1;
1798}
1799
1800static const EVP_TEST_METHOD kdf_test_method = {
1801    "KDF",
1802    kdf_test_init,
1803    kdf_test_cleanup,
1804    kdf_test_parse,
1805    kdf_test_run
1806};
1807
1808
1809/**
1810***  KEYPAIR TESTS
1811**/
1812
1813typedef struct keypair_test_data_st {
1814    EVP_PKEY *privk;
1815    EVP_PKEY *pubk;
1816} KEYPAIR_TEST_DATA;
1817
1818static int keypair_test_init(EVP_TEST *t, const char *pair)
1819{
1820    KEYPAIR_TEST_DATA *data;
1821    int rv = 0;
1822    EVP_PKEY *pk = NULL, *pubk = NULL;
1823    char *pub, *priv = NULL;
1824
1825    /* Split private and public names. */
1826    if (!TEST_ptr(priv = OPENSSL_strdup(pair))
1827            || !TEST_ptr(pub = strchr(priv, ':'))) {
1828        t->err = "PARSING_ERROR";
1829        goto end;
1830    }
1831    *pub++ = '\0';
1832
1833    if (!TEST_true(find_key(&pk, priv, private_keys))) {
1834        TEST_info("Can't find private key: %s", priv);
1835        t->err = "MISSING_PRIVATE_KEY";
1836        goto end;
1837    }
1838    if (!TEST_true(find_key(&pubk, pub, public_keys))) {
1839        TEST_info("Can't find public key: %s", pub);
1840        t->err = "MISSING_PUBLIC_KEY";
1841        goto end;
1842    }
1843
1844    if (pk == NULL && pubk == NULL) {
1845        /* Both keys are listed but unsupported: skip this test */
1846        t->skip = 1;
1847        rv = 1;
1848        goto end;
1849    }
1850
1851    if (!TEST_ptr(data = OPENSSL_malloc(sizeof(*data))))
1852        goto end;
1853    data->privk = pk;
1854    data->pubk = pubk;
1855    t->data = data;
1856    rv = 1;
1857    t->err = NULL;
1858
1859end:
1860    OPENSSL_free(priv);
1861    return rv;
1862}
1863
1864static void keypair_test_cleanup(EVP_TEST *t)
1865{
1866    OPENSSL_free(t->data);
1867    t->data = NULL;
1868}
1869
1870/*
1871 * For tests that do not accept any custom keywords.
1872 */
1873static int void_test_parse(EVP_TEST *t, const char *keyword, const char *value)
1874{
1875    return 0;
1876}
1877
1878static int keypair_test_run(EVP_TEST *t)
1879{
1880    int rv = 0;
1881    const KEYPAIR_TEST_DATA *pair = t->data;
1882
1883    if (pair->privk == NULL || pair->pubk == NULL) {
1884        /*
1885         * this can only happen if only one of the keys is not set
1886         * which means that one of them was unsupported while the
1887         * other isn't: hence a key type mismatch.
1888         */
1889        t->err = "KEYPAIR_TYPE_MISMATCH";
1890        rv = 1;
1891        goto end;
1892    }
1893
1894    if ((rv = EVP_PKEY_cmp(pair->privk, pair->pubk)) != 1 ) {
1895        if ( 0 == rv ) {
1896            t->err = "KEYPAIR_MISMATCH";
1897        } else if ( -1 == rv ) {
1898            t->err = "KEYPAIR_TYPE_MISMATCH";
1899        } else if ( -2 == rv ) {
1900            t->err = "UNSUPPORTED_KEY_COMPARISON";
1901        } else {
1902            TEST_error("Unexpected error in key comparison");
1903            rv = 0;
1904            goto end;
1905        }
1906        rv = 1;
1907        goto end;
1908    }
1909
1910    rv = 1;
1911    t->err = NULL;
1912
1913end:
1914    return rv;
1915}
1916
1917static const EVP_TEST_METHOD keypair_test_method = {
1918    "PrivPubKeyPair",
1919    keypair_test_init,
1920    keypair_test_cleanup,
1921    void_test_parse,
1922    keypair_test_run
1923};
1924
1925/**
1926***  KEYGEN TEST
1927**/
1928
1929typedef struct keygen_test_data_st {
1930    EVP_PKEY_CTX *genctx; /* Keygen context to use */
1931    char *keyname; /* Key name to store key or NULL */
1932} KEYGEN_TEST_DATA;
1933
1934static int keygen_test_init(EVP_TEST *t, const char *alg)
1935{
1936    KEYGEN_TEST_DATA *data;
1937    EVP_PKEY_CTX *genctx;
1938    int nid = OBJ_sn2nid(alg);
1939
1940    if (nid == NID_undef) {
1941        nid = OBJ_ln2nid(alg);
1942        if (nid == NID_undef)
1943            return 0;
1944    }
1945
1946    if (!TEST_ptr(genctx = EVP_PKEY_CTX_new_id(nid, NULL))) {
1947        /* assume algorithm disabled */
1948        t->skip = 1;
1949        return 1;
1950    }
1951
1952    if (EVP_PKEY_keygen_init(genctx) <= 0) {
1953        t->err = "KEYGEN_INIT_ERROR";
1954        goto err;
1955    }
1956
1957    if (!TEST_ptr(data = OPENSSL_malloc(sizeof(*data))))
1958        goto err;
1959    data->genctx = genctx;
1960    data->keyname = NULL;
1961    t->data = data;
1962    t->err = NULL;
1963    return 1;
1964
1965err:
1966    EVP_PKEY_CTX_free(genctx);
1967    return 0;
1968}
1969
1970static void keygen_test_cleanup(EVP_TEST *t)
1971{
1972    KEYGEN_TEST_DATA *keygen = t->data;
1973
1974    EVP_PKEY_CTX_free(keygen->genctx);
1975    OPENSSL_free(keygen->keyname);
1976    OPENSSL_free(t->data);
1977    t->data = NULL;
1978}
1979
1980static int keygen_test_parse(EVP_TEST *t,
1981                             const char *keyword, const char *value)
1982{
1983    KEYGEN_TEST_DATA *keygen = t->data;
1984
1985    if (strcmp(keyword, "KeyName") == 0)
1986        return TEST_ptr(keygen->keyname = OPENSSL_strdup(value));
1987    if (strcmp(keyword, "Ctrl") == 0)
1988        return pkey_test_ctrl(t, keygen->genctx, value);
1989    return 0;
1990}
1991
1992static int keygen_test_run(EVP_TEST *t)
1993{
1994    KEYGEN_TEST_DATA *keygen = t->data;
1995    EVP_PKEY *pkey = NULL;
1996
1997    t->err = NULL;
1998    if (EVP_PKEY_keygen(keygen->genctx, &pkey) <= 0) {
1999        t->err = "KEYGEN_GENERATE_ERROR";
2000        goto err;
2001    }
2002
2003    if (keygen->keyname != NULL) {
2004        KEY_LIST *key;
2005
2006        if (find_key(NULL, keygen->keyname, private_keys)) {
2007            TEST_info("Duplicate key %s", keygen->keyname);
2008            goto err;
2009        }
2010
2011        if (!TEST_ptr(key = OPENSSL_malloc(sizeof(*key))))
2012            goto err;
2013        key->name = keygen->keyname;
2014        keygen->keyname = NULL;
2015        key->key = pkey;
2016        key->next = private_keys;
2017        private_keys = key;
2018    } else {
2019        EVP_PKEY_free(pkey);
2020    }
2021
2022    return 1;
2023
2024err:
2025    EVP_PKEY_free(pkey);
2026    return 0;
2027}
2028
2029static const EVP_TEST_METHOD keygen_test_method = {
2030    "KeyGen",
2031    keygen_test_init,
2032    keygen_test_cleanup,
2033    keygen_test_parse,
2034    keygen_test_run,
2035};
2036
2037/**
2038***  DIGEST SIGN+VERIFY TESTS
2039**/
2040
2041typedef struct {
2042    int is_verify; /* Set to 1 if verifying */
2043    int is_oneshot; /* Set to 1 for one shot operation */
2044    const EVP_MD *md; /* Digest to use */
2045    EVP_MD_CTX *ctx; /* Digest context */
2046    EVP_PKEY_CTX *pctx;
2047    STACK_OF(EVP_TEST_BUFFER) *input; /* Input data: streaming */
2048    unsigned char *osin; /* Input data if one shot */
2049    size_t osin_len; /* Input length data if one shot */
2050    unsigned char *output; /* Expected output */
2051    size_t output_len; /* Expected output length */
2052} DIGESTSIGN_DATA;
2053
2054static int digestsigver_test_init(EVP_TEST *t, const char *alg, int is_verify,
2055                                  int is_oneshot)
2056{
2057    const EVP_MD *md = NULL;
2058    DIGESTSIGN_DATA *mdat;
2059
2060    if (strcmp(alg, "NULL") != 0) {
2061        if ((md = EVP_get_digestbyname(alg)) == NULL) {
2062            /* If alg has an OID assume disabled algorithm */
2063            if (OBJ_sn2nid(alg) != NID_undef || OBJ_ln2nid(alg) != NID_undef) {
2064                t->skip = 1;
2065                return 1;
2066            }
2067            return 0;
2068        }
2069    }
2070    if (!TEST_ptr(mdat = OPENSSL_zalloc(sizeof(*mdat))))
2071        return 0;
2072    mdat->md = md;
2073    if (!TEST_ptr(mdat->ctx = EVP_MD_CTX_new())) {
2074        OPENSSL_free(mdat);
2075        return 0;
2076    }
2077    mdat->is_verify = is_verify;
2078    mdat->is_oneshot = is_oneshot;
2079    t->data = mdat;
2080    return 1;
2081}
2082
2083static int digestsign_test_init(EVP_TEST *t, const char *alg)
2084{
2085    return digestsigver_test_init(t, alg, 0, 0);
2086}
2087
2088static void digestsigver_test_cleanup(EVP_TEST *t)
2089{
2090    DIGESTSIGN_DATA *mdata = t->data;
2091
2092    EVP_MD_CTX_free(mdata->ctx);
2093    sk_EVP_TEST_BUFFER_pop_free(mdata->input, evp_test_buffer_free);
2094    OPENSSL_free(mdata->osin);
2095    OPENSSL_free(mdata->output);
2096    OPENSSL_free(mdata);
2097    t->data = NULL;
2098}
2099
2100static int digestsigver_test_parse(EVP_TEST *t,
2101                                   const char *keyword, const char *value)
2102{
2103    DIGESTSIGN_DATA *mdata = t->data;
2104
2105    if (strcmp(keyword, "Key") == 0) {
2106        EVP_PKEY *pkey = NULL;
2107        int rv = 0;
2108
2109        if (mdata->is_verify)
2110            rv = find_key(&pkey, value, public_keys);
2111        if (rv == 0)
2112            rv = find_key(&pkey, value, private_keys);
2113        if (rv == 0 || pkey == NULL) {
2114            t->skip = 1;
2115            return 1;
2116        }
2117        if (mdata->is_verify) {
2118            if (!EVP_DigestVerifyInit(mdata->ctx, &mdata->pctx, mdata->md,
2119                                      NULL, pkey))
2120                t->err = "DIGESTVERIFYINIT_ERROR";
2121            return 1;
2122        }
2123        if (!EVP_DigestSignInit(mdata->ctx, &mdata->pctx, mdata->md, NULL,
2124                                pkey))
2125            t->err = "DIGESTSIGNINIT_ERROR";
2126        return 1;
2127    }
2128
2129    if (strcmp(keyword, "Input") == 0) {
2130        if (mdata->is_oneshot)
2131            return parse_bin(value, &mdata->osin, &mdata->osin_len);
2132        return evp_test_buffer_append(value, &mdata->input);
2133    }
2134    if (strcmp(keyword, "Output") == 0)
2135        return parse_bin(value, &mdata->output, &mdata->output_len);
2136
2137    if (!mdata->is_oneshot) {
2138        if (strcmp(keyword, "Count") == 0)
2139            return evp_test_buffer_set_count(value, mdata->input);
2140        if (strcmp(keyword, "Ncopy") == 0)
2141            return evp_test_buffer_ncopy(value, mdata->input);
2142    }
2143    if (strcmp(keyword, "Ctrl") == 0) {
2144        if (mdata->pctx == NULL)
2145            return -1;
2146        return pkey_test_ctrl(t, mdata->pctx, value);
2147    }
2148    return 0;
2149}
2150
2151static int digestsign_update_fn(void *ctx, const unsigned char *buf,
2152                                size_t buflen)
2153{
2154    return EVP_DigestSignUpdate(ctx, buf, buflen);
2155}
2156
2157static int digestsign_test_run(EVP_TEST *t)
2158{
2159    DIGESTSIGN_DATA *expected = t->data;
2160    unsigned char *got = NULL;
2161    size_t got_len;
2162
2163    if (!evp_test_buffer_do(expected->input, digestsign_update_fn,
2164                            expected->ctx)) {
2165        t->err = "DIGESTUPDATE_ERROR";
2166        goto err;
2167    }
2168
2169    if (!EVP_DigestSignFinal(expected->ctx, NULL, &got_len)) {
2170        t->err = "DIGESTSIGNFINAL_LENGTH_ERROR";
2171        goto err;
2172    }
2173    if (!TEST_ptr(got = OPENSSL_malloc(got_len))) {
2174        t->err = "MALLOC_FAILURE";
2175        goto err;
2176    }
2177    if (!EVP_DigestSignFinal(expected->ctx, got, &got_len)) {
2178        t->err = "DIGESTSIGNFINAL_ERROR";
2179        goto err;
2180    }
2181    if (!memory_err_compare(t, "SIGNATURE_MISMATCH",
2182                            expected->output, expected->output_len,
2183                            got, got_len))
2184        goto err;
2185
2186    t->err = NULL;
2187 err:
2188    OPENSSL_free(got);
2189    return 1;
2190}
2191
2192static const EVP_TEST_METHOD digestsign_test_method = {
2193    "DigestSign",
2194    digestsign_test_init,
2195    digestsigver_test_cleanup,
2196    digestsigver_test_parse,
2197    digestsign_test_run
2198};
2199
2200static int digestverify_test_init(EVP_TEST *t, const char *alg)
2201{
2202    return digestsigver_test_init(t, alg, 1, 0);
2203}
2204
2205static int digestverify_update_fn(void *ctx, const unsigned char *buf,
2206                                  size_t buflen)
2207{
2208    return EVP_DigestVerifyUpdate(ctx, buf, buflen);
2209}
2210
2211static int digestverify_test_run(EVP_TEST *t)
2212{
2213    DIGESTSIGN_DATA *mdata = t->data;
2214
2215    if (!evp_test_buffer_do(mdata->input, digestverify_update_fn, mdata->ctx)) {
2216        t->err = "DIGESTUPDATE_ERROR";
2217        return 1;
2218    }
2219
2220    if (EVP_DigestVerifyFinal(mdata->ctx, mdata->output,
2221                              mdata->output_len) <= 0)
2222        t->err = "VERIFY_ERROR";
2223    return 1;
2224}
2225
2226static const EVP_TEST_METHOD digestverify_test_method = {
2227    "DigestVerify",
2228    digestverify_test_init,
2229    digestsigver_test_cleanup,
2230    digestsigver_test_parse,
2231    digestverify_test_run
2232};
2233
2234static int oneshot_digestsign_test_init(EVP_TEST *t, const char *alg)
2235{
2236    return digestsigver_test_init(t, alg, 0, 1);
2237}
2238
2239static int oneshot_digestsign_test_run(EVP_TEST *t)
2240{
2241    DIGESTSIGN_DATA *expected = t->data;
2242    unsigned char *got = NULL;
2243    size_t got_len;
2244
2245    if (!EVP_DigestSign(expected->ctx, NULL, &got_len,
2246                        expected->osin, expected->osin_len)) {
2247        t->err = "DIGESTSIGN_LENGTH_ERROR";
2248        goto err;
2249    }
2250    if (!TEST_ptr(got = OPENSSL_malloc(got_len))) {
2251        t->err = "MALLOC_FAILURE";
2252        goto err;
2253    }
2254    if (!EVP_DigestSign(expected->ctx, got, &got_len,
2255                        expected->osin, expected->osin_len)) {
2256        t->err = "DIGESTSIGN_ERROR";
2257        goto err;
2258    }
2259    if (!memory_err_compare(t, "SIGNATURE_MISMATCH",
2260                            expected->output, expected->output_len,
2261                            got, got_len))
2262        goto err;
2263
2264    t->err = NULL;
2265 err:
2266    OPENSSL_free(got);
2267    return 1;
2268}
2269
2270static const EVP_TEST_METHOD oneshot_digestsign_test_method = {
2271    "OneShotDigestSign",
2272    oneshot_digestsign_test_init,
2273    digestsigver_test_cleanup,
2274    digestsigver_test_parse,
2275    oneshot_digestsign_test_run
2276};
2277
2278static int oneshot_digestverify_test_init(EVP_TEST *t, const char *alg)
2279{
2280    return digestsigver_test_init(t, alg, 1, 1);
2281}
2282
2283static int oneshot_digestverify_test_run(EVP_TEST *t)
2284{
2285    DIGESTSIGN_DATA *mdata = t->data;
2286
2287    if (EVP_DigestVerify(mdata->ctx, mdata->output, mdata->output_len,
2288                         mdata->osin, mdata->osin_len) <= 0)
2289        t->err = "VERIFY_ERROR";
2290    return 1;
2291}
2292
2293static const EVP_TEST_METHOD oneshot_digestverify_test_method = {
2294    "OneShotDigestVerify",
2295    oneshot_digestverify_test_init,
2296    digestsigver_test_cleanup,
2297    digestsigver_test_parse,
2298    oneshot_digestverify_test_run
2299};
2300
2301
2302/**
2303***  PARSING AND DISPATCH
2304**/
2305
2306static const EVP_TEST_METHOD *evp_test_list[] = {
2307    &cipher_test_method,
2308    &digest_test_method,
2309    &digestsign_test_method,
2310    &digestverify_test_method,
2311    &encode_test_method,
2312    &kdf_test_method,
2313    &keypair_test_method,
2314    &keygen_test_method,
2315    &mac_test_method,
2316    &oneshot_digestsign_test_method,
2317    &oneshot_digestverify_test_method,
2318    &pbe_test_method,
2319    &pdecrypt_test_method,
2320    &pderive_test_method,
2321    &psign_test_method,
2322    &pverify_recover_test_method,
2323    &pverify_test_method,
2324    NULL
2325};
2326
2327static const EVP_TEST_METHOD *find_test(const char *name)
2328{
2329    const EVP_TEST_METHOD **tt;
2330
2331    for (tt = evp_test_list; *tt; tt++) {
2332        if (strcmp(name, (*tt)->name) == 0)
2333            return *tt;
2334    }
2335    return NULL;
2336}
2337
2338static void clear_test(EVP_TEST *t)
2339{
2340    test_clearstanza(&t->s);
2341    ERR_clear_error();
2342    if (t->data != NULL) {
2343        if (t->meth != NULL)
2344            t->meth->cleanup(t);
2345        OPENSSL_free(t->data);
2346        t->data = NULL;
2347    }
2348    OPENSSL_free(t->expected_err);
2349    t->expected_err = NULL;
2350    OPENSSL_free(t->func);
2351    t->func = NULL;
2352    OPENSSL_free(t->reason);
2353    t->reason = NULL;
2354
2355    /* Text literal. */
2356    t->err = NULL;
2357    t->skip = 0;
2358    t->meth = NULL;
2359}
2360
2361/*
2362 * Check for errors in the test structure; return 1 if okay, else 0.
2363 */
2364static int check_test_error(EVP_TEST *t)
2365{
2366    unsigned long err;
2367    const char *func;
2368    const char *reason;
2369
2370    if (t->err == NULL && t->expected_err == NULL)
2371        return 1;
2372    if (t->err != NULL && t->expected_err == NULL) {
2373        if (t->aux_err != NULL) {
2374            TEST_info("%s:%d: Source of above error (%s); unexpected error %s",
2375                      t->s.test_file, t->s.start, t->aux_err, t->err);
2376        } else {
2377            TEST_info("%s:%d: Source of above error; unexpected error %s",
2378                      t->s.test_file, t->s.start, t->err);
2379        }
2380        return 0;
2381    }
2382    if (t->err == NULL && t->expected_err != NULL) {
2383        TEST_info("%s:%d: Succeeded but was expecting %s",
2384                  t->s.test_file, t->s.start, t->expected_err);
2385        return 0;
2386    }
2387
2388    if (strcmp(t->err, t->expected_err) != 0) {
2389        TEST_info("%s:%d: Expected %s got %s",
2390                  t->s.test_file, t->s.start, t->expected_err, t->err);
2391        return 0;
2392    }
2393
2394    if (t->func == NULL && t->reason == NULL)
2395        return 1;
2396
2397    if (t->func == NULL || t->reason == NULL) {
2398        TEST_info("%s:%d: Test is missing function or reason code",
2399                  t->s.test_file, t->s.start);
2400        return 0;
2401    }
2402
2403    err = ERR_peek_error();
2404    if (err == 0) {
2405        TEST_info("%s:%d: Expected error \"%s:%s\" not set",
2406                  t->s.test_file, t->s.start, t->func, t->reason);
2407        return 0;
2408    }
2409
2410    func = ERR_func_error_string(err);
2411    reason = ERR_reason_error_string(err);
2412    if (func == NULL && reason == NULL) {
2413        TEST_info("%s:%d: Expected error \"%s:%s\", no strings available."
2414                  " Assuming ok.",
2415                  t->s.test_file, t->s.start, t->func, t->reason);
2416        return 1;
2417    }
2418
2419    if (strcmp(func, t->func) == 0 && strcmp(reason, t->reason) == 0)
2420        return 1;
2421
2422    TEST_info("%s:%d: Expected error \"%s:%s\", got \"%s:%s\"",
2423              t->s.test_file, t->s.start, t->func, t->reason, func, reason);
2424
2425    return 0;
2426}
2427
2428/*
2429 * Run a parsed test. Log a message and return 0 on error.
2430 */
2431static int run_test(EVP_TEST *t)
2432{
2433    if (t->meth == NULL)
2434        return 1;
2435    t->s.numtests++;
2436    if (t->skip) {
2437        t->s.numskip++;
2438    } else {
2439        /* run the test */
2440        if (t->err == NULL && t->meth->run_test(t) != 1) {
2441            TEST_info("%s:%d %s error",
2442                      t->s.test_file, t->s.start, t->meth->name);
2443            return 0;
2444        }
2445        if (!check_test_error(t)) {
2446            TEST_openssl_errors();
2447            t->s.errors++;
2448        }
2449    }
2450
2451    /* clean it up */
2452    return 1;
2453}
2454
2455static int find_key(EVP_PKEY **ppk, const char *name, KEY_LIST *lst)
2456{
2457    for (; lst != NULL; lst = lst->next) {
2458        if (strcmp(lst->name, name) == 0) {
2459            if (ppk != NULL)
2460                *ppk = lst->key;
2461            return 1;
2462        }
2463    }
2464    return 0;
2465}
2466
2467static void free_key_list(KEY_LIST *lst)
2468{
2469    while (lst != NULL) {
2470        KEY_LIST *next = lst->next;
2471
2472        EVP_PKEY_free(lst->key);
2473        OPENSSL_free(lst->name);
2474        OPENSSL_free(lst);
2475        lst = next;
2476    }
2477}
2478
2479/*
2480 * Is the key type an unsupported algorithm?
2481 */
2482static int key_unsupported(void)
2483{
2484    long err = ERR_peek_error();
2485
2486    if (ERR_GET_LIB(err) == ERR_LIB_EVP
2487            && ERR_GET_REASON(err) == EVP_R_UNSUPPORTED_ALGORITHM) {
2488        ERR_clear_error();
2489        return 1;
2490    }
2491#ifndef OPENSSL_NO_EC
2492    /*
2493     * If EC support is enabled we should catch also EC_R_UNKNOWN_GROUP as an
2494     * hint to an unsupported algorithm/curve (e.g. if binary EC support is
2495     * disabled).
2496     */
2497    if (ERR_GET_LIB(err) == ERR_LIB_EC
2498        && ERR_GET_REASON(err) == EC_R_UNKNOWN_GROUP) {
2499        ERR_clear_error();
2500        return 1;
2501    }
2502#endif /* OPENSSL_NO_EC */
2503    return 0;
2504}
2505
2506/*
2507 * NULL out the value from |pp| but return it.  This "steals" a pointer.
2508 */
2509static char *take_value(PAIR *pp)
2510{
2511    char *p = pp->value;
2512
2513    pp->value = NULL;
2514    return p;
2515}
2516
2517/*
2518 * Read and parse one test.  Return 0 if failure, 1 if okay.
2519 */
2520static int parse(EVP_TEST *t)
2521{
2522    KEY_LIST *key, **klist;
2523    EVP_PKEY *pkey;
2524    PAIR *pp;
2525    int i;
2526
2527top:
2528    do {
2529        if (BIO_eof(t->s.fp))
2530            return EOF;
2531        clear_test(t);
2532        if (!test_readstanza(&t->s))
2533            return 0;
2534    } while (t->s.numpairs == 0);
2535    pp = &t->s.pairs[0];
2536
2537    /* Are we adding a key? */
2538    klist = NULL;
2539    pkey = NULL;
2540    if (strcmp(pp->key, "PrivateKey") == 0) {
2541        pkey = PEM_read_bio_PrivateKey(t->s.key, NULL, 0, NULL);
2542        if (pkey == NULL && !key_unsupported()) {
2543            EVP_PKEY_free(pkey);
2544            TEST_info("Can't read private key %s", pp->value);
2545            TEST_openssl_errors();
2546            return 0;
2547        }
2548        klist = &private_keys;
2549    } else if (strcmp(pp->key, "PublicKey") == 0) {
2550        pkey = PEM_read_bio_PUBKEY(t->s.key, NULL, 0, NULL);
2551        if (pkey == NULL && !key_unsupported()) {
2552            EVP_PKEY_free(pkey);
2553            TEST_info("Can't read public key %s", pp->value);
2554            TEST_openssl_errors();
2555            return 0;
2556        }
2557        klist = &public_keys;
2558    } else if (strcmp(pp->key, "PrivateKeyRaw") == 0
2559               || strcmp(pp->key, "PublicKeyRaw") == 0 ) {
2560        char *strnid = NULL, *keydata = NULL;
2561        unsigned char *keybin;
2562        size_t keylen;
2563        int nid;
2564
2565        if (strcmp(pp->key, "PrivateKeyRaw") == 0)
2566            klist = &private_keys;
2567        else
2568            klist = &public_keys;
2569
2570        strnid = strchr(pp->value, ':');
2571        if (strnid != NULL) {
2572            *strnid++ = '\0';
2573            keydata = strchr(strnid, ':');
2574            if (keydata != NULL)
2575                *keydata++ = '\0';
2576        }
2577        if (keydata == NULL) {
2578            TEST_info("Failed to parse %s value", pp->key);
2579            return 0;
2580        }
2581
2582        nid = OBJ_txt2nid(strnid);
2583        if (nid == NID_undef) {
2584            TEST_info("Uncrecognised algorithm NID");
2585            return 0;
2586        }
2587        if (!parse_bin(keydata, &keybin, &keylen)) {
2588            TEST_info("Failed to create binary key");
2589            return 0;
2590        }
2591        if (klist == &private_keys)
2592            pkey = EVP_PKEY_new_raw_private_key(nid, NULL, keybin, keylen);
2593        else
2594            pkey = EVP_PKEY_new_raw_public_key(nid, NULL, keybin, keylen);
2595        if (pkey == NULL && !key_unsupported()) {
2596            TEST_info("Can't read %s data", pp->key);
2597            OPENSSL_free(keybin);
2598            TEST_openssl_errors();
2599            return 0;
2600        }
2601        OPENSSL_free(keybin);
2602    }
2603
2604    /* If we have a key add to list */
2605    if (klist != NULL) {
2606        if (find_key(NULL, pp->value, *klist)) {
2607            TEST_info("Duplicate key %s", pp->value);
2608            return 0;
2609        }
2610        if (!TEST_ptr(key = OPENSSL_malloc(sizeof(*key))))
2611            return 0;
2612        key->name = take_value(pp);
2613
2614        /* Hack to detect SM2 keys */
2615        if(pkey != NULL && strstr(key->name, "SM2") != NULL) {
2616#ifdef OPENSSL_NO_SM2
2617            EVP_PKEY_free(pkey);
2618            pkey = NULL;
2619#else
2620            EVP_PKEY_set_alias_type(pkey, EVP_PKEY_SM2);
2621#endif
2622        }
2623
2624        key->key = pkey;
2625        key->next = *klist;
2626        *klist = key;
2627
2628        /* Go back and start a new stanza. */
2629        if (t->s.numpairs != 1)
2630            TEST_info("Line %d: missing blank line\n", t->s.curr);
2631        goto top;
2632    }
2633
2634    /* Find the test, based on first keyword. */
2635    if (!TEST_ptr(t->meth = find_test(pp->key)))
2636        return 0;
2637    if (!t->meth->init(t, pp->value)) {
2638        TEST_error("unknown %s: %s\n", pp->key, pp->value);
2639        return 0;
2640    }
2641    if (t->skip == 1) {
2642        /* TEST_info("skipping %s %s", pp->key, pp->value); */
2643        return 0;
2644    }
2645
2646    for (pp++, i = 1; i < t->s.numpairs; pp++, i++) {
2647        if (strcmp(pp->key, "Result") == 0) {
2648            if (t->expected_err != NULL) {
2649                TEST_info("Line %d: multiple result lines", t->s.curr);
2650                return 0;
2651            }
2652            t->expected_err = take_value(pp);
2653        } else if (strcmp(pp->key, "Function") == 0) {
2654            if (t->func != NULL) {
2655                TEST_info("Line %d: multiple function lines\n", t->s.curr);
2656                return 0;
2657            }
2658            t->func = take_value(pp);
2659        } else if (strcmp(pp->key, "Reason") == 0) {
2660            if (t->reason != NULL) {
2661                TEST_info("Line %d: multiple reason lines", t->s.curr);
2662                return 0;
2663            }
2664            t->reason = take_value(pp);
2665        } else {
2666            /* Must be test specific line: try to parse it */
2667            int rv = t->meth->parse(t, pp->key, pp->value);
2668
2669            if (rv == 0) {
2670                TEST_info("Line %d: unknown keyword %s", t->s.curr, pp->key);
2671                return 0;
2672            }
2673            if (rv < 0) {
2674                TEST_info("Line %d: error processing keyword %s = %s\n",
2675                          t->s.curr, pp->key, pp->value);
2676                return 0;
2677            }
2678        }
2679    }
2680
2681    return 1;
2682}
2683
2684static int run_file_tests(int i)
2685{
2686    EVP_TEST *t;
2687    const char *testfile = test_get_argument(i);
2688    int c;
2689
2690    if (!TEST_ptr(t = OPENSSL_zalloc(sizeof(*t))))
2691        return 0;
2692    if (!test_start_file(&t->s, testfile)) {
2693        OPENSSL_free(t);
2694        return 0;
2695    }
2696
2697    while (!BIO_eof(t->s.fp)) {
2698        c = parse(t);
2699        if (t->skip)
2700            continue;
2701        if (c == 0 || !run_test(t)) {
2702            t->s.errors++;
2703            break;
2704        }
2705    }
2706    test_end_file(&t->s);
2707    clear_test(t);
2708
2709    free_key_list(public_keys);
2710    free_key_list(private_keys);
2711    BIO_free(t->s.key);
2712    c = t->s.errors;
2713    OPENSSL_free(t);
2714    return c == 0;
2715}
2716
2717int setup_tests(void)
2718{
2719    size_t n = test_get_argument_count();
2720
2721    if (n == 0) {
2722        TEST_error("Usage: %s file...", test_get_program_name());
2723        return 0;
2724    }
2725
2726    ADD_ALL_TESTS(run_file_tests, n);
2727    return 1;
2728}
2729