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