xref: /freebsd/contrib/unbound/validator/val_anchor.c (revision 7a789145f88a6aceacc59029a0cafe7de7aeefea)
1 /*
2  * validator/val_anchor.c - validator trust anchor storage.
3  *
4  * Copyright (c) 2007, NLnet Labs. All rights reserved.
5  *
6  * This software is open source.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  *
12  * Redistributions of source code must retain the above copyright notice,
13  * this list of conditions and the following disclaimer.
14  *
15  * Redistributions in binary form must reproduce the above copyright notice,
16  * this list of conditions and the following disclaimer in the documentation
17  * and/or other materials provided with the distribution.
18  *
19  * Neither the name of the NLNET LABS nor the names of its contributors may
20  * be used to endorse or promote products derived from this software without
21  * specific prior written permission.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
26  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
27  * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
28  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
29  * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
30  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
31  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
32  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
33  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
34  */
35 
36 /**
37  * \file
38  *
39  * This file contains storage for the trust anchors for the validator.
40  */
41 #include "config.h"
42 #include <ctype.h>
43 #include "validator/val_anchor.h"
44 #include "validator/val_sigcrypt.h"
45 #include "validator/autotrust.h"
46 #include "util/data/packed_rrset.h"
47 #include "util/data/dname.h"
48 #include "util/log.h"
49 #include "util/net_help.h"
50 #include "util/config_file.h"
51 #include "util/as112.h"
52 #include "sldns/sbuffer.h"
53 #include "sldns/rrdef.h"
54 #include "sldns/str2wire.h"
55 #ifdef HAVE_GLOB_H
56 #include <glob.h>
57 #endif
58 
59 int
anchor_cmp(const void * k1,const void * k2)60 anchor_cmp(const void* k1, const void* k2)
61 {
62 	int m;
63 	struct trust_anchor* n1 = (struct trust_anchor*)k1;
64 	struct trust_anchor* n2 = (struct trust_anchor*)k2;
65 	/* no need to ntohs(class) because sort order is irrelevant */
66 	if(n1->dclass != n2->dclass) {
67 		if(n1->dclass < n2->dclass)
68 			return -1;
69 		return 1;
70 	}
71 	return dname_lab_cmp(n1->name, n1->namelabs, n2->name, n2->namelabs,
72 		&m);
73 }
74 
75 struct val_anchors*
anchors_create(void)76 anchors_create(void)
77 {
78 	struct val_anchors* a = (struct val_anchors*)calloc(1, sizeof(*a));
79 	if(!a)
80 		return NULL;
81 	a->tree = rbtree_create(anchor_cmp);
82 	if(!a->tree) {
83 		anchors_delete(a);
84 		return NULL;
85 	}
86 	a->autr = autr_global_create();
87 	if(!a->autr) {
88 		anchors_delete(a);
89 		return NULL;
90 	}
91 	lock_basic_init(&a->lock);
92 	lock_protect(&a->lock, a, sizeof(*a));
93 	lock_protect(&a->lock, a->autr, sizeof(*a->autr));
94 	return a;
95 }
96 
97 /** delete assembled rrset */
98 static void
assembled_rrset_delete(struct ub_packed_rrset_key * pkey)99 assembled_rrset_delete(struct ub_packed_rrset_key* pkey)
100 {
101 	if(!pkey) return;
102 	if(pkey->entry.data) {
103 		struct packed_rrset_data* pd = (struct packed_rrset_data*)
104 			pkey->entry.data;
105 		free(pd->rr_data);
106 		free(pd->rr_ttl);
107 		free(pd->rr_len);
108 		free(pd);
109 	}
110 	free(pkey->rk.dname);
111 	free(pkey);
112 }
113 
114 /** destroy locks in tree and delete autotrust anchors */
115 static void
anchors_delfunc(rbnode_type * elem,void * ATTR_UNUSED (arg))116 anchors_delfunc(rbnode_type* elem, void* ATTR_UNUSED(arg))
117 {
118 	struct trust_anchor* ta = (struct trust_anchor*)elem;
119 	if(!ta) return;
120 	if(ta->autr) {
121 		autr_point_delete(ta);
122 	} else {
123 		struct ta_key* p, *np;
124 		lock_basic_destroy(&ta->lock);
125 		free(ta->name);
126 		p = ta->keylist;
127 		while(p) {
128 			np = p->next;
129 			free(p->data);
130 			free(p);
131 			p = np;
132 		}
133 		assembled_rrset_delete(ta->ds_rrset);
134 		assembled_rrset_delete(ta->dnskey_rrset);
135 		free(ta);
136 	}
137 }
138 
139 void
anchors_delete(struct val_anchors * anchors)140 anchors_delete(struct val_anchors* anchors)
141 {
142 	if(!anchors)
143 		return;
144 	lock_unprotect(&anchors->lock, anchors->autr);
145 	lock_unprotect(&anchors->lock, anchors);
146 	lock_basic_destroy(&anchors->lock);
147 	if(anchors->tree)
148 		traverse_postorder(anchors->tree, anchors_delfunc, NULL);
149 	free(anchors->tree);
150 	autr_global_delete(anchors->autr);
151 	free(anchors);
152 }
153 
154 void
anchors_init_parents_locked(struct val_anchors * anchors)155 anchors_init_parents_locked(struct val_anchors* anchors)
156 {
157 	struct trust_anchor* node, *prev = NULL, *p;
158 	int m;
159 	/* nobody else can grab locks because we hold the main lock.
160 	 * Thus the previous items, after unlocked, are not deleted */
161 	RBTREE_FOR(node, struct trust_anchor*, anchors->tree) {
162 		lock_basic_lock(&node->lock);
163 		node->parent = NULL;
164 		if(!prev || prev->dclass != node->dclass) {
165 			prev = node;
166 			lock_basic_unlock(&node->lock);
167 			continue;
168 		}
169 		(void)dname_lab_cmp(prev->name, prev->namelabs, node->name,
170 			node->namelabs, &m); /* we know prev is smaller */
171 		/* sort order like: . com. bla.com. zwb.com. net. */
172 		/* find the previous, or parent-parent-parent */
173 		for(p = prev; p; p = p->parent)
174 			/* looking for name with few labels, a parent */
175 			if(p->namelabs <= m) {
176 				/* ==: since prev matched m, this is closest*/
177 				/* <: prev matches more, but is not a parent,
178 			 	* this one is a (grand)parent */
179 				node->parent = p;
180 				break;
181 			}
182 		lock_basic_unlock(&node->lock);
183 		prev = node;
184 	}
185 }
186 
187 /** initialise parent pointers in the tree */
188 static void
init_parents(struct val_anchors * anchors)189 init_parents(struct val_anchors* anchors)
190 {
191 	lock_basic_lock(&anchors->lock);
192 	anchors_init_parents_locked(anchors);
193 	lock_basic_unlock(&anchors->lock);
194 }
195 
196 struct trust_anchor*
anchor_find(struct val_anchors * anchors,uint8_t * name,int namelabs,size_t namelen,uint16_t dclass)197 anchor_find(struct val_anchors* anchors, uint8_t* name, int namelabs,
198 	size_t namelen, uint16_t dclass)
199 {
200 	struct trust_anchor key;
201 	rbnode_type* n;
202 	if(!name) return NULL;
203 	key.node.key = &key;
204 	key.name = name;
205 	key.namelabs = namelabs;
206 	key.namelen = namelen;
207 	key.dclass = dclass;
208 	lock_basic_lock(&anchors->lock);
209 	n = rbtree_search(anchors->tree, &key);
210 	if(n) {
211 		lock_basic_lock(&((struct trust_anchor*)n->key)->lock);
212 	}
213 	lock_basic_unlock(&anchors->lock);
214 	if(!n)
215 		return NULL;
216 	return (struct trust_anchor*)n->key;
217 }
218 
219 /** create new trust anchor object */
220 static struct trust_anchor*
anchor_new_ta(struct val_anchors * anchors,uint8_t * name,int namelabs,size_t namelen,uint16_t dclass,int lockit)221 anchor_new_ta(struct val_anchors* anchors, uint8_t* name, int namelabs,
222 	size_t namelen, uint16_t dclass, int lockit)
223 {
224 #ifdef UNBOUND_DEBUG
225 	rbnode_type* r;
226 #endif
227 	struct trust_anchor* ta = (struct trust_anchor*)malloc(
228 		sizeof(struct trust_anchor));
229 	if(!ta)
230 		return NULL;
231 	memset(ta, 0, sizeof(*ta));
232 	ta->node.key = ta;
233 	ta->name = memdup(name, namelen);
234 	if(!ta->name) {
235 		free(ta);
236 		return NULL;
237 	}
238 	ta->namelabs = namelabs;
239 	ta->namelen = namelen;
240 	ta->dclass = dclass;
241 	lock_basic_init(&ta->lock);
242 	if(lockit) {
243 		lock_basic_lock(&anchors->lock);
244 	}
245 #ifdef UNBOUND_DEBUG
246 	r =
247 #else
248 	(void)
249 #endif
250 	rbtree_insert(anchors->tree, &ta->node);
251 	if(lockit) {
252 		lock_basic_unlock(&anchors->lock);
253 	}
254 	log_assert(r != NULL);
255 	return ta;
256 }
257 
258 /** find trustanchor key by exact data match */
259 static struct ta_key*
anchor_find_key(struct trust_anchor * ta,uint8_t * rdata,size_t rdata_len,uint16_t type)260 anchor_find_key(struct trust_anchor* ta, uint8_t* rdata, size_t rdata_len,
261 	uint16_t type)
262 {
263 	struct ta_key* k;
264 	for(k = ta->keylist; k; k = k->next) {
265 		if(k->type == type && k->len == rdata_len &&
266 			memcmp(k->data, rdata, rdata_len) == 0)
267 			return k;
268 	}
269 	return NULL;
270 }
271 
272 /** create new trustanchor key */
273 static struct ta_key*
anchor_new_ta_key(uint8_t * rdata,size_t rdata_len,uint16_t type)274 anchor_new_ta_key(uint8_t* rdata, size_t rdata_len, uint16_t type)
275 {
276 	struct ta_key* k = (struct ta_key*)malloc(sizeof(*k));
277 	if(!k)
278 		return NULL;
279 	memset(k, 0, sizeof(*k));
280 	k->data = memdup(rdata, rdata_len);
281 	if(!k->data) {
282 		free(k);
283 		return NULL;
284 	}
285 	k->len = rdata_len;
286 	k->type = type;
287 	return k;
288 }
289 
290 /**
291  * This routine adds a new RR to a trust anchor. The trust anchor may not
292  * exist yet, and is created if not. The RR can be DS or DNSKEY.
293  * This routine will also remove duplicates; storing them only once.
294  * @param anchors: anchor storage.
295  * @param name: name of trust anchor (wireformat)
296  * @param type: type or RR
297  * @param dclass: class of RR
298  * @param rdata: rdata wireformat, starting with rdlength.
299  *	If NULL, nothing is stored, but an entry is created.
300  * @param rdata_len: length of rdata including rdlength.
301  * @return: NULL on error, else the trust anchor.
302  */
303 static struct trust_anchor*
anchor_store_new_key(struct val_anchors * anchors,uint8_t * name,uint16_t type,uint16_t dclass,uint8_t * rdata,size_t rdata_len)304 anchor_store_new_key(struct val_anchors* anchors, uint8_t* name, uint16_t type,
305 	uint16_t dclass, uint8_t* rdata, size_t rdata_len)
306 {
307 	struct ta_key* k;
308 	struct trust_anchor* ta;
309 	int namelabs;
310 	size_t namelen;
311 	namelabs = dname_count_size_labels(name, &namelen);
312 	if(type != LDNS_RR_TYPE_DS && type != LDNS_RR_TYPE_DNSKEY) {
313 		log_err("Bad type for trust anchor");
314 		return 0;
315 	}
316 	/* lookup or create trustanchor */
317 	ta = anchor_find(anchors, name, namelabs, namelen, dclass);
318 	if(!ta) {
319 		ta = anchor_new_ta(anchors, name, namelabs, namelen, dclass, 1);
320 		if(!ta)
321 			return NULL;
322 		lock_basic_lock(&ta->lock);
323 	}
324 	if(!rdata) {
325 		lock_basic_unlock(&ta->lock);
326 		return ta;
327 	}
328 	/* look for duplicates */
329 	if(anchor_find_key(ta, rdata, rdata_len, type)) {
330 		lock_basic_unlock(&ta->lock);
331 		return ta;
332 	}
333 	k = anchor_new_ta_key(rdata, rdata_len, type);
334 	if(!k) {
335 		lock_basic_unlock(&ta->lock);
336 		return NULL;
337 	}
338 	/* add new key */
339 	if(type == LDNS_RR_TYPE_DS)
340 		ta->numDS++;
341 	else	ta->numDNSKEY++;
342 	k->next = ta->keylist;
343 	ta->keylist = k;
344 	lock_basic_unlock(&ta->lock);
345 	return ta;
346 }
347 
348 /**
349  * Add new RR. It converts ldns RR to wire format.
350  * @param anchors: anchor storage.
351  * @param rr: the wirerr.
352  * @param rl: length of rr.
353  * @param dl: length of dname.
354  * @return NULL on error, else the trust anchor.
355  */
356 static struct trust_anchor*
anchor_store_new_rr(struct val_anchors * anchors,uint8_t * rr,size_t rl,size_t dl)357 anchor_store_new_rr(struct val_anchors* anchors, uint8_t* rr, size_t rl,
358 	size_t dl)
359 {
360 	struct trust_anchor* ta;
361 	if(!(ta=anchor_store_new_key(anchors, rr,
362 		sldns_wirerr_get_type(rr, rl, dl),
363 		sldns_wirerr_get_class(rr, rl, dl),
364 		sldns_wirerr_get_rdatawl(rr, rl, dl),
365 		sldns_wirerr_get_rdatalen(rr, rl, dl)+2))) {
366 		return NULL;
367 	}
368 	log_nametypeclass(VERB_QUERY, "adding trusted key",
369 		rr, sldns_wirerr_get_type(rr, rl, dl),
370 		sldns_wirerr_get_class(rr, rl, dl));
371 	return ta;
372 }
373 
374 /**
375  * Insert insecure anchor
376  * @param anchors: anchor storage.
377  * @param str: the domain name.
378  * @return NULL on error, Else last trust anchor point
379  */
380 static struct trust_anchor*
anchor_insert_insecure(struct val_anchors * anchors,const char * str)381 anchor_insert_insecure(struct val_anchors* anchors, const char* str)
382 {
383 	struct trust_anchor* ta;
384 	size_t dname_len = 0;
385 	uint8_t* nm = sldns_str2wire_dname(str, &dname_len);
386 	if(!nm) {
387 		log_err("parse error in domain name '%s'", str);
388 		return NULL;
389 	}
390 	ta = anchor_store_new_key(anchors, nm, LDNS_RR_TYPE_DS,
391 		LDNS_RR_CLASS_IN, NULL, 0);
392 	free(nm);
393 	return ta;
394 }
395 
396 struct trust_anchor*
anchor_store_str(struct val_anchors * anchors,sldns_buffer * buffer,const char * str)397 anchor_store_str(struct val_anchors* anchors, sldns_buffer* buffer,
398 	const char* str)
399 {
400 	struct trust_anchor* ta;
401 	uint8_t* rr = sldns_buffer_begin(buffer);
402 	size_t len = sldns_buffer_capacity(buffer), dname_len = 0;
403 	int status = sldns_str2wire_rr_buf(str, rr, &len, &dname_len,
404 		0, NULL, 0, NULL, 0);
405 	if(status != 0) {
406 		log_err("error parsing trust anchor %s: at %d: %s",
407 			str, LDNS_WIREPARSE_OFFSET(status),
408 			sldns_get_errorstr_parse(status));
409 		return NULL;
410 	}
411 	if(!(ta=anchor_store_new_rr(anchors, rr, len, dname_len))) {
412 		log_err("out of memory");
413 		return NULL;
414 	}
415 	return ta;
416 }
417 
418 /**
419  * Read a file with trust anchors
420  * @param anchors: anchor storage.
421  * @param buffer: parsing buffer.
422  * @param fname: string.
423  * @param onlyone: only one trust anchor allowed in file.
424  * @return NULL on error. Else last trust-anchor point.
425  */
426 static struct trust_anchor*
anchor_read_file(struct val_anchors * anchors,sldns_buffer * buffer,const char * fname,int onlyone)427 anchor_read_file(struct val_anchors* anchors, sldns_buffer* buffer,
428 	const char* fname, int onlyone)
429 {
430 	struct trust_anchor* ta = NULL, *tanew;
431 	struct sldns_file_parse_state pst;
432 	int status;
433 	size_t len, dname_len;
434 	uint8_t* rr = sldns_buffer_begin(buffer);
435 	int ok = 1;
436 	FILE* in = fopen(fname, "r");
437 	if(!in) {
438 		log_err("error opening file %s: %s", fname, strerror(errno));
439 		return 0;
440 	}
441 	memset(&pst, 0, sizeof(pst));
442 	pst.default_ttl = 3600;
443 	pst.lineno = 1;
444 	while(!feof(in)) {
445 		len = sldns_buffer_capacity(buffer);
446 		dname_len = 0;
447 		status = sldns_fp2wire_rr_buf(in, rr, &len, &dname_len, &pst);
448 		if(len == 0) /* empty, $TTL, $ORIGIN */
449 			continue;
450 		if(status != 0) {
451 			log_err("parse error in %s:%d:%d : %s", fname,
452 				pst.lineno, LDNS_WIREPARSE_OFFSET(status),
453 				sldns_get_errorstr_parse(status));
454 			ok = 0;
455 			break;
456 		}
457 		if(sldns_wirerr_get_type(rr, len, dname_len) !=
458 			LDNS_RR_TYPE_DS && sldns_wirerr_get_type(rr, len,
459 			dname_len) != LDNS_RR_TYPE_DNSKEY) {
460 			continue;
461 		}
462 		if(!(tanew=anchor_store_new_rr(anchors, rr, len, dname_len))) {
463 			log_err("mem error at %s line %d", fname, pst.lineno);
464 			ok = 0;
465 			break;
466 		}
467 		if(onlyone && ta && ta != tanew) {
468 			log_err("error at %s line %d: no multiple anchor "
469 				"domains allowed (you can have multiple "
470 				"keys, but they must have the same name).",
471 				fname, pst.lineno);
472 			ok = 0;
473 			break;
474 		}
475 		ta = tanew;
476 	}
477 	fclose(in);
478 	if(!ok) return NULL;
479 	/* empty file is OK when multiple anchors are allowed */
480 	if(!onlyone && !ta) return (struct trust_anchor*)1;
481 	return ta;
482 }
483 
484 /** skip file to end of line */
485 static void
skip_to_eol(FILE * in,int * c)486 skip_to_eol(FILE* in, int *c)
487 {
488 	while((*c = getc(in)) != EOF ) {
489 		if(*c == '\n')
490 			return;
491 	}
492 }
493 
494 /** true for special characters in bind configs */
495 static int
is_bind_special(int c)496 is_bind_special(int c)
497 {
498 	switch(c) {
499 		case '{':
500 		case '}':
501 		case '"':
502 		case ';':
503 			return 1;
504 	}
505 	return 0;
506 }
507 
508 /**
509  * Read a keyword skipping bind comments; spaces, specials, restkeywords.
510  * The file is split into the following tokens:
511  *	* special characters, on their own, rdlen=1, { } doublequote ;
512  *	* whitespace becomes a single ' ' or tab. Newlines become spaces.
513  *	* other words ('keywords')
514  *	* comments are skipped if desired
515  *		/ / C++ style comment to end of line
516  *		# to end of line
517  *		/ * C style comment * /
518  * @param in: file to read from.
519  * @param buf: buffer, what is read is stored after current buffer position.
520  *	Space is left in the buffer to write a terminating 0.
521  * @param line: line number is increased per line, for error reports.
522  * @param comments: if 0, comments are not possible and become text.
523  *	if 1, comments are skipped entirely.
524  *	In BIND files, this is when reading quoted strings, for example
525  *	" base 64 text with / / in there "
526  * @return the number of character written to the buffer.
527  *	0 on end of file.
528  */
529 static int
readkeyword_bindfile(FILE * in,sldns_buffer * buf,int * line,int comments)530 readkeyword_bindfile(FILE* in, sldns_buffer* buf, int* line, int comments)
531 {
532 	int c;
533 	int numdone = 0;
534 	while((c = getc(in)) != EOF ) {
535 		if(comments && c == '#') {	/*   # blabla   */
536 			skip_to_eol(in, &c);
537 			if(c == EOF) {
538 				log_err("trusted-keys, %d, got EOF", *line);
539 				return 0;
540 			}
541 			(*line)++;
542 			continue;
543 		} else if(comments && c=='/' && numdone>0 && /* /_/ bla*/
544 			sldns_buffer_read_u8_at(buf,
545 			sldns_buffer_position(buf)-1) == '/') {
546 			sldns_buffer_skip(buf, -1);
547 			numdone--;
548 			skip_to_eol(in, &c);
549 			if(c == EOF) {
550 				log_err("trusted-keys, %d, got EOF", *line);
551 				return 0;
552 			}
553 			(*line)++;
554 			continue;
555 		} else if(comments && c=='*' && numdone>0 && /* /_* bla *_/ */
556 			sldns_buffer_read_u8_at(buf,
557 			sldns_buffer_position(buf)-1) == '/') {
558 			sldns_buffer_skip(buf, -1);
559 			numdone--;
560 			/* skip to end of comment */
561 			while(c != EOF && (c=getc(in)) != EOF ) {
562 				if(c == '*') {
563 					if((c=getc(in)) == '/')
564 						break;
565 				}
566 				if(c == '\n')
567 					(*line)++;
568 			}
569 			if(c == EOF) {
570 				log_err("trusted-keys, %d, got EOF", *line);
571 				return 0;
572 			}
573 			continue;
574 		}
575 		/* not a comment, complete the keyword */
576 		if(numdone > 0) {
577 			/* check same type */
578 			if(isspace((unsigned char)c)) {
579 				ungetc(c, in);
580 				return numdone;
581 			}
582 			if(is_bind_special(c)) {
583 				ungetc(c, in);
584 				return numdone;
585 			}
586 		}
587 		if(c == '\n') {
588 			c = ' ';
589 			(*line)++;
590 		}
591 		/* space for 1 char + 0 string terminator */
592 		if(sldns_buffer_remaining(buf) < 2) {
593 			log_err("trusted-keys, %d, string too long", *line);
594 			return 0;
595 		}
596 		sldns_buffer_write_u8(buf, (uint8_t)c);
597 		numdone++;
598 		if(isspace((unsigned char)c)) {
599 			/* collate whitespace into ' ' */
600 			while((c = getc(in)) != EOF ) {
601 				if(c == '\n')
602 					(*line)++;
603 				if(!isspace((unsigned char)c)) {
604 					ungetc(c, in);
605 					break;
606 				}
607 			}
608 			if(c == EOF) {
609 				log_err("trusted-keys, %d, got EOF", *line);
610 				return 0;
611 			}
612 			return numdone;
613 		}
614 		if(is_bind_special(c))
615 			return numdone;
616 	}
617 	return numdone;
618 }
619 
620 /** skip through file to { or ; */
621 static int
skip_to_special(FILE * in,sldns_buffer * buf,int * line,int spec)622 skip_to_special(FILE* in, sldns_buffer* buf, int* line, int spec)
623 {
624 	int rdlen;
625 	sldns_buffer_clear(buf);
626 	while((rdlen=readkeyword_bindfile(in, buf, line, 1))) {
627 		if(rdlen == 1 && isspace((unsigned char)*sldns_buffer_begin(buf))) {
628 			sldns_buffer_clear(buf);
629 			continue;
630 		}
631 		if(rdlen != 1 || *sldns_buffer_begin(buf) != (uint8_t)spec) {
632 			sldns_buffer_write_u8(buf, 0);
633 			log_err("trusted-keys, line %d, expected %c",
634 				*line, spec);
635 			return 0;
636 		}
637 		return 1;
638 	}
639 	log_err("trusted-keys, line %d, expected %c, read failed", *line, spec);
640 	return 0;
641 }
642 
643 /**
644  * read contents of trusted-keys{ ... ; clauses and insert keys into storage.
645  * @param anchors: where to store keys
646  * @param buf: buffer to use
647  * @param line: line number in file
648  * @param in: file to read from.
649  * @return 0 on error.
650  */
651 static int
process_bind_contents(struct val_anchors * anchors,sldns_buffer * buf,int * line,FILE * in)652 process_bind_contents(struct val_anchors* anchors, sldns_buffer* buf,
653 	int* line, FILE* in)
654 {
655 	/* loop over contents, collate strings before ; */
656 	/* contents is (numbered): 0   1    2  3 4   5  6 7 8    */
657 	/*                           name. 257 3 5 base64 base64 */
658 	/* quoted value:           0 "111"  0  0 0   0  0 0 0    */
659 	/* comments value:         1 "000"  1  1  1 "0  0 0 0"  1 */
660 	int contnum = 0;
661 	int quoted = 0;
662 	int comments = 1;
663 	int rdlen;
664 	char* str = 0;
665 	sldns_buffer_clear(buf);
666 	while((rdlen=readkeyword_bindfile(in, buf, line, comments))) {
667 		if(rdlen == 1 && sldns_buffer_position(buf) == 1
668 			&& isspace((unsigned char)*sldns_buffer_begin(buf))) {
669 			/* starting whitespace is removed */
670 			sldns_buffer_clear(buf);
671 			continue;
672 		} else if(rdlen == 1 && sldns_buffer_current(buf)[-1] == '"') {
673 			/* remove " from the string */
674 			if(contnum == 0) {
675 				quoted = 1;
676 				comments = 0;
677 			}
678 			sldns_buffer_skip(buf, -1);
679 			if(contnum > 0 && quoted) {
680 				if(sldns_buffer_remaining(buf) < 8+1) {
681 					log_err("line %d, too long", *line);
682 					return 0;
683 				}
684 				sldns_buffer_write(buf, " DNSKEY ", 8);
685 				quoted = 0;
686 				comments = 1;
687 			} else if(contnum > 0)
688 				comments = !comments;
689 			continue;
690 		} else if(rdlen == 1 && sldns_buffer_current(buf)[-1] == ';') {
691 
692 			if(contnum < 5) {
693 				sldns_buffer_write_u8(buf, 0);
694 				log_err("line %d, bad key", *line);
695 				return 0;
696 			}
697 			sldns_buffer_skip(buf, -1);
698 			sldns_buffer_write_u8(buf, 0);
699 			str = strdup((char*)sldns_buffer_begin(buf));
700 			if(!str) {
701 				log_err("line %d, allocation failure", *line);
702 				return 0;
703 			}
704 			if(!anchor_store_str(anchors, buf, str)) {
705 				log_err("line %d, bad key", *line);
706 				free(str);
707 				return 0;
708 			}
709 			free(str);
710 			sldns_buffer_clear(buf);
711 			contnum = 0;
712 			quoted = 0;
713 			comments = 1;
714 			continue;
715 		} else if(rdlen == 1 && sldns_buffer_current(buf)[-1] == '}') {
716 			if(contnum > 0) {
717 				sldns_buffer_write_u8(buf, 0);
718 				log_err("line %d, bad key before }", *line);
719 				return 0;
720 			}
721 			return 1;
722 		} else if(rdlen == 1 &&
723 			isspace((unsigned char)sldns_buffer_current(buf)[-1])) {
724 			/* leave whitespace here */
725 		} else {
726 			/* not space or whatnot, so actual content */
727 			contnum ++;
728 			if(contnum == 1 && !quoted) {
729 				if(sldns_buffer_remaining(buf) < 8+1) {
730 					log_err("line %d, too long", *line);
731 					return 0;
732 				}
733 				sldns_buffer_write(buf, " DNSKEY ", 8);
734 			}
735 		}
736 	}
737 
738 	log_err("line %d, EOF before }", *line);
739 	return 0;
740 }
741 
742 /**
743  * Read a BIND9 like file with trust anchors in named.conf format.
744  * @param anchors: anchor storage.
745  * @param buffer: parsing buffer.
746  * @param fname: string.
747  * @return false on error.
748  */
749 static int
anchor_read_bind_file(struct val_anchors * anchors,sldns_buffer * buffer,const char * fname)750 anchor_read_bind_file(struct val_anchors* anchors, sldns_buffer* buffer,
751 	const char* fname)
752 {
753 	int line_nr = 1;
754 	FILE* in = fopen(fname, "r");
755 	int rdlen = 0;
756 	if(!in) {
757 		log_err("error opening file %s: %s", fname, strerror(errno));
758 		return 0;
759 	}
760 	verbose(VERB_QUERY, "reading in bind-compat-mode: '%s'", fname);
761 	/* scan for  trusted-keys  keyword, ignore everything else */
762 	sldns_buffer_clear(buffer);
763 	while((rdlen=readkeyword_bindfile(in, buffer, &line_nr, 1)) != 0) {
764 		if(rdlen != 12 || strncmp((char*)sldns_buffer_begin(buffer),
765 			"trusted-keys", 12) != 0) {
766 			sldns_buffer_clear(buffer);
767 			/* ignore everything but trusted-keys */
768 			continue;
769 		}
770 		if(!skip_to_special(in, buffer, &line_nr, '{')) {
771 			log_err("error in trusted key: \"%s\"", fname);
772 			fclose(in);
773 			return 0;
774 		}
775 		/* process contents */
776 		if(!process_bind_contents(anchors, buffer, &line_nr, in)) {
777 			log_err("error in trusted key: \"%s\"", fname);
778 			fclose(in);
779 			return 0;
780 		}
781 		if(!skip_to_special(in, buffer, &line_nr, ';')) {
782 			log_err("error in trusted key: \"%s\"", fname);
783 			fclose(in);
784 			return 0;
785 		}
786 		sldns_buffer_clear(buffer);
787 	}
788 	fclose(in);
789 	return 1;
790 }
791 
792 /**
793  * Read a BIND9 like files with trust anchors in named.conf format.
794  * Performs wildcard processing of name.
795  * @param anchors: anchor storage.
796  * @param buffer: parsing buffer.
797  * @param pat: pattern string. (can be wildcarded)
798  * @return false on error.
799  */
800 static int
anchor_read_bind_file_wild(struct val_anchors * anchors,sldns_buffer * buffer,const char * pat)801 anchor_read_bind_file_wild(struct val_anchors* anchors, sldns_buffer* buffer,
802 	const char* pat)
803 {
804 #ifdef HAVE_GLOB
805 	glob_t g;
806 	size_t i;
807 	int r, flags;
808 	if(!strchr(pat, '*') && !strchr(pat, '?') && !strchr(pat, '[') &&
809 		!strchr(pat, '{') && !strchr(pat, '~')) {
810 		return anchor_read_bind_file(anchors, buffer, pat);
811 	}
812 	verbose(VERB_QUERY, "wildcard found, processing %s", pat);
813 	flags = 0
814 #ifdef GLOB_ERR
815 		| GLOB_ERR
816 #endif
817 #ifdef GLOB_NOSORT
818 		| GLOB_NOSORT
819 #endif
820 #ifdef GLOB_BRACE
821 		| GLOB_BRACE
822 #endif
823 #ifdef GLOB_TILDE
824 		| GLOB_TILDE
825 #endif
826 	;
827 	memset(&g, 0, sizeof(g));
828 	r = glob(pat, flags, NULL, &g);
829 	if(r) {
830 		/* some error */
831 		if(r == GLOB_NOMATCH) {
832 			verbose(VERB_QUERY, "trusted-keys-file: "
833 				"no matches for %s", pat);
834 			return 1;
835 		} else if(r == GLOB_NOSPACE) {
836 			log_err("wildcard trusted-keys-file %s: "
837 				"pattern out of memory", pat);
838 		} else if(r == GLOB_ABORTED) {
839 			log_err("wildcard trusted-keys-file %s: expansion "
840 				"aborted (%s)", pat, strerror(errno));
841 		} else {
842 			log_err("wildcard trusted-keys-file %s: expansion "
843 				"failed (%s)", pat, strerror(errno));
844 		}
845 		/* ignore globs that yield no files */
846 		return 1;
847 	}
848 	/* process files found, if any */
849 	for(i=0; i<(size_t)g.gl_pathc; i++) {
850 		if(!anchor_read_bind_file(anchors, buffer, g.gl_pathv[i])) {
851 			log_err("error reading wildcard "
852 				"trusted-keys-file: %s", g.gl_pathv[i]);
853 			globfree(&g);
854 			return 0;
855 		}
856 	}
857 	globfree(&g);
858 	return 1;
859 #else /* not HAVE_GLOB */
860 	return anchor_read_bind_file(anchors, buffer, pat);
861 #endif /* HAVE_GLOB */
862 }
863 
864 /**
865  * Assemble an rrset structure for the type
866  * @param ta: trust anchor.
867  * @param num: number of items to fetch from list.
868  * @param type: fetch only items of this type.
869  * @return rrset or NULL on error.
870  */
871 static struct ub_packed_rrset_key*
assemble_it(struct trust_anchor * ta,size_t num,uint16_t type)872 assemble_it(struct trust_anchor* ta, size_t num, uint16_t type)
873 {
874 	struct ub_packed_rrset_key* pkey = (struct ub_packed_rrset_key*)
875 		malloc(sizeof(*pkey));
876 	struct packed_rrset_data* pd;
877 	struct ta_key* tk;
878 	size_t i;
879 	if(!pkey)
880 		return NULL;
881 	memset(pkey, 0, sizeof(*pkey));
882 	pkey->rk.dname = memdup(ta->name, ta->namelen);
883 	if(!pkey->rk.dname) {
884 		free(pkey);
885 		return NULL;
886 	}
887 
888 	pkey->rk.dname_len = ta->namelen;
889 	pkey->rk.type = htons(type);
890 	pkey->rk.rrset_class = htons(ta->dclass);
891 	/* The rrset is build in an uncompressed way. This means it
892 	 * cannot be copied in the normal way. */
893 	pd = (struct packed_rrset_data*)malloc(sizeof(*pd));
894 	if(!pd) {
895 		free(pkey->rk.dname);
896 		free(pkey);
897 		return NULL;
898 	}
899 	memset(pd, 0, sizeof(*pd));
900 	pd->count = num;
901 	pd->trust = rrset_trust_ultimate;
902 	pd->rr_len = (size_t*)reallocarray(NULL, num, sizeof(size_t));
903 	if(!pd->rr_len) {
904 		free(pd);
905 		free(pkey->rk.dname);
906 		free(pkey);
907 		return NULL;
908 	}
909 	pd->rr_ttl = (time_t*)reallocarray(NULL, num, sizeof(time_t));
910 	if(!pd->rr_ttl) {
911 		free(pd->rr_len);
912 		free(pd);
913 		free(pkey->rk.dname);
914 		free(pkey);
915 		return NULL;
916 	}
917 	pd->rr_data = (uint8_t**)reallocarray(NULL, num, sizeof(uint8_t*));
918 	if(!pd->rr_data) {
919 		free(pd->rr_ttl);
920 		free(pd->rr_len);
921 		free(pd);
922 		free(pkey->rk.dname);
923 		free(pkey);
924 		return NULL;
925 	}
926 	/* fill in rrs */
927 	i=0;
928 	for(tk = ta->keylist; tk; tk = tk->next) {
929 		if(tk->type != type)
930 			continue;
931 		pd->rr_len[i] = tk->len;
932 		/* reuse data ptr to allocation in talist */
933 		pd->rr_data[i] = tk->data;
934 		pd->rr_ttl[i] = 0;
935 		i++;
936 	}
937 	pkey->entry.data = (void*)pd;
938 	return pkey;
939 }
940 
941 /**
942  * Assemble structures for the trust DS and DNSKEY rrsets.
943  * @param ta: trust anchor
944  * @return: false on error.
945  */
946 static int
anchors_assemble(struct trust_anchor * ta)947 anchors_assemble(struct trust_anchor* ta)
948 {
949 	if(ta->numDS > 0) {
950 		ta->ds_rrset = assemble_it(ta, ta->numDS, LDNS_RR_TYPE_DS);
951 		if(!ta->ds_rrset)
952 			return 0;
953 	}
954 	if(ta->numDNSKEY > 0) {
955 		ta->dnskey_rrset = assemble_it(ta, ta->numDNSKEY,
956 			LDNS_RR_TYPE_DNSKEY);
957 		if(!ta->dnskey_rrset)
958 			return 0;
959 	}
960 	return 1;
961 }
962 
963 /**
964  * Check DS algos for support, warn if not.
965  * @param ta: trust anchor
966  * @return number of DS anchors with unsupported algorithms.
967  */
968 static size_t
anchors_ds_unsupported(struct trust_anchor * ta)969 anchors_ds_unsupported(struct trust_anchor* ta)
970 {
971 	size_t i, num = 0;
972 	for(i=0; i<ta->numDS; i++) {
973 		if(!ds_digest_algo_is_supported(ta->ds_rrset, i) ||
974 			!ds_key_algo_is_supported(ta->ds_rrset, i))
975 			num++;
976 	}
977 	return num;
978 }
979 
980 /**
981  * Check DNSKEY algos for support, warn if not.
982  * @param ta: trust anchor
983  * @return number of DNSKEY anchors with unsupported algorithms.
984  */
985 static size_t
anchors_dnskey_unsupported(struct trust_anchor * ta)986 anchors_dnskey_unsupported(struct trust_anchor* ta)
987 {
988 	size_t i, num = 0;
989 	for(i=0; i<ta->numDNSKEY; i++) {
990 		if(!dnskey_algo_is_supported(ta->dnskey_rrset, i) ||
991 			!dnskey_size_is_supported(ta->dnskey_rrset, i))
992 			num++;
993 	}
994 	return num;
995 }
996 
997 /**
998  * Assemble the rrsets in the anchors, ready for use by validator.
999  * @param anchors: trust anchor storage.
1000  * @return: false on error.
1001  */
1002 static int
anchors_assemble_rrsets(struct val_anchors * anchors)1003 anchors_assemble_rrsets(struct val_anchors* anchors)
1004 {
1005 	struct trust_anchor* ta;
1006 	struct trust_anchor* next;
1007 	size_t nods, nokey;
1008 	lock_basic_lock(&anchors->lock);
1009 	ta=(struct trust_anchor*)rbtree_first(anchors->tree);
1010 	while((rbnode_type*)ta != RBTREE_NULL) {
1011 		next = (struct trust_anchor*)rbtree_next(&ta->node);
1012 		lock_basic_lock(&ta->lock);
1013 		if(ta->autr || (ta->numDS == 0 && ta->numDNSKEY == 0)) {
1014 			lock_basic_unlock(&ta->lock);
1015 			ta = next; /* skip */
1016 			continue;
1017 		}
1018 		if(!anchors_assemble(ta)) {
1019 			log_err("out of memory");
1020 			lock_basic_unlock(&ta->lock);
1021 			lock_basic_unlock(&anchors->lock);
1022 			return 0;
1023 		}
1024 		nods = anchors_ds_unsupported(ta);
1025 		nokey = anchors_dnskey_unsupported(ta);
1026 		if(nods) {
1027 			log_nametypeclass(NO_VERBOSE, "warning: unsupported "
1028 				"algorithm for trust anchor",
1029 				ta->name, LDNS_RR_TYPE_DS, ta->dclass);
1030 		}
1031 		if(nokey) {
1032 			log_nametypeclass(NO_VERBOSE, "warning: unsupported "
1033 				"algorithm for trust anchor",
1034 				ta->name, LDNS_RR_TYPE_DNSKEY, ta->dclass);
1035 		}
1036 		if(nods == ta->numDS && nokey == ta->numDNSKEY) {
1037 			char b[LDNS_MAX_DOMAINLEN];
1038 			dname_str(ta->name, b);
1039 			log_warn("trust anchor %s has no supported algorithms,"
1040 				" the anchor is ignored (check if you need to"
1041 				" upgrade unbound and "
1042 #ifdef HAVE_LIBRESSL
1043 				"libressl"
1044 #else
1045 				"openssl"
1046 #endif
1047 				")", b);
1048 			(void)rbtree_delete(anchors->tree, &ta->node);
1049 			lock_basic_unlock(&ta->lock);
1050 			anchors_delfunc(&ta->node, NULL);
1051 			ta = next;
1052 			continue;
1053 		}
1054 		lock_basic_unlock(&ta->lock);
1055 		ta = next;
1056 	}
1057 	lock_basic_unlock(&anchors->lock);
1058 	return 1;
1059 }
1060 
1061 int
anchors_apply_cfg(struct val_anchors * anchors,struct config_file * cfg)1062 anchors_apply_cfg(struct val_anchors* anchors, struct config_file* cfg)
1063 {
1064 	struct config_strlist* f;
1065 	const char** zstr;
1066 	char* nm;
1067 	sldns_buffer* parsebuf = sldns_buffer_new(65535);
1068 	if(!parsebuf) {
1069 		log_err("malloc error in anchors_apply_cfg.");
1070 		return 0;
1071 	}
1072 	if(cfg->insecure_lan_zones) {
1073 		for(zstr = as112_zones; *zstr; zstr++) {
1074 			if(!anchor_insert_insecure(anchors, *zstr)) {
1075 				log_err("error in insecure-lan-zones: %s", *zstr);
1076 				sldns_buffer_free(parsebuf);
1077 				return 0;
1078 			}
1079 		}
1080 	}
1081 	for(f = cfg->domain_insecure; f; f = f->next) {
1082 		if(!f->str || f->str[0] == 0) /* empty "" */
1083 			continue;
1084 		if(!anchor_insert_insecure(anchors, f->str)) {
1085 			log_err("error in domain-insecure: %s", f->str);
1086 			sldns_buffer_free(parsebuf);
1087 			return 0;
1088 		}
1089 	}
1090 	for(f = cfg->trust_anchor_file_list; f; f = f->next) {
1091 		if(!f->str || f->str[0] == 0) /* empty "" */
1092 			continue;
1093 		nm = f->str;
1094 		if(cfg->chrootdir && cfg->chrootdir[0] && strncmp(nm,
1095 			cfg->chrootdir, strlen(cfg->chrootdir)) == 0)
1096 			nm += strlen(cfg->chrootdir);
1097 		if(!anchor_read_file(anchors, parsebuf, nm, 0)) {
1098 			log_err("error reading trust-anchor-file: %s", f->str);
1099 			sldns_buffer_free(parsebuf);
1100 			return 0;
1101 		}
1102 	}
1103 	for(f = cfg->trusted_keys_file_list; f; f = f->next) {
1104 		if(!f->str || f->str[0] == 0) /* empty "" */
1105 			continue;
1106 		nm = f->str;
1107 		if(cfg->chrootdir && cfg->chrootdir[0] && strncmp(nm,
1108 			cfg->chrootdir, strlen(cfg->chrootdir)) == 0)
1109 			nm += strlen(cfg->chrootdir);
1110 		if(!anchor_read_bind_file_wild(anchors, parsebuf, nm)) {
1111 			log_err("error reading trusted-keys-file: %s", f->str);
1112 			sldns_buffer_free(parsebuf);
1113 			return 0;
1114 		}
1115 	}
1116 	for(f = cfg->trust_anchor_list; f; f = f->next) {
1117 		if(!f->str || f->str[0] == 0) /* empty "" */
1118 			continue;
1119 		if(!anchor_store_str(anchors, parsebuf, f->str)) {
1120 			log_err("error in trust-anchor: \"%s\"", f->str);
1121 			sldns_buffer_free(parsebuf);
1122 			return 0;
1123 		}
1124 	}
1125 	/* do autr last, so that it sees what anchors are filled by other
1126 	 * means can can print errors about double config for the name */
1127 	for(f = cfg->auto_trust_anchor_file_list; f; f = f->next) {
1128 		if(!f->str || f->str[0] == 0) /* empty "" */
1129 			continue;
1130 		nm = f->str;
1131 		if(cfg->chrootdir && cfg->chrootdir[0] && strncmp(nm,
1132 			cfg->chrootdir, strlen(cfg->chrootdir)) == 0)
1133 			nm += strlen(cfg->chrootdir);
1134 		if(!autr_read_file(anchors, nm)) {
1135 			log_err("error reading auto-trust-anchor-file: %s",
1136 				f->str);
1137 			sldns_buffer_free(parsebuf);
1138 			return 0;
1139 		}
1140 	}
1141 	/* first assemble, since it may delete useless anchors */
1142 	anchors_assemble_rrsets(anchors);
1143 	init_parents(anchors);
1144 	sldns_buffer_free(parsebuf);
1145 	if(verbosity >= VERB_ALGO) autr_debug_print(anchors);
1146 	return 1;
1147 }
1148 
1149 struct trust_anchor*
anchors_lookup(struct val_anchors * anchors,uint8_t * qname,size_t qname_len,uint16_t qclass)1150 anchors_lookup(struct val_anchors* anchors,
1151         uint8_t* qname, size_t qname_len, uint16_t qclass)
1152 {
1153 	struct trust_anchor key;
1154 	struct trust_anchor* result;
1155 	rbnode_type* res = NULL;
1156 	key.node.key = &key;
1157 	key.name = qname;
1158 	key.namelabs = dname_count_labels(qname);
1159 	key.namelen = qname_len;
1160 	key.dclass = qclass;
1161 	lock_basic_lock(&anchors->lock);
1162 	if(rbtree_find_less_equal(anchors->tree, &key, &res)) {
1163 		/* exact */
1164 		result = (struct trust_anchor*)res;
1165 	} else {
1166 		/* smaller element (or no element) */
1167 		int m;
1168 		result = (struct trust_anchor*)res;
1169 		if(!result || result->dclass != qclass) {
1170 			lock_basic_unlock(&anchors->lock);
1171 			return NULL;
1172 		}
1173 		/* count number of labels matched */
1174 		(void)dname_lab_cmp(result->name, result->namelabs, key.name,
1175 			key.namelabs, &m);
1176 		while(result) { /* go up until qname is subdomain of stub */
1177 			if(result->namelabs <= m)
1178 				break;
1179 			result = result->parent;
1180 		}
1181 	}
1182 	if(result) {
1183 		lock_basic_lock(&result->lock);
1184 	}
1185 	lock_basic_unlock(&anchors->lock);
1186 	return result;
1187 }
1188 
1189 /** Get memory usage of assembled key rrset */
1190 static size_t
assembled_rrset_get_mem(struct ub_packed_rrset_key * pkey)1191 assembled_rrset_get_mem(struct ub_packed_rrset_key* pkey)
1192 {
1193 	size_t s;
1194 	if(!pkey)
1195 		return 0;
1196 	s = sizeof(*pkey) + pkey->rk.dname_len;
1197 	if(pkey->entry.data) {
1198 		struct packed_rrset_data* pd = (struct packed_rrset_data*)
1199 			pkey->entry.data;
1200 		s += sizeof(*pd) + pd->count * (sizeof(size_t)+sizeof(time_t)+
1201 			sizeof(uint8_t*));
1202 	}
1203 	return s;
1204 }
1205 
1206 size_t
anchors_get_mem(struct val_anchors * anchors)1207 anchors_get_mem(struct val_anchors* anchors)
1208 {
1209 	struct trust_anchor *ta;
1210 	struct ta_key *k;
1211 	size_t s;
1212 	if(!anchors) return 0;
1213 	s = sizeof(*anchors);
1214 	lock_basic_lock(&anchors->lock);
1215 	RBTREE_FOR(ta, struct trust_anchor*, anchors->tree) {
1216 		lock_basic_lock(&ta->lock);
1217 		s += sizeof(*ta) + ta->namelen;
1218 		/* keys and so on */
1219 		for(k = ta->keylist; k; k = k->next) {
1220 			s += sizeof(*k) + k->len;
1221 		}
1222 		s += assembled_rrset_get_mem(ta->ds_rrset);
1223 		s += assembled_rrset_get_mem(ta->dnskey_rrset);
1224 		if(ta->autr) {
1225 			struct autr_ta* p;
1226 			s += sizeof(*ta->autr);
1227 			if(ta->autr->file)
1228 				s += strlen(ta->autr->file);
1229 			for(p = ta->autr->keys; p; p=p->next) {
1230 				s += sizeof(*p) + p->rr_len;
1231 			}
1232 		}
1233 		lock_basic_unlock(&ta->lock);
1234 	}
1235 	lock_basic_unlock(&anchors->lock);
1236 	return s;
1237 }
1238 
1239 int
anchors_add_insecure(struct val_anchors * anchors,uint16_t c,uint8_t * nm)1240 anchors_add_insecure(struct val_anchors* anchors, uint16_t c, uint8_t* nm)
1241 {
1242 	struct trust_anchor key;
1243 	key.node.key = &key;
1244 	key.name = nm;
1245 	key.namelabs = dname_count_size_labels(nm, &key.namelen);
1246 	key.dclass = c;
1247 	lock_basic_lock(&anchors->lock);
1248 	if(rbtree_search(anchors->tree, &key)) {
1249 		lock_basic_unlock(&anchors->lock);
1250 		/* nothing to do, already an anchor or insecure point */
1251 		return 1;
1252 	}
1253 	if(!anchor_new_ta(anchors, nm, key.namelabs, key.namelen, c, 0)) {
1254 		log_err("out of memory");
1255 		lock_basic_unlock(&anchors->lock);
1256 		return 0;
1257 	}
1258 	/* no other contents in new ta, because it is insecure point */
1259 	anchors_init_parents_locked(anchors);
1260 	lock_basic_unlock(&anchors->lock);
1261 	return 1;
1262 }
1263 
1264 void
anchors_delete_insecure(struct val_anchors * anchors,uint16_t c,uint8_t * nm)1265 anchors_delete_insecure(struct val_anchors* anchors, uint16_t c,
1266         uint8_t* nm)
1267 {
1268 	struct trust_anchor key;
1269 	struct trust_anchor* ta;
1270 	key.node.key = &key;
1271 	key.name = nm;
1272 	key.namelabs = dname_count_size_labels(nm, &key.namelen);
1273 	key.dclass = c;
1274 	lock_basic_lock(&anchors->lock);
1275 	if(!(ta=(struct trust_anchor*)rbtree_search(anchors->tree, &key))) {
1276 		lock_basic_unlock(&anchors->lock);
1277 		/* nothing there */
1278 		return;
1279 	}
1280 	/* lock it to drive away other threads that use it */
1281 	lock_basic_lock(&ta->lock);
1282 	/* see if its really an insecure point */
1283 	if(ta->keylist || ta->autr || ta->numDS || ta->numDNSKEY) {
1284 		lock_basic_unlock(&anchors->lock);
1285 		lock_basic_unlock(&ta->lock);
1286 		/* its not an insecure point, do not remove it */
1287 		return;
1288 	}
1289 
1290 	/* remove from tree */
1291 	(void)rbtree_delete(anchors->tree, &ta->node);
1292 	anchors_init_parents_locked(anchors);
1293 	lock_basic_unlock(&anchors->lock);
1294 
1295 	/* actual free of data */
1296 	lock_basic_unlock(&ta->lock);
1297 	anchors_delfunc(&ta->node, NULL);
1298 }
1299 
1300 /** compare two keytags, return -1, 0 or 1 */
1301 static int
keytag_compare(const void * x,const void * y)1302 keytag_compare(const void* x, const void* y)
1303 {
1304 	if(*(uint16_t*)x == *(uint16_t*)y)
1305 		return 0;
1306 	if(*(uint16_t*)x > *(uint16_t*)y)
1307 		return 1;
1308 	return -1;
1309 }
1310 
1311 size_t
anchor_list_keytags(struct trust_anchor * ta,uint16_t * list,size_t num)1312 anchor_list_keytags(struct trust_anchor* ta, uint16_t* list, size_t num)
1313 {
1314 	size_t i, ret = 0;
1315 	if(ta->numDS == 0 && ta->numDNSKEY == 0)
1316 		return 0; /* insecure point */
1317 	if(ta->numDS != 0 && ta->ds_rrset) {
1318 		struct packed_rrset_data* d=(struct packed_rrset_data*)
1319 			ta->ds_rrset->entry.data;
1320 		for(i=0; i<d->count; i++) {
1321 			if(ret == num) continue;
1322 			list[ret++] = ds_get_keytag(ta->ds_rrset, i);
1323 		}
1324 	}
1325 	if(ta->numDNSKEY != 0 && ta->dnskey_rrset) {
1326 		struct packed_rrset_data* d=(struct packed_rrset_data*)
1327 			ta->dnskey_rrset->entry.data;
1328 		for(i=0; i<d->count; i++) {
1329 			if(ret == num) continue;
1330 			list[ret++] = dnskey_calc_keytag(ta->dnskey_rrset, i);
1331 		}
1332 	}
1333 	qsort(list, ret, sizeof(*list), keytag_compare);
1334 	return ret;
1335 }
1336 
1337 int
anchor_has_keytag(struct val_anchors * anchors,uint8_t * name,int namelabs,size_t namelen,uint16_t dclass,uint16_t keytag)1338 anchor_has_keytag(struct val_anchors* anchors, uint8_t* name, int namelabs,
1339 	size_t namelen, uint16_t dclass, uint16_t keytag)
1340 {
1341 	uint16_t* taglist;
1342 	uint16_t* tl;
1343 	size_t numtag, i;
1344 	struct trust_anchor* anchor = anchor_find(anchors,
1345 		name, namelabs, namelen, dclass);
1346 	if(!anchor)
1347 		return 0;
1348 	if(!anchor->numDS && !anchor->numDNSKEY) {
1349 		lock_basic_unlock(&anchor->lock);
1350 		return 0;
1351 	}
1352 
1353 	taglist = calloc(anchor->numDS + anchor->numDNSKEY, sizeof(*taglist));
1354 	if(!taglist) {
1355 		lock_basic_unlock(&anchor->lock);
1356 		return 0;
1357 	}
1358 
1359 	numtag = anchor_list_keytags(anchor, taglist,
1360 		anchor->numDS+anchor->numDNSKEY);
1361 	lock_basic_unlock(&anchor->lock);
1362 	if(!numtag) {
1363 		free(taglist);
1364 		return 0;
1365 	}
1366 	tl = taglist;
1367 	for(i=0; i<numtag; i++) {
1368 		if(*tl == keytag) {
1369 			free(taglist);
1370 			return 1;
1371 		}
1372 		tl++;
1373 	}
1374 	free(taglist);
1375 	return 0;
1376 }
1377 
1378 struct trust_anchor*
anchors_find_any_noninsecure(struct val_anchors * anchors)1379 anchors_find_any_noninsecure(struct val_anchors* anchors)
1380 {
1381 	struct trust_anchor* ta, *next;
1382 	lock_basic_lock(&anchors->lock);
1383 	ta=(struct trust_anchor*)rbtree_first(anchors->tree);
1384 	while((rbnode_type*)ta != RBTREE_NULL) {
1385 		next = (struct trust_anchor*)rbtree_next(&ta->node);
1386 		lock_basic_lock(&ta->lock);
1387 		if(ta->numDS != 0 || ta->numDNSKEY != 0) {
1388 			/* not an insecurepoint */
1389 			lock_basic_unlock(&anchors->lock);
1390 			return ta;
1391 		}
1392 		lock_basic_unlock(&ta->lock);
1393 		ta = next;
1394 	}
1395 	lock_basic_unlock(&anchors->lock);
1396 	return NULL;
1397 }
1398 
1399 void
anchors_swap_tree(struct val_anchors * anchors,struct val_anchors * data)1400 anchors_swap_tree(struct val_anchors* anchors, struct val_anchors* data)
1401 {
1402 	rbtree_type* oldtree;
1403 	rbtree_type oldprobe;
1404 
1405 	if(!anchors || !data)
1406 		return; /* If anchors is NULL, there is no validation. */
1407 
1408 	oldtree = anchors->tree;
1409 	oldprobe = anchors->autr->probe;
1410 
1411 	anchors->tree = data->tree;
1412 	anchors->autr->probe = data->autr->probe;
1413 
1414 	data->tree = oldtree;
1415 	data->autr->probe = oldprobe;
1416 }
1417