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