xref: /freebsd/contrib/unbound/validator/val_anchor.c (revision 7afb8adff33d47f10a11368ff54bb2eec5b30165)
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 "ldns/sbuffer.h"
52 #include "ldns/rrdef.h"
53 #include "ldns/str2wire.h"
54 #ifdef HAVE_GLOB_H
55 #include <glob.h>
56 #endif
57 
58 int
59 anchor_cmp(const void* k1, const void* k2)
60 {
61 	int m;
62 	struct trust_anchor* n1 = (struct trust_anchor*)k1;
63 	struct trust_anchor* n2 = (struct trust_anchor*)k2;
64 	/* no need to ntohs(class) because sort order is irrelevant */
65 	if(n1->dclass != n2->dclass) {
66 		if(n1->dclass < n2->dclass)
67 			return -1;
68 		return 1;
69 	}
70 	return dname_lab_cmp(n1->name, n1->namelabs, n2->name, n2->namelabs,
71 		&m);
72 }
73 
74 struct val_anchors*
75 anchors_create(void)
76 {
77 	struct val_anchors* a = (struct val_anchors*)calloc(1, sizeof(*a));
78 	if(!a)
79 		return NULL;
80 	a->tree = rbtree_create(anchor_cmp);
81 	if(!a->tree) {
82 		anchors_delete(a);
83 		return NULL;
84 	}
85 	a->autr = autr_global_create();
86 	if(!a->autr) {
87 		anchors_delete(a);
88 		return NULL;
89 	}
90 	lock_basic_init(&a->lock);
91 	lock_protect(&a->lock, a, sizeof(*a));
92 	lock_protect(&a->lock, a->autr, sizeof(*a->autr));
93 	return a;
94 }
95 
96 /** delete assembled rrset */
97 static void
98 assembled_rrset_delete(struct ub_packed_rrset_key* pkey)
99 {
100 	if(!pkey) return;
101 	if(pkey->entry.data) {
102 		struct packed_rrset_data* pd = (struct packed_rrset_data*)
103 			pkey->entry.data;
104 		free(pd->rr_data);
105 		free(pd->rr_ttl);
106 		free(pd->rr_len);
107 		free(pd);
108 	}
109 	free(pkey->rk.dname);
110 	free(pkey);
111 }
112 
113 /** destroy locks in tree and delete autotrust anchors */
114 static void
115 anchors_delfunc(rbnode_t* elem, void* ATTR_UNUSED(arg))
116 {
117 	struct trust_anchor* ta = (struct trust_anchor*)elem;
118 	if(!ta) return;
119 	if(ta->autr) {
120 		autr_point_delete(ta);
121 	} else {
122 		struct ta_key* p, *np;
123 		lock_basic_destroy(&ta->lock);
124 		free(ta->name);
125 		p = ta->keylist;
126 		while(p) {
127 			np = p->next;
128 			free(p->data);
129 			free(p);
130 			p = np;
131 		}
132 		assembled_rrset_delete(ta->ds_rrset);
133 		assembled_rrset_delete(ta->dnskey_rrset);
134 		free(ta);
135 	}
136 }
137 
138 void
139 anchors_delete(struct val_anchors* anchors)
140 {
141 	if(!anchors)
142 		return;
143 	lock_unprotect(&anchors->lock, anchors->autr);
144 	lock_unprotect(&anchors->lock, anchors);
145 	lock_basic_destroy(&anchors->lock);
146 	if(anchors->tree)
147 		traverse_postorder(anchors->tree, anchors_delfunc, NULL);
148 	free(anchors->tree);
149 	autr_global_delete(anchors->autr);
150 	free(anchors);
151 }
152 
153 void
154 anchors_init_parents_locked(struct val_anchors* anchors)
155 {
156 	struct trust_anchor* node, *prev = NULL, *p;
157 	int m;
158 	/* nobody else can grab locks because we hold the main lock.
159 	 * Thus the previous items, after unlocked, are not deleted */
160 	RBTREE_FOR(node, struct trust_anchor*, anchors->tree) {
161 		lock_basic_lock(&node->lock);
162 		node->parent = NULL;
163 		if(!prev || prev->dclass != node->dclass) {
164 			prev = node;
165 			lock_basic_unlock(&node->lock);
166 			continue;
167 		}
168 		(void)dname_lab_cmp(prev->name, prev->namelabs, node->name,
169 			node->namelabs, &m); /* we know prev is smaller */
170 		/* sort order like: . com. bla.com. zwb.com. net. */
171 		/* find the previous, or parent-parent-parent */
172 		for(p = prev; p; p = p->parent)
173 			/* looking for name with few labels, a parent */
174 			if(p->namelabs <= m) {
175 				/* ==: since prev matched m, this is closest*/
176 				/* <: prev matches more, but is not a parent,
177 			 	* this one is a (grand)parent */
178 				node->parent = p;
179 				break;
180 			}
181 		lock_basic_unlock(&node->lock);
182 		prev = node;
183 	}
184 }
185 
186 /** initialise parent pointers in the tree */
187 static void
188 init_parents(struct val_anchors* anchors)
189 {
190 	lock_basic_lock(&anchors->lock);
191 	anchors_init_parents_locked(anchors);
192 	lock_basic_unlock(&anchors->lock);
193 }
194 
195 struct trust_anchor*
196 anchor_find(struct val_anchors* anchors, uint8_t* name, int namelabs,
197 	size_t namelen, uint16_t dclass)
198 {
199 	struct trust_anchor key;
200 	rbnode_t* n;
201 	if(!name) return NULL;
202 	key.node.key = &key;
203 	key.name = name;
204 	key.namelabs = namelabs;
205 	key.namelen = namelen;
206 	key.dclass = dclass;
207 	lock_basic_lock(&anchors->lock);
208 	n = rbtree_search(anchors->tree, &key);
209 	if(n) {
210 		lock_basic_lock(&((struct trust_anchor*)n->key)->lock);
211 	}
212 	lock_basic_unlock(&anchors->lock);
213 	if(!n)
214 		return NULL;
215 	return (struct trust_anchor*)n->key;
216 }
217 
218 /** create new trust anchor object */
219 static struct trust_anchor*
220 anchor_new_ta(struct val_anchors* anchors, uint8_t* name, int namelabs,
221 	size_t namelen, uint16_t dclass, int lockit)
222 {
223 #ifdef UNBOUND_DEBUG
224 	rbnode_t* r;
225 #endif
226 	struct trust_anchor* ta = (struct trust_anchor*)malloc(
227 		sizeof(struct trust_anchor));
228 	if(!ta)
229 		return NULL;
230 	memset(ta, 0, sizeof(*ta));
231 	ta->node.key = ta;
232 	ta->name = memdup(name, namelen);
233 	if(!ta->name) {
234 		free(ta);
235 		return NULL;
236 	}
237 	ta->namelabs = namelabs;
238 	ta->namelen = namelen;
239 	ta->dclass = dclass;
240 	lock_basic_init(&ta->lock);
241 	if(lockit) {
242 		lock_basic_lock(&anchors->lock);
243 	}
244 #ifdef UNBOUND_DEBUG
245 	r =
246 #else
247 	(void)
248 #endif
249 	rbtree_insert(anchors->tree, &ta->node);
250 	if(lockit) {
251 		lock_basic_unlock(&anchors->lock);
252 	}
253 	log_assert(r != NULL);
254 	return ta;
255 }
256 
257 /** find trustanchor key by exact data match */
258 static struct ta_key*
259 anchor_find_key(struct trust_anchor* ta, uint8_t* rdata, size_t rdata_len,
260 	uint16_t type)
261 {
262 	struct ta_key* k;
263 	for(k = ta->keylist; k; k = k->next) {
264 		if(k->type == type && k->len == rdata_len &&
265 			memcmp(k->data, rdata, rdata_len) == 0)
266 			return k;
267 	}
268 	return NULL;
269 }
270 
271 /** create new trustanchor key */
272 static struct ta_key*
273 anchor_new_ta_key(uint8_t* rdata, size_t rdata_len, uint16_t type)
274 {
275 	struct ta_key* k = (struct ta_key*)malloc(sizeof(*k));
276 	if(!k)
277 		return NULL;
278 	memset(k, 0, sizeof(*k));
279 	k->data = memdup(rdata, rdata_len);
280 	if(!k->data) {
281 		free(k);
282 		return NULL;
283 	}
284 	k->len = rdata_len;
285 	k->type = type;
286 	return k;
287 }
288 
289 /**
290  * This routine adds a new RR to a trust anchor. The trust anchor may not
291  * exist yet, and is created if not. The RR can be DS or DNSKEY.
292  * This routine will also remove duplicates; storing them only once.
293  * @param anchors: anchor storage.
294  * @param name: name of trust anchor (wireformat)
295  * @param type: type or RR
296  * @param dclass: class of RR
297  * @param rdata: rdata wireformat, starting with rdlength.
298  *	If NULL, nothing is stored, but an entry is created.
299  * @param rdata_len: length of rdata including rdlength.
300  * @return: NULL on error, else the trust anchor.
301  */
302 static struct trust_anchor*
303 anchor_store_new_key(struct val_anchors* anchors, uint8_t* name, uint16_t type,
304 	uint16_t dclass, uint8_t* rdata, size_t rdata_len)
305 {
306 	struct ta_key* k;
307 	struct trust_anchor* ta;
308 	int namelabs;
309 	size_t namelen;
310 	namelabs = dname_count_size_labels(name, &namelen);
311 	if(type != LDNS_RR_TYPE_DS && type != LDNS_RR_TYPE_DNSKEY) {
312 		log_err("Bad type for trust anchor");
313 		return 0;
314 	}
315 	/* lookup or create trustanchor */
316 	ta = anchor_find(anchors, name, namelabs, namelen, dclass);
317 	if(!ta) {
318 		ta = anchor_new_ta(anchors, name, namelabs, namelen, dclass, 1);
319 		if(!ta)
320 			return NULL;
321 		lock_basic_lock(&ta->lock);
322 	}
323 	if(!rdata) {
324 		lock_basic_unlock(&ta->lock);
325 		return ta;
326 	}
327 	/* look for duplicates */
328 	if(anchor_find_key(ta, rdata, rdata_len, type)) {
329 		lock_basic_unlock(&ta->lock);
330 		return ta;
331 	}
332 	k = anchor_new_ta_key(rdata, rdata_len, type);
333 	if(!k) {
334 		lock_basic_unlock(&ta->lock);
335 		return NULL;
336 	}
337 	/* add new key */
338 	if(type == LDNS_RR_TYPE_DS)
339 		ta->numDS++;
340 	else	ta->numDNSKEY++;
341 	k->next = ta->keylist;
342 	ta->keylist = k;
343 	lock_basic_unlock(&ta->lock);
344 	return ta;
345 }
346 
347 /**
348  * Add new RR. It converts ldns RR to wire format.
349  * @param anchors: anchor storage.
350  * @param rr: the wirerr.
351  * @param rl: length of rr.
352  * @param dl: length of dname.
353  * @return NULL on error, else the trust anchor.
354  */
355 static struct trust_anchor*
356 anchor_store_new_rr(struct val_anchors* anchors, uint8_t* rr, size_t rl,
357 	size_t dl)
358 {
359 	struct trust_anchor* ta;
360 	if(!(ta=anchor_store_new_key(anchors, rr,
361 		sldns_wirerr_get_type(rr, rl, dl),
362 		sldns_wirerr_get_class(rr, rl, dl),
363 		sldns_wirerr_get_rdatawl(rr, rl, dl),
364 		sldns_wirerr_get_rdatalen(rr, rl, dl)+2))) {
365 		return NULL;
366 	}
367 	log_nametypeclass(VERB_QUERY, "adding trusted key",
368 		rr, sldns_wirerr_get_type(rr, rl, dl),
369 		sldns_wirerr_get_class(rr, rl, dl));
370 	return ta;
371 }
372 
373 /**
374  * Insert insecure anchor
375  * @param anchors: anchor storage.
376  * @param str: the domain name.
377  * @return NULL on error, Else last trust anchor point
378  */
379 static struct trust_anchor*
380 anchor_insert_insecure(struct val_anchors* anchors, const char* str)
381 {
382 	struct trust_anchor* ta;
383 	size_t dname_len = 0;
384 	uint8_t* nm = sldns_str2wire_dname(str, &dname_len);
385 	if(!nm) {
386 		log_err("parse error in domain name '%s'", str);
387 		return NULL;
388 	}
389 	ta = anchor_store_new_key(anchors, nm, LDNS_RR_TYPE_DS,
390 		LDNS_RR_CLASS_IN, NULL, 0);
391 	free(nm);
392 	return ta;
393 }
394 
395 struct trust_anchor*
396 anchor_store_str(struct val_anchors* anchors, sldns_buffer* buffer,
397 	const char* str)
398 {
399 	struct trust_anchor* ta;
400 	uint8_t* rr = sldns_buffer_begin(buffer);
401 	size_t len = sldns_buffer_capacity(buffer), dname_len = 0;
402 	int status = sldns_str2wire_rr_buf(str, rr, &len, &dname_len,
403 		0, NULL, 0, NULL, 0);
404 	if(status != 0) {
405 		log_err("error parsing trust anchor %s: at %d: %s",
406 			str, LDNS_WIREPARSE_OFFSET(status),
407 			sldns_get_errorstr_parse(status));
408 		return NULL;
409 	}
410 	if(!(ta=anchor_store_new_rr(anchors, rr, len, dname_len))) {
411 		log_err("out of memory");
412 		return NULL;
413 	}
414 	return ta;
415 }
416 
417 /**
418  * Read a file with trust anchors
419  * @param anchors: anchor storage.
420  * @param buffer: parsing buffer.
421  * @param fname: string.
422  * @param onlyone: only one trust anchor allowed in file.
423  * @return NULL on error. Else last trust-anchor point.
424  */
425 static struct trust_anchor*
426 anchor_read_file(struct val_anchors* anchors, sldns_buffer* buffer,
427 	const char* fname, int onlyone)
428 {
429 	struct trust_anchor* ta = NULL, *tanew;
430 	struct sldns_file_parse_state pst;
431 	int status;
432 	size_t len, dname_len;
433 	uint8_t* rr = sldns_buffer_begin(buffer);
434 	int ok = 1;
435 	FILE* in = fopen(fname, "r");
436 	if(!in) {
437 		log_err("error opening file %s: %s", fname, strerror(errno));
438 		return 0;
439 	}
440 	memset(&pst, 0, sizeof(pst));
441 	pst.default_ttl = 3600;
442 	pst.lineno = 1;
443 	while(!feof(in)) {
444 		len = sldns_buffer_capacity(buffer);
445 		dname_len = 0;
446 		status = sldns_fp2wire_rr_buf(in, rr, &len, &dname_len, &pst);
447 		if(len == 0) /* empty, $TTL, $ORIGIN */
448 			continue;
449 		if(status != 0) {
450 			log_err("parse error in %s:%d:%d : %s", fname,
451 				pst.lineno, LDNS_WIREPARSE_OFFSET(status),
452 				sldns_get_errorstr_parse(status));
453 			ok = 0;
454 			break;
455 		}
456 		if(sldns_wirerr_get_type(rr, len, dname_len) !=
457 			LDNS_RR_TYPE_DS && sldns_wirerr_get_type(rr, len,
458 			dname_len) != LDNS_RR_TYPE_DNSKEY) {
459 			continue;
460 		}
461 		if(!(tanew=anchor_store_new_rr(anchors, rr, len, dname_len))) {
462 			log_err("mem error at %s line %d", fname, pst.lineno);
463 			ok = 0;
464 			break;
465 		}
466 		if(onlyone && ta && ta != tanew) {
467 			log_err("error at %s line %d: no multiple anchor "
468 				"domains allowed (you can have multiple "
469 				"keys, but they must have the same name).",
470 				fname, pst.lineno);
471 			ok = 0;
472 			break;
473 		}
474 		ta = tanew;
475 	}
476 	fclose(in);
477 	if(!ok) return NULL;
478 	/* empty file is OK when multiple anchors are allowed */
479 	if(!onlyone && !ta) return (struct trust_anchor*)1;
480 	return ta;
481 }
482 
483 /** skip file to end of line */
484 static void
485 skip_to_eol(FILE* in)
486 {
487 	int c;
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
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
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);
537 			(*line)++;
538 			continue;
539 		} else if(comments && c=='/' && numdone>0 && /* /_/ bla*/
540 			sldns_buffer_read_u8_at(buf,
541 			sldns_buffer_position(buf)-1) == '/') {
542 			sldns_buffer_skip(buf, -1);
543 			numdone--;
544 			skip_to_eol(in);
545 			(*line)++;
546 			continue;
547 		} else if(comments && c=='*' && numdone>0 && /* /_* bla *_/ */
548 			sldns_buffer_read_u8_at(buf,
549 			sldns_buffer_position(buf)-1) == '/') {
550 			sldns_buffer_skip(buf, -1);
551 			numdone--;
552 			/* skip to end of comment */
553 			while(c != EOF && (c=getc(in)) != EOF ) {
554 				if(c == '*') {
555 					if((c=getc(in)) == '/')
556 						break;
557 				}
558 				if(c == '\n')
559 					(*line)++;
560 			}
561 			continue;
562 		}
563 		/* not a comment, complete the keyword */
564 		if(numdone > 0) {
565 			/* check same type */
566 			if(isspace((unsigned char)c)) {
567 				ungetc(c, in);
568 				return numdone;
569 			}
570 			if(is_bind_special(c)) {
571 				ungetc(c, in);
572 				return numdone;
573 			}
574 		}
575 		if(c == '\n') {
576 			c = ' ';
577 			(*line)++;
578 		}
579 		/* space for 1 char + 0 string terminator */
580 		if(sldns_buffer_remaining(buf) < 2) {
581 			fatal_exit("trusted-keys, %d, string too long", *line);
582 		}
583 		sldns_buffer_write_u8(buf, (uint8_t)c);
584 		numdone++;
585 		if(isspace((unsigned char)c)) {
586 			/* collate whitespace into ' ' */
587 			while((c = getc(in)) != EOF ) {
588 				if(c == '\n')
589 					(*line)++;
590 				if(!isspace((unsigned char)c)) {
591 					ungetc(c, in);
592 					break;
593 				}
594 			}
595 			return numdone;
596 		}
597 		if(is_bind_special(c))
598 			return numdone;
599 	}
600 	return numdone;
601 }
602 
603 /** skip through file to { or ; */
604 static int
605 skip_to_special(FILE* in, sldns_buffer* buf, int* line, int spec)
606 {
607 	int rdlen;
608 	sldns_buffer_clear(buf);
609 	while((rdlen=readkeyword_bindfile(in, buf, line, 1))) {
610 		if(rdlen == 1 && isspace((unsigned char)*sldns_buffer_begin(buf))) {
611 			sldns_buffer_clear(buf);
612 			continue;
613 		}
614 		if(rdlen != 1 || *sldns_buffer_begin(buf) != (uint8_t)spec) {
615 			sldns_buffer_write_u8(buf, 0);
616 			log_err("trusted-keys, line %d, expected %c",
617 				*line, spec);
618 			return 0;
619 		}
620 		return 1;
621 	}
622 	log_err("trusted-keys, line %d, expected %c got EOF", *line, spec);
623 	return 0;
624 }
625 
626 /**
627  * read contents of trusted-keys{ ... ; clauses and insert keys into storage.
628  * @param anchors: where to store keys
629  * @param buf: buffer to use
630  * @param line: line number in file
631  * @param in: file to read from.
632  * @return 0 on error.
633  */
634 static int
635 process_bind_contents(struct val_anchors* anchors, sldns_buffer* buf,
636 	int* line, FILE* in)
637 {
638 	/* loop over contents, collate strings before ; */
639 	/* contents is (numbered): 0   1    2  3 4   5  6 7 8    */
640 	/*                           name. 257 3 5 base64 base64 */
641 	/* quoted value:           0 "111"  0  0 0   0  0 0 0    */
642 	/* comments value:         1 "000"  1  1  1 "0  0 0 0"  1 */
643 	int contnum = 0;
644 	int quoted = 0;
645 	int comments = 1;
646 	int rdlen;
647 	char* str = 0;
648 	sldns_buffer_clear(buf);
649 	while((rdlen=readkeyword_bindfile(in, buf, line, comments))) {
650 		if(rdlen == 1 && sldns_buffer_position(buf) == 1
651 			&& isspace((unsigned char)*sldns_buffer_begin(buf))) {
652 			/* starting whitespace is removed */
653 			sldns_buffer_clear(buf);
654 			continue;
655 		} else if(rdlen == 1 && sldns_buffer_current(buf)[-1] == '"') {
656 			/* remove " from the string */
657 			if(contnum == 0) {
658 				quoted = 1;
659 				comments = 0;
660 			}
661 			sldns_buffer_skip(buf, -1);
662 			if(contnum > 0 && quoted) {
663 				if(sldns_buffer_remaining(buf) < 8+1) {
664 					log_err("line %d, too long", *line);
665 					return 0;
666 				}
667 				sldns_buffer_write(buf, " DNSKEY ", 8);
668 				quoted = 0;
669 				comments = 1;
670 			} else if(contnum > 0)
671 				comments = !comments;
672 			continue;
673 		} else if(rdlen == 1 && sldns_buffer_current(buf)[-1] == ';') {
674 
675 			if(contnum < 5) {
676 				sldns_buffer_write_u8(buf, 0);
677 				log_err("line %d, bad key", *line);
678 				return 0;
679 			}
680 			sldns_buffer_skip(buf, -1);
681 			sldns_buffer_write_u8(buf, 0);
682 			str = strdup((char*)sldns_buffer_begin(buf));
683 			if(!str) {
684 				log_err("line %d, allocation failure", *line);
685 				return 0;
686 			}
687 			if(!anchor_store_str(anchors, buf, str)) {
688 				log_err("line %d, bad key", *line);
689 				free(str);
690 				return 0;
691 			}
692 			free(str);
693 			sldns_buffer_clear(buf);
694 			contnum = 0;
695 			quoted = 0;
696 			comments = 1;
697 			continue;
698 		} else if(rdlen == 1 && sldns_buffer_current(buf)[-1] == '}') {
699 			if(contnum > 0) {
700 				sldns_buffer_write_u8(buf, 0);
701 				log_err("line %d, bad key before }", *line);
702 				return 0;
703 			}
704 			return 1;
705 		} else if(rdlen == 1 &&
706 			isspace((unsigned char)sldns_buffer_current(buf)[-1])) {
707 			/* leave whitespace here */
708 		} else {
709 			/* not space or whatnot, so actual content */
710 			contnum ++;
711 			if(contnum == 1 && !quoted) {
712 				if(sldns_buffer_remaining(buf) < 8+1) {
713 					log_err("line %d, too long", *line);
714 					return 0;
715 				}
716 				sldns_buffer_write(buf, " DNSKEY ", 8);
717 			}
718 		}
719 	}
720 
721 	log_err("line %d, EOF before }", *line);
722 	return 0;
723 }
724 
725 /**
726  * Read a BIND9 like file with trust anchors in named.conf format.
727  * @param anchors: anchor storage.
728  * @param buffer: parsing buffer.
729  * @param fname: string.
730  * @return false on error.
731  */
732 static int
733 anchor_read_bind_file(struct val_anchors* anchors, sldns_buffer* buffer,
734 	const char* fname)
735 {
736 	int line_nr = 1;
737 	FILE* in = fopen(fname, "r");
738 	int rdlen = 0;
739 	if(!in) {
740 		log_err("error opening file %s: %s", fname, strerror(errno));
741 		return 0;
742 	}
743 	verbose(VERB_QUERY, "reading in bind-compat-mode: '%s'", fname);
744 	/* scan for  trusted-keys  keyword, ignore everything else */
745 	sldns_buffer_clear(buffer);
746 	while((rdlen=readkeyword_bindfile(in, buffer, &line_nr, 1)) != 0) {
747 		if(rdlen != 12 || strncmp((char*)sldns_buffer_begin(buffer),
748 			"trusted-keys", 12) != 0) {
749 			sldns_buffer_clear(buffer);
750 			/* ignore everything but trusted-keys */
751 			continue;
752 		}
753 		if(!skip_to_special(in, buffer, &line_nr, '{')) {
754 			log_err("error in trusted key: \"%s\"", fname);
755 			fclose(in);
756 			return 0;
757 		}
758 		/* process contents */
759 		if(!process_bind_contents(anchors, buffer, &line_nr, in)) {
760 			log_err("error in trusted key: \"%s\"", fname);
761 			fclose(in);
762 			return 0;
763 		}
764 		if(!skip_to_special(in, buffer, &line_nr, ';')) {
765 			log_err("error in trusted key: \"%s\"", fname);
766 			fclose(in);
767 			return 0;
768 		}
769 		sldns_buffer_clear(buffer);
770 	}
771 	fclose(in);
772 	return 1;
773 }
774 
775 /**
776  * Read a BIND9 like files with trust anchors in named.conf format.
777  * Performs wildcard processing of name.
778  * @param anchors: anchor storage.
779  * @param buffer: parsing buffer.
780  * @param pat: pattern string. (can be wildcarded)
781  * @return false on error.
782  */
783 static int
784 anchor_read_bind_file_wild(struct val_anchors* anchors, sldns_buffer* buffer,
785 	const char* pat)
786 {
787 #ifdef HAVE_GLOB
788 	glob_t g;
789 	size_t i;
790 	int r, flags;
791 	if(!strchr(pat, '*') && !strchr(pat, '?') && !strchr(pat, '[') &&
792 		!strchr(pat, '{') && !strchr(pat, '~')) {
793 		return anchor_read_bind_file(anchors, buffer, pat);
794 	}
795 	verbose(VERB_QUERY, "wildcard found, processing %s", pat);
796 	flags = 0
797 #ifdef GLOB_ERR
798 		| GLOB_ERR
799 #endif
800 #ifdef GLOB_NOSORT
801 		| GLOB_NOSORT
802 #endif
803 #ifdef GLOB_BRACE
804 		| GLOB_BRACE
805 #endif
806 #ifdef GLOB_TILDE
807 		| GLOB_TILDE
808 #endif
809 	;
810 	memset(&g, 0, sizeof(g));
811 	r = glob(pat, flags, NULL, &g);
812 	if(r) {
813 		/* some error */
814 		if(r == GLOB_NOMATCH) {
815 			verbose(VERB_QUERY, "trusted-keys-file: "
816 				"no matches for %s", pat);
817 			return 1;
818 		} else if(r == GLOB_NOSPACE) {
819 			log_err("wildcard trusted-keys-file %s: "
820 				"pattern out of memory", pat);
821 		} else if(r == GLOB_ABORTED) {
822 			log_err("wildcard trusted-keys-file %s: expansion "
823 				"aborted (%s)", pat, strerror(errno));
824 		} else {
825 			log_err("wildcard trusted-keys-file %s: expansion "
826 				"failed (%s)", pat, strerror(errno));
827 		}
828 		/* ignore globs that yield no files */
829 		return 1;
830 	}
831 	/* process files found, if any */
832 	for(i=0; i<(size_t)g.gl_pathc; i++) {
833 		if(!anchor_read_bind_file(anchors, buffer, g.gl_pathv[i])) {
834 			log_err("error reading wildcard "
835 				"trusted-keys-file: %s", g.gl_pathv[i]);
836 			globfree(&g);
837 			return 0;
838 		}
839 	}
840 	globfree(&g);
841 	return 1;
842 #else /* not HAVE_GLOB */
843 	return anchor_read_bind_file(anchors, buffer, pat);
844 #endif /* HAVE_GLOB */
845 }
846 
847 /**
848  * Assemble an rrset structure for the type
849  * @param ta: trust anchor.
850  * @param num: number of items to fetch from list.
851  * @param type: fetch only items of this type.
852  * @return rrset or NULL on error.
853  */
854 static struct ub_packed_rrset_key*
855 assemble_it(struct trust_anchor* ta, size_t num, uint16_t type)
856 {
857 	struct ub_packed_rrset_key* pkey = (struct ub_packed_rrset_key*)
858 		malloc(sizeof(*pkey));
859 	struct packed_rrset_data* pd;
860 	struct ta_key* tk;
861 	size_t i;
862 	if(!pkey)
863 		return NULL;
864 	memset(pkey, 0, sizeof(*pkey));
865 	pkey->rk.dname = memdup(ta->name, ta->namelen);
866 	if(!pkey->rk.dname) {
867 		free(pkey);
868 		return NULL;
869 	}
870 
871 	pkey->rk.dname_len = ta->namelen;
872 	pkey->rk.type = htons(type);
873 	pkey->rk.rrset_class = htons(ta->dclass);
874 	/* The rrset is build in an uncompressed way. This means it
875 	 * cannot be copied in the normal way. */
876 	pd = (struct packed_rrset_data*)malloc(sizeof(*pd));
877 	if(!pd) {
878 		free(pkey->rk.dname);
879 		free(pkey);
880 		return NULL;
881 	}
882 	memset(pd, 0, sizeof(*pd));
883 	pd->count = num;
884 	pd->trust = rrset_trust_ultimate;
885 	pd->rr_len = (size_t*)malloc(num*sizeof(size_t));
886 	if(!pd->rr_len) {
887 		free(pd);
888 		free(pkey->rk.dname);
889 		free(pkey);
890 		return NULL;
891 	}
892 	pd->rr_ttl = (time_t*)malloc(num*sizeof(time_t));
893 	if(!pd->rr_ttl) {
894 		free(pd->rr_len);
895 		free(pd);
896 		free(pkey->rk.dname);
897 		free(pkey);
898 		return NULL;
899 	}
900 	pd->rr_data = (uint8_t**)malloc(num*sizeof(uint8_t*));
901 	if(!pd->rr_data) {
902 		free(pd->rr_ttl);
903 		free(pd->rr_len);
904 		free(pd);
905 		free(pkey->rk.dname);
906 		free(pkey);
907 		return NULL;
908 	}
909 	/* fill in rrs */
910 	i=0;
911 	for(tk = ta->keylist; tk; tk = tk->next) {
912 		if(tk->type != type)
913 			continue;
914 		pd->rr_len[i] = tk->len;
915 		/* reuse data ptr to allocation in talist */
916 		pd->rr_data[i] = tk->data;
917 		pd->rr_ttl[i] = 0;
918 		i++;
919 	}
920 	pkey->entry.data = (void*)pd;
921 	return pkey;
922 }
923 
924 /**
925  * Assemble structures for the trust DS and DNSKEY rrsets.
926  * @param ta: trust anchor
927  * @return: false on error.
928  */
929 static int
930 anchors_assemble(struct trust_anchor* ta)
931 {
932 	if(ta->numDS > 0) {
933 		ta->ds_rrset = assemble_it(ta, ta->numDS, LDNS_RR_TYPE_DS);
934 		if(!ta->ds_rrset)
935 			return 0;
936 	}
937 	if(ta->numDNSKEY > 0) {
938 		ta->dnskey_rrset = assemble_it(ta, ta->numDNSKEY,
939 			LDNS_RR_TYPE_DNSKEY);
940 		if(!ta->dnskey_rrset)
941 			return 0;
942 	}
943 	return 1;
944 }
945 
946 /**
947  * Check DS algos for support, warn if not.
948  * @param ta: trust anchor
949  * @return number of DS anchors with unsupported algorithms.
950  */
951 static size_t
952 anchors_ds_unsupported(struct trust_anchor* ta)
953 {
954 	size_t i, num = 0;
955 	for(i=0; i<ta->numDS; i++) {
956 		if(!ds_digest_algo_is_supported(ta->ds_rrset, i) ||
957 			!ds_key_algo_is_supported(ta->ds_rrset, i))
958 			num++;
959 	}
960 	return num;
961 }
962 
963 /**
964  * Check DNSKEY algos for support, warn if not.
965  * @param ta: trust anchor
966  * @return number of DNSKEY anchors with unsupported algorithms.
967  */
968 static size_t
969 anchors_dnskey_unsupported(struct trust_anchor* ta)
970 {
971 	size_t i, num = 0;
972 	for(i=0; i<ta->numDNSKEY; i++) {
973 		if(!dnskey_algo_is_supported(ta->dnskey_rrset, i))
974 			num++;
975 	}
976 	return num;
977 }
978 
979 /**
980  * Assemble the rrsets in the anchors, ready for use by validator.
981  * @param anchors: trust anchor storage.
982  * @return: false on error.
983  */
984 static int
985 anchors_assemble_rrsets(struct val_anchors* anchors)
986 {
987 	struct trust_anchor* ta;
988 	struct trust_anchor* next;
989 	size_t nods, nokey;
990 	lock_basic_lock(&anchors->lock);
991 	ta=(struct trust_anchor*)rbtree_first(anchors->tree);
992 	while((rbnode_t*)ta != RBTREE_NULL) {
993 		next = (struct trust_anchor*)rbtree_next(&ta->node);
994 		lock_basic_lock(&ta->lock);
995 		if(ta->autr || (ta->numDS == 0 && ta->numDNSKEY == 0)) {
996 			lock_basic_unlock(&ta->lock);
997 			ta = next; /* skip */
998 			continue;
999 		}
1000 		if(!anchors_assemble(ta)) {
1001 			log_err("out of memory");
1002 			lock_basic_unlock(&ta->lock);
1003 			lock_basic_unlock(&anchors->lock);
1004 			return 0;
1005 		}
1006 		nods = anchors_ds_unsupported(ta);
1007 		nokey = anchors_dnskey_unsupported(ta);
1008 		if(nods) {
1009 			log_nametypeclass(0, "warning: unsupported "
1010 				"algorithm for trust anchor",
1011 				ta->name, LDNS_RR_TYPE_DS, ta->dclass);
1012 		}
1013 		if(nokey) {
1014 			log_nametypeclass(0, "warning: unsupported "
1015 				"algorithm for trust anchor",
1016 				ta->name, LDNS_RR_TYPE_DNSKEY, ta->dclass);
1017 		}
1018 		if(nods == ta->numDS && nokey == ta->numDNSKEY) {
1019 			char b[257];
1020 			dname_str(ta->name, b);
1021 			log_warn("trust anchor %s has no supported algorithms,"
1022 				" the anchor is ignored (check if you need to"
1023 				" upgrade unbound and openssl)", b);
1024 			(void)rbtree_delete(anchors->tree, &ta->node);
1025 			lock_basic_unlock(&ta->lock);
1026 			anchors_delfunc(&ta->node, NULL);
1027 			ta = next;
1028 			continue;
1029 		}
1030 		lock_basic_unlock(&ta->lock);
1031 		ta = next;
1032 	}
1033 	lock_basic_unlock(&anchors->lock);
1034 	return 1;
1035 }
1036 
1037 int
1038 anchors_apply_cfg(struct val_anchors* anchors, struct config_file* cfg)
1039 {
1040 	struct config_strlist* f;
1041 	char* nm;
1042 	sldns_buffer* parsebuf = sldns_buffer_new(65535);
1043 	for(f = cfg->domain_insecure; f; f = f->next) {
1044 		if(!f->str || f->str[0] == 0) /* empty "" */
1045 			continue;
1046 		if(!anchor_insert_insecure(anchors, f->str)) {
1047 			log_err("error in domain-insecure: %s", f->str);
1048 			sldns_buffer_free(parsebuf);
1049 			return 0;
1050 		}
1051 	}
1052 	for(f = cfg->trust_anchor_file_list; f; f = f->next) {
1053 		if(!f->str || f->str[0] == 0) /* empty "" */
1054 			continue;
1055 		nm = f->str;
1056 		if(cfg->chrootdir && cfg->chrootdir[0] && strncmp(nm,
1057 			cfg->chrootdir, strlen(cfg->chrootdir)) == 0)
1058 			nm += strlen(cfg->chrootdir);
1059 		if(!anchor_read_file(anchors, parsebuf, nm, 0)) {
1060 			log_err("error reading trust-anchor-file: %s", f->str);
1061 			sldns_buffer_free(parsebuf);
1062 			return 0;
1063 		}
1064 	}
1065 	for(f = cfg->trusted_keys_file_list; f; f = f->next) {
1066 		if(!f->str || f->str[0] == 0) /* empty "" */
1067 			continue;
1068 		nm = f->str;
1069 		if(cfg->chrootdir && cfg->chrootdir[0] && strncmp(nm,
1070 			cfg->chrootdir, strlen(cfg->chrootdir)) == 0)
1071 			nm += strlen(cfg->chrootdir);
1072 		if(!anchor_read_bind_file_wild(anchors, parsebuf, nm)) {
1073 			log_err("error reading trusted-keys-file: %s", f->str);
1074 			sldns_buffer_free(parsebuf);
1075 			return 0;
1076 		}
1077 	}
1078 	for(f = cfg->trust_anchor_list; f; f = f->next) {
1079 		if(!f->str || f->str[0] == 0) /* empty "" */
1080 			continue;
1081 		if(!anchor_store_str(anchors, parsebuf, f->str)) {
1082 			log_err("error in trust-anchor: \"%s\"", f->str);
1083 			sldns_buffer_free(parsebuf);
1084 			return 0;
1085 		}
1086 	}
1087 	if(cfg->dlv_anchor_file && cfg->dlv_anchor_file[0] != 0) {
1088 		struct trust_anchor* dlva;
1089 		nm = cfg->dlv_anchor_file;
1090 		if(cfg->chrootdir && cfg->chrootdir[0] && strncmp(nm,
1091 			cfg->chrootdir, strlen(cfg->chrootdir)) == 0)
1092 			nm += strlen(cfg->chrootdir);
1093 		if(!(dlva = anchor_read_file(anchors, parsebuf,
1094 			nm, 1))) {
1095 			log_err("error reading dlv-anchor-file: %s",
1096 				cfg->dlv_anchor_file);
1097 			sldns_buffer_free(parsebuf);
1098 			return 0;
1099 		}
1100 		lock_basic_lock(&anchors->lock);
1101 		anchors->dlv_anchor = dlva;
1102 		lock_basic_unlock(&anchors->lock);
1103 	}
1104 	for(f = cfg->dlv_anchor_list; f; f = f->next) {
1105 		struct trust_anchor* dlva;
1106 		if(!f->str || f->str[0] == 0) /* empty "" */
1107 			continue;
1108 		if(!(dlva = anchor_store_str(
1109 			anchors, parsebuf, f->str))) {
1110 			log_err("error in dlv-anchor: \"%s\"", f->str);
1111 			sldns_buffer_free(parsebuf);
1112 			return 0;
1113 		}
1114 		lock_basic_lock(&anchors->lock);
1115 		anchors->dlv_anchor = dlva;
1116 		lock_basic_unlock(&anchors->lock);
1117 	}
1118 	/* do autr last, so that it sees what anchors are filled by other
1119 	 * means can can print errors about double config for the name */
1120 	for(f = cfg->auto_trust_anchor_file_list; f; f = f->next) {
1121 		if(!f->str || f->str[0] == 0) /* empty "" */
1122 			continue;
1123 		nm = f->str;
1124 		if(cfg->chrootdir && cfg->chrootdir[0] && strncmp(nm,
1125 			cfg->chrootdir, strlen(cfg->chrootdir)) == 0)
1126 			nm += strlen(cfg->chrootdir);
1127 		if(!autr_read_file(anchors, nm)) {
1128 			log_err("error reading auto-trust-anchor-file: %s",
1129 				f->str);
1130 			sldns_buffer_free(parsebuf);
1131 			return 0;
1132 		}
1133 	}
1134 	/* first assemble, since it may delete useless anchors */
1135 	anchors_assemble_rrsets(anchors);
1136 	init_parents(anchors);
1137 	sldns_buffer_free(parsebuf);
1138 	if(verbosity >= VERB_ALGO) autr_debug_print(anchors);
1139 	return 1;
1140 }
1141 
1142 struct trust_anchor*
1143 anchors_lookup(struct val_anchors* anchors,
1144         uint8_t* qname, size_t qname_len, uint16_t qclass)
1145 {
1146 	struct trust_anchor key;
1147 	struct trust_anchor* result;
1148 	rbnode_t* res = NULL;
1149 	key.node.key = &key;
1150 	key.name = qname;
1151 	key.namelabs = dname_count_labels(qname);
1152 	key.namelen = qname_len;
1153 	key.dclass = qclass;
1154 	lock_basic_lock(&anchors->lock);
1155 	if(rbtree_find_less_equal(anchors->tree, &key, &res)) {
1156 		/* exact */
1157 		result = (struct trust_anchor*)res;
1158 	} else {
1159 		/* smaller element (or no element) */
1160 		int m;
1161 		result = (struct trust_anchor*)res;
1162 		if(!result || result->dclass != qclass) {
1163 			lock_basic_unlock(&anchors->lock);
1164 			return NULL;
1165 		}
1166 		/* count number of labels matched */
1167 		(void)dname_lab_cmp(result->name, result->namelabs, key.name,
1168 			key.namelabs, &m);
1169 		while(result) { /* go up until qname is subdomain of stub */
1170 			if(result->namelabs <= m)
1171 				break;
1172 			result = result->parent;
1173 		}
1174 	}
1175 	if(result) {
1176 		lock_basic_lock(&result->lock);
1177 	}
1178 	lock_basic_unlock(&anchors->lock);
1179 	return result;
1180 }
1181 
1182 size_t
1183 anchors_get_mem(struct val_anchors* anchors)
1184 {
1185 	struct trust_anchor *ta;
1186 	size_t s = sizeof(*anchors);
1187 	if(!anchors)
1188 		return 0;
1189 	RBTREE_FOR(ta, struct trust_anchor*, anchors->tree) {
1190 		s += sizeof(*ta) + ta->namelen;
1191 		/* keys and so on */
1192 	}
1193 	return s;
1194 }
1195 
1196 int
1197 anchors_add_insecure(struct val_anchors* anchors, uint16_t c, uint8_t* nm)
1198 {
1199 	struct trust_anchor key;
1200 	key.node.key = &key;
1201 	key.name = nm;
1202 	key.namelabs = dname_count_size_labels(nm, &key.namelen);
1203 	key.dclass = c;
1204 	lock_basic_lock(&anchors->lock);
1205 	if(rbtree_search(anchors->tree, &key)) {
1206 		lock_basic_unlock(&anchors->lock);
1207 		/* nothing to do, already an anchor or insecure point */
1208 		return 1;
1209 	}
1210 	if(!anchor_new_ta(anchors, nm, key.namelabs, key.namelen, c, 0)) {
1211 		log_err("out of memory");
1212 		lock_basic_unlock(&anchors->lock);
1213 		return 0;
1214 	}
1215 	/* no other contents in new ta, because it is insecure point */
1216 	anchors_init_parents_locked(anchors);
1217 	lock_basic_unlock(&anchors->lock);
1218 	return 1;
1219 }
1220 
1221 void
1222 anchors_delete_insecure(struct val_anchors* anchors, uint16_t c,
1223         uint8_t* nm)
1224 {
1225 	struct trust_anchor key;
1226 	struct trust_anchor* ta;
1227 	key.node.key = &key;
1228 	key.name = nm;
1229 	key.namelabs = dname_count_size_labels(nm, &key.namelen);
1230 	key.dclass = c;
1231 	lock_basic_lock(&anchors->lock);
1232 	if(!(ta=(struct trust_anchor*)rbtree_search(anchors->tree, &key))) {
1233 		lock_basic_unlock(&anchors->lock);
1234 		/* nothing there */
1235 		return;
1236 	}
1237 	/* lock it to drive away other threads that use it */
1238 	lock_basic_lock(&ta->lock);
1239 	/* see if its really an insecure point */
1240 	if(ta->keylist || ta->autr || ta->numDS || ta->numDNSKEY) {
1241 		lock_basic_unlock(&anchors->lock);
1242 		lock_basic_unlock(&ta->lock);
1243 		/* its not an insecure point, do not remove it */
1244 		return;
1245 	}
1246 
1247 	/* remove from tree */
1248 	(void)rbtree_delete(anchors->tree, &ta->node);
1249 	anchors_init_parents_locked(anchors);
1250 	lock_basic_unlock(&anchors->lock);
1251 
1252 	/* actual free of data */
1253 	lock_basic_unlock(&ta->lock);
1254 	anchors_delfunc(&ta->node, NULL);
1255 }
1256 
1257