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