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