xref: /freebsd/contrib/unbound/validator/val_utils.c (revision e1e636193db45630c7881246d25902e57c43d24e)
1 /*
2  * validator/val_utils.c - validator utility functions.
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 helper functions for the validator module.
40  */
41 #include "config.h"
42 #include "validator/val_utils.h"
43 #include "validator/validator.h"
44 #include "validator/val_kentry.h"
45 #include "validator/val_sigcrypt.h"
46 #include "validator/val_anchor.h"
47 #include "validator/val_nsec.h"
48 #include "validator/val_neg.h"
49 #include "services/cache/rrset.h"
50 #include "services/cache/dns.h"
51 #include "util/data/msgreply.h"
52 #include "util/data/packed_rrset.h"
53 #include "util/data/dname.h"
54 #include "util/net_help.h"
55 #include "util/module.h"
56 #include "util/regional.h"
57 #include "util/config_file.h"
58 #include "sldns/wire2str.h"
59 #include "sldns/parseutil.h"
60 
61 /** Maximum allowed digest match failures per DS, for DNSKEYs with the same
62  *  properties */
63 #define MAX_DS_MATCH_FAILURES 4
64 
65 enum val_classification
66 val_classify_response(uint16_t query_flags, struct query_info* origqinf,
67 	struct query_info* qinf, struct reply_info* rep, size_t skip)
68 {
69 	int rcode = (int)FLAGS_GET_RCODE(rep->flags);
70 	size_t i;
71 
72 	/* Normal Name Error's are easy to detect -- but don't mistake a CNAME
73 	 * chain ending in NXDOMAIN. */
74 	if(rcode == LDNS_RCODE_NXDOMAIN && rep->an_numrrsets == 0)
75 		return VAL_CLASS_NAMEERROR;
76 
77 	/* check for referral: nonRD query and it looks like a nodata */
78 	if(!(query_flags&BIT_RD) && rep->an_numrrsets == 0 &&
79 		rcode == LDNS_RCODE_NOERROR) {
80 		/* SOA record in auth indicates it is NODATA instead.
81 		 * All validation requiring NODATA messages have SOA in
82 		 * authority section. */
83 		/* uses fact that answer section is empty */
84 		int saw_ns = 0;
85 		for(i=0; i<rep->ns_numrrsets; i++) {
86 			if(ntohs(rep->rrsets[i]->rk.type) == LDNS_RR_TYPE_SOA)
87 				return VAL_CLASS_NODATA;
88 			if(ntohs(rep->rrsets[i]->rk.type) == LDNS_RR_TYPE_DS)
89 				return VAL_CLASS_REFERRAL;
90 			if(ntohs(rep->rrsets[i]->rk.type) == LDNS_RR_TYPE_NS)
91 				saw_ns = 1;
92 		}
93 		return saw_ns?VAL_CLASS_REFERRAL:VAL_CLASS_NODATA;
94 	}
95 	/* root referral where NS set is in the answer section */
96 	if(!(query_flags&BIT_RD) && rep->ns_numrrsets == 0 &&
97 		rep->an_numrrsets == 1 && rcode == LDNS_RCODE_NOERROR &&
98 		ntohs(rep->rrsets[0]->rk.type) == LDNS_RR_TYPE_NS &&
99 		query_dname_compare(rep->rrsets[0]->rk.dname,
100 			origqinf->qname) != 0)
101 		return VAL_CLASS_REFERRAL;
102 
103 	/* dump bad messages */
104 	if(rcode != LDNS_RCODE_NOERROR && rcode != LDNS_RCODE_NXDOMAIN)
105 		return VAL_CLASS_UNKNOWN;
106 	/* next check if the skip into the answer section shows no answer */
107 	if(skip>0 && rep->an_numrrsets <= skip)
108 		return VAL_CLASS_CNAMENOANSWER;
109 
110 	/* Next is NODATA */
111 	if(rcode == LDNS_RCODE_NOERROR && rep->an_numrrsets == 0)
112 		return VAL_CLASS_NODATA;
113 
114 	/* We distinguish between CNAME response and other positive/negative
115 	 * responses because CNAME answers require extra processing. */
116 
117 	/* We distinguish between ANY and CNAME or POSITIVE because
118 	 * ANY responses are validated differently. */
119 	if(rcode == LDNS_RCODE_NOERROR && qinf->qtype == LDNS_RR_TYPE_ANY)
120 		return VAL_CLASS_ANY;
121 
122 	/* Note that DNAMEs will be ignored here, unless qtype=DNAME. Unless
123 	 * qtype=CNAME, this will yield a CNAME response. */
124 	for(i=skip; i<rep->an_numrrsets; i++) {
125 		if(rcode == LDNS_RCODE_NOERROR &&
126 			ntohs(rep->rrsets[i]->rk.type) == qinf->qtype)
127 			return VAL_CLASS_POSITIVE;
128 		if(ntohs(rep->rrsets[i]->rk.type) == LDNS_RR_TYPE_CNAME)
129 			return VAL_CLASS_CNAME;
130 	}
131 	log_dns_msg("validator: error. failed to classify response message: ",
132 		qinf, rep);
133 	return VAL_CLASS_UNKNOWN;
134 }
135 
136 /** Get signer name from RRSIG */
137 static void
138 rrsig_get_signer(uint8_t* data, size_t len, uint8_t** sname, size_t* slen)
139 {
140 	/* RRSIG rdata is not allowed to be compressed, it is stored
141 	 * uncompressed in memory as well, so return a ptr to the name */
142 	if(len < 21) {
143 		/* too short RRSig:
144 		 * short, byte, byte, long, long, long, short, "." is
145 		 * 2	1	1	4	4  4	2	1 = 19
146 		 * 			and a skip of 18 bytes to the name.
147 		 * +2 for the rdatalen is 21 bytes len for root label */
148 		*sname = NULL;
149 		*slen = 0;
150 		return;
151 	}
152 	data += 20; /* skip the fixed size bits */
153 	len -= 20;
154 	*slen = dname_valid(data, len);
155 	if(!*slen) {
156 		/* bad dname in this rrsig. */
157 		*sname = NULL;
158 		return;
159 	}
160 	*sname = data;
161 }
162 
163 void
164 val_find_rrset_signer(struct ub_packed_rrset_key* rrset, uint8_t** sname,
165 	size_t* slen)
166 {
167 	struct packed_rrset_data* d = (struct packed_rrset_data*)
168 		rrset->entry.data;
169 	/* return signer for first signature, or NULL */
170 	if(d->rrsig_count == 0) {
171 		*sname = NULL;
172 		*slen = 0;
173 		return;
174 	}
175 	/* get rrsig signer name out of the signature */
176 	rrsig_get_signer(d->rr_data[d->count], d->rr_len[d->count],
177 		sname, slen);
178 }
179 
180 /**
181  * Find best signer name in this set of rrsigs.
182  * @param rrset: which rrsigs to look through.
183  * @param qinf: the query name that needs validation.
184  * @param signer_name: the best signer_name. Updated if a better one is found.
185  * @param signer_len: length of signer name.
186  * @param matchcount: count of current best name (starts at 0 for no match).
187  * 	Updated if match is improved.
188  */
189 static void
190 val_find_best_signer(struct ub_packed_rrset_key* rrset,
191 	struct query_info* qinf, uint8_t** signer_name, size_t* signer_len,
192 	int* matchcount)
193 {
194 	struct packed_rrset_data* d = (struct packed_rrset_data*)
195 		rrset->entry.data;
196 	uint8_t* sign;
197 	size_t i;
198 	int m;
199 	for(i=d->count; i<d->count+d->rrsig_count; i++) {
200 		sign = d->rr_data[i]+2+18;
201 		/* look at signatures that are valid (long enough),
202 		 * and have a signer name that is a superdomain of qname,
203 		 * and then check the number of labels in the shared topdomain
204 		 * improve the match if possible */
205 		if(d->rr_len[i] > 2+19 && /* rdata, sig + root label*/
206 			dname_subdomain_c(qinf->qname, sign)) {
207 			(void)dname_lab_cmp(qinf->qname,
208 				dname_count_labels(qinf->qname),
209 				sign, dname_count_labels(sign), &m);
210 			if(m > *matchcount) {
211 				*matchcount = m;
212 				*signer_name = sign;
213 				(void)dname_count_size_labels(*signer_name,
214 					signer_len);
215 			}
216 		}
217 	}
218 }
219 
220 void
221 val_find_signer(enum val_classification subtype, struct query_info* qinf,
222 	struct reply_info* rep, size_t skip, uint8_t** signer_name,
223 	size_t* signer_len)
224 {
225 	size_t i;
226 
227 	if(subtype == VAL_CLASS_POSITIVE) {
228 		/* check for the answer rrset */
229 		for(i=skip; i<rep->an_numrrsets; i++) {
230 			if(query_dname_compare(qinf->qname,
231 				rep->rrsets[i]->rk.dname) == 0) {
232 				val_find_rrset_signer(rep->rrsets[i],
233 					signer_name, signer_len);
234 				return;
235 			}
236 		}
237 		*signer_name = NULL;
238 		*signer_len = 0;
239 	} else if(subtype == VAL_CLASS_CNAME) {
240 		/* check for the first signed cname/dname rrset */
241 		for(i=skip; i<rep->an_numrrsets; i++) {
242 			val_find_rrset_signer(rep->rrsets[i],
243 				signer_name, signer_len);
244 			if(*signer_name)
245 				return;
246 			if(ntohs(rep->rrsets[i]->rk.type) != LDNS_RR_TYPE_DNAME)
247 				break; /* only check CNAME after a DNAME */
248 		}
249 		*signer_name = NULL;
250 		*signer_len = 0;
251 	} else if(subtype == VAL_CLASS_NAMEERROR
252 		|| subtype == VAL_CLASS_NODATA) {
253 		/*Check to see if the AUTH section NSEC record(s) have rrsigs*/
254 		for(i=rep->an_numrrsets; i<
255 			rep->an_numrrsets+rep->ns_numrrsets; i++) {
256 			if(ntohs(rep->rrsets[i]->rk.type) == LDNS_RR_TYPE_NSEC
257 				|| ntohs(rep->rrsets[i]->rk.type) ==
258 				LDNS_RR_TYPE_NSEC3) {
259 				val_find_rrset_signer(rep->rrsets[i],
260 					signer_name, signer_len);
261 				return;
262 			}
263 		}
264 	} else if(subtype == VAL_CLASS_CNAMENOANSWER) {
265 		/* find closest superdomain signer name in authority section
266 		 * NSEC and NSEC3s */
267 		int matchcount = 0;
268 		*signer_name = NULL;
269 		*signer_len = 0;
270 		for(i=rep->an_numrrsets; i<rep->an_numrrsets+rep->
271 			ns_numrrsets; i++) {
272 			if(ntohs(rep->rrsets[i]->rk.type) == LDNS_RR_TYPE_NSEC
273 				|| ntohs(rep->rrsets[i]->rk.type) ==
274 				LDNS_RR_TYPE_NSEC3) {
275 				val_find_best_signer(rep->rrsets[i], qinf,
276 					signer_name, signer_len, &matchcount);
277 			}
278 		}
279 	} else if(subtype == VAL_CLASS_ANY) {
280 		/* check for one of the answer rrset that has signatures,
281 		 * or potentially a DNAME is in use with a different qname */
282 		for(i=skip; i<rep->an_numrrsets; i++) {
283 			if(query_dname_compare(qinf->qname,
284 				rep->rrsets[i]->rk.dname) == 0) {
285 				val_find_rrset_signer(rep->rrsets[i],
286 					signer_name, signer_len);
287 				if(*signer_name)
288 					return;
289 			}
290 		}
291 		/* no answer RRSIGs with qname, try a DNAME */
292 		if(skip < rep->an_numrrsets &&
293 			ntohs(rep->rrsets[skip]->rk.type) ==
294 			LDNS_RR_TYPE_DNAME) {
295 			val_find_rrset_signer(rep->rrsets[skip],
296 				signer_name, signer_len);
297 			if(*signer_name)
298 				return;
299 		}
300 		*signer_name = NULL;
301 		*signer_len = 0;
302 	} else if(subtype == VAL_CLASS_REFERRAL) {
303 		/* find keys for the item at skip */
304 		if(skip < rep->rrset_count) {
305 			val_find_rrset_signer(rep->rrsets[skip],
306 				signer_name, signer_len);
307 			return;
308 		}
309 		*signer_name = NULL;
310 		*signer_len = 0;
311 	} else {
312 		verbose(VERB_QUERY, "find_signer: could not find signer name"
313 			" for unknown type response");
314 		*signer_name = NULL;
315 		*signer_len = 0;
316 	}
317 }
318 
319 /** return number of rrs in an rrset */
320 static size_t
321 rrset_get_count(struct ub_packed_rrset_key* rrset)
322 {
323 	struct packed_rrset_data* d = (struct packed_rrset_data*)
324 		rrset->entry.data;
325 	if(!d) return 0;
326 	return d->count;
327 }
328 
329 /** return TTL of rrset */
330 static uint32_t
331 rrset_get_ttl(struct ub_packed_rrset_key* rrset)
332 {
333 	struct packed_rrset_data* d = (struct packed_rrset_data*)
334 		rrset->entry.data;
335 	if(!d) return 0;
336 	return d->ttl;
337 }
338 
339 static enum sec_status
340 val_verify_rrset(struct module_env* env, struct val_env* ve,
341         struct ub_packed_rrset_key* rrset, struct ub_packed_rrset_key* keys,
342 	uint8_t* sigalg, char** reason, sldns_ede_code *reason_bogus,
343 	sldns_pkt_section section, struct module_qstate* qstate,
344 	int *verified)
345 {
346 	enum sec_status sec;
347 	struct packed_rrset_data* d = (struct packed_rrset_data*)rrset->
348 		entry.data;
349 	if(d->security == sec_status_secure) {
350 		/* re-verify all other statuses, because keyset may change*/
351 		log_nametypeclass(VERB_ALGO, "verify rrset cached",
352 			rrset->rk.dname, ntohs(rrset->rk.type),
353 			ntohs(rrset->rk.rrset_class));
354 		*verified = 0;
355 		return d->security;
356 	}
357 	/* check in the cache if verification has already been done */
358 	rrset_check_sec_status(env->rrset_cache, rrset, *env->now);
359 	if(d->security == sec_status_secure) {
360 		log_nametypeclass(VERB_ALGO, "verify rrset from cache",
361 			rrset->rk.dname, ntohs(rrset->rk.type),
362 			ntohs(rrset->rk.rrset_class));
363 		*verified = 0;
364 		return d->security;
365 	}
366 	log_nametypeclass(VERB_ALGO, "verify rrset", rrset->rk.dname,
367 		ntohs(rrset->rk.type), ntohs(rrset->rk.rrset_class));
368 	sec = dnskeyset_verify_rrset(env, ve, rrset, keys, sigalg, reason,
369 		reason_bogus, section, qstate, verified);
370 	verbose(VERB_ALGO, "verify result: %s", sec_status_to_string(sec));
371 	regional_free_all(env->scratch);
372 
373 	/* update rrset security status
374 	 * only improves security status
375 	 * and bogus is set only once, even if we rechecked the status */
376 	if(sec > d->security) {
377 		d->security = sec;
378 		if(sec == sec_status_secure)
379 			d->trust = rrset_trust_validated;
380 		else if(sec == sec_status_bogus) {
381 			size_t i;
382 			/* update ttl for rrset to fixed value. */
383 			d->ttl = ve->bogus_ttl;
384 			for(i=0; i<d->count+d->rrsig_count; i++)
385 				d->rr_ttl[i] = ve->bogus_ttl;
386 			/* leave RR specific TTL: not used for determine
387 			 * if RRset timed out and clients see proper value. */
388 			lock_basic_lock(&ve->bogus_lock);
389 			ve->num_rrset_bogus++;
390 			lock_basic_unlock(&ve->bogus_lock);
391 		}
392 		/* if status updated - store in cache for reuse */
393 		rrset_update_sec_status(env->rrset_cache, rrset, *env->now);
394 	}
395 
396 	return sec;
397 }
398 
399 enum sec_status
400 val_verify_rrset_entry(struct module_env* env, struct val_env* ve,
401         struct ub_packed_rrset_key* rrset, struct key_entry_key* kkey,
402 	char** reason, sldns_ede_code *reason_bogus,
403 	sldns_pkt_section section, struct module_qstate* qstate,
404 	int* verified)
405 {
406 	/* temporary dnskey rrset-key */
407 	struct ub_packed_rrset_key dnskey;
408 	struct key_entry_data* kd = (struct key_entry_data*)kkey->entry.data;
409 	enum sec_status sec;
410 	dnskey.rk.type = htons(kd->rrset_type);
411 	dnskey.rk.rrset_class = htons(kkey->key_class);
412 	dnskey.rk.flags = 0;
413 	dnskey.rk.dname = kkey->name;
414 	dnskey.rk.dname_len = kkey->namelen;
415 	dnskey.entry.key = &dnskey;
416 	dnskey.entry.data = kd->rrset_data;
417 	sec = val_verify_rrset(env, ve, rrset, &dnskey, kd->algo, reason,
418 		reason_bogus, section, qstate, verified);
419 	return sec;
420 }
421 
422 /** verify that a DS RR hashes to a key and that key signs the set */
423 static enum sec_status
424 verify_dnskeys_with_ds_rr(struct module_env* env, struct val_env* ve,
425 	struct ub_packed_rrset_key* dnskey_rrset,
426         struct ub_packed_rrset_key* ds_rrset, size_t ds_idx, char** reason,
427 	sldns_ede_code *reason_bogus, struct module_qstate* qstate,
428 	int *nonechecked)
429 {
430 	enum sec_status sec = sec_status_bogus;
431 	size_t i, num, numchecked = 0, numhashok = 0, numsizesupp = 0;
432 	num = rrset_get_count(dnskey_rrset);
433 	*nonechecked = 0;
434 	for(i=0; i<num; i++) {
435 		/* Skip DNSKEYs that don't match the basic criteria. */
436 		if(ds_get_key_algo(ds_rrset, ds_idx)
437 		   != dnskey_get_algo(dnskey_rrset, i)
438 		   || dnskey_calc_keytag(dnskey_rrset, i)
439 		   != ds_get_keytag(ds_rrset, ds_idx)) {
440 			continue;
441 		}
442 		numchecked++;
443 		verbose(VERB_ALGO, "attempt DS match algo %d keytag %d",
444 			ds_get_key_algo(ds_rrset, ds_idx),
445 			ds_get_keytag(ds_rrset, ds_idx));
446 
447 		/* Convert the candidate DNSKEY into a hash using the
448 		 * same DS hash algorithm. */
449 		if(!ds_digest_match_dnskey(env, dnskey_rrset, i, ds_rrset,
450 			ds_idx)) {
451 			verbose(VERB_ALGO, "DS match attempt failed");
452 			if(numchecked > numhashok + MAX_DS_MATCH_FAILURES) {
453 				verbose(VERB_ALGO, "DS match attempt reached "
454 					"MAX_DS_MATCH_FAILURES (%d); bogus",
455 					MAX_DS_MATCH_FAILURES);
456 				return sec_status_bogus;
457 			}
458 			continue;
459 		}
460 		numhashok++;
461 		if(!dnskey_size_is_supported(dnskey_rrset, i)) {
462 			verbose(VERB_ALGO, "DS okay but that DNSKEY size is not supported");
463 			numsizesupp++;
464 			continue;
465 		}
466 		verbose(VERB_ALGO, "DS match digest ok, trying signature");
467 
468 		/* Otherwise, we have a match! Make sure that the DNSKEY
469 		 * verifies *with this key*  */
470 		sec = dnskey_verify_rrset(env, ve, dnskey_rrset, dnskey_rrset,
471 			i, reason, reason_bogus, LDNS_SECTION_ANSWER, qstate);
472 		if(sec == sec_status_secure) {
473 			return sec;
474 		}
475 		/* If it didn't validate with the DNSKEY, try the next one! */
476 	}
477 	if(numsizesupp != 0 || sec == sec_status_indeterminate) {
478 		/* there is a working DS, but that DNSKEY is not supported */
479 		return sec_status_insecure;
480 	}
481 	if(numchecked == 0) {
482 		algo_needs_reason(env, ds_get_key_algo(ds_rrset, ds_idx),
483 			reason, "no keys have a DS");
484 		*nonechecked = 1;
485 	} else if(numhashok == 0) {
486 		*reason = "DS hash mismatches key";
487 	} else if(!*reason) {
488 		*reason = "keyset not secured by DNSKEY that matches DS";
489 	}
490 	return sec_status_bogus;
491 }
492 
493 int val_favorite_ds_algo(struct ub_packed_rrset_key* ds_rrset)
494 {
495 	size_t i, num = rrset_get_count(ds_rrset);
496 	int d, digest_algo = 0; /* DS digest algo 0 is not used. */
497 	/* find favorite algo, for now, highest number supported */
498 	for(i=0; i<num; i++) {
499 		if(!ds_digest_algo_is_supported(ds_rrset, i) ||
500 			!ds_key_algo_is_supported(ds_rrset, i)) {
501 			continue;
502 		}
503 		d = ds_get_digest_algo(ds_rrset, i);
504 		if(d > digest_algo)
505 			digest_algo = d;
506 	}
507 	return digest_algo;
508 }
509 
510 enum sec_status
511 val_verify_DNSKEY_with_DS(struct module_env* env, struct val_env* ve,
512 	struct ub_packed_rrset_key* dnskey_rrset,
513 	struct ub_packed_rrset_key* ds_rrset, uint8_t* sigalg, char** reason,
514 	sldns_ede_code *reason_bogus, struct module_qstate* qstate)
515 {
516 	/* as long as this is false, we can consider this DS rrset to be
517 	 * equivalent to no DS rrset. */
518 	int has_useful_ds = 0, digest_algo, alg, has_algo_refusal = 0,
519 		nonechecked, has_checked_ds = 0;
520 	struct algo_needs needs;
521 	size_t i, num;
522 	enum sec_status sec;
523 
524 	if(dnskey_rrset->rk.dname_len != ds_rrset->rk.dname_len ||
525 		query_dname_compare(dnskey_rrset->rk.dname, ds_rrset->rk.dname)
526 		!= 0) {
527 		verbose(VERB_QUERY, "DNSKEY RRset did not match DS RRset "
528 			"by name");
529 		*reason = "DNSKEY RRset did not match DS RRset by name";
530 		return sec_status_bogus;
531 	}
532 
533 	if(sigalg) {
534 		/* harden against algo downgrade is enabled */
535 		digest_algo = val_favorite_ds_algo(ds_rrset);
536 		algo_needs_init_ds(&needs, ds_rrset, digest_algo, sigalg);
537 	} else {
538 		/* accept any key algo, any digest algo */
539 		digest_algo = -1;
540 	}
541 	num = rrset_get_count(ds_rrset);
542 	for(i=0; i<num; i++) {
543 		/* Check to see if we can understand this DS.
544 		 * And check it is the strongest digest */
545 		if(!ds_digest_algo_is_supported(ds_rrset, i) ||
546 			!ds_key_algo_is_supported(ds_rrset, i) ||
547 			(sigalg && (ds_get_digest_algo(ds_rrset, i) != digest_algo))) {
548 			continue;
549 		}
550 
551 		sec = verify_dnskeys_with_ds_rr(env, ve, dnskey_rrset,
552 			ds_rrset, i, reason, reason_bogus, qstate,
553 			&nonechecked);
554 		if(sec == sec_status_insecure) {
555 			/* DNSKEY too large unsupported or algo refused by
556 			 * crypto lib. */
557 			has_algo_refusal = 1;
558 			continue;
559 		}
560 		if(!nonechecked)
561 			has_checked_ds = 1;
562 
563 		/* Once we see a single DS with a known digestID and
564 		 * algorithm, we cannot return INSECURE (with a
565 		 * "null" KeyEntry). */
566 		has_useful_ds = 1;
567 
568 		if(sec == sec_status_secure) {
569 			if(!sigalg || algo_needs_set_secure(&needs,
570 				(uint8_t)ds_get_key_algo(ds_rrset, i))) {
571 				verbose(VERB_ALGO, "DS matched DNSKEY.");
572 				if(!dnskeyset_size_is_supported(dnskey_rrset)) {
573 					verbose(VERB_ALGO, "DS works, but dnskeyset contain keys that are unsupported, treat as insecure");
574 					return sec_status_insecure;
575 				}
576 				return sec_status_secure;
577 			}
578 		} else if(sigalg && sec == sec_status_bogus) {
579 			algo_needs_set_bogus(&needs,
580 				(uint8_t)ds_get_key_algo(ds_rrset, i));
581 		}
582 	}
583 
584 	/* None of the DS's worked out. */
585 
586 	/* If none of the DSes have been checked, eg. that means no matches
587 	 * for keytags, and the other dses are all algo_refusal, it is an
588 	 * insecure delegation point, since the only matched DS records
589 	 * have an algo refusal, or are unsupported. */
590 	if(has_algo_refusal && !has_checked_ds) {
591 		verbose(VERB_ALGO, "No supported DS records were found -- "
592 			"treating as insecure.");
593 		return sec_status_insecure;
594 	}
595 	/* If no DSs were understandable, then this is OK. */
596 	if(!has_useful_ds) {
597 		verbose(VERB_ALGO, "No usable DS records were found -- "
598 			"treating as insecure.");
599 		return sec_status_insecure;
600 	}
601 	/* If any were understandable, then it is bad. */
602 	verbose(VERB_QUERY, "Failed to match any usable DS to a DNSKEY.");
603 	if(sigalg && (alg=algo_needs_missing(&needs)) != 0) {
604 		algo_needs_reason(env, alg, reason, "missing verification of "
605 			"DNSKEY signature");
606 	}
607 	return sec_status_bogus;
608 }
609 
610 struct key_entry_key*
611 val_verify_new_DNSKEYs(struct regional* region, struct module_env* env,
612 	struct val_env* ve, struct ub_packed_rrset_key* dnskey_rrset,
613 	struct ub_packed_rrset_key* ds_rrset, int downprot, char** reason,
614 	sldns_ede_code *reason_bogus, struct module_qstate* qstate)
615 {
616 	uint8_t sigalg[ALGO_NEEDS_MAX+1];
617 	enum sec_status sec = val_verify_DNSKEY_with_DS(env, ve,
618 		dnskey_rrset, ds_rrset, downprot?sigalg:NULL, reason,
619 		reason_bogus, qstate);
620 
621 	if(sec == sec_status_secure) {
622 		return key_entry_create_rrset(region,
623 			ds_rrset->rk.dname, ds_rrset->rk.dname_len,
624 			ntohs(ds_rrset->rk.rrset_class), dnskey_rrset,
625 			downprot?sigalg:NULL, LDNS_EDE_NONE, NULL,
626 			*env->now);
627 	} else if(sec == sec_status_insecure) {
628 		return key_entry_create_null(region, ds_rrset->rk.dname,
629 			ds_rrset->rk.dname_len,
630 			ntohs(ds_rrset->rk.rrset_class),
631 			rrset_get_ttl(ds_rrset), *reason_bogus, *reason,
632 			*env->now);
633 	}
634 	return key_entry_create_bad(region, ds_rrset->rk.dname,
635 		ds_rrset->rk.dname_len, ntohs(ds_rrset->rk.rrset_class),
636 		BOGUS_KEY_TTL, *reason_bogus, *reason, *env->now);
637 }
638 
639 enum sec_status
640 val_verify_DNSKEY_with_TA(struct module_env* env, struct val_env* ve,
641 	struct ub_packed_rrset_key* dnskey_rrset,
642 	struct ub_packed_rrset_key* ta_ds,
643 	struct ub_packed_rrset_key* ta_dnskey, uint8_t* sigalg, char** reason,
644 	sldns_ede_code *reason_bogus, struct module_qstate* qstate)
645 {
646 	/* as long as this is false, we can consider this anchor to be
647 	 * equivalent to no anchor. */
648 	int has_useful_ta = 0, digest_algo = 0, alg, has_algo_refusal = 0,
649 		nonechecked, has_checked_ds = 0;
650 	struct algo_needs needs;
651 	size_t i, num;
652 	enum sec_status sec;
653 
654 	if(ta_ds && (dnskey_rrset->rk.dname_len != ta_ds->rk.dname_len ||
655 		query_dname_compare(dnskey_rrset->rk.dname, ta_ds->rk.dname)
656 		!= 0)) {
657 		verbose(VERB_QUERY, "DNSKEY RRset did not match DS RRset "
658 			"by name");
659 		*reason = "DNSKEY RRset did not match DS RRset by name";
660 		if(reason_bogus)
661 			*reason_bogus = LDNS_EDE_DNSKEY_MISSING;
662 		return sec_status_bogus;
663 	}
664 	if(ta_dnskey && (dnskey_rrset->rk.dname_len != ta_dnskey->rk.dname_len
665 	     || query_dname_compare(dnskey_rrset->rk.dname, ta_dnskey->rk.dname)
666 		!= 0)) {
667 		verbose(VERB_QUERY, "DNSKEY RRset did not match anchor RRset "
668 			"by name");
669 		*reason = "DNSKEY RRset did not match anchor RRset by name";
670 		if(reason_bogus)
671 			*reason_bogus = LDNS_EDE_DNSKEY_MISSING;
672 		return sec_status_bogus;
673 	}
674 
675 	if(ta_ds)
676 		digest_algo = val_favorite_ds_algo(ta_ds);
677 	if(sigalg) {
678 		if(ta_ds)
679 			algo_needs_init_ds(&needs, ta_ds, digest_algo, sigalg);
680 		else	memset(&needs, 0, sizeof(needs));
681 		if(ta_dnskey)
682 			algo_needs_init_dnskey_add(&needs, ta_dnskey, sigalg);
683 	}
684 	if(ta_ds) {
685 	    num = rrset_get_count(ta_ds);
686 	    for(i=0; i<num; i++) {
687 		/* Check to see if we can understand this DS.
688 		 * And check it is the strongest digest */
689 		if(!ds_digest_algo_is_supported(ta_ds, i) ||
690 			!ds_key_algo_is_supported(ta_ds, i) ||
691 			ds_get_digest_algo(ta_ds, i) != digest_algo)
692 			continue;
693 
694 		sec = verify_dnskeys_with_ds_rr(env, ve, dnskey_rrset,
695 			ta_ds, i, reason, reason_bogus, qstate, &nonechecked);
696 		if(sec == sec_status_insecure) {
697 			has_algo_refusal = 1;
698 			continue;
699 		}
700 		if(!nonechecked)
701 			has_checked_ds = 1;
702 
703 		/* Once we see a single DS with a known digestID and
704 		 * algorithm, we cannot return INSECURE (with a
705 		 * "null" KeyEntry). */
706 		has_useful_ta = 1;
707 
708 		if(sec == sec_status_secure) {
709 			if(!sigalg || algo_needs_set_secure(&needs,
710 				(uint8_t)ds_get_key_algo(ta_ds, i))) {
711 				verbose(VERB_ALGO, "DS matched DNSKEY.");
712 				if(!dnskeyset_size_is_supported(dnskey_rrset)) {
713 					verbose(VERB_ALGO, "trustanchor works, but dnskeyset contain keys that are unsupported, treat as insecure");
714 					return sec_status_insecure;
715 				}
716 				return sec_status_secure;
717 			}
718 		} else if(sigalg && sec == sec_status_bogus) {
719 			algo_needs_set_bogus(&needs,
720 				(uint8_t)ds_get_key_algo(ta_ds, i));
721 		}
722 	    }
723 	}
724 
725 	/* None of the DS's worked out: check the DNSKEYs. */
726 	if(ta_dnskey) {
727 	    num = rrset_get_count(ta_dnskey);
728 	    for(i=0; i<num; i++) {
729 		/* Check to see if we can understand this DNSKEY */
730 		if(!dnskey_algo_is_supported(ta_dnskey, i))
731 			continue;
732 		if(!dnskey_size_is_supported(ta_dnskey, i))
733 			continue;
734 
735 		/* we saw a useful TA */
736 		has_useful_ta = 1;
737 
738 		sec = dnskey_verify_rrset(env, ve, dnskey_rrset,
739 			ta_dnskey, i, reason, reason_bogus, LDNS_SECTION_ANSWER, qstate);
740 		if(sec == sec_status_secure) {
741 			if(!sigalg || algo_needs_set_secure(&needs,
742 				(uint8_t)dnskey_get_algo(ta_dnskey, i))) {
743 				verbose(VERB_ALGO, "anchor matched DNSKEY.");
744 				if(!dnskeyset_size_is_supported(dnskey_rrset)) {
745 					verbose(VERB_ALGO, "trustanchor works, but dnskeyset contain keys that are unsupported, treat as insecure");
746 					return sec_status_insecure;
747 				}
748 				return sec_status_secure;
749 			}
750 		} else if(sigalg && sec == sec_status_bogus) {
751 			algo_needs_set_bogus(&needs,
752 				(uint8_t)dnskey_get_algo(ta_dnskey, i));
753 		}
754 	    }
755 	}
756 
757 	/* If none of the DSes have been checked, eg. that means no matches
758 	 * for keytags, and the other dses are all algo_refusal, it is an
759 	 * insecure delegation point, since the only matched DS records
760 	 * have an algo refusal, or are unsupported. */
761 	if(has_algo_refusal && !has_checked_ds) {
762 		verbose(VERB_ALGO, "No supported trust anchors were found -- "
763 			"treating as insecure.");
764 		return sec_status_insecure;
765 	}
766 	/* If no DSs were understandable, then this is OK. */
767 	if(!has_useful_ta) {
768 		verbose(VERB_ALGO, "No usable trust anchors were found -- "
769 			"treating as insecure.");
770 		return sec_status_insecure;
771 	}
772 	/* If any were understandable, then it is bad. */
773 	verbose(VERB_QUERY, "Failed to match any usable anchor to a DNSKEY.");
774 	if(sigalg && (alg=algo_needs_missing(&needs)) != 0) {
775 		algo_needs_reason(env, alg, reason, "missing verification of "
776 			"DNSKEY signature");
777 	}
778 	return sec_status_bogus;
779 }
780 
781 struct key_entry_key*
782 val_verify_new_DNSKEYs_with_ta(struct regional* region, struct module_env* env,
783 	struct val_env* ve, struct ub_packed_rrset_key* dnskey_rrset,
784 	struct ub_packed_rrset_key* ta_ds_rrset,
785 	struct ub_packed_rrset_key* ta_dnskey_rrset, int downprot,
786 	char** reason, sldns_ede_code *reason_bogus, struct module_qstate* qstate)
787 {
788 	uint8_t sigalg[ALGO_NEEDS_MAX+1];
789 	enum sec_status sec = val_verify_DNSKEY_with_TA(env, ve,
790 		dnskey_rrset, ta_ds_rrset, ta_dnskey_rrset,
791 		downprot?sigalg:NULL, reason, reason_bogus, qstate);
792 
793 	if(sec == sec_status_secure) {
794 		return key_entry_create_rrset(region,
795 			dnskey_rrset->rk.dname, dnskey_rrset->rk.dname_len,
796 			ntohs(dnskey_rrset->rk.rrset_class), dnskey_rrset,
797 			downprot?sigalg:NULL, LDNS_EDE_NONE, NULL, *env->now);
798 	} else if(sec == sec_status_insecure) {
799 		return key_entry_create_null(region, dnskey_rrset->rk.dname,
800 			dnskey_rrset->rk.dname_len,
801 			ntohs(dnskey_rrset->rk.rrset_class),
802 			rrset_get_ttl(dnskey_rrset), *reason_bogus, *reason,
803 			*env->now);
804 	}
805 	return key_entry_create_bad(region, dnskey_rrset->rk.dname,
806 		dnskey_rrset->rk.dname_len, ntohs(dnskey_rrset->rk.rrset_class),
807 		BOGUS_KEY_TTL, *reason_bogus, *reason, *env->now);
808 }
809 
810 int
811 val_dsset_isusable(struct ub_packed_rrset_key* ds_rrset)
812 {
813 	size_t i;
814 	for(i=0; i<rrset_get_count(ds_rrset); i++) {
815 		if(ds_digest_algo_is_supported(ds_rrset, i) &&
816 			ds_key_algo_is_supported(ds_rrset, i))
817 			return 1;
818 	}
819 	if(verbosity < VERB_ALGO)
820 		return 0;
821 	if(rrset_get_count(ds_rrset) == 0)
822 		verbose(VERB_ALGO, "DS is not usable");
823 	else {
824 		/* report usability for the first DS RR */
825 		sldns_lookup_table *lt;
826 		char herr[64], aerr[64];
827 		lt = sldns_lookup_by_id(sldns_hashes,
828 			(int)ds_get_digest_algo(ds_rrset, 0));
829 		if(lt) snprintf(herr, sizeof(herr), "%s", lt->name);
830 		else snprintf(herr, sizeof(herr), "%d",
831 			(int)ds_get_digest_algo(ds_rrset, 0));
832 		lt = sldns_lookup_by_id(sldns_algorithms,
833 			(int)ds_get_key_algo(ds_rrset, 0));
834 		if(lt) snprintf(aerr, sizeof(aerr), "%s", lt->name);
835 		else snprintf(aerr, sizeof(aerr), "%d",
836 			(int)ds_get_key_algo(ds_rrset, 0));
837 
838 		verbose(VERB_ALGO, "DS unsupported, hash %s %s, "
839 			"key algorithm %s %s", herr,
840 			(ds_digest_algo_is_supported(ds_rrset, 0)?
841 			"(supported)":"(unsupported)"), aerr,
842 			(ds_key_algo_is_supported(ds_rrset, 0)?
843 			"(supported)":"(unsupported)"));
844 	}
845 	return 0;
846 }
847 
848 /** get label count for a signature */
849 static uint8_t
850 rrsig_get_labcount(struct packed_rrset_data* d, size_t sig)
851 {
852 	if(d->rr_len[sig] < 2+4)
853 		return 0; /* bad sig length */
854 	return d->rr_data[sig][2+3];
855 }
856 
857 int
858 val_rrset_wildcard(struct ub_packed_rrset_key* rrset, uint8_t** wc,
859 	size_t* wc_len)
860 {
861 	struct packed_rrset_data* d = (struct packed_rrset_data*)rrset->
862 		entry.data;
863 	uint8_t labcount;
864 	int labdiff;
865 	uint8_t* wn;
866 	size_t i, wl;
867 	if(d->rrsig_count == 0) {
868 		return 1;
869 	}
870 	labcount = rrsig_get_labcount(d, d->count + 0);
871 	/* check rest of signatures identical */
872 	for(i=1; i<d->rrsig_count; i++) {
873 		if(labcount != rrsig_get_labcount(d, d->count + i)) {
874 			return 0;
875 		}
876 	}
877 	/* OK the rrsigs check out */
878 	/* if the RRSIG label count is shorter than the number of actual
879 	 * labels, then this rrset was synthesized from a wildcard.
880 	 * Note that the RRSIG label count doesn't count the root label. */
881 	wn = rrset->rk.dname;
882 	wl = rrset->rk.dname_len;
883 	/* skip a leading wildcard label in the dname (RFC4035 2.2) */
884 	if(dname_is_wild(wn)) {
885 		wn += 2;
886 		wl -= 2;
887 	}
888 	labdiff = (dname_count_labels(wn) - 1) - (int)labcount;
889 	if(labdiff > 0) {
890 		*wc = wn;
891 		dname_remove_labels(wc, &wl, labdiff);
892 		*wc_len = wl;
893 		return 1;
894 	}
895 	return 1;
896 }
897 
898 int
899 val_chase_cname(struct query_info* qchase, struct reply_info* rep,
900 	size_t* cname_skip) {
901 	size_t i;
902 	/* skip any DNAMEs, go to the CNAME for next part */
903 	for(i = *cname_skip; i < rep->an_numrrsets; i++) {
904 		if(ntohs(rep->rrsets[i]->rk.type) == LDNS_RR_TYPE_CNAME &&
905 			query_dname_compare(qchase->qname, rep->rrsets[i]->
906 				rk.dname) == 0) {
907 			qchase->qname = NULL;
908 			get_cname_target(rep->rrsets[i], &qchase->qname,
909 				&qchase->qname_len);
910 			if(!qchase->qname)
911 				return 0; /* bad CNAME rdata */
912 			(*cname_skip) = i+1;
913 			return 1;
914 		}
915 	}
916 	return 0; /* CNAME classified but no matching CNAME ?! */
917 }
918 
919 /** see if rrset has signer name as one of the rrsig signers */
920 static int
921 rrset_has_signer(struct ub_packed_rrset_key* rrset, uint8_t* name, size_t len)
922 {
923 	struct packed_rrset_data* d = (struct packed_rrset_data*)rrset->
924 		entry.data;
925 	size_t i;
926 	for(i = d->count; i< d->count+d->rrsig_count; i++) {
927 		if(d->rr_len[i] > 2+18+len) {
928 			/* at least rdatalen + signature + signame (+1 sig)*/
929 			if(!dname_valid(d->rr_data[i]+2+18, d->rr_len[i]-2-18))
930 				continue;
931 			if(query_dname_compare(name, d->rr_data[i]+2+18) == 0)
932 			{
933 				return 1;
934 			}
935 		}
936 	}
937 	return 0;
938 }
939 
940 void
941 val_fill_reply(struct reply_info* chase, struct reply_info* orig,
942 	size_t skip, uint8_t* name, size_t len, uint8_t* signer)
943 {
944 	size_t i;
945 	int seen_dname = 0;
946 	chase->rrset_count = 0;
947 	chase->an_numrrsets = 0;
948 	chase->ns_numrrsets = 0;
949 	chase->ar_numrrsets = 0;
950 	/* ANSWER section */
951 	for(i=skip; i<orig->an_numrrsets; i++) {
952 		if(!signer) {
953 			if(query_dname_compare(name,
954 				orig->rrsets[i]->rk.dname) == 0)
955 				chase->rrsets[chase->an_numrrsets++] =
956 					orig->rrsets[i];
957 		} else if(seen_dname && ntohs(orig->rrsets[i]->rk.type) ==
958 			LDNS_RR_TYPE_CNAME) {
959 			chase->rrsets[chase->an_numrrsets++] = orig->rrsets[i];
960 			seen_dname = 0;
961 		} else if(rrset_has_signer(orig->rrsets[i], name, len)) {
962 			chase->rrsets[chase->an_numrrsets++] = orig->rrsets[i];
963 			if(ntohs(orig->rrsets[i]->rk.type) ==
964 				LDNS_RR_TYPE_DNAME) {
965 					seen_dname = 1;
966 			}
967 		}
968 	}
969 	/* AUTHORITY section */
970 	for(i = (skip > orig->an_numrrsets)?skip:orig->an_numrrsets;
971 		i<orig->an_numrrsets+orig->ns_numrrsets;
972 		i++) {
973 		if(!signer) {
974 			if(query_dname_compare(name,
975 				orig->rrsets[i]->rk.dname) == 0)
976 				chase->rrsets[chase->an_numrrsets+
977 				    chase->ns_numrrsets++] = orig->rrsets[i];
978 		} else if(rrset_has_signer(orig->rrsets[i], name, len)) {
979 			chase->rrsets[chase->an_numrrsets+
980 				chase->ns_numrrsets++] = orig->rrsets[i];
981 		}
982 	}
983 	/* ADDITIONAL section */
984 	for(i= (skip>orig->an_numrrsets+orig->ns_numrrsets)?
985 		skip:orig->an_numrrsets+orig->ns_numrrsets;
986 		i<orig->rrset_count; i++) {
987 		if(!signer) {
988 			if(query_dname_compare(name,
989 				orig->rrsets[i]->rk.dname) == 0)
990 			    chase->rrsets[chase->an_numrrsets
991 				+orig->ns_numrrsets+chase->ar_numrrsets++]
992 				= orig->rrsets[i];
993 		} else if(rrset_has_signer(orig->rrsets[i], name, len)) {
994 			chase->rrsets[chase->an_numrrsets+orig->ns_numrrsets+
995 				chase->ar_numrrsets++] = orig->rrsets[i];
996 		}
997 	}
998 	chase->rrset_count = chase->an_numrrsets + chase->ns_numrrsets +
999 		chase->ar_numrrsets;
1000 }
1001 
1002 void val_reply_remove_auth(struct reply_info* rep, size_t index)
1003 {
1004 	log_assert(index < rep->rrset_count);
1005 	log_assert(index >= rep->an_numrrsets);
1006 	log_assert(index < rep->an_numrrsets+rep->ns_numrrsets);
1007 	memmove(rep->rrsets+index, rep->rrsets+index+1,
1008 		sizeof(struct ub_packed_rrset_key*)*
1009 		(rep->rrset_count - index - 1));
1010 	rep->ns_numrrsets--;
1011 	rep->rrset_count--;
1012 }
1013 
1014 void
1015 val_check_nonsecure(struct module_env* env, struct reply_info* rep)
1016 {
1017 	size_t i;
1018 	/* authority */
1019 	for(i=rep->an_numrrsets; i<rep->an_numrrsets+rep->ns_numrrsets; i++) {
1020 		if(((struct packed_rrset_data*)rep->rrsets[i]->entry.data)
1021 			->security != sec_status_secure) {
1022 			/* because we want to return the authentic original
1023 			 * message when presented with CD-flagged queries,
1024 			 * we need to preserve AUTHORITY section data.
1025 			 * However, this rrset is not signed or signed
1026 			 * with the wrong keys. Validation has tried to
1027 			 * verify this rrset with the keysets of import.
1028 			 * But this rrset did not verify.
1029 			 * Therefore the message is bogus.
1030 			 */
1031 
1032 			/* check if authority has an NS record
1033 			 * which is bad, and there is an answer section with
1034 			 * data.  In that case, delete NS and additional to
1035 			 * be lenient and make a minimal response */
1036 			if(rep->an_numrrsets != 0 &&
1037 				ntohs(rep->rrsets[i]->rk.type)
1038 				== LDNS_RR_TYPE_NS) {
1039 				verbose(VERB_ALGO, "truncate to minimal");
1040 				rep->ar_numrrsets = 0;
1041 				rep->rrset_count = rep->an_numrrsets +
1042 					rep->ns_numrrsets;
1043 				/* remove this unneeded authority rrset */
1044 				memmove(rep->rrsets+i, rep->rrsets+i+1,
1045 					sizeof(struct ub_packed_rrset_key*)*
1046 					(rep->rrset_count - i - 1));
1047 				rep->ns_numrrsets--;
1048 				rep->rrset_count--;
1049 				i--;
1050 				return;
1051 			}
1052 
1053 			log_nametypeclass(VERB_QUERY, "message is bogus, "
1054 				"non secure rrset",
1055 				rep->rrsets[i]->rk.dname,
1056 				ntohs(rep->rrsets[i]->rk.type),
1057 				ntohs(rep->rrsets[i]->rk.rrset_class));
1058 			rep->security = sec_status_bogus;
1059 			return;
1060 		}
1061 	}
1062 	/* additional */
1063 	if(!env->cfg->val_clean_additional)
1064 		return;
1065 	for(i=rep->an_numrrsets+rep->ns_numrrsets; i<rep->rrset_count; i++) {
1066 		if(((struct packed_rrset_data*)rep->rrsets[i]->entry.data)
1067 			->security != sec_status_secure) {
1068 			/* This does not cause message invalidation. It was
1069 			 * simply unsigned data in the additional. The
1070 			 * RRSIG must have been truncated off the message.
1071 			 *
1072 			 * However, we do not want to return possible bogus
1073 			 * data to clients that rely on this service for
1074 			 * their authentication.
1075 			 */
1076 			/* remove this unneeded additional rrset */
1077 			memmove(rep->rrsets+i, rep->rrsets+i+1,
1078 				sizeof(struct ub_packed_rrset_key*)*
1079 				(rep->rrset_count - i - 1));
1080 			rep->ar_numrrsets--;
1081 			rep->rrset_count--;
1082 			i--;
1083 		}
1084 	}
1085 }
1086 
1087 /** check no anchor and unlock */
1088 static int
1089 check_no_anchor(struct val_anchors* anchors, uint8_t* nm, size_t l, uint16_t c)
1090 {
1091 	struct trust_anchor* ta;
1092 	if((ta=anchors_lookup(anchors, nm, l, c))) {
1093 		lock_basic_unlock(&ta->lock);
1094 	}
1095 	return !ta;
1096 }
1097 
1098 void
1099 val_mark_indeterminate(struct reply_info* rep, struct val_anchors* anchors,
1100 	struct rrset_cache* r, struct module_env* env)
1101 {
1102 	size_t i;
1103 	struct packed_rrset_data* d;
1104 	for(i=0; i<rep->rrset_count; i++) {
1105 		d = (struct packed_rrset_data*)rep->rrsets[i]->entry.data;
1106 		if(d->security == sec_status_unchecked &&
1107 		   check_no_anchor(anchors, rep->rrsets[i]->rk.dname,
1108 			rep->rrsets[i]->rk.dname_len,
1109 			ntohs(rep->rrsets[i]->rk.rrset_class)))
1110 		{
1111 			/* mark as indeterminate */
1112 			d->security = sec_status_indeterminate;
1113 			rrset_update_sec_status(r, rep->rrsets[i], *env->now);
1114 		}
1115 	}
1116 }
1117 
1118 void
1119 val_mark_insecure(struct reply_info* rep, uint8_t* kname,
1120 	struct rrset_cache* r, struct module_env* env)
1121 {
1122 	size_t i;
1123 	struct packed_rrset_data* d;
1124 	for(i=0; i<rep->rrset_count; i++) {
1125 		d = (struct packed_rrset_data*)rep->rrsets[i]->entry.data;
1126 		if(d->security == sec_status_unchecked &&
1127 		   dname_subdomain_c(rep->rrsets[i]->rk.dname, kname)) {
1128 			/* mark as insecure */
1129 			d->security = sec_status_insecure;
1130 			rrset_update_sec_status(r, rep->rrsets[i], *env->now);
1131 		}
1132 	}
1133 }
1134 
1135 size_t
1136 val_next_unchecked(struct reply_info* rep, size_t skip)
1137 {
1138 	size_t i;
1139 	struct packed_rrset_data* d;
1140 	for(i=skip+1; i<rep->rrset_count; i++) {
1141 		d = (struct packed_rrset_data*)rep->rrsets[i]->entry.data;
1142 		if(d->security == sec_status_unchecked) {
1143 			return i;
1144 		}
1145 	}
1146 	return rep->rrset_count;
1147 }
1148 
1149 const char*
1150 val_classification_to_string(enum val_classification subtype)
1151 {
1152 	switch(subtype) {
1153 		case VAL_CLASS_UNTYPED: 	return "untyped";
1154 		case VAL_CLASS_UNKNOWN: 	return "unknown";
1155 		case VAL_CLASS_POSITIVE: 	return "positive";
1156 		case VAL_CLASS_CNAME: 		return "cname";
1157 		case VAL_CLASS_NODATA: 		return "nodata";
1158 		case VAL_CLASS_NAMEERROR: 	return "nameerror";
1159 		case VAL_CLASS_CNAMENOANSWER: 	return "cnamenoanswer";
1160 		case VAL_CLASS_REFERRAL: 	return "referral";
1161 		case VAL_CLASS_ANY: 		return "qtype_any";
1162 		default:
1163 			return "bad_val_classification";
1164 	}
1165 }
1166 
1167 /** log a sock_list entry */
1168 static void
1169 sock_list_logentry(enum verbosity_value v, const char* s, struct sock_list* p)
1170 {
1171 	if(p->len)
1172 		log_addr(v, s, &p->addr, p->len);
1173 	else	verbose(v, "%s cache", s);
1174 }
1175 
1176 void val_blacklist(struct sock_list** blacklist, struct regional* region,
1177 	struct sock_list* origin, int cross)
1178 {
1179 	/* debug printout */
1180 	if(verbosity >= VERB_ALGO) {
1181 		struct sock_list* p;
1182 		for(p=*blacklist; p; p=p->next)
1183 			sock_list_logentry(VERB_ALGO, "blacklist", p);
1184 		if(!origin)
1185 			verbose(VERB_ALGO, "blacklist add: cache");
1186 		for(p=origin; p; p=p->next)
1187 			sock_list_logentry(VERB_ALGO, "blacklist add", p);
1188 	}
1189 	/* blacklist the IPs or the cache */
1190 	if(!origin) {
1191 		/* only add if nothing there. anything else also stops cache*/
1192 		if(!*blacklist)
1193 			sock_list_insert(blacklist, NULL, 0, region);
1194 	} else if(!cross)
1195 		sock_list_prepend(blacklist, origin);
1196 	else	sock_list_merge(blacklist, region, origin);
1197 }
1198 
1199 int val_has_signed_nsecs(struct reply_info* rep, char** reason)
1200 {
1201 	size_t i, num_nsec = 0, num_nsec3 = 0;
1202 	struct packed_rrset_data* d;
1203 	for(i=rep->an_numrrsets; i<rep->an_numrrsets+rep->ns_numrrsets; i++) {
1204 		if(rep->rrsets[i]->rk.type == htons(LDNS_RR_TYPE_NSEC))
1205 			num_nsec++;
1206 		else if(rep->rrsets[i]->rk.type == htons(LDNS_RR_TYPE_NSEC3))
1207 			num_nsec3++;
1208 		else continue;
1209 		d = (struct packed_rrset_data*)rep->rrsets[i]->entry.data;
1210 		if(d && d->rrsig_count != 0) {
1211 			return 1;
1212 		}
1213 	}
1214 	if(num_nsec == 0 && num_nsec3 == 0)
1215 		*reason = "no DNSSEC records";
1216 	else if(num_nsec != 0)
1217 		*reason = "no signatures over NSECs";
1218 	else	*reason = "no signatures over NSEC3s";
1219 	return 0;
1220 }
1221 
1222 struct dns_msg*
1223 val_find_DS(struct module_env* env, uint8_t* nm, size_t nmlen, uint16_t c,
1224 	struct regional* region, uint8_t* topname)
1225 {
1226 	struct dns_msg* msg;
1227 	struct query_info qinfo;
1228 	struct ub_packed_rrset_key *rrset = rrset_cache_lookup(
1229 		env->rrset_cache, nm, nmlen, LDNS_RR_TYPE_DS, c, 0,
1230 		*env->now, 0);
1231 	if(rrset) {
1232 		/* DS rrset exists. Return it to the validator immediately*/
1233 		struct ub_packed_rrset_key* copy = packed_rrset_copy_region(
1234 			rrset, region, *env->now);
1235 		lock_rw_unlock(&rrset->entry.lock);
1236 		if(!copy)
1237 			return NULL;
1238 		msg = dns_msg_create(nm, nmlen, LDNS_RR_TYPE_DS, c, region, 1);
1239 		if(!msg)
1240 			return NULL;
1241 		msg->rep->rrsets[0] = copy;
1242 		msg->rep->rrset_count++;
1243 		msg->rep->an_numrrsets++;
1244 		return msg;
1245 	}
1246 	/* lookup in rrset and negative cache for NSEC/NSEC3 */
1247 	qinfo.qname = nm;
1248 	qinfo.qname_len = nmlen;
1249 	qinfo.qtype = LDNS_RR_TYPE_DS;
1250 	qinfo.qclass = c;
1251 	qinfo.local_alias = NULL;
1252 	/* do not add SOA to reply message, it is going to be used internal */
1253 	msg = val_neg_getmsg(env->neg_cache, &qinfo, region, env->rrset_cache,
1254 		env->scratch_buffer, *env->now, 0, topname, env->cfg);
1255 	return msg;
1256 }
1257