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