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