]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/unbound/smallapp/unbound-anchor.c
config: Fix a few mandoc related errors
[FreeBSD/FreeBSD.git] / contrib / unbound / smallapp / unbound-anchor.c
1 /*
2  * unbound-anchor.c - update the root anchor if necessary.
3  *
4  * Copyright (c) 2010, NLnet Labs. All rights reserved.
5  *
6  * This software is open source.
7  * 
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 
12  * Redistributions of source code must retain the above copyright notice,
13  * this list of conditions and the following disclaimer.
14  * 
15  * Redistributions in binary form must reproduce the above copyright notice,
16  * this list of conditions and the following disclaimer in the documentation
17  * and/or other materials provided with the distribution.
18  * 
19  * Neither the name of the NLNET LABS nor the names of its contributors may
20  * be used to endorse or promote products derived from this software without
21  * specific prior written permission.
22  * 
23  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
26  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
27  * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
28  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
29  * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
30  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
31  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
32  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
33  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
34  */
35
36 /**
37  * \file
38  *
39  * This file checks to see that the current 5011 keys work to prime the
40  * current root anchor.  If not a certificate is used to update the anchor,
41  * with RFC7958 https xml fetch.
42  *
43  * This is a concept solution for distribution of the DNSSEC root
44  * trust anchor.  It is a small tool, called "unbound-anchor", that
45  * runs before the main validator starts.  I.e. in the init script:
46  * unbound-anchor; unbound.  Thus it is meant to run at system boot time.
47  *
48  * Management-Abstract:
49  *    * first run: fill root.key file with hardcoded DS record.
50  *    * mostly: use RFC5011 tracking, quick . DNSKEY UDP query.
51  *    * failover: use RFC7958 builtin certificate, do https and update.
52  * Special considerations:
53  *    * 30-days RFC5011 timer saves a lot of https traffic.
54  *    * DNSKEY probe must be NOERROR, saves a lot of https traffic.
55  *    * fail if clock before sign date of the root, if cert expired.
56  *    * if the root goes back to unsigned, deals with it.
57  *
58  * It has hardcoded the root DS anchors and the ICANN CA root certificate.
59  * It allows with options to override those.  It also takes root-hints (it
60  * has to do a DNS resolve), and also has hardcoded defaults for those.
61  *
62  * Once it starts, just before the validator starts, it quickly checks if
63  * the root anchor file needs to be updated.  First it tries to use
64  * RFC5011-tracking of the root key.  If that fails (and for 30-days since
65  * last successful probe), then it attempts to update using the
66  * certificate.  So most of the time, the RFC5011 tracking will work fine,
67  * and within a couple milliseconds, the main daemon can start.  It will
68  * have only probed the . DNSKEY, not done expensive https transfers on the
69  * root infrastructure.
70  *
71  * If there is no root key in the root.key file, it bootstraps the
72  * RFC5011-tracking with its builtin DS anchors; if that fails it
73  * bootstraps the RFC5011-tracking using the certificate.  (again to avoid
74  * https, and it is also faster).
75  * 
76  * It uses the XML file by converting it to DS records and writing that to the
77  * key file.  Unbound can detect that the 'special comments' are gone, and
78  * the file contains a list of normal DNSKEY/DS records, and uses that to
79  * bootstrap 5011 (the KSK is made VALID).
80  *
81  * The certificate RFC7958 update is done by fetching root-anchors.xml and
82  * root-anchors.p7s via SSL.  The HTTPS certificate can be logged but is
83  * not validated (https for channel security; the security comes from the
84  * certificate).  The 'data.iana.org' domain name A and AAAA are resolved
85  * without DNSSEC.  It tries a random IP until the transfer succeeds.  It
86  * then checks the p7s signature.
87  *
88  * On any failure, it leaves the root key file untouched.  The main
89  * validator has to cope with it, it cannot fix things (So a failure does
90  * not go 'without DNSSEC', no downgrade).  If it used its builtin stuff or
91  * did the https, it exits with an exit code, so that this can trigger the
92  * init script to log the event and potentially alert the operator that can
93  * do a manual check.
94  *
95  * The date is also checked.  Before 2010-07-15 is a failure (root not
96  * signed yet; avoids attacks on system clock).  The
97  * last-successful-RFC5011-probe (if available) has to be more than 30 days
98  * in the past (otherwise, RFC5011 should have worked).  This keeps
99  * unnecessary https traffic down.  If the main certificate is expired, it
100  * fails.
101  *
102  * The dates on the keys in the xml are checked (uses the libexpat xml
103  * parser), only the valid ones are used to re-enstate RFC5011 tracking.
104  * If 0 keys are valid, the zone has gone to insecure (a special marker is
105  * written in the keyfile that tells the main validator daemon the zone is
106  * insecure).
107  *
108  * Only the root ICANN CA is shipped, not the intermediate ones.  The
109  * intermediate CAs are included in the p7s file that was downloaded.  (the
110  * root cert is valid to 2028 and the intermediate to 2014, today).
111  *
112  * Obviously, the tool also has options so the operator can provide a new
113  * keyfile, a new certificate and new URLs, and fresh root hints.  By
114  * default it logs nothing on failure and success; it 'just works'.
115  *
116  */
117
118 #include "config.h"
119 #include "libunbound/unbound.h"
120 #include "sldns/rrdef.h"
121 #include "sldns/parseutil.h"
122 #include <expat.h>
123 #ifndef HAVE_EXPAT_H
124 #error "need libexpat to parse root-anchors.xml file."
125 #endif
126 #ifdef HAVE_GETOPT_H
127 #include <getopt.h>
128 #endif
129 #ifdef HAVE_OPENSSL_SSL_H
130 #include <openssl/ssl.h>
131 #endif
132 #ifdef HAVE_OPENSSL_ERR_H
133 #include <openssl/err.h>
134 #endif
135 #ifdef HAVE_OPENSSL_RAND_H
136 #include <openssl/rand.h>
137 #endif
138 #include <openssl/x509.h>
139 #include <openssl/x509v3.h>
140 #include <openssl/pem.h>
141
142 /** name of server in URL to fetch HTTPS from */
143 #define URLNAME "data.iana.org"
144 /** path on HTTPS server to xml file */
145 #define XMLNAME "root-anchors/root-anchors.xml"
146 /** path on HTTPS server to p7s file */
147 #define P7SNAME "root-anchors/root-anchors.p7s"
148 /** name of the signer of the certificate */
149 #define P7SIGNER "dnssec@iana.org"
150 /** port number for https access */
151 #define HTTPS_PORT 443
152
153 #ifdef USE_WINSOCK
154 /* sneakily reuse the the wsa_strerror function, on windows */
155 char* wsa_strerror(int err);
156 #endif
157
158 /** verbosity for this application */
159 static int verb = 0;
160
161 /** list of IP addresses */
162 struct ip_list {
163         /** next in list */
164         struct ip_list* next;
165         /** length of addr */
166         socklen_t len;
167         /** address ready to connect to */
168         struct sockaddr_storage addr;
169         /** has the address been used */
170         int used;
171 };
172
173 /** Give unbound-anchor usage, and exit (1). */
174 static void
175 usage(void)
176 {
177         printf("Usage:  local-unbound-anchor [opts]\n");
178         printf("        Setup or update root anchor. "
179                 "Most options have defaults.\n");
180         printf("        Run this program before you start the validator.\n");
181         printf("\n");
182         printf("        The anchor and cert have default builtin content\n");
183         printf("        if the file does not exist or is empty.\n");
184         printf("\n");
185         printf("-a file         root key file, default %s\n", ROOT_ANCHOR_FILE);
186         printf("                The key is input and output for this tool.\n");
187         printf("-c file         cert file, default %s\n", ROOT_CERT_FILE);
188         printf("-l              list builtin key and cert on stdout\n");
189         printf("-u name         server in https url, default %s\n", URLNAME);
190         printf("-S              do not use SNI for the https connection\n");
191         printf("-x path         pathname to xml in url, default %s\n", XMLNAME);
192         printf("-s path         pathname to p7s in url, default %s\n", P7SNAME);
193         printf("-n name         signer's subject emailAddress, default %s\n", P7SIGNER);
194         printf("-b address      source address to bind to\n");
195         printf("-4              work using IPv4 only\n");
196         printf("-6              work using IPv6 only\n");
197         printf("-f resolv.conf  use given resolv.conf\n");
198         printf("-r root.hints   use given root.hints\n"
199                 "               builtin root hints are used by default\n");
200         printf("-R              fallback from -f to root query on error\n");
201         printf("-v              more verbose\n");
202         printf("-C conf         debug, read config\n");
203         printf("-P port         use port for https connect, default 443\n");
204         printf("-F              debug, force update with cert\n");
205         printf("-h              show this usage help\n");
206         printf("Version %s\n", PACKAGE_VERSION);
207         printf("BSD licensed, see LICENSE in source package for details.\n");
208         printf("Report bugs to %s\n", PACKAGE_BUGREPORT);
209         exit(1);
210 }
211
212 /** return the built in root update certificate */
213 static const char*
214 get_builtin_cert(void)
215 {
216         return
217 /* The ICANN CA fetched at 24 Sep 2010.  Valid to 2028 */
218 "-----BEGIN CERTIFICATE-----\n"
219 "MIIDdzCCAl+gAwIBAgIBATANBgkqhkiG9w0BAQsFADBdMQ4wDAYDVQQKEwVJQ0FO\n"
220 "TjEmMCQGA1UECxMdSUNBTk4gQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkxFjAUBgNV\n"
221 "BAMTDUlDQU5OIFJvb3QgQ0ExCzAJBgNVBAYTAlVTMB4XDTA5MTIyMzA0MTkxMloX\n"
222 "DTI5MTIxODA0MTkxMlowXTEOMAwGA1UEChMFSUNBTk4xJjAkBgNVBAsTHUlDQU5O\n"
223 "IENlcnRpZmljYXRpb24gQXV0aG9yaXR5MRYwFAYDVQQDEw1JQ0FOTiBSb290IENB\n"
224 "MQswCQYDVQQGEwJVUzCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAKDb\n"
225 "cLhPNNqc1NB+u+oVvOnJESofYS9qub0/PXagmgr37pNublVThIzyLPGCJ8gPms9S\n"
226 "G1TaKNIsMI7d+5IgMy3WyPEOECGIcfqEIktdR1YWfJufXcMReZwU4v/AdKzdOdfg\n"
227 "ONiwc6r70duEr1IiqPbVm5T05l1e6D+HkAvHGnf1LtOPGs4CHQdpIUcy2kauAEy2\n"
228 "paKcOcHASvbTHK7TbbvHGPB+7faAztABLoneErruEcumetcNfPMIjXKdv1V1E3C7\n"
229 "MSJKy+jAqqQJqjZoQGB0necZgUMiUv7JK1IPQRM2CXJllcyJrm9WFxY0c1KjBO29\n"
230 "iIKK69fcglKcBuFShUECAwEAAaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8B\n"
231 "Af8EBAMCAf4wHQYDVR0OBBYEFLpS6UmDJIZSL8eZzfyNa2kITcBQMA0GCSqGSIb3\n"
232 "DQEBCwUAA4IBAQAP8emCogqHny2UYFqywEuhLys7R9UKmYY4suzGO4nkbgfPFMfH\n"
233 "6M+Zj6owwxlwueZt1j/IaCayoKU3QsrYYoDRolpILh+FPwx7wseUEV8ZKpWsoDoD\n"
234 "2JFbLg2cfB8u/OlE4RYmcxxFSmXBg0yQ8/IoQt/bxOcEEhhiQ168H2yE5rxJMt9h\n"
235 "15nu5JBSewrCkYqYYmaxyOC3WrVGfHZxVI7MpIFcGdvSb2a1uyuua8l0BKgk3ujF\n"
236 "0/wsHNeP22qNyVO+XVBzrM8fk8BSUFuiT/6tZTYXRtEt5aKQZgXbKU5dUF3jT9qg\n"
237 "j/Br5BZw3X/zd325TvnswzMC1+ljLzHnQGGk\n"
238 "-----END CERTIFICATE-----\n"
239                 ;
240 }
241
242 /** return the built in root DS trust anchor */
243 static const char*
244 get_builtin_ds(void)
245 {
246         return
247 /* The anchors must start on a new line with ". IN DS and end with \n"[;]
248  * because the makedist script greps on the source here */
249 /* anchor 20326 is from 2017 */
250 ". IN DS 20326 8 2 E06D44B80B8F1D39A95C0B0D7C65D08458E880409BBC683457104237C7F8EC8D\n";
251 }
252
253 /** print hex data */
254 static void
255 print_data(const char* msg, const char* data, int len)
256 {
257         int i;
258         printf("%s: ", msg);
259         for(i=0; i<len; i++) {
260                 printf(" %2.2x", (unsigned char)data[i]);
261         }
262         printf("\n");
263 }
264
265 /** print ub context creation error and exit */
266 static void
267 ub_ctx_error_exit(struct ub_ctx* ctx, const char* str, const char* str2)
268 {
269         ub_ctx_delete(ctx);
270         if(str && str2 && verb) printf("%s: %s\n", str, str2);
271         if(verb) printf("error: could not create unbound resolver context\n");
272         exit(0);
273 }
274
275 /**
276  * Create a new unbound context with the commandline settings applied
277  */
278 static struct ub_ctx* 
279 create_unbound_context(const char* res_conf, const char* root_hints,
280         const char* debugconf, const char* srcaddr, int ip4only, int ip6only)
281 {
282         int r;
283         struct ub_ctx* ctx = ub_ctx_create();
284         if(!ctx) {
285                 if(verb) printf("out of memory\n");
286                 exit(0);
287         }
288         /* do not waste time and network traffic to fetch extra nameservers */
289         r = ub_ctx_set_option(ctx, "target-fetch-policy:", "0 0 0 0 0");
290         if(r && verb) printf("ctx targetfetchpolicy: %s\n", ub_strerror(r));
291         /* read config file first, so its settings can be overridden */
292         if(debugconf) {
293                 r = ub_ctx_config(ctx, debugconf);
294                 if(r) ub_ctx_error_exit(ctx, debugconf, ub_strerror(r));
295         }
296         if(res_conf) {
297                 r = ub_ctx_resolvconf(ctx, res_conf);
298                 if(r) ub_ctx_error_exit(ctx, res_conf, ub_strerror(r));
299         }
300         if(root_hints) {
301                 r = ub_ctx_set_option(ctx, "root-hints:", root_hints);
302                 if(r) ub_ctx_error_exit(ctx, root_hints, ub_strerror(r));
303         }
304         if(srcaddr) {
305                 r = ub_ctx_set_option(ctx, "outgoing-interface:", srcaddr);
306                 if(r) ub_ctx_error_exit(ctx, srcaddr, ub_strerror(r));
307         }
308         if(ip4only) {
309                 r = ub_ctx_set_option(ctx, "do-ip6:", "no");
310                 if(r) ub_ctx_error_exit(ctx, "ip4only", ub_strerror(r));
311         }
312         if(ip6only) {
313                 r = ub_ctx_set_option(ctx, "do-ip4:", "no");
314                 if(r) ub_ctx_error_exit(ctx, "ip6only", ub_strerror(r));
315         }
316         return ctx;
317 }
318
319 /** printout certificate in detail */
320 static void
321 verb_cert(const char* msg, X509* x)
322 {
323         if(verb == 0 || verb == 1) return;
324         if(verb == 2) {
325                 if(msg) printf("%s\n", msg);
326                 X509_print_ex_fp(stdout, x, 0, (unsigned long)-1
327                         ^(X509_FLAG_NO_SUBJECT
328                         |X509_FLAG_NO_ISSUER|X509_FLAG_NO_VALIDITY));
329                 return;
330         }
331         if(msg) printf("%s\n", msg);
332         X509_print_fp(stdout, x);
333 }
334
335 /** printout certificates in detail */
336 static void
337 verb_certs(const char* msg, STACK_OF(X509)* sk)
338 {
339         int i, num = sk_X509_num(sk);
340         if(verb == 0 || verb == 1) return;
341         for(i=0; i<num; i++) {
342                 printf("%s (%d/%d)\n", msg, i, num);
343                 verb_cert(NULL, sk_X509_value(sk, i));
344         }
345 }
346
347 /** read certificates from a PEM bio */
348 static STACK_OF(X509)*
349 read_cert_bio(BIO* bio)
350 {
351         STACK_OF(X509) *sk = sk_X509_new_null();
352         if(!sk) {
353                 if(verb) printf("out of memory\n");
354                 exit(0);
355         }
356         while(!BIO_eof(bio)) {
357                 X509* x = PEM_read_bio_X509(bio, NULL, NULL, NULL);
358                 if(x == NULL) {
359                         if(verb) {
360                                 printf("failed to read X509\n");
361                                 ERR_print_errors_fp(stdout);
362                         }
363                         continue;
364                 }
365                 if(!sk_X509_push(sk, x)) {
366                         if(verb) printf("out of memory\n");
367                         exit(0);
368                 }
369         }
370         return sk;
371 }
372
373 /* read the certificate file */
374 static STACK_OF(X509)*
375 read_cert_file(const char* file)
376 {
377         STACK_OF(X509)* sk;
378         FILE* in;
379         int content = 0;
380         char buf[128];
381         if(file == NULL || strcmp(file, "") == 0) {
382                 return NULL;
383         }
384         sk = sk_X509_new_null();
385         if(!sk) {
386                 if(verb) printf("out of memory\n");
387                 exit(0);
388         }
389         in = fopen(file, "r");
390         if(!in) {
391                 if(verb) printf("%s: %s\n", file, strerror(errno));
392 #ifndef S_SPLINT_S
393                 sk_X509_pop_free(sk, X509_free);
394 #endif
395                 return NULL;
396         }
397         while(!feof(in)) {
398                 X509* x = PEM_read_X509(in, NULL, NULL, NULL);
399                 if(x == NULL) {
400                         if(verb) {
401                                 printf("failed to read X509 file\n");
402                                 ERR_print_errors_fp(stdout);
403                         }
404                         continue;
405                 }
406                 if(!sk_X509_push(sk, x)) {
407                         if(verb) printf("out of memory\n");
408                         fclose(in);
409                         exit(0);
410                 }
411                 content = 1;
412                 /* read away newline after --END CERT-- */
413                 if(!fgets(buf, (int)sizeof(buf), in))
414                         break;
415         }
416         fclose(in);
417         if(!content) {
418                 if(verb) printf("%s is empty\n", file);
419 #ifndef S_SPLINT_S
420                 sk_X509_pop_free(sk, X509_free);
421 #endif
422                 return NULL;
423         }
424         return sk;
425 }
426
427 /** read certificates from the builtin certificate */
428 static STACK_OF(X509)*
429 read_builtin_cert(void)
430 {
431         const char* builtin_cert = get_builtin_cert();
432         STACK_OF(X509)* sk;
433         BIO *bio = BIO_new_mem_buf(builtin_cert,
434                 (int)strlen(builtin_cert));
435         if(!bio) {
436                 if(verb) printf("out of memory\n");
437                 exit(0);
438         }
439         sk = read_cert_bio(bio);
440         if(!sk) {
441                 if(verb) printf("internal error, out of memory\n");
442                 exit(0);
443         }
444         BIO_free(bio);
445         return sk;
446 }
447
448 /** read update cert file or use builtin */
449 static STACK_OF(X509)*
450 read_cert_or_builtin(const char* file)
451 {
452         STACK_OF(X509) *sk = read_cert_file(file);
453         if(!sk) {
454                 if(verb) printf("using builtin certificate\n");
455                 sk = read_builtin_cert();
456         }
457         if(verb) printf("have %d trusted certificates\n", sk_X509_num(sk));
458         verb_certs("trusted certificates", sk);
459         return sk;
460 }
461
462 static void
463 do_list_builtin(void)
464 {
465         const char* builtin_cert = get_builtin_cert();
466         const char* builtin_ds = get_builtin_ds();
467         printf("%s\n", builtin_ds);
468         printf("%s\n", builtin_cert);
469         exit(0);
470 }
471
472 /** printout IP address with message */
473 static void
474 verb_addr(const char* msg, struct ip_list* ip)
475 {
476         if(verb) {
477                 char out[100];
478                 void* a = &((struct sockaddr_in*)&ip->addr)->sin_addr;
479                 if(ip->len != (socklen_t)sizeof(struct sockaddr_in))
480                         a = &((struct sockaddr_in6*)&ip->addr)->sin6_addr;
481
482                 if(inet_ntop((int)((struct sockaddr_in*)&ip->addr)->sin_family,
483                         a, out, (socklen_t)sizeof(out))==0)
484                         printf("%s (inet_ntop error)\n", msg);
485                 else printf("%s %s\n", msg, out);
486         }
487 }
488
489 /** free ip_list */
490 static void
491 ip_list_free(struct ip_list* p)
492 {
493         struct ip_list* np;
494         while(p) {
495                 np = p->next;
496                 free(p);
497                 p = np;
498         }
499 }
500
501 /** create ip_list entry for a RR record */
502 static struct ip_list*
503 RR_to_ip(int tp, char* data, int len, int port)
504 {
505         struct ip_list* ip = (struct ip_list*)calloc(1, sizeof(*ip));
506         uint16_t p = (uint16_t)port;
507         if(tp == LDNS_RR_TYPE_A) {
508                 struct sockaddr_in* sa = (struct sockaddr_in*)&ip->addr;
509                 ip->len = (socklen_t)sizeof(*sa);
510                 sa->sin_family = AF_INET;
511                 sa->sin_port = (in_port_t)htons(p);
512                 if(len != (int)sizeof(sa->sin_addr)) {
513                         if(verb) printf("skipped badly formatted A\n");
514                         free(ip);
515                         return NULL;
516                 }
517                 memmove(&sa->sin_addr, data, sizeof(sa->sin_addr));
518
519         } else if(tp == LDNS_RR_TYPE_AAAA) {
520                 struct sockaddr_in6* sa = (struct sockaddr_in6*)&ip->addr;
521                 ip->len = (socklen_t)sizeof(*sa);
522                 sa->sin6_family = AF_INET6;
523                 sa->sin6_port = (in_port_t)htons(p);
524                 if(len != (int)sizeof(sa->sin6_addr)) {
525                         if(verb) printf("skipped badly formatted AAAA\n");
526                         free(ip);
527                         return NULL;
528                 }
529                 memmove(&sa->sin6_addr, data, sizeof(sa->sin6_addr));
530         } else {
531                 if(verb) printf("internal error: bad type in RRtoip\n");
532                 free(ip);
533                 return NULL;
534         }
535         verb_addr("resolved server address", ip);
536         return ip;
537 }
538
539 /** Resolve name, type, class and add addresses to iplist */
540 static void
541 resolve_host_ip(struct ub_ctx* ctx, const char* host, int port, int tp, int cl,
542         struct ip_list** head)
543 {
544         struct ub_result* res = NULL;
545         int r;
546         int i;
547
548         r = ub_resolve(ctx, host, tp, cl, &res);
549         if(r) {
550                 if(verb) printf("error: resolve %s %s: %s\n", host,
551                         (tp==LDNS_RR_TYPE_A)?"A":"AAAA", ub_strerror(r));
552                 return;
553         }
554         if(!res) {
555                 if(verb) printf("out of memory\n");
556                 ub_ctx_delete(ctx);
557                 exit(0);
558         }
559         if(!res->havedata || res->rcode || !res->data) {
560                 if(verb) printf("resolve %s %s: no result\n", host,
561                         (tp==LDNS_RR_TYPE_A)?"A":"AAAA");
562                 return;
563         }
564         for(i = 0; res->data[i]; i++) {
565                 struct ip_list* ip = RR_to_ip(tp, res->data[i], res->len[i],
566                         port);
567                 if(!ip) continue;
568                 ip->next = *head;
569                 *head = ip;
570         }
571         ub_resolve_free(res);
572 }
573
574 /** parse a text IP address into a sockaddr */
575 static struct ip_list*
576 parse_ip_addr(const char* str, int port)
577 {
578         socklen_t len = 0;
579         union {
580                 struct sockaddr_in6 a6;
581                 struct sockaddr_in a;
582         } addr;
583         struct ip_list* ip;
584         uint16_t p = (uint16_t)port;
585         memset(&addr, 0, sizeof(addr));
586
587         if(inet_pton(AF_INET6, str, &addr.a6.sin6_addr) > 0) {
588                 /* it is an IPv6 */
589                 addr.a6.sin6_family = AF_INET6;
590                 addr.a6.sin6_port = (in_port_t)htons(p);
591                 len = (socklen_t)sizeof(addr.a6);
592         }
593         if(inet_pton(AF_INET, str, &addr.a.sin_addr) > 0) {
594                 /* it is an IPv4 */
595                 addr.a.sin_family = AF_INET;
596                 addr.a.sin_port = (in_port_t)htons(p);
597                 len = (socklen_t)sizeof(struct sockaddr_in);
598         }
599         if(!len) return NULL;
600         ip = (struct ip_list*)calloc(1, sizeof(*ip));
601         if(!ip) {
602                 if(verb) printf("out of memory\n");
603                 exit(0);
604         }
605         ip->len = len;
606         memmove(&ip->addr, &addr, len);
607         if(verb) printf("server address is %s\n", str);
608         return ip;
609 }
610
611 /**
612  * Resolve a domain name (even though the resolver is down and there is
613  * no trust anchor).  Without DNSSEC validation.
614  * @param host: the name to resolve.
615  *      If this name is an IP4 or IP6 address this address is returned.
616  * @param port: the port number used for the returned IP structs.
617  * @param res_conf: resolv.conf (if any).
618  * @param root_hints: root hints (if any).
619  * @param debugconf: unbound.conf for debugging options.
620  * @param srcaddr: source address option (if any).
621  * @param ip4only: use only ip4 for resolve and only lookup A
622  * @param ip6only: use only ip6 for resolve and only lookup AAAA
623  *      default is to lookup A and AAAA using ip4 and ip6.
624  * @return list of IP addresses.
625  */
626 static struct ip_list*
627 resolve_name(const char* host, int port, const char* res_conf,
628         const char* root_hints, const char* debugconf,
629         const char* srcaddr, int ip4only, int ip6only)
630 {
631         struct ub_ctx* ctx;
632         struct ip_list* list = NULL;
633         /* first see if name is an IP address itself */
634         if( (list=parse_ip_addr(host, port)) ) {
635                 return list;
636         }
637         
638         /* create resolver context */
639         ctx = create_unbound_context(res_conf, root_hints, debugconf,
640                 srcaddr, ip4only, ip6only);
641
642         /* try resolution of A */
643         if(!ip6only) {
644                 resolve_host_ip(ctx, host, port, LDNS_RR_TYPE_A,
645                         LDNS_RR_CLASS_IN, &list);
646         }
647
648         /* try resolution of AAAA */
649         if(!ip4only) {
650                 resolve_host_ip(ctx, host, port, LDNS_RR_TYPE_AAAA,
651                         LDNS_RR_CLASS_IN, &list);
652         }
653
654         ub_ctx_delete(ctx);
655         if(!list) {
656                 if(verb) printf("%s has no IP addresses I can use\n", host);
657                 exit(0);
658         }
659         return list;
660 }
661
662 /** clear used flags */
663 static void
664 wipe_ip_usage(struct ip_list* p)
665 {
666         while(p) {
667                 p->used = 0;
668                 p = p->next;
669         }
670 }
671
672 /** count unused IPs */
673 static int
674 count_unused(struct ip_list* p)
675 {
676         int num = 0;
677         while(p) {
678                 if(!p->used) num++;
679                 p = p->next;
680         }
681         return num;
682 }
683
684 /** pick random unused element from IP list */
685 static struct ip_list*
686 pick_random_ip(struct ip_list* list)
687 {
688         struct ip_list* p = list;
689         int num = count_unused(list);
690         int sel;
691         if(num == 0) return NULL;
692         /* not perfect, but random enough */
693         sel = (int)arc4random_uniform((uint32_t)num);
694         /* skip over unused elements that we did not select */
695         while(sel > 0 && p) {
696                 if(!p->used) sel--;
697                 p = p->next;
698         }
699         /* find the next unused element */
700         while(p && p->used)
701                 p = p->next;
702         if(!p) return NULL; /* robustness */
703         return p;
704 }
705
706 /** close the fd */
707 static void
708 fd_close(int fd)
709 {
710 #ifndef USE_WINSOCK
711         close(fd);
712 #else
713         closesocket(fd);
714 #endif
715 }
716
717 /** printout socket errno */
718 static void
719 print_sock_err(const char* msg)
720 {
721 #ifndef USE_WINSOCK
722         if(verb) printf("%s: %s\n", msg, strerror(errno));
723 #else
724         if(verb) printf("%s: %s\n", msg, wsa_strerror(WSAGetLastError()));
725 #endif
726 }
727
728 /** connect to IP address */
729 static int
730 connect_to_ip(struct ip_list* ip, struct ip_list* src)
731 {
732         int fd;
733         verb_addr("connect to", ip);
734         fd = socket(ip->len==(socklen_t)sizeof(struct sockaddr_in)?
735                 AF_INET:AF_INET6, SOCK_STREAM, 0);
736         if(fd == -1) {
737                 print_sock_err("socket");
738                 return -1;
739         }
740         if(src && bind(fd, (struct sockaddr*)&src->addr, src->len) < 0) {
741                 print_sock_err("bind");
742                 fd_close(fd);
743                 return -1;
744         }
745         if(connect(fd, (struct sockaddr*)&ip->addr, ip->len) < 0) {
746                 print_sock_err("connect");
747                 fd_close(fd);
748                 return -1;
749         }
750         return fd;
751 }
752
753 /** create SSL context */
754 static SSL_CTX*
755 setup_sslctx(void)
756 {
757         SSL_CTX* sslctx = SSL_CTX_new(SSLv23_client_method());
758         if(!sslctx) {
759                 if(verb) printf("SSL_CTX_new error\n");
760                 return NULL;
761         }
762         return sslctx;
763 }
764
765 /** initiate TLS on a connection */
766 static SSL*
767 TLS_initiate(SSL_CTX* sslctx, int fd, const char* urlname, int use_sni)
768 {
769         X509* x;
770         int r;
771         SSL* ssl = SSL_new(sslctx);
772         if(!ssl) {
773                 if(verb) printf("SSL_new error\n");
774                 return NULL;
775         }
776         SSL_set_connect_state(ssl);
777         (void)SSL_set_mode(ssl, (long)SSL_MODE_AUTO_RETRY);
778         if(!SSL_set_fd(ssl, fd)) {
779                 if(verb) printf("SSL_set_fd error\n");
780                 SSL_free(ssl);
781                 return NULL;
782         }
783         if(use_sni) {
784                 (void)SSL_set_tlsext_host_name(ssl, urlname);
785         }
786         while(1) {
787                 ERR_clear_error();
788                 if( (r=SSL_do_handshake(ssl)) == 1)
789                         break;
790                 r = SSL_get_error(ssl, r);
791                 if(r != SSL_ERROR_WANT_READ && r != SSL_ERROR_WANT_WRITE) {
792                         if(verb) printf("SSL handshake failed\n");
793                         SSL_free(ssl);
794                         return NULL;
795                 }
796                 /* wants to be called again */
797         }
798         x = SSL_get_peer_certificate(ssl);
799         if(!x) {
800                 if(verb) printf("Server presented no peer certificate\n");
801                 SSL_free(ssl);
802                 return NULL;
803         }
804         verb_cert("server SSL certificate", x);
805         X509_free(x);
806         return ssl;
807 }
808
809 /** perform neat TLS shutdown */
810 static void
811 TLS_shutdown(int fd, SSL* ssl, SSL_CTX* sslctx)
812 {
813         /* shutdown the SSL connection nicely */
814         if(SSL_shutdown(ssl) == 0) {
815                 SSL_shutdown(ssl);
816         }
817         SSL_free(ssl);
818         SSL_CTX_free(sslctx);
819         fd_close(fd);
820 }
821
822 /** write a line over SSL */
823 static int
824 write_ssl_line(SSL* ssl, const char* str, const char* sec)
825 {
826         char buf[1024];
827         size_t l;
828         if(sec) {
829                 snprintf(buf, sizeof(buf), str, sec);
830         } else {
831                 snprintf(buf, sizeof(buf), "%s", str);
832         }
833         l = strlen(buf);
834         if(l+2 >= sizeof(buf)) {
835                 if(verb) printf("line too long\n");
836                 return 0;
837         }
838         if(verb >= 2) printf("SSL_write: %s\n", buf);
839         buf[l] = '\r';
840         buf[l+1] = '\n';
841         buf[l+2] = 0;
842         /* add \r\n */
843         if(SSL_write(ssl, buf, (int)strlen(buf)) <= 0) {
844                 if(verb) printf("could not SSL_write %s", str);
845                 return 0;
846         }
847         return 1;
848 }
849
850 /** process header line, check rcode and keeping track of size */
851 static int
852 process_one_header(char* buf, size_t* clen, int* chunked)
853 {
854         if(verb>=2) printf("header: '%s'\n", buf);
855         if(strncasecmp(buf, "HTTP/1.1 ", 9) == 0) {
856                 /* check returncode */
857                 if(buf[9] != '2') {
858                         if(verb) printf("bad status %s\n", buf+9);
859                         return 0;
860                 }
861         } else if(strncasecmp(buf, "Content-Length: ", 16) == 0) {
862                 if(!*chunked)
863                         *clen = (size_t)atoi(buf+16);
864         } else if(strncasecmp(buf, "Transfer-Encoding: chunked", 19+7) == 0) {
865                 *clen = 0;
866                 *chunked = 1;
867         }
868         return 1;
869 }
870
871 /** 
872  * Read one line from SSL
873  * zero terminates.
874  * skips "\r\n" (but not copied to buf).
875  * @param ssl: the SSL connection to read from (blocking).
876  * @param buf: buffer to return line in.
877  * @param len: size of the buffer.
878  * @return 0 on error, 1 on success.
879  */
880 static int
881 read_ssl_line(SSL* ssl, char* buf, size_t len)
882 {
883         size_t n = 0;
884         int r;
885         int endnl = 0;
886         while(1) {
887                 if(n >= len) {
888                         if(verb) printf("line too long\n");
889                         return 0;
890                 }
891                 if((r = SSL_read(ssl, buf+n, 1)) <= 0) {
892                         if(SSL_get_error(ssl, r) == SSL_ERROR_ZERO_RETURN) {
893                                 /* EOF */
894                                 break;
895                         }
896                         if(verb) printf("could not SSL_read\n");
897                         return 0;
898                 }
899                 if(endnl && buf[n] == '\n') {
900                         break;
901                 } else if(endnl) {
902                         /* bad data */
903                         if(verb) printf("error: stray linefeeds\n");
904                         return 0;
905                 } else if(buf[n] == '\r') {
906                         /* skip \r, and also \n on the wire */
907                         endnl = 1;
908                         continue;
909                 } else if(buf[n] == '\n') {
910                         /* skip the \n, we are done */
911                         break;
912                 } else n++;
913         }
914         buf[n] = 0;
915         return 1;
916 }
917
918 /** read http headers and process them */
919 static size_t
920 read_http_headers(SSL* ssl, size_t* clen)
921 {
922         char buf[1024];
923         int chunked = 0;
924         *clen = 0;
925         while(read_ssl_line(ssl, buf, sizeof(buf))) {
926                 if(buf[0] == 0)
927                         return 1;
928                 if(!process_one_header(buf, clen, &chunked))
929                         return 0;
930         }
931         return 0;
932 }
933
934 /** read a data chunk */
935 static char*
936 read_data_chunk(SSL* ssl, size_t len)
937 {
938         size_t got = 0;
939         int r;
940         char* data;
941         if((unsigned)len >= (unsigned)0xfffffff0)
942                 return NULL; /* to protect against integer overflow in malloc*/
943         data = malloc(len+1);
944         if(!data) {
945                 if(verb) printf("out of memory\n");
946                 return NULL;
947         }
948         while(got < len) {
949                 if((r = SSL_read(ssl, data+got, (int)(len-got))) <= 0) {
950                         if(SSL_get_error(ssl, r) == SSL_ERROR_ZERO_RETURN) {
951                                 /* EOF */
952                                 if(verb) printf("could not SSL_read: unexpected EOF\n");
953                                 free(data);
954                                 return NULL;
955                         }
956                         if(verb) printf("could not SSL_read\n");
957                         free(data);
958                         return NULL;
959                 }
960                 if(verb >= 2) printf("at %d/%d\n", (int)got, (int)len);
961                 got += r;
962         }
963         if(verb>=2) printf("read %d data\n", (int)len);
964         data[len] = 0;
965         return data;
966 }
967
968 /** parse chunk header */
969 static int
970 parse_chunk_header(char* buf, size_t* result)
971 {
972         char* e = NULL;
973         size_t v = (size_t)strtol(buf, &e, 16);
974         if(e == buf)
975                 return 0;
976         *result = v;
977         return 1;
978 }
979
980 /** read chunked data from connection */
981 static BIO*
982 do_chunked_read(SSL* ssl)
983 {
984         char buf[1024];
985         size_t len;
986         char* body;
987         BIO* mem = BIO_new(BIO_s_mem());
988         if(verb>=3) printf("do_chunked_read\n");
989         if(!mem) {
990                 if(verb) printf("out of memory\n");
991                 return NULL;
992         }
993         while(read_ssl_line(ssl, buf, sizeof(buf))) {
994                 /* read the chunked start line */
995                 if(verb>=2) printf("chunk header: %s\n", buf);
996                 if(!parse_chunk_header(buf, &len)) {
997                         BIO_free(mem);
998                         if(verb>=3) printf("could not parse chunk header\n");
999                         return NULL;
1000                 }
1001                 if(verb>=2) printf("chunk len: %d\n", (int)len);
1002                 /* are we done? */
1003                 if(len == 0) {
1004                         char z = 0;
1005                         /* skip end-of-chunk-trailer lines,
1006                          * until the empty line after that */
1007                         do {
1008                                 if(!read_ssl_line(ssl, buf, sizeof(buf))) {
1009                                         BIO_free(mem);
1010                                         return NULL;
1011                                 }
1012                         } while (strlen(buf) > 0);
1013                         /* end of chunks, zero terminate it */
1014                         if(BIO_write(mem, &z, 1) <= 0) {
1015                                 if(verb) printf("out of memory\n");
1016                                 BIO_free(mem);
1017                                 return NULL;
1018                         }
1019                         return mem;
1020                 }
1021                 /* read the chunked body */
1022                 body = read_data_chunk(ssl, len);
1023                 if(!body) {
1024                         BIO_free(mem);
1025                         return NULL;
1026                 }
1027                 if(BIO_write(mem, body, (int)len) <= 0) {
1028                         if(verb) printf("out of memory\n");
1029                         free(body);
1030                         BIO_free(mem);
1031                         return NULL;
1032                 }
1033                 free(body);
1034                 /* skip empty line after data chunk */
1035                 if(!read_ssl_line(ssl, buf, sizeof(buf))) {
1036                         BIO_free(mem);
1037                         return NULL;
1038                 }
1039         }
1040         BIO_free(mem);
1041         return NULL;
1042 }
1043
1044 /** start HTTP1.1 transaction on SSL */
1045 static int
1046 write_http_get(SSL* ssl, const char* pathname, const char* urlname)
1047 {
1048         if(write_ssl_line(ssl, "GET /%s HTTP/1.1", pathname) &&
1049            write_ssl_line(ssl, "Host: %s", urlname) &&
1050            write_ssl_line(ssl, "User-Agent: unbound-anchor/%s",
1051                 PACKAGE_VERSION) &&
1052            /* We do not really do multiple queries per connection,
1053             * but this header setting is also not needed.
1054             * write_ssl_line(ssl, "Connection: close", NULL) &&*/
1055            write_ssl_line(ssl, "", NULL)) {
1056                 return 1;
1057         }
1058         return 0;
1059 }
1060
1061 /** read chunked data and zero terminate; len is without zero */
1062 static char*
1063 read_chunked_zero_terminate(SSL* ssl, size_t* len)
1064 {
1065         /* do the chunked version */
1066         BIO* tmp = do_chunked_read(ssl);
1067         char* data, *d = NULL;
1068         size_t l;
1069         if(!tmp) {
1070                 if(verb) printf("could not read from https\n");
1071                 return NULL;
1072         }
1073         l = (size_t)BIO_get_mem_data(tmp, &d);
1074         if(verb>=2) printf("chunked data is %d\n", (int)l);
1075         if(l == 0 || d == NULL) {
1076                 if(verb) printf("out of memory\n");
1077                 return NULL;
1078         }
1079         *len = l-1;
1080         data = (char*)malloc(l);
1081         if(data == NULL) {
1082                 if(verb) printf("out of memory\n");
1083                 return NULL;
1084         }
1085         memcpy(data, d, l);
1086         BIO_free(tmp);
1087         return data;
1088 }
1089
1090 /** read HTTP result from SSL */
1091 static BIO*
1092 read_http_result(SSL* ssl)
1093 {
1094         size_t len = 0;
1095         char* data;
1096         BIO* m;
1097         if(!read_http_headers(ssl, &len)) {
1098                 return NULL;
1099         }
1100         if(len == 0) {
1101                 data = read_chunked_zero_terminate(ssl, &len);
1102         } else {
1103                 data = read_data_chunk(ssl, len);
1104         }
1105         if(!data) return NULL;
1106         if(verb >= 4) print_data("read data", data, (int)len);
1107         m = BIO_new(BIO_s_mem());
1108         if(!m) {
1109                 if(verb) printf("out of memory\n");
1110                 free(data);
1111                 exit(0);
1112         }
1113         BIO_write(m, data, (int)len);
1114         free(data);
1115         return m;
1116 }
1117
1118 /** https to an IP addr, return BIO with pathname or NULL */
1119 static BIO*
1120 https_to_ip(struct ip_list* ip, const char* pathname, const char* urlname,
1121         struct ip_list* src, int use_sni)
1122 {
1123         int fd;
1124         SSL* ssl;
1125         BIO* bio;
1126         SSL_CTX* sslctx = setup_sslctx();
1127         if(!sslctx) {
1128                 return NULL;
1129         }
1130         fd = connect_to_ip(ip, src);
1131         if(fd == -1) {
1132                 SSL_CTX_free(sslctx);
1133                 return NULL;
1134         }
1135         ssl = TLS_initiate(sslctx, fd, urlname, use_sni);
1136         if(!ssl) {
1137                 SSL_CTX_free(sslctx);
1138                 fd_close(fd);
1139                 return NULL;
1140         }
1141         if(!write_http_get(ssl, pathname, urlname)) {
1142                 if(verb) printf("could not write to server\n");
1143                 SSL_free(ssl);
1144                 SSL_CTX_free(sslctx);
1145                 fd_close(fd);
1146                 return NULL;
1147         }
1148         bio = read_http_result(ssl);
1149         TLS_shutdown(fd, ssl, sslctx);
1150         return bio;
1151 }
1152
1153 /**
1154  * Do a HTTPS, HTTP1.1 over TLS, to fetch a file
1155  * @param ip_list: list of IP addresses to use to fetch from.
1156  * @param pathname: pathname of file on server to GET.
1157  * @param urlname: name to pass as the virtual host for this request.
1158  * @param src: if nonNULL, source address to bind to.
1159  * @param use_sni: if SNI will be used.
1160  * @return a memory BIO with the file in it.
1161  */
1162 static BIO*
1163 https(struct ip_list* ip_list, const char* pathname, const char* urlname,
1164         struct ip_list* src, int use_sni)
1165 {
1166         struct ip_list* ip;
1167         BIO* bio = NULL;
1168         /* try random address first, and work through the list */
1169         wipe_ip_usage(ip_list);
1170         while( (ip = pick_random_ip(ip_list)) ) {
1171                 ip->used = 1;
1172                 bio = https_to_ip(ip, pathname, urlname, src, use_sni);
1173                 if(bio) break;
1174         }
1175         if(!bio) {
1176                 if(verb) printf("could not fetch %s\n", pathname);
1177                 exit(0);
1178         } else {
1179                 if(verb) printf("fetched %s (%d bytes)\n",
1180                         pathname, (int)BIO_ctrl_pending(bio));
1181         }
1182         return bio;
1183 }
1184
1185 /** XML parse private data during the parse */
1186 struct xml_data {
1187         /** the parser, reference */
1188         XML_Parser parser;
1189         /** the current tag; malloced; or NULL outside of tags */
1190         char* tag;
1191         /** current date to use during the parse */
1192         time_t date;
1193         /** number of keys usefully read in */
1194         int num_keys;
1195         /** the compiled anchors as DS records */
1196         BIO* ds;
1197
1198         /** do we want to use this anchor? */
1199         int use_key;
1200         /** the current anchor: Zone */
1201         BIO* czone;
1202         /** the current anchor: KeyTag */
1203         BIO* ctag;
1204         /** the current anchor: Algorithm */
1205         BIO* calgo;
1206         /** the current anchor: DigestType */
1207         BIO* cdigtype;
1208         /** the current anchor: Digest*/
1209         BIO* cdigest;
1210 };
1211
1212 /** The BIO for the tag */
1213 static BIO*
1214 xml_selectbio(struct xml_data* data, const char* tag)
1215 {
1216         BIO* b = NULL;
1217         if(strcasecmp(tag, "KeyTag") == 0)
1218                 b = data->ctag;
1219         else if(strcasecmp(tag, "Algorithm") == 0)
1220                 b = data->calgo;
1221         else if(strcasecmp(tag, "DigestType") == 0)
1222                 b = data->cdigtype;
1223         else if(strcasecmp(tag, "Digest") == 0)
1224                 b = data->cdigest;
1225         return b;
1226 }
1227
1228 /**
1229  * XML handle character data, the data inside an element.
1230  * @param userData: xml_data structure
1231  * @param s: the character data.  May not all be in one callback.
1232  *      NOT zero terminated.
1233  * @param len: length of this part of the data.
1234  */
1235 static void
1236 xml_charhandle(void *userData, const XML_Char *s, int len)
1237 {
1238         struct xml_data* data = (struct xml_data*)userData;
1239         BIO* b = NULL;
1240         /* skip characters outside of elements */
1241         if(!data->tag)
1242                 return;
1243         if(verb>=4) {
1244                 int i;
1245                 printf("%s%s charhandle: '",
1246                         data->use_key?"use ":"",
1247                         data->tag?data->tag:"none");
1248                 for(i=0; i<len; i++)
1249                         printf("%c", s[i]);
1250                 printf("'\n");
1251         }
1252         if(strcasecmp(data->tag, "Zone") == 0) {
1253                 if(BIO_write(data->czone, s, len) < 0) {
1254                         if(verb) printf("out of memory in BIO_write\n");
1255                         exit(0);
1256                 }
1257                 return;
1258         }
1259         /* only store if key is used */
1260         if(!data->use_key)
1261                 return;
1262         b = xml_selectbio(data, data->tag);
1263         if(b) {
1264                 if(BIO_write(b, s, len) < 0) {
1265                         if(verb) printf("out of memory in BIO_write\n");
1266                         exit(0);
1267                 }
1268         }
1269 }
1270
1271 /**
1272  * XML fetch value of particular attribute(by name) or NULL if not present.
1273  * @param atts: attribute array (from xml_startelem).
1274  * @param name: name of attribute to look for.
1275  * @return the value or NULL. (ptr into atts).
1276  */
1277 static const XML_Char*
1278 find_att(const XML_Char **atts, const XML_Char* name)
1279 {
1280         int i;
1281         for(i=0; atts[i]; i+=2) {
1282                 if(strcasecmp(atts[i], name) == 0)
1283                         return atts[i+1];
1284         }
1285         return NULL;
1286 }
1287
1288 /**
1289  * XML convert DateTime element to time_t.
1290  * [-]CCYY-MM-DDThh:mm:ss[Z|(+|-)hh:mm]
1291  * (with optional .ssssss fractional seconds)
1292  * @param str: the string
1293  * @return a time_t representation or 0 on failure.
1294  */
1295 static time_t
1296 xml_convertdate(const char* str)
1297 {
1298         time_t t = 0;
1299         struct tm tm;
1300         const char* s;
1301         /* for this application, ignore minus in front;
1302          * only positive dates are expected */
1303         s = str;
1304         if(s[0] == '-') s++;
1305         memset(&tm, 0, sizeof(tm));
1306         /* parse initial content of the string (lots of whitespace allowed) */
1307         s = strptime(s, "%t%Y%t-%t%m%t-%t%d%tT%t%H%t:%t%M%t:%t%S%t", &tm);
1308         if(!s) {
1309                 if(verb) printf("xml_convertdate parse failure %s\n", str);
1310                 return 0;
1311         }
1312         /* parse remainder of date string */
1313         if(*s == '.') {
1314                 /* optional '.' and fractional seconds */
1315                 int frac = 0, n = 0;
1316                 if(sscanf(s+1, "%d%n", &frac, &n) < 1) {
1317                         if(verb) printf("xml_convertdate f failure %s\n", str);
1318                         return 0;
1319                 }
1320                 /* fraction is not used, time_t has second accuracy */
1321                 s++;
1322                 s+=n;
1323         }
1324         if(*s == 'Z' || *s == 'z') {
1325                 /* nothing to do for this */
1326                 s++;
1327         } else if(*s == '+' || *s == '-') {
1328                 /* optional timezone spec: Z or +hh:mm or -hh:mm */
1329                 int hr = 0, mn = 0, n = 0;
1330                 if(sscanf(s+1, "%d:%d%n", &hr, &mn, &n) < 2) {
1331                         if(verb) printf("xml_convertdate tz failure %s\n", str);
1332                         return 0;
1333                 }
1334                 if(*s == '+') {
1335                         tm.tm_hour += hr;
1336                         tm.tm_min += mn;
1337                 } else {
1338                         tm.tm_hour -= hr;
1339                         tm.tm_min -= mn;
1340                 }
1341                 s++;
1342                 s += n;
1343         }
1344         if(*s != 0) {
1345                 /* not ended properly */
1346                 /* but ignore, (lenient) */
1347         }
1348
1349         t = sldns_mktime_from_utc(&tm);
1350         if(t == (time_t)-1) {
1351                 if(verb) printf("xml_convertdate mktime failure\n");
1352                 return 0;
1353         }
1354         return t;
1355 }
1356
1357 /**
1358  * XML handle the KeyDigest start tag, check validity periods.
1359  */
1360 static void
1361 handle_keydigest(struct xml_data* data, const XML_Char **atts)
1362 {
1363         data->use_key = 0;
1364         if(find_att(atts, "validFrom")) {
1365                 time_t from = xml_convertdate(find_att(atts, "validFrom"));
1366                 if(from == 0) {
1367                         if(verb) printf("error: xml cannot be parsed\n");
1368                         exit(0);
1369                 }
1370                 if(data->date < from)
1371                         return;
1372         }
1373         if(find_att(atts, "validUntil")) {
1374                 time_t until = xml_convertdate(find_att(atts, "validUntil"));
1375                 if(until == 0) {
1376                         if(verb) printf("error: xml cannot be parsed\n");
1377                         exit(0);
1378                 }
1379                 if(data->date > until)
1380                         return;
1381         }
1382         /* yes we want to use this key */
1383         data->use_key = 1;
1384         (void)BIO_reset(data->ctag);
1385         (void)BIO_reset(data->calgo);
1386         (void)BIO_reset(data->cdigtype);
1387         (void)BIO_reset(data->cdigest);
1388 }
1389
1390 /** See if XML element equals the zone name */
1391 static int
1392 xml_is_zone_name(BIO* zone, const char* name)
1393 {
1394         char buf[1024];
1395         char* z = NULL;
1396         long zlen;
1397         (void)BIO_seek(zone, 0);
1398         zlen = BIO_get_mem_data(zone, &z);
1399         if(!zlen || !z) return 0;
1400         /* zero terminate */
1401         if(zlen >= (long)sizeof(buf)) return 0;
1402         memmove(buf, z, (size_t)zlen);
1403         buf[zlen] = 0;
1404         /* compare */
1405         return (strncasecmp(buf, name, strlen(name)) == 0);
1406 }
1407
1408 /** 
1409  * XML start of element. This callback is called whenever an XML tag starts.
1410  * XML_Char is UTF8.
1411  * @param userData: the xml_data structure.
1412  * @param name: the tag that starts.
1413  * @param atts: array of strings, pairs of attr = value, ends with NULL.
1414  *      i.e. att[0]="att[1]" att[2]="att[3]" att[4]isNull
1415  */
1416 static void
1417 xml_startelem(void *userData, const XML_Char *name, const XML_Char **atts)
1418 {
1419         struct xml_data* data = (struct xml_data*)userData;
1420         BIO* b;
1421         if(verb>=4) printf("xml tag start '%s'\n", name);
1422         free(data->tag);
1423         data->tag = strdup(name);
1424         if(!data->tag) {
1425                 if(verb) printf("out of memory\n");
1426                 exit(0);
1427         }
1428         if(verb>=4) {
1429                 int i;
1430                 for(i=0; atts[i]; i+=2) {
1431                         printf("  %s='%s'\n", atts[i], atts[i+1]);
1432                 }
1433         }
1434         /* handle attributes to particular types */
1435         if(strcasecmp(name, "KeyDigest") == 0) {
1436                 handle_keydigest(data, atts);
1437                 return;
1438         } else if(strcasecmp(name, "Zone") == 0) {
1439                 (void)BIO_reset(data->czone);
1440                 return;
1441         }
1442
1443         /* for other types we prepare to pick up the data */
1444         if(!data->use_key)
1445                 return;
1446         b = xml_selectbio(data, data->tag);
1447         if(b) {
1448                 /* empty it */
1449                 (void)BIO_reset(b);
1450         }
1451 }
1452
1453 /** Append str to bio */
1454 static void
1455 xml_append_str(BIO* b, const char* s)
1456 {
1457         if(BIO_write(b, s, (int)strlen(s)) < 0) {
1458                 if(verb) printf("out of memory in BIO_write\n");
1459                 exit(0);
1460         }
1461 }
1462
1463 /** Append bio to bio */
1464 static void
1465 xml_append_bio(BIO* b, BIO* a)
1466 {
1467         char* z = NULL;
1468         long i, len;
1469         (void)BIO_seek(a, 0);
1470         len = BIO_get_mem_data(a, &z);
1471         if(!len || !z) {
1472                 if(verb) printf("out of memory in BIO_write\n");
1473                 exit(0);
1474         }
1475         /* remove newlines in the data here */
1476         for(i=0; i<len; i++) {
1477                 if(z[i] == '\r' || z[i] == '\n')
1478                         z[i] = ' ';
1479         }
1480         /* write to BIO */
1481         if(BIO_write(b, z, len) < 0) {
1482                 if(verb) printf("out of memory in BIO_write\n");
1483                 exit(0);
1484         }
1485 }
1486
1487 /** write the parsed xml-DS to the DS list */
1488 static void
1489 xml_append_ds(struct xml_data* data)
1490 {
1491         /* write DS to accumulated DS */
1492         xml_append_str(data->ds, ". IN DS ");
1493         xml_append_bio(data->ds, data->ctag);
1494         xml_append_str(data->ds, " ");
1495         xml_append_bio(data->ds, data->calgo);
1496         xml_append_str(data->ds, " ");
1497         xml_append_bio(data->ds, data->cdigtype);
1498         xml_append_str(data->ds, " ");
1499         xml_append_bio(data->ds, data->cdigest);
1500         xml_append_str(data->ds, "\n");
1501         data->num_keys++;
1502 }
1503
1504 /**
1505  * XML end of element. This callback is called whenever an XML tag ends.
1506  * XML_Char is UTF8.
1507  * @param userData: the xml_data structure
1508  * @param name: the tag that ends.
1509  */
1510 static void
1511 xml_endelem(void *userData, const XML_Char *name)
1512 {
1513         struct xml_data* data = (struct xml_data*)userData;
1514         if(verb>=4) printf("xml tag end   '%s'\n", name);
1515         free(data->tag);
1516         data->tag = NULL;
1517         if(strcasecmp(name, "KeyDigest") == 0) {
1518                 if(data->use_key)
1519                         xml_append_ds(data);
1520                 data->use_key = 0;
1521         } else if(strcasecmp(name, "Zone") == 0) {
1522                 if(!xml_is_zone_name(data->czone, ".")) {
1523                         if(verb) printf("xml not for the right zone\n");
1524                         exit(0);
1525                 }
1526         }
1527 }
1528
1529 /* Stop the parser when an entity declaration is encountered. For safety. */
1530 static void
1531 xml_entitydeclhandler(void *userData,
1532         const XML_Char *ATTR_UNUSED(entityName),
1533         int ATTR_UNUSED(is_parameter_entity),
1534         const XML_Char *ATTR_UNUSED(value), int ATTR_UNUSED(value_length),
1535         const XML_Char *ATTR_UNUSED(base),
1536         const XML_Char *ATTR_UNUSED(systemId),
1537         const XML_Char *ATTR_UNUSED(publicId),
1538         const XML_Char *ATTR_UNUSED(notationName))
1539 {
1540 #if HAVE_DECL_XML_STOPPARSER
1541         (void)XML_StopParser((XML_Parser)userData, XML_FALSE);
1542 #else
1543         (void)userData;
1544 #endif
1545 }
1546
1547 /**
1548  * XML parser setup of the callbacks for the tags
1549  */
1550 static void
1551 xml_parse_setup(XML_Parser parser, struct xml_data* data, time_t now)
1552 {
1553         char buf[1024];
1554         memset(data, 0, sizeof(*data));
1555         XML_SetUserData(parser, data);
1556         data->parser = parser;
1557         data->date = now;
1558         data->ds = BIO_new(BIO_s_mem());
1559         data->ctag = BIO_new(BIO_s_mem());
1560         data->czone = BIO_new(BIO_s_mem());
1561         data->calgo = BIO_new(BIO_s_mem());
1562         data->cdigtype = BIO_new(BIO_s_mem());
1563         data->cdigest = BIO_new(BIO_s_mem());
1564         if(!data->ds || !data->ctag || !data->calgo || !data->czone ||
1565                 !data->cdigtype || !data->cdigest) {
1566                 if(verb) printf("out of memory\n");
1567                 exit(0);
1568         }
1569         snprintf(buf, sizeof(buf), "; created by unbound-anchor on %s",
1570                 ctime(&now));
1571         if(BIO_write(data->ds, buf, (int)strlen(buf)) < 0) {
1572                 if(verb) printf("out of memory\n");
1573                 exit(0);
1574         }
1575         XML_SetEntityDeclHandler(parser, xml_entitydeclhandler);
1576         XML_SetElementHandler(parser, xml_startelem, xml_endelem);
1577         XML_SetCharacterDataHandler(parser, xml_charhandle);
1578 }
1579
1580 /**
1581  * Perform XML parsing of the root-anchors file
1582  * Its format description can be read here
1583  * https://data.iana.org/root-anchors/draft-icann-dnssec-trust-anchor.txt
1584  * It uses libexpat.
1585  * @param xml: BIO with xml data.
1586  * @param now: the current time for checking DS validity periods.
1587  * @return memoryBIO with the DS data in zone format.
1588  *      or NULL if the zone is insecure.
1589  *      (It exit()s on error)
1590  */
1591 static BIO*
1592 xml_parse(BIO* xml, time_t now)
1593 {
1594         char* pp;
1595         int len;
1596         XML_Parser parser;
1597         struct xml_data data;
1598
1599         parser = XML_ParserCreate(NULL);
1600         if(!parser) {
1601                 if(verb) printf("could not XML_ParserCreate\n");
1602                 exit(0);
1603         }
1604
1605         /* setup callbacks */
1606         xml_parse_setup(parser, &data, now);
1607
1608         /* parse it */
1609         (void)BIO_seek(xml, 0);
1610         len = (int)BIO_get_mem_data(xml, &pp);
1611         if(!len || !pp) {
1612                 if(verb) printf("out of memory\n");
1613                 exit(0);
1614         }
1615         if(!XML_Parse(parser, pp, len, 1 /*isfinal*/ )) {
1616                 const char *e = XML_ErrorString(XML_GetErrorCode(parser));
1617                 if(verb) printf("XML_Parse failure %s\n", e?e:"");
1618                 exit(0);
1619         }
1620
1621         /* parsed */
1622         if(verb) printf("XML was parsed successfully, %d keys\n",
1623                         data.num_keys);
1624         free(data.tag);
1625         XML_ParserFree(parser);
1626
1627         if(verb >= 4) {
1628                 (void)BIO_seek(data.ds, 0);
1629                 len = BIO_get_mem_data(data.ds, &pp);
1630                 printf("got DS bio %d: '", len);
1631                 if(!fwrite(pp, (size_t)len, 1, stdout))
1632                         /* compilers do not allow us to ignore fwrite .. */
1633                         fprintf(stderr, "error writing to stdout\n");
1634                 printf("'\n");
1635         }
1636         BIO_free(data.czone);
1637         BIO_free(data.ctag);
1638         BIO_free(data.calgo);
1639         BIO_free(data.cdigtype);
1640         BIO_free(data.cdigest);
1641
1642         if(data.num_keys == 0) {
1643                 /* the root zone seems to have gone insecure */
1644                 BIO_free(data.ds);
1645                 return NULL;
1646         } else {
1647                 return data.ds;
1648         }
1649 }
1650
1651 /* get key usage out of its extension, returns 0 if no key_usage extension */
1652 static unsigned long
1653 get_usage_of_ex(X509* cert)
1654 {
1655         unsigned long val = 0;
1656         ASN1_BIT_STRING* s;
1657         if((s=X509_get_ext_d2i(cert, NID_key_usage, NULL, NULL))) {
1658                 if(s->length > 0) {
1659                         val = s->data[0];
1660                         if(s->length > 1)
1661                                 val |= s->data[1] << 8;
1662                 }
1663                 ASN1_BIT_STRING_free(s);
1664         }
1665         return val;
1666 }
1667
1668 /** get valid signers from the list of signers in the signature */
1669 static STACK_OF(X509)*
1670 get_valid_signers(PKCS7* p7, const char* p7signer)
1671 {
1672         int i;
1673         STACK_OF(X509)* validsigners = sk_X509_new_null();
1674         STACK_OF(X509)* signers = PKCS7_get0_signers(p7, NULL, 0);
1675         unsigned long usage = 0;
1676         if(!validsigners) {
1677                 if(verb) printf("out of memory\n");
1678                 sk_X509_free(signers);
1679                 return NULL;
1680         }
1681         if(!signers) {
1682                 if(verb) printf("no signers in pkcs7 signature\n");
1683                 sk_X509_free(validsigners);
1684                 return NULL;
1685         }
1686         for(i=0; i<sk_X509_num(signers); i++) {
1687                 X509_NAME* nm = X509_get_subject_name(
1688                         sk_X509_value(signers, i));
1689                 char buf[1024];
1690                 if(!nm) {
1691                         if(verb) printf("signer %d: cert has no subject name\n", i);
1692                         continue;
1693                 }
1694                 if(verb && nm) {
1695                         char* nmline = X509_NAME_oneline(nm, buf,
1696                                 (int)sizeof(buf));
1697                         printf("signer %d: Subject: %s\n", i,
1698                                 nmline?nmline:"no subject");
1699                         if(verb >= 3 && X509_NAME_get_text_by_NID(nm,
1700                                 NID_commonName, buf, (int)sizeof(buf)))
1701                                 printf("commonName: %s\n", buf);
1702                         if(verb >= 3 && X509_NAME_get_text_by_NID(nm,
1703                                 NID_pkcs9_emailAddress, buf, (int)sizeof(buf)))
1704                                 printf("emailAddress: %s\n", buf);
1705                 }
1706                 if(verb) {
1707                         int ku_loc = X509_get_ext_by_NID(
1708                                 sk_X509_value(signers, i), NID_key_usage, -1);
1709                         if(verb >= 3 && ku_loc >= 0) {
1710                                 X509_EXTENSION *ex = X509_get_ext(
1711                                         sk_X509_value(signers, i), ku_loc);
1712                                 if(ex) {
1713                                         printf("keyUsage: ");
1714                                         X509V3_EXT_print_fp(stdout, ex, 0, 0);
1715                                         printf("\n");
1716                                 }
1717                         }
1718                 }
1719                 if(!p7signer || strcmp(p7signer, "")==0) {
1720                         /* there is no name to check, return all records */
1721                         if(verb) printf("did not check commonName of signer\n");
1722                 } else {
1723                         if(!X509_NAME_get_text_by_NID(nm,
1724                                 NID_pkcs9_emailAddress,
1725                                 buf, (int)sizeof(buf))) {
1726                                 if(verb) printf("removed cert with no name\n");
1727                                 continue; /* no name, no use */
1728                         }
1729                         if(strcmp(buf, p7signer) != 0) {
1730                                 if(verb) printf("removed cert with wrong name\n");
1731                                 continue; /* wrong name, skip it */
1732                         }
1733                 }
1734
1735                 /* check that the key usage allows digital signatures
1736                  * (the p7s) */
1737                 usage = get_usage_of_ex(sk_X509_value(signers, i));
1738                 if(!(usage & KU_DIGITAL_SIGNATURE)) {
1739                         if(verb) printf("removed cert with no key usage Digital Signature allowed\n");
1740                         continue;
1741                 }
1742
1743                 /* we like this cert, add it to our list of valid
1744                  * signers certificates */
1745                 sk_X509_push(validsigners, sk_X509_value(signers, i));
1746         }
1747         sk_X509_free(signers);
1748         return validsigners;
1749 }
1750
1751 /** verify a PKCS7 signature, false on failure */
1752 static int
1753 verify_p7sig(BIO* data, BIO* p7s, STACK_OF(X509)* trust, const char* p7signer)
1754 {
1755         PKCS7* p7;
1756         X509_STORE *store = X509_STORE_new();
1757         STACK_OF(X509)* validsigners;
1758         int secure = 0;
1759         int i;
1760 #ifdef X509_V_FLAG_CHECK_SS_SIGNATURE
1761         X509_VERIFY_PARAM* param = X509_VERIFY_PARAM_new();
1762         if(!param) {
1763                 if(verb) printf("out of memory\n");
1764                 X509_STORE_free(store);
1765                 return 0;
1766         }
1767         /* do the selfcheck on the root certificate; it checks that the
1768          * input is valid */
1769         X509_VERIFY_PARAM_set_flags(param, X509_V_FLAG_CHECK_SS_SIGNATURE);
1770         if(store) X509_STORE_set1_param(store, param);
1771 #endif
1772         if(!store) {
1773                 if(verb) printf("out of memory\n");
1774 #ifdef X509_V_FLAG_CHECK_SS_SIGNATURE
1775                 X509_VERIFY_PARAM_free(param);
1776 #endif
1777                 return 0;
1778         }
1779 #ifdef X509_V_FLAG_CHECK_SS_SIGNATURE
1780         X509_VERIFY_PARAM_free(param);
1781 #endif
1782
1783         (void)BIO_seek(p7s, 0);
1784         (void)BIO_seek(data, 0);
1785
1786         /* convert p7s to p7 (the signature) */
1787         p7 = d2i_PKCS7_bio(p7s, NULL);
1788         if(!p7) {
1789                 if(verb) printf("could not parse p7s signature file\n");
1790                 X509_STORE_free(store);
1791                 return 0;
1792         }
1793         if(verb >= 2) printf("parsed the PKCS7 signature\n");
1794
1795         /* convert trust to trusted certificate store */
1796         for(i=0; i<sk_X509_num(trust); i++) {
1797                 if(!X509_STORE_add_cert(store, sk_X509_value(trust, i))) {
1798                         if(verb) printf("failed X509_STORE_add_cert\n");
1799                         X509_STORE_free(store);
1800                         PKCS7_free(p7);
1801                         return 0;
1802                 }
1803         }
1804         if(verb >= 2) printf("setup the X509_STORE\n");
1805
1806         /* check what is in the Subject name of the certificates,
1807          * and build a stack that contains only the right certificates */
1808         validsigners = get_valid_signers(p7, p7signer);
1809         if(!validsigners) {
1810                         X509_STORE_free(store);
1811                         PKCS7_free(p7);
1812                         return 0;
1813         }
1814         if(PKCS7_verify(p7, validsigners, store, data, NULL, PKCS7_NOINTERN) == 1) {
1815                 secure = 1;
1816                 if(verb) printf("the PKCS7 signature verified\n");
1817         } else {
1818                 if(verb) {
1819                         ERR_print_errors_fp(stdout);
1820                 }
1821         }
1822
1823         sk_X509_free(validsigners);
1824         X509_STORE_free(store);
1825         PKCS7_free(p7);
1826         return secure;
1827 }
1828
1829 /** write unsigned root anchor file, a 5011 revoked tp */
1830 static void
1831 write_unsigned_root(const char* root_anchor_file)
1832 {
1833         FILE* out;
1834         time_t now = time(NULL);
1835         out = fopen(root_anchor_file, "w");
1836         if(!out) {
1837                 if(verb) printf("%s: %s\n", root_anchor_file, strerror(errno));
1838                 return;
1839         }
1840         if(fprintf(out, "; autotrust trust anchor file\n"
1841                 ";;REVOKED\n"
1842                 ";;id: . 1\n"
1843                 "; This file was written by unbound-anchor on %s"
1844                 "; It indicates that the root does not use DNSSEC\n"
1845                 "; to restart DNSSEC overwrite this file with a\n"
1846                 "; valid trustanchor or (empty-it and run unbound-anchor)\n"
1847                 , ctime(&now)) < 0) {
1848                 if(verb) printf("failed to write 'unsigned' to %s\n",
1849                         root_anchor_file);
1850                 if(verb && errno != 0) printf("%s\n", strerror(errno));
1851         }
1852         fflush(out);
1853 #ifdef HAVE_FSYNC
1854         fsync(fileno(out));
1855 #else
1856         FlushFileBuffers((HANDLE)_get_osfhandle(_fileno(out)));
1857 #endif
1858         fclose(out);
1859 }
1860
1861 /** write root anchor file */
1862 static void
1863 write_root_anchor(const char* root_anchor_file, BIO* ds)
1864 {
1865         char* pp = NULL;
1866         int len;
1867         FILE* out;
1868         (void)BIO_seek(ds, 0);
1869         len = BIO_get_mem_data(ds, &pp);
1870         if(!len || !pp) {
1871                 if(verb) printf("out of memory\n");
1872                 return;
1873         }
1874         out = fopen(root_anchor_file, "w");
1875         if(!out) {
1876                 if(verb) printf("%s: %s\n", root_anchor_file, strerror(errno));
1877                 return;
1878         }
1879         if(fwrite(pp, (size_t)len, 1, out) != 1) {
1880                 if(verb) printf("failed to write all data to %s\n",
1881                         root_anchor_file);
1882                 if(verb && errno != 0) printf("%s\n", strerror(errno));
1883         }
1884         fflush(out);
1885 #ifdef HAVE_FSYNC
1886         fsync(fileno(out));
1887 #else
1888         FlushFileBuffers((HANDLE)_get_osfhandle(_fileno(out)));
1889 #endif
1890         fclose(out);
1891 }
1892
1893 /** Perform the verification and update of the trustanchor file */
1894 static void
1895 verify_and_update_anchor(const char* root_anchor_file, BIO* xml, BIO* p7s,
1896         STACK_OF(X509)* cert, const char* p7signer)
1897 {
1898         BIO* ds;
1899
1900         /* verify xml file */
1901         if(!verify_p7sig(xml, p7s, cert, p7signer)) {
1902                 printf("the PKCS7 signature failed\n");
1903                 exit(0);
1904         }
1905
1906         /* parse the xml file into DS records */
1907         ds = xml_parse(xml, time(NULL));
1908         if(!ds) {
1909                 /* the root zone is unsigned now */
1910                 write_unsigned_root(root_anchor_file);
1911         } else {
1912                 /* reinstate 5011 tracking */
1913                 write_root_anchor(root_anchor_file, ds);
1914         }
1915         BIO_free(ds);
1916 }
1917
1918 #ifdef USE_WINSOCK
1919 static void do_wsa_cleanup(void) { WSACleanup(); }
1920 #endif
1921
1922 /** perform actual certupdate work */
1923 static int
1924 do_certupdate(const char* root_anchor_file, const char* root_cert_file,
1925         const char* urlname, const char* xmlname, const char* p7sname,
1926         const char* p7signer, const char* res_conf, const char* root_hints,
1927         const char* debugconf, const char* srcaddr, int ip4only, int ip6only,
1928         int port, int use_sni)
1929
1930 {
1931         STACK_OF(X509)* cert;
1932         BIO *xml, *p7s;
1933         struct ip_list* ip_list = NULL;
1934         struct ip_list* src = NULL;
1935
1936         /* read pem file or provide builtin */
1937         cert = read_cert_or_builtin(root_cert_file);
1938
1939         /* lookup A, AAAA for the urlname (or parse urlname if IP address) */
1940         ip_list = resolve_name(urlname, port, res_conf, root_hints, debugconf,
1941                 srcaddr, ip4only, ip6only);
1942
1943         if(srcaddr && !(src = parse_ip_addr(srcaddr, 0))) {
1944                 if(verb) printf("cannot parse source address: %s\n", srcaddr);
1945                 exit(0);
1946         }
1947
1948 #ifdef USE_WINSOCK
1949         if(1) { /* libunbound finished, startup WSA for the https connection */
1950                 WSADATA wsa_data;
1951                 int r;
1952                 if((r = WSAStartup(MAKEWORD(2,2), &wsa_data)) != 0) {
1953                         if(verb) printf("WSAStartup failed: %s\n",
1954                                 wsa_strerror(r));
1955                         exit(0);
1956                 }
1957                 atexit(&do_wsa_cleanup);
1958         }
1959 #endif
1960
1961         /* fetch the necessary files over HTTPS */
1962         xml = https(ip_list, xmlname, urlname, src, use_sni);
1963         p7s = https(ip_list, p7sname, urlname, src, use_sni);
1964
1965         /* verify and update the root anchor */
1966         verify_and_update_anchor(root_anchor_file, xml, p7s, cert, p7signer);
1967         if(verb) printf("success: the anchor has been updated "
1968                         "using the cert\n");
1969
1970         BIO_free(xml);
1971         BIO_free(p7s);
1972 #ifndef S_SPLINT_S
1973         sk_X509_pop_free(cert, X509_free);
1974 #endif
1975         ip_list_free(ip_list);
1976         return 1;
1977 }
1978
1979 /**
1980  * Try to read the root RFC5011 autotrust anchor file,
1981  * @param file: filename.
1982  * @return:
1983  *      0 if does not exist or empty
1984  *      1 if trust-point-revoked-5011
1985  *      2 if it is OK.
1986  */
1987 static int
1988 try_read_anchor(const char* file)
1989 {
1990         int empty = 1;
1991         char line[10240];
1992         char* p;
1993         FILE* in = fopen(file, "r");
1994         if(!in) {
1995                 /* only if the file does not exist, can we fix it */
1996                 if(errno != ENOENT) {
1997                         if(verb) printf("%s: %s\n", file, strerror(errno));
1998                         if(verb) printf("error: cannot access the file\n");
1999                         exit(0);
2000                 }
2001                 if(verb) printf("%s does not exist\n", file);
2002                 return 0;
2003         }
2004         while(fgets(line, (int)sizeof(line), in)) {
2005                 line[sizeof(line)-1] = 0;
2006                 if(strncmp(line, ";;REVOKED", 9) == 0) {
2007                         fclose(in);
2008                         if(verb) printf("%s : the trust point is revoked\n"
2009                                 "and the zone is considered unsigned.\n"
2010                                 "if you wish to re-enable, delete the file\n",
2011                                 file);
2012                         return 1;
2013                 }
2014                 p=line;
2015                 while(*p == ' ' || *p == '\t')
2016                         p++;
2017                 if(p[0]==0 || p[0]=='\n' || p[0]==';') continue;
2018                 /* this line is a line of content */
2019                 empty = 0;
2020         }
2021         fclose(in);
2022         if(empty) {
2023                 if(verb) printf("%s is empty\n", file);
2024                 return 0;
2025         }
2026         if(verb) printf("%s has content\n", file);
2027         return 2;
2028 }
2029
2030 /** Write the builtin root anchor to a file */
2031 static void
2032 write_builtin_anchor(const char* file)
2033 {
2034         const char* builtin_root_anchor = get_builtin_ds();
2035         FILE* out = fopen(file, "w");
2036         if(!out) {
2037                 if(verb) printf("%s: %s\n", file, strerror(errno));
2038                 if(verb) printf("  could not write builtin anchor\n");
2039                 return;
2040         }
2041         if(!fwrite(builtin_root_anchor, strlen(builtin_root_anchor), 1, out)) {
2042                 if(verb) printf("%s: %s\n", file, strerror(errno));
2043                 if(verb) printf("  could not complete write builtin anchor\n");
2044         }
2045         fclose(out);
2046 }
2047
2048 /** 
2049  * Check the root anchor file.
2050  * If does not exist, provide builtin and write file.
2051  * If empty, provide builtin and write file.
2052  * If trust-point-revoked-5011 file: make the program exit.
2053  * @param root_anchor_file: filename of the root anchor.
2054  * @param used_builtin: set to 1 if the builtin is written.
2055  * @return 0 if trustpoint is insecure, 1 on success.  Exit on failure.
2056  */
2057 static int
2058 provide_builtin(const char* root_anchor_file, int* used_builtin)
2059 {
2060         /* try to read it */
2061         switch(try_read_anchor(root_anchor_file))
2062         {
2063                 case 0: /* no exist or empty */
2064                         write_builtin_anchor(root_anchor_file);
2065                         *used_builtin = 1;
2066                         break;
2067                 case 1: /* revoked tp */
2068                         return 0;       
2069                 case 2: /* it is fine */
2070                 default:
2071                         break;
2072         }
2073         return 1;
2074 }
2075
2076 /**
2077  * add an autotrust anchor for the root to the context
2078  */
2079 static void
2080 add_5011_probe_root(struct ub_ctx* ctx, const char* root_anchor_file)
2081 {
2082         int r;
2083         r = ub_ctx_set_option(ctx, "auto-trust-anchor-file:", root_anchor_file);
2084         if(r) {
2085                 if(verb) printf("add 5011 probe to ctx: %s\n", ub_strerror(r));
2086                 ub_ctx_delete(ctx);
2087                 exit(0);
2088         }
2089 }
2090
2091 /**
2092  * Prime the root key and return the result.  Exit on error.
2093  * @param ctx: the unbound context to perform the priming with.
2094  * @return: the result of the prime, on error it exit()s.
2095  */
2096 static struct ub_result*
2097 prime_root_key(struct ub_ctx* ctx)
2098 {
2099         struct ub_result* res = NULL;
2100         int r;
2101         r = ub_resolve(ctx, ".", LDNS_RR_TYPE_DNSKEY, LDNS_RR_CLASS_IN, &res);
2102         if(r) {
2103                 if(verb) printf("resolve DNSKEY: %s\n", ub_strerror(r));
2104                 ub_ctx_delete(ctx);
2105                 exit(0);
2106         }
2107         if(!res) {
2108                 if(verb) printf("out of memory\n");
2109                 ub_ctx_delete(ctx);
2110                 exit(0);
2111         }
2112         return res;
2113 }
2114
2115 /** see if ADDPEND keys exist in autotrust file (if possible) */
2116 static int
2117 read_if_pending_keys(const char* file)
2118 {
2119         FILE* in = fopen(file, "r");
2120         char line[8192];
2121         if(!in) {
2122                 if(verb>=2) printf("%s: %s\n", file, strerror(errno));
2123                 return 0;
2124         }
2125         while(fgets(line, (int)sizeof(line), in)) {
2126                 if(line[0]==';') continue;
2127                 if(strstr(line, "[ ADDPEND ]")) {
2128                         fclose(in);
2129                         if(verb) printf("RFC5011-state has ADDPEND keys\n");
2130                         return 1;
2131                 }
2132         }
2133         fclose(in);
2134         return 0;
2135 }
2136
2137 /** read last successful probe time from autotrust file (if possible) */
2138 static int32_t
2139 read_last_success_time(const char* file)
2140 {
2141         FILE* in = fopen(file, "r");
2142         char line[1024];
2143         if(!in) {
2144                 if(verb) printf("%s: %s\n", file, strerror(errno));
2145                 return 0;
2146         }
2147         while(fgets(line, (int)sizeof(line), in)) {
2148                 if(strncmp(line, ";;last_success: ", 16) == 0) {
2149                         char* e;
2150                         time_t x = (unsigned int)strtol(line+16, &e, 10);
2151                         fclose(in);
2152                         if(line+16 == e) {
2153                                 if(verb) printf("failed to parse "
2154                                         "last_success probe time\n");
2155                                 return 0;
2156                         }
2157                         if(verb) printf("last successful probe: %s", ctime(&x));
2158                         return (int32_t)x;
2159                 }
2160         }
2161         fclose(in);
2162         if(verb) printf("no last_success probe time in anchor file\n");
2163         return 0;
2164 }
2165
2166 /**
2167  * Read autotrust 5011 probe file and see if the date
2168  * compared to the current date allows a certupdate.
2169  * If the last successful probe was recent then 5011 cannot be behind,
2170  * and the failure cannot be solved with a certupdate.
2171  * The debugconf is to validation-override the date for testing.
2172  * @param root_anchor_file: filename of root key
2173  * @return true if certupdate is ok.
2174  */
2175 static int
2176 probe_date_allows_certupdate(const char* root_anchor_file)
2177 {
2178         int has_pending_keys = read_if_pending_keys(root_anchor_file);
2179         int32_t last_success = read_last_success_time(root_anchor_file);
2180         int32_t now = (int32_t)time(NULL);
2181         int32_t leeway = 30 * 24 * 3600; /* 30 days leeway */
2182         /* if the date is before 2010-07-15:00.00.00 then the root has not
2183          * been signed yet, and thus we refuse to take action. */
2184         if(time(NULL) < xml_convertdate("2010-07-15T00:00:00")) {
2185                 if(verb) printf("the date is before the root was first signed,"
2186                         " please correct the clock\n");
2187                 return 0;
2188         }
2189         if(last_success == 0)
2190                 return 1; /* no probe time */
2191         if(has_pending_keys)
2192                 return 1; /* key in ADDPEND state, a previous probe has
2193                 inserted that, and it was present in all recent probes,
2194                 but it has not become active.  The 30 day timer may not have
2195                 expired, but we know(for sure) there is a rollover going on.
2196                 If we only managed to pickup the new key on its last day
2197                 of announcement (for example) this can happen. */
2198         if(now - last_success < 0) {
2199                 if(verb) printf("the last successful probe is in the future,"
2200                         " clock was modified\n");
2201                 return 0;
2202         }
2203         if(now - last_success >= leeway) {
2204                 if(verb) printf("the last successful probe was more than 30 "
2205                         "days ago\n");
2206                 return 1;
2207         }
2208         if(verb) printf("the last successful probe is recent\n");
2209         return 0;
2210 }
2211
2212 static struct ub_result *
2213 fetch_root_key(const char* root_anchor_file, const char* res_conf,
2214         const char* root_hints, const char* debugconf, const char* srcaddr,
2215         int ip4only, int ip6only)
2216 {
2217         struct ub_ctx* ctx;
2218         struct ub_result* dnskey;
2219
2220         ctx = create_unbound_context(res_conf, root_hints, debugconf,
2221                 srcaddr, ip4only, ip6only);
2222         add_5011_probe_root(ctx, root_anchor_file);
2223         dnskey = prime_root_key(ctx);
2224         ub_ctx_delete(ctx);
2225         return dnskey;
2226 }
2227
2228 /** perform the unbound-anchor work */
2229 static int
2230 do_root_update_work(const char* root_anchor_file, const char* root_cert_file,
2231         const char* urlname, const char* xmlname, const char* p7sname,
2232         const char* p7signer, const char* res_conf, const char* root_hints,
2233         const char* debugconf, const char* srcaddr, int ip4only, int ip6only, 
2234         int force, int res_conf_fallback, int port, int use_sni)
2235 {
2236         struct ub_result* dnskey;
2237         int used_builtin = 0;
2238         int rcode;
2239
2240         /* see if builtin rootanchor needs to be provided, or if
2241          * rootanchor is 'revoked-trust-point' */
2242         if(!provide_builtin(root_anchor_file, &used_builtin))
2243                 return 0;
2244
2245         /* make unbound context with 5011-probe for root anchor,
2246          * and probe . DNSKEY */
2247         dnskey = fetch_root_key(root_anchor_file, res_conf,
2248                 root_hints, debugconf, srcaddr, ip4only, ip6only);
2249         rcode = dnskey->rcode;
2250
2251         if (res_conf_fallback && res_conf && !dnskey->secure) {
2252                 if (verb) printf("%s failed, retrying direct\n", res_conf);
2253                 ub_resolve_free(dnskey);
2254                 /* try direct query without res_conf */
2255                 dnskey = fetch_root_key(root_anchor_file, NULL,
2256                         root_hints, debugconf, srcaddr, ip4only, ip6only);
2257                 if (rcode != 0 && dnskey->rcode == 0) {
2258                         res_conf = NULL;
2259                         rcode = 0;
2260                 }
2261         }
2262
2263         /* if secure: exit */
2264         if(dnskey->secure && !force) {
2265                 if(verb) printf("success: the anchor is ok\n");
2266                 ub_resolve_free(dnskey);
2267                 return used_builtin;
2268         }
2269         if(force && verb) printf("debug cert update forced\n");
2270         ub_resolve_free(dnskey);
2271
2272         /* if not (and NOERROR): check date and do certupdate */
2273         if((rcode == 0 &&
2274                 probe_date_allows_certupdate(root_anchor_file)) || force) {
2275                 if(do_certupdate(root_anchor_file, root_cert_file, urlname,
2276                         xmlname, p7sname, p7signer, res_conf, root_hints,
2277                         debugconf, srcaddr, ip4only, ip6only, port, use_sni))
2278                         return 1;
2279                 return used_builtin;
2280         }
2281         if(verb) printf("fail: the anchor is NOT ok and could not be fixed\n");
2282         return used_builtin;
2283 }
2284
2285 /** getopt global, in case header files fail to declare it. */
2286 extern int optind;
2287 /** getopt global, in case header files fail to declare it. */
2288 extern char* optarg;
2289
2290 /** Main routine for unbound-anchor */
2291 int main(int argc, char* argv[])
2292 {
2293         int c;
2294         const char* root_anchor_file = ROOT_ANCHOR_FILE;
2295         const char* root_cert_file = ROOT_CERT_FILE;
2296         const char* urlname = URLNAME;
2297         const char* xmlname = XMLNAME;
2298         const char* p7sname = P7SNAME;
2299         const char* p7signer = P7SIGNER;
2300         const char* res_conf = NULL;
2301         const char* root_hints = NULL;
2302         const char* debugconf = NULL;
2303         const char* srcaddr = NULL;
2304         int dolist=0, ip4only=0, ip6only=0, force=0, port = HTTPS_PORT;
2305         int res_conf_fallback = 0;
2306         int use_sni = 1;
2307         /* parse the options */
2308         while( (c=getopt(argc, argv, "46C:FRSP:a:b:c:f:hln:r:s:u:vx:")) != -1) {
2309                 switch(c) {
2310                 case 'l':
2311                         dolist = 1;
2312                         break;
2313                 case '4':
2314                         ip4only = 1;
2315                         break;
2316                 case '6':
2317                         ip6only = 1;
2318                         break;
2319                 case 'a':
2320                         root_anchor_file = optarg;
2321                         break;
2322                 case 'b':
2323                         srcaddr = optarg;
2324                         break;
2325                 case 'c':
2326                         root_cert_file = optarg;
2327                         break;
2328                 case 'u':
2329                         urlname = optarg;
2330                         break;
2331                 case 'S':
2332                         use_sni = 0;
2333                         break;
2334                 case 'x':
2335                         xmlname = optarg;
2336                         break;
2337                 case 's':
2338                         p7sname = optarg;
2339                         break;
2340                 case 'n':
2341                         p7signer = optarg;
2342                         break;
2343                 case 'f':
2344                         res_conf = optarg;
2345                         break;
2346                 case 'r':
2347                         root_hints = optarg;
2348                         break;
2349                 case 'R':
2350                         res_conf_fallback = 1;
2351                         break;
2352                 case 'C':
2353                         debugconf = optarg;
2354                         break;
2355                 case 'F':
2356                         force = 1;
2357                         break;
2358                 case 'P':
2359                         port = atoi(optarg);
2360                         break;
2361                 case 'v':
2362                         verb++;
2363                         break;
2364                 case '?':
2365                 case 'h':
2366                 default:
2367                         usage();
2368                 }
2369         }
2370         argc -= optind;
2371         /* argv += optind; not using further arguments */
2372         if(argc != 0)
2373                 usage();
2374
2375 #ifdef HAVE_ERR_LOAD_CRYPTO_STRINGS
2376         ERR_load_crypto_strings();
2377 #endif
2378 #if OPENSSL_VERSION_NUMBER < 0x10100000 || !defined(HAVE_OPENSSL_INIT_SSL)
2379         ERR_load_SSL_strings();
2380 #endif
2381 #if OPENSSL_VERSION_NUMBER < 0x10100000 || !defined(HAVE_OPENSSL_INIT_CRYPTO)
2382 #  ifndef S_SPLINT_S
2383         OpenSSL_add_all_algorithms();
2384 #  endif
2385 #else
2386         OPENSSL_init_crypto(OPENSSL_INIT_ADD_ALL_CIPHERS
2387                 | OPENSSL_INIT_ADD_ALL_DIGESTS
2388                 | OPENSSL_INIT_LOAD_CRYPTO_STRINGS, NULL);
2389 #endif
2390 #if OPENSSL_VERSION_NUMBER < 0x10100000 || !defined(HAVE_OPENSSL_INIT_SSL)
2391         (void)SSL_library_init();
2392 #else
2393         (void)OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS, NULL);
2394 #endif
2395
2396         if(dolist) do_list_builtin();
2397
2398         return do_root_update_work(root_anchor_file, root_cert_file, urlname,
2399                 xmlname, p7sname, p7signer, res_conf, root_hints, debugconf,
2400                 srcaddr, ip4only, ip6only, force, res_conf_fallback, port, use_sni);
2401 }