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