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