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