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