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