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