2 * unbound-anchor.c - update the root anchor if necessary.
4 * Copyright (c) 2010, NLnet Labs. All rights reserved.
6 * This software is open source.
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
12 * Redistributions of source code must retain the above copyright notice,
13 * this list of conditions and the following disclaimer.
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.
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.
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.
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.
42 * This is a concept solution for distribution of the DNSSEC root
43 * trust anchor. It is a small tool, called "unbound-anchor", that
44 * runs before the main validator starts. I.e. in the init script:
45 * unbound-anchor; unbound. Thus it is meant to run at system boot time.
47 * Management-Abstract:
48 * * first run: fill root.key file with hardcoded DS record.
49 * * mostly: use RFC5011 tracking, quick . DNSKEY UDP query.
50 * * failover: use builtin certificate, do https and update.
51 * Special considerations:
52 * * 30-days RFC5011 timer saves a lot of https traffic.
53 * * DNSKEY probe must be NOERROR, saves a lot of https traffic.
54 * * fail if clock before sign date of the root, if cert expired.
55 * * if the root goes back to unsigned, deals with it.
57 * It has hardcoded the root DS anchors and the ICANN CA root certificate.
58 * It allows with options to override those. It also takes root-hints (it
59 * has to do a DNS resolve), and also has hardcoded defaults for those.
61 * Once it starts, just before the validator starts, it quickly checks if
62 * the root anchor file needs to be updated. First it tries to use
63 * RFC5011-tracking of the root key. If that fails (and for 30-days since
64 * last successful probe), then it attempts to update using the
65 * certificate. So most of the time, the RFC5011 tracking will work fine,
66 * and within a couple milliseconds, the main daemon can start. It will
67 * have only probed the . DNSKEY, not done expensive https transfers on the
68 * root infrastructure.
70 * If there is no root key in the root.key file, it bootstraps the
71 * RFC5011-tracking with its builtin DS anchors; if that fails it
72 * bootstraps the RFC5011-tracking using the certificate. (again to avoid
73 * https, and it is also faster).
75 * It uses the XML file by converting it to DS records and writing that to the
76 * key file. Unbound can detect that the 'special comments' are gone, and
77 * the file contains a list of normal DNSKEY/DS records, and uses that to
78 * bootstrap 5011 (the KSK is made VALID).
80 * The certificate update is done by fetching root-anchors.xml and
81 * root-anchors.p7s via SSL. The HTTPS certificate can be logged but is
82 * not validated (https for channel security; the security comes from the
83 * certificate). The 'data.iana.org' domain name A and AAAA are resolved
84 * without DNSSEC. It tries a random IP until the transfer succeeds. It
85 * then checks the p7s signature.
87 * On any failure, it leaves the root key file untouched. The main
88 * validator has to cope with it, it cannot fix things (So a failure does
89 * not go 'without DNSSEC', no downgrade). If it used its builtin stuff or
90 * did the https, it exits with an exit code, so that this can trigger the
91 * init script to log the event and potentially alert the operator that can
94 * The date is also checked. Before 2010-07-15 is a failure (root not
95 * signed yet; avoids attacks on system clock). The
96 * last-successful-RFC5011-probe (if available) has to be more than 30 days
97 * in the past (otherwise, RFC5011 should have worked). This keeps
98 * unnecessary https traffic down. If the main certificate is expired, it
101 * The dates on the keys in the xml are checked (uses the libexpat xml
102 * parser), only the valid ones are used to re-enstate RFC5011 tracking.
103 * If 0 keys are valid, the zone has gone to insecure (a special marker is
104 * written in the keyfile that tells the main validator daemon the zone is
107 * Only the root ICANN CA is shipped, not the intermediate ones. The
108 * intermediate CAs are included in the p7s file that was downloaded. (the
109 * root cert is valid to 2028 and the intermediate to 2014, today).
111 * Obviously, the tool also has options so the operator can provide a new
112 * keyfile, a new certificate and new URLs, and fresh root hints. By
113 * default it logs nothing on failure and success; it 'just works'.
118 #include "libunbound/unbound.h"
119 #include "sldns/rrdef.h"
120 #include "sldns/parseutil.h"
123 #error "need libexpat to parse root-anchors.xml file."
128 #ifdef HAVE_OPENSSL_SSL_H
129 #include <openssl/ssl.h>
131 #ifdef HAVE_OPENSSL_ERR_H
132 #include <openssl/err.h>
134 #ifdef HAVE_OPENSSL_RAND_H
135 #include <openssl/rand.h>
137 #include <openssl/x509.h>
138 #include <openssl/x509v3.h>
139 #include <openssl/pem.h>
141 /** name of server in URL to fetch HTTPS from */
142 #define URLNAME "data.iana.org"
143 /** path on HTTPS server to xml file */
144 #define XMLNAME "root-anchors/root-anchors.xml"
145 /** path on HTTPS server to p7s file */
146 #define P7SNAME "root-anchors/root-anchors.p7s"
147 /** name of the signer of the certificate */
148 #define P7SIGNER "dnssec@iana.org"
149 /** port number for https access */
150 #define HTTPS_PORT 443
153 /* sneakily reuse the the wsa_strerror function, on windows */
154 char* wsa_strerror(int err);
157 /** verbosity for this application */
160 /** list of IP addresses */
163 struct ip_list* next;
164 /** length of addr */
166 /** address ready to connect to */
167 struct sockaddr_storage addr;
168 /** has the address been used */
172 /** Give unbound-anchor usage, and exit (1). */
176 printf("Usage: unbound-anchor [opts]\n");
177 printf(" Setup or update root anchor. "
178 "Most options have defaults.\n");
179 printf(" Run this program before you start the validator.\n");
181 printf(" The anchor and cert have default builtin content\n");
182 printf(" if the file does not exist or is empty.\n");
184 printf("-a file root key file, default %s\n", ROOT_ANCHOR_FILE);
185 printf(" The key is input and output for this tool.\n");
186 printf("-c file cert file, default %s\n", ROOT_CERT_FILE);
187 printf("-l list builtin key and cert on stdout\n");
188 printf("-u name server in https url, default %s\n", URLNAME);
189 printf("-x path pathname to xml in url, default %s\n", XMLNAME);
190 printf("-s path pathname to p7s in url, default %s\n", P7SNAME);
191 printf("-n name signer's subject emailAddress, default %s\n", P7SIGNER);
192 printf("-4 work using IPv4 only\n");
193 printf("-6 work using IPv6 only\n");
194 printf("-f resolv.conf use given resolv.conf to resolve -u name\n");
195 printf("-r root.hints use given root.hints to resolve -u name\n"
196 " builtin root hints are used by default\n");
197 printf("-v more verbose\n");
198 printf("-C conf debug, read config\n");
199 printf("-P port use port for https connect, default 443\n");
200 printf("-F debug, force update with cert\n");
201 printf("-h show this usage help\n");
202 printf("Version %s\n", PACKAGE_VERSION);
203 printf("BSD licensed, see LICENSE in source package for details.\n");
204 printf("Report bugs to %s\n", PACKAGE_BUGREPORT);
208 /** return the built in root update certificate */
210 get_builtin_cert(void)
213 /* The ICANN CA fetched at 24 Sep 2010. Valid to 2028 */
214 "-----BEGIN CERTIFICATE-----\n"
215 "MIIDdzCCAl+gAwIBAgIBATANBgkqhkiG9w0BAQsFADBdMQ4wDAYDVQQKEwVJQ0FO\n"
216 "TjEmMCQGA1UECxMdSUNBTk4gQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkxFjAUBgNV\n"
217 "BAMTDUlDQU5OIFJvb3QgQ0ExCzAJBgNVBAYTAlVTMB4XDTA5MTIyMzA0MTkxMloX\n"
218 "DTI5MTIxODA0MTkxMlowXTEOMAwGA1UEChMFSUNBTk4xJjAkBgNVBAsTHUlDQU5O\n"
219 "IENlcnRpZmljYXRpb24gQXV0aG9yaXR5MRYwFAYDVQQDEw1JQ0FOTiBSb290IENB\n"
220 "MQswCQYDVQQGEwJVUzCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAKDb\n"
221 "cLhPNNqc1NB+u+oVvOnJESofYS9qub0/PXagmgr37pNublVThIzyLPGCJ8gPms9S\n"
222 "G1TaKNIsMI7d+5IgMy3WyPEOECGIcfqEIktdR1YWfJufXcMReZwU4v/AdKzdOdfg\n"
223 "ONiwc6r70duEr1IiqPbVm5T05l1e6D+HkAvHGnf1LtOPGs4CHQdpIUcy2kauAEy2\n"
224 "paKcOcHASvbTHK7TbbvHGPB+7faAztABLoneErruEcumetcNfPMIjXKdv1V1E3C7\n"
225 "MSJKy+jAqqQJqjZoQGB0necZgUMiUv7JK1IPQRM2CXJllcyJrm9WFxY0c1KjBO29\n"
226 "iIKK69fcglKcBuFShUECAwEAAaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8B\n"
227 "Af8EBAMCAf4wHQYDVR0OBBYEFLpS6UmDJIZSL8eZzfyNa2kITcBQMA0GCSqGSIb3\n"
228 "DQEBCwUAA4IBAQAP8emCogqHny2UYFqywEuhLys7R9UKmYY4suzGO4nkbgfPFMfH\n"
229 "6M+Zj6owwxlwueZt1j/IaCayoKU3QsrYYoDRolpILh+FPwx7wseUEV8ZKpWsoDoD\n"
230 "2JFbLg2cfB8u/OlE4RYmcxxFSmXBg0yQ8/IoQt/bxOcEEhhiQ168H2yE5rxJMt9h\n"
231 "15nu5JBSewrCkYqYYmaxyOC3WrVGfHZxVI7MpIFcGdvSb2a1uyuua8l0BKgk3ujF\n"
232 "0/wsHNeP22qNyVO+XVBzrM8fk8BSUFuiT/6tZTYXRtEt5aKQZgXbKU5dUF3jT9qg\n"
233 "j/Br5BZw3X/zd325TvnswzMC1+ljLzHnQGGk\n"
234 "-----END CERTIFICATE-----\n"
238 /** return the built in root DS trust anchor */
243 ". IN DS 19036 8 2 49AAC11D7B6F6446702E54A1607371607A1A41855200FD2CE1CDDE32F24E8FB5\n";
246 /** print hex data */
248 print_data(const char* msg, const char* data, int len)
252 for(i=0; i<len; i++) {
253 printf(" %2.2x", (unsigned char)data[i]);
258 /** print ub context creation error and exit */
260 ub_ctx_error_exit(struct ub_ctx* ctx, const char* str, const char* str2)
263 if(str && str2 && verb) printf("%s: %s\n", str, str2);
264 if(verb) printf("error: could not create unbound resolver context\n");
269 * Create a new unbound context with the commandline settings applied
271 static struct ub_ctx*
272 create_unbound_context(const char* res_conf, const char* root_hints,
273 const char* debugconf, int ip4only, int ip6only)
276 struct ub_ctx* ctx = ub_ctx_create();
278 if(verb) printf("out of memory\n");
281 /* do not waste time and network traffic to fetch extra nameservers */
282 r = ub_ctx_set_option(ctx, "target-fetch-policy:", "0 0 0 0 0");
283 if(r && verb) printf("ctx targetfetchpolicy: %s\n", ub_strerror(r));
284 /* read config file first, so its settings can be overridden */
286 r = ub_ctx_config(ctx, debugconf);
287 if(r) ub_ctx_error_exit(ctx, debugconf, ub_strerror(r));
290 r = ub_ctx_resolvconf(ctx, res_conf);
291 if(r) ub_ctx_error_exit(ctx, res_conf, ub_strerror(r));
294 r = ub_ctx_set_option(ctx, "root-hints:", root_hints);
295 if(r) ub_ctx_error_exit(ctx, root_hints, ub_strerror(r));
298 r = ub_ctx_set_option(ctx, "do-ip6:", "no");
299 if(r) ub_ctx_error_exit(ctx, "ip4only", ub_strerror(r));
302 r = ub_ctx_set_option(ctx, "do-ip4:", "no");
303 if(r) ub_ctx_error_exit(ctx, "ip6only", ub_strerror(r));
308 /** printout certificate in detail */
310 verb_cert(const char* msg, X509* x)
312 if(verb == 0 || verb == 1) return;
314 if(msg) printf("%s\n", msg);
315 X509_print_ex_fp(stdout, x, 0, (unsigned long)-1
316 ^(X509_FLAG_NO_SUBJECT
317 |X509_FLAG_NO_ISSUER|X509_FLAG_NO_VALIDITY));
320 if(msg) printf("%s\n", msg);
321 X509_print_fp(stdout, x);
324 /** printout certificates in detail */
326 verb_certs(const char* msg, STACK_OF(X509)* sk)
328 int i, num = sk_X509_num(sk);
329 if(verb == 0 || verb == 1) return;
330 for(i=0; i<num; i++) {
331 printf("%s (%d/%d)\n", msg, i, num);
332 verb_cert(NULL, sk_X509_value(sk, i));
336 /** read certificates from a PEM bio */
337 static STACK_OF(X509)*
338 read_cert_bio(BIO* bio)
340 STACK_OF(X509) *sk = sk_X509_new_null();
342 if(verb) printf("out of memory\n");
345 while(!BIO_eof(bio)) {
346 X509* x = PEM_read_bio_X509(bio, NULL, 0, NULL);
349 printf("failed to read X509\n");
350 ERR_print_errors_fp(stdout);
354 if(!sk_X509_push(sk, x)) {
355 if(verb) printf("out of memory\n");
362 /* read the certificate file */
363 static STACK_OF(X509)*
364 read_cert_file(const char* file)
370 if(file == NULL || strcmp(file, "") == 0) {
373 sk = sk_X509_new_null();
375 if(verb) printf("out of memory\n");
378 in = fopen(file, "r");
380 if(verb) printf("%s: %s\n", file, strerror(errno));
382 sk_X509_pop_free(sk, X509_free);
387 X509* x = PEM_read_X509(in, NULL, 0, NULL);
390 printf("failed to read X509 file\n");
391 ERR_print_errors_fp(stdout);
395 if(!sk_X509_push(sk, x)) {
396 if(verb) printf("out of memory\n");
401 /* read away newline after --END CERT-- */
402 if(!fgets(buf, (int)sizeof(buf), in))
407 if(verb) printf("%s is empty\n", file);
409 sk_X509_pop_free(sk, X509_free);
416 /** read certificates from the builtin certificate */
417 static STACK_OF(X509)*
418 read_builtin_cert(void)
420 const char* builtin_cert = get_builtin_cert();
422 BIO *bio = BIO_new_mem_buf((void*)builtin_cert,
423 (int)strlen(builtin_cert));
425 if(verb) printf("out of memory\n");
428 sk = read_cert_bio(bio);
430 if(verb) printf("internal error, out of memory\n");
437 /** read update cert file or use builtin */
438 static STACK_OF(X509)*
439 read_cert_or_builtin(const char* file)
441 STACK_OF(X509) *sk = read_cert_file(file);
443 if(verb) printf("using builtin certificate\n");
444 sk = read_builtin_cert();
446 if(verb) printf("have %d trusted certificates\n", sk_X509_num(sk));
447 verb_certs("trusted certificates", sk);
452 do_list_builtin(void)
454 const char* builtin_cert = get_builtin_cert();
455 const char* builtin_ds = get_builtin_ds();
456 printf("%s\n", builtin_ds);
457 printf("%s\n", builtin_cert);
461 /** printout IP address with message */
463 verb_addr(const char* msg, struct ip_list* ip)
467 void* a = &((struct sockaddr_in*)&ip->addr)->sin_addr;
468 if(ip->len != (socklen_t)sizeof(struct sockaddr_in))
469 a = &((struct sockaddr_in6*)&ip->addr)->sin6_addr;
471 if(inet_ntop((int)((struct sockaddr_in*)&ip->addr)->sin_family,
472 a, out, (socklen_t)sizeof(out))==0)
473 printf("%s (inet_ntop error)\n", msg);
474 else printf("%s %s\n", msg, out);
480 ip_list_free(struct ip_list* p)
490 /** create ip_list entry for a RR record */
491 static struct ip_list*
492 RR_to_ip(int tp, char* data, int len, int port)
494 struct ip_list* ip = (struct ip_list*)calloc(1, sizeof(*ip));
495 uint16_t p = (uint16_t)port;
496 if(tp == LDNS_RR_TYPE_A) {
497 struct sockaddr_in* sa = (struct sockaddr_in*)&ip->addr;
498 ip->len = (socklen_t)sizeof(*sa);
499 sa->sin_family = AF_INET;
500 sa->sin_port = (in_port_t)htons(p);
501 if(len != (int)sizeof(sa->sin_addr)) {
502 if(verb) printf("skipped badly formatted A\n");
506 memmove(&sa->sin_addr, data, sizeof(sa->sin_addr));
508 } else if(tp == LDNS_RR_TYPE_AAAA) {
509 struct sockaddr_in6* sa = (struct sockaddr_in6*)&ip->addr;
510 ip->len = (socklen_t)sizeof(*sa);
511 sa->sin6_family = AF_INET6;
512 sa->sin6_port = (in_port_t)htons(p);
513 if(len != (int)sizeof(sa->sin6_addr)) {
514 if(verb) printf("skipped badly formatted AAAA\n");
518 memmove(&sa->sin6_addr, data, sizeof(sa->sin6_addr));
520 if(verb) printf("internal error: bad type in RRtoip\n");
524 verb_addr("resolved server address", ip);
528 /** Resolve name, type, class and add addresses to iplist */
530 resolve_host_ip(struct ub_ctx* ctx, const char* host, int port, int tp, int cl,
531 struct ip_list** head)
533 struct ub_result* res = NULL;
537 r = ub_resolve(ctx, host, tp, cl, &res);
539 if(verb) printf("error: resolve %s %s: %s\n", host,
540 (tp==LDNS_RR_TYPE_A)?"A":"AAAA", ub_strerror(r));
544 if(verb) printf("out of memory\n");
548 if(!res->havedata || res->rcode || !res->data) {
549 if(verb) printf("resolve %s %s: no result\n", host,
550 (tp==LDNS_RR_TYPE_A)?"A":"AAAA");
553 for(i = 0; res->data[i]; i++) {
554 struct ip_list* ip = RR_to_ip(tp, res->data[i], res->len[i],
560 ub_resolve_free(res);
563 /** parse a text IP address into a sockaddr */
564 static struct ip_list*
565 parse_ip_addr(const char* str, int port)
569 struct sockaddr_in6 a6;
570 struct sockaddr_in a;
573 uint16_t p = (uint16_t)port;
574 memset(&addr, 0, sizeof(addr));
576 if(inet_pton(AF_INET6, str, &addr.a6.sin6_addr) > 0) {
578 addr.a6.sin6_family = AF_INET6;
579 addr.a6.sin6_port = (in_port_t)htons(p);
580 len = (socklen_t)sizeof(addr.a6);
582 if(inet_pton(AF_INET, str, &addr.a.sin_addr) > 0) {
584 addr.a.sin_family = AF_INET;
585 addr.a.sin_port = (in_port_t)htons(p);
586 len = (socklen_t)sizeof(struct sockaddr_in);
588 if(!len) return NULL;
589 ip = (struct ip_list*)calloc(1, sizeof(*ip));
591 if(verb) printf("out of memory\n");
595 memmove(&ip->addr, &addr, len);
596 if(verb) printf("server address is %s\n", str);
601 * Resolve a domain name (even though the resolver is down and there is
602 * no trust anchor). Without DNSSEC validation.
603 * @param host: the name to resolve.
604 * If this name is an IP4 or IP6 address this address is returned.
605 * @param port: the port number used for the returned IP structs.
606 * @param res_conf: resolv.conf (if any).
607 * @param root_hints: root hints (if any).
608 * @param debugconf: unbound.conf for debugging options.
609 * @param ip4only: use only ip4 for resolve and only lookup A
610 * @param ip6only: use only ip6 for resolve and only lookup AAAA
611 * default is to lookup A and AAAA using ip4 and ip6.
612 * @return list of IP addresses.
614 static struct ip_list*
615 resolve_name(const char* host, int port, const char* res_conf,
616 const char* root_hints, const char* debugconf, int ip4only, int ip6only)
619 struct ip_list* list = NULL;
620 /* first see if name is an IP address itself */
621 if( (list=parse_ip_addr(host, port)) ) {
625 /* create resolver context */
626 ctx = create_unbound_context(res_conf, root_hints, debugconf,
629 /* try resolution of A */
631 resolve_host_ip(ctx, host, port, LDNS_RR_TYPE_A,
632 LDNS_RR_CLASS_IN, &list);
635 /* try resolution of AAAA */
637 resolve_host_ip(ctx, host, port, LDNS_RR_TYPE_AAAA,
638 LDNS_RR_CLASS_IN, &list);
643 if(verb) printf("%s has no IP addresses I can use\n", host);
649 /** clear used flags */
651 wipe_ip_usage(struct ip_list* p)
659 /** cound unused IPs */
661 count_unused(struct ip_list* p)
671 /** pick random unused element from IP list */
672 static struct ip_list*
673 pick_random_ip(struct ip_list* list)
675 struct ip_list* p = list;
676 int num = count_unused(list);
678 if(num == 0) return NULL;
679 /* not perfect, but random enough */
680 sel = (int)arc4random_uniform((uint32_t)num);
681 /* skip over unused elements that we did not select */
682 while(sel > 0 && p) {
686 /* find the next unused element */
689 if(!p) return NULL; /* robustness */
704 /** printout socket errno */
706 print_sock_err(const char* msg)
709 if(verb) printf("%s: %s\n", msg, strerror(errno));
711 if(verb) printf("%s: %s\n", msg, wsa_strerror(WSAGetLastError()));
715 /** connect to IP address */
717 connect_to_ip(struct ip_list* ip)
720 verb_addr("connect to", ip);
721 fd = socket(ip->len==(socklen_t)sizeof(struct sockaddr_in)?
722 AF_INET:AF_INET6, SOCK_STREAM, 0);
724 print_sock_err("socket");
727 if(connect(fd, (struct sockaddr*)&ip->addr, ip->len) < 0) {
728 print_sock_err("connect");
735 /** create SSL context */
739 SSL_CTX* sslctx = SSL_CTX_new(SSLv23_client_method());
741 if(verb) printf("SSL_CTX_new error\n");
747 /** initiate TLS on a connection */
749 TLS_initiate(SSL_CTX* sslctx, int fd)
753 SSL* ssl = SSL_new(sslctx);
755 if(verb) printf("SSL_new error\n");
758 SSL_set_connect_state(ssl);
759 (void)SSL_set_mode(ssl, SSL_MODE_AUTO_RETRY);
760 if(!SSL_set_fd(ssl, fd)) {
761 if(verb) printf("SSL_set_fd error\n");
767 if( (r=SSL_do_handshake(ssl)) == 1)
769 r = SSL_get_error(ssl, r);
770 if(r != SSL_ERROR_WANT_READ && r != SSL_ERROR_WANT_WRITE) {
771 if(verb) printf("SSL handshake failed\n");
775 /* wants to be called again */
777 x = SSL_get_peer_certificate(ssl);
779 if(verb) printf("Server presented no peer certificate\n");
783 verb_cert("server SSL certificate", x);
788 /** perform neat TLS shutdown */
790 TLS_shutdown(int fd, SSL* ssl, SSL_CTX* sslctx)
792 /* shutdown the SSL connection nicely */
793 if(SSL_shutdown(ssl) == 0) {
797 SSL_CTX_free(sslctx);
801 /** write a line over SSL */
803 write_ssl_line(SSL* ssl, const char* str, const char* sec)
808 snprintf(buf, sizeof(buf), str, sec);
810 snprintf(buf, sizeof(buf), "%s", str);
813 if(l+2 >= sizeof(buf)) {
814 if(verb) printf("line too long\n");
817 if(verb >= 2) printf("SSL_write: %s\n", buf);
822 if(SSL_write(ssl, buf, (int)strlen(buf)) <= 0) {
823 if(verb) printf("could not SSL_write %s", str);
829 /** process header line, check rcode and keeping track of size */
831 process_one_header(char* buf, size_t* clen, int* chunked)
833 if(verb>=2) printf("header: '%s'\n", buf);
834 if(strncasecmp(buf, "HTTP/1.1 ", 9) == 0) {
835 /* check returncode */
837 if(verb) printf("bad status %s\n", buf+9);
840 } else if(strncasecmp(buf, "Content-Length: ", 16) == 0) {
842 *clen = (size_t)atoi(buf+16);
843 } else if(strncasecmp(buf, "Transfer-Encoding: chunked", 19+7) == 0) {
851 * Read one line from SSL
853 * skips "\r\n" (but not copied to buf).
854 * @param ssl: the SSL connection to read from (blocking).
855 * @param buf: buffer to return line in.
856 * @param len: size of the buffer.
857 * @return 0 on error, 1 on success.
860 read_ssl_line(SSL* ssl, char* buf, size_t len)
867 if(verb) printf("line too long\n");
870 if((r = SSL_read(ssl, buf+n, 1)) <= 0) {
871 if(SSL_get_error(ssl, r) == SSL_ERROR_ZERO_RETURN) {
875 if(verb) printf("could not SSL_read\n");
878 if(endnl && buf[n] == '\n') {
882 if(verb) printf("error: stray linefeeds\n");
884 } else if(buf[n] == '\r') {
885 /* skip \r, and also \n on the wire */
888 } else if(buf[n] == '\n') {
889 /* skip the \n, we are done */
897 /** read http headers and process them */
899 read_http_headers(SSL* ssl, size_t* clen)
904 while(read_ssl_line(ssl, buf, sizeof(buf))) {
907 if(!process_one_header(buf, clen, &chunked))
913 /** read a data chunk */
915 read_data_chunk(SSL* ssl, size_t len)
920 if(len >= 0xfffffff0)
921 return NULL; /* to protect against integer overflow in malloc*/
922 data = malloc(len+1);
924 if(verb) printf("out of memory\n");
928 if((r = SSL_read(ssl, data+got, (int)(len-got))) <= 0) {
929 if(SSL_get_error(ssl, r) == SSL_ERROR_ZERO_RETURN) {
931 if(verb) printf("could not SSL_read: unexpected EOF\n");
935 if(verb) printf("could not SSL_read\n");
939 if(verb >= 2) printf("at %d/%d\n", (int)got, (int)len);
942 if(verb>=2) printf("read %d data\n", (int)len);
947 /** parse chunk header */
949 parse_chunk_header(char* buf, size_t* result)
952 size_t v = (size_t)strtol(buf, &e, 16);
959 /** read chunked data from connection */
961 do_chunked_read(SSL* ssl)
966 BIO* mem = BIO_new(BIO_s_mem());
967 if(verb>=3) printf("do_chunked_read\n");
969 if(verb) printf("out of memory\n");
972 while(read_ssl_line(ssl, buf, sizeof(buf))) {
973 /* read the chunked start line */
974 if(verb>=2) printf("chunk header: %s\n", buf);
975 if(!parse_chunk_header(buf, &len)) {
977 if(verb>=3) printf("could not parse chunk header\n");
980 if(verb>=2) printf("chunk len: %d\n", (int)len);
984 /* skip end-of-chunk-trailer lines,
985 * until the empty line after that */
987 if(!read_ssl_line(ssl, buf, sizeof(buf))) {
991 } while (strlen(buf) > 0);
992 /* end of chunks, zero terminate it */
993 if(BIO_write(mem, &z, 1) <= 0) {
994 if(verb) printf("out of memory\n");
1000 /* read the chunked body */
1001 body = read_data_chunk(ssl, len);
1006 if(BIO_write(mem, body, (int)len) <= 0) {
1007 if(verb) printf("out of memory\n");
1013 /* skip empty line after data chunk */
1014 if(!read_ssl_line(ssl, buf, sizeof(buf))) {
1023 /** start HTTP1.1 transaction on SSL */
1025 write_http_get(SSL* ssl, const char* pathname, const char* urlname)
1027 if(write_ssl_line(ssl, "GET /%s HTTP/1.1", pathname) &&
1028 write_ssl_line(ssl, "Host: %s", urlname) &&
1029 write_ssl_line(ssl, "User-Agent: unbound-anchor/%s",
1031 /* We do not really do multiple queries per connection,
1032 * but this header setting is also not needed.
1033 * write_ssl_line(ssl, "Connection: close", NULL) &&*/
1034 write_ssl_line(ssl, "", NULL)) {
1040 /** read chunked data and zero terminate; len is without zero */
1042 read_chunked_zero_terminate(SSL* ssl, size_t* len)
1044 /* do the chunked version */
1045 BIO* tmp = do_chunked_read(ssl);
1046 char* data, *d = NULL;
1049 if(verb) printf("could not read from https\n");
1052 l = (size_t)BIO_get_mem_data(tmp, &d);
1053 if(verb>=2) printf("chunked data is %d\n", (int)l);
1054 if(l == 0 || d == NULL) {
1055 if(verb) printf("out of memory\n");
1059 data = (char*)malloc(l);
1061 if(verb) printf("out of memory\n");
1069 /** read HTTP result from SSL */
1071 read_http_result(SSL* ssl)
1076 if(!read_http_headers(ssl, &len)) {
1080 data = read_chunked_zero_terminate(ssl, &len);
1082 data = read_data_chunk(ssl, len);
1084 if(!data) return NULL;
1085 if(verb >= 4) print_data("read data", data, (int)len);
1086 m = BIO_new_mem_buf(data, (int)len);
1088 if(verb) printf("out of memory\n");
1094 /** https to an IP addr, return BIO with pathname or NULL */
1096 https_to_ip(struct ip_list* ip, const char* pathname, const char* urlname)
1101 SSL_CTX* sslctx = setup_sslctx();
1105 fd = connect_to_ip(ip);
1107 SSL_CTX_free(sslctx);
1110 ssl = TLS_initiate(sslctx, fd);
1112 SSL_CTX_free(sslctx);
1116 if(!write_http_get(ssl, pathname, urlname)) {
1117 if(verb) printf("could not write to server\n");
1119 SSL_CTX_free(sslctx);
1123 bio = read_http_result(ssl);
1124 TLS_shutdown(fd, ssl, sslctx);
1129 * Do a HTTPS, HTTP1.1 over TLS, to fetch a file
1130 * @param ip_list: list of IP addresses to use to fetch from.
1131 * @param pathname: pathname of file on server to GET.
1132 * @param urlname: name to pass as the virtual host for this request.
1133 * @return a memory BIO with the file in it.
1136 https(struct ip_list* ip_list, const char* pathname, const char* urlname)
1140 /* try random address first, and work through the list */
1141 wipe_ip_usage(ip_list);
1142 while( (ip = pick_random_ip(ip_list)) ) {
1144 bio = https_to_ip(ip, pathname, urlname);
1148 if(verb) printf("could not fetch %s\n", pathname);
1151 if(verb) printf("fetched %s (%d bytes)\n",
1152 pathname, (int)BIO_ctrl_pending(bio));
1157 /** free up a downloaded file BIO */
1159 free_file_bio(BIO* bio)
1162 (void)BIO_reset(bio);
1163 (void)BIO_get_mem_data(bio, &pp);
1168 /** XML parse private data during the parse */
1170 /** the parser, reference */
1172 /** the current tag; malloced; or NULL outside of tags */
1174 /** current date to use during the parse */
1176 /** number of keys usefully read in */
1178 /** the compiled anchors as DS records */
1181 /** do we want to use this anchor? */
1183 /** the current anchor: Zone */
1185 /** the current anchor: KeyTag */
1187 /** the current anchor: Algorithm */
1189 /** the current anchor: DigestType */
1191 /** the current anchor: Digest*/
1195 /** The BIO for the tag */
1197 xml_selectbio(struct xml_data* data, const char* tag)
1200 if(strcasecmp(tag, "KeyTag") == 0)
1202 else if(strcasecmp(tag, "Algorithm") == 0)
1204 else if(strcasecmp(tag, "DigestType") == 0)
1206 else if(strcasecmp(tag, "Digest") == 0)
1212 * XML handle character data, the data inside an element.
1213 * @param userData: xml_data structure
1214 * @param s: the character data. May not all be in one callback.
1215 * NOT zero terminated.
1216 * @param len: length of this part of the data.
1219 xml_charhandle(void *userData, const XML_Char *s, int len)
1221 struct xml_data* data = (struct xml_data*)userData;
1223 /* skip characters outside of elements */
1228 printf("%s%s charhandle: '",
1229 data->use_key?"use ":"",
1230 data->tag?data->tag:"none");
1231 for(i=0; i<len; i++)
1235 if(strcasecmp(data->tag, "Zone") == 0) {
1236 if(BIO_write(data->czone, s, len) < 0) {
1237 if(verb) printf("out of memory in BIO_write\n");
1242 /* only store if key is used */
1245 b = xml_selectbio(data, data->tag);
1247 if(BIO_write(b, s, len) < 0) {
1248 if(verb) printf("out of memory in BIO_write\n");
1255 * XML fetch value of particular attribute(by name) or NULL if not present.
1256 * @param atts: attribute array (from xml_startelem).
1257 * @param name: name of attribute to look for.
1258 * @return the value or NULL. (ptr into atts).
1260 static const XML_Char*
1261 find_att(const XML_Char **atts, const XML_Char* name)
1264 for(i=0; atts[i]; i+=2) {
1265 if(strcasecmp(atts[i], name) == 0)
1272 * XML convert DateTime element to time_t.
1273 * [-]CCYY-MM-DDThh:mm:ss[Z|(+|-)hh:mm]
1274 * (with optional .ssssss fractional seconds)
1275 * @param str: the string
1276 * @return a time_t representation or 0 on failure.
1279 xml_convertdate(const char* str)
1284 /* for this application, ignore minus in front;
1285 * only positive dates are expected */
1287 if(s[0] == '-') s++;
1288 memset(&tm, 0, sizeof(tm));
1289 /* parse initial content of the string (lots of whitespace allowed) */
1290 s = strptime(s, "%t%Y%t-%t%m%t-%t%d%tT%t%H%t:%t%M%t:%t%S%t", &tm);
1292 if(verb) printf("xml_convertdate parse failure %s\n", str);
1295 /* parse remainder of date string */
1297 /* optional '.' and fractional seconds */
1298 int frac = 0, n = 0;
1299 if(sscanf(s+1, "%d%n", &frac, &n) < 1) {
1300 if(verb) printf("xml_convertdate f failure %s\n", str);
1303 /* fraction is not used, time_t has second accuracy */
1307 if(*s == 'Z' || *s == 'z') {
1308 /* nothing to do for this */
1310 } else if(*s == '+' || *s == '-') {
1311 /* optional timezone spec: Z or +hh:mm or -hh:mm */
1312 int hr = 0, mn = 0, n = 0;
1313 if(sscanf(s+1, "%d:%d%n", &hr, &mn, &n) < 2) {
1314 if(verb) printf("xml_convertdate tz failure %s\n", str);
1328 /* not ended properly */
1329 /* but ignore, (lenient) */
1332 t = sldns_mktime_from_utc(&tm);
1333 if(t == (time_t)-1) {
1334 if(verb) printf("xml_convertdate mktime failure\n");
1341 * XML handle the KeyDigest start tag, check validity periods.
1344 handle_keydigest(struct xml_data* data, const XML_Char **atts)
1347 if(find_att(atts, "validFrom")) {
1348 time_t from = xml_convertdate(find_att(atts, "validFrom"));
1350 if(verb) printf("error: xml cannot be parsed\n");
1353 if(data->date < from)
1356 if(find_att(atts, "validUntil")) {
1357 time_t until = xml_convertdate(find_att(atts, "validUntil"));
1359 if(verb) printf("error: xml cannot be parsed\n");
1362 if(data->date > until)
1365 /* yes we want to use this key */
1367 (void)BIO_reset(data->ctag);
1368 (void)BIO_reset(data->calgo);
1369 (void)BIO_reset(data->cdigtype);
1370 (void)BIO_reset(data->cdigest);
1373 /** See if XML element equals the zone name */
1375 xml_is_zone_name(BIO* zone, const char* name)
1380 (void)BIO_seek(zone, 0);
1381 zlen = BIO_get_mem_data(zone, &z);
1382 if(!zlen || !z) return 0;
1383 /* zero terminate */
1384 if(zlen >= (long)sizeof(buf)) return 0;
1385 memmove(buf, z, (size_t)zlen);
1388 return (strncasecmp(buf, name, strlen(name)) == 0);
1392 * XML start of element. This callback is called whenever an XML tag starts.
1394 * @param userData: the xml_data structure.
1395 * @param name: the tag that starts.
1396 * @param atts: array of strings, pairs of attr = value, ends with NULL.
1397 * i.e. att[0]="att[1]" att[2]="att[3]" att[4]isNull
1400 xml_startelem(void *userData, const XML_Char *name, const XML_Char **atts)
1402 struct xml_data* data = (struct xml_data*)userData;
1404 if(verb>=4) printf("xml tag start '%s'\n", name);
1406 data->tag = strdup(name);
1408 if(verb) printf("out of memory\n");
1413 for(i=0; atts[i]; i+=2) {
1414 printf(" %s='%s'\n", atts[i], atts[i+1]);
1417 /* handle attributes to particular types */
1418 if(strcasecmp(name, "KeyDigest") == 0) {
1419 handle_keydigest(data, atts);
1421 } else if(strcasecmp(name, "Zone") == 0) {
1422 (void)BIO_reset(data->czone);
1426 /* for other types we prepare to pick up the data */
1429 b = xml_selectbio(data, data->tag);
1436 /** Append str to bio */
1438 xml_append_str(BIO* b, const char* s)
1440 if(BIO_write(b, s, (int)strlen(s)) < 0) {
1441 if(verb) printf("out of memory in BIO_write\n");
1446 /** Append bio to bio */
1448 xml_append_bio(BIO* b, BIO* a)
1452 (void)BIO_seek(a, 0);
1453 len = BIO_get_mem_data(a, &z);
1455 if(verb) printf("out of memory in BIO_write\n");
1458 /* remove newlines in the data here */
1459 for(i=0; i<len; i++) {
1460 if(z[i] == '\r' || z[i] == '\n')
1464 if(BIO_write(b, z, len) < 0) {
1465 if(verb) printf("out of memory in BIO_write\n");
1470 /** write the parsed xml-DS to the DS list */
1472 xml_append_ds(struct xml_data* data)
1474 /* write DS to accumulated DS */
1475 xml_append_str(data->ds, ". IN DS ");
1476 xml_append_bio(data->ds, data->ctag);
1477 xml_append_str(data->ds, " ");
1478 xml_append_bio(data->ds, data->calgo);
1479 xml_append_str(data->ds, " ");
1480 xml_append_bio(data->ds, data->cdigtype);
1481 xml_append_str(data->ds, " ");
1482 xml_append_bio(data->ds, data->cdigest);
1483 xml_append_str(data->ds, "\n");
1488 * XML end of element. This callback is called whenever an XML tag ends.
1490 * @param userData: the xml_data structure
1491 * @param name: the tag that ends.
1494 xml_endelem(void *userData, const XML_Char *name)
1496 struct xml_data* data = (struct xml_data*)userData;
1497 if(verb>=4) printf("xml tag end '%s'\n", name);
1500 if(strcasecmp(name, "KeyDigest") == 0) {
1502 xml_append_ds(data);
1504 } else if(strcasecmp(name, "Zone") == 0) {
1505 if(!xml_is_zone_name(data->czone, ".")) {
1506 if(verb) printf("xml not for the right zone\n");
1512 /* Stop the parser when an entity declaration is encountered. For safety. */
1514 xml_entitydeclhandler(void *userData,
1515 const XML_Char *ATTR_UNUSED(entityName),
1516 int ATTR_UNUSED(is_parameter_entity),
1517 const XML_Char *ATTR_UNUSED(value), int ATTR_UNUSED(value_length),
1518 const XML_Char *ATTR_UNUSED(base),
1519 const XML_Char *ATTR_UNUSED(systemId),
1520 const XML_Char *ATTR_UNUSED(publicId),
1521 const XML_Char *ATTR_UNUSED(notationName))
1523 #if HAVE_DECL_XML_STOPPARSER
1524 (void)XML_StopParser((XML_Parser)userData, XML_FALSE);
1531 * XML parser setup of the callbacks for the tags
1534 xml_parse_setup(XML_Parser parser, struct xml_data* data, time_t now)
1537 memset(data, 0, sizeof(*data));
1538 XML_SetUserData(parser, data);
1539 data->parser = parser;
1541 data->ds = BIO_new(BIO_s_mem());
1542 data->ctag = BIO_new(BIO_s_mem());
1543 data->czone = BIO_new(BIO_s_mem());
1544 data->calgo = BIO_new(BIO_s_mem());
1545 data->cdigtype = BIO_new(BIO_s_mem());
1546 data->cdigest = BIO_new(BIO_s_mem());
1547 if(!data->ds || !data->ctag || !data->calgo || !data->czone ||
1548 !data->cdigtype || !data->cdigest) {
1549 if(verb) printf("out of memory\n");
1552 snprintf(buf, sizeof(buf), "; created by unbound-anchor on %s",
1554 if(BIO_write(data->ds, buf, (int)strlen(buf)) < 0) {
1555 if(verb) printf("out of memory\n");
1558 XML_SetEntityDeclHandler(parser, xml_entitydeclhandler);
1559 XML_SetElementHandler(parser, xml_startelem, xml_endelem);
1560 XML_SetCharacterDataHandler(parser, xml_charhandle);
1564 * Perform XML parsing of the root-anchors file
1565 * Its format description can be read here
1566 * https://data.iana.org/root-anchors/draft-icann-dnssec-trust-anchor.txt
1568 * @param xml: BIO with xml data.
1569 * @param now: the current time for checking DS validity periods.
1570 * @return memoryBIO with the DS data in zone format.
1571 * or NULL if the zone is insecure.
1572 * (It exit()s on error)
1575 xml_parse(BIO* xml, time_t now)
1580 struct xml_data data;
1582 parser = XML_ParserCreate(NULL);
1584 if(verb) printf("could not XML_ParserCreate\n");
1588 /* setup callbacks */
1589 xml_parse_setup(parser, &data, now);
1592 (void)BIO_reset(xml);
1593 len = (int)BIO_get_mem_data(xml, &pp);
1595 if(verb) printf("out of memory\n");
1598 if(!XML_Parse(parser, pp, len, 1 /*isfinal*/ )) {
1599 const char *e = XML_ErrorString(XML_GetErrorCode(parser));
1600 if(verb) printf("XML_Parse failure %s\n", e?e:"");
1605 if(verb) printf("XML was parsed successfully, %d keys\n",
1608 XML_ParserFree(parser);
1611 (void)BIO_seek(data.ds, 0);
1612 len = BIO_get_mem_data(data.ds, &pp);
1613 printf("got DS bio %d: '", len);
1614 if(!fwrite(pp, (size_t)len, 1, stdout))
1615 /* compilers do not allow us to ignore fwrite .. */
1616 fprintf(stderr, "error writing to stdout\n");
1619 BIO_free(data.czone);
1620 BIO_free(data.ctag);
1621 BIO_free(data.calgo);
1622 BIO_free(data.cdigtype);
1623 BIO_free(data.cdigest);
1625 if(data.num_keys == 0) {
1626 /* the root zone seems to have gone insecure */
1634 /* get key usage out of its extension, returns 0 if no key_usage extension */
1635 static unsigned long
1636 get_usage_of_ex(X509* cert)
1638 unsigned long val = 0;
1640 if((s=X509_get_ext_d2i(cert, NID_key_usage, NULL, NULL))) {
1644 val |= s->data[1] << 8;
1646 ASN1_BIT_STRING_free(s);
1651 /** get valid signers from the list of signers in the signature */
1652 static STACK_OF(X509)*
1653 get_valid_signers(PKCS7* p7, const char* p7signer)
1656 STACK_OF(X509)* validsigners = sk_X509_new_null();
1657 STACK_OF(X509)* signers = PKCS7_get0_signers(p7, NULL, 0);
1658 unsigned long usage = 0;
1660 if(verb) printf("out of memory\n");
1661 sk_X509_free(signers);
1665 if(verb) printf("no signers in pkcs7 signature\n");
1666 sk_X509_free(validsigners);
1669 for(i=0; i<sk_X509_num(signers); i++) {
1670 X509_NAME* nm = X509_get_subject_name(
1671 sk_X509_value(signers, i));
1674 if(verb) printf("signer %d: cert has no subject name\n", i);
1678 char* nmline = X509_NAME_oneline(nm, buf,
1680 printf("signer %d: Subject: %s\n", i,
1681 nmline?nmline:"no subject");
1682 if(verb >= 3 && X509_NAME_get_text_by_NID(nm,
1683 NID_commonName, buf, (int)sizeof(buf)))
1684 printf("commonName: %s\n", buf);
1685 if(verb >= 3 && X509_NAME_get_text_by_NID(nm,
1686 NID_pkcs9_emailAddress, buf, (int)sizeof(buf)))
1687 printf("emailAddress: %s\n", buf);
1690 int ku_loc = X509_get_ext_by_NID(
1691 sk_X509_value(signers, i), NID_key_usage, -1);
1692 if(verb >= 3 && ku_loc >= 0) {
1693 X509_EXTENSION *ex = X509_get_ext(
1694 sk_X509_value(signers, i), ku_loc);
1696 printf("keyUsage: ");
1697 X509V3_EXT_print_fp(stdout, ex, 0, 0);
1702 if(!p7signer || strcmp(p7signer, "")==0) {
1703 /* there is no name to check, return all records */
1704 if(verb) printf("did not check commonName of signer\n");
1706 if(!X509_NAME_get_text_by_NID(nm,
1707 NID_pkcs9_emailAddress,
1708 buf, (int)sizeof(buf))) {
1709 if(verb) printf("removed cert with no name\n");
1710 continue; /* no name, no use */
1712 if(strcmp(buf, p7signer) != 0) {
1713 if(verb) printf("removed cert with wrong name\n");
1714 continue; /* wrong name, skip it */
1718 /* check that the key usage allows digital signatures
1720 usage = get_usage_of_ex(sk_X509_value(signers, i));
1721 if(!(usage & KU_DIGITAL_SIGNATURE)) {
1722 if(verb) printf("removed cert with no key usage Digital Signature allowed\n");
1726 /* we like this cert, add it to our list of valid
1727 * signers certificates */
1728 sk_X509_push(validsigners, sk_X509_value(signers, i));
1730 sk_X509_free(signers);
1731 return validsigners;
1734 /** verify a PKCS7 signature, false on failure */
1736 verify_p7sig(BIO* data, BIO* p7s, STACK_OF(X509)* trust, const char* p7signer)
1739 X509_STORE *store = X509_STORE_new();
1740 STACK_OF(X509)* validsigners;
1743 #ifdef X509_V_FLAG_CHECK_SS_SIGNATURE
1744 X509_VERIFY_PARAM* param = X509_VERIFY_PARAM_new();
1746 if(verb) printf("out of memory\n");
1747 X509_STORE_free(store);
1750 /* do the selfcheck on the root certificate; it checks that the
1752 X509_VERIFY_PARAM_set_flags(param, X509_V_FLAG_CHECK_SS_SIGNATURE);
1753 if(store) X509_STORE_set1_param(store, param);
1756 if(verb) printf("out of memory\n");
1757 #ifdef X509_V_FLAG_CHECK_SS_SIGNATURE
1758 X509_VERIFY_PARAM_free(param);
1762 #ifdef X509_V_FLAG_CHECK_SS_SIGNATURE
1763 X509_VERIFY_PARAM_free(param);
1766 (void)BIO_reset(p7s);
1767 (void)BIO_reset(data);
1769 /* convert p7s to p7 (the signature) */
1770 p7 = d2i_PKCS7_bio(p7s, NULL);
1772 if(verb) printf("could not parse p7s signature file\n");
1773 X509_STORE_free(store);
1776 if(verb >= 2) printf("parsed the PKCS7 signature\n");
1778 /* convert trust to trusted certificate store */
1779 for(i=0; i<sk_X509_num(trust); i++) {
1780 if(!X509_STORE_add_cert(store, sk_X509_value(trust, i))) {
1781 if(verb) printf("failed X509_STORE_add_cert\n");
1782 X509_STORE_free(store);
1787 if(verb >= 2) printf("setup the X509_STORE\n");
1789 /* check what is in the Subject name of the certificates,
1790 * and build a stack that contains only the right certificates */
1791 validsigners = get_valid_signers(p7, p7signer);
1793 X509_STORE_free(store);
1797 if(PKCS7_verify(p7, validsigners, store, data, NULL, PKCS7_NOINTERN) == 1) {
1799 if(verb) printf("the PKCS7 signature verified\n");
1802 ERR_print_errors_fp(stdout);
1806 sk_X509_free(validsigners);
1807 X509_STORE_free(store);
1812 /** write unsigned root anchor file, a 5011 revoked tp */
1814 write_unsigned_root(const char* root_anchor_file)
1817 time_t now = time(NULL);
1818 out = fopen(root_anchor_file, "w");
1820 if(verb) printf("%s: %s\n", root_anchor_file, strerror(errno));
1823 if(fprintf(out, "; autotrust trust anchor file\n"
1826 "; This file was written by unbound-anchor on %s"
1827 "; It indicates that the root does not use DNSSEC\n"
1828 "; to restart DNSSEC overwrite this file with a\n"
1829 "; valid trustanchor or (empty-it and run unbound-anchor)\n"
1830 , ctime(&now)) < 0) {
1831 if(verb) printf("failed to write 'unsigned' to %s\n",
1833 if(verb && errno != 0) printf("%s\n", strerror(errno));
1839 FlushFileBuffers((HANDLE)_fileno(out));
1844 /** write root anchor file */
1846 write_root_anchor(const char* root_anchor_file, BIO* ds)
1851 (void)BIO_seek(ds, 0);
1852 len = BIO_get_mem_data(ds, &pp);
1854 if(verb) printf("out of memory\n");
1857 out = fopen(root_anchor_file, "w");
1859 if(verb) printf("%s: %s\n", root_anchor_file, strerror(errno));
1862 if(fwrite(pp, (size_t)len, 1, out) != 1) {
1863 if(verb) printf("failed to write all data to %s\n",
1865 if(verb && errno != 0) printf("%s\n", strerror(errno));
1871 FlushFileBuffers((HANDLE)_fileno(out));
1876 /** Perform the verification and update of the trustanchor file */
1878 verify_and_update_anchor(const char* root_anchor_file, BIO* xml, BIO* p7s,
1879 STACK_OF(X509)* cert, const char* p7signer)
1883 /* verify xml file */
1884 if(!verify_p7sig(xml, p7s, cert, p7signer)) {
1885 printf("the PKCS7 signature failed\n");
1889 /* parse the xml file into DS records */
1890 ds = xml_parse(xml, time(NULL));
1892 /* the root zone is unsigned now */
1893 write_unsigned_root(root_anchor_file);
1895 /* reinstate 5011 tracking */
1896 write_root_anchor(root_anchor_file, ds);
1902 static void do_wsa_cleanup(void) { WSACleanup(); }
1905 /** perform actual certupdate work */
1907 do_certupdate(const char* root_anchor_file, const char* root_cert_file,
1908 const char* urlname, const char* xmlname, const char* p7sname,
1909 const char* p7signer, const char* res_conf, const char* root_hints,
1910 const char* debugconf, int ip4only, int ip6only, int port,
1911 struct ub_result* dnskey)
1913 STACK_OF(X509)* cert;
1915 struct ip_list* ip_list = NULL;
1917 /* read pem file or provide builtin */
1918 cert = read_cert_or_builtin(root_cert_file);
1920 /* lookup A, AAAA for the urlname (or parse urlname if IP address) */
1921 ip_list = resolve_name(urlname, port, res_conf, root_hints, debugconf,
1925 if(1) { /* libunbound finished, startup WSA for the https connection */
1928 if((r = WSAStartup(MAKEWORD(2,2), &wsa_data)) != 0) {
1929 if(verb) printf("WSAStartup failed: %s\n",
1933 atexit(&do_wsa_cleanup);
1937 /* fetch the necessary files over HTTPS */
1938 xml = https(ip_list, xmlname, urlname);
1939 p7s = https(ip_list, p7sname, urlname);
1941 /* verify and update the root anchor */
1942 verify_and_update_anchor(root_anchor_file, xml, p7s, cert, p7signer);
1943 if(verb) printf("success: the anchor has been updated "
1944 "using the cert\n");
1949 sk_X509_pop_free(cert, X509_free);
1951 ub_resolve_free(dnskey);
1952 ip_list_free(ip_list);
1957 * Try to read the root RFC5011 autotrust anchor file,
1958 * @param file: filename.
1960 * 0 if does not exist or empty
1961 * 1 if trust-point-revoked-5011
1965 try_read_anchor(const char* file)
1970 FILE* in = fopen(file, "r");
1972 /* only if the file does not exist, can we fix it */
1973 if(errno != ENOENT) {
1974 if(verb) printf("%s: %s\n", file, strerror(errno));
1975 if(verb) printf("error: cannot access the file\n");
1978 if(verb) printf("%s does not exist\n", file);
1981 while(fgets(line, (int)sizeof(line), in)) {
1982 line[sizeof(line)-1] = 0;
1983 if(strncmp(line, ";;REVOKED", 9) == 0) {
1985 if(verb) printf("%s : the trust point is revoked\n"
1986 "and the zone is considered unsigned.\n"
1987 "if you wish to re-enable, delete the file\n",
1992 while(*p == ' ' || *p == '\t')
1994 if(p[0]==0 || p[0]=='\n' || p[0]==';') continue;
1995 /* this line is a line of content */
2000 if(verb) printf("%s is empty\n", file);
2003 if(verb) printf("%s has content\n", file);
2007 /** Write the builtin root anchor to a file */
2009 write_builtin_anchor(const char* file)
2011 const char* builtin_root_anchor = get_builtin_ds();
2012 FILE* out = fopen(file, "w");
2014 if(verb) printf("%s: %s\n", file, strerror(errno));
2015 if(verb) printf(" could not write builtin anchor\n");
2018 if(!fwrite(builtin_root_anchor, strlen(builtin_root_anchor), 1, out)) {
2019 if(verb) printf("%s: %s\n", file, strerror(errno));
2020 if(verb) printf(" could not complete write builtin anchor\n");
2026 * Check the root anchor file.
2027 * If does not exist, provide builtin and write file.
2028 * If empty, provide builtin and write file.
2029 * If trust-point-revoked-5011 file: make the program exit.
2030 * @param root_anchor_file: filename of the root anchor.
2031 * @param used_builtin: set to 1 if the builtin is written.
2032 * @return 0 if trustpoint is insecure, 1 on success. Exit on failure.
2035 provide_builtin(const char* root_anchor_file, int* used_builtin)
2037 /* try to read it */
2038 switch(try_read_anchor(root_anchor_file))
2040 case 0: /* no exist or empty */
2041 write_builtin_anchor(root_anchor_file);
2044 case 1: /* revoked tp */
2046 case 2: /* it is fine */
2054 * add an autotrust anchor for the root to the context
2057 add_5011_probe_root(struct ub_ctx* ctx, const char* root_anchor_file)
2060 r = ub_ctx_set_option(ctx, "auto-trust-anchor-file:", root_anchor_file);
2062 if(verb) printf("add 5011 probe to ctx: %s\n", ub_strerror(r));
2069 * Prime the root key and return the result. Exit on error.
2070 * @param ctx: the unbound context to perform the priming with.
2071 * @return: the result of the prime, on error it exit()s.
2073 static struct ub_result*
2074 prime_root_key(struct ub_ctx* ctx)
2076 struct ub_result* res = NULL;
2078 r = ub_resolve(ctx, ".", LDNS_RR_TYPE_DNSKEY, LDNS_RR_CLASS_IN, &res);
2080 if(verb) printf("resolve DNSKEY: %s\n", ub_strerror(r));
2085 if(verb) printf("out of memory\n");
2092 /** see if ADDPEND keys exist in autotrust file (if possible) */
2094 read_if_pending_keys(const char* file)
2096 FILE* in = fopen(file, "r");
2099 if(verb>=2) printf("%s: %s\n", file, strerror(errno));
2102 while(fgets(line, (int)sizeof(line), in)) {
2103 if(line[0]==';') continue;
2104 if(strstr(line, "[ ADDPEND ]")) {
2106 if(verb) printf("RFC5011-state has ADDPEND keys\n");
2114 /** read last successful probe time from autotrust file (if possible) */
2116 read_last_success_time(const char* file)
2118 FILE* in = fopen(file, "r");
2121 if(verb) printf("%s: %s\n", file, strerror(errno));
2124 while(fgets(line, (int)sizeof(line), in)) {
2125 if(strncmp(line, ";;last_success: ", 16) == 0) {
2127 time_t x = (unsigned int)strtol(line+16, &e, 10);
2130 if(verb) printf("failed to parse "
2131 "last_success probe time\n");
2134 if(verb) printf("last successful probe: %s", ctime(&x));
2139 if(verb) printf("no last_success probe time in anchor file\n");
2144 * Read autotrust 5011 probe file and see if the date
2145 * compared to the current date allows a certupdate.
2146 * If the last successful probe was recent then 5011 cannot be behind,
2147 * and the failure cannot be solved with a certupdate.
2148 * The debugconf is to validation-override the date for testing.
2149 * @param root_anchor_file: filename of root key
2150 * @return true if certupdate is ok.
2153 probe_date_allows_certupdate(const char* root_anchor_file)
2155 int has_pending_keys = read_if_pending_keys(root_anchor_file);
2156 int32_t last_success = read_last_success_time(root_anchor_file);
2157 int32_t now = (int32_t)time(NULL);
2158 int32_t leeway = 30 * 24 * 3600; /* 30 days leeway */
2159 /* if the date is before 2010-07-15:00.00.00 then the root has not
2160 * been signed yet, and thus we refuse to take action. */
2161 if(time(NULL) < xml_convertdate("2010-07-15T00:00:00")) {
2162 if(verb) printf("the date is before the root was first signed,"
2163 " please correct the clock\n");
2166 if(last_success == 0)
2167 return 1; /* no probe time */
2168 if(has_pending_keys)
2169 return 1; /* key in ADDPEND state, a previous probe has
2170 inserted that, and it was present in all recent probes,
2171 but it has not become active. The 30 day timer may not have
2172 expired, but we know(for sure) there is a rollover going on.
2173 If we only managed to pickup the new key on its last day
2174 of announcement (for example) this can happen. */
2175 if(now - last_success < 0) {
2176 if(verb) printf("the last successful probe is in the future,"
2177 " clock was modified\n");
2180 if(now - last_success >= leeway) {
2181 if(verb) printf("the last successful probe was more than 30 "
2185 if(verb) printf("the last successful probe is recent\n");
2189 /** perform the unbound-anchor work */
2191 do_root_update_work(const char* root_anchor_file, const char* root_cert_file,
2192 const char* urlname, const char* xmlname, const char* p7sname,
2193 const char* p7signer, const char* res_conf, const char* root_hints,
2194 const char* debugconf, int ip4only, int ip6only, int force, int port)
2197 struct ub_result* dnskey;
2198 int used_builtin = 0;
2200 /* see if builtin rootanchor needs to be provided, or if
2201 * rootanchor is 'revoked-trust-point' */
2202 if(!provide_builtin(root_anchor_file, &used_builtin))
2205 /* make unbound context with 5011-probe for root anchor,
2206 * and probe . DNSKEY */
2207 ctx = create_unbound_context(res_conf, root_hints, debugconf,
2209 add_5011_probe_root(ctx, root_anchor_file);
2210 dnskey = prime_root_key(ctx);
2213 /* if secure: exit */
2214 if(dnskey->secure && !force) {
2215 if(verb) printf("success: the anchor is ok\n");
2216 ub_resolve_free(dnskey);
2217 return used_builtin;
2219 if(force && verb) printf("debug cert update forced\n");
2221 /* if not (and NOERROR): check date and do certupdate */
2222 if((dnskey->rcode == 0 &&
2223 probe_date_allows_certupdate(root_anchor_file)) || force) {
2224 if(do_certupdate(root_anchor_file, root_cert_file, urlname,
2225 xmlname, p7sname, p7signer, res_conf, root_hints,
2226 debugconf, ip4only, ip6only, port, dnskey))
2228 return used_builtin;
2230 if(verb) printf("fail: the anchor is NOT ok and could not be fixed\n");
2231 ub_resolve_free(dnskey);
2232 return used_builtin;
2235 /** getopt global, in case header files fail to declare it. */
2237 /** getopt global, in case header files fail to declare it. */
2238 extern char* optarg;
2240 /** Main routine for unbound-anchor */
2241 int main(int argc, char* argv[])
2244 const char* root_anchor_file = ROOT_ANCHOR_FILE;
2245 const char* root_cert_file = ROOT_CERT_FILE;
2246 const char* urlname = URLNAME;
2247 const char* xmlname = XMLNAME;
2248 const char* p7sname = P7SNAME;
2249 const char* p7signer = P7SIGNER;
2250 const char* res_conf = NULL;
2251 const char* root_hints = NULL;
2252 const char* debugconf = NULL;
2253 int dolist=0, ip4only=0, ip6only=0, force=0, port = HTTPS_PORT;
2254 /* parse the options */
2255 while( (c=getopt(argc, argv, "46C:FP:a:c:f:hln:r:s:u:vx:")) != -1) {
2267 root_anchor_file = optarg;
2270 root_cert_file = optarg;
2288 root_hints = optarg;
2297 port = atoi(optarg);
2313 ERR_load_crypto_strings();
2314 ERR_load_SSL_strings();
2315 OpenSSL_add_all_algorithms();
2316 (void)SSL_library_init();
2318 if(dolist) do_list_builtin();
2320 return do_root_update_work(root_anchor_file, root_cert_file, urlname,
2321 xmlname, p7sname, p7signer, res_conf, root_hints, debugconf,
2322 ip4only, ip6only, force, port);