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