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