xref: /freebsd/contrib/unbound/validator/validator.c (revision 64de80195bba295c961a4cdf96dbe0e4979bdf2a)
1 /*
2  * validator/validator.c - secure validator DNS query response module
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 a module that performs validation of DNS queries.
40  * According to RFC 4034.
41  */
42 #include "config.h"
43 #include "validator/validator.h"
44 #include "validator/val_anchor.h"
45 #include "validator/val_kcache.h"
46 #include "validator/val_kentry.h"
47 #include "validator/val_utils.h"
48 #include "validator/val_nsec.h"
49 #include "validator/val_nsec3.h"
50 #include "validator/val_neg.h"
51 #include "validator/val_sigcrypt.h"
52 #include "validator/autotrust.h"
53 #include "services/cache/dns.h"
54 #include "util/data/dname.h"
55 #include "util/module.h"
56 #include "util/log.h"
57 #include "util/net_help.h"
58 #include "util/regional.h"
59 #include "util/config_file.h"
60 #include "util/fptr_wlist.h"
61 #include "ldns/rrdef.h"
62 #include "ldns/wire2str.h"
63 
64 /* forward decl for cache response and normal super inform calls of a DS */
65 static void process_ds_response(struct module_qstate* qstate,
66 	struct val_qstate* vq, int id, int rcode, struct dns_msg* msg,
67 	struct query_info* qinfo, struct sock_list* origin);
68 
69 /** fill up nsec3 key iterations config entry */
70 static int
71 fill_nsec3_iter(struct val_env* ve, char* s, int c)
72 {
73 	char* e;
74 	int i;
75 	free(ve->nsec3_keysize);
76 	free(ve->nsec3_maxiter);
77 	ve->nsec3_keysize = (size_t*)calloc(sizeof(size_t), (size_t)c);
78 	ve->nsec3_maxiter = (size_t*)calloc(sizeof(size_t), (size_t)c);
79 	if(!ve->nsec3_keysize || !ve->nsec3_maxiter) {
80 		log_err("out of memory");
81 		return 0;
82 	}
83 	for(i=0; i<c; i++) {
84 		ve->nsec3_keysize[i] = (size_t)strtol(s, &e, 10);
85 		if(s == e) {
86 			log_err("cannot parse: %s", s);
87 			return 0;
88 		}
89 		s = e;
90 		ve->nsec3_maxiter[i] = (size_t)strtol(s, &e, 10);
91 		if(s == e) {
92 			log_err("cannot parse: %s", s);
93 			return 0;
94 		}
95 		s = e;
96 		if(i>0 && ve->nsec3_keysize[i-1] >= ve->nsec3_keysize[i]) {
97 			log_err("nsec3 key iterations not ascending: %d %d",
98 				(int)ve->nsec3_keysize[i-1],
99 				(int)ve->nsec3_keysize[i]);
100 			return 0;
101 		}
102 		verbose(VERB_ALGO, "validator nsec3cfg keysz %d mxiter %d",
103 			(int)ve->nsec3_keysize[i], (int)ve->nsec3_maxiter[i]);
104 	}
105 	return 1;
106 }
107 
108 /** apply config settings to validator */
109 static int
110 val_apply_cfg(struct module_env* env, struct val_env* val_env,
111 	struct config_file* cfg)
112 {
113 	int c;
114 	val_env->bogus_ttl = (uint32_t)cfg->bogus_ttl;
115 	val_env->clean_additional = cfg->val_clean_additional;
116 	val_env->permissive_mode = cfg->val_permissive_mode;
117 	if(!env->anchors)
118 		env->anchors = anchors_create();
119 	if(!env->anchors) {
120 		log_err("out of memory");
121 		return 0;
122 	}
123 	if(!val_env->kcache)
124 		val_env->kcache = key_cache_create(cfg);
125 	if(!val_env->kcache) {
126 		log_err("out of memory");
127 		return 0;
128 	}
129 	env->key_cache = val_env->kcache;
130 	if(!anchors_apply_cfg(env->anchors, cfg)) {
131 		log_err("validator: error in trustanchors config");
132 		return 0;
133 	}
134 	val_env->date_override = cfg->val_date_override;
135 	val_env->skew_min = cfg->val_sig_skew_min;
136 	val_env->skew_max = cfg->val_sig_skew_max;
137 	c = cfg_count_numbers(cfg->val_nsec3_key_iterations);
138 	if(c < 1 || (c&1)) {
139 		log_err("validator: unparseable or odd nsec3 key "
140 			"iterations: %s", cfg->val_nsec3_key_iterations);
141 		return 0;
142 	}
143 	val_env->nsec3_keyiter_count = c/2;
144 	if(!fill_nsec3_iter(val_env, cfg->val_nsec3_key_iterations, c/2)) {
145 		log_err("validator: cannot apply nsec3 key iterations");
146 		return 0;
147 	}
148 	if(!val_env->neg_cache)
149 		val_env->neg_cache = val_neg_create(cfg,
150 			val_env->nsec3_maxiter[val_env->nsec3_keyiter_count-1]);
151 	if(!val_env->neg_cache) {
152 		log_err("out of memory");
153 		return 0;
154 	}
155 	env->neg_cache = val_env->neg_cache;
156 	return 1;
157 }
158 
159 int
160 val_init(struct module_env* env, int id)
161 {
162 	struct val_env* val_env = (struct val_env*)calloc(1,
163 		sizeof(struct val_env));
164 	if(!val_env) {
165 		log_err("malloc failure");
166 		return 0;
167 	}
168 	env->modinfo[id] = (void*)val_env;
169 	env->need_to_validate = 1;
170 	val_env->permissive_mode = 0;
171 	lock_basic_init(&val_env->bogus_lock);
172 	lock_protect(&val_env->bogus_lock, &val_env->num_rrset_bogus,
173 		sizeof(val_env->num_rrset_bogus));
174 	if(!val_apply_cfg(env, val_env, env->cfg)) {
175 		log_err("validator: could not apply configuration settings.");
176 		return 0;
177 	}
178 	return 1;
179 }
180 
181 void
182 val_deinit(struct module_env* env, int id)
183 {
184 	struct val_env* val_env;
185 	if(!env || !env->modinfo[id])
186 		return;
187 	val_env = (struct val_env*)env->modinfo[id];
188 	lock_basic_destroy(&val_env->bogus_lock);
189 	anchors_delete(env->anchors);
190 	env->anchors = NULL;
191 	key_cache_delete(val_env->kcache);
192 	neg_cache_delete(val_env->neg_cache);
193 	free(val_env->nsec3_keysize);
194 	free(val_env->nsec3_maxiter);
195 	free(val_env);
196 	env->modinfo[id] = NULL;
197 }
198 
199 /** fill in message structure */
200 static struct val_qstate*
201 val_new_getmsg(struct module_qstate* qstate, struct val_qstate* vq)
202 {
203 	if(!qstate->return_msg || qstate->return_rcode != LDNS_RCODE_NOERROR) {
204 		/* create a message to verify */
205 		verbose(VERB_ALGO, "constructing reply for validation");
206 		vq->orig_msg = (struct dns_msg*)regional_alloc(qstate->region,
207 			sizeof(struct dns_msg));
208 		if(!vq->orig_msg)
209 			return NULL;
210 		vq->orig_msg->qinfo = qstate->qinfo;
211 		vq->orig_msg->rep = (struct reply_info*)regional_alloc(
212 			qstate->region, sizeof(struct reply_info));
213 		if(!vq->orig_msg->rep)
214 			return NULL;
215 		memset(vq->orig_msg->rep, 0, sizeof(struct reply_info));
216 		vq->orig_msg->rep->flags = (uint16_t)(qstate->return_rcode&0xf)
217 			|BIT_QR|BIT_RA|(qstate->query_flags|(BIT_CD|BIT_RD));
218 		vq->orig_msg->rep->qdcount = 1;
219 	} else {
220 		vq->orig_msg = qstate->return_msg;
221 	}
222 	vq->qchase = qstate->qinfo;
223 	/* chase reply will be an edited (sub)set of the orig msg rrset ptrs */
224 	vq->chase_reply = regional_alloc_init(qstate->region,
225 		vq->orig_msg->rep,
226 		sizeof(struct reply_info) - sizeof(struct rrset_ref));
227 	if(!vq->chase_reply)
228 		return NULL;
229 	vq->chase_reply->rrsets = regional_alloc_init(qstate->region,
230 		vq->orig_msg->rep->rrsets, sizeof(struct ub_packed_rrset_key*)
231 			* vq->orig_msg->rep->rrset_count);
232 	if(!vq->chase_reply->rrsets)
233 		return NULL;
234 	vq->rrset_skip = 0;
235 	return vq;
236 }
237 
238 /** allocate new validator query state */
239 static struct val_qstate*
240 val_new(struct module_qstate* qstate, int id)
241 {
242 	struct val_qstate* vq = (struct val_qstate*)regional_alloc(
243 		qstate->region, sizeof(*vq));
244 	log_assert(!qstate->minfo[id]);
245 	if(!vq)
246 		return NULL;
247 	memset(vq, 0, sizeof(*vq));
248 	qstate->minfo[id] = vq;
249 	vq->state = VAL_INIT_STATE;
250 	return val_new_getmsg(qstate, vq);
251 }
252 
253 /**
254  * Exit validation with an error status
255  *
256  * @param qstate: query state
257  * @param id: validator id.
258  * @return false, for use by caller to return to stop processing.
259  */
260 static int
261 val_error(struct module_qstate* qstate, int id)
262 {
263 	qstate->ext_state[id] = module_error;
264 	qstate->return_rcode = LDNS_RCODE_SERVFAIL;
265 	return 0;
266 }
267 
268 /**
269  * Check to see if a given response needs to go through the validation
270  * process. Typical reasons for this routine to return false are: CD bit was
271  * on in the original request, or the response is a kind of message that
272  * is unvalidatable (i.e., SERVFAIL, REFUSED, etc.)
273  *
274  * @param qstate: query state.
275  * @param ret_rc: rcode for this message (if noerror - examine ret_msg).
276  * @param ret_msg: return msg, can be NULL; look at rcode instead.
277  * @return true if the response could use validation (although this does not
278  *         mean we can actually validate this response).
279  */
280 static int
281 needs_validation(struct module_qstate* qstate, int ret_rc,
282 	struct dns_msg* ret_msg)
283 {
284 	int rcode;
285 
286 	/* If the CD bit is on in the original request, then you could think
287 	 * that we don't bother to validate anything.
288 	 * But this is signalled internally with the valrec flag.
289 	 * User queries are validated with BIT_CD to make our cache clean
290 	 * so that bogus messages get retried by the upstream also for
291 	 * downstream validators that set BIT_CD.
292 	 * For DNS64 bit_cd signals no dns64 processing, but we want to
293 	 * provide validation there too */
294 	/*
295 	if(qstate->query_flags & BIT_CD) {
296 		verbose(VERB_ALGO, "not validating response due to CD bit");
297 		return 0;
298 	}
299 	*/
300 	if(qstate->is_valrec) {
301 		verbose(VERB_ALGO, "not validating response, is valrec"
302 			"(validation recursion lookup)");
303 		return 0;
304 	}
305 
306 	if(ret_rc != LDNS_RCODE_NOERROR || !ret_msg)
307 		rcode = ret_rc;
308 	else 	rcode = (int)FLAGS_GET_RCODE(ret_msg->rep->flags);
309 
310 	if(rcode != LDNS_RCODE_NOERROR && rcode != LDNS_RCODE_NXDOMAIN) {
311 		if(verbosity >= VERB_ALGO) {
312 			char rc[16];
313 			rc[0]=0;
314 			(void)sldns_wire2str_rcode_buf(rcode, rc, sizeof(rc));
315 			verbose(VERB_ALGO, "cannot validate non-answer, rcode %s", rc);
316 		}
317 		return 0;
318 	}
319 
320 	/* cannot validate positive RRSIG response. (negatives can) */
321 	if(qstate->qinfo.qtype == LDNS_RR_TYPE_RRSIG &&
322 		rcode == LDNS_RCODE_NOERROR && ret_msg &&
323 		ret_msg->rep->an_numrrsets > 0) {
324 		verbose(VERB_ALGO, "cannot validate RRSIG, no sigs on sigs.");
325 		return 0;
326 	}
327 	return 1;
328 }
329 
330 /**
331  * Check to see if the response has already been validated.
332  * @param ret_msg: return msg, can be NULL
333  * @return true if the response has already been validated
334  */
335 static int
336 already_validated(struct dns_msg* ret_msg)
337 {
338 	/* validate unchecked, and re-validate bogus messages */
339 	if (ret_msg && ret_msg->rep->security > sec_status_bogus)
340 	{
341 		verbose(VERB_ALGO, "response has already been validated: %s",
342 			sec_status_to_string(ret_msg->rep->security));
343 		return 1;
344 	}
345 	return 0;
346 }
347 
348 /**
349  * Generate a request for DNS data.
350  *
351  * @param qstate: query state that is the parent.
352  * @param id: module id.
353  * @param name: what name to query for.
354  * @param namelen: length of name.
355  * @param qtype: query type.
356  * @param qclass: query class.
357  * @param flags: additional flags, such as the CD bit (BIT_CD), or 0.
358  * @return false on alloc failure.
359  */
360 static int
361 generate_request(struct module_qstate* qstate, int id, uint8_t* name,
362 	size_t namelen, uint16_t qtype, uint16_t qclass, uint16_t flags)
363 {
364 	struct val_qstate* vq = (struct val_qstate*)qstate->minfo[id];
365 	struct module_qstate* newq;
366 	struct query_info ask;
367 	int valrec;
368 	ask.qname = name;
369 	ask.qname_len = namelen;
370 	ask.qtype = qtype;
371 	ask.qclass = qclass;
372 	log_query_info(VERB_ALGO, "generate request", &ask);
373 	fptr_ok(fptr_whitelist_modenv_attach_sub(qstate->env->attach_sub));
374 	/* enable valrec flag to avoid recursion to the same validation
375 	 * routine, this lookup is simply a lookup. DLVs need validation */
376 	if(qtype == LDNS_RR_TYPE_DLV)
377 		valrec = 0;
378 	else valrec = 1;
379 	if(!(*qstate->env->attach_sub)(qstate, &ask,
380 		(uint16_t)(BIT_RD|flags), 0, valrec, &newq)){
381 		log_err("Could not generate request: out of memory");
382 		return 0;
383 	}
384 	/* newq; validator does not need state created for that
385 	 * query, and its a 'normal' for iterator as well */
386 	if(newq) {
387 		/* add our blacklist to the query blacklist */
388 		sock_list_merge(&newq->blacklist, newq->region,
389 			vq->chain_blacklist);
390 	}
391 	qstate->ext_state[id] = module_wait_subquery;
392 	return 1;
393 }
394 
395 /**
396  * Prime trust anchor for use.
397  * Generate and dispatch a priming query for the given trust anchor.
398  * The trust anchor can be DNSKEY or DS and does not have to be signed.
399  *
400  * @param qstate: query state.
401  * @param vq: validator query state.
402  * @param id: module id.
403  * @param toprime: what to prime.
404  * @return false on a processing error.
405  */
406 static int
407 prime_trust_anchor(struct module_qstate* qstate, struct val_qstate* vq,
408 	int id, struct trust_anchor* toprime)
409 {
410 	int ret = generate_request(qstate, id, toprime->name, toprime->namelen,
411 		LDNS_RR_TYPE_DNSKEY, toprime->dclass, BIT_CD);
412 	if(!ret) {
413 		log_err("Could not prime trust anchor: out of memory");
414 		return 0;
415 	}
416 	/* ignore newq; validator does not need state created for that
417 	 * query, and its a 'normal' for iterator as well */
418 	vq->wait_prime_ta = 1; /* to elicit PRIME_RESP_STATE processing
419 		from the validator inform_super() routine */
420 	/* store trust anchor name for later lookup when prime returns */
421 	vq->trust_anchor_name = regional_alloc_init(qstate->region,
422 		toprime->name, toprime->namelen);
423 	vq->trust_anchor_len = toprime->namelen;
424 	vq->trust_anchor_labs = toprime->namelabs;
425 	if(!vq->trust_anchor_name) {
426 		log_err("Could not prime trust anchor: out of memory");
427 		return 0;
428 	}
429 	return 1;
430 }
431 
432 /**
433  * Validate if the ANSWER and AUTHORITY sections contain valid rrsets.
434  * They must be validly signed with the given key.
435  * Tries to validate ADDITIONAL rrsets as well, but only to check them.
436  * Allows unsigned CNAME after a DNAME that expands the DNAME.
437  *
438  * Note that by the time this method is called, the process of finding the
439  * trusted DNSKEY rrset that signs this response must already have been
440  * completed.
441  *
442  * @param qstate: query state.
443  * @param env: module env for verify.
444  * @param ve: validator env for verify.
445  * @param qchase: query that was made.
446  * @param chase_reply: answer to validate.
447  * @param key_entry: the key entry, which is trusted, and which matches
448  * 	the signer of the answer. The key entry isgood().
449  * @return false if any of the rrsets in the an or ns sections of the message
450  * 	fail to verify. The message is then set to bogus.
451  */
452 static int
453 validate_msg_signatures(struct module_qstate* qstate, struct module_env* env,
454 	struct val_env* ve, struct query_info* qchase,
455 	struct reply_info* chase_reply, struct key_entry_key* key_entry)
456 {
457 	uint8_t* sname;
458 	size_t i, slen;
459 	struct ub_packed_rrset_key* s;
460 	enum sec_status sec;
461 	int dname_seen = 0;
462 	char* reason = NULL;
463 
464 	/* validate the ANSWER section */
465 	for(i=0; i<chase_reply->an_numrrsets; i++) {
466 		s = chase_reply->rrsets[i];
467 		/* Skip the CNAME following a (validated) DNAME.
468 		 * Because of the normalization routines in the iterator,
469 		 * there will always be an unsigned CNAME following a DNAME
470 		 * (unless qtype=DNAME). */
471 		if(dname_seen && ntohs(s->rk.type) == LDNS_RR_TYPE_CNAME) {
472 			dname_seen = 0;
473 			/* CNAME was synthesized by our own iterator */
474 			/* since the DNAME verified, mark the CNAME as secure */
475 			((struct packed_rrset_data*)s->entry.data)->security =
476 				sec_status_secure;
477 			((struct packed_rrset_data*)s->entry.data)->trust =
478 				rrset_trust_validated;
479 			continue;
480 		}
481 
482 		/* Verify the answer rrset */
483 		sec = val_verify_rrset_entry(env, ve, s, key_entry, &reason);
484 		/* If the (answer) rrset failed to validate, then this
485 		 * message is BAD. */
486 		if(sec != sec_status_secure) {
487 			log_nametypeclass(VERB_QUERY, "validator: response "
488 				"has failed ANSWER rrset:", s->rk.dname,
489 				ntohs(s->rk.type), ntohs(s->rk.rrset_class));
490 			errinf(qstate, reason);
491 			if(ntohs(s->rk.type) == LDNS_RR_TYPE_CNAME)
492 				errinf(qstate, "for CNAME");
493 			else if(ntohs(s->rk.type) == LDNS_RR_TYPE_DNAME)
494 				errinf(qstate, "for DNAME");
495 			errinf_origin(qstate, qstate->reply_origin);
496 			chase_reply->security = sec_status_bogus;
497 			return 0;
498 		}
499 
500 		/* Notice a DNAME that should be followed by an unsigned
501 		 * CNAME. */
502 		if(qchase->qtype != LDNS_RR_TYPE_DNAME &&
503 			ntohs(s->rk.type) == LDNS_RR_TYPE_DNAME) {
504 			dname_seen = 1;
505 		}
506 	}
507 
508 	/* validate the AUTHORITY section */
509 	for(i=chase_reply->an_numrrsets; i<chase_reply->an_numrrsets+
510 		chase_reply->ns_numrrsets; i++) {
511 		s = chase_reply->rrsets[i];
512 		sec = val_verify_rrset_entry(env, ve, s, key_entry, &reason);
513 		/* If anything in the authority section fails to be secure,
514 		 * we have a bad message. */
515 		if(sec != sec_status_secure) {
516 			log_nametypeclass(VERB_QUERY, "validator: response "
517 				"has failed AUTHORITY rrset:", s->rk.dname,
518 				ntohs(s->rk.type), ntohs(s->rk.rrset_class));
519 			errinf(qstate, reason);
520 			errinf_rrset(qstate, s);
521 			errinf_origin(qstate, qstate->reply_origin);
522 			chase_reply->security = sec_status_bogus;
523 			return 0;
524 		}
525 	}
526 
527 	/* attempt to validate the ADDITIONAL section rrsets */
528 	if(!ve->clean_additional)
529 		return 1;
530 	for(i=chase_reply->an_numrrsets+chase_reply->ns_numrrsets;
531 		i<chase_reply->rrset_count; i++) {
532 		s = chase_reply->rrsets[i];
533 		/* only validate rrs that have signatures with the key */
534 		/* leave others unchecked, those get removed later on too */
535 		val_find_rrset_signer(s, &sname, &slen);
536 		if(sname && query_dname_compare(sname, key_entry->name)==0)
537 			(void)val_verify_rrset_entry(env, ve, s, key_entry,
538 				&reason);
539 		/* the additional section can fail to be secure,
540 		 * it is optional, check signature in case we need
541 		 * to clean the additional section later. */
542 	}
543 
544 	return 1;
545 }
546 
547 /**
548  * Detect wrong truncated response (say from BIND 9.6.1 that is forwarding
549  * and saw the NS record without signatures from a referral).
550  * The positive response has a mangled authority section.
551  * Remove that authority section and the additional section.
552  * @param rep: reply
553  * @return true if a wrongly truncated response.
554  */
555 static int
556 detect_wrongly_truncated(struct reply_info* rep)
557 {
558 	size_t i;
559 	/* only NS in authority, and it is bogus */
560 	if(rep->ns_numrrsets != 1 || rep->an_numrrsets == 0)
561 		return 0;
562 	if(ntohs(rep->rrsets[ rep->an_numrrsets ]->rk.type) != LDNS_RR_TYPE_NS)
563 		return 0;
564 	if(((struct packed_rrset_data*)rep->rrsets[ rep->an_numrrsets ]
565 		->entry.data)->security == sec_status_secure)
566 		return 0;
567 	/* answer section is present and secure */
568 	for(i=0; i<rep->an_numrrsets; i++) {
569 		if(((struct packed_rrset_data*)rep->rrsets[ i ]
570 			->entry.data)->security != sec_status_secure)
571 			return 0;
572 	}
573 	verbose(VERB_ALGO, "truncating to minimal response");
574 	return 1;
575 }
576 
577 
578 /**
579  * Given a "positive" response -- a response that contains an answer to the
580  * question, and no CNAME chain, validate this response.
581  *
582  * The answer and authority RRsets must already be verified as secure.
583  *
584  * @param env: module env for verify.
585  * @param ve: validator env for verify.
586  * @param qchase: query that was made.
587  * @param chase_reply: answer to that query to validate.
588  * @param kkey: the key entry, which is trusted, and which matches
589  * 	the signer of the answer. The key entry isgood().
590  */
591 static void
592 validate_positive_response(struct module_env* env, struct val_env* ve,
593 	struct query_info* qchase, struct reply_info* chase_reply,
594 	struct key_entry_key* kkey)
595 {
596 	uint8_t* wc = NULL;
597 	int wc_NSEC_ok = 0;
598 	int nsec3s_seen = 0;
599 	size_t i;
600 	struct ub_packed_rrset_key* s;
601 
602 	/* validate the ANSWER section - this will be the answer itself */
603 	for(i=0; i<chase_reply->an_numrrsets; i++) {
604 		s = chase_reply->rrsets[i];
605 
606 		/* Check to see if the rrset is the result of a wildcard
607 		 * expansion. If so, an additional check will need to be
608 		 * made in the authority section. */
609 		if(!val_rrset_wildcard(s, &wc)) {
610 			log_nametypeclass(VERB_QUERY, "Positive response has "
611 				"inconsistent wildcard sigs:", s->rk.dname,
612 				ntohs(s->rk.type), ntohs(s->rk.rrset_class));
613 			chase_reply->security = sec_status_bogus;
614 			return;
615 		}
616 	}
617 
618 	/* validate the AUTHORITY section as well - this will generally be
619 	 * the NS rrset (which could be missing, no problem) */
620 	for(i=chase_reply->an_numrrsets; i<chase_reply->an_numrrsets+
621 		chase_reply->ns_numrrsets; i++) {
622 		s = chase_reply->rrsets[i];
623 
624 		/* If this is a positive wildcard response, and we have a
625 		 * (just verified) NSEC record, try to use it to 1) prove
626 		 * that qname doesn't exist and 2) that the correct wildcard
627 		 * was used. */
628 		if(wc != NULL && ntohs(s->rk.type) == LDNS_RR_TYPE_NSEC) {
629 			if(val_nsec_proves_positive_wildcard(s, qchase, wc)) {
630 				wc_NSEC_ok = 1;
631 			}
632 			/* if not, continue looking for proof */
633 		}
634 
635 		/* Otherwise, if this is a positive wildcard response and
636 		 * we have NSEC3 records */
637 		if(wc != NULL && ntohs(s->rk.type) == LDNS_RR_TYPE_NSEC3) {
638 			nsec3s_seen = 1;
639 		}
640 	}
641 
642 	/* If this was a positive wildcard response that we haven't already
643 	 * proven, and we have NSEC3 records, try to prove it using the NSEC3
644 	 * records. */
645 	if(wc != NULL && !wc_NSEC_ok && nsec3s_seen) {
646 		enum sec_status sec = nsec3_prove_wildcard(env, ve,
647 			chase_reply->rrsets+chase_reply->an_numrrsets,
648 			chase_reply->ns_numrrsets, qchase, kkey, wc);
649 		if(sec == sec_status_insecure) {
650 			verbose(VERB_ALGO, "Positive wildcard response is "
651 				"insecure");
652 			chase_reply->security = sec_status_insecure;
653 			return;
654 		} else if(sec == sec_status_secure)
655 			wc_NSEC_ok = 1;
656 	}
657 
658 	/* If after all this, we still haven't proven the positive wildcard
659 	 * response, fail. */
660 	if(wc != NULL && !wc_NSEC_ok) {
661 		verbose(VERB_QUERY, "positive response was wildcard "
662 			"expansion and did not prove original data "
663 			"did not exist");
664 		chase_reply->security = sec_status_bogus;
665 		return;
666 	}
667 
668 	verbose(VERB_ALGO, "Successfully validated positive response");
669 	chase_reply->security = sec_status_secure;
670 }
671 
672 /**
673  * Validate a NOERROR/NODATA signed response -- a response that has a
674  * NOERROR Rcode but no ANSWER section RRsets. This consists of making
675  * certain that the authority section NSEC/NSEC3s proves that the qname
676  * does exist and the qtype doesn't.
677  *
678  * The answer and authority RRsets must already be verified as secure.
679  *
680  * @param env: module env for verify.
681  * @param ve: validator env for verify.
682  * @param qchase: query that was made.
683  * @param chase_reply: answer to that query to validate.
684  * @param kkey: the key entry, which is trusted, and which matches
685  * 	the signer of the answer. The key entry isgood().
686  */
687 static void
688 validate_nodata_response(struct module_env* env, struct val_env* ve,
689 	struct query_info* qchase, struct reply_info* chase_reply,
690 	struct key_entry_key* kkey)
691 {
692 	/* Since we are here, there must be nothing in the ANSWER section to
693 	 * validate. */
694 	/* (Note: CNAME/DNAME responses will not directly get here --
695 	 * instead, they are chased down into indiviual CNAME validations,
696 	 * and at the end of the cname chain a POSITIVE, or CNAME_NOANSWER
697 	 * validation.) */
698 
699 	/* validate the AUTHORITY section */
700 	int has_valid_nsec = 0; /* If true, then the NODATA has been proven.*/
701 	uint8_t* ce = NULL; /* for wildcard nodata responses. This is the
702 				proven closest encloser. */
703 	uint8_t* wc = NULL; /* for wildcard nodata responses. wildcard nsec */
704 	int nsec3s_seen = 0; /* nsec3s seen */
705 	struct ub_packed_rrset_key* s;
706 	size_t i;
707 
708 	for(i=chase_reply->an_numrrsets; i<chase_reply->an_numrrsets+
709 		chase_reply->ns_numrrsets; i++) {
710 		s = chase_reply->rrsets[i];
711 		/* If we encounter an NSEC record, try to use it to prove
712 		 * NODATA.
713 		 * This needs to handle the ENT NODATA case. */
714 		if(ntohs(s->rk.type) == LDNS_RR_TYPE_NSEC) {
715 			if(nsec_proves_nodata(s, qchase, &wc)) {
716 				has_valid_nsec = 1;
717 				/* sets wc-encloser if wildcard applicable */
718 			}
719 			if(val_nsec_proves_name_error(s, qchase->qname)) {
720 				ce = nsec_closest_encloser(qchase->qname, s);
721 			}
722 			if(val_nsec_proves_insecuredelegation(s, qchase)) {
723 				verbose(VERB_ALGO, "delegation is insecure");
724 				chase_reply->security = sec_status_insecure;
725 				return;
726 			}
727 		} else if(ntohs(s->rk.type) == LDNS_RR_TYPE_NSEC3) {
728 			nsec3s_seen = 1;
729 		}
730 	}
731 
732 	/* check to see if we have a wildcard NODATA proof. */
733 
734 	/* The wildcard NODATA is 1 NSEC proving that qname does not exist
735 	 * (and also proving what the closest encloser is), and 1 NSEC
736 	 * showing the matching wildcard, which must be *.closest_encloser. */
737 	if(wc && !ce)
738 		has_valid_nsec = 0;
739 	else if(wc && ce) {
740 		if(query_dname_compare(wc, ce) != 0) {
741 			has_valid_nsec = 0;
742 		}
743 	}
744 
745 	if(!has_valid_nsec && nsec3s_seen) {
746 		enum sec_status sec = nsec3_prove_nodata(env, ve,
747 			chase_reply->rrsets+chase_reply->an_numrrsets,
748 			chase_reply->ns_numrrsets, qchase, kkey);
749 		if(sec == sec_status_insecure) {
750 			verbose(VERB_ALGO, "NODATA response is insecure");
751 			chase_reply->security = sec_status_insecure;
752 			return;
753 		} else if(sec == sec_status_secure)
754 			has_valid_nsec = 1;
755 	}
756 
757 	if(!has_valid_nsec) {
758 		verbose(VERB_QUERY, "NODATA response failed to prove NODATA "
759 			"status with NSEC/NSEC3");
760 		if(verbosity >= VERB_ALGO)
761 			log_dns_msg("Failed NODATA", qchase, chase_reply);
762 		chase_reply->security = sec_status_bogus;
763 		return;
764 	}
765 
766 	verbose(VERB_ALGO, "successfully validated NODATA response.");
767 	chase_reply->security = sec_status_secure;
768 }
769 
770 /**
771  * Validate a NAMEERROR signed response -- a response that has a NXDOMAIN
772  * Rcode.
773  * This consists of making certain that the authority section NSEC proves
774  * that the qname doesn't exist and the covering wildcard also doesn't exist..
775  *
776  * The answer and authority RRsets must have already been verified as secure.
777  *
778  * @param env: module env for verify.
779  * @param ve: validator env for verify.
780  * @param qchase: query that was made.
781  * @param chase_reply: answer to that query to validate.
782  * @param kkey: the key entry, which is trusted, and which matches
783  * 	the signer of the answer. The key entry isgood().
784  * @param rcode: adjusted RCODE, in case of RCODE/proof mismatch leniency.
785  */
786 static void
787 validate_nameerror_response(struct module_env* env, struct val_env* ve,
788 	struct query_info* qchase, struct reply_info* chase_reply,
789 	struct key_entry_key* kkey, int* rcode)
790 {
791 	int has_valid_nsec = 0;
792 	int has_valid_wnsec = 0;
793 	int nsec3s_seen = 0;
794 	struct ub_packed_rrset_key* s;
795 	size_t i;
796 
797 	for(i=chase_reply->an_numrrsets; i<chase_reply->an_numrrsets+
798 		chase_reply->ns_numrrsets; i++) {
799 		s = chase_reply->rrsets[i];
800 		if(ntohs(s->rk.type) == LDNS_RR_TYPE_NSEC) {
801 			if(val_nsec_proves_name_error(s, qchase->qname))
802 				has_valid_nsec = 1;
803 			if(val_nsec_proves_no_wc(s, qchase->qname,
804 				qchase->qname_len))
805 				has_valid_wnsec = 1;
806 			if(val_nsec_proves_insecuredelegation(s, qchase)) {
807 				verbose(VERB_ALGO, "delegation is insecure");
808 				chase_reply->security = sec_status_insecure;
809 				return;
810 			}
811 		} else if(ntohs(s->rk.type) == LDNS_RR_TYPE_NSEC3)
812 			nsec3s_seen = 1;
813 	}
814 
815 	if((!has_valid_nsec || !has_valid_wnsec) && nsec3s_seen) {
816 		/* use NSEC3 proof, both answer and auth rrsets, in case
817 		 * NSEC3s end up in the answer (due to qtype=NSEC3 or so) */
818 		chase_reply->security = nsec3_prove_nameerror(env, ve,
819 			chase_reply->rrsets, chase_reply->an_numrrsets+
820 			chase_reply->ns_numrrsets, qchase, kkey);
821 		if(chase_reply->security != sec_status_secure) {
822 			verbose(VERB_QUERY, "NameError response failed nsec, "
823 				"nsec3 proof was %s", sec_status_to_string(
824 				chase_reply->security));
825 			return;
826 		}
827 		has_valid_nsec = 1;
828 		has_valid_wnsec = 1;
829 	}
830 
831 	/* If the message fails to prove either condition, it is bogus. */
832 	if(!has_valid_nsec) {
833 		verbose(VERB_QUERY, "NameError response has failed to prove: "
834 		          "qname does not exist");
835 		chase_reply->security = sec_status_bogus;
836 		/* Be lenient with RCODE in NSEC NameError responses */
837 		validate_nodata_response(env, ve, qchase, chase_reply, kkey);
838 		if (chase_reply->security == sec_status_secure)
839 			*rcode = LDNS_RCODE_NOERROR;
840 		return;
841 	}
842 
843 	if(!has_valid_wnsec) {
844 		verbose(VERB_QUERY, "NameError response has failed to prove: "
845 		          "covering wildcard does not exist");
846 		chase_reply->security = sec_status_bogus;
847 		/* Be lenient with RCODE in NSEC NameError responses */
848 		validate_nodata_response(env, ve, qchase, chase_reply, kkey);
849 		if (chase_reply->security == sec_status_secure)
850 			*rcode = LDNS_RCODE_NOERROR;
851 		return;
852 	}
853 
854 	/* Otherwise, we consider the message secure. */
855 	verbose(VERB_ALGO, "successfully validated NAME ERROR response.");
856 	chase_reply->security = sec_status_secure;
857 }
858 
859 /**
860  * Given a referral response, validate rrsets and take least trusted rrset
861  * as the current validation status.
862  *
863  * Note that by the time this method is called, the process of finding the
864  * trusted DNSKEY rrset that signs this response must already have been
865  * completed.
866  *
867  * @param chase_reply: answer to validate.
868  */
869 static void
870 validate_referral_response(struct reply_info* chase_reply)
871 {
872 	size_t i;
873 	enum sec_status s;
874 	/* message security equals lowest rrset security */
875 	chase_reply->security = sec_status_secure;
876 	for(i=0; i<chase_reply->rrset_count; i++) {
877 		s = ((struct packed_rrset_data*)chase_reply->rrsets[i]
878 			->entry.data)->security;
879 		if(s < chase_reply->security)
880 			chase_reply->security = s;
881 	}
882 	verbose(VERB_ALGO, "validated part of referral response as %s",
883 		sec_status_to_string(chase_reply->security));
884 }
885 
886 /**
887  * Given an "ANY" response -- a response that contains an answer to a
888  * qtype==ANY question, with answers. This does no checking that all
889  * types are present.
890  *
891  * NOTE: it may be possible to get parent-side delegation point records
892  * here, which won't all be signed. Right now, this routine relies on the
893  * upstream iterative resolver to not return these responses -- instead
894  * treating them as referrals.
895  *
896  * NOTE: RFC 4035 is silent on this issue, so this may change upon
897  * clarification. Clarification draft -05 says to not check all types are
898  * present.
899  *
900  * Note that by the time this method is called, the process of finding the
901  * trusted DNSKEY rrset that signs this response must already have been
902  * completed.
903  *
904  * @param env: module env for verify.
905  * @param ve: validator env for verify.
906  * @param qchase: query that was made.
907  * @param chase_reply: answer to that query to validate.
908  * @param kkey: the key entry, which is trusted, and which matches
909  * 	the signer of the answer. The key entry isgood().
910  */
911 static void
912 validate_any_response(struct module_env* env, struct val_env* ve,
913 	struct query_info* qchase, struct reply_info* chase_reply,
914 	struct key_entry_key* kkey)
915 {
916 	/* all answer and auth rrsets already verified */
917 	/* but check if a wildcard response is given, then check NSEC/NSEC3
918 	 * for qname denial to see if wildcard is applicable */
919 	uint8_t* wc = NULL;
920 	int wc_NSEC_ok = 0;
921 	int nsec3s_seen = 0;
922 	size_t i;
923 	struct ub_packed_rrset_key* s;
924 
925 	if(qchase->qtype != LDNS_RR_TYPE_ANY) {
926 		log_err("internal error: ANY validation called for non-ANY");
927 		chase_reply->security = sec_status_bogus;
928 		return;
929 	}
930 
931 	/* validate the ANSWER section - this will be the answer itself */
932 	for(i=0; i<chase_reply->an_numrrsets; i++) {
933 		s = chase_reply->rrsets[i];
934 
935 		/* Check to see if the rrset is the result of a wildcard
936 		 * expansion. If so, an additional check will need to be
937 		 * made in the authority section. */
938 		if(!val_rrset_wildcard(s, &wc)) {
939 			log_nametypeclass(VERB_QUERY, "Positive ANY response"
940 				" has inconsistent wildcard sigs:",
941 				s->rk.dname, ntohs(s->rk.type),
942 				ntohs(s->rk.rrset_class));
943 			chase_reply->security = sec_status_bogus;
944 			return;
945 		}
946 	}
947 
948 	/* if it was a wildcard, check for NSEC/NSEC3s in both answer
949 	 * and authority sections (NSEC may be moved to the ANSWER section) */
950 	if(wc != NULL)
951 	  for(i=0; i<chase_reply->an_numrrsets+chase_reply->ns_numrrsets;
952 	  	i++) {
953 		s = chase_reply->rrsets[i];
954 
955 		/* If this is a positive wildcard response, and we have a
956 		 * (just verified) NSEC record, try to use it to 1) prove
957 		 * that qname doesn't exist and 2) that the correct wildcard
958 		 * was used. */
959 		if(ntohs(s->rk.type) == LDNS_RR_TYPE_NSEC) {
960 			if(val_nsec_proves_positive_wildcard(s, qchase, wc)) {
961 				wc_NSEC_ok = 1;
962 			}
963 			/* if not, continue looking for proof */
964 		}
965 
966 		/* Otherwise, if this is a positive wildcard response and
967 		 * we have NSEC3 records */
968 		if(ntohs(s->rk.type) == LDNS_RR_TYPE_NSEC3) {
969 			nsec3s_seen = 1;
970 		}
971 	}
972 
973 	/* If this was a positive wildcard response that we haven't already
974 	 * proven, and we have NSEC3 records, try to prove it using the NSEC3
975 	 * records. */
976 	if(wc != NULL && !wc_NSEC_ok && nsec3s_seen) {
977 		/* look both in answer and auth section for NSEC3s */
978 		enum sec_status sec = nsec3_prove_wildcard(env, ve,
979 			chase_reply->rrsets,
980 			chase_reply->an_numrrsets+chase_reply->ns_numrrsets,
981 			qchase, kkey, wc);
982 		if(sec == sec_status_insecure) {
983 			verbose(VERB_ALGO, "Positive ANY wildcard response is "
984 				"insecure");
985 			chase_reply->security = sec_status_insecure;
986 			return;
987 		} else if(sec == sec_status_secure)
988 			wc_NSEC_ok = 1;
989 	}
990 
991 	/* If after all this, we still haven't proven the positive wildcard
992 	 * response, fail. */
993 	if(wc != NULL && !wc_NSEC_ok) {
994 		verbose(VERB_QUERY, "positive ANY response was wildcard "
995 			"expansion and did not prove original data "
996 			"did not exist");
997 		chase_reply->security = sec_status_bogus;
998 		return;
999 	}
1000 
1001 	verbose(VERB_ALGO, "Successfully validated positive ANY response");
1002 	chase_reply->security = sec_status_secure;
1003 }
1004 
1005 /**
1006  * Validate CNAME response, or DNAME+CNAME.
1007  * This is just like a positive proof, except that this is about a
1008  * DNAME+CNAME. Possible wildcard proof.
1009  * Difference with positive proof is that this routine refuses
1010  * wildcarded DNAMEs.
1011  *
1012  * The answer and authority rrsets must already be verified as secure.
1013  *
1014  * @param env: module env for verify.
1015  * @param ve: validator env for verify.
1016  * @param qchase: query that was made.
1017  * @param chase_reply: answer to that query to validate.
1018  * @param kkey: the key entry, which is trusted, and which matches
1019  * 	the signer of the answer. The key entry isgood().
1020  */
1021 static void
1022 validate_cname_response(struct module_env* env, struct val_env* ve,
1023 	struct query_info* qchase, struct reply_info* chase_reply,
1024 	struct key_entry_key* kkey)
1025 {
1026 	uint8_t* wc = NULL;
1027 	int wc_NSEC_ok = 0;
1028 	int nsec3s_seen = 0;
1029 	size_t i;
1030 	struct ub_packed_rrset_key* s;
1031 
1032 	/* validate the ANSWER section - this will be the CNAME (+DNAME) */
1033 	for(i=0; i<chase_reply->an_numrrsets; i++) {
1034 		s = chase_reply->rrsets[i];
1035 
1036 		/* Check to see if the rrset is the result of a wildcard
1037 		 * expansion. If so, an additional check will need to be
1038 		 * made in the authority section. */
1039 		if(!val_rrset_wildcard(s, &wc)) {
1040 			log_nametypeclass(VERB_QUERY, "Cname response has "
1041 				"inconsistent wildcard sigs:", s->rk.dname,
1042 				ntohs(s->rk.type), ntohs(s->rk.rrset_class));
1043 			chase_reply->security = sec_status_bogus;
1044 			return;
1045 		}
1046 
1047 		/* Refuse wildcarded DNAMEs rfc 4597.
1048 		 * Do not follow a wildcarded DNAME because
1049 		 * its synthesized CNAME expansion is underdefined */
1050 		if(qchase->qtype != LDNS_RR_TYPE_DNAME &&
1051 			ntohs(s->rk.type) == LDNS_RR_TYPE_DNAME && wc) {
1052 			log_nametypeclass(VERB_QUERY, "cannot validate a "
1053 				"wildcarded DNAME:", s->rk.dname,
1054 				ntohs(s->rk.type), ntohs(s->rk.rrset_class));
1055 			chase_reply->security = sec_status_bogus;
1056 			return;
1057 		}
1058 
1059 		/* If we have found a CNAME, stop looking for one.
1060 		 * The iterator has placed the CNAME chain in correct
1061 		 * order. */
1062 		if (ntohs(s->rk.type) == LDNS_RR_TYPE_CNAME) {
1063 			break;
1064 		}
1065 	}
1066 
1067 	/* AUTHORITY section */
1068 	for(i=chase_reply->an_numrrsets; i<chase_reply->an_numrrsets+
1069 		chase_reply->ns_numrrsets; i++) {
1070 		s = chase_reply->rrsets[i];
1071 
1072 		/* If this is a positive wildcard response, and we have a
1073 		 * (just verified) NSEC record, try to use it to 1) prove
1074 		 * that qname doesn't exist and 2) that the correct wildcard
1075 		 * was used. */
1076 		if(wc != NULL && ntohs(s->rk.type) == LDNS_RR_TYPE_NSEC) {
1077 			if(val_nsec_proves_positive_wildcard(s, qchase, wc)) {
1078 				wc_NSEC_ok = 1;
1079 			}
1080 			/* if not, continue looking for proof */
1081 		}
1082 
1083 		/* Otherwise, if this is a positive wildcard response and
1084 		 * we have NSEC3 records */
1085 		if(wc != NULL && ntohs(s->rk.type) == LDNS_RR_TYPE_NSEC3) {
1086 			nsec3s_seen = 1;
1087 		}
1088 	}
1089 
1090 	/* If this was a positive wildcard response that we haven't already
1091 	 * proven, and we have NSEC3 records, try to prove it using the NSEC3
1092 	 * records. */
1093 	if(wc != NULL && !wc_NSEC_ok && nsec3s_seen) {
1094 		enum sec_status sec = nsec3_prove_wildcard(env, ve,
1095 			chase_reply->rrsets+chase_reply->an_numrrsets,
1096 			chase_reply->ns_numrrsets, qchase, kkey, wc);
1097 		if(sec == sec_status_insecure) {
1098 			verbose(VERB_ALGO, "wildcard CNAME response is "
1099 				"insecure");
1100 			chase_reply->security = sec_status_insecure;
1101 			return;
1102 		} else if(sec == sec_status_secure)
1103 			wc_NSEC_ok = 1;
1104 	}
1105 
1106 	/* If after all this, we still haven't proven the positive wildcard
1107 	 * response, fail. */
1108 	if(wc != NULL && !wc_NSEC_ok) {
1109 		verbose(VERB_QUERY, "CNAME response was wildcard "
1110 			"expansion and did not prove original data "
1111 			"did not exist");
1112 		chase_reply->security = sec_status_bogus;
1113 		return;
1114 	}
1115 
1116 	verbose(VERB_ALGO, "Successfully validated CNAME response");
1117 	chase_reply->security = sec_status_secure;
1118 }
1119 
1120 /**
1121  * Validate CNAME NOANSWER response, no more data after a CNAME chain.
1122  * This can be a NODATA or a NAME ERROR case, but not both at the same time.
1123  * We don't know because the rcode has been set to NOERROR by the CNAME.
1124  *
1125  * The answer and authority rrsets must already be verified as secure.
1126  *
1127  * @param env: module env for verify.
1128  * @param ve: validator env for verify.
1129  * @param qchase: query that was made.
1130  * @param chase_reply: answer to that query to validate.
1131  * @param kkey: the key entry, which is trusted, and which matches
1132  * 	the signer of the answer. The key entry isgood().
1133  */
1134 static void
1135 validate_cname_noanswer_response(struct module_env* env, struct val_env* ve,
1136 	struct query_info* qchase, struct reply_info* chase_reply,
1137 	struct key_entry_key* kkey)
1138 {
1139 	int nodata_valid_nsec = 0; /* If true, then NODATA has been proven.*/
1140 	uint8_t* ce = NULL; /* for wildcard nodata responses. This is the
1141 				proven closest encloser. */
1142 	uint8_t* wc = NULL; /* for wildcard nodata responses. wildcard nsec */
1143 	int nxdomain_valid_nsec = 0; /* if true, namerror has been proven */
1144 	int nxdomain_valid_wnsec = 0;
1145 	int nsec3s_seen = 0; /* nsec3s seen */
1146 	struct ub_packed_rrset_key* s;
1147 	size_t i;
1148 
1149 	/* the AUTHORITY section */
1150 	for(i=chase_reply->an_numrrsets; i<chase_reply->an_numrrsets+
1151 		chase_reply->ns_numrrsets; i++) {
1152 		s = chase_reply->rrsets[i];
1153 
1154 		/* If we encounter an NSEC record, try to use it to prove
1155 		 * NODATA. This needs to handle the ENT NODATA case.
1156 		 * Also try to prove NAMEERROR, and absence of a wildcard */
1157 		if(ntohs(s->rk.type) == LDNS_RR_TYPE_NSEC) {
1158 			if(nsec_proves_nodata(s, qchase, &wc)) {
1159 				nodata_valid_nsec = 1;
1160 				/* set wc encloser if wildcard applicable */
1161 			}
1162 			if(val_nsec_proves_name_error(s, qchase->qname)) {
1163 				ce = nsec_closest_encloser(qchase->qname, s);
1164 				nxdomain_valid_nsec = 1;
1165 			}
1166 			if(val_nsec_proves_no_wc(s, qchase->qname,
1167 				qchase->qname_len))
1168 				nxdomain_valid_wnsec = 1;
1169 			if(val_nsec_proves_insecuredelegation(s, qchase)) {
1170 				verbose(VERB_ALGO, "delegation is insecure");
1171 				chase_reply->security = sec_status_insecure;
1172 				return;
1173 			}
1174 		} else if(ntohs(s->rk.type) == LDNS_RR_TYPE_NSEC3) {
1175 			nsec3s_seen = 1;
1176 		}
1177 	}
1178 
1179 	/* check to see if we have a wildcard NODATA proof. */
1180 
1181 	/* The wildcard NODATA is 1 NSEC proving that qname does not exists
1182 	 * (and also proving what the closest encloser is), and 1 NSEC
1183 	 * showing the matching wildcard, which must be *.closest_encloser. */
1184 	if(wc && !ce)
1185 		nodata_valid_nsec = 0;
1186 	else if(wc && ce) {
1187 		if(query_dname_compare(wc, ce) != 0) {
1188 			nodata_valid_nsec = 0;
1189 		}
1190 	}
1191 	if(nxdomain_valid_nsec && !nxdomain_valid_wnsec) {
1192 		/* name error is missing wildcard denial proof */
1193 		nxdomain_valid_nsec = 0;
1194 	}
1195 
1196 	if(nodata_valid_nsec && nxdomain_valid_nsec) {
1197 		verbose(VERB_QUERY, "CNAMEchain to noanswer proves that name "
1198 			"exists and not exists, bogus");
1199 		chase_reply->security = sec_status_bogus;
1200 		return;
1201 	}
1202 	if(!nodata_valid_nsec && !nxdomain_valid_nsec && nsec3s_seen) {
1203 		int nodata;
1204 		enum sec_status sec = nsec3_prove_nxornodata(env, ve,
1205 			chase_reply->rrsets+chase_reply->an_numrrsets,
1206 			chase_reply->ns_numrrsets, qchase, kkey, &nodata);
1207 		if(sec == sec_status_insecure) {
1208 			verbose(VERB_ALGO, "CNAMEchain to noanswer response "
1209 				"is insecure");
1210 			chase_reply->security = sec_status_insecure;
1211 			return;
1212 		} else if(sec == sec_status_secure) {
1213 			if(nodata)
1214 				nodata_valid_nsec = 1;
1215 			else	nxdomain_valid_nsec = 1;
1216 		}
1217 	}
1218 
1219 	if(!nodata_valid_nsec && !nxdomain_valid_nsec) {
1220 		verbose(VERB_QUERY, "CNAMEchain to noanswer response failed "
1221 			"to prove status with NSEC/NSEC3");
1222 		if(verbosity >= VERB_ALGO)
1223 			log_dns_msg("Failed CNAMEnoanswer", qchase, chase_reply);
1224 		chase_reply->security = sec_status_bogus;
1225 		return;
1226 	}
1227 
1228 	if(nodata_valid_nsec)
1229 		verbose(VERB_ALGO, "successfully validated CNAME chain to a "
1230 			"NODATA response.");
1231 	else	verbose(VERB_ALGO, "successfully validated CNAME chain to a "
1232 			"NAMEERROR response.");
1233 	chase_reply->security = sec_status_secure;
1234 }
1235 
1236 /**
1237  * Process init state for validator.
1238  * Process the INIT state. First tier responses start in the INIT state.
1239  * This is where they are vetted for validation suitability, and the initial
1240  * key search is done.
1241  *
1242  * Currently, events the come through this routine will be either promoted
1243  * to FINISHED/CNAME_RESP (no validation needed), FINDKEY (next step to
1244  * validation), or will be (temporarily) retired and a new priming request
1245  * event will be generated.
1246  *
1247  * @param qstate: query state.
1248  * @param vq: validator query state.
1249  * @param ve: validator shared global environment.
1250  * @param id: module id.
1251  * @return true if the event should be processed further on return, false if
1252  *         not.
1253  */
1254 static int
1255 processInit(struct module_qstate* qstate, struct val_qstate* vq,
1256 	struct val_env* ve, int id)
1257 {
1258 	uint8_t* lookup_name;
1259 	size_t lookup_len;
1260 	struct trust_anchor* anchor;
1261 	enum val_classification subtype = val_classify_response(
1262 		qstate->query_flags, &qstate->qinfo, &vq->qchase,
1263 		vq->orig_msg->rep, vq->rrset_skip);
1264 	if(vq->restart_count > VAL_MAX_RESTART_COUNT) {
1265 		verbose(VERB_ALGO, "restart count exceeded");
1266 		return val_error(qstate, id);
1267 	}
1268 	verbose(VERB_ALGO, "validator classification %s",
1269 		val_classification_to_string(subtype));
1270 	if(subtype == VAL_CLASS_REFERRAL &&
1271 		vq->rrset_skip < vq->orig_msg->rep->rrset_count) {
1272 		/* referral uses the rrset name as qchase, to find keys for
1273 		 * that rrset */
1274 		vq->qchase.qname = vq->orig_msg->rep->
1275 			rrsets[vq->rrset_skip]->rk.dname;
1276 		vq->qchase.qname_len = vq->orig_msg->rep->
1277 			rrsets[vq->rrset_skip]->rk.dname_len;
1278 		vq->qchase.qtype = ntohs(vq->orig_msg->rep->
1279 			rrsets[vq->rrset_skip]->rk.type);
1280 		vq->qchase.qclass = ntohs(vq->orig_msg->rep->
1281 			rrsets[vq->rrset_skip]->rk.rrset_class);
1282 	}
1283 	lookup_name = vq->qchase.qname;
1284 	lookup_len = vq->qchase.qname_len;
1285 	/* for type DS look at the parent side for keys/trustanchor */
1286 	/* also for NSEC not at apex */
1287 	if(vq->qchase.qtype == LDNS_RR_TYPE_DS ||
1288 		(vq->qchase.qtype == LDNS_RR_TYPE_NSEC &&
1289 		 vq->orig_msg->rep->rrset_count > vq->rrset_skip &&
1290 		 ntohs(vq->orig_msg->rep->rrsets[vq->rrset_skip]->rk.type) ==
1291 		 LDNS_RR_TYPE_NSEC &&
1292 		 !(vq->orig_msg->rep->rrsets[vq->rrset_skip]->
1293 		 rk.flags&PACKED_RRSET_NSEC_AT_APEX))) {
1294 		dname_remove_label(&lookup_name, &lookup_len);
1295 	}
1296 
1297 	val_mark_indeterminate(vq->chase_reply, qstate->env->anchors,
1298 		qstate->env->rrset_cache, qstate->env);
1299 	vq->key_entry = NULL;
1300 	vq->empty_DS_name = NULL;
1301 	vq->ds_rrset = 0;
1302 	anchor = anchors_lookup(qstate->env->anchors,
1303 		lookup_name, lookup_len, vq->qchase.qclass);
1304 
1305 	/* Determine the signer/lookup name */
1306 	val_find_signer(subtype, &vq->qchase, vq->orig_msg->rep,
1307 		vq->rrset_skip, &vq->signer_name, &vq->signer_len);
1308 	if(vq->signer_name != NULL &&
1309 		!dname_subdomain_c(lookup_name, vq->signer_name)) {
1310 		log_nametypeclass(VERB_ALGO, "this signer name is not a parent "
1311 			"of lookupname, omitted", vq->signer_name, 0, 0);
1312 		vq->signer_name = NULL;
1313 	}
1314 	if(vq->signer_name == NULL) {
1315 		log_nametypeclass(VERB_ALGO, "no signer, using", lookup_name,
1316 			0, 0);
1317 	} else {
1318 		lookup_name = vq->signer_name;
1319 		lookup_len = vq->signer_len;
1320 		log_nametypeclass(VERB_ALGO, "signer is", lookup_name, 0, 0);
1321 	}
1322 
1323 	/* for NXDOMAIN it could be signed by a parent of the trust anchor */
1324 	if(subtype == VAL_CLASS_NAMEERROR && vq->signer_name &&
1325 		anchor && dname_strict_subdomain_c(anchor->name, lookup_name)){
1326 		lock_basic_unlock(&anchor->lock);
1327 		anchor = anchors_lookup(qstate->env->anchors,
1328 			lookup_name, lookup_len, vq->qchase.qclass);
1329 		if(!anchor) { /* unsigned parent denies anchor*/
1330 			verbose(VERB_QUERY, "unsigned parent zone denies"
1331 				" trust anchor, indeterminate");
1332 			vq->chase_reply->security = sec_status_indeterminate;
1333 			vq->state = VAL_FINISHED_STATE;
1334 			return 1;
1335 		}
1336 		verbose(VERB_ALGO, "trust anchor NXDOMAIN by signed parent");
1337 	} else if(subtype == VAL_CLASS_POSITIVE &&
1338 		qstate->qinfo.qtype == LDNS_RR_TYPE_DNSKEY &&
1339 		query_dname_compare(lookup_name, qstate->qinfo.qname) == 0) {
1340 		/* is a DNSKEY so lookup a bit higher since we want to
1341 		 * get it from a parent or from trustanchor */
1342 		dname_remove_label(&lookup_name, &lookup_len);
1343 	}
1344 
1345 	if(vq->rrset_skip > 0 || subtype == VAL_CLASS_CNAME ||
1346 		subtype == VAL_CLASS_REFERRAL) {
1347 		/* extract this part of orig_msg into chase_reply for
1348 		 * the eventual VALIDATE stage */
1349 		val_fill_reply(vq->chase_reply, vq->orig_msg->rep,
1350 			vq->rrset_skip, lookup_name, lookup_len,
1351 			vq->signer_name);
1352 		if(verbosity >= VERB_ALGO)
1353 			log_dns_msg("chased extract", &vq->qchase,
1354 				vq->chase_reply);
1355 	}
1356 
1357 	vq->key_entry = key_cache_obtain(ve->kcache, lookup_name, lookup_len,
1358 		vq->qchase.qclass, qstate->region, *qstate->env->now);
1359 
1360 	/* there is no key(from DLV) and no trust anchor */
1361 	if(vq->key_entry == NULL && anchor == NULL) {
1362 		/*response isn't under a trust anchor, so we cannot validate.*/
1363 		vq->chase_reply->security = sec_status_indeterminate;
1364 		/* go to finished state to cache this result */
1365 		vq->state = VAL_FINISHED_STATE;
1366 		return 1;
1367 	}
1368 	/* if not key, or if keyentry is *above* the trustanchor, i.e.
1369 	 * the keyentry is based on another (higher) trustanchor */
1370 	else if(vq->key_entry == NULL || (anchor &&
1371 		dname_strict_subdomain_c(anchor->name, vq->key_entry->name))) {
1372 		/* trust anchor is an 'unsigned' trust anchor */
1373 		if(anchor && anchor->numDS == 0 && anchor->numDNSKEY == 0) {
1374 			vq->chase_reply->security = sec_status_insecure;
1375 			val_mark_insecure(vq->chase_reply, anchor->name,
1376 				qstate->env->rrset_cache, qstate->env);
1377 			lock_basic_unlock(&anchor->lock);
1378 			vq->dlv_checked=1; /* skip DLV check */
1379 			/* go to finished state to cache this result */
1380 			vq->state = VAL_FINISHED_STATE;
1381 			return 1;
1382 		}
1383 		/* fire off a trust anchor priming query. */
1384 		verbose(VERB_DETAIL, "prime trust anchor");
1385 		if(!prime_trust_anchor(qstate, vq, id, anchor)) {
1386 			lock_basic_unlock(&anchor->lock);
1387 			return val_error(qstate, id);
1388 		}
1389 		lock_basic_unlock(&anchor->lock);
1390 		/* and otherwise, don't continue processing this event.
1391 		 * (it will be reactivated when the priming query returns). */
1392 		vq->state = VAL_FINDKEY_STATE;
1393 		return 0;
1394 	}
1395 	if(anchor) {
1396 		lock_basic_unlock(&anchor->lock);
1397 	}
1398 
1399 	if(key_entry_isnull(vq->key_entry)) {
1400 		/* response is under a null key, so we cannot validate
1401 		 * However, we do set the status to INSECURE, since it is
1402 		 * essentially proven insecure. */
1403 		vq->chase_reply->security = sec_status_insecure;
1404 		val_mark_insecure(vq->chase_reply, vq->key_entry->name,
1405 			qstate->env->rrset_cache, qstate->env);
1406 		/* go to finished state to cache this result */
1407 		vq->state = VAL_FINISHED_STATE;
1408 		return 1;
1409 	} else if(key_entry_isbad(vq->key_entry)) {
1410 		/* key is bad, chain is bad, reply is bogus */
1411 		errinf_dname(qstate, "key for validation", vq->key_entry->name);
1412 		errinf(qstate, "is marked as invalid");
1413 		if(key_entry_get_reason(vq->key_entry)) {
1414 			errinf(qstate, "because of a previous");
1415 			errinf(qstate, key_entry_get_reason(vq->key_entry));
1416 		}
1417 		/* no retries, stop bothering the authority until timeout */
1418 		vq->restart_count = VAL_MAX_RESTART_COUNT;
1419 		vq->chase_reply->security = sec_status_bogus;
1420 		vq->state = VAL_FINISHED_STATE;
1421 		return 1;
1422 	}
1423 
1424 	/* otherwise, we have our "closest" cached key -- continue
1425 	 * processing in the next state. */
1426 	vq->state = VAL_FINDKEY_STATE;
1427 	return 1;
1428 }
1429 
1430 /**
1431  * Process the FINDKEY state. Generally this just calculates the next name
1432  * to query and either issues a DS or a DNSKEY query. It will check to see
1433  * if the correct key has already been reached, in which case it will
1434  * advance the event to the next state.
1435  *
1436  * @param qstate: query state.
1437  * @param vq: validator query state.
1438  * @param id: module id.
1439  * @return true if the event should be processed further on return, false if
1440  *         not.
1441  */
1442 static int
1443 processFindKey(struct module_qstate* qstate, struct val_qstate* vq, int id)
1444 {
1445 	uint8_t* target_key_name, *current_key_name;
1446 	size_t target_key_len;
1447 	int strip_lab;
1448 
1449 	log_query_info(VERB_ALGO, "validator: FindKey", &vq->qchase);
1450 	/* We know that state.key_entry is not 0 or bad key -- if it were,
1451 	 * then previous processing should have directed this event to
1452 	 * a different state.
1453 	 * It could be an isnull key, which signals that a DLV was just
1454 	 * done and the DNSKEY after the DLV failed with dnssec-retry state
1455 	 * and the DNSKEY has to be performed again. */
1456 	log_assert(vq->key_entry && !key_entry_isbad(vq->key_entry));
1457 	if(key_entry_isnull(vq->key_entry)) {
1458 		if(!generate_request(qstate, id, vq->ds_rrset->rk.dname,
1459 			vq->ds_rrset->rk.dname_len, LDNS_RR_TYPE_DNSKEY,
1460 			vq->qchase.qclass, BIT_CD)) {
1461 			log_err("mem error generating DNSKEY request");
1462 			return val_error(qstate, id);
1463 		}
1464 		return 0;
1465 	}
1466 
1467 	target_key_name = vq->signer_name;
1468 	target_key_len = vq->signer_len;
1469 	if(!target_key_name) {
1470 		target_key_name = vq->qchase.qname;
1471 		target_key_len = vq->qchase.qname_len;
1472 	}
1473 
1474 	current_key_name = vq->key_entry->name;
1475 
1476 	/* If our current key entry matches our target, then we are done. */
1477 	if(query_dname_compare(target_key_name, current_key_name) == 0) {
1478 		vq->state = VAL_VALIDATE_STATE;
1479 		return 1;
1480 	}
1481 
1482 	if(vq->empty_DS_name) {
1483 		/* if the last empty nonterminal/emptyDS name we detected is
1484 		 * below the current key, use that name to make progress
1485 		 * along the chain of trust */
1486 		if(query_dname_compare(target_key_name,
1487 			vq->empty_DS_name) == 0) {
1488 			/* do not query for empty_DS_name again */
1489 			verbose(VERB_ALGO, "Cannot retrieve DS for signature");
1490 			errinf(qstate, "no signatures");
1491 			errinf_origin(qstate, qstate->reply_origin);
1492 			vq->chase_reply->security = sec_status_bogus;
1493 			vq->state = VAL_FINISHED_STATE;
1494 			return 1;
1495 		}
1496 		current_key_name = vq->empty_DS_name;
1497 	}
1498 
1499 	log_nametypeclass(VERB_ALGO, "current keyname", current_key_name,
1500 		LDNS_RR_TYPE_DNSKEY, LDNS_RR_CLASS_IN);
1501 	log_nametypeclass(VERB_ALGO, "target keyname", target_key_name,
1502 		LDNS_RR_TYPE_DNSKEY, LDNS_RR_CLASS_IN);
1503 	/* assert we are walking down the DNS tree */
1504 	if(!dname_subdomain_c(target_key_name, current_key_name)) {
1505 		verbose(VERB_ALGO, "bad signer name");
1506 		vq->chase_reply->security = sec_status_bogus;
1507 		vq->state = VAL_FINISHED_STATE;
1508 		return 1;
1509 	}
1510 	/* so this value is >= -1 */
1511 	strip_lab = dname_count_labels(target_key_name) -
1512 		dname_count_labels(current_key_name) - 1;
1513 	log_assert(strip_lab >= -1);
1514 	verbose(VERB_ALGO, "striplab %d", strip_lab);
1515 	if(strip_lab > 0) {
1516 		dname_remove_labels(&target_key_name, &target_key_len,
1517 			strip_lab);
1518 	}
1519 	log_nametypeclass(VERB_ALGO, "next keyname", target_key_name,
1520 		LDNS_RR_TYPE_DNSKEY, LDNS_RR_CLASS_IN);
1521 
1522 	/* The next step is either to query for the next DS, or to query
1523 	 * for the next DNSKEY. */
1524 	if(vq->ds_rrset)
1525 		log_nametypeclass(VERB_ALGO, "DS RRset", vq->ds_rrset->rk.dname, LDNS_RR_TYPE_DS, LDNS_RR_CLASS_IN);
1526 	else verbose(VERB_ALGO, "No DS RRset");
1527 
1528 	if(vq->ds_rrset && query_dname_compare(vq->ds_rrset->rk.dname,
1529 		vq->key_entry->name) != 0) {
1530 		if(!generate_request(qstate, id, vq->ds_rrset->rk.dname,
1531 			vq->ds_rrset->rk.dname_len, LDNS_RR_TYPE_DNSKEY,
1532 			vq->qchase.qclass, BIT_CD)) {
1533 			log_err("mem error generating DNSKEY request");
1534 			return val_error(qstate, id);
1535 		}
1536 		return 0;
1537 	}
1538 
1539 	if(!vq->ds_rrset || query_dname_compare(vq->ds_rrset->rk.dname,
1540 		target_key_name) != 0) {
1541 		/* check if there is a cache entry : pick up an NSEC if
1542 		 * there is no DS, check if that NSEC has DS-bit unset, and
1543 		 * thus can disprove the secure delagation we seek.
1544 		 * We can then use that NSEC even in the absence of a SOA
1545 		 * record that would be required by the iterator to supply
1546 		 * a completely protocol-correct response.
1547 		 * Uses negative cache for NSEC3 lookup of DS responses. */
1548 		/* only if cache not blacklisted, of course */
1549 		struct dns_msg* msg;
1550 		if(!qstate->blacklist && !vq->chain_blacklist &&
1551 			(msg=val_find_DS(qstate->env, target_key_name,
1552 			target_key_len, vq->qchase.qclass, qstate->region,
1553 			vq->key_entry->name)) ) {
1554 			verbose(VERB_ALGO, "Process cached DS response");
1555 			process_ds_response(qstate, vq, id, LDNS_RCODE_NOERROR,
1556 				msg, &msg->qinfo, NULL);
1557 			return 1; /* continue processing ds-response results */
1558 		}
1559 		if(!generate_request(qstate, id, target_key_name,
1560 			target_key_len, LDNS_RR_TYPE_DS, vq->qchase.qclass,
1561 			BIT_CD)) {
1562 			log_err("mem error generating DS request");
1563 			return val_error(qstate, id);
1564 		}
1565 		return 0;
1566 	}
1567 
1568 	/* Otherwise, it is time to query for the DNSKEY */
1569 	if(!generate_request(qstate, id, vq->ds_rrset->rk.dname,
1570 		vq->ds_rrset->rk.dname_len, LDNS_RR_TYPE_DNSKEY,
1571 		vq->qchase.qclass, BIT_CD)) {
1572 		log_err("mem error generating DNSKEY request");
1573 		return val_error(qstate, id);
1574 	}
1575 
1576 	return 0;
1577 }
1578 
1579 /**
1580  * Process the VALIDATE stage, the init and findkey stages are finished,
1581  * and the right keys are available to validate the response.
1582  * Or, there are no keys available, in order to invalidate the response.
1583  *
1584  * After validation, the status is recorded in the message and rrsets,
1585  * and finished state is started.
1586  *
1587  * @param qstate: query state.
1588  * @param vq: validator query state.
1589  * @param ve: validator shared global environment.
1590  * @param id: module id.
1591  * @return true if the event should be processed further on return, false if
1592  *         not.
1593  */
1594 static int
1595 processValidate(struct module_qstate* qstate, struct val_qstate* vq,
1596 	struct val_env* ve, int id)
1597 {
1598 	enum val_classification subtype;
1599 	int rcode;
1600 
1601 	if(!vq->key_entry) {
1602 		verbose(VERB_ALGO, "validate: no key entry, failed");
1603 		return val_error(qstate, id);
1604 	}
1605 
1606 	/* This is the default next state. */
1607 	vq->state = VAL_FINISHED_STATE;
1608 
1609 	/* Unsigned responses must be underneath a "null" key entry.*/
1610 	if(key_entry_isnull(vq->key_entry)) {
1611 		verbose(VERB_DETAIL, "Verified that %sresponse is INSECURE",
1612 			vq->signer_name?"":"unsigned ");
1613 		vq->chase_reply->security = sec_status_insecure;
1614 		val_mark_insecure(vq->chase_reply, vq->key_entry->name,
1615 			qstate->env->rrset_cache, qstate->env);
1616 		key_cache_insert(ve->kcache, vq->key_entry, qstate);
1617 		return 1;
1618 	}
1619 
1620 	if(key_entry_isbad(vq->key_entry)) {
1621 		log_nametypeclass(VERB_DETAIL, "Could not establish a chain "
1622 			"of trust to keys for", vq->key_entry->name,
1623 			LDNS_RR_TYPE_DNSKEY, vq->key_entry->key_class);
1624 		vq->chase_reply->security = sec_status_bogus;
1625 		errinf(qstate, "while building chain of trust");
1626 		if(vq->restart_count >= VAL_MAX_RESTART_COUNT)
1627 			key_cache_insert(ve->kcache, vq->key_entry, qstate);
1628 		return 1;
1629 	}
1630 
1631 	/* signerName being null is the indicator that this response was
1632 	 * unsigned */
1633 	if(vq->signer_name == NULL) {
1634 		log_query_info(VERB_ALGO, "processValidate: state has no "
1635 			"signer name", &vq->qchase);
1636 		verbose(VERB_DETAIL, "Could not establish validation of "
1637 		          "INSECURE status of unsigned response.");
1638 		errinf(qstate, "no signatures");
1639 		errinf_origin(qstate, qstate->reply_origin);
1640 		vq->chase_reply->security = sec_status_bogus;
1641 		return 1;
1642 	}
1643 	subtype = val_classify_response(qstate->query_flags, &qstate->qinfo,
1644 		&vq->qchase, vq->orig_msg->rep, vq->rrset_skip);
1645 
1646 	/* check signatures in the message;
1647 	 * answer and authority must be valid, additional is only checked. */
1648 	if(!validate_msg_signatures(qstate, qstate->env, ve, &vq->qchase,
1649 		vq->chase_reply, vq->key_entry)) {
1650 		/* workaround bad recursor out there that truncates (even
1651 		 * with EDNS4k) to 512 by removing RRSIG from auth section
1652 		 * for positive replies*/
1653 		if((subtype == VAL_CLASS_POSITIVE || subtype == VAL_CLASS_ANY
1654 			|| subtype == VAL_CLASS_CNAME) &&
1655 			detect_wrongly_truncated(vq->orig_msg->rep)) {
1656 			/* truncate the message some more */
1657 			vq->orig_msg->rep->ns_numrrsets = 0;
1658 			vq->orig_msg->rep->ar_numrrsets = 0;
1659 			vq->orig_msg->rep->rrset_count =
1660 				vq->orig_msg->rep->an_numrrsets;
1661 			vq->chase_reply->ns_numrrsets = 0;
1662 			vq->chase_reply->ar_numrrsets = 0;
1663 			vq->chase_reply->rrset_count =
1664 				vq->chase_reply->an_numrrsets;
1665 			qstate->errinf = NULL;
1666 		}
1667 		else {
1668 			verbose(VERB_DETAIL, "Validate: message contains "
1669 				"bad rrsets");
1670 			return 1;
1671 		}
1672 	}
1673 
1674 	switch(subtype) {
1675 		case VAL_CLASS_POSITIVE:
1676 			verbose(VERB_ALGO, "Validating a positive response");
1677 			validate_positive_response(qstate->env, ve,
1678 				&vq->qchase, vq->chase_reply, vq->key_entry);
1679 			verbose(VERB_DETAIL, "validate(positive): %s",
1680 			  	sec_status_to_string(
1681 				vq->chase_reply->security));
1682 			break;
1683 
1684 		case VAL_CLASS_NODATA:
1685 			verbose(VERB_ALGO, "Validating a nodata response");
1686 			validate_nodata_response(qstate->env, ve,
1687 				&vq->qchase, vq->chase_reply, vq->key_entry);
1688 			verbose(VERB_DETAIL, "validate(nodata): %s",
1689 			  	sec_status_to_string(
1690 				vq->chase_reply->security));
1691 			break;
1692 
1693 		case VAL_CLASS_NAMEERROR:
1694 			rcode = (int)FLAGS_GET_RCODE(vq->orig_msg->rep->flags);
1695 			verbose(VERB_ALGO, "Validating a nxdomain response");
1696 			validate_nameerror_response(qstate->env, ve,
1697 				&vq->qchase, vq->chase_reply, vq->key_entry, &rcode);
1698 			verbose(VERB_DETAIL, "validate(nxdomain): %s",
1699 			  	sec_status_to_string(
1700 				vq->chase_reply->security));
1701 			FLAGS_SET_RCODE(vq->orig_msg->rep->flags, rcode);
1702 			FLAGS_SET_RCODE(vq->chase_reply->flags, rcode);
1703 			break;
1704 
1705 		case VAL_CLASS_CNAME:
1706 			verbose(VERB_ALGO, "Validating a cname response");
1707 			validate_cname_response(qstate->env, ve,
1708 				&vq->qchase, vq->chase_reply, vq->key_entry);
1709 			verbose(VERB_DETAIL, "validate(cname): %s",
1710 			  	sec_status_to_string(
1711 				vq->chase_reply->security));
1712 			break;
1713 
1714 		case VAL_CLASS_CNAMENOANSWER:
1715 			verbose(VERB_ALGO, "Validating a cname noanswer "
1716 				"response");
1717 			validate_cname_noanswer_response(qstate->env, ve,
1718 				&vq->qchase, vq->chase_reply, vq->key_entry);
1719 			verbose(VERB_DETAIL, "validate(cname_noanswer): %s",
1720 			  	sec_status_to_string(
1721 				vq->chase_reply->security));
1722 			break;
1723 
1724 		case VAL_CLASS_REFERRAL:
1725 			verbose(VERB_ALGO, "Validating a referral response");
1726 			validate_referral_response(vq->chase_reply);
1727 			verbose(VERB_DETAIL, "validate(referral): %s",
1728 			  	sec_status_to_string(
1729 				vq->chase_reply->security));
1730 			break;
1731 
1732 		case VAL_CLASS_ANY:
1733 			verbose(VERB_ALGO, "Validating a positive ANY "
1734 				"response");
1735 			validate_any_response(qstate->env, ve, &vq->qchase,
1736 				vq->chase_reply, vq->key_entry);
1737 			verbose(VERB_DETAIL, "validate(positive_any): %s",
1738 			  	sec_status_to_string(
1739 				vq->chase_reply->security));
1740 			break;
1741 
1742 		default:
1743 			log_err("validate: unhandled response subtype: %d",
1744 				subtype);
1745 	}
1746 	if(vq->chase_reply->security == sec_status_bogus) {
1747 		if(subtype == VAL_CLASS_POSITIVE)
1748 			errinf(qstate, "wildcard");
1749 		else errinf(qstate, val_classification_to_string(subtype));
1750 		errinf(qstate, "proof failed");
1751 		errinf_origin(qstate, qstate->reply_origin);
1752 	}
1753 
1754 	return 1;
1755 }
1756 
1757 /**
1758  * Init DLV check.
1759  * Called when a query is determined by other trust anchors to be insecure
1760  * (or indeterminate).  Then we look if there is a key in the DLV.
1761  * Performs aggressive negative cache check to see if there is no key.
1762  * Otherwise, spawns a DLV query, and changes to the DLV wait state.
1763  *
1764  * @param qstate: query state.
1765  * @param vq: validator query state.
1766  * @param ve: validator shared global environment.
1767  * @param id: module id.
1768  * @return  true if there is no DLV.
1769  * 	false: processing is finished for the validator operate().
1770  * 	This function may exit in three ways:
1771  *         o	no DLV (agressive cache), so insecure. (true)
1772  *         o	error - stop processing (false)
1773  *         o	DLV lookup was started, stop processing (false)
1774  */
1775 static int
1776 val_dlv_init(struct module_qstate* qstate, struct val_qstate* vq,
1777 	struct val_env* ve, int id)
1778 {
1779 	uint8_t* nm;
1780 	size_t nm_len;
1781 	/* there must be a DLV configured */
1782 	log_assert(qstate->env->anchors->dlv_anchor);
1783 	/* this bool is true to avoid looping in the DLV checks */
1784 	log_assert(vq->dlv_checked);
1785 
1786 	/* init the DLV lookup variables */
1787 	vq->dlv_lookup_name = NULL;
1788 	vq->dlv_lookup_name_len = 0;
1789 	vq->dlv_insecure_at = NULL;
1790 	vq->dlv_insecure_at_len = 0;
1791 
1792 	/* Determine the name for which we want to lookup DLV.
1793 	 * This name is for the current message, or
1794 	 * for the current RRset for CNAME, referral subtypes.
1795 	 * If there is a signer, use that, otherwise the domain name */
1796 	if(vq->signer_name) {
1797 		nm = vq->signer_name;
1798 		nm_len = vq->signer_len;
1799 	} else {
1800 		/* use qchase */
1801 		nm = vq->qchase.qname;
1802 		nm_len = vq->qchase.qname_len;
1803 		if(vq->qchase.qtype == LDNS_RR_TYPE_DS)
1804 			dname_remove_label(&nm, &nm_len);
1805 	}
1806 	log_nametypeclass(VERB_ALGO, "DLV init look", nm, LDNS_RR_TYPE_DS,
1807 		vq->qchase.qclass);
1808 	log_assert(nm && nm_len);
1809 	/* sanity check: no DLV lookups below the DLV anchor itself.
1810 	 * Like, an securely insecure delegation there makes no sense. */
1811 	if(dname_subdomain_c(nm, qstate->env->anchors->dlv_anchor->name)) {
1812 		verbose(VERB_ALGO, "DLV lookup within DLV repository denied");
1813 		return 1;
1814 	}
1815 	/* concat name (minus root label) + dlv name */
1816 	vq->dlv_lookup_name_len = nm_len - 1 +
1817 		qstate->env->anchors->dlv_anchor->namelen;
1818 	vq->dlv_lookup_name = regional_alloc(qstate->region,
1819 		vq->dlv_lookup_name_len);
1820 	if(!vq->dlv_lookup_name) {
1821 		log_err("Out of memory preparing DLV lookup");
1822 		return val_error(qstate, id);
1823 	}
1824 	memmove(vq->dlv_lookup_name, nm, nm_len-1);
1825 	memmove(vq->dlv_lookup_name+nm_len-1,
1826 		qstate->env->anchors->dlv_anchor->name,
1827 		qstate->env->anchors->dlv_anchor->namelen);
1828 	log_nametypeclass(VERB_ALGO, "DLV name", vq->dlv_lookup_name,
1829 		LDNS_RR_TYPE_DLV, vq->qchase.qclass);
1830 
1831 	/* determine where the insecure point was determined, the DLV must
1832 	 * be equal or below that to continue building the trust chain
1833 	 * down. May be NULL if no trust chain was built yet */
1834 	nm = NULL;
1835 	if(vq->key_entry && key_entry_isnull(vq->key_entry)) {
1836 		nm = vq->key_entry->name;
1837 		nm_len = vq->key_entry->namelen;
1838 	}
1839 	if(nm) {
1840 		vq->dlv_insecure_at_len = nm_len - 1 +
1841 			qstate->env->anchors->dlv_anchor->namelen;
1842 		vq->dlv_insecure_at = regional_alloc(qstate->region,
1843 			vq->dlv_insecure_at_len);
1844 		if(!vq->dlv_insecure_at) {
1845 			log_err("Out of memory preparing DLV lookup");
1846 			return val_error(qstate, id);
1847 		}
1848 		memmove(vq->dlv_insecure_at, nm, nm_len-1);
1849 		memmove(vq->dlv_insecure_at+nm_len-1,
1850 			qstate->env->anchors->dlv_anchor->name,
1851 			qstate->env->anchors->dlv_anchor->namelen);
1852 		log_nametypeclass(VERB_ALGO, "insecure_at",
1853 			vq->dlv_insecure_at, 0, vq->qchase.qclass);
1854 	}
1855 
1856 	/* If we can find the name in the aggressive negative cache,
1857 	 * give up; insecure is the answer */
1858 	while(val_neg_dlvlookup(ve->neg_cache, vq->dlv_lookup_name,
1859 		vq->dlv_lookup_name_len, vq->qchase.qclass,
1860 		qstate->env->rrset_cache, *qstate->env->now)) {
1861 		/* go up */
1862 		dname_remove_label(&vq->dlv_lookup_name,
1863 			&vq->dlv_lookup_name_len);
1864 		/* too high? */
1865 		if(!dname_subdomain_c(vq->dlv_lookup_name,
1866 			qstate->env->anchors->dlv_anchor->name)) {
1867 			verbose(VERB_ALGO, "ask above dlv repo");
1868 			return 1; /* Above the repo is insecure */
1869 		}
1870 		/* above chain of trust? */
1871 		if(vq->dlv_insecure_at && !dname_subdomain_c(
1872 			vq->dlv_lookup_name, vq->dlv_insecure_at)) {
1873 			verbose(VERB_ALGO, "ask above insecure endpoint");
1874 			return 1;
1875 		}
1876 	}
1877 
1878 	/* perform a lookup for the DLV; with validation */
1879 	vq->state = VAL_DLVLOOKUP_STATE;
1880 	if(!generate_request(qstate, id, vq->dlv_lookup_name,
1881 		vq->dlv_lookup_name_len, LDNS_RR_TYPE_DLV,
1882 		vq->qchase.qclass, 0)) {
1883 		return val_error(qstate, id);
1884 	}
1885 
1886 	/* Find the closest encloser DLV from the repository.
1887 	 * then that is used to build another chain of trust
1888 	 * This may first require a query 'too low' that has NSECs in
1889 	 * the answer, from which we determine the closest encloser DLV.
1890 	 * When determine the closest encloser, skip empty nonterminals,
1891 	 * since we want a nonempty node in the DLV repository. */
1892 
1893 	return 0;
1894 }
1895 
1896 /**
1897  * The Finished state. The validation status (good or bad) has been determined.
1898  *
1899  * @param qstate: query state.
1900  * @param vq: validator query state.
1901  * @param ve: validator shared global environment.
1902  * @param id: module id.
1903  * @return true if the event should be processed further on return, false if
1904  *         not.
1905  */
1906 static int
1907 processFinished(struct module_qstate* qstate, struct val_qstate* vq,
1908 	struct val_env* ve, int id)
1909 {
1910 	enum val_classification subtype = val_classify_response(
1911 		qstate->query_flags, &qstate->qinfo, &vq->qchase,
1912 		vq->orig_msg->rep, vq->rrset_skip);
1913 
1914 	/* if the result is insecure or indeterminate and we have not
1915 	 * checked the DLV yet, check the DLV */
1916 	if((vq->chase_reply->security == sec_status_insecure ||
1917 		vq->chase_reply->security == sec_status_indeterminate) &&
1918 		qstate->env->anchors->dlv_anchor && !vq->dlv_checked) {
1919 		vq->dlv_checked = 1;
1920 		if(!val_dlv_init(qstate, vq, ve, id))
1921 			return 0;
1922 	}
1923 
1924 	/* store overall validation result in orig_msg */
1925 	if(vq->rrset_skip == 0)
1926 		vq->orig_msg->rep->security = vq->chase_reply->security;
1927 	else if(subtype != VAL_CLASS_REFERRAL ||
1928 		vq->rrset_skip < vq->orig_msg->rep->an_numrrsets +
1929 		vq->orig_msg->rep->ns_numrrsets) {
1930 		/* ignore sec status of additional section if a referral
1931 		 * type message skips there and
1932 		 * use the lowest security status as end result. */
1933 		if(vq->chase_reply->security < vq->orig_msg->rep->security)
1934 			vq->orig_msg->rep->security =
1935 				vq->chase_reply->security;
1936 	}
1937 
1938 	if(subtype == VAL_CLASS_REFERRAL) {
1939 		/* for a referral, move to next unchecked rrset and check it*/
1940 		vq->rrset_skip = val_next_unchecked(vq->orig_msg->rep,
1941 			vq->rrset_skip);
1942 		if(vq->rrset_skip < vq->orig_msg->rep->rrset_count) {
1943 			/* and restart for this rrset */
1944 			verbose(VERB_ALGO, "validator: go to next rrset");
1945 			vq->chase_reply->security = sec_status_unchecked;
1946 			vq->dlv_checked = 0; /* can do DLV for this RR */
1947 			vq->state = VAL_INIT_STATE;
1948 			return 1;
1949 		}
1950 		/* referral chase is done */
1951 	}
1952 	if(vq->chase_reply->security != sec_status_bogus &&
1953 		subtype == VAL_CLASS_CNAME) {
1954 		/* chase the CNAME; process next part of the message */
1955 		if(!val_chase_cname(&vq->qchase, vq->orig_msg->rep,
1956 			&vq->rrset_skip)) {
1957 			verbose(VERB_ALGO, "validator: failed to chase CNAME");
1958 			vq->orig_msg->rep->security = sec_status_bogus;
1959 		} else {
1960 			/* restart process for new qchase at rrset_skip */
1961 			log_query_info(VERB_ALGO, "validator: chased to",
1962 				&vq->qchase);
1963 			vq->chase_reply->security = sec_status_unchecked;
1964 			vq->dlv_checked = 0; /* can do DLV for this RR */
1965 			vq->state = VAL_INIT_STATE;
1966 			return 1;
1967 		}
1968 	}
1969 
1970 	if(vq->orig_msg->rep->security == sec_status_secure) {
1971 		/* If the message is secure, check that all rrsets are
1972 		 * secure (i.e. some inserted RRset for CNAME chain with
1973 		 * a different signer name). And drop additional rrsets
1974 		 * that are not secure (if clean-additional option is set) */
1975 		/* this may cause the msg to be marked bogus */
1976 		val_check_nonsecure(ve, vq->orig_msg->rep);
1977 		if(vq->orig_msg->rep->security == sec_status_secure) {
1978 			log_query_info(VERB_DETAIL, "validation success",
1979 				&qstate->qinfo);
1980 		}
1981 	}
1982 
1983 	/* if the result is bogus - set message ttl to bogus ttl to avoid
1984 	 * endless bogus revalidation */
1985 	if(vq->orig_msg->rep->security == sec_status_bogus) {
1986 		/* see if we can try again to fetch data */
1987 		if(vq->restart_count < VAL_MAX_RESTART_COUNT) {
1988 			int restart_count = vq->restart_count+1;
1989 			verbose(VERB_ALGO, "validation failed, "
1990 				"blacklist and retry to fetch data");
1991 			val_blacklist(&qstate->blacklist, qstate->region,
1992 				qstate->reply_origin, 0);
1993 			qstate->reply_origin = NULL;
1994 			qstate->errinf = NULL;
1995 			memset(vq, 0, sizeof(*vq));
1996 			vq->restart_count = restart_count;
1997 			vq->state = VAL_INIT_STATE;
1998 			verbose(VERB_ALGO, "pass back to next module");
1999 			qstate->ext_state[id] = module_restart_next;
2000 			return 0;
2001 		}
2002 
2003 		vq->orig_msg->rep->ttl = ve->bogus_ttl;
2004 		vq->orig_msg->rep->prefetch_ttl =
2005 			PREFETCH_TTL_CALC(vq->orig_msg->rep->ttl);
2006 		if(qstate->env->cfg->val_log_level >= 1 &&
2007 			!qstate->env->cfg->val_log_squelch) {
2008 			if(qstate->env->cfg->val_log_level < 2)
2009 				log_query_info(0, "validation failure",
2010 					&qstate->qinfo);
2011 			else {
2012 				char* err = errinf_to_str(qstate);
2013 				if(err) log_info("%s", err);
2014 				free(err);
2015 			}
2016 		}
2017 		/* If we are in permissive mode, bogus gets indeterminate */
2018 		if(ve->permissive_mode)
2019 			vq->orig_msg->rep->security = sec_status_indeterminate;
2020 	}
2021 
2022 	/* store results in cache */
2023 	if(qstate->query_flags&BIT_RD) {
2024 		/* if secure, this will override cache anyway, no need
2025 		 * to check if from parentNS */
2026 		if(!dns_cache_store(qstate->env, &vq->orig_msg->qinfo,
2027 			vq->orig_msg->rep, 0, qstate->prefetch_leeway, 0, NULL,
2028 			qstate->query_flags)) {
2029 			log_err("out of memory caching validator results");
2030 		}
2031 	} else {
2032 		/* for a referral, store the verified RRsets */
2033 		/* and this does not get prefetched, so no leeway */
2034 		if(!dns_cache_store(qstate->env, &vq->orig_msg->qinfo,
2035 			vq->orig_msg->rep, 1, 0, 0, NULL,
2036 			qstate->query_flags)) {
2037 			log_err("out of memory caching validator results");
2038 		}
2039 	}
2040 	qstate->return_rcode = LDNS_RCODE_NOERROR;
2041 	qstate->return_msg = vq->orig_msg;
2042 	qstate->ext_state[id] = module_finished;
2043 	return 0;
2044 }
2045 
2046 /**
2047  * The DLVLookup state. Process DLV lookups.
2048  *
2049  * @param qstate: query state.
2050  * @param vq: validator query state.
2051  * @param ve: validator shared global environment.
2052  * @param id: module id.
2053  * @return true if the event should be processed further on return, false if
2054  *         not.
2055  */
2056 static int
2057 processDLVLookup(struct module_qstate* qstate, struct val_qstate* vq,
2058 	struct val_env* ve, int id)
2059 {
2060 	/* see if this we are ready to continue normal resolution */
2061 	/* we may need more DLV lookups */
2062 	if(vq->dlv_status==dlv_error)
2063 		verbose(VERB_ALGO, "DLV woke up with status dlv_error");
2064 	else if(vq->dlv_status==dlv_success)
2065 		verbose(VERB_ALGO, "DLV woke up with status dlv_success");
2066 	else if(vq->dlv_status==dlv_ask_higher)
2067 		verbose(VERB_ALGO, "DLV woke up with status dlv_ask_higher");
2068 	else if(vq->dlv_status==dlv_there_is_no_dlv)
2069 		verbose(VERB_ALGO, "DLV woke up with status dlv_there_is_no_dlv");
2070 	else 	verbose(VERB_ALGO, "DLV woke up with status unknown");
2071 
2072 	if(vq->dlv_status == dlv_error) {
2073 		verbose(VERB_QUERY, "failed DLV lookup");
2074 		return val_error(qstate, id);
2075 	} else if(vq->dlv_status == dlv_success) {
2076 		uint8_t* nm;
2077 		size_t nmlen;
2078 		/* chain continues with DNSKEY, continue in FINDKEY */
2079 		vq->state = VAL_FINDKEY_STATE;
2080 
2081 		/* strip off the DLV suffix from the name; could result in . */
2082 		log_assert(dname_subdomain_c(vq->ds_rrset->rk.dname,
2083 			qstate->env->anchors->dlv_anchor->name));
2084 		nmlen = vq->ds_rrset->rk.dname_len -
2085 			qstate->env->anchors->dlv_anchor->namelen + 1;
2086 		nm = regional_alloc_init(qstate->region,
2087 			vq->ds_rrset->rk.dname, nmlen);
2088 		if(!nm) {
2089 			log_err("Out of memory in DLVLook");
2090 			return val_error(qstate, id);
2091 		}
2092 		nm[nmlen-1] = 0;
2093 
2094 		vq->ds_rrset->rk.dname = nm;
2095 		vq->ds_rrset->rk.dname_len = nmlen;
2096 
2097 		/* create a nullentry for the key so the dnskey lookup
2098 		 * can be retried after a validation failure for it */
2099 		vq->key_entry = key_entry_create_null(qstate->region,
2100 			nm, nmlen, vq->qchase.qclass, 0, 0);
2101 		if(!vq->key_entry) {
2102 			log_err("Out of memory in DLVLook");
2103 			return val_error(qstate, id);
2104 		}
2105 
2106 		if(!generate_request(qstate, id, vq->ds_rrset->rk.dname,
2107 			vq->ds_rrset->rk.dname_len, LDNS_RR_TYPE_DNSKEY,
2108 			vq->qchase.qclass, BIT_CD)) {
2109 			log_err("mem error generating DNSKEY request");
2110 			return val_error(qstate, id);
2111 		}
2112 		return 0;
2113 	} else if(vq->dlv_status == dlv_there_is_no_dlv) {
2114 		/* continue with the insecure result we got */
2115 		vq->state = VAL_FINISHED_STATE;
2116 		return 1;
2117 	}
2118 	log_assert(vq->dlv_status == dlv_ask_higher);
2119 
2120 	/* ask higher, make sure we stay in DLV repo, below dlv_at */
2121 	if(!dname_subdomain_c(vq->dlv_lookup_name,
2122 		qstate->env->anchors->dlv_anchor->name)) {
2123 		/* just like, there is no DLV */
2124 		verbose(VERB_ALGO, "ask above dlv repo");
2125 		vq->state = VAL_FINISHED_STATE;
2126 		return 1;
2127 	}
2128 	if(vq->dlv_insecure_at && !dname_subdomain_c(vq->dlv_lookup_name,
2129 		vq->dlv_insecure_at)) {
2130 		/* already checked a chain lower than dlv_lookup_name */
2131 		verbose(VERB_ALGO, "ask above insecure endpoint");
2132 		log_nametypeclass(VERB_ALGO, "enpt", vq->dlv_insecure_at, 0, 0);
2133 		vq->state = VAL_FINISHED_STATE;
2134 		return 1;
2135 	}
2136 
2137 	/* check negative cache before making new request */
2138 	if(val_neg_dlvlookup(ve->neg_cache, vq->dlv_lookup_name,
2139 		vq->dlv_lookup_name_len, vq->qchase.qclass,
2140 		qstate->env->rrset_cache, *qstate->env->now)) {
2141 		/* does not exist, go up one (go higher). */
2142 		dname_remove_label(&vq->dlv_lookup_name,
2143 			&vq->dlv_lookup_name_len);
2144 		/* limit number of labels, limited number of recursion */
2145 		return processDLVLookup(qstate, vq, ve, id);
2146 	}
2147 
2148 	if(!generate_request(qstate, id, vq->dlv_lookup_name,
2149 		vq->dlv_lookup_name_len, LDNS_RR_TYPE_DLV,
2150 		vq->qchase.qclass, 0)) {
2151 		return val_error(qstate, id);
2152 	}
2153 
2154 	return 0;
2155 }
2156 
2157 /**
2158  * Handle validator state.
2159  * If a method returns true, the next state is started. If false, then
2160  * processing will stop.
2161  * @param qstate: query state.
2162  * @param vq: validator query state.
2163  * @param ve: validator shared global environment.
2164  * @param id: module id.
2165  */
2166 static void
2167 val_handle(struct module_qstate* qstate, struct val_qstate* vq,
2168 	struct val_env* ve, int id)
2169 {
2170 	int cont = 1;
2171 	while(cont) {
2172 		verbose(VERB_ALGO, "val handle processing q with state %s",
2173 			val_state_to_string(vq->state));
2174 		switch(vq->state) {
2175 			case VAL_INIT_STATE:
2176 				cont = processInit(qstate, vq, ve, id);
2177 				break;
2178 			case VAL_FINDKEY_STATE:
2179 				cont = processFindKey(qstate, vq, id);
2180 				break;
2181 			case VAL_VALIDATE_STATE:
2182 				cont = processValidate(qstate, vq, ve, id);
2183 				break;
2184 			case VAL_FINISHED_STATE:
2185 				cont = processFinished(qstate, vq, ve, id);
2186 				break;
2187 			case VAL_DLVLOOKUP_STATE:
2188 				cont = processDLVLookup(qstate, vq, ve, id);
2189 				break;
2190 			default:
2191 				log_warn("validator: invalid state %d",
2192 					vq->state);
2193 				cont = 0;
2194 				break;
2195 		}
2196 	}
2197 }
2198 
2199 void
2200 val_operate(struct module_qstate* qstate, enum module_ev event, int id,
2201         struct outbound_entry* outbound)
2202 {
2203 	struct val_env* ve = (struct val_env*)qstate->env->modinfo[id];
2204 	struct val_qstate* vq = (struct val_qstate*)qstate->minfo[id];
2205 	verbose(VERB_QUERY, "validator[module %d] operate: extstate:%s "
2206 		"event:%s", id, strextstate(qstate->ext_state[id]),
2207 		strmodulevent(event));
2208 	log_query_info(VERB_QUERY, "validator operate: query",
2209 		&qstate->qinfo);
2210 	if(vq && qstate->qinfo.qname != vq->qchase.qname)
2211 		log_query_info(VERB_QUERY, "validator operate: chased to",
2212 		&vq->qchase);
2213 	(void)outbound;
2214 	if(event == module_event_new ||
2215 		(event == module_event_pass && vq == NULL)) {
2216 		/* pass request to next module, to get it */
2217 		verbose(VERB_ALGO, "validator: pass to next module");
2218 		qstate->ext_state[id] = module_wait_module;
2219 		return;
2220 	}
2221 	if(event == module_event_moddone) {
2222 		/* check if validation is needed */
2223 		verbose(VERB_ALGO, "validator: nextmodule returned");
2224 		if(!needs_validation(qstate, qstate->return_rcode,
2225 			qstate->return_msg)) {
2226 			/* no need to validate this */
2227 			if(qstate->return_msg)
2228 				qstate->return_msg->rep->security =
2229 					sec_status_indeterminate;
2230 			qstate->ext_state[id] = module_finished;
2231 			return;
2232 		}
2233 		if(already_validated(qstate->return_msg)) {
2234 			qstate->ext_state[id] = module_finished;
2235 			return;
2236 		}
2237 		/* qclass ANY should have validation result from spawned
2238 		 * queries. If we get here, it is bogus or an internal error */
2239 		if(qstate->qinfo.qclass == LDNS_RR_CLASS_ANY) {
2240 			verbose(VERB_ALGO, "cannot validate classANY: bogus");
2241 			if(qstate->return_msg)
2242 				qstate->return_msg->rep->security =
2243 					sec_status_bogus;
2244 			qstate->ext_state[id] = module_finished;
2245 			return;
2246 		}
2247 		/* create state to start validation */
2248 		qstate->ext_state[id] = module_error; /* override this */
2249 		if(!vq) {
2250 			vq = val_new(qstate, id);
2251 			if(!vq) {
2252 				log_err("validator: malloc failure");
2253 				qstate->ext_state[id] = module_error;
2254 				return;
2255 			}
2256 		} else if(!vq->orig_msg) {
2257 			if(!val_new_getmsg(qstate, vq)) {
2258 				log_err("validator: malloc failure");
2259 				qstate->ext_state[id] = module_error;
2260 				return;
2261 			}
2262 		}
2263 		val_handle(qstate, vq, ve, id);
2264 		return;
2265 	}
2266 	if(event == module_event_pass) {
2267 		qstate->ext_state[id] = module_error; /* override this */
2268 		/* continue processing, since val_env exists */
2269 		val_handle(qstate, vq, ve, id);
2270 		return;
2271 	}
2272 	log_err("validator: bad event %s", strmodulevent(event));
2273 	qstate->ext_state[id] = module_error;
2274 	return;
2275 }
2276 
2277 /**
2278  * Evaluate the response to a priming request.
2279  *
2280  * @param dnskey_rrset: DNSKEY rrset (can be NULL if none) in prime reply.
2281  * 	(this rrset is allocated in the wrong region, not the qstate).
2282  * @param ta: trust anchor.
2283  * @param qstate: qstate that needs key.
2284  * @param id: module id.
2285  * @return new key entry or NULL on allocation failure.
2286  *	The key entry will either contain a validated DNSKEY rrset, or
2287  *	represent a Null key (query failed, but validation did not), or a
2288  *	Bad key (validation failed).
2289  */
2290 static struct key_entry_key*
2291 primeResponseToKE(struct ub_packed_rrset_key* dnskey_rrset,
2292 	struct trust_anchor* ta, struct module_qstate* qstate, int id)
2293 {
2294 	struct val_env* ve = (struct val_env*)qstate->env->modinfo[id];
2295 	struct key_entry_key* kkey = NULL;
2296 	enum sec_status sec = sec_status_unchecked;
2297 	char* reason = NULL;
2298 	int downprot = 1;
2299 
2300 	if(!dnskey_rrset) {
2301 		log_nametypeclass(VERB_OPS, "failed to prime trust anchor -- "
2302 			"could not fetch DNSKEY rrset",
2303 			ta->name, LDNS_RR_TYPE_DNSKEY, ta->dclass);
2304 		if(qstate->env->cfg->harden_dnssec_stripped) {
2305 			errinf(qstate, "no DNSKEY rrset");
2306 			kkey = key_entry_create_bad(qstate->region, ta->name,
2307 				ta->namelen, ta->dclass, BOGUS_KEY_TTL,
2308 				*qstate->env->now);
2309 		} else 	kkey = key_entry_create_null(qstate->region, ta->name,
2310 				ta->namelen, ta->dclass, NULL_KEY_TTL,
2311 				*qstate->env->now);
2312 		if(!kkey) {
2313 			log_err("out of memory: allocate fail prime key");
2314 			return NULL;
2315 		}
2316 		return kkey;
2317 	}
2318 	/* attempt to verify with trust anchor DS and DNSKEY */
2319 	kkey = val_verify_new_DNSKEYs_with_ta(qstate->region, qstate->env, ve,
2320 		dnskey_rrset, ta->ds_rrset, ta->dnskey_rrset, downprot,
2321 		&reason);
2322 	if(!kkey) {
2323 		log_err("out of memory: verifying prime TA");
2324 		return NULL;
2325 	}
2326 	if(key_entry_isgood(kkey))
2327 		sec = sec_status_secure;
2328 	else
2329 		sec = sec_status_bogus;
2330 	verbose(VERB_DETAIL, "validate keys with anchor(DS): %s",
2331 		sec_status_to_string(sec));
2332 
2333 	if(sec != sec_status_secure) {
2334 		log_nametypeclass(VERB_OPS, "failed to prime trust anchor -- "
2335 			"DNSKEY rrset is not secure",
2336 			ta->name, LDNS_RR_TYPE_DNSKEY, ta->dclass);
2337 		/* NOTE: in this case, we should probably reject the trust
2338 		 * anchor for longer, perhaps forever. */
2339 		if(qstate->env->cfg->harden_dnssec_stripped) {
2340 			errinf(qstate, reason);
2341 			kkey = key_entry_create_bad(qstate->region, ta->name,
2342 				ta->namelen, ta->dclass, BOGUS_KEY_TTL,
2343 				*qstate->env->now);
2344 		} else 	kkey = key_entry_create_null(qstate->region, ta->name,
2345 				ta->namelen, ta->dclass, NULL_KEY_TTL,
2346 				*qstate->env->now);
2347 		if(!kkey) {
2348 			log_err("out of memory: allocate null prime key");
2349 			return NULL;
2350 		}
2351 		return kkey;
2352 	}
2353 
2354 	log_nametypeclass(VERB_DETAIL, "Successfully primed trust anchor",
2355 		ta->name, LDNS_RR_TYPE_DNSKEY, ta->dclass);
2356 	return kkey;
2357 }
2358 
2359 /**
2360  * In inform supers, with the resulting message and rcode and the current
2361  * keyset in the super state, validate the DS response, returning a KeyEntry.
2362  *
2363  * @param qstate: query state that is validating and asked for a DS.
2364  * @param vq: validator query state
2365  * @param id: module id.
2366  * @param rcode: rcode result value.
2367  * @param msg: result message (if rcode is OK).
2368  * @param qinfo: from the sub query state, query info.
2369  * @param ke: the key entry to return. It returns
2370  *	is_bad if the DS response fails to validate, is_null if the
2371  *	DS response indicated an end to secure space, is_good if the DS
2372  *	validated. It returns ke=NULL if the DS response indicated that the
2373  *	request wasn't a delegation point.
2374  * @return 0 on servfail error (malloc failure).
2375  */
2376 static int
2377 ds_response_to_ke(struct module_qstate* qstate, struct val_qstate* vq,
2378         int id, int rcode, struct dns_msg* msg, struct query_info* qinfo,
2379 	struct key_entry_key** ke)
2380 {
2381 	struct val_env* ve = (struct val_env*)qstate->env->modinfo[id];
2382 	char* reason = NULL;
2383 	enum val_classification subtype;
2384 	if(rcode != LDNS_RCODE_NOERROR) {
2385 		char rc[16];
2386 		rc[0]=0;
2387 		(void)sldns_wire2str_rcode_buf(rcode, rc, sizeof(rc));
2388 		/* errors here pretty much break validation */
2389 		verbose(VERB_DETAIL, "DS response was error, thus bogus");
2390 		errinf(qstate, rc);
2391 		errinf(qstate, "no DS");
2392 		goto return_bogus;
2393 	}
2394 
2395 	subtype = val_classify_response(BIT_RD, qinfo, qinfo, msg->rep, 0);
2396 	if(subtype == VAL_CLASS_POSITIVE) {
2397 		struct ub_packed_rrset_key* ds;
2398 		enum sec_status sec;
2399 		ds = reply_find_answer_rrset(qinfo, msg->rep);
2400 		/* If there was no DS rrset, then we have mis-classified
2401 		 * this message. */
2402 		if(!ds) {
2403 			log_warn("internal error: POSITIVE DS response was "
2404 				"missing DS.");
2405 			errinf(qstate, "no DS record");
2406 			goto return_bogus;
2407 		}
2408 		/* Verify only returns BOGUS or SECURE. If the rrset is
2409 		 * bogus, then we are done. */
2410 		sec = val_verify_rrset_entry(qstate->env, ve, ds,
2411 			vq->key_entry, &reason);
2412 		if(sec != sec_status_secure) {
2413 			verbose(VERB_DETAIL, "DS rrset in DS response did "
2414 				"not verify");
2415 			errinf(qstate, reason);
2416 			goto return_bogus;
2417 		}
2418 
2419 		/* If the DS rrset validates, we still have to make sure
2420 		 * that they are usable. */
2421 		if(!val_dsset_isusable(ds)) {
2422 			/* If they aren't usable, then we treat it like
2423 			 * there was no DS. */
2424 			*ke = key_entry_create_null(qstate->region,
2425 				qinfo->qname, qinfo->qname_len, qinfo->qclass,
2426 				ub_packed_rrset_ttl(ds), *qstate->env->now);
2427 			return (*ke) != NULL;
2428 		}
2429 
2430 		/* Otherwise, we return the positive response. */
2431 		log_query_info(VERB_DETAIL, "validated DS", qinfo);
2432 		*ke = key_entry_create_rrset(qstate->region,
2433 			qinfo->qname, qinfo->qname_len, qinfo->qclass, ds,
2434 			NULL, *qstate->env->now);
2435 		return (*ke) != NULL;
2436 	} else if(subtype == VAL_CLASS_NODATA ||
2437 		subtype == VAL_CLASS_NAMEERROR) {
2438 		/* NODATA means that the qname exists, but that there was
2439 		 * no DS.  This is a pretty normal case. */
2440 		time_t proof_ttl = 0;
2441 		enum sec_status sec;
2442 
2443 		/* make sure there are NSECs or NSEC3s with signatures */
2444 		if(!val_has_signed_nsecs(msg->rep, &reason)) {
2445 			verbose(VERB_ALGO, "no NSECs: %s", reason);
2446 			errinf(qstate, reason);
2447 			goto return_bogus;
2448 		}
2449 
2450 		/* For subtype Name Error.
2451 		 * attempt ANS 2.8.1.0 compatibility where it sets rcode
2452 		 * to nxdomain, but really this is an Nodata/Noerror response.
2453 		 * Find and prove the empty nonterminal in that case */
2454 
2455 		/* Try to prove absence of the DS with NSEC */
2456 		sec = val_nsec_prove_nodata_dsreply(
2457 			qstate->env, ve, qinfo, msg->rep, vq->key_entry,
2458 			&proof_ttl, &reason);
2459 		switch(sec) {
2460 			case sec_status_secure:
2461 				verbose(VERB_DETAIL, "NSEC RRset for the "
2462 					"referral proved no DS.");
2463 				*ke = key_entry_create_null(qstate->region,
2464 					qinfo->qname, qinfo->qname_len,
2465 					qinfo->qclass, proof_ttl,
2466 					*qstate->env->now);
2467 				return (*ke) != NULL;
2468 			case sec_status_insecure:
2469 				verbose(VERB_DETAIL, "NSEC RRset for the "
2470 				  "referral proved not a delegation point");
2471 				*ke = NULL;
2472 				return 1;
2473 			case sec_status_bogus:
2474 				verbose(VERB_DETAIL, "NSEC RRset for the "
2475 					"referral did not prove no DS.");
2476 				errinf(qstate, reason);
2477 				goto return_bogus;
2478 			case sec_status_unchecked:
2479 			default:
2480 				/* NSEC proof did not work, try next */
2481 				break;
2482 		}
2483 
2484 		sec = nsec3_prove_nods(qstate->env, ve,
2485 			msg->rep->rrsets + msg->rep->an_numrrsets,
2486 			msg->rep->ns_numrrsets, qinfo, vq->key_entry, &reason);
2487 		switch(sec) {
2488 			case sec_status_insecure:
2489 				/* case insecure also continues to unsigned
2490 				 * space.  If nsec3-iter-count too high or
2491 				 * optout, then treat below as unsigned */
2492 			case sec_status_secure:
2493 				verbose(VERB_DETAIL, "NSEC3s for the "
2494 					"referral proved no DS.");
2495 				*ke = key_entry_create_null(qstate->region,
2496 					qinfo->qname, qinfo->qname_len,
2497 					qinfo->qclass, proof_ttl,
2498 					*qstate->env->now);
2499 				return (*ke) != NULL;
2500 			case sec_status_indeterminate:
2501 				verbose(VERB_DETAIL, "NSEC3s for the "
2502 				  "referral proved no delegation");
2503 				*ke = NULL;
2504 				return 1;
2505 			case sec_status_bogus:
2506 				verbose(VERB_DETAIL, "NSEC3s for the "
2507 					"referral did not prove no DS.");
2508 				errinf(qstate, reason);
2509 				goto return_bogus;
2510 			case sec_status_unchecked:
2511 			default:
2512 				/* NSEC3 proof did not work */
2513 				break;
2514 		}
2515 
2516 		/* Apparently, no available NSEC/NSEC3 proved NODATA, so
2517 		 * this is BOGUS. */
2518 		verbose(VERB_DETAIL, "DS %s ran out of options, so return "
2519 			"bogus", val_classification_to_string(subtype));
2520 		errinf(qstate, "no DS but also no proof of that");
2521 		goto return_bogus;
2522 	} else if(subtype == VAL_CLASS_CNAME ||
2523 		subtype == VAL_CLASS_CNAMENOANSWER) {
2524 		/* if the CNAME matches the exact name we want and is signed
2525 		 * properly, then also, we are sure that no DS exists there,
2526 		 * much like a NODATA proof */
2527 		enum sec_status sec;
2528 		struct ub_packed_rrset_key* cname;
2529 		cname = reply_find_rrset_section_an(msg->rep, qinfo->qname,
2530 			qinfo->qname_len, LDNS_RR_TYPE_CNAME, qinfo->qclass);
2531 		if(!cname) {
2532 			errinf(qstate, "validator classified CNAME but no "
2533 				"CNAME of the queried name for DS");
2534 			goto return_bogus;
2535 		}
2536 		if(((struct packed_rrset_data*)cname->entry.data)->rrsig_count
2537 			== 0) {
2538 		        if(msg->rep->an_numrrsets != 0 && ntohs(msg->rep->
2539 				rrsets[0]->rk.type)==LDNS_RR_TYPE_DNAME) {
2540 				errinf(qstate, "DS got DNAME answer");
2541 			} else {
2542 				errinf(qstate, "DS got unsigned CNAME answer");
2543 			}
2544 			goto return_bogus;
2545 		}
2546 		sec = val_verify_rrset_entry(qstate->env, ve, cname,
2547 			vq->key_entry, &reason);
2548 		if(sec == sec_status_secure) {
2549 			verbose(VERB_ALGO, "CNAME validated, "
2550 				"proof that DS does not exist");
2551 			/* and that it is not a referral point */
2552 			*ke = NULL;
2553 			return 1;
2554 		}
2555 		errinf(qstate, "CNAME in DS response was not secure.");
2556 		errinf(qstate, reason);
2557 		goto return_bogus;
2558 	} else {
2559 		verbose(VERB_QUERY, "Encountered an unhandled type of "
2560 			"DS response, thus bogus.");
2561 		errinf(qstate, "no DS and");
2562 		if(FLAGS_GET_RCODE(msg->rep->flags) != LDNS_RCODE_NOERROR) {
2563 			char rc[16];
2564 			rc[0]=0;
2565 			(void)sldns_wire2str_rcode_buf((int)FLAGS_GET_RCODE(
2566 				msg->rep->flags), rc, sizeof(rc));
2567 			errinf(qstate, rc);
2568 		} else	errinf(qstate, val_classification_to_string(subtype));
2569 		errinf(qstate, "message fails to prove that");
2570 		goto return_bogus;
2571 	}
2572 return_bogus:
2573 	*ke = key_entry_create_bad(qstate->region, qinfo->qname,
2574 		qinfo->qname_len, qinfo->qclass,
2575 		BOGUS_KEY_TTL, *qstate->env->now);
2576 	return (*ke) != NULL;
2577 }
2578 
2579 /**
2580  * Process DS response. Called from inform_supers.
2581  * Because it is in inform_supers, the mesh itself is busy doing callbacks
2582  * for a state that is to be deleted soon; don't touch the mesh; instead
2583  * set a state in the super, as the super will be reactivated soon.
2584  * Perform processing to determine what state to set in the super.
2585  *
2586  * @param qstate: query state that is validating and asked for a DS.
2587  * @param vq: validator query state
2588  * @param id: module id.
2589  * @param rcode: rcode result value.
2590  * @param msg: result message (if rcode is OK).
2591  * @param qinfo: from the sub query state, query info.
2592  * @param origin: the origin of msg.
2593  */
2594 static void
2595 process_ds_response(struct module_qstate* qstate, struct val_qstate* vq,
2596 	int id, int rcode, struct dns_msg* msg, struct query_info* qinfo,
2597 	struct sock_list* origin)
2598 {
2599 	struct key_entry_key* dske = NULL;
2600 	uint8_t* olds = vq->empty_DS_name;
2601 	vq->empty_DS_name = NULL;
2602 	if(!ds_response_to_ke(qstate, vq, id, rcode, msg, qinfo, &dske)) {
2603 			log_err("malloc failure in process_ds_response");
2604 			vq->key_entry = NULL; /* make it error */
2605 			vq->state = VAL_VALIDATE_STATE;
2606 			return;
2607 	}
2608 	if(dske == NULL) {
2609 		vq->empty_DS_name = regional_alloc_init(qstate->region,
2610 			qinfo->qname, qinfo->qname_len);
2611 		if(!vq->empty_DS_name) {
2612 			log_err("malloc failure in empty_DS_name");
2613 			vq->key_entry = NULL; /* make it error */
2614 			vq->state = VAL_VALIDATE_STATE;
2615 			return;
2616 		}
2617 		vq->empty_DS_len = qinfo->qname_len;
2618 		vq->chain_blacklist = NULL;
2619 		/* ds response indicated that we aren't on a delegation point.
2620 		 * Keep the forState.state on FINDKEY. */
2621 	} else if(key_entry_isgood(dske)) {
2622 		vq->ds_rrset = key_entry_get_rrset(dske, qstate->region);
2623 		if(!vq->ds_rrset) {
2624 			log_err("malloc failure in process DS");
2625 			vq->key_entry = NULL; /* make it error */
2626 			vq->state = VAL_VALIDATE_STATE;
2627 			return;
2628 		}
2629 		vq->chain_blacklist = NULL; /* fresh blacklist for next part*/
2630 		/* Keep the forState.state on FINDKEY. */
2631 	} else if(key_entry_isbad(dske)
2632 		&& vq->restart_count < VAL_MAX_RESTART_COUNT) {
2633 		vq->empty_DS_name = olds;
2634 		val_blacklist(&vq->chain_blacklist, qstate->region, origin, 1);
2635 		qstate->errinf = NULL;
2636 		vq->restart_count++;
2637 	} else {
2638 		if(key_entry_isbad(dske)) {
2639 			errinf_origin(qstate, origin);
2640 			errinf_dname(qstate, "for DS", qinfo->qname);
2641 		}
2642 		/* NOTE: the reason for the DS to be not good (that is,
2643 		 * either bad or null) should have been logged by
2644 		 * dsResponseToKE. */
2645 		vq->key_entry = dske;
2646 		/* The FINDKEY phase has ended, so move on. */
2647 		vq->state = VAL_VALIDATE_STATE;
2648 	}
2649 }
2650 
2651 /**
2652  * Process DNSKEY response. Called from inform_supers.
2653  * Sets the key entry in the state.
2654  * Because it is in inform_supers, the mesh itself is busy doing callbacks
2655  * for a state that is to be deleted soon; don't touch the mesh; instead
2656  * set a state in the super, as the super will be reactivated soon.
2657  * Perform processing to determine what state to set in the super.
2658  *
2659  * @param qstate: query state that is validating and asked for a DNSKEY.
2660  * @param vq: validator query state
2661  * @param id: module id.
2662  * @param rcode: rcode result value.
2663  * @param msg: result message (if rcode is OK).
2664  * @param qinfo: from the sub query state, query info.
2665  * @param origin: the origin of msg.
2666  */
2667 static void
2668 process_dnskey_response(struct module_qstate* qstate, struct val_qstate* vq,
2669 	int id, int rcode, struct dns_msg* msg, struct query_info* qinfo,
2670 	struct sock_list* origin)
2671 {
2672 	struct val_env* ve = (struct val_env*)qstate->env->modinfo[id];
2673 	struct key_entry_key* old = vq->key_entry;
2674 	struct ub_packed_rrset_key* dnskey = NULL;
2675 	int downprot;
2676 	char* reason = NULL;
2677 
2678 	if(rcode == LDNS_RCODE_NOERROR)
2679 		dnskey = reply_find_answer_rrset(qinfo, msg->rep);
2680 
2681 	if(dnskey == NULL) {
2682 		/* bad response */
2683 		verbose(VERB_DETAIL, "Missing DNSKEY RRset in response to "
2684 			"DNSKEY query.");
2685 		if(vq->restart_count < VAL_MAX_RESTART_COUNT) {
2686 			val_blacklist(&vq->chain_blacklist, qstate->region,
2687 				origin, 1);
2688 			qstate->errinf = NULL;
2689 			vq->restart_count++;
2690 			return;
2691 		}
2692 		vq->key_entry = key_entry_create_bad(qstate->region,
2693 			qinfo->qname, qinfo->qname_len, qinfo->qclass,
2694 			BOGUS_KEY_TTL, *qstate->env->now);
2695 		if(!vq->key_entry) {
2696 			log_err("alloc failure in missing dnskey response");
2697 			/* key_entry is NULL for failure in Validate */
2698 		}
2699 		errinf(qstate, "No DNSKEY record");
2700 		errinf_origin(qstate, origin);
2701 		errinf_dname(qstate, "for key", qinfo->qname);
2702 		vq->state = VAL_VALIDATE_STATE;
2703 		return;
2704 	}
2705 	if(!vq->ds_rrset) {
2706 		log_err("internal error: no DS rrset for new DNSKEY response");
2707 		vq->key_entry = NULL;
2708 		vq->state = VAL_VALIDATE_STATE;
2709 		return;
2710 	}
2711 	downprot = 1;
2712 	vq->key_entry = val_verify_new_DNSKEYs(qstate->region, qstate->env,
2713 		ve, dnskey, vq->ds_rrset, downprot, &reason);
2714 
2715 	if(!vq->key_entry) {
2716 		log_err("out of memory in verify new DNSKEYs");
2717 		vq->state = VAL_VALIDATE_STATE;
2718 		return;
2719 	}
2720 	/* If the key entry isBad or isNull, then we can move on to the next
2721 	 * state. */
2722 	if(!key_entry_isgood(vq->key_entry)) {
2723 		if(key_entry_isbad(vq->key_entry)) {
2724 			if(vq->restart_count < VAL_MAX_RESTART_COUNT) {
2725 				val_blacklist(&vq->chain_blacklist,
2726 					qstate->region, origin, 1);
2727 				qstate->errinf = NULL;
2728 				vq->restart_count++;
2729 				vq->key_entry = old;
2730 				return;
2731 			}
2732 			verbose(VERB_DETAIL, "Did not match a DS to a DNSKEY, "
2733 				"thus bogus.");
2734 			errinf(qstate, reason);
2735 			errinf_origin(qstate, origin);
2736 			errinf_dname(qstate, "for key", qinfo->qname);
2737 		}
2738 		vq->chain_blacklist = NULL;
2739 		vq->state = VAL_VALIDATE_STATE;
2740 		return;
2741 	}
2742 	vq->chain_blacklist = NULL;
2743 	qstate->errinf = NULL;
2744 
2745 	/* The DNSKEY validated, so cache it as a trusted key rrset. */
2746 	key_cache_insert(ve->kcache, vq->key_entry, qstate);
2747 
2748 	/* If good, we stay in the FINDKEY state. */
2749 	log_query_info(VERB_DETAIL, "validated DNSKEY", qinfo);
2750 }
2751 
2752 /**
2753  * Process prime response
2754  * Sets the key entry in the state.
2755  *
2756  * @param qstate: query state that is validating and primed a trust anchor.
2757  * @param vq: validator query state
2758  * @param id: module id.
2759  * @param rcode: rcode result value.
2760  * @param msg: result message (if rcode is OK).
2761  * @param origin: the origin of msg.
2762  */
2763 static void
2764 process_prime_response(struct module_qstate* qstate, struct val_qstate* vq,
2765 	int id, int rcode, struct dns_msg* msg, struct sock_list* origin)
2766 {
2767 	struct val_env* ve = (struct val_env*)qstate->env->modinfo[id];
2768 	struct ub_packed_rrset_key* dnskey_rrset = NULL;
2769 	struct trust_anchor* ta = anchor_find(qstate->env->anchors,
2770 		vq->trust_anchor_name, vq->trust_anchor_labs,
2771 		vq->trust_anchor_len, vq->qchase.qclass);
2772 	if(!ta) {
2773 		/* trust anchor revoked, restart with less anchors */
2774 		vq->state = VAL_INIT_STATE;
2775 		if(!vq->trust_anchor_name)
2776 			vq->state = VAL_VALIDATE_STATE; /* break a loop */
2777 		vq->trust_anchor_name = NULL;
2778 		return;
2779 	}
2780 	/* Fetch and validate the keyEntry that corresponds to the
2781 	 * current trust anchor. */
2782 	if(rcode == LDNS_RCODE_NOERROR) {
2783 		dnskey_rrset = reply_find_rrset_section_an(msg->rep,
2784 			ta->name, ta->namelen, LDNS_RR_TYPE_DNSKEY,
2785 			ta->dclass);
2786 	}
2787 	if(ta->autr) {
2788 		if(!autr_process_prime(qstate->env, ve, ta, dnskey_rrset)) {
2789 			/* trust anchor revoked, restart with less anchors */
2790 			vq->state = VAL_INIT_STATE;
2791 			vq->trust_anchor_name = NULL;
2792 			return;
2793 		}
2794 	}
2795 	vq->key_entry = primeResponseToKE(dnskey_rrset, ta, qstate, id);
2796 	lock_basic_unlock(&ta->lock);
2797 	if(vq->key_entry) {
2798 		if(key_entry_isbad(vq->key_entry)
2799 			&& vq->restart_count < VAL_MAX_RESTART_COUNT) {
2800 			val_blacklist(&vq->chain_blacklist, qstate->region,
2801 				origin, 1);
2802 			qstate->errinf = NULL;
2803 			vq->restart_count++;
2804 			vq->key_entry = NULL;
2805 			vq->state = VAL_INIT_STATE;
2806 			return;
2807 		}
2808 		vq->chain_blacklist = NULL;
2809 		errinf_origin(qstate, origin);
2810 		errinf_dname(qstate, "for trust anchor", ta->name);
2811 		/* store the freshly primed entry in the cache */
2812 		key_cache_insert(ve->kcache, vq->key_entry, qstate);
2813 	}
2814 
2815 	/* If the result of the prime is a null key, skip the FINDKEY state.*/
2816 	if(!vq->key_entry || key_entry_isnull(vq->key_entry) ||
2817 		key_entry_isbad(vq->key_entry)) {
2818 		vq->state = VAL_VALIDATE_STATE;
2819 	}
2820 	/* the qstate will be reactivated after inform_super is done */
2821 }
2822 
2823 /**
2824  * Process DLV response. Called from inform_supers.
2825  * Because it is in inform_supers, the mesh itself is busy doing callbacks
2826  * for a state that is to be deleted soon; don't touch the mesh; instead
2827  * set a state in the super, as the super will be reactivated soon.
2828  * Perform processing to determine what state to set in the super.
2829  *
2830  * @param qstate: query state that is validating and asked for a DLV.
2831  * @param vq: validator query state
2832  * @param id: module id.
2833  * @param rcode: rcode result value.
2834  * @param msg: result message (if rcode is OK).
2835  * @param qinfo: from the sub query state, query info.
2836  */
2837 static void
2838 process_dlv_response(struct module_qstate* qstate, struct val_qstate* vq,
2839 	int id, int rcode, struct dns_msg* msg, struct query_info* qinfo)
2840 {
2841 	struct val_env* ve = (struct val_env*)qstate->env->modinfo[id];
2842 
2843 	verbose(VERB_ALGO, "process dlv response to super");
2844 	if(rcode != LDNS_RCODE_NOERROR) {
2845 		/* lookup failed, set in vq to give up */
2846 		vq->dlv_status = dlv_error;
2847 		verbose(VERB_ALGO, "response is error");
2848 		return;
2849 	}
2850 	if(msg->rep->security != sec_status_secure) {
2851 		vq->dlv_status = dlv_error;
2852 		verbose(VERB_ALGO, "response is not secure, %s",
2853 			sec_status_to_string(msg->rep->security));
2854 		return;
2855 	}
2856 	/* was the lookup a success? validated DLV? */
2857 	if(FLAGS_GET_RCODE(msg->rep->flags) == LDNS_RCODE_NOERROR &&
2858 		msg->rep->an_numrrsets == 1 &&
2859 		msg->rep->security == sec_status_secure &&
2860 		ntohs(msg->rep->rrsets[0]->rk.type) == LDNS_RR_TYPE_DLV &&
2861 		ntohs(msg->rep->rrsets[0]->rk.rrset_class) == qinfo->qclass &&
2862 		query_dname_compare(msg->rep->rrsets[0]->rk.dname,
2863 			vq->dlv_lookup_name) == 0) {
2864 		/* yay! it is just like a DS */
2865 		vq->ds_rrset = (struct ub_packed_rrset_key*)
2866 			regional_alloc_init(qstate->region,
2867 			msg->rep->rrsets[0], sizeof(*vq->ds_rrset));
2868 		if(!vq->ds_rrset) {
2869 			log_err("out of memory in process_dlv");
2870 			return;
2871 		}
2872 		vq->ds_rrset->entry.key = vq->ds_rrset;
2873 		vq->ds_rrset->rk.dname = (uint8_t*)regional_alloc_init(
2874 			qstate->region, vq->ds_rrset->rk.dname,
2875 			vq->ds_rrset->rk.dname_len);
2876 		if(!vq->ds_rrset->rk.dname) {
2877 			log_err("out of memory in process_dlv");
2878 			vq->dlv_status = dlv_error;
2879 			return;
2880 		}
2881 		vq->ds_rrset->entry.data = regional_alloc_init(qstate->region,
2882 			vq->ds_rrset->entry.data,
2883 			packed_rrset_sizeof(vq->ds_rrset->entry.data));
2884 		if(!vq->ds_rrset->entry.data) {
2885 			log_err("out of memory in process_dlv");
2886 			vq->dlv_status = dlv_error;
2887 			return;
2888 		}
2889 		packed_rrset_ptr_fixup(vq->ds_rrset->entry.data);
2890 		/* make vq do a DNSKEY query next up */
2891 		vq->dlv_status = dlv_success;
2892 		return;
2893 	}
2894 	/* store NSECs into negative cache */
2895 	val_neg_addreply(ve->neg_cache, msg->rep);
2896 
2897 	/* was the lookup a failure?
2898 	 *   if we have to go up into the DLV for a higher DLV anchor
2899 	 *   then set this in the vq, so it can make queries when activated.
2900 	 * See if the NSECs indicate that we should look for higher DLV
2901 	 * or, that there is no DLV securely */
2902 	if(!val_nsec_check_dlv(qinfo, msg->rep, &vq->dlv_lookup_name,
2903 		&vq->dlv_lookup_name_len)) {
2904 		vq->dlv_status = dlv_error;
2905 		verbose(VERB_ALGO, "nsec error");
2906 		return;
2907 	}
2908 	if(!dname_subdomain_c(vq->dlv_lookup_name,
2909 		qstate->env->anchors->dlv_anchor->name)) {
2910 		vq->dlv_status = dlv_there_is_no_dlv;
2911 		return;
2912 	}
2913 	vq->dlv_status = dlv_ask_higher;
2914 }
2915 
2916 /*
2917  * inform validator super.
2918  *
2919  * @param qstate: query state that finished.
2920  * @param id: module id.
2921  * @param super: the qstate to inform.
2922  */
2923 void
2924 val_inform_super(struct module_qstate* qstate, int id,
2925 	struct module_qstate* super)
2926 {
2927 	struct val_qstate* vq = (struct val_qstate*)super->minfo[id];
2928 	log_query_info(VERB_ALGO, "validator: inform_super, sub is",
2929 		&qstate->qinfo);
2930 	log_query_info(VERB_ALGO, "super is", &super->qinfo);
2931 	if(!vq) {
2932 		verbose(VERB_ALGO, "super: has no validator state");
2933 		return;
2934 	}
2935 	if(vq->wait_prime_ta) {
2936 		vq->wait_prime_ta = 0;
2937 		process_prime_response(super, vq, id, qstate->return_rcode,
2938 			qstate->return_msg, qstate->reply_origin);
2939 		return;
2940 	}
2941 	if(qstate->qinfo.qtype == LDNS_RR_TYPE_DS) {
2942 		process_ds_response(super, vq, id, qstate->return_rcode,
2943 			qstate->return_msg, &qstate->qinfo,
2944 			qstate->reply_origin);
2945 		return;
2946 	} else if(qstate->qinfo.qtype == LDNS_RR_TYPE_DNSKEY) {
2947 		process_dnskey_response(super, vq, id, qstate->return_rcode,
2948 			qstate->return_msg, &qstate->qinfo,
2949 			qstate->reply_origin);
2950 		return;
2951 	} else if(qstate->qinfo.qtype == LDNS_RR_TYPE_DLV) {
2952 		process_dlv_response(super, vq, id, qstate->return_rcode,
2953 			qstate->return_msg, &qstate->qinfo);
2954 		return;
2955 	}
2956 	log_err("internal error in validator: no inform_supers possible");
2957 }
2958 
2959 void
2960 val_clear(struct module_qstate* qstate, int id)
2961 {
2962 	if(!qstate)
2963 		return;
2964 	/* everything is allocated in the region, so assign NULL */
2965 	qstate->minfo[id] = NULL;
2966 }
2967 
2968 size_t
2969 val_get_mem(struct module_env* env, int id)
2970 {
2971 	struct val_env* ve = (struct val_env*)env->modinfo[id];
2972 	if(!ve)
2973 		return 0;
2974 	return sizeof(*ve) + key_cache_get_mem(ve->kcache) +
2975 		val_neg_get_mem(ve->neg_cache) +
2976 		sizeof(size_t)*2*ve->nsec3_keyiter_count;
2977 }
2978 
2979 /**
2980  * The validator function block
2981  */
2982 static struct module_func_block val_block = {
2983 	"validator",
2984 	&val_init, &val_deinit, &val_operate, &val_inform_super, &val_clear,
2985 	&val_get_mem
2986 };
2987 
2988 struct module_func_block*
2989 val_get_funcblock(void)
2990 {
2991 	return &val_block;
2992 }
2993 
2994 const char*
2995 val_state_to_string(enum val_state state)
2996 {
2997 	switch(state) {
2998 		case VAL_INIT_STATE: return "VAL_INIT_STATE";
2999 		case VAL_FINDKEY_STATE: return "VAL_FINDKEY_STATE";
3000 		case VAL_VALIDATE_STATE: return "VAL_VALIDATE_STATE";
3001 		case VAL_FINISHED_STATE: return "VAL_FINISHED_STATE";
3002 		case VAL_DLVLOOKUP_STATE: return "VAL_DLVLOOKUP_STATE";
3003 	}
3004 	return "UNKNOWN VALIDATOR STATE";
3005 }
3006 
3007