xref: /openbsd-src/usr.sbin/unbound/validator/val_nsec3.c (revision 4c1e55dc91edd6e69ccc60ce855900fbc12cf34f)
1 /*
2  * validator/val_nsec3.c - validator NSEC3 denial of existance 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  * The functions help with NSEC3 checking, the different NSEC3 proofs
41  * for denial of existance, and proofs for presence of types.
42  */
43 #include "config.h"
44 #include <ctype.h>
45 #ifdef HAVE_OPENSSL_SSL_H
46 #include "openssl/ssl.h"
47 #endif
48 #include "validator/val_nsec3.h"
49 #include "validator/validator.h"
50 #include "validator/val_kentry.h"
51 #include "services/cache/rrset.h"
52 #include "util/regional.h"
53 #include "util/rbtree.h"
54 #include "util/module.h"
55 #include "util/net_help.h"
56 #include "util/data/packed_rrset.h"
57 #include "util/data/dname.h"
58 #include "util/data/msgreply.h"
59 /* we include nsec.h for the bitmap_has_type function */
60 #include "validator/val_nsec.h"
61 
62 /**
63  * This function we get from ldns-compat or from base system
64  * it returns the number of data bytes stored at the target, or <0 on error.
65  */
66 int ldns_b32_ntop_extended_hex(uint8_t const *src, size_t srclength,
67 	char *target, size_t targsize);
68 /**
69  * This function we get from ldns-compat or from base system
70  * it returns the number of data bytes stored at the target, or <0 on error.
71  */
72 int ldns_b32_pton_extended_hex(char const *src, size_t hashed_owner_str_len,
73 	uint8_t *target, size_t targsize);
74 
75 /**
76  * Closest encloser (ce) proof results
77  * Contains the ce and the next-closer (nc) proof.
78  */
79 struct ce_response {
80 	/** the closest encloser name */
81 	uint8_t* ce;
82 	/** length of ce */
83 	size_t ce_len;
84 	/** NSEC3 record that proved ce. rrset */
85 	struct ub_packed_rrset_key* ce_rrset;
86 	/** NSEC3 record that proved ce. rr number */
87 	int ce_rr;
88 	/** NSEC3 record that proved nc. rrset */
89 	struct ub_packed_rrset_key* nc_rrset;
90 	/** NSEC3 record that proved nc. rr*/
91 	int nc_rr;
92 };
93 
94 /**
95  * Filter conditions for NSEC3 proof
96  * Used to iterate over the applicable NSEC3 RRs.
97  */
98 struct nsec3_filter {
99 	/** Zone name, only NSEC3 records for this zone are considered */
100 	uint8_t* zone;
101 	/** length of the zonename */
102 	size_t zone_len;
103 	/** the list of NSEC3s to filter; array */
104 	struct ub_packed_rrset_key** list;
105 	/** number of rrsets in list */
106 	size_t num;
107 	/** class of records for the NSEC3, only this class applies */
108 	uint16_t fclass;
109 };
110 
111 /** return number of rrs in an rrset */
112 static size_t
113 rrset_get_count(struct ub_packed_rrset_key* rrset)
114 {
115         struct packed_rrset_data* d = (struct packed_rrset_data*)
116 	        rrset->entry.data;
117         if(!d) return 0;
118         return d->count;
119 }
120 
121 /** return if nsec3 RR has unknown flags */
122 static int
123 nsec3_unknown_flags(struct ub_packed_rrset_key* rrset, int r)
124 {
125         struct packed_rrset_data* d = (struct packed_rrset_data*)
126 	        rrset->entry.data;
127 	log_assert(d && r < (int)d->count);
128 	if(d->rr_len[r] < 2+2)
129 		return 0; /* malformed */
130 	return (int)(d->rr_data[r][2+1] & NSEC3_UNKNOWN_FLAGS);
131 }
132 
133 int
134 nsec3_has_optout(struct ub_packed_rrset_key* rrset, int r)
135 {
136         struct packed_rrset_data* d = (struct packed_rrset_data*)
137 	        rrset->entry.data;
138 	log_assert(d && r < (int)d->count);
139 	if(d->rr_len[r] < 2+2)
140 		return 0; /* malformed */
141 	return (int)(d->rr_data[r][2+1] & NSEC3_OPTOUT);
142 }
143 
144 /** return nsec3 RR algorithm */
145 static int
146 nsec3_get_algo(struct ub_packed_rrset_key* rrset, int r)
147 {
148         struct packed_rrset_data* d = (struct packed_rrset_data*)
149 	        rrset->entry.data;
150 	log_assert(d && r < (int)d->count);
151 	if(d->rr_len[r] < 2+1)
152 		return 0; /* malformed */
153 	return (int)(d->rr_data[r][2+0]);
154 }
155 
156 /** return if nsec3 RR has known algorithm */
157 static int
158 nsec3_known_algo(struct ub_packed_rrset_key* rrset, int r)
159 {
160         struct packed_rrset_data* d = (struct packed_rrset_data*)
161 	        rrset->entry.data;
162 	log_assert(d && r < (int)d->count);
163 	if(d->rr_len[r] < 2+1)
164 		return 0; /* malformed */
165 	switch(d->rr_data[r][2+0]) {
166 		case NSEC3_HASH_SHA1:
167 			return 1;
168 	}
169 	return 0;
170 }
171 
172 /** return nsec3 RR iteration count */
173 static size_t
174 nsec3_get_iter(struct ub_packed_rrset_key* rrset, int r)
175 {
176 	uint16_t i;
177         struct packed_rrset_data* d = (struct packed_rrset_data*)
178 	        rrset->entry.data;
179 	log_assert(d && r < (int)d->count);
180 	if(d->rr_len[r] < 2+4)
181 		return 0; /* malformed */
182 	memmove(&i, d->rr_data[r]+2+2, sizeof(i));
183 	i = ntohs(i);
184 	return (size_t)i;
185 }
186 
187 /** return nsec3 RR salt */
188 static int
189 nsec3_get_salt(struct ub_packed_rrset_key* rrset, int r,
190 	uint8_t** salt, size_t* saltlen)
191 {
192         struct packed_rrset_data* d = (struct packed_rrset_data*)
193 	        rrset->entry.data;
194 	log_assert(d && r < (int)d->count);
195 	if(d->rr_len[r] < 2+5) {
196 		*salt = 0;
197 		*saltlen = 0;
198 		return 0; /* malformed */
199 	}
200 	*saltlen = (size_t)d->rr_data[r][2+4];
201 	if(d->rr_len[r] < 2+5+(size_t)*saltlen) {
202 		*salt = 0;
203 		*saltlen = 0;
204 		return 0; /* malformed */
205 	}
206 	*salt = d->rr_data[r]+2+5;
207 	return 1;
208 }
209 
210 int nsec3_get_params(struct ub_packed_rrset_key* rrset, int r,
211 	int* algo, size_t* iter, uint8_t** salt, size_t* saltlen)
212 {
213 	if(!nsec3_known_algo(rrset, r) || nsec3_unknown_flags(rrset, r))
214 		return 0;
215 	if(!nsec3_get_salt(rrset, r, salt, saltlen))
216 		return 0;
217 	*algo = nsec3_get_algo(rrset, r);
218 	*iter = nsec3_get_iter(rrset, r);
219 	return 1;
220 }
221 
222 int
223 nsec3_get_nextowner(struct ub_packed_rrset_key* rrset, int r,
224 	uint8_t** next, size_t* nextlen)
225 {
226 	size_t saltlen;
227         struct packed_rrset_data* d = (struct packed_rrset_data*)
228 	        rrset->entry.data;
229 	log_assert(d && r < (int)d->count);
230 	if(d->rr_len[r] < 2+5) {
231 		*next = 0;
232 		*nextlen = 0;
233 		return 0; /* malformed */
234 	}
235 	saltlen = (size_t)d->rr_data[r][2+4];
236 	if(d->rr_len[r] < 2+5+saltlen+1) {
237 		*next = 0;
238 		*nextlen = 0;
239 		return 0; /* malformed */
240 	}
241 	*nextlen = (size_t)d->rr_data[r][2+5+saltlen];
242 	if(d->rr_len[r] < 2+5+saltlen+1+*nextlen) {
243 		*next = 0;
244 		*nextlen = 0;
245 		return 0; /* malformed */
246 	}
247 	*next = d->rr_data[r]+2+5+saltlen+1;
248 	return 1;
249 }
250 
251 size_t nsec3_hash_to_b32(uint8_t* hash, size_t hashlen, uint8_t* zone,
252 	size_t zonelen, uint8_t* buf, size_t max)
253 {
254 	/* write b32 of name, leave one for length */
255 	int ret;
256 	if(max < hashlen*2+1) /* quick approx of b32, as if hexb16 */
257 		return 0;
258 	ret = ldns_b32_ntop_extended_hex(hash, hashlen, (char*)buf+1, max-1);
259 	if(ret < 1)
260 		return 0;
261 	buf[0] = (uint8_t)ret; /* length of b32 label */
262 	ret++;
263 	if(max - ret < zonelen)
264 		return 0;
265 	memmove(buf+ret, zone, zonelen);
266 	return zonelen+(size_t)ret;
267 }
268 
269 size_t nsec3_get_nextowner_b32(struct ub_packed_rrset_key* rrset, int r,
270 	uint8_t* buf, size_t max)
271 {
272 	uint8_t* nm, *zone;
273 	size_t nmlen, zonelen;
274 	if(!nsec3_get_nextowner(rrset, r, &nm, &nmlen))
275 		return 0;
276 	/* append zone name; the owner name must be <b32>.zone */
277 	zone = rrset->rk.dname;
278 	zonelen = rrset->rk.dname_len;
279 	dname_remove_label(&zone, &zonelen);
280 	return nsec3_hash_to_b32(nm, nmlen, zone, zonelen, buf, max);
281 }
282 
283 int
284 nsec3_has_type(struct ub_packed_rrset_key* rrset, int r, uint16_t type)
285 {
286 	uint8_t* bitmap;
287 	size_t bitlen, skiplen;
288         struct packed_rrset_data* d = (struct packed_rrset_data*)
289 	        rrset->entry.data;
290 	log_assert(d && r < (int)d->count);
291 	skiplen = 2+4;
292 	/* skip salt */
293 	if(d->rr_len[r] < skiplen+1)
294 		return 0; /* malformed, too short */
295 	skiplen += 1+(size_t)d->rr_data[r][skiplen];
296 	/* skip next hashed owner */
297 	if(d->rr_len[r] < skiplen+1)
298 		return 0; /* malformed, too short */
299 	skiplen += 1+(size_t)d->rr_data[r][skiplen];
300 	if(d->rr_len[r] < skiplen)
301 		return 0; /* malformed, too short */
302 	bitlen = d->rr_len[r] - skiplen;
303 	bitmap = d->rr_data[r]+skiplen;
304 	return nsecbitmap_has_type_rdata(bitmap, bitlen, type);
305 }
306 
307 /**
308  * Iterate through NSEC3 list, per RR
309  * This routine gives the next RR in the list (or sets rrset null).
310  * Usage:
311  *
312  * size_t rrsetnum;
313  * int rrnum;
314  * struct ub_packed_rrset_key* rrset;
315  * for(rrset=filter_first(filter, &rrsetnum, &rrnum); rrset;
316  *	rrset=filter_next(filter, &rrsetnum, &rrnum))
317  *		do_stuff;
318  *
319  * Also filters out
320  * 	o unknown flag NSEC3s
321  * 	o unknown algorithm NSEC3s.
322  * @param filter: nsec3 filter structure.
323  * @param rrsetnum: in/out rrset number to look at.
324  * @param rrnum: in/out rr number in rrset to look at.
325  * @returns ptr to the next rrset (or NULL at end).
326  */
327 static struct ub_packed_rrset_key*
328 filter_next(struct nsec3_filter* filter, size_t* rrsetnum, int* rrnum)
329 {
330 	size_t i;
331 	int r;
332 	uint8_t* nm;
333 	size_t nmlen;
334 	if(!filter->zone) /* empty list */
335 		return NULL;
336 	for(i=*rrsetnum; i<filter->num; i++) {
337 		/* see if RRset qualifies */
338 		if(ntohs(filter->list[i]->rk.type) != LDNS_RR_TYPE_NSEC3 ||
339 			ntohs(filter->list[i]->rk.rrset_class) !=
340 			filter->fclass)
341 			continue;
342 		/* check RRset zone */
343 		nm = filter->list[i]->rk.dname;
344 		nmlen = filter->list[i]->rk.dname_len;
345 		dname_remove_label(&nm, &nmlen);
346 		if(query_dname_compare(nm, filter->zone) != 0)
347 			continue;
348 		if(i == *rrsetnum)
349 			r = (*rrnum) + 1; /* continue at next RR */
350 		else	r = 0;		/* new RRset start at first RR */
351 		for(; r < (int)rrset_get_count(filter->list[i]); r++) {
352 			/* skip unknown flags, algo */
353 			if(nsec3_unknown_flags(filter->list[i], r) ||
354 				!nsec3_known_algo(filter->list[i], r))
355 				continue;
356 			/* this one is a good target */
357 			*rrsetnum = i;
358 			*rrnum = r;
359 			return filter->list[i];
360 		}
361 	}
362 	return NULL;
363 }
364 
365 /**
366  * Start iterating over NSEC3 records.
367  * @param filter: the filter structure, must have been filter_init-ed.
368  * @param rrsetnum: can be undefined on call, inited.
369  * @param rrnum: can be undefined on call, inited.
370  * @return first rrset of an NSEC3, together with rrnum this points to
371  *	the first RR to examine. Is NULL on empty list.
372  */
373 static struct ub_packed_rrset_key*
374 filter_first(struct nsec3_filter* filter, size_t* rrsetnum, int* rrnum)
375 {
376 	*rrsetnum = 0;
377 	*rrnum = -1;
378 	return filter_next(filter, rrsetnum, rrnum);
379 }
380 
381 /** see if at least one RR is known (flags, algo) */
382 static int
383 nsec3_rrset_has_known(struct ub_packed_rrset_key* s)
384 {
385 	int r;
386 	for(r=0; r < (int)rrset_get_count(s); r++) {
387 		if(!nsec3_unknown_flags(s, r) && nsec3_known_algo(s, r))
388 			return 1;
389 	}
390 	return 0;
391 }
392 
393 /**
394  * Initialize the filter structure.
395  * Finds the zone by looking at available NSEC3 records and best match.
396  * 	(skips the unknown flag and unknown algo NSEC3s).
397  *
398  * @param filter: nsec3 filter structure.
399  * @param list: list of rrsets, an array of them.
400  * @param num: number of rrsets in list.
401  * @param qinfo:
402  *	query name to match a zone for.
403  *	query type (if DS a higher zone must be chosen)
404  *	qclass, to filter NSEC3s with.
405  */
406 static void
407 filter_init(struct nsec3_filter* filter, struct ub_packed_rrset_key** list,
408 	size_t num, struct query_info* qinfo)
409 {
410 	size_t i;
411 	uint8_t* nm;
412 	size_t nmlen;
413 	filter->zone = NULL;
414 	filter->zone_len = 0;
415 	filter->list = list;
416 	filter->num = num;
417 	filter->fclass = qinfo->qclass;
418 	for(i=0; i<num; i++) {
419 		/* ignore other stuff in the list */
420 		if(ntohs(list[i]->rk.type) != LDNS_RR_TYPE_NSEC3 ||
421 			ntohs(list[i]->rk.rrset_class) != qinfo->qclass)
422 			continue;
423 		/* skip unknown flags, algo */
424 		if(!nsec3_rrset_has_known(list[i]))
425 			continue;
426 
427 		/* since NSEC3s are base32.zonename, we can find the zone
428 		 * name by stripping off the first label of the record */
429 		nm = list[i]->rk.dname;
430 		nmlen = list[i]->rk.dname_len;
431 		dname_remove_label(&nm, &nmlen);
432 		/* if we find a domain that can prove about the qname,
433 		 * and if this domain is closer to the qname */
434 		if(dname_subdomain_c(qinfo->qname, nm) && (!filter->zone ||
435 			dname_subdomain_c(nm, filter->zone))) {
436 			/* for a type DS do not accept a zone equal to qname*/
437 			if(qinfo->qtype == LDNS_RR_TYPE_DS &&
438 				query_dname_compare(qinfo->qname, nm) == 0 &&
439 				!dname_is_root(qinfo->qname))
440 				continue;
441 			filter->zone = nm;
442 			filter->zone_len = nmlen;
443 		}
444 	}
445 }
446 
447 /**
448  * Find max iteration count using config settings and key size
449  * @param ve: validator environment with iteration count config settings.
450  * @param bits: key size
451  * @return max iteration count
452  */
453 static size_t
454 get_max_iter(struct val_env* ve, size_t bits)
455 {
456 	int i;
457 	log_assert(ve->nsec3_keyiter_count > 0);
458 	/* round up to nearest config keysize, linear search, keep it small */
459 	for(i=0; i<ve->nsec3_keyiter_count; i++) {
460 		if(bits <= ve->nsec3_keysize[i])
461 			return ve->nsec3_maxiter[i];
462 	}
463 	/* else, use value for biggest key */
464 	return ve->nsec3_maxiter[ve->nsec3_keyiter_count-1];
465 }
466 
467 /**
468  * Determine if any of the NSEC3 rrs iteration count is too high, from key.
469  * @param ve: validator environment with iteration count config settings.
470  * @param filter: what NSEC3s to loop over.
471  * @param kkey: key entry used for verification; used for iteration counts.
472  * @return 1 if some nsec3s are above the max iteration count.
473  */
474 static int
475 nsec3_iteration_count_high(struct val_env* ve, struct nsec3_filter* filter,
476 	struct key_entry_key* kkey)
477 {
478 	size_t rrsetnum;
479 	int rrnum;
480 	struct ub_packed_rrset_key* rrset;
481 	/* first determine the max number of iterations */
482 	size_t bits = key_entry_keysize(kkey);
483 	size_t max_iter = get_max_iter(ve, bits);
484 	verbose(VERB_ALGO, "nsec3: keysize %d bits, max iterations %d",
485 		(int)bits, (int)max_iter);
486 
487 	for(rrset=filter_first(filter, &rrsetnum, &rrnum); rrset;
488 		rrset=filter_next(filter, &rrsetnum, &rrnum)) {
489 		if(nsec3_get_iter(rrset, rrnum) > max_iter)
490 			return 1;
491 	}
492 	return 0;
493 }
494 
495 /* nsec3_cache_compare for rbtree */
496 int
497 nsec3_hash_cmp(const void* c1, const void* c2)
498 {
499 	struct nsec3_cached_hash* h1 = (struct nsec3_cached_hash*)c1;
500 	struct nsec3_cached_hash* h2 = (struct nsec3_cached_hash*)c2;
501 	uint8_t* s1, *s2;
502 	size_t s1len, s2len;
503 	int c = query_dname_compare(h1->dname, h2->dname);
504 	if(c != 0)
505 		return c;
506 	/* compare parameters */
507 	/* if both malformed, its equal, robustness */
508 	if(nsec3_get_algo(h1->nsec3, h1->rr) !=
509 		nsec3_get_algo(h2->nsec3, h2->rr)) {
510 		if(nsec3_get_algo(h1->nsec3, h1->rr) <
511 			nsec3_get_algo(h2->nsec3, h2->rr))
512 			return -1;
513 		return 1;
514 	}
515 	if(nsec3_get_iter(h1->nsec3, h1->rr) !=
516 		nsec3_get_iter(h2->nsec3, h2->rr)) {
517 		if(nsec3_get_iter(h1->nsec3, h1->rr) <
518 			nsec3_get_iter(h2->nsec3, h2->rr))
519 			return -1;
520 		return 1;
521 	}
522 	(void)nsec3_get_salt(h1->nsec3, h1->rr, &s1, &s1len);
523 	(void)nsec3_get_salt(h2->nsec3, h2->rr, &s2, &s2len);
524 	if(s1len != s2len) {
525 		if(s1len < s2len)
526 			return -1;
527 		return 1;
528 	}
529 	return memcmp(s1, s2, s1len);
530 }
531 
532 size_t
533 nsec3_get_hashed(ldns_buffer* buf, uint8_t* nm, size_t nmlen, int algo,
534 	size_t iter, uint8_t* salt, size_t saltlen, uint8_t* res, size_t max)
535 {
536 	size_t i, hash_len;
537 	/* prepare buffer for first iteration */
538 	ldns_buffer_clear(buf);
539 	ldns_buffer_write(buf, nm, nmlen);
540 	query_dname_tolower(ldns_buffer_begin(buf));
541 	ldns_buffer_write(buf, salt, saltlen);
542 	ldns_buffer_flip(buf);
543 	switch(algo) {
544 #ifdef HAVE_EVP_SHA1
545 		case NSEC3_HASH_SHA1:
546 			hash_len = SHA_DIGEST_LENGTH;
547 			if(hash_len > max)
548 				return 0;
549 			(void)SHA1((unsigned char*)ldns_buffer_begin(buf),
550 				(unsigned long)ldns_buffer_limit(buf),
551 				(unsigned char*)res);
552 			for(i=0; i<iter; i++) {
553 				ldns_buffer_clear(buf);
554 				ldns_buffer_write(buf, res, hash_len);
555 				ldns_buffer_write(buf, salt, saltlen);
556 				ldns_buffer_flip(buf);
557 				(void)SHA1(
558 					(unsigned char*)ldns_buffer_begin(buf),
559 					(unsigned long)ldns_buffer_limit(buf),
560 					(unsigned char*)res);
561 			}
562 			break;
563 #endif /* HAVE_EVP_SHA1 */
564 		default:
565 			log_err("nsec3 hash of unknown algo %d", algo);
566 			return 0;
567 	}
568 	return hash_len;
569 }
570 
571 /** perform hash of name */
572 static int
573 nsec3_calc_hash(struct regional* region, ldns_buffer* buf,
574 	struct nsec3_cached_hash* c)
575 {
576 	int algo = nsec3_get_algo(c->nsec3, c->rr);
577 	size_t iter = nsec3_get_iter(c->nsec3, c->rr);
578 	uint8_t* salt;
579 	size_t saltlen, i;
580 	if(!nsec3_get_salt(c->nsec3, c->rr, &salt, &saltlen))
581 		return -1;
582 	/* prepare buffer for first iteration */
583 	ldns_buffer_clear(buf);
584 	ldns_buffer_write(buf, c->dname, c->dname_len);
585 	query_dname_tolower(ldns_buffer_begin(buf));
586 	ldns_buffer_write(buf, salt, saltlen);
587 	ldns_buffer_flip(buf);
588 	switch(algo) {
589 #ifdef HAVE_EVP_SHA1
590 		case NSEC3_HASH_SHA1:
591 			c->hash_len = SHA_DIGEST_LENGTH;
592 			c->hash = (uint8_t*)regional_alloc(region,
593 				c->hash_len);
594 			if(!c->hash)
595 				return 0;
596 			(void)SHA1((unsigned char*)ldns_buffer_begin(buf),
597 				(unsigned long)ldns_buffer_limit(buf),
598 				(unsigned char*)c->hash);
599 			for(i=0; i<iter; i++) {
600 				ldns_buffer_clear(buf);
601 				ldns_buffer_write(buf, c->hash, c->hash_len);
602 				ldns_buffer_write(buf, salt, saltlen);
603 				ldns_buffer_flip(buf);
604 				(void)SHA1(
605 					(unsigned char*)ldns_buffer_begin(buf),
606 					(unsigned long)ldns_buffer_limit(buf),
607 					(unsigned char*)c->hash);
608 			}
609 			break;
610 #endif /* HAVE_EVP_SHA1 */
611 		default:
612 			log_err("nsec3 hash of unknown algo %d", algo);
613 			return -1;
614 	}
615 	return 1;
616 }
617 
618 /** perform b32 encoding of hash */
619 static int
620 nsec3_calc_b32(struct regional* region, ldns_buffer* buf,
621 	struct nsec3_cached_hash* c)
622 {
623 	int r;
624 	ldns_buffer_clear(buf);
625 	r = ldns_b32_ntop_extended_hex(c->hash, c->hash_len,
626 		(char*)ldns_buffer_begin(buf), ldns_buffer_limit(buf));
627 	if(r < 1) {
628 		log_err("b32_ntop_extended_hex: error in encoding: %d", r);
629 		return 0;
630 	}
631 	c->b32_len = (size_t)r;
632 	c->b32 = regional_alloc_init(region, ldns_buffer_begin(buf),
633 		c->b32_len);
634 	if(!c->b32)
635 		return 0;
636 	return 1;
637 }
638 
639 int
640 nsec3_hash_name(rbtree_t* table, struct regional* region, ldns_buffer* buf,
641 	struct ub_packed_rrset_key* nsec3, int rr, uint8_t* dname,
642 	size_t dname_len, struct nsec3_cached_hash** hash)
643 {
644 	struct nsec3_cached_hash* c;
645 	struct nsec3_cached_hash looki;
646 #ifdef UNBOUND_DEBUG
647 	rbnode_t* n;
648 #endif
649 	int r;
650 	looki.node.key = &looki;
651 	looki.nsec3 = nsec3;
652 	looki.rr = rr;
653 	looki.dname = dname;
654 	looki.dname_len = dname_len;
655 	/* lookup first in cache */
656 	c = (struct nsec3_cached_hash*)rbtree_search(table, &looki);
657 	if(c) {
658 		*hash = c;
659 		return 1;
660 	}
661 	/* create a new entry */
662 	c = (struct nsec3_cached_hash*)regional_alloc(region, sizeof(*c));
663 	if(!c) return 0;
664 	c->node.key = c;
665 	c->nsec3 = nsec3;
666 	c->rr = rr;
667 	c->dname = dname;
668 	c->dname_len = dname_len;
669 	r = nsec3_calc_hash(region, buf, c);
670 	if(r != 1)
671 		return r;
672 	r = nsec3_calc_b32(region, buf, c);
673 	if(r != 1)
674 		return r;
675 #ifdef UNBOUND_DEBUG
676 	n =
677 #endif
678 	rbtree_insert(table, &c->node);
679 	log_assert(n); /* cannot be duplicate, just did lookup */
680 	*hash = c;
681 	return 1;
682 }
683 
684 /**
685  * compare a label lowercased
686  */
687 static int
688 label_compare_lower(uint8_t* lab1, uint8_t* lab2, size_t lablen)
689 {
690 	size_t i;
691 	for(i=0; i<lablen; i++) {
692 		if(tolower((int)*lab1) != tolower((int)*lab2)) {
693 			if(tolower((int)*lab1) < tolower((int)*lab2))
694 				return -1;
695 			return 1;
696 		}
697 		lab1++;
698 		lab2++;
699 	}
700 	return 0;
701 }
702 
703 /**
704  * Compare a hashed name with the owner name of an NSEC3 RRset.
705  * @param flt: filter with zone name.
706  * @param hash: the hashed name.
707  * @param s: rrset with owner name.
708  * @return true if matches exactly, false if not.
709  */
710 static int
711 nsec3_hash_matches_owner(struct nsec3_filter* flt,
712 	struct nsec3_cached_hash* hash, struct ub_packed_rrset_key* s)
713 {
714 	uint8_t* nm = s->rk.dname;
715 	/* compare, does hash of name based on params in this NSEC3
716 	 * match the owner name of this NSEC3?
717 	 * name must be: <hashlength>base32 . zone name
718 	 * so; first label must not be root label (not zero length),
719 	 * and match the b32 encoded hash length,
720 	 * and the label content match the b32 encoded hash
721 	 * and the rest must be the zone name.
722 	 */
723 	if(hash->b32_len != 0 && (size_t)nm[0] == hash->b32_len &&
724 		label_compare_lower(nm+1, hash->b32, hash->b32_len) == 0 &&
725 		query_dname_compare(nm+(size_t)nm[0]+1, flt->zone) == 0) {
726 		return 1;
727 	}
728 	return 0;
729 }
730 
731 /**
732  * Find matching NSEC3
733  * Find the NSEC3Record that matches a hash of a name.
734  * @param env: module environment with temporary region and buffer.
735  * @param flt: the NSEC3 RR filter, contains zone name and RRs.
736  * @param ct: cached hashes table.
737  * @param nm: name to look for.
738  * @param nmlen: length of name.
739  * @param rrset: nsec3 that matches is returned here.
740  * @param rr: rr number in nsec3 rrset that matches.
741  * @return true if a matching NSEC3 is found, false if not.
742  */
743 static int
744 find_matching_nsec3(struct module_env* env, struct nsec3_filter* flt,
745 	rbtree_t* ct, uint8_t* nm, size_t nmlen,
746 	struct ub_packed_rrset_key** rrset, int* rr)
747 {
748 	size_t i_rs;
749 	int i_rr;
750 	struct ub_packed_rrset_key* s;
751 	struct nsec3_cached_hash* hash;
752 	int r;
753 
754 	/* this loop skips other-zone and unknown NSEC3s, also non-NSEC3 RRs */
755 	for(s=filter_first(flt, &i_rs, &i_rr); s;
756 		s=filter_next(flt, &i_rs, &i_rr)) {
757 		/* get name hashed for this NSEC3 RR */
758 		r = nsec3_hash_name(ct, env->scratch, env->scratch_buffer,
759 			s, i_rr, nm, nmlen, &hash);
760 		if(r == 0) {
761 			log_err("nsec3: malloc failure");
762 			break; /* alloc failure */
763 		} else if(r < 0)
764 			continue; /* malformed NSEC3 */
765 		else if(nsec3_hash_matches_owner(flt, hash, s)) {
766 			*rrset = s; /* rrset with this name */
767 			*rr = i_rr; /* matches hash with these parameters */
768 			return 1;
769 		}
770 	}
771 	*rrset = NULL;
772 	*rr = 0;
773 	return 0;
774 }
775 
776 int
777 nsec3_covers(uint8_t* zone, struct nsec3_cached_hash* hash,
778 	struct ub_packed_rrset_key* rrset, int rr, ldns_buffer* buf)
779 {
780 	uint8_t* next, *owner;
781 	size_t nextlen;
782 	int len;
783 	if(!nsec3_get_nextowner(rrset, rr, &next, &nextlen))
784 		return 0; /* malformed RR proves nothing */
785 
786 	/* check the owner name is a hashed value . apex
787 	 * base32 encoded values must have equal length.
788 	 * hash_value and next hash value must have equal length. */
789 	if(nextlen != hash->hash_len || hash->hash_len==0||hash->b32_len==0||
790 		(size_t)*rrset->rk.dname != hash->b32_len ||
791 		query_dname_compare(rrset->rk.dname+1+
792 			(size_t)*rrset->rk.dname, zone) != 0)
793 		return 0; /* bad lengths or owner name */
794 
795 	/* This is the "normal case: owner < next and owner < hash < next */
796 	if(label_compare_lower(rrset->rk.dname+1, hash->b32,
797 		hash->b32_len) < 0 &&
798 		memcmp(hash->hash, next, nextlen) < 0)
799 		return 1;
800 
801 	/* convert owner name from text to binary */
802 	ldns_buffer_clear(buf);
803 	owner = ldns_buffer_begin(buf);
804 	len = ldns_b32_pton_extended_hex((char*)rrset->rk.dname+1,
805 		hash->b32_len, owner, ldns_buffer_limit(buf));
806 	if(len<1)
807 		return 0; /* bad owner name in some way */
808 	if((size_t)len != hash->hash_len || (size_t)len != nextlen)
809 		return 0; /* wrong length */
810 
811 	/* this is the end of zone case: next <= owner &&
812 	 * 	(hash > owner || hash < next)
813 	 * this also covers the only-apex case of next==owner.
814 	 */
815 	if(memcmp(next, owner, nextlen) <= 0 &&
816 		( memcmp(hash->hash, owner, nextlen) > 0 ||
817 		  memcmp(hash->hash, next, nextlen) < 0)) {
818 		return 1;
819 	}
820 	return 0;
821 }
822 
823 /**
824  * findCoveringNSEC3
825  * Given a name, find a covering NSEC3 from among a list of NSEC3s.
826  *
827  * @param env: module environment with temporary region and buffer.
828  * @param flt: the NSEC3 RR filter, contains zone name and RRs.
829  * @param ct: cached hashes table.
830  * @param nm: name to check if covered.
831  * @param nmlen: length of name.
832  * @param rrset: covering NSEC3 rrset is returned here.
833  * @param rr: rr of cover is returned here.
834  * @return true if a covering NSEC3 is found, false if not.
835  */
836 static int
837 find_covering_nsec3(struct module_env* env, struct nsec3_filter* flt,
838         rbtree_t* ct, uint8_t* nm, size_t nmlen,
839 	struct ub_packed_rrset_key** rrset, int* rr)
840 {
841 	size_t i_rs;
842 	int i_rr;
843 	struct ub_packed_rrset_key* s;
844 	struct nsec3_cached_hash* hash;
845 	int r;
846 
847 	/* this loop skips other-zone and unknown NSEC3s, also non-NSEC3 RRs */
848 	for(s=filter_first(flt, &i_rs, &i_rr); s;
849 		s=filter_next(flt, &i_rs, &i_rr)) {
850 		/* get name hashed for this NSEC3 RR */
851 		r = nsec3_hash_name(ct, env->scratch, env->scratch_buffer,
852 			s, i_rr, nm, nmlen, &hash);
853 		if(r == 0) {
854 			log_err("nsec3: malloc failure");
855 			break; /* alloc failure */
856 		} else if(r < 0)
857 			continue; /* malformed NSEC3 */
858 		else if(nsec3_covers(flt->zone, hash, s, i_rr,
859 			env->scratch_buffer)) {
860 			*rrset = s; /* rrset with this name */
861 			*rr = i_rr; /* covers hash with these parameters */
862 			return 1;
863 		}
864 	}
865 	*rrset = NULL;
866 	*rr = 0;
867 	return 0;
868 }
869 
870 /**
871  * findClosestEncloser
872  * Given a name and a list of NSEC3s, find the candidate closest encloser.
873  * This will be the first ancestor of 'name' (including itself) to have a
874  * matching NSEC3 RR.
875  * @param env: module environment with temporary region and buffer.
876  * @param flt: the NSEC3 RR filter, contains zone name and RRs.
877  * @param ct: cached hashes table.
878  * @param qinfo: query that is verified for.
879  * @param ce: closest encloser information is returned in here.
880  * @return true if a closest encloser candidate is found, false if not.
881  */
882 static int
883 nsec3_find_closest_encloser(struct module_env* env, struct nsec3_filter* flt,
884 	rbtree_t* ct, struct query_info* qinfo, struct ce_response* ce)
885 {
886 	uint8_t* nm = qinfo->qname;
887 	size_t nmlen = qinfo->qname_len;
888 
889 	/* This scans from longest name to shortest, so the first match
890 	 * we find is the only viable candidate. */
891 
892 	/* (David:) FIXME: modify so that the NSEC3 matching the zone apex need
893 	 * not be present. (Mark Andrews idea).
894 	 * (Wouter:) But make sure you check for DNAME bit in zone apex,
895 	 * if the NSEC3 you find is the only NSEC3 in the zone, then this
896 	 * may be the case. */
897 
898 	while(dname_subdomain_c(nm, flt->zone)) {
899 		if(find_matching_nsec3(env, flt, ct, nm, nmlen,
900 			&ce->ce_rrset, &ce->ce_rr)) {
901 			ce->ce = nm;
902 			ce->ce_len = nmlen;
903 			return 1;
904 		}
905 		dname_remove_label(&nm, &nmlen);
906 	}
907 	return 0;
908 }
909 
910 /**
911  * Given a qname and its proven closest encloser, calculate the "next
912  * closest" name. Basically, this is the name that is one label longer than
913  * the closest encloser that is still a subdomain of qname.
914  *
915  * @param qname: query name.
916  * @param qnamelen: length of qname.
917  * @param ce: closest encloser
918  * @param nm: result name.
919  * @param nmlen: length of nm.
920  */
921 static void
922 next_closer(uint8_t* qname, size_t qnamelen, uint8_t* ce,
923 	uint8_t** nm, size_t* nmlen)
924 {
925 	int strip = dname_count_labels(qname) - dname_count_labels(ce) -1;
926 	*nm = qname;
927 	*nmlen = qnamelen;
928 	if(strip>0)
929 		dname_remove_labels(nm, nmlen, strip);
930 }
931 
932 /**
933  * proveClosestEncloser
934  * Given a List of nsec3 RRs, find and prove the closest encloser to qname.
935  * @param env: module environment with temporary region and buffer.
936  * @param flt: the NSEC3 RR filter, contains zone name and RRs.
937  * @param ct: cached hashes table.
938  * @param qinfo: query that is verified for.
939  * @param prove_does_not_exist: If true, then if the closest encloser
940  * 	turns out to be qname, then null is returned.
941  * 	If set true, and the return value is true, then you can be
942  * 	certain that the ce.nc_rrset and ce.nc_rr are set properly.
943  * @param ce: closest encloser information is returned in here.
944  * @return bogus if no closest encloser could be proven.
945  * 	secure if a closest encloser could be proven, ce is set.
946  * 	insecure if the closest-encloser candidate turns out to prove
947  * 		that an insecure delegation exists above the qname.
948  */
949 static enum sec_status
950 nsec3_prove_closest_encloser(struct module_env* env, struct nsec3_filter* flt,
951 	rbtree_t* ct, struct query_info* qinfo, int prove_does_not_exist,
952 	struct ce_response* ce)
953 {
954 	uint8_t* nc;
955 	size_t nc_len;
956 	/* robust: clean out ce, in case it gets abused later */
957 	memset(ce, 0, sizeof(*ce));
958 
959 	if(!nsec3_find_closest_encloser(env, flt, ct, qinfo, ce)) {
960 		verbose(VERB_ALGO, "nsec3 proveClosestEncloser: could "
961 			"not find a candidate for the closest encloser.");
962 		return sec_status_bogus;
963 	}
964 	log_nametypeclass(VERB_ALGO, "ce candidate", ce->ce, 0, 0);
965 
966 	if(query_dname_compare(ce->ce, qinfo->qname) == 0) {
967 		if(prove_does_not_exist) {
968 			verbose(VERB_ALGO, "nsec3 proveClosestEncloser: "
969 				"proved that qname existed, bad");
970 			return sec_status_bogus;
971 		}
972 		/* otherwise, we need to nothing else to prove that qname
973 		 * is its own closest encloser. */
974 		return sec_status_secure;
975 	}
976 
977 	/* If the closest encloser is actually a delegation, then the
978 	 * response should have been a referral. If it is a DNAME, then
979 	 * it should have been a DNAME response. */
980 	if(nsec3_has_type(ce->ce_rrset, ce->ce_rr, LDNS_RR_TYPE_NS) &&
981 		!nsec3_has_type(ce->ce_rrset, ce->ce_rr, LDNS_RR_TYPE_SOA)) {
982 		if(!nsec3_has_type(ce->ce_rrset, ce->ce_rr, LDNS_RR_TYPE_DS)) {
983 			verbose(VERB_ALGO, "nsec3 proveClosestEncloser: "
984 				"closest encloser is insecure delegation");
985 			return sec_status_insecure;
986 		}
987 		verbose(VERB_ALGO, "nsec3 proveClosestEncloser: closest "
988 			"encloser was a delegation, bad");
989 		return sec_status_bogus;
990 	}
991 	if(nsec3_has_type(ce->ce_rrset, ce->ce_rr, LDNS_RR_TYPE_DNAME)) {
992 		verbose(VERB_ALGO, "nsec3 proveClosestEncloser: closest "
993 			"encloser was a DNAME, bad");
994 		return sec_status_bogus;
995 	}
996 
997 	/* Otherwise, we need to show that the next closer name is covered. */
998 	next_closer(qinfo->qname, qinfo->qname_len, ce->ce, &nc, &nc_len);
999 	if(!find_covering_nsec3(env, flt, ct, nc, nc_len,
1000 		&ce->nc_rrset, &ce->nc_rr)) {
1001 		verbose(VERB_ALGO, "nsec3: Could not find proof that the "
1002 		          "candidate encloser was the closest encloser");
1003 		return sec_status_bogus;
1004 	}
1005 	return sec_status_secure;
1006 }
1007 
1008 /** allocate a wildcard for the closest encloser */
1009 static uint8_t*
1010 nsec3_ce_wildcard(struct regional* region, uint8_t* ce, size_t celen,
1011 	size_t* len)
1012 {
1013 	uint8_t* nm;
1014 	if(celen > LDNS_MAX_DOMAINLEN - 2)
1015 		return 0; /* too long */
1016 	nm = (uint8_t*)regional_alloc(region, celen+2);
1017 	if(!nm) {
1018 		log_err("nsec3 wildcard: out of memory");
1019 		return 0; /* alloc failure */
1020 	}
1021 	nm[0] = 1;
1022 	nm[1] = (uint8_t)'*'; /* wildcard label */
1023 	memmove(nm+2, ce, celen);
1024 	*len = celen+2;
1025 	return nm;
1026 }
1027 
1028 /** Do the name error proof */
1029 static enum sec_status
1030 nsec3_do_prove_nameerror(struct module_env* env, struct nsec3_filter* flt,
1031 	rbtree_t* ct, struct query_info* qinfo)
1032 {
1033 	struct ce_response ce;
1034 	uint8_t* wc;
1035 	size_t wclen;
1036 	struct ub_packed_rrset_key* wc_rrset;
1037 	int wc_rr;
1038 	enum sec_status sec;
1039 
1040 	/* First locate and prove the closest encloser to qname. We will
1041 	 * use the variant that fails if the closest encloser turns out
1042 	 * to be qname. */
1043 	sec = nsec3_prove_closest_encloser(env, flt, ct, qinfo, 1, &ce);
1044 	if(sec != sec_status_secure) {
1045 		if(sec == sec_status_bogus)
1046 			verbose(VERB_ALGO, "nsec3 nameerror proof: failed "
1047 				"to prove a closest encloser");
1048 		else 	verbose(VERB_ALGO, "nsec3 nameerror proof: closest "
1049 				"nsec3 is an insecure delegation");
1050 		return sec;
1051 	}
1052 	log_nametypeclass(VERB_ALGO, "nsec3 namerror: proven ce=", ce.ce,0,0);
1053 
1054 	/* At this point, we know that qname does not exist. Now we need
1055 	 * to prove that the wildcard does not exist. */
1056 	log_assert(ce.ce);
1057 	wc = nsec3_ce_wildcard(env->scratch, ce.ce, ce.ce_len, &wclen);
1058 	if(!wc || !find_covering_nsec3(env, flt, ct, wc, wclen,
1059 		&wc_rrset, &wc_rr)) {
1060 		verbose(VERB_ALGO, "nsec3 nameerror proof: could not prove "
1061 			"that the applicable wildcard did not exist.");
1062 		return sec_status_bogus;
1063 	}
1064 
1065 	if(ce.nc_rrset && nsec3_has_optout(ce.nc_rrset, ce.nc_rr)) {
1066 		verbose(VERB_ALGO, "nsec3 nameerror proof: nc has optout");
1067 		return sec_status_insecure;
1068 	}
1069 	return sec_status_secure;
1070 }
1071 
1072 enum sec_status
1073 nsec3_prove_nameerror(struct module_env* env, struct val_env* ve,
1074 	struct ub_packed_rrset_key** list, size_t num,
1075 	struct query_info* qinfo, struct key_entry_key* kkey)
1076 {
1077 	rbtree_t ct;
1078 	struct nsec3_filter flt;
1079 
1080 	if(!list || num == 0 || !kkey || !key_entry_isgood(kkey))
1081 		return sec_status_bogus; /* no valid NSEC3s, bogus */
1082 	rbtree_init(&ct, &nsec3_hash_cmp); /* init names-to-hash cache */
1083 	filter_init(&flt, list, num, qinfo); /* init RR iterator */
1084 	if(!flt.zone)
1085 		return sec_status_bogus; /* no RRs */
1086 	if(nsec3_iteration_count_high(ve, &flt, kkey))
1087 		return sec_status_insecure; /* iteration count too high */
1088 	log_nametypeclass(VERB_ALGO, "start nsec3 nameerror proof, zone",
1089 		flt.zone, 0, 0);
1090 	return nsec3_do_prove_nameerror(env, &flt, &ct, qinfo);
1091 }
1092 
1093 /*
1094  * No code to handle qtype=NSEC3 specially.
1095  * This existed in early drafts, but was later (-05) removed.
1096  */
1097 
1098 /** Do the nodata proof */
1099 static enum sec_status
1100 nsec3_do_prove_nodata(struct module_env* env, struct nsec3_filter* flt,
1101 	rbtree_t* ct, struct query_info* qinfo)
1102 {
1103 	struct ce_response ce;
1104 	uint8_t* wc;
1105 	size_t wclen;
1106 	struct ub_packed_rrset_key* rrset;
1107 	int rr;
1108 	enum sec_status sec;
1109 
1110 	if(find_matching_nsec3(env, flt, ct, qinfo->qname, qinfo->qname_len,
1111 		&rrset, &rr)) {
1112 		/* cases 1 and 2 */
1113 		if(nsec3_has_type(rrset, rr, qinfo->qtype)) {
1114 			verbose(VERB_ALGO, "proveNodata: Matching NSEC3 "
1115 				"proved that type existed, bogus");
1116 			return sec_status_bogus;
1117 		} else if(nsec3_has_type(rrset, rr, LDNS_RR_TYPE_CNAME)) {
1118 			verbose(VERB_ALGO, "proveNodata: Matching NSEC3 "
1119 				"proved that a CNAME existed, bogus");
1120 			return sec_status_bogus;
1121 		}
1122 
1123 		/*
1124 		 * If type DS: filter_init zone find already found a parent
1125 		 *   zone, so this nsec3 is from a parent zone.
1126 		 *   o can be not a delegation (unusual query for normal name,
1127 		 *   	no DS anyway, but we can verify that).
1128 		 *   o can be a delegation (which is the usual DS check).
1129 		 *   o may not have the SOA bit set (only the top of the
1130 		 *   	zone, which must have been above the name, has that).
1131 		 *   	Except for the root; which is checked by itself.
1132 		 *
1133 		 * If not type DS: matching nsec3 must not be a delegation.
1134 		 */
1135 		if(qinfo->qtype == LDNS_RR_TYPE_DS && qinfo->qname_len != 1
1136 			&& nsec3_has_type(rrset, rr, LDNS_RR_TYPE_SOA &&
1137 			!dname_is_root(qinfo->qname))) {
1138 			verbose(VERB_ALGO, "proveNodata: apex NSEC3 "
1139 				"abused for no DS proof, bogus");
1140 			return sec_status_bogus;
1141 		} else if(qinfo->qtype != LDNS_RR_TYPE_DS &&
1142 			nsec3_has_type(rrset, rr, LDNS_RR_TYPE_NS) &&
1143 			!nsec3_has_type(rrset, rr, LDNS_RR_TYPE_SOA)) {
1144 			if(!nsec3_has_type(rrset, rr, LDNS_RR_TYPE_DS)) {
1145 				verbose(VERB_ALGO, "proveNodata: matching "
1146 					"NSEC3 is insecure delegation");
1147 				return sec_status_insecure;
1148 			}
1149 			verbose(VERB_ALGO, "proveNodata: matching "
1150 				"NSEC3 is a delegation, bogus");
1151 			return sec_status_bogus;
1152 		}
1153 		return sec_status_secure;
1154 	}
1155 
1156 	/* For cases 3 - 5, we need the proven closest encloser, and it
1157 	 * can't match qname. Although, at this point, we know that it
1158 	 * won't since we just checked that. */
1159 	sec = nsec3_prove_closest_encloser(env, flt, ct, qinfo, 1, &ce);
1160 	if(sec == sec_status_bogus) {
1161 		verbose(VERB_ALGO, "proveNodata: did not match qname, "
1162 		          "nor found a proven closest encloser.");
1163 		return sec_status_bogus;
1164 	} else if(sec==sec_status_insecure && qinfo->qtype!=LDNS_RR_TYPE_DS){
1165 		verbose(VERB_ALGO, "proveNodata: closest nsec3 is insecure "
1166 		          "delegation.");
1167 		return sec_status_insecure;
1168 	}
1169 
1170 	/* Case 3: removed */
1171 
1172 	/* Case 4: */
1173 	log_assert(ce.ce);
1174 	wc = nsec3_ce_wildcard(env->scratch, ce.ce, ce.ce_len, &wclen);
1175 	if(wc && find_matching_nsec3(env, flt, ct, wc, wclen, &rrset, &rr)) {
1176 		/* found wildcard */
1177 		if(nsec3_has_type(rrset, rr, qinfo->qtype)) {
1178 			verbose(VERB_ALGO, "nsec3 nodata proof: matching "
1179 				"wildcard had qtype, bogus");
1180 			return sec_status_bogus;
1181 		} else if(nsec3_has_type(rrset, rr, LDNS_RR_TYPE_CNAME)) {
1182 			verbose(VERB_ALGO, "nsec3 nodata proof: matching "
1183 				"wildcard had a CNAME, bogus");
1184 			return sec_status_bogus;
1185 		}
1186 		if(qinfo->qtype == LDNS_RR_TYPE_DS && qinfo->qname_len != 1
1187 			&& nsec3_has_type(rrset, rr, LDNS_RR_TYPE_SOA)) {
1188 			verbose(VERB_ALGO, "nsec3 nodata proof: matching "
1189 				"wildcard for no DS proof has a SOA, bogus");
1190 			return sec_status_bogus;
1191 		} else if(qinfo->qtype != LDNS_RR_TYPE_DS &&
1192 			nsec3_has_type(rrset, rr, LDNS_RR_TYPE_NS) &&
1193 			!nsec3_has_type(rrset, rr, LDNS_RR_TYPE_SOA)) {
1194 			verbose(VERB_ALGO, "nsec3 nodata proof: matching "
1195 				"wilcard is a delegation, bogus");
1196 			return sec_status_bogus;
1197 		}
1198 		/* everything is peachy keen, except for optout spans */
1199 		if(ce.nc_rrset && nsec3_has_optout(ce.nc_rrset, ce.nc_rr)) {
1200 			verbose(VERB_ALGO, "nsec3 nodata proof: matching "
1201 				"wildcard is in optout range, insecure");
1202 			return sec_status_insecure;
1203 		}
1204 		return sec_status_secure;
1205 	}
1206 
1207 	/* Case 5: */
1208 	/* Due to forwarders, cnames, and other collating effects, we
1209 	 * can see the ordinary unsigned data from a zone beneath an
1210 	 * insecure delegation under an optout here */
1211 	if(!ce.nc_rrset) {
1212 		verbose(VERB_ALGO, "nsec3 nodata proof: no next closer nsec3");
1213 		return sec_status_bogus;
1214 	}
1215 
1216 	/* We need to make sure that the covering NSEC3 is opt-out. */
1217 	log_assert(ce.nc_rrset);
1218 	if(!nsec3_has_optout(ce.nc_rrset, ce.nc_rr)) {
1219 		if(qinfo->qtype == LDNS_RR_TYPE_DS)
1220 		  verbose(VERB_ALGO, "proveNodata: covering NSEC3 was not "
1221 			"opt-out in an opt-out DS NOERROR/NODATA case.");
1222 		else verbose(VERB_ALGO, "proveNodata: could not find matching "
1223 			"NSEC3, nor matching wildcard, nor optout NSEC3 "
1224 			"-- no more options, bogus.");
1225 		return sec_status_bogus;
1226 	}
1227 	/* RFC5155 section 9.2: if nc has optout then no AD flag set */
1228 	return sec_status_insecure;
1229 }
1230 
1231 enum sec_status
1232 nsec3_prove_nodata(struct module_env* env, struct val_env* ve,
1233 	struct ub_packed_rrset_key** list, size_t num,
1234 	struct query_info* qinfo, struct key_entry_key* kkey)
1235 {
1236 	rbtree_t ct;
1237 	struct nsec3_filter flt;
1238 
1239 	if(!list || num == 0 || !kkey || !key_entry_isgood(kkey))
1240 		return sec_status_bogus; /* no valid NSEC3s, bogus */
1241 	rbtree_init(&ct, &nsec3_hash_cmp); /* init names-to-hash cache */
1242 	filter_init(&flt, list, num, qinfo); /* init RR iterator */
1243 	if(!flt.zone)
1244 		return sec_status_bogus; /* no RRs */
1245 	if(nsec3_iteration_count_high(ve, &flt, kkey))
1246 		return sec_status_insecure; /* iteration count too high */
1247 	return nsec3_do_prove_nodata(env, &flt, &ct, qinfo);
1248 }
1249 
1250 enum sec_status
1251 nsec3_prove_wildcard(struct module_env* env, struct val_env* ve,
1252         struct ub_packed_rrset_key** list, size_t num,
1253 	struct query_info* qinfo, struct key_entry_key* kkey, uint8_t* wc)
1254 {
1255 	rbtree_t ct;
1256 	struct nsec3_filter flt;
1257 	struct ce_response ce;
1258 	uint8_t* nc;
1259 	size_t nc_len;
1260 	size_t wclen;
1261 	(void)dname_count_size_labels(wc, &wclen);
1262 
1263 	if(!list || num == 0 || !kkey || !key_entry_isgood(kkey))
1264 		return sec_status_bogus; /* no valid NSEC3s, bogus */
1265 	rbtree_init(&ct, &nsec3_hash_cmp); /* init names-to-hash cache */
1266 	filter_init(&flt, list, num, qinfo); /* init RR iterator */
1267 	if(!flt.zone)
1268 		return sec_status_bogus; /* no RRs */
1269 	if(nsec3_iteration_count_high(ve, &flt, kkey))
1270 		return sec_status_insecure; /* iteration count too high */
1271 
1272 	/* We know what the (purported) closest encloser is by just
1273 	 * looking at the supposed generating wildcard.
1274 	 * The *. has already been removed from the wc name.
1275 	 */
1276 	memset(&ce, 0, sizeof(ce));
1277 	ce.ce = wc;
1278 	ce.ce_len = wclen;
1279 
1280 	/* Now we still need to prove that the original data did not exist.
1281 	 * Otherwise, we need to show that the next closer name is covered. */
1282 	next_closer(qinfo->qname, qinfo->qname_len, ce.ce, &nc, &nc_len);
1283 	if(!find_covering_nsec3(env, &flt, &ct, nc, nc_len,
1284 		&ce.nc_rrset, &ce.nc_rr)) {
1285 		verbose(VERB_ALGO, "proveWildcard: did not find a covering "
1286 			"NSEC3 that covered the next closer name.");
1287 		return sec_status_bogus;
1288 	}
1289 	if(ce.nc_rrset && nsec3_has_optout(ce.nc_rrset, ce.nc_rr)) {
1290 		verbose(VERB_ALGO, "proveWildcard: NSEC3 optout");
1291 		return sec_status_insecure;
1292 	}
1293 	return sec_status_secure;
1294 }
1295 
1296 /** test if list is all secure */
1297 static int
1298 list_is_secure(struct module_env* env, struct val_env* ve,
1299 	struct ub_packed_rrset_key** list, size_t num,
1300 	struct key_entry_key* kkey, char** reason)
1301 {
1302 	struct packed_rrset_data* d;
1303 	size_t i;
1304 	for(i=0; i<num; i++) {
1305 		d = (struct packed_rrset_data*)list[i]->entry.data;
1306 		if(list[i]->rk.type != htons(LDNS_RR_TYPE_NSEC3))
1307 			continue;
1308 		if(d->security == sec_status_secure)
1309 			continue;
1310 		rrset_check_sec_status(env->rrset_cache, list[i], *env->now);
1311 		if(d->security == sec_status_secure)
1312 			continue;
1313 		d->security = val_verify_rrset_entry(env, ve, list[i], kkey,
1314 			reason);
1315 		if(d->security != sec_status_secure) {
1316 			verbose(VERB_ALGO, "NSEC3 did not verify");
1317 			return 0;
1318 		}
1319 		rrset_update_sec_status(env->rrset_cache, list[i], *env->now);
1320 	}
1321 	return 1;
1322 }
1323 
1324 enum sec_status
1325 nsec3_prove_nods(struct module_env* env, struct val_env* ve,
1326 	struct ub_packed_rrset_key** list, size_t num,
1327 	struct query_info* qinfo, struct key_entry_key* kkey, char** reason)
1328 {
1329 	rbtree_t ct;
1330 	struct nsec3_filter flt;
1331 	struct ce_response ce;
1332 	struct ub_packed_rrset_key* rrset;
1333 	int rr;
1334 	log_assert(qinfo->qtype == LDNS_RR_TYPE_DS);
1335 
1336 	if(!list || num == 0 || !kkey || !key_entry_isgood(kkey)) {
1337 		*reason = "no valid NSEC3s";
1338 		return sec_status_bogus; /* no valid NSEC3s, bogus */
1339 	}
1340 	if(!list_is_secure(env, ve, list, num, kkey, reason))
1341 		return sec_status_bogus; /* not all NSEC3 records secure */
1342 	rbtree_init(&ct, &nsec3_hash_cmp); /* init names-to-hash cache */
1343 	filter_init(&flt, list, num, qinfo); /* init RR iterator */
1344 	if(!flt.zone) {
1345 		*reason = "no NSEC3 records";
1346 		return sec_status_bogus; /* no RRs */
1347 	}
1348 	if(nsec3_iteration_count_high(ve, &flt, kkey))
1349 		return sec_status_insecure; /* iteration count too high */
1350 
1351 	/* Look for a matching NSEC3 to qname -- this is the normal
1352 	 * NODATA case. */
1353 	if(find_matching_nsec3(env, &flt, &ct, qinfo->qname, qinfo->qname_len,
1354 		&rrset, &rr)) {
1355 		/* If the matching NSEC3 has the SOA bit set, it is from
1356 		 * the wrong zone (the child instead of the parent). If
1357 		 * it has the DS bit set, then we were lied to. */
1358 		if(nsec3_has_type(rrset, rr, LDNS_RR_TYPE_SOA) &&
1359 			qinfo->qname_len != 1) {
1360 			verbose(VERB_ALGO, "nsec3 provenods: NSEC3 is from"
1361 				" child zone, bogus");
1362 			*reason = "NSEC3 from child zone";
1363 			return sec_status_bogus;
1364 		} else if(nsec3_has_type(rrset, rr, LDNS_RR_TYPE_DS)) {
1365 			verbose(VERB_ALGO, "nsec3 provenods: NSEC3 has qtype"
1366 				" DS, bogus");
1367 			*reason = "NSEC3 has DS in bitmap";
1368 			return sec_status_bogus;
1369 		}
1370 		/* If the NSEC3 RR doesn't have the NS bit set, then
1371 		 * this wasn't a delegation point. */
1372 		if(!nsec3_has_type(rrset, rr, LDNS_RR_TYPE_NS))
1373 			return sec_status_indeterminate;
1374 		/* Otherwise, this proves no DS. */
1375 		return sec_status_secure;
1376 	}
1377 
1378 	/* Otherwise, we are probably in the opt-out case. */
1379 	if(nsec3_prove_closest_encloser(env, &flt, &ct, qinfo, 1, &ce)
1380 		!= sec_status_secure) {
1381 		/* an insecure delegation *above* the qname does not prove
1382 		 * anything about this qname exactly, and bogus is bogus */
1383 		verbose(VERB_ALGO, "nsec3 provenods: did not match qname, "
1384 		          "nor found a proven closest encloser.");
1385 		*reason = "no NSEC3 closest encloser";
1386 		return sec_status_bogus;
1387 	}
1388 
1389 	/* robust extra check */
1390 	if(!ce.nc_rrset) {
1391 		verbose(VERB_ALGO, "nsec3 nods proof: no next closer nsec3");
1392 		*reason = "no NSEC3 next closer";
1393 		return sec_status_bogus;
1394 	}
1395 
1396 	/* we had the closest encloser proof, then we need to check that the
1397 	 * covering NSEC3 was opt-out -- the proveClosestEncloser step already
1398 	 * checked to see if the closest encloser was a delegation or DNAME.
1399 	 */
1400 	log_assert(ce.nc_rrset);
1401 	if(!nsec3_has_optout(ce.nc_rrset, ce.nc_rr)) {
1402 		verbose(VERB_ALGO, "nsec3 provenods: covering NSEC3 was not "
1403 			"opt-out in an opt-out DS NOERROR/NODATA case.");
1404 		*reason = "covering NSEC3 was not opt-out in an opt-out "
1405 			"DS NOERROR/NODATA case";
1406 		return sec_status_bogus;
1407 	}
1408 	/* RFC5155 section 9.2: if nc has optout then no AD flag set */
1409 	return sec_status_insecure;
1410 }
1411 
1412 enum sec_status
1413 nsec3_prove_nxornodata(struct module_env* env, struct val_env* ve,
1414 	struct ub_packed_rrset_key** list, size_t num,
1415 	struct query_info* qinfo, struct key_entry_key* kkey, int* nodata)
1416 {
1417 	enum sec_status sec, secnx;
1418 	rbtree_t ct;
1419 	struct nsec3_filter flt;
1420 	*nodata = 0;
1421 
1422 	if(!list || num == 0 || !kkey || !key_entry_isgood(kkey))
1423 		return sec_status_bogus; /* no valid NSEC3s, bogus */
1424 	rbtree_init(&ct, &nsec3_hash_cmp); /* init names-to-hash cache */
1425 	filter_init(&flt, list, num, qinfo); /* init RR iterator */
1426 	if(!flt.zone)
1427 		return sec_status_bogus; /* no RRs */
1428 	if(nsec3_iteration_count_high(ve, &flt, kkey))
1429 		return sec_status_insecure; /* iteration count too high */
1430 
1431 	/* try nxdomain and nodata after another, while keeping the
1432 	 * hash cache intact */
1433 
1434 	secnx = nsec3_do_prove_nameerror(env, &flt, &ct, qinfo);
1435 	if(secnx==sec_status_secure)
1436 		return sec_status_secure;
1437 	sec = nsec3_do_prove_nodata(env, &flt, &ct, qinfo);
1438 	if(sec==sec_status_secure) {
1439 		*nodata = 1;
1440 	} else if(sec == sec_status_insecure) {
1441 		*nodata = 1;
1442 	} else if(secnx == sec_status_insecure) {
1443 		sec = sec_status_insecure;
1444 	}
1445 	return sec;
1446 }
1447