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