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