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