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