2 * validator/autotrust.c - RFC5011 trust anchor management for unbound.
4 * Copyright (c) 2009, NLnet Labs. All rights reserved.
6 * This software is open source.
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
12 * Redistributions of source code must retain the above copyright notice,
13 * this list of conditions and the following disclaimer.
15 * Redistributions in binary form must reproduce the above copyright notice,
16 * this list of conditions and the following disclaimer in the documentation
17 * and/or other materials provided with the distribution.
19 * Neither the name of the NLNET LABS nor the names of its contributors may
20 * be used to endorse or promote products derived from this software without
21 * specific prior written permission.
23 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
25 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
26 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE
27 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
28 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
29 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
30 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
31 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
32 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
33 * POSSIBILITY OF SUCH DAMAGE.
39 * Contains autotrust implementation. The implementation was taken from
40 * the autotrust daemon (BSD licensed), written by Matthijs Mekking.
41 * It was modified to fit into unbound. The state table process is the same.
44 #include <ldns/ldns.h>
45 #include "validator/autotrust.h"
46 #include "validator/val_anchor.h"
47 #include "validator/val_utils.h"
48 #include "validator/val_sigcrypt.h"
49 #include "util/data/dname.h"
50 #include "util/data/packed_rrset.h"
52 #include "util/module.h"
53 #include "util/net_help.h"
54 #include "util/config_file.h"
55 #include "util/regional.h"
56 #include "util/random.h"
57 #include "util/data/msgparse.h"
58 #include "services/mesh.h"
59 #include "services/cache/rrset.h"
60 #include "validator/val_kcache.h"
62 /** number of times a key must be seen before it can become valid */
63 #define MIN_PENDINGCOUNT 2
66 static void do_revoked(struct module_env* env, struct autr_ta* anchor, int* c);
68 struct autr_global_data* autr_global_create(void)
70 struct autr_global_data* global;
71 global = (struct autr_global_data*)malloc(sizeof(*global));
74 rbtree_init(&global->probe, &probetree_cmp);
78 void autr_global_delete(struct autr_global_data* global)
82 /* elements deleted by parent */
83 memset(global, 0, sizeof(*global));
87 int probetree_cmp(const void* x, const void* y)
89 struct trust_anchor* a = (struct trust_anchor*)x;
90 struct trust_anchor* b = (struct trust_anchor*)y;
91 log_assert(a->autr && b->autr);
92 if(a->autr->next_probe_time < b->autr->next_probe_time)
94 if(a->autr->next_probe_time > b->autr->next_probe_time)
96 /* time is equal, sort on trust point identity */
97 return anchor_cmp(x, y);
101 autr_get_num_anchors(struct val_anchors* anchors)
106 lock_basic_lock(&anchors->lock);
108 res = anchors->autr->probe.count;
109 lock_basic_unlock(&anchors->lock);
113 /** Position in string */
115 position_in_string(char *str, const char* sub)
117 char* pos = strstr(str, sub);
119 return (int)(pos-str)+(int)strlen(sub);
123 /** Debug routine to print pretty key information */
125 verbose_key(struct autr_ta* ta, enum verbosity_value level,
126 const char* format, ...) ATTR_FORMAT(printf, 3, 4);
129 * Implementation of debug pretty key print
130 * @param ta: trust anchor key with DNSKEY data.
131 * @param level: verbosity level to print at.
132 * @param format: printf style format string.
135 verbose_key(struct autr_ta* ta, enum verbosity_value level,
136 const char* format, ...)
139 va_start(args, format);
140 if(verbosity >= level) {
141 char* str = ldns_rdf2str(ldns_rr_owner(ta->rr));
142 int keytag = (int)ldns_calc_keytag(ta->rr);
143 char msg[MAXSYSLOGMSGLEN];
144 vsnprintf(msg, sizeof(msg), format, args);
145 verbose(level, "%s key %d %s", str?str:"??", keytag, msg);
153 * @param str: to parse
154 * @param ta: trust key autotrust metadata
155 * @return false on failure.
158 parse_comments(char* str, struct autr_ta* ta)
160 int len = (int)strlen(str), pos = 0, timestamp = 0;
161 char* comment = (char*) malloc(sizeof(char)*len+1);
162 char* comments = comment;
164 log_err("malloc failure in parse");
167 /* skip over whitespace and data at start of line */
168 while (*str != '\0' && *str != ';')
184 pos = position_in_string(comments, "state=");
185 if (pos >= (int) strlen(comments))
187 log_err("parse error");
192 ta->s = AUTR_STATE_VALID;
195 int s = (int) comments[pos] - '0';
198 case AUTR_STATE_START:
199 case AUTR_STATE_ADDPEND:
200 case AUTR_STATE_VALID:
201 case AUTR_STATE_MISSING:
202 case AUTR_STATE_REVOKED:
203 case AUTR_STATE_REMOVED:
207 verbose_key(ta, VERB_OPS, "has undefined "
208 "state, considered NewKey");
209 ta->s = AUTR_STATE_START;
213 /* read pending count */
214 pos = position_in_string(comments, "count=");
215 if (pos >= (int) strlen(comments))
217 log_err("parse error");
222 ta->pending_count = 0;
226 ta->pending_count = (uint8_t)atoi(comments);
229 /* read last change */
230 pos = position_in_string(comments, "lastchange=");
231 if (pos >= (int) strlen(comments))
233 log_err("parse error");
240 timestamp = atoi(comments);
242 if (pos < 0 || !timestamp)
245 ta->last_change = (time_t)timestamp;
251 /** Check if a line contains data (besides comments) */
253 str_contains_data(char* str, char comment)
255 while (*str != '\0') {
256 if (*str == comment || *str == '\n')
258 if (*str != ' ' && *str != '\t')
265 /** Get DNSKEY flags */
267 dnskey_flags(ldns_rr* rr)
269 if(ldns_rr_get_type(rr) != LDNS_RR_TYPE_DNSKEY)
271 return (int)ldns_read_uint16(ldns_rdf_data(ldns_rr_dnskey_flags(rr)));
275 /** Check if KSK DNSKEY */
277 rr_is_dnskey_sep(ldns_rr* rr)
279 return (dnskey_flags(rr)&DNSKEY_BIT_SEP);
282 /** Check if REVOKED DNSKEY */
284 rr_is_dnskey_revoked(ldns_rr* rr)
286 return (dnskey_flags(rr)&LDNS_KEY_REVOKE_KEY);
290 static struct autr_ta*
291 autr_ta_create(ldns_rr* rr)
293 struct autr_ta* ta = (struct autr_ta*)calloc(1, sizeof(*ta));
303 static struct trust_anchor*
304 autr_tp_create(struct val_anchors* anchors, ldns_rdf* own, uint16_t dc)
306 struct trust_anchor* tp = (struct trust_anchor*)calloc(1, sizeof(*tp));
308 tp->name = memdup(ldns_rdf_data(own), ldns_rdf_size(own));
313 tp->namelen = ldns_rdf_size(own);
314 tp->namelabs = dname_count_labels(tp->name);
317 tp->autr = (struct autr_point_data*)calloc(1, sizeof(*tp->autr));
323 tp->autr->pnode.key = tp;
325 lock_basic_lock(&anchors->lock);
326 if(!rbtree_insert(anchors->tree, &tp->node)) {
327 lock_basic_unlock(&anchors->lock);
328 log_err("trust anchor presented twice");
334 if(!rbtree_insert(&anchors->autr->probe, &tp->autr->pnode)) {
335 (void)rbtree_delete(anchors->tree, tp);
336 lock_basic_unlock(&anchors->lock);
337 log_err("trust anchor in probetree twice");
343 lock_basic_unlock(&anchors->lock);
344 lock_basic_init(&tp->lock);
345 lock_protect(&tp->lock, tp, sizeof(*tp));
346 lock_protect(&tp->lock, tp->autr, sizeof(*tp->autr));
350 /** delete assembled rrsets */
352 autr_rrset_delete(struct ub_packed_rrset_key* r)
361 void autr_point_delete(struct trust_anchor* tp)
365 lock_unprotect(&tp->lock, tp);
366 lock_unprotect(&tp->lock, tp->autr);
367 lock_basic_destroy(&tp->lock);
368 autr_rrset_delete(tp->ds_rrset);
369 autr_rrset_delete(tp->dnskey_rrset);
371 struct autr_ta* p = tp->autr->keys, *np;
378 free(tp->autr->file);
385 /** find or add a new trust point for autotrust */
386 static struct trust_anchor*
387 find_add_tp(struct val_anchors* anchors, ldns_rr* rr)
389 struct trust_anchor* tp;
390 ldns_rdf* own = ldns_rr_owner(rr);
391 tp = anchor_find(anchors, ldns_rdf_data(own),
392 dname_count_labels(ldns_rdf_data(own)),
393 ldns_rdf_size(own), ldns_rr_get_class(rr));
396 log_err("anchor cannot be with and without autotrust");
397 lock_basic_unlock(&tp->lock);
402 tp = autr_tp_create(anchors, ldns_rr_owner(rr), ldns_rr_get_class(rr));
403 lock_basic_lock(&tp->lock);
407 /** Add trust anchor from RR */
408 static struct autr_ta*
409 add_trustanchor_frm_rr(struct val_anchors* anchors, ldns_rr* rr,
410 struct trust_anchor** tp)
412 struct autr_ta* ta = autr_ta_create(rr);
415 *tp = find_add_tp(anchors, rr);
417 ldns_rr_free(ta->rr);
422 ta->next = (*tp)->autr->keys;
423 (*tp)->autr->keys = ta;
424 lock_basic_unlock(&(*tp)->lock);
429 * Add new trust anchor from a string in file.
430 * @param anchors: all anchors
431 * @param str: string with anchor and comments, if any comments.
432 * @param tp: trust point returned.
433 * @param origin: what to use for @
434 * @param prev: previous rr name
435 * @param skip: if true, the result is NULL, but not an error, skip it.
436 * @return new key in trust point.
438 static struct autr_ta*
439 add_trustanchor_frm_str(struct val_anchors* anchors, char* str,
440 struct trust_anchor** tp, ldns_rdf* origin, ldns_rdf** prev, int* skip)
444 if (!str_contains_data(str, ';')) {
446 return NULL; /* empty line */
448 if (LDNS_STATUS_OK !=
449 (lstatus = ldns_rr_new_frm_str(&rr, str, 0, origin, prev)))
451 log_err("ldns error while converting string to RR: %s",
452 ldns_get_errorstr_by_id(lstatus));
455 if(ldns_rr_get_type(rr) != LDNS_RR_TYPE_DNSKEY &&
456 ldns_rr_get_type(rr) != LDNS_RR_TYPE_DS) {
459 return NULL; /* only DS and DNSKEY allowed */
461 return add_trustanchor_frm_rr(anchors, rr, tp);
466 * @param anchors: all points.
467 * @param str: comments line
468 * @param fname: filename
469 * @param origin: the $ORIGIN.
470 * @param prev: passed to ldns.
471 * @param skip: if true, the result is NULL, but not an error, skip it.
472 * @return false on failure, otherwise the tp read.
474 static struct trust_anchor*
475 load_trustanchor(struct val_anchors* anchors, char* str, const char* fname,
476 ldns_rdf* origin, ldns_rdf** prev, int* skip)
478 struct autr_ta* ta = NULL;
479 struct trust_anchor* tp = NULL;
481 ta = add_trustanchor_frm_str(anchors, str, &tp, origin, prev, skip);
484 lock_basic_lock(&tp->lock);
485 if(!parse_comments(str, ta)) {
486 lock_basic_unlock(&tp->lock);
489 if(!tp->autr->file) {
490 tp->autr->file = strdup(fname);
491 if(!tp->autr->file) {
492 lock_basic_unlock(&tp->lock);
493 log_err("malloc failure");
497 lock_basic_unlock(&tp->lock);
502 * Assemble the trust anchors into DS and DNSKEY packed rrsets.
503 * Uses only VALID and MISSING DNSKEYs.
504 * Read the ldns_rrs and builds packed rrsets
505 * @param tp: the trust point. Must be locked.
506 * @return false on malloc failure.
509 autr_assemble(struct trust_anchor* tp)
511 ldns_rr_list* ds, *dnskey;
513 struct ub_packed_rrset_key* ubds=NULL, *ubdnskey=NULL;
515 ds = ldns_rr_list_new();
516 dnskey = ldns_rr_list_new();
518 ldns_rr_list_free(ds);
519 ldns_rr_list_free(dnskey);
522 for(ta = tp->autr->keys; ta; ta = ta->next) {
523 if(ldns_rr_get_type(ta->rr) == LDNS_RR_TYPE_DS) {
524 if(!ldns_rr_list_push_rr(ds, ta->rr)) {
525 ldns_rr_list_free(ds);
526 ldns_rr_list_free(dnskey);
529 } else if(ta->s == AUTR_STATE_VALID ||
530 ta->s == AUTR_STATE_MISSING) {
531 if(!ldns_rr_list_push_rr(dnskey, ta->rr)) {
532 ldns_rr_list_free(ds);
533 ldns_rr_list_free(dnskey);
539 /* make packed rrset keys - malloced with no ID number, they
540 * are not in the cache */
541 /* make packed rrset data (if there is a key) */
543 if(ldns_rr_list_rr_count(ds) > 0) {
544 ubds = ub_packed_rrset_heap_key(ds);
547 ubds->entry.data = packed_rrset_heap_data(ds);
548 if(!ubds->entry.data)
551 if(ldns_rr_list_rr_count(dnskey) > 0) {
552 ubdnskey = ub_packed_rrset_heap_key(dnskey);
555 ubdnskey->entry.data = packed_rrset_heap_data(dnskey);
556 if(!ubdnskey->entry.data) {
558 autr_rrset_delete(ubds);
559 autr_rrset_delete(ubdnskey);
560 ldns_rr_list_free(ds);
561 ldns_rr_list_free(dnskey);
565 /* we have prepared the new keys so nothing can go wrong any more.
566 * And we are sure we cannot be left without trustanchor after
567 * any errors. Put in the new keys and remove old ones. */
569 /* free the old data */
570 autr_rrset_delete(tp->ds_rrset);
571 autr_rrset_delete(tp->dnskey_rrset);
573 /* assign the data to replace the old */
575 tp->dnskey_rrset = ubdnskey;
576 tp->numDS = ldns_rr_list_rr_count(ds);
577 tp->numDNSKEY = ldns_rr_list_rr_count(dnskey);
579 ldns_rr_list_free(ds);
580 ldns_rr_list_free(dnskey);
586 parse_int(char* line, int* ret)
589 unsigned int x = (unsigned int)strtol(line, &e, 10);
591 *ret = -1; /* parse error */
594 *ret = 1; /* matched */
598 /** parse id sequence for anchor */
599 static struct trust_anchor*
600 parse_id(struct val_anchors* anchors, char* line)
602 struct trust_anchor *tp;
606 /* read the owner name */
607 char* next = strchr(line, ' ');
611 rdf = ldns_dname_new_frm_str(line);
616 dclass = parse_int(next+1, &r);
618 ldns_rdf_deep_free(rdf);
622 /* find the trust point */
623 tp = autr_tp_create(anchors, rdf, dclass);
624 ldns_rdf_deep_free(rdf);
629 * Parse variable from trustanchor header
630 * @param line: to parse
631 * @param anchors: the anchor is added to this, if "id:" is seen.
632 * @param anchor: the anchor as result value or previously returned anchor
633 * value to read the variable lines into.
634 * @return: 0 no match, -1 failed syntax error, +1 success line read.
635 * +2 revoked trust anchor file.
638 parse_var_line(char* line, struct val_anchors* anchors,
639 struct trust_anchor** anchor)
641 struct trust_anchor* tp = *anchor;
643 if(strncmp(line, ";;id: ", 6) == 0) {
644 *anchor = parse_id(anchors, line+6);
645 if(!*anchor) return -1;
647 } else if(strncmp(line, ";;REVOKED", 9) == 0) {
649 log_err("REVOKED statement must be at start of file");
653 } else if(strncmp(line, ";;last_queried: ", 16) == 0) {
655 lock_basic_lock(&tp->lock);
656 tp->autr->last_queried = (time_t)parse_int(line+16, &r);
657 lock_basic_unlock(&tp->lock);
658 } else if(strncmp(line, ";;last_success: ", 16) == 0) {
660 lock_basic_lock(&tp->lock);
661 tp->autr->last_success = (time_t)parse_int(line+16, &r);
662 lock_basic_unlock(&tp->lock);
663 } else if(strncmp(line, ";;next_probe_time: ", 19) == 0) {
665 lock_basic_lock(&anchors->lock);
666 lock_basic_lock(&tp->lock);
667 (void)rbtree_delete(&anchors->autr->probe, tp);
668 tp->autr->next_probe_time = (time_t)parse_int(line+19, &r);
669 (void)rbtree_insert(&anchors->autr->probe, &tp->autr->pnode);
670 lock_basic_unlock(&tp->lock);
671 lock_basic_unlock(&anchors->lock);
672 } else if(strncmp(line, ";;query_failed: ", 16) == 0) {
674 lock_basic_lock(&tp->lock);
675 tp->autr->query_failed = (uint8_t)parse_int(line+16, &r);
676 lock_basic_unlock(&tp->lock);
677 } else if(strncmp(line, ";;query_interval: ", 18) == 0) {
679 lock_basic_lock(&tp->lock);
680 tp->autr->query_interval = (time_t)parse_int(line+18, &r);
681 lock_basic_unlock(&tp->lock);
682 } else if(strncmp(line, ";;retry_time: ", 14) == 0) {
684 lock_basic_lock(&tp->lock);
685 tp->autr->retry_time = (time_t)parse_int(line+14, &r);
686 lock_basic_unlock(&tp->lock);
691 /** handle origin lines */
693 handle_origin(char* line, ldns_rdf** origin)
695 while(isspace((int)*line))
697 if(strncmp(line, "$ORIGIN", 7) != 0)
699 ldns_rdf_deep_free(*origin);
701 while(isspace((int)*line))
703 *origin = ldns_dname_new_frm_str(line);
705 log_warn("malloc failure or parse error in $ORIGIN");
709 /** Read one line and put multiline RRs onto one line string */
711 read_multiline(char* buf, size_t len, FILE* in, int* linenr)
717 while(left > 0 && fgets(pos, (int)left, in) != NULL) {
718 size_t i, poslen = strlen(pos);
721 /* check what the new depth is after the line */
722 /* this routine cannot handle braces inside quotes,
723 say for TXT records, but this routine only has to read keys */
724 for(i=0; i<poslen; i++) {
727 } else if(pos[i] == ')') {
729 log_err("mismatch: too many ')'");
733 } else if(pos[i] == ';') {
738 /* normal oneline or last line: keeps newline and comments */
743 /* more lines expected, snip off comments and newline */
745 pos[poslen-1] = 0; /* strip newline */
747 strchr(pos, ';')[0] = 0; /* strip comments */
749 /* move to paste other lines behind this one */
750 poslen = strlen(pos);
753 /* the newline is changed into a space */
754 if(left <= 2 /* space and eos */) {
755 log_err("line too long");
764 log_err("mismatch: too many '('");
772 int autr_read_file(struct val_anchors* anchors, const char* nm)
774 /* the file descriptor */
776 /* keep track of line numbers */
780 /* trust point being read */
781 struct trust_anchor *tp = NULL, *tp2;
783 /* for $ORIGIN parsing */
784 ldns_rdf *origin=NULL, *prev=NULL;
786 if (!(fd = fopen(nm, "r"))) {
787 log_err("unable to open %s for reading: %s",
788 nm, strerror(errno));
791 verbose(VERB_ALGO, "reading autotrust anchor file %s", nm);
792 while ( (r=read_multiline(line, sizeof(line), fd, &line_nr)) != 0) {
793 if(r == -1 || (r = parse_var_line(line, anchors, &tp)) == -1) {
794 log_err("could not parse auto-trust-anchor-file "
795 "%s line %d", nm, line_nr);
797 ldns_rdf_deep_free(origin);
798 ldns_rdf_deep_free(prev);
803 log_warn("trust anchor %s has been revoked", nm);
805 ldns_rdf_deep_free(origin);
806 ldns_rdf_deep_free(prev);
809 if (!str_contains_data(line, ';'))
810 continue; /* empty lines allowed */
811 if(handle_origin(line, &origin))
814 if(!(tp2=load_trustanchor(anchors, line, nm, origin, &prev,
816 if(!r) log_err("failed to load trust anchor from %s "
817 "at line %i, skipping", nm, line_nr);
818 /* try to do the rest */
821 if(tp && tp != tp2) {
822 log_err("file %s has mismatching data inside: "
823 "the file may only contain keys for one name, "
824 "remove keys for other domain names", nm);
826 ldns_rdf_deep_free(origin);
827 ldns_rdf_deep_free(prev);
833 ldns_rdf_deep_free(origin);
834 ldns_rdf_deep_free(prev);
836 log_err("failed to read %s", nm);
840 /* now assemble the data into DNSKEY and DS packed rrsets */
841 lock_basic_lock(&tp->lock);
842 if(!autr_assemble(tp)) {
843 lock_basic_unlock(&tp->lock);
844 log_err("malloc failure assembling %s", nm);
847 lock_basic_unlock(&tp->lock);
851 /** string for a trustanchor state */
853 trustanchor_state2str(autr_state_t s)
856 case AUTR_STATE_START: return " START ";
857 case AUTR_STATE_ADDPEND: return " ADDPEND ";
858 case AUTR_STATE_VALID: return " VALID ";
859 case AUTR_STATE_MISSING: return " MISSING ";
860 case AUTR_STATE_REVOKED: return " REVOKED ";
861 case AUTR_STATE_REMOVED: return " REMOVED ";
866 /** print ID to file */
868 print_id(FILE* out, char* fname, struct module_env* env,
869 uint8_t* nm, size_t nmlen, uint16_t dclass)
876 memset(&rdf, 0, sizeof(rdf));
877 ldns_rdf_set_data(&rdf, nm);
878 ldns_rdf_set_size(&rdf, nmlen);
879 ldns_rdf_set_type(&rdf, LDNS_RDF_TYPE_DNAME);
881 ldns_buffer_clear(env->scratch_buffer);
887 ldns_rdf2buffer_str_dname(env->scratch_buffer, &rdf);
888 log_assert(s == LDNS_STATUS_OK);
889 ldns_buffer_write_u8(env->scratch_buffer, 0);
890 ldns_buffer_flip(env->scratch_buffer);
891 if(fprintf(out, ";;id: %s %d\n",
892 (char*)ldns_buffer_begin(env->scratch_buffer),
894 log_err("could not write to %s: %s", fname, strerror(errno));
901 autr_write_contents(FILE* out, char* fn, struct module_env* env,
902 struct trust_anchor* tp)
908 /* write pretty header */
909 if(fprintf(out, "; autotrust trust anchor file\n") < 0) {
910 log_err("could not write to %s: %s", fn, strerror(errno));
913 if(tp->autr->revoked) {
914 if(fprintf(out, ";;REVOKED\n") < 0 ||
915 fprintf(out, "; The zone has all keys revoked, and is\n"
916 "; considered as if it has no trust anchors.\n"
917 "; the remainder of the file is the last probe.\n"
918 "; to restart the trust anchor, overwrite this file.\n"
919 "; with one containing valid DNSKEYs or DSes.\n") < 0) {
920 log_err("could not write to %s: %s", fn, strerror(errno));
924 if(!print_id(out, fn, env, tp->name, tp->namelen, tp->dclass)) {
927 if(fprintf(out, ";;last_queried: %u ;;%s",
928 (unsigned int)tp->autr->last_queried,
929 ctime_r(&(tp->autr->last_queried), tmi)) < 0 ||
930 fprintf(out, ";;last_success: %u ;;%s",
931 (unsigned int)tp->autr->last_success,
932 ctime_r(&(tp->autr->last_success), tmi)) < 0 ||
933 fprintf(out, ";;next_probe_time: %u ;;%s",
934 (unsigned int)tp->autr->next_probe_time,
935 ctime_r(&(tp->autr->next_probe_time), tmi)) < 0 ||
936 fprintf(out, ";;query_failed: %d\n", (int)tp->autr->query_failed)<0
937 || fprintf(out, ";;query_interval: %d\n",
938 (int)tp->autr->query_interval) < 0 ||
939 fprintf(out, ";;retry_time: %d\n", (int)tp->autr->retry_time) < 0) {
940 log_err("could not write to %s: %s", fn, strerror(errno));
945 for(ta=tp->autr->keys; ta; ta=ta->next) {
946 /* by default do not store START and REMOVED keys */
947 if(ta->s == AUTR_STATE_START)
949 if(ta->s == AUTR_STATE_REMOVED)
951 /* only store keys */
952 if(ldns_rr_get_type(ta->rr) != LDNS_RR_TYPE_DNSKEY)
954 str = ldns_rr2str(ta->rr);
955 if(!str || !str[0]) {
957 log_err("malloc failure writing %s", fn);
960 str[strlen(str)-1] = 0; /* remove newline */
961 if(fprintf(out, "%s ;;state=%d [%s] ;;count=%d "
962 ";;lastchange=%u ;;%s", str, (int)ta->s,
963 trustanchor_state2str(ta->s), (int)ta->pending_count,
964 (unsigned int)ta->last_change,
965 ctime_r(&(ta->last_change), tmi)) < 0) {
966 log_err("could not write to %s: %s", fn, strerror(errno));
975 void autr_write_file(struct module_env* env, struct trust_anchor* tp)
978 char* fname = tp->autr->file;
980 log_assert(tp->autr);
982 log_err("autr_write_file: Module environment is NULL.");
985 /* unique name with pid number and thread number */
986 snprintf(tempf, sizeof(tempf), "%s.%d-%d", fname, (int)getpid(),
987 env->worker?*(int*)env->worker:0);
988 verbose(VERB_ALGO, "autotrust: write to disk: %s", tempf);
989 out = fopen(tempf, "w");
991 log_err("could not open autotrust file for writing, %s: %s",
992 tempf, strerror(errno));
995 if(!autr_write_contents(out, tempf, env, tp)) {
996 /* failed to write contents (completely) */
999 log_err("could not completely write: %s", fname);
1002 /* success; overwrite actual file */
1004 verbose(VERB_ALGO, "autotrust: replaced %s", fname);
1005 #ifdef UB_ON_WINDOWS
1006 (void)unlink(fname); /* windows does not replace file with rename() */
1008 if(rename(tempf, fname) < 0) {
1009 log_err("rename(%s to %s): %s", tempf, fname, strerror(errno));
1014 * Verify if dnskey works for trust point
1015 * @param env: environment (with time) for verification
1016 * @param ve: validator environment (with options) for verification.
1017 * @param tp: trust point to verify with
1018 * @param rrset: DNSKEY rrset to verify.
1019 * @return false on failure, true if verification successful.
1022 verify_dnskey(struct module_env* env, struct val_env* ve,
1023 struct trust_anchor* tp, struct ub_packed_rrset_key* rrset)
1025 char* reason = NULL;
1026 uint8_t sigalg[ALGO_NEEDS_MAX+1];
1028 enum sec_status sec = val_verify_DNSKEY_with_TA(env, ve, rrset,
1029 tp->ds_rrset, tp->dnskey_rrset, downprot?sigalg:NULL, &reason);
1030 /* sigalg is ignored, it returns algorithms signalled to exist, but
1031 * in 5011 there are no other rrsets to check. if downprot is
1032 * enabled, then it checks that the DNSKEY is signed with all
1033 * algorithms available in the trust store. */
1034 verbose(VERB_ALGO, "autotrust: validate DNSKEY with anchor: %s",
1035 sec_status_to_string(sec));
1036 return sec == sec_status_secure;
1039 /** Find minimum expiration interval from signatures */
1041 min_expiry(struct module_env* env, ldns_rr_list* rrset)
1044 int32_t t, r = 15 * 24 * 3600; /* 15 days max */
1045 for(i=0; i<ldns_rr_list_rr_count(rrset); i++) {
1046 ldns_rr* rr = ldns_rr_list_rr(rrset, i);
1047 if(ldns_rr_get_type(rr) != LDNS_RR_TYPE_RRSIG)
1049 t = ldns_rdf2native_int32(ldns_rr_rrsig_expiration(rr));
1050 if((int32_t)t - (int32_t)*env->now > 0) {
1059 /** Is rr self-signed revoked key */
1061 rr_is_selfsigned_revoked(struct module_env* env, struct val_env* ve,
1062 struct ub_packed_rrset_key* dnskey_rrset, size_t i)
1064 enum sec_status sec;
1065 char* reason = NULL;
1066 verbose(VERB_ALGO, "seen REVOKE flag, check self-signed, rr %d",
1068 /* no algorithm downgrade protection necessary, if it is selfsigned
1069 * revoked it can be removed. */
1070 sec = dnskey_verify_rrset(env, ve, dnskey_rrset, dnskey_rrset, i,
1072 return (sec == sec_status_secure);
1075 /** Set fetched value */
1077 seen_trustanchor(struct autr_ta* ta, uint8_t seen)
1080 if(ta->pending_count < 250) /* no numerical overflow, please */
1081 ta->pending_count++;
1084 /** set revoked value */
1086 seen_revoked_trustanchor(struct autr_ta* ta, uint8_t revoked)
1088 ta->revoked = revoked;
1091 /** revoke a trust anchor */
1093 revoke_dnskey(struct autr_ta* ta, int off)
1097 log_assert(ta && ta->rr);
1098 if(ldns_rr_get_type(ta->rr) != LDNS_RR_TYPE_DNSKEY)
1100 rdf = ldns_rr_dnskey_flags(ta->rr);
1101 flags = ldns_read_uint16(ldns_rdf_data(rdf));
1103 if (off && (flags&LDNS_KEY_REVOKE_KEY))
1104 flags ^= LDNS_KEY_REVOKE_KEY; /* flip */
1106 flags |= LDNS_KEY_REVOKE_KEY;
1107 ldns_write_uint16(ldns_rdf_data(rdf), flags);
1110 /** Compare two RR buffers skipping the REVOKED bit */
1112 ldns_rr_compare_wire_skip_revbit(ldns_buffer* rr1_buf, ldns_buffer* rr2_buf)
1114 size_t rr1_len, rr2_len, min_len, i, offset;
1115 rr1_len = ldns_buffer_capacity(rr1_buf);
1116 rr2_len = ldns_buffer_capacity(rr2_buf);
1117 /* jump past dname (checked in earlier part) and especially past TTL */
1119 while (offset < rr1_len && *ldns_buffer_at(rr1_buf, offset) != 0)
1120 offset += *ldns_buffer_at(rr1_buf, offset) + 1;
1121 /* jump to rdata section (PAST the rdata length field) */
1122 offset += 11; /* 0-dname-end + type + class + ttl + rdatalen */
1123 min_len = (rr1_len < rr2_len) ? rr1_len : rr2_len;
1124 /* compare RRs RDATA byte for byte. */
1125 for(i = offset; i < min_len; i++)
1127 uint8_t *rdf1, *rdf2;
1128 rdf1 = ldns_buffer_at(rr1_buf, i);
1129 rdf2 = ldns_buffer_at(rr2_buf, i);
1132 /* this is the second part of the flags field */
1133 *rdf1 = *rdf1 | LDNS_KEY_REVOKE_KEY;
1134 *rdf2 = *rdf2 | LDNS_KEY_REVOKE_KEY;
1136 if (*rdf1 < *rdf2) return -1;
1137 else if (*rdf1 > *rdf2) return 1;
1142 /** Compare two RRs skipping the REVOKED bit */
1144 ldns_rr_compare_skip_revbit(const ldns_rr* rr1, const ldns_rr* rr2, int* result)
1146 size_t rr1_len, rr2_len;
1147 ldns_buffer* rr1_buf;
1148 ldns_buffer* rr2_buf;
1150 *result = ldns_rr_compare_no_rdata(rr1, rr2);
1153 rr1_len = ldns_rr_uncompressed_size(rr1);
1154 rr2_len = ldns_rr_uncompressed_size(rr2);
1155 rr1_buf = ldns_buffer_new(rr1_len);
1156 rr2_buf = ldns_buffer_new(rr2_len);
1157 if(!rr1_buf || !rr2_buf) {
1158 ldns_buffer_free(rr1_buf);
1159 ldns_buffer_free(rr2_buf);
1162 if (ldns_rr2buffer_wire_canonical(rr1_buf, rr1,
1163 LDNS_SECTION_ANY) != LDNS_STATUS_OK)
1165 ldns_buffer_free(rr1_buf);
1166 ldns_buffer_free(rr2_buf);
1169 if (ldns_rr2buffer_wire_canonical(rr2_buf, rr2,
1170 LDNS_SECTION_ANY) != LDNS_STATUS_OK) {
1171 ldns_buffer_free(rr1_buf);
1172 ldns_buffer_free(rr2_buf);
1175 *result = ldns_rr_compare_wire_skip_revbit(rr1_buf, rr2_buf);
1176 ldns_buffer_free(rr1_buf);
1177 ldns_buffer_free(rr2_buf);
1183 /** compare two trust anchors */
1185 ta_compare(ldns_rr* a, ldns_rr* b, int* result)
1187 if (!a && !b) *result = 0;
1188 else if (!a) *result = -1;
1189 else if (!b) *result = 1;
1190 else if (ldns_rr_get_type(a) != ldns_rr_get_type(b))
1191 *result = (int)ldns_rr_get_type(a) - (int)ldns_rr_get_type(b);
1192 else if (ldns_rr_get_type(a) == LDNS_RR_TYPE_DNSKEY) {
1193 if(!ldns_rr_compare_skip_revbit(a, b, result))
1196 else if (ldns_rr_get_type(a) == LDNS_RR_TYPE_DS)
1197 *result = ldns_rr_compare(a, b);
1204 * @param tp: to search in
1205 * @param rr: to look for
1206 * @param result: returns NULL or the ta key looked for.
1207 * @return false on malloc failure during search. if true examine result.
1210 find_key(struct trust_anchor* tp, ldns_rr* rr, struct autr_ta** result)
1216 for(ta=tp->autr->keys; ta; ta=ta->next) {
1217 if(!ta_compare(ta->rr, rr, &ret))
1228 /** add key and clone RR and tp already locked */
1229 static struct autr_ta*
1230 add_key(struct trust_anchor* tp, ldns_rr* rr)
1234 c = ldns_rr_clone(rr);
1236 ta = autr_ta_create(c);
1241 /* link in, tp already locked */
1242 ta->next = tp->autr->keys;
1243 tp->autr->keys = ta;
1247 /** get TTL from DNSKEY rrset */
1249 key_ttl(struct ub_packed_rrset_key* k)
1251 struct packed_rrset_data* d = (struct packed_rrset_data*)k->entry.data;
1255 /** update the time values for the trustpoint */
1257 set_tp_times(struct trust_anchor* tp, time_t rrsig_exp_interval,
1258 time_t origttl, int* changed)
1260 time_t x, qi = tp->autr->query_interval, rt = tp->autr->retry_time;
1262 /* x = MIN(15days, ttl/2, expire/2) */
1266 if(rrsig_exp_interval/2 < x)
1267 x = rrsig_exp_interval/2;
1270 tp->autr->query_interval = 3600;
1271 else tp->autr->query_interval = x;
1273 /* x= MIN(1day, ttl/10, expire/10) */
1277 if(rrsig_exp_interval/10 < x)
1278 x = rrsig_exp_interval/10;
1281 tp->autr->retry_time = 3600;
1282 else tp->autr->retry_time = x;
1284 if(qi != tp->autr->query_interval || rt != tp->autr->retry_time) {
1286 verbose(VERB_ALGO, "orig_ttl is %d", (int)origttl);
1287 verbose(VERB_ALGO, "rrsig_exp_interval is %d",
1288 (int)rrsig_exp_interval);
1289 verbose(VERB_ALGO, "query_interval: %d, retry_time: %d",
1290 (int)tp->autr->query_interval,
1291 (int)tp->autr->retry_time);
1295 /** init events to zero */
1297 init_events(struct trust_anchor* tp)
1300 for(ta=tp->autr->keys; ta; ta=ta->next) {
1305 /** check for revoked keys without trusting any other information */
1307 check_contains_revoked(struct module_env* env, struct val_env* ve,
1308 struct trust_anchor* tp, struct ub_packed_rrset_key* dnskey_rrset,
1311 ldns_rr_list* r = packed_rrset_to_rr_list(dnskey_rrset,
1312 env->scratch_buffer);
1315 log_err("malloc failure");
1318 for(i=0; i<ldns_rr_list_rr_count(r); i++) {
1319 ldns_rr* rr = ldns_rr_list_rr(r, i);
1320 struct autr_ta* ta = NULL;
1321 if(ldns_rr_get_type(rr) != LDNS_RR_TYPE_DNSKEY)
1323 if(!rr_is_dnskey_sep(rr) || !rr_is_dnskey_revoked(rr))
1324 continue; /* not a revoked KSK */
1325 if(!find_key(tp, rr, &ta)) {
1326 log_err("malloc failure");
1327 continue; /* malloc fail in compare*/
1330 continue; /* key not found */
1331 if(rr_is_selfsigned_revoked(env, ve, dnskey_rrset, i)) {
1332 /* checked if there is an rrsig signed by this key. */
1333 log_assert(dnskey_calc_keytag(dnskey_rrset, i) ==
1334 ldns_calc_keytag(rr)); /* checks conversion*/
1335 verbose_key(ta, VERB_ALGO, "is self-signed revoked");
1338 seen_revoked_trustanchor(ta, 1);
1339 do_revoked(env, ta, changed);
1342 ldns_rr_list_deep_free(r);
1345 /** See if a DNSKEY is verified by one of the DSes */
1347 key_matches_a_ds(struct module_env* env, struct val_env* ve,
1348 struct ub_packed_rrset_key* dnskey_rrset, size_t key_idx,
1349 struct ub_packed_rrset_key* ds_rrset)
1351 struct packed_rrset_data* dd = (struct packed_rrset_data*)
1352 ds_rrset->entry.data;
1353 size_t ds_idx, num = dd->count;
1354 int d = val_favorite_ds_algo(ds_rrset);
1356 for(ds_idx=0; ds_idx<num; ds_idx++) {
1357 if(!ds_digest_algo_is_supported(ds_rrset, ds_idx) ||
1358 !ds_key_algo_is_supported(ds_rrset, ds_idx) ||
1359 ds_get_digest_algo(ds_rrset, ds_idx) != d)
1361 if(ds_get_key_algo(ds_rrset, ds_idx)
1362 != dnskey_get_algo(dnskey_rrset, key_idx)
1363 || dnskey_calc_keytag(dnskey_rrset, key_idx)
1364 != ds_get_keytag(ds_rrset, ds_idx)) {
1367 if(!ds_digest_match_dnskey(env, dnskey_rrset, key_idx,
1368 ds_rrset, ds_idx)) {
1369 verbose(VERB_ALGO, "DS match attempt failed");
1372 if(dnskey_verify_rrset(env, ve, dnskey_rrset,
1373 dnskey_rrset, key_idx, &reason) == sec_status_secure) {
1376 verbose(VERB_ALGO, "DS match failed because the key "
1377 "does not verify the keyset: %s", reason);
1383 /** Set update events */
1385 update_events(struct module_env* env, struct val_env* ve,
1386 struct trust_anchor* tp, struct ub_packed_rrset_key* dnskey_rrset,
1389 ldns_rr_list* r = packed_rrset_to_rr_list(dnskey_rrset,
1390 env->scratch_buffer);
1395 for(i=0; i<ldns_rr_list_rr_count(r); i++) {
1396 ldns_rr* rr = ldns_rr_list_rr(r, i);
1397 struct autr_ta* ta = NULL;
1398 if(ldns_rr_get_type(rr) != LDNS_RR_TYPE_DNSKEY)
1400 if(!rr_is_dnskey_sep(rr))
1402 if(rr_is_dnskey_revoked(rr)) {
1403 /* self-signed revoked keys already detected before,
1404 * other revoked keys are not 'added' again */
1407 /* is a key of this type supported?. Note rr_list and
1408 * packed_rrset are in the same order. */
1409 if(!dnskey_algo_is_supported(dnskey_rrset, i)) {
1410 /* skip unknown algorithm key, it is useless to us */
1411 log_nametypeclass(VERB_DETAIL, "trust point has "
1412 "unsupported algorithm at",
1413 tp->name, LDNS_RR_TYPE_DNSKEY, tp->dclass);
1417 /* is it new? if revocation bit set, find the unrevoked key */
1418 if(!find_key(tp, rr, &ta)) {
1419 ldns_rr_list_deep_free(r); /* malloc fail in compare*/
1423 ta = add_key(tp, rr);
1425 /* first time seen, do we have DSes? if match: VALID */
1426 if(ta && tp->ds_rrset && key_matches_a_ds(env, ve,
1427 dnskey_rrset, i, tp->ds_rrset)) {
1428 verbose_key(ta, VERB_ALGO, "verified by DS");
1429 ta->s = AUTR_STATE_VALID;
1433 ldns_rr_list_deep_free(r);
1436 seen_trustanchor(ta, 1);
1437 verbose_key(ta, VERB_ALGO, "in DNS response");
1439 set_tp_times(tp, min_expiry(env, r), key_ttl(dnskey_rrset), changed);
1440 ldns_rr_list_deep_free(r);
1445 * Check if the holddown time has already exceeded
1446 * setting: add-holddown: add holddown timer
1447 * setting: del-holddown: del holddown timer
1448 * @param env: environment with current time
1449 * @param ta: trust anchor to check for.
1450 * @param holddown: the timer value
1451 * @return number of seconds the holddown has passed.
1454 check_holddown(struct module_env* env, struct autr_ta* ta,
1455 unsigned int holddown)
1458 if(*env->now < ta->last_change) {
1459 log_warn("time goes backwards. delaying key holddown");
1462 elapsed = *env->now - ta->last_change;
1463 if (elapsed > (time_t)holddown) {
1464 return elapsed-(time_t)holddown;
1466 verbose_key(ta, VERB_ALGO, "holddown time %lld seconds to go",
1467 (long long) ((time_t)holddown-elapsed));
1472 /** Set last_change to now */
1474 reset_holddown(struct module_env* env, struct autr_ta* ta, int* changed)
1476 ta->last_change = *env->now;
1480 /** Set the state for this trust anchor */
1482 set_trustanchor_state(struct module_env* env, struct autr_ta* ta, int* changed,
1485 verbose_key(ta, VERB_ALGO, "update: %s to %s",
1486 trustanchor_state2str(ta->s), trustanchor_state2str(s));
1488 reset_holddown(env, ta, changed);
1492 /** Event: NewKey */
1494 do_newkey(struct module_env* env, struct autr_ta* anchor, int* c)
1496 if (anchor->s == AUTR_STATE_START)
1497 set_trustanchor_state(env, anchor, c, AUTR_STATE_ADDPEND);
1500 /** Event: AddTime */
1502 do_addtime(struct module_env* env, struct autr_ta* anchor, int* c)
1504 /* This not according to RFC, this is 30 days, but the RFC demands
1505 * MAX(30days, TTL expire time of first DNSKEY set with this key),
1506 * The value may be too small if a very large TTL was used. */
1507 time_t exceeded = check_holddown(env, anchor, env->cfg->add_holddown);
1508 if (exceeded && anchor->s == AUTR_STATE_ADDPEND) {
1509 verbose_key(anchor, VERB_ALGO, "add-holddown time exceeded "
1510 "%lld seconds ago, and pending-count %d",
1511 (long long)exceeded, anchor->pending_count);
1512 if(anchor->pending_count >= MIN_PENDINGCOUNT) {
1513 set_trustanchor_state(env, anchor, c, AUTR_STATE_VALID);
1514 anchor->pending_count = 0;
1517 verbose_key(anchor, VERB_ALGO, "add-holddown time sanity check "
1518 "failed (pending count: %d)", anchor->pending_count);
1522 /** Event: RemTime */
1524 do_remtime(struct module_env* env, struct autr_ta* anchor, int* c)
1526 time_t exceeded = check_holddown(env, anchor, env->cfg->del_holddown);
1527 if(exceeded && anchor->s == AUTR_STATE_REVOKED) {
1528 verbose_key(anchor, VERB_ALGO, "del-holddown time exceeded "
1529 "%lld seconds ago", (long long)exceeded);
1530 set_trustanchor_state(env, anchor, c, AUTR_STATE_REMOVED);
1534 /** Event: KeyRem */
1536 do_keyrem(struct module_env* env, struct autr_ta* anchor, int* c)
1538 if(anchor->s == AUTR_STATE_ADDPEND) {
1539 set_trustanchor_state(env, anchor, c, AUTR_STATE_START);
1540 anchor->pending_count = 0;
1541 } else if(anchor->s == AUTR_STATE_VALID)
1542 set_trustanchor_state(env, anchor, c, AUTR_STATE_MISSING);
1545 /** Event: KeyPres */
1547 do_keypres(struct module_env* env, struct autr_ta* anchor, int* c)
1549 if(anchor->s == AUTR_STATE_MISSING)
1550 set_trustanchor_state(env, anchor, c, AUTR_STATE_VALID);
1553 /* Event: Revoked */
1555 do_revoked(struct module_env* env, struct autr_ta* anchor, int* c)
1557 if(anchor->s == AUTR_STATE_VALID || anchor->s == AUTR_STATE_MISSING) {
1558 set_trustanchor_state(env, anchor, c, AUTR_STATE_REVOKED);
1559 verbose_key(anchor, VERB_ALGO, "old id, prior to revocation");
1560 revoke_dnskey(anchor, 0);
1561 verbose_key(anchor, VERB_ALGO, "new id, after revocation");
1565 /** Do statestable transition matrix for anchor */
1567 anchor_state_update(struct module_env* env, struct autr_ta* anchor, int* c)
1572 case AUTR_STATE_START:
1573 /* NewKey: ADDPEND */
1574 if (anchor->fetched)
1575 do_newkey(env, anchor, c);
1578 case AUTR_STATE_ADDPEND:
1580 if (!anchor->fetched)
1581 do_keyrem(env, anchor, c);
1582 /* AddTime: VALID */
1583 else do_addtime(env, anchor, c);
1586 case AUTR_STATE_VALID:
1587 /* RevBit: REVOKED */
1588 if (anchor->revoked)
1589 do_revoked(env, anchor, c);
1590 /* KeyRem: MISSING */
1591 else if (!anchor->fetched)
1592 do_keyrem(env, anchor, c);
1593 else if(!anchor->last_change) {
1594 verbose_key(anchor, VERB_ALGO, "first seen");
1595 reset_holddown(env, anchor, c);
1599 case AUTR_STATE_MISSING:
1600 /* RevBit: REVOKED */
1601 if (anchor->revoked)
1602 do_revoked(env, anchor, c);
1604 else if (anchor->fetched)
1605 do_keypres(env, anchor, c);
1608 case AUTR_STATE_REVOKED:
1609 if (anchor->fetched)
1610 reset_holddown(env, anchor, c);
1611 /* RemTime: REMOVED */
1612 else do_remtime(env, anchor, c);
1615 case AUTR_STATE_REMOVED:
1621 /** if ZSK init then trust KSKs */
1623 init_zsk_to_ksk(struct module_env* env, struct trust_anchor* tp, int* changed)
1625 /* search for VALID ZSKs */
1626 struct autr_ta* anchor;
1629 for(anchor = tp->autr->keys; anchor; anchor = anchor->next) {
1630 /* last_change test makes sure it was manually configured */
1631 if (ldns_rr_get_type(anchor->rr) == LDNS_RR_TYPE_DNSKEY &&
1632 anchor->last_change == 0 &&
1633 !rr_is_dnskey_sep(anchor->rr) &&
1634 anchor->s == AUTR_STATE_VALID)
1639 for(anchor = tp->autr->keys; anchor; anchor = anchor->next) {
1640 if (rr_is_dnskey_sep(anchor->rr) &&
1641 anchor->s == AUTR_STATE_ADDPEND) {
1642 verbose_key(anchor, VERB_ALGO, "trust KSK from "
1644 set_trustanchor_state(env, anchor, changed,
1652 /** Remove missing trustanchors so the list does not grow forever */
1654 remove_missing_trustanchors(struct module_env* env, struct trust_anchor* tp,
1657 struct autr_ta* anchor;
1660 /* see if we have anchors that are valid */
1661 for(anchor = tp->autr->keys; anchor; anchor = anchor->next) {
1663 if (!rr_is_dnskey_sep(anchor->rr))
1665 if (anchor->s == AUTR_STATE_VALID)
1668 /* if there are no SEP Valid anchors, see if we started out with
1669 * a ZSK (last-change=0) anchor, which is VALID and there are KSKs
1670 * now that can be made valid. Do this immediately because there
1671 * is no guarantee that the ZSKs get announced long enough. Usually
1672 * this is immediately after init with a ZSK trusted, unless the domain
1673 * was not advertising any KSKs at all. In which case we perfectly
1674 * track the zero number of KSKs. */
1676 valid = init_zsk_to_ksk(env, tp, changed);
1681 for(anchor = tp->autr->keys; anchor; anchor = anchor->next) {
1682 /* ignore ZSKs if newly added */
1683 if(anchor->s == AUTR_STATE_START)
1685 /* remove ZSKs if a KSK is present */
1686 if (!rr_is_dnskey_sep(anchor->rr)) {
1688 verbose_key(anchor, VERB_ALGO, "remove ZSK "
1689 "[%d key(s) VALID]", valid);
1690 set_trustanchor_state(env, anchor, changed,
1691 AUTR_STATE_REMOVED);
1695 /* Only do MISSING keys */
1696 if (anchor->s != AUTR_STATE_MISSING)
1698 if(env->cfg->keep_missing == 0)
1699 continue; /* keep forever */
1701 exceeded = check_holddown(env, anchor, env->cfg->keep_missing);
1702 /* If keep_missing has exceeded and we still have more than
1703 * one valid KSK: remove missing trust anchor */
1704 if (exceeded && valid > 0) {
1705 verbose_key(anchor, VERB_ALGO, "keep-missing time "
1706 "exceeded %lld seconds ago, [%d key(s) VALID]",
1707 (long long)exceeded, valid);
1708 set_trustanchor_state(env, anchor, changed,
1709 AUTR_STATE_REMOVED);
1714 /** Do the statetable from RFC5011 transition matrix */
1716 do_statetable(struct module_env* env, struct trust_anchor* tp, int* changed)
1718 struct autr_ta* anchor;
1719 for(anchor = tp->autr->keys; anchor; anchor = anchor->next) {
1721 if(!rr_is_dnskey_sep(anchor->rr))
1723 anchor_state_update(env, anchor, changed);
1725 remove_missing_trustanchors(env, tp, changed);
1729 /** See if time alone makes ADDPEND to VALID transition */
1731 autr_holddown_exceed(struct module_env* env, struct trust_anchor* tp, int* c)
1733 struct autr_ta* anchor;
1734 for(anchor = tp->autr->keys; anchor; anchor = anchor->next) {
1735 if(rr_is_dnskey_sep(anchor->rr) &&
1736 anchor->s == AUTR_STATE_ADDPEND)
1737 do_addtime(env, anchor, c);
1741 /** cleanup key list */
1743 autr_cleanup_keys(struct trust_anchor* tp)
1745 struct autr_ta* p, **prevp;
1746 prevp = &tp->autr->keys;
1749 /* do we want to remove this key? */
1750 if(p->s == AUTR_STATE_START || p->s == AUTR_STATE_REMOVED ||
1751 ldns_rr_get_type(p->rr) != LDNS_RR_TYPE_DNSKEY) {
1752 struct autr_ta* np = p->next;
1754 ldns_rr_free(p->rr);
1756 /* snip and go to next item */
1761 /* remove pending counts if no longer pending */
1762 if(p->s != AUTR_STATE_ADDPEND)
1763 p->pending_count = 0;
1769 /** calculate next probe time */
1771 calc_next_probe(struct module_env* env, time_t wait)
1773 /* make it random, 90-100% */
1779 rnd = (time_t)ub_random_max(env->rnd, (long int)rnd);
1780 return (time_t)(*env->now + rest + rnd);
1783 /** what is first probe time (anchors must be locked) */
1785 wait_probe_time(struct val_anchors* anchors)
1787 rbnode_t* t = rbtree_first(&anchors->autr->probe);
1788 if(t != RBTREE_NULL)
1789 return ((struct trust_anchor*)t->key)->autr->next_probe_time;
1793 /** reset worker timer */
1795 reset_worker_timer(struct module_env* env)
1799 time_t next = (time_t)wait_probe_time(env->anchors);
1800 /* in case this is libunbound, no timer */
1801 if(!env->probe_timer)
1803 if(next > *env->now)
1804 tv.tv_sec = (time_t)(next - *env->now);
1808 comm_timer_set(env->probe_timer, &tv);
1809 verbose(VERB_ALGO, "scheduled next probe in %lld sec", (long long)tv.tv_sec);
1812 /** set next probe for trust anchor */
1814 set_next_probe(struct module_env* env, struct trust_anchor* tp,
1815 struct ub_packed_rrset_key* dnskey_rrset)
1817 struct trust_anchor key, *tp2;
1819 /* use memory allocated in rrset for temporary name storage */
1820 key.node.key = &key;
1821 key.name = dnskey_rrset->rk.dname;
1822 key.namelen = dnskey_rrset->rk.dname_len;
1823 key.namelabs = dname_count_labels(key.name);
1824 key.dclass = tp->dclass;
1825 lock_basic_unlock(&tp->lock);
1827 /* fetch tp again and lock anchors, so that we can modify the trees */
1828 lock_basic_lock(&env->anchors->lock);
1829 tp2 = (struct trust_anchor*)rbtree_search(env->anchors->tree, &key);
1831 verbose(VERB_ALGO, "trustpoint was deleted in set_next_probe");
1832 lock_basic_unlock(&env->anchors->lock);
1835 log_assert(tp == tp2);
1836 lock_basic_lock(&tp->lock);
1839 mold = wait_probe_time(env->anchors);
1840 (void)rbtree_delete(&env->anchors->autr->probe, tp);
1841 tp->autr->next_probe_time = calc_next_probe(env,
1842 tp->autr->query_interval);
1843 (void)rbtree_insert(&env->anchors->autr->probe, &tp->autr->pnode);
1844 mnew = wait_probe_time(env->anchors);
1846 lock_basic_unlock(&env->anchors->lock);
1847 verbose(VERB_ALGO, "next probe set in %d seconds",
1848 (int)tp->autr->next_probe_time - (int)*env->now);
1850 reset_worker_timer(env);
1855 /** Revoke and Delete a trust point */
1857 autr_tp_remove(struct module_env* env, struct trust_anchor* tp,
1858 struct ub_packed_rrset_key* dnskey_rrset)
1860 struct trust_anchor* del_tp;
1861 struct trust_anchor key;
1862 struct autr_point_data pd;
1865 log_nametypeclass(VERB_OPS, "trust point was revoked",
1866 tp->name, LDNS_RR_TYPE_DNSKEY, tp->dclass);
1867 tp->autr->revoked = 1;
1869 /* use space allocated for dnskey_rrset to save name of anchor */
1870 memset(&key, 0, sizeof(key));
1871 memset(&pd, 0, sizeof(pd));
1873 key.node.key = &key;
1874 pd.pnode.key = &key;
1875 pd.next_probe_time = tp->autr->next_probe_time;
1876 key.name = dnskey_rrset->rk.dname;
1877 key.namelen = tp->namelen;
1878 key.namelabs = tp->namelabs;
1879 key.dclass = tp->dclass;
1882 lock_basic_unlock(&tp->lock);
1884 /* take from tree. It could be deleted by someone else,hence (void). */
1885 lock_basic_lock(&env->anchors->lock);
1886 del_tp = (struct trust_anchor*)rbtree_delete(env->anchors->tree, &key);
1887 mold = wait_probe_time(env->anchors);
1888 (void)rbtree_delete(&env->anchors->autr->probe, &key);
1889 mnew = wait_probe_time(env->anchors);
1890 anchors_init_parents_locked(env->anchors);
1891 lock_basic_unlock(&env->anchors->lock);
1893 /* if !del_tp then the trust point is no longer present in the tree,
1894 * it was deleted by someone else, who will write the zonefile and
1895 * clean up the structure */
1898 del_tp->autr->next_probe_time = 0; /* no more probing for it */
1899 autr_write_file(env, del_tp);
1902 autr_point_delete(del_tp);
1905 reset_worker_timer(env);
1909 int autr_process_prime(struct module_env* env, struct val_env* ve,
1910 struct trust_anchor* tp, struct ub_packed_rrset_key* dnskey_rrset)
1913 log_assert(tp && tp->autr);
1914 /* autotrust update trust anchors */
1915 /* the tp is locked, and stays locked unless it is deleted */
1917 /* we could just catch the anchor here while another thread
1918 * is busy deleting it. Just unlock and let the other do its job */
1919 if(tp->autr->revoked) {
1920 log_nametypeclass(VERB_ALGO, "autotrust not processed, "
1921 "trust point revoked", tp->name,
1922 LDNS_RR_TYPE_DNSKEY, tp->dclass);
1923 lock_basic_unlock(&tp->lock);
1924 return 0; /* it is revoked */
1927 /* query_dnskeys(): */
1928 tp->autr->last_queried = *env->now;
1930 log_nametypeclass(VERB_ALGO, "autotrust process for",
1931 tp->name, LDNS_RR_TYPE_DNSKEY, tp->dclass);
1932 /* see if time alone makes some keys valid */
1933 autr_holddown_exceed(env, tp, &changed);
1935 verbose(VERB_ALGO, "autotrust: morekeys, reassemble");
1936 if(!autr_assemble(tp)) {
1937 log_err("malloc failure assembling autotrust keys");
1938 return 1; /* unchanged */
1941 /* did we get any data? */
1943 verbose(VERB_ALGO, "autotrust: no dnskey rrset");
1944 /* no update of query_failed, because then we would have
1945 * to write to disk. But we cannot because we maybe are
1946 * still 'initialising' with DS records, that we cannot write
1947 * in the full format (which only contains KSKs). */
1948 return 1; /* trust point exists */
1950 /* check for revoked keys to remove immediately */
1951 check_contains_revoked(env, ve, tp, dnskey_rrset, &changed);
1953 verbose(VERB_ALGO, "autotrust: revokedkeys, reassemble");
1954 if(!autr_assemble(tp)) {
1955 log_err("malloc failure assembling autotrust keys");
1956 return 1; /* unchanged */
1958 if(!tp->ds_rrset && !tp->dnskey_rrset) {
1959 /* no more keys, all are revoked */
1960 /* this is a success for this probe attempt */
1961 tp->autr->last_success = *env->now;
1962 autr_tp_remove(env, tp, dnskey_rrset);
1963 return 0; /* trust point removed */
1966 /* verify the dnskey rrset and see if it is valid. */
1967 if(!verify_dnskey(env, ve, tp, dnskey_rrset)) {
1968 verbose(VERB_ALGO, "autotrust: dnskey did not verify.");
1969 /* only increase failure count if this is not the first prime,
1970 * this means there was a previous succesful probe */
1971 if(tp->autr->last_success) {
1972 tp->autr->query_failed += 1;
1973 autr_write_file(env, tp);
1975 return 1; /* trust point exists */
1978 tp->autr->last_success = *env->now;
1979 tp->autr->query_failed = 0;
1981 /* Add new trust anchors to the data structure
1982 * - note which trust anchors are seen this probe.
1983 * Set trustpoint query_interval and retry_time.
1984 * - find minimum rrsig expiration interval
1986 if(!update_events(env, ve, tp, dnskey_rrset, &changed)) {
1987 log_err("malloc failure in autotrust update_events. "
1988 "trust point unchanged.");
1989 return 1; /* trust point unchanged, so exists */
1992 /* - for every SEP key do the 5011 statetable.
1993 * - remove missing trustanchors (if veryold and we have new anchors).
1995 if(!do_statetable(env, tp, &changed)) {
1996 log_err("malloc failure in autotrust do_statetable. "
1997 "trust point unchanged.");
1998 return 1; /* trust point unchanged, so exists */
2001 autr_cleanup_keys(tp);
2002 if(!set_next_probe(env, tp, dnskey_rrset))
2003 return 0; /* trust point does not exist */
2004 autr_write_file(env, tp);
2006 verbose(VERB_ALGO, "autotrust: changed, reassemble");
2007 if(!autr_assemble(tp)) {
2008 log_err("malloc failure assembling autotrust keys");
2009 return 1; /* unchanged */
2011 if(!tp->ds_rrset && !tp->dnskey_rrset) {
2012 /* no more keys, all are revoked */
2013 autr_tp_remove(env, tp, dnskey_rrset);
2014 return 0; /* trust point removed */
2016 } else verbose(VERB_ALGO, "autotrust: no changes");
2018 return 1; /* trust point exists */
2021 /** debug print a trust anchor key */
2023 autr_debug_print_ta(struct autr_ta* ta)
2026 char* str = ldns_rr2str(ta->rr);
2028 log_info("out of memory in debug_print_ta");
2031 if(str && str[0]) str[strlen(str)-1]=0; /* remove newline */
2032 ctime_r(&ta->last_change, buf);
2033 if(buf[0]) buf[strlen(buf)-1]=0; /* remove newline */
2034 log_info("[%s] %s ;;state:%d ;;pending_count:%d%s%s last:%s",
2035 trustanchor_state2str(ta->s), str, ta->s, ta->pending_count,
2036 ta->fetched?" fetched":"", ta->revoked?" revoked":"", buf);
2040 /** debug print a trust point */
2042 autr_debug_print_tp(struct trust_anchor* tp)
2048 dname_str(tp->name, buf);
2049 log_info("trust point %s : %d", buf, (int)tp->dclass);
2050 log_info("assembled %d DS and %d DNSKEYs",
2051 (int)tp->numDS, (int)tp->numDNSKEY);
2052 if(0) { /* turned off because it prints to stderr */
2053 ldns_buffer* bf = ldns_buffer_new(70000);
2056 list = packed_rrset_to_rr_list(tp->ds_rrset, bf);
2057 ldns_rr_list_print(stderr, list);
2058 ldns_rr_list_deep_free(list);
2060 if(tp->dnskey_rrset) {
2061 list = packed_rrset_to_rr_list(tp->dnskey_rrset, bf);
2062 ldns_rr_list_print(stderr, list);
2063 ldns_rr_list_deep_free(list);
2065 ldns_buffer_free(bf);
2067 log_info("file %s", tp->autr->file);
2068 ctime_r(&tp->autr->last_queried, buf);
2069 if(buf[0]) buf[strlen(buf)-1]=0; /* remove newline */
2070 log_info("last_queried: %u %s", (unsigned)tp->autr->last_queried, buf);
2071 ctime_r(&tp->autr->last_success, buf);
2072 if(buf[0]) buf[strlen(buf)-1]=0; /* remove newline */
2073 log_info("last_success: %u %s", (unsigned)tp->autr->last_success, buf);
2074 ctime_r(&tp->autr->next_probe_time, buf);
2075 if(buf[0]) buf[strlen(buf)-1]=0; /* remove newline */
2076 log_info("next_probe_time: %u %s", (unsigned)tp->autr->next_probe_time,
2078 log_info("query_interval: %u", (unsigned)tp->autr->query_interval);
2079 log_info("retry_time: %u", (unsigned)tp->autr->retry_time);
2080 log_info("query_failed: %u", (unsigned)tp->autr->query_failed);
2082 for(ta=tp->autr->keys; ta; ta=ta->next) {
2083 autr_debug_print_ta(ta);
2088 autr_debug_print(struct val_anchors* anchors)
2090 struct trust_anchor* tp;
2091 lock_basic_lock(&anchors->lock);
2092 RBTREE_FOR(tp, struct trust_anchor*, anchors->tree) {
2093 lock_basic_lock(&tp->lock);
2094 autr_debug_print_tp(tp);
2095 lock_basic_unlock(&tp->lock);
2097 lock_basic_unlock(&anchors->lock);
2100 void probe_answer_cb(void* arg, int ATTR_UNUSED(rcode),
2101 ldns_buffer* ATTR_UNUSED(buf), enum sec_status ATTR_UNUSED(sec),
2102 char* ATTR_UNUSED(why_bogus))
2104 /* retry was set before the query was done,
2105 * re-querytime is set when query succeeded, but that may not
2106 * have reset this timer because the query could have been
2107 * handled by another thread. In that case, this callback would
2108 * get called after the original timeout is done.
2109 * By not resetting the timer, it may probe more often, but not
2111 * Unless the new lookup resulted in smaller TTLs and thus smaller
2112 * timeout values. In that case one old TTL could be mistakenly done.
2114 struct module_env* env = (struct module_env*)arg;
2115 verbose(VERB_ALGO, "autotrust probe answer cb");
2116 reset_worker_timer(env);
2119 /** probe a trust anchor DNSKEY and unlocks tp */
2121 probe_anchor(struct module_env* env, struct trust_anchor* tp)
2123 struct query_info qinfo;
2124 uint16_t qflags = BIT_RD;
2125 struct edns_data edns;
2126 ldns_buffer* buf = env->scratch_buffer;
2127 qinfo.qname = regional_alloc_init(env->scratch, tp->name, tp->namelen);
2129 log_err("out of memory making 5011 probe");
2132 qinfo.qname_len = tp->namelen;
2133 qinfo.qtype = LDNS_RR_TYPE_DNSKEY;
2134 qinfo.qclass = tp->dclass;
2135 log_query_info(VERB_ALGO, "autotrust probe", &qinfo);
2136 verbose(VERB_ALGO, "retry probe set in %d seconds",
2137 (int)tp->autr->next_probe_time - (int)*env->now);
2138 edns.edns_present = 1;
2140 edns.edns_version = 0;
2141 edns.bits = EDNS_DO;
2142 if(ldns_buffer_capacity(buf) < 65535)
2143 edns.udp_size = (uint16_t)ldns_buffer_capacity(buf);
2144 else edns.udp_size = 65535;
2146 /* can't hold the lock while mesh_run is processing */
2147 lock_basic_unlock(&tp->lock);
2149 /* delete the DNSKEY from rrset and key cache so an active probe
2150 * is done. First the rrset so another thread does not use it
2151 * to recreate the key entry in a race condition. */
2152 rrset_cache_remove(env->rrset_cache, qinfo.qname, qinfo.qname_len,
2153 qinfo.qtype, qinfo.qclass, 0);
2154 key_cache_remove(env->key_cache, qinfo.qname, qinfo.qname_len,
2157 if(!mesh_new_callback(env->mesh, &qinfo, qflags, &edns, buf, 0,
2158 &probe_answer_cb, env)) {
2159 log_err("out of memory making 5011 probe");
2163 /** fetch first to-probe trust-anchor and lock it and set retrytime */
2164 static struct trust_anchor*
2165 todo_probe(struct module_env* env, time_t* next)
2167 struct trust_anchor* tp;
2170 lock_basic_lock(&env->anchors->lock);
2171 if( (el=rbtree_first(&env->anchors->autr->probe)) == RBTREE_NULL) {
2172 /* in case of revoked anchors */
2173 lock_basic_unlock(&env->anchors->lock);
2176 tp = (struct trust_anchor*)el->key;
2177 lock_basic_lock(&tp->lock);
2179 /* is it eligible? */
2180 if((time_t)tp->autr->next_probe_time > *env->now) {
2181 /* no more to probe */
2182 *next = (time_t)tp->autr->next_probe_time - *env->now;
2183 lock_basic_unlock(&tp->lock);
2184 lock_basic_unlock(&env->anchors->lock);
2188 /* reset its next probe time */
2189 (void)rbtree_delete(&env->anchors->autr->probe, tp);
2190 tp->autr->next_probe_time = calc_next_probe(env, tp->autr->retry_time);
2191 (void)rbtree_insert(&env->anchors->autr->probe, &tp->autr->pnode);
2192 lock_basic_unlock(&env->anchors->lock);
2198 autr_probe_timer(struct module_env* env)
2200 struct trust_anchor* tp;
2201 time_t next_probe = 3600;
2203 verbose(VERB_ALGO, "autotrust probe timer callback");
2204 /* while there are still anchors to probe */
2205 while( (tp = todo_probe(env, &next_probe)) ) {
2206 /* make a probe for this anchor */
2207 probe_anchor(env, tp);
2210 regional_free_all(env->scratch);
2212 return 0; /* no trust points to probe */
2213 verbose(VERB_ALGO, "autotrust probe timer %d callbacks done", num);