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,
41 * with RFC7958 https xml fetch.
43 * This is a concept solution for distribution of the DNSSEC root
44 * trust anchor. It is a small tool, called "unbound-anchor", that
45 * runs before the main validator starts. I.e. in the init script:
46 * unbound-anchor; unbound. Thus it is meant to run at system boot time.
48 * Management-Abstract:
49 * * first run: fill root.key file with hardcoded DS record.
50 * * mostly: use RFC5011 tracking, quick . DNSKEY UDP query.
51 * * failover: use RFC7958 builtin certificate, do https and update.
52 * Special considerations:
53 * * 30-days RFC5011 timer saves a lot of https traffic.
54 * * DNSKEY probe must be NOERROR, saves a lot of https traffic.
55 * * fail if clock before sign date of the root, if cert expired.
56 * * if the root goes back to unsigned, deals with it.
58 * It has hardcoded the root DS anchors and the ICANN CA root certificate.
59 * It allows with options to override those. It also takes root-hints (it
60 * has to do a DNS resolve), and also has hardcoded defaults for those.
62 * Once it starts, just before the validator starts, it quickly checks if
63 * the root anchor file needs to be updated. First it tries to use
64 * RFC5011-tracking of the root key. If that fails (and for 30-days since
65 * last successful probe), then it attempts to update using the
66 * certificate. So most of the time, the RFC5011 tracking will work fine,
67 * and within a couple milliseconds, the main daemon can start. It will
68 * have only probed the . DNSKEY, not done expensive https transfers on the
69 * root infrastructure.
71 * If there is no root key in the root.key file, it bootstraps the
72 * RFC5011-tracking with its builtin DS anchors; if that fails it
73 * bootstraps the RFC5011-tracking using the certificate. (again to avoid
74 * https, and it is also faster).
76 * It uses the XML file by converting it to DS records and writing that to the
77 * key file. Unbound can detect that the 'special comments' are gone, and
78 * the file contains a list of normal DNSKEY/DS records, and uses that to
79 * bootstrap 5011 (the KSK is made VALID).
81 * The certificate RFC7958 update is done by fetching root-anchors.xml and
82 * root-anchors.p7s via SSL. The HTTPS certificate can be logged but is
83 * not validated (https for channel security; the security comes from the
84 * certificate). The 'data.iana.org' domain name A and AAAA are resolved
85 * without DNSSEC. It tries a random IP until the transfer succeeds. It
86 * then checks the p7s signature.
88 * On any failure, it leaves the root key file untouched. The main
89 * validator has to cope with it, it cannot fix things (So a failure does
90 * not go 'without DNSSEC', no downgrade). If it used its builtin stuff or
91 * did the https, it exits with an exit code, so that this can trigger the
92 * init script to log the event and potentially alert the operator that can
95 * The date is also checked. Before 2010-07-15 is a failure (root not
96 * signed yet; avoids attacks on system clock). The
97 * last-successful-RFC5011-probe (if available) has to be more than 30 days
98 * in the past (otherwise, RFC5011 should have worked). This keeps
99 * unnecessary https traffic down. If the main certificate is expired, it
102 * The dates on the keys in the xml are checked (uses the libexpat xml
103 * parser), only the valid ones are used to re-enstate RFC5011 tracking.
104 * If 0 keys are valid, the zone has gone to insecure (a special marker is
105 * written in the keyfile that tells the main validator daemon the zone is
108 * Only the root ICANN CA is shipped, not the intermediate ones. The
109 * intermediate CAs are included in the p7s file that was downloaded. (the
110 * root cert is valid to 2028 and the intermediate to 2014, today).
112 * Obviously, the tool also has options so the operator can provide a new
113 * keyfile, a new certificate and new URLs, and fresh root hints. By
114 * default it logs nothing on failure and success; it 'just works'.
119 #include "libunbound/unbound.h"
120 #include "sldns/rrdef.h"
121 #include "sldns/parseutil.h"
124 #error "need libexpat to parse root-anchors.xml file."
129 #ifdef HAVE_OPENSSL_SSL_H
130 #include <openssl/ssl.h>
132 #ifdef HAVE_OPENSSL_ERR_H
133 #include <openssl/err.h>
135 #ifdef HAVE_OPENSSL_RAND_H
136 #include <openssl/rand.h>
138 #include <openssl/x509.h>
139 #include <openssl/x509v3.h>
140 #include <openssl/pem.h>
142 /** name of server in URL to fetch HTTPS from */
143 #define URLNAME "data.iana.org"
144 /** path on HTTPS server to xml file */
145 #define XMLNAME "root-anchors/root-anchors.xml"
146 /** path on HTTPS server to p7s file */
147 #define P7SNAME "root-anchors/root-anchors.p7s"
148 /** name of the signer of the certificate */
149 #define P7SIGNER "dnssec@iana.org"
150 /** port number for https access */
151 #define HTTPS_PORT 443
154 /* sneakily reuse the the wsa_strerror function, on windows */
155 char* wsa_strerror(int err);
158 /** verbosity for this application */
161 /** list of IP addresses */
164 struct ip_list* next;
165 /** length of addr */
167 /** address ready to connect to */
168 struct sockaddr_storage addr;
169 /** has the address been used */
173 /** Give unbound-anchor usage, and exit (1). */
177 printf("Usage: unbound-anchor [opts]\n");
178 printf(" Setup or update root anchor. "
179 "Most options have defaults.\n");
180 printf(" Run this program before you start the validator.\n");
182 printf(" The anchor and cert have default builtin content\n");
183 printf(" if the file does not exist or is empty.\n");
185 printf("-a file root key file, default %s\n", ROOT_ANCHOR_FILE);
186 printf(" The key is input and output for this tool.\n");
187 printf("-c file cert file, default %s\n", ROOT_CERT_FILE);
188 printf("-l list builtin key and cert on stdout\n");
189 printf("-u name server in https url, default %s\n", URLNAME);
190 printf("-x path pathname to xml in url, default %s\n", XMLNAME);
191 printf("-s path pathname to p7s in url, default %s\n", P7SNAME);
192 printf("-n name signer's subject emailAddress, default %s\n", P7SIGNER);
193 printf("-4 work using IPv4 only\n");
194 printf("-6 work using IPv6 only\n");
195 printf("-f resolv.conf use given resolv.conf to resolve -u name\n");
196 printf("-r root.hints use given root.hints to resolve -u name\n"
197 " builtin root hints are used by default\n");
198 printf("-v more verbose\n");
199 printf("-C conf debug, read config\n");
200 printf("-P port use port for https connect, default 443\n");
201 printf("-F debug, force update with cert\n");
202 printf("-h show this usage help\n");
203 printf("Version %s\n", PACKAGE_VERSION);
204 printf("BSD licensed, see LICENSE in source package for details.\n");
205 printf("Report bugs to %s\n", PACKAGE_BUGREPORT);
209 /** return the built in root update certificate */
211 get_builtin_cert(void)
214 /* The ICANN CA fetched at 24 Sep 2010. Valid to 2028 */
215 "-----BEGIN CERTIFICATE-----\n"
216 "MIIDdzCCAl+gAwIBAgIBATANBgkqhkiG9w0BAQsFADBdMQ4wDAYDVQQKEwVJQ0FO\n"
217 "TjEmMCQGA1UECxMdSUNBTk4gQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkxFjAUBgNV\n"
218 "BAMTDUlDQU5OIFJvb3QgQ0ExCzAJBgNVBAYTAlVTMB4XDTA5MTIyMzA0MTkxMloX\n"
219 "DTI5MTIxODA0MTkxMlowXTEOMAwGA1UEChMFSUNBTk4xJjAkBgNVBAsTHUlDQU5O\n"
220 "IENlcnRpZmljYXRpb24gQXV0aG9yaXR5MRYwFAYDVQQDEw1JQ0FOTiBSb290IENB\n"
221 "MQswCQYDVQQGEwJVUzCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAKDb\n"
222 "cLhPNNqc1NB+u+oVvOnJESofYS9qub0/PXagmgr37pNublVThIzyLPGCJ8gPms9S\n"
223 "G1TaKNIsMI7d+5IgMy3WyPEOECGIcfqEIktdR1YWfJufXcMReZwU4v/AdKzdOdfg\n"
224 "ONiwc6r70duEr1IiqPbVm5T05l1e6D+HkAvHGnf1LtOPGs4CHQdpIUcy2kauAEy2\n"
225 "paKcOcHASvbTHK7TbbvHGPB+7faAztABLoneErruEcumetcNfPMIjXKdv1V1E3C7\n"
226 "MSJKy+jAqqQJqjZoQGB0necZgUMiUv7JK1IPQRM2CXJllcyJrm9WFxY0c1KjBO29\n"
227 "iIKK69fcglKcBuFShUECAwEAAaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8B\n"
228 "Af8EBAMCAf4wHQYDVR0OBBYEFLpS6UmDJIZSL8eZzfyNa2kITcBQMA0GCSqGSIb3\n"
229 "DQEBCwUAA4IBAQAP8emCogqHny2UYFqywEuhLys7R9UKmYY4suzGO4nkbgfPFMfH\n"
230 "6M+Zj6owwxlwueZt1j/IaCayoKU3QsrYYoDRolpILh+FPwx7wseUEV8ZKpWsoDoD\n"
231 "2JFbLg2cfB8u/OlE4RYmcxxFSmXBg0yQ8/IoQt/bxOcEEhhiQ168H2yE5rxJMt9h\n"
232 "15nu5JBSewrCkYqYYmaxyOC3WrVGfHZxVI7MpIFcGdvSb2a1uyuua8l0BKgk3ujF\n"
233 "0/wsHNeP22qNyVO+XVBzrM8fk8BSUFuiT/6tZTYXRtEt5aKQZgXbKU5dUF3jT9qg\n"
234 "j/Br5BZw3X/zd325TvnswzMC1+ljLzHnQGGk\n"
235 "-----END CERTIFICATE-----\n"
239 /** return the built in root DS trust anchor */
244 /* The anchors must start on a new line with ". IN DS and end with \n"[;]
245 * because the makedist script greps on the source here */
246 /* anchor 19036 is from 2010 */
247 /* anchor 20326 is from 2017 */
248 ". IN DS 19036 8 2 49AAC11D7B6F6446702E54A1607371607A1A41855200FD2CE1CDDE32F24E8FB5\n"
249 ". IN DS 20326 8 2 E06D44B80B8F1D39A95C0B0D7C65D08458E880409BBC683457104237C7F8EC8D\n";
252 /** print hex data */
254 print_data(const char* msg, const char* data, int len)
258 for(i=0; i<len; i++) {
259 printf(" %2.2x", (unsigned char)data[i]);
264 /** print ub context creation error and exit */
266 ub_ctx_error_exit(struct ub_ctx* ctx, const char* str, const char* str2)
269 if(str && str2 && verb) printf("%s: %s\n", str, str2);
270 if(verb) printf("error: could not create unbound resolver context\n");
275 * Create a new unbound context with the commandline settings applied
277 static struct ub_ctx*
278 create_unbound_context(const char* res_conf, const char* root_hints,
279 const char* debugconf, int ip4only, int ip6only)
282 struct ub_ctx* ctx = ub_ctx_create();
284 if(verb) printf("out of memory\n");
287 /* do not waste time and network traffic to fetch extra nameservers */
288 r = ub_ctx_set_option(ctx, "target-fetch-policy:", "0 0 0 0 0");
289 if(r && verb) printf("ctx targetfetchpolicy: %s\n", ub_strerror(r));
290 /* read config file first, so its settings can be overridden */
292 r = ub_ctx_config(ctx, debugconf);
293 if(r) ub_ctx_error_exit(ctx, debugconf, ub_strerror(r));
296 r = ub_ctx_resolvconf(ctx, res_conf);
297 if(r) ub_ctx_error_exit(ctx, res_conf, ub_strerror(r));
300 r = ub_ctx_set_option(ctx, "root-hints:", root_hints);
301 if(r) ub_ctx_error_exit(ctx, root_hints, ub_strerror(r));
304 r = ub_ctx_set_option(ctx, "do-ip6:", "no");
305 if(r) ub_ctx_error_exit(ctx, "ip4only", ub_strerror(r));
308 r = ub_ctx_set_option(ctx, "do-ip4:", "no");
309 if(r) ub_ctx_error_exit(ctx, "ip6only", ub_strerror(r));
314 /** printout certificate in detail */
316 verb_cert(const char* msg, X509* x)
318 if(verb == 0 || verb == 1) return;
320 if(msg) printf("%s\n", msg);
321 X509_print_ex_fp(stdout, x, 0, (unsigned long)-1
322 ^(X509_FLAG_NO_SUBJECT
323 |X509_FLAG_NO_ISSUER|X509_FLAG_NO_VALIDITY));
326 if(msg) printf("%s\n", msg);
327 X509_print_fp(stdout, x);
330 /** printout certificates in detail */
332 verb_certs(const char* msg, STACK_OF(X509)* sk)
334 int i, num = sk_X509_num(sk);
335 if(verb == 0 || verb == 1) return;
336 for(i=0; i<num; i++) {
337 printf("%s (%d/%d)\n", msg, i, num);
338 verb_cert(NULL, sk_X509_value(sk, i));
342 /** read certificates from a PEM bio */
343 static STACK_OF(X509)*
344 read_cert_bio(BIO* bio)
346 STACK_OF(X509) *sk = sk_X509_new_null();
348 if(verb) printf("out of memory\n");
351 while(!BIO_eof(bio)) {
352 X509* x = PEM_read_bio_X509(bio, NULL, 0, NULL);
355 printf("failed to read X509\n");
356 ERR_print_errors_fp(stdout);
360 if(!sk_X509_push(sk, x)) {
361 if(verb) printf("out of memory\n");
368 /* read the certificate file */
369 static STACK_OF(X509)*
370 read_cert_file(const char* file)
376 if(file == NULL || strcmp(file, "") == 0) {
379 sk = sk_X509_new_null();
381 if(verb) printf("out of memory\n");
384 in = fopen(file, "r");
386 if(verb) printf("%s: %s\n", file, strerror(errno));
388 sk_X509_pop_free(sk, X509_free);
393 X509* x = PEM_read_X509(in, NULL, 0, NULL);
396 printf("failed to read X509 file\n");
397 ERR_print_errors_fp(stdout);
401 if(!sk_X509_push(sk, x)) {
402 if(verb) printf("out of memory\n");
407 /* read away newline after --END CERT-- */
408 if(!fgets(buf, (int)sizeof(buf), in))
413 if(verb) printf("%s is empty\n", file);
415 sk_X509_pop_free(sk, X509_free);
422 /** read certificates from the builtin certificate */
423 static STACK_OF(X509)*
424 read_builtin_cert(void)
426 const char* builtin_cert = get_builtin_cert();
429 char* d = strdup(builtin_cert); /* to avoid const warnings in the
430 changed prototype of BIO_new_mem_buf */
432 if(verb) printf("out of memory\n");
435 bio = BIO_new_mem_buf(d, (int)strlen(d));
437 if(verb) printf("out of memory\n");
440 sk = read_cert_bio(bio);
442 if(verb) printf("internal error, out of memory\n");
450 /** read update cert file or use builtin */
451 static STACK_OF(X509)*
452 read_cert_or_builtin(const char* file)
454 STACK_OF(X509) *sk = read_cert_file(file);
456 if(verb) printf("using builtin certificate\n");
457 sk = read_builtin_cert();
459 if(verb) printf("have %d trusted certificates\n", sk_X509_num(sk));
460 verb_certs("trusted certificates", sk);
465 do_list_builtin(void)
467 const char* builtin_cert = get_builtin_cert();
468 const char* builtin_ds = get_builtin_ds();
469 printf("%s\n", builtin_ds);
470 printf("%s\n", builtin_cert);
474 /** printout IP address with message */
476 verb_addr(const char* msg, struct ip_list* ip)
480 void* a = &((struct sockaddr_in*)&ip->addr)->sin_addr;
481 if(ip->len != (socklen_t)sizeof(struct sockaddr_in))
482 a = &((struct sockaddr_in6*)&ip->addr)->sin6_addr;
484 if(inet_ntop((int)((struct sockaddr_in*)&ip->addr)->sin_family,
485 a, out, (socklen_t)sizeof(out))==0)
486 printf("%s (inet_ntop error)\n", msg);
487 else printf("%s %s\n", msg, out);
493 ip_list_free(struct ip_list* p)
503 /** create ip_list entry for a RR record */
504 static struct ip_list*
505 RR_to_ip(int tp, char* data, int len, int port)
507 struct ip_list* ip = (struct ip_list*)calloc(1, sizeof(*ip));
508 uint16_t p = (uint16_t)port;
509 if(tp == LDNS_RR_TYPE_A) {
510 struct sockaddr_in* sa = (struct sockaddr_in*)&ip->addr;
511 ip->len = (socklen_t)sizeof(*sa);
512 sa->sin_family = AF_INET;
513 sa->sin_port = (in_port_t)htons(p);
514 if(len != (int)sizeof(sa->sin_addr)) {
515 if(verb) printf("skipped badly formatted A\n");
519 memmove(&sa->sin_addr, data, sizeof(sa->sin_addr));
521 } else if(tp == LDNS_RR_TYPE_AAAA) {
522 struct sockaddr_in6* sa = (struct sockaddr_in6*)&ip->addr;
523 ip->len = (socklen_t)sizeof(*sa);
524 sa->sin6_family = AF_INET6;
525 sa->sin6_port = (in_port_t)htons(p);
526 if(len != (int)sizeof(sa->sin6_addr)) {
527 if(verb) printf("skipped badly formatted AAAA\n");
531 memmove(&sa->sin6_addr, data, sizeof(sa->sin6_addr));
533 if(verb) printf("internal error: bad type in RRtoip\n");
537 verb_addr("resolved server address", ip);
541 /** Resolve name, type, class and add addresses to iplist */
543 resolve_host_ip(struct ub_ctx* ctx, const char* host, int port, int tp, int cl,
544 struct ip_list** head)
546 struct ub_result* res = NULL;
550 r = ub_resolve(ctx, host, tp, cl, &res);
552 if(verb) printf("error: resolve %s %s: %s\n", host,
553 (tp==LDNS_RR_TYPE_A)?"A":"AAAA", ub_strerror(r));
557 if(verb) printf("out of memory\n");
561 if(!res->havedata || res->rcode || !res->data) {
562 if(verb) printf("resolve %s %s: no result\n", host,
563 (tp==LDNS_RR_TYPE_A)?"A":"AAAA");
566 for(i = 0; res->data[i]; i++) {
567 struct ip_list* ip = RR_to_ip(tp, res->data[i], res->len[i],
573 ub_resolve_free(res);
576 /** parse a text IP address into a sockaddr */
577 static struct ip_list*
578 parse_ip_addr(const char* str, int port)
582 struct sockaddr_in6 a6;
583 struct sockaddr_in a;
586 uint16_t p = (uint16_t)port;
587 memset(&addr, 0, sizeof(addr));
589 if(inet_pton(AF_INET6, str, &addr.a6.sin6_addr) > 0) {
591 addr.a6.sin6_family = AF_INET6;
592 addr.a6.sin6_port = (in_port_t)htons(p);
593 len = (socklen_t)sizeof(addr.a6);
595 if(inet_pton(AF_INET, str, &addr.a.sin_addr) > 0) {
597 addr.a.sin_family = AF_INET;
598 addr.a.sin_port = (in_port_t)htons(p);
599 len = (socklen_t)sizeof(struct sockaddr_in);
601 if(!len) return NULL;
602 ip = (struct ip_list*)calloc(1, sizeof(*ip));
604 if(verb) printf("out of memory\n");
608 memmove(&ip->addr, &addr, len);
609 if(verb) printf("server address is %s\n", str);
614 * Resolve a domain name (even though the resolver is down and there is
615 * no trust anchor). Without DNSSEC validation.
616 * @param host: the name to resolve.
617 * If this name is an IP4 or IP6 address this address is returned.
618 * @param port: the port number used for the returned IP structs.
619 * @param res_conf: resolv.conf (if any).
620 * @param root_hints: root hints (if any).
621 * @param debugconf: unbound.conf for debugging options.
622 * @param ip4only: use only ip4 for resolve and only lookup A
623 * @param ip6only: use only ip6 for resolve and only lookup AAAA
624 * default is to lookup A and AAAA using ip4 and ip6.
625 * @return list of IP addresses.
627 static struct ip_list*
628 resolve_name(const char* host, int port, const char* res_conf,
629 const char* root_hints, const char* debugconf, int ip4only, int ip6only)
632 struct ip_list* list = NULL;
633 /* first see if name is an IP address itself */
634 if( (list=parse_ip_addr(host, port)) ) {
638 /* create resolver context */
639 ctx = create_unbound_context(res_conf, root_hints, debugconf,
642 /* try resolution of A */
644 resolve_host_ip(ctx, host, port, LDNS_RR_TYPE_A,
645 LDNS_RR_CLASS_IN, &list);
648 /* try resolution of AAAA */
650 resolve_host_ip(ctx, host, port, LDNS_RR_TYPE_AAAA,
651 LDNS_RR_CLASS_IN, &list);
656 if(verb) printf("%s has no IP addresses I can use\n", host);
662 /** clear used flags */
664 wipe_ip_usage(struct ip_list* p)
672 /** cound unused IPs */
674 count_unused(struct ip_list* p)
684 /** pick random unused element from IP list */
685 static struct ip_list*
686 pick_random_ip(struct ip_list* list)
688 struct ip_list* p = list;
689 int num = count_unused(list);
691 if(num == 0) return NULL;
692 /* not perfect, but random enough */
693 sel = (int)arc4random_uniform((uint32_t)num);
694 /* skip over unused elements that we did not select */
695 while(sel > 0 && p) {
699 /* find the next unused element */
702 if(!p) return NULL; /* robustness */
717 /** printout socket errno */
719 print_sock_err(const char* msg)
722 if(verb) printf("%s: %s\n", msg, strerror(errno));
724 if(verb) printf("%s: %s\n", msg, wsa_strerror(WSAGetLastError()));
728 /** connect to IP address */
730 connect_to_ip(struct ip_list* ip)
733 verb_addr("connect to", ip);
734 fd = socket(ip->len==(socklen_t)sizeof(struct sockaddr_in)?
735 AF_INET:AF_INET6, SOCK_STREAM, 0);
737 print_sock_err("socket");
740 if(connect(fd, (struct sockaddr*)&ip->addr, ip->len) < 0) {
741 print_sock_err("connect");
748 /** create SSL context */
752 SSL_CTX* sslctx = SSL_CTX_new(SSLv23_client_method());
754 if(verb) printf("SSL_CTX_new error\n");
760 /** initiate TLS on a connection */
762 TLS_initiate(SSL_CTX* sslctx, int fd)
766 SSL* ssl = SSL_new(sslctx);
768 if(verb) printf("SSL_new error\n");
771 SSL_set_connect_state(ssl);
772 (void)SSL_set_mode(ssl, SSL_MODE_AUTO_RETRY);
773 if(!SSL_set_fd(ssl, fd)) {
774 if(verb) printf("SSL_set_fd error\n");
780 if( (r=SSL_do_handshake(ssl)) == 1)
782 r = SSL_get_error(ssl, r);
783 if(r != SSL_ERROR_WANT_READ && r != SSL_ERROR_WANT_WRITE) {
784 if(verb) printf("SSL handshake failed\n");
788 /* wants to be called again */
790 x = SSL_get_peer_certificate(ssl);
792 if(verb) printf("Server presented no peer certificate\n");
796 verb_cert("server SSL certificate", x);
801 /** perform neat TLS shutdown */
803 TLS_shutdown(int fd, SSL* ssl, SSL_CTX* sslctx)
805 /* shutdown the SSL connection nicely */
806 if(SSL_shutdown(ssl) == 0) {
810 SSL_CTX_free(sslctx);
814 /** write a line over SSL */
816 write_ssl_line(SSL* ssl, const char* str, const char* sec)
821 snprintf(buf, sizeof(buf), str, sec);
823 snprintf(buf, sizeof(buf), "%s", str);
826 if(l+2 >= sizeof(buf)) {
827 if(verb) printf("line too long\n");
830 if(verb >= 2) printf("SSL_write: %s\n", buf);
835 if(SSL_write(ssl, buf, (int)strlen(buf)) <= 0) {
836 if(verb) printf("could not SSL_write %s", str);
842 /** process header line, check rcode and keeping track of size */
844 process_one_header(char* buf, size_t* clen, int* chunked)
846 if(verb>=2) printf("header: '%s'\n", buf);
847 if(strncasecmp(buf, "HTTP/1.1 ", 9) == 0) {
848 /* check returncode */
850 if(verb) printf("bad status %s\n", buf+9);
853 } else if(strncasecmp(buf, "Content-Length: ", 16) == 0) {
855 *clen = (size_t)atoi(buf+16);
856 } else if(strncasecmp(buf, "Transfer-Encoding: chunked", 19+7) == 0) {
864 * Read one line from SSL
866 * skips "\r\n" (but not copied to buf).
867 * @param ssl: the SSL connection to read from (blocking).
868 * @param buf: buffer to return line in.
869 * @param len: size of the buffer.
870 * @return 0 on error, 1 on success.
873 read_ssl_line(SSL* ssl, char* buf, size_t len)
880 if(verb) printf("line too long\n");
883 if((r = SSL_read(ssl, buf+n, 1)) <= 0) {
884 if(SSL_get_error(ssl, r) == SSL_ERROR_ZERO_RETURN) {
888 if(verb) printf("could not SSL_read\n");
891 if(endnl && buf[n] == '\n') {
895 if(verb) printf("error: stray linefeeds\n");
897 } else if(buf[n] == '\r') {
898 /* skip \r, and also \n on the wire */
901 } else if(buf[n] == '\n') {
902 /* skip the \n, we are done */
910 /** read http headers and process them */
912 read_http_headers(SSL* ssl, size_t* clen)
917 while(read_ssl_line(ssl, buf, sizeof(buf))) {
920 if(!process_one_header(buf, clen, &chunked))
926 /** read a data chunk */
928 read_data_chunk(SSL* ssl, size_t len)
933 if(len >= 0xfffffff0)
934 return NULL; /* to protect against integer overflow in malloc*/
935 data = malloc(len+1);
937 if(verb) printf("out of memory\n");
941 if((r = SSL_read(ssl, data+got, (int)(len-got))) <= 0) {
942 if(SSL_get_error(ssl, r) == SSL_ERROR_ZERO_RETURN) {
944 if(verb) printf("could not SSL_read: unexpected EOF\n");
948 if(verb) printf("could not SSL_read\n");
952 if(verb >= 2) printf("at %d/%d\n", (int)got, (int)len);
955 if(verb>=2) printf("read %d data\n", (int)len);
960 /** parse chunk header */
962 parse_chunk_header(char* buf, size_t* result)
965 size_t v = (size_t)strtol(buf, &e, 16);
972 /** read chunked data from connection */
974 do_chunked_read(SSL* ssl)
979 BIO* mem = BIO_new(BIO_s_mem());
980 if(verb>=3) printf("do_chunked_read\n");
982 if(verb) printf("out of memory\n");
985 while(read_ssl_line(ssl, buf, sizeof(buf))) {
986 /* read the chunked start line */
987 if(verb>=2) printf("chunk header: %s\n", buf);
988 if(!parse_chunk_header(buf, &len)) {
990 if(verb>=3) printf("could not parse chunk header\n");
993 if(verb>=2) printf("chunk len: %d\n", (int)len);
997 /* skip end-of-chunk-trailer lines,
998 * until the empty line after that */
1000 if(!read_ssl_line(ssl, buf, sizeof(buf))) {
1004 } while (strlen(buf) > 0);
1005 /* end of chunks, zero terminate it */
1006 if(BIO_write(mem, &z, 1) <= 0) {
1007 if(verb) printf("out of memory\n");
1013 /* read the chunked body */
1014 body = read_data_chunk(ssl, len);
1019 if(BIO_write(mem, body, (int)len) <= 0) {
1020 if(verb) printf("out of memory\n");
1026 /* skip empty line after data chunk */
1027 if(!read_ssl_line(ssl, buf, sizeof(buf))) {
1036 /** start HTTP1.1 transaction on SSL */
1038 write_http_get(SSL* ssl, const char* pathname, const char* urlname)
1040 if(write_ssl_line(ssl, "GET /%s HTTP/1.1", pathname) &&
1041 write_ssl_line(ssl, "Host: %s", urlname) &&
1042 write_ssl_line(ssl, "User-Agent: unbound-anchor/%s",
1044 /* We do not really do multiple queries per connection,
1045 * but this header setting is also not needed.
1046 * write_ssl_line(ssl, "Connection: close", NULL) &&*/
1047 write_ssl_line(ssl, "", NULL)) {
1053 /** read chunked data and zero terminate; len is without zero */
1055 read_chunked_zero_terminate(SSL* ssl, size_t* len)
1057 /* do the chunked version */
1058 BIO* tmp = do_chunked_read(ssl);
1059 char* data, *d = NULL;
1062 if(verb) printf("could not read from https\n");
1065 l = (size_t)BIO_get_mem_data(tmp, &d);
1066 if(verb>=2) printf("chunked data is %d\n", (int)l);
1067 if(l == 0 || d == NULL) {
1068 if(verb) printf("out of memory\n");
1072 data = (char*)malloc(l);
1074 if(verb) printf("out of memory\n");
1082 /** read HTTP result from SSL */
1084 read_http_result(SSL* ssl)
1089 if(!read_http_headers(ssl, &len)) {
1093 data = read_chunked_zero_terminate(ssl, &len);
1095 data = read_data_chunk(ssl, len);
1097 if(!data) return NULL;
1098 if(verb >= 4) print_data("read data", data, (int)len);
1099 m = BIO_new_mem_buf(data, (int)len);
1101 if(verb) printf("out of memory\n");
1107 /** https to an IP addr, return BIO with pathname or NULL */
1109 https_to_ip(struct ip_list* ip, const char* pathname, const char* urlname)
1114 SSL_CTX* sslctx = setup_sslctx();
1118 fd = connect_to_ip(ip);
1120 SSL_CTX_free(sslctx);
1123 ssl = TLS_initiate(sslctx, fd);
1125 SSL_CTX_free(sslctx);
1129 if(!write_http_get(ssl, pathname, urlname)) {
1130 if(verb) printf("could not write to server\n");
1132 SSL_CTX_free(sslctx);
1136 bio = read_http_result(ssl);
1137 TLS_shutdown(fd, ssl, sslctx);
1142 * Do a HTTPS, HTTP1.1 over TLS, to fetch a file
1143 * @param ip_list: list of IP addresses to use to fetch from.
1144 * @param pathname: pathname of file on server to GET.
1145 * @param urlname: name to pass as the virtual host for this request.
1146 * @return a memory BIO with the file in it.
1149 https(struct ip_list* ip_list, const char* pathname, const char* urlname)
1153 /* try random address first, and work through the list */
1154 wipe_ip_usage(ip_list);
1155 while( (ip = pick_random_ip(ip_list)) ) {
1157 bio = https_to_ip(ip, pathname, urlname);
1161 if(verb) printf("could not fetch %s\n", pathname);
1164 if(verb) printf("fetched %s (%d bytes)\n",
1165 pathname, (int)BIO_ctrl_pending(bio));
1170 /** free up a downloaded file BIO */
1172 free_file_bio(BIO* bio)
1175 (void)BIO_reset(bio);
1176 (void)BIO_get_mem_data(bio, &pp);
1181 /** XML parse private data during the parse */
1183 /** the parser, reference */
1185 /** the current tag; malloced; or NULL outside of tags */
1187 /** current date to use during the parse */
1189 /** number of keys usefully read in */
1191 /** the compiled anchors as DS records */
1194 /** do we want to use this anchor? */
1196 /** the current anchor: Zone */
1198 /** the current anchor: KeyTag */
1200 /** the current anchor: Algorithm */
1202 /** the current anchor: DigestType */
1204 /** the current anchor: Digest*/
1208 /** The BIO for the tag */
1210 xml_selectbio(struct xml_data* data, const char* tag)
1213 if(strcasecmp(tag, "KeyTag") == 0)
1215 else if(strcasecmp(tag, "Algorithm") == 0)
1217 else if(strcasecmp(tag, "DigestType") == 0)
1219 else if(strcasecmp(tag, "Digest") == 0)
1225 * XML handle character data, the data inside an element.
1226 * @param userData: xml_data structure
1227 * @param s: the character data. May not all be in one callback.
1228 * NOT zero terminated.
1229 * @param len: length of this part of the data.
1232 xml_charhandle(void *userData, const XML_Char *s, int len)
1234 struct xml_data* data = (struct xml_data*)userData;
1236 /* skip characters outside of elements */
1241 printf("%s%s charhandle: '",
1242 data->use_key?"use ":"",
1243 data->tag?data->tag:"none");
1244 for(i=0; i<len; i++)
1248 if(strcasecmp(data->tag, "Zone") == 0) {
1249 if(BIO_write(data->czone, s, len) < 0) {
1250 if(verb) printf("out of memory in BIO_write\n");
1255 /* only store if key is used */
1258 b = xml_selectbio(data, data->tag);
1260 if(BIO_write(b, s, len) < 0) {
1261 if(verb) printf("out of memory in BIO_write\n");
1268 * XML fetch value of particular attribute(by name) or NULL if not present.
1269 * @param atts: attribute array (from xml_startelem).
1270 * @param name: name of attribute to look for.
1271 * @return the value or NULL. (ptr into atts).
1273 static const XML_Char*
1274 find_att(const XML_Char **atts, const XML_Char* name)
1277 for(i=0; atts[i]; i+=2) {
1278 if(strcasecmp(atts[i], name) == 0)
1285 * XML convert DateTime element to time_t.
1286 * [-]CCYY-MM-DDThh:mm:ss[Z|(+|-)hh:mm]
1287 * (with optional .ssssss fractional seconds)
1288 * @param str: the string
1289 * @return a time_t representation or 0 on failure.
1292 xml_convertdate(const char* str)
1297 /* for this application, ignore minus in front;
1298 * only positive dates are expected */
1300 if(s[0] == '-') s++;
1301 memset(&tm, 0, sizeof(tm));
1302 /* parse initial content of the string (lots of whitespace allowed) */
1303 s = strptime(s, "%t%Y%t-%t%m%t-%t%d%tT%t%H%t:%t%M%t:%t%S%t", &tm);
1305 if(verb) printf("xml_convertdate parse failure %s\n", str);
1308 /* parse remainder of date string */
1310 /* optional '.' and fractional seconds */
1311 int frac = 0, n = 0;
1312 if(sscanf(s+1, "%d%n", &frac, &n) < 1) {
1313 if(verb) printf("xml_convertdate f failure %s\n", str);
1316 /* fraction is not used, time_t has second accuracy */
1320 if(*s == 'Z' || *s == 'z') {
1321 /* nothing to do for this */
1323 } else if(*s == '+' || *s == '-') {
1324 /* optional timezone spec: Z or +hh:mm or -hh:mm */
1325 int hr = 0, mn = 0, n = 0;
1326 if(sscanf(s+1, "%d:%d%n", &hr, &mn, &n) < 2) {
1327 if(verb) printf("xml_convertdate tz failure %s\n", str);
1341 /* not ended properly */
1342 /* but ignore, (lenient) */
1345 t = sldns_mktime_from_utc(&tm);
1346 if(t == (time_t)-1) {
1347 if(verb) printf("xml_convertdate mktime failure\n");
1354 * XML handle the KeyDigest start tag, check validity periods.
1357 handle_keydigest(struct xml_data* data, const XML_Char **atts)
1360 if(find_att(atts, "validFrom")) {
1361 time_t from = xml_convertdate(find_att(atts, "validFrom"));
1363 if(verb) printf("error: xml cannot be parsed\n");
1366 if(data->date < from)
1369 if(find_att(atts, "validUntil")) {
1370 time_t until = xml_convertdate(find_att(atts, "validUntil"));
1372 if(verb) printf("error: xml cannot be parsed\n");
1375 if(data->date > until)
1378 /* yes we want to use this key */
1380 (void)BIO_reset(data->ctag);
1381 (void)BIO_reset(data->calgo);
1382 (void)BIO_reset(data->cdigtype);
1383 (void)BIO_reset(data->cdigest);
1386 /** See if XML element equals the zone name */
1388 xml_is_zone_name(BIO* zone, const char* name)
1393 (void)BIO_seek(zone, 0);
1394 zlen = BIO_get_mem_data(zone, &z);
1395 if(!zlen || !z) return 0;
1396 /* zero terminate */
1397 if(zlen >= (long)sizeof(buf)) return 0;
1398 memmove(buf, z, (size_t)zlen);
1401 return (strncasecmp(buf, name, strlen(name)) == 0);
1405 * XML start of element. This callback is called whenever an XML tag starts.
1407 * @param userData: the xml_data structure.
1408 * @param name: the tag that starts.
1409 * @param atts: array of strings, pairs of attr = value, ends with NULL.
1410 * i.e. att[0]="att[1]" att[2]="att[3]" att[4]isNull
1413 xml_startelem(void *userData, const XML_Char *name, const XML_Char **atts)
1415 struct xml_data* data = (struct xml_data*)userData;
1417 if(verb>=4) printf("xml tag start '%s'\n", name);
1419 data->tag = strdup(name);
1421 if(verb) printf("out of memory\n");
1426 for(i=0; atts[i]; i+=2) {
1427 printf(" %s='%s'\n", atts[i], atts[i+1]);
1430 /* handle attributes to particular types */
1431 if(strcasecmp(name, "KeyDigest") == 0) {
1432 handle_keydigest(data, atts);
1434 } else if(strcasecmp(name, "Zone") == 0) {
1435 (void)BIO_reset(data->czone);
1439 /* for other types we prepare to pick up the data */
1442 b = xml_selectbio(data, data->tag);
1449 /** Append str to bio */
1451 xml_append_str(BIO* b, const char* s)
1453 if(BIO_write(b, s, (int)strlen(s)) < 0) {
1454 if(verb) printf("out of memory in BIO_write\n");
1459 /** Append bio to bio */
1461 xml_append_bio(BIO* b, BIO* a)
1465 (void)BIO_seek(a, 0);
1466 len = BIO_get_mem_data(a, &z);
1468 if(verb) printf("out of memory in BIO_write\n");
1471 /* remove newlines in the data here */
1472 for(i=0; i<len; i++) {
1473 if(z[i] == '\r' || z[i] == '\n')
1477 if(BIO_write(b, z, len) < 0) {
1478 if(verb) printf("out of memory in BIO_write\n");
1483 /** write the parsed xml-DS to the DS list */
1485 xml_append_ds(struct xml_data* data)
1487 /* write DS to accumulated DS */
1488 xml_append_str(data->ds, ". IN DS ");
1489 xml_append_bio(data->ds, data->ctag);
1490 xml_append_str(data->ds, " ");
1491 xml_append_bio(data->ds, data->calgo);
1492 xml_append_str(data->ds, " ");
1493 xml_append_bio(data->ds, data->cdigtype);
1494 xml_append_str(data->ds, " ");
1495 xml_append_bio(data->ds, data->cdigest);
1496 xml_append_str(data->ds, "\n");
1501 * XML end of element. This callback is called whenever an XML tag ends.
1503 * @param userData: the xml_data structure
1504 * @param name: the tag that ends.
1507 xml_endelem(void *userData, const XML_Char *name)
1509 struct xml_data* data = (struct xml_data*)userData;
1510 if(verb>=4) printf("xml tag end '%s'\n", name);
1513 if(strcasecmp(name, "KeyDigest") == 0) {
1515 xml_append_ds(data);
1517 } else if(strcasecmp(name, "Zone") == 0) {
1518 if(!xml_is_zone_name(data->czone, ".")) {
1519 if(verb) printf("xml not for the right zone\n");
1525 /* Stop the parser when an entity declaration is encountered. For safety. */
1527 xml_entitydeclhandler(void *userData,
1528 const XML_Char *ATTR_UNUSED(entityName),
1529 int ATTR_UNUSED(is_parameter_entity),
1530 const XML_Char *ATTR_UNUSED(value), int ATTR_UNUSED(value_length),
1531 const XML_Char *ATTR_UNUSED(base),
1532 const XML_Char *ATTR_UNUSED(systemId),
1533 const XML_Char *ATTR_UNUSED(publicId),
1534 const XML_Char *ATTR_UNUSED(notationName))
1536 #if HAVE_DECL_XML_STOPPARSER
1537 (void)XML_StopParser((XML_Parser)userData, XML_FALSE);
1544 * XML parser setup of the callbacks for the tags
1547 xml_parse_setup(XML_Parser parser, struct xml_data* data, time_t now)
1550 memset(data, 0, sizeof(*data));
1551 XML_SetUserData(parser, data);
1552 data->parser = parser;
1554 data->ds = BIO_new(BIO_s_mem());
1555 data->ctag = BIO_new(BIO_s_mem());
1556 data->czone = BIO_new(BIO_s_mem());
1557 data->calgo = BIO_new(BIO_s_mem());
1558 data->cdigtype = BIO_new(BIO_s_mem());
1559 data->cdigest = BIO_new(BIO_s_mem());
1560 if(!data->ds || !data->ctag || !data->calgo || !data->czone ||
1561 !data->cdigtype || !data->cdigest) {
1562 if(verb) printf("out of memory\n");
1565 snprintf(buf, sizeof(buf), "; created by unbound-anchor on %s",
1567 if(BIO_write(data->ds, buf, (int)strlen(buf)) < 0) {
1568 if(verb) printf("out of memory\n");
1571 XML_SetEntityDeclHandler(parser, xml_entitydeclhandler);
1572 XML_SetElementHandler(parser, xml_startelem, xml_endelem);
1573 XML_SetCharacterDataHandler(parser, xml_charhandle);
1577 * Perform XML parsing of the root-anchors file
1578 * Its format description can be read here
1579 * https://data.iana.org/root-anchors/draft-icann-dnssec-trust-anchor.txt
1581 * @param xml: BIO with xml data.
1582 * @param now: the current time for checking DS validity periods.
1583 * @return memoryBIO with the DS data in zone format.
1584 * or NULL if the zone is insecure.
1585 * (It exit()s on error)
1588 xml_parse(BIO* xml, time_t now)
1593 struct xml_data data;
1595 parser = XML_ParserCreate(NULL);
1597 if(verb) printf("could not XML_ParserCreate\n");
1601 /* setup callbacks */
1602 xml_parse_setup(parser, &data, now);
1605 (void)BIO_reset(xml);
1606 len = (int)BIO_get_mem_data(xml, &pp);
1608 if(verb) printf("out of memory\n");
1611 if(!XML_Parse(parser, pp, len, 1 /*isfinal*/ )) {
1612 const char *e = XML_ErrorString(XML_GetErrorCode(parser));
1613 if(verb) printf("XML_Parse failure %s\n", e?e:"");
1618 if(verb) printf("XML was parsed successfully, %d keys\n",
1621 XML_ParserFree(parser);
1624 (void)BIO_seek(data.ds, 0);
1625 len = BIO_get_mem_data(data.ds, &pp);
1626 printf("got DS bio %d: '", len);
1627 if(!fwrite(pp, (size_t)len, 1, stdout))
1628 /* compilers do not allow us to ignore fwrite .. */
1629 fprintf(stderr, "error writing to stdout\n");
1632 BIO_free(data.czone);
1633 BIO_free(data.ctag);
1634 BIO_free(data.calgo);
1635 BIO_free(data.cdigtype);
1636 BIO_free(data.cdigest);
1638 if(data.num_keys == 0) {
1639 /* the root zone seems to have gone insecure */
1647 /* get key usage out of its extension, returns 0 if no key_usage extension */
1648 static unsigned long
1649 get_usage_of_ex(X509* cert)
1651 unsigned long val = 0;
1653 if((s=X509_get_ext_d2i(cert, NID_key_usage, NULL, NULL))) {
1657 val |= s->data[1] << 8;
1659 ASN1_BIT_STRING_free(s);
1664 /** get valid signers from the list of signers in the signature */
1665 static STACK_OF(X509)*
1666 get_valid_signers(PKCS7* p7, const char* p7signer)
1669 STACK_OF(X509)* validsigners = sk_X509_new_null();
1670 STACK_OF(X509)* signers = PKCS7_get0_signers(p7, NULL, 0);
1671 unsigned long usage = 0;
1673 if(verb) printf("out of memory\n");
1674 sk_X509_free(signers);
1678 if(verb) printf("no signers in pkcs7 signature\n");
1679 sk_X509_free(validsigners);
1682 for(i=0; i<sk_X509_num(signers); i++) {
1683 X509_NAME* nm = X509_get_subject_name(
1684 sk_X509_value(signers, i));
1687 if(verb) printf("signer %d: cert has no subject name\n", i);
1691 char* nmline = X509_NAME_oneline(nm, buf,
1693 printf("signer %d: Subject: %s\n", i,
1694 nmline?nmline:"no subject");
1695 if(verb >= 3 && X509_NAME_get_text_by_NID(nm,
1696 NID_commonName, buf, (int)sizeof(buf)))
1697 printf("commonName: %s\n", buf);
1698 if(verb >= 3 && X509_NAME_get_text_by_NID(nm,
1699 NID_pkcs9_emailAddress, buf, (int)sizeof(buf)))
1700 printf("emailAddress: %s\n", buf);
1703 int ku_loc = X509_get_ext_by_NID(
1704 sk_X509_value(signers, i), NID_key_usage, -1);
1705 if(verb >= 3 && ku_loc >= 0) {
1706 X509_EXTENSION *ex = X509_get_ext(
1707 sk_X509_value(signers, i), ku_loc);
1709 printf("keyUsage: ");
1710 X509V3_EXT_print_fp(stdout, ex, 0, 0);
1715 if(!p7signer || strcmp(p7signer, "")==0) {
1716 /* there is no name to check, return all records */
1717 if(verb) printf("did not check commonName of signer\n");
1719 if(!X509_NAME_get_text_by_NID(nm,
1720 NID_pkcs9_emailAddress,
1721 buf, (int)sizeof(buf))) {
1722 if(verb) printf("removed cert with no name\n");
1723 continue; /* no name, no use */
1725 if(strcmp(buf, p7signer) != 0) {
1726 if(verb) printf("removed cert with wrong name\n");
1727 continue; /* wrong name, skip it */
1731 /* check that the key usage allows digital signatures
1733 usage = get_usage_of_ex(sk_X509_value(signers, i));
1734 if(!(usage & KU_DIGITAL_SIGNATURE)) {
1735 if(verb) printf("removed cert with no key usage Digital Signature allowed\n");
1739 /* we like this cert, add it to our list of valid
1740 * signers certificates */
1741 sk_X509_push(validsigners, sk_X509_value(signers, i));
1743 sk_X509_free(signers);
1744 return validsigners;
1747 /** verify a PKCS7 signature, false on failure */
1749 verify_p7sig(BIO* data, BIO* p7s, STACK_OF(X509)* trust, const char* p7signer)
1752 X509_STORE *store = X509_STORE_new();
1753 STACK_OF(X509)* validsigners;
1756 #ifdef X509_V_FLAG_CHECK_SS_SIGNATURE
1757 X509_VERIFY_PARAM* param = X509_VERIFY_PARAM_new();
1759 if(verb) printf("out of memory\n");
1760 X509_STORE_free(store);
1763 /* do the selfcheck on the root certificate; it checks that the
1765 X509_VERIFY_PARAM_set_flags(param, X509_V_FLAG_CHECK_SS_SIGNATURE);
1766 if(store) X509_STORE_set1_param(store, param);
1769 if(verb) printf("out of memory\n");
1770 #ifdef X509_V_FLAG_CHECK_SS_SIGNATURE
1771 X509_VERIFY_PARAM_free(param);
1775 #ifdef X509_V_FLAG_CHECK_SS_SIGNATURE
1776 X509_VERIFY_PARAM_free(param);
1779 (void)BIO_reset(p7s);
1780 (void)BIO_reset(data);
1782 /* convert p7s to p7 (the signature) */
1783 p7 = d2i_PKCS7_bio(p7s, NULL);
1785 if(verb) printf("could not parse p7s signature file\n");
1786 X509_STORE_free(store);
1789 if(verb >= 2) printf("parsed the PKCS7 signature\n");
1791 /* convert trust to trusted certificate store */
1792 for(i=0; i<sk_X509_num(trust); i++) {
1793 if(!X509_STORE_add_cert(store, sk_X509_value(trust, i))) {
1794 if(verb) printf("failed X509_STORE_add_cert\n");
1795 X509_STORE_free(store);
1800 if(verb >= 2) printf("setup the X509_STORE\n");
1802 /* check what is in the Subject name of the certificates,
1803 * and build a stack that contains only the right certificates */
1804 validsigners = get_valid_signers(p7, p7signer);
1806 X509_STORE_free(store);
1810 if(PKCS7_verify(p7, validsigners, store, data, NULL, PKCS7_NOINTERN) == 1) {
1812 if(verb) printf("the PKCS7 signature verified\n");
1815 ERR_print_errors_fp(stdout);
1819 sk_X509_free(validsigners);
1820 X509_STORE_free(store);
1825 /** write unsigned root anchor file, a 5011 revoked tp */
1827 write_unsigned_root(const char* root_anchor_file)
1830 time_t now = time(NULL);
1831 out = fopen(root_anchor_file, "w");
1833 if(verb) printf("%s: %s\n", root_anchor_file, strerror(errno));
1836 if(fprintf(out, "; autotrust trust anchor file\n"
1839 "; This file was written by unbound-anchor on %s"
1840 "; It indicates that the root does not use DNSSEC\n"
1841 "; to restart DNSSEC overwrite this file with a\n"
1842 "; valid trustanchor or (empty-it and run unbound-anchor)\n"
1843 , ctime(&now)) < 0) {
1844 if(verb) printf("failed to write 'unsigned' to %s\n",
1846 if(verb && errno != 0) printf("%s\n", strerror(errno));
1852 FlushFileBuffers((HANDLE)_get_osfhandle(_fileno(out)));
1857 /** write root anchor file */
1859 write_root_anchor(const char* root_anchor_file, BIO* ds)
1864 (void)BIO_seek(ds, 0);
1865 len = BIO_get_mem_data(ds, &pp);
1867 if(verb) printf("out of memory\n");
1870 out = fopen(root_anchor_file, "w");
1872 if(verb) printf("%s: %s\n", root_anchor_file, strerror(errno));
1875 if(fwrite(pp, (size_t)len, 1, out) != 1) {
1876 if(verb) printf("failed to write all data to %s\n",
1878 if(verb && errno != 0) printf("%s\n", strerror(errno));
1884 FlushFileBuffers((HANDLE)_get_osfhandle(_fileno(out)));
1889 /** Perform the verification and update of the trustanchor file */
1891 verify_and_update_anchor(const char* root_anchor_file, BIO* xml, BIO* p7s,
1892 STACK_OF(X509)* cert, const char* p7signer)
1896 /* verify xml file */
1897 if(!verify_p7sig(xml, p7s, cert, p7signer)) {
1898 printf("the PKCS7 signature failed\n");
1902 /* parse the xml file into DS records */
1903 ds = xml_parse(xml, time(NULL));
1905 /* the root zone is unsigned now */
1906 write_unsigned_root(root_anchor_file);
1908 /* reinstate 5011 tracking */
1909 write_root_anchor(root_anchor_file, ds);
1915 static void do_wsa_cleanup(void) { WSACleanup(); }
1918 /** perform actual certupdate work */
1920 do_certupdate(const char* root_anchor_file, const char* root_cert_file,
1921 const char* urlname, const char* xmlname, const char* p7sname,
1922 const char* p7signer, const char* res_conf, const char* root_hints,
1923 const char* debugconf, int ip4only, int ip6only, int port,
1924 struct ub_result* dnskey)
1926 STACK_OF(X509)* cert;
1928 struct ip_list* ip_list = NULL;
1930 /* read pem file or provide builtin */
1931 cert = read_cert_or_builtin(root_cert_file);
1933 /* lookup A, AAAA for the urlname (or parse urlname if IP address) */
1934 ip_list = resolve_name(urlname, port, res_conf, root_hints, debugconf,
1938 if(1) { /* libunbound finished, startup WSA for the https connection */
1941 if((r = WSAStartup(MAKEWORD(2,2), &wsa_data)) != 0) {
1942 if(verb) printf("WSAStartup failed: %s\n",
1946 atexit(&do_wsa_cleanup);
1950 /* fetch the necessary files over HTTPS */
1951 xml = https(ip_list, xmlname, urlname);
1952 p7s = https(ip_list, p7sname, urlname);
1954 /* verify and update the root anchor */
1955 verify_and_update_anchor(root_anchor_file, xml, p7s, cert, p7signer);
1956 if(verb) printf("success: the anchor has been updated "
1957 "using the cert\n");
1962 sk_X509_pop_free(cert, X509_free);
1964 ub_resolve_free(dnskey);
1965 ip_list_free(ip_list);
1970 * Try to read the root RFC5011 autotrust anchor file,
1971 * @param file: filename.
1973 * 0 if does not exist or empty
1974 * 1 if trust-point-revoked-5011
1978 try_read_anchor(const char* file)
1983 FILE* in = fopen(file, "r");
1985 /* only if the file does not exist, can we fix it */
1986 if(errno != ENOENT) {
1987 if(verb) printf("%s: %s\n", file, strerror(errno));
1988 if(verb) printf("error: cannot access the file\n");
1991 if(verb) printf("%s does not exist\n", file);
1994 while(fgets(line, (int)sizeof(line), in)) {
1995 line[sizeof(line)-1] = 0;
1996 if(strncmp(line, ";;REVOKED", 9) == 0) {
1998 if(verb) printf("%s : the trust point is revoked\n"
1999 "and the zone is considered unsigned.\n"
2000 "if you wish to re-enable, delete the file\n",
2005 while(*p == ' ' || *p == '\t')
2007 if(p[0]==0 || p[0]=='\n' || p[0]==';') continue;
2008 /* this line is a line of content */
2013 if(verb) printf("%s is empty\n", file);
2016 if(verb) printf("%s has content\n", file);
2020 /** Write the builtin root anchor to a file */
2022 write_builtin_anchor(const char* file)
2024 const char* builtin_root_anchor = get_builtin_ds();
2025 FILE* out = fopen(file, "w");
2027 if(verb) printf("%s: %s\n", file, strerror(errno));
2028 if(verb) printf(" could not write builtin anchor\n");
2031 if(!fwrite(builtin_root_anchor, strlen(builtin_root_anchor), 1, out)) {
2032 if(verb) printf("%s: %s\n", file, strerror(errno));
2033 if(verb) printf(" could not complete write builtin anchor\n");
2039 * Check the root anchor file.
2040 * If does not exist, provide builtin and write file.
2041 * If empty, provide builtin and write file.
2042 * If trust-point-revoked-5011 file: make the program exit.
2043 * @param root_anchor_file: filename of the root anchor.
2044 * @param used_builtin: set to 1 if the builtin is written.
2045 * @return 0 if trustpoint is insecure, 1 on success. Exit on failure.
2048 provide_builtin(const char* root_anchor_file, int* used_builtin)
2050 /* try to read it */
2051 switch(try_read_anchor(root_anchor_file))
2053 case 0: /* no exist or empty */
2054 write_builtin_anchor(root_anchor_file);
2057 case 1: /* revoked tp */
2059 case 2: /* it is fine */
2067 * add an autotrust anchor for the root to the context
2070 add_5011_probe_root(struct ub_ctx* ctx, const char* root_anchor_file)
2073 r = ub_ctx_set_option(ctx, "auto-trust-anchor-file:", root_anchor_file);
2075 if(verb) printf("add 5011 probe to ctx: %s\n", ub_strerror(r));
2082 * Prime the root key and return the result. Exit on error.
2083 * @param ctx: the unbound context to perform the priming with.
2084 * @return: the result of the prime, on error it exit()s.
2086 static struct ub_result*
2087 prime_root_key(struct ub_ctx* ctx)
2089 struct ub_result* res = NULL;
2091 r = ub_resolve(ctx, ".", LDNS_RR_TYPE_DNSKEY, LDNS_RR_CLASS_IN, &res);
2093 if(verb) printf("resolve DNSKEY: %s\n", ub_strerror(r));
2098 if(verb) printf("out of memory\n");
2105 /** see if ADDPEND keys exist in autotrust file (if possible) */
2107 read_if_pending_keys(const char* file)
2109 FILE* in = fopen(file, "r");
2112 if(verb>=2) printf("%s: %s\n", file, strerror(errno));
2115 while(fgets(line, (int)sizeof(line), in)) {
2116 if(line[0]==';') continue;
2117 if(strstr(line, "[ ADDPEND ]")) {
2119 if(verb) printf("RFC5011-state has ADDPEND keys\n");
2127 /** read last successful probe time from autotrust file (if possible) */
2129 read_last_success_time(const char* file)
2131 FILE* in = fopen(file, "r");
2134 if(verb) printf("%s: %s\n", file, strerror(errno));
2137 while(fgets(line, (int)sizeof(line), in)) {
2138 if(strncmp(line, ";;last_success: ", 16) == 0) {
2140 time_t x = (unsigned int)strtol(line+16, &e, 10);
2143 if(verb) printf("failed to parse "
2144 "last_success probe time\n");
2147 if(verb) printf("last successful probe: %s", ctime(&x));
2152 if(verb) printf("no last_success probe time in anchor file\n");
2157 * Read autotrust 5011 probe file and see if the date
2158 * compared to the current date allows a certupdate.
2159 * If the last successful probe was recent then 5011 cannot be behind,
2160 * and the failure cannot be solved with a certupdate.
2161 * The debugconf is to validation-override the date for testing.
2162 * @param root_anchor_file: filename of root key
2163 * @return true if certupdate is ok.
2166 probe_date_allows_certupdate(const char* root_anchor_file)
2168 int has_pending_keys = read_if_pending_keys(root_anchor_file);
2169 int32_t last_success = read_last_success_time(root_anchor_file);
2170 int32_t now = (int32_t)time(NULL);
2171 int32_t leeway = 30 * 24 * 3600; /* 30 days leeway */
2172 /* if the date is before 2010-07-15:00.00.00 then the root has not
2173 * been signed yet, and thus we refuse to take action. */
2174 if(time(NULL) < xml_convertdate("2010-07-15T00:00:00")) {
2175 if(verb) printf("the date is before the root was first signed,"
2176 " please correct the clock\n");
2179 if(last_success == 0)
2180 return 1; /* no probe time */
2181 if(has_pending_keys)
2182 return 1; /* key in ADDPEND state, a previous probe has
2183 inserted that, and it was present in all recent probes,
2184 but it has not become active. The 30 day timer may not have
2185 expired, but we know(for sure) there is a rollover going on.
2186 If we only managed to pickup the new key on its last day
2187 of announcement (for example) this can happen. */
2188 if(now - last_success < 0) {
2189 if(verb) printf("the last successful probe is in the future,"
2190 " clock was modified\n");
2193 if(now - last_success >= leeway) {
2194 if(verb) printf("the last successful probe was more than 30 "
2198 if(verb) printf("the last successful probe is recent\n");
2202 /** perform the unbound-anchor work */
2204 do_root_update_work(const char* root_anchor_file, const char* root_cert_file,
2205 const char* urlname, const char* xmlname, const char* p7sname,
2206 const char* p7signer, const char* res_conf, const char* root_hints,
2207 const char* debugconf, int ip4only, int ip6only, int force, int port)
2210 struct ub_result* dnskey;
2211 int used_builtin = 0;
2213 /* see if builtin rootanchor needs to be provided, or if
2214 * rootanchor is 'revoked-trust-point' */
2215 if(!provide_builtin(root_anchor_file, &used_builtin))
2218 /* make unbound context with 5011-probe for root anchor,
2219 * and probe . DNSKEY */
2220 ctx = create_unbound_context(res_conf, root_hints, debugconf,
2222 add_5011_probe_root(ctx, root_anchor_file);
2223 dnskey = prime_root_key(ctx);
2226 /* if secure: exit */
2227 if(dnskey->secure && !force) {
2228 if(verb) printf("success: the anchor is ok\n");
2229 ub_resolve_free(dnskey);
2230 return used_builtin;
2232 if(force && verb) printf("debug cert update forced\n");
2234 /* if not (and NOERROR): check date and do certupdate */
2235 if((dnskey->rcode == 0 &&
2236 probe_date_allows_certupdate(root_anchor_file)) || force) {
2237 if(do_certupdate(root_anchor_file, root_cert_file, urlname,
2238 xmlname, p7sname, p7signer, res_conf, root_hints,
2239 debugconf, ip4only, ip6only, port, dnskey))
2241 return used_builtin;
2243 if(verb) printf("fail: the anchor is NOT ok and could not be fixed\n");
2244 ub_resolve_free(dnskey);
2245 return used_builtin;
2248 /** getopt global, in case header files fail to declare it. */
2250 /** getopt global, in case header files fail to declare it. */
2251 extern char* optarg;
2253 /** Main routine for unbound-anchor */
2254 int main(int argc, char* argv[])
2257 const char* root_anchor_file = ROOT_ANCHOR_FILE;
2258 const char* root_cert_file = ROOT_CERT_FILE;
2259 const char* urlname = URLNAME;
2260 const char* xmlname = XMLNAME;
2261 const char* p7sname = P7SNAME;
2262 const char* p7signer = P7SIGNER;
2263 const char* res_conf = NULL;
2264 const char* root_hints = NULL;
2265 const char* debugconf = NULL;
2266 int dolist=0, ip4only=0, ip6only=0, force=0, port = HTTPS_PORT;
2267 /* parse the options */
2268 while( (c=getopt(argc, argv, "46C:FP:a:c:f:hln:r:s:u:vx:")) != -1) {
2280 root_anchor_file = optarg;
2283 root_cert_file = optarg;
2301 root_hints = optarg;
2310 port = atoi(optarg);
2326 #ifdef HAVE_ERR_LOAD_CRYPTO_STRINGS
2327 ERR_load_crypto_strings();
2329 #if OPENSSL_VERSION_NUMBER < 0x10100000 || !defined(HAVE_OPENSSL_INIT_SSL)
2330 ERR_load_SSL_strings();
2332 #if OPENSSL_VERSION_NUMBER < 0x10100000 || !defined(HAVE_OPENSSL_INIT_CRYPTO)
2333 OpenSSL_add_all_algorithms();
2335 OPENSSL_init_crypto(OPENSSL_INIT_ADD_ALL_CIPHERS
2336 | OPENSSL_INIT_ADD_ALL_DIGESTS
2337 | OPENSSL_INIT_LOAD_CRYPTO_STRINGS, NULL);
2339 #if OPENSSL_VERSION_NUMBER < 0x10100000 || !defined(HAVE_OPENSSL_INIT_SSL)
2340 (void)SSL_library_init();
2342 (void)OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS, NULL);
2345 if(dolist) do_list_builtin();
2347 return do_root_update_work(root_anchor_file, root_cert_file, urlname,
2348 xmlname, p7sname, p7signer, res_conf, root_hints, debugconf,
2349 ip4only, ip6only, force, port);