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