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