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