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