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 LIMITED
25 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
26 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE
27 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
28 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
29 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
30 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
31 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
32 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
33 * 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 * unneccesary 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"
122 #error "need libexpat to parse root-anchors.xml file."
127 #ifdef HAVE_OPENSSL_SSL_H
128 #include <openssl/ssl.h>
130 #ifdef HAVE_OPENSSL_ERR_H
131 #include <openssl/err.h>
133 #ifdef HAVE_OPENSSL_RAND_H
134 #include <openssl/rand.h>
136 #include <openssl/x509.h>
137 #include <openssl/x509v3.h>
138 #include <openssl/pem.h>
140 /** name of server in URL to fetch HTTPS from */
141 #define URLNAME "data.iana.org"
142 /** path on HTTPS server to xml file */
143 #define XMLNAME "root-anchors/root-anchors.xml"
144 /** path on HTTPS server to p7s file */
145 #define P7SNAME "root-anchors/root-anchors.p7s"
146 /** name of the signer of the certificate */
147 #define P7SIGNER "dnssec@iana.org"
148 /** port number for https access */
149 #define HTTPS_PORT 443
152 /* sneakily reuse the the wsa_strerror function, on windows */
153 char* wsa_strerror(int err);
156 /** verbosity for this application */
159 /** list of IP addresses */
162 struct ip_list* next;
163 /** length of addr */
165 /** address ready to connect to */
166 struct sockaddr_storage addr;
167 /** has the address been used */
171 /** Give unbound-anchor usage, and exit (1). */
175 printf("Usage: unbound-anchor [opts]\n");
176 printf(" Setup or update root anchor. "
177 "Most options have defaults.\n");
178 printf(" Run this program before you start the validator.\n");
180 printf(" The anchor and cert have default builtin content\n");
181 printf(" if the file does not exist or is empty.\n");
183 printf("-a file root key file, default %s\n", ROOT_ANCHOR_FILE);
184 printf(" The key is input and output for this tool.\n");
185 printf("-c file cert file, default %s\n", ROOT_CERT_FILE);
186 printf("-l list builtin key and cert on stdout\n");
187 printf("-u name server in https url, default %s\n", URLNAME);
188 printf("-x path pathname to xml in url, default %s\n", XMLNAME);
189 printf("-s path pathname to p7s in url, default %s\n", P7SNAME);
190 printf("-n name signer's subject emailAddress, default %s\n", P7SIGNER);
191 printf("-4 work using IPv4 only\n");
192 printf("-6 work using IPv6 only\n");
193 printf("-f resolv.conf use given resolv.conf to resolve -u name\n");
194 printf("-r root.hints use given root.hints to resolve -u name\n"
195 " builtin root hints are used by default\n");
196 printf("-v more verbose\n");
197 printf("-C conf debug, read config\n");
198 printf("-P port use port for https connect, default 443\n");
199 printf("-F debug, force update with cert\n");
200 printf("-h show this usage help\n");
201 printf("Version %s\n", PACKAGE_VERSION);
202 printf("BSD licensed, see LICENSE in source package for details.\n");
203 printf("Report bugs to %s\n", PACKAGE_BUGREPORT);
207 /** return the built in root update certificate */
209 get_builtin_cert(void)
212 /* The ICANN CA fetched at 24 Sep 2010. Valid to 2028 */
213 "-----BEGIN CERTIFICATE-----\n"
214 "MIIDdzCCAl+gAwIBAgIBATANBgkqhkiG9w0BAQsFADBdMQ4wDAYDVQQKEwVJQ0FO\n"
215 "TjEmMCQGA1UECxMdSUNBTk4gQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkxFjAUBgNV\n"
216 "BAMTDUlDQU5OIFJvb3QgQ0ExCzAJBgNVBAYTAlVTMB4XDTA5MTIyMzA0MTkxMloX\n"
217 "DTI5MTIxODA0MTkxMlowXTEOMAwGA1UEChMFSUNBTk4xJjAkBgNVBAsTHUlDQU5O\n"
218 "IENlcnRpZmljYXRpb24gQXV0aG9yaXR5MRYwFAYDVQQDEw1JQ0FOTiBSb290IENB\n"
219 "MQswCQYDVQQGEwJVUzCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAKDb\n"
220 "cLhPNNqc1NB+u+oVvOnJESofYS9qub0/PXagmgr37pNublVThIzyLPGCJ8gPms9S\n"
221 "G1TaKNIsMI7d+5IgMy3WyPEOECGIcfqEIktdR1YWfJufXcMReZwU4v/AdKzdOdfg\n"
222 "ONiwc6r70duEr1IiqPbVm5T05l1e6D+HkAvHGnf1LtOPGs4CHQdpIUcy2kauAEy2\n"
223 "paKcOcHASvbTHK7TbbvHGPB+7faAztABLoneErruEcumetcNfPMIjXKdv1V1E3C7\n"
224 "MSJKy+jAqqQJqjZoQGB0necZgUMiUv7JK1IPQRM2CXJllcyJrm9WFxY0c1KjBO29\n"
225 "iIKK69fcglKcBuFShUECAwEAAaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8B\n"
226 "Af8EBAMCAf4wHQYDVR0OBBYEFLpS6UmDJIZSL8eZzfyNa2kITcBQMA0GCSqGSIb3\n"
227 "DQEBCwUAA4IBAQAP8emCogqHny2UYFqywEuhLys7R9UKmYY4suzGO4nkbgfPFMfH\n"
228 "6M+Zj6owwxlwueZt1j/IaCayoKU3QsrYYoDRolpILh+FPwx7wseUEV8ZKpWsoDoD\n"
229 "2JFbLg2cfB8u/OlE4RYmcxxFSmXBg0yQ8/IoQt/bxOcEEhhiQ168H2yE5rxJMt9h\n"
230 "15nu5JBSewrCkYqYYmaxyOC3WrVGfHZxVI7MpIFcGdvSb2a1uyuua8l0BKgk3ujF\n"
231 "0/wsHNeP22qNyVO+XVBzrM8fk8BSUFuiT/6tZTYXRtEt5aKQZgXbKU5dUF3jT9qg\n"
232 "j/Br5BZw3X/zd325TvnswzMC1+ljLzHnQGGk\n"
233 "-----END CERTIFICATE-----\n"
237 /** return the built in root DS trust anchor */
242 ". IN DS 19036 8 2 49AAC11D7B6F6446702E54A1607371607A1A41855200FD2CE1CDDE32F24E8FB5\n";
245 /** print hex data */
247 print_data(char* msg, char* data, int len)
251 for(i=0; i<len; i++) {
252 printf(" %2.2x", (unsigned char)data[i]);
257 /** print ub context creation error and exit */
259 ub_ctx_error_exit(struct ub_ctx* ctx, const char* str, const char* str2)
262 if(str && str2 && verb) printf("%s: %s\n", str, str2);
263 if(verb) printf("error: could not create unbound resolver context\n");
268 * Create a new unbound context with the commandline settings applied
270 static struct ub_ctx*
271 create_unbound_context(char* res_conf, char* root_hints, char* debugconf,
272 int ip4only, int ip6only)
275 struct ub_ctx* ctx = ub_ctx_create();
277 if(verb) printf("out of memory\n");
280 /* do not waste time and network traffic to fetch extra nameservers */
281 r = ub_ctx_set_option(ctx, "target-fetch-policy:", "0 0 0 0 0");
282 if(r && verb) printf("ctx targetfetchpolicy: %s\n", ub_strerror(r));
283 /* read config file first, so its settings can be overridden */
285 r = ub_ctx_config(ctx, debugconf);
286 if(r) ub_ctx_error_exit(ctx, debugconf, ub_strerror(r));
289 r = ub_ctx_resolvconf(ctx, res_conf);
290 if(r) ub_ctx_error_exit(ctx, res_conf, ub_strerror(r));
293 r = ub_ctx_set_option(ctx, "root-hints:", root_hints);
294 if(r) ub_ctx_error_exit(ctx, root_hints, ub_strerror(r));
297 r = ub_ctx_set_option(ctx, "do-ip6:", "no");
298 if(r) ub_ctx_error_exit(ctx, "ip4only", ub_strerror(r));
301 r = ub_ctx_set_option(ctx, "do-ip4:", "no");
302 if(r) ub_ctx_error_exit(ctx, "ip6only", ub_strerror(r));
307 /** printout certificate in detail */
309 verb_cert(char* msg, X509* x)
311 if(verb == 0 || verb == 1) return;
313 if(msg) printf("%s\n", msg);
314 X509_print_ex_fp(stdout, x, 0, (unsigned long)-1
315 ^(X509_FLAG_NO_SUBJECT
316 |X509_FLAG_NO_ISSUER|X509_FLAG_NO_VALIDITY));
319 if(msg) printf("%s\n", msg);
320 X509_print_fp(stdout, x);
323 /** printout certificates in detail */
325 verb_certs(char* msg, STACK_OF(X509)* sk)
327 int i, num = sk_X509_num(sk);
328 if(verb == 0 || verb == 1) return;
329 for(i=0; i<num; i++) {
330 printf("%s (%d/%d)\n", msg, i, num);
331 verb_cert(NULL, sk_X509_value(sk, i));
335 /** read certificates from a PEM bio */
336 static STACK_OF(X509)*
337 read_cert_bio(BIO* bio)
339 STACK_OF(X509) *sk = sk_X509_new_null();
341 if(verb) printf("out of memory\n");
344 while(!BIO_eof(bio)) {
345 X509* x = PEM_read_bio_X509(bio, NULL, 0, NULL);
348 printf("failed to read X509\n");
349 ERR_print_errors_fp(stdout);
353 if(!sk_X509_push(sk, x)) {
354 if(verb) printf("out of memory\n");
361 /* read the certificate file */
362 static STACK_OF(X509)*
363 read_cert_file(char* file)
369 if(file == NULL || strcmp(file, "") == 0) {
372 sk = sk_X509_new_null();
374 if(verb) printf("out of memory\n");
377 in = fopen(file, "r");
379 if(verb) printf("%s: %s\n", file, strerror(errno));
381 sk_X509_pop_free(sk, X509_free);
386 X509* x = PEM_read_X509(in, NULL, 0, NULL);
389 printf("failed to read X509 file\n");
390 ERR_print_errors_fp(stdout);
394 if(!sk_X509_push(sk, x)) {
395 if(verb) printf("out of memory\n");
400 /* read away newline after --END CERT-- */
401 if(!fgets(buf, (int)sizeof(buf), in))
406 if(verb) printf("%s is empty\n", file);
408 sk_X509_pop_free(sk, X509_free);
415 /** read certificates from the builtin certificate */
416 static STACK_OF(X509)*
417 read_builtin_cert(void)
419 const char* builtin_cert = get_builtin_cert();
421 BIO *bio = BIO_new_mem_buf((void*)builtin_cert,
422 (int)strlen(builtin_cert));
424 if(verb) printf("out of memory\n");
427 sk = read_cert_bio(bio);
429 if(verb) printf("internal error, out of memory\n");
436 /** read update cert file or use builtin */
437 static STACK_OF(X509)*
438 read_cert_or_builtin(char* file)
440 STACK_OF(X509) *sk = read_cert_file(file);
442 if(verb) printf("using builtin certificate\n");
443 sk = read_builtin_cert();
445 if(verb) printf("have %d trusted certificates\n", sk_X509_num(sk));
446 verb_certs("trusted certificates", sk);
451 do_list_builtin(void)
453 const char* builtin_cert = get_builtin_cert();
454 const char* builtin_ds = get_builtin_ds();
455 printf("%s\n", builtin_ds);
456 printf("%s\n", builtin_cert);
460 /** printout IP address with message */
462 verb_addr(char* msg, struct ip_list* ip)
466 void* a = &((struct sockaddr_in*)&ip->addr)->sin_addr;
467 if(ip->len != (socklen_t)sizeof(struct sockaddr_in))
468 a = &((struct sockaddr_in6*)&ip->addr)->sin6_addr;
470 if(inet_ntop((int)((struct sockaddr_in*)&ip->addr)->sin_family,
471 a, out, (socklen_t)sizeof(out))==0)
472 printf("%s (inet_ntop error)\n", msg);
473 else printf("%s %s\n", msg, out);
479 ip_list_free(struct ip_list* p)
489 /** create ip_list entry for a RR record */
490 static struct ip_list*
491 RR_to_ip(int tp, char* data, int len, int port)
493 struct ip_list* ip = (struct ip_list*)calloc(1, sizeof(*ip));
494 uint16_t p = (uint16_t)port;
495 if(tp == LDNS_RR_TYPE_A) {
496 struct sockaddr_in* sa = (struct sockaddr_in*)&ip->addr;
497 ip->len = (socklen_t)sizeof(*sa);
498 sa->sin_family = AF_INET;
499 sa->sin_port = (in_port_t)htons(p);
500 if(len != (int)sizeof(sa->sin_addr)) {
501 if(verb) printf("skipped badly formatted A\n");
505 memmove(&sa->sin_addr, data, sizeof(sa->sin_addr));
507 } else if(tp == LDNS_RR_TYPE_AAAA) {
508 struct sockaddr_in6* sa = (struct sockaddr_in6*)&ip->addr;
509 ip->len = (socklen_t)sizeof(*sa);
510 sa->sin6_family = AF_INET6;
511 sa->sin6_port = (in_port_t)htons(p);
512 if(len != (int)sizeof(sa->sin6_addr)) {
513 if(verb) printf("skipped badly formatted AAAA\n");
517 memmove(&sa->sin6_addr, data, sizeof(sa->sin6_addr));
519 if(verb) printf("internal error: bad type in RRtoip\n");
523 verb_addr("resolved server address", ip);
527 /** Resolve name, type, class and add addresses to iplist */
529 resolve_host_ip(struct ub_ctx* ctx, char* host, int port, int tp, int cl,
530 struct ip_list** head)
532 struct ub_result* res = NULL;
536 r = ub_resolve(ctx, host, tp, cl, &res);
538 if(verb) printf("error: resolve %s %s: %s\n", host,
539 (tp==LDNS_RR_TYPE_A)?"A":"AAAA", ub_strerror(r));
543 if(verb) printf("out of memory\n");
547 if(!res->havedata || res->rcode || !res->data) {
548 if(verb) printf("resolve %s %s: no result\n", host,
549 (tp==LDNS_RR_TYPE_A)?"A":"AAAA");
552 for(i = 0; res->data[i]; i++) {
553 struct ip_list* ip = RR_to_ip(tp, res->data[i], res->len[i],
559 ub_resolve_free(res);
562 /** parse a text IP address into a sockaddr */
563 static struct ip_list*
564 parse_ip_addr(char* str, int port)
567 struct sockaddr_storage* addr = NULL;
568 struct sockaddr_in6 a6;
569 struct sockaddr_in a;
571 uint16_t p = (uint16_t)port;
572 memset(&a6, 0, sizeof(a6));
573 memset(&a, 0, sizeof(a));
575 if(inet_pton(AF_INET6, str, &a6.sin6_addr) > 0) {
577 a6.sin6_family = AF_INET6;
578 a6.sin6_port = (in_port_t)htons(p);
579 addr = (struct sockaddr_storage*)&a6;
580 len = (socklen_t)sizeof(struct sockaddr_in6);
582 if(inet_pton(AF_INET, str, &a.sin_addr) > 0) {
584 a.sin_family = AF_INET;
585 a.sin_port = (in_port_t)htons(p);
586 addr = (struct sockaddr_storage*)&a;
587 len = (socklen_t)sizeof(struct sockaddr_in);
589 if(!len) return NULL;
590 ip = (struct ip_list*)calloc(1, sizeof(*ip));
592 if(verb) printf("out of memory\n");
596 memmove(&ip->addr, addr, len);
597 if(verb) printf("server address is %s\n", str);
602 * Resolve a domain name (even though the resolver is down and there is
603 * no trust anchor). Without DNSSEC validation.
604 * @param host: the name to resolve.
605 * If this name is an IP4 or IP6 address this address is returned.
606 * @param port: the port number used for the returned IP structs.
607 * @param res_conf: resolv.conf (if any).
608 * @param root_hints: root hints (if any).
609 * @param debugconf: unbound.conf for debugging options.
610 * @param ip4only: use only ip4 for resolve and only lookup A
611 * @param ip6only: use only ip6 for resolve and only lookup AAAA
612 * default is to lookup A and AAAA using ip4 and ip6.
613 * @return list of IP addresses.
615 static struct ip_list*
616 resolve_name(char* host, int port, char* res_conf, char* root_hints,
617 char* debugconf, int ip4only, int ip6only)
620 struct ip_list* list = NULL;
621 /* first see if name is an IP address itself */
622 if( (list=parse_ip_addr(host, port)) ) {
626 /* create resolver context */
627 ctx = create_unbound_context(res_conf, root_hints, debugconf,
630 /* try resolution of A */
632 resolve_host_ip(ctx, host, port, LDNS_RR_TYPE_A,
633 LDNS_RR_CLASS_IN, &list);
636 /* try resolution of AAAA */
638 resolve_host_ip(ctx, host, port, LDNS_RR_TYPE_AAAA,
639 LDNS_RR_CLASS_IN, &list);
644 if(verb) printf("%s has no IP addresses I can use\n", host);
650 /** clear used flags */
652 wipe_ip_usage(struct ip_list* p)
660 /** cound unused IPs */
662 count_unused(struct ip_list* p)
672 /** pick random unused element from IP list */
673 static struct ip_list*
674 pick_random_ip(struct ip_list* list)
676 struct ip_list* p = list;
677 int num = count_unused(list);
679 if(num == 0) return NULL;
680 /* not perfect, but random enough */
681 sel = (int)ldns_get_random() % num;
682 /* skip over unused elements that we did not select */
683 while(sel > 0 && p) {
687 /* find the next unused element */
690 if(!p) return NULL; /* robustness */
705 /** printout socket errno */
707 print_sock_err(const char* msg)
710 if(verb) printf("%s: %s\n", msg, strerror(errno));
712 if(verb) printf("%s: %s\n", msg, wsa_strerror(WSAGetLastError()));
716 /** connect to IP address */
718 connect_to_ip(struct ip_list* ip)
721 verb_addr("connect to", ip);
722 fd = socket(ip->len==(socklen_t)sizeof(struct sockaddr_in)?
723 AF_INET:AF_INET6, SOCK_STREAM, 0);
725 print_sock_err("socket");
728 if(connect(fd, (struct sockaddr*)&ip->addr, ip->len) < 0) {
729 print_sock_err("connect");
736 /** create SSL context */
740 SSL_CTX* sslctx = SSL_CTX_new(SSLv23_client_method());
742 if(verb) printf("SSL_CTX_new error\n");
748 /** initiate TLS on a connection */
750 TLS_initiate(SSL_CTX* sslctx, int fd)
754 SSL* ssl = SSL_new(sslctx);
756 if(verb) printf("SSL_new error\n");
759 SSL_set_connect_state(ssl);
760 (void)SSL_set_mode(ssl, SSL_MODE_AUTO_RETRY);
761 if(!SSL_set_fd(ssl, fd)) {
762 if(verb) printf("SSL_set_fd error\n");
768 if( (r=SSL_do_handshake(ssl)) == 1)
770 r = SSL_get_error(ssl, r);
771 if(r != SSL_ERROR_WANT_READ && r != SSL_ERROR_WANT_WRITE) {
772 if(verb) printf("SSL handshake failed\n");
776 /* wants to be called again */
778 x = SSL_get_peer_certificate(ssl);
780 if(verb) printf("Server presented no peer certificate\n");
784 verb_cert("server SSL certificate", x);
789 /** perform neat TLS shutdown */
791 TLS_shutdown(int fd, SSL* ssl, SSL_CTX* sslctx)
793 /* shutdown the SSL connection nicely */
794 if(SSL_shutdown(ssl) == 0) {
798 SSL_CTX_free(sslctx);
802 /** write a line over SSL */
804 write_ssl_line(SSL* ssl, char* str, char* sec)
809 snprintf(buf, sizeof(buf), str, sec);
811 snprintf(buf, sizeof(buf), "%s", str);
814 if(l+2 >= sizeof(buf)) {
815 if(verb) printf("line too long\n");
818 if(verb >= 2) printf("SSL_write: %s\n", buf);
823 if(SSL_write(ssl, buf, (int)strlen(buf)) <= 0) {
824 if(verb) printf("could not SSL_write %s", str);
830 /** process header line, check rcode and keeping track of size */
832 process_one_header(char* buf, size_t* clen, int* chunked)
834 if(verb>=2) printf("header: '%s'\n", buf);
835 if(strncasecmp(buf, "HTTP/1.1 ", 9) == 0) {
836 /* check returncode */
838 if(verb) printf("bad status %s\n", buf+9);
841 } else if(strncasecmp(buf, "Content-Length: ", 16) == 0) {
843 *clen = (size_t)atoi(buf+16);
844 } else if(strncasecmp(buf, "Transfer-Encoding: chunked", 19+7) == 0) {
852 * Read one line from SSL
854 * skips "\r\n" (but not copied to buf).
855 * @param ssl: the SSL connection to read from (blocking).
856 * @param buf: buffer to return line in.
857 * @param len: size of the buffer.
858 * @return 0 on error, 1 on success.
861 read_ssl_line(SSL* ssl, char* buf, size_t len)
868 if(verb) printf("line too long\n");
871 if((r = SSL_read(ssl, buf+n, 1)) <= 0) {
872 if(SSL_get_error(ssl, r) == SSL_ERROR_ZERO_RETURN) {
876 if(verb) printf("could not SSL_read\n");
879 if(endnl && buf[n] == '\n') {
883 if(verb) printf("error: stray linefeeds\n");
885 } else if(buf[n] == '\r') {
886 /* skip \r, and also \n on the wire */
889 } else if(buf[n] == '\n') {
890 /* skip the \n, we are done */
898 /** read http headers and process them */
900 read_http_headers(SSL* ssl, size_t* clen)
905 while(read_ssl_line(ssl, buf, sizeof(buf))) {
908 if(!process_one_header(buf, clen, &chunked))
914 /** read a data chunk */
916 read_data_chunk(SSL* ssl, size_t len)
920 char* data = malloc(len+1);
922 if(verb) printf("out of memory\n");
926 if((r = SSL_read(ssl, data+got, (int)(len-got))) <= 0) {
927 if(SSL_get_error(ssl, r) == SSL_ERROR_ZERO_RETURN) {
929 if(verb) printf("could not SSL_read: unexpected EOF\n");
933 if(verb) printf("could not SSL_read\n");
937 if(verb >= 2) printf("at %d/%d\n", (int)got, (int)len);
940 if(verb>=2) printf("read %d data\n", (int)len);
945 /** parse chunk header */
947 parse_chunk_header(char* buf, size_t* result)
950 size_t v = (size_t)strtol(buf, &e, 16);
957 /** read chunked data from connection */
959 do_chunked_read(SSL* ssl)
964 BIO* mem = BIO_new(BIO_s_mem());
965 if(verb>=3) printf("do_chunked_read\n");
967 if(verb) printf("out of memory\n");
970 while(read_ssl_line(ssl, buf, sizeof(buf))) {
971 /* read the chunked start line */
972 if(verb>=2) printf("chunk header: %s\n", buf);
973 if(!parse_chunk_header(buf, &len)) {
975 if(verb>=3) printf("could not parse chunk header\n");
978 if(verb>=2) printf("chunk len: %d\n", (int)len);
982 /* skip end-of-chunk-trailer lines,
983 * until the empty line after that */
985 if(!read_ssl_line(ssl, buf, sizeof(buf))) {
989 } while (strlen(buf) > 0);
990 /* end of chunks, zero terminate it */
991 if(BIO_write(mem, &z, 1) <= 0) {
992 if(verb) printf("out of memory\n");
998 /* read the chunked body */
999 body = read_data_chunk(ssl, len);
1004 if(BIO_write(mem, body, (int)len) <= 0) {
1005 if(verb) printf("out of memory\n");
1011 /* skip empty line after data chunk */
1012 if(!read_ssl_line(ssl, buf, sizeof(buf))) {
1021 /** start HTTP1.1 transaction on SSL */
1023 write_http_get(SSL* ssl, char* pathname, char* urlname)
1025 if(write_ssl_line(ssl, "GET /%s HTTP/1.1", pathname) &&
1026 write_ssl_line(ssl, "Host: %s", urlname) &&
1027 write_ssl_line(ssl, "User-Agent: unbound-anchor/%s",
1029 /* We do not really do multiple queries per connection,
1030 * but this header setting is also not needed.
1031 * write_ssl_line(ssl, "Connection: close", NULL) &&*/
1032 write_ssl_line(ssl, "", NULL)) {
1038 /** read chunked data and zero terminate; len is without zero */
1040 read_chunked_zero_terminate(SSL* ssl, size_t* len)
1042 /* do the chunked version */
1043 BIO* tmp = do_chunked_read(ssl);
1044 char* data, *d = NULL;
1047 if(verb) printf("could not read from https\n");
1050 l = (size_t)BIO_get_mem_data(tmp, &d);
1051 if(verb>=2) printf("chunked data is %d\n", (int)l);
1052 if(l == 0 || d == NULL) {
1053 if(verb) printf("out of memory\n");
1057 data = (char*)malloc(l);
1059 if(verb) printf("out of memory\n");
1067 /** read HTTP result from SSL */
1069 read_http_result(SSL* ssl)
1074 if(!read_http_headers(ssl, &len)) {
1078 data = read_chunked_zero_terminate(ssl, &len);
1080 data = read_data_chunk(ssl, len);
1082 if(!data) return NULL;
1083 if(verb >= 4) print_data("read data", data, (int)len);
1084 m = BIO_new_mem_buf(data, (int)len);
1086 if(verb) printf("out of memory\n");
1092 /** https to an IP addr, return BIO with pathname or NULL */
1094 https_to_ip(struct ip_list* ip, char* pathname, char* urlname)
1099 SSL_CTX* sslctx = setup_sslctx();
1103 fd = connect_to_ip(ip);
1105 SSL_CTX_free(sslctx);
1108 ssl = TLS_initiate(sslctx, fd);
1110 SSL_CTX_free(sslctx);
1114 if(!write_http_get(ssl, pathname, urlname)) {
1115 if(verb) printf("could not write to server\n");
1117 SSL_CTX_free(sslctx);
1121 bio = read_http_result(ssl);
1122 TLS_shutdown(fd, ssl, sslctx);
1127 * Do a HTTPS, HTTP1.1 over TLS, to fetch a file
1128 * @param ip_list: list of IP addresses to use to fetch from.
1129 * @param pathname: pathname of file on server to GET.
1130 * @param urlname: name to pass as the virtual host for this request.
1131 * @return a memory BIO with the file in it.
1134 https(struct ip_list* ip_list, char* pathname, char* urlname)
1138 /* try random address first, and work through the list */
1139 wipe_ip_usage(ip_list);
1140 while( (ip = pick_random_ip(ip_list)) ) {
1142 bio = https_to_ip(ip, pathname, urlname);
1146 if(verb) printf("could not fetch %s\n", pathname);
1149 if(verb) printf("fetched %s (%d bytes)\n",
1150 pathname, (int)BIO_ctrl_pending(bio));
1155 /** free up a downloaded file BIO */
1157 free_file_bio(BIO* bio)
1160 (void)BIO_reset(bio);
1161 (void)BIO_get_mem_data(bio, &pp);
1166 /** XML parse private data during the parse */
1168 /** the parser, reference */
1170 /** the current tag; malloced; or NULL outside of tags */
1172 /** current date to use during the parse */
1174 /** number of keys usefully read in */
1176 /** the compiled anchors as DS records */
1179 /** do we want to use this anchor? */
1181 /** the current anchor: Zone */
1183 /** the current anchor: KeyTag */
1185 /** the current anchor: Algorithm */
1187 /** the current anchor: DigestType */
1189 /** the current anchor: Digest*/
1193 /** The BIO for the tag */
1195 xml_selectbio(struct xml_data* data, const char* tag)
1198 if(strcasecmp(tag, "KeyTag") == 0)
1200 else if(strcasecmp(tag, "Algorithm") == 0)
1202 else if(strcasecmp(tag, "DigestType") == 0)
1204 else if(strcasecmp(tag, "Digest") == 0)
1210 * XML handle character data, the data inside an element.
1211 * @param userData: xml_data structure
1212 * @param s: the character data. May not all be in one callback.
1213 * NOT zero terminated.
1214 * @param len: length of this part of the data.
1217 xml_charhandle(void *userData, const XML_Char *s, int len)
1219 struct xml_data* data = (struct xml_data*)userData;
1221 /* skip characters outside of elements */
1226 printf("%s%s charhandle: '",
1227 data->use_key?"use ":"",
1228 data->tag?data->tag:"none");
1229 for(i=0; i<len; i++)
1233 if(strcasecmp(data->tag, "Zone") == 0) {
1234 if(BIO_write(data->czone, s, len) < 0) {
1235 if(verb) printf("out of memory in BIO_write\n");
1240 /* only store if key is used */
1243 b = xml_selectbio(data, data->tag);
1245 if(BIO_write(b, s, len) < 0) {
1246 if(verb) printf("out of memory in BIO_write\n");
1253 * XML fetch value of particular attribute(by name) or NULL if not present.
1254 * @param atts: attribute array (from xml_startelem).
1255 * @param name: name of attribute to look for.
1256 * @return the value or NULL. (ptr into atts).
1258 static const XML_Char*
1259 find_att(const XML_Char **atts, XML_Char* name)
1262 for(i=0; atts[i]; i+=2) {
1263 if(strcasecmp(atts[i], name) == 0)
1270 * XML convert DateTime element to time_t.
1271 * [-]CCYY-MM-DDThh:mm:ss[Z|(+|-)hh:mm]
1272 * (with optional .ssssss fractional seconds)
1273 * @param str: the string
1274 * @return a time_t representation or 0 on failure.
1277 xml_convertdate(const char* str)
1282 /* for this application, ignore minus in front;
1283 * only positive dates are expected */
1285 if(s[0] == '-') s++;
1286 memset(&tm, 0, sizeof(tm));
1287 /* parse initial content of the string (lots of whitespace allowed) */
1288 s = strptime(s, "%t%Y%t-%t%m%t-%t%d%tT%t%H%t:%t%M%t:%t%S%t", &tm);
1290 if(verb) printf("xml_convertdate parse failure %s\n", str);
1293 /* parse remainder of date string */
1295 /* optional '.' and fractional seconds */
1296 int frac = 0, n = 0;
1297 if(sscanf(s+1, "%d%n", &frac, &n) < 1) {
1298 if(verb) printf("xml_convertdate f failure %s\n", str);
1301 /* fraction is not used, time_t has second accuracy */
1305 if(*s == 'Z' || *s == 'z') {
1306 /* nothing to do for this */
1308 } else if(*s == '+' || *s == '-') {
1309 /* optional timezone spec: Z or +hh:mm or -hh:mm */
1310 int hr = 0, mn = 0, n = 0;
1311 if(sscanf(s+1, "%d:%d%n", &hr, &mn, &n) < 2) {
1312 if(verb) printf("xml_convertdate tz failure %s\n", str);
1326 /* not ended properly */
1327 /* but ignore, (lenient) */
1331 if(t == (time_t)-1) {
1332 if(verb) printf("xml_convertdate mktime failure\n");
1339 * XML handle the KeyDigest start tag, check validity periods.
1342 handle_keydigest(struct xml_data* data, const XML_Char **atts)
1345 if(find_att(atts, "validFrom")) {
1346 time_t from = xml_convertdate(find_att(atts, "validFrom"));
1348 if(verb) printf("error: xml cannot be parsed\n");
1351 if(data->date < from)
1354 if(find_att(atts, "validUntil")) {
1355 time_t until = xml_convertdate(find_att(atts, "validUntil"));
1357 if(verb) printf("error: xml cannot be parsed\n");
1360 if(data->date > until)
1363 /* yes we want to use this key */
1365 (void)BIO_reset(data->ctag);
1366 (void)BIO_reset(data->calgo);
1367 (void)BIO_reset(data->cdigtype);
1368 (void)BIO_reset(data->cdigest);
1371 /** See if XML element equals the zone name */
1373 xml_is_zone_name(BIO* zone, char* name)
1378 (void)BIO_seek(zone, 0);
1379 zlen = BIO_get_mem_data(zone, &z);
1380 if(!zlen || !z) return 0;
1381 /* zero terminate */
1382 if(zlen >= (long)sizeof(buf)) return 0;
1383 memmove(buf, z, (size_t)zlen);
1386 return (strncasecmp(buf, name, strlen(name)) == 0);
1390 * XML start of element. This callback is called whenever an XML tag starts.
1392 * @param userData: the xml_data structure.
1393 * @param name: the tag that starts.
1394 * @param atts: array of strings, pairs of attr = value, ends with NULL.
1395 * i.e. att[0]="att[1]" att[2]="att[3]" att[4]isNull
1398 xml_startelem(void *userData, const XML_Char *name, const XML_Char **atts)
1400 struct xml_data* data = (struct xml_data*)userData;
1402 if(verb>=4) printf("xml tag start '%s'\n", name);
1404 data->tag = strdup(name);
1406 if(verb) printf("out of memory\n");
1411 for(i=0; atts[i]; i+=2) {
1412 printf(" %s='%s'\n", atts[i], atts[i+1]);
1415 /* handle attributes to particular types */
1416 if(strcasecmp(name, "KeyDigest") == 0) {
1417 handle_keydigest(data, atts);
1419 } else if(strcasecmp(name, "Zone") == 0) {
1420 (void)BIO_reset(data->czone);
1424 /* for other types we prepare to pick up the data */
1427 b = xml_selectbio(data, data->tag);
1434 /** Append str to bio */
1436 xml_append_str(BIO* b, const char* s)
1438 if(BIO_write(b, s, (int)strlen(s)) < 0) {
1439 if(verb) printf("out of memory in BIO_write\n");
1444 /** Append bio to bio */
1446 xml_append_bio(BIO* b, BIO* a)
1450 (void)BIO_seek(a, 0);
1451 len = BIO_get_mem_data(a, &z);
1453 if(verb) printf("out of memory in BIO_write\n");
1456 /* remove newlines in the data here */
1457 for(i=0; i<len; i++) {
1458 if(z[i] == '\r' || z[i] == '\n')
1462 if(BIO_write(b, z, len) < 0) {
1463 if(verb) printf("out of memory in BIO_write\n");
1468 /** write the parsed xml-DS to the DS list */
1470 xml_append_ds(struct xml_data* data)
1472 /* write DS to accumulated DS */
1473 xml_append_str(data->ds, ". IN DS ");
1474 xml_append_bio(data->ds, data->ctag);
1475 xml_append_str(data->ds, " ");
1476 xml_append_bio(data->ds, data->calgo);
1477 xml_append_str(data->ds, " ");
1478 xml_append_bio(data->ds, data->cdigtype);
1479 xml_append_str(data->ds, " ");
1480 xml_append_bio(data->ds, data->cdigest);
1481 xml_append_str(data->ds, "\n");
1486 * XML end of element. This callback is called whenever an XML tag ends.
1488 * @param userData: the xml_data structure
1489 * @param name: the tag that ends.
1492 xml_endelem(void *userData, const XML_Char *name)
1494 struct xml_data* data = (struct xml_data*)userData;
1495 if(verb>=4) printf("xml tag end '%s'\n", name);
1498 if(strcasecmp(name, "KeyDigest") == 0) {
1500 xml_append_ds(data);
1502 } else if(strcasecmp(name, "Zone") == 0) {
1503 if(!xml_is_zone_name(data->czone, ".")) {
1504 if(verb) printf("xml not for the right zone\n");
1510 /* Stop the parser when an entity declaration is encountered. For safety. */
1512 xml_entitydeclhandler(void *userData,
1513 const XML_Char *ATTR_UNUSED(entityName),
1514 int ATTR_UNUSED(is_parameter_entity),
1515 const XML_Char *ATTR_UNUSED(value), int ATTR_UNUSED(value_length),
1516 const XML_Char *ATTR_UNUSED(base),
1517 const XML_Char *ATTR_UNUSED(systemId),
1518 const XML_Char *ATTR_UNUSED(publicId),
1519 const XML_Char *ATTR_UNUSED(notationName))
1521 (void)XML_StopParser((XML_Parser)userData, XML_FALSE);
1525 * XML parser setup of the callbacks for the tags
1528 xml_parse_setup(XML_Parser parser, struct xml_data* data, time_t now)
1531 memset(data, 0, sizeof(*data));
1532 XML_SetUserData(parser, data);
1533 data->parser = parser;
1535 data->ds = BIO_new(BIO_s_mem());
1536 data->ctag = BIO_new(BIO_s_mem());
1537 data->czone = BIO_new(BIO_s_mem());
1538 data->calgo = BIO_new(BIO_s_mem());
1539 data->cdigtype = BIO_new(BIO_s_mem());
1540 data->cdigest = BIO_new(BIO_s_mem());
1541 if(!data->ds || !data->ctag || !data->calgo || !data->czone ||
1542 !data->cdigtype || !data->cdigest) {
1543 if(verb) printf("out of memory\n");
1546 snprintf(buf, sizeof(buf), "; created by unbound-anchor on %s",
1548 if(BIO_write(data->ds, buf, (int)strlen(buf)) < 0) {
1549 if(verb) printf("out of memory\n");
1552 XML_SetEntityDeclHandler(parser, xml_entitydeclhandler);
1553 XML_SetElementHandler(parser, xml_startelem, xml_endelem);
1554 XML_SetCharacterDataHandler(parser, xml_charhandle);
1558 * Perform XML parsing of the root-anchors file
1559 * Its format description can be read here
1560 * https://data.iana.org/root-anchors/draft-icann-dnssec-trust-anchor.txt
1562 * @param xml: BIO with xml data.
1563 * @param now: the current time for checking DS validity periods.
1564 * @return memoryBIO with the DS data in zone format.
1565 * or NULL if the zone is insecure.
1566 * (It exit()s on error)
1569 xml_parse(BIO* xml, time_t now)
1574 struct xml_data data;
1576 parser = XML_ParserCreate(NULL);
1578 if(verb) printf("could not XML_ParserCreate\n");
1582 /* setup callbacks */
1583 xml_parse_setup(parser, &data, now);
1586 (void)BIO_reset(xml);
1587 len = (int)BIO_get_mem_data(xml, &pp);
1589 if(verb) printf("out of memory\n");
1592 if(!XML_Parse(parser, pp, len, 1 /*isfinal*/ )) {
1593 const char *e = XML_ErrorString(XML_GetErrorCode(parser));
1594 if(verb) printf("XML_Parse failure %s\n", e?e:"");
1599 if(verb) printf("XML was parsed successfully, %d keys\n",
1602 XML_ParserFree(parser);
1607 (void)BIO_seek(data.ds, 0);
1608 len = BIO_get_mem_data(data.ds, &pp);
1609 printf("got DS bio %d: '", len);
1610 if(!fwrite(pp, (size_t)len, 1, stdout))
1611 /* compilers do not allow us to ignore fwrite .. */
1612 fprintf(stderr, "error writing to stdout\n");
1615 BIO_free(data.czone);
1616 BIO_free(data.ctag);
1617 BIO_free(data.calgo);
1618 BIO_free(data.cdigtype);
1619 BIO_free(data.cdigest);
1621 if(data.num_keys == 0) {
1622 /* the root zone seems to have gone insecure */
1630 /* get key usage out of its extension, returns 0 if no key_usage extension */
1631 static unsigned long
1632 get_usage_of_ex(X509* cert)
1634 unsigned long val = 0;
1636 if((s=X509_get_ext_d2i(cert, NID_key_usage, NULL, NULL))) {
1640 val |= s->data[1] << 8;
1642 ASN1_BIT_STRING_free(s);
1647 /** get valid signers from the list of signers in the signature */
1648 static STACK_OF(X509)*
1649 get_valid_signers(PKCS7* p7, char* p7signer)
1652 STACK_OF(X509)* validsigners = sk_X509_new_null();
1653 STACK_OF(X509)* signers = PKCS7_get0_signers(p7, NULL, 0);
1654 unsigned long usage = 0;
1656 if(verb) printf("out of memory\n");
1657 sk_X509_free(signers);
1661 if(verb) printf("no signers in pkcs7 signature\n");
1662 sk_X509_free(validsigners);
1665 for(i=0; i<sk_X509_num(signers); i++) {
1666 X509_NAME* nm = X509_get_subject_name(
1667 sk_X509_value(signers, i));
1670 if(verb) printf("signer %d: cert has no subject name\n", i);
1674 char* nmline = X509_NAME_oneline(nm, buf,
1676 printf("signer %d: Subject: %s\n", i,
1677 nmline?nmline:"no subject");
1678 if(verb >= 3 && X509_NAME_get_text_by_NID(nm,
1679 NID_commonName, buf, (int)sizeof(buf)))
1680 printf("commonName: %s\n", buf);
1681 if(verb >= 3 && X509_NAME_get_text_by_NID(nm,
1682 NID_pkcs9_emailAddress, buf, (int)sizeof(buf)))
1683 printf("emailAddress: %s\n", buf);
1686 int ku_loc = X509_get_ext_by_NID(
1687 sk_X509_value(signers, i), NID_key_usage, -1);
1688 if(verb >= 3 && ku_loc >= 0) {
1689 X509_EXTENSION *ex = X509_get_ext(
1690 sk_X509_value(signers, i), ku_loc);
1692 printf("keyUsage: ");
1693 X509V3_EXT_print_fp(stdout, ex, 0, 0);
1698 if(!p7signer || strcmp(p7signer, "")==0) {
1699 /* there is no name to check, return all records */
1700 if(verb) printf("did not check commonName of signer\n");
1702 if(!X509_NAME_get_text_by_NID(nm,
1703 NID_pkcs9_emailAddress,
1704 buf, (int)sizeof(buf))) {
1705 if(verb) printf("removed cert with no name\n");
1706 continue; /* no name, no use */
1708 if(strcmp(buf, p7signer) != 0) {
1709 if(verb) printf("removed cert with wrong name\n");
1710 continue; /* wrong name, skip it */
1714 /* check that the key usage allows digital signatures
1716 usage = get_usage_of_ex(sk_X509_value(signers, i));
1717 if(!(usage & KU_DIGITAL_SIGNATURE)) {
1718 if(verb) printf("removed cert with no key usage Digital Signature allowed\n");
1722 /* we like this cert, add it to our list of valid
1723 * signers certificates */
1724 sk_X509_push(validsigners, sk_X509_value(signers, i));
1726 sk_X509_free(signers);
1727 return validsigners;
1730 /** verify a PKCS7 signature, false on failure */
1732 verify_p7sig(BIO* data, BIO* p7s, STACK_OF(X509)* trust, char* p7signer)
1735 X509_STORE *store = X509_STORE_new();
1736 STACK_OF(X509)* validsigners;
1739 #ifdef X509_V_FLAG_CHECK_SS_SIGNATURE
1740 X509_VERIFY_PARAM* param = X509_VERIFY_PARAM_new();
1742 if(verb) printf("out of memory\n");
1743 X509_STORE_free(store);
1746 /* do the selfcheck on the root certificate; it checks that the
1748 X509_VERIFY_PARAM_set_flags(param, X509_V_FLAG_CHECK_SS_SIGNATURE);
1749 if(store) X509_STORE_set1_param(store, param);
1752 if(verb) printf("out of memory\n");
1753 #ifdef X509_V_FLAG_CHECK_SS_SIGNATURE
1754 X509_VERIFY_PARAM_free(param);
1758 #ifdef X509_V_FLAG_CHECK_SS_SIGNATURE
1759 X509_VERIFY_PARAM_free(param);
1762 (void)BIO_reset(p7s);
1763 (void)BIO_reset(data);
1765 /* convert p7s to p7 (the signature) */
1766 p7 = d2i_PKCS7_bio(p7s, NULL);
1768 if(verb) printf("could not parse p7s signature file\n");
1769 X509_STORE_free(store);
1772 if(verb >= 2) printf("parsed the PKCS7 signature\n");
1774 /* convert trust to trusted certificate store */
1775 for(i=0; i<sk_X509_num(trust); i++) {
1776 if(!X509_STORE_add_cert(store, sk_X509_value(trust, i))) {
1777 if(verb) printf("failed X509_STORE_add_cert\n");
1778 X509_STORE_free(store);
1783 if(verb >= 2) printf("setup the X509_STORE\n");
1785 /* check what is in the Subject name of the certificates,
1786 * and build a stack that contains only the right certificates */
1787 validsigners = get_valid_signers(p7, p7signer);
1789 X509_STORE_free(store);
1793 if(PKCS7_verify(p7, validsigners, store, data, NULL, PKCS7_NOINTERN) == 1) {
1795 if(verb) printf("the PKCS7 signature verified\n");
1798 ERR_print_errors_fp(stdout);
1802 sk_X509_free(validsigners);
1803 X509_STORE_free(store);
1808 /** write unsigned root anchor file, a 5011 revoked tp */
1810 write_unsigned_root(char* root_anchor_file)
1813 time_t now = time(NULL);
1814 out = fopen(root_anchor_file, "w");
1816 if(verb) printf("%s: %s\n", root_anchor_file, strerror(errno));
1819 if(fprintf(out, "; autotrust trust anchor file\n"
1822 "; This file was written by unbound-anchor on %s"
1823 "; It indicates that the root does not use DNSSEC\n"
1824 "; to restart DNSSEC overwrite this file with a\n"
1825 "; valid trustanchor or (empty-it and run unbound-anchor)\n"
1826 , ctime(&now)) < 0) {
1827 if(verb) printf("failed to write 'unsigned' to %s\n",
1829 if(verb && errno != 0) printf("%s\n", strerror(errno));
1834 /** write root anchor file */
1836 write_root_anchor(char* root_anchor_file, BIO* ds)
1841 (void)BIO_seek(ds, 0);
1842 len = BIO_get_mem_data(ds, &pp);
1844 if(verb) printf("out of memory\n");
1847 out = fopen(root_anchor_file, "w");
1849 if(verb) printf("%s: %s\n", root_anchor_file, strerror(errno));
1852 if(fwrite(pp, (size_t)len, 1, out) != 1) {
1853 if(verb) printf("failed to write all data to %s\n",
1855 if(verb && errno != 0) printf("%s\n", strerror(errno));
1860 /** Perform the verification and update of the trustanchor file */
1862 verify_and_update_anchor(char* root_anchor_file, BIO* xml, BIO* p7s,
1863 STACK_OF(X509)* cert, char* p7signer)
1867 /* verify xml file */
1868 if(!verify_p7sig(xml, p7s, cert, p7signer)) {
1869 printf("the PKCS7 signature failed\n");
1873 /* parse the xml file into DS records */
1874 ds = xml_parse(xml, time(NULL));
1876 /* the root zone is unsigned now */
1877 write_unsigned_root(root_anchor_file);
1879 /* reinstate 5011 tracking */
1880 write_root_anchor(root_anchor_file, ds);
1886 static void do_wsa_cleanup(void) { WSACleanup(); }
1889 /** perform actual certupdate work */
1891 do_certupdate(char* root_anchor_file, char* root_cert_file,
1892 char* urlname, char* xmlname, char* p7sname, char* p7signer,
1893 char* res_conf, char* root_hints, char* debugconf,
1894 int ip4only, int ip6only, int port, struct ub_result* dnskey)
1896 STACK_OF(X509)* cert;
1898 struct ip_list* ip_list = NULL;
1900 /* read pem file or provide builtin */
1901 cert = read_cert_or_builtin(root_cert_file);
1903 /* lookup A, AAAA for the urlname (or parse urlname if IP address) */
1904 ip_list = resolve_name(urlname, port, res_conf, root_hints, debugconf,
1908 if(1) { /* libunbound finished, startup WSA for the https connection */
1911 if((r = WSAStartup(MAKEWORD(2,2), &wsa_data)) != 0) {
1912 if(verb) printf("WSAStartup failed: %s\n",
1916 atexit(&do_wsa_cleanup);
1920 /* fetch the necessary files over HTTPS */
1921 xml = https(ip_list, xmlname, urlname);
1922 p7s = https(ip_list, p7sname, urlname);
1924 /* verify and update the root anchor */
1925 verify_and_update_anchor(root_anchor_file, xml, p7s, cert, p7signer);
1926 if(verb) printf("success: the anchor has been updated "
1927 "using the cert\n");
1932 sk_X509_pop_free(cert, X509_free);
1934 ub_resolve_free(dnskey);
1935 ip_list_free(ip_list);
1940 * Try to read the root RFC5011 autotrust anchor file,
1941 * @param file: filename.
1943 * 0 if does not exist or empty
1944 * 1 if trust-point-revoked-5011
1948 try_read_anchor(char* file)
1953 FILE* in = fopen(file, "r");
1955 /* only if the file does not exist, can we fix it */
1956 if(errno != ENOENT) {
1957 if(verb) printf("%s: %s\n", file, strerror(errno));
1958 if(verb) printf("error: cannot access the file\n");
1961 if(verb) printf("%s does not exist\n", file);
1964 while(fgets(line, (int)sizeof(line), in)) {
1965 line[sizeof(line)-1] = 0;
1966 if(strncmp(line, ";;REVOKED", 9) == 0) {
1968 if(verb) printf("%s : the trust point is revoked\n"
1969 "and the zone is considered unsigned.\n"
1970 "if you wish to re-enable, delete the file\n",
1975 while(*p == ' ' || *p == '\t')
1977 if(p[0]==0 || p[0]=='\n' || p[0]==';') continue;
1978 /* this line is a line of content */
1983 if(verb) printf("%s is empty\n", file);
1986 if(verb) printf("%s has content\n", file);
1990 /** Write the builtin root anchor to a file */
1992 write_builtin_anchor(char* file)
1994 const char* builtin_root_anchor = get_builtin_ds();
1995 FILE* out = fopen(file, "w");
1997 if(verb) printf("%s: %s\n", file, strerror(errno));
1998 if(verb) printf(" could not write builtin anchor\n");
2001 if(!fwrite(builtin_root_anchor, strlen(builtin_root_anchor), 1, out)) {
2002 if(verb) printf("%s: %s\n", file, strerror(errno));
2003 if(verb) printf(" could not complete write builtin anchor\n");
2009 * Check the root anchor file.
2010 * If does not exist, provide builtin and write file.
2011 * If empty, provide builtin and write file.
2012 * If trust-point-revoked-5011 file: make the program exit.
2013 * @param root_anchor_file: filename of the root anchor.
2014 * @param used_builtin: set to 1 if the builtin is written.
2015 * @return 0 if trustpoint is insecure, 1 on success. Exit on failure.
2018 provide_builtin(char* root_anchor_file, int* used_builtin)
2020 /* try to read it */
2021 switch(try_read_anchor(root_anchor_file))
2023 case 0: /* no exist or empty */
2024 write_builtin_anchor(root_anchor_file);
2027 case 1: /* revoked tp */
2029 case 2: /* it is fine */
2037 * add an autotrust anchor for the root to the context
2040 add_5011_probe_root(struct ub_ctx* ctx, char* root_anchor_file)
2043 r = ub_ctx_set_option(ctx, "auto-trust-anchor-file:", root_anchor_file);
2045 if(verb) printf("add 5011 probe to ctx: %s\n", ub_strerror(r));
2052 * Prime the root key and return the result. Exit on error.
2053 * @param ctx: the unbound context to perform the priming with.
2054 * @return: the result of the prime, on error it exit()s.
2056 static struct ub_result*
2057 prime_root_key(struct ub_ctx* ctx)
2059 struct ub_result* res = NULL;
2061 r = ub_resolve(ctx, ".", LDNS_RR_TYPE_DNSKEY, LDNS_RR_CLASS_IN, &res);
2063 if(verb) printf("resolve DNSKEY: %s\n", ub_strerror(r));
2068 if(verb) printf("out of memory\n");
2075 /** see if ADDPEND keys exist in autotrust file (if possible) */
2077 read_if_pending_keys(char* file)
2079 FILE* in = fopen(file, "r");
2082 if(verb>=2) printf("%s: %s\n", file, strerror(errno));
2085 while(fgets(line, (int)sizeof(line), in)) {
2086 if(line[0]==';') continue;
2087 if(strstr(line, "[ ADDPEND ]")) {
2089 if(verb) printf("RFC5011-state has ADDPEND keys\n");
2097 /** read last successful probe time from autotrust file (if possible) */
2099 read_last_success_time(char* file)
2101 FILE* in = fopen(file, "r");
2104 if(verb) printf("%s: %s\n", file, strerror(errno));
2107 while(fgets(line, (int)sizeof(line), in)) {
2108 if(strncmp(line, ";;last_success: ", 16) == 0) {
2110 time_t x = (unsigned int)strtol(line+16, &e, 10);
2113 if(verb) printf("failed to parse "
2114 "last_success probe time\n");
2117 if(verb) printf("last successful probe: %s", ctime(&x));
2122 if(verb) printf("no last_success probe time in anchor file\n");
2127 * Read autotrust 5011 probe file and see if the date
2128 * compared to the current date allows a certupdate.
2129 * If the last successful probe was recent then 5011 cannot be behind,
2130 * and the failure cannot be solved with a certupdate.
2131 * The debugconf is to validation-override the date for testing.
2132 * @param root_anchor_file: filename of root key
2133 * @return true if certupdate is ok.
2136 probe_date_allows_certupdate(char* root_anchor_file)
2138 int has_pending_keys = read_if_pending_keys(root_anchor_file);
2139 int32_t last_success = read_last_success_time(root_anchor_file);
2140 int32_t now = (int32_t)time(NULL);
2141 int32_t leeway = 30 * 24 * 3600; /* 30 days leeway */
2142 /* if the date is before 2010-07-15:00.00.00 then the root has not
2143 * been signed yet, and thus we refuse to take action. */
2144 if(time(NULL) < xml_convertdate("2010-07-15T00:00:00")) {
2145 if(verb) printf("the date is before the root was first signed,"
2146 " please correct the clock\n");
2149 if(last_success == 0)
2150 return 1; /* no probe time */
2151 if(has_pending_keys)
2152 return 1; /* key in ADDPEND state, a previous probe has
2153 inserted that, and it was present in all recent probes,
2154 but it has not become active. The 30 day timer may not have
2155 expired, but we know(for sure) there is a rollover going on.
2156 If we only managed to pickup the new key on its last day
2157 of announcement (for example) this can happen. */
2158 if(now - last_success < 0) {
2159 if(verb) printf("the last successful probe is in the future,"
2160 " clock was modified\n");
2163 if(now - last_success >= leeway) {
2164 if(verb) printf("the last successful probe was more than 30 "
2168 if(verb) printf("the last successful probe is recent\n");
2172 /** perform the unbound-anchor work */
2174 do_root_update_work(char* root_anchor_file, char* root_cert_file,
2175 char* urlname, char* xmlname, char* p7sname, char* p7signer,
2176 char* res_conf, char* root_hints, char* debugconf,
2177 int ip4only, int ip6only, int force, int port)
2180 struct ub_result* dnskey;
2181 int used_builtin = 0;
2183 /* see if builtin rootanchor needs to be provided, or if
2184 * rootanchor is 'revoked-trust-point' */
2185 if(!provide_builtin(root_anchor_file, &used_builtin))
2188 /* make unbound context with 5011-probe for root anchor,
2189 * and probe . DNSKEY */
2190 ctx = create_unbound_context(res_conf, root_hints, debugconf,
2192 add_5011_probe_root(ctx, root_anchor_file);
2193 dnskey = prime_root_key(ctx);
2196 /* if secure: exit */
2197 if(dnskey->secure && !force) {
2198 if(verb) printf("success: the anchor is ok\n");
2199 ub_resolve_free(dnskey);
2200 return used_builtin;
2202 if(force && verb) printf("debug cert update forced\n");
2204 /* if not (and NOERROR): check date and do certupdate */
2205 if((dnskey->rcode == 0 &&
2206 probe_date_allows_certupdate(root_anchor_file)) || force) {
2207 if(do_certupdate(root_anchor_file, root_cert_file, urlname,
2208 xmlname, p7sname, p7signer, res_conf, root_hints,
2209 debugconf, ip4only, ip6only, port, dnskey))
2211 return used_builtin;
2213 if(verb) printf("fail: the anchor is NOT ok and could not be fixed\n");
2214 ub_resolve_free(dnskey);
2215 return used_builtin;
2218 /** getopt global, in case header files fail to declare it. */
2220 /** getopt global, in case header files fail to declare it. */
2221 extern char* optarg;
2223 /** Main routine for unbound-anchor */
2224 int main(int argc, char* argv[])
2227 char* root_anchor_file = ROOT_ANCHOR_FILE;
2228 char* root_cert_file = ROOT_CERT_FILE;
2229 char* urlname = URLNAME;
2230 char* xmlname = XMLNAME;
2231 char* p7sname = P7SNAME;
2232 char* p7signer = P7SIGNER;
2233 char* res_conf = NULL;
2234 char* root_hints = NULL;
2235 char* debugconf = NULL;
2236 int dolist=0, ip4only=0, ip6only=0, force=0, port = HTTPS_PORT;
2237 /* parse the options */
2238 while( (c=getopt(argc, argv, "46C:FP:a:c:f:hln:r:s:u:vx:")) != -1) {
2250 root_anchor_file = optarg;
2253 root_cert_file = optarg;
2271 root_hints = optarg;
2280 port = atoi(optarg);
2296 ERR_load_crypto_strings();
2297 ERR_load_SSL_strings();
2298 OpenSSL_add_all_algorithms();
2299 (void)SSL_library_init();
2301 if(dolist) do_list_builtin();
2303 return do_root_update_work(root_anchor_file, root_cert_file, urlname,
2304 xmlname, p7sname, p7signer, res_conf, root_hints, debugconf,
2305 ip4only, ip6only, force, port);