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