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