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