Home | History | Annotate | Line # | Download | only in validator
      1 /*
      2  * validator/autotrust.c - RFC5011 trust anchor management for unbound.
      3  *
      4  * Copyright (c) 2009, 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  * 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.
     42  */
     43 #include "config.h"
     44 #include "validator/autotrust.h"
     45 #include "validator/val_anchor.h"
     46 #include "validator/val_utils.h"
     47 #include "validator/val_sigcrypt.h"
     48 #include "util/data/dname.h"
     49 #include "util/data/packed_rrset.h"
     50 #include "util/log.h"
     51 #include "util/module.h"
     52 #include "util/net_help.h"
     53 #include "util/config_file.h"
     54 #include "util/regional.h"
     55 #include "util/random.h"
     56 #include "util/data/msgparse.h"
     57 #include "services/mesh.h"
     58 #include "services/cache/rrset.h"
     59 #include "validator/val_kcache.h"
     60 #include "sldns/sbuffer.h"
     61 #include "sldns/wire2str.h"
     62 #include "sldns/str2wire.h"
     63 #include "sldns/keyraw.h"
     64 #include "sldns/rrdef.h"
     65 #include <stdarg.h>
     66 #include <ctype.h>
     67 
     68 /** number of times a key must be seen before it can become valid */
     69 #define MIN_PENDINGCOUNT 2
     70 
     71 /** Event: Revoked */
     72 static void do_revoked(struct module_env* env, struct autr_ta* anchor, int* c);
     73 
     74 struct autr_global_data* autr_global_create(void)
     75 {
     76 	struct autr_global_data* global;
     77 	global = (struct autr_global_data*)malloc(sizeof(*global));
     78 	if(!global)
     79 		return NULL;
     80 	rbtree_init(&global->probe, &probetree_cmp);
     81 	return global;
     82 }
     83 
     84 void autr_global_delete(struct autr_global_data* global)
     85 {
     86 	if(!global)
     87 		return;
     88 	/* elements deleted by parent */
     89 	free(global);
     90 }
     91 
     92 int probetree_cmp(const void* x, const void* y)
     93 {
     94 	struct trust_anchor* a = (struct trust_anchor*)x;
     95 	struct trust_anchor* b = (struct trust_anchor*)y;
     96 	log_assert(a->autr && b->autr);
     97 	if(a->autr->next_probe_time < b->autr->next_probe_time)
     98 		return -1;
     99 	if(a->autr->next_probe_time > b->autr->next_probe_time)
    100 		return 1;
    101 	/* time is equal, sort on trust point identity */
    102 	return anchor_cmp(x, y);
    103 }
    104 
    105 size_t
    106 autr_get_num_anchors(struct val_anchors* anchors)
    107 {
    108 	size_t res = 0;
    109 	if(!anchors)
    110 		return 0;
    111 	lock_basic_lock(&anchors->lock);
    112 	if(anchors->autr)
    113 		res = anchors->autr->probe.count;
    114 	lock_basic_unlock(&anchors->lock);
    115 	return res;
    116 }
    117 
    118 /** Position in string */
    119 static int
    120 position_in_string(char *str, const char* sub)
    121 {
    122 	char* pos = strstr(str, sub);
    123 	if(pos)
    124 		return (int)(pos-str)+(int)strlen(sub);
    125 	return -1;
    126 }
    127 
    128 /** Debug routine to print pretty key information */
    129 static void
    130 verbose_key(struct autr_ta* ta, enum verbosity_value level,
    131 	const char* format, ...) ATTR_FORMAT(printf, 3, 4);
    132 
    133 /**
    134  * Implementation of debug pretty key print
    135  * @param ta: trust anchor key with DNSKEY data.
    136  * @param level: verbosity level to print at.
    137  * @param format: printf style format string.
    138  */
    139 static void
    140 verbose_key(struct autr_ta* ta, enum verbosity_value level,
    141 	const char* format, ...)
    142 {
    143 	va_list args;
    144 	va_start(args, format);
    145 	if(verbosity >= level) {
    146 		char* str = sldns_wire2str_dname(ta->rr, ta->dname_len);
    147 		int keytag = (int)sldns_calc_keytag_raw(sldns_wirerr_get_rdata(
    148 			ta->rr, ta->rr_len, ta->dname_len),
    149 			sldns_wirerr_get_rdatalen(ta->rr, ta->rr_len,
    150 			ta->dname_len));
    151 		char msg[MAXSYSLOGMSGLEN];
    152 		vsnprintf(msg, sizeof(msg), format, args);
    153 		verbose(level, "%s key %d %s", str?str:"??", keytag, msg);
    154 		free(str);
    155 	}
    156 	va_end(args);
    157 }
    158 
    159 /**
    160  * Parse comments
    161  * @param str: to parse
    162  * @param ta: trust key autotrust metadata
    163  * @param header_seen: if an autotrust file header was seen.
    164  *	Without such a header it is a list of resource records.
    165  * @return false on failure.
    166  */
    167 static int
    168 parse_comments(char* str, struct autr_ta* ta, int header_seen)
    169 {
    170         int len = (int)strlen(str), pos = 0, timestamp = 0;
    171         char* comment = (char*) malloc(sizeof(char)*len+1);
    172         char* comments = comment;
    173 	if(!comment) {
    174 		log_err("malloc failure in parse");
    175                 return 0;
    176 	}
    177 	/* skip over whitespace and data at start of line */
    178         while (*str != '\0' && *str != ';')
    179                 str++;
    180         if (*str == ';')
    181                 str++;
    182         /* copy comments */
    183         while (*str != '\0')
    184         {
    185                 *comments = *str;
    186                 comments++;
    187                 str++;
    188         }
    189         *comments = '\0';
    190 
    191         comments = comment;
    192 
    193         /* read state */
    194         pos = position_in_string(comments, "state=");
    195         if (pos >= (int) strlen(comments))
    196         {
    197 		log_err("parse error");
    198                 free(comment);
    199                 return 0;
    200         }
    201         if (pos <= 0) {
    202 		if(header_seen) {
    203 			/* There was an autotrust trust anchor file header,
    204 			 * with a ;; id=.. line, so the entries
    205 			 * have to have ;;state= annotations. */
    206 			log_err("trust anchor in state file has no ;;state= "
    207 				"annotation, ignoring");
    208 			free(comment);
    209 			return 0;
    210 		}
    211 		ta->s = AUTR_STATE_VALID;
    212         } else {
    213                 int s = (int) comments[pos] - '0';
    214                 switch(s)
    215                 {
    216                         case AUTR_STATE_START:
    217                         case AUTR_STATE_ADDPEND:
    218                         case AUTR_STATE_VALID:
    219                         case AUTR_STATE_MISSING:
    220                         case AUTR_STATE_REVOKED:
    221                         case AUTR_STATE_REMOVED:
    222                                 ta->s = s;
    223                                 break;
    224                         default:
    225 				verbose_key(ta, VERB_OPS, "has undefined "
    226 					"state, considered NewKey");
    227                                 ta->s = AUTR_STATE_START;
    228                                 break;
    229                 }
    230         }
    231         /* read pending count */
    232         pos = position_in_string(comments, "count=");
    233         if (pos >= (int) strlen(comments))
    234         {
    235 		log_err("parse error");
    236                 free(comment);
    237                 return 0;
    238         }
    239         if (pos <= 0)
    240                 ta->pending_count = 0;
    241         else
    242         {
    243                 comments += pos;
    244                 ta->pending_count = (uint8_t)atoi(comments);
    245         }
    246 
    247         /* read last change */
    248         pos = position_in_string(comments, "lastchange=");
    249         if (pos >= (int) strlen(comments))
    250         {
    251 		log_err("parse error");
    252                 free(comment);
    253                 return 0;
    254         }
    255         if (pos >= 0)
    256         {
    257                 comments += pos;
    258                 timestamp = atoi(comments);
    259         }
    260         if (pos < 0 || !timestamp)
    261 		ta->last_change = 0;
    262         else
    263                 ta->last_change = (time_t)timestamp;
    264 
    265         free(comment);
    266         return 1;
    267 }
    268 
    269 /** Check if a line contains data (besides comments) */
    270 static int
    271 str_contains_data(char* str, char comment)
    272 {
    273         while (*str != '\0') {
    274                 if (*str == comment || *str == '\n')
    275                         return 0;
    276                 if (*str != ' ' && *str != '\t')
    277                         return 1;
    278                 str++;
    279         }
    280         return 0;
    281 }
    282 
    283 /** Get DNSKEY flags
    284  * rdata without rdatalen in front of it. */
    285 static int
    286 dnskey_flags(uint16_t t, uint8_t* rdata, size_t len)
    287 {
    288 	uint16_t f;
    289 	if(t != LDNS_RR_TYPE_DNSKEY)
    290 		return 0;
    291 	if(len < 2)
    292 		return 0;
    293 	memmove(&f, rdata, 2);
    294 	f = ntohs(f);
    295 	return (int)f;
    296 }
    297 
    298 /** Check if KSK DNSKEY.
    299  * pass rdata without rdatalen in front of it */
    300 static int
    301 rr_is_dnskey_sep(uint16_t t, uint8_t* rdata, size_t len)
    302 {
    303 	return (dnskey_flags(t, rdata, len)&DNSKEY_BIT_SEP);
    304 }
    305 
    306 /** Check if TA is KSK DNSKEY */
    307 static int
    308 ta_is_dnskey_sep(struct autr_ta* ta)
    309 {
    310 	return (dnskey_flags(
    311 		sldns_wirerr_get_type(ta->rr, ta->rr_len, ta->dname_len),
    312 		sldns_wirerr_get_rdata(ta->rr, ta->rr_len, ta->dname_len),
    313 		sldns_wirerr_get_rdatalen(ta->rr, ta->rr_len, ta->dname_len)
    314 		) & DNSKEY_BIT_SEP);
    315 }
    316 
    317 /** Check if REVOKED DNSKEY
    318  * pass rdata without rdatalen in front of it */
    319 static int
    320 rr_is_dnskey_revoked(uint16_t t, uint8_t* rdata, size_t len)
    321 {
    322 	return (dnskey_flags(t, rdata, len)&LDNS_KEY_REVOKE_KEY);
    323 }
    324 
    325 /** create ta */
    326 static struct autr_ta*
    327 autr_ta_create(uint8_t* rr, size_t rr_len, size_t dname_len)
    328 {
    329 	struct autr_ta* ta = (struct autr_ta*)calloc(1, sizeof(*ta));
    330 	if(!ta) {
    331 		free(rr);
    332 		return NULL;
    333 	}
    334 	ta->rr = rr;
    335 	ta->rr_len = rr_len;
    336 	ta->dname_len = dname_len;
    337 	return ta;
    338 }
    339 
    340 /** create tp */
    341 static struct trust_anchor*
    342 autr_tp_create(struct val_anchors* anchors, uint8_t* own, size_t own_len,
    343 	uint16_t dc)
    344 {
    345 	struct trust_anchor* tp = (struct trust_anchor*)calloc(1, sizeof(*tp));
    346 	if(!tp) return NULL;
    347 	tp->name = memdup(own, own_len);
    348 	if(!tp->name) {
    349 		free(tp);
    350 		return NULL;
    351 	}
    352 	tp->namelen = own_len;
    353 	tp->namelabs = dname_count_labels(tp->name);
    354 	tp->node.key = tp;
    355 	tp->dclass = dc;
    356 	tp->autr = (struct autr_point_data*)calloc(1, sizeof(*tp->autr));
    357 	if(!tp->autr) {
    358 		free(tp->name);
    359 		free(tp);
    360 		return NULL;
    361 	}
    362 	tp->autr->pnode.key = tp;
    363 
    364 	lock_basic_lock(&anchors->lock);
    365 	if(!rbtree_insert(anchors->tree, &tp->node)) {
    366 		char buf[LDNS_MAX_DOMAINLEN];
    367 		lock_basic_unlock(&anchors->lock);
    368 		dname_str(tp->name, buf);
    369 		log_err("trust anchor for '%s' presented twice", buf);
    370 		free(tp->name);
    371 		free(tp->autr);
    372 		free(tp);
    373 		return NULL;
    374 	}
    375 	if(!rbtree_insert(&anchors->autr->probe, &tp->autr->pnode)) {
    376 		char buf[LDNS_MAX_DOMAINLEN];
    377 		(void)rbtree_delete(anchors->tree, tp);
    378 		lock_basic_unlock(&anchors->lock);
    379 		dname_str(tp->name, buf);
    380 		log_err("trust anchor for '%s' in probetree twice", buf);
    381 		free(tp->name);
    382 		free(tp->autr);
    383 		free(tp);
    384 		return NULL;
    385 	}
    386 	lock_basic_init(&tp->lock);
    387 	lock_protect(&tp->lock, tp, sizeof(*tp));
    388 	lock_protect(&tp->lock, tp->autr, sizeof(*tp->autr));
    389 	lock_basic_unlock(&anchors->lock);
    390 	return tp;
    391 }
    392 
    393 /** delete assembled rrsets */
    394 static void
    395 autr_rrset_delete(struct ub_packed_rrset_key* r)
    396 {
    397 	if(r) {
    398 		free(r->rk.dname);
    399 		free(r->entry.data);
    400 		free(r);
    401 	}
    402 }
    403 
    404 /** delete autotrust key data */
    405 static void
    406 autr_ta_delete(struct autr_ta* ta)
    407 {
    408 	if(!ta) return;
    409 	free(ta->rr);
    410 	free(ta);
    411 }
    412 
    413 void autr_point_delete(struct trust_anchor* tp)
    414 {
    415 	if(!tp)
    416 		return;
    417 	lock_unprotect(&tp->lock, tp);
    418 	lock_unprotect(&tp->lock, tp->autr);
    419 	lock_basic_destroy(&tp->lock);
    420 	autr_rrset_delete(tp->ds_rrset);
    421 	autr_rrset_delete(tp->dnskey_rrset);
    422 	if(tp->autr) {
    423 		struct autr_ta* p = tp->autr->keys, *np;
    424 		while(p) {
    425 			np = p->next;
    426 			autr_ta_delete(p);
    427 			p = np;
    428 		}
    429 		free(tp->autr->file);
    430 		free(tp->autr);
    431 	}
    432 	free(tp->name);
    433 	free(tp);
    434 }
    435 
    436 /** find or add a new trust point for autotrust */
    437 static struct trust_anchor*
    438 find_add_tp(struct val_anchors* anchors, uint8_t* rr, size_t rr_len,
    439 	size_t dname_len)
    440 {
    441 	struct trust_anchor* tp;
    442 	tp = anchor_find(anchors, rr, dname_count_labels(rr), dname_len,
    443 		sldns_wirerr_get_class(rr, rr_len, dname_len));
    444 	if(tp) {
    445 		if(!tp->autr) {
    446 			log_err("anchor cannot be with and without autotrust");
    447 			lock_basic_unlock(&tp->lock);
    448 			return NULL;
    449 		}
    450 		return tp;
    451 	}
    452 	tp = autr_tp_create(anchors, rr, dname_len, sldns_wirerr_get_class(rr,
    453 		rr_len, dname_len));
    454 	if(!tp)
    455 		return NULL;
    456 	lock_basic_lock(&tp->lock);
    457 	return tp;
    458 }
    459 
    460 /** Add trust anchor from RR */
    461 static struct autr_ta*
    462 add_trustanchor_frm_rr(struct val_anchors* anchors, uint8_t* rr, size_t rr_len,
    463         size_t dname_len, struct trust_anchor** tp)
    464 {
    465 	struct autr_ta* ta = autr_ta_create(rr, rr_len, dname_len);
    466 	if(!ta)
    467 		return NULL;
    468 	*tp = find_add_tp(anchors, rr, rr_len, dname_len);
    469 	if(!*tp) {
    470 		autr_ta_delete(ta);
    471 		return NULL;
    472 	}
    473 	/* add ta to tp */
    474 	ta->next = (*tp)->autr->keys;
    475 	(*tp)->autr->keys = ta;
    476 	lock_basic_unlock(&(*tp)->lock);
    477 	return ta;
    478 }
    479 
    480 /**
    481  * Add new trust anchor from a string in file.
    482  * @param anchors: all anchors
    483  * @param str: string with anchor and comments, if any comments.
    484  * @param tp: trust point returned.
    485  * @param origin: what to use for @
    486  * @param origin_len: length of origin
    487  * @param prev: previous rr name
    488  * @param prev_len: length of prev
    489  * @param skip: if true, the result is NULL, but not an error, skip it.
    490  * @return new key in trust point.
    491  */
    492 static struct autr_ta*
    493 add_trustanchor_frm_str(struct val_anchors* anchors, char* str,
    494 	struct trust_anchor** tp, uint8_t* origin, size_t origin_len,
    495 	uint8_t** prev, size_t* prev_len, int* skip)
    496 {
    497 	uint8_t rr[LDNS_RR_BUF_SIZE];
    498 	size_t rr_len = sizeof(rr), dname_len;
    499 	uint8_t* drr;
    500 	int lstatus;
    501         if (!str_contains_data(str, ';')) {
    502 		*skip = 1;
    503                 return NULL; /* empty line */
    504 	}
    505 	if(0 != (lstatus = sldns_str2wire_rr_buf(str, rr, &rr_len, &dname_len,
    506 		0, origin, origin_len, *prev, *prev_len)))
    507 	{
    508 		log_err("ldns error while converting string to RR at%d: %s: %s",
    509 			LDNS_WIREPARSE_OFFSET(lstatus),
    510 			sldns_get_errorstr_parse(lstatus), str);
    511 		return NULL;
    512 	}
    513 	free(*prev);
    514 	*prev = memdup(rr, dname_len);
    515 	*prev_len = dname_len;
    516 	if(!*prev) {
    517 		log_err("malloc failure in add_trustanchor");
    518 		return NULL;
    519 	}
    520 	if(sldns_wirerr_get_type(rr, rr_len, dname_len)!=LDNS_RR_TYPE_DNSKEY &&
    521 		sldns_wirerr_get_type(rr, rr_len, dname_len)!=LDNS_RR_TYPE_DS) {
    522 		*skip = 1;
    523 		return NULL; /* only DS and DNSKEY allowed */
    524 	}
    525 	drr = memdup(rr, rr_len);
    526 	if(!drr) {
    527 		log_err("malloc failure in add trustanchor");
    528 		return NULL;
    529 	}
    530 	return add_trustanchor_frm_rr(anchors, drr, rr_len, dname_len, tp);
    531 }
    532 
    533 /**
    534  * Load single anchor
    535  * @param anchors: all points.
    536  * @param str: comments line
    537  * @param fname: filename
    538  * @param origin: the $ORIGIN.
    539  * @param origin_len: length of origin
    540  * @param prev: passed to ldns.
    541  * @param prev_len: length of prev
    542  * @param skip: if true, the result is NULL, but not an error, skip it.
    543  * @param header_seen: if an autotrust file header was seen.
    544  *	Without such a header it is a list of resource records.
    545  * @return false on failure, otherwise the tp read.
    546  */
    547 static struct trust_anchor*
    548 load_trustanchor(struct val_anchors* anchors, char* str, const char* fname,
    549 	uint8_t* origin, size_t origin_len, uint8_t** prev, size_t* prev_len,
    550 	int* skip, int header_seen)
    551 {
    552 	struct autr_ta* ta = NULL;
    553 	struct trust_anchor* tp = NULL;
    554 
    555 	ta = add_trustanchor_frm_str(anchors, str, &tp, origin, origin_len,
    556 		prev, prev_len, skip);
    557 	if(!ta)
    558 		return NULL;
    559 	lock_basic_lock(&tp->lock);
    560 	if(!parse_comments(str, ta, header_seen)) {
    561 		/* ta was already linked into the list of keys, unlink it */
    562 		log_assert(tp->autr->keys == ta);
    563 		tp->autr->keys = ta->next;
    564 		autr_ta_delete(ta);
    565 		lock_basic_unlock(&tp->lock);
    566 		return NULL;
    567 	}
    568 	if(!tp->autr->file) {
    569 		tp->autr->file = strdup(fname);
    570 		if(!tp->autr->file) {
    571 			lock_basic_unlock(&tp->lock);
    572 			log_err("malloc failure");
    573 			return NULL;
    574 		}
    575 	}
    576 	lock_basic_unlock(&tp->lock);
    577         return tp;
    578 }
    579 
    580 /** iterator for DSes from keylist. return true if a next element exists */
    581 static int
    582 assemble_iterate_ds(struct autr_ta** list, uint8_t** rr, size_t* rr_len,
    583 	size_t* dname_len)
    584 {
    585 	while(*list) {
    586 		if(sldns_wirerr_get_type((*list)->rr, (*list)->rr_len,
    587 			(*list)->dname_len) == LDNS_RR_TYPE_DS) {
    588 			*rr = (*list)->rr;
    589 			*rr_len = (*list)->rr_len;
    590 			*dname_len = (*list)->dname_len;
    591 			*list = (*list)->next;
    592 			return 1;
    593 		}
    594 		*list = (*list)->next;
    595 	}
    596 	return 0;
    597 }
    598 
    599 /** iterator for DNSKEYs from keylist. return true if a next element exists */
    600 static int
    601 assemble_iterate_dnskey(struct autr_ta** list, uint8_t** rr, size_t* rr_len,
    602 	size_t* dname_len)
    603 {
    604 	while(*list) {
    605 		if(sldns_wirerr_get_type((*list)->rr, (*list)->rr_len,
    606 		   (*list)->dname_len) != LDNS_RR_TYPE_DS &&
    607 			((*list)->s == AUTR_STATE_VALID ||
    608 			 (*list)->s == AUTR_STATE_MISSING)) {
    609 			*rr = (*list)->rr;
    610 			*rr_len = (*list)->rr_len;
    611 			*dname_len = (*list)->dname_len;
    612 			*list = (*list)->next;
    613 			return 1;
    614 		}
    615 		*list = (*list)->next;
    616 	}
    617 	return 0;
    618 }
    619 
    620 /** see if iterator-list has any elements in it, or it is empty */
    621 static int
    622 assemble_iterate_hasfirst(int iter(struct autr_ta**, uint8_t**, size_t*,
    623 	size_t*), struct autr_ta* list)
    624 {
    625 	uint8_t* rr = NULL;
    626 	size_t rr_len = 0, dname_len = 0;
    627 	return iter(&list, &rr, &rr_len, &dname_len);
    628 }
    629 
    630 /** number of elements in iterator list */
    631 static size_t
    632 assemble_iterate_count(int iter(struct autr_ta**, uint8_t**, size_t*,
    633 	size_t*), struct autr_ta* list)
    634 {
    635 	uint8_t* rr = NULL;
    636 	size_t i = 0, rr_len = 0, dname_len = 0;
    637 	while(iter(&list, &rr, &rr_len, &dname_len)) {
    638 		i++;
    639 	}
    640 	return i;
    641 }
    642 
    643 /**
    644  * Create a ub_packed_rrset_key allocated on the heap.
    645  * It therefore does not have the correct ID value, and cannot be used
    646  * inside the cache.  It can be used in storage outside of the cache.
    647  * Keys for the cache have to be obtained from alloc.h .
    648  * @param iter: iterator over the elements in the list.  It filters elements.
    649  * @param list: the list.
    650  * @return key allocated or NULL on failure.
    651  */
    652 static struct ub_packed_rrset_key*
    653 ub_packed_rrset_heap_key(int iter(struct autr_ta**, uint8_t**, size_t*,
    654 	size_t*), struct autr_ta* list)
    655 {
    656 	uint8_t* rr = NULL;
    657 	size_t rr_len = 0, dname_len = 0;
    658 	struct ub_packed_rrset_key* k;
    659 	if(!iter(&list, &rr, &rr_len, &dname_len))
    660 		return NULL;
    661 	k = (struct ub_packed_rrset_key*)calloc(1, sizeof(*k));
    662 	if(!k)
    663 		return NULL;
    664 	k->rk.type = htons(sldns_wirerr_get_type(rr, rr_len, dname_len));
    665 	k->rk.rrset_class = htons(sldns_wirerr_get_class(rr, rr_len, dname_len));
    666 	k->rk.dname_len = dname_len;
    667 	k->rk.dname = memdup(rr, dname_len);
    668 	if(!k->rk.dname) {
    669 		free(k);
    670 		return NULL;
    671 	}
    672 	return k;
    673 }
    674 
    675 /**
    676  * Create packed_rrset data on the heap.
    677  * @param iter: iterator over the elements in the list.  It filters elements.
    678  * @param list: the list.
    679  * @return data allocated or NULL on failure.
    680  */
    681 static struct packed_rrset_data*
    682 packed_rrset_heap_data(int iter(struct autr_ta**, uint8_t**, size_t*,
    683 	size_t*), struct autr_ta* list)
    684 {
    685 	uint8_t* rr = NULL;
    686 	size_t rr_len = 0, dname_len = 0;
    687 	struct packed_rrset_data* data;
    688 	size_t count=0, rrsig_count=0, len=0, i, total;
    689 	uint8_t* nextrdata;
    690 	struct autr_ta* list_i;
    691 	time_t ttl = 0;
    692 
    693 	list_i = list;
    694 	while(iter(&list_i, &rr, &rr_len, &dname_len)) {
    695 		if(sldns_wirerr_get_type(rr, rr_len, dname_len) ==
    696 			LDNS_RR_TYPE_RRSIG)
    697 			rrsig_count++;
    698 		else	count++;
    699 		/* sizeof the rdlength + rdatalen */
    700 		len += 2 + sldns_wirerr_get_rdatalen(rr, rr_len, dname_len);
    701 		ttl = (time_t)sldns_wirerr_get_ttl(rr, rr_len, dname_len);
    702 	}
    703 	if(count == 0 && rrsig_count == 0)
    704 		return NULL;
    705 
    706 	/* allocate */
    707 	total = count + rrsig_count;
    708 	len += sizeof(*data) + total*(sizeof(size_t) + sizeof(time_t) +
    709 		sizeof(uint8_t*));
    710 	data = (struct packed_rrset_data*)calloc(1, len);
    711 	if(!data)
    712 		return NULL;
    713 
    714 	/* fill it */
    715 	data->ttl = ttl;
    716 	data->count = count;
    717 	data->rrsig_count = rrsig_count;
    718 	data->rr_len = (size_t*)((uint8_t*)data +
    719 		sizeof(struct packed_rrset_data));
    720 	data->rr_data = (uint8_t**)&(data->rr_len[total]);
    721 	data->rr_ttl = (time_t*)&(data->rr_data[total]);
    722 	nextrdata = (uint8_t*)&(data->rr_ttl[total]);
    723 
    724 	/* fill out len, ttl, fields */
    725 	list_i = list;
    726 	i = 0;
    727 	while(iter(&list_i, &rr, &rr_len, &dname_len)) {
    728 		data->rr_ttl[i] = (time_t)sldns_wirerr_get_ttl(rr, rr_len,
    729 			dname_len);
    730 		if(data->rr_ttl[i] < data->ttl)
    731 			data->ttl = data->rr_ttl[i];
    732 		data->rr_len[i] = 2 /* the rdlength */ +
    733 			sldns_wirerr_get_rdatalen(rr, rr_len, dname_len);
    734 		i++;
    735 	}
    736 
    737 	/* fixup rest of ptrs */
    738 	for(i=0; i<total; i++) {
    739 		data->rr_data[i] = nextrdata;
    740 		nextrdata += data->rr_len[i];
    741 	}
    742 
    743 	/* copy data in there */
    744 	list_i = list;
    745 	i = 0;
    746 	while(iter(&list_i, &rr, &rr_len, &dname_len)) {
    747 		log_assert(data->rr_data[i]);
    748 		memmove(data->rr_data[i],
    749 			sldns_wirerr_get_rdatawl(rr, rr_len, dname_len),
    750 			data->rr_len[i]);
    751 		i++;
    752 	}
    753 
    754 	if(data->rrsig_count && data->count == 0) {
    755 		data->count = data->rrsig_count; /* rrset type is RRSIG */
    756 		data->rrsig_count = 0;
    757 	}
    758 	return data;
    759 }
    760 
    761 /**
    762  * Assemble the trust anchors into DS and DNSKEY packed rrsets.
    763  * Uses only VALID and MISSING DNSKEYs.
    764  * Read the sldns_rrs and builds packed rrsets
    765  * @param tp: the trust point. Must be locked.
    766  * @return false on malloc failure.
    767  */
    768 static int
    769 autr_assemble(struct trust_anchor* tp)
    770 {
    771 	struct ub_packed_rrset_key* ubds=NULL, *ubdnskey=NULL;
    772 
    773 	/* make packed rrset keys - malloced with no ID number, they
    774 	 * are not in the cache */
    775 	/* make packed rrset data (if there is a key) */
    776 	if(assemble_iterate_hasfirst(assemble_iterate_ds, tp->autr->keys)) {
    777 		ubds = ub_packed_rrset_heap_key(
    778 			assemble_iterate_ds, tp->autr->keys);
    779 		if(!ubds)
    780 			goto error_cleanup;
    781 		ubds->entry.data = packed_rrset_heap_data(
    782 			assemble_iterate_ds, tp->autr->keys);
    783 		if(!ubds->entry.data)
    784 			goto error_cleanup;
    785 	}
    786 
    787 	/* make packed DNSKEY data */
    788 	if(assemble_iterate_hasfirst(assemble_iterate_dnskey, tp->autr->keys)) {
    789 		ubdnskey = ub_packed_rrset_heap_key(
    790 			assemble_iterate_dnskey, tp->autr->keys);
    791 		if(!ubdnskey)
    792 			goto error_cleanup;
    793 		ubdnskey->entry.data = packed_rrset_heap_data(
    794 			assemble_iterate_dnskey, tp->autr->keys);
    795 		if(!ubdnskey->entry.data) {
    796 		error_cleanup:
    797 			autr_rrset_delete(ubds);
    798 			autr_rrset_delete(ubdnskey);
    799 			return 0;
    800 		}
    801 	}
    802 
    803 	/* we have prepared the new keys so nothing can go wrong any more.
    804 	 * And we are sure we cannot be left without trustanchor after
    805 	 * any errors. Put in the new keys and remove old ones. */
    806 
    807 	/* free the old data */
    808 	autr_rrset_delete(tp->ds_rrset);
    809 	autr_rrset_delete(tp->dnskey_rrset);
    810 
    811 	/* assign the data to replace the old */
    812 	tp->ds_rrset = ubds;
    813 	tp->dnskey_rrset = ubdnskey;
    814 	tp->numDS = assemble_iterate_count(assemble_iterate_ds,
    815 		tp->autr->keys);
    816 	tp->numDNSKEY = assemble_iterate_count(assemble_iterate_dnskey,
    817 		tp->autr->keys);
    818 	return 1;
    819 }
    820 
    821 /** parse integer */
    822 static unsigned int
    823 parse_int(char* line, int* ret)
    824 {
    825 	char *e;
    826 	unsigned int x = (unsigned int)strtol(line, &e, 10);
    827 	if(line == e) {
    828 		*ret = -1; /* parse error */
    829 		return 0;
    830 	}
    831 	*ret = 1; /* matched */
    832 	return x;
    833 }
    834 
    835 /** parse id sequence for anchor */
    836 static struct trust_anchor*
    837 parse_id(struct val_anchors* anchors, char* line)
    838 {
    839 	struct trust_anchor *tp;
    840 	int r;
    841 	uint16_t dclass;
    842 	uint8_t* dname;
    843 	size_t dname_len;
    844 	/* read the owner name */
    845 	char* next = strchr(line, ' ');
    846 	if(!next)
    847 		return NULL;
    848 	next[0] = 0;
    849 	dname = sldns_str2wire_dname(line, &dname_len);
    850 	if(!dname)
    851 		return NULL;
    852 
    853 	/* read the class */
    854 	dclass = parse_int(next+1, &r);
    855 	if(r == -1) {
    856 		free(dname);
    857 		return NULL;
    858 	}
    859 
    860 	/* find the trust point */
    861 	tp = autr_tp_create(anchors, dname, dname_len, dclass);
    862 	free(dname);
    863 	return tp;
    864 }
    865 
    866 /**
    867  * Parse variable from trustanchor header
    868  * @param line: to parse
    869  * @param anchors: the anchor is added to this, if "id:" is seen.
    870  * @param anchor: the anchor as result value or previously returned anchor
    871  * 	value to read the variable lines into.
    872  * @param header_seen: if a header ';;id: example.com.' was seen.
    873  * @param nm: file name.
    874  * @return: 0 no match, -1 failed syntax error, +1 success line read.
    875  * 	+2 revoked trust anchor file.
    876  */
    877 static int
    878 parse_var_line(char* line, struct val_anchors* anchors,
    879 	struct trust_anchor** anchor, int* header_seen, const char* nm)
    880 {
    881 	struct trust_anchor* tp = *anchor;
    882 	int r = 0;
    883 	if(strncmp(line, ";;id: ", 6) == 0) {
    884 		*header_seen = 1;
    885 		*anchor = parse_id(anchors, line+6);
    886 		if(!*anchor) return -1;
    887 		lock_basic_lock(&(*anchor)->lock);
    888 		if(*anchor && !(*anchor)->autr->file) {
    889 			(*anchor)->autr->file = strdup(nm);
    890 			if(!(*anchor)->autr->file) {
    891 				lock_basic_unlock(&(*anchor)->lock);
    892 				log_err("malloc failure");
    893 				return -1;
    894 			}
    895 		}
    896 		lock_basic_unlock(&(*anchor)->lock);
    897 		if(*anchor) return 1;
    898 	} else if(strncmp(line, ";;REVOKED", 9) == 0) {
    899 		if(tp) {
    900 			log_err("REVOKED statement must be at start of file");
    901 			return -1;
    902 		}
    903 		return 2;
    904 	} else if(strncmp(line, ";;last_queried: ", 16) == 0) {
    905 		if(!tp) return -1;
    906 		lock_basic_lock(&tp->lock);
    907 		tp->autr->last_queried = (time_t)parse_int(line+16, &r);
    908 		lock_basic_unlock(&tp->lock);
    909 	} else if(strncmp(line, ";;last_success: ", 16) == 0) {
    910 		if(!tp) return -1;
    911 		lock_basic_lock(&tp->lock);
    912 		tp->autr->last_success = (time_t)parse_int(line+16, &r);
    913 		lock_basic_unlock(&tp->lock);
    914 	} else if(strncmp(line, ";;next_probe_time: ", 19) == 0) {
    915 		if(!tp) return -1;
    916 		lock_basic_lock(&anchors->lock);
    917 		lock_basic_lock(&tp->lock);
    918 		(void)rbtree_delete(&anchors->autr->probe, tp);
    919 		tp->autr->next_probe_time = (time_t)parse_int(line+19, &r);
    920 		(void)rbtree_insert(&anchors->autr->probe, &tp->autr->pnode);
    921 		lock_basic_unlock(&tp->lock);
    922 		lock_basic_unlock(&anchors->lock);
    923 	} else if(strncmp(line, ";;query_failed: ", 16) == 0) {
    924 		if(!tp) return -1;
    925 		lock_basic_lock(&tp->lock);
    926 		tp->autr->query_failed = (uint8_t)parse_int(line+16, &r);
    927 		lock_basic_unlock(&tp->lock);
    928 	} else if(strncmp(line, ";;query_interval: ", 18) == 0) {
    929 		if(!tp) return -1;
    930 		lock_basic_lock(&tp->lock);
    931 		tp->autr->query_interval = (time_t)parse_int(line+18, &r);
    932 		lock_basic_unlock(&tp->lock);
    933 	} else if(strncmp(line, ";;retry_time: ", 14) == 0) {
    934 		if(!tp) return -1;
    935 		lock_basic_lock(&tp->lock);
    936 		tp->autr->retry_time = (time_t)parse_int(line+14, &r);
    937 		lock_basic_unlock(&tp->lock);
    938 	}
    939 	return r;
    940 }
    941 
    942 /** handle origin lines */
    943 static int
    944 handle_origin(char* line, uint8_t** origin, size_t* origin_len)
    945 {
    946 	size_t len = 0;
    947 	while(isspace((unsigned char)*line))
    948 		line++;
    949 	if(strncmp(line, "$ORIGIN", 7) != 0)
    950 		return 0;
    951 	free(*origin);
    952 	line += 7;
    953 	while(isspace((unsigned char)*line))
    954 		line++;
    955 	*origin = sldns_str2wire_dname(line, &len);
    956 	*origin_len = len;
    957 	if(!*origin)
    958 		log_warn("malloc failure or parse error in $ORIGIN");
    959 	return 1;
    960 }
    961 
    962 /** Read one line and put multiline RRs onto one line string */
    963 static int
    964 read_multiline(char* buf, size_t len, FILE* in, int* linenr)
    965 {
    966 	char* pos = buf;
    967 	size_t left = len;
    968 	int depth = 0;
    969 	buf[len-1] = 0;
    970 	while(left > 0 && fgets(pos, (int)left, in) != NULL) {
    971 		size_t i, poslen = strlen(pos);
    972 		(*linenr)++;
    973 
    974 		/* check what the new depth is after the line */
    975 		/* this routine cannot handle braces inside quotes,
    976 		   say for TXT records, but this routine only has to read keys */
    977 		for(i=0; i<poslen; i++) {
    978 			if(pos[i] == '(') {
    979 				depth++;
    980 			} else if(pos[i] == ')') {
    981 				if(depth == 0) {
    982 					log_err("mismatch: too many ')'");
    983 					return -1;
    984 				}
    985 				depth--;
    986 			} else if(pos[i] == ';') {
    987 				break;
    988 			}
    989 		}
    990 
    991 		/* normal oneline or last line: keeps newline and comments */
    992 		if(depth == 0) {
    993 			return 1;
    994 		}
    995 
    996 		/* more lines expected, snip off comments and newline */
    997 		if(poslen>0)
    998 			pos[poslen-1] = 0; /* strip newline */
    999 		if(strchr(pos, ';'))
   1000 			strchr(pos, ';')[0] = 0; /* strip comments */
   1001 
   1002 		/* move to paste other lines behind this one */
   1003 		poslen = strlen(pos);
   1004 		pos += poslen;
   1005 		left -= poslen;
   1006 		/* the newline is changed into a space */
   1007 		if(left <= 2 /* space and eos */) {
   1008 			log_err("line too long");
   1009 			return -1;
   1010 		}
   1011 		pos[0] = ' ';
   1012 		pos[1] = 0;
   1013 		pos += 1;
   1014 		left -= 1;
   1015 	}
   1016 	if(depth != 0) {
   1017 		log_err("mismatch: too many '('");
   1018 		return -1;
   1019 	}
   1020 	if(pos != buf)
   1021 		return 1;
   1022 	return 0;
   1023 }
   1024 
   1025 int autr_read_file(struct val_anchors* anchors, const char* nm)
   1026 {
   1027         /* the file descriptor */
   1028         FILE* fd;
   1029         /* keep track of line numbers */
   1030         int line_nr = 0;
   1031         /* single line, enough space for large DNSKEY, 64K, in hex and dname */
   1032         char line[10240+65536*2];
   1033 	/* trust point being read */
   1034 	struct trust_anchor *tp = NULL, *tp2;
   1035 	int r;
   1036 	/* for $ORIGIN parsing */
   1037 	uint8_t *origin=NULL, *prev=NULL;
   1038 	size_t origin_len=0, prev_len=0;
   1039 	int header_seen = 0;
   1040 
   1041         if (!(fd = fopen(nm, "r"))) {
   1042                 log_err("unable to open %s for reading: %s",
   1043 			nm, strerror(errno));
   1044                 return 0;
   1045         }
   1046         verbose(VERB_ALGO, "reading autotrust anchor file %s", nm);
   1047         while ( (r=read_multiline(line, sizeof(line), fd, &line_nr)) != 0) {
   1048 		if(r == -1 || (r = parse_var_line(line, anchors, &tp, &header_seen, nm)) == -1) {
   1049 			log_err("could not parse auto-trust-anchor-file "
   1050 				"%s line %d", nm, line_nr);
   1051 			fclose(fd);
   1052 			free(origin);
   1053 			free(prev);
   1054 			return 0;
   1055 		} else if(r == 1) {
   1056 			continue;
   1057 		} else if(r == 2) {
   1058 			log_warn("trust anchor %s has been revoked", nm);
   1059 			fclose(fd);
   1060 			free(origin);
   1061 			free(prev);
   1062 			return 1;
   1063 		}
   1064         	if (!str_contains_data(line, ';'))
   1065                 	continue; /* empty lines allowed */
   1066  		if(handle_origin(line, &origin, &origin_len))
   1067 			continue;
   1068 		r = 0;
   1069                 if(!(tp2=load_trustanchor(anchors, line, nm, origin,
   1070 			origin_len, &prev, &prev_len, &r, header_seen))) {
   1071 			if(!r) log_err("failed to load trust anchor from %s "
   1072 				"at line %i, skipping", nm, line_nr);
   1073                         /* try to do the rest */
   1074 			continue;
   1075                 }
   1076 		if(tp && tp != tp2) {
   1077 			log_err("file %s has mismatching data inside: "
   1078 				"the file may only contain keys for one name, "
   1079 				"remove keys for other domain names", nm);
   1080         		fclose(fd);
   1081 			free(origin);
   1082 			free(prev);
   1083 			return 0;
   1084 		}
   1085 		tp = tp2;
   1086         }
   1087         fclose(fd);
   1088 	free(origin);
   1089 	free(prev);
   1090 	if(!tp) {
   1091 		log_err("failed to read %s", nm);
   1092 		return 0;
   1093 	}
   1094 
   1095 	/* now assemble the data into DNSKEY and DS packed rrsets */
   1096 	lock_basic_lock(&tp->lock);
   1097 	if(!autr_assemble(tp)) {
   1098 		lock_basic_unlock(&tp->lock);
   1099 		log_err("malloc failure assembling %s", nm);
   1100 		return 0;
   1101 	}
   1102 	lock_basic_unlock(&tp->lock);
   1103 	return 1;
   1104 }
   1105 
   1106 /** string for a trustanchor state */
   1107 static const char*
   1108 trustanchor_state2str(autr_state_type s)
   1109 {
   1110         switch (s) {
   1111                 case AUTR_STATE_START:       return "  START  ";
   1112                 case AUTR_STATE_ADDPEND:     return " ADDPEND ";
   1113                 case AUTR_STATE_VALID:       return "  VALID  ";
   1114                 case AUTR_STATE_MISSING:     return " MISSING ";
   1115                 case AUTR_STATE_REVOKED:     return " REVOKED ";
   1116                 case AUTR_STATE_REMOVED:     return " REMOVED ";
   1117         }
   1118         return " UNKNOWN ";
   1119 }
   1120 
   1121 /** ctime r for autotrust */
   1122 static char* autr_ctime_r(time_t* t, char* s)
   1123 {
   1124 	ctime_r(t, s);
   1125 #ifdef USE_WINSOCK
   1126 	if(strlen(s) > 10 && s[7]==' ' && s[8]=='0')
   1127 		s[8]=' '; /* fix error in windows ctime */
   1128 #endif
   1129 	return s;
   1130 }
   1131 
   1132 /** print ID to file */
   1133 static int
   1134 print_id(FILE* out, char* fname, uint8_t* nm, size_t nmlen, uint16_t dclass)
   1135 {
   1136 	char* s = sldns_wire2str_dname(nm, nmlen);
   1137 	if(!s) {
   1138 		log_err("malloc failure in write to %s", fname);
   1139 		return 0;
   1140 	}
   1141 	if(fprintf(out, ";;id: %s %d\n", s, (int)dclass) < 0) {
   1142 		log_err("could not write to %s: %s", fname, strerror(errno));
   1143 		free(s);
   1144 		return 0;
   1145 	}
   1146 	free(s);
   1147 	return 1;
   1148 }
   1149 
   1150 static int
   1151 autr_write_contents(FILE* out, char* fn, struct trust_anchor* tp)
   1152 {
   1153 	char tmi[32];
   1154 	struct autr_ta* ta;
   1155 	char* str;
   1156 
   1157 	/* write pretty header */
   1158 	if(fprintf(out, "; autotrust trust anchor file\n") < 0) {
   1159 		log_err("could not write to %s: %s", fn, strerror(errno));
   1160 		return 0;
   1161 	}
   1162 	if(tp->autr->revoked) {
   1163 		if(fprintf(out, ";;REVOKED\n") < 0 ||
   1164 		   fprintf(out, "; The zone has all keys revoked, and is\n"
   1165 			"; considered as if it has no trust anchors.\n"
   1166 			"; the remainder of the file is the last probe.\n"
   1167 			"; to restart the trust anchor, overwrite this file.\n"
   1168 			"; with one containing valid DNSKEYs or DSes.\n") < 0) {
   1169 		   log_err("could not write to %s: %s", fn, strerror(errno));
   1170 		   return 0;
   1171 		}
   1172 	}
   1173 	if(!print_id(out, fn, tp->name, tp->namelen, tp->dclass)) {
   1174 		return 0;
   1175 	}
   1176 	if(fprintf(out, ";;last_queried: %u ;;%s",
   1177 		(unsigned int)tp->autr->last_queried,
   1178 		autr_ctime_r(&(tp->autr->last_queried), tmi)) < 0 ||
   1179 	   fprintf(out, ";;last_success: %u ;;%s",
   1180 		(unsigned int)tp->autr->last_success,
   1181 		autr_ctime_r(&(tp->autr->last_success), tmi)) < 0 ||
   1182 	   fprintf(out, ";;next_probe_time: %u ;;%s",
   1183 		(unsigned int)tp->autr->next_probe_time,
   1184 		autr_ctime_r(&(tp->autr->next_probe_time), tmi)) < 0 ||
   1185 	   fprintf(out, ";;query_failed: %d\n", (int)tp->autr->query_failed)<0
   1186 	   || fprintf(out, ";;query_interval: %d\n",
   1187 	   (int)tp->autr->query_interval) < 0 ||
   1188 	   fprintf(out, ";;retry_time: %d\n", (int)tp->autr->retry_time) < 0) {
   1189 		log_err("could not write to %s: %s", fn, strerror(errno));
   1190 		return 0;
   1191 	}
   1192 
   1193 	/* write anchors */
   1194 	for(ta=tp->autr->keys; ta; ta=ta->next) {
   1195 		/* by default do not store START and REMOVED keys */
   1196 		if(ta->s == AUTR_STATE_START)
   1197 			continue;
   1198 		if(ta->s == AUTR_STATE_REMOVED)
   1199 			continue;
   1200 		/* only store keys */
   1201 		if(sldns_wirerr_get_type(ta->rr, ta->rr_len, ta->dname_len)
   1202 			!= LDNS_RR_TYPE_DNSKEY)
   1203 			continue;
   1204 		str = sldns_wire2str_rr(ta->rr, ta->rr_len);
   1205 		if(!str || !str[0]) {
   1206 			free(str);
   1207 			log_err("malloc failure writing %s", fn);
   1208 			return 0;
   1209 		}
   1210 		str[strlen(str)-1] = 0; /* remove newline */
   1211 		if(fprintf(out, "%s ;;state=%d [%s] ;;count=%d "
   1212 			";;lastchange=%u ;;%s", str, (int)ta->s,
   1213 			trustanchor_state2str(ta->s), (int)ta->pending_count,
   1214 			(unsigned int)ta->last_change,
   1215 			autr_ctime_r(&(ta->last_change), tmi)) < 0) {
   1216 		   log_err("could not write to %s: %s", fn, strerror(errno));
   1217 		   free(str);
   1218 		   return 0;
   1219 		}
   1220 		free(str);
   1221 	}
   1222 	return 1;
   1223 }
   1224 
   1225 void autr_write_file(struct module_env* env, struct trust_anchor* tp)
   1226 {
   1227 	FILE* out;
   1228 	char* fname = tp->autr->file;
   1229 #ifndef S_SPLINT_S
   1230 	long long llvalue;
   1231 #endif
   1232 	char tempf[2048];
   1233 	log_assert(tp->autr);
   1234 	if(!fname) {
   1235 		log_err("autotrust: trust point has no backing file, "
   1236 			"skipping write");
   1237 		return;
   1238 	}
   1239 	if(!env) {
   1240 		log_err("autr_write_file: Module environment is NULL.");
   1241 		return;
   1242 	}
   1243 	/* unique name with pid number, thread number, and struct pointer
   1244 	 * (the pointer uniquifies for multiple libunbound contexts) */
   1245 #ifndef S_SPLINT_S
   1246 #if defined(SIZE_MAX) && defined(UINT32_MAX) && (UINT32_MAX == SIZE_MAX || INT32_MAX == SIZE_MAX)
   1247 	/* avoid warning about upcast on 32bit systems */
   1248 	llvalue = (unsigned long)tp;
   1249 #else
   1250 	llvalue = (unsigned long long)tp;
   1251 #endif
   1252 	snprintf(tempf, sizeof(tempf), "%s.%d-%d-" ARG_LL "x", fname, (int)getpid(),
   1253 		env->worker?*(int*)env->worker:0, llvalue);
   1254 #endif /* S_SPLINT_S */
   1255 	verbose(VERB_ALGO, "autotrust: write to disk: %s", tempf);
   1256 	out = fopen(tempf, "w");
   1257 	if(!out) {
   1258 		fatal_exit("could not open autotrust file for writing, %s: %s",
   1259 			tempf, strerror(errno));
   1260 		return;
   1261 	}
   1262 	if(!autr_write_contents(out, tempf, tp)) {
   1263 		/* failed to write contents (completely) */
   1264 		fclose(out);
   1265 		unlink(tempf);
   1266 		fatal_exit("could not completely write: %s", fname);
   1267 		return;
   1268 	}
   1269 	if(fflush(out) != 0)
   1270 		log_err("could not fflush(%s): %s", fname, strerror(errno));
   1271 #ifdef HAVE_FSYNC
   1272 	if(fsync(fileno(out)) != 0)
   1273 		log_err("could not fsync(%s): %s", fname, strerror(errno));
   1274 #else
   1275 	FlushFileBuffers((HANDLE)_get_osfhandle(_fileno(out)));
   1276 #endif
   1277 	if(fclose(out) != 0) {
   1278 		fatal_exit("could not complete write: %s: %s",
   1279 			fname, strerror(errno));
   1280 		unlink(tempf);
   1281 		return;
   1282 	}
   1283 	/* success; overwrite actual file */
   1284 	verbose(VERB_ALGO, "autotrust: replaced %s", fname);
   1285 #ifdef UB_ON_WINDOWS
   1286 	(void)unlink(fname); /* windows does not replace file with rename() */
   1287 #endif
   1288 	if(rename(tempf, fname) < 0) {
   1289 		fatal_exit("rename(%s to %s): %s", tempf, fname, strerror(errno));
   1290 	}
   1291 }
   1292 
   1293 /**
   1294  * Verify if dnskey works for trust point
   1295  * @param env: environment (with time) for verification
   1296  * @param ve: validator environment (with options) for verification.
   1297  * @param tp: trust point to verify with
   1298  * @param rrset: DNSKEY rrset to verify.
   1299  * @param qstate: qstate with region.
   1300  * @param vq: validator query state.
   1301  * @return false on failure, true if verification successful.
   1302  */
   1303 static int
   1304 verify_dnskey(struct module_env* env, struct val_env* ve,
   1305         struct trust_anchor* tp, struct ub_packed_rrset_key* rrset,
   1306 	struct module_qstate* qstate, struct val_qstate* vq)
   1307 {
   1308 	char reasonbuf[256];
   1309 	char* reason = NULL;
   1310 	uint8_t sigalg[ALGO_NEEDS_MAX+1];
   1311 	int downprot = env->cfg->harden_algo_downgrade;
   1312 	enum sec_status sec = val_verify_DNSKEY_with_TA(env, ve, rrset,
   1313 		tp->ds_rrset, tp->dnskey_rrset, downprot?sigalg:NULL, &reason,
   1314 		NULL, qstate, vq, reasonbuf, sizeof(reasonbuf));
   1315 	/* sigalg is ignored, it returns algorithms signalled to exist, but
   1316 	 * in 5011 there are no other rrsets to check.  if downprot is
   1317 	 * enabled, then it checks that the DNSKEY is signed with all
   1318 	 * algorithms available in the trust store. */
   1319 	verbose(VERB_ALGO, "autotrust: validate DNSKEY with anchor: %s",
   1320 		sec_status_to_string(sec));
   1321 	return sec == sec_status_secure;
   1322 }
   1323 
   1324 static int32_t
   1325 rrsig_get_expiry(uint8_t* d, size_t len)
   1326 {
   1327 	/* rrsig: 2(rdlen), 2(type) 1(alg) 1(v) 4(origttl), then 4(expi), (4)incep) */
   1328 	if(len < 2+8+4)
   1329 		return 0;
   1330 	return sldns_read_uint32(d+2+8);
   1331 }
   1332 
   1333 /** Find minimum expiration interval from signatures */
   1334 static time_t
   1335 min_expiry(struct module_env* env, struct packed_rrset_data* dd)
   1336 {
   1337 	size_t i;
   1338 	int32_t t, r = 15 * 24 * 3600; /* 15 days max */
   1339 	for(i=dd->count; i<dd->count+dd->rrsig_count; i++) {
   1340 		t = rrsig_get_expiry(dd->rr_data[i], dd->rr_len[i]);
   1341 		if((int32_t)t - (int32_t)*env->now > 0) {
   1342 			t -= (int32_t)*env->now;
   1343 			if(t < r)
   1344 				r = t;
   1345 		}
   1346 	}
   1347 	return (time_t)r;
   1348 }
   1349 
   1350 /** Is rr self-signed revoked key */
   1351 static int
   1352 rr_is_selfsigned_revoked(struct module_env* env, struct val_env* ve,
   1353 	struct ub_packed_rrset_key* dnskey_rrset, size_t i,
   1354 	struct module_qstate* qstate, struct val_qstate* vq)
   1355 {
   1356 	enum sec_status sec;
   1357 	char* reason = NULL;
   1358 	size_t num_tagmatches = 0;
   1359 	verbose(VERB_ALGO, "seen REVOKE flag, check self-signed, rr %d",
   1360 		(int)i);
   1361 	/* no algorithm downgrade protection necessary, if it is selfsigned
   1362 	 * revoked it can be removed. */
   1363 	sec = dnskey_verify_rrset(env, ve, dnskey_rrset, dnskey_rrset, i,
   1364 		&reason, NULL, LDNS_SECTION_ANSWER, qstate, vq,
   1365 		&num_tagmatches);
   1366 	return (sec == sec_status_secure);
   1367 }
   1368 
   1369 /** Set fetched value */
   1370 static void
   1371 seen_trustanchor(struct autr_ta* ta, uint8_t seen)
   1372 {
   1373 	ta->fetched = seen;
   1374 	if(ta->pending_count < 250) /* no numerical overflow, please */
   1375 		ta->pending_count++;
   1376 }
   1377 
   1378 /** set revoked value */
   1379 static void
   1380 seen_revoked_trustanchor(struct autr_ta* ta, uint8_t revoked)
   1381 {
   1382 	ta->revoked = revoked;
   1383 }
   1384 
   1385 /** revoke a trust anchor */
   1386 static void
   1387 revoke_dnskey(struct autr_ta* ta, int off)
   1388 {
   1389 	uint16_t flags;
   1390 	uint8_t* data;
   1391 	if(sldns_wirerr_get_type(ta->rr, ta->rr_len, ta->dname_len) !=
   1392 		LDNS_RR_TYPE_DNSKEY)
   1393 		return;
   1394 	if(sldns_wirerr_get_rdatalen(ta->rr, ta->rr_len, ta->dname_len) < 2)
   1395 		return;
   1396 	data = sldns_wirerr_get_rdata(ta->rr, ta->rr_len, ta->dname_len);
   1397 	flags = sldns_read_uint16(data);
   1398 	if (off && (flags&LDNS_KEY_REVOKE_KEY))
   1399 		flags ^= LDNS_KEY_REVOKE_KEY; /* flip */
   1400 	else
   1401 		flags |= LDNS_KEY_REVOKE_KEY;
   1402 	sldns_write_uint16(data, flags);
   1403 }
   1404 
   1405 /** Compare two RRs skipping the REVOKED bit. Pass rdata(no len) */
   1406 static int
   1407 dnskey_compare_skip_revbit(uint8_t* a, size_t a_len, uint8_t* b, size_t b_len)
   1408 {
   1409 	size_t i;
   1410 	if(a_len != b_len)
   1411 		return -1;
   1412 	/* compare RRs RDATA byte for byte. */
   1413 	for(i = 0; i < a_len; i++)
   1414 	{
   1415 		uint8_t rdf1, rdf2;
   1416 		rdf1 = a[i];
   1417 		rdf2 = b[i];
   1418 		if(i==1) {
   1419 			/* this is the second part of the flags field */
   1420 			rdf1 |= LDNS_KEY_REVOKE_KEY;
   1421 			rdf2 |= LDNS_KEY_REVOKE_KEY;
   1422 		}
   1423 		if (rdf1 < rdf2)	return -1;
   1424 		else if (rdf1 > rdf2)	return 1;
   1425         }
   1426 	return 0;
   1427 }
   1428 
   1429 
   1430 /** compare trust anchor with rdata, 0 if equal. Pass rdata(no len) */
   1431 static int
   1432 ta_compare(struct autr_ta* a, uint16_t t, uint8_t* b, size_t b_len)
   1433 {
   1434 	if(!a) return -1;
   1435 	else if(!b) return -1;
   1436 	else if(sldns_wirerr_get_type(a->rr, a->rr_len, a->dname_len) != t)
   1437 		return (int)sldns_wirerr_get_type(a->rr, a->rr_len,
   1438 			a->dname_len) - (int)t;
   1439 	else if(t == LDNS_RR_TYPE_DNSKEY) {
   1440 		return dnskey_compare_skip_revbit(
   1441 			sldns_wirerr_get_rdata(a->rr, a->rr_len, a->dname_len),
   1442 			sldns_wirerr_get_rdatalen(a->rr, a->rr_len,
   1443 			a->dname_len), b, b_len);
   1444 	}
   1445 	else if(t == LDNS_RR_TYPE_DS) {
   1446 		if(sldns_wirerr_get_rdatalen(a->rr, a->rr_len, a->dname_len) !=
   1447 			b_len)
   1448 			return -1;
   1449 		return memcmp(sldns_wirerr_get_rdata(a->rr,
   1450 			a->rr_len, a->dname_len), b, b_len);
   1451 	}
   1452 	return -1;
   1453 }
   1454 
   1455 /**
   1456  * Find key
   1457  * @param tp: to search in
   1458  * @param t: rr type of the rdata.
   1459  * @param rdata: to look for  (no rdatalen in it)
   1460  * @param rdata_len: length of rdata
   1461  * @param result: returns NULL or the ta key looked for.
   1462  * @return false on malloc failure during search. if true examine result.
   1463  */
   1464 static int
   1465 find_key(struct trust_anchor* tp, uint16_t t, uint8_t* rdata, size_t rdata_len,
   1466 	struct autr_ta** result)
   1467 {
   1468 	struct autr_ta* ta;
   1469 	if(!tp || !rdata) {
   1470 		*result = NULL;
   1471 		return 0;
   1472 	}
   1473 	for(ta=tp->autr->keys; ta; ta=ta->next) {
   1474 		if(ta_compare(ta, t, rdata, rdata_len) == 0) {
   1475 			*result = ta;
   1476 			return 1;
   1477 		}
   1478 	}
   1479 	*result = NULL;
   1480 	return 1;
   1481 }
   1482 
   1483 /** add key and clone RR and tp already locked. rdata without rdlen. */
   1484 static struct autr_ta*
   1485 add_key(struct trust_anchor* tp, uint32_t ttl, uint8_t* rdata, size_t rdata_len)
   1486 {
   1487 	struct autr_ta* ta;
   1488 	uint8_t* rr;
   1489 	size_t rr_len, dname_len;
   1490 	uint16_t rrtype = htons(LDNS_RR_TYPE_DNSKEY);
   1491 	uint16_t rrclass = htons(LDNS_RR_CLASS_IN);
   1492 	uint16_t rdlen = htons(rdata_len);
   1493 	dname_len = tp->namelen;
   1494 	ttl = htonl(ttl);
   1495 	rr_len = dname_len + 10 /* type,class,ttl,rdatalen */ + rdata_len;
   1496 	rr = (uint8_t*)malloc(rr_len);
   1497 	if(!rr) return NULL;
   1498 	memmove(rr, tp->name, tp->namelen);
   1499 	memmove(rr+dname_len, &rrtype, 2);
   1500 	memmove(rr+dname_len+2, &rrclass, 2);
   1501 	memmove(rr+dname_len+4, &ttl, 4);
   1502 	memmove(rr+dname_len+8, &rdlen, 2);
   1503 	memmove(rr+dname_len+10, rdata, rdata_len);
   1504 	ta = autr_ta_create(rr, rr_len, dname_len);
   1505 	if(!ta) {
   1506 		/* rr freed in autr_ta_create */
   1507 		return NULL;
   1508 	}
   1509 	/* link in, tp already locked */
   1510 	ta->next = tp->autr->keys;
   1511 	tp->autr->keys = ta;
   1512 	return ta;
   1513 }
   1514 
   1515 /** get TTL from DNSKEY rrset */
   1516 static time_t
   1517 key_ttl(struct ub_packed_rrset_key* k)
   1518 {
   1519 	struct packed_rrset_data* d = (struct packed_rrset_data*)k->entry.data;
   1520 	return d->ttl;
   1521 }
   1522 
   1523 /** update the time values for the trustpoint */
   1524 static void
   1525 set_tp_times(struct trust_anchor* tp, time_t rrsig_exp_interval,
   1526 	time_t origttl, int* changed)
   1527 {
   1528 	time_t x, qi = tp->autr->query_interval, rt = tp->autr->retry_time;
   1529 
   1530 	/* x = MIN(15days, ttl/2, expire/2) */
   1531 	x = 15 * 24 * 3600;
   1532 	if(origttl/2 < x)
   1533 		x = origttl/2;
   1534 	if(rrsig_exp_interval/2 < x)
   1535 		x = rrsig_exp_interval/2;
   1536 	/* MAX(1hr, x) */
   1537 	if(!autr_permit_small_holddown) {
   1538 		if(x < 3600)
   1539 			tp->autr->query_interval = 3600;
   1540 		else	tp->autr->query_interval = x;
   1541 	}	else    tp->autr->query_interval = x;
   1542 
   1543 	/* x= MIN(1day, ttl/10, expire/10) */
   1544 	x = 24 * 3600;
   1545 	if(origttl/10 < x)
   1546 		x = origttl/10;
   1547 	if(rrsig_exp_interval/10 < x)
   1548 		x = rrsig_exp_interval/10;
   1549 	/* MAX(1hr, x) */
   1550 	if(!autr_permit_small_holddown) {
   1551 		if(x < 3600)
   1552 			tp->autr->retry_time = 3600;
   1553 		else	tp->autr->retry_time = x;
   1554 	}	else    tp->autr->retry_time = x;
   1555 
   1556 	if(qi != tp->autr->query_interval || rt != tp->autr->retry_time) {
   1557 		*changed = 1;
   1558 		verbose(VERB_ALGO, "orig_ttl is %d", (int)origttl);
   1559 		verbose(VERB_ALGO, "rrsig_exp_interval is %d",
   1560 			(int)rrsig_exp_interval);
   1561 		verbose(VERB_ALGO, "query_interval: %d, retry_time: %d",
   1562 			(int)tp->autr->query_interval,
   1563 			(int)tp->autr->retry_time);
   1564 	}
   1565 }
   1566 
   1567 /** init events to zero */
   1568 static void
   1569 init_events(struct trust_anchor* tp)
   1570 {
   1571 	struct autr_ta* ta;
   1572 	for(ta=tp->autr->keys; ta; ta=ta->next) {
   1573 		ta->fetched = 0;
   1574 	}
   1575 }
   1576 
   1577 /** check for revoked keys without trusting any other information */
   1578 static void
   1579 check_contains_revoked(struct module_env* env, struct val_env* ve,
   1580 	struct trust_anchor* tp, struct ub_packed_rrset_key* dnskey_rrset,
   1581 	int* changed, struct module_qstate* qstate, struct val_qstate* vq)
   1582 {
   1583 	struct packed_rrset_data* dd = (struct packed_rrset_data*)
   1584 		dnskey_rrset->entry.data;
   1585 	size_t i;
   1586 	log_assert(ntohs(dnskey_rrset->rk.type) == LDNS_RR_TYPE_DNSKEY);
   1587 	for(i=0; i<dd->count; i++) {
   1588 		struct autr_ta* ta = NULL;
   1589 		if(!rr_is_dnskey_sep(ntohs(dnskey_rrset->rk.type),
   1590 			dd->rr_data[i]+2, dd->rr_len[i]-2) ||
   1591 			!rr_is_dnskey_revoked(ntohs(dnskey_rrset->rk.type),
   1592 			dd->rr_data[i]+2, dd->rr_len[i]-2))
   1593 			continue; /* not a revoked KSK */
   1594 		if(!find_key(tp, ntohs(dnskey_rrset->rk.type),
   1595 			dd->rr_data[i]+2, dd->rr_len[i]-2, &ta)) {
   1596 			log_err("malloc failure");
   1597 			continue; /* malloc fail in compare*/
   1598 		}
   1599 		if(!ta)
   1600 			continue; /* key not found */
   1601 		if(rr_is_selfsigned_revoked(env, ve, dnskey_rrset, i, qstate,
   1602 			vq)) {
   1603 			/* checked if there is an rrsig signed by this key. */
   1604 			/* same keytag, but stored can be revoked already, so
   1605 			 * compare keytags, with +0 or +128(REVOKE flag) */
   1606 			log_assert(dnskey_calc_keytag(dnskey_rrset, i)-128 ==
   1607 				sldns_calc_keytag_raw(sldns_wirerr_get_rdata(
   1608 				ta->rr, ta->rr_len, ta->dname_len),
   1609 				sldns_wirerr_get_rdatalen(ta->rr, ta->rr_len,
   1610 				ta->dname_len)) ||
   1611 				dnskey_calc_keytag(dnskey_rrset, i) ==
   1612 				sldns_calc_keytag_raw(sldns_wirerr_get_rdata(
   1613 				ta->rr, ta->rr_len, ta->dname_len),
   1614 				sldns_wirerr_get_rdatalen(ta->rr, ta->rr_len,
   1615 				ta->dname_len))); /* checks conversion*/
   1616 			verbose_key(ta, VERB_ALGO, "is self-signed revoked");
   1617 			if(!ta->revoked)
   1618 				*changed = 1;
   1619 			seen_revoked_trustanchor(ta, 1);
   1620 			do_revoked(env, ta, changed);
   1621 		}
   1622 	}
   1623 }
   1624 
   1625 /** See if a DNSKEY is verified by one of the DSes */
   1626 static int
   1627 key_matches_a_ds(struct module_env* env, struct val_env* ve,
   1628 	struct ub_packed_rrset_key* dnskey_rrset, size_t key_idx,
   1629 	struct ub_packed_rrset_key* ds_rrset)
   1630 {
   1631 	struct packed_rrset_data* dd = (struct packed_rrset_data*)
   1632 	                ds_rrset->entry.data;
   1633 	size_t ds_idx, num = dd->count;
   1634 	int d = val_favorite_ds_algo(ds_rrset);
   1635 	char* reason = "";
   1636 	for(ds_idx=0; ds_idx<num; ds_idx++) {
   1637 		if(!ds_digest_algo_is_supported(ds_rrset, ds_idx) ||
   1638 			!ds_key_algo_is_supported(ds_rrset, ds_idx) ||
   1639 			!dnskey_size_is_supported(dnskey_rrset, key_idx) ||
   1640 			ds_get_digest_algo(ds_rrset, ds_idx) != d)
   1641 			continue;
   1642 		if(ds_get_key_algo(ds_rrset, ds_idx)
   1643 		   != dnskey_get_algo(dnskey_rrset, key_idx)
   1644 		   || dnskey_calc_keytag(dnskey_rrset, key_idx)
   1645 		   != ds_get_keytag(ds_rrset, ds_idx)) {
   1646 			continue;
   1647 		}
   1648 		if(!ds_digest_match_dnskey(env, dnskey_rrset, key_idx,
   1649 			ds_rrset, ds_idx)) {
   1650 			verbose(VERB_ALGO, "DS match attempt failed");
   1651 			continue;
   1652 		}
   1653 		/* match of hash is sufficient for bootstrap of trust point */
   1654 		(void)reason;
   1655 		(void)ve;
   1656 		return 1;
   1657 		/* no need to check RRSIG, DS hash already matched with source
   1658 		if(dnskey_verify_rrset(env, ve, dnskey_rrset,
   1659 			dnskey_rrset, key_idx, &reason) == sec_status_secure) {
   1660 			return 1;
   1661 		} else {
   1662 			verbose(VERB_ALGO, "DS match failed because the key "
   1663 				"does not verify the keyset: %s", reason);
   1664 		}
   1665 		*/
   1666 	}
   1667 	return 0;
   1668 }
   1669 
   1670 /** Set update events */
   1671 static int
   1672 update_events(struct module_env* env, struct val_env* ve,
   1673 	struct trust_anchor* tp, struct ub_packed_rrset_key* dnskey_rrset,
   1674 	int* changed)
   1675 {
   1676 	struct packed_rrset_data* dd = (struct packed_rrset_data*)
   1677 		dnskey_rrset->entry.data;
   1678 	size_t i;
   1679 	log_assert(ntohs(dnskey_rrset->rk.type) == LDNS_RR_TYPE_DNSKEY);
   1680 	init_events(tp);
   1681 	for(i=0; i<dd->count; i++) {
   1682 		struct autr_ta* ta = NULL;
   1683 		if(!rr_is_dnskey_sep(ntohs(dnskey_rrset->rk.type),
   1684 			dd->rr_data[i]+2, dd->rr_len[i]-2))
   1685 			continue;
   1686 		if(rr_is_dnskey_revoked(ntohs(dnskey_rrset->rk.type),
   1687 			dd->rr_data[i]+2, dd->rr_len[i]-2)) {
   1688 			/* self-signed revoked keys already detected before,
   1689 			 * other revoked keys are not 'added' again */
   1690 			continue;
   1691 		}
   1692 		/* is a key of this type supported?. Note rr_list and
   1693 		 * packed_rrset are in the same order. */
   1694 		if(!dnskey_algo_is_supported(dnskey_rrset, i) ||
   1695 			!dnskey_size_is_supported(dnskey_rrset, i)) {
   1696 			/* skip unknown algorithm key, it is useless to us */
   1697 			log_nametypeclass(VERB_DETAIL, "trust point has "
   1698 				"unsupported algorithm at",
   1699 				tp->name, LDNS_RR_TYPE_DNSKEY, tp->dclass);
   1700 			continue;
   1701 		}
   1702 
   1703 		/* is it new? if revocation bit set, find the unrevoked key */
   1704 		if(!find_key(tp, ntohs(dnskey_rrset->rk.type),
   1705 			dd->rr_data[i]+2, dd->rr_len[i]-2, &ta)) {
   1706 			return 0;
   1707 		}
   1708 		if(!ta) {
   1709 			ta = add_key(tp, (uint32_t)dd->rr_ttl[i],
   1710 				dd->rr_data[i]+2, dd->rr_len[i]-2);
   1711 			*changed = 1;
   1712 			/* first time seen, do we have DSes? if match: VALID */
   1713 			if(ta && tp->ds_rrset && key_matches_a_ds(env, ve,
   1714 				dnskey_rrset, i, tp->ds_rrset)) {
   1715 				verbose_key(ta, VERB_ALGO, "verified by DS");
   1716 				ta->s = AUTR_STATE_VALID;
   1717 			}
   1718 		}
   1719 		if(!ta) {
   1720 			return 0;
   1721 		}
   1722 		seen_trustanchor(ta, 1);
   1723 		verbose_key(ta, VERB_ALGO, "in DNS response");
   1724 	}
   1725 	set_tp_times(tp, min_expiry(env, dd), key_ttl(dnskey_rrset), changed);
   1726 	return 1;
   1727 }
   1728 
   1729 /**
   1730  * Check if the holddown time has already exceeded
   1731  * setting: add-holddown: add holddown timer
   1732  * setting: del-holddown: del holddown timer
   1733  * @param env: environment with current time
   1734  * @param ta: trust anchor to check for.
   1735  * @param holddown: the timer value
   1736  * @return number of seconds the holddown has passed.
   1737  */
   1738 static time_t
   1739 check_holddown(struct module_env* env, struct autr_ta* ta,
   1740 	unsigned int holddown)
   1741 {
   1742         time_t elapsed;
   1743 	if(*env->now < ta->last_change) {
   1744 		log_warn("time goes backwards. delaying key holddown");
   1745 		return 0;
   1746 	}
   1747 	elapsed = *env->now - ta->last_change;
   1748         if (elapsed > (time_t)holddown) {
   1749                 return elapsed-(time_t)holddown;
   1750         }
   1751 	verbose_key(ta, VERB_ALGO, "holddown time " ARG_LL "d seconds to go",
   1752 		(long long) ((time_t)holddown-elapsed));
   1753         return 0;
   1754 }
   1755 
   1756 
   1757 /** Set last_change to now */
   1758 static void
   1759 reset_holddown(struct module_env* env, struct autr_ta* ta, int* changed)
   1760 {
   1761 	ta->last_change = *env->now;
   1762 	*changed = 1;
   1763 }
   1764 
   1765 /** Set the state for this trust anchor */
   1766 static void
   1767 set_trustanchor_state(struct module_env* env, struct autr_ta* ta, int* changed,
   1768 	autr_state_type s)
   1769 {
   1770 	verbose_key(ta, VERB_ALGO, "update: %s to %s",
   1771 		trustanchor_state2str(ta->s), trustanchor_state2str(s));
   1772 	ta->s = s;
   1773 	reset_holddown(env, ta, changed);
   1774 }
   1775 
   1776 
   1777 /** Event: NewKey */
   1778 static void
   1779 do_newkey(struct module_env* env, struct autr_ta* anchor, int* c)
   1780 {
   1781 	if (anchor->s == AUTR_STATE_START)
   1782 		set_trustanchor_state(env, anchor, c, AUTR_STATE_ADDPEND);
   1783 }
   1784 
   1785 /** Event: AddTime */
   1786 static void
   1787 do_addtime(struct module_env* env, struct autr_ta* anchor, int* c)
   1788 {
   1789 	/* This not according to RFC, this is 30 days, but the RFC demands
   1790 	 * MAX(30days, TTL expire time of first DNSKEY set with this key),
   1791 	 * The value may be too small if a very large TTL was used. */
   1792 	time_t exceeded = check_holddown(env, anchor, env->cfg->add_holddown);
   1793 	if (exceeded && anchor->s == AUTR_STATE_ADDPEND) {
   1794 		verbose_key(anchor, VERB_ALGO, "add-holddown time exceeded "
   1795 			ARG_LL "d seconds ago, and pending-count %d",
   1796 			(long long)exceeded, anchor->pending_count);
   1797 		if(anchor->pending_count >= MIN_PENDINGCOUNT) {
   1798 			set_trustanchor_state(env, anchor, c, AUTR_STATE_VALID);
   1799 			anchor->pending_count = 0;
   1800 			return;
   1801 		}
   1802 		verbose_key(anchor, VERB_ALGO, "add-holddown time sanity check "
   1803 			"failed (pending count: %d)", anchor->pending_count);
   1804 	}
   1805 }
   1806 
   1807 /** Event: RemTime */
   1808 static void
   1809 do_remtime(struct module_env* env, struct autr_ta* anchor, int* c)
   1810 {
   1811 	time_t exceeded = check_holddown(env, anchor, env->cfg->del_holddown);
   1812 	if(exceeded && anchor->s == AUTR_STATE_REVOKED) {
   1813 		verbose_key(anchor, VERB_ALGO, "del-holddown time exceeded "
   1814 			ARG_LL "d seconds ago", (long long)exceeded);
   1815 		set_trustanchor_state(env, anchor, c, AUTR_STATE_REMOVED);
   1816 	}
   1817 }
   1818 
   1819 /** Event: KeyRem */
   1820 static void
   1821 do_keyrem(struct module_env* env, struct autr_ta* anchor, int* c)
   1822 {
   1823 	if(anchor->s == AUTR_STATE_ADDPEND) {
   1824 		set_trustanchor_state(env, anchor, c, AUTR_STATE_START);
   1825 		anchor->pending_count = 0;
   1826 	} else if(anchor->s == AUTR_STATE_VALID)
   1827 		set_trustanchor_state(env, anchor, c, AUTR_STATE_MISSING);
   1828 }
   1829 
   1830 /** Event: KeyPres */
   1831 static void
   1832 do_keypres(struct module_env* env, struct autr_ta* anchor, int* c)
   1833 {
   1834 	if(anchor->s == AUTR_STATE_MISSING)
   1835 		set_trustanchor_state(env, anchor, c, AUTR_STATE_VALID);
   1836 }
   1837 
   1838 /* Event: Revoked */
   1839 static void
   1840 do_revoked(struct module_env* env, struct autr_ta* anchor, int* c)
   1841 {
   1842 	if(anchor->s == AUTR_STATE_VALID || anchor->s == AUTR_STATE_MISSING) {
   1843                 set_trustanchor_state(env, anchor, c, AUTR_STATE_REVOKED);
   1844 		verbose_key(anchor, VERB_ALGO, "old id, prior to revocation");
   1845                 revoke_dnskey(anchor, 0);
   1846 		verbose_key(anchor, VERB_ALGO, "new id, after revocation");
   1847 	}
   1848 }
   1849 
   1850 /** Do statestable transition matrix for anchor */
   1851 static void
   1852 anchor_state_update(struct module_env* env, struct autr_ta* anchor, int* c)
   1853 {
   1854 	log_assert(anchor);
   1855 	switch(anchor->s) {
   1856 	/* START */
   1857 	case AUTR_STATE_START:
   1858 		/* NewKey: ADDPEND */
   1859 		if (anchor->fetched)
   1860 			do_newkey(env, anchor, c);
   1861 		break;
   1862 	/* ADDPEND */
   1863 	case AUTR_STATE_ADDPEND:
   1864 		/* KeyRem: START */
   1865 		if (!anchor->fetched)
   1866 			do_keyrem(env, anchor, c);
   1867 		/* AddTime: VALID */
   1868 		else	do_addtime(env, anchor, c);
   1869 		break;
   1870 	/* VALID */
   1871 	case AUTR_STATE_VALID:
   1872 		/* RevBit: REVOKED */
   1873 		if (anchor->revoked)
   1874 			do_revoked(env, anchor, c);
   1875 		/* KeyRem: MISSING */
   1876 		else if (!anchor->fetched)
   1877 			do_keyrem(env, anchor, c);
   1878 		else if(!anchor->last_change) {
   1879 			verbose_key(anchor, VERB_ALGO, "first seen");
   1880 			reset_holddown(env, anchor, c);
   1881 		}
   1882 		break;
   1883 	/* MISSING */
   1884 	case AUTR_STATE_MISSING:
   1885 		/* RevBit: REVOKED */
   1886 		if (anchor->revoked)
   1887 			do_revoked(env, anchor, c);
   1888 		/* KeyPres */
   1889 		else if (anchor->fetched)
   1890 			do_keypres(env, anchor, c);
   1891 		break;
   1892 	/* REVOKED */
   1893 	case AUTR_STATE_REVOKED:
   1894 		if (anchor->fetched)
   1895 			reset_holddown(env, anchor, c);
   1896 		/* RemTime: REMOVED */
   1897 		else	do_remtime(env, anchor, c);
   1898 		break;
   1899 	/* REMOVED */
   1900 	case AUTR_STATE_REMOVED:
   1901 	default:
   1902 		break;
   1903 	}
   1904 }
   1905 
   1906 /** if ZSK init then trust KSKs */
   1907 static int
   1908 init_zsk_to_ksk(struct module_env* env, struct trust_anchor* tp, int* changed)
   1909 {
   1910 	/* search for VALID ZSKs */
   1911 	struct autr_ta* anchor;
   1912 	int validzsk = 0;
   1913 	int validksk = 0;
   1914 	for(anchor = tp->autr->keys; anchor; anchor = anchor->next) {
   1915 		/* last_change test makes sure it was manually configured */
   1916 		if(sldns_wirerr_get_type(anchor->rr, anchor->rr_len,
   1917 			anchor->dname_len) == LDNS_RR_TYPE_DNSKEY &&
   1918 			anchor->last_change == 0 &&
   1919 			!ta_is_dnskey_sep(anchor) &&
   1920 			anchor->s == AUTR_STATE_VALID)
   1921                         validzsk++;
   1922 	}
   1923 	if(validzsk == 0)
   1924 		return 0;
   1925 	for(anchor = tp->autr->keys; anchor; anchor = anchor->next) {
   1926                 if (ta_is_dnskey_sep(anchor) &&
   1927 			anchor->s == AUTR_STATE_ADDPEND) {
   1928 			verbose_key(anchor, VERB_ALGO, "trust KSK from "
   1929 				"ZSK(config)");
   1930 			set_trustanchor_state(env, anchor, changed,
   1931 				AUTR_STATE_VALID);
   1932 			validksk++;
   1933 		}
   1934 	}
   1935 	return validksk;
   1936 }
   1937 
   1938 /** Remove missing trustanchors so the list does not grow forever */
   1939 static void
   1940 remove_missing_trustanchors(struct module_env* env, struct trust_anchor* tp,
   1941 	int* changed)
   1942 {
   1943 	struct autr_ta* anchor;
   1944 	time_t exceeded;
   1945 	int valid = 0;
   1946 	/* see if we have anchors that are valid */
   1947 	for(anchor = tp->autr->keys; anchor; anchor = anchor->next) {
   1948 		/* Only do KSKs */
   1949                 if (!ta_is_dnskey_sep(anchor))
   1950                         continue;
   1951                 if (anchor->s == AUTR_STATE_VALID)
   1952                         valid++;
   1953 	}
   1954 	/* if there are no SEP Valid anchors, see if we started out with
   1955 	 * a ZSK (last-change=0) anchor, which is VALID and there are KSKs
   1956 	 * now that can be made valid.  Do this immediately because there
   1957 	 * is no guarantee that the ZSKs get announced long enough.  Usually
   1958 	 * this is immediately after init with a ZSK trusted, unless the domain
   1959 	 * was not advertising any KSKs at all.  In which case we perfectly
   1960 	 * track the zero number of KSKs. */
   1961 	if(valid == 0) {
   1962 		valid = init_zsk_to_ksk(env, tp, changed);
   1963 		if(valid == 0)
   1964 			return;
   1965 	}
   1966 
   1967 	for(anchor = tp->autr->keys; anchor; anchor = anchor->next) {
   1968 		/* ignore ZSKs if newly added */
   1969 		if(anchor->s == AUTR_STATE_START)
   1970 			continue;
   1971 		/* remove ZSKs if a KSK is present */
   1972                 if (!ta_is_dnskey_sep(anchor)) {
   1973 			if(valid > 0) {
   1974 				verbose_key(anchor, VERB_ALGO, "remove ZSK "
   1975 					"[%d key(s) VALID]", valid);
   1976 				set_trustanchor_state(env, anchor, changed,
   1977 					AUTR_STATE_REMOVED);
   1978 			}
   1979                         continue;
   1980 		}
   1981                 /* Only do MISSING keys */
   1982                 if (anchor->s != AUTR_STATE_MISSING)
   1983                         continue;
   1984 		if(env->cfg->keep_missing == 0)
   1985 			continue; /* keep forever */
   1986 
   1987 		exceeded = check_holddown(env, anchor, env->cfg->keep_missing);
   1988 		/* If keep_missing has exceeded and we still have more than
   1989 		 * one valid KSK: remove missing trust anchor */
   1990                 if (exceeded && valid > 0) {
   1991 			verbose_key(anchor, VERB_ALGO, "keep-missing time "
   1992 				"exceeded " ARG_LL "d seconds ago, [%d key(s) VALID]",
   1993 				(long long)exceeded, valid);
   1994 			set_trustanchor_state(env, anchor, changed,
   1995 				AUTR_STATE_REMOVED);
   1996 		}
   1997 	}
   1998 }
   1999 
   2000 /** Do the statetable from RFC5011 transition matrix */
   2001 static int
   2002 do_statetable(struct module_env* env, struct trust_anchor* tp, int* changed)
   2003 {
   2004 	struct autr_ta* anchor;
   2005 	for(anchor = tp->autr->keys; anchor; anchor = anchor->next) {
   2006 		/* Only do KSKs */
   2007 		if(!ta_is_dnskey_sep(anchor))
   2008 			continue;
   2009 		anchor_state_update(env, anchor, changed);
   2010 	}
   2011 	remove_missing_trustanchors(env, tp, changed);
   2012 	return 1;
   2013 }
   2014 
   2015 /** See if time alone makes ADDPEND to VALID transition */
   2016 static void
   2017 autr_holddown_exceed(struct module_env* env, struct trust_anchor* tp, int* c)
   2018 {
   2019 	struct autr_ta* anchor;
   2020 	for(anchor = tp->autr->keys; anchor; anchor = anchor->next) {
   2021 		if(ta_is_dnskey_sep(anchor) &&
   2022 			anchor->s == AUTR_STATE_ADDPEND)
   2023 			do_addtime(env, anchor, c);
   2024 	}
   2025 }
   2026 
   2027 /** cleanup key list */
   2028 static void
   2029 autr_cleanup_keys(struct trust_anchor* tp)
   2030 {
   2031 	struct autr_ta* p, **prevp;
   2032 	prevp = &tp->autr->keys;
   2033 	p = tp->autr->keys;
   2034 	while(p) {
   2035 		/* do we want to remove this key? */
   2036 		if(p->s == AUTR_STATE_START || p->s == AUTR_STATE_REMOVED ||
   2037 			sldns_wirerr_get_type(p->rr, p->rr_len, p->dname_len)
   2038 			!= LDNS_RR_TYPE_DNSKEY) {
   2039 			struct autr_ta* np = p->next;
   2040 			/* remove */
   2041 			autr_ta_delete(p);
   2042 			/* snip and go to next item */
   2043 			*prevp = np;
   2044 			p = np;
   2045 			continue;
   2046 		}
   2047 		/* remove pending counts if no longer pending */
   2048 		if(p->s != AUTR_STATE_ADDPEND)
   2049 			p->pending_count = 0;
   2050 		prevp = &p->next;
   2051 		p = p->next;
   2052 	}
   2053 }
   2054 
   2055 /** calculate next probe time */
   2056 static time_t
   2057 calc_next_probe(struct module_env* env, time_t wait)
   2058 {
   2059 	/* make it random, 90-100% */
   2060 	time_t rnd, rest;
   2061 	if(!autr_permit_small_holddown) {
   2062 		if(wait < 3600)
   2063 			wait = 3600;
   2064 	} else {
   2065 		if(wait == 0) wait = 1;
   2066 	}
   2067 	rnd = wait/10;
   2068 	rest = wait-rnd;
   2069 	rnd = (time_t)ub_random_max(env->rnd, (long int)rnd);
   2070 	return (time_t)(*env->now + rest + rnd);
   2071 }
   2072 
   2073 /** what is first probe time (anchors must be locked) */
   2074 static time_t
   2075 wait_probe_time(struct val_anchors* anchors)
   2076 {
   2077 	rbnode_type* t = rbtree_first(&anchors->autr->probe);
   2078 	if(t != RBTREE_NULL)
   2079 		return ((struct trust_anchor*)t->key)->autr->next_probe_time;
   2080 	return 0;
   2081 }
   2082 
   2083 /** reset worker timer, at the time from wait_probe_time. */
   2084 static void
   2085 reset_worker_timer_at(struct module_env* env, time_t next)
   2086 {
   2087 	struct timeval tv;
   2088 #ifndef S_SPLINT_S
   2089 	/* in case this is libunbound, no timer */
   2090 	if(!env->probe_timer)
   2091 		return;
   2092 	if(next > *env->now)
   2093 		tv.tv_sec = (time_t)(next - *env->now);
   2094 	else	tv.tv_sec = 0;
   2095 #else
   2096 	(void)next;
   2097 #endif
   2098 	tv.tv_usec = 0;
   2099 	comm_timer_set(env->probe_timer, &tv);
   2100 	verbose(VERB_ALGO, "scheduled next probe in " ARG_LL "d sec", (long long)tv.tv_sec);
   2101 }
   2102 
   2103 /** reset worker timer. This routine manages the locks on acquiring the
   2104  * next time for the timer. */
   2105 static void
   2106 reset_worker_timer(struct module_env* env)
   2107 {
   2108 	time_t next;
   2109 	if(!env->anchors)
   2110 		return;
   2111 	lock_basic_lock(&env->anchors->lock);
   2112 	next = wait_probe_time(env->anchors);
   2113 	lock_basic_unlock(&env->anchors->lock);
   2114 	reset_worker_timer_at(env, next);
   2115 }
   2116 
   2117 /** set next probe for trust anchor */
   2118 static int
   2119 set_next_probe(struct module_env* env, struct trust_anchor* tp,
   2120 	struct ub_packed_rrset_key* dnskey_rrset)
   2121 {
   2122 	struct trust_anchor key, *tp2;
   2123 	time_t mold, mnew;
   2124 	/* use memory allocated in rrset for temporary name storage */
   2125 	key.node.key = &key;
   2126 	key.name = dnskey_rrset->rk.dname;
   2127 	key.namelen = dnskey_rrset->rk.dname_len;
   2128 	key.namelabs = dname_count_labels(key.name);
   2129 	key.dclass = tp->dclass;
   2130 	lock_basic_unlock(&tp->lock);
   2131 
   2132 	/* fetch tp again and lock anchors, so that we can modify the trees */
   2133 	lock_basic_lock(&env->anchors->lock);
   2134 	tp2 = (struct trust_anchor*)rbtree_search(env->anchors->tree, &key);
   2135 	if(!tp2) {
   2136 		verbose(VERB_ALGO, "trustpoint was deleted in set_next_probe");
   2137 		lock_basic_unlock(&env->anchors->lock);
   2138 		return 0;
   2139 	}
   2140 	log_assert(tp == tp2);
   2141 	lock_basic_lock(&tp->lock);
   2142 
   2143 	/* schedule */
   2144 	mold = wait_probe_time(env->anchors);
   2145 	(void)rbtree_delete(&env->anchors->autr->probe, tp);
   2146 	tp->autr->next_probe_time = calc_next_probe(env,
   2147 		tp->autr->query_interval);
   2148 	(void)rbtree_insert(&env->anchors->autr->probe, &tp->autr->pnode);
   2149 	mnew = wait_probe_time(env->anchors);
   2150 
   2151 	lock_basic_unlock(&env->anchors->lock);
   2152 	verbose(VERB_ALGO, "next probe set in %d seconds",
   2153 		(int)tp->autr->next_probe_time - (int)*env->now);
   2154 	if(mold != mnew) {
   2155 		reset_worker_timer_at(env, mnew);
   2156 	}
   2157 	return 1;
   2158 }
   2159 
   2160 /** Revoke and Delete a trust point */
   2161 static void
   2162 autr_tp_remove(struct module_env* env, struct trust_anchor* tp,
   2163 	struct ub_packed_rrset_key* dnskey_rrset)
   2164 {
   2165 	struct trust_anchor* del_tp;
   2166 	struct trust_anchor key;
   2167 	struct autr_point_data pd;
   2168 	time_t mold, mnew;
   2169 
   2170 	log_nametypeclass(VERB_OPS, "trust point was revoked",
   2171 		tp->name, LDNS_RR_TYPE_DNSKEY, tp->dclass);
   2172 	tp->autr->revoked = 1;
   2173 
   2174 	/* use space allocated for dnskey_rrset to save name of anchor */
   2175 	memset(&key, 0, sizeof(key));
   2176 	memset(&pd, 0, sizeof(pd));
   2177 	key.autr = &pd;
   2178 	key.node.key = &key;
   2179 	pd.pnode.key = &key;
   2180 	pd.next_probe_time = tp->autr->next_probe_time;
   2181 	key.name = dnskey_rrset->rk.dname;
   2182 	key.namelen = tp->namelen;
   2183 	key.namelabs = tp->namelabs;
   2184 	key.dclass = tp->dclass;
   2185 
   2186 	/* unlock */
   2187 	lock_basic_unlock(&tp->lock);
   2188 
   2189 	/* take from tree. It could be deleted by someone else,hence (void). */
   2190 	lock_basic_lock(&env->anchors->lock);
   2191 	del_tp = (struct trust_anchor*)rbtree_delete(env->anchors->tree, &key);
   2192 	mold = wait_probe_time(env->anchors);
   2193 	(void)rbtree_delete(&env->anchors->autr->probe, &key);
   2194 	mnew = wait_probe_time(env->anchors);
   2195 	anchors_init_parents_locked(env->anchors);
   2196 	lock_basic_unlock(&env->anchors->lock);
   2197 
   2198 	/* if !del_tp then the trust point is no longer present in the tree,
   2199 	 * it was deleted by someone else, who will write the zonefile and
   2200 	 * clean up the structure */
   2201 	if(del_tp) {
   2202 		/* save on disk */
   2203 		del_tp->autr->next_probe_time = 0; /* no more probing for it */
   2204 		autr_write_file(env, del_tp);
   2205 
   2206 		/* delete */
   2207 		autr_point_delete(del_tp);
   2208 	}
   2209 	if(mold != mnew) {
   2210 		reset_worker_timer_at(env, mnew);
   2211 	}
   2212 }
   2213 
   2214 int autr_process_prime(struct module_env* env, struct val_env* ve,
   2215 	struct trust_anchor* tp, struct ub_packed_rrset_key* dnskey_rrset,
   2216 	struct module_qstate* qstate, struct val_qstate* vq)
   2217 {
   2218 	int changed = 0;
   2219 	log_assert(tp && tp->autr);
   2220 	/* autotrust update trust anchors */
   2221 	/* the tp is locked, and stays locked unless it is deleted */
   2222 
   2223 	/* we could just catch the anchor here while another thread
   2224 	 * is busy deleting it. Just unlock and let the other do its job */
   2225 	if(tp->autr->revoked) {
   2226 		log_nametypeclass(VERB_ALGO, "autotrust not processed, "
   2227 			"trust point revoked", tp->name,
   2228 			LDNS_RR_TYPE_DNSKEY, tp->dclass);
   2229 		lock_basic_unlock(&tp->lock);
   2230 		return 0; /* it is revoked */
   2231 	}
   2232 
   2233 	/* query_dnskeys(): */
   2234 	tp->autr->last_queried = *env->now;
   2235 
   2236 	log_nametypeclass(VERB_ALGO, "autotrust process for",
   2237 		tp->name, LDNS_RR_TYPE_DNSKEY, tp->dclass);
   2238 	/* see if time alone makes some keys valid */
   2239 	autr_holddown_exceed(env, tp, &changed);
   2240 	if(changed) {
   2241 		verbose(VERB_ALGO, "autotrust: morekeys, reassemble");
   2242 		if(!autr_assemble(tp)) {
   2243 			log_err("malloc failure assembling autotrust keys");
   2244 			return 1; /* unchanged */
   2245 		}
   2246 	}
   2247 	/* did we get any data? */
   2248 	if(!dnskey_rrset) {
   2249 		verbose(VERB_ALGO, "autotrust: no dnskey rrset");
   2250 		/* no update of query_failed, because then we would have
   2251 		 * to write to disk. But we cannot because we maybe are
   2252 		 * still 'initializing' with DS records, that we cannot write
   2253 		 * in the full format (which only contains KSKs). */
   2254 		return 1; /* trust point exists */
   2255 	}
   2256 	/* check for revoked keys to remove immediately */
   2257 	check_contains_revoked(env, ve, tp, dnskey_rrset, &changed, qstate, vq);
   2258 	if(changed) {
   2259 		verbose(VERB_ALGO, "autotrust: revokedkeys, reassemble");
   2260 		if(!autr_assemble(tp)) {
   2261 			log_err("malloc failure assembling autotrust keys");
   2262 			return 1; /* unchanged */
   2263 		}
   2264 		if(!tp->ds_rrset && !tp->dnskey_rrset) {
   2265 			/* no more keys, all are revoked */
   2266 			/* this is a success for this probe attempt */
   2267 			tp->autr->last_success = *env->now;
   2268 			autr_tp_remove(env, tp, dnskey_rrset);
   2269 			return 0; /* trust point removed */
   2270 		}
   2271 	}
   2272 	/* verify the dnskey rrset and see if it is valid. */
   2273 	if(!verify_dnskey(env, ve, tp, dnskey_rrset, qstate, vq)) {
   2274 		verbose(VERB_ALGO, "autotrust: dnskey did not verify.");
   2275 		/* only increase failure count if this is not the first prime,
   2276 		 * this means there was a previous successful probe */
   2277 		if(tp->autr->last_success) {
   2278 			tp->autr->query_failed += 1;
   2279 			autr_write_file(env, tp);
   2280 		}
   2281 		return 1; /* trust point exists */
   2282 	}
   2283 
   2284 	tp->autr->last_success = *env->now;
   2285 	tp->autr->query_failed = 0;
   2286 
   2287 	/* Add new trust anchors to the data structure
   2288 	 * - note which trust anchors are seen this probe.
   2289 	 * Set trustpoint query_interval and retry_time.
   2290 	 * - find minimum rrsig expiration interval
   2291 	 */
   2292 	if(!update_events(env, ve, tp, dnskey_rrset, &changed)) {
   2293 		log_err("malloc failure in autotrust update_events. "
   2294 			"trust point unchanged.");
   2295 		return 1; /* trust point unchanged, so exists */
   2296 	}
   2297 
   2298 	/* - for every SEP key do the 5011 statetable.
   2299 	 * - remove missing trustanchors (if veryold and we have new anchors).
   2300 	 */
   2301 	if(!do_statetable(env, tp, &changed)) {
   2302 		log_err("malloc failure in autotrust do_statetable. "
   2303 			"trust point unchanged.");
   2304 		return 1; /* trust point unchanged, so exists */
   2305 	}
   2306 
   2307 	autr_cleanup_keys(tp);
   2308 	if(!set_next_probe(env, tp, dnskey_rrset))
   2309 		return 0; /* trust point does not exist */
   2310 	autr_write_file(env, tp);
   2311 	if(changed) {
   2312 		verbose(VERB_ALGO, "autotrust: changed, reassemble");
   2313 		if(!autr_assemble(tp)) {
   2314 			log_err("malloc failure assembling autotrust keys");
   2315 			return 1; /* unchanged */
   2316 		}
   2317 		if(!tp->ds_rrset && !tp->dnskey_rrset) {
   2318 			/* no more keys, all are revoked */
   2319 			autr_tp_remove(env, tp, dnskey_rrset);
   2320 			return 0; /* trust point removed */
   2321 		}
   2322 	} else verbose(VERB_ALGO, "autotrust: no changes");
   2323 
   2324 	return 1; /* trust point exists */
   2325 }
   2326 
   2327 /** debug print a trust anchor key */
   2328 static void
   2329 autr_debug_print_ta(struct autr_ta* ta)
   2330 {
   2331 	char buf[32];
   2332 	char* str = sldns_wire2str_rr(ta->rr, ta->rr_len);
   2333 	if(!str) {
   2334 		log_info("out of memory in debug_print_ta");
   2335 		return;
   2336 	}
   2337 	if(str[0]) str[strlen(str)-1]=0; /* remove newline */
   2338 	(void)autr_ctime_r(&ta->last_change, buf);
   2339 	if(buf[0]) buf[strlen(buf)-1]=0; /* remove newline */
   2340 	log_info("[%s] %s ;;state:%d ;;pending_count:%d%s%s last:%s",
   2341 		trustanchor_state2str(ta->s), str, ta->s, ta->pending_count,
   2342 		ta->fetched?" fetched":"", ta->revoked?" revoked":"", buf);
   2343 	free(str);
   2344 }
   2345 
   2346 /** debug print a trust point */
   2347 static void
   2348 autr_debug_print_tp(struct trust_anchor* tp)
   2349 {
   2350 	struct autr_ta* ta;
   2351 	/* Note: buf is also used for autr_ctime_r but that only needs a size
   2352 	 *       of 26, so LDNS_MAX_DOMAINLEN is enough. */
   2353 	char buf[LDNS_MAX_DOMAINLEN];
   2354 	if(!tp->autr)
   2355 		return;
   2356 	dname_str(tp->name, buf);
   2357 	log_info("trust point %s : %d", buf, (int)tp->dclass);
   2358 	log_info("assembled %d DS and %d DNSKEYs",
   2359 		(int)tp->numDS, (int)tp->numDNSKEY);
   2360 	if(tp->ds_rrset) {
   2361 		log_packed_rrset(NO_VERBOSE, "DS:", tp->ds_rrset);
   2362 	}
   2363 	if(tp->dnskey_rrset) {
   2364 		log_packed_rrset(NO_VERBOSE, "DNSKEY:", tp->dnskey_rrset);
   2365 	}
   2366 	log_info("file %s", (tp->autr->file?tp->autr->file:"null"));
   2367 	(void)autr_ctime_r(&tp->autr->last_queried, buf);
   2368 	if(buf[0]) buf[strlen(buf)-1]=0; /* remove newline */
   2369 	log_info("last_queried: %u %s", (unsigned)tp->autr->last_queried, buf);
   2370 	(void)autr_ctime_r(&tp->autr->last_success, buf);
   2371 	if(buf[0]) buf[strlen(buf)-1]=0; /* remove newline */
   2372 	log_info("last_success: %u %s", (unsigned)tp->autr->last_success, buf);
   2373 	(void)autr_ctime_r(&tp->autr->next_probe_time, buf);
   2374 	if(buf[0]) buf[strlen(buf)-1]=0; /* remove newline */
   2375 	log_info("next_probe_time: %u %s", (unsigned)tp->autr->next_probe_time,
   2376 		buf);
   2377 	log_info("query_interval: %u", (unsigned)tp->autr->query_interval);
   2378 	log_info("retry_time: %u", (unsigned)tp->autr->retry_time);
   2379 	log_info("query_failed: %u", (unsigned)tp->autr->query_failed);
   2380 
   2381 	for(ta=tp->autr->keys; ta; ta=ta->next) {
   2382 		autr_debug_print_ta(ta);
   2383 	}
   2384 }
   2385 
   2386 void
   2387 autr_debug_print(struct val_anchors* anchors)
   2388 {
   2389 	struct trust_anchor* tp;
   2390 	lock_basic_lock(&anchors->lock);
   2391 	RBTREE_FOR(tp, struct trust_anchor*, anchors->tree) {
   2392 		lock_basic_lock(&tp->lock);
   2393 		autr_debug_print_tp(tp);
   2394 		lock_basic_unlock(&tp->lock);
   2395 	}
   2396 	lock_basic_unlock(&anchors->lock);
   2397 }
   2398 
   2399 void probe_answer_cb(void* arg, int ATTR_UNUSED(rcode),
   2400 	sldns_buffer* ATTR_UNUSED(buf), enum sec_status ATTR_UNUSED(sec),
   2401 	char* ATTR_UNUSED(why_bogus), int ATTR_UNUSED(was_ratelimited))
   2402 {
   2403 	/* retry was set before the query was done,
   2404 	 * re-querytime is set when query succeeded, but that may not
   2405 	 * have reset this timer because the query could have been
   2406 	 * handled by another thread. In that case, this callback would
   2407 	 * get called after the original timeout is done.
   2408 	 * By not resetting the timer, it may probe more often, but not
   2409 	 * less often.
   2410 	 * Unless the new lookup resulted in smaller TTLs and thus smaller
   2411 	 * timeout values. In that case one old TTL could be mistakenly done.
   2412 	 */
   2413 	struct module_env* env = (struct module_env*)arg;
   2414 	verbose(VERB_ALGO, "autotrust probe answer cb");
   2415 	reset_worker_timer(env);
   2416 }
   2417 
   2418 /** probe a trust anchor DNSKEY and unlocks tp */
   2419 static void
   2420 probe_anchor(struct module_env* env, struct trust_anchor* tp)
   2421 {
   2422 	struct query_info qinfo;
   2423 	uint16_t qflags = BIT_RD;
   2424 	struct edns_data edns;
   2425 	sldns_buffer* buf = env->scratch_buffer;
   2426 	qinfo.qname = regional_alloc_init(env->scratch, tp->name, tp->namelen);
   2427 	if(!qinfo.qname) {
   2428 		log_err("out of memory making 5011 probe");
   2429 		return;
   2430 	}
   2431 	qinfo.qname_len = tp->namelen;
   2432 	qinfo.qtype = LDNS_RR_TYPE_DNSKEY;
   2433 	qinfo.qclass = tp->dclass;
   2434 	qinfo.local_alias = NULL;
   2435 	log_query_info(VERB_ALGO, "autotrust probe", &qinfo);
   2436 	verbose(VERB_ALGO, "retry probe set in %d seconds",
   2437 		(int)tp->autr->next_probe_time - (int)*env->now);
   2438 	edns.edns_present = 1;
   2439 	edns.ext_rcode = 0;
   2440 	edns.edns_version = 0;
   2441 	edns.bits = EDNS_DO;
   2442 	edns.opt_list_in = NULL;
   2443 	edns.opt_list_out = NULL;
   2444 	edns.opt_list_inplace_cb_out = NULL;
   2445 	edns.padding_block_size = 0;
   2446 	edns.cookie_present = 0;
   2447 	edns.cookie_valid = 0;
   2448 	if(sldns_buffer_capacity(buf) < 65535)
   2449 		edns.udp_size = (uint16_t)sldns_buffer_capacity(buf);
   2450 	else	edns.udp_size = 65535;
   2451 
   2452 	/* can't hold the lock while mesh_run is processing */
   2453 	lock_basic_unlock(&tp->lock);
   2454 
   2455 	/* delete the DNSKEY from rrset and key cache so an active probe
   2456 	 * is done. First the rrset so another thread does not use it
   2457 	 * to recreate the key entry in a race condition. */
   2458 	rrset_cache_remove(env->rrset_cache, qinfo.qname, qinfo.qname_len,
   2459 		qinfo.qtype, qinfo.qclass, 0);
   2460 	key_cache_remove(env->key_cache, qinfo.qname, qinfo.qname_len,
   2461 		qinfo.qclass);
   2462 
   2463 	if(!mesh_new_callback(env->mesh, &qinfo, qflags, &edns, buf, 0,
   2464 		&probe_answer_cb, env, 0, NULL)) {
   2465 		log_err("out of memory making 5011 probe");
   2466 	}
   2467 }
   2468 
   2469 /** fetch first to-probe trust-anchor and lock it and set retrytime */
   2470 static struct trust_anchor*
   2471 todo_probe(struct module_env* env, time_t* next)
   2472 {
   2473 	struct trust_anchor* tp;
   2474 	rbnode_type* el;
   2475 	/* get first one */
   2476 	lock_basic_lock(&env->anchors->lock);
   2477 	if( (el=rbtree_first(&env->anchors->autr->probe)) == RBTREE_NULL) {
   2478 		/* in case of revoked anchors */
   2479 		lock_basic_unlock(&env->anchors->lock);
   2480 		/* signal that there are no anchors to probe */
   2481 		*next = 0;
   2482 		return NULL;
   2483 	}
   2484 	tp = (struct trust_anchor*)el->key;
   2485 	lock_basic_lock(&tp->lock);
   2486 
   2487 	/* is it eligible? */
   2488 	if((time_t)tp->autr->next_probe_time > *env->now) {
   2489 		/* no more to probe */
   2490 		*next = (time_t)tp->autr->next_probe_time - *env->now;
   2491 		lock_basic_unlock(&tp->lock);
   2492 		lock_basic_unlock(&env->anchors->lock);
   2493 		return NULL;
   2494 	}
   2495 
   2496 	/* reset its next probe time */
   2497 	(void)rbtree_delete(&env->anchors->autr->probe, tp);
   2498 	tp->autr->next_probe_time = calc_next_probe(env, tp->autr->retry_time);
   2499 	(void)rbtree_insert(&env->anchors->autr->probe, &tp->autr->pnode);
   2500 	lock_basic_unlock(&env->anchors->lock);
   2501 
   2502 	return tp;
   2503 }
   2504 
   2505 time_t
   2506 autr_probe_timer(struct module_env* env)
   2507 {
   2508 	struct trust_anchor* tp;
   2509 	time_t next_probe = 3600;
   2510 	int num = 0;
   2511 	if(autr_permit_small_holddown) next_probe = 1;
   2512 	verbose(VERB_ALGO, "autotrust probe timer callback");
   2513 	/* while there are still anchors to probe */
   2514 	while( (tp = todo_probe(env, &next_probe)) ) {
   2515 		/* make a probe for this anchor */
   2516 		probe_anchor(env, tp);
   2517 		num++;
   2518 	}
   2519 	regional_free_all(env->scratch);
   2520 	if(next_probe == 0)
   2521 		return 0; /* no trust points to probe */
   2522 	verbose(VERB_ALGO, "autotrust probe timer %d callbacks done", num);
   2523 	return next_probe;
   2524 }
   2525