test/[dane|evp_]test.c: BIO-fy file I/O.
[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         char c;
256
257         if (isspace(_UC(*in)))
258             continue;
259         c = tolower(_UC(*in));
260         if ('0' <= c && c <= '9') {
261             byte |= c - '0';
262         } else if ('a' <= c && c <= 'f') {
263             byte |= c - 'a' + 10;
264         } else {
265             OPENSSL_free(ret);
266             return 0;
267         }
268         if ((nibble ^= 1) == 0) {
269             *cp++ = byte;
270             byte = 0;
271         } else {
272             byte <<= 4;
273         }
274     }
275     if (nibble != 0) {
276         OPENSSL_free(ret);
277         return 0;
278     }
279
280     return cp - (*out = ret);
281 }
282
283 static ossl_ssize_t checked_uint8(const char *in, void *out)
284 {
285     uint8_t *result = (uint8_t *)out;
286     const char *cp = in;
287     char *endp;
288     long v;
289     int e;
290
291     save_errno();
292     v = strtol(cp, &endp, 10);
293     e = restore_errno();
294
295     if (((v == LONG_MIN || v == LONG_MAX) && e == ERANGE) ||
296         endp == cp || !isspace(_UC(*endp)) ||
297         v != (*(uint8_t *)result = (uint8_t) v)) {
298         return -1;
299     }
300     for (cp = endp; isspace(_UC(*cp)); ++cp)
301         continue;
302     return cp - in;
303 }
304
305 struct tlsa_field {
306     void *var;
307     const char *name;
308     ossl_ssize_t (*parser)(const char *, void *);
309 };
310
311 static int tlsa_import_rr(SSL *ssl, const char *rrdata)
312 {
313     static uint8_t usage;
314     static uint8_t selector;
315     static uint8_t mtype;
316     static unsigned char *data = NULL;
317     static struct tlsa_field tlsa_fields[] = {
318         { &usage, "usage", checked_uint8 },
319         { &selector, "selector", checked_uint8 },
320         { &mtype, "mtype", checked_uint8 },
321         { &data, "data", hexdecode },
322         { NULL, }
323     };
324     int ret;
325     struct tlsa_field *f;
326     const char *cp = rrdata;
327     ossl_ssize_t len = 0;
328
329     for (f = tlsa_fields; f->var; ++f) {
330         if ((len = f->parser(cp += len, f->var)) <= 0) {
331             fprintf(stderr, "%s: warning: bad TLSA %s field in: %s\n",
332                     progname, f->name, rrdata);
333             return 0;
334         }
335     }
336     ret = SSL_dane_tlsa_add(ssl, usage, selector, mtype, data, len);
337     OPENSSL_free(data);
338
339     if (ret == 0) {
340         print_errors();
341         fprintf(stderr, "%s: warning: unusable TLSA rrdata: %s\n",
342                 progname, rrdata);
343         return 0;
344     }
345     if (ret < 0) {
346         fprintf(stderr, "%s: warning: error loading TLSA rrdata: %s\n",
347                 progname, rrdata);
348         return 0;
349     }
350     return ret;
351 }
352
353 static int allws(const char *cp)
354 {
355     while (*cp)
356         if (!isspace(_UC(*cp++)))
357             return 0;
358     return 1;
359 }
360
361 static int test_tlsafile(SSL_CTX *ctx, const char *basename,
362                          BIO *f, const char *path)
363 {
364     char *line;
365     int testno = 0;
366     int ret = 1;
367     SSL *ssl;
368
369     while (ret > 0 && (line = read_to_eol(f)) != NULL) {
370         STACK_OF(X509) *chain;
371         int ntlsa;
372         int ncert;
373         int want;
374         int want_depth;
375         int off;
376         int i;
377         int ok;
378         int err;
379         int mdpth;
380
381         if (*line == '\0' || *line == '#')
382             continue;
383
384         ++testno;
385         if (sscanf(line, "%d %d %d %d%n", &ntlsa, &ncert, &want, &want_depth, &off) != 4
386             || !allws(line + off)) {
387             fprintf(stderr, "Expected tlsa count, cert count and result"
388                     " at test %d of %s\n", testno, path);
389             return 0;
390         }
391
392         if ((ssl = SSL_new(ctx)) == NULL)
393             return -1;
394         SSL_set_connect_state(ssl);
395         if (SSL_dane_enable(ssl, basename) <= 0) {
396             SSL_free(ssl);
397             return -1;
398         }
399
400         for (i = 0; i < ntlsa; ++i) {
401             if ((line = read_to_eol(f)) == NULL || !tlsa_import_rr(ssl, line)) {
402                 SSL_free(ssl);
403                 return 0;
404             }
405         }
406
407         /* Don't report old news */
408         ERR_clear_error();
409         chain = load_chain(f, ncert);
410         if (chain == NULL) {
411             SSL_free(ssl);
412             return -1;
413         }
414
415         ok = verify_chain(ssl, chain);
416         sk_X509_pop_free(chain, X509_free);
417         err = SSL_get_verify_result(ssl);
418         /*
419          * Peek under the hood, normally TLSA match data is hidden when
420          * verification fails, we can obtain any suppressed data by setting the
421          * verification result to X509_V_OK before looking.
422          */
423         SSL_set_verify_result(ssl, X509_V_OK);
424         mdpth = SSL_get0_dane_authority(ssl, NULL, NULL);
425         /* Not needed any more, but lead by example and put the error back. */
426         SSL_set_verify_result(ssl, err);
427         SSL_free(ssl);
428
429         if (ok < 0) {
430             ret = 0;
431             fprintf(stderr, "verify_chain internal error in %s test %d\n",
432                     path, testno);
433             print_errors();
434             continue;
435         }
436         if (err != want || (want == 0 && !ok)) {
437             ret = 0;
438             if (err != want) {
439                 if (want == X509_V_OK)
440                     fprintf(stderr, "Verification failure in %s test %d: %d: %s\n",
441                             path, testno, err, X509_verify_cert_error_string(err));
442                 else
443                     fprintf(stderr, "Unexpected error in %s test %d: %d: wanted %d\n",
444                             path, testno, err, want);
445             } else {
446                 fprintf(stderr, "Verification failure in %s test %d: ok=0\n",
447                         path, testno);
448             }
449             print_errors();
450             continue;
451         }
452         if (mdpth != want_depth) {
453             ret = 0;
454             fprintf(stderr, "Wrong match depth, in %s test %d: wanted %d, got: %d\n",
455                     path, testno, want_depth, mdpth);
456         }
457         fprintf(stderr, "%s: test %d successful\n", path, testno);
458     }
459     ERR_clear_error();
460
461     return ret;
462 }
463
464 int main(int argc, char *argv[])
465 {
466     BIO *f;
467     BIO *bio_err;
468     SSL_CTX *ctx = NULL;
469     const char *basedomain;
470     const char *CAfile;
471     const char *tlsafile;
472     const char *p;
473     int ret = 1;
474
475     progname = argv[0];
476     if (argc != 4) {
477         test_usage();
478         EXIT(1);
479     }
480     basedomain = argv[1];
481     CAfile = argv[2];
482     tlsafile = argv[3];
483
484     bio_err = BIO_new_fp(stderr, BIO_NOCLOSE | BIO_FP_TEXT);
485
486     p = getenv("OPENSSL_DEBUG_MEMORY");
487     if (p != NULL && strcmp(p, "on") == 0)
488         CRYPTO_set_mem_debug(1);
489     CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON);
490
491     f = BIO_new_file(tlsafile, "r");
492     if (f == NULL) {
493         fprintf(stderr, "%s: Error opening tlsa record file: '%s': %s\n",
494                 progname, tlsafile, strerror(errno));
495         return 0;
496     }
497
498
499     ctx = SSL_CTX_new(TLS_client_method());
500     if (SSL_CTX_dane_enable(ctx) <= 0) {
501         print_errors();
502         goto end;
503     }
504     if (!SSL_CTX_load_verify_locations(ctx, CAfile, NULL)) {
505         print_errors();
506         goto end;
507     }
508     if ((SSL_CTX_dane_mtype_set(ctx, EVP_sha512(), 2, 1)) <= 0) {
509         print_errors();
510         goto end;
511     }
512     if ((SSL_CTX_dane_mtype_set(ctx, EVP_sha256(), 1, 2)) <= 0) {
513         print_errors();
514         goto end;
515     }
516
517     if (test_tlsafile(ctx, basedomain, f, tlsafile) <= 0) {
518         print_errors();
519         goto end;
520     }
521
522     ret = 0;
523
524 end:
525
526     BIO_free(f);
527     SSL_CTX_free(ctx);
528
529 #ifndef OPENSSL_NO_CRYPTO_MDEBUG
530     if (CRYPTO_mem_leaks(bio_err) <= 0)
531         ret = 1;
532 #endif
533     BIO_free(bio_err);
534     EXIT(ret);
535 }
536
537 #include <internal/dane.h>
538
539 static void store_ctx_dane_init(X509_STORE_CTX *store_ctx, SSL *ssl)
540 {
541     X509_STORE_CTX_set0_dane(store_ctx, SSL_get0_dane(ssl));
542 }