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