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