xref: /freebsd/contrib/unbound/smallapp/unbound-anchor.c (revision c6a33c8e88c5684876e670c8189d03ad25108d8a)
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  * unneccesary 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 	(void)XML_StopParser((XML_Parser)userData, XML_FALSE);
1524 }
1525 
1526 /**
1527  * XML parser setup of the callbacks for the tags
1528  */
1529 static void
1530 xml_parse_setup(XML_Parser parser, struct xml_data* data, time_t now)
1531 {
1532 	char buf[1024];
1533 	memset(data, 0, sizeof(*data));
1534 	XML_SetUserData(parser, data);
1535 	data->parser = parser;
1536 	data->date = now;
1537 	data->ds = BIO_new(BIO_s_mem());
1538 	data->ctag = BIO_new(BIO_s_mem());
1539 	data->czone = BIO_new(BIO_s_mem());
1540 	data->calgo = BIO_new(BIO_s_mem());
1541 	data->cdigtype = BIO_new(BIO_s_mem());
1542 	data->cdigest = BIO_new(BIO_s_mem());
1543 	if(!data->ds || !data->ctag || !data->calgo || !data->czone ||
1544 		!data->cdigtype || !data->cdigest) {
1545 		if(verb) printf("out of memory\n");
1546 		exit(0);
1547 	}
1548 	snprintf(buf, sizeof(buf), "; created by unbound-anchor on %s",
1549 		ctime(&now));
1550 	if(BIO_write(data->ds, buf, (int)strlen(buf)) < 0) {
1551 		if(verb) printf("out of memory\n");
1552 		exit(0);
1553 	}
1554 	XML_SetEntityDeclHandler(parser, xml_entitydeclhandler);
1555 	XML_SetElementHandler(parser, xml_startelem, xml_endelem);
1556 	XML_SetCharacterDataHandler(parser, xml_charhandle);
1557 }
1558 
1559 /**
1560  * Perform XML parsing of the root-anchors file
1561  * Its format description can be read here
1562  * https://data.iana.org/root-anchors/draft-icann-dnssec-trust-anchor.txt
1563  * It uses libexpat.
1564  * @param xml: BIO with xml data.
1565  * @param now: the current time for checking DS validity periods.
1566  * @return memoryBIO with the DS data in zone format.
1567  * 	or NULL if the zone is insecure.
1568  * 	(It exit()s on error)
1569  */
1570 static BIO*
1571 xml_parse(BIO* xml, time_t now)
1572 {
1573 	char* pp;
1574 	int len;
1575 	XML_Parser parser;
1576 	struct xml_data data;
1577 
1578 	parser = XML_ParserCreate(NULL);
1579 	if(!parser) {
1580 		if(verb) printf("could not XML_ParserCreate\n");
1581 		exit(0);
1582 	}
1583 
1584 	/* setup callbacks */
1585 	xml_parse_setup(parser, &data, now);
1586 
1587 	/* parse it */
1588 	(void)BIO_reset(xml);
1589 	len = (int)BIO_get_mem_data(xml, &pp);
1590 	if(!len || !pp) {
1591 		if(verb) printf("out of memory\n");
1592 		exit(0);
1593 	}
1594 	if(!XML_Parse(parser, pp, len, 1 /*isfinal*/ )) {
1595 		const char *e = XML_ErrorString(XML_GetErrorCode(parser));
1596 		if(verb) printf("XML_Parse failure %s\n", e?e:"");
1597 		exit(0);
1598 	}
1599 
1600 	/* parsed */
1601 	if(verb) printf("XML was parsed successfully, %d keys\n",
1602 			data.num_keys);
1603 	free(data.tag);
1604 	XML_ParserFree(parser);
1605 
1606 	if(verb >= 4) {
1607 		(void)BIO_seek(data.ds, 0);
1608 		len = BIO_get_mem_data(data.ds, &pp);
1609 		printf("got DS bio %d: '", len);
1610 		if(!fwrite(pp, (size_t)len, 1, stdout))
1611 			/* compilers do not allow us to ignore fwrite .. */
1612 			fprintf(stderr, "error writing to stdout\n");
1613 		printf("'\n");
1614 	}
1615 	BIO_free(data.czone);
1616 	BIO_free(data.ctag);
1617 	BIO_free(data.calgo);
1618 	BIO_free(data.cdigtype);
1619 	BIO_free(data.cdigest);
1620 
1621 	if(data.num_keys == 0) {
1622 		/* the root zone seems to have gone insecure */
1623 		BIO_free(data.ds);
1624 		return NULL;
1625 	} else {
1626 		return data.ds;
1627 	}
1628 }
1629 
1630 /* get key usage out of its extension, returns 0 if no key_usage extension */
1631 static unsigned long
1632 get_usage_of_ex(X509* cert)
1633 {
1634 	unsigned long val = 0;
1635 	ASN1_BIT_STRING* s;
1636 	if((s=X509_get_ext_d2i(cert, NID_key_usage, NULL, NULL))) {
1637 		if(s->length > 0) {
1638 			val = s->data[0];
1639 			if(s->length > 1)
1640 				val |= s->data[1] << 8;
1641 		}
1642 		ASN1_BIT_STRING_free(s);
1643 	}
1644 	return val;
1645 }
1646 
1647 /** get valid signers from the list of signers in the signature */
1648 static STACK_OF(X509)*
1649 get_valid_signers(PKCS7* p7, const char* p7signer)
1650 {
1651 	int i;
1652 	STACK_OF(X509)* validsigners = sk_X509_new_null();
1653 	STACK_OF(X509)* signers = PKCS7_get0_signers(p7, NULL, 0);
1654 	unsigned long usage = 0;
1655 	if(!validsigners) {
1656 		if(verb) printf("out of memory\n");
1657 		sk_X509_free(signers);
1658 		return NULL;
1659 	}
1660 	if(!signers) {
1661 		if(verb) printf("no signers in pkcs7 signature\n");
1662 		sk_X509_free(validsigners);
1663 		return NULL;
1664 	}
1665 	for(i=0; i<sk_X509_num(signers); i++) {
1666 		X509_NAME* nm = X509_get_subject_name(
1667 			sk_X509_value(signers, i));
1668 		char buf[1024];
1669 		if(!nm) {
1670 			if(verb) printf("signer %d: cert has no subject name\n", i);
1671 			continue;
1672 		}
1673 		if(verb && nm) {
1674 			char* nmline = X509_NAME_oneline(nm, buf,
1675 				(int)sizeof(buf));
1676 			printf("signer %d: Subject: %s\n", i,
1677 				nmline?nmline:"no subject");
1678 			if(verb >= 3 && X509_NAME_get_text_by_NID(nm,
1679 				NID_commonName, buf, (int)sizeof(buf)))
1680 				printf("commonName: %s\n", buf);
1681 			if(verb >= 3 && X509_NAME_get_text_by_NID(nm,
1682 				NID_pkcs9_emailAddress, buf, (int)sizeof(buf)))
1683 				printf("emailAddress: %s\n", buf);
1684 		}
1685 		if(verb) {
1686 			int ku_loc = X509_get_ext_by_NID(
1687 				sk_X509_value(signers, i), NID_key_usage, -1);
1688 			if(verb >= 3 && ku_loc >= 0) {
1689 				X509_EXTENSION *ex = X509_get_ext(
1690 					sk_X509_value(signers, i), ku_loc);
1691 				if(ex) {
1692 					printf("keyUsage: ");
1693 					X509V3_EXT_print_fp(stdout, ex, 0, 0);
1694 					printf("\n");
1695 				}
1696 			}
1697 		}
1698 		if(!p7signer || strcmp(p7signer, "")==0) {
1699 			/* there is no name to check, return all records */
1700 			if(verb) printf("did not check commonName of signer\n");
1701 		} else {
1702 			if(!X509_NAME_get_text_by_NID(nm,
1703 				NID_pkcs9_emailAddress,
1704 				buf, (int)sizeof(buf))) {
1705 				if(verb) printf("removed cert with no name\n");
1706 				continue; /* no name, no use */
1707 			}
1708 			if(strcmp(buf, p7signer) != 0) {
1709 				if(verb) printf("removed cert with wrong name\n");
1710 				continue; /* wrong name, skip it */
1711 			}
1712 		}
1713 
1714 		/* check that the key usage allows digital signatures
1715 		 * (the p7s) */
1716 		usage = get_usage_of_ex(sk_X509_value(signers, i));
1717 		if(!(usage & KU_DIGITAL_SIGNATURE)) {
1718 			if(verb) printf("removed cert with no key usage Digital Signature allowed\n");
1719 			continue;
1720 		}
1721 
1722 		/* we like this cert, add it to our list of valid
1723 		 * signers certificates */
1724 		sk_X509_push(validsigners, sk_X509_value(signers, i));
1725 	}
1726 	sk_X509_free(signers);
1727 	return validsigners;
1728 }
1729 
1730 /** verify a PKCS7 signature, false on failure */
1731 static int
1732 verify_p7sig(BIO* data, BIO* p7s, STACK_OF(X509)* trust, const char* p7signer)
1733 {
1734 	PKCS7* p7;
1735 	X509_STORE *store = X509_STORE_new();
1736 	STACK_OF(X509)* validsigners;
1737 	int secure = 0;
1738 	int i;
1739 #ifdef X509_V_FLAG_CHECK_SS_SIGNATURE
1740 	X509_VERIFY_PARAM* param = X509_VERIFY_PARAM_new();
1741 	if(!param) {
1742 		if(verb) printf("out of memory\n");
1743 		X509_STORE_free(store);
1744 		return 0;
1745 	}
1746 	/* do the selfcheck on the root certificate; it checks that the
1747 	 * input is valid */
1748 	X509_VERIFY_PARAM_set_flags(param, X509_V_FLAG_CHECK_SS_SIGNATURE);
1749 	if(store) X509_STORE_set1_param(store, param);
1750 #endif
1751 	if(!store) {
1752 		if(verb) printf("out of memory\n");
1753 #ifdef X509_V_FLAG_CHECK_SS_SIGNATURE
1754 		X509_VERIFY_PARAM_free(param);
1755 #endif
1756 		return 0;
1757 	}
1758 #ifdef X509_V_FLAG_CHECK_SS_SIGNATURE
1759 	X509_VERIFY_PARAM_free(param);
1760 #endif
1761 
1762 	(void)BIO_reset(p7s);
1763 	(void)BIO_reset(data);
1764 
1765 	/* convert p7s to p7 (the signature) */
1766 	p7 = d2i_PKCS7_bio(p7s, NULL);
1767 	if(!p7) {
1768 		if(verb) printf("could not parse p7s signature file\n");
1769 		X509_STORE_free(store);
1770 		return 0;
1771 	}
1772 	if(verb >= 2) printf("parsed the PKCS7 signature\n");
1773 
1774 	/* convert trust to trusted certificate store */
1775 	for(i=0; i<sk_X509_num(trust); i++) {
1776 		if(!X509_STORE_add_cert(store, sk_X509_value(trust, i))) {
1777 			if(verb) printf("failed X509_STORE_add_cert\n");
1778 			X509_STORE_free(store);
1779 			PKCS7_free(p7);
1780 			return 0;
1781 		}
1782 	}
1783 	if(verb >= 2) printf("setup the X509_STORE\n");
1784 
1785 	/* check what is in the Subject name of the certificates,
1786 	 * and build a stack that contains only the right certificates */
1787 	validsigners = get_valid_signers(p7, p7signer);
1788 	if(!validsigners) {
1789 			X509_STORE_free(store);
1790 			PKCS7_free(p7);
1791 			return 0;
1792 	}
1793 	if(PKCS7_verify(p7, validsigners, store, data, NULL, PKCS7_NOINTERN) == 1) {
1794 		secure = 1;
1795 		if(verb) printf("the PKCS7 signature verified\n");
1796 	} else {
1797 		if(verb) {
1798 			ERR_print_errors_fp(stdout);
1799 		}
1800 	}
1801 
1802 	sk_X509_free(validsigners);
1803 	X509_STORE_free(store);
1804 	PKCS7_free(p7);
1805 	return secure;
1806 }
1807 
1808 /** write unsigned root anchor file, a 5011 revoked tp */
1809 static void
1810 write_unsigned_root(const char* root_anchor_file)
1811 {
1812 	FILE* out;
1813 	time_t now = time(NULL);
1814 	out = fopen(root_anchor_file, "w");
1815 	if(!out) {
1816 		if(verb) printf("%s: %s\n", root_anchor_file, strerror(errno));
1817 		return;
1818 	}
1819 	if(fprintf(out, "; autotrust trust anchor file\n"
1820 		";;REVOKED\n"
1821 		";;id: . 1\n"
1822 		"; This file was written by unbound-anchor on %s"
1823 		"; It indicates that the root does not use DNSSEC\n"
1824 		"; to restart DNSSEC overwrite this file with a\n"
1825 		"; valid trustanchor or (empty-it and run unbound-anchor)\n"
1826 		, ctime(&now)) < 0) {
1827 		if(verb) printf("failed to write 'unsigned' to %s\n",
1828 			root_anchor_file);
1829 		if(verb && errno != 0) printf("%s\n", strerror(errno));
1830 	}
1831 	fclose(out);
1832 }
1833 
1834 /** write root anchor file */
1835 static void
1836 write_root_anchor(const char* root_anchor_file, BIO* ds)
1837 {
1838 	char* pp = NULL;
1839 	int len;
1840 	FILE* out;
1841 	(void)BIO_seek(ds, 0);
1842 	len = BIO_get_mem_data(ds, &pp);
1843 	if(!len || !pp) {
1844 		if(verb) printf("out of memory\n");
1845 		return;
1846 	}
1847 	out = fopen(root_anchor_file, "w");
1848 	if(!out) {
1849 		if(verb) printf("%s: %s\n", root_anchor_file, strerror(errno));
1850 		return;
1851 	}
1852 	if(fwrite(pp, (size_t)len, 1, out) != 1) {
1853 		if(verb) printf("failed to write all data to %s\n",
1854 			root_anchor_file);
1855 		if(verb && errno != 0) printf("%s\n", strerror(errno));
1856 	}
1857 	fclose(out);
1858 }
1859 
1860 /** Perform the verification and update of the trustanchor file */
1861 static void
1862 verify_and_update_anchor(const char* root_anchor_file, BIO* xml, BIO* p7s,
1863 	STACK_OF(X509)* cert, const char* p7signer)
1864 {
1865 	BIO* ds;
1866 
1867 	/* verify xml file */
1868 	if(!verify_p7sig(xml, p7s, cert, p7signer)) {
1869 		printf("the PKCS7 signature failed\n");
1870 		exit(0);
1871 	}
1872 
1873 	/* parse the xml file into DS records */
1874 	ds = xml_parse(xml, time(NULL));
1875 	if(!ds) {
1876 		/* the root zone is unsigned now */
1877 		write_unsigned_root(root_anchor_file);
1878 	} else {
1879 		/* reinstate 5011 tracking */
1880 		write_root_anchor(root_anchor_file, ds);
1881 	}
1882 	BIO_free(ds);
1883 }
1884 
1885 #ifdef USE_WINSOCK
1886 static void do_wsa_cleanup(void) { WSACleanup(); }
1887 #endif
1888 
1889 /** perform actual certupdate work */
1890 static int
1891 do_certupdate(const char* root_anchor_file, const char* root_cert_file,
1892 	const char* urlname, const char* xmlname, const char* p7sname,
1893 	const char* p7signer, const char* res_conf, const char* root_hints,
1894 	const char* debugconf, int ip4only, int ip6only, int port,
1895 	struct ub_result* dnskey)
1896 {
1897 	STACK_OF(X509)* cert;
1898 	BIO *xml, *p7s;
1899 	struct ip_list* ip_list = NULL;
1900 
1901 	/* read pem file or provide builtin */
1902 	cert = read_cert_or_builtin(root_cert_file);
1903 
1904 	/* lookup A, AAAA for the urlname (or parse urlname if IP address) */
1905 	ip_list = resolve_name(urlname, port, res_conf, root_hints, debugconf,
1906 		ip4only, ip6only);
1907 
1908 #ifdef USE_WINSOCK
1909 	if(1) { /* libunbound finished, startup WSA for the https connection */
1910 		WSADATA wsa_data;
1911 		int r;
1912 		if((r = WSAStartup(MAKEWORD(2,2), &wsa_data)) != 0) {
1913 			if(verb) printf("WSAStartup failed: %s\n",
1914 				wsa_strerror(r));
1915 			exit(0);
1916 		}
1917 		atexit(&do_wsa_cleanup);
1918 	}
1919 #endif
1920 
1921 	/* fetch the necessary files over HTTPS */
1922 	xml = https(ip_list, xmlname, urlname);
1923 	p7s = https(ip_list, p7sname, urlname);
1924 
1925 	/* verify and update the root anchor */
1926 	verify_and_update_anchor(root_anchor_file, xml, p7s, cert, p7signer);
1927 	if(verb) printf("success: the anchor has been updated "
1928 			"using the cert\n");
1929 
1930 	free_file_bio(xml);
1931 	free_file_bio(p7s);
1932 #ifndef S_SPLINT_S
1933 	sk_X509_pop_free(cert, X509_free);
1934 #endif
1935 	ub_resolve_free(dnskey);
1936 	ip_list_free(ip_list);
1937 	return 1;
1938 }
1939 
1940 /**
1941  * Try to read the root RFC5011 autotrust anchor file,
1942  * @param file: filename.
1943  * @return:
1944  * 	0 if does not exist or empty
1945  * 	1 if trust-point-revoked-5011
1946  * 	2 if it is OK.
1947  */
1948 static int
1949 try_read_anchor(const char* file)
1950 {
1951 	int empty = 1;
1952 	char line[10240];
1953 	char* p;
1954 	FILE* in = fopen(file, "r");
1955 	if(!in) {
1956 		/* only if the file does not exist, can we fix it */
1957 		if(errno != ENOENT) {
1958 			if(verb) printf("%s: %s\n", file, strerror(errno));
1959 			if(verb) printf("error: cannot access the file\n");
1960 			exit(0);
1961 		}
1962 		if(verb) printf("%s does not exist\n", file);
1963 		return 0;
1964 	}
1965 	while(fgets(line, (int)sizeof(line), in)) {
1966 		line[sizeof(line)-1] = 0;
1967 		if(strncmp(line, ";;REVOKED", 9) == 0) {
1968 			fclose(in);
1969 			if(verb) printf("%s : the trust point is revoked\n"
1970 				"and the zone is considered unsigned.\n"
1971 				"if you wish to re-enable, delete the file\n",
1972 				file);
1973 			return 1;
1974 		}
1975 		p=line;
1976 		while(*p == ' ' || *p == '\t')
1977 			p++;
1978 		if(p[0]==0 || p[0]=='\n' || p[0]==';') continue;
1979 		/* this line is a line of content */
1980 		empty = 0;
1981 	}
1982 	fclose(in);
1983 	if(empty) {
1984 		if(verb) printf("%s is empty\n", file);
1985 		return 0;
1986 	}
1987 	if(verb) printf("%s has content\n", file);
1988 	return 2;
1989 }
1990 
1991 /** Write the builtin root anchor to a file */
1992 static void
1993 write_builtin_anchor(const char* file)
1994 {
1995 	const char* builtin_root_anchor = get_builtin_ds();
1996 	FILE* out = fopen(file, "w");
1997 	if(!out) {
1998 		if(verb) printf("%s: %s\n", file, strerror(errno));
1999 		if(verb) printf("  could not write builtin anchor\n");
2000 		return;
2001 	}
2002 	if(!fwrite(builtin_root_anchor, strlen(builtin_root_anchor), 1, out)) {
2003 		if(verb) printf("%s: %s\n", file, strerror(errno));
2004 		if(verb) printf("  could not complete write builtin anchor\n");
2005 	}
2006 	fclose(out);
2007 }
2008 
2009 /**
2010  * Check the root anchor file.
2011  * If does not exist, provide builtin and write file.
2012  * If empty, provide builtin and write file.
2013  * If trust-point-revoked-5011 file: make the program exit.
2014  * @param root_anchor_file: filename of the root anchor.
2015  * @param used_builtin: set to 1 if the builtin is written.
2016  * @return 0 if trustpoint is insecure, 1 on success.  Exit on failure.
2017  */
2018 static int
2019 provide_builtin(const char* root_anchor_file, int* used_builtin)
2020 {
2021 	/* try to read it */
2022 	switch(try_read_anchor(root_anchor_file))
2023 	{
2024 		case 0: /* no exist or empty */
2025 			write_builtin_anchor(root_anchor_file);
2026 			*used_builtin = 1;
2027 			break;
2028 		case 1: /* revoked tp */
2029 			return 0;
2030 		case 2: /* it is fine */
2031 		default:
2032 			break;
2033 	}
2034 	return 1;
2035 }
2036 
2037 /**
2038  * add an autotrust anchor for the root to the context
2039  */
2040 static void
2041 add_5011_probe_root(struct ub_ctx* ctx, const char* root_anchor_file)
2042 {
2043 	int r;
2044 	r = ub_ctx_set_option(ctx, "auto-trust-anchor-file:", root_anchor_file);
2045 	if(r) {
2046 		if(verb) printf("add 5011 probe to ctx: %s\n", ub_strerror(r));
2047 		ub_ctx_delete(ctx);
2048 		exit(0);
2049 	}
2050 }
2051 
2052 /**
2053  * Prime the root key and return the result.  Exit on error.
2054  * @param ctx: the unbound context to perform the priming with.
2055  * @return: the result of the prime, on error it exit()s.
2056  */
2057 static struct ub_result*
2058 prime_root_key(struct ub_ctx* ctx)
2059 {
2060 	struct ub_result* res = NULL;
2061 	int r;
2062 	r = ub_resolve(ctx, ".", LDNS_RR_TYPE_DNSKEY, LDNS_RR_CLASS_IN, &res);
2063 	if(r) {
2064 		if(verb) printf("resolve DNSKEY: %s\n", ub_strerror(r));
2065 		ub_ctx_delete(ctx);
2066 		exit(0);
2067 	}
2068 	if(!res) {
2069 		if(verb) printf("out of memory\n");
2070 		ub_ctx_delete(ctx);
2071 		exit(0);
2072 	}
2073 	return res;
2074 }
2075 
2076 /** see if ADDPEND keys exist in autotrust file (if possible) */
2077 static int
2078 read_if_pending_keys(const char* file)
2079 {
2080 	FILE* in = fopen(file, "r");
2081 	char line[8192];
2082 	if(!in) {
2083 		if(verb>=2) printf("%s: %s\n", file, strerror(errno));
2084 		return 0;
2085 	}
2086 	while(fgets(line, (int)sizeof(line), in)) {
2087 		if(line[0]==';') continue;
2088 		if(strstr(line, "[ ADDPEND ]")) {
2089 			fclose(in);
2090 			if(verb) printf("RFC5011-state has ADDPEND keys\n");
2091 			return 1;
2092 		}
2093 	}
2094 	fclose(in);
2095 	return 0;
2096 }
2097 
2098 /** read last successful probe time from autotrust file (if possible) */
2099 static int32_t
2100 read_last_success_time(const char* file)
2101 {
2102 	FILE* in = fopen(file, "r");
2103 	char line[1024];
2104 	if(!in) {
2105 		if(verb) printf("%s: %s\n", file, strerror(errno));
2106 		return 0;
2107 	}
2108 	while(fgets(line, (int)sizeof(line), in)) {
2109 		if(strncmp(line, ";;last_success: ", 16) == 0) {
2110 			char* e;
2111 			time_t x = (unsigned int)strtol(line+16, &e, 10);
2112 			fclose(in);
2113 			if(line+16 == e) {
2114 				if(verb) printf("failed to parse "
2115 					"last_success probe time\n");
2116 				return 0;
2117 			}
2118 			if(verb) printf("last successful probe: %s", ctime(&x));
2119 			return (int32_t)x;
2120 		}
2121 	}
2122 	fclose(in);
2123 	if(verb) printf("no last_success probe time in anchor file\n");
2124 	return 0;
2125 }
2126 
2127 /**
2128  * Read autotrust 5011 probe file and see if the date
2129  * compared to the current date allows a certupdate.
2130  * If the last successful probe was recent then 5011 cannot be behind,
2131  * and the failure cannot be solved with a certupdate.
2132  * The debugconf is to validation-override the date for testing.
2133  * @param root_anchor_file: filename of root key
2134  * @return true if certupdate is ok.
2135  */
2136 static int
2137 probe_date_allows_certupdate(const char* root_anchor_file)
2138 {
2139 	int has_pending_keys = read_if_pending_keys(root_anchor_file);
2140 	int32_t last_success = read_last_success_time(root_anchor_file);
2141 	int32_t now = (int32_t)time(NULL);
2142 	int32_t leeway = 30 * 24 * 3600; /* 30 days leeway */
2143 	/* if the date is before 2010-07-15:00.00.00 then the root has not
2144 	 * been signed yet, and thus we refuse to take action. */
2145 	if(time(NULL) < xml_convertdate("2010-07-15T00:00:00")) {
2146 		if(verb) printf("the date is before the root was first signed,"
2147 			" please correct the clock\n");
2148 		return 0;
2149 	}
2150 	if(last_success == 0)
2151 		return 1; /* no probe time */
2152 	if(has_pending_keys)
2153 		return 1; /* key in ADDPEND state, a previous probe has
2154 		inserted that, and it was present in all recent probes,
2155 		but it has not become active.  The 30 day timer may not have
2156 		expired, but we know(for sure) there is a rollover going on.
2157 		If we only managed to pickup the new key on its last day
2158 		of announcement (for example) this can happen. */
2159 	if(now - last_success < 0) {
2160 		if(verb) printf("the last successful probe is in the future,"
2161 			" clock was modified\n");
2162 		return 0;
2163 	}
2164 	if(now - last_success >= leeway) {
2165 		if(verb) printf("the last successful probe was more than 30 "
2166 			"days ago\n");
2167 		return 1;
2168 	}
2169 	if(verb) printf("the last successful probe is recent\n");
2170 	return 0;
2171 }
2172 
2173 /** perform the unbound-anchor work */
2174 static int
2175 do_root_update_work(const char* root_anchor_file, const char* root_cert_file,
2176 	const char* urlname, const char* xmlname, const char* p7sname,
2177 	const char* p7signer, const char* res_conf, const char* root_hints,
2178 	const char* debugconf, int ip4only, int ip6only, int force, int port)
2179 {
2180 	struct ub_ctx* ctx;
2181 	struct ub_result* dnskey;
2182 	int used_builtin = 0;
2183 
2184 	/* see if builtin rootanchor needs to be provided, or if
2185 	 * rootanchor is 'revoked-trust-point' */
2186 	if(!provide_builtin(root_anchor_file, &used_builtin))
2187 		return 0;
2188 
2189 	/* make unbound context with 5011-probe for root anchor,
2190 	 * and probe . DNSKEY */
2191 	ctx = create_unbound_context(res_conf, root_hints, debugconf,
2192 		ip4only, ip6only);
2193 	add_5011_probe_root(ctx, root_anchor_file);
2194 	dnskey = prime_root_key(ctx);
2195 	ub_ctx_delete(ctx);
2196 
2197 	/* if secure: exit */
2198 	if(dnskey->secure && !force) {
2199 		if(verb) printf("success: the anchor is ok\n");
2200 		ub_resolve_free(dnskey);
2201 		return used_builtin;
2202 	}
2203 	if(force && verb) printf("debug cert update forced\n");
2204 
2205 	/* if not (and NOERROR): check date and do certupdate */
2206 	if((dnskey->rcode == 0 &&
2207 		probe_date_allows_certupdate(root_anchor_file)) || force) {
2208 		if(do_certupdate(root_anchor_file, root_cert_file, urlname,
2209 			xmlname, p7sname, p7signer, res_conf, root_hints,
2210 			debugconf, ip4only, ip6only, port, dnskey))
2211 			return 1;
2212 		return used_builtin;
2213 	}
2214 	if(verb) printf("fail: the anchor is NOT ok and could not be fixed\n");
2215 	ub_resolve_free(dnskey);
2216 	return used_builtin;
2217 }
2218 
2219 /** getopt global, in case header files fail to declare it. */
2220 extern int optind;
2221 /** getopt global, in case header files fail to declare it. */
2222 extern char* optarg;
2223 
2224 /** Main routine for unbound-anchor */
2225 int main(int argc, char* argv[])
2226 {
2227 	int c;
2228 	const char* root_anchor_file = ROOT_ANCHOR_FILE;
2229 	const char* root_cert_file = ROOT_CERT_FILE;
2230 	const char* urlname = URLNAME;
2231 	const char* xmlname = XMLNAME;
2232 	const char* p7sname = P7SNAME;
2233 	const char* p7signer = P7SIGNER;
2234 	const char* res_conf = NULL;
2235 	const char* root_hints = NULL;
2236 	const char* debugconf = NULL;
2237 	int dolist=0, ip4only=0, ip6only=0, force=0, port = HTTPS_PORT;
2238 	/* parse the options */
2239 	while( (c=getopt(argc, argv, "46C:FP:a:c:f:hln:r:s:u:vx:")) != -1) {
2240 		switch(c) {
2241 		case 'l':
2242 			dolist = 1;
2243 			break;
2244 		case '4':
2245 			ip4only = 1;
2246 			break;
2247 		case '6':
2248 			ip6only = 1;
2249 			break;
2250 		case 'a':
2251 			root_anchor_file = optarg;
2252 			break;
2253 		case 'c':
2254 			root_cert_file = optarg;
2255 			break;
2256 		case 'u':
2257 			urlname = optarg;
2258 			break;
2259 		case 'x':
2260 			xmlname = optarg;
2261 			break;
2262 		case 's':
2263 			p7sname = optarg;
2264 			break;
2265 		case 'n':
2266 			p7signer = optarg;
2267 			break;
2268 		case 'f':
2269 			res_conf = optarg;
2270 			break;
2271 		case 'r':
2272 			root_hints = optarg;
2273 			break;
2274 		case 'C':
2275 			debugconf = optarg;
2276 			break;
2277 		case 'F':
2278 			force = 1;
2279 			break;
2280 		case 'P':
2281 			port = atoi(optarg);
2282 			break;
2283 		case 'v':
2284 			verb++;
2285 			break;
2286 		case '?':
2287 		case 'h':
2288 		default:
2289 			usage();
2290 		}
2291 	}
2292 	argc -= optind;
2293 	argv += optind;
2294 	if(argc != 0)
2295 		usage();
2296 
2297 	ERR_load_crypto_strings();
2298 	ERR_load_SSL_strings();
2299 	OpenSSL_add_all_algorithms();
2300 	(void)SSL_library_init();
2301 
2302 	if(dolist) do_list_builtin();
2303 
2304 	return do_root_update_work(root_anchor_file, root_cert_file, urlname,
2305 		xmlname, p7sname, p7signer, res_conf, root_hints, debugconf,
2306 		ip4only, ip6only, force, port);
2307 }
2308