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