xref: /freebsd/contrib/unbound/validator/autotrust.c (revision 7a789145f88a6aceacc59029a0cafe7de7aeefea)
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 
autr_global_create(void)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 
autr_global_delete(struct autr_global_data * global)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 
probetree_cmp(const void * x,const void * y)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
autr_get_num_anchors(struct val_anchors * anchors)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
position_in_string(char * str,const char * sub)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
verbose_key(struct autr_ta * ta,enum verbosity_value level,const char * format,...)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
parse_comments(char * str,struct autr_ta * ta,int header_seen)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
str_contains_data(char * str,char comment)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
dnskey_flags(uint16_t t,uint8_t * rdata,size_t len)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
rr_is_dnskey_sep(uint16_t t,uint8_t * rdata,size_t len)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
ta_is_dnskey_sep(struct autr_ta * ta)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
rr_is_dnskey_revoked(uint16_t t,uint8_t * rdata,size_t len)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*
autr_ta_create(uint8_t * rr,size_t rr_len,size_t dname_len)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*
autr_tp_create(struct val_anchors * anchors,uint8_t * own,size_t own_len,uint16_t dc)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
autr_rrset_delete(struct ub_packed_rrset_key * r)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
autr_ta_delete(struct autr_ta * ta)406 autr_ta_delete(struct autr_ta* ta)
407 {
408 	if(!ta) return;
409 	free(ta->rr);
410 	free(ta);
411 }
412 
autr_point_delete(struct trust_anchor * tp)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*
find_add_tp(struct val_anchors * anchors,uint8_t * rr,size_t rr_len,size_t dname_len)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*
add_trustanchor_frm_rr(struct val_anchors * anchors,uint8_t * rr,size_t rr_len,size_t dname_len,struct trust_anchor ** tp)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*
add_trustanchor_frm_str(struct val_anchors * anchors,char * str,struct trust_anchor ** tp,uint8_t * origin,size_t origin_len,uint8_t ** prev,size_t * prev_len,int * skip)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*
load_trustanchor(struct val_anchors * anchors,char * str,const char * fname,uint8_t * origin,size_t origin_len,uint8_t ** prev,size_t * prev_len,int * skip,int header_seen)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
assemble_iterate_ds(struct autr_ta ** list,uint8_t ** rr,size_t * rr_len,size_t * dname_len)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
assemble_iterate_dnskey(struct autr_ta ** list,uint8_t ** rr,size_t * rr_len,size_t * dname_len)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
assemble_iterate_hasfirst(int iter (struct autr_ta **,uint8_t **,size_t *,size_t *),struct autr_ta * list)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
assemble_iterate_count(int iter (struct autr_ta **,uint8_t **,size_t *,size_t *),struct autr_ta * list)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*
ub_packed_rrset_heap_key(int iter (struct autr_ta **,uint8_t **,size_t *,size_t *),struct autr_ta * list)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*
packed_rrset_heap_data(int iter (struct autr_ta **,uint8_t **,size_t *,size_t *),struct autr_ta * list)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
autr_assemble(struct trust_anchor * tp)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
parse_int(char * line,int * ret)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*
parse_id(struct val_anchors * anchors,char * line)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
parse_var_line(char * line,struct val_anchors * anchors,struct trust_anchor ** anchor,int * header_seen,const char * nm)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
handle_origin(char * line,uint8_t ** origin,size_t * origin_len)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
read_multiline(char * buf,size_t len,FILE * in,int * linenr)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 
autr_read_file(struct val_anchors * anchors,const char * nm)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*
trustanchor_state2str(autr_state_type s)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 */
autr_ctime_r(time_t * t,char * s)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
print_id(FILE * out,char * fname,uint8_t * nm,size_t nmlen,uint16_t dclass)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
autr_write_contents(FILE * out,char * fn,struct trust_anchor * tp)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 
autr_write_file(struct module_env * env,struct trust_anchor * tp)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  * @return false on failure, true if verification successful.
1301  */
1302 static int
verify_dnskey(struct module_env * env,struct val_env * ve,struct trust_anchor * tp,struct ub_packed_rrset_key * rrset,struct module_qstate * qstate)1303 verify_dnskey(struct module_env* env, struct val_env* ve,
1304         struct trust_anchor* tp, struct ub_packed_rrset_key* rrset,
1305 	struct module_qstate* qstate)
1306 {
1307 	char reasonbuf[256];
1308 	char* reason = NULL;
1309 	uint8_t sigalg[ALGO_NEEDS_MAX+1];
1310 	int downprot = env->cfg->harden_algo_downgrade;
1311 	enum sec_status sec = val_verify_DNSKEY_with_TA(env, ve, rrset,
1312 		tp->ds_rrset, tp->dnskey_rrset, downprot?sigalg:NULL, &reason,
1313 		NULL, qstate, reasonbuf, sizeof(reasonbuf));
1314 	/* sigalg is ignored, it returns algorithms signalled to exist, but
1315 	 * in 5011 there are no other rrsets to check.  if downprot is
1316 	 * enabled, then it checks that the DNSKEY is signed with all
1317 	 * algorithms available in the trust store. */
1318 	verbose(VERB_ALGO, "autotrust: validate DNSKEY with anchor: %s",
1319 		sec_status_to_string(sec));
1320 	return sec == sec_status_secure;
1321 }
1322 
1323 static int32_t
rrsig_get_expiry(uint8_t * d,size_t len)1324 rrsig_get_expiry(uint8_t* d, size_t len)
1325 {
1326 	/* rrsig: 2(rdlen), 2(type) 1(alg) 1(v) 4(origttl), then 4(expi), (4)incep) */
1327 	if(len < 2+8+4)
1328 		return 0;
1329 	return sldns_read_uint32(d+2+8);
1330 }
1331 
1332 /** Find minimum expiration interval from signatures */
1333 static time_t
min_expiry(struct module_env * env,struct packed_rrset_data * dd)1334 min_expiry(struct module_env* env, struct packed_rrset_data* dd)
1335 {
1336 	size_t i;
1337 	int32_t t, r = 15 * 24 * 3600; /* 15 days max */
1338 	for(i=dd->count; i<dd->count+dd->rrsig_count; i++) {
1339 		t = rrsig_get_expiry(dd->rr_data[i], dd->rr_len[i]);
1340 		if((int32_t)t - (int32_t)*env->now > 0) {
1341 			t -= (int32_t)*env->now;
1342 			if(t < r)
1343 				r = t;
1344 		}
1345 	}
1346 	return (time_t)r;
1347 }
1348 
1349 /** Is rr self-signed revoked key */
1350 static int
rr_is_selfsigned_revoked(struct module_env * env,struct val_env * ve,struct ub_packed_rrset_key * dnskey_rrset,size_t i,struct module_qstate * qstate)1351 rr_is_selfsigned_revoked(struct module_env* env, struct val_env* ve,
1352 	struct ub_packed_rrset_key* dnskey_rrset, size_t i,
1353 	struct module_qstate* qstate)
1354 {
1355 	enum sec_status sec;
1356 	char* reason = NULL;
1357 	verbose(VERB_ALGO, "seen REVOKE flag, check self-signed, rr %d",
1358 		(int)i);
1359 	/* no algorithm downgrade protection necessary, if it is selfsigned
1360 	 * revoked it can be removed. */
1361 	sec = dnskey_verify_rrset(env, ve, dnskey_rrset, dnskey_rrset, i,
1362 		&reason, NULL, LDNS_SECTION_ANSWER, qstate);
1363 	return (sec == sec_status_secure);
1364 }
1365 
1366 /** Set fetched value */
1367 static void
seen_trustanchor(struct autr_ta * ta,uint8_t seen)1368 seen_trustanchor(struct autr_ta* ta, uint8_t seen)
1369 {
1370 	ta->fetched = seen;
1371 	if(ta->pending_count < 250) /* no numerical overflow, please */
1372 		ta->pending_count++;
1373 }
1374 
1375 /** set revoked value */
1376 static void
seen_revoked_trustanchor(struct autr_ta * ta,uint8_t revoked)1377 seen_revoked_trustanchor(struct autr_ta* ta, uint8_t revoked)
1378 {
1379 	ta->revoked = revoked;
1380 }
1381 
1382 /** revoke a trust anchor */
1383 static void
revoke_dnskey(struct autr_ta * ta,int off)1384 revoke_dnskey(struct autr_ta* ta, int off)
1385 {
1386 	uint16_t flags;
1387 	uint8_t* data;
1388 	if(sldns_wirerr_get_type(ta->rr, ta->rr_len, ta->dname_len) !=
1389 		LDNS_RR_TYPE_DNSKEY)
1390 		return;
1391 	if(sldns_wirerr_get_rdatalen(ta->rr, ta->rr_len, ta->dname_len) < 2)
1392 		return;
1393 	data = sldns_wirerr_get_rdata(ta->rr, ta->rr_len, ta->dname_len);
1394 	flags = sldns_read_uint16(data);
1395 	if (off && (flags&LDNS_KEY_REVOKE_KEY))
1396 		flags ^= LDNS_KEY_REVOKE_KEY; /* flip */
1397 	else
1398 		flags |= LDNS_KEY_REVOKE_KEY;
1399 	sldns_write_uint16(data, flags);
1400 }
1401 
1402 /** Compare two RRs skipping the REVOKED bit. Pass rdata(no len) */
1403 static int
dnskey_compare_skip_revbit(uint8_t * a,size_t a_len,uint8_t * b,size_t b_len)1404 dnskey_compare_skip_revbit(uint8_t* a, size_t a_len, uint8_t* b, size_t b_len)
1405 {
1406 	size_t i;
1407 	if(a_len != b_len)
1408 		return -1;
1409 	/* compare RRs RDATA byte for byte. */
1410 	for(i = 0; i < a_len; i++)
1411 	{
1412 		uint8_t rdf1, rdf2;
1413 		rdf1 = a[i];
1414 		rdf2 = b[i];
1415 		if(i==1) {
1416 			/* this is the second part of the flags field */
1417 			rdf1 |= LDNS_KEY_REVOKE_KEY;
1418 			rdf2 |= LDNS_KEY_REVOKE_KEY;
1419 		}
1420 		if (rdf1 < rdf2)	return -1;
1421 		else if (rdf1 > rdf2)	return 1;
1422         }
1423 	return 0;
1424 }
1425 
1426 
1427 /** compare trust anchor with rdata, 0 if equal. Pass rdata(no len) */
1428 static int
ta_compare(struct autr_ta * a,uint16_t t,uint8_t * b,size_t b_len)1429 ta_compare(struct autr_ta* a, uint16_t t, uint8_t* b, size_t b_len)
1430 {
1431 	if(!a) return -1;
1432 	else if(!b) return -1;
1433 	else if(sldns_wirerr_get_type(a->rr, a->rr_len, a->dname_len) != t)
1434 		return (int)sldns_wirerr_get_type(a->rr, a->rr_len,
1435 			a->dname_len) - (int)t;
1436 	else if(t == LDNS_RR_TYPE_DNSKEY) {
1437 		return dnskey_compare_skip_revbit(
1438 			sldns_wirerr_get_rdata(a->rr, a->rr_len, a->dname_len),
1439 			sldns_wirerr_get_rdatalen(a->rr, a->rr_len,
1440 			a->dname_len), b, b_len);
1441 	}
1442 	else if(t == LDNS_RR_TYPE_DS) {
1443 		if(sldns_wirerr_get_rdatalen(a->rr, a->rr_len, a->dname_len) !=
1444 			b_len)
1445 			return -1;
1446 		return memcmp(sldns_wirerr_get_rdata(a->rr,
1447 			a->rr_len, a->dname_len), b, b_len);
1448 	}
1449 	return -1;
1450 }
1451 
1452 /**
1453  * Find key
1454  * @param tp: to search in
1455  * @param t: rr type of the rdata.
1456  * @param rdata: to look for  (no rdatalen in it)
1457  * @param rdata_len: length of rdata
1458  * @param result: returns NULL or the ta key looked for.
1459  * @return false on malloc failure during search. if true examine result.
1460  */
1461 static int
find_key(struct trust_anchor * tp,uint16_t t,uint8_t * rdata,size_t rdata_len,struct autr_ta ** result)1462 find_key(struct trust_anchor* tp, uint16_t t, uint8_t* rdata, size_t rdata_len,
1463 	struct autr_ta** result)
1464 {
1465 	struct autr_ta* ta;
1466 	if(!tp || !rdata) {
1467 		*result = NULL;
1468 		return 0;
1469 	}
1470 	for(ta=tp->autr->keys; ta; ta=ta->next) {
1471 		if(ta_compare(ta, t, rdata, rdata_len) == 0) {
1472 			*result = ta;
1473 			return 1;
1474 		}
1475 	}
1476 	*result = NULL;
1477 	return 1;
1478 }
1479 
1480 /** add key and clone RR and tp already locked. rdata without rdlen. */
1481 static struct autr_ta*
add_key(struct trust_anchor * tp,uint32_t ttl,uint8_t * rdata,size_t rdata_len)1482 add_key(struct trust_anchor* tp, uint32_t ttl, uint8_t* rdata, size_t rdata_len)
1483 {
1484 	struct autr_ta* ta;
1485 	uint8_t* rr;
1486 	size_t rr_len, dname_len;
1487 	uint16_t rrtype = htons(LDNS_RR_TYPE_DNSKEY);
1488 	uint16_t rrclass = htons(LDNS_RR_CLASS_IN);
1489 	uint16_t rdlen = htons(rdata_len);
1490 	dname_len = tp->namelen;
1491 	ttl = htonl(ttl);
1492 	rr_len = dname_len + 10 /* type,class,ttl,rdatalen */ + rdata_len;
1493 	rr = (uint8_t*)malloc(rr_len);
1494 	if(!rr) return NULL;
1495 	memmove(rr, tp->name, tp->namelen);
1496 	memmove(rr+dname_len, &rrtype, 2);
1497 	memmove(rr+dname_len+2, &rrclass, 2);
1498 	memmove(rr+dname_len+4, &ttl, 4);
1499 	memmove(rr+dname_len+8, &rdlen, 2);
1500 	memmove(rr+dname_len+10, rdata, rdata_len);
1501 	ta = autr_ta_create(rr, rr_len, dname_len);
1502 	if(!ta) {
1503 		/* rr freed in autr_ta_create */
1504 		return NULL;
1505 	}
1506 	/* link in, tp already locked */
1507 	ta->next = tp->autr->keys;
1508 	tp->autr->keys = ta;
1509 	return ta;
1510 }
1511 
1512 /** get TTL from DNSKEY rrset */
1513 static time_t
key_ttl(struct ub_packed_rrset_key * k)1514 key_ttl(struct ub_packed_rrset_key* k)
1515 {
1516 	struct packed_rrset_data* d = (struct packed_rrset_data*)k->entry.data;
1517 	return d->ttl;
1518 }
1519 
1520 /** update the time values for the trustpoint */
1521 static void
set_tp_times(struct trust_anchor * tp,time_t rrsig_exp_interval,time_t origttl,int * changed)1522 set_tp_times(struct trust_anchor* tp, time_t rrsig_exp_interval,
1523 	time_t origttl, int* changed)
1524 {
1525 	time_t x, qi = tp->autr->query_interval, rt = tp->autr->retry_time;
1526 
1527 	/* x = MIN(15days, ttl/2, expire/2) */
1528 	x = 15 * 24 * 3600;
1529 	if(origttl/2 < x)
1530 		x = origttl/2;
1531 	if(rrsig_exp_interval/2 < x)
1532 		x = rrsig_exp_interval/2;
1533 	/* MAX(1hr, x) */
1534 	if(!autr_permit_small_holddown) {
1535 		if(x < 3600)
1536 			tp->autr->query_interval = 3600;
1537 		else	tp->autr->query_interval = x;
1538 	}	else    tp->autr->query_interval = x;
1539 
1540 	/* x= MIN(1day, ttl/10, expire/10) */
1541 	x = 24 * 3600;
1542 	if(origttl/10 < x)
1543 		x = origttl/10;
1544 	if(rrsig_exp_interval/10 < x)
1545 		x = rrsig_exp_interval/10;
1546 	/* MAX(1hr, x) */
1547 	if(!autr_permit_small_holddown) {
1548 		if(x < 3600)
1549 			tp->autr->retry_time = 3600;
1550 		else	tp->autr->retry_time = x;
1551 	}	else    tp->autr->retry_time = x;
1552 
1553 	if(qi != tp->autr->query_interval || rt != tp->autr->retry_time) {
1554 		*changed = 1;
1555 		verbose(VERB_ALGO, "orig_ttl is %d", (int)origttl);
1556 		verbose(VERB_ALGO, "rrsig_exp_interval is %d",
1557 			(int)rrsig_exp_interval);
1558 		verbose(VERB_ALGO, "query_interval: %d, retry_time: %d",
1559 			(int)tp->autr->query_interval,
1560 			(int)tp->autr->retry_time);
1561 	}
1562 }
1563 
1564 /** init events to zero */
1565 static void
init_events(struct trust_anchor * tp)1566 init_events(struct trust_anchor* tp)
1567 {
1568 	struct autr_ta* ta;
1569 	for(ta=tp->autr->keys; ta; ta=ta->next) {
1570 		ta->fetched = 0;
1571 	}
1572 }
1573 
1574 /** check for revoked keys without trusting any other information */
1575 static void
check_contains_revoked(struct module_env * env,struct val_env * ve,struct trust_anchor * tp,struct ub_packed_rrset_key * dnskey_rrset,int * changed,struct module_qstate * qstate)1576 check_contains_revoked(struct module_env* env, struct val_env* ve,
1577 	struct trust_anchor* tp, struct ub_packed_rrset_key* dnskey_rrset,
1578 	int* changed, struct module_qstate* qstate)
1579 {
1580 	struct packed_rrset_data* dd = (struct packed_rrset_data*)
1581 		dnskey_rrset->entry.data;
1582 	size_t i;
1583 	log_assert(ntohs(dnskey_rrset->rk.type) == LDNS_RR_TYPE_DNSKEY);
1584 	for(i=0; i<dd->count; i++) {
1585 		struct autr_ta* ta = NULL;
1586 		if(!rr_is_dnskey_sep(ntohs(dnskey_rrset->rk.type),
1587 			dd->rr_data[i]+2, dd->rr_len[i]-2) ||
1588 			!rr_is_dnskey_revoked(ntohs(dnskey_rrset->rk.type),
1589 			dd->rr_data[i]+2, dd->rr_len[i]-2))
1590 			continue; /* not a revoked KSK */
1591 		if(!find_key(tp, ntohs(dnskey_rrset->rk.type),
1592 			dd->rr_data[i]+2, dd->rr_len[i]-2, &ta)) {
1593 			log_err("malloc failure");
1594 			continue; /* malloc fail in compare*/
1595 		}
1596 		if(!ta)
1597 			continue; /* key not found */
1598 		if(rr_is_selfsigned_revoked(env, ve, dnskey_rrset, i, qstate)) {
1599 			/* checked if there is an rrsig signed by this key. */
1600 			/* same keytag, but stored can be revoked already, so
1601 			 * compare keytags, with +0 or +128(REVOKE flag) */
1602 			log_assert(dnskey_calc_keytag(dnskey_rrset, i)-128 ==
1603 				sldns_calc_keytag_raw(sldns_wirerr_get_rdata(
1604 				ta->rr, ta->rr_len, ta->dname_len),
1605 				sldns_wirerr_get_rdatalen(ta->rr, ta->rr_len,
1606 				ta->dname_len)) ||
1607 				dnskey_calc_keytag(dnskey_rrset, i) ==
1608 				sldns_calc_keytag_raw(sldns_wirerr_get_rdata(
1609 				ta->rr, ta->rr_len, ta->dname_len),
1610 				sldns_wirerr_get_rdatalen(ta->rr, ta->rr_len,
1611 				ta->dname_len))); /* checks conversion*/
1612 			verbose_key(ta, VERB_ALGO, "is self-signed revoked");
1613 			if(!ta->revoked)
1614 				*changed = 1;
1615 			seen_revoked_trustanchor(ta, 1);
1616 			do_revoked(env, ta, changed);
1617 		}
1618 	}
1619 }
1620 
1621 /** See if a DNSKEY is verified by one of the DSes */
1622 static int
key_matches_a_ds(struct module_env * env,struct val_env * ve,struct ub_packed_rrset_key * dnskey_rrset,size_t key_idx,struct ub_packed_rrset_key * ds_rrset)1623 key_matches_a_ds(struct module_env* env, struct val_env* ve,
1624 	struct ub_packed_rrset_key* dnskey_rrset, size_t key_idx,
1625 	struct ub_packed_rrset_key* ds_rrset)
1626 {
1627 	struct packed_rrset_data* dd = (struct packed_rrset_data*)
1628 	                ds_rrset->entry.data;
1629 	size_t ds_idx, num = dd->count;
1630 	int d = val_favorite_ds_algo(ds_rrset);
1631 	char* reason = "";
1632 	for(ds_idx=0; ds_idx<num; ds_idx++) {
1633 		if(!ds_digest_algo_is_supported(ds_rrset, ds_idx) ||
1634 			!ds_key_algo_is_supported(ds_rrset, ds_idx) ||
1635 			!dnskey_size_is_supported(dnskey_rrset, key_idx) ||
1636 			ds_get_digest_algo(ds_rrset, ds_idx) != d)
1637 			continue;
1638 		if(ds_get_key_algo(ds_rrset, ds_idx)
1639 		   != dnskey_get_algo(dnskey_rrset, key_idx)
1640 		   || dnskey_calc_keytag(dnskey_rrset, key_idx)
1641 		   != ds_get_keytag(ds_rrset, ds_idx)) {
1642 			continue;
1643 		}
1644 		if(!ds_digest_match_dnskey(env, dnskey_rrset, key_idx,
1645 			ds_rrset, ds_idx)) {
1646 			verbose(VERB_ALGO, "DS match attempt failed");
1647 			continue;
1648 		}
1649 		/* match of hash is sufficient for bootstrap of trust point */
1650 		(void)reason;
1651 		(void)ve;
1652 		return 1;
1653 		/* no need to check RRSIG, DS hash already matched with source
1654 		if(dnskey_verify_rrset(env, ve, dnskey_rrset,
1655 			dnskey_rrset, key_idx, &reason) == sec_status_secure) {
1656 			return 1;
1657 		} else {
1658 			verbose(VERB_ALGO, "DS match failed because the key "
1659 				"does not verify the keyset: %s", reason);
1660 		}
1661 		*/
1662 	}
1663 	return 0;
1664 }
1665 
1666 /** Set update events */
1667 static int
update_events(struct module_env * env,struct val_env * ve,struct trust_anchor * tp,struct ub_packed_rrset_key * dnskey_rrset,int * changed)1668 update_events(struct module_env* env, struct val_env* ve,
1669 	struct trust_anchor* tp, struct ub_packed_rrset_key* dnskey_rrset,
1670 	int* changed)
1671 {
1672 	struct packed_rrset_data* dd = (struct packed_rrset_data*)
1673 		dnskey_rrset->entry.data;
1674 	size_t i;
1675 	log_assert(ntohs(dnskey_rrset->rk.type) == LDNS_RR_TYPE_DNSKEY);
1676 	init_events(tp);
1677 	for(i=0; i<dd->count; i++) {
1678 		struct autr_ta* ta = NULL;
1679 		if(!rr_is_dnskey_sep(ntohs(dnskey_rrset->rk.type),
1680 			dd->rr_data[i]+2, dd->rr_len[i]-2))
1681 			continue;
1682 		if(rr_is_dnskey_revoked(ntohs(dnskey_rrset->rk.type),
1683 			dd->rr_data[i]+2, dd->rr_len[i]-2)) {
1684 			/* self-signed revoked keys already detected before,
1685 			 * other revoked keys are not 'added' again */
1686 			continue;
1687 		}
1688 		/* is a key of this type supported?. Note rr_list and
1689 		 * packed_rrset are in the same order. */
1690 		if(!dnskey_algo_is_supported(dnskey_rrset, i) ||
1691 			!dnskey_size_is_supported(dnskey_rrset, i)) {
1692 			/* skip unknown algorithm key, it is useless to us */
1693 			log_nametypeclass(VERB_DETAIL, "trust point has "
1694 				"unsupported algorithm at",
1695 				tp->name, LDNS_RR_TYPE_DNSKEY, tp->dclass);
1696 			continue;
1697 		}
1698 
1699 		/* is it new? if revocation bit set, find the unrevoked key */
1700 		if(!find_key(tp, ntohs(dnskey_rrset->rk.type),
1701 			dd->rr_data[i]+2, dd->rr_len[i]-2, &ta)) {
1702 			return 0;
1703 		}
1704 		if(!ta) {
1705 			ta = add_key(tp, (uint32_t)dd->rr_ttl[i],
1706 				dd->rr_data[i]+2, dd->rr_len[i]-2);
1707 			*changed = 1;
1708 			/* first time seen, do we have DSes? if match: VALID */
1709 			if(ta && tp->ds_rrset && key_matches_a_ds(env, ve,
1710 				dnskey_rrset, i, tp->ds_rrset)) {
1711 				verbose_key(ta, VERB_ALGO, "verified by DS");
1712 				ta->s = AUTR_STATE_VALID;
1713 			}
1714 		}
1715 		if(!ta) {
1716 			return 0;
1717 		}
1718 		seen_trustanchor(ta, 1);
1719 		verbose_key(ta, VERB_ALGO, "in DNS response");
1720 	}
1721 	set_tp_times(tp, min_expiry(env, dd), key_ttl(dnskey_rrset), changed);
1722 	return 1;
1723 }
1724 
1725 /**
1726  * Check if the holddown time has already exceeded
1727  * setting: add-holddown: add holddown timer
1728  * setting: del-holddown: del holddown timer
1729  * @param env: environment with current time
1730  * @param ta: trust anchor to check for.
1731  * @param holddown: the timer value
1732  * @return number of seconds the holddown has passed.
1733  */
1734 static time_t
check_holddown(struct module_env * env,struct autr_ta * ta,unsigned int holddown)1735 check_holddown(struct module_env* env, struct autr_ta* ta,
1736 	unsigned int holddown)
1737 {
1738         time_t elapsed;
1739 	if(*env->now < ta->last_change) {
1740 		log_warn("time goes backwards. delaying key holddown");
1741 		return 0;
1742 	}
1743 	elapsed = *env->now - ta->last_change;
1744         if (elapsed > (time_t)holddown) {
1745                 return elapsed-(time_t)holddown;
1746         }
1747 	verbose_key(ta, VERB_ALGO, "holddown time " ARG_LL "d seconds to go",
1748 		(long long) ((time_t)holddown-elapsed));
1749         return 0;
1750 }
1751 
1752 
1753 /** Set last_change to now */
1754 static void
reset_holddown(struct module_env * env,struct autr_ta * ta,int * changed)1755 reset_holddown(struct module_env* env, struct autr_ta* ta, int* changed)
1756 {
1757 	ta->last_change = *env->now;
1758 	*changed = 1;
1759 }
1760 
1761 /** Set the state for this trust anchor */
1762 static void
set_trustanchor_state(struct module_env * env,struct autr_ta * ta,int * changed,autr_state_type s)1763 set_trustanchor_state(struct module_env* env, struct autr_ta* ta, int* changed,
1764 	autr_state_type s)
1765 {
1766 	verbose_key(ta, VERB_ALGO, "update: %s to %s",
1767 		trustanchor_state2str(ta->s), trustanchor_state2str(s));
1768 	ta->s = s;
1769 	reset_holddown(env, ta, changed);
1770 }
1771 
1772 
1773 /** Event: NewKey */
1774 static void
do_newkey(struct module_env * env,struct autr_ta * anchor,int * c)1775 do_newkey(struct module_env* env, struct autr_ta* anchor, int* c)
1776 {
1777 	if (anchor->s == AUTR_STATE_START)
1778 		set_trustanchor_state(env, anchor, c, AUTR_STATE_ADDPEND);
1779 }
1780 
1781 /** Event: AddTime */
1782 static void
do_addtime(struct module_env * env,struct autr_ta * anchor,int * c)1783 do_addtime(struct module_env* env, struct autr_ta* anchor, int* c)
1784 {
1785 	/* This not according to RFC, this is 30 days, but the RFC demands
1786 	 * MAX(30days, TTL expire time of first DNSKEY set with this key),
1787 	 * The value may be too small if a very large TTL was used. */
1788 	time_t exceeded = check_holddown(env, anchor, env->cfg->add_holddown);
1789 	if (exceeded && anchor->s == AUTR_STATE_ADDPEND) {
1790 		verbose_key(anchor, VERB_ALGO, "add-holddown time exceeded "
1791 			ARG_LL "d seconds ago, and pending-count %d",
1792 			(long long)exceeded, anchor->pending_count);
1793 		if(anchor->pending_count >= MIN_PENDINGCOUNT) {
1794 			set_trustanchor_state(env, anchor, c, AUTR_STATE_VALID);
1795 			anchor->pending_count = 0;
1796 			return;
1797 		}
1798 		verbose_key(anchor, VERB_ALGO, "add-holddown time sanity check "
1799 			"failed (pending count: %d)", anchor->pending_count);
1800 	}
1801 }
1802 
1803 /** Event: RemTime */
1804 static void
do_remtime(struct module_env * env,struct autr_ta * anchor,int * c)1805 do_remtime(struct module_env* env, struct autr_ta* anchor, int* c)
1806 {
1807 	time_t exceeded = check_holddown(env, anchor, env->cfg->del_holddown);
1808 	if(exceeded && anchor->s == AUTR_STATE_REVOKED) {
1809 		verbose_key(anchor, VERB_ALGO, "del-holddown time exceeded "
1810 			ARG_LL "d seconds ago", (long long)exceeded);
1811 		set_trustanchor_state(env, anchor, c, AUTR_STATE_REMOVED);
1812 	}
1813 }
1814 
1815 /** Event: KeyRem */
1816 static void
do_keyrem(struct module_env * env,struct autr_ta * anchor,int * c)1817 do_keyrem(struct module_env* env, struct autr_ta* anchor, int* c)
1818 {
1819 	if(anchor->s == AUTR_STATE_ADDPEND) {
1820 		set_trustanchor_state(env, anchor, c, AUTR_STATE_START);
1821 		anchor->pending_count = 0;
1822 	} else if(anchor->s == AUTR_STATE_VALID)
1823 		set_trustanchor_state(env, anchor, c, AUTR_STATE_MISSING);
1824 }
1825 
1826 /** Event: KeyPres */
1827 static void
do_keypres(struct module_env * env,struct autr_ta * anchor,int * c)1828 do_keypres(struct module_env* env, struct autr_ta* anchor, int* c)
1829 {
1830 	if(anchor->s == AUTR_STATE_MISSING)
1831 		set_trustanchor_state(env, anchor, c, AUTR_STATE_VALID);
1832 }
1833 
1834 /* Event: Revoked */
1835 static void
do_revoked(struct module_env * env,struct autr_ta * anchor,int * c)1836 do_revoked(struct module_env* env, struct autr_ta* anchor, int* c)
1837 {
1838 	if(anchor->s == AUTR_STATE_VALID || anchor->s == AUTR_STATE_MISSING) {
1839                 set_trustanchor_state(env, anchor, c, AUTR_STATE_REVOKED);
1840 		verbose_key(anchor, VERB_ALGO, "old id, prior to revocation");
1841                 revoke_dnskey(anchor, 0);
1842 		verbose_key(anchor, VERB_ALGO, "new id, after revocation");
1843 	}
1844 }
1845 
1846 /** Do statestable transition matrix for anchor */
1847 static void
anchor_state_update(struct module_env * env,struct autr_ta * anchor,int * c)1848 anchor_state_update(struct module_env* env, struct autr_ta* anchor, int* c)
1849 {
1850 	log_assert(anchor);
1851 	switch(anchor->s) {
1852 	/* START */
1853 	case AUTR_STATE_START:
1854 		/* NewKey: ADDPEND */
1855 		if (anchor->fetched)
1856 			do_newkey(env, anchor, c);
1857 		break;
1858 	/* ADDPEND */
1859 	case AUTR_STATE_ADDPEND:
1860 		/* KeyRem: START */
1861 		if (!anchor->fetched)
1862 			do_keyrem(env, anchor, c);
1863 		/* AddTime: VALID */
1864 		else	do_addtime(env, anchor, c);
1865 		break;
1866 	/* VALID */
1867 	case AUTR_STATE_VALID:
1868 		/* RevBit: REVOKED */
1869 		if (anchor->revoked)
1870 			do_revoked(env, anchor, c);
1871 		/* KeyRem: MISSING */
1872 		else if (!anchor->fetched)
1873 			do_keyrem(env, anchor, c);
1874 		else if(!anchor->last_change) {
1875 			verbose_key(anchor, VERB_ALGO, "first seen");
1876 			reset_holddown(env, anchor, c);
1877 		}
1878 		break;
1879 	/* MISSING */
1880 	case AUTR_STATE_MISSING:
1881 		/* RevBit: REVOKED */
1882 		if (anchor->revoked)
1883 			do_revoked(env, anchor, c);
1884 		/* KeyPres */
1885 		else if (anchor->fetched)
1886 			do_keypres(env, anchor, c);
1887 		break;
1888 	/* REVOKED */
1889 	case AUTR_STATE_REVOKED:
1890 		if (anchor->fetched)
1891 			reset_holddown(env, anchor, c);
1892 		/* RemTime: REMOVED */
1893 		else	do_remtime(env, anchor, c);
1894 		break;
1895 	/* REMOVED */
1896 	case AUTR_STATE_REMOVED:
1897 	default:
1898 		break;
1899 	}
1900 }
1901 
1902 /** if ZSK init then trust KSKs */
1903 static int
init_zsk_to_ksk(struct module_env * env,struct trust_anchor * tp,int * changed)1904 init_zsk_to_ksk(struct module_env* env, struct trust_anchor* tp, int* changed)
1905 {
1906 	/* search for VALID ZSKs */
1907 	struct autr_ta* anchor;
1908 	int validzsk = 0;
1909 	int validksk = 0;
1910 	for(anchor = tp->autr->keys; anchor; anchor = anchor->next) {
1911 		/* last_change test makes sure it was manually configured */
1912 		if(sldns_wirerr_get_type(anchor->rr, anchor->rr_len,
1913 			anchor->dname_len) == LDNS_RR_TYPE_DNSKEY &&
1914 			anchor->last_change == 0 &&
1915 			!ta_is_dnskey_sep(anchor) &&
1916 			anchor->s == AUTR_STATE_VALID)
1917                         validzsk++;
1918 	}
1919 	if(validzsk == 0)
1920 		return 0;
1921 	for(anchor = tp->autr->keys; anchor; anchor = anchor->next) {
1922                 if (ta_is_dnskey_sep(anchor) &&
1923 			anchor->s == AUTR_STATE_ADDPEND) {
1924 			verbose_key(anchor, VERB_ALGO, "trust KSK from "
1925 				"ZSK(config)");
1926 			set_trustanchor_state(env, anchor, changed,
1927 				AUTR_STATE_VALID);
1928 			validksk++;
1929 		}
1930 	}
1931 	return validksk;
1932 }
1933 
1934 /** Remove missing trustanchors so the list does not grow forever */
1935 static void
remove_missing_trustanchors(struct module_env * env,struct trust_anchor * tp,int * changed)1936 remove_missing_trustanchors(struct module_env* env, struct trust_anchor* tp,
1937 	int* changed)
1938 {
1939 	struct autr_ta* anchor;
1940 	time_t exceeded;
1941 	int valid = 0;
1942 	/* see if we have anchors that are valid */
1943 	for(anchor = tp->autr->keys; anchor; anchor = anchor->next) {
1944 		/* Only do KSKs */
1945                 if (!ta_is_dnskey_sep(anchor))
1946                         continue;
1947                 if (anchor->s == AUTR_STATE_VALID)
1948                         valid++;
1949 	}
1950 	/* if there are no SEP Valid anchors, see if we started out with
1951 	 * a ZSK (last-change=0) anchor, which is VALID and there are KSKs
1952 	 * now that can be made valid.  Do this immediately because there
1953 	 * is no guarantee that the ZSKs get announced long enough.  Usually
1954 	 * this is immediately after init with a ZSK trusted, unless the domain
1955 	 * was not advertising any KSKs at all.  In which case we perfectly
1956 	 * track the zero number of KSKs. */
1957 	if(valid == 0) {
1958 		valid = init_zsk_to_ksk(env, tp, changed);
1959 		if(valid == 0)
1960 			return;
1961 	}
1962 
1963 	for(anchor = tp->autr->keys; anchor; anchor = anchor->next) {
1964 		/* ignore ZSKs if newly added */
1965 		if(anchor->s == AUTR_STATE_START)
1966 			continue;
1967 		/* remove ZSKs if a KSK is present */
1968                 if (!ta_is_dnskey_sep(anchor)) {
1969 			if(valid > 0) {
1970 				verbose_key(anchor, VERB_ALGO, "remove ZSK "
1971 					"[%d key(s) VALID]", valid);
1972 				set_trustanchor_state(env, anchor, changed,
1973 					AUTR_STATE_REMOVED);
1974 			}
1975                         continue;
1976 		}
1977                 /* Only do MISSING keys */
1978                 if (anchor->s != AUTR_STATE_MISSING)
1979                         continue;
1980 		if(env->cfg->keep_missing == 0)
1981 			continue; /* keep forever */
1982 
1983 		exceeded = check_holddown(env, anchor, env->cfg->keep_missing);
1984 		/* If keep_missing has exceeded and we still have more than
1985 		 * one valid KSK: remove missing trust anchor */
1986                 if (exceeded && valid > 0) {
1987 			verbose_key(anchor, VERB_ALGO, "keep-missing time "
1988 				"exceeded " ARG_LL "d seconds ago, [%d key(s) VALID]",
1989 				(long long)exceeded, valid);
1990 			set_trustanchor_state(env, anchor, changed,
1991 				AUTR_STATE_REMOVED);
1992 		}
1993 	}
1994 }
1995 
1996 /** Do the statetable from RFC5011 transition matrix */
1997 static int
do_statetable(struct module_env * env,struct trust_anchor * tp,int * changed)1998 do_statetable(struct module_env* env, struct trust_anchor* tp, int* changed)
1999 {
2000 	struct autr_ta* anchor;
2001 	for(anchor = tp->autr->keys; anchor; anchor = anchor->next) {
2002 		/* Only do KSKs */
2003 		if(!ta_is_dnskey_sep(anchor))
2004 			continue;
2005 		anchor_state_update(env, anchor, changed);
2006 	}
2007 	remove_missing_trustanchors(env, tp, changed);
2008 	return 1;
2009 }
2010 
2011 /** See if time alone makes ADDPEND to VALID transition */
2012 static void
autr_holddown_exceed(struct module_env * env,struct trust_anchor * tp,int * c)2013 autr_holddown_exceed(struct module_env* env, struct trust_anchor* tp, int* c)
2014 {
2015 	struct autr_ta* anchor;
2016 	for(anchor = tp->autr->keys; anchor; anchor = anchor->next) {
2017 		if(ta_is_dnskey_sep(anchor) &&
2018 			anchor->s == AUTR_STATE_ADDPEND)
2019 			do_addtime(env, anchor, c);
2020 	}
2021 }
2022 
2023 /** cleanup key list */
2024 static void
autr_cleanup_keys(struct trust_anchor * tp)2025 autr_cleanup_keys(struct trust_anchor* tp)
2026 {
2027 	struct autr_ta* p, **prevp;
2028 	prevp = &tp->autr->keys;
2029 	p = tp->autr->keys;
2030 	while(p) {
2031 		/* do we want to remove this key? */
2032 		if(p->s == AUTR_STATE_START || p->s == AUTR_STATE_REMOVED ||
2033 			sldns_wirerr_get_type(p->rr, p->rr_len, p->dname_len)
2034 			!= LDNS_RR_TYPE_DNSKEY) {
2035 			struct autr_ta* np = p->next;
2036 			/* remove */
2037 			autr_ta_delete(p);
2038 			/* snip and go to next item */
2039 			*prevp = np;
2040 			p = np;
2041 			continue;
2042 		}
2043 		/* remove pending counts if no longer pending */
2044 		if(p->s != AUTR_STATE_ADDPEND)
2045 			p->pending_count = 0;
2046 		prevp = &p->next;
2047 		p = p->next;
2048 	}
2049 }
2050 
2051 /** calculate next probe time */
2052 static time_t
calc_next_probe(struct module_env * env,time_t wait)2053 calc_next_probe(struct module_env* env, time_t wait)
2054 {
2055 	/* make it random, 90-100% */
2056 	time_t rnd, rest;
2057 	if(!autr_permit_small_holddown) {
2058 		if(wait < 3600)
2059 			wait = 3600;
2060 	} else {
2061 		if(wait == 0) wait = 1;
2062 	}
2063 	rnd = wait/10;
2064 	rest = wait-rnd;
2065 	rnd = (time_t)ub_random_max(env->rnd, (long int)rnd);
2066 	return (time_t)(*env->now + rest + rnd);
2067 }
2068 
2069 /** what is first probe time (anchors must be locked) */
2070 static time_t
wait_probe_time(struct val_anchors * anchors)2071 wait_probe_time(struct val_anchors* anchors)
2072 {
2073 	rbnode_type* t = rbtree_first(&anchors->autr->probe);
2074 	if(t != RBTREE_NULL)
2075 		return ((struct trust_anchor*)t->key)->autr->next_probe_time;
2076 	return 0;
2077 }
2078 
2079 /** reset worker timer, at the time from wait_probe_time. */
2080 static void
reset_worker_timer_at(struct module_env * env,time_t next)2081 reset_worker_timer_at(struct module_env* env, time_t next)
2082 {
2083 	struct timeval tv;
2084 #ifndef S_SPLINT_S
2085 	/* in case this is libunbound, no timer */
2086 	if(!env->probe_timer)
2087 		return;
2088 	if(next > *env->now)
2089 		tv.tv_sec = (time_t)(next - *env->now);
2090 	else	tv.tv_sec = 0;
2091 #else
2092 	(void)next;
2093 #endif
2094 	tv.tv_usec = 0;
2095 	comm_timer_set(env->probe_timer, &tv);
2096 	verbose(VERB_ALGO, "scheduled next probe in " ARG_LL "d sec", (long long)tv.tv_sec);
2097 }
2098 
2099 /** reset worker timer. This routine manages the locks on acquiring the
2100  * next time for the timer. */
2101 static void
reset_worker_timer(struct module_env * env)2102 reset_worker_timer(struct module_env* env)
2103 {
2104 	time_t next;
2105 	if(!env->anchors)
2106 		return;
2107 	lock_basic_lock(&env->anchors->lock);
2108 	next = wait_probe_time(env->anchors);
2109 	lock_basic_unlock(&env->anchors->lock);
2110 	reset_worker_timer_at(env, next);
2111 }
2112 
2113 /** set next probe for trust anchor */
2114 static int
set_next_probe(struct module_env * env,struct trust_anchor * tp,struct ub_packed_rrset_key * dnskey_rrset)2115 set_next_probe(struct module_env* env, struct trust_anchor* tp,
2116 	struct ub_packed_rrset_key* dnskey_rrset)
2117 {
2118 	struct trust_anchor key, *tp2;
2119 	time_t mold, mnew;
2120 	/* use memory allocated in rrset for temporary name storage */
2121 	key.node.key = &key;
2122 	key.name = dnskey_rrset->rk.dname;
2123 	key.namelen = dnskey_rrset->rk.dname_len;
2124 	key.namelabs = dname_count_labels(key.name);
2125 	key.dclass = tp->dclass;
2126 	lock_basic_unlock(&tp->lock);
2127 
2128 	/* fetch tp again and lock anchors, so that we can modify the trees */
2129 	lock_basic_lock(&env->anchors->lock);
2130 	tp2 = (struct trust_anchor*)rbtree_search(env->anchors->tree, &key);
2131 	if(!tp2) {
2132 		verbose(VERB_ALGO, "trustpoint was deleted in set_next_probe");
2133 		lock_basic_unlock(&env->anchors->lock);
2134 		return 0;
2135 	}
2136 	log_assert(tp == tp2);
2137 	lock_basic_lock(&tp->lock);
2138 
2139 	/* schedule */
2140 	mold = wait_probe_time(env->anchors);
2141 	(void)rbtree_delete(&env->anchors->autr->probe, tp);
2142 	tp->autr->next_probe_time = calc_next_probe(env,
2143 		tp->autr->query_interval);
2144 	(void)rbtree_insert(&env->anchors->autr->probe, &tp->autr->pnode);
2145 	mnew = wait_probe_time(env->anchors);
2146 
2147 	lock_basic_unlock(&env->anchors->lock);
2148 	verbose(VERB_ALGO, "next probe set in %d seconds",
2149 		(int)tp->autr->next_probe_time - (int)*env->now);
2150 	if(mold != mnew) {
2151 		reset_worker_timer_at(env, mnew);
2152 	}
2153 	return 1;
2154 }
2155 
2156 /** Revoke and Delete a trust point */
2157 static void
autr_tp_remove(struct module_env * env,struct trust_anchor * tp,struct ub_packed_rrset_key * dnskey_rrset)2158 autr_tp_remove(struct module_env* env, struct trust_anchor* tp,
2159 	struct ub_packed_rrset_key* dnskey_rrset)
2160 {
2161 	struct trust_anchor* del_tp;
2162 	struct trust_anchor key;
2163 	struct autr_point_data pd;
2164 	time_t mold, mnew;
2165 
2166 	log_nametypeclass(VERB_OPS, "trust point was revoked",
2167 		tp->name, LDNS_RR_TYPE_DNSKEY, tp->dclass);
2168 	tp->autr->revoked = 1;
2169 
2170 	/* use space allocated for dnskey_rrset to save name of anchor */
2171 	memset(&key, 0, sizeof(key));
2172 	memset(&pd, 0, sizeof(pd));
2173 	key.autr = &pd;
2174 	key.node.key = &key;
2175 	pd.pnode.key = &key;
2176 	pd.next_probe_time = tp->autr->next_probe_time;
2177 	key.name = dnskey_rrset->rk.dname;
2178 	key.namelen = tp->namelen;
2179 	key.namelabs = tp->namelabs;
2180 	key.dclass = tp->dclass;
2181 
2182 	/* unlock */
2183 	lock_basic_unlock(&tp->lock);
2184 
2185 	/* take from tree. It could be deleted by someone else,hence (void). */
2186 	lock_basic_lock(&env->anchors->lock);
2187 	del_tp = (struct trust_anchor*)rbtree_delete(env->anchors->tree, &key);
2188 	mold = wait_probe_time(env->anchors);
2189 	(void)rbtree_delete(&env->anchors->autr->probe, &key);
2190 	mnew = wait_probe_time(env->anchors);
2191 	anchors_init_parents_locked(env->anchors);
2192 	lock_basic_unlock(&env->anchors->lock);
2193 
2194 	/* if !del_tp then the trust point is no longer present in the tree,
2195 	 * it was deleted by someone else, who will write the zonefile and
2196 	 * clean up the structure */
2197 	if(del_tp) {
2198 		/* save on disk */
2199 		del_tp->autr->next_probe_time = 0; /* no more probing for it */
2200 		autr_write_file(env, del_tp);
2201 
2202 		/* delete */
2203 		autr_point_delete(del_tp);
2204 	}
2205 	if(mold != mnew) {
2206 		reset_worker_timer_at(env, mnew);
2207 	}
2208 }
2209 
autr_process_prime(struct module_env * env,struct val_env * ve,struct trust_anchor * tp,struct ub_packed_rrset_key * dnskey_rrset,struct module_qstate * qstate)2210 int autr_process_prime(struct module_env* env, struct val_env* ve,
2211 	struct trust_anchor* tp, struct ub_packed_rrset_key* dnskey_rrset,
2212 	struct module_qstate* qstate)
2213 {
2214 	int changed = 0;
2215 	log_assert(tp && tp->autr);
2216 	/* autotrust update trust anchors */
2217 	/* the tp is locked, and stays locked unless it is deleted */
2218 
2219 	/* we could just catch the anchor here while another thread
2220 	 * is busy deleting it. Just unlock and let the other do its job */
2221 	if(tp->autr->revoked) {
2222 		log_nametypeclass(VERB_ALGO, "autotrust not processed, "
2223 			"trust point revoked", tp->name,
2224 			LDNS_RR_TYPE_DNSKEY, tp->dclass);
2225 		lock_basic_unlock(&tp->lock);
2226 		return 0; /* it is revoked */
2227 	}
2228 
2229 	/* query_dnskeys(): */
2230 	tp->autr->last_queried = *env->now;
2231 
2232 	log_nametypeclass(VERB_ALGO, "autotrust process for",
2233 		tp->name, LDNS_RR_TYPE_DNSKEY, tp->dclass);
2234 	/* see if time alone makes some keys valid */
2235 	autr_holddown_exceed(env, tp, &changed);
2236 	if(changed) {
2237 		verbose(VERB_ALGO, "autotrust: morekeys, reassemble");
2238 		if(!autr_assemble(tp)) {
2239 			log_err("malloc failure assembling autotrust keys");
2240 			return 1; /* unchanged */
2241 		}
2242 	}
2243 	/* did we get any data? */
2244 	if(!dnskey_rrset) {
2245 		verbose(VERB_ALGO, "autotrust: no dnskey rrset");
2246 		/* no update of query_failed, because then we would have
2247 		 * to write to disk. But we cannot because we maybe are
2248 		 * still 'initializing' with DS records, that we cannot write
2249 		 * in the full format (which only contains KSKs). */
2250 		return 1; /* trust point exists */
2251 	}
2252 	/* check for revoked keys to remove immediately */
2253 	check_contains_revoked(env, ve, tp, dnskey_rrset, &changed, qstate);
2254 	if(changed) {
2255 		verbose(VERB_ALGO, "autotrust: revokedkeys, reassemble");
2256 		if(!autr_assemble(tp)) {
2257 			log_err("malloc failure assembling autotrust keys");
2258 			return 1; /* unchanged */
2259 		}
2260 		if(!tp->ds_rrset && !tp->dnskey_rrset) {
2261 			/* no more keys, all are revoked */
2262 			/* this is a success for this probe attempt */
2263 			tp->autr->last_success = *env->now;
2264 			autr_tp_remove(env, tp, dnskey_rrset);
2265 			return 0; /* trust point removed */
2266 		}
2267 	}
2268 	/* verify the dnskey rrset and see if it is valid. */
2269 	if(!verify_dnskey(env, ve, tp, dnskey_rrset, qstate)) {
2270 		verbose(VERB_ALGO, "autotrust: dnskey did not verify.");
2271 		/* only increase failure count if this is not the first prime,
2272 		 * this means there was a previous successful probe */
2273 		if(tp->autr->last_success) {
2274 			tp->autr->query_failed += 1;
2275 			autr_write_file(env, tp);
2276 		}
2277 		return 1; /* trust point exists */
2278 	}
2279 
2280 	tp->autr->last_success = *env->now;
2281 	tp->autr->query_failed = 0;
2282 
2283 	/* Add new trust anchors to the data structure
2284 	 * - note which trust anchors are seen this probe.
2285 	 * Set trustpoint query_interval and retry_time.
2286 	 * - find minimum rrsig expiration interval
2287 	 */
2288 	if(!update_events(env, ve, tp, dnskey_rrset, &changed)) {
2289 		log_err("malloc failure in autotrust update_events. "
2290 			"trust point unchanged.");
2291 		return 1; /* trust point unchanged, so exists */
2292 	}
2293 
2294 	/* - for every SEP key do the 5011 statetable.
2295 	 * - remove missing trustanchors (if veryold and we have new anchors).
2296 	 */
2297 	if(!do_statetable(env, tp, &changed)) {
2298 		log_err("malloc failure in autotrust do_statetable. "
2299 			"trust point unchanged.");
2300 		return 1; /* trust point unchanged, so exists */
2301 	}
2302 
2303 	autr_cleanup_keys(tp);
2304 	if(!set_next_probe(env, tp, dnskey_rrset))
2305 		return 0; /* trust point does not exist */
2306 	autr_write_file(env, tp);
2307 	if(changed) {
2308 		verbose(VERB_ALGO, "autotrust: changed, reassemble");
2309 		if(!autr_assemble(tp)) {
2310 			log_err("malloc failure assembling autotrust keys");
2311 			return 1; /* unchanged */
2312 		}
2313 		if(!tp->ds_rrset && !tp->dnskey_rrset) {
2314 			/* no more keys, all are revoked */
2315 			autr_tp_remove(env, tp, dnskey_rrset);
2316 			return 0; /* trust point removed */
2317 		}
2318 	} else verbose(VERB_ALGO, "autotrust: no changes");
2319 
2320 	return 1; /* trust point exists */
2321 }
2322 
2323 /** debug print a trust anchor key */
2324 static void
autr_debug_print_ta(struct autr_ta * ta)2325 autr_debug_print_ta(struct autr_ta* ta)
2326 {
2327 	char buf[32];
2328 	char* str = sldns_wire2str_rr(ta->rr, ta->rr_len);
2329 	if(!str) {
2330 		log_info("out of memory in debug_print_ta");
2331 		return;
2332 	}
2333 	if(str[0]) str[strlen(str)-1]=0; /* remove newline */
2334 	(void)autr_ctime_r(&ta->last_change, buf);
2335 	if(buf[0]) buf[strlen(buf)-1]=0; /* remove newline */
2336 	log_info("[%s] %s ;;state:%d ;;pending_count:%d%s%s last:%s",
2337 		trustanchor_state2str(ta->s), str, ta->s, ta->pending_count,
2338 		ta->fetched?" fetched":"", ta->revoked?" revoked":"", buf);
2339 	free(str);
2340 }
2341 
2342 /** debug print a trust point */
2343 static void
autr_debug_print_tp(struct trust_anchor * tp)2344 autr_debug_print_tp(struct trust_anchor* tp)
2345 {
2346 	struct autr_ta* ta;
2347 	/* Note: buf is also used for autr_ctime_r but that only needs a size
2348 	 *       of 26, so LDNS_MAX_DOMAINLEN is enough. */
2349 	char buf[LDNS_MAX_DOMAINLEN];
2350 	if(!tp->autr)
2351 		return;
2352 	dname_str(tp->name, buf);
2353 	log_info("trust point %s : %d", buf, (int)tp->dclass);
2354 	log_info("assembled %d DS and %d DNSKEYs",
2355 		(int)tp->numDS, (int)tp->numDNSKEY);
2356 	if(tp->ds_rrset) {
2357 		log_packed_rrset(NO_VERBOSE, "DS:", tp->ds_rrset);
2358 	}
2359 	if(tp->dnskey_rrset) {
2360 		log_packed_rrset(NO_VERBOSE, "DNSKEY:", tp->dnskey_rrset);
2361 	}
2362 	log_info("file %s", (tp->autr->file?tp->autr->file:"null"));
2363 	(void)autr_ctime_r(&tp->autr->last_queried, buf);
2364 	if(buf[0]) buf[strlen(buf)-1]=0; /* remove newline */
2365 	log_info("last_queried: %u %s", (unsigned)tp->autr->last_queried, buf);
2366 	(void)autr_ctime_r(&tp->autr->last_success, buf);
2367 	if(buf[0]) buf[strlen(buf)-1]=0; /* remove newline */
2368 	log_info("last_success: %u %s", (unsigned)tp->autr->last_success, buf);
2369 	(void)autr_ctime_r(&tp->autr->next_probe_time, buf);
2370 	if(buf[0]) buf[strlen(buf)-1]=0; /* remove newline */
2371 	log_info("next_probe_time: %u %s", (unsigned)tp->autr->next_probe_time,
2372 		buf);
2373 	log_info("query_interval: %u", (unsigned)tp->autr->query_interval);
2374 	log_info("retry_time: %u", (unsigned)tp->autr->retry_time);
2375 	log_info("query_failed: %u", (unsigned)tp->autr->query_failed);
2376 
2377 	for(ta=tp->autr->keys; ta; ta=ta->next) {
2378 		autr_debug_print_ta(ta);
2379 	}
2380 }
2381 
2382 void
autr_debug_print(struct val_anchors * anchors)2383 autr_debug_print(struct val_anchors* anchors)
2384 {
2385 	struct trust_anchor* tp;
2386 	lock_basic_lock(&anchors->lock);
2387 	RBTREE_FOR(tp, struct trust_anchor*, anchors->tree) {
2388 		lock_basic_lock(&tp->lock);
2389 		autr_debug_print_tp(tp);
2390 		lock_basic_unlock(&tp->lock);
2391 	}
2392 	lock_basic_unlock(&anchors->lock);
2393 }
2394 
probe_answer_cb(void * arg,int ATTR_UNUSED (rcode),sldns_buffer * ATTR_UNUSED (buf),enum sec_status ATTR_UNUSED (sec),char * ATTR_UNUSED (why_bogus),int ATTR_UNUSED (was_ratelimited))2395 void probe_answer_cb(void* arg, int ATTR_UNUSED(rcode),
2396 	sldns_buffer* ATTR_UNUSED(buf), enum sec_status ATTR_UNUSED(sec),
2397 	char* ATTR_UNUSED(why_bogus), int ATTR_UNUSED(was_ratelimited))
2398 {
2399 	/* retry was set before the query was done,
2400 	 * re-querytime is set when query succeeded, but that may not
2401 	 * have reset this timer because the query could have been
2402 	 * handled by another thread. In that case, this callback would
2403 	 * get called after the original timeout is done.
2404 	 * By not resetting the timer, it may probe more often, but not
2405 	 * less often.
2406 	 * Unless the new lookup resulted in smaller TTLs and thus smaller
2407 	 * timeout values. In that case one old TTL could be mistakenly done.
2408 	 */
2409 	struct module_env* env = (struct module_env*)arg;
2410 	verbose(VERB_ALGO, "autotrust probe answer cb");
2411 	reset_worker_timer(env);
2412 }
2413 
2414 /** probe a trust anchor DNSKEY and unlocks tp */
2415 static void
probe_anchor(struct module_env * env,struct trust_anchor * tp)2416 probe_anchor(struct module_env* env, struct trust_anchor* tp)
2417 {
2418 	struct query_info qinfo;
2419 	uint16_t qflags = BIT_RD;
2420 	struct edns_data edns;
2421 	sldns_buffer* buf = env->scratch_buffer;
2422 	qinfo.qname = regional_alloc_init(env->scratch, tp->name, tp->namelen);
2423 	if(!qinfo.qname) {
2424 		log_err("out of memory making 5011 probe");
2425 		return;
2426 	}
2427 	qinfo.qname_len = tp->namelen;
2428 	qinfo.qtype = LDNS_RR_TYPE_DNSKEY;
2429 	qinfo.qclass = tp->dclass;
2430 	qinfo.local_alias = NULL;
2431 	log_query_info(VERB_ALGO, "autotrust probe", &qinfo);
2432 	verbose(VERB_ALGO, "retry probe set in %d seconds",
2433 		(int)tp->autr->next_probe_time - (int)*env->now);
2434 	edns.edns_present = 1;
2435 	edns.ext_rcode = 0;
2436 	edns.edns_version = 0;
2437 	edns.bits = EDNS_DO;
2438 	edns.opt_list_in = NULL;
2439 	edns.opt_list_out = NULL;
2440 	edns.opt_list_inplace_cb_out = NULL;
2441 	edns.padding_block_size = 0;
2442 	edns.cookie_present = 0;
2443 	edns.cookie_valid = 0;
2444 	if(sldns_buffer_capacity(buf) < 65535)
2445 		edns.udp_size = (uint16_t)sldns_buffer_capacity(buf);
2446 	else	edns.udp_size = 65535;
2447 
2448 	/* can't hold the lock while mesh_run is processing */
2449 	lock_basic_unlock(&tp->lock);
2450 
2451 	/* delete the DNSKEY from rrset and key cache so an active probe
2452 	 * is done. First the rrset so another thread does not use it
2453 	 * to recreate the key entry in a race condition. */
2454 	rrset_cache_remove(env->rrset_cache, qinfo.qname, qinfo.qname_len,
2455 		qinfo.qtype, qinfo.qclass, 0);
2456 	key_cache_remove(env->key_cache, qinfo.qname, qinfo.qname_len,
2457 		qinfo.qclass);
2458 
2459 	if(!mesh_new_callback(env->mesh, &qinfo, qflags, &edns, buf, 0,
2460 		&probe_answer_cb, env, 0, NULL)) {
2461 		log_err("out of memory making 5011 probe");
2462 	}
2463 }
2464 
2465 /** fetch first to-probe trust-anchor and lock it and set retrytime */
2466 static struct trust_anchor*
todo_probe(struct module_env * env,time_t * next)2467 todo_probe(struct module_env* env, time_t* next)
2468 {
2469 	struct trust_anchor* tp;
2470 	rbnode_type* el;
2471 	/* get first one */
2472 	lock_basic_lock(&env->anchors->lock);
2473 	if( (el=rbtree_first(&env->anchors->autr->probe)) == RBTREE_NULL) {
2474 		/* in case of revoked anchors */
2475 		lock_basic_unlock(&env->anchors->lock);
2476 		/* signal that there are no anchors to probe */
2477 		*next = 0;
2478 		return NULL;
2479 	}
2480 	tp = (struct trust_anchor*)el->key;
2481 	lock_basic_lock(&tp->lock);
2482 
2483 	/* is it eligible? */
2484 	if((time_t)tp->autr->next_probe_time > *env->now) {
2485 		/* no more to probe */
2486 		*next = (time_t)tp->autr->next_probe_time - *env->now;
2487 		lock_basic_unlock(&tp->lock);
2488 		lock_basic_unlock(&env->anchors->lock);
2489 		return NULL;
2490 	}
2491 
2492 	/* reset its next probe time */
2493 	(void)rbtree_delete(&env->anchors->autr->probe, tp);
2494 	tp->autr->next_probe_time = calc_next_probe(env, tp->autr->retry_time);
2495 	(void)rbtree_insert(&env->anchors->autr->probe, &tp->autr->pnode);
2496 	lock_basic_unlock(&env->anchors->lock);
2497 
2498 	return tp;
2499 }
2500 
2501 time_t
autr_probe_timer(struct module_env * env)2502 autr_probe_timer(struct module_env* env)
2503 {
2504 	struct trust_anchor* tp;
2505 	time_t next_probe = 3600;
2506 	int num = 0;
2507 	if(autr_permit_small_holddown) next_probe = 1;
2508 	verbose(VERB_ALGO, "autotrust probe timer callback");
2509 	/* while there are still anchors to probe */
2510 	while( (tp = todo_probe(env, &next_probe)) ) {
2511 		/* make a probe for this anchor */
2512 		probe_anchor(env, tp);
2513 		num++;
2514 	}
2515 	regional_free_all(env->scratch);
2516 	if(next_probe == 0)
2517 		return 0; /* no trust points to probe */
2518 	verbose(VERB_ALGO, "autotrust probe timer %d callbacks done", num);
2519 	return next_probe;
2520 }
2521