5c4a785c00bff6f9313702abbb90ac47b21674cd
[openssl.git] / test / danetest.c
1 /* ====================================================================
2  * Copyright (c) 2015 The OpenSSL Project.  All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  *
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  *
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in
13  *    the documentation and/or other materials provided with the
14  *    distribution.
15  *
16  * 3. All advertising materials mentioning features or use of this
17  *    software must display the following acknowledgment:
18  *    "This product includes software developed by the OpenSSL Project
19  *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
20  *
21  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
22  *    endorse or promote products derived from this software without
23  *    prior written permission. For written permission, please contact
24  *    openssl-core@openssl.org.
25  *
26  * 5. Products derived from this software may not be called "OpenSSL"
27  *    nor may "OpenSSL" appear in their names without prior written
28  *    permission of the OpenSSL Project.
29  *
30  * 6. Redistributions of any form whatsoever must retain the following
31  *    acknowledgment:
32  *    "This product includes software developed by the OpenSSL Project
33  *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
34  *
35  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
36  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
37  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
38  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
39  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
40  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
41  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
42  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
43  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
44  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
45  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
46  * OF THE POSSIBILITY OF SUCH DAMAGE.
47  * ====================================================================
48  */
49
50 #include <stdio.h>
51 #include <string.h>
52 #include <ctype.h>
53 #include <limits.h>
54 #include <errno.h>
55
56 #include <openssl/crypto.h>
57 #include <openssl/evp.h>
58 #include <openssl/x509.h>
59 #include <openssl/ssl.h>
60 #include <openssl/err.h>
61 #include <openssl/conf.h>
62 #ifndef OPENSSL_NO_ENGINE
63 #include <openssl/engine.h>
64 #endif
65
66 #include "../e_os.h"
67
68 static const char *progname;
69
70 /*
71  * Forward declaration, of function that uses internal interfaces, from headers
72  * included at the end of this module.
73  */
74 static void store_ctx_dane_init(X509_STORE_CTX *, SSL *);
75
76 static int saved_errno;
77
78 static void save_errno(void)
79 {
80     saved_errno = errno;
81 }
82
83 static int restore_errno(void)
84 {
85     int ret = errno;
86     errno = saved_errno;
87     return ret;
88 }
89
90 static void test_usage(void)
91 {
92     fprintf(stderr, "usage: %s: danetest basedomain CAfile tlsafile\n", progname);
93 }
94
95 static void print_errors(void)
96 {
97     unsigned long err;
98     char buffer[1024];
99     const char *file;
100     const char *data;
101     int line;
102     int flags;
103
104     while ((err = ERR_get_error_line_data(&file, &line, &data, &flags)) != 0) {
105         ERR_error_string_n(err, buffer, sizeof(buffer));
106         if (flags & ERR_TXT_STRING)
107             fprintf(stderr, "Error: %s:%s:%d:%s\n", buffer, file, line, data);
108         else
109             fprintf(stderr, "Error: %s:%s:%d\n", buffer, file, line);
110     }
111 }
112
113 static int verify_chain(SSL *ssl, STACK_OF(X509) *chain)
114 {
115     int ret;
116     X509_STORE_CTX *store_ctx;
117     SSL_CTX *ssl_ctx = SSL_get_SSL_CTX(ssl);
118     X509_STORE *store = SSL_CTX_get_cert_store(ssl_ctx);
119     int store_ctx_idx = SSL_get_ex_data_X509_STORE_CTX_idx();
120     X509 *cert = sk_X509_value(chain, 0);
121
122     if ((store_ctx = X509_STORE_CTX_new()) == NULL)
123         return -1;
124
125     if (!X509_STORE_CTX_init(store_ctx, store, cert, chain))
126         return 0;
127     X509_STORE_CTX_set_ex_data(store_ctx, store_ctx_idx, ssl);
128
129     X509_STORE_CTX_set_default(store_ctx,
130             SSL_is_server(ssl) ? "ssl_client" : "ssl_server");
131     X509_VERIFY_PARAM_set1(X509_STORE_CTX_get0_param(store_ctx),
132             SSL_get0_param(ssl));
133     store_ctx_dane_init(store_ctx, ssl);
134
135     if (SSL_get_verify_callback(ssl))
136         X509_STORE_CTX_set_verify_cb(store_ctx, SSL_get_verify_callback(ssl));
137
138     ret = X509_verify_cert(store_ctx);
139
140     SSL_set_verify_result(ssl, X509_STORE_CTX_get_error(store_ctx));
141     X509_STORE_CTX_cleanup(store_ctx);
142     X509_STORE_CTX_free(store_ctx);
143
144     return (ret);
145 }
146
147 static STACK_OF(X509) *load_chain(FILE *fp, int nelem)
148 {
149     int count;
150     char *name = 0;
151     char *header = 0;
152     unsigned char *data = 0;
153     long len;
154     char *errtype = 0;          /* if error: cert or pkey? */
155     STACK_OF(X509) *chain;
156     typedef X509 *(*d2i_X509_t)(X509 **, const unsigned char **, long);
157
158     if ((chain = sk_X509_new_null()) == 0) {
159         perror("malloc");
160         exit(1);
161     }
162
163     for (count = 0;
164          count < nelem && errtype == 0
165          && PEM_read(fp, &name, &header, &data, &len);
166          ++count) {
167         const unsigned char *p = data;
168
169         if (strcmp(name, PEM_STRING_X509) == 0
170             || strcmp(name, PEM_STRING_X509_TRUSTED) == 0
171             || strcmp(name, PEM_STRING_X509_OLD) == 0) {
172             d2i_X509_t d = strcmp(name, PEM_STRING_X509_TRUSTED) ?
173                 d2i_X509_AUX : d2i_X509;
174             X509 *cert = d(0, &p, len);
175
176             if (cert == 0 || (p - data) != len)
177                 errtype = "certificate";
178             else if (sk_X509_push(chain, cert) == 0) {
179                 perror("malloc");
180                 goto err;
181             }
182         } else {
183             fprintf(stderr, "unexpected chain file object: %s\n", name);
184             goto err;
185         }
186
187         /*
188          * If any of these were null, PEM_read() would have failed.
189          */
190         OPENSSL_free(name);
191         OPENSSL_free(header);
192         OPENSSL_free(data);
193     }
194
195     if (errtype) {
196         fprintf(stderr, "error reading: malformed %s\n", errtype);
197         goto err;
198     }
199     
200     if (count == nelem) {
201         ERR_clear_error();
202         return chain;
203     }
204
205 err:
206     /* Some other PEM read error */
207     sk_X509_pop_free(chain, X509_free);
208     print_errors();
209     return NULL;
210 }
211
212 static char *read_to_eol(FILE *f)
213 {
214     static char buf[1024];
215     int n;
216
217     if (fgets(buf, sizeof(buf), f)== NULL)
218         return NULL;
219
220     n = strlen(buf);
221
222     if (buf[n-1] != '\n') {
223         if (n+1 == sizeof(buf)) {
224             fprintf(stderr, "%s: warning: input too long\n", progname);
225         } else {
226             fprintf(stderr, "%s: warning: EOF before newline\n", progname);
227         }
228         return NULL;
229     }
230
231     /* Trim trailing whitespace */
232     while (n > 0 && isspace(buf[n-1]))
233         buf[--n] = '\0';
234
235     return buf;
236 }
237
238 /*
239  * Hex decoder that tolerates optional whitespace
240  */
241 static ossl_ssize_t hexdecode(const char *in, void *result)
242 {
243     unsigned char **out = (unsigned char **)result;
244     unsigned char *ret = OPENSSL_malloc(strlen(in)/2);
245     unsigned char *cp = ret;
246     uint8_t byte;
247     int nibble = 0;
248
249     if (ret == NULL)
250         return -1;
251
252     for (byte = 0; *in; ++in) {
253         char c;
254
255         if (isspace(*in))
256             continue;
257         c = tolower(*in);
258         if ('0' <= c && c <= '9') {
259             byte |= c - '0';
260         } else if ('a' <= c && c <= 'f') {
261             byte |= c - 'a' + 10;
262         } else {
263             OPENSSL_free(ret);
264             return 0;
265         }
266         if ((nibble ^= 1) == 0) {
267             *cp++ = byte;
268             byte = 0;
269         } else {
270             byte <<= 4;
271         }
272     }
273     if (nibble != 0) {
274         OPENSSL_free(ret);
275         return 0;
276     }
277
278     return cp - (*out = ret);
279 }
280
281 static ossl_ssize_t checked_uint8(const char *in, void *out)
282 {
283     uint8_t *result = (uint8_t *)out;
284     const char *cp = in;
285     char *endp;
286     long v;
287     int e;
288
289     save_errno();
290     v = strtol(cp, &endp, 10);
291     e = restore_errno();
292
293     if (((v == LONG_MIN || v == LONG_MAX) && e == ERANGE) ||
294         endp == cp || !isspace(*endp) ||
295         v != (*(uint8_t *)result = (uint8_t) v)) {
296         return -1;
297     }
298     for (cp = endp; isspace(*cp); ++cp)
299         continue;
300     return cp - in;
301 }
302
303 struct tlsa_field {
304     void *var;
305     const char *name;
306     ossl_ssize_t (*parser)(const char *, void *);
307 };
308
309 static int tlsa_import_rr(SSL *ssl, const char *rrdata)
310 {
311     static uint8_t usage;
312     static uint8_t selector;
313     static uint8_t mtype;
314     static unsigned char *data = NULL;
315     static struct tlsa_field tlsa_fields[] = {
316         { &usage, "usage", checked_uint8 },
317         { &selector, "selector", checked_uint8 },
318         { &mtype, "mtype", checked_uint8 },
319         { &data, "data", hexdecode },
320         { NULL, }
321     };
322     int ret;
323     struct tlsa_field *f;
324     const char *cp = rrdata;
325     ossl_ssize_t len = 0;
326
327     for (f = tlsa_fields; f->var; ++f) {
328         if ((len = f->parser(cp += len, f->var)) <= 0) {
329             fprintf(stderr, "%s: warning: bad TLSA %s field in: %s\n",
330                     progname, f->name, rrdata);
331             return 0;
332         }
333     }
334     ret = SSL_dane_tlsa_add(ssl, usage, selector, mtype, data, len);
335     OPENSSL_free(data);
336
337     if (ret == 0) {
338         print_errors();
339         fprintf(stderr, "%s: warning: unusable TLSA rrdata: %s\n",
340                 progname, rrdata);
341         return 0;
342     }
343     if (ret < 0) {
344         fprintf(stderr, "%s: warning: error loading TLSA rrdata: %s\n",
345                 progname, rrdata);
346         return 0;
347     }
348     return ret;
349 }
350
351 static int allws(const char *cp)
352 {
353     while (*cp)
354         if (!isspace(*cp++))
355             return 0;
356     return 1;
357 }
358
359 static int test_tlsafile(SSL_CTX *ctx, const char *basename,
360                          FILE *f, const char *path)
361 {
362     char *line;
363     int testno = 0;
364     int ret = 1;
365     SSL *ssl;
366
367     while (ret > 0 && (line = read_to_eol(f)) != NULL) {
368         STACK_OF(X509) *chain;
369         int ntlsa;
370         int ncert;
371         int want;
372         int want_depth;
373         int off;
374         int i;
375         int ok;
376         int err;
377         int mdpth;
378
379         if (*line == '\0' || *line == '#')
380             continue;
381
382         ++testno;
383         if (sscanf(line, "%d %d %d %d%n", &ntlsa, &ncert, &want, &want_depth, &off) != 4
384             || !allws(line + off)) {
385             fprintf(stderr, "Expected tlsa count, cert count and result"
386                     " at test %d of %s\n", testno, path);
387             return 0;
388         }
389
390         if ((ssl = SSL_new(ctx)) == NULL)
391             return -1;
392         SSL_set_connect_state(ssl);
393         if (SSL_dane_enable(ssl, basename) <= 0) {
394             SSL_free(ssl);
395             return -1;
396         }
397
398         for (i = 0; i < ntlsa; ++i) {
399             if ((line = read_to_eol(f)) == NULL || !tlsa_import_rr(ssl, line)) {
400                 SSL_free(ssl);
401                 return 0;
402             }
403         }
404
405         /* Don't report old news */
406         ERR_clear_error();
407         chain = load_chain(f, ncert);
408         if (chain == NULL) {
409             SSL_free(ssl);
410             return -1;
411         }
412
413         ok = verify_chain(ssl, chain);
414         sk_X509_pop_free(chain, X509_free);
415         err = SSL_get_verify_result(ssl);
416         mdpth = SSL_get0_dane_authority(ssl, NULL, NULL);
417         SSL_free(ssl);
418
419         if (ok < 0) {
420             ret = 0;
421             fprintf(stderr, "verify_chain internal error in %s test %d\n",
422                     path, testno);
423             print_errors();
424             continue;
425         }
426         if (err != want || (want == 0 && !ok)) {
427             ret = 0;
428             if (err != want) {
429                 if (want == X509_V_OK)
430                     fprintf(stderr, "Verification failure in %s test %d: %d: %s\n",
431                             path, testno, err, X509_verify_cert_error_string(err));
432                 else
433                     fprintf(stderr, "Unexpected error in %s test %d: %d: wanted %d\n",
434                             path, testno, err, want);
435             } else {
436                 fprintf(stderr, "Verification failure in %s test %d: ok=0\n",
437                         path, testno);
438             }
439             print_errors();
440             continue;
441         }
442         if (mdpth != want_depth) {
443             ret = 0;
444             fprintf(stderr, "Wrong match depth, in %s test %d: wanted %d, got: %d\n",
445                     path, testno, want_depth, mdpth);
446         }
447         fprintf(stderr, "%s: test %d successful\n", path, testno);
448     }
449     ERR_clear_error();
450
451     return ret;
452 }
453
454 int main(int argc, char *argv[])
455 {
456     FILE *f;
457     BIO *bio_err;
458     SSL_CTX *ctx = NULL;
459     const char *basedomain;
460     const char *CAfile;
461     const char *tlsafile;
462     const char *p;
463     int ret = 1;
464
465     progname = argv[0];
466     if (argc != 4) {
467         test_usage();
468         EXIT(1);
469     }
470     basedomain = argv[1];
471     CAfile = argv[2];
472     tlsafile = argv[3];
473
474     p = getenv("OPENSSL_DEBUG_MEMORY");
475     if (p != NULL && strcmp(p, "on") == 0)
476         CRYPTO_set_mem_debug(1);
477
478     f = fopen(tlsafile, "r");
479     if (f == NULL) {
480         fprintf(stderr, "%s: Error opening tlsa record file: '%s': %s\n",
481                 progname, tlsafile, strerror(errno));
482         return 0;
483     }
484
485     bio_err = BIO_new_fp(stderr, BIO_NOCLOSE | BIO_FP_TEXT);
486
487     SSL_library_init();
488     SSL_load_error_strings();
489
490     ctx = SSL_CTX_new(TLS_client_method());
491     if (SSL_CTX_dane_enable(ctx) <= 0) {
492         print_errors();
493         goto end;
494     }
495     if (!SSL_CTX_load_verify_locations(ctx, CAfile, NULL)) {
496         print_errors();
497         goto end;
498     }
499     if ((SSL_CTX_dane_mtype_set(ctx, EVP_sha512(), 2, 1)) <= 0) {
500         print_errors();
501         goto end;
502     }
503     if ((SSL_CTX_dane_mtype_set(ctx, EVP_sha256(), 1, 2)) <= 0) {
504         print_errors();
505         goto end;
506     }
507
508     if (test_tlsafile(ctx, basedomain, f, tlsafile) <= 0) {
509         print_errors();
510         goto end;
511     }
512
513     ret = 0;
514
515 end:
516
517     (void) fclose(f);
518     SSL_CTX_free(ctx);
519
520 #ifndef OPENSSL_NO_ENGINE
521     ENGINE_cleanup();
522 #endif
523     CONF_modules_unload(1);
524     CRYPTO_cleanup_all_ex_data();
525     ERR_free_strings();
526     ERR_remove_thread_state(NULL);
527     EVP_cleanup();
528 #ifndef OPENSSL_NO_CRYPTO_MDEBUG
529     if (CRYPTO_mem_leaks(bio_err) <= 0)
530         ret = 1;
531 #endif
532     BIO_free(bio_err);
533     EXIT(ret);
534 }
535
536 #include <internal/dane.h>
537
538 static void store_ctx_dane_init(X509_STORE_CTX *store_ctx, SSL *ssl)
539 {
540     X509_STORE_CTX_set0_dane(store_ctx, SSL_get0_dane(ssl));
541 }