xref: /freebsd/contrib/unbound/services/authzone.c (revision 7a789145f88a6aceacc59029a0cafe7de7aeefea)
1 /*
2  * services/authzone.c - authoritative zone that is locally hosted.
3  *
4  * Copyright (c) 2017, 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 the functions for an authority zone.  This zone
40  * is queried by the iterator, just like a stub or forward zone, but then
41  * the data is locally held.
42  */
43 
44 #include "config.h"
45 #include "services/authzone.h"
46 #include "util/data/dname.h"
47 #include "util/data/msgparse.h"
48 #include "util/data/msgreply.h"
49 #include "util/data/msgencode.h"
50 #include "util/data/packed_rrset.h"
51 #include "util/regional.h"
52 #include "util/net_help.h"
53 #include "util/netevent.h"
54 #include "util/config_file.h"
55 #include "util/log.h"
56 #include "util/module.h"
57 #include "util/random.h"
58 #include "util/timeval_func.h"
59 #include "services/cache/dns.h"
60 #include "services/outside_network.h"
61 #include "services/listen_dnsport.h"
62 #include "services/mesh.h"
63 #include "sldns/rrdef.h"
64 #include "sldns/pkthdr.h"
65 #include "sldns/sbuffer.h"
66 #include "sldns/str2wire.h"
67 #include "sldns/wire2str.h"
68 #include "sldns/parseutil.h"
69 #include "sldns/keyraw.h"
70 #include "validator/val_nsec3.h"
71 #include "validator/val_nsec.h"
72 #include "validator/val_secalgo.h"
73 #include "validator/val_sigcrypt.h"
74 #include "validator/val_anchor.h"
75 #include "validator/val_utils.h"
76 #include <ctype.h>
77 
78 /** bytes to use for NSEC3 hash buffer. 20 for sha1 */
79 #define N3HASHBUFLEN 32
80 /** max number of CNAMEs we are willing to follow (in one answer) */
81 #define MAX_CNAME_CHAIN 8
82 /** timeout for probe packets for SOA */
83 #define AUTH_PROBE_TIMEOUT 100 /* msec */
84 /** when to stop with SOA probes (when exponential timeouts exceed this) */
85 #define AUTH_PROBE_TIMEOUT_STOP 1000 /* msec */
86 /* auth transfer timeout for TCP connections, in msec */
87 #define AUTH_TRANSFER_TIMEOUT 10000 /* msec */
88 /* auth transfer max backoff for failed transfers and probes */
89 #define AUTH_TRANSFER_MAX_BACKOFF 86400 /* sec */
90 /* auth http port number */
91 #define AUTH_HTTP_PORT 80
92 /* auth https port number */
93 #define AUTH_HTTPS_PORT 443
94 /* max depth for nested $INCLUDEs */
95 #define MAX_INCLUDE_DEPTH 10
96 /** number of timeouts before we fallback from IXFR to AXFR,
97  * because some versions of servers (eg. dnsmasq) drop IXFR packets. */
98 #define NUM_TIMEOUTS_FALLBACK_IXFR 3
99 /** number of IXFRs before an AXFR is performed, to consolidate RPZ memory. */
100 #define NUM_IXFR_BEFORE_AXFR 5
101 
102 /** pick up nextprobe task to start waiting to perform transfer actions */
103 static void xfr_set_timeout(struct auth_xfer* xfr, struct module_env* env,
104 	int failure, int lookup_only);
105 /** move to sending the probe packets, next if fails. task_probe */
106 static void xfr_probe_send_or_end(struct auth_xfer* xfr,
107 	struct module_env* env);
108 /** pick up probe task with specified(or NULL) destination first,
109  * or transfer task if nothing to probe, or false if already in progress */
110 static int xfr_start_probe(struct auth_xfer* xfr, struct module_env* env,
111 	struct auth_master* spec);
112 /** copy the master addresses from the task_probe lookups to the allow_notify
113  * list of masters */
114 static void probe_copy_masters_for_allow_notify(struct auth_xfer* xfr);
115 /** delete xfer structure (not its tree entry) */
116 void auth_xfer_delete(struct auth_xfer* xfr);
117 
118 /** create new dns_msg */
119 static struct dns_msg*
msg_create(struct regional * region,struct query_info * qinfo)120 msg_create(struct regional* region, struct query_info* qinfo)
121 {
122 	struct dns_msg* msg = (struct dns_msg*)regional_alloc(region,
123 		sizeof(struct dns_msg));
124 	if(!msg)
125 		return NULL;
126 	msg->qinfo.qname = regional_alloc_init(region, qinfo->qname,
127 		qinfo->qname_len);
128 	if(!msg->qinfo.qname)
129 		return NULL;
130 	msg->qinfo.qname_len = qinfo->qname_len;
131 	msg->qinfo.qtype = qinfo->qtype;
132 	msg->qinfo.qclass = qinfo->qclass;
133 	msg->qinfo.local_alias = NULL;
134 	/* non-packed reply_info, because it needs to grow the array */
135 	msg->rep = (struct reply_info*)regional_alloc_zero(region,
136 		sizeof(struct reply_info)-sizeof(struct rrset_ref));
137 	if(!msg->rep)
138 		return NULL;
139 	msg->rep->flags = (uint16_t)(BIT_QR | BIT_AA);
140 	msg->rep->authoritative = 1;
141 	msg->rep->reason_bogus = LDNS_EDE_NONE;
142 	msg->rep->qdcount = 1;
143 	/* rrsets is NULL, no rrsets yet */
144 	return msg;
145 }
146 
147 /** grow rrset array by one in msg */
148 static int
msg_grow_array(struct regional * region,struct dns_msg * msg)149 msg_grow_array(struct regional* region, struct dns_msg* msg)
150 {
151 	if(msg->rep->rrsets == NULL) {
152 		msg->rep->rrsets = regional_alloc_zero(region,
153 			sizeof(struct ub_packed_rrset_key*)*(msg->rep->rrset_count+1));
154 		if(!msg->rep->rrsets)
155 			return 0;
156 	} else {
157 		struct ub_packed_rrset_key** rrsets_old = msg->rep->rrsets;
158 		msg->rep->rrsets = regional_alloc_zero(region,
159 			sizeof(struct ub_packed_rrset_key*)*(msg->rep->rrset_count+1));
160 		if(!msg->rep->rrsets)
161 			return 0;
162 		memmove(msg->rep->rrsets, rrsets_old,
163 			sizeof(struct ub_packed_rrset_key*)*msg->rep->rrset_count);
164 	}
165 	return 1;
166 }
167 
168 /** get ttl of rrset */
169 static time_t
get_rrset_ttl(struct ub_packed_rrset_key * k)170 get_rrset_ttl(struct ub_packed_rrset_key* k)
171 {
172 	struct packed_rrset_data* d = (struct packed_rrset_data*)
173 		k->entry.data;
174 	return d->ttl;
175 }
176 
177 /** Copy rrset into region from domain-datanode and packet rrset */
178 static struct ub_packed_rrset_key*
auth_packed_rrset_copy_region(struct auth_zone * z,struct auth_data * node,struct auth_rrset * rrset,struct regional * region)179 auth_packed_rrset_copy_region(struct auth_zone* z, struct auth_data* node,
180 	struct auth_rrset* rrset, struct regional* region)
181 {
182 	struct ub_packed_rrset_key key;
183 	memset(&key, 0, sizeof(key));
184 	key.entry.key = &key;
185 	key.entry.data = rrset->data;
186 	key.rk.dname = node->name;
187 	key.rk.dname_len = node->namelen;
188 	key.rk.type = htons(rrset->type);
189 	key.rk.rrset_class = htons(z->dclass);
190 	key.entry.hash = rrset_key_hash(&key.rk);
191 	return packed_rrset_copy_region(&key, region, 0);
192 }
193 
194 /** fix up msg->rep TTL and prefetch ttl */
195 static void
msg_ttl(struct dns_msg * msg)196 msg_ttl(struct dns_msg* msg)
197 {
198 	if(msg->rep->rrset_count == 0) return;
199 	if(msg->rep->rrset_count == 1) {
200 		msg->rep->ttl = get_rrset_ttl(msg->rep->rrsets[0]);
201 		msg->rep->prefetch_ttl = PREFETCH_TTL_CALC(msg->rep->ttl);
202 		msg->rep->serve_expired_ttl = msg->rep->ttl + SERVE_EXPIRED_TTL;
203 	} else if(get_rrset_ttl(msg->rep->rrsets[msg->rep->rrset_count-1]) <
204 		msg->rep->ttl) {
205 		msg->rep->ttl = get_rrset_ttl(msg->rep->rrsets[
206 			msg->rep->rrset_count-1]);
207 		msg->rep->prefetch_ttl = PREFETCH_TTL_CALC(msg->rep->ttl);
208 		msg->rep->serve_expired_ttl = msg->rep->ttl + SERVE_EXPIRED_TTL;
209 	}
210 }
211 
212 /** see if rrset is a duplicate in the answer message */
213 static int
msg_rrset_duplicate(struct dns_msg * msg,uint8_t * nm,size_t nmlen,uint16_t type,uint16_t dclass)214 msg_rrset_duplicate(struct dns_msg* msg, uint8_t* nm, size_t nmlen,
215 	uint16_t type, uint16_t dclass)
216 {
217 	size_t i;
218 	for(i=0; i<msg->rep->rrset_count; i++) {
219 		struct ub_packed_rrset_key* k = msg->rep->rrsets[i];
220 		if(ntohs(k->rk.type) == type && k->rk.dname_len == nmlen &&
221 			ntohs(k->rk.rrset_class) == dclass &&
222 			query_dname_compare(k->rk.dname, nm) == 0)
223 			return 1;
224 	}
225 	return 0;
226 }
227 
228 /** add rrset to answer section (no auth, add rrsets yet) */
229 static int
msg_add_rrset_an(struct auth_zone * z,struct regional * region,struct dns_msg * msg,struct auth_data * node,struct auth_rrset * rrset)230 msg_add_rrset_an(struct auth_zone* z, struct regional* region,
231 	struct dns_msg* msg, struct auth_data* node, struct auth_rrset* rrset)
232 {
233 	log_assert(msg->rep->ns_numrrsets == 0);
234 	log_assert(msg->rep->ar_numrrsets == 0);
235 	if(!rrset || !node)
236 		return 1;
237 	if(msg_rrset_duplicate(msg, node->name, node->namelen, rrset->type,
238 		z->dclass))
239 		return 1;
240 	/* grow array */
241 	if(!msg_grow_array(region, msg))
242 		return 0;
243 	/* copy it */
244 	if(!(msg->rep->rrsets[msg->rep->rrset_count] =
245 		auth_packed_rrset_copy_region(z, node, rrset, region)))
246 		return 0;
247 	msg->rep->rrset_count++;
248 	msg->rep->an_numrrsets++;
249 	msg_ttl(msg);
250 	return 1;
251 }
252 
253 /** add rrset to authority section (no additional section rrsets yet) */
254 static int
msg_add_rrset_ns(struct auth_zone * z,struct regional * region,struct dns_msg * msg,struct auth_data * node,struct auth_rrset * rrset)255 msg_add_rrset_ns(struct auth_zone* z, struct regional* region,
256 	struct dns_msg* msg, struct auth_data* node, struct auth_rrset* rrset)
257 {
258 	log_assert(msg->rep->ar_numrrsets == 0);
259 	if(!rrset || !node)
260 		return 1;
261 	if(msg_rrset_duplicate(msg, node->name, node->namelen, rrset->type,
262 		z->dclass))
263 		return 1;
264 	/* grow array */
265 	if(!msg_grow_array(region, msg))
266 		return 0;
267 	/* copy it */
268 	if(!(msg->rep->rrsets[msg->rep->rrset_count] =
269 		auth_packed_rrset_copy_region(z, node, rrset, region)))
270 		return 0;
271 	msg->rep->rrset_count++;
272 	msg->rep->ns_numrrsets++;
273 	msg_ttl(msg);
274 	return 1;
275 }
276 
277 /** add rrset to additional section */
278 static int
msg_add_rrset_ar(struct auth_zone * z,struct regional * region,struct dns_msg * msg,struct auth_data * node,struct auth_rrset * rrset)279 msg_add_rrset_ar(struct auth_zone* z, struct regional* region,
280 	struct dns_msg* msg, struct auth_data* node, struct auth_rrset* rrset)
281 {
282 	if(!rrset || !node)
283 		return 1;
284 	if(msg_rrset_duplicate(msg, node->name, node->namelen, rrset->type,
285 		z->dclass))
286 		return 1;
287 	/* grow array */
288 	if(!msg_grow_array(region, msg))
289 		return 0;
290 	/* copy it */
291 	if(!(msg->rep->rrsets[msg->rep->rrset_count] =
292 		auth_packed_rrset_copy_region(z, node, rrset, region)))
293 		return 0;
294 	msg->rep->rrset_count++;
295 	msg->rep->ar_numrrsets++;
296 	msg_ttl(msg);
297 	return 1;
298 }
299 
auth_zones_create(void)300 struct auth_zones* auth_zones_create(void)
301 {
302 	struct auth_zones* az = (struct auth_zones*)calloc(1, sizeof(*az));
303 	if(!az) {
304 		log_err("out of memory");
305 		return NULL;
306 	}
307 	rbtree_init(&az->ztree, &auth_zone_cmp);
308 	rbtree_init(&az->xtree, &auth_xfer_cmp);
309 	lock_rw_init(&az->lock);
310 	lock_protect(&az->lock, &az->ztree, sizeof(az->ztree));
311 	lock_protect(&az->lock, &az->xtree, sizeof(az->xtree));
312 	/* also lock protects the rbnode's in struct auth_zone, auth_xfer */
313 	lock_rw_init(&az->rpz_lock);
314 	lock_protect(&az->rpz_lock, &az->rpz_first, sizeof(az->rpz_first));
315 	return az;
316 }
317 
auth_zone_cmp(const void * z1,const void * z2)318 int auth_zone_cmp(const void* z1, const void* z2)
319 {
320 	/* first sort on class, so that hierarchy can be maintained within
321 	 * a class */
322 	struct auth_zone* a = (struct auth_zone*)z1;
323 	struct auth_zone* b = (struct auth_zone*)z2;
324 	int m;
325 	if(a->dclass != b->dclass) {
326 		if(a->dclass < b->dclass)
327 			return -1;
328 		return 1;
329 	}
330 	/* sorted such that higher zones sort before lower zones (their
331 	 * contents) */
332 	return dname_lab_cmp(a->name, a->namelabs, b->name, b->namelabs, &m);
333 }
334 
auth_data_cmp(const void * z1,const void * z2)335 int auth_data_cmp(const void* z1, const void* z2)
336 {
337 	struct auth_data* a = (struct auth_data*)z1;
338 	struct auth_data* b = (struct auth_data*)z2;
339 	int m;
340 	/* canonical sort, because DNSSEC needs that */
341 	return dname_canon_lab_cmp(a->name, a->namelabs, b->name,
342 		b->namelabs, &m);
343 }
344 
auth_xfer_cmp(const void * z1,const void * z2)345 int auth_xfer_cmp(const void* z1, const void* z2)
346 {
347 	/* first sort on class, so that hierarchy can be maintained within
348 	 * a class */
349 	struct auth_xfer* a = (struct auth_xfer*)z1;
350 	struct auth_xfer* b = (struct auth_xfer*)z2;
351 	int m;
352 	if(a->dclass != b->dclass) {
353 		if(a->dclass < b->dclass)
354 			return -1;
355 		return 1;
356 	}
357 	/* sorted such that higher zones sort before lower zones (their
358 	 * contents) */
359 	return dname_lab_cmp(a->name, a->namelabs, b->name, b->namelabs, &m);
360 }
361 
362 /** delete auth rrset node */
363 static void
auth_rrset_delete(struct auth_rrset * rrset)364 auth_rrset_delete(struct auth_rrset* rrset)
365 {
366 	if(!rrset) return;
367 	free(rrset->data);
368 	free(rrset);
369 }
370 
371 /** delete auth data domain node */
372 static void
auth_data_delete(struct auth_data * n)373 auth_data_delete(struct auth_data* n)
374 {
375 	struct auth_rrset* p, *np;
376 	if(!n) return;
377 	p = n->rrsets;
378 	while(p) {
379 		np = p->next;
380 		auth_rrset_delete(p);
381 		p = np;
382 	}
383 	free(n->name);
384 	free(n);
385 }
386 
387 /** helper traverse to delete zones */
388 static void
auth_data_del(rbnode_type * n,void * ATTR_UNUSED (arg))389 auth_data_del(rbnode_type* n, void* ATTR_UNUSED(arg))
390 {
391 	struct auth_data* z = (struct auth_data*)n->key;
392 	auth_data_delete(z);
393 }
394 
395 /** delete an auth zone structure (tree remove must be done elsewhere) */
396 static void
auth_zone_delete(struct auth_zone * z,struct auth_zones * az)397 auth_zone_delete(struct auth_zone* z, struct auth_zones* az)
398 {
399 	if(!z) return;
400 	lock_rw_destroy(&z->lock);
401 	traverse_postorder(&z->data, auth_data_del, NULL);
402 
403 	if(az && z->rpz) {
404 		/* keep RPZ linked list intact */
405 		lock_rw_wrlock(&az->rpz_lock);
406 		if(z->rpz_az_prev)
407 			z->rpz_az_prev->rpz_az_next = z->rpz_az_next;
408 		else
409 			az->rpz_first = z->rpz_az_next;
410 		if(z->rpz_az_next)
411 			z->rpz_az_next->rpz_az_prev = z->rpz_az_prev;
412 		lock_rw_unlock(&az->rpz_lock);
413 	}
414 	if(z->rpz)
415 		rpz_delete(z->rpz);
416 	free(z->name);
417 	free(z->zonefile);
418 	free(z);
419 }
420 
421 struct auth_zone*
auth_zone_create(struct auth_zones * az,uint8_t * nm,size_t nmlen,uint16_t dclass)422 auth_zone_create(struct auth_zones* az, uint8_t* nm, size_t nmlen,
423 	uint16_t dclass)
424 {
425 	struct auth_zone* z = (struct auth_zone*)calloc(1, sizeof(*z));
426 	if(!z) {
427 		return NULL;
428 	}
429 	z->node.key = z;
430 	z->dclass = dclass;
431 	z->namelen = nmlen;
432 	z->namelabs = dname_count_labels(nm);
433 	z->name = memdup(nm, nmlen);
434 	if(!z->name) {
435 		free(z);
436 		return NULL;
437 	}
438 	rbtree_init(&z->data, &auth_data_cmp);
439 	lock_rw_init(&z->lock);
440 	lock_protect(&z->lock, &z->name, sizeof(*z)-sizeof(rbnode_type)-
441 			sizeof(z->rpz_az_next)-sizeof(z->rpz_az_prev)-
442 			sizeof(z->max_transfer_size)-sizeof(z->max_transfer_size));
443 	lock_protect(&z->lock, &z->max_transfer_size,
444 		sizeof(z->max_transfer_size));
445 	lock_protect(&z->lock, &z->max_transfer_time,
446 		sizeof(z->max_transfer_time));
447 	lock_rw_wrlock(&z->lock);
448 	/* z lock protects all, except rbtree itself and the rpz linked list
449 	 * pointers, which are protected using az->lock */
450 	if(!rbtree_insert(&az->ztree, &z->node)) {
451 		lock_rw_unlock(&z->lock);
452 		auth_zone_delete(z, NULL);
453 		log_warn("duplicate auth zone");
454 		return NULL;
455 	}
456 	return z;
457 }
458 
459 struct auth_zone*
auth_zone_find(struct auth_zones * az,uint8_t * nm,size_t nmlen,uint16_t dclass)460 auth_zone_find(struct auth_zones* az, uint8_t* nm, size_t nmlen,
461 	uint16_t dclass)
462 {
463 	struct auth_zone key;
464 	key.node.key = &key;
465 	key.dclass = dclass;
466 	key.name = nm;
467 	key.namelen = nmlen;
468 	key.namelabs = dname_count_labels(nm);
469 	return (struct auth_zone*)rbtree_search(&az->ztree, &key);
470 }
471 
472 struct auth_xfer*
auth_xfer_find(struct auth_zones * az,uint8_t * nm,size_t nmlen,uint16_t dclass)473 auth_xfer_find(struct auth_zones* az, uint8_t* nm, size_t nmlen,
474 	uint16_t dclass)
475 {
476 	struct auth_xfer key;
477 	key.node.key = &key;
478 	key.dclass = dclass;
479 	key.name = nm;
480 	key.namelen = nmlen;
481 	key.namelabs = dname_count_labels(nm);
482 	return (struct auth_xfer*)rbtree_search(&az->xtree, &key);
483 }
484 
485 /** find an auth zone or sorted less-or-equal, return true if exact */
486 static int
auth_zone_find_less_equal(struct auth_zones * az,uint8_t * nm,size_t nmlen,uint16_t dclass,struct auth_zone ** z)487 auth_zone_find_less_equal(struct auth_zones* az, uint8_t* nm, size_t nmlen,
488 	uint16_t dclass, struct auth_zone** z)
489 {
490 	struct auth_zone key;
491 	key.node.key = &key;
492 	key.dclass = dclass;
493 	key.name = nm;
494 	key.namelen = nmlen;
495 	key.namelabs = dname_count_labels(nm);
496 	return rbtree_find_less_equal(&az->ztree, &key, (rbnode_type**)z);
497 }
498 
499 
500 /** find the auth zone that is above the given name */
501 struct auth_zone*
auth_zones_find_zone(struct auth_zones * az,uint8_t * name,size_t name_len,uint16_t dclass)502 auth_zones_find_zone(struct auth_zones* az, uint8_t* name, size_t name_len,
503 	uint16_t dclass)
504 {
505 	uint8_t* nm = name;
506 	size_t nmlen = name_len;
507 	struct auth_zone* z;
508 	if(auth_zone_find_less_equal(az, nm, nmlen, dclass, &z)) {
509 		/* exact match */
510 		return z;
511 	} else {
512 		/* less-or-nothing */
513 		if(!z) return NULL; /* nothing smaller, nothing above it */
514 		/* we found smaller name; smaller may be above the name,
515 		 * but not below it. */
516 		nm = dname_get_shared_topdomain(z->name, name);
517 		dname_count_size_labels(nm, &nmlen);
518 		z = NULL;
519 	}
520 
521 	/* search up */
522 	while(!z) {
523 		z = auth_zone_find(az, nm, nmlen, dclass);
524 		if(z) return z;
525 		if(dname_is_root(nm)) break;
526 		dname_remove_label(&nm, &nmlen);
527 	}
528 	return NULL;
529 }
530 
531 /** find or create zone with name str. caller must have lock on az.
532  * returns a wrlocked zone */
533 static struct auth_zone*
auth_zones_find_or_add_zone(struct auth_zones * az,char * name)534 auth_zones_find_or_add_zone(struct auth_zones* az, char* name)
535 {
536 	uint8_t nm[LDNS_MAX_DOMAINLEN+1];
537 	size_t nmlen = sizeof(nm);
538 	struct auth_zone* z;
539 
540 	if(sldns_str2wire_dname_buf(name, nm, &nmlen) != 0) {
541 		log_err("cannot parse auth zone name: %s", name);
542 		return 0;
543 	}
544 	z = auth_zone_find(az, nm, nmlen, LDNS_RR_CLASS_IN);
545 	if(!z) {
546 		/* not found, create the zone */
547 		z = auth_zone_create(az, nm, nmlen, LDNS_RR_CLASS_IN);
548 	} else {
549 		lock_rw_wrlock(&z->lock);
550 	}
551 	return z;
552 }
553 
554 /** find or create xfer zone with name str. caller must have lock on az.
555  * returns a locked xfer */
556 static struct auth_xfer*
auth_zones_find_or_add_xfer(struct auth_zones * az,struct auth_zone * z)557 auth_zones_find_or_add_xfer(struct auth_zones* az, struct auth_zone* z)
558 {
559 	struct auth_xfer* x;
560 	x = auth_xfer_find(az, z->name, z->namelen, z->dclass);
561 	if(!x) {
562 		/* not found, create the zone */
563 		x = auth_xfer_create(az, z);
564 	} else {
565 		lock_basic_lock(&x->lock);
566 	}
567 	return x;
568 }
569 
570 int
auth_zone_set_zonefile(struct auth_zone * z,char * zonefile)571 auth_zone_set_zonefile(struct auth_zone* z, char* zonefile)
572 {
573 	if(z->zonefile) free(z->zonefile);
574 	if(zonefile == NULL) {
575 		z->zonefile = NULL;
576 	} else {
577 		z->zonefile = strdup(zonefile);
578 		if(!z->zonefile) {
579 			log_err("malloc failure");
580 			return 0;
581 		}
582 	}
583 	return 1;
584 }
585 
586 /** set auth zone fallback. caller must have lock on zone */
587 int
auth_zone_set_fallback(struct auth_zone * z,char * fallbackstr)588 auth_zone_set_fallback(struct auth_zone* z, char* fallbackstr)
589 {
590 	if(strcmp(fallbackstr, "yes") != 0 && strcmp(fallbackstr, "no") != 0){
591 		log_err("auth zone fallback, expected yes or no, got %s",
592 			fallbackstr);
593 		return 0;
594 	}
595 	z->fallback_enabled = (strcmp(fallbackstr, "yes")==0);
596 	return 1;
597 }
598 
599 /** create domain with the given name */
600 static struct auth_data*
az_domain_create(struct auth_zone * z,uint8_t * nm,size_t nmlen)601 az_domain_create(struct auth_zone* z, uint8_t* nm, size_t nmlen)
602 {
603 	struct auth_data* n = (struct auth_data*)malloc(sizeof(*n));
604 	if(!n) return NULL;
605 	memset(n, 0, sizeof(*n));
606 	n->node.key = n;
607 	n->name = memdup(nm, nmlen);
608 	if(!n->name) {
609 		free(n);
610 		return NULL;
611 	}
612 	n->namelen = nmlen;
613 	n->namelabs = dname_count_labels(nm);
614 	if(!rbtree_insert(&z->data, &n->node)) {
615 		log_warn("duplicate auth domain name");
616 		free(n->name);
617 		free(n);
618 		return NULL;
619 	}
620 	return n;
621 }
622 
623 /** find domain with exactly the given name */
624 static struct auth_data*
az_find_name(struct auth_zone * z,uint8_t * nm,size_t nmlen)625 az_find_name(struct auth_zone* z, uint8_t* nm, size_t nmlen)
626 {
627 	struct auth_zone key;
628 	key.node.key = &key;
629 	key.name = nm;
630 	key.namelen = nmlen;
631 	key.namelabs = dname_count_labels(nm);
632 	return (struct auth_data*)rbtree_search(&z->data, &key);
633 }
634 
635 /** Find domain name (or closest match) */
636 static void
az_find_domain(struct auth_zone * z,struct query_info * qinfo,int * node_exact,struct auth_data ** node)637 az_find_domain(struct auth_zone* z, struct query_info* qinfo, int* node_exact,
638 	struct auth_data** node)
639 {
640 	struct auth_zone key;
641 	key.node.key = &key;
642 	key.name = qinfo->qname;
643 	key.namelen = qinfo->qname_len;
644 	key.namelabs = dname_count_labels(key.name);
645 	*node_exact = rbtree_find_less_equal(&z->data, &key,
646 		(rbnode_type**)node);
647 }
648 
649 /** find or create domain with name in zone */
650 static struct auth_data*
az_domain_find_or_create(struct auth_zone * z,uint8_t * dname,size_t dname_len)651 az_domain_find_or_create(struct auth_zone* z, uint8_t* dname,
652 	size_t dname_len)
653 {
654 	struct auth_data* n = az_find_name(z, dname, dname_len);
655 	if(!n) {
656 		n = az_domain_create(z, dname, dname_len);
657 	}
658 	return n;
659 }
660 
661 /** find rrset of given type in the domain */
662 static struct auth_rrset*
az_domain_rrset(struct auth_data * n,uint16_t t)663 az_domain_rrset(struct auth_data* n, uint16_t t)
664 {
665 	struct auth_rrset* rrset;
666 	if(!n) return NULL;
667 	rrset = n->rrsets;
668 	while(rrset) {
669 		if(rrset->type == t)
670 			return rrset;
671 		rrset = rrset->next;
672 	}
673 	return NULL;
674 }
675 
676 /** remove rrset of this type from domain */
677 static void
domain_remove_rrset(struct auth_data * node,uint16_t rr_type)678 domain_remove_rrset(struct auth_data* node, uint16_t rr_type)
679 {
680 	struct auth_rrset* rrset, *prev;
681 	if(!node) return;
682 	prev = NULL;
683 	rrset = node->rrsets;
684 	while(rrset) {
685 		if(rrset->type == rr_type) {
686 			/* found it, now delete it */
687 			if(prev) prev->next = rrset->next;
688 			else	node->rrsets = rrset->next;
689 			auth_rrset_delete(rrset);
690 			return;
691 		}
692 		prev = rrset;
693 		rrset = rrset->next;
694 	}
695 }
696 
697 /** find an rrsig index in the rrset.  returns true if found */
698 static int
az_rrset_find_rrsig(struct packed_rrset_data * d,uint8_t * rdata,size_t len,size_t * index)699 az_rrset_find_rrsig(struct packed_rrset_data* d, uint8_t* rdata, size_t len,
700 	size_t* index)
701 {
702 	size_t i;
703 	for(i=d->count; i<d->count + d->rrsig_count; i++) {
704 		if(d->rr_len[i] != len)
705 			continue;
706 		if(memcmp(d->rr_data[i], rdata, len) == 0) {
707 			*index = i;
708 			return 1;
709 		}
710 	}
711 	return 0;
712 }
713 
714 /** see if rdata is duplicate */
715 static int
rdata_duplicate(struct packed_rrset_data * d,uint8_t * rdata,size_t len)716 rdata_duplicate(struct packed_rrset_data* d, uint8_t* rdata, size_t len)
717 {
718 	size_t i;
719 	for(i=0; i<d->count + d->rrsig_count; i++) {
720 		if(d->rr_len[i] != len)
721 			continue;
722 		if(memcmp(d->rr_data[i], rdata, len) == 0)
723 			return 1;
724 	}
725 	return 0;
726 }
727 
728 /** get rrsig type covered from rdata.
729  * @param rdata: rdata in wireformat, starting with 16bit rdlength.
730  * @param rdatalen: length of rdata buffer.
731  * @return type covered (or 0).
732  */
733 static uint16_t
rrsig_rdata_get_type_covered(uint8_t * rdata,size_t rdatalen)734 rrsig_rdata_get_type_covered(uint8_t* rdata, size_t rdatalen)
735 {
736 	if(rdatalen < 4)
737 		return 0;
738 	return sldns_read_uint16(rdata+2);
739 }
740 
741 /** remove RR from existing RRset. Also sig, if it is a signature.
742  * reallocates the packed rrset for a new one, false on alloc failure */
743 static int
rrset_remove_rr(struct auth_rrset * rrset,size_t index)744 rrset_remove_rr(struct auth_rrset* rrset, size_t index)
745 {
746 	struct packed_rrset_data* d, *old = rrset->data;
747 	size_t i;
748 	if(index >= old->count + old->rrsig_count)
749 		return 0; /* index out of bounds */
750 	d = (struct packed_rrset_data*)calloc(1, packed_rrset_sizeof(old) - (
751 		sizeof(size_t) + sizeof(uint8_t*) + sizeof(time_t) +
752 		old->rr_len[index]));
753 	if(!d) {
754 		log_err("malloc failure");
755 		return 0;
756 	}
757 	d->ttl = old->ttl;
758 	d->count = old->count;
759 	d->rrsig_count = old->rrsig_count;
760 	if(index < d->count) d->count--;
761 	else d->rrsig_count--;
762 	d->trust = old->trust;
763 	d->security = old->security;
764 
765 	/* set rr_len, needed for ptr_fixup */
766 	d->rr_len = (size_t*)((uint8_t*)d +
767 		sizeof(struct packed_rrset_data));
768 	if(index > 0)
769 		memmove(d->rr_len, old->rr_len, (index)*sizeof(size_t));
770 	if(index+1 < old->count+old->rrsig_count)
771 		memmove(&d->rr_len[index], &old->rr_len[index+1],
772 		(old->count+old->rrsig_count - (index+1))*sizeof(size_t));
773 	packed_rrset_ptr_fixup(d);
774 
775 	/* move over ttls */
776 	if(index > 0)
777 		memmove(d->rr_ttl, old->rr_ttl, (index)*sizeof(time_t));
778 	if(index+1 < old->count+old->rrsig_count)
779 		memmove(&d->rr_ttl[index], &old->rr_ttl[index+1],
780 		(old->count+old->rrsig_count - (index+1))*sizeof(time_t));
781 
782 	/* move over rr_data */
783 	for(i=0; i<d->count+d->rrsig_count; i++) {
784 		size_t oldi;
785 		if(i < index) oldi = i;
786 		else oldi = i+1;
787 		memmove(d->rr_data[i], old->rr_data[oldi], d->rr_len[i]);
788 	}
789 
790 	/* recalc ttl (lowest of remaining RR ttls) */
791 	if(d->count + d->rrsig_count > 0)
792 		d->ttl = d->rr_ttl[0];
793 	for(i=0; i<d->count+d->rrsig_count; i++) {
794 		if(d->rr_ttl[i] < d->ttl)
795 			d->ttl = d->rr_ttl[i];
796 	}
797 
798 	free(rrset->data);
799 	rrset->data = d;
800 	return 1;
801 }
802 
803 /** add RR to existing RRset. If insert_sig is true, add to rrsigs.
804  * This reallocates the packed rrset for a new one */
805 static int
rrset_add_rr(struct auth_rrset * rrset,uint32_t rr_ttl,uint8_t * rdata,size_t rdatalen,int insert_sig)806 rrset_add_rr(struct auth_rrset* rrset, uint32_t rr_ttl, uint8_t* rdata,
807 	size_t rdatalen, int insert_sig)
808 {
809 	struct packed_rrset_data* d, *old = rrset->data;
810 	size_t total, old_total;
811 
812 	d = (struct packed_rrset_data*)calloc(1, packed_rrset_sizeof(old)
813 		+ sizeof(size_t) + sizeof(uint8_t*) + sizeof(time_t)
814 		+ rdatalen);
815 	if(!d) {
816 		log_err("out of memory");
817 		return 0;
818 	}
819 	/* copy base values */
820 	memcpy(d, old, sizeof(struct packed_rrset_data));
821 	if(!insert_sig) {
822 		d->count++;
823 	} else {
824 		d->rrsig_count++;
825 	}
826 	old_total = old->count + old->rrsig_count;
827 	total = d->count + d->rrsig_count;
828 	/* set rr_len, needed for ptr_fixup */
829 	d->rr_len = (size_t*)((uint8_t*)d +
830 		sizeof(struct packed_rrset_data));
831 	if(old->count != 0)
832 		memmove(d->rr_len, old->rr_len, old->count*sizeof(size_t));
833 	if(old->rrsig_count != 0)
834 		memmove(d->rr_len+d->count, old->rr_len+old->count,
835 			old->rrsig_count*sizeof(size_t));
836 	if(!insert_sig)
837 		d->rr_len[d->count-1] = rdatalen;
838 	else	d->rr_len[total-1] = rdatalen;
839 	packed_rrset_ptr_fixup(d);
840 	if((time_t)rr_ttl < d->ttl)
841 		d->ttl = rr_ttl;
842 
843 	/* copy old values into new array */
844 	if(old->count != 0) {
845 		memmove(d->rr_ttl, old->rr_ttl, old->count*sizeof(time_t));
846 		/* all the old rr pieces are allocated sequential, so we
847 		 * can copy them in one go */
848 		memmove(d->rr_data[0], old->rr_data[0],
849 			(old->rr_data[old->count-1] - old->rr_data[0]) +
850 			old->rr_len[old->count-1]);
851 	}
852 	if(old->rrsig_count != 0) {
853 		memmove(d->rr_ttl+d->count, old->rr_ttl+old->count,
854 			old->rrsig_count*sizeof(time_t));
855 		memmove(d->rr_data[d->count], old->rr_data[old->count],
856 			(old->rr_data[old_total-1] - old->rr_data[old->count]) +
857 			old->rr_len[old_total-1]);
858 	}
859 
860 	/* insert new value */
861 	if(!insert_sig) {
862 		d->rr_ttl[d->count-1] = rr_ttl;
863 		memmove(d->rr_data[d->count-1], rdata, rdatalen);
864 	} else {
865 		d->rr_ttl[total-1] = rr_ttl;
866 		memmove(d->rr_data[total-1], rdata, rdatalen);
867 	}
868 
869 	rrset->data = d;
870 	free(old);
871 	return 1;
872 }
873 
874 /** Create new rrset for node with packed rrset with one RR element */
875 static struct auth_rrset*
rrset_create(struct auth_data * node,uint16_t rr_type,uint32_t rr_ttl,uint8_t * rdata,size_t rdatalen)876 rrset_create(struct auth_data* node, uint16_t rr_type, uint32_t rr_ttl,
877 	uint8_t* rdata, size_t rdatalen)
878 {
879 	struct auth_rrset* rrset = (struct auth_rrset*)calloc(1,
880 		sizeof(*rrset));
881 	struct auth_rrset* p, *prev;
882 	struct packed_rrset_data* d;
883 	if(!rrset) {
884 		log_err("out of memory");
885 		return NULL;
886 	}
887 	rrset->type = rr_type;
888 
889 	/* the rrset data structure, with one RR */
890 	d = (struct packed_rrset_data*)calloc(1,
891 		sizeof(struct packed_rrset_data) + sizeof(size_t) +
892 		sizeof(uint8_t*) + sizeof(time_t) + rdatalen);
893 	if(!d) {
894 		free(rrset);
895 		log_err("out of memory");
896 		return NULL;
897 	}
898 	rrset->data = d;
899 	d->ttl = rr_ttl;
900 	d->trust = rrset_trust_prim_noglue;
901 	d->rr_len = (size_t*)((uint8_t*)d + sizeof(struct packed_rrset_data));
902 	d->rr_data = (uint8_t**)&(d->rr_len[1]);
903 	d->rr_ttl = (time_t*)&(d->rr_data[1]);
904 	d->rr_data[0] = (uint8_t*)&(d->rr_ttl[1]);
905 
906 	/* insert the RR */
907 	d->rr_len[0] = rdatalen;
908 	d->rr_ttl[0] = rr_ttl;
909 	memmove(d->rr_data[0], rdata, rdatalen);
910 	d->count++;
911 
912 	/* insert rrset into linked list for domain */
913 	/* find sorted place to link the rrset into the list */
914 	prev = NULL;
915 	p = node->rrsets;
916 	while(p && p->type<=rr_type) {
917 		prev = p;
918 		p = p->next;
919 	}
920 	/* so, prev is smaller, and p is larger than rr_type */
921 	rrset->next = p;
922 	if(prev) prev->next = rrset;
923 	else node->rrsets = rrset;
924 	return rrset;
925 }
926 
927 /** count number (and size) of rrsigs that cover a type */
928 static size_t
rrsig_num_that_cover(struct auth_rrset * rrsig,uint16_t rr_type,size_t * sigsz)929 rrsig_num_that_cover(struct auth_rrset* rrsig, uint16_t rr_type, size_t* sigsz)
930 {
931 	struct packed_rrset_data* d = rrsig->data;
932 	size_t i, num = 0;
933 	*sigsz = 0;
934 	log_assert(d && rrsig->type == LDNS_RR_TYPE_RRSIG);
935 	for(i=0; i<d->count+d->rrsig_count; i++) {
936 		if(rrsig_rdata_get_type_covered(d->rr_data[i],
937 			d->rr_len[i]) == rr_type) {
938 			num++;
939 			(*sigsz) += d->rr_len[i];
940 		}
941 	}
942 	return num;
943 }
944 
945 /** See if rrsig set has covered sigs for rrset and move them over */
946 static int
rrset_moveover_rrsigs(struct auth_data * node,uint16_t rr_type,struct auth_rrset * rrset,struct auth_rrset * rrsig)947 rrset_moveover_rrsigs(struct auth_data* node, uint16_t rr_type,
948 	struct auth_rrset* rrset, struct auth_rrset* rrsig)
949 {
950 	size_t sigs, sigsz, i, j, total;
951 	struct packed_rrset_data* sigold = rrsig->data;
952 	struct packed_rrset_data* old = rrset->data;
953 	struct packed_rrset_data* d, *sigd;
954 
955 	log_assert(rrset->type == rr_type);
956 	log_assert(rrsig->type == LDNS_RR_TYPE_RRSIG);
957 	sigs = rrsig_num_that_cover(rrsig, rr_type, &sigsz);
958 	if(sigs == 0) {
959 		/* 0 rrsigs to move over, done */
960 		return 1;
961 	}
962 
963 	/* allocate rrset sigsz larger for extra sigs elements, and
964 	 * allocate rrsig sigsz smaller for less sigs elements. */
965 	d = (struct packed_rrset_data*)calloc(1, packed_rrset_sizeof(old)
966 		+ sigs*(sizeof(size_t) + sizeof(uint8_t*) + sizeof(time_t))
967 		+ sigsz);
968 	if(!d) {
969 		log_err("out of memory");
970 		return 0;
971 	}
972 	/* copy base values */
973 	total = old->count + old->rrsig_count;
974 	memcpy(d, old, sizeof(struct packed_rrset_data));
975 	d->rrsig_count += sigs;
976 	/* setup rr_len */
977 	d->rr_len = (size_t*)((uint8_t*)d +
978 		sizeof(struct packed_rrset_data));
979 	if(total != 0)
980 		memmove(d->rr_len, old->rr_len, total*sizeof(size_t));
981 	j = d->count+d->rrsig_count-sigs;
982 	for(i=0; i<sigold->count+sigold->rrsig_count; i++) {
983 		if(rrsig_rdata_get_type_covered(sigold->rr_data[i],
984 			sigold->rr_len[i]) == rr_type) {
985 			d->rr_len[j] = sigold->rr_len[i];
986 			j++;
987 		}
988 	}
989 	packed_rrset_ptr_fixup(d);
990 
991 	/* copy old values into new array */
992 	if(total != 0) {
993 		memmove(d->rr_ttl, old->rr_ttl, total*sizeof(time_t));
994 		/* all the old rr pieces are allocated sequential, so we
995 		 * can copy them in one go */
996 		memmove(d->rr_data[0], old->rr_data[0],
997 			(old->rr_data[total-1] - old->rr_data[0]) +
998 			old->rr_len[total-1]);
999 	}
1000 
1001 	/* move over the rrsigs to the larger rrset*/
1002 	j = d->count+d->rrsig_count-sigs;
1003 	for(i=0; i<sigold->count+sigold->rrsig_count; i++) {
1004 		if(rrsig_rdata_get_type_covered(sigold->rr_data[i],
1005 			sigold->rr_len[i]) == rr_type) {
1006 			/* move this one over to location j */
1007 			d->rr_ttl[j] = sigold->rr_ttl[i];
1008 			memmove(d->rr_data[j], sigold->rr_data[i],
1009 				sigold->rr_len[i]);
1010 			if(d->rr_ttl[j] < d->ttl)
1011 				d->ttl = d->rr_ttl[j];
1012 			j++;
1013 		}
1014 	}
1015 
1016 	/* put it in and deallocate the old rrset */
1017 	rrset->data = d;
1018 	free(old);
1019 
1020 	/* now make rrsig set smaller */
1021 	if(sigold->count+sigold->rrsig_count == sigs) {
1022 		/* remove all sigs from rrsig, remove it entirely */
1023 		domain_remove_rrset(node, LDNS_RR_TYPE_RRSIG);
1024 		return 1;
1025 	}
1026 	log_assert(packed_rrset_sizeof(sigold) > sigs*(sizeof(size_t) +
1027 		sizeof(uint8_t*) + sizeof(time_t)) + sigsz);
1028 	sigd = (struct packed_rrset_data*)calloc(1, packed_rrset_sizeof(sigold)
1029 		- sigs*(sizeof(size_t) + sizeof(uint8_t*) + sizeof(time_t))
1030 		- sigsz);
1031 	if(!sigd) {
1032 		/* no need to free up d, it has already been placed in the
1033 		 * node->rrset structure */
1034 		log_err("out of memory");
1035 		return 0;
1036 	}
1037 	/* copy base values */
1038 	memcpy(sigd, sigold, sizeof(struct packed_rrset_data));
1039 	/* in sigd the RRSIGs are stored in the base of the RR, in count */
1040 	sigd->count -= sigs;
1041 	/* setup rr_len */
1042 	sigd->rr_len = (size_t*)((uint8_t*)sigd +
1043 		sizeof(struct packed_rrset_data));
1044 	j = 0;
1045 	for(i=0; i<sigold->count+sigold->rrsig_count; i++) {
1046 		if(rrsig_rdata_get_type_covered(sigold->rr_data[i],
1047 			sigold->rr_len[i]) != rr_type) {
1048 			sigd->rr_len[j] = sigold->rr_len[i];
1049 			j++;
1050 		}
1051 	}
1052 	packed_rrset_ptr_fixup(sigd);
1053 
1054 	/* copy old values into new rrsig array */
1055 	j = 0;
1056 	for(i=0; i<sigold->count+sigold->rrsig_count; i++) {
1057 		if(rrsig_rdata_get_type_covered(sigold->rr_data[i],
1058 			sigold->rr_len[i]) != rr_type) {
1059 			/* move this one over to location j */
1060 			sigd->rr_ttl[j] = sigold->rr_ttl[i];
1061 			memmove(sigd->rr_data[j], sigold->rr_data[i],
1062 				sigold->rr_len[i]);
1063 			if(j==0) sigd->ttl = sigd->rr_ttl[j];
1064 			else {
1065 				if(sigd->rr_ttl[j] < sigd->ttl)
1066 					sigd->ttl = sigd->rr_ttl[j];
1067 			}
1068 			j++;
1069 		}
1070 	}
1071 
1072 	/* put it in and deallocate the old rrset */
1073 	rrsig->data = sigd;
1074 	free(sigold);
1075 
1076 	return 1;
1077 }
1078 
1079 /** copy the rrsigs from the rrset to the rrsig rrset, because the rrset
1080  * is going to be deleted.  reallocates the RRSIG rrset data. */
1081 static int
rrsigs_copy_from_rrset_to_rrsigset(struct auth_rrset * rrset,struct auth_rrset * rrsigset)1082 rrsigs_copy_from_rrset_to_rrsigset(struct auth_rrset* rrset,
1083 	struct auth_rrset* rrsigset)
1084 {
1085 	size_t i;
1086 	if(rrset->data->rrsig_count == 0)
1087 		return 1;
1088 
1089 	/* move them over one by one, because there might be duplicates,
1090 	 * duplicates are ignored */
1091 	for(i=rrset->data->count;
1092 		i<rrset->data->count+rrset->data->rrsig_count; i++) {
1093 		uint8_t* rdata = rrset->data->rr_data[i];
1094 		size_t rdatalen = rrset->data->rr_len[i];
1095 		time_t rr_ttl  = rrset->data->rr_ttl[i];
1096 
1097 		if(rdata_duplicate(rrsigset->data, rdata, rdatalen)) {
1098 			continue;
1099 		}
1100 		if(!rrset_add_rr(rrsigset, rr_ttl, rdata, rdatalen, 0))
1101 			return 0;
1102 	}
1103 	return 1;
1104 }
1105 
1106 /** Add rr to node, ignores duplicate RRs,
1107  * rdata points to buffer with rdatalen octets, starts with 2bytelength. */
1108 static int
az_domain_add_rr(struct auth_data * node,uint16_t rr_type,uint32_t rr_ttl,uint8_t * rdata,size_t rdatalen,int * duplicate)1109 az_domain_add_rr(struct auth_data* node, uint16_t rr_type, uint32_t rr_ttl,
1110 	uint8_t* rdata, size_t rdatalen, int* duplicate)
1111 {
1112 	struct auth_rrset* rrset;
1113 	/* packed rrsets have their rrsigs along with them, sort them out */
1114 	if(rr_type == LDNS_RR_TYPE_RRSIG) {
1115 		uint16_t ctype = rrsig_rdata_get_type_covered(rdata, rdatalen);
1116 		if((rrset=az_domain_rrset(node, ctype))!= NULL) {
1117 			/* a node of the correct type exists, add the RRSIG
1118 			 * to the rrset of the covered data type */
1119 			if(rdata_duplicate(rrset->data, rdata, rdatalen)) {
1120 				if(duplicate) *duplicate = 1;
1121 				return 1;
1122 			}
1123 			if(!rrset_add_rr(rrset, rr_ttl, rdata, rdatalen, 1))
1124 				return 0;
1125 		} else if((rrset=az_domain_rrset(node, rr_type))!= NULL) {
1126 			/* add RRSIG to rrset of type RRSIG */
1127 			if(rdata_duplicate(rrset->data, rdata, rdatalen)) {
1128 				if(duplicate) *duplicate = 1;
1129 				return 1;
1130 			}
1131 			if(!rrset_add_rr(rrset, rr_ttl, rdata, rdatalen, 0))
1132 				return 0;
1133 		} else {
1134 			/* create rrset of type RRSIG */
1135 			if(!rrset_create(node, rr_type, rr_ttl, rdata,
1136 				rdatalen))
1137 				return 0;
1138 		}
1139 	} else {
1140 		/* normal RR type */
1141 		if((rrset=az_domain_rrset(node, rr_type))!= NULL) {
1142 			/* add data to existing node with data type */
1143 			if(rdata_duplicate(rrset->data, rdata, rdatalen)) {
1144 				if(duplicate) *duplicate = 1;
1145 				return 1;
1146 			}
1147 			if(!rrset_add_rr(rrset, rr_ttl, rdata, rdatalen, 0))
1148 				return 0;
1149 		} else {
1150 			struct auth_rrset* rrsig;
1151 			/* create new node with data type */
1152 			if(!(rrset=rrset_create(node, rr_type, rr_ttl, rdata,
1153 				rdatalen)))
1154 				return 0;
1155 
1156 			/* see if node of type RRSIG has signatures that
1157 			 * cover the data type, and move them over */
1158 			/* and then make the RRSIG type smaller */
1159 			if((rrsig=az_domain_rrset(node, LDNS_RR_TYPE_RRSIG))
1160 				!= NULL) {
1161 				if(!rrset_moveover_rrsigs(node, rr_type,
1162 					rrset, rrsig))
1163 					return 0;
1164 			}
1165 		}
1166 	}
1167 	return 1;
1168 }
1169 
1170 /** insert RR into zone, ignore duplicates */
1171 static int
az_insert_rr(struct auth_zone * z,uint8_t * rr,size_t rr_len,size_t dname_len,int * duplicate)1172 az_insert_rr(struct auth_zone* z, uint8_t* rr, size_t rr_len,
1173 	size_t dname_len, int* duplicate)
1174 {
1175 	struct auth_data* node;
1176 	uint8_t* dname = rr;
1177 	uint16_t rr_type = sldns_wirerr_get_type(rr, rr_len, dname_len);
1178 	uint16_t rr_class = sldns_wirerr_get_class(rr, rr_len, dname_len);
1179 	uint32_t rr_ttl = sldns_wirerr_get_ttl(rr, rr_len, dname_len);
1180 	size_t rdatalen = ((size_t)sldns_wirerr_get_rdatalen(rr, rr_len,
1181 		dname_len))+2;
1182 	/* rdata points to rdata prefixed with uint16 rdatalength */
1183 	uint8_t* rdata = sldns_wirerr_get_rdatawl(rr, rr_len, dname_len);
1184 
1185 	if(rr_class != z->dclass) {
1186 		log_err("wrong class for RR");
1187 		return 0;
1188 	}
1189 	if(rr_type == LDNS_RR_TYPE_A && rdatalen != 6 /* 2 + 4 */) {
1190 		log_err("malformed A record");
1191 		return 0;
1192 	} else if(rr_type == LDNS_RR_TYPE_AAAA && rdatalen != 18 /* 2 + 16 */) {
1193 		log_err("malformed AAAA record");
1194 		return 0;
1195 	}
1196 	if(!dname_subdomain_c(dname, z->name)) {
1197 		char nm[LDNS_MAX_DOMAINLEN], zn[LDNS_MAX_DOMAINLEN];
1198 		dname_str(dname, nm);
1199 		dname_str(z->name, zn);
1200 		verbose(VERB_ALGO, "auth-zone %s: dropping out-of-zone RR "
1201 			"%s", zn, nm);
1202 		if(duplicate) *duplicate=1; /* treat as bad insert */
1203 		return 1;
1204 	}
1205 	if(!(node=az_domain_find_or_create(z, dname, dname_len))) {
1206 		log_err("cannot create domain");
1207 		return 0;
1208 	}
1209 	if(!az_domain_add_rr(node, rr_type, rr_ttl, rdata, rdatalen,
1210 		duplicate)) {
1211 		log_err("cannot add RR to domain");
1212 		if(node->rrsets == NULL) {
1213 			(void)rbtree_delete(&z->data, node);
1214 			auth_data_delete(node);
1215 		}
1216 		return 0;
1217 	}
1218 	if(z->rpz) {
1219 		if(!(rpz_insert_rr(z->rpz, z->name, z->namelen, dname,
1220 			dname_len, rr_type, rr_class, rr_ttl, rdata, rdatalen,
1221 			rr, rr_len)))
1222 			return 0;
1223 	}
1224 	return 1;
1225 }
1226 
1227 /** Remove rr from node, ignores nonexisting RRs,
1228  * rdata points to buffer with rdatalen octets, starts with 2bytelength. */
1229 static int
az_domain_remove_rr(struct auth_data * node,uint16_t rr_type,uint8_t * rdata,size_t rdatalen,int * nonexist)1230 az_domain_remove_rr(struct auth_data* node, uint16_t rr_type,
1231 	uint8_t* rdata, size_t rdatalen, int* nonexist)
1232 {
1233 	struct auth_rrset* rrset;
1234 	size_t index = 0;
1235 
1236 	/* find the plain RR of the given type */
1237 	if((rrset=az_domain_rrset(node, rr_type))!= NULL) {
1238 		if(packed_rrset_find_rr(rrset->data, rdata, rdatalen, &index)) {
1239 			if(rrset->data->count == 1 &&
1240 				rrset->data->rrsig_count == 0) {
1241 				/* last RR, delete the rrset */
1242 				domain_remove_rrset(node, rr_type);
1243 			} else if(rrset->data->count == 1 &&
1244 				rrset->data->rrsig_count != 0) {
1245 				/* move RRSIGs to the RRSIG rrset, or
1246 				 * this one becomes that RRset */
1247 				struct auth_rrset* rrsigset = az_domain_rrset(
1248 					node, LDNS_RR_TYPE_RRSIG);
1249 				if(rrsigset) {
1250 					/* move left over rrsigs to the
1251 					 * existing rrset of type RRSIG */
1252 					rrsigs_copy_from_rrset_to_rrsigset(
1253 						rrset, rrsigset);
1254 					/* and then delete the rrset */
1255 					domain_remove_rrset(node, rr_type);
1256 				} else {
1257 					/* no rrset of type RRSIG, this
1258 					 * set is now of that type,
1259 					 * just remove the rr */
1260 					if(!rrset_remove_rr(rrset, index))
1261 						return 0;
1262 					rrset->type = LDNS_RR_TYPE_RRSIG;
1263 					rrset->data->count = rrset->data->rrsig_count;
1264 					rrset->data->rrsig_count = 0;
1265 				}
1266 			} else {
1267 				/* remove the RR from the rrset */
1268 				if(!rrset_remove_rr(rrset, index))
1269 					return 0;
1270 			}
1271 			return 1;
1272 		}
1273 		/* rr not found in rrset */
1274 	}
1275 
1276 	/* is it a type RRSIG, look under the covered type */
1277 	if(rr_type == LDNS_RR_TYPE_RRSIG) {
1278 		uint16_t ctype = rrsig_rdata_get_type_covered(rdata, rdatalen);
1279 		if((rrset=az_domain_rrset(node, ctype))!= NULL) {
1280 			if(az_rrset_find_rrsig(rrset->data, rdata, rdatalen,
1281 				&index)) {
1282 				/* rrsig should have d->count > 0, be
1283 				 * over some rr of that type */
1284 				/* remove the rrsig from the rrsigs list of the
1285 				 * rrset */
1286 				if(!rrset_remove_rr(rrset, index))
1287 					return 0;
1288 				return 1;
1289 			}
1290 		}
1291 		/* also RRSIG not found */
1292 	}
1293 
1294 	/* nothing found to delete */
1295 	if(nonexist) *nonexist = 1;
1296 	return 1;
1297 }
1298 
1299 /** remove RR from zone, ignore if it does not exist, false on alloc failure*/
1300 static int
az_remove_rr(struct auth_zone * z,uint8_t * rr,size_t rr_len,size_t dname_len,int * nonexist)1301 az_remove_rr(struct auth_zone* z, uint8_t* rr, size_t rr_len,
1302 	size_t dname_len, int* nonexist)
1303 {
1304 	struct auth_data* node;
1305 	uint8_t* dname = rr;
1306 	uint16_t rr_type = sldns_wirerr_get_type(rr, rr_len, dname_len);
1307 	uint16_t rr_class = sldns_wirerr_get_class(rr, rr_len, dname_len);
1308 	size_t rdatalen = ((size_t)sldns_wirerr_get_rdatalen(rr, rr_len,
1309 		dname_len))+2;
1310 	/* rdata points to rdata prefixed with uint16 rdatalength */
1311 	uint8_t* rdata = sldns_wirerr_get_rdatawl(rr, rr_len, dname_len);
1312 
1313 	if(rr_class != z->dclass) {
1314 		log_err("wrong class for RR");
1315 		/* really also a nonexisting entry, because no records
1316 		 * of that class in the zone, but return an error because
1317 		 * getting records of the wrong class is a failure of the
1318 		 * zone transfer */
1319 		return 0;
1320 	}
1321 	node = az_find_name(z, dname, dname_len);
1322 	if(!node) {
1323 		/* node with that name does not exist */
1324 		/* nonexisting entry, because no such name */
1325 		*nonexist = 1;
1326 		return 1;
1327 	}
1328 	if(!az_domain_remove_rr(node, rr_type, rdata, rdatalen, nonexist)) {
1329 		/* alloc failure or so */
1330 		return 0;
1331 	}
1332 	/* remove the node, if necessary */
1333 	/* an rrsets==NULL entry is not kept around for empty nonterminals,
1334 	 * and also parent nodes are not kept around, so we just delete it */
1335 	if(node->rrsets == NULL) {
1336 		(void)rbtree_delete(&z->data, node);
1337 		auth_data_delete(node);
1338 	}
1339 	if(z->rpz) {
1340 		rpz_remove_rr(z->rpz, z->name, z->namelen, dname, dname_len,
1341 			rr_type, rr_class, rdata, rdatalen);
1342 	}
1343 	return 1;
1344 }
1345 
1346 /** decompress an RR into the buffer where it'll be an uncompressed RR
1347  * with uncompressed dname and uncompressed rdata (dnames) */
1348 static int
decompress_rr_into_buffer(struct sldns_buffer * buf,uint8_t * pkt,size_t pktlen,uint8_t * dname,uint16_t rr_type,uint16_t rr_class,uint32_t rr_ttl,uint8_t * rr_data,uint16_t rr_rdlen)1349 decompress_rr_into_buffer(struct sldns_buffer* buf, uint8_t* pkt,
1350 	size_t pktlen, uint8_t* dname, uint16_t rr_type, uint16_t rr_class,
1351 	uint32_t rr_ttl, uint8_t* rr_data, uint16_t rr_rdlen)
1352 {
1353 	sldns_buffer pktbuf;
1354 	size_t dname_len = 0;
1355 	size_t rdlenpos;
1356 	size_t rdlen;
1357 	uint8_t* rd;
1358 	const sldns_rr_descriptor* desc;
1359 	sldns_buffer_init_frm_data(&pktbuf, pkt, pktlen);
1360 	sldns_buffer_clear(buf);
1361 
1362 	/* decompress dname */
1363 	sldns_buffer_set_position(&pktbuf,
1364 		(size_t)(dname - sldns_buffer_current(&pktbuf)));
1365 	dname_len = pkt_dname_len(&pktbuf);
1366 	if(dname_len == 0) return 0; /* parse fail on dname */
1367 	if(!sldns_buffer_available(buf, dname_len)) return 0;
1368 	dname_pkt_copy(&pktbuf, sldns_buffer_current(buf), dname);
1369 	sldns_buffer_skip(buf, (ssize_t)dname_len);
1370 
1371 	/* type, class, ttl and rdatalength fields */
1372 	if(!sldns_buffer_available(buf, 10)) return 0;
1373 	sldns_buffer_write_u16(buf, rr_type);
1374 	sldns_buffer_write_u16(buf, rr_class);
1375 	sldns_buffer_write_u32(buf, rr_ttl);
1376 	rdlenpos = sldns_buffer_position(buf);
1377 	sldns_buffer_write_u16(buf, 0); /* rd length position */
1378 
1379 	/* decompress rdata */
1380 	desc = sldns_rr_descript(rr_type);
1381 	rd = rr_data;
1382 	rdlen = rr_rdlen;
1383 	if(rdlen > 0 && desc && desc->_dname_count > 0) {
1384 		int count = (int)desc->_dname_count;
1385 		int rdf = 0;
1386 		size_t len; /* how much rdata to plain copy */
1387 		size_t uncompressed_len, compressed_len;
1388 		size_t oldpos;
1389 		/* decompress dnames. */
1390 		while(rdlen > 0 && count) {
1391 			switch(desc->_wireformat[rdf]) {
1392 			case LDNS_RDF_TYPE_DNAME:
1393 				sldns_buffer_set_position(&pktbuf,
1394 					(size_t)(rd -
1395 					sldns_buffer_begin(&pktbuf)));
1396 				oldpos = sldns_buffer_position(&pktbuf);
1397 				/* moves pktbuf to right after the
1398 				 * compressed dname, and returns uncompressed
1399 				 * dname length */
1400 				uncompressed_len = pkt_dname_len(&pktbuf);
1401 				if(!uncompressed_len)
1402 					return 0; /* parse error in dname */
1403 				compressed_len = sldns_buffer_position(
1404 					&pktbuf) - oldpos;
1405 				if(compressed_len > rdlen)
1406 					return 0; /* dname exceeds rdata */
1407 				if(!sldns_buffer_available(buf,
1408 					uncompressed_len))
1409 					/* dname too long for buffer */
1410 					return 0;
1411 				dname_pkt_copy(&pktbuf,
1412 					sldns_buffer_current(buf), rd);
1413 				sldns_buffer_skip(buf, (ssize_t)uncompressed_len);
1414 				rd += compressed_len;
1415 				rdlen -= compressed_len;
1416 				count--;
1417 				len = 0;
1418 				break;
1419 			case LDNS_RDF_TYPE_STR:
1420 				/* Check rdlen for resilience, because it is
1421 				 * checked above, that rdlen > 0 */
1422 				if(rdlen < 1) return 0; /* malformed */
1423 				len = rd[0] + 1;
1424 				break;
1425 			default:
1426 				len = get_rdf_size(desc->_wireformat[rdf]);
1427 				break;
1428 			}
1429 			if(len) {
1430 				if(len > rdlen)
1431 					return 0; /* malformed */
1432 				if(!sldns_buffer_available(buf, len))
1433 					return 0; /* too long for buffer */
1434 				sldns_buffer_write(buf, rd, len);
1435 				rd += len;
1436 				rdlen -= len;
1437 			}
1438 			rdf++;
1439 		}
1440 	}
1441 	/* copy remaining data */
1442 	if(rdlen > 0) {
1443 		if(!sldns_buffer_available(buf, rdlen)) return 0;
1444 		sldns_buffer_write(buf, rd, rdlen);
1445 	}
1446 	/* fixup rdlength */
1447 	sldns_buffer_write_u16_at(buf, rdlenpos,
1448 		sldns_buffer_position(buf)-rdlenpos-2);
1449 	sldns_buffer_flip(buf);
1450 	return 1;
1451 }
1452 
1453 /** insert RR into zone, from packet, decompress RR,
1454  * if duplicate is nonNULL set the flag but otherwise ignore duplicates */
1455 static int
az_insert_rr_decompress(struct auth_zone * z,uint8_t * pkt,size_t pktlen,struct sldns_buffer * scratch_buffer,uint8_t * dname,uint16_t rr_type,uint16_t rr_class,uint32_t rr_ttl,uint8_t * rr_data,uint16_t rr_rdlen,int * duplicate)1456 az_insert_rr_decompress(struct auth_zone* z, uint8_t* pkt, size_t pktlen,
1457 	struct sldns_buffer* scratch_buffer, uint8_t* dname, uint16_t rr_type,
1458 	uint16_t rr_class, uint32_t rr_ttl, uint8_t* rr_data,
1459 	uint16_t rr_rdlen, int* duplicate)
1460 {
1461 	uint8_t* rr;
1462 	size_t rr_len;
1463 	size_t dname_len;
1464 	if(!decompress_rr_into_buffer(scratch_buffer, pkt, pktlen, dname,
1465 		rr_type, rr_class, rr_ttl, rr_data, rr_rdlen)) {
1466 		log_err("could not decompress RR");
1467 		return 0;
1468 	}
1469 	rr = sldns_buffer_begin(scratch_buffer);
1470 	rr_len = sldns_buffer_limit(scratch_buffer);
1471 	dname_len = dname_valid(rr, rr_len);
1472 	return az_insert_rr(z, rr, rr_len, dname_len, duplicate);
1473 }
1474 
1475 /** remove RR from zone, from packet, decompress RR,
1476  * if nonexist is nonNULL set the flag but otherwise ignore nonexisting entries*/
1477 static int
az_remove_rr_decompress(struct auth_zone * z,uint8_t * pkt,size_t pktlen,struct sldns_buffer * scratch_buffer,uint8_t * dname,uint16_t rr_type,uint16_t rr_class,uint32_t rr_ttl,uint8_t * rr_data,uint16_t rr_rdlen,int * nonexist)1478 az_remove_rr_decompress(struct auth_zone* z, uint8_t* pkt, size_t pktlen,
1479 	struct sldns_buffer* scratch_buffer, uint8_t* dname, uint16_t rr_type,
1480 	uint16_t rr_class, uint32_t rr_ttl, uint8_t* rr_data,
1481 	uint16_t rr_rdlen, int* nonexist)
1482 {
1483 	uint8_t* rr;
1484 	size_t rr_len;
1485 	size_t dname_len;
1486 	if(!decompress_rr_into_buffer(scratch_buffer, pkt, pktlen, dname,
1487 		rr_type, rr_class, rr_ttl, rr_data, rr_rdlen)) {
1488 		log_err("could not decompress RR");
1489 		return 0;
1490 	}
1491 	rr = sldns_buffer_begin(scratch_buffer);
1492 	rr_len = sldns_buffer_limit(scratch_buffer);
1493 	dname_len = dname_valid(rr, rr_len);
1494 	return az_remove_rr(z, rr, rr_len, dname_len, nonexist);
1495 }
1496 
1497 /**
1498  * Parse zonefile
1499  * @param z: zone to read in.
1500  * @param in: file to read from (just opened).
1501  * @param rr: buffer to use for RRs, 64k.
1502  *	passed so that recursive includes can use the same buffer and do
1503  *	not grow the stack too much.
1504  * @param rrbuflen: sizeof rr buffer.
1505  * @param state: parse state with $ORIGIN, $TTL and 'prev-dname' and so on,
1506  *	that is kept between includes.
1507  *	The lineno is set at 1 and then increased by the function.
1508  * @param fname: file name.
1509  * @param depth: recursion depth for includes
1510  * @param cfg: config for chroot.
1511  * returns false on failure, has printed an error message
1512  */
1513 static int
az_parse_file(struct auth_zone * z,FILE * in,uint8_t * rr,size_t rrbuflen,struct sldns_file_parse_state * state,char * fname,int depth,struct config_file * cfg)1514 az_parse_file(struct auth_zone* z, FILE* in, uint8_t* rr, size_t rrbuflen,
1515 	struct sldns_file_parse_state* state, char* fname, int depth,
1516 	struct config_file* cfg)
1517 {
1518 	size_t rr_len, dname_len;
1519 	int status;
1520 	state->lineno = 1;
1521 
1522 	while(!feof(in)) {
1523 		rr_len = rrbuflen;
1524 		dname_len = 0;
1525 		status = sldns_fp2wire_rr_buf(in, rr, &rr_len, &dname_len,
1526 			state);
1527 		if(status == LDNS_WIREPARSE_ERR_INCLUDE && rr_len == 0) {
1528 			/* we have $INCLUDE or $something */
1529 			if(strncmp((char*)rr, "$INCLUDE ", 9) == 0 ||
1530 			   strncmp((char*)rr, "$INCLUDE\t", 9) == 0) {
1531 				FILE* inc;
1532 				int lineno_orig = state->lineno;
1533 				char* incfile = (char*)rr + 8;
1534 				if(depth > MAX_INCLUDE_DEPTH) {
1535 					log_err("%s:%d max include depth"
1536 					  "exceeded", fname, state->lineno);
1537 					return 0;
1538 				}
1539 				/* A $INCLUDE is not expected for a secondary zone. */
1540 				if(z->zone_is_slave) {
1541 					log_err("%s:%d $INCLUDE not allowed for secondary zone", fname, state->lineno);
1542 					return 0;
1543 				}
1544 				/* skip spaces */
1545 				while(*incfile == ' ' || *incfile == '\t')
1546 					incfile++;
1547 				/* adjust for chroot on include file */
1548 				if(cfg->chrootdir && cfg->chrootdir[0] &&
1549 					strncmp(incfile, cfg->chrootdir,
1550 						strlen(cfg->chrootdir)) == 0)
1551 					incfile += strlen(cfg->chrootdir);
1552 				incfile = strdup(incfile);
1553 				if(!incfile) {
1554 					log_err("malloc failure");
1555 					return 0;
1556 				}
1557 				verbose(VERB_ALGO, "opening $INCLUDE %s",
1558 					incfile);
1559 				inc = fopen(incfile, "r");
1560 				if(!inc) {
1561 					log_err("%s:%d cannot open include "
1562 						"file %s: %s", fname,
1563 						lineno_orig, incfile,
1564 						strerror(errno));
1565 					free(incfile);
1566 					return 0;
1567 				}
1568 				/* recurse read that file now */
1569 				if(!az_parse_file(z, inc, rr, rrbuflen,
1570 					state, incfile, depth+1, cfg)) {
1571 					log_err("%s:%d cannot parse include "
1572 						"file %s", fname,
1573 						lineno_orig, incfile);
1574 					fclose(inc);
1575 					free(incfile);
1576 					return 0;
1577 				}
1578 				fclose(inc);
1579 				verbose(VERB_ALGO, "done with $INCLUDE %s",
1580 					incfile);
1581 				free(incfile);
1582 				state->lineno = lineno_orig;
1583 			}
1584 			continue;
1585 		}
1586 		if(status != 0) {
1587 			log_err("parse error %s %d:%d: %s", fname,
1588 				state->lineno, LDNS_WIREPARSE_OFFSET(status),
1589 				sldns_get_errorstr_parse(status));
1590 			return 0;
1591 		}
1592 		if(rr_len == 0) {
1593 			/* EMPTY line, TTL or ORIGIN */
1594 			continue;
1595 		}
1596 		/* insert wirerr in rrbuf */
1597 		if(!az_insert_rr(z, rr, rr_len, dname_len, NULL)) {
1598 			char buf[17];
1599 			sldns_wire2str_type_buf(sldns_wirerr_get_type(rr,
1600 				rr_len, dname_len), buf, sizeof(buf));
1601 			log_err("%s:%d cannot insert RR of type %s",
1602 				fname, state->lineno, buf);
1603 			return 0;
1604 		}
1605 	}
1606 	return 1;
1607 }
1608 
auth_zone_clear_data(struct auth_zone * z)1609 void auth_zone_clear_data(struct auth_zone* z)
1610 {
1611 	/* clear the data tree */
1612 	traverse_postorder(&z->data, auth_data_del, NULL);
1613 	rbtree_init(&z->data, &auth_data_cmp);
1614 	/* clear the RPZ policies */
1615 	if(z->rpz)
1616 		rpz_clear(z->rpz);
1617 }
1618 
1619 int
auth_zone_read_zonefile(struct auth_zone * z,struct config_file * cfg)1620 auth_zone_read_zonefile(struct auth_zone* z, struct config_file* cfg)
1621 {
1622 	uint8_t rr[LDNS_RR_BUF_SIZE];
1623 	struct sldns_file_parse_state state;
1624 	char* zfilename;
1625 	FILE* in;
1626 	if(!z || !z->zonefile || z->zonefile[0]==0)
1627 		return 1; /* no file, or "", nothing to read */
1628 
1629 	zfilename = z->zonefile;
1630 	if(cfg->chrootdir && cfg->chrootdir[0] && strncmp(zfilename,
1631 		cfg->chrootdir, strlen(cfg->chrootdir)) == 0)
1632 		zfilename += strlen(cfg->chrootdir);
1633 	if(verbosity >= VERB_ALGO) {
1634 		char nm[LDNS_MAX_DOMAINLEN];
1635 		dname_str(z->name, nm);
1636 		verbose(VERB_ALGO, "read zonefile %s for %s", zfilename, nm);
1637 	}
1638 	in = fopen(zfilename, "r");
1639 	if(!in) {
1640 		char* n = sldns_wire2str_dname(z->name, z->namelen);
1641 		if(errno == ENOENT) {
1642 			/* For a secondary, fetch the zone contents later, no
1643 			 * file yet. For a primary, no way to fetch the zone,
1644 			 * so warn. */
1645 			if(z->zone_is_slave)
1646 				verbose(VERB_ALGO, "no zonefile %s for %s",
1647 					zfilename, n?n:"error");
1648 			else
1649 				log_warn("no zonefile %s for %s",
1650 					zfilename, n?n:"error");
1651 			free(n);
1652 			return 1;
1653 		}
1654 		log_err("cannot open zonefile %s for %s: %s",
1655 			zfilename, n?n:"error", strerror(errno));
1656 		free(n);
1657 		return 0;
1658 	}
1659 
1660 	/* clear the data tree */
1661 	traverse_postorder(&z->data, auth_data_del, NULL);
1662 	rbtree_init(&z->data, &auth_data_cmp);
1663 	/* clear the RPZ policies */
1664 	if(z->rpz)
1665 		rpz_clear(z->rpz);
1666 
1667 	memset(&state, 0, sizeof(state));
1668 	/* default TTL to 3600 */
1669 	state.default_ttl = 3600;
1670 	/* set $ORIGIN to the zone name */
1671 	if(z->namelen <= sizeof(state.origin)) {
1672 		memcpy(state.origin, z->name, z->namelen);
1673 		state.origin_len = z->namelen;
1674 	}
1675 	/* parse the (toplevel) file */
1676 	if(!az_parse_file(z, in, rr, sizeof(rr), &state, zfilename, 0, cfg)) {
1677 		char* n = sldns_wire2str_dname(z->name, z->namelen);
1678 		log_err("error parsing zonefile %s for %s",
1679 			zfilename, n?n:"error");
1680 		free(n);
1681 		fclose(in);
1682 		return 0;
1683 	}
1684 	fclose(in);
1685 
1686 	if(z->rpz)
1687 		rpz_finish_config(z->rpz);
1688 	return 1;
1689 }
1690 
1691 /** write buffer to file and check return codes */
1692 static int
write_out(FILE * out,const char * str,size_t len)1693 write_out(FILE* out, const char* str, size_t len)
1694 {
1695 	size_t r;
1696 	if(len == 0)
1697 		return 1;
1698 	r = fwrite(str, 1, len, out);
1699 	if(r == 0) {
1700 		log_err("write failed: %s", strerror(errno));
1701 		return 0;
1702 	} else if(r < len) {
1703 		log_err("write failed: too short (disk full?)");
1704 		return 0;
1705 	}
1706 	return 1;
1707 }
1708 
1709 /** convert auth rr to string */
1710 static int
auth_rr_to_string(uint8_t * nm,size_t nmlen,uint16_t tp,uint16_t cl,struct packed_rrset_data * data,size_t i,char * s,size_t buflen)1711 auth_rr_to_string(uint8_t* nm, size_t nmlen, uint16_t tp, uint16_t cl,
1712 	struct packed_rrset_data* data, size_t i, char* s, size_t buflen)
1713 {
1714 	int w = 0;
1715 	size_t slen = buflen, datlen;
1716 	uint8_t* dat;
1717 	if(i >= data->count) tp = LDNS_RR_TYPE_RRSIG;
1718 	dat = nm;
1719 	datlen = nmlen;
1720 	w += sldns_wire2str_dname_scan(&dat, &datlen, &s, &slen, NULL, 0, NULL);
1721 	w += sldns_str_print(&s, &slen, "\t");
1722 	w += sldns_str_print(&s, &slen, "%lu\t", (unsigned long)data->rr_ttl[i]);
1723 	w += sldns_wire2str_class_print(&s, &slen, cl);
1724 	w += sldns_str_print(&s, &slen, "\t");
1725 	w += sldns_wire2str_type_print(&s, &slen, tp);
1726 	w += sldns_str_print(&s, &slen, "\t");
1727 	datlen = data->rr_len[i]-2;
1728 	dat = data->rr_data[i]+2;
1729 	w += sldns_wire2str_rdata_scan(&dat, &datlen, &s, &slen, tp, NULL, 0, NULL);
1730 
1731 	if(tp == LDNS_RR_TYPE_DNSKEY) {
1732 		w += sldns_str_print(&s, &slen, " ;{id = %u}",
1733 			sldns_calc_keytag_raw(data->rr_data[i]+2,
1734 				data->rr_len[i]-2));
1735 	}
1736 	w += sldns_str_print(&s, &slen, "\n");
1737 
1738 	if(w >= (int)buflen) {
1739 		log_nametypeclass(NO_VERBOSE, "RR too long to print", nm, tp, cl);
1740 		return 0;
1741 	}
1742 	return 1;
1743 }
1744 
1745 /** write rrset to file */
1746 static int
auth_zone_write_rrset(struct auth_zone * z,struct auth_data * node,struct auth_rrset * r,FILE * out)1747 auth_zone_write_rrset(struct auth_zone* z, struct auth_data* node,
1748 	struct auth_rrset* r, FILE* out)
1749 {
1750 	size_t i, count = r->data->count + r->data->rrsig_count;
1751 	char buf[LDNS_RR_BUF_SIZE];
1752 	for(i=0; i<count; i++) {
1753 		if(!auth_rr_to_string(node->name, node->namelen, r->type,
1754 			z->dclass, r->data, i, buf, sizeof(buf))) {
1755 			verbose(VERB_ALGO, "failed to rr2str rr %d", (int)i);
1756 			continue;
1757 		}
1758 		if(!write_out(out, buf, strlen(buf)))
1759 			return 0;
1760 	}
1761 	return 1;
1762 }
1763 
1764 /** write domain to file */
1765 static int
auth_zone_write_domain(struct auth_zone * z,struct auth_data * n,FILE * out)1766 auth_zone_write_domain(struct auth_zone* z, struct auth_data* n, FILE* out)
1767 {
1768 	struct auth_rrset* r;
1769 	/* if this is zone apex, write SOA first */
1770 	if(z->namelen == n->namelen) {
1771 		struct auth_rrset* soa = az_domain_rrset(n, LDNS_RR_TYPE_SOA);
1772 		if(soa) {
1773 			if(!auth_zone_write_rrset(z, n, soa, out))
1774 				return 0;
1775 		}
1776 	}
1777 	/* write all the RRsets for this domain */
1778 	for(r = n->rrsets; r; r = r->next) {
1779 		if(z->namelen == n->namelen &&
1780 			r->type == LDNS_RR_TYPE_SOA)
1781 			continue; /* skip SOA here */
1782 		if(!auth_zone_write_rrset(z, n, r, out))
1783 			return 0;
1784 	}
1785 	return 1;
1786 }
1787 
auth_zone_write_file(struct auth_zone * z,const char * fname)1788 int auth_zone_write_file(struct auth_zone* z, const char* fname)
1789 {
1790 	FILE* out;
1791 	struct auth_data* n;
1792 	out = fopen(fname, "w");
1793 	if(!out) {
1794 		log_err("could not open %s: %s", fname, strerror(errno));
1795 		return 0;
1796 	}
1797 	RBTREE_FOR(n, struct auth_data*, &z->data) {
1798 		if(!auth_zone_write_domain(z, n, out)) {
1799 			log_err("could not write domain to %s", fname);
1800 			fclose(out);
1801 			return 0;
1802 		}
1803 	}
1804 	fclose(out);
1805 	return 1;
1806 }
1807 
1808 /** offline verify for zonemd, while reading a zone file to immediately
1809  * spot bad hashes in zonefile as they are read.
1810  * Creates temp buffers, but uses anchors and validation environment
1811  * from the module_env. */
1812 static void
zonemd_offline_verify(struct auth_zone * z,struct module_env * env_for_val,struct module_stack * mods)1813 zonemd_offline_verify(struct auth_zone* z, struct module_env* env_for_val,
1814 	struct module_stack* mods)
1815 {
1816 	struct module_env env;
1817 	time_t now = 0;
1818 	if(!z->zonemd_check)
1819 		return;
1820 	env = *env_for_val;
1821 	env.scratch_buffer = sldns_buffer_new(env.cfg->msg_buffer_size);
1822 	if(!env.scratch_buffer) {
1823 		log_err("out of memory");
1824 		goto clean_exit;
1825 	}
1826 	env.scratch = regional_create();
1827 	if(!env.now) {
1828 		env.now = &now;
1829 		now = time(NULL);
1830 	}
1831 	if(!env.scratch) {
1832 		log_err("out of memory");
1833 		goto clean_exit;
1834 	}
1835 	auth_zone_verify_zonemd(z, &env, mods, NULL, 1, 0);
1836 
1837 clean_exit:
1838 	/* clean up and exit */
1839 	sldns_buffer_free(env.scratch_buffer);
1840 	regional_destroy(env.scratch);
1841 }
1842 
1843 /** read all auth zones from file (if they have) */
1844 static int
auth_zones_read_zones(struct auth_zones * az,struct config_file * cfg,struct module_env * env,struct module_stack * mods)1845 auth_zones_read_zones(struct auth_zones* az, struct config_file* cfg,
1846 	struct module_env* env, struct module_stack* mods)
1847 {
1848 	struct auth_zone* z;
1849 	lock_rw_wrlock(&az->lock);
1850 	RBTREE_FOR(z, struct auth_zone*, &az->ztree) {
1851 		lock_rw_wrlock(&z->lock);
1852 		if(!auth_zone_read_zonefile(z, cfg)) {
1853 			/* For both secondary and primary zones, not fatal.
1854 			 * This keeps the server up. */
1855 			auth_zone_clear_data(z);
1856 			lock_rw_unlock(&z->lock);
1857 			continue;
1858 		}
1859 		if(z->zonefile && z->zonefile[0]!=0 && env)
1860 			zonemd_offline_verify(z, env, mods);
1861 		lock_rw_unlock(&z->lock);
1862 	}
1863 	lock_rw_unlock(&az->lock);
1864 	return 1;
1865 }
1866 
1867 /** fetch the content of a ZONEMD RR from the rdata */
zonemd_fetch_parameters(struct auth_rrset * zonemd_rrset,size_t i,uint32_t * serial,int * scheme,int * hashalgo,uint8_t ** hash,size_t * hashlen)1868 static int zonemd_fetch_parameters(struct auth_rrset* zonemd_rrset, size_t i,
1869 	uint32_t* serial, int* scheme, int* hashalgo, uint8_t** hash,
1870 	size_t* hashlen)
1871 {
1872 	size_t rr_len;
1873 	uint8_t* rdata;
1874 	if(i >= zonemd_rrset->data->count)
1875 		return 0;
1876 	rr_len = zonemd_rrset->data->rr_len[i];
1877 	if(rr_len < 2+4+1+1)
1878 		return 0; /* too short, for rdlen+serial+scheme+algo */
1879 	rdata = zonemd_rrset->data->rr_data[i];
1880 	*serial = sldns_read_uint32(rdata+2);
1881 	*scheme = rdata[6];
1882 	*hashalgo = rdata[7];
1883 	*hashlen = rr_len - 8;
1884 	if(*hashlen == 0)
1885 		*hash = NULL;
1886 	else	*hash = rdata+8;
1887 	return 1;
1888 }
1889 
1890 /**
1891  * See if the ZONEMD scheme, hash occurs more than once.
1892  * @param zonemd_rrset: the zonemd rrset to check with the RRs in it.
1893  * @param index: index of the original, this is allowed to have that
1894  * 	scheme and hashalgo, but other RRs should not have it.
1895  * @param scheme: the scheme to check for.
1896  * @param hashalgo: the hash algorithm to check for.
1897  * @return true if it occurs more than once.
1898  */
zonemd_is_duplicate_scheme_hash(struct auth_rrset * zonemd_rrset,size_t index,int scheme,int hashalgo)1899 static int zonemd_is_duplicate_scheme_hash(struct auth_rrset* zonemd_rrset,
1900 	size_t index, int scheme, int hashalgo)
1901 {
1902 	size_t j;
1903 	for(j=0; j<zonemd_rrset->data->count; j++) {
1904 		uint32_t serial2 = 0;
1905 		int scheme2 = 0, hashalgo2 = 0;
1906 		uint8_t* hash2 = NULL;
1907 		size_t hashlen2 = 0;
1908 		if(index == j) {
1909 			/* this is the original */
1910 			continue;
1911 		}
1912 		if(!zonemd_fetch_parameters(zonemd_rrset, j, &serial2,
1913 			&scheme2, &hashalgo2, &hash2, &hashlen2)) {
1914 			/* malformed, skip it */
1915 			continue;
1916 		}
1917 		if(scheme == scheme2 && hashalgo == hashalgo2) {
1918 			/* duplicate scheme, hash */
1919 			verbose(VERB_ALGO, "zonemd duplicate for scheme %d "
1920 				"and hash %d", scheme, hashalgo);
1921 			return 1;
1922 		}
1923 	}
1924 	return 0;
1925 }
1926 
1927 /**
1928  * Check ZONEMDs if present for the auth zone.  Depending on config
1929  * it can warn or fail on that.  Checks the hash of the ZONEMD.
1930  * @param z: auth zone to check for.
1931  * 	caller must hold lock on zone.
1932  * @param env: module env for temp buffers.
1933  * @param reason: returned on failure.
1934  * @return false on failure, true if hash checks out.
1935  */
auth_zone_zonemd_check_hash(struct auth_zone * z,struct module_env * env,char ** reason)1936 static int auth_zone_zonemd_check_hash(struct auth_zone* z,
1937 	struct module_env* env, char** reason)
1938 {
1939 	/* loop over ZONEMDs and see which one is valid. if not print
1940 	 * failure (depending on config) */
1941 	struct auth_data* apex;
1942 	struct auth_rrset* zonemd_rrset;
1943 	size_t i;
1944 	struct regional* region = NULL;
1945 	struct sldns_buffer* buf = NULL;
1946 	uint32_t soa_serial = 0;
1947 	char* unsupported_reason = NULL;
1948 	int only_unsupported = 1;
1949 	region = env->scratch;
1950 	regional_free_all(region);
1951 	buf = env->scratch_buffer;
1952 	if(!auth_zone_get_serial(z, &soa_serial)) {
1953 		*reason = "zone has no SOA serial";
1954 		return 0;
1955 	}
1956 
1957 	apex = az_find_name(z, z->name, z->namelen);
1958 	if(!apex) {
1959 		*reason = "zone has no apex";
1960 		return 0;
1961 	}
1962 	zonemd_rrset = az_domain_rrset(apex, LDNS_RR_TYPE_ZONEMD);
1963 	if(!zonemd_rrset || zonemd_rrset->data->count==0) {
1964 		*reason = "zone has no ZONEMD";
1965 		return 0; /* no RRset or no RRs in rrset */
1966 	}
1967 
1968 	/* we have a ZONEMD, check if it is correct */
1969 	for(i=0; i<zonemd_rrset->data->count; i++) {
1970 		uint32_t serial = 0;
1971 		int scheme = 0, hashalgo = 0;
1972 		uint8_t* hash = NULL;
1973 		size_t hashlen = 0;
1974 		if(!zonemd_fetch_parameters(zonemd_rrset, i, &serial, &scheme,
1975 			&hashalgo, &hash, &hashlen)) {
1976 			/* malformed RR */
1977 			*reason = "ZONEMD rdata malformed";
1978 			only_unsupported = 0;
1979 			continue;
1980 		}
1981 		/* check for duplicates */
1982 		if(zonemd_is_duplicate_scheme_hash(zonemd_rrset, i, scheme,
1983 			hashalgo)) {
1984 			/* duplicate hash of the same scheme,hash
1985 			 * is not allowed. */
1986 			*reason = "ZONEMD RRSet contains more than one RR "
1987 				"with the same scheme and hash algorithm";
1988 			only_unsupported = 0;
1989 			continue;
1990 		}
1991 		regional_free_all(region);
1992 		if(serial != soa_serial) {
1993 			*reason = "ZONEMD serial is wrong";
1994 			only_unsupported = 0;
1995 			continue;
1996 		}
1997 		*reason = NULL;
1998 		if(auth_zone_generate_zonemd_check(z, scheme, hashalgo,
1999 			hash, hashlen, region, buf, reason)) {
2000 			/* success */
2001 			if(*reason) {
2002 				if(!unsupported_reason)
2003 					unsupported_reason = *reason;
2004 				/* continue to check for valid ZONEMD */
2005 				if(verbosity >= VERB_ALGO) {
2006 					char zstr[LDNS_MAX_DOMAINLEN];
2007 					dname_str(z->name, zstr);
2008 					verbose(VERB_ALGO, "auth-zone %s ZONEMD %d %d is unsupported: %s", zstr, (int)scheme, (int)hashalgo, *reason);
2009 				}
2010 				*reason = NULL;
2011 				continue;
2012 			}
2013 			if(verbosity >= VERB_ALGO) {
2014 				char zstr[LDNS_MAX_DOMAINLEN];
2015 				dname_str(z->name, zstr);
2016 				if(!*reason)
2017 					verbose(VERB_ALGO, "auth-zone %s ZONEMD hash is correct", zstr);
2018 			}
2019 			return 1;
2020 		}
2021 		only_unsupported = 0;
2022 		/* try next one */
2023 	}
2024 	/* have we seen no failures but only unsupported algo,
2025 	 * and one unsupported algorithm, or more. */
2026 	if(only_unsupported && unsupported_reason) {
2027 		/* only unsupported algorithms, with valid serial, not
2028 		 * malformed. Did not see supported algorithms, failed or
2029 		 * successful ones. */
2030 		*reason = unsupported_reason;
2031 		return 1;
2032 	}
2033 	/* fail, we may have reason */
2034 	if(!*reason)
2035 		*reason = "no ZONEMD records found";
2036 	if(verbosity >= VERB_ALGO) {
2037 		char zstr[LDNS_MAX_DOMAINLEN];
2038 		dname_str(z->name, zstr);
2039 		verbose(VERB_ALGO, "auth-zone %s ZONEMD failed: %s", zstr, *reason);
2040 	}
2041 	return 0;
2042 }
2043 
2044 /** find the apex SOA RRset, if it exists */
auth_zone_get_soa_rrset(struct auth_zone * z)2045 struct auth_rrset* auth_zone_get_soa_rrset(struct auth_zone* z)
2046 {
2047 	struct auth_data* apex;
2048 	struct auth_rrset* soa;
2049 	apex = az_find_name(z, z->name, z->namelen);
2050 	if(!apex) return NULL;
2051 	soa = az_domain_rrset(apex, LDNS_RR_TYPE_SOA);
2052 	return soa;
2053 }
2054 
2055 /** find serial number of zone or false if none */
2056 int
auth_zone_get_serial(struct auth_zone * z,uint32_t * serial)2057 auth_zone_get_serial(struct auth_zone* z, uint32_t* serial)
2058 {
2059 	struct auth_data* apex;
2060 	struct auth_rrset* soa;
2061 	struct packed_rrset_data* d;
2062 	size_t primlen, mboxlen;
2063 	apex = az_find_name(z, z->name, z->namelen);
2064 	if(!apex) return 0;
2065 	soa = az_domain_rrset(apex, LDNS_RR_TYPE_SOA);
2066 	if(!soa || soa->data->count==0)
2067 		return 0; /* no RRset or no RRs in rrset */
2068 	if(soa->data->rr_len[0] < 2+4*5) return 0; /* SOA too short */
2069 	if((primlen = dname_valid(soa->data->rr_data[0]+2,
2070 		soa->data->rr_len[0]-2)) == 0)
2071 		return 0; /* primary dname malformed */
2072 	if((mboxlen = dname_valid(soa->data->rr_data[0]+2+primlen,
2073 		soa->data->rr_len[0]-2-primlen)) == 0)
2074 		return 0; /* mailbox dname malformed */
2075 	if(2+primlen+mboxlen+4*5 != soa->data->rr_len[0])
2076 		return 0; /* rdata malformed */
2077 	d = soa->data;
2078 	*serial = sldns_read_uint32(d->rr_data[0]+(d->rr_len[0]-20));
2079 	return 1;
2080 }
2081 
2082 /** Find auth_zone SOA and populate the values in xfr(soa values). */
2083 int
xfr_find_soa(struct auth_zone * z,struct auth_xfer * xfr)2084 xfr_find_soa(struct auth_zone* z, struct auth_xfer* xfr)
2085 {
2086 	struct auth_data* apex;
2087 	struct auth_rrset* soa;
2088 	struct packed_rrset_data* d;
2089 	size_t primlen, mboxlen;
2090 	apex = az_find_name(z, z->name, z->namelen);
2091 	if(!apex) return 0;
2092 	soa = az_domain_rrset(apex, LDNS_RR_TYPE_SOA);
2093 	if(!soa || soa->data->count==0)
2094 		return 0; /* no RRset or no RRs in rrset */
2095 	if(soa->data->rr_len[0] < 2+4*5) return 0; /* SOA too short */
2096 	if((primlen = dname_valid(soa->data->rr_data[0]+2,
2097 		soa->data->rr_len[0]-2)) == 0)
2098 		return 0; /* primary dname malformed */
2099 	if((mboxlen = dname_valid(soa->data->rr_data[0]+2+primlen,
2100 		soa->data->rr_len[0]-2-primlen)) == 0)
2101 		return 0; /* mailbox dname malformed */
2102 	if(2+primlen+mboxlen+4*5 != soa->data->rr_len[0])
2103 		return 0; /* rdata malformed */
2104 	/* SOA record ends with serial, refresh, retry, expiry, minimum,
2105 	 * as 4 byte fields */
2106 	d = soa->data;
2107 	xfr->have_zone = 1;
2108 	xfr->serial = sldns_read_uint32(d->rr_data[0]+(d->rr_len[0]-20));
2109 	xfr->refresh = sldns_read_uint32(d->rr_data[0]+(d->rr_len[0]-16));
2110 	xfr->retry = sldns_read_uint32(d->rr_data[0]+(d->rr_len[0]-12));
2111 	xfr->expiry = sldns_read_uint32(d->rr_data[0]+(d->rr_len[0]-8));
2112 	/* soa minimum at d->rr_len[0]-4 */
2113 	return 1;
2114 }
2115 
2116 /**
2117  * Setup auth_xfer zone
2118  * This populates the have_zone, soa values, and so on times.
2119  * Doesn't do network traffic yet, can set option flags.
2120  * @param z: locked by caller, and modified for setup
2121  * @param x: locked by caller, and modified.
2122  * @return false on failure.
2123  */
2124 static int
auth_xfer_setup(struct auth_zone * z,struct auth_xfer * x)2125 auth_xfer_setup(struct auth_zone* z, struct auth_xfer* x)
2126 {
2127 	/* for a zone without zone transfers, x==NULL, so skip them,
2128 	 * i.e. the zone config is fixed with no masters or urls */
2129 	if(!z || !x) return 1;
2130 	if(!xfr_find_soa(z, x)) {
2131 		return 1;
2132 	}
2133 	x->is_rpz = (z->rpz!=NULL);
2134 	/* nothing for probe, nextprobe and transfer tasks */
2135 	return 1;
2136 }
2137 
2138 /**
2139  * Setup all zones
2140  * @param az: auth zones structure
2141  * @return false on failure.
2142  */
2143 static int
auth_zones_setup_zones(struct auth_zones * az)2144 auth_zones_setup_zones(struct auth_zones* az)
2145 {
2146 	struct auth_zone* z;
2147 	struct auth_xfer* x;
2148 	lock_rw_wrlock(&az->lock);
2149 	RBTREE_FOR(z, struct auth_zone*, &az->ztree) {
2150 		lock_rw_wrlock(&z->lock);
2151 		x = auth_xfer_find(az, z->name, z->namelen, z->dclass);
2152 		if(x) {
2153 			lock_basic_lock(&x->lock);
2154 		}
2155 		if(!auth_xfer_setup(z, x)) {
2156 			if(x) {
2157 				lock_basic_unlock(&x->lock);
2158 			}
2159 			lock_rw_unlock(&z->lock);
2160 			lock_rw_unlock(&az->lock);
2161 			return 0;
2162 		}
2163 		if(x) {
2164 			lock_basic_unlock(&x->lock);
2165 		}
2166 		lock_rw_unlock(&z->lock);
2167 	}
2168 	lock_rw_unlock(&az->lock);
2169 	return 1;
2170 }
2171 
2172 /** set config items and create zones */
2173 static int
auth_zones_cfg(struct auth_zones * az,struct config_auth * c)2174 auth_zones_cfg(struct auth_zones* az, struct config_auth* c)
2175 {
2176 	struct auth_zone* z;
2177 	struct auth_xfer* x = NULL;
2178 
2179 	/* create zone */
2180 	if(c->isrpz) {
2181 		/* if the rpz lock is needed, grab it before the other
2182 		 * locks to avoid a lock dependency cycle */
2183 		lock_rw_wrlock(&az->rpz_lock);
2184 	}
2185 	lock_rw_wrlock(&az->lock);
2186 	if(!(z=auth_zones_find_or_add_zone(az, c->name))) {
2187 		lock_rw_unlock(&az->lock);
2188 		if(c->isrpz) {
2189 			lock_rw_unlock(&az->rpz_lock);
2190 		}
2191 		return 0;
2192 	}
2193 	/* Populate the xfer related options early since we may create one now */
2194 	z->max_transfer_size = c->max_transfer_size;
2195 	z->max_transfer_time = c->max_transfer_time;
2196 	if(c->masters || c->urls) {
2197 		if(!(x=auth_zones_find_or_add_xfer(az, z))) {
2198 			lock_rw_unlock(&az->lock);
2199 			lock_rw_unlock(&z->lock);
2200 			if(c->isrpz) {
2201 				lock_rw_unlock(&az->rpz_lock);
2202 			}
2203 			return 0;
2204 		}
2205 	}
2206 	if(c->for_downstream)
2207 		az->have_downstream = 1;
2208 	lock_rw_unlock(&az->lock);
2209 
2210 	/* set options */
2211 	z->zone_deleted = 0;
2212 	if(!auth_zone_set_zonefile(z, c->zonefile)) {
2213 		if(x) {
2214 			lock_basic_unlock(&x->lock);
2215 		}
2216 		lock_rw_unlock(&z->lock);
2217 		if(c->isrpz) {
2218 			lock_rw_unlock(&az->rpz_lock);
2219 		}
2220 		return 0;
2221 	}
2222 	z->for_downstream = c->for_downstream;
2223 	z->for_upstream = c->for_upstream;
2224 	z->fallback_enabled = c->fallback_enabled;
2225 	z->zonemd_check = c->zonemd_check;
2226 	z->zonemd_reject_absence = c->zonemd_reject_absence;
2227 	if(c->isrpz && !z->rpz){
2228 		if(!(z->rpz = rpz_create(c))){
2229 			log_err("Could not setup RPZ zones");
2230 			if(x) {
2231 				lock_basic_unlock(&x->lock);
2232 			}
2233 			lock_rw_unlock(&z->lock);
2234 			lock_rw_unlock(&az->rpz_lock);
2235 			return 0;
2236 		}
2237 		lock_protect(&z->lock, &z->rpz->local_zones, sizeof(*z->rpz));
2238 		/* the az->rpz_lock is locked above */
2239 		z->rpz_az_next = az->rpz_first;
2240 		if(az->rpz_first)
2241 			az->rpz_first->rpz_az_prev = z;
2242 		az->rpz_first = z;
2243 	} else if(c->isrpz && z->rpz) {
2244 		if(!rpz_config(z->rpz, c)) {
2245 			log_err("Could not change rpz config");
2246 			if(x) {
2247 				lock_basic_unlock(&x->lock);
2248 			}
2249 			lock_rw_unlock(&z->lock);
2250 			lock_rw_unlock(&az->rpz_lock);
2251 			return 0;
2252 		}
2253 	}
2254 	if(c->isrpz) {
2255 		lock_rw_unlock(&az->rpz_lock);
2256 	}
2257 
2258 	/* xfer zone */
2259 	if(x) {
2260 		z->zone_is_slave = 1;
2261 		/* set options on xfer zone */
2262 		if(!xfer_set_masters(&x->task_probe->masters, c, 0)) {
2263 			lock_basic_unlock(&x->lock);
2264 			lock_rw_unlock(&z->lock);
2265 			return 0;
2266 		}
2267 		if(!xfer_set_masters(&x->task_transfer->masters, c, 1)) {
2268 			lock_basic_unlock(&x->lock);
2269 			lock_rw_unlock(&z->lock);
2270 			return 0;
2271 		}
2272 		/* Pick up allow notify entries, early. This works for
2273 		 * addresses and netblocks. */
2274 		if(!x->allow_notify_list)
2275 			probe_copy_masters_for_allow_notify(x);
2276 		lock_basic_unlock(&x->lock);
2277 	}
2278 
2279 	lock_rw_unlock(&z->lock);
2280 	return 1;
2281 }
2282 
2283 /** set all auth zones deleted, then in auth_zones_cfg, it marks them
2284  * as nondeleted (if they are still in the config), and then later
2285  * we can find deleted zones */
2286 static void
az_setall_deleted(struct auth_zones * az)2287 az_setall_deleted(struct auth_zones* az)
2288 {
2289 	struct auth_zone* z;
2290 	lock_rw_wrlock(&az->lock);
2291 	RBTREE_FOR(z, struct auth_zone*, &az->ztree) {
2292 		lock_rw_wrlock(&z->lock);
2293 		z->zone_deleted = 1;
2294 		lock_rw_unlock(&z->lock);
2295 	}
2296 	lock_rw_unlock(&az->lock);
2297 }
2298 
2299 /** find zones that are marked deleted and delete them.
2300  * This is called from apply_cfg, and there are no threads and no
2301  * workers, so the xfr can just be deleted. */
2302 static void
az_delete_deleted_zones(struct auth_zones * az)2303 az_delete_deleted_zones(struct auth_zones* az)
2304 {
2305 	struct auth_zone* z;
2306 	struct auth_zone* delete_list = NULL, *next;
2307 	struct auth_xfer* xfr;
2308 	lock_rw_wrlock(&az->lock);
2309 	RBTREE_FOR(z, struct auth_zone*, &az->ztree) {
2310 		lock_rw_wrlock(&z->lock);
2311 		if(z->zone_deleted) {
2312 			/* we cannot alter the rbtree right now, but
2313 			 * we can put it on a linked list and then
2314 			 * delete it */
2315 			z->delete_next = delete_list;
2316 			delete_list = z;
2317 		}
2318 		lock_rw_unlock(&z->lock);
2319 	}
2320 	/* now we are out of the tree loop and we can loop and delete
2321 	 * the zones */
2322 	z = delete_list;
2323 	while(z) {
2324 		next = z->delete_next;
2325 		xfr = auth_xfer_find(az, z->name, z->namelen, z->dclass);
2326 		if(xfr) {
2327 			(void)rbtree_delete(&az->xtree, &xfr->node);
2328 			auth_xfer_delete(xfr);
2329 		}
2330 		(void)rbtree_delete(&az->ztree, &z->node);
2331 		auth_zone_delete(z, az);
2332 		z = next;
2333 	}
2334 	lock_rw_unlock(&az->lock);
2335 }
2336 
auth_zones_apply_cfg(struct auth_zones * az,struct config_file * cfg,int setup,int * is_rpz,struct module_env * env,struct module_stack * mods)2337 int auth_zones_apply_cfg(struct auth_zones* az, struct config_file* cfg,
2338 	int setup, int* is_rpz, struct module_env* env,
2339 	struct module_stack* mods)
2340 {
2341 	struct config_auth* p;
2342 	az_setall_deleted(az);
2343 	for(p = cfg->auths; p; p = p->next) {
2344 		if(!p->name || p->name[0] == 0) {
2345 			log_warn("auth-zone without a name, skipped");
2346 			continue;
2347 		}
2348 		*is_rpz = (*is_rpz || p->isrpz);
2349 		if(!auth_zones_cfg(az, p)) {
2350 			log_err("cannot config auth zone %s", p->name);
2351 			return 0;
2352 		}
2353 	}
2354 	az_delete_deleted_zones(az);
2355 	if(!auth_zones_read_zones(az, cfg, env, mods))
2356 		return 0;
2357 	if(setup) {
2358 		if(!auth_zones_setup_zones(az))
2359 			return 0;
2360 	}
2361 	return 1;
2362 }
2363 
2364 /** delete chunks
2365  * @param at: transfer structure with chunks list.  The chunks and their
2366  * 	data are freed.
2367  */
2368 static void
auth_chunks_delete(struct auth_transfer * at)2369 auth_chunks_delete(struct auth_transfer* at)
2370 {
2371 	if(at->chunks_first) {
2372 		struct auth_chunk* c, *cn;
2373 		c = at->chunks_first;
2374 		while(c) {
2375 			cn = c->next;
2376 			free(c->data);
2377 			free(c);
2378 			c = cn;
2379 		}
2380 	}
2381 	at->chunks_first = NULL;
2382 	at->chunks_last = NULL;
2383 	at->chunks_total = 0;
2384 }
2385 
2386 /** free master addr list */
2387 static void
auth_free_master_addrs(struct auth_addr * list)2388 auth_free_master_addrs(struct auth_addr* list)
2389 {
2390 	struct auth_addr *n;
2391 	while(list) {
2392 		n = list->next;
2393 		free(list);
2394 		list = n;
2395 	}
2396 }
2397 
2398 /** free the masters list */
2399 static void
auth_free_masters(struct auth_master * list)2400 auth_free_masters(struct auth_master* list)
2401 {
2402 	struct auth_master* n;
2403 	while(list) {
2404 		n = list->next;
2405 		auth_free_master_addrs(list->list);
2406 		free(list->host);
2407 		free(list->file);
2408 		free(list);
2409 		list = n;
2410 	}
2411 }
2412 
2413 void
auth_xfer_delete(struct auth_xfer * xfr)2414 auth_xfer_delete(struct auth_xfer* xfr)
2415 {
2416 	if(!xfr) return;
2417 	lock_basic_destroy(&xfr->lock);
2418 	free(xfr->name);
2419 	if(xfr->task_nextprobe) {
2420 		comm_timer_delete(xfr->task_nextprobe->timer);
2421 		free(xfr->task_nextprobe);
2422 	}
2423 	if(xfr->task_probe) {
2424 		auth_free_masters(xfr->task_probe->masters);
2425 		comm_point_delete(xfr->task_probe->cp);
2426 		comm_timer_delete(xfr->task_probe->timer);
2427 		free(xfr->task_probe);
2428 	}
2429 	if(xfr->task_transfer) {
2430 		auth_free_masters(xfr->task_transfer->masters);
2431 		comm_point_delete(xfr->task_transfer->cp);
2432 		comm_timer_delete(xfr->task_transfer->timer);
2433 		if(xfr->task_transfer->chunks_first) {
2434 			auth_chunks_delete(xfr->task_transfer);
2435 		}
2436 		free(xfr->task_transfer);
2437 	}
2438 	auth_free_masters(xfr->allow_notify_list);
2439 	free(xfr);
2440 }
2441 
2442 /** helper traverse to delete zones */
2443 static void
auth_zone_del(rbnode_type * n,void * ATTR_UNUSED (arg))2444 auth_zone_del(rbnode_type* n, void* ATTR_UNUSED(arg))
2445 {
2446 	struct auth_zone* z = (struct auth_zone*)n->key;
2447 	auth_zone_delete(z, NULL);
2448 }
2449 
2450 /** helper traverse to delete xfer zones */
2451 static void
auth_xfer_del(rbnode_type * n,void * ATTR_UNUSED (arg))2452 auth_xfer_del(rbnode_type* n, void* ATTR_UNUSED(arg))
2453 {
2454 	struct auth_xfer* z = (struct auth_xfer*)n->key;
2455 	auth_xfer_delete(z);
2456 }
2457 
auth_zones_delete(struct auth_zones * az)2458 void auth_zones_delete(struct auth_zones* az)
2459 {
2460 	if(!az) return;
2461 	lock_rw_destroy(&az->lock);
2462 	lock_rw_destroy(&az->rpz_lock);
2463 	traverse_postorder(&az->ztree, auth_zone_del, NULL);
2464 	traverse_postorder(&az->xtree, auth_xfer_del, NULL);
2465 	free(az);
2466 }
2467 
2468 /** true if domain has only nsec3 */
2469 static int
domain_has_only_nsec3(struct auth_data * n)2470 domain_has_only_nsec3(struct auth_data* n)
2471 {
2472 	struct auth_rrset* rrset = n->rrsets;
2473 	int nsec3_seen = 0;
2474 	while(rrset) {
2475 		if(rrset->type == LDNS_RR_TYPE_NSEC3) {
2476 			nsec3_seen = 1;
2477 		} else if(rrset->type != LDNS_RR_TYPE_RRSIG) {
2478 			return 0;
2479 		}
2480 		rrset = rrset->next;
2481 	}
2482 	return nsec3_seen;
2483 }
2484 
2485 /** see if the domain has a wildcard child '*.domain' */
2486 static struct auth_data*
az_find_wildcard_domain(struct auth_zone * z,uint8_t * nm,size_t nmlen)2487 az_find_wildcard_domain(struct auth_zone* z, uint8_t* nm, size_t nmlen)
2488 {
2489 	uint8_t wc[LDNS_MAX_DOMAINLEN];
2490 	if(nmlen+2 > sizeof(wc))
2491 		return NULL; /* result would be too long */
2492 	wc[0] = 1; /* length of wildcard label */
2493 	wc[1] = (uint8_t)'*'; /* wildcard label */
2494 	memmove(wc+2, nm, nmlen);
2495 	return az_find_name(z, wc, nmlen+2);
2496 }
2497 
2498 /** find wildcard between qname and cename */
2499 static struct auth_data*
az_find_wildcard(struct auth_zone * z,struct query_info * qinfo,struct auth_data * ce)2500 az_find_wildcard(struct auth_zone* z, struct query_info* qinfo,
2501 	struct auth_data* ce)
2502 {
2503 	uint8_t* nm = qinfo->qname;
2504 	size_t nmlen = qinfo->qname_len;
2505 	struct auth_data* node;
2506 	if(!dname_subdomain_c(nm, z->name))
2507 		return NULL; /* out of zone */
2508 	while((node=az_find_wildcard_domain(z, nm, nmlen))==NULL) {
2509 		if(nmlen == z->namelen)
2510 			return NULL; /* top of zone reached */
2511 		if(ce && nmlen == ce->namelen)
2512 			return NULL; /* ce reached */
2513 		if(!dname_remove_label_limit_len(&nm, &nmlen, z->namelen))
2514 			return NULL; /* can't go up */
2515 	}
2516 	return node;
2517 }
2518 
2519 /** domain is not exact, find first candidate ce (name that matches
2520  * a part of qname) in tree */
2521 static struct auth_data*
az_find_candidate_ce(struct auth_zone * z,struct query_info * qinfo,struct auth_data * n)2522 az_find_candidate_ce(struct auth_zone* z, struct query_info* qinfo,
2523 	struct auth_data* n)
2524 {
2525 	uint8_t* nm;
2526 	size_t nmlen;
2527 	if(n) {
2528 		nm = dname_get_shared_topdomain(qinfo->qname, n->name);
2529 	} else {
2530 		nm = qinfo->qname;
2531 	}
2532 	dname_count_size_labels(nm, &nmlen);
2533 	n = az_find_name(z, nm, nmlen);
2534 	/* delete labels and go up on name */
2535 	while(!n) {
2536 		if(!dname_remove_label_limit_len(&nm, &nmlen, z->namelen))
2537 			return NULL; /* can't go up */
2538 		n = az_find_name(z, nm, nmlen);
2539 	}
2540 	return n;
2541 }
2542 
2543 /** go up the auth tree to next existing name. */
2544 static struct auth_data*
az_domain_go_up(struct auth_zone * z,struct auth_data * n)2545 az_domain_go_up(struct auth_zone* z, struct auth_data* n)
2546 {
2547 	uint8_t* nm = n->name;
2548 	size_t nmlen = n->namelen;
2549 	while(dname_remove_label_limit_len(&nm, &nmlen, z->namelen)) {
2550 		if((n=az_find_name(z, nm, nmlen)) != NULL)
2551 			return n;
2552 	}
2553 	return NULL;
2554 }
2555 
2556 /** Find the closest encloser, an name that exists and is above the
2557  * qname.
2558  * return true if the node (param node) is existing, nonobscured and
2559  * 	can be used to generate answers from.  It is then also node_exact.
2560  * returns false if the node is not good enough (or it wasn't node_exact)
2561  *	in this case the ce can be filled.
2562  *	if ce is NULL, no ce exists, and likely the zone is completely empty,
2563  *	not even with a zone apex.
2564  *	if ce is nonNULL it is the closest enclosing upper name (that exists
2565  *	itself for answer purposes).  That name may have DNAME, NS or wildcard
2566  *	rrset is the closest DNAME or NS rrset that was found.
2567  */
2568 static int
az_find_ce(struct auth_zone * z,struct query_info * qinfo,struct auth_data * node,int node_exact,struct auth_data ** ce,struct auth_rrset ** rrset)2569 az_find_ce(struct auth_zone* z, struct query_info* qinfo,
2570 	struct auth_data* node, int node_exact, struct auth_data** ce,
2571 	struct auth_rrset** rrset)
2572 {
2573 	struct auth_data* n = node;
2574 	struct auth_rrset* lookrrset;
2575 	*ce = NULL;
2576 	*rrset = NULL;
2577 	if(!node_exact) {
2578 		/* if not exact, lookup closest exact match */
2579 		n = az_find_candidate_ce(z, qinfo, n);
2580 	} else {
2581 		/* if exact, the node itself is the first candidate ce */
2582 		*ce = n;
2583 	}
2584 
2585 	/* no direct answer from nsec3-only domains */
2586 	if(n && domain_has_only_nsec3(n)) {
2587 		node_exact = 0;
2588 		*ce = NULL;
2589 	}
2590 
2591 	/* with exact matches, walk up the labels until we find the
2592 	 * delegation, or DNAME or zone end */
2593 	while(n) {
2594 		/* see if the current candidate has issues */
2595 		/* not zone apex and has type NS */
2596 		if(n->namelen != z->namelen &&
2597 			(lookrrset=az_domain_rrset(n, LDNS_RR_TYPE_NS)) &&
2598 			/* delegate here, but DS at exact the dp has notype */
2599 			(qinfo->qtype != LDNS_RR_TYPE_DS ||
2600 			n->namelen != qinfo->qname_len)) {
2601 			/* referral */
2602 			/* this is ce and the lowernode is nonexisting */
2603 			*ce = n;
2604 			*rrset = lookrrset;
2605 			node_exact = 0;
2606 		}
2607 		/* not equal to qname and has type DNAME */
2608 		if(n->namelen != qinfo->qname_len &&
2609 			(lookrrset=az_domain_rrset(n, LDNS_RR_TYPE_DNAME))) {
2610 			/* this is ce and the lowernode is nonexisting */
2611 			*ce = n;
2612 			*rrset = lookrrset;
2613 			node_exact = 0;
2614 		}
2615 
2616 		if(*ce == NULL && !domain_has_only_nsec3(n)) {
2617 			/* if not found yet, this exact name must be
2618 			 * our lowest match (but not nsec3onlydomain) */
2619 			*ce = n;
2620 		}
2621 
2622 		/* walk up the tree by removing labels from name and lookup */
2623 		n = az_domain_go_up(z, n);
2624 	}
2625 	/* found no problems, if it was an exact node, it is fine to use */
2626 	return node_exact;
2627 }
2628 
2629 /** add additional A/AAAA from domain names in rrset rdata (+offset)
2630  * offset is number of bytes in rdata where the dname is located. */
2631 static int
az_add_additionals_from(struct auth_zone * z,struct regional * region,struct dns_msg * msg,struct auth_rrset * rrset,size_t offset)2632 az_add_additionals_from(struct auth_zone* z, struct regional* region,
2633 	struct dns_msg* msg, struct auth_rrset* rrset, size_t offset)
2634 {
2635 	struct packed_rrset_data* d = rrset->data;
2636 	size_t i;
2637 	if(!d) return 0;
2638 	for(i=0; i<d->count; i++) {
2639 		size_t dlen;
2640 		struct auth_data* domain;
2641 		struct auth_rrset* ref;
2642 		if(d->rr_len[i] < 2+offset)
2643 			continue; /* too short */
2644 		if(!(dlen = dname_valid(d->rr_data[i]+2+offset,
2645 			d->rr_len[i]-2-offset)))
2646 			continue; /* malformed */
2647 		domain = az_find_name(z, d->rr_data[i]+2+offset, dlen);
2648 		if(!domain)
2649 			continue;
2650 		if((ref=az_domain_rrset(domain, LDNS_RR_TYPE_A)) != NULL) {
2651 			if(!msg_add_rrset_ar(z, region, msg, domain, ref))
2652 				return 0;
2653 		}
2654 		if((ref=az_domain_rrset(domain, LDNS_RR_TYPE_AAAA)) != NULL) {
2655 			if(!msg_add_rrset_ar(z, region, msg, domain, ref))
2656 				return 0;
2657 		}
2658 	}
2659 	return 1;
2660 }
2661 
2662 /** add negative SOA record (with negative TTL) */
2663 static int
az_add_negative_soa(struct auth_zone * z,struct regional * region,struct dns_msg * msg)2664 az_add_negative_soa(struct auth_zone* z, struct regional* region,
2665 	struct dns_msg* msg)
2666 {
2667 	time_t minimum;
2668 	size_t i;
2669 	struct packed_rrset_data* d;
2670 	struct auth_rrset* soa;
2671 	struct auth_data* apex = az_find_name(z, z->name, z->namelen);
2672 	if(!apex) return 0;
2673 	soa = az_domain_rrset(apex, LDNS_RR_TYPE_SOA);
2674 	if(!soa) return 0;
2675 	/* must be first to put in message; we want to fix the TTL with
2676 	 * one RRset here, otherwise we'd need to loop over the RRs to get
2677 	 * the resulting lower TTL */
2678 	log_assert(msg->rep->rrset_count == 0);
2679 	if(!msg_add_rrset_ns(z, region, msg, apex, soa)) return 0;
2680 	/* fixup TTL */
2681 	d = (struct packed_rrset_data*)msg->rep->rrsets[msg->rep->rrset_count-1]->entry.data;
2682 	/* last 4 bytes are minimum ttl in network format */
2683 	if(d->count == 0) return 0;
2684 	if(d->rr_len[0] < 2+4) return 0;
2685 	minimum = (time_t)sldns_read_uint32(d->rr_data[0]+(d->rr_len[0]-4));
2686 	minimum = d->ttl<minimum?d->ttl:minimum;
2687 	d->ttl = minimum;
2688 	for(i=0; i < d->count + d->rrsig_count; i++)
2689 		d->rr_ttl[i] = minimum;
2690 	msg->rep->ttl = get_rrset_ttl(msg->rep->rrsets[0]);
2691 	msg->rep->prefetch_ttl = PREFETCH_TTL_CALC(msg->rep->ttl);
2692 	msg->rep->serve_expired_ttl = msg->rep->ttl + SERVE_EXPIRED_TTL;
2693 	return 1;
2694 }
2695 
2696 /** See if the query goes to empty nonterminal (that has no auth_data,
2697  * but there are nodes underneath.  We already checked that there are
2698  * not NS, or DNAME above, so that we only need to check if some node
2699  * exists below (with nonempty rr list), return true if emptynonterminal */
2700 static int
az_empty_nonterminal(struct auth_zone * z,struct query_info * qinfo,struct auth_data * node)2701 az_empty_nonterminal(struct auth_zone* z, struct query_info* qinfo,
2702 	struct auth_data* node)
2703 {
2704 	struct auth_data* next;
2705 	if(!node) {
2706 		/* no smaller was found, use first (smallest) node as the
2707 		 * next one */
2708 		next = (struct auth_data*)rbtree_first(&z->data);
2709 	} else {
2710 		next = (struct auth_data*)rbtree_next(&node->node);
2711 	}
2712 	while(next && (rbnode_type*)next != RBTREE_NULL && next->rrsets == NULL) {
2713 		/* the next name has empty rrsets, is an empty nonterminal
2714 		 * itself, see if there exists something below it */
2715 		next = (struct auth_data*)rbtree_next(&next->node);
2716 	}
2717 	if((rbnode_type*)next == RBTREE_NULL || !next) {
2718 		/* there is no next node, so something below it cannot
2719 		 * exist */
2720 		return 0;
2721 	}
2722 	/* a next node exists, if there was something below the query,
2723 	 * this node has to be it.  See if it is below the query name */
2724 	if(dname_strict_subdomain_c(next->name, qinfo->qname))
2725 		return 1;
2726 	return 0;
2727 }
2728 
2729 /** create synth cname target name in buffer, or fail if too long */
2730 static size_t
synth_cname_buf(uint8_t * qname,size_t qname_len,size_t dname_len,uint8_t * dtarg,size_t dtarglen,uint8_t * buf,size_t buflen)2731 synth_cname_buf(uint8_t* qname, size_t qname_len, size_t dname_len,
2732 	uint8_t* dtarg, size_t dtarglen, uint8_t* buf, size_t buflen)
2733 {
2734 	size_t newlen = qname_len + dtarglen - dname_len;
2735 	if(newlen > buflen) {
2736 		/* YXDOMAIN error */
2737 		return 0;
2738 	}
2739 	/* new name is concatenation of qname front (without DNAME owner)
2740 	 * and DNAME target name */
2741 	memcpy(buf, qname, qname_len-dname_len);
2742 	memmove(buf+(qname_len-dname_len), dtarg, dtarglen);
2743 	return newlen;
2744 }
2745 
2746 /** create synthetic CNAME rrset for in a DNAME answer in region,
2747  * false on alloc failure, cname==NULL when name too long. */
2748 static int
create_synth_cname(uint8_t * qname,size_t qname_len,struct regional * region,struct auth_data * node,struct auth_rrset * dname,uint16_t dclass,struct ub_packed_rrset_key ** cname)2749 create_synth_cname(uint8_t* qname, size_t qname_len, struct regional* region,
2750 	struct auth_data* node, struct auth_rrset* dname, uint16_t dclass,
2751 	struct ub_packed_rrset_key** cname)
2752 {
2753 	uint8_t buf[LDNS_MAX_DOMAINLEN];
2754 	uint8_t* dtarg;
2755 	size_t dtarglen, newlen;
2756 	struct packed_rrset_data* d;
2757 
2758 	/* get DNAME target name */
2759 	if(dname->data->count < 1) return 0;
2760 	if(dname->data->rr_len[0] < 3) return 0; /* at least rdatalen +1 */
2761 	dtarg = dname->data->rr_data[0]+2;
2762 	dtarglen = dname->data->rr_len[0]-2;
2763 	if(sldns_read_uint16(dname->data->rr_data[0]) != dtarglen)
2764 		return 0; /* rdatalen in DNAME rdata is malformed */
2765 	if(dname_valid(dtarg, dtarglen) != dtarglen)
2766 		return 0; /* DNAME RR has malformed rdata */
2767 	if(qname_len == 0)
2768 		return 0; /* too short */
2769 	if(qname_len <= node->namelen)
2770 		return 0; /* qname too short for dname removal */
2771 
2772 	/* synthesize a CNAME */
2773 	newlen = synth_cname_buf(qname, qname_len, node->namelen,
2774 		dtarg, dtarglen, buf, sizeof(buf));
2775 	if(newlen == 0) {
2776 		/* YXDOMAIN error */
2777 		*cname = NULL;
2778 		return 1;
2779 	}
2780 	*cname = (struct ub_packed_rrset_key*)regional_alloc(region,
2781 		sizeof(struct ub_packed_rrset_key));
2782 	if(!*cname)
2783 		return 0; /* out of memory */
2784 	memset(&(*cname)->entry, 0, sizeof((*cname)->entry));
2785 	(*cname)->entry.key = (*cname);
2786 	(*cname)->rk.type = htons(LDNS_RR_TYPE_CNAME);
2787 	(*cname)->rk.rrset_class = htons(dclass);
2788 	(*cname)->rk.flags = 0;
2789 	(*cname)->rk.dname = regional_alloc_init(region, qname, qname_len);
2790 	if(!(*cname)->rk.dname)
2791 		return 0; /* out of memory */
2792 	(*cname)->rk.dname_len = qname_len;
2793 	(*cname)->entry.hash = rrset_key_hash(&(*cname)->rk);
2794 	d = (struct packed_rrset_data*)regional_alloc_zero(region,
2795 		sizeof(struct packed_rrset_data) + sizeof(size_t) +
2796 		sizeof(uint8_t*) + sizeof(time_t) + sizeof(uint16_t)
2797 		+ newlen);
2798 	if(!d)
2799 		return 0; /* out of memory */
2800 	(*cname)->entry.data = d;
2801 	d->ttl = dname->data->ttl; /* RFC6672: synth CNAME TTL == DNAME TTL */
2802 	d->count = 1;
2803 	d->rrsig_count = 0;
2804 	d->trust = rrset_trust_ans_noAA;
2805 	d->rr_len = (size_t*)((uint8_t*)d +
2806 		sizeof(struct packed_rrset_data));
2807 	d->rr_len[0] = newlen + sizeof(uint16_t);
2808 	packed_rrset_ptr_fixup(d);
2809 	d->rr_ttl[0] = d->ttl;
2810 	sldns_write_uint16(d->rr_data[0], newlen);
2811 	memmove(d->rr_data[0] + sizeof(uint16_t), buf, newlen);
2812 	return 1;
2813 }
2814 
2815 /** add a synthesized CNAME to the answer section */
2816 static int
add_synth_cname(struct auth_zone * z,uint8_t * qname,size_t qname_len,struct regional * region,struct dns_msg * msg,struct auth_data * dname,struct auth_rrset * rrset)2817 add_synth_cname(struct auth_zone* z, uint8_t* qname, size_t qname_len,
2818 	struct regional* region, struct dns_msg* msg, struct auth_data* dname,
2819 	struct auth_rrset* rrset)
2820 {
2821 	struct ub_packed_rrset_key* cname;
2822 	/* synthesize a CNAME */
2823 	if(!create_synth_cname(qname, qname_len, region, dname, rrset,
2824 		z->dclass, &cname)) {
2825 		/* out of memory */
2826 		return 0;
2827 	}
2828 	if(!cname) {
2829 		/* cname cannot be create because of YXDOMAIN */
2830 		msg->rep->flags |= LDNS_RCODE_YXDOMAIN;
2831 		return 1;
2832 	}
2833 	/* add cname to message */
2834 	if(!msg_grow_array(region, msg))
2835 		return 0;
2836 	msg->rep->rrsets[msg->rep->rrset_count] = cname;
2837 	msg->rep->rrset_count++;
2838 	msg->rep->an_numrrsets++;
2839 	msg_ttl(msg);
2840 	return 1;
2841 }
2842 
2843 /** Change a dname to a different one, for wildcard namechange */
2844 static void
az_change_dnames(struct dns_msg * msg,uint8_t * oldname,uint8_t * newname,size_t newlen,int an_only)2845 az_change_dnames(struct dns_msg* msg, uint8_t* oldname, uint8_t* newname,
2846 	size_t newlen, int an_only)
2847 {
2848 	size_t i;
2849 	size_t start = 0, end = msg->rep->rrset_count;
2850 	if(!an_only) start = msg->rep->an_numrrsets;
2851 	if(an_only) end = msg->rep->an_numrrsets;
2852 	for(i=start; i<end; i++) {
2853 		/* allocated in region so we can change the ptrs */
2854 		if(query_dname_compare(msg->rep->rrsets[i]->rk.dname, oldname)
2855 			== 0) {
2856 			msg->rep->rrsets[i]->rk.dname = newname;
2857 			msg->rep->rrsets[i]->rk.dname_len = newlen;
2858 			msg->rep->rrsets[i]->entry.hash = rrset_key_hash(&msg->rep->rrsets[i]->rk);
2859 		}
2860 	}
2861 }
2862 
2863 /** find NSEC record covering the query, with the given node in the zone */
2864 static struct auth_rrset*
az_find_nsec_cover(struct auth_zone * z,struct auth_data ** node)2865 az_find_nsec_cover(struct auth_zone* z, struct auth_data** node)
2866 {
2867 	uint8_t* nm;
2868 	size_t nmlen;
2869 	struct auth_rrset* rrset;
2870 	log_assert(*node); /* we already have a node when calling this */
2871 	nm = (*node)->name;
2872 	nmlen = (*node)->namelen;
2873 	/* find the NSEC for the smallest-or-equal node */
2874 	/* But there could be glue, and then it has no NSEC.
2875 	 * Go up to find nonglue (previous) NSEC-holding nodes */
2876 	while((rrset=az_domain_rrset(*node, LDNS_RR_TYPE_NSEC)) == NULL) {
2877 		if(nmlen == z->namelen) return NULL;
2878 		if(!dname_remove_label_limit_len(&nm, &nmlen, z->namelen))
2879 			return NULL; /* can't go up */
2880 		/* adjust *node for the nsec rrset to find in */
2881 		*node = az_find_name(z, nm, nmlen);
2882 	}
2883 	return rrset;
2884 }
2885 
2886 /** Find NSEC and add for wildcard denial */
2887 static int
az_nsec_wildcard_denial(struct auth_zone * z,struct regional * region,struct dns_msg * msg,uint8_t * cenm,size_t cenmlen)2888 az_nsec_wildcard_denial(struct auth_zone* z, struct regional* region,
2889 	struct dns_msg* msg, uint8_t* cenm, size_t cenmlen)
2890 {
2891 	struct query_info qinfo;
2892 	int node_exact;
2893 	struct auth_data* node;
2894 	struct auth_rrset* nsec;
2895 	uint8_t wc[LDNS_MAX_DOMAINLEN];
2896 	if(cenmlen+2 > sizeof(wc))
2897 		return 0; /* result would be too long */
2898 	wc[0] = 1; /* length of wildcard label */
2899 	wc[1] = (uint8_t)'*'; /* wildcard label */
2900 	memmove(wc+2, cenm, cenmlen);
2901 
2902 	/* we have '*.ce' in wc wildcard name buffer */
2903 	/* get nsec cover for that */
2904 	qinfo.qname = wc;
2905 	qinfo.qname_len = cenmlen+2;
2906 	qinfo.qtype = 0;
2907 	qinfo.qclass = 0;
2908 	az_find_domain(z, &qinfo, &node_exact, &node);
2909 	if((nsec=az_find_nsec_cover(z, &node)) != NULL) {
2910 		if(!msg_add_rrset_ns(z, region, msg, node, nsec)) return 0;
2911 	}
2912 	return 1;
2913 }
2914 
2915 /** Find the NSEC3PARAM rrset (if any) and if true you have the parameters */
2916 static int
az_nsec3_param(struct auth_zone * z,int * algo,size_t * iter,uint8_t ** salt,size_t * saltlen)2917 az_nsec3_param(struct auth_zone* z, int* algo, size_t* iter, uint8_t** salt,
2918 	size_t* saltlen)
2919 {
2920 	struct auth_data* apex;
2921 	struct auth_rrset* param;
2922 	size_t i;
2923 	apex = az_find_name(z, z->name, z->namelen);
2924 	if(!apex) return 0;
2925 	param = az_domain_rrset(apex, LDNS_RR_TYPE_NSEC3PARAM);
2926 	if(!param || param->data->count==0)
2927 		return 0; /* no RRset or no RRs in rrset */
2928 	/* find out which NSEC3PARAM RR has supported parameters */
2929 	/* skip unknown flags (dynamic signer is recalculating nsec3 chain) */
2930 	for(i=0; i<param->data->count; i++) {
2931 		uint8_t* rdata = param->data->rr_data[i]+2;
2932 		size_t rdatalen = param->data->rr_len[i];
2933 		if(rdatalen < 2+5)
2934 			continue; /* too short */
2935 		if(!nsec3_hash_algo_size_supported((int)(rdata[0])))
2936 			continue; /* unsupported algo */
2937 		if(rdatalen < (size_t)(2+5+(size_t)rdata[4]))
2938 			continue; /* salt missing */
2939 		if((rdata[1]&NSEC3_UNKNOWN_FLAGS)!=0)
2940 			continue; /* unknown flags */
2941 		*algo = (int)(rdata[0]);
2942 		*iter = sldns_read_uint16(rdata+2);
2943 		*saltlen = rdata[4];
2944 		if(*saltlen == 0)
2945 			*salt = NULL;
2946 		else	*salt = rdata+5;
2947 		return 1;
2948 	}
2949 	/* no supported params */
2950 	return 0;
2951 }
2952 
2953 /** Hash a name with nsec3param into buffer, it has zone name appended.
2954  * return length of hash */
2955 static size_t
az_nsec3_hash(uint8_t * buf,size_t buflen,uint8_t * nm,size_t nmlen,int algo,size_t iter,uint8_t * salt,size_t saltlen)2956 az_nsec3_hash(uint8_t* buf, size_t buflen, uint8_t* nm, size_t nmlen,
2957 	int algo, size_t iter, uint8_t* salt, size_t saltlen)
2958 {
2959 	size_t hlen = nsec3_hash_algo_size_supported(algo);
2960 	/* buffer has domain name, nsec3hash, and 256 is for max saltlen
2961 	 * (salt has 0-255 length) */
2962 	unsigned char p[LDNS_MAX_DOMAINLEN+1+N3HASHBUFLEN+256];
2963 	size_t i;
2964 	if(nmlen+saltlen > sizeof(p) || hlen+saltlen > sizeof(p))
2965 		return 0;
2966 	if(hlen > buflen)
2967 		return 0; /* somehow too large for destination buffer */
2968 	/* hashfunc(name, salt) */
2969 	memmove(p, nm, nmlen);
2970 	query_dname_tolower(p);
2971 	if(salt && saltlen > 0)
2972 		memmove(p+nmlen, salt, saltlen);
2973 	(void)secalgo_nsec3_hash(algo, p, nmlen+saltlen, (unsigned char*)buf);
2974 	for(i=0; i<iter; i++) {
2975 		/* hashfunc(hash, salt) */
2976 		memmove(p, buf, hlen);
2977 		if(salt && saltlen > 0)
2978 			memmove(p+hlen, salt, saltlen);
2979 		(void)secalgo_nsec3_hash(algo, p, hlen+saltlen,
2980 			(unsigned char*)buf);
2981 	}
2982 	return hlen;
2983 }
2984 
2985 /** Hash name and return b32encoded hashname for lookup, zone name appended */
2986 static int
az_nsec3_hashname(struct auth_zone * z,uint8_t * hashname,size_t * hashnmlen,uint8_t * nm,size_t nmlen,int algo,size_t iter,uint8_t * salt,size_t saltlen)2987 az_nsec3_hashname(struct auth_zone* z, uint8_t* hashname, size_t* hashnmlen,
2988 	uint8_t* nm, size_t nmlen, int algo, size_t iter, uint8_t* salt,
2989 	size_t saltlen)
2990 {
2991 	uint8_t hash[N3HASHBUFLEN];
2992 	size_t hlen;
2993 	int ret;
2994 	hlen = az_nsec3_hash(hash, sizeof(hash), nm, nmlen, algo, iter,
2995 		salt, saltlen);
2996 	if(!hlen) return 0;
2997 	/* b32 encode */
2998 	if(*hashnmlen < hlen*2+1+z->namelen) /* approx b32 as hexb16 */
2999 		return 0;
3000 	ret = sldns_b32_ntop_extended_hex(hash, hlen, (char*)(hashname+1),
3001 		(*hashnmlen)-1);
3002 	if(ret<1)
3003 		return 0;
3004 	hashname[0] = (uint8_t)ret;
3005 	ret++;
3006 	if((*hashnmlen) - ret < z->namelen)
3007 		return 0;
3008 	memmove(hashname+ret, z->name, z->namelen);
3009 	*hashnmlen = z->namelen+(size_t)ret;
3010 	return 1;
3011 }
3012 
3013 /** Find the datanode that covers the nsec3hash-name */
3014 static struct auth_data*
az_nsec3_findnode(struct auth_zone * z,uint8_t * hashnm,size_t hashnmlen)3015 az_nsec3_findnode(struct auth_zone* z, uint8_t* hashnm, size_t hashnmlen)
3016 {
3017 	struct query_info qinfo;
3018 	struct auth_data* node;
3019 	int node_exact;
3020 	qinfo.qclass = 0;
3021 	qinfo.qtype = 0;
3022 	qinfo.qname = hashnm;
3023 	qinfo.qname_len = hashnmlen;
3024 	/* because canonical ordering and b32 nsec3 ordering are the same.
3025 	 * this is a good lookup to find the nsec3 name. */
3026 	az_find_domain(z, &qinfo, &node_exact, &node);
3027 	/* but we may have to skip non-nsec3 nodes */
3028 	/* this may be a lot, the way to speed that up is to have a
3029 	 * separate nsec3 tree with nsec3 nodes */
3030 	while(node && (rbnode_type*)node != RBTREE_NULL &&
3031 		!az_domain_rrset(node, LDNS_RR_TYPE_NSEC3)) {
3032 		node = (struct auth_data*)rbtree_previous(&node->node);
3033 	}
3034 	if((rbnode_type*)node == RBTREE_NULL)
3035 		node = NULL;
3036 	return node;
3037 }
3038 
3039 /** Find cover for hashed(nm, nmlen) (or NULL) */
3040 static struct auth_data*
az_nsec3_find_cover(struct auth_zone * z,uint8_t * nm,size_t nmlen,int algo,size_t iter,uint8_t * salt,size_t saltlen)3041 az_nsec3_find_cover(struct auth_zone* z, uint8_t* nm, size_t nmlen,
3042 	int algo, size_t iter, uint8_t* salt, size_t saltlen)
3043 {
3044 	struct auth_data* node;
3045 	uint8_t hname[LDNS_MAX_DOMAINLEN];
3046 	size_t hlen = sizeof(hname);
3047 	if(!az_nsec3_hashname(z, hname, &hlen, nm, nmlen, algo, iter,
3048 		salt, saltlen))
3049 		return NULL;
3050 	node = az_nsec3_findnode(z, hname, hlen);
3051 	if(node)
3052 		return node;
3053 	/* we did not find any, perhaps because the NSEC3 hash is before
3054 	 * the first hash, we have to find the 'last hash' in the zone */
3055 	node = (struct auth_data*)rbtree_last(&z->data);
3056 	while(node && (rbnode_type*)node != RBTREE_NULL &&
3057 		!az_domain_rrset(node, LDNS_RR_TYPE_NSEC3)) {
3058 		node = (struct auth_data*)rbtree_previous(&node->node);
3059 	}
3060 	if((rbnode_type*)node == RBTREE_NULL)
3061 		node = NULL;
3062 	return node;
3063 }
3064 
3065 /** Find exact match for hashed(nm, nmlen) NSEC3 record or NULL */
3066 static struct auth_data*
az_nsec3_find_exact(struct auth_zone * z,uint8_t * nm,size_t nmlen,int algo,size_t iter,uint8_t * salt,size_t saltlen)3067 az_nsec3_find_exact(struct auth_zone* z, uint8_t* nm, size_t nmlen,
3068 	int algo, size_t iter, uint8_t* salt, size_t saltlen)
3069 {
3070 	struct auth_data* node;
3071 	uint8_t hname[LDNS_MAX_DOMAINLEN];
3072 	size_t hlen = sizeof(hname);
3073 	if(!az_nsec3_hashname(z, hname, &hlen, nm, nmlen, algo, iter,
3074 		salt, saltlen))
3075 		return NULL;
3076 	node = az_find_name(z, hname, hlen);
3077 	if(az_domain_rrset(node, LDNS_RR_TYPE_NSEC3))
3078 		return node;
3079 	return NULL;
3080 }
3081 
3082 /** Return nextcloser name (as a ref into the qname).  This is one label
3083  * more than the cenm (cename must be a suffix of qname) */
3084 static void
az_nsec3_get_nextcloser(uint8_t * cenm,uint8_t * qname,size_t qname_len,uint8_t ** nx,size_t * nxlen)3085 az_nsec3_get_nextcloser(uint8_t* cenm, uint8_t* qname, size_t qname_len,
3086 	uint8_t** nx, size_t* nxlen)
3087 {
3088 	int celabs = dname_count_labels(cenm);
3089 	int qlabs = dname_count_labels(qname);
3090 	int strip = qlabs - celabs -1;
3091 	log_assert(dname_strict_subdomain(qname, qlabs, cenm, celabs));
3092 	*nx = qname;
3093 	*nxlen = qname_len;
3094 	if(strip>0)
3095 		dname_remove_labels(nx, nxlen, strip);
3096 }
3097 
3098 /** Find the closest encloser that has exact NSEC3.
3099  * updated cenm to the new name. If it went up no-exact-ce is true. */
3100 static struct auth_data*
az_nsec3_find_ce(struct auth_zone * z,uint8_t ** cenm,size_t * cenmlen,int * no_exact_ce,int algo,size_t iter,uint8_t * salt,size_t saltlen)3101 az_nsec3_find_ce(struct auth_zone* z, uint8_t** cenm, size_t* cenmlen,
3102 	int* no_exact_ce, int algo, size_t iter, uint8_t* salt, size_t saltlen)
3103 {
3104 	struct auth_data* node;
3105 	while((node = az_nsec3_find_exact(z, *cenm, *cenmlen,
3106 		algo, iter, salt, saltlen)) == NULL) {
3107 		if(!dname_remove_label_limit_len(cenm, cenmlen, z->namelen))
3108 			return NULL; /* can't go up */
3109 		*no_exact_ce = 1;
3110 	}
3111 	return node;
3112 }
3113 
3114 /* Insert NSEC3 record in authority section, if NULL does nothing */
3115 static int
az_nsec3_insert(struct auth_zone * z,struct regional * region,struct dns_msg * msg,struct auth_data * node)3116 az_nsec3_insert(struct auth_zone* z, struct regional* region,
3117 	struct dns_msg* msg, struct auth_data* node)
3118 {
3119 	struct auth_rrset* nsec3;
3120 	if(!node) return 1; /* no node, skip this */
3121 	nsec3 = az_domain_rrset(node, LDNS_RR_TYPE_NSEC3);
3122 	if(!nsec3) return 1; /* if no nsec3 RR, skip it */
3123 	if(!msg_add_rrset_ns(z, region, msg, node, nsec3)) return 0;
3124 	return 1;
3125 }
3126 
3127 /** add NSEC3 records to the zone for the nsec3 proof.
3128  * Specify with the flags with parts of the proof are required.
3129  * the ce is the exact matching name (for notype) but also delegation points.
3130  * qname is the one where the nextcloser name can be derived from.
3131  * If NSEC3 is not properly there (in the zone) nothing is added.
3132  * always enabled: include nsec3 proving about the Closest Encloser.
3133  * 	that is an exact match that should exist for it.
3134  * 	If that does not exist, a higher exact match + nxproof is enabled
3135  * 	(for some sort of opt-out empty nonterminal cases).
3136  * nodataproof: search for exact match and include that instead.
3137  * ceproof: include ce proof NSEC3 (omitted for wildcard replies).
3138  * nxproof: include denial of the qname.
3139  * wcproof: include denial of wildcard (wildcard.ce).
3140  */
3141 static int
az_add_nsec3_proof(struct auth_zone * z,struct regional * region,struct dns_msg * msg,uint8_t * cenm,size_t cenmlen,uint8_t * qname,size_t qname_len,int nodataproof,int ceproof,int nxproof,int wcproof)3142 az_add_nsec3_proof(struct auth_zone* z, struct regional* region,
3143 	struct dns_msg* msg, uint8_t* cenm, size_t cenmlen, uint8_t* qname,
3144 	size_t qname_len, int nodataproof, int ceproof, int nxproof,
3145 	int wcproof)
3146 {
3147 	int algo;
3148 	size_t iter, saltlen;
3149 	uint8_t* salt;
3150 	int no_exact_ce = 0;
3151 	struct auth_data* node;
3152 
3153 	/* find parameters of nsec3 proof */
3154 	if(!az_nsec3_param(z, &algo, &iter, &salt, &saltlen))
3155 		return 1; /* no nsec3 */
3156 	if(nodataproof) {
3157 		/* see if the node has a hash of itself for the nodata
3158 		 * proof nsec3, this has to be an exact match nsec3. */
3159 		struct auth_data* match;
3160 		match = az_nsec3_find_exact(z, qname, qname_len, algo,
3161 			iter, salt, saltlen);
3162 		if(match) {
3163 			if(!az_nsec3_insert(z, region, msg, match))
3164 				return 0;
3165 			/* only nodata NSEC3 needed, no CE or others. */
3166 			return 1;
3167 		}
3168 	}
3169 	/* find ce that has an NSEC3 */
3170 	if(ceproof) {
3171 		node = az_nsec3_find_ce(z, &cenm, &cenmlen, &no_exact_ce,
3172 			algo, iter, salt, saltlen);
3173 		if(no_exact_ce) nxproof = 1;
3174 		if(!az_nsec3_insert(z, region, msg, node))
3175 			return 0;
3176 	}
3177 
3178 	if(nxproof) {
3179 		uint8_t* nx;
3180 		size_t nxlen;
3181 		/* create nextcloser domain name */
3182 		az_nsec3_get_nextcloser(cenm, qname, qname_len, &nx, &nxlen);
3183 		/* find nsec3 that matches or covers it */
3184 		node = az_nsec3_find_cover(z, nx, nxlen, algo, iter, salt,
3185 			saltlen);
3186 		if(!az_nsec3_insert(z, region, msg, node))
3187 			return 0;
3188 	}
3189 	if(wcproof) {
3190 		/* create wildcard name *.ce */
3191 		uint8_t wc[LDNS_MAX_DOMAINLEN];
3192 		size_t wclen;
3193 		if(cenmlen+2 > sizeof(wc))
3194 			return 0; /* result would be too long */
3195 		wc[0] = 1; /* length of wildcard label */
3196 		wc[1] = (uint8_t)'*'; /* wildcard label */
3197 		memmove(wc+2, cenm, cenmlen);
3198 		wclen = cenmlen+2;
3199 		/* find nsec3 that matches or covers it */
3200 		node = az_nsec3_find_cover(z, wc, wclen, algo, iter, salt,
3201 			saltlen);
3202 		if(!az_nsec3_insert(z, region, msg, node))
3203 			return 0;
3204 	}
3205 	return 1;
3206 }
3207 
3208 /** generate answer for positive answer */
3209 static int
az_generate_positive_answer(struct auth_zone * z,struct regional * region,struct dns_msg * msg,struct auth_data * node,struct auth_rrset * rrset)3210 az_generate_positive_answer(struct auth_zone* z, struct regional* region,
3211 	struct dns_msg* msg, struct auth_data* node, struct auth_rrset* rrset)
3212 {
3213 	if(!msg_add_rrset_an(z, region, msg, node, rrset)) return 0;
3214 	/* see if we want additional rrs */
3215 	if(rrset->type == LDNS_RR_TYPE_MX) {
3216 		if(!az_add_additionals_from(z, region, msg, rrset, 2))
3217 			return 0;
3218 	} else if(rrset->type == LDNS_RR_TYPE_SRV) {
3219 		if(!az_add_additionals_from(z, region, msg, rrset, 6))
3220 			return 0;
3221 	} else if(rrset->type == LDNS_RR_TYPE_NS) {
3222 		if(!az_add_additionals_from(z, region, msg, rrset, 0))
3223 			return 0;
3224 	}
3225 	return 1;
3226 }
3227 
3228 /** generate answer for type ANY answer */
3229 static int
az_generate_any_answer(struct auth_zone * z,struct regional * region,struct dns_msg * msg,struct auth_data * node)3230 az_generate_any_answer(struct auth_zone* z, struct regional* region,
3231 	struct dns_msg* msg, struct auth_data* node)
3232 {
3233 	struct auth_rrset* rrset;
3234 	int added = 0;
3235 	/* add a couple (at least one) RRs */
3236 	if((rrset=az_domain_rrset(node, LDNS_RR_TYPE_SOA)) != NULL) {
3237 		if(!msg_add_rrset_an(z, region, msg, node, rrset)) return 0;
3238 		added++;
3239 	}
3240 	if((rrset=az_domain_rrset(node, LDNS_RR_TYPE_MX)) != NULL) {
3241 		if(!msg_add_rrset_an(z, region, msg, node, rrset)) return 0;
3242 		added++;
3243 	}
3244 	if((rrset=az_domain_rrset(node, LDNS_RR_TYPE_A)) != NULL) {
3245 		if(!msg_add_rrset_an(z, region, msg, node, rrset)) return 0;
3246 		added++;
3247 	}
3248 	if((rrset=az_domain_rrset(node, LDNS_RR_TYPE_AAAA)) != NULL) {
3249 		if(!msg_add_rrset_an(z, region, msg, node, rrset)) return 0;
3250 		added++;
3251 	}
3252 	if(added == 0 && node && node->rrsets) {
3253 		if(!msg_add_rrset_an(z, region, msg, node,
3254 			node->rrsets)) return 0;
3255 	}
3256 	return 1;
3257 }
3258 
3259 /** follow cname chain and add more data to the answer section */
3260 static int
follow_cname_chain(struct auth_zone * z,uint16_t qtype,struct regional * region,struct dns_msg * msg,struct packed_rrset_data * d)3261 follow_cname_chain(struct auth_zone* z, uint16_t qtype,
3262 	struct regional* region, struct dns_msg* msg,
3263 	struct packed_rrset_data* d)
3264 {
3265 	int maxchain = 0;
3266 	/* see if we can add the target of the CNAME into the answer */
3267 	while(maxchain++ < MAX_CNAME_CHAIN) {
3268 		struct auth_data* node;
3269 		struct auth_rrset* rrset;
3270 		size_t clen;
3271 		/* d has cname rdata */
3272 		if(d->count == 0) break; /* no CNAME */
3273 		if(d->rr_len[0] < 2+1) break; /* too small */
3274 		if((clen=dname_valid(d->rr_data[0]+2, d->rr_len[0]-2))==0)
3275 			break; /* malformed */
3276 		if(!dname_subdomain_c(d->rr_data[0]+2, z->name))
3277 			break; /* target out of zone */
3278 		if((node = az_find_name(z, d->rr_data[0]+2, clen))==NULL)
3279 			break; /* no such target name */
3280 		if((rrset=az_domain_rrset(node, qtype))!=NULL) {
3281 			/* done we found the target */
3282 			if(!msg_add_rrset_an(z, region, msg, node, rrset))
3283 				return 0;
3284 			break;
3285 		}
3286 		if((rrset=az_domain_rrset(node, LDNS_RR_TYPE_CNAME))==NULL)
3287 			break; /* no further CNAME chain, notype */
3288 		if(!msg_add_rrset_an(z, region, msg, node, rrset)) return 0;
3289 		d = rrset->data;
3290 	}
3291 	return 1;
3292 }
3293 
3294 /** generate answer for cname answer */
3295 static int
az_generate_cname_answer(struct auth_zone * z,struct query_info * qinfo,struct regional * region,struct dns_msg * msg,struct auth_data * node,struct auth_rrset * rrset)3296 az_generate_cname_answer(struct auth_zone* z, struct query_info* qinfo,
3297 	struct regional* region, struct dns_msg* msg,
3298 	struct auth_data* node, struct auth_rrset* rrset)
3299 {
3300 	if(!msg_add_rrset_an(z, region, msg, node, rrset)) return 0;
3301 	if(!rrset) return 1;
3302 	if(!follow_cname_chain(z, qinfo->qtype, region, msg, rrset->data))
3303 		return 0;
3304 	return 1;
3305 }
3306 
3307 /** generate answer for notype answer */
3308 static int
az_generate_notype_answer(struct auth_zone * z,struct regional * region,struct dns_msg * msg,struct auth_data * node)3309 az_generate_notype_answer(struct auth_zone* z, struct regional* region,
3310 	struct dns_msg* msg, struct auth_data* node)
3311 {
3312 	struct auth_rrset* rrset;
3313 	if(!az_add_negative_soa(z, region, msg)) return 0;
3314 	/* DNSSEC denial NSEC */
3315 	if((rrset=az_domain_rrset(node, LDNS_RR_TYPE_NSEC))!=NULL) {
3316 		if(!msg_add_rrset_ns(z, region, msg, node, rrset)) return 0;
3317 	} else if(node) {
3318 		/* DNSSEC denial NSEC3 */
3319 		if(!az_add_nsec3_proof(z, region, msg, node->name,
3320 			node->namelen, msg->qinfo.qname,
3321 			msg->qinfo.qname_len, 1, 1, 0, 0))
3322 			return 0;
3323 	}
3324 	return 1;
3325 }
3326 
3327 /** generate answer for referral answer */
3328 static int
az_generate_referral_answer(struct auth_zone * z,struct regional * region,struct dns_msg * msg,struct auth_data * ce,struct auth_rrset * rrset)3329 az_generate_referral_answer(struct auth_zone* z, struct regional* region,
3330 	struct dns_msg* msg, struct auth_data* ce, struct auth_rrset* rrset)
3331 {
3332 	struct auth_rrset* ds, *nsec;
3333 	/* turn off AA flag, referral is nonAA because it leaves the zone */
3334 	log_assert(ce);
3335 	msg->rep->flags &= ~BIT_AA;
3336 	if(!msg_add_rrset_ns(z, region, msg, ce, rrset)) return 0;
3337 	/* add DS or deny it */
3338 	if((ds=az_domain_rrset(ce, LDNS_RR_TYPE_DS))!=NULL) {
3339 		if(!msg_add_rrset_ns(z, region, msg, ce, ds)) return 0;
3340 	} else {
3341 		/* deny the DS */
3342 		if((nsec=az_domain_rrset(ce, LDNS_RR_TYPE_NSEC))!=NULL) {
3343 			if(!msg_add_rrset_ns(z, region, msg, ce, nsec))
3344 				return 0;
3345 		} else {
3346 			if(!az_add_nsec3_proof(z, region, msg, ce->name,
3347 				ce->namelen, msg->qinfo.qname,
3348 				msg->qinfo.qname_len, 1, 1, 0, 0))
3349 				return 0;
3350 		}
3351 	}
3352 	/* add additional rrs for type NS */
3353 	if(!az_add_additionals_from(z, region, msg, rrset, 0)) return 0;
3354 	return 1;
3355 }
3356 
3357 /** generate answer for DNAME answer */
3358 static int
az_generate_dname_answer(struct auth_zone * z,struct query_info * qinfo,struct regional * region,struct dns_msg * msg,struct auth_data * ce,struct auth_rrset * rrset)3359 az_generate_dname_answer(struct auth_zone* z, struct query_info* qinfo,
3360 	struct regional* region, struct dns_msg* msg, struct auth_data* ce,
3361 	struct auth_rrset* rrset)
3362 {
3363 	log_assert(ce);
3364 	/* add the DNAME and then a CNAME */
3365 	if(!msg_add_rrset_an(z, region, msg, ce, rrset)) return 0;
3366 	if(!add_synth_cname(z, qinfo->qname, qinfo->qname_len, region,
3367 		msg, ce, rrset)) return 0;
3368 	if(FLAGS_GET_RCODE(msg->rep->flags) == LDNS_RCODE_YXDOMAIN)
3369 		return 1;
3370 	if(msg->rep->rrset_count == 0 ||
3371 		!msg->rep->rrsets[msg->rep->rrset_count-1])
3372 		return 0;
3373 	if(!follow_cname_chain(z, qinfo->qtype, region, msg,
3374 		(struct packed_rrset_data*)msg->rep->rrsets[
3375 		msg->rep->rrset_count-1]->entry.data))
3376 		return 0;
3377 	return 1;
3378 }
3379 
3380 /** generate answer for wildcard answer */
3381 static int
az_generate_wildcard_answer(struct auth_zone * z,struct query_info * qinfo,struct regional * region,struct dns_msg * msg,struct auth_data * ce,struct auth_data * wildcard,struct auth_data * node)3382 az_generate_wildcard_answer(struct auth_zone* z, struct query_info* qinfo,
3383 	struct regional* region, struct dns_msg* msg, struct auth_data* ce,
3384 	struct auth_data* wildcard, struct auth_data* node)
3385 {
3386 	struct auth_rrset* rrset, *nsec;
3387 	int insert_ce = 0;
3388 	if((rrset=az_domain_rrset(wildcard, qinfo->qtype)) != NULL) {
3389 		/* wildcard has type, add it */
3390 		if(!msg_add_rrset_an(z, region, msg, wildcard, rrset))
3391 			return 0;
3392 		az_change_dnames(msg, wildcard->name, msg->qinfo.qname,
3393 			msg->qinfo.qname_len, 1);
3394 	} else if((rrset=az_domain_rrset(wildcard, LDNS_RR_TYPE_CNAME))!=NULL) {
3395 		/* wildcard has cname instead, do that */
3396 		if(!msg_add_rrset_an(z, region, msg, wildcard, rrset))
3397 			return 0;
3398 		az_change_dnames(msg, wildcard->name, msg->qinfo.qname,
3399 			msg->qinfo.qname_len, 1);
3400 		if(!follow_cname_chain(z, qinfo->qtype, region, msg,
3401 			rrset->data))
3402 			return 0;
3403 	} else if(qinfo->qtype == LDNS_RR_TYPE_ANY && wildcard->rrsets) {
3404 		/* add ANY rrsets from wildcard node */
3405 		if(!az_generate_any_answer(z, region, msg, wildcard))
3406 			return 0;
3407 		az_change_dnames(msg, wildcard->name, msg->qinfo.qname,
3408 			msg->qinfo.qname_len, 1);
3409 	} else {
3410 		/* wildcard has nodata, notype answer */
3411 		/* call other notype routine for dnssec notype denials */
3412 		if(!az_generate_notype_answer(z, region, msg, wildcard))
3413 			return 0;
3414 		/* because the notype, there is no positive data with an
3415 		 * RRSIG that indicates the wildcard position.  Thus the
3416 		 * wildcard qname denial needs to have a CE nsec3. */
3417 		insert_ce = 1;
3418 	}
3419 
3420 	/* ce and node for dnssec denial of wildcard original name */
3421 	if((nsec=az_find_nsec_cover(z, &node)) != NULL) {
3422 		if(!msg_add_rrset_ns(z, region, msg, node, nsec)) return 0;
3423 	} else if(ce) {
3424 		uint8_t* wildup = wildcard->name;
3425 		size_t wilduplen= wildcard->namelen;
3426 		if(!dname_remove_label_limit_len(&wildup, &wilduplen, z->namelen))
3427 			return 0; /* can't go up */
3428 		if(!az_add_nsec3_proof(z, region, msg, wildup,
3429 			wilduplen, msg->qinfo.qname,
3430 			msg->qinfo.qname_len, 0, insert_ce, 1, 0))
3431 			return 0;
3432 	}
3433 
3434 	/* fixup name of wildcard from *.zone to qname, use already allocated
3435 	 * pointer to msg qname */
3436 	az_change_dnames(msg, wildcard->name, msg->qinfo.qname,
3437 		msg->qinfo.qname_len, 0);
3438 	return 1;
3439 }
3440 
3441 /** generate answer for nxdomain answer */
3442 static int
az_generate_nxdomain_answer(struct auth_zone * z,struct regional * region,struct dns_msg * msg,struct auth_data * ce,struct auth_data * node)3443 az_generate_nxdomain_answer(struct auth_zone* z, struct regional* region,
3444 	struct dns_msg* msg, struct auth_data* ce, struct auth_data* node)
3445 {
3446 	struct auth_rrset* nsec;
3447 	msg->rep->flags |= LDNS_RCODE_NXDOMAIN;
3448 	if(!az_add_negative_soa(z, region, msg)) return 0;
3449 	if((nsec=az_find_nsec_cover(z, &node)) != NULL) {
3450 		if(!msg_add_rrset_ns(z, region, msg, node, nsec)) return 0;
3451 		if(ce && !az_nsec_wildcard_denial(z, region, msg, ce->name,
3452 			ce->namelen)) return 0;
3453 	} else if(ce) {
3454 		if(!az_add_nsec3_proof(z, region, msg, ce->name,
3455 			ce->namelen, msg->qinfo.qname,
3456 			msg->qinfo.qname_len, 0, 1, 1, 1))
3457 			return 0;
3458 	}
3459 	return 1;
3460 }
3461 
3462 /** Create answers when an exact match exists for the domain name */
3463 static int
az_generate_answer_with_node(struct auth_zone * z,struct query_info * qinfo,struct regional * region,struct dns_msg * msg,struct auth_data * node)3464 az_generate_answer_with_node(struct auth_zone* z, struct query_info* qinfo,
3465 	struct regional* region, struct dns_msg* msg, struct auth_data* node)
3466 {
3467 	struct auth_rrset* rrset;
3468 	/* positive answer, rrset we are looking for exists */
3469 	if((rrset=az_domain_rrset(node, qinfo->qtype)) != NULL) {
3470 		return az_generate_positive_answer(z, region, msg, node, rrset);
3471 	}
3472 	/* CNAME? */
3473 	if((rrset=az_domain_rrset(node, LDNS_RR_TYPE_CNAME)) != NULL) {
3474 		return az_generate_cname_answer(z, qinfo, region, msg,
3475 			node, rrset);
3476 	}
3477 	/* type ANY ? */
3478 	if(qinfo->qtype == LDNS_RR_TYPE_ANY) {
3479 		return az_generate_any_answer(z, region, msg, node);
3480 	}
3481 	/* NOERROR/NODATA (no such type at domain name) */
3482 	return az_generate_notype_answer(z, region, msg, node);
3483 }
3484 
3485 /** Generate answer without an existing-node that we can use.
3486  * So it'll be a referral, DNAME, notype, wildcard or nxdomain */
3487 static int
az_generate_answer_nonexistnode(struct auth_zone * z,struct query_info * qinfo,struct regional * region,struct dns_msg * msg,struct auth_data * ce,struct auth_rrset * rrset,struct auth_data * node)3488 az_generate_answer_nonexistnode(struct auth_zone* z, struct query_info* qinfo,
3489 	struct regional* region, struct dns_msg* msg, struct auth_data* ce,
3490 	struct auth_rrset* rrset, struct auth_data* node)
3491 {
3492 	struct auth_data* wildcard;
3493 
3494 	/* we do not have an exact matching name (that exists) */
3495 	/* see if we have a NS or DNAME in the ce */
3496 	if(ce && rrset && rrset->type == LDNS_RR_TYPE_NS) {
3497 		return az_generate_referral_answer(z, region, msg, ce, rrset);
3498 	}
3499 	if(ce && rrset && rrset->type == LDNS_RR_TYPE_DNAME) {
3500 		return az_generate_dname_answer(z, qinfo, region, msg, ce,
3501 			rrset);
3502 	}
3503 	/* if there is an empty nonterminal, wildcard and nxdomain don't
3504 	 * happen, it is a notype answer */
3505 	if(az_empty_nonterminal(z, qinfo, node)) {
3506 		return az_generate_notype_answer(z, region, msg, node);
3507 	}
3508 	/* see if we have a wildcard under the ce */
3509 	if((wildcard=az_find_wildcard(z, qinfo, ce)) != NULL) {
3510 		return az_generate_wildcard_answer(z, qinfo, region, msg,
3511 			ce, wildcard, node);
3512 	}
3513 	/* generate nxdomain answer */
3514 	return az_generate_nxdomain_answer(z, region, msg, ce, node);
3515 }
3516 
3517 /** Lookup answer in a zone. */
3518 static int
auth_zone_generate_answer(struct auth_zone * z,struct query_info * qinfo,struct regional * region,struct dns_msg ** msg,int * fallback)3519 auth_zone_generate_answer(struct auth_zone* z, struct query_info* qinfo,
3520 	struct regional* region, struct dns_msg** msg, int* fallback)
3521 {
3522 	struct auth_data* node, *ce;
3523 	struct auth_rrset* rrset;
3524 	int node_exact, node_exists;
3525 	/* does the zone want fallback in case of failure? */
3526 	*fallback = z->fallback_enabled;
3527 	if(!(*msg=msg_create(region, qinfo))) return 0;
3528 
3529 	/* lookup if there is a matching domain name for the query */
3530 	az_find_domain(z, qinfo, &node_exact, &node);
3531 
3532 	/* see if node exists for generating answers from (i.e. not glue and
3533 	 * obscured by NS or DNAME or NSEC3-only), and also return the
3534 	 * closest-encloser from that, closest node that should be used
3535 	 * to generate answers from that is above the query */
3536 	node_exists = az_find_ce(z, qinfo, node, node_exact, &ce, &rrset);
3537 
3538 	if(verbosity >= VERB_ALGO) {
3539 		char zname[256], qname[256], nname[256], cename[256],
3540 			tpstr[32], rrstr[32];
3541 		sldns_wire2str_dname_buf(qinfo->qname, qinfo->qname_len, qname,
3542 			sizeof(qname));
3543 		sldns_wire2str_type_buf(qinfo->qtype, tpstr, sizeof(tpstr));
3544 		sldns_wire2str_dname_buf(z->name, z->namelen, zname,
3545 			sizeof(zname));
3546 		if(node)
3547 			sldns_wire2str_dname_buf(node->name, node->namelen,
3548 				nname, sizeof(nname));
3549 		else	snprintf(nname, sizeof(nname), "NULL");
3550 		if(ce)
3551 			sldns_wire2str_dname_buf(ce->name, ce->namelen,
3552 				cename, sizeof(cename));
3553 		else	snprintf(cename, sizeof(cename), "NULL");
3554 		if(rrset) sldns_wire2str_type_buf(rrset->type, rrstr,
3555 			sizeof(rrstr));
3556 		else	snprintf(rrstr, sizeof(rrstr), "NULL");
3557 		log_info("auth_zone %s query %s %s, domain %s %s %s, "
3558 			"ce %s, rrset %s", zname, qname, tpstr, nname,
3559 			(node_exact?"exact":"notexact"),
3560 			(node_exists?"exist":"notexist"), cename, rrstr);
3561 	}
3562 
3563 	if(node_exists) {
3564 		/* the node is fine, generate answer from node */
3565 		return az_generate_answer_with_node(z, qinfo, region, *msg,
3566 			node);
3567 	}
3568 	return az_generate_answer_nonexistnode(z, qinfo, region, *msg,
3569 		ce, rrset, node);
3570 }
3571 
auth_zones_lookup(struct auth_zones * az,struct query_info * qinfo,struct regional * region,struct dns_msg ** msg,int * fallback,uint8_t * dp_nm,size_t dp_nmlen)3572 int auth_zones_lookup(struct auth_zones* az, struct query_info* qinfo,
3573 	struct regional* region, struct dns_msg** msg, int* fallback,
3574 	uint8_t* dp_nm, size_t dp_nmlen)
3575 {
3576 	int r;
3577 	struct auth_zone* z;
3578 	/* find the zone that should contain the answer. */
3579 	lock_rw_rdlock(&az->lock);
3580 	z = auth_zone_find(az, dp_nm, dp_nmlen, qinfo->qclass);
3581 	if(!z) {
3582 		lock_rw_unlock(&az->lock);
3583 		/* no auth zone, fallback to internet */
3584 		*fallback = 1;
3585 		return 0;
3586 	}
3587 	lock_rw_rdlock(&z->lock);
3588 	lock_rw_unlock(&az->lock);
3589 
3590 	/* if not for upstream queries, fallback */
3591 	if(!z->for_upstream) {
3592 		lock_rw_unlock(&z->lock);
3593 		*fallback = 1;
3594 		return 0;
3595 	}
3596 	if(z->zone_expired) {
3597 		*fallback = z->fallback_enabled;
3598 		lock_rw_unlock(&z->lock);
3599 		return 0;
3600 	}
3601 	/* see what answer that zone would generate */
3602 	r = auth_zone_generate_answer(z, qinfo, region, msg, fallback);
3603 	lock_rw_unlock(&z->lock);
3604 	return r;
3605 }
3606 
3607 /** encode auth answer */
3608 static void
auth_answer_encode(struct query_info * qinfo,struct module_env * env,struct edns_data * edns,struct comm_reply * repinfo,sldns_buffer * buf,struct regional * temp,struct dns_msg * msg)3609 auth_answer_encode(struct query_info* qinfo, struct module_env* env,
3610 	struct edns_data* edns, struct comm_reply* repinfo, sldns_buffer* buf,
3611 	struct regional* temp, struct dns_msg* msg)
3612 {
3613 	uint16_t udpsize;
3614 	udpsize = edns->udp_size;
3615 	edns->edns_version = EDNS_ADVERTISED_VERSION;
3616 	edns->udp_size = EDNS_ADVERTISED_SIZE;
3617 	edns->ext_rcode = 0;
3618 	edns->bits &= EDNS_DO;
3619 
3620 	if(!inplace_cb_reply_local_call(env, qinfo, NULL, msg->rep,
3621 		(int)FLAGS_GET_RCODE(msg->rep->flags), edns, repinfo, temp, env->now_tv)
3622 		|| !reply_info_answer_encode(qinfo, msg->rep,
3623 		*(uint16_t*)sldns_buffer_begin(buf),
3624 		sldns_buffer_read_u16_at(buf, 2),
3625 		buf, 0, 0, temp, udpsize, edns,
3626 		(int)(edns->bits&EDNS_DO), 0)) {
3627 		error_encode(buf, (LDNS_RCODE_SERVFAIL|BIT_AA), qinfo,
3628 			*(uint16_t*)sldns_buffer_begin(buf),
3629 			sldns_buffer_read_u16_at(buf, 2), edns);
3630 	}
3631 }
3632 
3633 /** encode auth error answer */
3634 static void
auth_error_encode(struct query_info * qinfo,struct module_env * env,struct edns_data * edns,struct comm_reply * repinfo,sldns_buffer * buf,struct regional * temp,int rcode)3635 auth_error_encode(struct query_info* qinfo, struct module_env* env,
3636 	struct edns_data* edns, struct comm_reply* repinfo, sldns_buffer* buf,
3637 	struct regional* temp, int rcode)
3638 {
3639 	edns->edns_version = EDNS_ADVERTISED_VERSION;
3640 	edns->udp_size = EDNS_ADVERTISED_SIZE;
3641 	edns->ext_rcode = 0;
3642 	edns->bits &= EDNS_DO;
3643 
3644 	if(!inplace_cb_reply_local_call(env, qinfo, NULL, NULL,
3645 		rcode, edns, repinfo, temp, env->now_tv))
3646 		edns->opt_list_inplace_cb_out = NULL;
3647 	error_encode(buf, rcode|BIT_AA, qinfo,
3648 		*(uint16_t*)sldns_buffer_begin(buf),
3649 		sldns_buffer_read_u16_at(buf, 2), edns);
3650 }
3651 
auth_zones_downstream_answer(struct auth_zones * az,struct module_env * env,struct query_info * qinfo,struct edns_data * edns,struct comm_reply * repinfo,struct sldns_buffer * buf,struct regional * temp)3652 int auth_zones_downstream_answer(struct auth_zones* az, struct module_env* env,
3653 	struct query_info* qinfo, struct edns_data* edns,
3654 	struct comm_reply* repinfo, struct sldns_buffer* buf,
3655 	struct regional* temp)
3656 {
3657 	struct dns_msg* msg = NULL;
3658 	struct auth_zone* z;
3659 	int r;
3660 	int fallback = 0;
3661 	/* Copy the qinfo in case of cname aliasing from local-zone */
3662 	struct query_info zqinfo = *qinfo;
3663 
3664 	lock_rw_rdlock(&az->lock);
3665 	if(!az->have_downstream) {
3666 		/* no downstream auth zones */
3667 		lock_rw_unlock(&az->lock);
3668 		return 0;
3669 	}
3670 
3671 	if(qinfo->qtype == LDNS_RR_TYPE_DS) {
3672 		uint8_t* delname = qinfo->qname;
3673 		size_t delnamelen = qinfo->qname_len;
3674 		dname_remove_label(&delname, &delnamelen);
3675 		z = auth_zones_find_zone(az, delname, delnamelen,
3676 			qinfo->qclass);
3677 	} else {
3678 		if(zqinfo.local_alias && !local_alias_shallow_copy_qname(
3679 			zqinfo.local_alias, &zqinfo.qname,
3680 			&zqinfo.qname_len)) {
3681 			lock_rw_unlock(&az->lock);
3682 			return 0;
3683 		}
3684 		z = auth_zones_find_zone(az, zqinfo.qname, zqinfo.qname_len,
3685 			zqinfo.qclass);
3686 	}
3687 	if(!z) {
3688 		/* no zone above it */
3689 		lock_rw_unlock(&az->lock);
3690 		return 0;
3691 	}
3692 	lock_rw_rdlock(&z->lock);
3693 	lock_rw_unlock(&az->lock);
3694 	if(!z->for_downstream) {
3695 		lock_rw_unlock(&z->lock);
3696 		return 0;
3697 	}
3698 	if(z->zone_expired) {
3699 		if(z->fallback_enabled) {
3700 			lock_rw_unlock(&z->lock);
3701 			return 0;
3702 		}
3703 		lock_rw_unlock(&z->lock);
3704 		env->mesh->num_query_authzone_down++;
3705 		auth_error_encode(qinfo, env, edns, repinfo, buf, temp,
3706 			LDNS_RCODE_SERVFAIL);
3707 		return 1;
3708 	}
3709 
3710 	/* answer it from zone z */
3711 	r = auth_zone_generate_answer(z, &zqinfo, temp, &msg, &fallback);
3712 	lock_rw_unlock(&z->lock);
3713 	if(!r && fallback) {
3714 		/* fallback to regular answering (recursive) */
3715 		return 0;
3716 	}
3717 	env->mesh->num_query_authzone_down++;
3718 
3719 	/* encode answer */
3720 	if(!r)
3721 		auth_error_encode(qinfo, env, edns, repinfo, buf, temp,
3722 			LDNS_RCODE_SERVFAIL);
3723 	else	auth_answer_encode(qinfo, env, edns, repinfo, buf, temp, msg);
3724 
3725 	return 1;
3726 }
3727 
auth_zones_can_fallback(struct auth_zones * az,uint8_t * nm,size_t nmlen,uint16_t dclass)3728 int auth_zones_can_fallback(struct auth_zones* az, uint8_t* nm, size_t nmlen,
3729 	uint16_t dclass)
3730 {
3731 	int r;
3732 	struct auth_zone* z;
3733 	lock_rw_rdlock(&az->lock);
3734 	z = auth_zone_find(az, nm, nmlen, dclass);
3735 	if(!z) {
3736 		lock_rw_unlock(&az->lock);
3737 		/* no such auth zone, fallback */
3738 		return 1;
3739 	}
3740 	lock_rw_rdlock(&z->lock);
3741 	lock_rw_unlock(&az->lock);
3742 	r = z->fallback_enabled || (!z->for_upstream);
3743 	lock_rw_unlock(&z->lock);
3744 	return r;
3745 }
3746 
3747 int
auth_zone_parse_notify_serial(sldns_buffer * pkt,uint32_t * serial)3748 auth_zone_parse_notify_serial(sldns_buffer* pkt, uint32_t *serial)
3749 {
3750 	struct query_info q;
3751 	uint16_t rdlen;
3752 	memset(&q, 0, sizeof(q));
3753 	sldns_buffer_set_position(pkt, 0);
3754 	if(!query_info_parse(&q, pkt)) return 0;
3755 	if(LDNS_ANCOUNT(sldns_buffer_begin(pkt)) == 0) return 0;
3756 	/* skip name of RR in answer section */
3757 	if(sldns_buffer_remaining(pkt) < 1) return 0;
3758 	if(pkt_dname_len(pkt) == 0) return 0;
3759 	/* check type */
3760 	if(sldns_buffer_remaining(pkt) < 10 /* type,class,ttl,rdatalen*/)
3761 		return 0;
3762 	if(sldns_buffer_read_u16(pkt) != LDNS_RR_TYPE_SOA) return 0;
3763 	sldns_buffer_skip(pkt, 2); /* class */
3764 	sldns_buffer_skip(pkt, 4); /* ttl */
3765 	rdlen = sldns_buffer_read_u16(pkt); /* rdatalen */
3766 	if(sldns_buffer_remaining(pkt) < rdlen) return 0;
3767 	if(rdlen < 22) return 0; /* bad soa length */
3768 	sldns_buffer_skip(pkt, (ssize_t)(rdlen-20));
3769 	*serial = sldns_buffer_read_u32(pkt);
3770 	/* return true when has serial in answer section */
3771 	return 1;
3772 }
3773 
3774 /** print addr to str, and if not 53, append "@port_number", for logs. */
addr_port_to_str(struct sockaddr_storage * addr,socklen_t addrlen,char * buf,size_t len)3775 static void addr_port_to_str(struct sockaddr_storage* addr, socklen_t addrlen,
3776 	char* buf, size_t len)
3777 {
3778 	uint16_t port = 0;
3779 	if(addr_is_ip6(addr, addrlen)) {
3780 		struct sockaddr_in6* sa = (struct sockaddr_in6*)addr;
3781 		port = ntohs((uint16_t)sa->sin6_port);
3782 	} else {
3783 		struct sockaddr_in* sa = (struct sockaddr_in*)addr;
3784 		port = ntohs((uint16_t)sa->sin_port);
3785 	}
3786 	if(port == UNBOUND_DNS_PORT) {
3787 		/* If it is port 53, print it plainly. */
3788 		addr_to_str(addr, addrlen, buf, len);
3789 	} else {
3790 		char a[256];
3791 		a[0]=0;
3792 		addr_to_str(addr, addrlen, a, sizeof(a));
3793 		snprintf(buf, len, "%s@%d", a, (int)port);
3794 	}
3795 }
3796 
3797 /** see if addr appears in the list */
3798 static int
addr_in_list(struct auth_addr * list,struct sockaddr_storage * addr,socklen_t addrlen)3799 addr_in_list(struct auth_addr* list, struct sockaddr_storage* addr,
3800 	socklen_t addrlen)
3801 {
3802 	struct auth_addr* p;
3803 	for(p=list; p; p=p->next) {
3804 		if(sockaddr_cmp_addr(addr, addrlen, &p->addr, p->addrlen)==0)
3805 			return 1;
3806 	}
3807 	return 0;
3808 }
3809 
3810 /** check if an address matches a master specification (or one of its
3811  * addresses in the addr list) */
3812 static int
addr_matches_master(struct auth_master * master,struct sockaddr_storage * addr,socklen_t addrlen,struct auth_master ** fromhost)3813 addr_matches_master(struct auth_master* master, struct sockaddr_storage* addr,
3814 	socklen_t addrlen, struct auth_master** fromhost)
3815 {
3816 	struct sockaddr_storage a;
3817 	socklen_t alen = 0;
3818 	int net = 0;
3819 	if(addr_in_list(master->list, addr, addrlen)) {
3820 		*fromhost = master;
3821 		return 1;
3822 	}
3823 	/* compare address (but not port number, that is the destination
3824 	 * port of the master, the port number of the received notify is
3825 	 * allowed to by any port on that master) */
3826 	if(extstrtoaddr(master->host, &a, &alen, UNBOUND_DNS_PORT) &&
3827 		sockaddr_cmp_addr(addr, addrlen, &a, alen)==0) {
3828 		*fromhost = master;
3829 		return 1;
3830 	}
3831 	/* prefixes, addr/len, like 10.0.0.0/8 */
3832 	/* not http and has a / and there is one / */
3833 	if(master->allow_notify && !master->http &&
3834 		strchr(master->host, '/') != NULL &&
3835 		strchr(master->host, '/') == strrchr(master->host, '/') &&
3836 		netblockstrtoaddr(master->host, UNBOUND_DNS_PORT, &a, &alen,
3837 		&net) && alen == addrlen) {
3838 		if(addr_in_common(addr, (addr_is_ip6(addr, addrlen)?128:32),
3839 			&a, net, alen) >= net) {
3840 			*fromhost = NULL; /* prefix does not have destination
3841 				to send the probe or transfer with */
3842 			return 1; /* matches the netblock */
3843 		}
3844 	}
3845 	return 0;
3846 }
3847 
3848 /** check access list for notifies */
3849 static int
az_xfr_allowed_notify(struct auth_xfer * xfr,struct sockaddr_storage * addr,socklen_t addrlen,struct auth_master ** fromhost)3850 az_xfr_allowed_notify(struct auth_xfer* xfr, struct sockaddr_storage* addr,
3851 	socklen_t addrlen, struct auth_master** fromhost)
3852 {
3853 	struct auth_master* p;
3854 	for(p=xfr->allow_notify_list; p; p=p->next) {
3855 		if(addr_matches_master(p, addr, addrlen, fromhost)) {
3856 			return 1;
3857 		}
3858 	}
3859 	return 0;
3860 }
3861 
3862 /** see if the serial means the zone has to be updated, i.e. the serial
3863  * is newer than the zone serial, or we have no zone */
3864 static int
xfr_serial_means_update(struct auth_xfer * xfr,uint32_t serial)3865 xfr_serial_means_update(struct auth_xfer* xfr, uint32_t serial)
3866 {
3867 	if(!xfr->have_zone)
3868 		return 1; /* no zone, anything is better */
3869 	if(xfr->zone_expired)
3870 		return 1; /* expired, the sent serial is better than expired
3871 			data */
3872 	if(compare_serial(xfr->serial, serial) < 0)
3873 		return 1; /* our serial is smaller than the sent serial,
3874 			the data is newer, fetch it */
3875 	return 0;
3876 }
3877 
3878 /** note notify serial, updates the notify information in the xfr struct */
3879 static void
xfr_note_notify_serial(struct auth_xfer * xfr,int has_serial,uint32_t serial)3880 xfr_note_notify_serial(struct auth_xfer* xfr, int has_serial, uint32_t serial)
3881 {
3882 	if(xfr->notify_received && xfr->notify_has_serial && has_serial) {
3883 		/* see if this serial is newer */
3884 		if(compare_serial(xfr->notify_serial, serial) < 0)
3885 			xfr->notify_serial = serial;
3886 	} else if(xfr->notify_received && xfr->notify_has_serial &&
3887 		!has_serial) {
3888 		/* remove serial, we have notify without serial */
3889 		xfr->notify_has_serial = 0;
3890 		xfr->notify_serial = 0;
3891 	} else if(xfr->notify_received && !xfr->notify_has_serial) {
3892 		/* we already have notify without serial, keep it
3893 		 * that way; no serial check when current operation
3894 		 * is done */
3895 	} else {
3896 		xfr->notify_received = 1;
3897 		xfr->notify_has_serial = has_serial;
3898 		xfr->notify_serial = serial;
3899 	}
3900 }
3901 
3902 /** process a notify serial, start new probe or note serial. xfr is locked */
3903 static void
xfr_process_notify(struct auth_xfer * xfr,struct module_env * env,int has_serial,uint32_t serial,struct auth_master * fromhost)3904 xfr_process_notify(struct auth_xfer* xfr, struct module_env* env,
3905 	int has_serial, uint32_t serial, struct auth_master* fromhost)
3906 {
3907 	/* if the serial of notify is older than we have, don't fetch
3908 	 * a zone, we already have it */
3909 	if(has_serial && !xfr_serial_means_update(xfr, serial)) {
3910 		lock_basic_unlock(&xfr->lock);
3911 		return;
3912 	}
3913 	/* start new probe with this addr src, or note serial */
3914 	if(!xfr_start_probe(xfr, env, fromhost)) {
3915 		/* not started because already in progress, note the serial */
3916 		xfr_note_notify_serial(xfr, has_serial, serial);
3917 		lock_basic_unlock(&xfr->lock);
3918 	}
3919 	/* successful end of start_probe unlocked xfr->lock */
3920 }
3921 
auth_zones_notify(struct auth_zones * az,struct module_env * env,uint8_t * nm,size_t nmlen,uint16_t dclass,struct sockaddr_storage * addr,socklen_t addrlen,int has_serial,uint32_t serial,int * refused)3922 int auth_zones_notify(struct auth_zones* az, struct module_env* env,
3923 	uint8_t* nm, size_t nmlen, uint16_t dclass,
3924 	struct sockaddr_storage* addr, socklen_t addrlen, int has_serial,
3925 	uint32_t serial, int* refused)
3926 {
3927 	struct auth_xfer* xfr;
3928 	struct auth_master* fromhost = NULL;
3929 	/* see which zone this is */
3930 	lock_rw_rdlock(&az->lock);
3931 	xfr = auth_xfer_find(az, nm, nmlen, dclass);
3932 	if(!xfr) {
3933 		lock_rw_unlock(&az->lock);
3934 		/* no such zone, refuse the notify */
3935 		*refused = 1;
3936 		return 0;
3937 	}
3938 	lock_basic_lock(&xfr->lock);
3939 	lock_rw_unlock(&az->lock);
3940 
3941 	/* check access list for notifies */
3942 	if(!az_xfr_allowed_notify(xfr, addr, addrlen, &fromhost)) {
3943 		lock_basic_unlock(&xfr->lock);
3944 		/* notify not allowed, refuse the notify */
3945 		*refused = 1;
3946 		return 0;
3947 	}
3948 
3949 	/* process the notify */
3950 	xfr_process_notify(xfr, env, has_serial, serial, fromhost);
3951 	return 1;
3952 }
3953 
auth_zones_startprobesequence(struct auth_zones * az,struct module_env * env,uint8_t * nm,size_t nmlen,uint16_t dclass)3954 int auth_zones_startprobesequence(struct auth_zones* az,
3955 	struct module_env* env, uint8_t* nm, size_t nmlen, uint16_t dclass)
3956 {
3957 	struct auth_xfer* xfr;
3958 	lock_rw_rdlock(&az->lock);
3959 	xfr = auth_xfer_find(az, nm, nmlen, dclass);
3960 	if(!xfr) {
3961 		lock_rw_unlock(&az->lock);
3962 		return 0;
3963 	}
3964 	lock_basic_lock(&xfr->lock);
3965 	lock_rw_unlock(&az->lock);
3966 
3967 	xfr_process_notify(xfr, env, 0, 0, NULL);
3968 	return 1;
3969 }
3970 
3971 /** set a zone expired */
3972 static void
auth_xfer_set_expired(struct auth_xfer * xfr,struct module_env * env,int expired)3973 auth_xfer_set_expired(struct auth_xfer* xfr, struct module_env* env,
3974 	int expired)
3975 {
3976 	struct auth_zone* z;
3977 
3978 	/* expire xfr */
3979 	lock_basic_lock(&xfr->lock);
3980 	xfr->zone_expired = expired;
3981 	lock_basic_unlock(&xfr->lock);
3982 
3983 	/* find auth_zone */
3984 	lock_rw_rdlock(&env->auth_zones->lock);
3985 	z = auth_zone_find(env->auth_zones, xfr->name, xfr->namelen,
3986 		xfr->dclass);
3987 	if(!z) {
3988 		lock_rw_unlock(&env->auth_zones->lock);
3989 		return;
3990 	}
3991 	lock_rw_wrlock(&z->lock);
3992 	lock_rw_unlock(&env->auth_zones->lock);
3993 
3994 	/* expire auth_zone */
3995 	z->zone_expired = expired;
3996 	lock_rw_unlock(&z->lock);
3997 }
3998 
3999 /** find master (from notify or probe) in list of masters */
4000 static struct auth_master*
find_master_by_host(struct auth_master * list,char * host)4001 find_master_by_host(struct auth_master* list, char* host)
4002 {
4003 	struct auth_master* p;
4004 	for(p=list; p; p=p->next) {
4005 		if(strcmp(p->host, host) == 0)
4006 			return p;
4007 	}
4008 	return NULL;
4009 }
4010 
4011 /** delete the looked up auth_addrs for all the masters in the list */
4012 static void
xfr_masterlist_free_addrs(struct auth_master * list)4013 xfr_masterlist_free_addrs(struct auth_master* list)
4014 {
4015 	struct auth_master* m;
4016 	for(m=list; m; m=m->next) {
4017 		if(m->list) {
4018 			auth_free_master_addrs(m->list);
4019 			m->list = NULL;
4020 		}
4021 	}
4022 }
4023 
4024 /** copy a list of auth_addrs */
4025 static struct auth_addr*
auth_addr_list_copy(struct auth_addr * source)4026 auth_addr_list_copy(struct auth_addr* source)
4027 {
4028 	struct auth_addr* list = NULL, *last = NULL;
4029 	struct auth_addr* p;
4030 	for(p=source; p; p=p->next) {
4031 		struct auth_addr* a = (struct auth_addr*)memdup(p, sizeof(*p));
4032 		if(!a) {
4033 			log_err("malloc failure");
4034 			auth_free_master_addrs(list);
4035 			return NULL;
4036 		}
4037 		a->next = NULL;
4038 		if(last) last->next = a;
4039 		if(!list) list = a;
4040 		last = a;
4041 	}
4042 	return list;
4043 }
4044 
4045 /** copy a master to a new structure, NULL on alloc failure */
4046 static struct auth_master*
auth_master_copy(struct auth_master * o)4047 auth_master_copy(struct auth_master* o)
4048 {
4049 	struct auth_master* m;
4050 	if(!o) return NULL;
4051 	m = (struct auth_master*)memdup(o, sizeof(*o));
4052 	if(!m) {
4053 		log_err("malloc failure");
4054 		return NULL;
4055 	}
4056 	m->next = NULL;
4057 	if(m->host) {
4058 		m->host = strdup(m->host);
4059 		if(!m->host) {
4060 			free(m);
4061 			log_err("malloc failure");
4062 			return NULL;
4063 		}
4064 	}
4065 	if(m->file) {
4066 		m->file = strdup(m->file);
4067 		if(!m->file) {
4068 			free(m->host);
4069 			free(m);
4070 			log_err("malloc failure");
4071 			return NULL;
4072 		}
4073 	}
4074 	if(m->list) {
4075 		m->list = auth_addr_list_copy(m->list);
4076 		if(!m->list) {
4077 			free(m->file);
4078 			free(m->host);
4079 			free(m);
4080 			return NULL;
4081 		}
4082 	}
4083 	return m;
4084 }
4085 
4086 /** append the master to the copied list. */
4087 static int
auth_master_copy_and_append(struct auth_master * p,struct auth_master ** list,struct auth_master ** last)4088 auth_master_copy_and_append(struct auth_master* p, struct auth_master** list,
4089 	struct auth_master** last)
4090 {
4091 	struct auth_master* m = auth_master_copy(p);
4092 	if(!m) {
4093 		return 0;
4094 	}
4095 	m->next = NULL;
4096 	if(*last) (*last)->next = m;
4097 	if(!*list) *list = m;
4098 	*last = m;
4099 	return 1;
4100 }
4101 
4102 /** copy the master addresses from the task_probe lookups to the allow_notify
4103  * list of masters */
4104 static void
probe_copy_masters_for_allow_notify(struct auth_xfer * xfr)4105 probe_copy_masters_for_allow_notify(struct auth_xfer* xfr)
4106 {
4107 	struct auth_master* list = NULL, *last = NULL;
4108 	struct auth_master* p;
4109 	/* build up new list with copies */
4110 	/* The list in task probe has been looked up before the list in
4111 	 * task transfer. */
4112 	for(p = xfr->task_probe->masters; p; p=p->next) {
4113 		if(!auth_master_copy_and_append(p, &list, &last)) {
4114 			auth_free_masters(list);
4115 			/* failed because of malloc failure, use old list */
4116 			return;
4117 		}
4118 	}
4119 	/* The list in task transfer also contains the http entries. */
4120 	for(p = xfr->task_transfer->masters; p; p=p->next) {
4121 		/* Copy the http entries from this lookup. The allow_notify
4122 		 * entries are not looked up from this list. The other
4123 		 * ones are already in from the probe lookups. */
4124 		if(!p->http)
4125 			continue;
4126 		if(!auth_master_copy_and_append(p, &list, &last)) {
4127 			auth_free_masters(list);
4128 			/* failed because of malloc failure, use old list */
4129 			return;
4130 		}
4131 	}
4132 	/* success, replace list */
4133 	auth_free_masters(xfr->allow_notify_list);
4134 	xfr->allow_notify_list = list;
4135 }
4136 
4137 /** start the lookups for task_transfer */
4138 static void
xfr_transfer_start_lookups(struct auth_xfer * xfr)4139 xfr_transfer_start_lookups(struct auth_xfer* xfr)
4140 {
4141 	/* delete all the looked up addresses in the list */
4142 	xfr->task_transfer->scan_addr = NULL;
4143 	xfr_masterlist_free_addrs(xfr->task_transfer->masters);
4144 
4145 	/* start lookup at the first master */
4146 	xfr->task_transfer->lookup_target = xfr->task_transfer->masters;
4147 	xfr->task_transfer->lookup_aaaa = 0;
4148 }
4149 
4150 /** move to the next lookup of hostname for task_transfer */
4151 static void
xfr_transfer_move_to_next_lookup(struct auth_xfer * xfr,struct module_env * env)4152 xfr_transfer_move_to_next_lookup(struct auth_xfer* xfr, struct module_env* env)
4153 {
4154 	if(!xfr->task_transfer->lookup_target)
4155 		return; /* already at end of list */
4156 	if(!xfr->task_transfer->lookup_aaaa && env->cfg->do_ip6) {
4157 		/* move to lookup AAAA */
4158 		xfr->task_transfer->lookup_aaaa = 1;
4159 		return;
4160 	}
4161 	xfr->task_transfer->lookup_target =
4162 		xfr->task_transfer->lookup_target->next;
4163 	xfr->task_transfer->lookup_aaaa = 0;
4164 	if(!env->cfg->do_ip4 && xfr->task_transfer->lookup_target!=NULL)
4165 		xfr->task_transfer->lookup_aaaa = 1;
4166 }
4167 
4168 /** start the lookups for task_probe */
4169 static void
xfr_probe_start_lookups(struct auth_xfer * xfr)4170 xfr_probe_start_lookups(struct auth_xfer* xfr)
4171 {
4172 	/* delete all the looked up addresses in the list */
4173 	xfr->task_probe->scan_addr = NULL;
4174 	xfr_masterlist_free_addrs(xfr->task_probe->masters);
4175 
4176 	/* start lookup at the first master */
4177 	xfr->task_probe->lookup_target = xfr->task_probe->masters;
4178 	xfr->task_probe->lookup_aaaa = 0;
4179 }
4180 
4181 /** move to the next lookup of hostname for task_probe */
4182 static void
xfr_probe_move_to_next_lookup(struct auth_xfer * xfr,struct module_env * env)4183 xfr_probe_move_to_next_lookup(struct auth_xfer* xfr, struct module_env* env)
4184 {
4185 	if(!xfr->task_probe->lookup_target)
4186 		return; /* already at end of list */
4187 	if(!xfr->task_probe->lookup_aaaa && env->cfg->do_ip6) {
4188 		/* move to lookup AAAA */
4189 		xfr->task_probe->lookup_aaaa = 1;
4190 		return;
4191 	}
4192 	xfr->task_probe->lookup_target = xfr->task_probe->lookup_target->next;
4193 	xfr->task_probe->lookup_aaaa = 0;
4194 	if(!env->cfg->do_ip4 && xfr->task_probe->lookup_target!=NULL)
4195 		xfr->task_probe->lookup_aaaa = 1;
4196 }
4197 
4198 /** start the iteration of the task_transfer list of masters */
4199 static void
xfr_transfer_start_list(struct auth_xfer * xfr,struct auth_master * spec)4200 xfr_transfer_start_list(struct auth_xfer* xfr, struct auth_master* spec)
4201 {
4202 	if(spec) {
4203 		xfr->task_transfer->scan_specific = find_master_by_host(
4204 			xfr->task_transfer->masters, spec->host);
4205 		if(xfr->task_transfer->scan_specific) {
4206 			xfr->task_transfer->scan_target = NULL;
4207 			xfr->task_transfer->scan_addr = NULL;
4208 			if(xfr->task_transfer->scan_specific->list)
4209 				xfr->task_transfer->scan_addr =
4210 					xfr->task_transfer->scan_specific->list;
4211 			return;
4212 		}
4213 	}
4214 	/* no specific (notified) host to scan */
4215 	xfr->task_transfer->scan_specific = NULL;
4216 	xfr->task_transfer->scan_addr = NULL;
4217 	/* pick up first scan target */
4218 	xfr->task_transfer->scan_target = xfr->task_transfer->masters;
4219 	if(xfr->task_transfer->scan_target && xfr->task_transfer->
4220 		scan_target->list)
4221 		xfr->task_transfer->scan_addr =
4222 			xfr->task_transfer->scan_target->list;
4223 }
4224 
4225 /** start the iteration of the task_probe list of masters */
4226 static void
xfr_probe_start_list(struct auth_xfer * xfr,struct auth_master * spec)4227 xfr_probe_start_list(struct auth_xfer* xfr, struct auth_master* spec)
4228 {
4229 	if(spec) {
4230 		xfr->task_probe->scan_specific = find_master_by_host(
4231 			xfr->task_probe->masters, spec->host);
4232 		if(xfr->task_probe->scan_specific) {
4233 			xfr->task_probe->scan_target = NULL;
4234 			xfr->task_probe->scan_addr = NULL;
4235 			if(xfr->task_probe->scan_specific->list)
4236 				xfr->task_probe->scan_addr =
4237 					xfr->task_probe->scan_specific->list;
4238 			return;
4239 		}
4240 	}
4241 	/* no specific (notified) host to scan */
4242 	xfr->task_probe->scan_specific = NULL;
4243 	xfr->task_probe->scan_addr = NULL;
4244 	/* pick up first scan target */
4245 	xfr->task_probe->scan_target = xfr->task_probe->masters;
4246 	if(xfr->task_probe->scan_target && xfr->task_probe->scan_target->list)
4247 		xfr->task_probe->scan_addr =
4248 			xfr->task_probe->scan_target->list;
4249 }
4250 
4251 /** pick up the master that is being scanned right now, task_transfer */
4252 static struct auth_master*
xfr_transfer_current_master(struct auth_xfer * xfr)4253 xfr_transfer_current_master(struct auth_xfer* xfr)
4254 {
4255 	if(xfr->task_transfer->scan_specific)
4256 		return xfr->task_transfer->scan_specific;
4257 	return xfr->task_transfer->scan_target;
4258 }
4259 
4260 /** pick up the master that is being scanned right now, task_probe */
4261 static struct auth_master*
xfr_probe_current_master(struct auth_xfer * xfr)4262 xfr_probe_current_master(struct auth_xfer* xfr)
4263 {
4264 	if(xfr->task_probe->scan_specific)
4265 		return xfr->task_probe->scan_specific;
4266 	return xfr->task_probe->scan_target;
4267 }
4268 
4269 /** true if at end of list, task_transfer */
4270 static int
xfr_transfer_end_of_list(struct auth_xfer * xfr)4271 xfr_transfer_end_of_list(struct auth_xfer* xfr)
4272 {
4273 	return !xfr->task_transfer->scan_specific &&
4274 		!xfr->task_transfer->scan_target;
4275 }
4276 
4277 /** true if at end of list, task_probe */
4278 static int
xfr_probe_end_of_list(struct auth_xfer * xfr)4279 xfr_probe_end_of_list(struct auth_xfer* xfr)
4280 {
4281 	return !xfr->task_probe->scan_specific && !xfr->task_probe->scan_target;
4282 }
4283 
4284 /** move to next master in list, task_transfer */
4285 static void
xfr_transfer_nextmaster(struct auth_xfer * xfr)4286 xfr_transfer_nextmaster(struct auth_xfer* xfr)
4287 {
4288 	if(!xfr->task_transfer->scan_specific &&
4289 		!xfr->task_transfer->scan_target)
4290 		return;
4291 	if(xfr->task_transfer->scan_addr) {
4292 		xfr->task_transfer->scan_addr =
4293 			xfr->task_transfer->scan_addr->next;
4294 		if(xfr->task_transfer->scan_addr)
4295 			return;
4296 	}
4297 	if(xfr->task_transfer->scan_specific) {
4298 		xfr->task_transfer->scan_specific = NULL;
4299 		xfr->task_transfer->scan_target = xfr->task_transfer->masters;
4300 		if(xfr->task_transfer->scan_target && xfr->task_transfer->
4301 			scan_target->list)
4302 			xfr->task_transfer->scan_addr =
4303 				xfr->task_transfer->scan_target->list;
4304 		return;
4305 	}
4306 	if(!xfr->task_transfer->scan_target)
4307 		return;
4308 	xfr->task_transfer->scan_target = xfr->task_transfer->scan_target->next;
4309 	if(xfr->task_transfer->scan_target && xfr->task_transfer->
4310 		scan_target->list)
4311 		xfr->task_transfer->scan_addr =
4312 			xfr->task_transfer->scan_target->list;
4313 	return;
4314 }
4315 
4316 /** move to next master in list, task_probe */
4317 static void
xfr_probe_nextmaster(struct auth_xfer * xfr)4318 xfr_probe_nextmaster(struct auth_xfer* xfr)
4319 {
4320 	if(!xfr->task_probe->scan_specific && !xfr->task_probe->scan_target)
4321 		return;
4322 	if(xfr->task_probe->scan_addr) {
4323 		xfr->task_probe->scan_addr = xfr->task_probe->scan_addr->next;
4324 		if(xfr->task_probe->scan_addr)
4325 			return;
4326 	}
4327 	if(xfr->task_probe->scan_specific) {
4328 		xfr->task_probe->scan_specific = NULL;
4329 		xfr->task_probe->scan_target = xfr->task_probe->masters;
4330 		if(xfr->task_probe->scan_target && xfr->task_probe->
4331 			scan_target->list)
4332 			xfr->task_probe->scan_addr =
4333 				xfr->task_probe->scan_target->list;
4334 		return;
4335 	}
4336 	if(!xfr->task_probe->scan_target)
4337 		return;
4338 	xfr->task_probe->scan_target = xfr->task_probe->scan_target->next;
4339 	if(xfr->task_probe->scan_target && xfr->task_probe->
4340 		scan_target->list)
4341 		xfr->task_probe->scan_addr =
4342 			xfr->task_probe->scan_target->list;
4343 	return;
4344 }
4345 
4346 /** create SOA probe packet for xfr */
4347 static void
xfr_create_soa_probe_packet(struct auth_xfer * xfr,sldns_buffer * buf,uint16_t id)4348 xfr_create_soa_probe_packet(struct auth_xfer* xfr, sldns_buffer* buf,
4349 	uint16_t id)
4350 {
4351 	struct query_info qinfo;
4352 
4353 	memset(&qinfo, 0, sizeof(qinfo));
4354 	qinfo.qname = xfr->name;
4355 	qinfo.qname_len = xfr->namelen;
4356 	qinfo.qtype = LDNS_RR_TYPE_SOA;
4357 	qinfo.qclass = xfr->dclass;
4358 	qinfo_query_encode(buf, &qinfo);
4359 	sldns_buffer_write_u16_at(buf, 0, id);
4360 }
4361 
4362 /** create IXFR/AXFR packet for xfr */
4363 static void
xfr_create_ixfr_packet(struct auth_xfer * xfr,sldns_buffer * buf,uint16_t id,struct auth_master * master)4364 xfr_create_ixfr_packet(struct auth_xfer* xfr, sldns_buffer* buf, uint16_t id,
4365 	struct auth_master* master)
4366 {
4367 	struct query_info qinfo;
4368 	uint32_t serial;
4369 	int have_zone, get_full = 0;
4370 	have_zone = xfr->have_zone;
4371 	serial = xfr->serial;
4372 
4373 	memset(&qinfo, 0, sizeof(qinfo));
4374 	qinfo.qname = xfr->name;
4375 	qinfo.qname_len = xfr->namelen;
4376 	xfr->task_transfer->got_xfr_serial = 0;
4377 	xfr->task_transfer->rr_scan_num = 0;
4378 	xfr->task_transfer->incoming_xfr_serial = 0;
4379 	xfr->task_transfer->on_ixfr_is_axfr = 0;
4380 	xfr->task_transfer->on_ixfr = 1;
4381 	qinfo.qtype = LDNS_RR_TYPE_IXFR;
4382 	if(xfr->num_ixfrs >= NUM_IXFR_BEFORE_AXFR && xfr->is_rpz) {
4383 		/* For the RPZ, an IXFR is going to grow regions, and a
4384 		 * full transfer, zonefile read, AXFR and HTTP clear the
4385 		 * region, but IXFR does not. That memory keeps growing,
4386 		 * and getting a full transfer with AXFR here resets that.
4387 		 * The rpz->client_set->region, rpz->ns_set->region and
4388 		 * rpz->respip_set->region need to be reset, they are for
4389 		 * rpz-client-ip, rpz-nsip and rpz-ip. */
4390 		get_full = 1;
4391 	}
4392 	if(!have_zone || xfr->task_transfer->ixfr_fail || !master->ixfr
4393 		|| get_full) {
4394 		qinfo.qtype = LDNS_RR_TYPE_AXFR;
4395 		xfr->task_transfer->ixfr_fail = 0;
4396 		xfr->task_transfer->on_ixfr = 0;
4397 	}
4398 
4399 	qinfo.qclass = xfr->dclass;
4400 	qinfo_query_encode(buf, &qinfo);
4401 	sldns_buffer_write_u16_at(buf, 0, id);
4402 
4403 	/* append serial for IXFR */
4404 	if(qinfo.qtype == LDNS_RR_TYPE_IXFR) {
4405 		size_t end = sldns_buffer_limit(buf);
4406 		sldns_buffer_clear(buf);
4407 		sldns_buffer_set_position(buf, end);
4408 		/* auth section count 1 */
4409 		sldns_buffer_write_u16_at(buf, LDNS_NSCOUNT_OFF, 1);
4410 		/* write SOA */
4411 		sldns_buffer_write_u8(buf, 0xC0); /* compressed ptr to qname */
4412 		sldns_buffer_write_u8(buf, 0x0C);
4413 		sldns_buffer_write_u16(buf, LDNS_RR_TYPE_SOA);
4414 		sldns_buffer_write_u16(buf, qinfo.qclass);
4415 		sldns_buffer_write_u32(buf, 0); /* ttl */
4416 		sldns_buffer_write_u16(buf, 22); /* rdata length */
4417 		sldns_buffer_write_u8(buf, 0); /* . */
4418 		sldns_buffer_write_u8(buf, 0); /* . */
4419 		sldns_buffer_write_u32(buf, serial); /* serial */
4420 		sldns_buffer_write_u32(buf, 0); /* refresh */
4421 		sldns_buffer_write_u32(buf, 0); /* retry */
4422 		sldns_buffer_write_u32(buf, 0); /* expire */
4423 		sldns_buffer_write_u32(buf, 0); /* minimum */
4424 		sldns_buffer_flip(buf);
4425 	}
4426 }
4427 
4428 /** check if returned packet is OK */
4429 static int
check_packet_ok(sldns_buffer * pkt,uint16_t qtype,struct auth_xfer * xfr,uint32_t * serial)4430 check_packet_ok(sldns_buffer* pkt, uint16_t qtype, struct auth_xfer* xfr,
4431 	uint32_t* serial)
4432 {
4433 	/* parse to see if packet worked, valid reply */
4434 
4435 	/* check serial number of SOA */
4436 	if(sldns_buffer_limit(pkt) < LDNS_HEADER_SIZE)
4437 		return 0;
4438 
4439 	/* check ID */
4440 	if(LDNS_ID_WIRE(sldns_buffer_begin(pkt)) != xfr->task_probe->id)
4441 		return 0;
4442 
4443 	/* check flag bits and rcode */
4444 	if(!LDNS_QR_WIRE(sldns_buffer_begin(pkt)))
4445 		return 0;
4446 	if(LDNS_OPCODE_WIRE(sldns_buffer_begin(pkt)) != LDNS_PACKET_QUERY)
4447 		return 0;
4448 	if(LDNS_RCODE_WIRE(sldns_buffer_begin(pkt)) != LDNS_RCODE_NOERROR)
4449 		return 0;
4450 
4451 	/* check qname */
4452 	if(LDNS_QDCOUNT(sldns_buffer_begin(pkt)) != 1)
4453 		return 0;
4454 	sldns_buffer_skip(pkt, LDNS_HEADER_SIZE);
4455 	if(sldns_buffer_remaining(pkt) < xfr->namelen)
4456 		return 0;
4457 	if(query_dname_compare(sldns_buffer_current(pkt), xfr->name) != 0)
4458 		return 0;
4459 	sldns_buffer_skip(pkt, (ssize_t)xfr->namelen);
4460 
4461 	/* check qtype, qclass */
4462 	if(sldns_buffer_remaining(pkt) < 4)
4463 		return 0;
4464 	if(sldns_buffer_read_u16(pkt) != qtype)
4465 		return 0;
4466 	if(sldns_buffer_read_u16(pkt) != xfr->dclass)
4467 		return 0;
4468 
4469 	if(serial) {
4470 		uint16_t rdlen;
4471 		/* read serial number, from answer section SOA */
4472 		if(LDNS_ANCOUNT(sldns_buffer_begin(pkt)) == 0)
4473 			return 0;
4474 		/* read from first record SOA record */
4475 		if(sldns_buffer_remaining(pkt) < 1)
4476 			return 0;
4477 		if(dname_pkt_compare(pkt, sldns_buffer_current(pkt),
4478 			xfr->name) != 0)
4479 			return 0;
4480 		if(!pkt_dname_len(pkt))
4481 			return 0;
4482 		/* type, class, ttl, rdatalen */
4483 		if(sldns_buffer_remaining(pkt) < 4+4+2)
4484 			return 0;
4485 		if(sldns_buffer_read_u16(pkt) != qtype)
4486 			return 0;
4487 		if(sldns_buffer_read_u16(pkt) != xfr->dclass)
4488 			return 0;
4489 		sldns_buffer_skip(pkt, 4); /* ttl */
4490 		rdlen = sldns_buffer_read_u16(pkt);
4491 		if(sldns_buffer_remaining(pkt) < rdlen)
4492 			return 0;
4493 		if(sldns_buffer_remaining(pkt) < 1)
4494 			return 0;
4495 		if(!pkt_dname_len(pkt)) /* soa name */
4496 			return 0;
4497 		if(sldns_buffer_remaining(pkt) < 1)
4498 			return 0;
4499 		if(!pkt_dname_len(pkt)) /* soa name */
4500 			return 0;
4501 		if(sldns_buffer_remaining(pkt) < 20)
4502 			return 0;
4503 		*serial = sldns_buffer_read_u32(pkt);
4504 	}
4505 	return 1;
4506 }
4507 
4508 /** read one line from chunks into buffer at current position */
4509 static int
chunkline_get_line(struct auth_chunk ** chunk,size_t * chunk_pos,sldns_buffer * buf)4510 chunkline_get_line(struct auth_chunk** chunk, size_t* chunk_pos,
4511 	sldns_buffer* buf)
4512 {
4513 	int readsome = 0;
4514 	while(*chunk) {
4515 		/* more text in this chunk? */
4516 		if(*chunk_pos < (*chunk)->len) {
4517 			readsome = 1;
4518 			while(*chunk_pos < (*chunk)->len) {
4519 				char c = (char)((*chunk)->data[*chunk_pos]);
4520 				(*chunk_pos)++;
4521 				if(sldns_buffer_remaining(buf) < 2) {
4522 					/* buffer too short */
4523 					verbose(VERB_ALGO, "http chunkline, "
4524 						"line too long");
4525 					return 0;
4526 				}
4527 				sldns_buffer_write_u8(buf, (uint8_t)c);
4528 				if(c == '\n') {
4529 					/* we are done */
4530 					return 1;
4531 				}
4532 			}
4533 		}
4534 		/* move to next chunk */
4535 		*chunk = (*chunk)->next;
4536 		*chunk_pos = 0;
4537 	}
4538 	/* no more text */
4539 	if(readsome) return 1;
4540 	return 0;
4541 }
4542 
4543 /** count number of open and closed parenthesis in a chunkline */
4544 int
chunkline_count_parens(sldns_buffer * buf,size_t start)4545 chunkline_count_parens(sldns_buffer* buf, size_t start)
4546 {
4547 	size_t end = sldns_buffer_position(buf);
4548 	size_t i;
4549 	int count = 0;
4550 	int dquote = 0;
4551 	char prev_c = 0;
4552 	for(i=start; i<end; i++) {
4553 		char c = (char)sldns_buffer_read_u8_at(buf, i);
4554 		if(dquote && !(c == '"' && prev_c != '\\')) {
4555 			prev_c = (prev_c == '\\' && c == '\\') ? 0 : c;
4556 			continue;
4557 		}
4558 		if(c == '"' && prev_c != '\\')
4559 			dquote = !dquote; /* skip quoted part */
4560 		else if(c == '(' && prev_c != '\\')
4561 			count ++;
4562 		else if(c == ')' && prev_c != '\\')
4563 			count --;
4564 		else if(c == ';' && prev_c != '\\') {
4565 			/* rest is a comment */
4566 			return count;
4567 		}
4568 		prev_c = (prev_c == '\\' && c == '\\') ? 0 : c;
4569 	}
4570 	return count;
4571 }
4572 
4573 /** remove trailing ;... comment from a line in the chunkline buffer */
4574 static void
chunkline_remove_trailcomment(sldns_buffer * buf,size_t start)4575 chunkline_remove_trailcomment(sldns_buffer* buf, size_t start)
4576 {
4577 	size_t end = sldns_buffer_position(buf);
4578 	size_t i;
4579 	int dquote = 0;
4580 	char prev_c = 0;
4581 	for(i=start; i<end; i++) {
4582 		char c = (char)sldns_buffer_read_u8_at(buf, i);
4583 		if(dquote && !(c == '"' && prev_c != '\\')) {
4584 			prev_c = (prev_c == '\\' && c == '\\') ? 0 : c;
4585 			continue;
4586 		}
4587 		if(c == '"' && prev_c != '\\')
4588 			dquote = !dquote; /* skip quoted part */
4589 		else if(c == ';' && prev_c != '\\') {
4590 			/* rest is a comment */
4591 			sldns_buffer_set_position(buf, i);
4592 			return;
4593 		}
4594 		prev_c = (prev_c == '\\' && c == '\\') ? 0 : c;
4595 	}
4596 	/* nothing to remove */
4597 }
4598 
4599 /** see if a chunkline is a comment line (or empty line) */
4600 static int
chunkline_is_comment_line_or_empty(sldns_buffer * buf)4601 chunkline_is_comment_line_or_empty(sldns_buffer* buf)
4602 {
4603 	size_t i, end = sldns_buffer_limit(buf);
4604 	for(i=0; i<end; i++) {
4605 		char c = (char)sldns_buffer_read_u8_at(buf, i);
4606 		if(c == ';')
4607 			return 1; /* comment */
4608 		else if(c != ' ' && c != '\t' && c != '\r' && c != '\n')
4609 			return 0; /* not a comment */
4610 	}
4611 	return 1; /* empty */
4612 }
4613 
4614 /** find a line with ( ) collated */
4615 static int
chunkline_get_line_collated(struct auth_chunk ** chunk,size_t * chunk_pos,sldns_buffer * buf)4616 chunkline_get_line_collated(struct auth_chunk** chunk, size_t* chunk_pos,
4617 	sldns_buffer* buf)
4618 {
4619 	size_t pos;
4620 	int parens = 0;
4621 	sldns_buffer_clear(buf);
4622 	pos = sldns_buffer_position(buf);
4623 	if(!chunkline_get_line(chunk, chunk_pos, buf)) {
4624 		if(sldns_buffer_position(buf) < sldns_buffer_limit(buf))
4625 			sldns_buffer_write_u8_at(buf, sldns_buffer_position(buf), 0);
4626 		else sldns_buffer_write_u8_at(buf, sldns_buffer_position(buf)-1, 0);
4627 		sldns_buffer_flip(buf);
4628 		return 0;
4629 	}
4630 	parens += chunkline_count_parens(buf, pos);
4631 	while(parens > 0) {
4632 		chunkline_remove_trailcomment(buf, pos);
4633 		pos = sldns_buffer_position(buf);
4634 		if(!chunkline_get_line(chunk, chunk_pos, buf)) {
4635 			if(sldns_buffer_position(buf) < sldns_buffer_limit(buf))
4636 				sldns_buffer_write_u8_at(buf, sldns_buffer_position(buf), 0);
4637 			else sldns_buffer_write_u8_at(buf, sldns_buffer_position(buf)-1, 0);
4638 			sldns_buffer_flip(buf);
4639 			return 0;
4640 		}
4641 		parens += chunkline_count_parens(buf, pos);
4642 	}
4643 
4644 	if(sldns_buffer_remaining(buf) < 1) {
4645 		verbose(VERB_ALGO, "http chunkline: "
4646 			"line too long");
4647 		return 0;
4648 	}
4649 	sldns_buffer_write_u8_at(buf, sldns_buffer_position(buf), 0);
4650 	sldns_buffer_flip(buf);
4651 	return 1;
4652 }
4653 
4654 /** process $ORIGIN for http, 0 nothing, 1 done, 2 error */
4655 static int
http_parse_origin(sldns_buffer * buf,struct sldns_file_parse_state * pstate)4656 http_parse_origin(sldns_buffer* buf, struct sldns_file_parse_state* pstate)
4657 {
4658 	char* line = (char*)sldns_buffer_begin(buf);
4659 	if(strncmp(line, "$ORIGIN", 7) == 0 &&
4660 		isspace((unsigned char)line[7])) {
4661 		int s;
4662 		pstate->origin_len = sizeof(pstate->origin);
4663 		s = sldns_str2wire_dname_buf(sldns_strip_ws(line+8),
4664 			pstate->origin, &pstate->origin_len);
4665 		if(s) {
4666 			pstate->origin_len = 0;
4667 			return 2;
4668 		}
4669 		return 1;
4670 	}
4671 	return 0;
4672 }
4673 
4674 /** process $TTL for http, 0 nothing, 1 done, 2 error */
4675 static int
http_parse_ttl(sldns_buffer * buf,struct sldns_file_parse_state * pstate)4676 http_parse_ttl(sldns_buffer* buf, struct sldns_file_parse_state* pstate)
4677 {
4678 	char* line = (char*)sldns_buffer_begin(buf);
4679 	if(strncmp(line, "$TTL", 4) == 0 &&
4680 		isspace((unsigned char)line[4])) {
4681 		const char* end = NULL;
4682 		int overflow = 0;
4683 		pstate->default_ttl = sldns_str2period(
4684 			sldns_strip_ws(line+5), &end, &overflow);
4685 		if(overflow) {
4686 			return 2;
4687 		}
4688 		return 1;
4689 	}
4690 	return 0;
4691 }
4692 
4693 /** remove newlines from collated line */
4694 static void
chunkline_newline_removal(sldns_buffer * buf)4695 chunkline_newline_removal(sldns_buffer* buf)
4696 {
4697 	size_t i, end=sldns_buffer_limit(buf);
4698 	for(i=0; i<end; i++) {
4699 		char c = (char)sldns_buffer_read_u8_at(buf, i);
4700 		if(c == '\n' && i==end-1) {
4701 			sldns_buffer_write_u8_at(buf, i, 0);
4702 			sldns_buffer_set_limit(buf, end-1);
4703 			return;
4704 		}
4705 		if(c == '\n')
4706 			sldns_buffer_write_u8_at(buf, i, (uint8_t)' ');
4707 	}
4708 }
4709 
4710 /** find noncomment RR line in chunks, collates lines if ( ) format */
4711 static int
chunkline_non_comment_RR(struct auth_chunk ** chunk,size_t * chunk_pos,sldns_buffer * buf,struct sldns_file_parse_state * pstate)4712 chunkline_non_comment_RR(struct auth_chunk** chunk, size_t* chunk_pos,
4713 	sldns_buffer* buf, struct sldns_file_parse_state* pstate)
4714 {
4715 	int ret;
4716 	while(chunkline_get_line_collated(chunk, chunk_pos, buf)) {
4717 		chunkline_newline_removal(buf);
4718 		if(chunkline_is_comment_line_or_empty(buf)) {
4719 			/* a comment, go to next line */
4720 			continue;
4721 		}
4722 		if((ret=http_parse_origin(buf, pstate))!=0) {
4723 			if(ret == 2)
4724 				return 0;
4725 			continue; /* $ORIGIN has been handled */
4726 		}
4727 		if((ret=http_parse_ttl(buf, pstate))!=0) {
4728 			if(ret == 2)
4729 				return 0;
4730 			continue; /* $TTL has been handled */
4731 		}
4732 		return 1;
4733 	}
4734 	/* no noncomments, fail */
4735 	return 0;
4736 }
4737 
4738 /** check syntax of chunklist zonefile, parse first RR, return false on
4739  * failure and return a string in the scratch buffer (first RR string)
4740  * on failure. */
4741 static int
http_zonefile_syntax_check(struct auth_xfer * xfr,sldns_buffer * buf)4742 http_zonefile_syntax_check(struct auth_xfer* xfr, sldns_buffer* buf)
4743 {
4744 	uint8_t rr[LDNS_RR_BUF_SIZE];
4745 	size_t rr_len, dname_len = 0;
4746 	struct sldns_file_parse_state pstate;
4747 	struct auth_chunk* chunk;
4748 	size_t chunk_pos;
4749 	int e;
4750 	memset(&pstate, 0, sizeof(pstate));
4751 	pstate.default_ttl = 3600;
4752 	if(xfr->namelen < sizeof(pstate.origin)) {
4753 		pstate.origin_len = xfr->namelen;
4754 		memmove(pstate.origin, xfr->name, xfr->namelen);
4755 	}
4756 	chunk = xfr->task_transfer->chunks_first;
4757 	chunk_pos = 0;
4758 	if(!chunkline_non_comment_RR(&chunk, &chunk_pos, buf, &pstate)) {
4759 		return 0;
4760 	}
4761 	rr_len = sizeof(rr);
4762 	e=sldns_str2wire_rr_buf((char*)sldns_buffer_begin(buf), rr, &rr_len,
4763 		&dname_len, pstate.default_ttl,
4764 		pstate.origin_len?pstate.origin:NULL, pstate.origin_len,
4765 		pstate.prev_rr_len?pstate.prev_rr:NULL, pstate.prev_rr_len);
4766 	if(e != 0) {
4767 		log_err("parse failure on first RR[%d]: %s",
4768 			LDNS_WIREPARSE_OFFSET(e),
4769 			sldns_get_errorstr_parse(LDNS_WIREPARSE_ERROR(e)));
4770 		return 0;
4771 	}
4772 	/* check that class is correct */
4773 	if(sldns_wirerr_get_class(rr, rr_len, dname_len) != xfr->dclass) {
4774 		log_err("parse failure: first record in downloaded zonefile "
4775 			"from wrong RR class");
4776 		return 0;
4777 	}
4778 	return 1;
4779 }
4780 
4781 /** sum sizes of chunklist */
4782 static size_t
chunklist_sum(struct auth_chunk * list)4783 chunklist_sum(struct auth_chunk* list)
4784 {
4785 	struct auth_chunk* p;
4786 	size_t s = 0;
4787 	for(p=list; p; p=p->next) {
4788 		s += p->len;
4789 	}
4790 	return s;
4791 }
4792 
4793 /** for http download, parse and add RR to zone */
4794 static int
http_parse_add_rr(struct auth_xfer * xfr,struct auth_zone * z,sldns_buffer * buf,struct sldns_file_parse_state * pstate)4795 http_parse_add_rr(struct auth_xfer* xfr, struct auth_zone* z,
4796 	sldns_buffer* buf, struct sldns_file_parse_state* pstate)
4797 {
4798 	uint8_t rr[LDNS_RR_BUF_SIZE];
4799 	size_t rr_len, dname_len = 0;
4800 	int e;
4801 	char* line = (char*)sldns_buffer_begin(buf);
4802 	rr_len = sizeof(rr);
4803 	e = sldns_str2wire_rr_buf(line, rr, &rr_len, &dname_len,
4804 		pstate->default_ttl,
4805 		pstate->origin_len?pstate->origin:NULL, pstate->origin_len,
4806 		pstate->prev_rr_len?pstate->prev_rr:NULL, pstate->prev_rr_len);
4807 	if(e != 0) {
4808 		log_err("%s/%s parse failure RR[%d]: %s in '%s'",
4809 			xfr->task_transfer->master->host,
4810 			xfr->task_transfer->master->file,
4811 			LDNS_WIREPARSE_OFFSET(e),
4812 			sldns_get_errorstr_parse(LDNS_WIREPARSE_ERROR(e)),
4813 			line);
4814 		return 0;
4815 	}
4816 	if(rr_len == 0)
4817 		return 1; /* empty line or so */
4818 
4819 	/* set prev */
4820 	if(dname_len < sizeof(pstate->prev_rr)) {
4821 		memmove(pstate->prev_rr, rr, dname_len);
4822 		pstate->prev_rr_len = dname_len;
4823 	}
4824 
4825 	return az_insert_rr(z, rr, rr_len, dname_len, NULL);
4826 }
4827 
4828 /** RR list iterator, returns RRs from answer section one by one from the
4829  * dns packets in the chunklist */
4830 static void
chunk_rrlist_start(struct auth_xfer * xfr,struct auth_chunk ** rr_chunk,int * rr_num,size_t * rr_pos)4831 chunk_rrlist_start(struct auth_xfer* xfr, struct auth_chunk** rr_chunk,
4832 	int* rr_num, size_t* rr_pos)
4833 {
4834 	*rr_chunk = xfr->task_transfer->chunks_first;
4835 	*rr_num = 0;
4836 	*rr_pos = 0;
4837 }
4838 
4839 /** RR list iterator, see if we are at the end of the list */
4840 static int
chunk_rrlist_end(struct auth_chunk * rr_chunk,int rr_num)4841 chunk_rrlist_end(struct auth_chunk* rr_chunk, int rr_num)
4842 {
4843 	while(rr_chunk) {
4844 		if(rr_chunk->len < LDNS_HEADER_SIZE)
4845 			return 1;
4846 		if(rr_num < (int)LDNS_ANCOUNT(rr_chunk->data))
4847 			return 0;
4848 		/* no more RRs in this chunk */
4849 		/* continue with next chunk, see if it has RRs */
4850 		rr_chunk = rr_chunk->next;
4851 		rr_num = 0;
4852 	}
4853 	return 1;
4854 }
4855 
4856 /** RR list iterator, move to next RR */
4857 static void
chunk_rrlist_gonext(struct auth_chunk ** rr_chunk,int * rr_num,size_t * rr_pos,size_t rr_nextpos)4858 chunk_rrlist_gonext(struct auth_chunk** rr_chunk, int* rr_num,
4859 	size_t* rr_pos, size_t rr_nextpos)
4860 {
4861 	/* already at end of chunks? */
4862 	if(!*rr_chunk)
4863 		return;
4864 	/* move within this chunk */
4865 	if((*rr_chunk)->len >= LDNS_HEADER_SIZE &&
4866 		(*rr_num)+1 < (int)LDNS_ANCOUNT((*rr_chunk)->data)) {
4867 		(*rr_num) += 1;
4868 		*rr_pos = rr_nextpos;
4869 		return;
4870 	}
4871 	/* no more RRs in this chunk */
4872 	/* continue with next chunk, see if it has RRs */
4873 	if(*rr_chunk)
4874 		*rr_chunk = (*rr_chunk)->next;
4875 	while(*rr_chunk) {
4876 		*rr_num = 0;
4877 		*rr_pos = 0;
4878 		if((*rr_chunk)->len >= LDNS_HEADER_SIZE &&
4879 			LDNS_ANCOUNT((*rr_chunk)->data) > 0) {
4880 			return;
4881 		}
4882 		*rr_chunk = (*rr_chunk)->next;
4883 	}
4884 }
4885 
4886 /** RR iterator, get current RR information, false on parse error */
4887 static int
chunk_rrlist_get_current(struct auth_chunk * rr_chunk,int rr_num,size_t rr_pos,uint8_t ** rr_dname,uint16_t * rr_type,uint16_t * rr_class,uint32_t * rr_ttl,uint16_t * rr_rdlen,uint8_t ** rr_rdata,size_t * rr_nextpos)4888 chunk_rrlist_get_current(struct auth_chunk* rr_chunk, int rr_num,
4889 	size_t rr_pos, uint8_t** rr_dname, uint16_t* rr_type,
4890 	uint16_t* rr_class, uint32_t* rr_ttl, uint16_t* rr_rdlen,
4891 	uint8_t** rr_rdata, size_t* rr_nextpos)
4892 {
4893 	sldns_buffer pkt;
4894 	/* integrity checks on position */
4895 	if(!rr_chunk) return 0;
4896 	if(rr_chunk->len < LDNS_HEADER_SIZE) return 0;
4897 	if(rr_num >= (int)LDNS_ANCOUNT(rr_chunk->data)) return 0;
4898 	if(rr_pos >= rr_chunk->len) return 0;
4899 
4900 	/* fetch rr information */
4901 	sldns_buffer_init_frm_data(&pkt, rr_chunk->data, rr_chunk->len);
4902 	if(rr_pos == 0) {
4903 		size_t i;
4904 		/* skip question section */
4905 		sldns_buffer_set_position(&pkt, LDNS_HEADER_SIZE);
4906 		for(i=0; i<LDNS_QDCOUNT(rr_chunk->data); i++) {
4907 			if(pkt_dname_len(&pkt) == 0) return 0;
4908 			if(sldns_buffer_remaining(&pkt) < 4) return 0;
4909 			sldns_buffer_skip(&pkt, 4); /* type and class */
4910 		}
4911 	} else	{
4912 		sldns_buffer_set_position(&pkt, rr_pos);
4913 	}
4914 	*rr_dname = sldns_buffer_current(&pkt);
4915 	if(pkt_dname_len(&pkt) == 0) return 0;
4916 	if(sldns_buffer_remaining(&pkt) < 10) return 0;
4917 	*rr_type = sldns_buffer_read_u16(&pkt);
4918 	*rr_class = sldns_buffer_read_u16(&pkt);
4919 	*rr_ttl = sldns_buffer_read_u32(&pkt);
4920 	*rr_rdlen = sldns_buffer_read_u16(&pkt);
4921 	if(sldns_buffer_remaining(&pkt) < (*rr_rdlen)) return 0;
4922 	*rr_rdata = sldns_buffer_current(&pkt);
4923 	sldns_buffer_skip(&pkt, (ssize_t)(*rr_rdlen));
4924 	*rr_nextpos = sldns_buffer_position(&pkt);
4925 	return 1;
4926 }
4927 
4928 /** print log message where we are in parsing the zone transfer */
4929 static void
log_rrlist_position(const char * label,struct auth_chunk * rr_chunk,uint8_t * rr_dname,uint16_t rr_type,size_t rr_counter)4930 log_rrlist_position(const char* label, struct auth_chunk* rr_chunk,
4931 	uint8_t* rr_dname, uint16_t rr_type, size_t rr_counter)
4932 {
4933 	sldns_buffer pkt;
4934 	size_t dlen;
4935 	uint8_t buf[LDNS_MAX_DOMAINLEN];
4936 	char str[LDNS_MAX_DOMAINLEN];
4937 	char typestr[32];
4938 	sldns_buffer_init_frm_data(&pkt, rr_chunk->data, rr_chunk->len);
4939 	sldns_buffer_set_position(&pkt, (size_t)(rr_dname -
4940 		sldns_buffer_begin(&pkt)));
4941 	if((dlen=pkt_dname_len(&pkt)) == 0) return;
4942 	if(dlen >= sizeof(buf)) return;
4943 	dname_pkt_copy(&pkt, buf, rr_dname);
4944 	dname_str(buf, str);
4945 	(void)sldns_wire2str_type_buf(rr_type, typestr, sizeof(typestr));
4946 	verbose(VERB_ALGO, "%s at[%d] %s %s", label, (int)rr_counter,
4947 		str, typestr);
4948 }
4949 
4950 /** check that start serial is OK for ixfr. we are at rr_counter == 0,
4951  * and we are going to check rr_counter == 1 (has to be type SOA) serial */
4952 static int
ixfr_start_serial(struct auth_chunk * rr_chunk,int rr_num,size_t rr_pos,uint8_t * rr_dname,uint16_t rr_type,uint16_t rr_class,uint32_t rr_ttl,uint16_t rr_rdlen,uint8_t * rr_rdata,size_t rr_nextpos,uint32_t transfer_serial,uint32_t xfr_serial)4953 ixfr_start_serial(struct auth_chunk* rr_chunk, int rr_num, size_t rr_pos,
4954 	uint8_t* rr_dname, uint16_t rr_type, uint16_t rr_class,
4955 	uint32_t rr_ttl, uint16_t rr_rdlen, uint8_t* rr_rdata,
4956 	size_t rr_nextpos, uint32_t transfer_serial, uint32_t xfr_serial)
4957 {
4958 	uint32_t startserial;
4959 	/* move forward on RR */
4960 	chunk_rrlist_gonext(&rr_chunk, &rr_num, &rr_pos, rr_nextpos);
4961 	if(chunk_rrlist_end(rr_chunk, rr_num)) {
4962 		/* no second SOA */
4963 		verbose(VERB_OPS, "IXFR has no second SOA record");
4964 		return 0;
4965 	}
4966 	if(!chunk_rrlist_get_current(rr_chunk, rr_num, rr_pos,
4967 		&rr_dname, &rr_type, &rr_class, &rr_ttl, &rr_rdlen,
4968 		&rr_rdata, &rr_nextpos)) {
4969 		verbose(VERB_OPS, "IXFR cannot parse second SOA record");
4970 		/* failed to parse RR */
4971 		return 0;
4972 	}
4973 	if(rr_type != LDNS_RR_TYPE_SOA) {
4974 		verbose(VERB_OPS, "IXFR second record is not type SOA");
4975 		return 0;
4976 	}
4977 	if(rr_rdlen < 22) {
4978 		verbose(VERB_OPS, "IXFR, second SOA has short rdlength");
4979 		return 0; /* bad SOA rdlen */
4980 	}
4981 	startserial = sldns_read_uint32(rr_rdata+rr_rdlen-20);
4982 	if(startserial == transfer_serial) {
4983 		/* empty AXFR, not an IXFR */
4984 		verbose(VERB_OPS, "IXFR second serial same as first");
4985 		return 0;
4986 	}
4987 	if(startserial != xfr_serial) {
4988 		/* wrong start serial, it does not match the serial in
4989 		 * memory */
4990 		verbose(VERB_OPS, "IXFR is from serial %u to %u but %u "
4991 			"in memory, rejecting the zone transfer",
4992 			(unsigned)startserial, (unsigned)transfer_serial,
4993 			(unsigned)xfr_serial);
4994 		return 0;
4995 	}
4996 	/* everything OK in second SOA serial */
4997 	return 1;
4998 }
4999 
5000 /** apply IXFR to zone in memory. z is locked. false on failure(mallocfail) */
5001 static int
apply_ixfr(struct auth_xfer * xfr,struct auth_zone * z,struct sldns_buffer * scratch_buffer)5002 apply_ixfr(struct auth_xfer* xfr, struct auth_zone* z,
5003 	struct sldns_buffer* scratch_buffer)
5004 {
5005 	struct auth_chunk* rr_chunk;
5006 	int rr_num;
5007 	size_t rr_pos;
5008 	uint8_t* rr_dname, *rr_rdata;
5009 	uint16_t rr_type, rr_class, rr_rdlen;
5010 	uint32_t rr_ttl;
5011 	size_t rr_nextpos;
5012 	int have_transfer_serial = 0;
5013 	uint32_t transfer_serial = 0;
5014 	size_t rr_counter = 0;
5015 	int delmode = 0;
5016 	int softfail = 0;
5017 
5018 	xfr->num_ixfrs++;
5019 
5020 	/* start RR iterator over chunklist of packets */
5021 	chunk_rrlist_start(xfr, &rr_chunk, &rr_num, &rr_pos);
5022 	while(!chunk_rrlist_end(rr_chunk, rr_num)) {
5023 		if(!chunk_rrlist_get_current(rr_chunk, rr_num, rr_pos,
5024 			&rr_dname, &rr_type, &rr_class, &rr_ttl, &rr_rdlen,
5025 			&rr_rdata, &rr_nextpos)) {
5026 			/* failed to parse RR */
5027 			return 0;
5028 		}
5029 		if(verbosity>=7) log_rrlist_position("apply ixfr",
5030 			rr_chunk, rr_dname, rr_type, rr_counter);
5031 		/* twiddle add/del mode and check for start and end */
5032 		if(rr_counter == 0 && rr_type != LDNS_RR_TYPE_SOA)
5033 			return 0;
5034 		if(rr_counter == 1 && rr_type != LDNS_RR_TYPE_SOA) {
5035 			/* this is an AXFR returned from the IXFR master */
5036 			/* but that should already have been detected, by
5037 			 * on_ixfr_is_axfr */
5038 			return 0;
5039 		}
5040 		if(rr_type == LDNS_RR_TYPE_SOA) {
5041 			uint32_t serial;
5042 			if(rr_rdlen < 22) return 0; /* bad SOA rdlen */
5043 			serial = sldns_read_uint32(rr_rdata+rr_rdlen-20);
5044 			if(have_transfer_serial == 0) {
5045 				have_transfer_serial = 1;
5046 				transfer_serial = serial;
5047 				delmode = 1; /* gets negated below */
5048 				/* check second RR before going any further */
5049 				if(!ixfr_start_serial(rr_chunk, rr_num, rr_pos,
5050 					rr_dname, rr_type, rr_class, rr_ttl,
5051 					rr_rdlen, rr_rdata, rr_nextpos,
5052 					transfer_serial, xfr->serial)) {
5053 					return 0;
5054 				}
5055 			} else if(transfer_serial == serial) {
5056 				have_transfer_serial++;
5057 				if(rr_counter == 1) {
5058 					/* empty AXFR, with SOA; SOA; */
5059 					/* should have been detected by
5060 					 * on_ixfr_is_axfr */
5061 					return 0;
5062 				}
5063 				if(have_transfer_serial == 3) {
5064 					/* see serial three times for end */
5065 					/* eg. IXFR:
5066 					 *  SOA 3 start
5067 					 *  SOA 1 second RR, followed by del
5068 					 *  SOA 2 followed by add
5069 					 *  SOA 2 followed by del
5070 					 *  SOA 3 followed by add
5071 					 *  SOA 3 end */
5072 					/* ended by SOA record */
5073 					xfr->serial = transfer_serial;
5074 					break;
5075 				}
5076 			}
5077 			/* twiddle add/del mode */
5078 			/* switch from delete part to add part and back again
5079 			 * just before the soa, it gets deleted and added too
5080 			 * this means we switch to delete mode for the final
5081 			 * SOA(so skip that one) */
5082 			delmode = !delmode;
5083 		}
5084 		/* process this RR */
5085 		/* if the RR is deleted twice or added twice, then we
5086 		 * softfail, and continue with the rest of the IXFR, so
5087 		 * that we serve something fairly nice during the refetch */
5088 		if(verbosity>=7) log_rrlist_position((delmode?"del":"add"),
5089 			rr_chunk, rr_dname, rr_type, rr_counter);
5090 		if(delmode) {
5091 			/* delete this RR */
5092 			int nonexist = 0;
5093 			if(!az_remove_rr_decompress(z, rr_chunk->data,
5094 				rr_chunk->len, scratch_buffer, rr_dname,
5095 				rr_type, rr_class, rr_ttl, rr_rdata, rr_rdlen,
5096 				&nonexist)) {
5097 				/* failed, malloc error or so */
5098 				return 0;
5099 			}
5100 			if(nonexist) {
5101 				/* it was removal of a nonexisting RR */
5102 				if(verbosity>=4) log_rrlist_position(
5103 					"IXFR error nonexistent RR",
5104 					rr_chunk, rr_dname, rr_type, rr_counter);
5105 				softfail = 1;
5106 			}
5107 		} else if(rr_counter != 0) {
5108 			/* skip first SOA RR for addition, it is added in
5109 			 * the addition part near the end of the ixfr, when
5110 			 * that serial is seen the second time. */
5111 			int duplicate = 0;
5112 			/* add this RR */
5113 			if(!az_insert_rr_decompress(z, rr_chunk->data,
5114 				rr_chunk->len, scratch_buffer, rr_dname,
5115 				rr_type, rr_class, rr_ttl, rr_rdata, rr_rdlen,
5116 				&duplicate)) {
5117 				/* failed, malloc error or so */
5118 				return 0;
5119 			}
5120 			if(duplicate) {
5121 				/* it was a duplicate */
5122 				if(verbosity>=4) log_rrlist_position(
5123 					"IXFR error duplicate RR",
5124 					rr_chunk, rr_dname, rr_type, rr_counter);
5125 				softfail = 1;
5126 			}
5127 		}
5128 
5129 		rr_counter++;
5130 		chunk_rrlist_gonext(&rr_chunk, &rr_num, &rr_pos, rr_nextpos);
5131 	}
5132 	if(softfail) {
5133 		verbose(VERB_ALGO, "IXFR did not apply cleanly, fetching full zone");
5134 		return 0;
5135 	}
5136 	return 1;
5137 }
5138 
5139 /** apply AXFR to zone in memory. z is locked. false on failure(mallocfail) */
5140 static int
apply_axfr(struct auth_xfer * xfr,struct auth_zone * z,struct sldns_buffer * scratch_buffer)5141 apply_axfr(struct auth_xfer* xfr, struct auth_zone* z,
5142 	struct sldns_buffer* scratch_buffer)
5143 {
5144 	struct auth_chunk* rr_chunk;
5145 	int rr_num;
5146 	size_t rr_pos;
5147 	uint8_t* rr_dname, *rr_rdata;
5148 	uint16_t rr_type, rr_class, rr_rdlen;
5149 	uint32_t rr_ttl;
5150 	uint32_t serial = 0;
5151 	size_t rr_nextpos;
5152 	size_t rr_counter = 0;
5153 	int have_end_soa = 0;
5154 
5155 	auth_zone_clear_data(z);
5156 	xfr->have_zone = 0;
5157 	xfr->serial = 0;
5158 	xfr->soa_zone_acquired = 0;
5159 	xfr->num_ixfrs = 0;
5160 
5161 	/* insert all RRs in to the zone */
5162 	/* insert the SOA only once, skip the last one */
5163 	/* start RR iterator over chunklist of packets */
5164 	chunk_rrlist_start(xfr, &rr_chunk, &rr_num, &rr_pos);
5165 	while(!chunk_rrlist_end(rr_chunk, rr_num)) {
5166 		if(!chunk_rrlist_get_current(rr_chunk, rr_num, rr_pos,
5167 			&rr_dname, &rr_type, &rr_class, &rr_ttl, &rr_rdlen,
5168 			&rr_rdata, &rr_nextpos)) {
5169 			/* failed to parse RR */
5170 			return 0;
5171 		}
5172 		if(verbosity>=7) log_rrlist_position("apply_axfr",
5173 			rr_chunk, rr_dname, rr_type, rr_counter);
5174 		if(rr_type == LDNS_RR_TYPE_SOA) {
5175 			if(rr_counter != 0) {
5176 				/* end of the axfr */
5177 				have_end_soa = 1;
5178 				break;
5179 			}
5180 			if(rr_rdlen < 22) return 0; /* bad SOA rdlen */
5181 			serial = sldns_read_uint32(rr_rdata+rr_rdlen-20);
5182 		}
5183 
5184 		/* add this RR */
5185 		if(!az_insert_rr_decompress(z, rr_chunk->data, rr_chunk->len,
5186 			scratch_buffer, rr_dname, rr_type, rr_class, rr_ttl,
5187 			rr_rdata, rr_rdlen, NULL)) {
5188 			/* failed, malloc error or so */
5189 			return 0;
5190 		}
5191 
5192 		rr_counter++;
5193 		chunk_rrlist_gonext(&rr_chunk, &rr_num, &rr_pos, rr_nextpos);
5194 	}
5195 	if(!have_end_soa) {
5196 		log_err("no end SOA record for AXFR");
5197 		return 0;
5198 	}
5199 
5200 	xfr->serial = serial;
5201 	xfr->have_zone = 1;
5202 	return 1;
5203 }
5204 
5205 /** apply HTTP to zone in memory. z is locked. false on failure(mallocfail) */
5206 static int
apply_http(struct auth_xfer * xfr,struct auth_zone * z,struct sldns_buffer * scratch_buffer)5207 apply_http(struct auth_xfer* xfr, struct auth_zone* z,
5208 	struct sldns_buffer* scratch_buffer)
5209 {
5210 	/* parse data in chunks */
5211 	/* parse RR's and read into memory. ignore $INCLUDE from the
5212 	 * downloaded file*/
5213 	struct sldns_file_parse_state pstate;
5214 	struct auth_chunk* chunk;
5215 	size_t chunk_pos;
5216 	int ret;
5217 	memset(&pstate, 0, sizeof(pstate));
5218 	pstate.default_ttl = 3600;
5219 	if(xfr->namelen < sizeof(pstate.origin)) {
5220 		pstate.origin_len = xfr->namelen;
5221 		memmove(pstate.origin, xfr->name, xfr->namelen);
5222 	}
5223 
5224 	if(verbosity >= VERB_ALGO)
5225 		verbose(VERB_ALGO, "http download %s of size %d",
5226 		xfr->task_transfer->master->file,
5227 		(int)chunklist_sum(xfr->task_transfer->chunks_first));
5228 	if(xfr->task_transfer->chunks_first && verbosity >= VERB_ALGO) {
5229 		char preview[1024];
5230 		if(xfr->task_transfer->chunks_first->len+1 > sizeof(preview)) {
5231 			memmove(preview, xfr->task_transfer->chunks_first->data,
5232 				sizeof(preview)-1);
5233 			preview[sizeof(preview)-1]=0;
5234 		} else {
5235 			memmove(preview, xfr->task_transfer->chunks_first->data,
5236 				xfr->task_transfer->chunks_first->len);
5237 			preview[xfr->task_transfer->chunks_first->len]=0;
5238 		}
5239 		log_info("auth zone http downloaded content preview: %s",
5240 			preview);
5241 	}
5242 
5243 	/* perhaps a little syntax check before we try to apply the data? */
5244 	if(!http_zonefile_syntax_check(xfr, scratch_buffer)) {
5245 		log_err("http download %s/%s does not contain a zonefile, "
5246 			"but got '%s'", xfr->task_transfer->master->host,
5247 			xfr->task_transfer->master->file,
5248 			sldns_buffer_begin(scratch_buffer));
5249 		return 0;
5250 	}
5251 
5252 	auth_zone_clear_data(z);
5253 	xfr->have_zone = 0;
5254 	xfr->serial = 0;
5255 	xfr->soa_zone_acquired = 0;
5256 	xfr->num_ixfrs = 0;
5257 
5258 	chunk = xfr->task_transfer->chunks_first;
5259 	chunk_pos = 0;
5260 	pstate.lineno = 0;
5261 	while(chunkline_get_line_collated(&chunk, &chunk_pos, scratch_buffer)) {
5262 		/* process this line */
5263 		pstate.lineno++;
5264 		chunkline_newline_removal(scratch_buffer);
5265 		if(chunkline_is_comment_line_or_empty(scratch_buffer)) {
5266 			continue;
5267 		}
5268 		/* parse line and add RR */
5269 		if((ret=http_parse_origin(scratch_buffer, &pstate))!=0) {
5270 			if(ret == 2) {
5271 				verbose(VERB_ALGO, "error parsing ORIGIN on line [%s:%d] %s",
5272 					xfr->task_transfer->master->file,
5273 					pstate.lineno,
5274 					sldns_buffer_begin(scratch_buffer));
5275 				return 0;
5276 			}
5277 			continue; /* $ORIGIN has been handled */
5278 		}
5279 		if((ret=http_parse_ttl(scratch_buffer, &pstate))!=0) {
5280 			if(ret == 2) {
5281 				verbose(VERB_ALGO, "error parsing TTL on line [%s:%d] %s",
5282 					xfr->task_transfer->master->file,
5283 					pstate.lineno,
5284 					sldns_buffer_begin(scratch_buffer));
5285 				return 0;
5286 			}
5287 			continue; /* $TTL has been handled */
5288 		}
5289 		if(!http_parse_add_rr(xfr, z, scratch_buffer, &pstate)) {
5290 			verbose(VERB_ALGO, "error parsing line [%s:%d] %s",
5291 				xfr->task_transfer->master->file,
5292 				pstate.lineno,
5293 				sldns_buffer_begin(scratch_buffer));
5294 			return 0;
5295 		}
5296 	}
5297 	return 1;
5298 }
5299 
5300 /** write http chunks to zonefile to create downloaded file */
5301 static int
auth_zone_write_chunks(struct auth_xfer * xfr,const char * fname)5302 auth_zone_write_chunks(struct auth_xfer* xfr, const char* fname)
5303 {
5304 	FILE* out;
5305 	struct auth_chunk* p;
5306 	out = fopen(fname, "w");
5307 	if(!out) {
5308 		log_err("could not open %s: %s", fname, strerror(errno));
5309 		return 0;
5310 	}
5311 	for(p = xfr->task_transfer->chunks_first; p ; p = p->next) {
5312 		if(!write_out(out, (char*)p->data, p->len)) {
5313 			log_err("could not write http download to %s", fname);
5314 			fclose(out);
5315 			return 0;
5316 		}
5317 	}
5318 	fclose(out);
5319 	return 1;
5320 }
5321 
5322 /** write to zonefile after zone has been updated */
5323 static void
xfr_write_after_update(struct auth_xfer * xfr,struct module_env * env)5324 xfr_write_after_update(struct auth_xfer* xfr, struct module_env* env)
5325 {
5326 	struct config_file* cfg = env->cfg;
5327 	struct auth_zone* z;
5328 	char tmpfile[1024];
5329 	char* zfilename;
5330 	lock_basic_unlock(&xfr->lock);
5331 
5332 	/* get lock again, so it is a readlock and concurrently queries
5333 	 * can be answered */
5334 	lock_rw_rdlock(&env->auth_zones->lock);
5335 	z = auth_zone_find(env->auth_zones, xfr->name, xfr->namelen,
5336 		xfr->dclass);
5337 	if(!z) {
5338 		lock_rw_unlock(&env->auth_zones->lock);
5339 		/* the zone is gone, ignore xfr results */
5340 		lock_basic_lock(&xfr->lock);
5341 		return;
5342 	}
5343 	lock_rw_rdlock(&z->lock);
5344 	lock_basic_lock(&xfr->lock);
5345 	lock_rw_unlock(&env->auth_zones->lock);
5346 
5347 	if(z->zonefile == NULL || z->zonefile[0] == 0) {
5348 		lock_rw_unlock(&z->lock);
5349 		/* no write needed, no zonefile set */
5350 		return;
5351 	}
5352 	zfilename = z->zonefile;
5353 	if(cfg->chrootdir && cfg->chrootdir[0] && strncmp(zfilename,
5354 		cfg->chrootdir, strlen(cfg->chrootdir)) == 0)
5355 		zfilename += strlen(cfg->chrootdir);
5356 	if(verbosity >= VERB_ALGO) {
5357 		char nm[LDNS_MAX_DOMAINLEN];
5358 		dname_str(z->name, nm);
5359 		verbose(VERB_ALGO, "write zonefile %s for %s", zfilename, nm);
5360 	}
5361 
5362 	/* write to tempfile first */
5363 	if((size_t)strlen(zfilename) + 16 > sizeof(tmpfile)) {
5364 		verbose(VERB_ALGO, "tmpfilename too long, cannot update "
5365 			" zonefile %s", zfilename);
5366 		lock_rw_unlock(&z->lock);
5367 		return;
5368 	}
5369 	snprintf(tmpfile, sizeof(tmpfile), "%s.tmp%u", zfilename,
5370 		(unsigned)getpid());
5371 	if(xfr->task_transfer->master->http) {
5372 		/* use the stored chunk list to write them */
5373 		if(!auth_zone_write_chunks(xfr, tmpfile)) {
5374 			unlink(tmpfile);
5375 			lock_rw_unlock(&z->lock);
5376 			return;
5377 		}
5378 	} else if(!auth_zone_write_file(z, tmpfile)) {
5379 		unlink(tmpfile);
5380 		lock_rw_unlock(&z->lock);
5381 		return;
5382 	}
5383 #ifdef UB_ON_WINDOWS
5384 	(void)unlink(zfilename); /* windows does not replace file with rename() */
5385 #endif
5386 	if(rename(tmpfile, zfilename) < 0) {
5387 		log_err("could not rename(%s, %s): %s", tmpfile, zfilename,
5388 			strerror(errno));
5389 		unlink(tmpfile);
5390 		lock_rw_unlock(&z->lock);
5391 		return;
5392 	}
5393 	lock_rw_unlock(&z->lock);
5394 }
5395 
5396 /** reacquire locks and structures. Starts with no locks, ends
5397  * with xfr and z locks, if fail, no z lock */
xfr_process_reacquire_locks(struct auth_xfer * xfr,struct module_env * env,struct auth_zone ** z)5398 static int xfr_process_reacquire_locks(struct auth_xfer* xfr,
5399 	struct module_env* env, struct auth_zone** z)
5400 {
5401 	/* release xfr lock, then, while holding az->lock grab both
5402 	 * z->lock and xfr->lock */
5403 	lock_rw_rdlock(&env->auth_zones->lock);
5404 	*z = auth_zone_find(env->auth_zones, xfr->name, xfr->namelen,
5405 		xfr->dclass);
5406 	if(!*z) {
5407 		lock_rw_unlock(&env->auth_zones->lock);
5408 		lock_basic_lock(&xfr->lock);
5409 		*z = NULL;
5410 		return 0;
5411 	}
5412 	lock_rw_wrlock(&(*z)->lock);
5413 	lock_basic_lock(&xfr->lock);
5414 	lock_rw_unlock(&env->auth_zones->lock);
5415 	return 1;
5416 }
5417 
5418 /** process chunk list and update zone in memory,
5419  * return false if it did not work */
5420 static int
xfr_process_chunk_list(struct auth_xfer * xfr,struct module_env * env,int * ixfr_fail)5421 xfr_process_chunk_list(struct auth_xfer* xfr, struct module_env* env,
5422 	int* ixfr_fail)
5423 {
5424 	struct auth_zone* z;
5425 
5426 	/* obtain locks and structures */
5427 	lock_basic_unlock(&xfr->lock);
5428 	if(!xfr_process_reacquire_locks(xfr, env, &z)) {
5429 		/* the zone is gone, ignore xfr results */
5430 		return 0;
5431 	}
5432 	/* holding xfr and z locks */
5433 
5434 	/* apply data */
5435 	if(xfr->task_transfer->master->http) {
5436 		if(!apply_http(xfr, z, env->scratch_buffer)) {
5437 			auth_zone_clear_data(z);
5438 			lock_rw_unlock(&z->lock);
5439 			verbose(VERB_ALGO, "http from %s: could not store data",
5440 				xfr->task_transfer->master->host);
5441 			return 0;
5442 		}
5443 	} else if(xfr->task_transfer->on_ixfr &&
5444 		!xfr->task_transfer->on_ixfr_is_axfr) {
5445 		if(!apply_ixfr(xfr, z, env->scratch_buffer)) {
5446 			auth_zone_clear_data(z);
5447 			lock_rw_unlock(&z->lock);
5448 			verbose(VERB_ALGO, "xfr from %s: could not store IXFR"
5449 				" data", xfr->task_transfer->master->host);
5450 			*ixfr_fail = 1;
5451 			return 0;
5452 		}
5453 	} else {
5454 		if(!apply_axfr(xfr, z, env->scratch_buffer)) {
5455 			auth_zone_clear_data(z);
5456 			lock_rw_unlock(&z->lock);
5457 			verbose(VERB_ALGO, "xfr from %s: could not store AXFR"
5458 				" data", xfr->task_transfer->master->host);
5459 			return 0;
5460 		}
5461 	}
5462 	xfr->zone_expired = 0;
5463 	z->zone_expired = 0;
5464 	if(!xfr_find_soa(z, xfr)) {
5465 		lock_rw_unlock(&z->lock);
5466 		verbose(VERB_ALGO, "xfr from %s: no SOA in zone after update"
5467 			" (or malformed RR)", xfr->task_transfer->master->host);
5468 		return 0;
5469 	}
5470 	z->soa_zone_acquired = *env->now;
5471 	xfr->soa_zone_acquired = *env->now;
5472 	xfr->is_rpz = (z->rpz!=NULL);
5473 
5474 	/* release xfr lock while verifying zonemd because it may have
5475 	 * to spawn lookups in the state machines */
5476 	lock_basic_unlock(&xfr->lock);
5477 	/* holding z lock */
5478 	auth_zone_verify_zonemd(z, env, &env->mesh->mods, NULL, 0, 0);
5479 	if(z->zone_expired) {
5480 		char zname[LDNS_MAX_DOMAINLEN];
5481 		/* ZONEMD must have failed */
5482 		/* reacquire locks, so we hold xfr lock on exit of routine,
5483 		 * and both xfr and z again after releasing xfr for potential
5484 		 * state machine mesh callbacks */
5485 		lock_rw_unlock(&z->lock);
5486 		if(!xfr_process_reacquire_locks(xfr, env, &z))
5487 			return 0;
5488 		dname_str(xfr->name, zname);
5489 		verbose(VERB_ALGO, "xfr from %s: ZONEMD failed for %s, transfer is failed", xfr->task_transfer->master->host, zname);
5490 		xfr->zone_expired = 1;
5491 		lock_rw_unlock(&z->lock);
5492 		return 0;
5493 	}
5494 	/* reacquire locks, so we hold xfr lock on exit of routine,
5495 	 * and both xfr and z again after releasing xfr for potential
5496 	 * state machine mesh callbacks */
5497 	lock_rw_unlock(&z->lock);
5498 	if(!xfr_process_reacquire_locks(xfr, env, &z))
5499 		return 0;
5500 	/* holding xfr and z locks */
5501 
5502 	if(xfr->have_zone)
5503 		xfr->lease_time = *env->now;
5504 
5505 	if(z->rpz)
5506 		rpz_finish_config(z->rpz);
5507 
5508 	/* unlock */
5509 	lock_rw_unlock(&z->lock);
5510 
5511 	if(verbosity >= VERB_QUERY && xfr->have_zone) {
5512 		char zname[LDNS_MAX_DOMAINLEN];
5513 		dname_str(xfr->name, zname);
5514 		verbose(VERB_QUERY, "auth zone %s updated to serial %u", zname,
5515 			(unsigned)xfr->serial);
5516 	}
5517 	/* see if we need to write to a zonefile */
5518 	xfr_write_after_update(xfr, env);
5519 	return 1;
5520 }
5521 
5522 /** Stop lookup using callback */
5523 static void
xfr_stop_lookup(struct auth_master ** lookup_target,void * lookup_unique_info,int lookup_aaaa,uint16_t dclass,struct mesh_area * mesh,mesh_cb_func_type cb,void * cb_arg)5524 xfr_stop_lookup(struct auth_master** lookup_target, void* lookup_unique_info,
5525 	int lookup_aaaa, uint16_t dclass, struct mesh_area* mesh,
5526 	mesh_cb_func_type cb, void* cb_arg)
5527 {
5528 	struct query_info qinfo;
5529 	uint8_t dname[LDNS_MAX_DOMAINLEN+1];
5530 	if(!*lookup_target) return;
5531 	qinfo.qname_len = sizeof(dname);
5532 	if(sldns_str2wire_dname_buf((*lookup_target)->host, dname,
5533 		&qinfo.qname_len) != 0) {
5534 		*lookup_target = NULL;
5535 		return;
5536 	}
5537 	qinfo.qname = dname;
5538 	qinfo.qclass = dclass;
5539 	qinfo.qtype = lookup_aaaa ? LDNS_RR_TYPE_AAAA : LDNS_RR_TYPE_A;
5540 	qinfo.local_alias = NULL;
5541 	log_query_info(VERB_ALGO, "removing xfr callback", &qinfo);
5542 
5543 	mesh_remove_callback(mesh, &qinfo, BIT_RD, cb, cb_arg,
5544 		lookup_unique_info);
5545 	*lookup_target = NULL;
5546 }
5547 
5548 /** disown task_transfer.  caller must hold xfr.lock */
5549 static void
xfr_transfer_disown(struct auth_xfer * xfr)5550 xfr_transfer_disown(struct auth_xfer* xfr)
5551 {
5552 	/* remove data chunks */
5553 	auth_chunks_delete(xfr->task_transfer);
5554 	/* remove timer (from this worker's event base) */
5555 	comm_timer_delete(xfr->task_transfer->timer);
5556 	xfr->task_transfer->timer = NULL;
5557 	/* remove the commpoint */
5558 	comm_point_delete(xfr->task_transfer->cp);
5559 	xfr->task_transfer->cp = NULL;
5560 	if(xfr->task_transfer->env)
5561 		xfr_stop_lookup(&xfr->task_transfer->lookup_target,
5562 			xfr->task_transfer->lookup_unique_info,
5563 			xfr->task_transfer->lookup_aaaa, xfr->dclass,
5564 			xfr->task_transfer->env->mesh,
5565 			&auth_xfer_transfer_lookup_callback, xfr);
5566 	/* we don't own this item anymore */
5567 	xfr->task_transfer->worker = NULL;
5568 	xfr->task_transfer->env = NULL;
5569 }
5570 
5571 /** lookup a host name for its addresses, if needed */
5572 static int
xfr_transfer_lookup_host(struct auth_xfer * xfr,struct module_env * env)5573 xfr_transfer_lookup_host(struct auth_xfer* xfr, struct module_env* env)
5574 {
5575 	struct sockaddr_storage addr;
5576 	socklen_t addrlen = 0;
5577 	struct auth_master* master = xfr->task_transfer->lookup_target;
5578 	struct query_info qinfo;
5579 	uint16_t qflags = BIT_RD;
5580 	uint8_t dname[LDNS_MAX_DOMAINLEN+1];
5581 	struct edns_data edns;
5582 	sldns_buffer* buf = env->scratch_buffer;
5583 	if(!master) return 0;
5584 	if(extstrtoaddr(master->host, &addr, &addrlen, UNBOUND_DNS_PORT)) {
5585 		/* not needed, host is in IP addr format */
5586 		return 0;
5587 	}
5588 	if(master->allow_notify)
5589 		return 0; /* allow-notifies are not transferred from, no
5590 		lookup is needed */
5591 
5592 	/* use mesh_new_callback to probe for non-addr hosts,
5593 	 * and then wait for them to be looked up (in cache, or query) */
5594 	qinfo.qname_len = sizeof(dname);
5595 	if(sldns_str2wire_dname_buf(master->host, dname, &qinfo.qname_len)
5596 		!= 0) {
5597 		log_err("cannot parse host name of master %s", master->host);
5598 		return 0;
5599 	}
5600 	qinfo.qname = dname;
5601 	qinfo.qclass = xfr->dclass;
5602 	qinfo.qtype = LDNS_RR_TYPE_A;
5603 	if(xfr->task_transfer->lookup_aaaa)
5604 		qinfo.qtype = LDNS_RR_TYPE_AAAA;
5605 	qinfo.local_alias = NULL;
5606 	if(verbosity >= VERB_ALGO) {
5607 		char buf1[512];
5608 		char buf2[LDNS_MAX_DOMAINLEN];
5609 		dname_str(xfr->name, buf2);
5610 		snprintf(buf1, sizeof(buf1), "auth zone %s: master lookup"
5611 			" for task_transfer", buf2);
5612 		log_query_info(VERB_ALGO, buf1, &qinfo);
5613 	}
5614 	edns.edns_present = 1;
5615 	edns.ext_rcode = 0;
5616 	edns.edns_version = 0;
5617 	edns.bits = EDNS_DO;
5618 	edns.opt_list_in = NULL;
5619 	edns.opt_list_out = NULL;
5620 	edns.opt_list_inplace_cb_out = NULL;
5621 	edns.padding_block_size = 0;
5622 	edns.cookie_present = 0;
5623 	edns.cookie_valid = 0;
5624 	if(sldns_buffer_capacity(buf) < 65535)
5625 		edns.udp_size = (uint16_t)sldns_buffer_capacity(buf);
5626 	else	edns.udp_size = 65535;
5627 
5628 	/* unlock xfr during mesh_new_callback() because the callback can be
5629 	 * called straight away */
5630 	lock_basic_unlock(&xfr->lock);
5631 	if(!mesh_new_callback(env->mesh, &qinfo, qflags, &edns, buf, 0,
5632 		&auth_xfer_transfer_lookup_callback, xfr, 0,
5633 		&xfr->task_transfer->lookup_unique_info)) {
5634 		lock_basic_lock(&xfr->lock);
5635 		log_err("out of memory lookup up master %s", master->host);
5636 		return 0;
5637 	}
5638 	lock_basic_lock(&xfr->lock);
5639 	return 1;
5640 }
5641 
5642 /** initiate TCP to the target and fetch zone.
5643  * returns true if that was successfully started, and timeout setup. */
5644 static int
xfr_transfer_init_fetch(struct auth_xfer * xfr,struct module_env * env)5645 xfr_transfer_init_fetch(struct auth_xfer* xfr, struct module_env* env)
5646 {
5647 	struct sockaddr_storage addr;
5648 	socklen_t addrlen = 0;
5649 	struct auth_master* master = xfr->task_transfer->master;
5650 	char *auth_name = NULL;
5651 	struct timeval t;
5652 	int timeout;
5653 	if(!master) return 0;
5654 	if(master->allow_notify) return 0; /* only for notify */
5655 
5656 	/* get master addr */
5657 	if(xfr->task_transfer->scan_addr) {
5658 		addrlen = xfr->task_transfer->scan_addr->addrlen;
5659 		memmove(&addr, &xfr->task_transfer->scan_addr->addr, addrlen);
5660 	} else {
5661 		if(!authextstrtoaddr(master->host, &addr, &addrlen, &auth_name)) {
5662 			/* the ones that are not in addr format are supposed
5663 			 * to be looked up.  The lookup has failed however,
5664 			 * so skip them */
5665 			char zname[LDNS_MAX_DOMAINLEN];
5666 			dname_str(xfr->name, zname);
5667 			log_err("%s: failed lookup, cannot transfer from master %s",
5668 				zname, master->host);
5669 			return 0;
5670 		}
5671 	}
5672 
5673 	/* remove previous TCP connection (if any) */
5674 	if(xfr->task_transfer->cp) {
5675 		comm_point_delete(xfr->task_transfer->cp);
5676 		xfr->task_transfer->cp = NULL;
5677 	}
5678 	if(!xfr->task_transfer->timer) {
5679 		xfr->task_transfer->timer = comm_timer_create(env->worker_base,
5680 			auth_xfer_transfer_timer_callback, xfr);
5681 		if(!xfr->task_transfer->timer) {
5682 			log_err("malloc failure");
5683 			return 0;
5684 		}
5685 	}
5686 	timeout = AUTH_TRANSFER_TIMEOUT;
5687 #ifndef S_SPLINT_S
5688         t.tv_sec = timeout/1000;
5689         t.tv_usec = (timeout%1000)*1000;
5690 #endif
5691 	xfr->task_transfer->start_time = *env->now_tv;
5692 
5693 	if(master->http) {
5694 		/* perform http fetch */
5695 		/* store http port number into sockaddr,
5696 		 * unless someone used unbound's host@port notation */
5697 		xfr->task_transfer->on_ixfr = 0;
5698 		if(strchr(master->host, '@') == NULL)
5699 			sockaddr_store_port(&addr, addrlen, master->port);
5700 		xfr->task_transfer->cp = outnet_comm_point_for_http(
5701 			env->outnet, auth_xfer_transfer_http_callback, xfr,
5702 			&addr, addrlen, -1, master->ssl, master->host,
5703 			master->file, env->cfg);
5704 		if(!xfr->task_transfer->cp) {
5705 			char zname[LDNS_MAX_DOMAINLEN], as[256];
5706 			dname_str(xfr->name, zname);
5707 			addr_port_to_str(&addr, addrlen, as, sizeof(as));
5708 			verbose(VERB_ALGO, "cannot create http cp "
5709 				"connection for %s to %s", zname, as);
5710 			return 0;
5711 		}
5712 		comm_timer_set(xfr->task_transfer->timer, &t);
5713 		if(verbosity >= VERB_ALGO) {
5714 			char zname[LDNS_MAX_DOMAINLEN], as[256];
5715 			dname_str(xfr->name, zname);
5716 			addr_port_to_str(&addr, addrlen, as, sizeof(as));
5717 			verbose(VERB_ALGO, "auth zone %s transfer next HTTP fetch from %s started", zname, as);
5718 		}
5719 		/* Create or refresh the list of allow_notify addrs */
5720 		probe_copy_masters_for_allow_notify(xfr);
5721 		return 1;
5722 	}
5723 
5724 	/* perform AXFR/IXFR */
5725 	/* set the packet to be written */
5726 	/* create new ID */
5727 	xfr->task_transfer->id = GET_RANDOM_ID(env->rnd);
5728 	xfr_create_ixfr_packet(xfr, env->scratch_buffer,
5729 		xfr->task_transfer->id, master);
5730 
5731 	/* connect on fd */
5732 	xfr->task_transfer->cp = outnet_comm_point_for_tcp(env->outnet,
5733 		auth_xfer_transfer_tcp_callback, xfr, &addr, addrlen,
5734 		env->scratch_buffer, -1,
5735 		auth_name != NULL, auth_name);
5736 	if(!xfr->task_transfer->cp) {
5737 		char zname[LDNS_MAX_DOMAINLEN], as[256];
5738  		dname_str(xfr->name, zname);
5739 		addr_port_to_str(&addr, addrlen, as, sizeof(as));
5740 		verbose(VERB_ALGO, "cannot create tcp cp connection for "
5741 			"xfr %s to %s", zname, as);
5742 		return 0;
5743 	}
5744 	comm_timer_set(xfr->task_transfer->timer, &t);
5745 	if(verbosity >= VERB_ALGO) {
5746 		char zname[LDNS_MAX_DOMAINLEN], as[256];
5747  		dname_str(xfr->name, zname);
5748 		addr_port_to_str(&addr, addrlen, as, sizeof(as));
5749 		verbose(VERB_ALGO, "auth zone %s transfer next %s fetch from %s started", zname,
5750 			(xfr->task_transfer->on_ixfr?"IXFR":"AXFR"), as);
5751 	}
5752 	return 1;
5753 }
5754 
5755 /** perform next lookup, next transfer TCP, or end and resume wait time task */
5756 static void
xfr_transfer_nexttarget_or_end(struct auth_xfer * xfr,struct module_env * env)5757 xfr_transfer_nexttarget_or_end(struct auth_xfer* xfr, struct module_env* env)
5758 {
5759 	log_assert(xfr->task_transfer->worker == env->worker);
5760 
5761 	/* are we performing lookups? */
5762 	while(xfr->task_transfer->lookup_target) {
5763 		if(xfr_transfer_lookup_host(xfr, env)) {
5764 			/* wait for lookup to finish,
5765 			 * note that the hostname may be in unbound's cache
5766 			 * and we may then get an instant cache response,
5767 			 * and that calls the callback just like a full
5768 			 * lookup and lookup failures also call callback */
5769 			if(verbosity >= VERB_ALGO) {
5770 				char zname[LDNS_MAX_DOMAINLEN];
5771 				dname_str(xfr->name, zname);
5772 				verbose(VERB_ALGO, "auth zone %s transfer next target lookup", zname);
5773 			}
5774 			lock_basic_unlock(&xfr->lock);
5775 			return;
5776 		}
5777 		xfr_transfer_move_to_next_lookup(xfr, env);
5778 	}
5779 
5780 	/* initiate TCP and fetch the zone from the master */
5781 	/* and set timeout on it */
5782 	while(!xfr_transfer_end_of_list(xfr)) {
5783 		xfr->task_transfer->master = xfr_transfer_current_master(xfr);
5784 		if(xfr_transfer_init_fetch(xfr, env)) {
5785 			/* successfully started, wait for callback */
5786 			lock_basic_unlock(&xfr->lock);
5787 			return;
5788 		}
5789 		/* failed to fetch, next master */
5790 		xfr_transfer_nextmaster(xfr);
5791 	}
5792 	if(verbosity >= VERB_ALGO) {
5793 		char zname[LDNS_MAX_DOMAINLEN];
5794 		dname_str(xfr->name, zname);
5795 		verbose(VERB_ALGO, "auth zone %s transfer failed, wait", zname);
5796 	}
5797 
5798 	/* we failed to fetch the zone, move to wait task
5799 	 * use the shorter retry timeout */
5800 	xfr_transfer_disown(xfr);
5801 
5802 	/* pick up the nextprobe task and wait */
5803 	if(xfr->task_nextprobe->worker == NULL)
5804 		xfr_set_timeout(xfr, env, 1, 0);
5805 	lock_basic_unlock(&xfr->lock);
5806 }
5807 
5808 /** add addrs from A or AAAA rrset to the master */
5809 static void
xfr_master_add_addrs(struct auth_master * m,struct ub_packed_rrset_key * rrset,uint16_t rrtype)5810 xfr_master_add_addrs(struct auth_master* m, struct ub_packed_rrset_key* rrset,
5811 	uint16_t rrtype)
5812 {
5813 	size_t i;
5814 	struct packed_rrset_data* data;
5815 	if(!m || !rrset) return;
5816 	if(rrtype != LDNS_RR_TYPE_A && rrtype != LDNS_RR_TYPE_AAAA)
5817 		return;
5818 	data = (struct packed_rrset_data*)rrset->entry.data;
5819 	for(i=0; i<data->count; i++) {
5820 		struct auth_addr* a;
5821 		size_t len = data->rr_len[i] - 2;
5822 		uint8_t* rdata = data->rr_data[i]+2;
5823 		if(rrtype == LDNS_RR_TYPE_A && len != INET_SIZE)
5824 			continue; /* wrong length for A */
5825 		if(rrtype == LDNS_RR_TYPE_AAAA && len != INET6_SIZE)
5826 			continue; /* wrong length for AAAA */
5827 
5828 		/* add and alloc it */
5829 		a = (struct auth_addr*)calloc(1, sizeof(*a));
5830 		if(!a) {
5831 			log_err("out of memory");
5832 			return;
5833 		}
5834 		if(rrtype == LDNS_RR_TYPE_A) {
5835 			struct sockaddr_in* sa;
5836 			a->addrlen = (socklen_t)sizeof(*sa);
5837 			sa = (struct sockaddr_in*)&a->addr;
5838 			sa->sin_family = AF_INET;
5839 			sa->sin_port = (in_port_t)htons(UNBOUND_DNS_PORT);
5840 			memmove(&sa->sin_addr, rdata, INET_SIZE);
5841 		} else {
5842 			struct sockaddr_in6* sa;
5843 			a->addrlen = (socklen_t)sizeof(*sa);
5844 			sa = (struct sockaddr_in6*)&a->addr;
5845 			sa->sin6_family = AF_INET6;
5846 			sa->sin6_port = (in_port_t)htons(UNBOUND_DNS_PORT);
5847 			memmove(&sa->sin6_addr, rdata, INET6_SIZE);
5848 		}
5849 		if(verbosity >= VERB_ALGO) {
5850 			char s[64];
5851 			addr_port_to_str(&a->addr, a->addrlen, s, sizeof(s));
5852 			verbose(VERB_ALGO, "auth host %s lookup %s",
5853 				m->host, s);
5854 		}
5855 		/* append to list */
5856 		a->next = m->list;
5857 		m->list = a;
5858 	}
5859 }
5860 
5861 /** check if the lookup target name equals the found answer name. */
5862 static int
xfer_target_equals_answer_name(struct auth_master * lookup_target,struct ub_packed_rrset_key * answer,struct query_info * rq,struct reply_info * rep)5863 xfer_target_equals_answer_name(struct auth_master* lookup_target,
5864 	struct ub_packed_rrset_key* answer, struct query_info* rq,
5865 	struct reply_info* rep)
5866 {
5867 	uint8_t qname[LDNS_MAX_DOMAINLEN+1];
5868 	size_t qname_len;
5869 	if(!lookup_target) return 0;
5870 	if(!answer) return 0;
5871 	qname_len = sizeof(qname);
5872 	if(sldns_str2wire_dname_buf(lookup_target->host, qname, &qname_len)
5873 		!= 0) {
5874 		verbose(VERB_ALGO, "xfer_target_equals_answer_name: could not parse auth host name");
5875 		return 0;
5876 	}
5877 	if(query_dname_compare(answer->rk.dname, qname) == 0)
5878 		return 1;
5879 	/* It could be a CNAME. */
5880 	if(reply_find_rrset_section_an(rep, qname, qname_len,
5881 		LDNS_RR_TYPE_CNAME, rq->qclass))
5882 		return 1;
5883 	return 0;
5884 }
5885 
5886 /** callback for task_transfer lookup of host name, of A or AAAA */
auth_xfer_transfer_lookup_callback(void * arg,int rcode,sldns_buffer * buf,enum sec_status sec,char * why_bogus,int ATTR_UNUSED (was_ratelimited))5887 void auth_xfer_transfer_lookup_callback(void* arg, int rcode, sldns_buffer* buf,
5888 	enum sec_status sec, char* why_bogus, int ATTR_UNUSED(was_ratelimited))
5889 {
5890 	struct auth_xfer* xfr = (struct auth_xfer*)arg;
5891 	struct module_env* env;
5892 	log_assert(xfr->task_transfer);
5893 	lock_basic_lock(&xfr->lock);
5894 	env = xfr->task_transfer->env;
5895 	if(!env || env->outnet->want_to_quit) {
5896 		lock_basic_unlock(&xfr->lock);
5897 		return; /* stop on quit */
5898 	}
5899 
5900 	/* process result */
5901 	if(sec == sec_status_bogus || sec == sec_status_secure_sentinel_fail) {
5902 		if(verbosity >= VERB_OPS) {
5903 			char zname[LDNS_MAX_DOMAINLEN];
5904 			dname_str(xfr->name, zname);
5905 			verbose(VERB_OPS, "auth zone %s: primary %s address lookup is DNSSEC bogus: %s",
5906 				zname, xfr->task_transfer->lookup_target->host,
5907 				(why_bogus?why_bogus:""));
5908 		}
5909 		/* fall through to next-lookup / next-master */
5910 	} else if(rcode == LDNS_RCODE_NOERROR) {
5911 		uint16_t wanted_qtype = LDNS_RR_TYPE_A;
5912 		struct regional* temp = env->scratch;
5913 		struct query_info rq;
5914 		struct reply_info* rep;
5915 		if(xfr->task_transfer->lookup_aaaa)
5916 			wanted_qtype = LDNS_RR_TYPE_AAAA;
5917 		memset(&rq, 0, sizeof(rq));
5918 		rep = parse_reply_in_temp_region(buf, temp, &rq);
5919 		if(rep && rq.qtype == wanted_qtype &&
5920 			FLAGS_GET_RCODE(rep->flags) == LDNS_RCODE_NOERROR) {
5921 			/* parsed successfully */
5922 			struct ub_packed_rrset_key* answer =
5923 				reply_find_answer_rrset(&rq, rep);
5924 			if(answer && xfer_target_equals_answer_name(
5925 				xfr->task_transfer->lookup_target, answer,
5926 				&rq, rep)) {
5927 				xfr_master_add_addrs(xfr->task_transfer->
5928 					lookup_target, answer, wanted_qtype);
5929 			} else if(answer) {
5930 				if(verbosity >= VERB_ALGO) {
5931 					char zname[LDNS_MAX_DOMAINLEN];
5932 					dname_str(xfr->name, zname);
5933 					verbose(VERB_ALGO, "auth zone %s host %s type %s transfer lookup has mismatch in answer name", zname, ((xfr->task_transfer->lookup_target && xfr->task_transfer->lookup_target->host) ? xfr->task_transfer->lookup_target->host : "null"), (xfr->task_transfer->lookup_aaaa?"AAAA":"A"));
5934 				}
5935 			} else {
5936 				if(verbosity >= VERB_ALGO) {
5937 					char zname[LDNS_MAX_DOMAINLEN];
5938 					dname_str(xfr->name, zname);
5939 					verbose(VERB_ALGO, "auth zone %s host %s type %s transfer lookup has nodata", zname, ((xfr->task_transfer->lookup_target && xfr->task_transfer->lookup_target->host) ? xfr->task_transfer->lookup_target->host : "null"), (xfr->task_transfer->lookup_aaaa?"AAAA":"A"));
5940 				}
5941 			}
5942 		} else {
5943 			if(verbosity >= VERB_ALGO) {
5944 				char zname[LDNS_MAX_DOMAINLEN];
5945 				dname_str(xfr->name, zname);
5946 				verbose(VERB_ALGO, "auth zone %s host %s type %s transfer lookup has no answer", zname, ((xfr->task_transfer->lookup_target && xfr->task_transfer->lookup_target->host) ? xfr->task_transfer->lookup_target->host : "null"), (xfr->task_transfer->lookup_aaaa?"AAAA":"A"));
5947 			}
5948 		}
5949 		regional_free_all(temp);
5950 	} else {
5951 		if(verbosity >= VERB_ALGO) {
5952 			char zname[LDNS_MAX_DOMAINLEN];
5953 			dname_str(xfr->name, zname);
5954 			verbose(VERB_ALGO, "auth zone %s host %s type %s transfer lookup failed", zname, ((xfr->task_transfer->lookup_target && xfr->task_transfer->lookup_target->host) ? xfr->task_transfer->lookup_target->host : "null"), (xfr->task_transfer->lookup_aaaa?"AAAA":"A"));
5955 		}
5956 	}
5957 	if(xfr->task_transfer->lookup_target &&
5958 		xfr->task_transfer->lookup_target->list &&
5959 		xfr->task_transfer->lookup_target == xfr_transfer_current_master(xfr))
5960 		xfr->task_transfer->scan_addr = xfr->task_transfer->lookup_target->list;
5961 
5962 	/* move to lookup AAAA after A lookup, move to next hostname lookup,
5963 	 * or move to fetch the zone, or, if nothing to do, end task_transfer */
5964 	xfr_transfer_move_to_next_lookup(xfr, env);
5965 	xfr_transfer_nexttarget_or_end(xfr, env);
5966 }
5967 
5968 /** check if xfer (AXFR or IXFR) packet is OK.
5969  * return false if we lost connection (SERVFAIL, or unreadable).
5970  * return false if we need to move from IXFR to AXFR, with gonextonfail
5971  * 	set to false, so the same master is tried again, but with AXFR.
5972  * return true if fine to link into data.
5973  * return true with transferdone=true when the transfer has ended.
5974  */
5975 static int
check_xfer_packet(sldns_buffer * pkt,struct auth_xfer * xfr,int * gonextonfail,int * transferdone)5976 check_xfer_packet(sldns_buffer* pkt, struct auth_xfer* xfr,
5977 	int* gonextonfail, int* transferdone)
5978 {
5979 	uint8_t* wire = sldns_buffer_begin(pkt);
5980 	int i;
5981 	if(sldns_buffer_limit(pkt) < LDNS_HEADER_SIZE) {
5982 		verbose(VERB_ALGO, "xfr to %s failed, packet too small",
5983 			xfr->task_transfer->master->host);
5984 		return 0;
5985 	}
5986 	if(!LDNS_QR_WIRE(wire)) {
5987 		verbose(VERB_ALGO, "xfr to %s failed, packet has no QR flag",
5988 			xfr->task_transfer->master->host);
5989 		return 0;
5990 	}
5991 	if(LDNS_TC_WIRE(wire)) {
5992 		verbose(VERB_ALGO, "xfr to %s failed, packet has TC flag",
5993 			xfr->task_transfer->master->host);
5994 		return 0;
5995 	}
5996 	/* check ID */
5997 	if(LDNS_ID_WIRE(wire) != xfr->task_transfer->id) {
5998 		verbose(VERB_ALGO, "xfr to %s failed, packet wrong ID",
5999 			xfr->task_transfer->master->host);
6000 		return 0;
6001 	}
6002 	if(LDNS_RCODE_WIRE(wire) != LDNS_RCODE_NOERROR) {
6003 		char rcode[32];
6004 		sldns_wire2str_rcode_buf((int)LDNS_RCODE_WIRE(wire), rcode,
6005 			sizeof(rcode));
6006 		/* if we are doing IXFR, check for fallback */
6007 		if(xfr->task_transfer->on_ixfr) {
6008 			if(LDNS_RCODE_WIRE(wire) == LDNS_RCODE_NOTIMPL ||
6009 				LDNS_RCODE_WIRE(wire) == LDNS_RCODE_SERVFAIL ||
6010 				LDNS_RCODE_WIRE(wire) == LDNS_RCODE_REFUSED ||
6011 				LDNS_RCODE_WIRE(wire) == LDNS_RCODE_FORMERR) {
6012 				verbose(VERB_ALGO, "xfr to %s, fallback "
6013 					"from IXFR to AXFR (with rcode %s)",
6014 					xfr->task_transfer->master->host,
6015 					rcode);
6016 				xfr->task_transfer->ixfr_fail = 1;
6017 				*gonextonfail = 0;
6018 				return 0;
6019 			}
6020 		}
6021 		verbose(VERB_ALGO, "xfr to %s failed, packet with rcode %s",
6022 			xfr->task_transfer->master->host, rcode);
6023 		return 0;
6024 	}
6025 	if(LDNS_OPCODE_WIRE(wire) != LDNS_PACKET_QUERY) {
6026 		verbose(VERB_ALGO, "xfr to %s failed, packet with bad opcode",
6027 			xfr->task_transfer->master->host);
6028 		return 0;
6029 	}
6030 	if(LDNS_QDCOUNT(wire) > 1) {
6031 		verbose(VERB_ALGO, "xfr to %s failed, packet has qdcount %d",
6032 			xfr->task_transfer->master->host,
6033 			(int)LDNS_QDCOUNT(wire));
6034 		return 0;
6035 	}
6036 
6037 	/* check qname */
6038 	sldns_buffer_set_position(pkt, LDNS_HEADER_SIZE);
6039 	for(i=0; i<(int)LDNS_QDCOUNT(wire); i++) {
6040 		size_t pos = sldns_buffer_position(pkt);
6041 		uint16_t qtype, qclass;
6042 		if(pkt_dname_len(pkt) == 0) {
6043 			verbose(VERB_ALGO, "xfr to %s failed, packet with "
6044 				"malformed dname",
6045 				xfr->task_transfer->master->host);
6046 			return 0;
6047 		}
6048 		if(dname_pkt_compare(pkt, sldns_buffer_at(pkt, pos),
6049 			xfr->name) != 0) {
6050 			verbose(VERB_ALGO, "xfr to %s failed, packet with "
6051 				"wrong qname",
6052 				xfr->task_transfer->master->host);
6053 			return 0;
6054 		}
6055 		if(sldns_buffer_remaining(pkt) < 4) {
6056 			verbose(VERB_ALGO, "xfr to %s failed, packet with "
6057 				"truncated query RR",
6058 				xfr->task_transfer->master->host);
6059 			return 0;
6060 		}
6061 		qtype = sldns_buffer_read_u16(pkt);
6062 		qclass = sldns_buffer_read_u16(pkt);
6063 		if(qclass != xfr->dclass) {
6064 			verbose(VERB_ALGO, "xfr to %s failed, packet with "
6065 				"wrong qclass",
6066 				xfr->task_transfer->master->host);
6067 			return 0;
6068 		}
6069 		if(xfr->task_transfer->on_ixfr) {
6070 			if(qtype != LDNS_RR_TYPE_IXFR) {
6071 				verbose(VERB_ALGO, "xfr to %s failed, packet "
6072 					"with wrong qtype, expected IXFR",
6073 				xfr->task_transfer->master->host);
6074 				return 0;
6075 			}
6076 		} else {
6077 			if(qtype != LDNS_RR_TYPE_AXFR) {
6078 				verbose(VERB_ALGO, "xfr to %s failed, packet "
6079 					"with wrong qtype, expected AXFR",
6080 				xfr->task_transfer->master->host);
6081 				return 0;
6082 			}
6083 		}
6084 	}
6085 
6086 	/* check parse of RRs in packet, store first SOA serial
6087 	 * to be able to detect last SOA (with that serial) to see if done */
6088 	/* also check for IXFR 'zone up to date' reply */
6089 	for(i=0; i<(int)LDNS_ANCOUNT(wire); i++) {
6090 		size_t pos = sldns_buffer_position(pkt);
6091 		uint16_t tp, rdlen;
6092 		if(pkt_dname_len(pkt) == 0) {
6093 			verbose(VERB_ALGO, "xfr to %s failed, packet with "
6094 				"malformed dname in answer section",
6095 				xfr->task_transfer->master->host);
6096 			return 0;
6097 		}
6098 		if(sldns_buffer_remaining(pkt) < 10) {
6099 			verbose(VERB_ALGO, "xfr to %s failed, packet with "
6100 				"truncated RR",
6101 				xfr->task_transfer->master->host);
6102 			return 0;
6103 		}
6104 		tp = sldns_buffer_read_u16(pkt);
6105 		(void)sldns_buffer_read_u16(pkt); /* class */
6106 		(void)sldns_buffer_read_u32(pkt); /* ttl */
6107 		rdlen = sldns_buffer_read_u16(pkt);
6108 		if(sldns_buffer_remaining(pkt) < rdlen) {
6109 			verbose(VERB_ALGO, "xfr to %s failed, packet with "
6110 				"truncated RR rdata",
6111 				xfr->task_transfer->master->host);
6112 			return 0;
6113 		}
6114 
6115 		/* RR parses (haven't checked rdata itself), now look at
6116 		 * SOA records to see serial number */
6117 		if(xfr->task_transfer->rr_scan_num == 0 &&
6118 			tp != LDNS_RR_TYPE_SOA) {
6119 			verbose(VERB_ALGO, "xfr to %s failed, packet with "
6120 				"malformed zone transfer, no start SOA",
6121 				xfr->task_transfer->master->host);
6122 			return 0;
6123 		}
6124 		if(xfr->task_transfer->rr_scan_num == 1 &&
6125 			tp != LDNS_RR_TYPE_SOA) {
6126 			/* second RR is not a SOA record, this is not an IXFR
6127 			 * the master is replying with an AXFR */
6128 			xfr->task_transfer->on_ixfr_is_axfr = 1;
6129 		}
6130 		if(tp == LDNS_RR_TYPE_SOA) {
6131 			uint32_t serial;
6132 			if(rdlen < 22) {
6133 				verbose(VERB_ALGO, "xfr to %s failed, packet "
6134 					"with SOA with malformed rdata",
6135 					xfr->task_transfer->master->host);
6136 				return 0;
6137 			}
6138 			if(dname_pkt_compare(pkt, sldns_buffer_at(pkt, pos),
6139 				xfr->name) != 0) {
6140 				verbose(VERB_ALGO, "xfr to %s failed, packet "
6141 					"with SOA with wrong dname",
6142 					xfr->task_transfer->master->host);
6143 				return 0;
6144 			}
6145 
6146 			/* read serial number of SOA */
6147 			serial = sldns_buffer_read_u32_at(pkt,
6148 				sldns_buffer_position(pkt)+rdlen-20);
6149 
6150 			/* check for IXFR 'zone has SOA x' reply */
6151 			if(xfr->task_transfer->on_ixfr &&
6152 				xfr->task_transfer->rr_scan_num == 0 &&
6153 				LDNS_ANCOUNT(wire)==1) {
6154 				verbose(VERB_ALGO, "xfr to %s ended, "
6155 					"IXFR reply that zone has serial %u,"
6156 					" fallback from IXFR to AXFR",
6157 					xfr->task_transfer->master->host,
6158 					(unsigned)serial);
6159 				xfr->task_transfer->ixfr_fail = 1;
6160 				*gonextonfail = 0;
6161 				return 0;
6162 			}
6163 
6164 			/* if first SOA, store serial number */
6165 			if(xfr->task_transfer->got_xfr_serial == 0) {
6166 				xfr->task_transfer->got_xfr_serial = 1;
6167 				xfr->task_transfer->incoming_xfr_serial =
6168 					serial;
6169 				verbose(VERB_ALGO, "xfr %s: contains "
6170 					"SOA serial %u",
6171 					xfr->task_transfer->master->host,
6172 					(unsigned)serial);
6173 			/* see if end of AXFR */
6174 			} else if(!xfr->task_transfer->on_ixfr ||
6175 				xfr->task_transfer->on_ixfr_is_axfr) {
6176 				/* second SOA with serial is the end
6177 				 * for AXFR */
6178 				*transferdone = 1;
6179 				verbose(VERB_ALGO, "xfr %s: last AXFR packet",
6180 					xfr->task_transfer->master->host);
6181 			/* for IXFR, count SOA records with that serial */
6182 			} else if(xfr->task_transfer->incoming_xfr_serial ==
6183 				serial && xfr->task_transfer->got_xfr_serial
6184 				== 1) {
6185 				xfr->task_transfer->got_xfr_serial++;
6186 			/* if not first soa, if serial==firstserial, the
6187 			 * third time we are at the end, for IXFR */
6188 			} else if(xfr->task_transfer->incoming_xfr_serial ==
6189 				serial && xfr->task_transfer->got_xfr_serial
6190 				== 2) {
6191 				verbose(VERB_ALGO, "xfr %s: last IXFR packet",
6192 					xfr->task_transfer->master->host);
6193 				*transferdone = 1;
6194 				/* continue parse check, if that succeeds,
6195 				 * transfer is done */
6196 			}
6197 		}
6198 		xfr->task_transfer->rr_scan_num++;
6199 
6200 		/* skip over RR rdata to go to the next RR */
6201 		sldns_buffer_skip(pkt, (ssize_t)rdlen);
6202 	}
6203 
6204 	/* check authority section */
6205 	/* we skip over the RRs checking packet format */
6206 	for(i=0; i<(int)LDNS_NSCOUNT(wire); i++) {
6207 		uint16_t rdlen;
6208 		if(pkt_dname_len(pkt) == 0) {
6209 			verbose(VERB_ALGO, "xfr to %s failed, packet with "
6210 				"malformed dname in authority section",
6211 				xfr->task_transfer->master->host);
6212 			return 0;
6213 		}
6214 		if(sldns_buffer_remaining(pkt) < 10) {
6215 			verbose(VERB_ALGO, "xfr to %s failed, packet with "
6216 				"truncated RR",
6217 				xfr->task_transfer->master->host);
6218 			return 0;
6219 		}
6220 		(void)sldns_buffer_read_u16(pkt); /* type */
6221 		(void)sldns_buffer_read_u16(pkt); /* class */
6222 		(void)sldns_buffer_read_u32(pkt); /* ttl */
6223 		rdlen = sldns_buffer_read_u16(pkt);
6224 		if(sldns_buffer_remaining(pkt) < rdlen) {
6225 			verbose(VERB_ALGO, "xfr to %s failed, packet with "
6226 				"truncated RR rdata",
6227 				xfr->task_transfer->master->host);
6228 			return 0;
6229 		}
6230 		/* skip over RR rdata to go to the next RR */
6231 		sldns_buffer_skip(pkt, (ssize_t)rdlen);
6232 	}
6233 
6234 	/* check additional section */
6235 	for(i=0; i<(int)LDNS_ARCOUNT(wire); i++) {
6236 		uint16_t rdlen;
6237 		if(pkt_dname_len(pkt) == 0) {
6238 			verbose(VERB_ALGO, "xfr to %s failed, packet with "
6239 				"malformed dname in additional section",
6240 				xfr->task_transfer->master->host);
6241 			return 0;
6242 		}
6243 		if(sldns_buffer_remaining(pkt) < 10) {
6244 			verbose(VERB_ALGO, "xfr to %s failed, packet with "
6245 				"truncated RR",
6246 				xfr->task_transfer->master->host);
6247 			return 0;
6248 		}
6249 		(void)sldns_buffer_read_u16(pkt); /* type */
6250 		(void)sldns_buffer_read_u16(pkt); /* class */
6251 		(void)sldns_buffer_read_u32(pkt); /* ttl */
6252 		rdlen = sldns_buffer_read_u16(pkt);
6253 		if(sldns_buffer_remaining(pkt) < rdlen) {
6254 			verbose(VERB_ALGO, "xfr to %s failed, packet with "
6255 				"truncated RR rdata",
6256 				xfr->task_transfer->master->host);
6257 			return 0;
6258 		}
6259 		/* skip over RR rdata to go to the next RR */
6260 		sldns_buffer_skip(pkt, (ssize_t)rdlen);
6261 	}
6262 
6263 	return 1;
6264 }
6265 
6266 /** Link the data from this packet into the worklist of transferred data */
6267 static int
xfer_link_data(sldns_buffer * pkt,struct auth_xfer * xfr)6268 xfer_link_data(sldns_buffer* pkt, struct auth_xfer* xfr)
6269 {
6270 	/* alloc it */
6271 	struct auth_chunk* e;
6272 	e = (struct auth_chunk*)calloc(1, sizeof(*e));
6273 	if(!e) return 0;
6274 	e->next = NULL;
6275 	e->len = sldns_buffer_limit(pkt);
6276 	e->data = memdup(sldns_buffer_begin(pkt), e->len);
6277 	if(!e->data) {
6278 		free(e);
6279 		return 0;
6280 	}
6281 
6282 	/* alloc succeeded, link into list */
6283 	if(!xfr->task_transfer->chunks_first)
6284 		xfr->task_transfer->chunks_first = e;
6285 	if(xfr->task_transfer->chunks_last)
6286 		xfr->task_transfer->chunks_last->next = e;
6287 	xfr->task_transfer->chunks_last = e;
6288 	xfr->task_transfer->chunks_total += e->len;
6289 	return 1;
6290 }
6291 
6292 /** task transfer.  the list of data is complete. process it and if failed
6293  * move to next master, if succeeded, end the task transfer */
6294 static void
process_list_end_transfer(struct auth_xfer * xfr,struct module_env * env)6295 process_list_end_transfer(struct auth_xfer* xfr, struct module_env* env)
6296 {
6297 	int ixfr_fail = 0;
6298 	if(xfr_process_chunk_list(xfr, env, &ixfr_fail)) {
6299 		/* it worked! */
6300 		auth_chunks_delete(xfr->task_transfer);
6301 
6302 		/* we fetched the zone, move to wait task */
6303 		xfr_transfer_disown(xfr);
6304 
6305 		if(xfr->notify_received && (!xfr->notify_has_serial ||
6306 			(xfr->notify_has_serial &&
6307 			xfr_serial_means_update(xfr, xfr->notify_serial)))) {
6308 			uint32_t sr = xfr->notify_serial;
6309 			int has_sr = xfr->notify_has_serial;
6310 			/* we received a notify while probe/transfer was
6311 			 * in progress.  start a new probe and transfer */
6312 			xfr->notify_received = 0;
6313 			xfr->notify_has_serial = 0;
6314 			xfr->notify_serial = 0;
6315 			if(!xfr_start_probe(xfr, env, NULL)) {
6316 				/* if we couldn't start it, already in
6317 				 * progress; restore notify serial,
6318 				 * while xfr still locked */
6319 				xfr->notify_received = 1;
6320 				xfr->notify_has_serial = has_sr;
6321 				xfr->notify_serial = sr;
6322 				lock_basic_unlock(&xfr->lock);
6323 			}
6324 			return;
6325 		} else {
6326 			/* pick up the nextprobe task and wait (normail wait time) */
6327 			if(xfr->task_nextprobe->worker == NULL)
6328 				xfr_set_timeout(xfr, env, 0, 0);
6329 		}
6330 		lock_basic_unlock(&xfr->lock);
6331 		return;
6332 	}
6333 	/* processing failed */
6334 	/* when done, delete data from list */
6335 	auth_chunks_delete(xfr->task_transfer);
6336 	if(ixfr_fail) {
6337 		xfr->task_transfer->ixfr_fail = 1;
6338 	} else {
6339 		xfr_transfer_nextmaster(xfr);
6340 	}
6341 	xfr_transfer_nexttarget_or_end(xfr, env);
6342 }
6343 
6344 /** callback for the task_transfer timer */
6345 void
auth_xfer_transfer_timer_callback(void * arg)6346 auth_xfer_transfer_timer_callback(void* arg)
6347 {
6348 	struct auth_xfer* xfr = (struct auth_xfer*)arg;
6349 	struct module_env* env;
6350 	int gonextonfail = 1;
6351 	log_assert(xfr->task_transfer);
6352 	lock_basic_lock(&xfr->lock);
6353 	env = xfr->task_transfer->env;
6354 	if(!env || env->outnet->want_to_quit) {
6355 		lock_basic_unlock(&xfr->lock);
6356 		return; /* stop on quit */
6357 	}
6358 
6359 	verbose(VERB_ALGO, "xfr stopped, connection timeout to %s",
6360 		xfr->task_transfer->master->host);
6361 
6362 	/* see if IXFR caused the failure, if so, try AXFR */
6363 	if(xfr->task_transfer->on_ixfr) {
6364 		xfr->task_transfer->ixfr_possible_timeout_count++;
6365 		if(xfr->task_transfer->ixfr_possible_timeout_count >=
6366 			NUM_TIMEOUTS_FALLBACK_IXFR) {
6367 			verbose(VERB_ALGO, "xfr to %s, fallback "
6368 				"from IXFR to AXFR (because of timeouts)",
6369 				xfr->task_transfer->master->host);
6370 			xfr->task_transfer->ixfr_fail = 1;
6371 			gonextonfail = 0;
6372 		}
6373 	}
6374 
6375 	/* delete transferred data from list */
6376 	auth_chunks_delete(xfr->task_transfer);
6377 	comm_point_delete(xfr->task_transfer->cp);
6378 	xfr->task_transfer->cp = NULL;
6379 	if(gonextonfail)
6380 		xfr_transfer_nextmaster(xfr);
6381 	xfr_transfer_nexttarget_or_end(xfr, env);
6382 }
6383 
6384 /** return the time taken by the transfer */
6385 static int
auth_xfer_transfer_time_taken(struct auth_xfer * xfr,struct module_env * env)6386 auth_xfer_transfer_time_taken(struct auth_xfer* xfr, struct module_env* env)
6387 {
6388 	struct timeval delta;
6389 	timeval_subtract(&delta, env->now_tv, &xfr->task_transfer->start_time);
6390 	return ((int)delta.tv_sec)*1000 + ((int)delta.tv_usec)/1000;
6391 }
6392 
6393 /** callback for task_transfer tcp connections */
6394 int
auth_xfer_transfer_tcp_callback(struct comm_point * c,void * arg,int err,struct comm_reply * ATTR_UNUSED (repinfo))6395 auth_xfer_transfer_tcp_callback(struct comm_point* c, void* arg, int err,
6396 	struct comm_reply* ATTR_UNUSED(repinfo))
6397 {
6398 	struct auth_xfer* xfr = (struct auth_xfer*)arg;
6399 	struct module_env* env;
6400 	int gonextonfail = 1;
6401 	int transferdone = 0;
6402 	log_assert(xfr->task_transfer);
6403 	lock_basic_lock(&xfr->lock);
6404 	env = xfr->task_transfer->env;
6405 	if(!env || env->outnet->want_to_quit) {
6406 		lock_basic_unlock(&xfr->lock);
6407 		return 0; /* stop on quit */
6408 	}
6409 	/* stop the timer */
6410 	comm_timer_disable(xfr->task_transfer->timer);
6411 
6412 	if(err != NETEVENT_NOERROR) {
6413 		/* connection failed, closed, or timeout */
6414 		/* stop this transfer, cleanup
6415 		 * and continue task_transfer*/
6416 		verbose(VERB_ALGO, "xfr stopped, connection lost to %s",
6417 			xfr->task_transfer->master->host);
6418 
6419 		/* see if IXFR caused the failure, if so, try AXFR */
6420 		if(xfr->task_transfer->on_ixfr) {
6421 			xfr->task_transfer->ixfr_possible_timeout_count++;
6422 			if(xfr->task_transfer->ixfr_possible_timeout_count >=
6423 				NUM_TIMEOUTS_FALLBACK_IXFR) {
6424 				verbose(VERB_ALGO, "xfr to %s, fallback "
6425 					"from IXFR to AXFR (because of timeouts)",
6426 					xfr->task_transfer->master->host);
6427 				xfr->task_transfer->ixfr_fail = 1;
6428 				gonextonfail = 0;
6429 			}
6430 		}
6431 
6432 	failed:
6433 		/* delete transferred data from list */
6434 		auth_chunks_delete(xfr->task_transfer);
6435 		comm_point_delete(xfr->task_transfer->cp);
6436 		xfr->task_transfer->cp = NULL;
6437 		if(gonextonfail)
6438 			xfr_transfer_nextmaster(xfr);
6439 		xfr_transfer_nexttarget_or_end(xfr, env);
6440 		return 0;
6441 	}
6442 	/* note that IXFR worked without timeout */
6443 	if(xfr->task_transfer->on_ixfr)
6444 		xfr->task_transfer->ixfr_possible_timeout_count = 0;
6445 
6446 	/* handle returned packet */
6447 	/* if it fails, cleanup and end this transfer */
6448 	/* if it needs to fallback from IXFR to AXFR, do that */
6449 	if(!check_xfer_packet(c->buffer, xfr, &gonextonfail, &transferdone)) {
6450 		goto failed;
6451 	}
6452 	/* if it is good, link it into the list of data */
6453 	/* if the link into list of data fails (malloc fail) cleanup and end */
6454 	if(!xfer_link_data(c->buffer, xfr)) {
6455 		verbose(VERB_ALGO, "xfr stopped to %s, malloc failed",
6456 			xfr->task_transfer->master->host);
6457 		goto failed;
6458 	}
6459 	if(xfr->max_transfer_size > 0 &&
6460 		xfr->task_transfer->chunks_total > xfr->max_transfer_size) {
6461 		char zname[LDNS_MAX_DOMAINLEN];
6462 		dname_str(xfr->name, zname);
6463 		log_err("auth zone %s transfer from %s exceeded %u bytes, aborting",
6464 			zname, xfr->task_transfer->master->host,
6465 			(unsigned)xfr->max_transfer_size);
6466 		goto failed;
6467 	}
6468 	/* if the transfer is done now, disconnect and process the list */
6469 	if(transferdone) {
6470 		comm_point_delete(xfr->task_transfer->cp);
6471 		xfr->task_transfer->cp = NULL;
6472 		process_list_end_transfer(xfr, env);
6473 		return 0;
6474 	}
6475 
6476 	if(xfr->max_transfer_time > 0 &&
6477 		auth_xfer_transfer_time_taken(xfr, env) > xfr->max_transfer_time) {
6478 		char zname[LDNS_MAX_DOMAINLEN];
6479 		dname_str(xfr->name, zname);
6480 		log_err("auth zone %s transfer from %s exceeded %u msec total running time, aborting",
6481 			zname, xfr->task_transfer->master->host,
6482 			(unsigned)xfr->max_transfer_time);
6483 		goto failed;
6484 	}
6485 
6486 	/* if we want to read more messages, setup the commpoint to read
6487 	 * a DNS packet, and the timeout */
6488 	lock_basic_unlock(&xfr->lock);
6489 	c->tcp_is_reading = 1;
6490 	sldns_buffer_clear(c->buffer);
6491 	comm_point_start_listening(c, -1, AUTH_TRANSFER_TIMEOUT);
6492 	return 0;
6493 }
6494 
6495 /** callback for task_transfer http connections */
6496 int
auth_xfer_transfer_http_callback(struct comm_point * c,void * arg,int err,struct comm_reply * repinfo)6497 auth_xfer_transfer_http_callback(struct comm_point* c, void* arg, int err,
6498 	struct comm_reply* repinfo)
6499 {
6500 	struct auth_xfer* xfr = (struct auth_xfer*)arg;
6501 	struct module_env* env;
6502 	log_assert(xfr->task_transfer);
6503 	lock_basic_lock(&xfr->lock);
6504 	env = xfr->task_transfer->env;
6505 	if(!env || env->outnet->want_to_quit) {
6506 		lock_basic_unlock(&xfr->lock);
6507 		return 0; /* stop on quit */
6508 	}
6509 	verbose(VERB_ALGO, "auth zone transfer http callback");
6510 	/* stop the timer */
6511 	comm_timer_disable(xfr->task_transfer->timer);
6512 
6513 	if(err != NETEVENT_NOERROR && err != NETEVENT_DONE) {
6514 		/* connection failed, closed, or timeout */
6515 		/* stop this transfer, cleanup
6516 		 * and continue task_transfer*/
6517 		verbose(VERB_ALGO, "http stopped, connection lost to %s",
6518 			xfr->task_transfer->master->host);
6519 	failed:
6520 		/* delete transferred data from list */
6521 		auth_chunks_delete(xfr->task_transfer);
6522 		if(repinfo) repinfo->c = NULL; /* signal cp deleted to
6523 				the routine calling this callback */
6524 		comm_point_delete(xfr->task_transfer->cp);
6525 		xfr->task_transfer->cp = NULL;
6526 		xfr_transfer_nextmaster(xfr);
6527 		xfr_transfer_nexttarget_or_end(xfr, env);
6528 		return 0;
6529 	}
6530 
6531 	/* if it is good, link it into the list of data */
6532 	/* if the link into list of data fails (malloc fail) cleanup and end */
6533 	if(sldns_buffer_limit(c->buffer) > 0) {
6534 		verbose(VERB_ALGO, "auth zone http queued up %d bytes",
6535 			(int)sldns_buffer_limit(c->buffer));
6536 		if(!xfer_link_data(c->buffer, xfr)) {
6537 			verbose(VERB_ALGO, "http stopped to %s, malloc failed",
6538 				xfr->task_transfer->master->host);
6539 			goto failed;
6540 		}
6541 		if(xfr->max_transfer_size > 0 &&
6542 			xfr->task_transfer->chunks_total > xfr->max_transfer_size) {
6543 			char zname[LDNS_MAX_DOMAINLEN];
6544 			dname_str(xfr->name, zname);
6545 			log_err("auth zone %s http %s/%s exceeded %u bytes, aborting",
6546 				zname, xfr->task_transfer->master->host,
6547 				xfr->task_transfer->master->file,
6548 				(unsigned)xfr->max_transfer_size);
6549 			goto failed;
6550 		}
6551 	}
6552 	/* if the transfer is done now, disconnect and process the list */
6553 	if(err == NETEVENT_DONE) {
6554 		if(repinfo) repinfo->c = NULL; /* signal cp deleted to
6555 				the routine calling this callback */
6556 		comm_point_delete(xfr->task_transfer->cp);
6557 		xfr->task_transfer->cp = NULL;
6558 		process_list_end_transfer(xfr, env);
6559 		return 0;
6560 	}
6561 
6562 	if(xfr->max_transfer_time > 0 &&
6563 		auth_xfer_transfer_time_taken(xfr, env) > xfr->max_transfer_time) {
6564 		char zname[LDNS_MAX_DOMAINLEN];
6565 		dname_str(xfr->name, zname);
6566 		log_err("auth zone %s transfer http %s/%s exceeded %u msec total running time, aborting",
6567 			zname, xfr->task_transfer->master->host,
6568 			xfr->task_transfer->master->file,
6569 			(unsigned)xfr->max_transfer_time);
6570 		goto failed;
6571 	}
6572 
6573 	/* if we want to read more messages, setup the commpoint to read
6574 	 * a DNS packet, and the timeout */
6575 	lock_basic_unlock(&xfr->lock);
6576 	c->tcp_is_reading = 1;
6577 	sldns_buffer_clear(c->buffer);
6578 	comm_point_start_listening(c, -1, AUTH_TRANSFER_TIMEOUT);
6579 	return 0;
6580 }
6581 
6582 
6583 /** start transfer task by this worker , xfr is locked. */
6584 static void
xfr_start_transfer(struct auth_xfer * xfr,struct module_env * env,struct auth_master * master)6585 xfr_start_transfer(struct auth_xfer* xfr, struct module_env* env,
6586 	struct auth_master* master)
6587 {
6588 	log_assert(xfr->task_transfer != NULL);
6589 	log_assert(xfr->task_transfer->worker == NULL);
6590 	log_assert(xfr->task_transfer->chunks_first == NULL);
6591 	log_assert(xfr->task_transfer->chunks_last == NULL);
6592 	xfr->task_transfer->worker = env->worker;
6593 	xfr->task_transfer->env = env;
6594 
6595 	/* init transfer process */
6596 	/* find that master in the transfer's list of masters? */
6597 	xfr_transfer_start_list(xfr, master);
6598 	/* start lookup for hostnames in transfer master list */
6599 	xfr_transfer_start_lookups(xfr);
6600 
6601 	/* initiate TCP, and set timeout on it */
6602 	xfr_transfer_nexttarget_or_end(xfr, env);
6603 }
6604 
6605 /** disown task_probe.  caller must hold xfr.lock */
6606 static void
xfr_probe_disown(struct auth_xfer * xfr)6607 xfr_probe_disown(struct auth_xfer* xfr)
6608 {
6609 	/* remove timer (from this worker's event base) */
6610 	comm_timer_delete(xfr->task_probe->timer);
6611 	xfr->task_probe->timer = NULL;
6612 	/* remove the commpoint */
6613 	comm_point_delete(xfr->task_probe->cp);
6614 	xfr->task_probe->cp = NULL;
6615 	if(xfr->task_probe->env)
6616 		xfr_stop_lookup(&xfr->task_probe->lookup_target,
6617 			xfr->task_probe->lookup_unique_info,
6618 			xfr->task_probe->lookup_aaaa, xfr->dclass,
6619 			xfr->task_probe->env->mesh,
6620 			&auth_xfer_probe_lookup_callback, xfr);
6621 	/* we don't own this item anymore */
6622 	xfr->task_probe->worker = NULL;
6623 	xfr->task_probe->env = NULL;
6624 }
6625 
6626 /** send the UDP probe to the master, this is part of task_probe */
6627 static int
xfr_probe_send_probe(struct auth_xfer * xfr,struct module_env * env,int timeout)6628 xfr_probe_send_probe(struct auth_xfer* xfr, struct module_env* env,
6629 	int timeout)
6630 {
6631 	struct sockaddr_storage addr;
6632 	socklen_t addrlen = 0;
6633 	struct timeval t;
6634 	/* pick master */
6635 	struct auth_master* master = xfr_probe_current_master(xfr);
6636 	char *auth_name = NULL;
6637 	if(!master) return 0;
6638 	if(master->allow_notify) return 0; /* only for notify */
6639 	if(master->http) return 0; /* only masters get SOA UDP probe,
6640 		not urls, if those are in this list */
6641 
6642 	/* get master addr */
6643 	if(xfr->task_probe->scan_addr) {
6644 		addrlen = xfr->task_probe->scan_addr->addrlen;
6645 		memmove(&addr, &xfr->task_probe->scan_addr->addr, addrlen);
6646 	} else {
6647 		if(!authextstrtoaddr(master->host, &addr, &addrlen, &auth_name)) {
6648 			/* the ones that are not in addr format are supposed
6649 			 * to be looked up.  The lookup has failed however,
6650 			 * so skip them */
6651 			char zname[LDNS_MAX_DOMAINLEN];
6652 			dname_str(xfr->name, zname);
6653 			log_err("%s: failed lookup, cannot probe to master %s",
6654 				zname, master->host);
6655 			return 0;
6656 		}
6657 		if (auth_name != NULL) {
6658 			if (addr.ss_family == AF_INET
6659 			&&  (int)ntohs(((struct sockaddr_in *)&addr)->sin_port)
6660 		            == env->cfg->ssl_port)
6661 				((struct sockaddr_in *)&addr)->sin_port
6662 					= htons((uint16_t)env->cfg->port);
6663 			else if (addr.ss_family == AF_INET6
6664 			&&  (int)ntohs(((struct sockaddr_in6 *)&addr)->sin6_port)
6665 		            == env->cfg->ssl_port)
6666                         	((struct sockaddr_in6 *)&addr)->sin6_port
6667 					= htons((uint16_t)env->cfg->port);
6668 		}
6669 	}
6670 
6671 	/* create packet */
6672 	/* create new ID for new probes, but not on timeout retries,
6673 	 * this means we'll accept replies to previous retries to same ip */
6674 	if(timeout == AUTH_PROBE_TIMEOUT)
6675 		xfr->task_probe->id = GET_RANDOM_ID(env->rnd);
6676 	xfr_create_soa_probe_packet(xfr, env->scratch_buffer,
6677 		xfr->task_probe->id);
6678 	/* we need to remove the cp if we have a different ip4/ip6 type now */
6679 	if(xfr->task_probe->cp &&
6680 		((xfr->task_probe->cp_is_ip6 && !addr_is_ip6(&addr, addrlen)) ||
6681 		(!xfr->task_probe->cp_is_ip6 && addr_is_ip6(&addr, addrlen)))
6682 		) {
6683 		comm_point_delete(xfr->task_probe->cp);
6684 		xfr->task_probe->cp = NULL;
6685 	}
6686 	if(!xfr->task_probe->cp) {
6687 		if(addr_is_ip6(&addr, addrlen))
6688 			xfr->task_probe->cp_is_ip6 = 1;
6689 		else 	xfr->task_probe->cp_is_ip6 = 0;
6690 		xfr->task_probe->cp = outnet_comm_point_for_udp(env->outnet,
6691 			auth_xfer_probe_udp_callback, xfr, &addr, addrlen);
6692 		if(!xfr->task_probe->cp) {
6693 			char zname[LDNS_MAX_DOMAINLEN], as[256];
6694 			dname_str(xfr->name, zname);
6695 			addr_port_to_str(&addr, addrlen, as, sizeof(as));
6696 			verbose(VERB_ALGO, "cannot create udp cp for "
6697 				"probe %s to %s", zname, as);
6698 			return 0;
6699 		}
6700 	}
6701 	if(!xfr->task_probe->timer) {
6702 		xfr->task_probe->timer = comm_timer_create(env->worker_base,
6703 			auth_xfer_probe_timer_callback, xfr);
6704 		if(!xfr->task_probe->timer) {
6705 			log_err("malloc failure");
6706 			return 0;
6707 		}
6708 	}
6709 
6710 	/* send udp packet */
6711 	if(!comm_point_send_udp_msg(xfr->task_probe->cp, env->scratch_buffer,
6712 		(struct sockaddr*)&addr, addrlen, 0)) {
6713 		char zname[LDNS_MAX_DOMAINLEN], as[256];
6714 		dname_str(xfr->name, zname);
6715 		addr_port_to_str(&addr, addrlen, as, sizeof(as));
6716 		verbose(VERB_ALGO, "failed to send soa probe for %s to %s",
6717 			zname, as);
6718 		return 0;
6719 	}
6720 	if(verbosity >= VERB_ALGO) {
6721 		char zname[LDNS_MAX_DOMAINLEN], as[256];
6722 		dname_str(xfr->name, zname);
6723 		addr_port_to_str(&addr, addrlen, as, sizeof(as));
6724 		verbose(VERB_ALGO, "auth zone %s soa probe sent to %s", zname,
6725 			as);
6726 	}
6727 	xfr->task_probe->timeout = timeout;
6728 #ifndef S_SPLINT_S
6729 	t.tv_sec = timeout/1000;
6730 	t.tv_usec = (timeout%1000)*1000;
6731 #endif
6732 	comm_timer_set(xfr->task_probe->timer, &t);
6733 
6734 	return 1;
6735 }
6736 
6737 /** callback for task_probe timer */
6738 void
auth_xfer_probe_timer_callback(void * arg)6739 auth_xfer_probe_timer_callback(void* arg)
6740 {
6741 	struct auth_xfer* xfr = (struct auth_xfer*)arg;
6742 	struct module_env* env;
6743 	log_assert(xfr->task_probe);
6744 	lock_basic_lock(&xfr->lock);
6745 	env = xfr->task_probe->env;
6746 	if(!env || env->outnet->want_to_quit) {
6747 		lock_basic_unlock(&xfr->lock);
6748 		return; /* stop on quit */
6749 	}
6750 
6751 	if(verbosity >= VERB_ALGO) {
6752 		char zname[LDNS_MAX_DOMAINLEN];
6753 		dname_str(xfr->name, zname);
6754 		verbose(VERB_ALGO, "auth zone %s soa probe timeout", zname);
6755 	}
6756 	if(xfr->task_probe->timeout <= AUTH_PROBE_TIMEOUT_STOP) {
6757 		/* try again with bigger timeout */
6758 		if(xfr_probe_send_probe(xfr, env, xfr->task_probe->timeout*2)) {
6759 			lock_basic_unlock(&xfr->lock);
6760 			return;
6761 		}
6762 	}
6763 	/* delete commpoint so a new one is created, with a fresh port nr */
6764 	comm_point_delete(xfr->task_probe->cp);
6765 	xfr->task_probe->cp = NULL;
6766 
6767 	/* too many timeouts (or fail to send), move to next or end */
6768 	xfr_probe_nextmaster(xfr);
6769 	xfr_probe_send_or_end(xfr, env);
6770 }
6771 
6772 /** callback for task_probe udp packets */
6773 int
auth_xfer_probe_udp_callback(struct comm_point * c,void * arg,int err,struct comm_reply * repinfo)6774 auth_xfer_probe_udp_callback(struct comm_point* c, void* arg, int err,
6775 	struct comm_reply* repinfo)
6776 {
6777 	struct auth_xfer* xfr = (struct auth_xfer*)arg;
6778 	struct module_env* env;
6779 	log_assert(xfr->task_probe);
6780 	lock_basic_lock(&xfr->lock);
6781 	env = xfr->task_probe->env;
6782 	if(!env || env->outnet->want_to_quit) {
6783 		lock_basic_unlock(&xfr->lock);
6784 		return 0; /* stop on quit */
6785 	}
6786 
6787 	/* the comm_point_udp_callback is in a for loop for NUM_UDP_PER_SELECT
6788 	 * and we set rep.c=NULL to stop if from looking inside the commpoint*/
6789 	repinfo->c = NULL;
6790 	/* stop the timer */
6791 	comm_timer_disable(xfr->task_probe->timer);
6792 
6793 	/* see if we got a packet and what that means */
6794 	if(err == NETEVENT_NOERROR) {
6795 		uint32_t serial = 0;
6796 		if(check_packet_ok(c->buffer, LDNS_RR_TYPE_SOA, xfr,
6797 			&serial)) {
6798 			/* successful lookup */
6799 			if(verbosity >= VERB_ALGO) {
6800 				char buf[LDNS_MAX_DOMAINLEN];
6801 				dname_str(xfr->name, buf);
6802 				verbose(VERB_ALGO, "auth zone %s: soa probe "
6803 					"serial is %u", buf, (unsigned)serial);
6804 			}
6805 			/* see if this serial indicates that the zone has
6806 			 * to be updated */
6807 			if(xfr_serial_means_update(xfr, serial)) {
6808 				/* if updated, start the transfer task, if needed */
6809 				verbose(VERB_ALGO, "auth_zone updated, start transfer");
6810 				if(xfr->task_transfer->worker == NULL) {
6811 					struct auth_master* master =
6812 						xfr_probe_current_master(xfr);
6813 					/* if we have download URLs use them
6814 					 * in preference to this master we
6815 					 * just probed the SOA from */
6816 					if(xfr->task_transfer->masters &&
6817 						xfr->task_transfer->masters->http)
6818 						master = NULL;
6819 					xfr_probe_disown(xfr);
6820 					xfr_start_transfer(xfr, env, master);
6821 					return 0;
6822 
6823 				}
6824 				/* other tasks are running, we don't do this anymore */
6825 				xfr_probe_disown(xfr);
6826 				lock_basic_unlock(&xfr->lock);
6827 				/* return, we don't sent a reply to this udp packet,
6828 				 * and we setup the tasks to do next */
6829 				return 0;
6830 			} else {
6831 				verbose(VERB_ALGO, "auth_zone master reports unchanged soa serial");
6832 				/* we if cannot find updates amongst the
6833 				 * masters, this means we then have a new lease
6834 				 * on the zone */
6835 				xfr->task_probe->have_new_lease = 1;
6836 			}
6837 		} else {
6838 			if(verbosity >= VERB_ALGO) {
6839 				char buf[LDNS_MAX_DOMAINLEN];
6840 				dname_str(xfr->name, buf);
6841 				verbose(VERB_ALGO, "auth zone %s: bad reply to soa probe", buf);
6842 			}
6843 		}
6844 	} else {
6845 		if(verbosity >= VERB_ALGO) {
6846 			char buf[LDNS_MAX_DOMAINLEN];
6847 			dname_str(xfr->name, buf);
6848 			verbose(VERB_ALGO, "auth zone %s: soa probe failed", buf);
6849 		}
6850 	}
6851 
6852 	/* failed lookup or not an update */
6853 	/* delete commpoint so a new one is created, with a fresh port nr */
6854 	comm_point_delete(xfr->task_probe->cp);
6855 	xfr->task_probe->cp = NULL;
6856 
6857 	/* if the result was not a successful probe, we need
6858 	 * to send the next one */
6859 	xfr_probe_nextmaster(xfr);
6860 	xfr_probe_send_or_end(xfr, env);
6861 	return 0;
6862 }
6863 
6864 /** lookup a host name for its addresses, if needed */
6865 static int
xfr_probe_lookup_host(struct auth_xfer * xfr,struct module_env * env)6866 xfr_probe_lookup_host(struct auth_xfer* xfr, struct module_env* env)
6867 {
6868 	struct sockaddr_storage addr;
6869 	socklen_t addrlen = 0;
6870 	struct auth_master* master = xfr->task_probe->lookup_target;
6871 	struct query_info qinfo;
6872 	uint16_t qflags = BIT_RD;
6873 	uint8_t dname[LDNS_MAX_DOMAINLEN+1];
6874 	struct edns_data edns;
6875 	sldns_buffer* buf = env->scratch_buffer;
6876 	if(!master) return 0;
6877 	if(extstrtoaddr(master->host, &addr, &addrlen, UNBOUND_DNS_PORT)) {
6878 		/* not needed, host is in IP addr format */
6879 		return 0;
6880 	}
6881 	if(master->allow_notify && !master->http &&
6882 		strchr(master->host, '/') != NULL &&
6883 		strchr(master->host, '/') == strrchr(master->host, '/')) {
6884 		return 0; /* is IP/prefix format, not something to look up */
6885 	}
6886 
6887 	/* use mesh_new_callback to probe for non-addr hosts,
6888 	 * and then wait for them to be looked up (in cache, or query) */
6889 	qinfo.qname_len = sizeof(dname);
6890 	if(sldns_str2wire_dname_buf(master->host, dname, &qinfo.qname_len)
6891 		!= 0) {
6892 		log_err("cannot parse host name of master %s", master->host);
6893 		return 0;
6894 	}
6895 	qinfo.qname = dname;
6896 	qinfo.qclass = xfr->dclass;
6897 	qinfo.qtype = LDNS_RR_TYPE_A;
6898 	if(xfr->task_probe->lookup_aaaa)
6899 		qinfo.qtype = LDNS_RR_TYPE_AAAA;
6900 	qinfo.local_alias = NULL;
6901 	if(verbosity >= VERB_ALGO) {
6902 		char buf1[512];
6903 		char buf2[LDNS_MAX_DOMAINLEN];
6904 		dname_str(xfr->name, buf2);
6905 		snprintf(buf1, sizeof(buf1), "auth zone %s: master lookup"
6906 			" for task_probe", buf2);
6907 		log_query_info(VERB_ALGO, buf1, &qinfo);
6908 	}
6909 	edns.edns_present = 1;
6910 	edns.ext_rcode = 0;
6911 	edns.edns_version = 0;
6912 	edns.bits = EDNS_DO;
6913 	edns.opt_list_in = NULL;
6914 	edns.opt_list_out = NULL;
6915 	edns.opt_list_inplace_cb_out = NULL;
6916 	edns.padding_block_size = 0;
6917 	edns.cookie_present = 0;
6918 	edns.cookie_valid = 0;
6919 	if(sldns_buffer_capacity(buf) < 65535)
6920 		edns.udp_size = (uint16_t)sldns_buffer_capacity(buf);
6921 	else	edns.udp_size = 65535;
6922 
6923 	/* unlock xfr during mesh_new_callback() because the callback can be
6924 	 * called straight away */
6925 	lock_basic_unlock(&xfr->lock);
6926 	if(!mesh_new_callback(env->mesh, &qinfo, qflags, &edns, buf, 0,
6927 		&auth_xfer_probe_lookup_callback, xfr, 0,
6928 		&xfr->task_probe->lookup_unique_info)) {
6929 		lock_basic_lock(&xfr->lock);
6930 		log_err("out of memory lookup up master %s", master->host);
6931 		return 0;
6932 	}
6933 	lock_basic_lock(&xfr->lock);
6934 	return 1;
6935 }
6936 
6937 /** return true if there are probe (SOA UDP query) targets in the master list*/
6938 static int
have_probe_targets(struct auth_master * list)6939 have_probe_targets(struct auth_master* list)
6940 {
6941 	struct auth_master* p;
6942 	for(p=list; p; p = p->next) {
6943 		if(!p->allow_notify && p->host)
6944 			return 1;
6945 	}
6946 	return 0;
6947 }
6948 
6949 /** move to sending the probe packets, next if fails. task_probe */
6950 static void
xfr_probe_send_or_end(struct auth_xfer * xfr,struct module_env * env)6951 xfr_probe_send_or_end(struct auth_xfer* xfr, struct module_env* env)
6952 {
6953 	/* are we doing hostname lookups? */
6954 	while(xfr->task_probe->lookup_target) {
6955 		if(xfr_probe_lookup_host(xfr, env)) {
6956 			/* wait for lookup to finish,
6957 			 * note that the hostname may be in unbound's cache
6958 			 * and we may then get an instant cache response,
6959 			 * and that calls the callback just like a full
6960 			 * lookup and lookup failures also call callback */
6961 			if(verbosity >= VERB_ALGO) {
6962 				char zname[LDNS_MAX_DOMAINLEN];
6963 				dname_str(xfr->name, zname);
6964 				verbose(VERB_ALGO, "auth zone %s probe next target lookup", zname);
6965 			}
6966 			lock_basic_unlock(&xfr->lock);
6967 			return;
6968 		}
6969 		xfr_probe_move_to_next_lookup(xfr, env);
6970 	}
6971 	/* probe of list has ended.  Create or refresh the list of of
6972 	 * allow_notify addrs */
6973 	probe_copy_masters_for_allow_notify(xfr);
6974 	if(verbosity >= VERB_ALGO) {
6975 		char zname[LDNS_MAX_DOMAINLEN];
6976 		dname_str(xfr->name, zname);
6977 		verbose(VERB_ALGO, "auth zone %s probe: notify addrs updated", zname);
6978 	}
6979 	if(xfr->task_probe->only_lookup) {
6980 		/* only wanted lookups for copy, stop probe and start wait */
6981 		xfr->task_probe->only_lookup = 0;
6982 		if(verbosity >= VERB_ALGO) {
6983 			char zname[LDNS_MAX_DOMAINLEN];
6984 			dname_str(xfr->name, zname);
6985 			verbose(VERB_ALGO, "auth zone %s probe: finished only_lookup", zname);
6986 		}
6987 		xfr_probe_disown(xfr);
6988 		if(!have_probe_targets(xfr->task_probe->masters)) {
6989 			/* If there are no masters to probe, go to transfer. */
6990 			if(xfr->task_transfer->worker == NULL) {
6991 				xfr_start_transfer(xfr, env, NULL);
6992 				return;
6993 			}
6994 			/* The transfer is already in progress. */
6995 			lock_basic_unlock(&xfr->lock);
6996 			return;
6997 		}
6998 		if(xfr->task_nextprobe->worker == NULL)
6999 			xfr_set_timeout(xfr, env, 0, 0);
7000 		lock_basic_unlock(&xfr->lock);
7001 		return;
7002 	}
7003 
7004 	/* send probe packets */
7005 	while(!xfr_probe_end_of_list(xfr)) {
7006 		if(xfr_probe_send_probe(xfr, env, AUTH_PROBE_TIMEOUT)) {
7007 			/* successfully sent probe, wait for callback */
7008 			lock_basic_unlock(&xfr->lock);
7009 			return;
7010 		}
7011 		/* failed to send probe, next master */
7012 		xfr_probe_nextmaster(xfr);
7013 	}
7014 
7015 	/* done with probe sequence, wait */
7016 	if(xfr->task_probe->have_new_lease) {
7017 		/* if zone not updated, start the wait timer again */
7018 		if(verbosity >= VERB_ALGO) {
7019 			char zname[LDNS_MAX_DOMAINLEN];
7020 			dname_str(xfr->name, zname);
7021 			verbose(VERB_ALGO, "auth_zone %s unchanged, new lease, wait", zname);
7022 		}
7023 		xfr_probe_disown(xfr);
7024 		if(xfr->have_zone)
7025 			xfr->lease_time = *env->now;
7026 		if(xfr->task_nextprobe->worker == NULL)
7027 			xfr_set_timeout(xfr, env, 0, 0);
7028 	} else {
7029 		if(verbosity >= VERB_ALGO) {
7030 			char zname[LDNS_MAX_DOMAINLEN];
7031 			dname_str(xfr->name, zname);
7032 			verbose(VERB_ALGO, "auth zone %s soa probe failed, wait to retry", zname);
7033 		}
7034 		/* we failed to send this as well, move to the wait task,
7035 		 * use the shorter retry timeout */
7036 		xfr_probe_disown(xfr);
7037 		/* pick up the nextprobe task and wait */
7038 		if(xfr->task_nextprobe->worker == NULL)
7039 			xfr_set_timeout(xfr, env, 1, 0);
7040 	}
7041 
7042 	lock_basic_unlock(&xfr->lock);
7043 }
7044 
7045 /** callback for task_probe lookup of host name, of A or AAAA */
auth_xfer_probe_lookup_callback(void * arg,int rcode,sldns_buffer * buf,enum sec_status sec,char * why_bogus,int ATTR_UNUSED (was_ratelimited))7046 void auth_xfer_probe_lookup_callback(void* arg, int rcode, sldns_buffer* buf,
7047 	enum sec_status sec, char* why_bogus, int ATTR_UNUSED(was_ratelimited))
7048 {
7049 	struct auth_xfer* xfr = (struct auth_xfer*)arg;
7050 	struct module_env* env;
7051 	log_assert(xfr->task_probe);
7052 	lock_basic_lock(&xfr->lock);
7053 	env = xfr->task_probe->env;
7054 	if(!env || env->outnet->want_to_quit) {
7055 		lock_basic_unlock(&xfr->lock);
7056 		return; /* stop on quit */
7057 	}
7058 
7059 	/* process result */
7060 	if(sec == sec_status_bogus || sec == sec_status_secure_sentinel_fail) {
7061 		if(verbosity >= VERB_OPS) {
7062 			char zname[LDNS_MAX_DOMAINLEN];
7063 			dname_str(xfr->name, zname);
7064 			verbose(VERB_OPS, "auth zone %s: primary %s address probe lookup is DNSSEC bogus: %s",
7065 				zname, xfr->task_probe->lookup_target->host,
7066 				(why_bogus?why_bogus:""));
7067 		}
7068 		/* fall through to next-lookup / next-master */
7069 	} else if(rcode == LDNS_RCODE_NOERROR) {
7070 		uint16_t wanted_qtype = LDNS_RR_TYPE_A;
7071 		struct regional* temp = env->scratch;
7072 		struct query_info rq;
7073 		struct reply_info* rep;
7074 		if(xfr->task_probe->lookup_aaaa)
7075 			wanted_qtype = LDNS_RR_TYPE_AAAA;
7076 		memset(&rq, 0, sizeof(rq));
7077 		rep = parse_reply_in_temp_region(buf, temp, &rq);
7078 		if(rep && rq.qtype == wanted_qtype &&
7079 			FLAGS_GET_RCODE(rep->flags) == LDNS_RCODE_NOERROR) {
7080 			/* parsed successfully */
7081 			struct ub_packed_rrset_key* answer =
7082 				reply_find_answer_rrset(&rq, rep);
7083 			if(answer && xfer_target_equals_answer_name(
7084 				xfr->task_probe->lookup_target, answer,
7085 				&rq, rep)) {
7086 				xfr_master_add_addrs(xfr->task_probe->
7087 					lookup_target, answer, wanted_qtype);
7088 			} else if(answer) {
7089 				if(verbosity >= VERB_ALGO) {
7090 					char zname[LDNS_MAX_DOMAINLEN];
7091 					dname_str(xfr->name, zname);
7092 					verbose(VERB_ALGO, "auth zone %s host %s type %s probe lookup has mismatch in answer name", zname, ((xfr->task_probe->lookup_target && xfr->task_probe->lookup_target->host) ? xfr->task_probe->lookup_target->host : "null"), (xfr->task_probe->lookup_aaaa?"AAAA":"A"));
7093 				}
7094 			} else {
7095 				if(verbosity >= VERB_ALGO) {
7096 					char zname[LDNS_MAX_DOMAINLEN];
7097 					dname_str(xfr->name, zname);
7098 					verbose(VERB_ALGO, "auth zone %s host %s type %s probe lookup has nodata", zname, ((xfr->task_probe->lookup_target && xfr->task_probe->lookup_target->host) ? xfr->task_probe->lookup_target->host : "null"), (xfr->task_probe->lookup_aaaa?"AAAA":"A"));
7099 				}
7100 			}
7101 		} else {
7102 			if(verbosity >= VERB_ALGO) {
7103 				char zname[LDNS_MAX_DOMAINLEN];
7104 				dname_str(xfr->name, zname);
7105 				verbose(VERB_ALGO, "auth zone %s host %s type %s probe lookup has no address", zname, ((xfr->task_probe->lookup_target && xfr->task_probe->lookup_target->host) ? xfr->task_probe->lookup_target->host : "null"), (xfr->task_probe->lookup_aaaa?"AAAA":"A"));
7106 			}
7107 		}
7108 		regional_free_all(temp);
7109 	} else {
7110 		if(verbosity >= VERB_ALGO) {
7111 			char zname[LDNS_MAX_DOMAINLEN];
7112 			dname_str(xfr->name, zname);
7113 			verbose(VERB_ALGO, "auth zone %s host %s type %s probe lookup failed", zname, ((xfr->task_probe->lookup_target && xfr->task_probe->lookup_target->host) ? xfr->task_probe->lookup_target->host : "null"), (xfr->task_probe->lookup_aaaa?"AAAA":"A"));
7114 		}
7115 	}
7116 	if(xfr->task_probe->lookup_target &&
7117 		xfr->task_probe->lookup_target->list &&
7118 		xfr->task_probe->lookup_target == xfr_probe_current_master(xfr))
7119 		xfr->task_probe->scan_addr = xfr->task_probe->lookup_target->list;
7120 
7121 	/* move to lookup AAAA after A lookup, move to next hostname lookup,
7122 	 * or move to send the probes, or, if nothing to do, end task_probe */
7123 	xfr_probe_move_to_next_lookup(xfr, env);
7124 	xfr_probe_send_or_end(xfr, env);
7125 }
7126 
7127 /** disown task_nextprobe.  caller must hold xfr.lock */
7128 static void
xfr_nextprobe_disown(struct auth_xfer * xfr)7129 xfr_nextprobe_disown(struct auth_xfer* xfr)
7130 {
7131 	/* delete the timer, because the next worker to pick this up may
7132 	 * not have the same event base */
7133 	comm_timer_delete(xfr->task_nextprobe->timer);
7134 	xfr->task_nextprobe->timer = NULL;
7135 	xfr->task_nextprobe->next_probe = 0;
7136 	/* we don't own this item anymore */
7137 	xfr->task_nextprobe->worker = NULL;
7138 	xfr->task_nextprobe->env = NULL;
7139 }
7140 
7141 /** xfer nextprobe timeout callback, this is part of task_nextprobe */
7142 void
auth_xfer_timer(void * arg)7143 auth_xfer_timer(void* arg)
7144 {
7145 	struct auth_xfer* xfr = (struct auth_xfer*)arg;
7146 	struct module_env* env;
7147 	log_assert(xfr->task_nextprobe);
7148 	lock_basic_lock(&xfr->lock);
7149 	env = xfr->task_nextprobe->env;
7150 	if(!env || env->outnet->want_to_quit) {
7151 		lock_basic_unlock(&xfr->lock);
7152 		return; /* stop on quit */
7153 	}
7154 
7155 	/* see if zone has expired, and if so, also set auth_zone expired */
7156 	if(xfr->have_zone && !xfr->zone_expired &&
7157 	   *env->now >= xfr->lease_time + xfr->expiry) {
7158 		lock_basic_unlock(&xfr->lock);
7159 		auth_xfer_set_expired(xfr, env, 1);
7160 		lock_basic_lock(&xfr->lock);
7161 	}
7162 
7163 	xfr_nextprobe_disown(xfr);
7164 
7165 	if(!xfr_start_probe(xfr, env, NULL)) {
7166 		/* not started because already in progress */
7167 		lock_basic_unlock(&xfr->lock);
7168 	}
7169 }
7170 
7171 /** start task_probe if possible, if no masters for probe start task_transfer
7172  * returns true if task has been started, and false if the task is already
7173  * in progress. */
7174 static int
xfr_start_probe(struct auth_xfer * xfr,struct module_env * env,struct auth_master * spec)7175 xfr_start_probe(struct auth_xfer* xfr, struct module_env* env,
7176 	struct auth_master* spec)
7177 {
7178 	/* see if we need to start a probe (or maybe it is already in
7179 	 * progress (due to notify)) */
7180 	if(xfr->task_probe->worker == NULL) {
7181 		if(!have_probe_targets(xfr->task_probe->masters) &&
7182 			xfr->task_probe->masters != NULL)
7183 			xfr->task_probe->only_lookup = 1;
7184 		if(!xfr->task_probe->only_lookup &&
7185 			!have_probe_targets(xfr->task_probe->masters)) {
7186 			/* useless to pick up task_probe, no masters to
7187 			 * probe. Instead attempt to pick up task transfer */
7188 			if(xfr->task_transfer->worker == NULL) {
7189 				xfr_start_transfer(xfr, env, spec);
7190 				return 1;
7191 			}
7192 			/* task transfer already in progress */
7193 			return 0;
7194 		}
7195 
7196 		/* pick up the probe task ourselves */
7197 		xfr->task_probe->worker = env->worker;
7198 		xfr->task_probe->env = env;
7199 		xfr->task_probe->cp = NULL;
7200 
7201 		/* start the task */
7202 		/* have not seen a new lease yet, this scan */
7203 		xfr->task_probe->have_new_lease = 0;
7204 		/* if this was a timeout, no specific first master to scan */
7205 		/* otherwise, spec is nonNULL the notified master, scan
7206 		 * first and also transfer first from it */
7207 		xfr_probe_start_list(xfr, spec);
7208 		/* setup to start the lookup of hostnames of masters afresh */
7209 		xfr_probe_start_lookups(xfr);
7210 		/* send the probe packet or next send, or end task */
7211 		xfr_probe_send_or_end(xfr, env);
7212 		return 1;
7213 	}
7214 	return 0;
7215 }
7216 
7217 /** for task_nextprobe.
7218  * determine next timeout for auth_xfer. Also (re)sets timer.
7219  * @param xfr: task structure
7220  * @param env: module environment, with worker and time.
7221  * @param failure: set true if timer should be set for failure retry.
7222  * @param lookup_only: only perform lookups when timer done, 0 sec timeout
7223  */
7224 static void
xfr_set_timeout(struct auth_xfer * xfr,struct module_env * env,int failure,int lookup_only)7225 xfr_set_timeout(struct auth_xfer* xfr, struct module_env* env,
7226 	int failure, int lookup_only)
7227 {
7228 	struct timeval tv;
7229 	log_assert(xfr->task_nextprobe != NULL);
7230 	log_assert(xfr->task_nextprobe->worker == NULL ||
7231 		xfr->task_nextprobe->worker == env->worker);
7232 	/* normally, nextprobe = startoflease + refresh,
7233 	 * but if expiry is sooner, use that one.
7234 	 * after a failure, use the retry timer instead. */
7235 	xfr->task_nextprobe->next_probe = *env->now;
7236 	if(xfr->lease_time && !failure)
7237 		xfr->task_nextprobe->next_probe = xfr->lease_time;
7238 
7239 	if(!failure) {
7240 		xfr->task_nextprobe->backoff = 0;
7241 	} else {
7242 		if(xfr->task_nextprobe->backoff == 0)
7243 				xfr->task_nextprobe->backoff = 3;
7244 		else	xfr->task_nextprobe->backoff *= 2;
7245 		if(xfr->task_nextprobe->backoff > AUTH_TRANSFER_MAX_BACKOFF)
7246 			xfr->task_nextprobe->backoff =
7247 				AUTH_TRANSFER_MAX_BACKOFF;
7248 	}
7249 
7250 	if(xfr->have_zone) {
7251 		time_t wait = xfr->refresh;
7252 		if(failure) wait = xfr->retry;
7253 		if(xfr->expiry < wait)
7254 			xfr->task_nextprobe->next_probe += xfr->expiry;
7255 		else	xfr->task_nextprobe->next_probe += wait;
7256 		if(failure)
7257 			xfr->task_nextprobe->next_probe +=
7258 				xfr->task_nextprobe->backoff;
7259 		/* put the timer exactly on expiry, if possible */
7260 		if(xfr->lease_time && xfr->lease_time+xfr->expiry <
7261 			xfr->task_nextprobe->next_probe &&
7262 			xfr->lease_time+xfr->expiry > *env->now)
7263 			xfr->task_nextprobe->next_probe =
7264 				xfr->lease_time+xfr->expiry;
7265 	} else {
7266 		xfr->task_nextprobe->next_probe +=
7267 			xfr->task_nextprobe->backoff;
7268 	}
7269 
7270 	if(!xfr->task_nextprobe->timer) {
7271 		xfr->task_nextprobe->timer = comm_timer_create(
7272 			env->worker_base, auth_xfer_timer, xfr);
7273 		if(!xfr->task_nextprobe->timer) {
7274 			/* failed to malloc memory. likely zone transfer
7275 			 * also fails for that. skip the timeout */
7276 			char zname[LDNS_MAX_DOMAINLEN];
7277 			dname_str(xfr->name, zname);
7278 			log_err("cannot allocate timer, no refresh for %s",
7279 				zname);
7280 			return;
7281 		}
7282 	}
7283 	xfr->task_nextprobe->worker = env->worker;
7284 	xfr->task_nextprobe->env = env;
7285 	if(*(xfr->task_nextprobe->env->now) <= xfr->task_nextprobe->next_probe)
7286 		tv.tv_sec = xfr->task_nextprobe->next_probe -
7287 			*(xfr->task_nextprobe->env->now);
7288 	else	tv.tv_sec = 0;
7289 	if(tv.tv_sec != 0 && lookup_only && xfr->task_probe->masters) {
7290 		/* don't lookup_only, if lookup timeout is 0 anyway,
7291 		 * or if we don't have masters to lookup */
7292 		tv.tv_sec = 0;
7293 		if(xfr->task_probe->worker == NULL)
7294 			xfr->task_probe->only_lookup = 1;
7295 	}
7296 	if(verbosity >= VERB_ALGO) {
7297 		char zname[LDNS_MAX_DOMAINLEN];
7298 		dname_str(xfr->name, zname);
7299 		verbose(VERB_ALGO, "auth zone %s timeout in %d seconds",
7300 			zname, (int)tv.tv_sec);
7301 	}
7302 	tv.tv_usec = 0;
7303 	comm_timer_set(xfr->task_nextprobe->timer, &tv);
7304 }
7305 
auth_zone_pickup_initial_zone(struct auth_zone * z,struct module_env * env)7306 void auth_zone_pickup_initial_zone(struct auth_zone* z, struct module_env* env)
7307 {
7308 	/* Set the time, because we now have timestamp in env,
7309 	 * (not earlier during startup and apply_cfg), and this
7310 	 * notes the start time when the data was acquired. */
7311 	z->soa_zone_acquired = *env->now;
7312 }
7313 
auth_xfer_pickup_initial_zone(struct auth_xfer * x,struct module_env * env)7314 void auth_xfer_pickup_initial_zone(struct auth_xfer* x, struct module_env* env)
7315 {
7316 	/* set lease_time, because we now have timestamp in env,
7317 	 * (not earlier during startup and apply_cfg), and this
7318 	 * notes the start time when the data was acquired */
7319 	if(x->have_zone) {
7320 		x->lease_time = *env->now;
7321 		x->soa_zone_acquired = *env->now;
7322 	}
7323 	if(x->task_nextprobe && x->task_nextprobe->worker == NULL) {
7324 		xfr_set_timeout(x, env, 0, 1);
7325 	}
7326 }
7327 
7328 /** initial pick up of worker timeouts, ties events to worker event loop */
7329 void
auth_xfer_pickup_initial(struct auth_zones * az,struct module_env * env)7330 auth_xfer_pickup_initial(struct auth_zones* az, struct module_env* env)
7331 {
7332 	struct auth_xfer* x;
7333 	struct auth_zone* z;
7334 	lock_rw_wrlock(&az->lock);
7335 	RBTREE_FOR(z, struct auth_zone*, &az->ztree) {
7336 		lock_rw_wrlock(&z->lock);
7337 		auth_zone_pickup_initial_zone(z, env);
7338 		lock_rw_unlock(&z->lock);
7339 	}
7340 	RBTREE_FOR(x, struct auth_xfer*, &az->xtree) {
7341 		lock_basic_lock(&x->lock);
7342 		auth_xfer_pickup_initial_zone(x, env);
7343 		lock_basic_unlock(&x->lock);
7344 	}
7345 	lock_rw_unlock(&az->lock);
7346 }
7347 
auth_zones_cleanup(struct auth_zones * az)7348 void auth_zones_cleanup(struct auth_zones* az)
7349 {
7350 	struct auth_xfer* x;
7351 	lock_rw_wrlock(&az->lock);
7352 	RBTREE_FOR(x, struct auth_xfer*, &az->xtree) {
7353 		lock_basic_lock(&x->lock);
7354 		if(x->task_nextprobe && x->task_nextprobe->worker != NULL) {
7355 			xfr_nextprobe_disown(x);
7356 		}
7357 		if(x->task_probe && x->task_probe->worker != NULL) {
7358 			xfr_probe_disown(x);
7359 		}
7360 		if(x->task_transfer && x->task_transfer->worker != NULL) {
7361 			auth_chunks_delete(x->task_transfer);
7362 			xfr_transfer_disown(x);
7363 		}
7364 		lock_basic_unlock(&x->lock);
7365 	}
7366 	lock_rw_unlock(&az->lock);
7367 }
7368 
7369 /**
7370  * malloc the xfer and tasks
7371  * @param z: auth_zone with name of zone.
7372  */
7373 static struct auth_xfer*
auth_xfer_new(struct auth_zone * z)7374 auth_xfer_new(struct auth_zone* z)
7375 {
7376 	struct auth_xfer* xfr;
7377 	xfr = (struct auth_xfer*)calloc(1, sizeof(*xfr));
7378 	if(!xfr) return NULL;
7379 	xfr->name = memdup(z->name, z->namelen);
7380 	if(!xfr->name) {
7381 		free(xfr);
7382 		return NULL;
7383 	}
7384 	xfr->node.key = xfr;
7385 	xfr->namelen = z->namelen;
7386 	xfr->namelabs = z->namelabs;
7387 	xfr->dclass = z->dclass;
7388 	xfr->max_transfer_size = z->max_transfer_size;
7389 	xfr->max_transfer_time = z->max_transfer_time;
7390 
7391 	xfr->task_nextprobe = (struct auth_nextprobe*)calloc(1,
7392 		sizeof(struct auth_nextprobe));
7393 	if(!xfr->task_nextprobe) {
7394 		free(xfr->name);
7395 		free(xfr);
7396 		return NULL;
7397 	}
7398 	xfr->task_probe = (struct auth_probe*)calloc(1,
7399 		sizeof(struct auth_probe));
7400 	if(!xfr->task_probe) {
7401 		free(xfr->task_nextprobe);
7402 		free(xfr->name);
7403 		free(xfr);
7404 		return NULL;
7405 	}
7406 	xfr->task_transfer = (struct auth_transfer*)calloc(1,
7407 		sizeof(struct auth_transfer));
7408 	if(!xfr->task_transfer) {
7409 		free(xfr->task_probe);
7410 		free(xfr->task_nextprobe);
7411 		free(xfr->name);
7412 		free(xfr);
7413 		return NULL;
7414 	}
7415 
7416 	lock_basic_init(&xfr->lock);
7417 	lock_protect(&xfr->lock, &xfr->name, sizeof(xfr->name));
7418 	lock_protect(&xfr->lock, &xfr->namelen, sizeof(xfr->namelen));
7419 	lock_protect(&xfr->lock, xfr->name, xfr->namelen);
7420 	lock_protect(&xfr->lock, &xfr->namelabs, sizeof(xfr->namelabs));
7421 	lock_protect(&xfr->lock, &xfr->dclass, sizeof(xfr->dclass));
7422 	lock_protect(&xfr->lock, &xfr->notify_received, sizeof(xfr->notify_received));
7423 	lock_protect(&xfr->lock, &xfr->notify_serial, sizeof(xfr->notify_serial));
7424 	lock_protect(&xfr->lock, &xfr->zone_expired, sizeof(xfr->zone_expired));
7425 	lock_protect(&xfr->lock, &xfr->have_zone, sizeof(xfr->have_zone));
7426 	lock_protect(&xfr->lock, &xfr->soa_zone_acquired, sizeof(xfr->soa_zone_acquired));
7427 	lock_protect(&xfr->lock, &xfr->serial, sizeof(xfr->serial));
7428 	lock_protect(&xfr->lock, &xfr->retry, sizeof(xfr->retry));
7429 	lock_protect(&xfr->lock, &xfr->refresh, sizeof(xfr->refresh));
7430 	lock_protect(&xfr->lock, &xfr->expiry, sizeof(xfr->expiry));
7431 	lock_protect(&xfr->lock, &xfr->lease_time, sizeof(xfr->lease_time));
7432 	lock_protect(&xfr->lock, &xfr->task_nextprobe->worker,
7433 		sizeof(xfr->task_nextprobe->worker));
7434 	lock_protect(&xfr->lock, &xfr->task_probe->worker,
7435 		sizeof(xfr->task_probe->worker));
7436 	lock_protect(&xfr->lock, &xfr->task_transfer->worker,
7437 		sizeof(xfr->task_transfer->worker));
7438 	lock_basic_lock(&xfr->lock);
7439 	return xfr;
7440 }
7441 
7442 /** Create auth_xfer structure.
7443  * This populates the have_zone, soa values, and so on times.
7444  * and sets the timeout, if a zone transfer is needed a short timeout is set.
7445  * For that the auth_zone itself must exist (and read in zonefile)
7446  * returns false on alloc failure. */
7447 struct auth_xfer*
auth_xfer_create(struct auth_zones * az,struct auth_zone * z)7448 auth_xfer_create(struct auth_zones* az, struct auth_zone* z)
7449 {
7450 	struct auth_xfer* xfr;
7451 
7452 	/* malloc it */
7453 	xfr = auth_xfer_new(z);
7454 	if(!xfr) {
7455 		log_err("malloc failure");
7456 		return NULL;
7457 	}
7458 	/* insert in tree */
7459 	(void)rbtree_insert(&az->xtree, &xfr->node);
7460 	return xfr;
7461 }
7462 
7463 /** create new auth_master structure */
7464 static struct auth_master*
auth_master_new(struct auth_master *** list)7465 auth_master_new(struct auth_master*** list)
7466 {
7467 	struct auth_master *m;
7468 	m = (struct auth_master*)calloc(1, sizeof(*m));
7469 	if(!m) {
7470 		log_err("malloc failure");
7471 		return NULL;
7472 	}
7473 	/* set first pointer to m, or next pointer of previous element to m */
7474 	(**list) = m;
7475 	/* store m's next pointer as future point to store at */
7476 	(*list) = &(m->next);
7477 	return m;
7478 }
7479 
7480 /** dup_prefix : create string from initial part of other string, malloced */
7481 static char*
dup_prefix(char * str,size_t num)7482 dup_prefix(char* str, size_t num)
7483 {
7484 	char* result;
7485 	size_t len = strlen(str);
7486 	if(len < num) num = len; /* not more than strlen */
7487 	result = (char*)malloc(num+1);
7488 	if(!result) {
7489 		log_err("malloc failure");
7490 		return result;
7491 	}
7492 	memmove(result, str, num);
7493 	result[num] = 0;
7494 	return result;
7495 }
7496 
7497 /** dup string and print error on error */
7498 static char*
dup_all(char * str)7499 dup_all(char* str)
7500 {
7501 	char* result = strdup(str);
7502 	if(!result) {
7503 		log_err("malloc failure");
7504 		return NULL;
7505 	}
7506 	return result;
7507 }
7508 
7509 /** find first of two characters */
7510 static char*
str_find_first_of_chars(char * s,char a,char b)7511 str_find_first_of_chars(char* s, char a, char b)
7512 {
7513 	char* ra = strchr(s, a);
7514 	char* rb = strchr(s, b);
7515 	if(!ra) return rb;
7516 	if(!rb) return ra;
7517 	if(ra < rb) return ra;
7518 	return rb;
7519 }
7520 
7521 /** parse URL into host and file parts, false on malloc or parse error */
7522 static int
parse_url(char * url,char ** host,char ** file,int * port,int * ssl)7523 parse_url(char* url, char** host, char** file, int* port, int* ssl)
7524 {
7525 	char* p = url;
7526 	/* parse http://www.example.com/file.htm
7527 	 * or http://127.0.0.1   (index.html)
7528 	 * or https://[::1@1234]/a/b/c/d */
7529 	*ssl = 1;
7530 	*port = AUTH_HTTPS_PORT;
7531 
7532 	/* parse http:// or https:// */
7533 	if(strncmp(p, "http://", 7) == 0) {
7534 		p += 7;
7535 		*ssl = 0;
7536 		*port = AUTH_HTTP_PORT;
7537 	} else if(strncmp(p, "https://", 8) == 0) {
7538 		p += 8;
7539 	} else if(strstr(p, "://") && strchr(p, '/') > strstr(p, "://") &&
7540 		strchr(p, ':') >= strstr(p, "://")) {
7541 		char* uri = dup_prefix(p, (size_t)(strstr(p, "://")-p));
7542 		log_err("protocol %s:// not supported (for url %s)",
7543 			uri?uri:"", p);
7544 		free(uri);
7545 		return 0;
7546 	}
7547 
7548 	/* parse hostname part */
7549 	if(p[0] == '[') {
7550 		char* end = strchr(p, ']');
7551 		p++; /* skip over [ */
7552 		if(end) {
7553 			*host = dup_prefix(p, (size_t)(end-p));
7554 			if(!*host) return 0;
7555 			p = end+1; /* skip over ] */
7556 		} else {
7557 			*host = dup_all(p);
7558 			if(!*host) return 0;
7559 			p = end;
7560 		}
7561 	} else {
7562 		char* end = str_find_first_of_chars(p, ':', '/');
7563 		if(end) {
7564 			*host = dup_prefix(p, (size_t)(end-p));
7565 			if(!*host) return 0;
7566 		} else {
7567 			*host = dup_all(p);
7568 			if(!*host) return 0;
7569 		}
7570 		p = end; /* at next : or / or NULL */
7571 	}
7572 
7573 	/* parse port number */
7574 	if(p && p[0] == ':') {
7575 		char* end = NULL;
7576 		*port = strtol(p+1, &end, 10);
7577 		p = end;
7578 	}
7579 
7580 	/* parse filename part */
7581 	while(p && *p == '/')
7582 		p++;
7583 	if(!p || p[0] == 0)
7584 		*file = strdup("/");
7585 	else	*file = strdup(p);
7586 	if(!*file) {
7587 		log_err("malloc failure");
7588 		return 0;
7589 	}
7590 	return 1;
7591 }
7592 
7593 int
xfer_set_masters(struct auth_master ** list,struct config_auth * c,int with_http)7594 xfer_set_masters(struct auth_master** list, struct config_auth* c,
7595 	int with_http)
7596 {
7597 	struct auth_master* m;
7598 	struct config_strlist* p;
7599 	struct auth_master** tail;
7600 	/* list points to the first, or next pointer for the new element */
7601 	while(*list) {
7602 		list = &( (*list)->next );
7603 	}
7604 	if(with_http)
7605 	  for(p = c->urls; p; p = p->next) {
7606 		tail = list;
7607 		m = auth_master_new(&list);
7608 		if(!m) return 0;
7609 		m->http = 1;
7610 		if(!parse_url(p->str, &m->host, &m->file, &m->port, &m->ssl)) {
7611 			free(m->host);
7612 			free(m->file);
7613 			free(m);
7614 			*tail = NULL;
7615 			return 0;
7616 		}
7617 	}
7618 	for(p = c->masters; p; p = p->next) {
7619 		tail = list;
7620 		m = auth_master_new(&list);
7621 		if(!m) return 0;
7622 		m->ixfr = 1; /* this flag is not configurable */
7623 		m->host = strdup(p->str);
7624 		if(!m->host) {
7625 			log_err("malloc failure");
7626 			free(m);
7627 			*tail = NULL;
7628 			return 0;
7629 		}
7630 	}
7631 	for(p = c->allow_notify; p; p = p->next) {
7632 		tail = list;
7633 		m = auth_master_new(&list);
7634 		if(!m) return 0;
7635 		m->allow_notify = 1;
7636 		m->host = strdup(p->str);
7637 		if(!m->host) {
7638 			log_err("malloc failure");
7639 			free(m);
7640 			*tail = NULL;
7641 			return 0;
7642 		}
7643 	}
7644 	return 1;
7645 }
7646 
7647 #define SERIAL_BITS	32
7648 int
compare_serial(uint32_t a,uint32_t b)7649 compare_serial(uint32_t a, uint32_t b)
7650 {
7651 	const uint32_t cutoff = ((uint32_t) 1 << (SERIAL_BITS - 1));
7652 
7653 	if (a == b) {
7654 		return 0;
7655 	} else if ((a < b && b - a < cutoff) || (a > b && a - b > cutoff)) {
7656 		return -1;
7657 	} else {
7658 		return 1;
7659 	}
7660 }
7661 
zonemd_hashalgo_supported(int hashalgo)7662 int zonemd_hashalgo_supported(int hashalgo)
7663 {
7664 	if(hashalgo == ZONEMD_ALGO_SHA384) return 1;
7665 	if(hashalgo == ZONEMD_ALGO_SHA512) return 1;
7666 	return 0;
7667 }
7668 
zonemd_scheme_supported(int scheme)7669 int zonemd_scheme_supported(int scheme)
7670 {
7671 	if(scheme == ZONEMD_SCHEME_SIMPLE) return 1;
7672 	return 0;
7673 }
7674 
7675 /** initialize hash for hashing with zonemd hash algo */
zonemd_digest_init(int hashalgo,char ** reason)7676 static struct secalgo_hash* zonemd_digest_init(int hashalgo, char** reason)
7677 {
7678 	struct secalgo_hash *h;
7679 	if(hashalgo == ZONEMD_ALGO_SHA384) {
7680 		/* sha384 */
7681 		h = secalgo_hash_create_sha384();
7682 		if(!h)
7683 			*reason = "digest sha384 could not be created";
7684 		return h;
7685 	} else if(hashalgo == ZONEMD_ALGO_SHA512) {
7686 		/* sha512 */
7687 		h = secalgo_hash_create_sha512();
7688 		if(!h)
7689 			*reason = "digest sha512 could not be created";
7690 		return h;
7691 	}
7692 	/* unknown hash algo */
7693 	*reason = "unsupported algorithm";
7694 	return NULL;
7695 }
7696 
7697 /** update the hash for zonemd */
zonemd_digest_update(int hashalgo,struct secalgo_hash * h,uint8_t * data,size_t len,char ** reason)7698 static int zonemd_digest_update(int hashalgo, struct secalgo_hash* h,
7699 	uint8_t* data, size_t len, char** reason)
7700 {
7701 	if(hashalgo == ZONEMD_ALGO_SHA384) {
7702 		if(!secalgo_hash_update(h, data, len)) {
7703 			*reason = "digest sha384 failed";
7704 			return 0;
7705 		}
7706 		return 1;
7707 	} else if(hashalgo == ZONEMD_ALGO_SHA512) {
7708 		if(!secalgo_hash_update(h, data, len)) {
7709 			*reason = "digest sha512 failed";
7710 			return 0;
7711 		}
7712 		return 1;
7713 	}
7714 	/* unknown hash algo */
7715 	*reason = "unsupported algorithm";
7716 	return 0;
7717 }
7718 
7719 /** finish the hash for zonemd */
zonemd_digest_finish(int hashalgo,struct secalgo_hash * h,uint8_t * result,size_t hashlen,size_t * resultlen,char ** reason)7720 static int zonemd_digest_finish(int hashalgo, struct secalgo_hash* h,
7721 	uint8_t* result, size_t hashlen, size_t* resultlen, char** reason)
7722 {
7723 	if(hashalgo == ZONEMD_ALGO_SHA384) {
7724 		if(hashlen < 384/8) {
7725 			*reason = "digest buffer too small for sha384";
7726 			return 0;
7727 		}
7728 		if(!secalgo_hash_final(h, result, hashlen, resultlen)) {
7729 			*reason = "digest sha384 finish failed";
7730 			return 0;
7731 		}
7732 		return 1;
7733 	} else if(hashalgo == ZONEMD_ALGO_SHA512) {
7734 		if(hashlen < 512/8) {
7735 			*reason = "digest buffer too small for sha512";
7736 			return 0;
7737 		}
7738 		if(!secalgo_hash_final(h, result, hashlen, resultlen)) {
7739 			*reason = "digest sha512 finish failed";
7740 			return 0;
7741 		}
7742 		return 1;
7743 	}
7744 	/* unknown algo */
7745 	*reason = "unsupported algorithm";
7746 	return 0;
7747 }
7748 
7749 /** add rrsets from node to the list */
authdata_rrsets_to_list(struct auth_rrset ** array,size_t arraysize,struct auth_rrset * first)7750 static size_t authdata_rrsets_to_list(struct auth_rrset** array,
7751 	size_t arraysize, struct auth_rrset* first)
7752 {
7753 	struct auth_rrset* rrset = first;
7754 	size_t num = 0;
7755 	while(rrset) {
7756 		if(num >= arraysize)
7757 			return num;
7758 		array[num] = rrset;
7759 		num++;
7760 		rrset = rrset->next;
7761 	}
7762 	return num;
7763 }
7764 
7765 /** compare rr list entries */
rrlist_compare(const void * arg1,const void * arg2)7766 static int rrlist_compare(const void* arg1, const void* arg2)
7767 {
7768 	struct auth_rrset* r1 = *(struct auth_rrset**)arg1;
7769 	struct auth_rrset* r2 = *(struct auth_rrset**)arg2;
7770 	uint16_t t1, t2;
7771 	if(r1 == NULL) t1 = LDNS_RR_TYPE_RRSIG;
7772 	else t1 = r1->type;
7773 	if(r2 == NULL) t2 = LDNS_RR_TYPE_RRSIG;
7774 	else t2 = r2->type;
7775 	if(t1 < t2)
7776 		return -1;
7777 	if(t1 > t2)
7778 		return 1;
7779 	return 0;
7780 }
7781 
7782 /** add type RRSIG to rr list if not one there already,
7783  * this is to perform RRSIG collate processing at that point. */
addrrsigtype_if_needed(struct auth_rrset ** array,size_t arraysize,size_t * rrnum,struct auth_data * node)7784 static void addrrsigtype_if_needed(struct auth_rrset** array,
7785 	size_t arraysize, size_t* rrnum, struct auth_data* node)
7786 {
7787 	if(az_domain_rrset(node, LDNS_RR_TYPE_RRSIG))
7788 		return; /* already one there */
7789 	if((*rrnum) >= arraysize)
7790 		return; /* array too small? */
7791 	array[*rrnum] = NULL; /* nothing there, but need entry in list */
7792 	(*rrnum)++;
7793 }
7794 
7795 /** collate the RRs in an RRset using the simple scheme */
zonemd_simple_rrset(struct auth_zone * z,int hashalgo,struct secalgo_hash * h,struct auth_data * node,struct auth_rrset * rrset,struct regional * region,struct sldns_buffer * buf,char ** reason)7796 static int zonemd_simple_rrset(struct auth_zone* z, int hashalgo,
7797 	struct secalgo_hash* h, struct auth_data* node,
7798 	struct auth_rrset* rrset, struct regional* region,
7799 	struct sldns_buffer* buf, char** reason)
7800 {
7801 	/* canonicalize */
7802 	struct ub_packed_rrset_key key;
7803 	memset(&key, 0, sizeof(key));
7804 	key.entry.key = &key;
7805 	key.entry.data = rrset->data;
7806 	key.rk.dname = node->name;
7807 	key.rk.dname_len = node->namelen;
7808 	key.rk.type = htons(rrset->type);
7809 	key.rk.rrset_class = htons(z->dclass);
7810 	if(!rrset_canonicalize_to_buffer(region, buf, &key)) {
7811 		*reason = "out of memory";
7812 		return 0;
7813 	}
7814 	regional_free_all(region);
7815 
7816 	/* hash */
7817 	if(!zonemd_digest_update(hashalgo, h, sldns_buffer_begin(buf),
7818 		sldns_buffer_limit(buf), reason)) {
7819 		return 0;
7820 	}
7821 	return 1;
7822 }
7823 
7824 /** count number of RRSIGs in a domain name rrset list */
zonemd_simple_count_rrsig(struct auth_rrset * rrset,struct auth_rrset ** rrlist,size_t rrnum,struct auth_zone * z,struct auth_data * node)7825 static size_t zonemd_simple_count_rrsig(struct auth_rrset* rrset,
7826 	struct auth_rrset** rrlist, size_t rrnum,
7827 	struct auth_zone* z, struct auth_data* node)
7828 {
7829 	size_t i, count = 0;
7830 	if(rrset) {
7831 		size_t j;
7832 		for(j = 0; j<rrset->data->count; j++) {
7833 			if(rrsig_rdata_get_type_covered(rrset->data->
7834 				rr_data[j], rrset->data->rr_len[j]) ==
7835 				LDNS_RR_TYPE_ZONEMD &&
7836 				query_dname_compare(z->name, node->name)==0) {
7837 				/* omit RRSIGs over type ZONEMD at apex */
7838 				continue;
7839 			}
7840 			count++;
7841 		}
7842 	}
7843 	for(i=0; i<rrnum; i++) {
7844 		if(rrlist[i] && rrlist[i]->type == LDNS_RR_TYPE_ZONEMD &&
7845 			query_dname_compare(z->name, node->name)==0) {
7846 			/* omit RRSIGs over type ZONEMD at apex */
7847 			continue;
7848 		}
7849 		count += (rrlist[i]?rrlist[i]->data->rrsig_count:0);
7850 	}
7851 	return count;
7852 }
7853 
7854 /** allocate sparse rrset data for the number of entries in tepm region */
zonemd_simple_rrsig_allocs(struct regional * region,struct packed_rrset_data * data,size_t count)7855 static int zonemd_simple_rrsig_allocs(struct regional* region,
7856 	struct packed_rrset_data* data, size_t count)
7857 {
7858 	data->rr_len = regional_alloc(region, sizeof(*data->rr_len) * count);
7859 	if(!data->rr_len) {
7860 		return 0;
7861 	}
7862 	data->rr_ttl = regional_alloc(region, sizeof(*data->rr_ttl) * count);
7863 	if(!data->rr_ttl) {
7864 		return 0;
7865 	}
7866 	data->rr_data = regional_alloc(region, sizeof(*data->rr_data) * count);
7867 	if(!data->rr_data) {
7868 		return 0;
7869 	}
7870 	return 1;
7871 }
7872 
7873 /** add the RRSIGs from the rrs in the domain into the data */
add_rrlist_rrsigs_into_data(struct packed_rrset_data * data,size_t * done,struct auth_rrset ** rrlist,size_t rrnum,struct auth_zone * z,struct auth_data * node)7874 static void add_rrlist_rrsigs_into_data(struct packed_rrset_data* data,
7875 	size_t* done, struct auth_rrset** rrlist, size_t rrnum,
7876 	struct auth_zone* z, struct auth_data* node)
7877 {
7878 	size_t i;
7879 	for(i=0; i<rrnum; i++) {
7880 		size_t j;
7881 		if(!rrlist[i])
7882 			continue;
7883 		if(rrlist[i]->type == LDNS_RR_TYPE_ZONEMD &&
7884 			query_dname_compare(z->name, node->name)==0) {
7885 			/* omit RRSIGs over type ZONEMD at apex */
7886 			continue;
7887 		}
7888 		for(j = 0; j<rrlist[i]->data->rrsig_count; j++) {
7889 			data->rr_len[*done] = rrlist[i]->data->rr_len[rrlist[i]->data->count + j];
7890 			data->rr_ttl[*done] = rrlist[i]->data->rr_ttl[rrlist[i]->data->count + j];
7891 			/* reference the rdata in the rrset, no need to
7892 			 * copy it, it is no longer needed at the end of
7893 			 * the routine */
7894 			data->rr_data[*done] = rrlist[i]->data->rr_data[rrlist[i]->data->count + j];
7895 			(*done)++;
7896 		}
7897 	}
7898 }
7899 
add_rrset_into_data(struct packed_rrset_data * data,size_t * done,struct auth_rrset * rrset,struct auth_zone * z,struct auth_data * node)7900 static void add_rrset_into_data(struct packed_rrset_data* data,
7901 	size_t* done, struct auth_rrset* rrset,
7902 	struct auth_zone* z, struct auth_data* node)
7903 {
7904 	if(rrset) {
7905 		size_t j;
7906 		for(j = 0; j<rrset->data->count; j++) {
7907 			if(rrsig_rdata_get_type_covered(rrset->data->
7908 				rr_data[j], rrset->data->rr_len[j]) ==
7909 				LDNS_RR_TYPE_ZONEMD &&
7910 				query_dname_compare(z->name, node->name)==0) {
7911 				/* omit RRSIGs over type ZONEMD at apex */
7912 				continue;
7913 			}
7914 			data->rr_len[*done] = rrset->data->rr_len[j];
7915 			data->rr_ttl[*done] = rrset->data->rr_ttl[j];
7916 			/* reference the rdata in the rrset, no need to
7917 			 * copy it, it is no longer need at the end of
7918 			 * the routine */
7919 			data->rr_data[*done] = rrset->data->rr_data[j];
7920 			(*done)++;
7921 		}
7922 	}
7923 }
7924 
7925 /** collate the RRSIGs using the simple scheme */
zonemd_simple_rrsig(struct auth_zone * z,int hashalgo,struct secalgo_hash * h,struct auth_data * node,struct auth_rrset * rrset,struct auth_rrset ** rrlist,size_t rrnum,struct regional * region,struct sldns_buffer * buf,char ** reason)7926 static int zonemd_simple_rrsig(struct auth_zone* z, int hashalgo,
7927 	struct secalgo_hash* h, struct auth_data* node,
7928 	struct auth_rrset* rrset, struct auth_rrset** rrlist, size_t rrnum,
7929 	struct regional* region, struct sldns_buffer* buf, char** reason)
7930 {
7931 	/* the rrset pointer can be NULL, this means it is type RRSIG and
7932 	 * there is no ordinary type RRSIG there.  The RRSIGs are stored
7933 	 * with the RRsets in their data.
7934 	 *
7935 	 * The RRset pointer can be nonNULL. This happens if there is
7936 	 * no RR that is covered by the RRSIG for the domain.  Then this
7937 	 * RRSIG RR is stored in an rrset of type RRSIG. The other RRSIGs
7938 	 * are stored in the rrset entries for the RRs in the rr list for
7939 	 * the domain node.  We need to collate the rrset's data, if any, and
7940 	 * the rrlist's rrsigs */
7941 	/* if this is the apex, omit RRSIGs that cover type ZONEMD */
7942 	/* build rrsig rrset */
7943 	size_t done = 0;
7944 	struct ub_packed_rrset_key key;
7945 	struct packed_rrset_data data;
7946 	memset(&key, 0, sizeof(key));
7947 	memset(&data, 0, sizeof(data));
7948 	key.entry.key = &key;
7949 	key.entry.data = &data;
7950 	key.rk.dname = node->name;
7951 	key.rk.dname_len = node->namelen;
7952 	key.rk.type = htons(LDNS_RR_TYPE_RRSIG);
7953 	key.rk.rrset_class = htons(z->dclass);
7954 	data.count = zonemd_simple_count_rrsig(rrset, rrlist, rrnum, z, node);
7955 	if(!zonemd_simple_rrsig_allocs(region, &data, data.count)) {
7956 		*reason = "out of memory";
7957 		regional_free_all(region);
7958 		return 0;
7959 	}
7960 	/* all the RRSIGs stored in the other rrsets for this domain node */
7961 	add_rrlist_rrsigs_into_data(&data, &done, rrlist, rrnum, z, node);
7962 	/* plus the RRSIGs stored in an rrset of type RRSIG for this node */
7963 	add_rrset_into_data(&data, &done, rrset, z, node);
7964 
7965 	/* canonicalize */
7966 	if(!rrset_canonicalize_to_buffer(region, buf, &key)) {
7967 		*reason = "out of memory";
7968 		regional_free_all(region);
7969 		return 0;
7970 	}
7971 	regional_free_all(region);
7972 
7973 	/* hash */
7974 	if(!zonemd_digest_update(hashalgo, h, sldns_buffer_begin(buf),
7975 		sldns_buffer_limit(buf), reason)) {
7976 		return 0;
7977 	}
7978 	return 1;
7979 }
7980 
7981 /** collate a domain's rrsets using the simple scheme */
zonemd_simple_domain(struct auth_zone * z,int hashalgo,struct secalgo_hash * h,struct auth_data * node,struct regional * region,struct sldns_buffer * buf,char ** reason)7982 static int zonemd_simple_domain(struct auth_zone* z, int hashalgo,
7983 	struct secalgo_hash* h, struct auth_data* node,
7984 	struct regional* region, struct sldns_buffer* buf, char** reason)
7985 {
7986 	const size_t rrlistsize = 65536;
7987 	struct auth_rrset* rrlist[rrlistsize];
7988 	size_t i, rrnum = 0;
7989 	/* see if the domain is out of scope, the zone origin,
7990 	 * that would be omitted */
7991 	if(!dname_subdomain_c(node->name, z->name))
7992 		return 1; /* continue */
7993 	/* loop over the rrsets in ascending order. */
7994 	rrnum = authdata_rrsets_to_list(rrlist, rrlistsize, node->rrsets);
7995 	addrrsigtype_if_needed(rrlist, rrlistsize, &rrnum, node);
7996 	qsort(rrlist, rrnum, sizeof(*rrlist), rrlist_compare);
7997 	for(i=0; i<rrnum; i++) {
7998 		if(rrlist[i] && rrlist[i]->type == LDNS_RR_TYPE_ZONEMD &&
7999 			query_dname_compare(z->name, node->name) == 0) {
8000 			/* omit type ZONEMD at apex */
8001 			continue;
8002 		}
8003 		if(rrlist[i] == NULL || rrlist[i]->type ==
8004 			LDNS_RR_TYPE_RRSIG) {
8005 			if(!zonemd_simple_rrsig(z, hashalgo, h, node,
8006 				rrlist[i], rrlist, rrnum, region, buf, reason))
8007 				return 0;
8008 		} else if(!zonemd_simple_rrset(z, hashalgo, h, node,
8009 			rrlist[i], region, buf, reason)) {
8010 			return 0;
8011 		}
8012 	}
8013 	return 1;
8014 }
8015 
8016 /** collate the zone using the simple scheme */
zonemd_simple_collate(struct auth_zone * z,int hashalgo,struct secalgo_hash * h,struct regional * region,struct sldns_buffer * buf,char ** reason)8017 static int zonemd_simple_collate(struct auth_zone* z, int hashalgo,
8018 	struct secalgo_hash* h, struct regional* region,
8019 	struct sldns_buffer* buf, char** reason)
8020 {
8021 	/* our tree is sorted in canonical order, so we can just loop over
8022 	 * the tree */
8023 	struct auth_data* n;
8024 	RBTREE_FOR(n, struct auth_data*, &z->data) {
8025 		if(!zonemd_simple_domain(z, hashalgo, h, n, region, buf,
8026 			reason))
8027 			return 0;
8028 	}
8029 	return 1;
8030 }
8031 
auth_zone_generate_zonemd_hash(struct auth_zone * z,int scheme,int hashalgo,uint8_t * hash,size_t hashlen,size_t * resultlen,struct regional * region,struct sldns_buffer * buf,char ** reason)8032 int auth_zone_generate_zonemd_hash(struct auth_zone* z, int scheme,
8033 	int hashalgo, uint8_t* hash, size_t hashlen, size_t* resultlen,
8034 	struct regional* region, struct sldns_buffer* buf, char** reason)
8035 {
8036 	struct secalgo_hash* h = zonemd_digest_init(hashalgo, reason);
8037 	if(!h) {
8038 		if(!*reason)
8039 			*reason = "digest init fail";
8040 		return 0;
8041 	}
8042 	if(scheme == ZONEMD_SCHEME_SIMPLE) {
8043 		if(!zonemd_simple_collate(z, hashalgo, h, region, buf, reason)) {
8044 			if(!*reason) *reason = "scheme simple collate fail";
8045 			secalgo_hash_delete(h);
8046 			return 0;
8047 		}
8048 	}
8049 	if(!zonemd_digest_finish(hashalgo, h, hash, hashlen, resultlen,
8050 		reason)) {
8051 		secalgo_hash_delete(h);
8052 		*reason = "digest finish fail";
8053 		return 0;
8054 	}
8055 	secalgo_hash_delete(h);
8056 	return 1;
8057 }
8058 
auth_zone_generate_zonemd_check(struct auth_zone * z,int scheme,int hashalgo,uint8_t * hash,size_t hashlen,struct regional * region,struct sldns_buffer * buf,char ** reason)8059 int auth_zone_generate_zonemd_check(struct auth_zone* z, int scheme,
8060 	int hashalgo, uint8_t* hash, size_t hashlen, struct regional* region,
8061 	struct sldns_buffer* buf, char** reason)
8062 {
8063 	uint8_t gen[512];
8064 	size_t genlen = 0;
8065 	*reason = NULL;
8066 	if(!zonemd_hashalgo_supported(hashalgo)) {
8067 		/* allow it */
8068 		*reason = "unsupported algorithm";
8069 		return 1;
8070 	}
8071 	if(!zonemd_scheme_supported(scheme)) {
8072 		/* allow it */
8073 		*reason = "unsupported scheme";
8074 		return 1;
8075 	}
8076 	if(hashlen < 12) {
8077 		/* the ZONEMD draft requires digests to fail if too small */
8078 		*reason = "digest length too small, less than 12";
8079 		return 0;
8080 	}
8081 	/* generate digest */
8082 	if(!auth_zone_generate_zonemd_hash(z, scheme, hashalgo, gen,
8083 		sizeof(gen), &genlen, region, buf, reason)) {
8084 		/* reason filled in by zonemd hash routine */
8085 		return 0;
8086 	}
8087 	/* check digest length */
8088 	if(hashlen != genlen) {
8089 		*reason = "incorrect digest length";
8090 		if(verbosity >= VERB_ALGO) {
8091 			verbose(VERB_ALGO, "zonemd scheme=%d hashalgo=%d",
8092 				scheme, hashalgo);
8093 			log_hex("ZONEMD should be  ", gen, genlen);
8094 			log_hex("ZONEMD to check is", hash, hashlen);
8095 		}
8096 		return 0;
8097 	}
8098 	/* check digest */
8099 	if(memcmp(hash, gen, genlen) != 0) {
8100 		*reason = "incorrect digest";
8101 		if(verbosity >= VERB_ALGO) {
8102 			verbose(VERB_ALGO, "zonemd scheme=%d hashalgo=%d",
8103 				scheme, hashalgo);
8104 			log_hex("ZONEMD should be  ", gen, genlen);
8105 			log_hex("ZONEMD to check is", hash, hashlen);
8106 		}
8107 		return 0;
8108 	}
8109 	return 1;
8110 }
8111 
8112 /** log auth zone message with zone name in front. */
8113 static void auth_zone_log(uint8_t* name, enum verbosity_value level,
8114 	const char* format, ...) ATTR_FORMAT(printf, 3, 4);
auth_zone_log(uint8_t * name,enum verbosity_value level,const char * format,...)8115 static void auth_zone_log(uint8_t* name, enum verbosity_value level,
8116 	const char* format, ...)
8117 {
8118 	va_list args;
8119 	va_start(args, format);
8120 	if(verbosity >= level) {
8121 		char str[LDNS_MAX_DOMAINLEN];
8122 		char msg[MAXSYSLOGMSGLEN];
8123 		dname_str(name, str);
8124 		vsnprintf(msg, sizeof(msg), format, args);
8125 		verbose(level, "auth zone %s %s", str, msg);
8126 	}
8127 	va_end(args);
8128 }
8129 
8130 /** ZONEMD, dnssec verify the rrset with the dnskey */
zonemd_dnssec_verify_rrset(struct auth_zone * z,struct module_env * env,struct module_stack * mods,struct ub_packed_rrset_key * dnskey,struct auth_data * node,struct auth_rrset * rrset,char ** why_bogus,uint8_t * sigalg,char * reasonbuf,size_t reasonlen)8131 static int zonemd_dnssec_verify_rrset(struct auth_zone* z,
8132 	struct module_env* env, struct module_stack* mods,
8133 	struct ub_packed_rrset_key* dnskey, struct auth_data* node,
8134 	struct auth_rrset* rrset, char** why_bogus, uint8_t* sigalg,
8135 	char* reasonbuf, size_t reasonlen)
8136 {
8137 	struct ub_packed_rrset_key pk;
8138 	enum sec_status sec;
8139 	struct val_env* ve;
8140 	int m;
8141 	int verified = 0;
8142 	m = modstack_find(mods, "validator");
8143 	if(m == -1) {
8144 		auth_zone_log(z->name, VERB_ALGO, "zonemd dnssec verify: have "
8145 			"DNSKEY chain of trust, but no validator module");
8146 		return 0;
8147 	}
8148 	ve = (struct val_env*)env->modinfo[m];
8149 
8150 	memset(&pk, 0, sizeof(pk));
8151 	pk.entry.key = &pk;
8152 	pk.entry.data = rrset->data;
8153 	pk.rk.dname = node->name;
8154 	pk.rk.dname_len = node->namelen;
8155 	pk.rk.type = htons(rrset->type);
8156 	pk.rk.rrset_class = htons(z->dclass);
8157 	if(verbosity >= VERB_ALGO) {
8158 		char typestr[32];
8159 		typestr[0]=0;
8160 		sldns_wire2str_type_buf(rrset->type, typestr, sizeof(typestr));
8161 		auth_zone_log(z->name, VERB_ALGO,
8162 			"zonemd: verify %s RRset with DNSKEY", typestr);
8163 	}
8164 	sec = dnskeyset_verify_rrset(env, ve, &pk, dnskey, sigalg, why_bogus, NULL,
8165 		LDNS_SECTION_ANSWER, NULL, &verified, reasonbuf, reasonlen);
8166 	if(sec == sec_status_secure) {
8167 		return 1;
8168 	}
8169 	if(why_bogus)
8170 		auth_zone_log(z->name, VERB_ALGO, "DNSSEC verify was bogus: %s", *why_bogus);
8171 	return 0;
8172 }
8173 
8174 /** check for nsec3, the RR with params equal, if bitmap has the type */
nsec3_of_param_has_type(struct auth_rrset * nsec3,int algo,size_t iter,uint8_t * salt,size_t saltlen,uint16_t rrtype)8175 static int nsec3_of_param_has_type(struct auth_rrset* nsec3, int algo,
8176 	size_t iter, uint8_t* salt, size_t saltlen, uint16_t rrtype)
8177 {
8178 	int i, count = (int)nsec3->data->count;
8179 	struct ub_packed_rrset_key pk;
8180 	memset(&pk, 0, sizeof(pk));
8181 	pk.entry.data = nsec3->data;
8182 	for(i=0; i<count; i++) {
8183 		int rralgo;
8184 		size_t rriter, rrsaltlen;
8185 		uint8_t* rrsalt;
8186 		if(!nsec3_get_params(&pk, i, &rralgo, &rriter, &rrsalt,
8187 			&rrsaltlen))
8188 			continue; /* no parameters, malformed */
8189 		if(rralgo != algo || rriter != iter || rrsaltlen != saltlen)
8190 			continue; /* different parameters */
8191 		if(saltlen != 0) {
8192 			if(rrsalt == NULL || salt == NULL)
8193 				continue;
8194 			if(memcmp(rrsalt, salt, saltlen) != 0)
8195 				continue; /* different salt parameters */
8196 		}
8197 		if(nsec3_has_type(&pk, i, rrtype))
8198 			return 1;
8199 	}
8200 	return 0;
8201 }
8202 
8203 /** Verify the absence of ZONEMD with DNSSEC by checking NSEC, NSEC3 type flag.
8204  * return false on failure, reason contains description of failure. */
zonemd_check_dnssec_absence(struct auth_zone * z,struct module_env * env,struct module_stack * mods,struct ub_packed_rrset_key * dnskey,struct auth_data * apex,char ** reason,char ** why_bogus,uint8_t * sigalg,char * reasonbuf,size_t reasonlen)8205 static int zonemd_check_dnssec_absence(struct auth_zone* z,
8206 	struct module_env* env, struct module_stack* mods,
8207 	struct ub_packed_rrset_key* dnskey, struct auth_data* apex,
8208 	char** reason, char** why_bogus, uint8_t* sigalg, char* reasonbuf,
8209 	size_t reasonlen)
8210 {
8211 	struct auth_rrset* nsec = NULL;
8212 	if(!apex) {
8213 		*reason = "zone has no apex domain but ZONEMD missing";
8214 		return 0;
8215 	}
8216 	nsec = az_domain_rrset(apex, LDNS_RR_TYPE_NSEC);
8217 	if(nsec) {
8218 		struct ub_packed_rrset_key pk;
8219 		/* dnssec verify the NSEC */
8220 		if(!zonemd_dnssec_verify_rrset(z, env, mods, dnskey, apex,
8221 			nsec, why_bogus, sigalg, reasonbuf, reasonlen)) {
8222 			*reason = "DNSSEC verify failed for NSEC RRset";
8223 			return 0;
8224 		}
8225 		/* check type bitmap */
8226 		memset(&pk, 0, sizeof(pk));
8227 		pk.entry.data = nsec->data;
8228 		if(nsec_has_type(&pk, LDNS_RR_TYPE_ZONEMD)) {
8229 			*reason = "DNSSEC NSEC bitmap says type ZONEMD exists";
8230 			return 0;
8231 		}
8232 		auth_zone_log(z->name, VERB_ALGO, "zonemd DNSSEC NSEC verification of absence of ZONEMD secure");
8233 	} else {
8234 		/* NSEC3 perhaps ? */
8235 		int algo;
8236 		size_t iter, saltlen;
8237 		uint8_t* salt;
8238 		struct auth_rrset* nsec3param = az_domain_rrset(apex,
8239 			LDNS_RR_TYPE_NSEC3PARAM);
8240 		struct auth_data* match;
8241 		struct auth_rrset* nsec3;
8242 		if(!nsec3param) {
8243 			*reason = "zone has no NSEC information but ZONEMD missing";
8244 			return 0;
8245 		}
8246 		if(!az_nsec3_param(z, &algo, &iter, &salt, &saltlen)) {
8247 			*reason = "zone has no NSEC information but ZONEMD missing";
8248 			return 0;
8249 		}
8250 		/* find the NSEC3 record */
8251 		match = az_nsec3_find_exact(z, z->name, z->namelen, algo,
8252 			iter, salt, saltlen);
8253 		if(!match) {
8254 			*reason = "zone has no NSEC3 domain for the apex but ZONEMD missing";
8255 			return 0;
8256 		}
8257 		nsec3 = az_domain_rrset(match, LDNS_RR_TYPE_NSEC3);
8258 		if(!nsec3) {
8259 			*reason = "zone has no NSEC3 RRset for the apex but ZONEMD missing";
8260 			return 0;
8261 		}
8262 		/* dnssec verify the NSEC3 */
8263 		if(!zonemd_dnssec_verify_rrset(z, env, mods, dnskey, match,
8264 			nsec3, why_bogus, sigalg, reasonbuf, reasonlen)) {
8265 			*reason = "DNSSEC verify failed for NSEC3 RRset";
8266 			return 0;
8267 		}
8268 		/* check type bitmap */
8269 		if(nsec3_of_param_has_type(nsec3, algo, iter, salt, saltlen,
8270 			LDNS_RR_TYPE_ZONEMD)) {
8271 			*reason = "DNSSEC NSEC3 bitmap says type ZONEMD exists";
8272 			return 0;
8273 		}
8274 		auth_zone_log(z->name, VERB_ALGO, "zonemd DNSSEC NSEC3 verification of absence of ZONEMD secure");
8275 	}
8276 
8277 	return 1;
8278 }
8279 
8280 /** Verify the SOA and ZONEMD DNSSEC signatures.
8281  * return false on failure, reason contains description of failure. */
zonemd_check_dnssec_soazonemd(struct auth_zone * z,struct module_env * env,struct module_stack * mods,struct ub_packed_rrset_key * dnskey,struct auth_data * apex,struct auth_rrset * zonemd_rrset,char ** reason,char ** why_bogus,uint8_t * sigalg,char * reasonbuf,size_t reasonlen)8282 static int zonemd_check_dnssec_soazonemd(struct auth_zone* z,
8283 	struct module_env* env, struct module_stack* mods,
8284 	struct ub_packed_rrset_key* dnskey, struct auth_data* apex,
8285 	struct auth_rrset* zonemd_rrset, char** reason, char** why_bogus,
8286 	uint8_t* sigalg, char* reasonbuf, size_t reasonlen)
8287 {
8288 	struct auth_rrset* soa;
8289 	if(!apex) {
8290 		*reason = "zone has no apex domain";
8291 		return 0;
8292 	}
8293 	soa = az_domain_rrset(apex, LDNS_RR_TYPE_SOA);
8294 	if(!soa) {
8295 		*reason = "zone has no SOA RRset";
8296 		return 0;
8297 	}
8298 	if(!zonemd_dnssec_verify_rrset(z, env, mods, dnskey, apex, soa,
8299 		why_bogus, sigalg, reasonbuf, reasonlen)) {
8300 		*reason = "DNSSEC verify failed for SOA RRset";
8301 		return 0;
8302 	}
8303 	if(!zonemd_dnssec_verify_rrset(z, env, mods, dnskey, apex,
8304 		zonemd_rrset, why_bogus, sigalg, reasonbuf, reasonlen)) {
8305 		*reason = "DNSSEC verify failed for ZONEMD RRset";
8306 		return 0;
8307 	}
8308 	auth_zone_log(z->name, VERB_ALGO, "zonemd DNSSEC verification of SOA and ZONEMD RRsets secure");
8309 	return 1;
8310 }
8311 
8312 /**
8313  * Fail the ZONEMD verification.
8314  * @param z: auth zone that fails.
8315  * @param env: environment with config, to ignore failure or not.
8316  * @param reason: failure string description.
8317  * @param why_bogus: failure string for DNSSEC verification failure.
8318  * @param result: strdup result in here if not NULL.
8319  */
auth_zone_zonemd_fail(struct auth_zone * z,struct module_env * env,char * reason,char * why_bogus,char ** result)8320 static void auth_zone_zonemd_fail(struct auth_zone* z, struct module_env* env,
8321 	char* reason, char* why_bogus, char** result)
8322 {
8323 	char zstr[LDNS_MAX_DOMAINLEN];
8324 	/* if fail: log reason, and depending on config also take action
8325 	 * and drop the zone, eg. it is gone from memory, set zone_expired */
8326 	dname_str(z->name, zstr);
8327 	if(!reason) reason = "verification failed";
8328 	if(result) {
8329 		if(why_bogus) {
8330 			char res[1024];
8331 			snprintf(res, sizeof(res), "%s: %s", reason,
8332 				why_bogus);
8333 			*result = strdup(res);
8334 		} else {
8335 			*result = strdup(reason);
8336 		}
8337 		if(!*result) log_err("out of memory");
8338 	} else {
8339 		log_warn("auth zone %s: ZONEMD verification failed: %s", zstr, reason);
8340 	}
8341 
8342 	if(env->cfg->zonemd_permissive_mode) {
8343 		verbose(VERB_ALGO, "zonemd-permissive-mode enabled, "
8344 			"not blocking zone %s", zstr);
8345 		return;
8346 	}
8347 
8348 	/* expired means the zone gives servfail and is not used by
8349 	 * lookup if fallback_enabled*/
8350 	z->zone_expired = 1;
8351 }
8352 
8353 /**
8354  * Verify the zonemd with DNSSEC and hash check, with given key.
8355  * @param z: auth zone.
8356  * @param env: environment with config and temp buffers.
8357  * @param mods: module stack with validator env for verification.
8358  * @param dnskey: dnskey that we can use, or NULL.  If nonnull, the key
8359  * 	has been verified and is the start of the chain of trust.
8360  * @param is_insecure: if true, the dnskey is not used, the zone is insecure.
8361  * 	And dnssec is not used.  It is DNSSEC secure insecure or not under
8362  * 	a trust anchor.
8363  * @param sigalg: if nonNULL provide algorithm downgrade protection.
8364  * 	Otherwise one algorithm is enough. Must have space of ALGO_NEEDS_MAX+1.
8365  * @param result: if not NULL result reason copied here.
8366  */
8367 static void
auth_zone_verify_zonemd_with_key(struct auth_zone * z,struct module_env * env,struct module_stack * mods,struct ub_packed_rrset_key * dnskey,int is_insecure,char ** result,uint8_t * sigalg)8368 auth_zone_verify_zonemd_with_key(struct auth_zone* z, struct module_env* env,
8369 	struct module_stack* mods, struct ub_packed_rrset_key* dnskey,
8370 	int is_insecure, char** result, uint8_t* sigalg)
8371 {
8372 	char reasonbuf[256];
8373 	char* reason = NULL, *why_bogus = NULL;
8374 	struct auth_data* apex = NULL;
8375 	struct auth_rrset* zonemd_rrset = NULL;
8376 	int zonemd_absent = 0, zonemd_absence_dnssecok = 0;
8377 
8378 	/* see if ZONEMD is present or absent. */
8379 	apex = az_find_name(z, z->name, z->namelen);
8380 	if(!apex) {
8381 		zonemd_absent = 1;
8382 	} else {
8383 		zonemd_rrset = az_domain_rrset(apex, LDNS_RR_TYPE_ZONEMD);
8384 		if(!zonemd_rrset || zonemd_rrset->data->count==0) {
8385 			zonemd_absent = 1;
8386 			zonemd_rrset = NULL;
8387 		}
8388 	}
8389 
8390 	/* if no DNSSEC, done. */
8391 	/* if no ZONEMD, and DNSSEC, use DNSKEY to verify NSEC or NSEC3 for
8392 	 * zone apex.  Check ZONEMD bit is turned off or else fail */
8393 	/* if ZONEMD, and DNSSEC, check DNSSEC signature on SOA and ZONEMD,
8394 	 * or else fail */
8395 	if(!dnskey && !is_insecure) {
8396 		auth_zone_zonemd_fail(z, env, "DNSKEY missing", NULL, result);
8397 		return;
8398 	} else if(!zonemd_rrset && dnskey && !is_insecure) {
8399 		/* fetch, DNSSEC verify, and check NSEC/NSEC3 */
8400 		if(!zonemd_check_dnssec_absence(z, env, mods, dnskey, apex,
8401 			&reason, &why_bogus, sigalg, reasonbuf,
8402 			sizeof(reasonbuf))) {
8403 			auth_zone_zonemd_fail(z, env, reason, why_bogus, result);
8404 			return;
8405 		}
8406 		zonemd_absence_dnssecok = 1;
8407 	} else if(zonemd_rrset && dnskey && !is_insecure) {
8408 		/* check DNSSEC verify of SOA and ZONEMD */
8409 		if(!zonemd_check_dnssec_soazonemd(z, env, mods, dnskey, apex,
8410 			zonemd_rrset, &reason, &why_bogus, sigalg, reasonbuf,
8411 			sizeof(reasonbuf))) {
8412 			auth_zone_zonemd_fail(z, env, reason, why_bogus, result);
8413 			return;
8414 		}
8415 	}
8416 
8417 	if(zonemd_absent && z->zonemd_reject_absence) {
8418 		auth_zone_zonemd_fail(z, env, "ZONEMD absent and that is not allowed by config", NULL, result);
8419 		return;
8420 	}
8421 	if(zonemd_absent && zonemd_absence_dnssecok) {
8422 		auth_zone_log(z->name, VERB_ALGO, "DNSSEC verified nonexistence of ZONEMD");
8423 		if(result) {
8424 			*result = strdup("DNSSEC verified nonexistence of ZONEMD");
8425 			if(!*result) log_err("out of memory");
8426 		}
8427 		return;
8428 	}
8429 	if(zonemd_absent) {
8430 		auth_zone_log(z->name, VERB_ALGO, "no ZONEMD present");
8431 		if(result) {
8432 			*result = strdup("no ZONEMD present");
8433 			if(!*result) log_err("out of memory");
8434 		}
8435 		return;
8436 	}
8437 
8438 	/* check ZONEMD checksum and report or else fail. */
8439 	if(!auth_zone_zonemd_check_hash(z, env, &reason)) {
8440 		auth_zone_zonemd_fail(z, env, reason, NULL, result);
8441 		return;
8442 	}
8443 
8444 	/* success! log the success */
8445 	if(reason)
8446 		auth_zone_log(z->name, VERB_ALGO, "ZONEMD %s", reason);
8447 	else	auth_zone_log(z->name, VERB_ALGO, "ZONEMD verification successful");
8448 	if(result) {
8449 		if(reason)
8450 			*result = strdup(reason);
8451 		else	*result = strdup("ZONEMD verification successful");
8452 		if(!*result) log_err("out of memory");
8453 	}
8454 }
8455 
8456 /**
8457  * verify the zone DNSKEY rrset from the trust anchor
8458  * This is possible because the anchor is for the zone itself, and can
8459  * thus apply straight to the zone DNSKEY set.
8460  * @param z: the auth zone.
8461  * @param env: environment with time and temp buffers.
8462  * @param mods: module stack for validator environment for dnssec validation.
8463  * @param anchor: trust anchor to use
8464  * @param is_insecure: returned, true if the zone is securely insecure.
8465  * @param why_bogus: if the routine fails, returns the failure reason.
8466  * @param keystorage: where to store the ub_packed_rrset_key that is created
8467  * 	on success. A pointer to it is returned on success.
8468  * @param reasonbuf: buffer to use for fail reason string print.
8469  * @param reasonlen: length of reasonbuf.
8470  * @return the dnskey RRset, reference to zone data and keystorage, or
8471  * 	NULL on failure.
8472  */
8473 static struct ub_packed_rrset_key*
zonemd_get_dnskey_from_anchor(struct auth_zone * z,struct module_env * env,struct module_stack * mods,struct trust_anchor * anchor,int * is_insecure,char ** why_bogus,struct ub_packed_rrset_key * keystorage,char * reasonbuf,size_t reasonlen)8474 zonemd_get_dnskey_from_anchor(struct auth_zone* z, struct module_env* env,
8475 	struct module_stack* mods, struct trust_anchor* anchor,
8476 	int* is_insecure, char** why_bogus,
8477 	struct ub_packed_rrset_key* keystorage, char* reasonbuf,
8478 	size_t reasonlen)
8479 {
8480 	struct auth_data* apex;
8481 	struct auth_rrset* dnskey_rrset;
8482 	enum sec_status sec;
8483 	struct val_env* ve;
8484 	int m;
8485 
8486 	apex = az_find_name(z, z->name, z->namelen);
8487 	if(!apex) {
8488 		*why_bogus = "have trust anchor, but zone has no apex domain for DNSKEY";
8489 		return 0;
8490 	}
8491 	dnskey_rrset = az_domain_rrset(apex, LDNS_RR_TYPE_DNSKEY);
8492 	if(!dnskey_rrset || dnskey_rrset->data->count==0) {
8493 		*why_bogus = "have trust anchor, but zone has no DNSKEY";
8494 		return 0;
8495 	}
8496 
8497 	m = modstack_find(mods, "validator");
8498 	if(m == -1) {
8499 		*why_bogus = "have trust anchor, but no validator module";
8500 		return 0;
8501 	}
8502 	ve = (struct val_env*)env->modinfo[m];
8503 
8504 	memset(keystorage, 0, sizeof(*keystorage));
8505 	keystorage->entry.key = keystorage;
8506 	keystorage->entry.data = dnskey_rrset->data;
8507 	keystorage->rk.dname = apex->name;
8508 	keystorage->rk.dname_len = apex->namelen;
8509 	keystorage->rk.type = htons(LDNS_RR_TYPE_DNSKEY);
8510 	keystorage->rk.rrset_class = htons(z->dclass);
8511 	auth_zone_log(z->name, VERB_QUERY,
8512 		"zonemd: verify DNSKEY RRset with trust anchor");
8513 	sec = val_verify_DNSKEY_with_TA(env, ve, keystorage, anchor->ds_rrset,
8514 		anchor->dnskey_rrset, NULL, why_bogus, NULL, NULL, reasonbuf,
8515 		reasonlen);
8516 	regional_free_all(env->scratch);
8517 	if(sec == sec_status_secure) {
8518 		/* success */
8519 		*is_insecure = 0;
8520 		return keystorage;
8521 	} else if(sec == sec_status_insecure) {
8522 		/* insecure */
8523 		*is_insecure = 1;
8524 	} else {
8525 		/* bogus */
8526 		*is_insecure = 0;
8527 		auth_zone_log(z->name, VERB_ALGO,
8528 			"zonemd: verify DNSKEY RRset with trust anchor failed: %s", *why_bogus);
8529 	}
8530 	return NULL;
8531 }
8532 
8533 /** verify the DNSKEY from the zone with looked up DS record */
8534 static struct ub_packed_rrset_key*
auth_zone_verify_zonemd_key_with_ds(struct auth_zone * z,struct module_env * env,struct module_stack * mods,struct ub_packed_rrset_key * ds,int * is_insecure,char ** why_bogus,struct ub_packed_rrset_key * keystorage,uint8_t * sigalg,char * reasonbuf,size_t reasonlen)8535 auth_zone_verify_zonemd_key_with_ds(struct auth_zone* z,
8536 	struct module_env* env, struct module_stack* mods,
8537 	struct ub_packed_rrset_key* ds, int* is_insecure, char** why_bogus,
8538 	struct ub_packed_rrset_key* keystorage, uint8_t* sigalg,
8539 	char* reasonbuf, size_t reasonlen)
8540 {
8541 	struct auth_data* apex;
8542 	struct auth_rrset* dnskey_rrset;
8543 	enum sec_status sec;
8544 	struct val_env* ve;
8545 	int m;
8546 
8547 	/* fetch DNSKEY from zone data */
8548 	apex = az_find_name(z, z->name, z->namelen);
8549 	if(!apex) {
8550 		*why_bogus = "in verifywithDS, zone has no apex";
8551 		return NULL;
8552 	}
8553 	dnskey_rrset = az_domain_rrset(apex, LDNS_RR_TYPE_DNSKEY);
8554 	if(!dnskey_rrset || dnskey_rrset->data->count==0) {
8555 		*why_bogus = "in verifywithDS, zone has no DNSKEY";
8556 		return NULL;
8557 	}
8558 
8559 	m = modstack_find(mods, "validator");
8560 	if(m == -1) {
8561 		*why_bogus = "in verifywithDS, have no validator module";
8562 		return NULL;
8563 	}
8564 	ve = (struct val_env*)env->modinfo[m];
8565 
8566 	memset(keystorage, 0, sizeof(*keystorage));
8567 	keystorage->entry.key = keystorage;
8568 	keystorage->entry.data = dnskey_rrset->data;
8569 	keystorage->rk.dname = apex->name;
8570 	keystorage->rk.dname_len = apex->namelen;
8571 	keystorage->rk.type = htons(LDNS_RR_TYPE_DNSKEY);
8572 	keystorage->rk.rrset_class = htons(z->dclass);
8573 	auth_zone_log(z->name, VERB_QUERY, "zonemd: verify zone DNSKEY with DS");
8574 	sec = val_verify_DNSKEY_with_DS(env, ve, keystorage, ds, sigalg,
8575 		why_bogus, NULL, NULL, reasonbuf, reasonlen);
8576 	regional_free_all(env->scratch);
8577 	if(sec == sec_status_secure) {
8578 		/* success */
8579 		return keystorage;
8580 	} else if(sec == sec_status_insecure) {
8581 		/* insecure */
8582 		*is_insecure = 1;
8583 	} else {
8584 		/* bogus */
8585 		*is_insecure = 0;
8586 		if(*why_bogus == NULL)
8587 			*why_bogus = "verify failed";
8588 		auth_zone_log(z->name, VERB_ALGO,
8589 			"zonemd: verify DNSKEY RRset with DS failed: %s",
8590 			*why_bogus);
8591 	}
8592 	return NULL;
8593 }
8594 
8595 /** callback for ZONEMD lookup of DNSKEY */
auth_zonemd_dnskey_lookup_callback(void * arg,int rcode,sldns_buffer * buf,enum sec_status sec,char * why_bogus,int ATTR_UNUSED (was_ratelimited))8596 void auth_zonemd_dnskey_lookup_callback(void* arg, int rcode, sldns_buffer* buf,
8597 	enum sec_status sec, char* why_bogus, int ATTR_UNUSED(was_ratelimited))
8598 {
8599 	struct auth_zone* z = (struct auth_zone*)arg;
8600 	struct module_env* env;
8601 	char reasonbuf[256];
8602 	char* reason = NULL, *ds_bogus = NULL, *typestr="DNSKEY";
8603 	struct ub_packed_rrset_key* dnskey = NULL, *ds = NULL;
8604 	int is_insecure = 0, downprot;
8605 	struct ub_packed_rrset_key keystorage;
8606 	uint8_t sigalg[ALGO_NEEDS_MAX+1];
8607 
8608 	lock_rw_wrlock(&z->lock);
8609 	env = z->zonemd_callback_env;
8610 	/* release the env variable so another worker can pick up the
8611 	 * ZONEMD verification task if it wants to */
8612 	z->zonemd_callback_env = NULL;
8613 	if(!env || env->outnet->want_to_quit || z->zone_deleted) {
8614 		lock_rw_unlock(&z->lock);
8615 		return; /* stop on quit */
8616 	}
8617 	if(z->zonemd_callback_qtype == LDNS_RR_TYPE_DS)
8618 		typestr = "DS";
8619 	downprot = env->cfg->harden_algo_downgrade;
8620 
8621 	/* process result */
8622 	if(sec == sec_status_bogus) {
8623 		reason = why_bogus;
8624 		if(!reason) {
8625 			if(z->zonemd_callback_qtype == LDNS_RR_TYPE_DNSKEY)
8626 				reason = "lookup of DNSKEY was bogus";
8627 			else	reason = "lookup of DS was bogus";
8628 		}
8629 		auth_zone_log(z->name, VERB_ALGO,
8630 			"zonemd lookup of %s was bogus: %s", typestr, reason);
8631 	} else if(rcode == LDNS_RCODE_NOERROR) {
8632 		uint16_t wanted_qtype = z->zonemd_callback_qtype;
8633 		struct regional* temp = env->scratch;
8634 		struct query_info rq;
8635 		struct reply_info* rep;
8636 		memset(&rq, 0, sizeof(rq));
8637 		rep = parse_reply_in_temp_region(buf, temp, &rq);
8638 		if(rep && rq.qtype == wanted_qtype &&
8639 			query_dname_compare(z->name, rq.qname) == 0 &&
8640 			FLAGS_GET_RCODE(rep->flags) == LDNS_RCODE_NOERROR) {
8641 			/* parsed successfully */
8642 			struct ub_packed_rrset_key* answer =
8643 				reply_find_answer_rrset(&rq, rep);
8644 			if(answer && sec == sec_status_secure) {
8645 				if(z->zonemd_callback_qtype == LDNS_RR_TYPE_DNSKEY)
8646 					dnskey = answer;
8647 				else	ds = answer;
8648 				auth_zone_log(z->name, VERB_ALGO,
8649 					"zonemd lookup of %s was secure", typestr);
8650 			} else if(sec == sec_status_secure && !answer) {
8651 				is_insecure = 1;
8652 				auth_zone_log(z->name, VERB_ALGO,
8653 					"zonemd lookup of %s has no content, but is secure, treat as insecure", typestr);
8654 			} else if(sec == sec_status_insecure) {
8655 				is_insecure = 1;
8656 				auth_zone_log(z->name, VERB_ALGO,
8657 					"zonemd lookup of %s was insecure", typestr);
8658 			} else if(sec == sec_status_indeterminate) {
8659 				is_insecure = 1;
8660 				auth_zone_log(z->name, VERB_ALGO,
8661 					"zonemd lookup of %s was indeterminate, treat as insecure", typestr);
8662 			} else {
8663 				auth_zone_log(z->name, VERB_ALGO,
8664 					"zonemd lookup of %s has nodata", typestr);
8665 				if(z->zonemd_callback_qtype == LDNS_RR_TYPE_DNSKEY)
8666 					reason = "lookup of DNSKEY has nodata";
8667 				else	reason = "lookup of DS has nodata";
8668 			}
8669 		} else if(rep && rq.qtype == wanted_qtype &&
8670 			query_dname_compare(z->name, rq.qname) == 0 &&
8671 			FLAGS_GET_RCODE(rep->flags) == LDNS_RCODE_NXDOMAIN &&
8672 			sec == sec_status_secure) {
8673 			/* secure nxdomain, so the zone is like some RPZ zone
8674 			 * that does not exist in the wider internet, with
8675 			 * a secure nxdomain answer outside of it. So we
8676 			 * treat the zonemd zone without a dnssec chain of
8677 			 * trust, as insecure. */
8678 			is_insecure = 1;
8679 			auth_zone_log(z->name, VERB_ALGO,
8680 				"zonemd lookup of %s was secure NXDOMAIN, treat as insecure", typestr);
8681 		} else if(rep && rq.qtype == wanted_qtype &&
8682 			query_dname_compare(z->name, rq.qname) == 0 &&
8683 			FLAGS_GET_RCODE(rep->flags) == LDNS_RCODE_NXDOMAIN &&
8684 			sec == sec_status_insecure) {
8685 			is_insecure = 1;
8686 			auth_zone_log(z->name, VERB_ALGO,
8687 				"zonemd lookup of %s was insecure NXDOMAIN, treat as insecure", typestr);
8688 		} else if(rep && rq.qtype == wanted_qtype &&
8689 			query_dname_compare(z->name, rq.qname) == 0 &&
8690 			FLAGS_GET_RCODE(rep->flags) == LDNS_RCODE_NXDOMAIN &&
8691 			sec == sec_status_indeterminate) {
8692 			is_insecure = 1;
8693 			auth_zone_log(z->name, VERB_ALGO,
8694 				"zonemd lookup of %s was indeterminate NXDOMAIN, treat as insecure", typestr);
8695 		} else {
8696 			auth_zone_log(z->name, VERB_ALGO,
8697 				"zonemd lookup of %s has no answer", typestr);
8698 			if(z->zonemd_callback_qtype == LDNS_RR_TYPE_DNSKEY)
8699 				reason = "lookup of DNSKEY has no answer";
8700 			else	reason = "lookup of DS has no answer";
8701 		}
8702 	} else {
8703 		auth_zone_log(z->name, VERB_ALGO,
8704 			"zonemd lookup of %s failed", typestr);
8705 		if(z->zonemd_callback_qtype == LDNS_RR_TYPE_DNSKEY)
8706 			reason = "lookup of DNSKEY failed";
8707 		else	reason = "lookup of DS failed";
8708 	}
8709 
8710 	if(!reason && !is_insecure && !dnskey && ds) {
8711 		dnskey = auth_zone_verify_zonemd_key_with_ds(z, env,
8712 			&env->mesh->mods, ds, &is_insecure, &ds_bogus,
8713 			&keystorage, downprot?sigalg:NULL, reasonbuf,
8714 			sizeof(reasonbuf));
8715 		if(!dnskey && !is_insecure && !reason)
8716 			reason = "DNSKEY verify with DS failed";
8717 	}
8718 
8719 	if(reason) {
8720 		auth_zone_zonemd_fail(z, env, reason, ds_bogus, NULL);
8721 		lock_rw_unlock(&z->lock);
8722 		regional_free_all(env->scratch);
8723 		return;
8724 	}
8725 
8726 	auth_zone_verify_zonemd_with_key(z, env, &env->mesh->mods, dnskey,
8727 		is_insecure, NULL, downprot?sigalg:NULL);
8728 	regional_free_all(env->scratch);
8729 	lock_rw_unlock(&z->lock);
8730 }
8731 
8732 /** lookup DNSKEY for ZONEMD verification */
8733 static int
zonemd_lookup_dnskey(struct auth_zone * z,struct module_env * env)8734 zonemd_lookup_dnskey(struct auth_zone* z, struct module_env* env)
8735 {
8736 	struct query_info qinfo;
8737 	uint16_t qflags = BIT_RD;
8738 	struct edns_data edns;
8739 	sldns_buffer* buf = env->scratch_buffer;
8740 	int fetch_ds = 0;
8741 
8742 	if(!z->fallback_enabled) {
8743 		/* we cannot actually get the DNSKEY, because it is in the
8744 		 * zone we have ourselves, and it is not served yet
8745 		 * (possibly), so fetch type DS */
8746 		fetch_ds = 1;
8747 	}
8748 	if(z->zonemd_callback_env) {
8749 		/* another worker is already working on the callback
8750 		 * for the DNSKEY lookup for ZONEMD verification.
8751 		 * We do not also have to do ZONEMD verification, let that
8752 		 * worker do it */
8753 		auth_zone_log(z->name, VERB_ALGO,
8754 			"zonemd needs lookup of %s and that already is worked on by another worker", (fetch_ds?"DS":"DNSKEY"));
8755 		return 1;
8756 	}
8757 
8758 	/* use mesh_new_callback to lookup the DNSKEY,
8759 	 * and then wait for them to be looked up (in cache, or query) */
8760 	qinfo.qname_len = z->namelen;
8761 	qinfo.qname = z->name;
8762 	qinfo.qclass = z->dclass;
8763 	if(fetch_ds)
8764 		qinfo.qtype = LDNS_RR_TYPE_DS;
8765 	else	qinfo.qtype = LDNS_RR_TYPE_DNSKEY;
8766 	qinfo.local_alias = NULL;
8767 	if(verbosity >= VERB_ALGO) {
8768 		char buf1[512];
8769 		char buf2[LDNS_MAX_DOMAINLEN];
8770 		dname_str(z->name, buf2);
8771 		snprintf(buf1, sizeof(buf1), "auth zone %s: lookup %s "
8772 			"for zonemd verification", buf2,
8773 			(fetch_ds?"DS":"DNSKEY"));
8774 		log_query_info(VERB_ALGO, buf1, &qinfo);
8775 	}
8776 	edns.edns_present = 1;
8777 	edns.ext_rcode = 0;
8778 	edns.edns_version = 0;
8779 	edns.bits = EDNS_DO;
8780 	edns.opt_list_in = NULL;
8781 	edns.opt_list_out = NULL;
8782 	edns.opt_list_inplace_cb_out = NULL;
8783 	if(sldns_buffer_capacity(buf) < 65535)
8784 		edns.udp_size = (uint16_t)sldns_buffer_capacity(buf);
8785 	else	edns.udp_size = 65535;
8786 
8787 	/* store the worker-specific module env for the callback.
8788 	 * We can then reference this when the callback executes */
8789 	z->zonemd_callback_env = env;
8790 	z->zonemd_callback_qtype = qinfo.qtype;
8791 	/* the callback can be called straight away */
8792 	lock_rw_unlock(&z->lock);
8793 	if(!mesh_new_callback(env->mesh, &qinfo, qflags, &edns, buf, 0,
8794 		&auth_zonemd_dnskey_lookup_callback, z, 0,
8795 		&z->zonemd_callback_unique_info)) {
8796 		lock_rw_wrlock(&z->lock);
8797 		log_err("out of memory lookup of %s for zonemd",
8798 			(fetch_ds?"DS":"DNSKEY"));
8799 		return 0;
8800 	}
8801 	lock_rw_wrlock(&z->lock);
8802 	return 1;
8803 }
8804 
auth_zone_verify_zonemd(struct auth_zone * z,struct module_env * env,struct module_stack * mods,char ** result,int offline,int only_online)8805 void auth_zone_verify_zonemd(struct auth_zone* z, struct module_env* env,
8806 	struct module_stack* mods, char** result, int offline, int only_online)
8807 {
8808 	char reasonbuf[256];
8809 	char* reason = NULL, *why_bogus = NULL;
8810 	struct trust_anchor* anchor = NULL;
8811 	struct ub_packed_rrset_key* dnskey = NULL;
8812 	struct ub_packed_rrset_key keystorage;
8813 	int is_insecure = 0;
8814 	/* verify the ZONEMD if present.
8815 	 * If not present check if absence is allowed by DNSSEC */
8816 	if(!z->zonemd_check)
8817 		return;
8818 	if(z->data.count == 0)
8819 		return; /* no data */
8820 
8821 	/* if zone is under a trustanchor */
8822 	/* is it equal to trustanchor - get dnskey's verified */
8823 	/* else, find chain of trust by fetching DNSKEYs lookup for zone */
8824 	/* result if that, if insecure, means no DNSSEC for the ZONEMD,
8825 	 * otherwise we have the zone DNSKEY for the DNSSEC verification. */
8826 	if(env->anchors)
8827 		anchor = anchors_lookup(env->anchors, z->name, z->namelen,
8828 			z->dclass);
8829 	if(anchor && anchor->numDS == 0 && anchor->numDNSKEY == 0) {
8830 		/* domain-insecure trust anchor for unsigned zones */
8831 		lock_basic_unlock(&anchor->lock);
8832 		if(only_online)
8833 			return;
8834 		dnskey = NULL;
8835 		is_insecure = 1;
8836 	} else if(anchor && query_dname_compare(z->name, anchor->name) == 0) {
8837 		if(only_online) {
8838 			lock_basic_unlock(&anchor->lock);
8839 			return;
8840 		}
8841 		/* equal to trustanchor, no need for online lookups */
8842 		dnskey = zonemd_get_dnskey_from_anchor(z, env, mods, anchor,
8843 			&is_insecure, &why_bogus, &keystorage, reasonbuf,
8844 			sizeof(reasonbuf));
8845 		lock_basic_unlock(&anchor->lock);
8846 		if(!dnskey && !reason && !is_insecure) {
8847 			reason = "verify DNSKEY RRset with trust anchor failed";
8848 		}
8849 	} else if(anchor) {
8850 		lock_basic_unlock(&anchor->lock);
8851 		/* perform online lookups */
8852 		if(offline)
8853 			return;
8854 		/* setup online lookups, and wait for them */
8855 		if(zonemd_lookup_dnskey(z, env)) {
8856 			/* wait for the lookup */
8857 			return;
8858 		}
8859 		reason = "could not lookup DNSKEY for chain of trust";
8860 	} else {
8861 		/* the zone is not under a trust anchor */
8862 		if(only_online)
8863 			return;
8864 		dnskey = NULL;
8865 		is_insecure = 1;
8866 	}
8867 
8868 	if(reason) {
8869 		auth_zone_zonemd_fail(z, env, reason, why_bogus, result);
8870 		regional_free_all(env->scratch);
8871 		return;
8872 	}
8873 
8874 	auth_zone_verify_zonemd_with_key(z, env, mods, dnskey, is_insecure,
8875 		result, NULL);
8876 	regional_free_all(env->scratch);
8877 }
8878 
auth_zones_pickup_zonemd_verify(struct auth_zones * az,struct module_env * env)8879 void auth_zones_pickup_zonemd_verify(struct auth_zones* az,
8880 	struct module_env* env)
8881 {
8882 	struct auth_zone key;
8883 	uint8_t savezname[255+1];
8884 	size_t savezname_len;
8885 	struct auth_zone* z;
8886 	key.node.key = &key;
8887 	lock_rw_rdlock(&az->lock);
8888 	RBTREE_FOR(z, struct auth_zone*, &az->ztree) {
8889 		lock_rw_wrlock(&z->lock);
8890 		if(!z->zonemd_check) {
8891 			lock_rw_unlock(&z->lock);
8892 			continue;
8893 		}
8894 		key.dclass = z->dclass;
8895 		key.namelabs = z->namelabs;
8896 		if(z->namelen > sizeof(savezname)) {
8897 			lock_rw_unlock(&z->lock);
8898 			log_err("auth_zones_pickup_zonemd_verify: zone name too long");
8899 			continue;
8900 		}
8901 		savezname_len = z->namelen;
8902 		memmove(savezname, z->name, z->namelen);
8903 		lock_rw_unlock(&az->lock);
8904 		auth_zone_verify_zonemd(z, env, &env->mesh->mods, NULL, 0, 1);
8905 		lock_rw_unlock(&z->lock);
8906 		lock_rw_rdlock(&az->lock);
8907 		/* find the zone we had before, it is not deleted,
8908 		 * because we have a flag for that that is processed at
8909 		 * apply_cfg time */
8910 		key.namelen = savezname_len;
8911 		key.name = savezname;
8912 		z = (struct auth_zone*)rbtree_search(&az->ztree, &key);
8913 		if(!z)
8914 			break;
8915 	}
8916 	lock_rw_unlock(&az->lock);
8917 }
8918 
8919 /** Get memory usage of auth rrset */
8920 static size_t
auth_rrset_get_mem(struct auth_rrset * rrset)8921 auth_rrset_get_mem(struct auth_rrset* rrset)
8922 {
8923 	size_t m = sizeof(*rrset) + packed_rrset_sizeof(rrset->data);
8924 	return m;
8925 }
8926 
8927 /** Get memory usage of auth data */
8928 static size_t
auth_data_get_mem(struct auth_data * node)8929 auth_data_get_mem(struct auth_data* node)
8930 {
8931 	size_t m = sizeof(*node) + node->namelen;
8932 	struct auth_rrset* rrset;
8933 	for(rrset = node->rrsets; rrset; rrset = rrset->next) {
8934 		m += auth_rrset_get_mem(rrset);
8935 	}
8936 	return m;
8937 }
8938 
8939 /** Get memory usage of auth zone */
8940 static size_t
auth_zone_get_mem(struct auth_zone * z)8941 auth_zone_get_mem(struct auth_zone* z)
8942 {
8943 	size_t m = sizeof(*z) + z->namelen;
8944 	struct auth_data* node;
8945 	if(z->zonefile)
8946 		m += strlen(z->zonefile)+1;
8947 	RBTREE_FOR(node, struct auth_data*, &z->data) {
8948 		m += auth_data_get_mem(node);
8949 	}
8950 	if(z->rpz)
8951 		m += rpz_get_mem(z->rpz);
8952 	return m;
8953 }
8954 
8955 /** Get memory usage of list of auth addr */
8956 static size_t
auth_addrs_get_mem(struct auth_addr * list)8957 auth_addrs_get_mem(struct auth_addr* list)
8958 {
8959 	size_t m = 0;
8960 	struct auth_addr* a;
8961 	for(a = list; a; a = a->next) {
8962 		m += sizeof(*a);
8963 	}
8964 	return m;
8965 }
8966 
8967 /** Get memory usage of list of primaries for auth xfer */
8968 static size_t
auth_primaries_get_mem(struct auth_master * list)8969 auth_primaries_get_mem(struct auth_master* list)
8970 {
8971 	size_t m = 0;
8972 	struct auth_master* n;
8973 	for(n = list; n; n = n->next) {
8974 		m += sizeof(*n);
8975 		m += auth_addrs_get_mem(n->list);
8976 		if(n->host)
8977 			m += strlen(n->host)+1;
8978 		if(n->file)
8979 			m += strlen(n->file)+1;
8980 	}
8981 	return m;
8982 }
8983 
8984 /** Get memory usage or list of auth chunks */
8985 static size_t
auth_chunks_get_mem(struct auth_chunk * list)8986 auth_chunks_get_mem(struct auth_chunk* list)
8987 {
8988 	size_t m = 0;
8989 	struct auth_chunk* chunk;
8990 	for(chunk = list; chunk; chunk = chunk->next) {
8991 		m += sizeof(*chunk) + chunk->len;
8992 	}
8993 	return m;
8994 }
8995 
8996 /** Get memory usage of auth xfer */
8997 static size_t
auth_xfer_get_mem(struct auth_xfer * xfr)8998 auth_xfer_get_mem(struct auth_xfer* xfr)
8999 {
9000 	size_t m = sizeof(*xfr) + xfr->namelen;
9001 
9002 	/* auth_nextprobe */
9003 	m += comm_timer_get_mem(xfr->task_nextprobe->timer);
9004 
9005 	/* auth_probe */
9006 	m += auth_primaries_get_mem(xfr->task_probe->masters);
9007 	m += comm_point_get_mem(xfr->task_probe->cp);
9008 	m += comm_timer_get_mem(xfr->task_probe->timer);
9009 
9010 	/* auth_transfer */
9011 	m += auth_chunks_get_mem(xfr->task_transfer->chunks_first);
9012 	m += auth_primaries_get_mem(xfr->task_transfer->masters);
9013 	m += comm_point_get_mem(xfr->task_transfer->cp);
9014 	m += comm_timer_get_mem(xfr->task_transfer->timer);
9015 
9016 	/* allow_notify_list */
9017 	m += auth_primaries_get_mem(xfr->allow_notify_list);
9018 
9019 	return m;
9020 }
9021 
9022 /** Get memory usage of auth zones ztree */
9023 static size_t
az_ztree_get_mem(struct auth_zones * az)9024 az_ztree_get_mem(struct auth_zones* az)
9025 {
9026 	size_t m = 0;
9027 	struct auth_zone* z;
9028 	RBTREE_FOR(z, struct auth_zone*, &az->ztree) {
9029 		lock_rw_rdlock(&z->lock);
9030 		m += auth_zone_get_mem(z);
9031 		lock_rw_unlock(&z->lock);
9032 	}
9033 	return m;
9034 }
9035 
9036 /** Get memory usage of auth zones xtree */
9037 static size_t
az_xtree_get_mem(struct auth_zones * az)9038 az_xtree_get_mem(struct auth_zones* az)
9039 {
9040 	size_t m = 0;
9041 	struct auth_xfer* xfr;
9042 	RBTREE_FOR(xfr, struct auth_xfer*, &az->xtree) {
9043 		lock_basic_lock(&xfr->lock);
9044 		m += auth_xfer_get_mem(xfr);
9045 		lock_basic_unlock(&xfr->lock);
9046 	}
9047 	return m;
9048 }
9049 
auth_zones_get_mem(struct auth_zones * zones)9050 size_t auth_zones_get_mem(struct auth_zones* zones)
9051 {
9052 	size_t m;
9053 	if(!zones) return 0;
9054 	m = sizeof(*zones);
9055 	lock_rw_rdlock(&zones->rpz_lock);
9056 	lock_rw_rdlock(&zones->lock);
9057 	m += az_ztree_get_mem(zones);
9058 	m += az_xtree_get_mem(zones);
9059 	lock_rw_unlock(&zones->lock);
9060 	lock_rw_unlock(&zones->rpz_lock);
9061 	return m;
9062 }
9063 
xfr_disown_tasks(struct auth_xfer * xfr,struct worker * worker)9064 void xfr_disown_tasks(struct auth_xfer* xfr, struct worker* worker)
9065 {
9066 	if(xfr->task_nextprobe->worker == worker) {
9067 		xfr_nextprobe_disown(xfr);
9068 	}
9069 	if(xfr->task_probe->worker == worker) {
9070 		xfr_probe_disown(xfr);
9071 	}
9072 	if(xfr->task_transfer->worker == worker) {
9073 		xfr_transfer_disown(xfr);
9074 	}
9075 }
9076