1/*
2 * Copyright 2015-2021 The OpenSSL Project Authors. All Rights Reserved.
3 *
4 * Licensed under the OpenSSL license (the "License").  You may not use
5 * this file except in compliance with the License.  You can obtain a copy
6 * in the file LICENSE in the source distribution or at
7 * https://www.openssl.org/source/license.html
8 */
9
10#include <stdio.h>
11#include <string.h>
12#include <ctype.h>
13#include <limits.h>
14#include <errno.h>
15
16#include <openssl/crypto.h>
17#include <openssl/evp.h>
18#include <openssl/x509.h>
19#include <openssl/ssl.h>
20#include <openssl/err.h>
21#include <openssl/conf.h>
22#ifndef OPENSSL_NO_ENGINE
23#include <openssl/engine.h>
24#endif
25#include "testutil.h"
26
27#include "internal/nelem.h"
28
29#define _UC(c) ((unsigned char)(c))
30
31static const char *basedomain;
32static const char *CAfile;
33static const char *tlsafile;
34
35/*
36 * Forward declaration, of function that uses internal interfaces, from headers
37 * included at the end of this module.
38 */
39static void store_ctx_dane_init(X509_STORE_CTX *, SSL *);
40
41static int saved_errno;
42
43static void save_errno(void)
44{
45    saved_errno = errno;
46}
47
48static int restore_errno(void)
49{
50    int ret = errno;
51    errno = saved_errno;
52    return ret;
53}
54
55static int verify_chain(SSL *ssl, STACK_OF(X509) *chain)
56{
57    X509_STORE_CTX *store_ctx = NULL;
58    SSL_CTX *ssl_ctx = NULL;
59    X509_STORE *store = NULL;
60    X509 *cert = NULL;
61    int ret = 0;
62    int store_ctx_idx = SSL_get_ex_data_X509_STORE_CTX_idx();
63
64    if (!TEST_ptr(store_ctx = X509_STORE_CTX_new())
65            || !TEST_ptr(ssl_ctx = SSL_get_SSL_CTX(ssl))
66            || !TEST_ptr(store = SSL_CTX_get_cert_store(ssl_ctx))
67            || !TEST_ptr(cert = sk_X509_value(chain, 0))
68            || !TEST_true(X509_STORE_CTX_init(store_ctx, store, cert, chain))
69            || !TEST_true(X509_STORE_CTX_set_ex_data(store_ctx, store_ctx_idx,
70                                                     ssl)))
71        goto end;
72
73    X509_STORE_CTX_set_default(store_ctx,
74            SSL_is_server(ssl) ? "ssl_client" : "ssl_server");
75    X509_VERIFY_PARAM_set1(X509_STORE_CTX_get0_param(store_ctx),
76            SSL_get0_param(ssl));
77    store_ctx_dane_init(store_ctx, ssl);
78
79    if (SSL_get_verify_callback(ssl) != NULL)
80        X509_STORE_CTX_set_verify_cb(store_ctx, SSL_get_verify_callback(ssl));
81
82    /* Mask "internal failures" (-1) from our return value. */
83    if (!TEST_int_ge(ret = X509_verify_cert(store_ctx), 0))
84        ret = 0;
85
86    SSL_set_verify_result(ssl, X509_STORE_CTX_get_error(store_ctx));
87    X509_STORE_CTX_cleanup(store_ctx);
88
89end:
90    X509_STORE_CTX_free(store_ctx);
91    return ret;
92}
93
94static STACK_OF(X509) *load_chain(BIO *fp, int nelem)
95{
96    int count;
97    char *name = 0;
98    char *header = 0;
99    unsigned char *data = 0;
100    long len;
101    char *errtype = 0;                /* if error: cert or pkey? */
102    STACK_OF(X509) *chain;
103    typedef X509 *(*d2i_X509_t)(X509 **, const unsigned char **, long);
104
105    if (!TEST_ptr(chain = sk_X509_new_null()))
106        goto err;
107
108    for (count = 0;
109         count < nelem && errtype == 0
110         && PEM_read_bio(fp, &name, &header, &data, &len) == 1;
111         ++count) {
112        if (strcmp(name, PEM_STRING_X509) == 0
113                    || strcmp(name, PEM_STRING_X509_TRUSTED) == 0
114                    || strcmp(name, PEM_STRING_X509_OLD) == 0) {
115            d2i_X509_t d = strcmp(name, PEM_STRING_X509_TRUSTED) != 0
116                ? d2i_X509_AUX : d2i_X509;
117            X509 *cert;
118            const unsigned char *p = data;
119
120            if (!TEST_ptr(cert = d(0, &p, len))
121                    || !TEST_long_eq(p - data, len)) {
122                TEST_info("Certificate parsing error");
123                goto err;
124            }
125
126            if (!TEST_true(sk_X509_push(chain, cert)))
127                goto err;
128        } else {
129            TEST_info("Unknown chain file object %s", name);
130            goto err;
131        }
132
133        OPENSSL_free(name);
134        OPENSSL_free(header);
135        OPENSSL_free(data);
136        name = header = NULL;
137        data = NULL;
138    }
139
140    if (count == nelem) {
141        ERR_clear_error();
142        return chain;
143    }
144
145err:
146    OPENSSL_free(name);
147    OPENSSL_free(header);
148    OPENSSL_free(data);
149    sk_X509_pop_free(chain, X509_free);
150    return NULL;
151}
152
153static char *read_to_eol(BIO *f)
154{
155    static char buf[4096];
156    int n;
157
158    if (!BIO_gets(f, buf, sizeof(buf)))
159        return NULL;
160
161    n = strlen(buf);
162    if (buf[n - 1] != '\n') {
163        if (n + 1 == sizeof(buf))
164            TEST_error("input too long");
165        else
166            TEST_error("EOF before newline");
167        return NULL;
168    }
169
170    /* Trim trailing whitespace */
171    while (n > 0 && isspace(_UC(buf[n - 1])))
172        buf[--n] = '\0';
173
174    return buf;
175}
176
177/*
178 * Hex decoder that tolerates optional whitespace
179 */
180static ossl_ssize_t hexdecode(const char *in, void *result)
181{
182    unsigned char **out = (unsigned char **)result;
183    unsigned char *ret;
184    unsigned char *cp;
185    uint8_t byte;
186    int nibble = 0;
187
188    if (!TEST_ptr(ret = OPENSSL_malloc(strlen(in) / 2)))
189        return -1;
190    cp = ret;
191
192    for (byte = 0; *in; ++in) {
193        int x;
194
195        if (isspace(_UC(*in)))
196            continue;
197        x = OPENSSL_hexchar2int(*in);
198        if (x < 0) {
199            OPENSSL_free(ret);
200            return 0;
201        }
202        byte |= (char)x;
203        if ((nibble ^= 1) == 0) {
204            *cp++ = byte;
205            byte = 0;
206        } else {
207            byte <<= 4;
208        }
209    }
210    if (nibble != 0) {
211        OPENSSL_free(ret);
212        return 0;
213    }
214
215    return cp - (*out = ret);
216}
217
218static ossl_ssize_t checked_uint8(const char *in, void *out)
219{
220    uint8_t *result = (uint8_t *)out;
221    const char *cp = in;
222    char *endp;
223    long v;
224    int e;
225
226    save_errno();
227    v = strtol(cp, &endp, 10);
228    e = restore_errno();
229
230    if (((v == LONG_MIN || v == LONG_MAX) && e == ERANGE) ||
231        endp == cp || !isspace(_UC(*endp)) ||
232        v != (*(uint8_t *)result = (uint8_t) v)) {
233        return -1;
234    }
235    for (cp = endp; isspace(_UC(*cp)); ++cp)
236        continue;
237    return cp - in;
238}
239
240struct tlsa_field {
241    void *var;
242    const char *name;
243    ossl_ssize_t (*parser)(const char *, void *);
244};
245
246static int tlsa_import_rr(SSL *ssl, const char *rrdata)
247{
248    static uint8_t usage;
249    static uint8_t selector;
250    static uint8_t mtype;
251    static unsigned char *data = NULL;
252    static struct tlsa_field tlsa_fields[] = {
253        { &usage, "usage", checked_uint8 },
254        { &selector, "selector", checked_uint8 },
255        { &mtype, "mtype", checked_uint8 },
256        { &data, "data", hexdecode },
257        { NULL, }
258    };
259    int ret;
260    struct tlsa_field *f;
261    const char *cp = rrdata;
262    ossl_ssize_t len = 0;
263
264    for (f = tlsa_fields; f->var; ++f) {
265        if ((len = f->parser(cp += len, f->var)) <= 0) {
266            TEST_info("bad TLSA %s field in: %s", f->name, rrdata);
267            return 0;
268        }
269    }
270
271    ret = SSL_dane_tlsa_add(ssl, usage, selector, mtype, data, len);
272    OPENSSL_free(data);
273    if (ret == 0) {
274        TEST_info("unusable TLSA rrdata: %s", rrdata);
275        return 0;
276    }
277    if (ret < 0) {
278        TEST_info("error loading TLSA rrdata: %s", rrdata);
279        return 0;
280    }
281
282    return ret;
283}
284
285static int allws(const char *cp)
286{
287    while (*cp)
288        if (!isspace(_UC(*cp++)))
289            return 0;
290    return 1;
291}
292
293static int test_tlsafile(SSL_CTX *ctx, const char *base_name,
294                         BIO *f, const char *path)
295{
296    char *line;
297    int testno = 0;
298    int ret = 1;
299    SSL *ssl;
300
301    while (ret > 0 && (line = read_to_eol(f)) != NULL) {
302        STACK_OF(X509) *chain;
303        int ntlsa;
304        int ncert;
305        int noncheck;
306        int want;
307        int want_depth;
308        int off;
309        int i;
310        int ok;
311        int err;
312        int mdpth;
313
314        if (*line == '\0' || *line == '#')
315            continue;
316
317        ++testno;
318        if (sscanf(line, "%d %d %d %d %d%n",
319                   &ntlsa, &ncert, &noncheck, &want, &want_depth, &off) != 5
320            || !allws(line + off)) {
321            TEST_error("Malformed line for test %d", testno);
322            return 0;
323        }
324
325        if (!TEST_ptr(ssl = SSL_new(ctx)))
326            return 0;
327        SSL_set_connect_state(ssl);
328        if (SSL_dane_enable(ssl, base_name) <= 0) {
329            SSL_free(ssl);
330            return 0;
331        }
332        if (noncheck)
333            SSL_dane_set_flags(ssl, DANE_FLAG_NO_DANE_EE_NAMECHECKS);
334
335        for (i = 0; i < ntlsa; ++i) {
336            if ((line = read_to_eol(f)) == NULL || !tlsa_import_rr(ssl, line)) {
337                SSL_free(ssl);
338                return 0;
339            }
340        }
341
342        /* Don't report old news */
343        ERR_clear_error();
344        if (!TEST_ptr(chain = load_chain(f, ncert))) {
345            SSL_free(ssl);
346            return 0;
347        }
348
349        ok = verify_chain(ssl, chain);
350        sk_X509_pop_free(chain, X509_free);
351        err = SSL_get_verify_result(ssl);
352        /*
353         * Peek under the hood, normally TLSA match data is hidden when
354         * verification fails, we can obtain any suppressed data by setting the
355         * verification result to X509_V_OK before looking.
356         */
357        SSL_set_verify_result(ssl, X509_V_OK);
358        mdpth = SSL_get0_dane_authority(ssl, NULL, NULL);
359        /* Not needed any more, but lead by example and put the error back. */
360        SSL_set_verify_result(ssl, err);
361        SSL_free(ssl);
362
363        if (!TEST_int_eq(err, want)) {
364            if (want == X509_V_OK)
365                TEST_info("Verification failure in test %d: %d=%s",
366                          testno, err, X509_verify_cert_error_string(err));
367            else
368                TEST_info("Unexpected error in test %d", testno);
369            ret = 0;
370            continue;
371        }
372        if (!TEST_false(want == 0 && ok == 0)) {
373            TEST_info("Verification failure in test %d: ok=0", testno);
374            ret = 0;
375            continue;
376        }
377        if (!TEST_int_eq(mdpth, want_depth)) {
378            TEST_info("In test test %d", testno);
379            ret = 0;
380        }
381    }
382    ERR_clear_error();
383
384    return ret;
385}
386
387static int run_tlsatest(void)
388{
389    SSL_CTX *ctx = NULL;
390    BIO *f = NULL;
391    int ret = 0;
392
393    if (!TEST_ptr(f = BIO_new_file(tlsafile, "r"))
394            || !TEST_ptr(ctx = SSL_CTX_new(TLS_client_method()))
395            || !TEST_int_gt(SSL_CTX_dane_enable(ctx), 0)
396            || !TEST_true(SSL_CTX_load_verify_locations(ctx, CAfile, NULL))
397            || !TEST_int_gt(SSL_CTX_dane_mtype_set(ctx, EVP_sha512(), 2, 1),
398                            0)
399            || !TEST_int_gt(SSL_CTX_dane_mtype_set(ctx, EVP_sha256(), 1, 2),
400                            0)
401            || !TEST_int_gt(test_tlsafile(ctx, basedomain, f, tlsafile), 0))
402        goto end;
403    ret = 1;
404
405end:
406    BIO_free(f);
407    SSL_CTX_free(ctx);
408
409    return ret;
410}
411
412int setup_tests(void)
413{
414    if (!TEST_ptr(basedomain = test_get_argument(0))
415            || !TEST_ptr(CAfile = test_get_argument(1))
416            || !TEST_ptr(tlsafile = test_get_argument(2))) {
417        TEST_error("Usage error: danetest basedomain CAfile tlsafile");
418        return 0;
419    }
420
421    ADD_TEST(run_tlsatest);
422    return 1;
423}
424
425#include "internal/dane.h"
426
427static void store_ctx_dane_init(X509_STORE_CTX *store_ctx, SSL *ssl)
428{
429    X509_STORE_CTX_set0_dane(store_ctx, SSL_get0_dane(ssl));
430}
431