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