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