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 if(nmlen == z->namelen)
2417 return NULL; /* top of zone reached */
2418 if(ce && nmlen == ce->namelen)
2419 return NULL; /* ce reached */
2420 if(!dname_remove_label_limit_len(&nm, &nmlen, z->namelen))
2421 return NULL; /* can't go up */
2422 }
2423 return node;
2424 }
2425
2426 /** domain is not exact, find first candidate ce (name that matches
2427 * a part of qname) in tree */
2428 static struct auth_data*
az_find_candidate_ce(struct auth_zone * z,struct query_info * qinfo,struct auth_data * n)2429 az_find_candidate_ce(struct auth_zone* z, struct query_info* qinfo,
2430 struct auth_data* n)
2431 {
2432 uint8_t* nm;
2433 size_t nmlen;
2434 if(n) {
2435 nm = dname_get_shared_topdomain(qinfo->qname, n->name);
2436 } else {
2437 nm = qinfo->qname;
2438 }
2439 dname_count_size_labels(nm, &nmlen);
2440 n = az_find_name(z, nm, nmlen);
2441 /* delete labels and go up on name */
2442 while(!n) {
2443 if(!dname_remove_label_limit_len(&nm, &nmlen, z->namelen))
2444 return NULL; /* can't go up */
2445 n = az_find_name(z, nm, nmlen);
2446 }
2447 return n;
2448 }
2449
2450 /** go up the auth tree to next existing name. */
2451 static struct auth_data*
az_domain_go_up(struct auth_zone * z,struct auth_data * n)2452 az_domain_go_up(struct auth_zone* z, struct auth_data* n)
2453 {
2454 uint8_t* nm = n->name;
2455 size_t nmlen = n->namelen;
2456 while(dname_remove_label_limit_len(&nm, &nmlen, z->namelen)) {
2457 if((n=az_find_name(z, nm, nmlen)) != NULL)
2458 return n;
2459 }
2460 return NULL;
2461 }
2462
2463 /** Find the closest encloser, an name that exists and is above the
2464 * qname.
2465 * return true if the node (param node) is existing, nonobscured and
2466 * can be used to generate answers from. It is then also node_exact.
2467 * returns false if the node is not good enough (or it wasn't node_exact)
2468 * in this case the ce can be filled.
2469 * if ce is NULL, no ce exists, and likely the zone is completely empty,
2470 * not even with a zone apex.
2471 * if ce is nonNULL it is the closest enclosing upper name (that exists
2472 * itself for answer purposes). That name may have DNAME, NS or wildcard
2473 * rrset is the closest DNAME or NS rrset that was found.
2474 */
2475 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)2476 az_find_ce(struct auth_zone* z, struct query_info* qinfo,
2477 struct auth_data* node, int node_exact, struct auth_data** ce,
2478 struct auth_rrset** rrset)
2479 {
2480 struct auth_data* n = node;
2481 struct auth_rrset* lookrrset;
2482 *ce = NULL;
2483 *rrset = NULL;
2484 if(!node_exact) {
2485 /* if not exact, lookup closest exact match */
2486 n = az_find_candidate_ce(z, qinfo, n);
2487 } else {
2488 /* if exact, the node itself is the first candidate ce */
2489 *ce = n;
2490 }
2491
2492 /* no direct answer from nsec3-only domains */
2493 if(n && domain_has_only_nsec3(n)) {
2494 node_exact = 0;
2495 *ce = NULL;
2496 }
2497
2498 /* with exact matches, walk up the labels until we find the
2499 * delegation, or DNAME or zone end */
2500 while(n) {
2501 /* see if the current candidate has issues */
2502 /* not zone apex and has type NS */
2503 if(n->namelen != z->namelen &&
2504 (lookrrset=az_domain_rrset(n, LDNS_RR_TYPE_NS)) &&
2505 /* delegate here, but DS at exact the dp has notype */
2506 (qinfo->qtype != LDNS_RR_TYPE_DS ||
2507 n->namelen != qinfo->qname_len)) {
2508 /* referral */
2509 /* this is ce and the lowernode is nonexisting */
2510 *ce = n;
2511 *rrset = lookrrset;
2512 node_exact = 0;
2513 }
2514 /* not equal to qname and has type DNAME */
2515 if(n->namelen != qinfo->qname_len &&
2516 (lookrrset=az_domain_rrset(n, LDNS_RR_TYPE_DNAME))) {
2517 /* this is ce and the lowernode is nonexisting */
2518 *ce = n;
2519 *rrset = lookrrset;
2520 node_exact = 0;
2521 }
2522
2523 if(*ce == NULL && !domain_has_only_nsec3(n)) {
2524 /* if not found yet, this exact name must be
2525 * our lowest match (but not nsec3onlydomain) */
2526 *ce = n;
2527 }
2528
2529 /* walk up the tree by removing labels from name and lookup */
2530 n = az_domain_go_up(z, n);
2531 }
2532 /* found no problems, if it was an exact node, it is fine to use */
2533 return node_exact;
2534 }
2535
2536 /** add additional A/AAAA from domain names in rrset rdata (+offset)
2537 * offset is number of bytes in rdata where the dname is located. */
2538 static int
az_add_additionals_from(struct auth_zone * z,struct regional * region,struct dns_msg * msg,struct auth_rrset * rrset,size_t offset)2539 az_add_additionals_from(struct auth_zone* z, struct regional* region,
2540 struct dns_msg* msg, struct auth_rrset* rrset, size_t offset)
2541 {
2542 struct packed_rrset_data* d = rrset->data;
2543 size_t i;
2544 if(!d) return 0;
2545 for(i=0; i<d->count; i++) {
2546 size_t dlen;
2547 struct auth_data* domain;
2548 struct auth_rrset* ref;
2549 if(d->rr_len[i] < 2+offset)
2550 continue; /* too short */
2551 if(!(dlen = dname_valid(d->rr_data[i]+2+offset,
2552 d->rr_len[i]-2-offset)))
2553 continue; /* malformed */
2554 domain = az_find_name(z, d->rr_data[i]+2+offset, dlen);
2555 if(!domain)
2556 continue;
2557 if((ref=az_domain_rrset(domain, LDNS_RR_TYPE_A)) != NULL) {
2558 if(!msg_add_rrset_ar(z, region, msg, domain, ref))
2559 return 0;
2560 }
2561 if((ref=az_domain_rrset(domain, LDNS_RR_TYPE_AAAA)) != NULL) {
2562 if(!msg_add_rrset_ar(z, region, msg, domain, ref))
2563 return 0;
2564 }
2565 }
2566 return 1;
2567 }
2568
2569 /** add negative SOA record (with negative TTL) */
2570 static int
az_add_negative_soa(struct auth_zone * z,struct regional * region,struct dns_msg * msg)2571 az_add_negative_soa(struct auth_zone* z, struct regional* region,
2572 struct dns_msg* msg)
2573 {
2574 time_t minimum;
2575 size_t i;
2576 struct packed_rrset_data* d;
2577 struct auth_rrset* soa;
2578 struct auth_data* apex = az_find_name(z, z->name, z->namelen);
2579 if(!apex) return 0;
2580 soa = az_domain_rrset(apex, LDNS_RR_TYPE_SOA);
2581 if(!soa) return 0;
2582 /* must be first to put in message; we want to fix the TTL with
2583 * one RRset here, otherwise we'd need to loop over the RRs to get
2584 * the resulting lower TTL */
2585 log_assert(msg->rep->rrset_count == 0);
2586 if(!msg_add_rrset_ns(z, region, msg, apex, soa)) return 0;
2587 /* fixup TTL */
2588 d = (struct packed_rrset_data*)msg->rep->rrsets[msg->rep->rrset_count-1]->entry.data;
2589 /* last 4 bytes are minimum ttl in network format */
2590 if(d->count == 0) return 0;
2591 if(d->rr_len[0] < 2+4) return 0;
2592 minimum = (time_t)sldns_read_uint32(d->rr_data[0]+(d->rr_len[0]-4));
2593 minimum = d->ttl<minimum?d->ttl:minimum;
2594 d->ttl = minimum;
2595 for(i=0; i < d->count + d->rrsig_count; i++)
2596 d->rr_ttl[i] = minimum;
2597 msg->rep->ttl = get_rrset_ttl(msg->rep->rrsets[0]);
2598 msg->rep->prefetch_ttl = PREFETCH_TTL_CALC(msg->rep->ttl);
2599 msg->rep->serve_expired_ttl = msg->rep->ttl + SERVE_EXPIRED_TTL;
2600 return 1;
2601 }
2602
2603 /** See if the query goes to empty nonterminal (that has no auth_data,
2604 * but there are nodes underneath. We already checked that there are
2605 * not NS, or DNAME above, so that we only need to check if some node
2606 * exists below (with nonempty rr list), return true if emptynonterminal */
2607 static int
az_empty_nonterminal(struct auth_zone * z,struct query_info * qinfo,struct auth_data * node)2608 az_empty_nonterminal(struct auth_zone* z, struct query_info* qinfo,
2609 struct auth_data* node)
2610 {
2611 struct auth_data* next;
2612 if(!node) {
2613 /* no smaller was found, use first (smallest) node as the
2614 * next one */
2615 next = (struct auth_data*)rbtree_first(&z->data);
2616 } else {
2617 next = (struct auth_data*)rbtree_next(&node->node);
2618 }
2619 while(next && (rbnode_type*)next != RBTREE_NULL && next->rrsets == NULL) {
2620 /* the next name has empty rrsets, is an empty nonterminal
2621 * itself, see if there exists something below it */
2622 next = (struct auth_data*)rbtree_next(&node->node);
2623 }
2624 if((rbnode_type*)next == RBTREE_NULL || !next) {
2625 /* there is no next node, so something below it cannot
2626 * exist */
2627 return 0;
2628 }
2629 /* a next node exists, if there was something below the query,
2630 * this node has to be it. See if it is below the query name */
2631 if(dname_strict_subdomain_c(next->name, qinfo->qname))
2632 return 1;
2633 return 0;
2634 }
2635
2636 /** create synth cname target name in buffer, or fail if too long */
2637 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)2638 synth_cname_buf(uint8_t* qname, size_t qname_len, size_t dname_len,
2639 uint8_t* dtarg, size_t dtarglen, uint8_t* buf, size_t buflen)
2640 {
2641 size_t newlen = qname_len + dtarglen - dname_len;
2642 if(newlen > buflen) {
2643 /* YXDOMAIN error */
2644 return 0;
2645 }
2646 /* new name is concatenation of qname front (without DNAME owner)
2647 * and DNAME target name */
2648 memcpy(buf, qname, qname_len-dname_len);
2649 memmove(buf+(qname_len-dname_len), dtarg, dtarglen);
2650 return newlen;
2651 }
2652
2653 /** create synthetic CNAME rrset for in a DNAME answer in region,
2654 * false on alloc failure, cname==NULL when name too long. */
2655 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)2656 create_synth_cname(uint8_t* qname, size_t qname_len, struct regional* region,
2657 struct auth_data* node, struct auth_rrset* dname, uint16_t dclass,
2658 struct ub_packed_rrset_key** cname)
2659 {
2660 uint8_t buf[LDNS_MAX_DOMAINLEN];
2661 uint8_t* dtarg;
2662 size_t dtarglen, newlen;
2663 struct packed_rrset_data* d;
2664
2665 /* get DNAME target name */
2666 if(dname->data->count < 1) return 0;
2667 if(dname->data->rr_len[0] < 3) return 0; /* at least rdatalen +1 */
2668 dtarg = dname->data->rr_data[0]+2;
2669 dtarglen = dname->data->rr_len[0]-2;
2670 if(sldns_read_uint16(dname->data->rr_data[0]) != dtarglen)
2671 return 0; /* rdatalen in DNAME rdata is malformed */
2672 if(dname_valid(dtarg, dtarglen) != dtarglen)
2673 return 0; /* DNAME RR has malformed rdata */
2674 if(qname_len == 0)
2675 return 0; /* too short */
2676 if(qname_len <= node->namelen)
2677 return 0; /* qname too short for dname removal */
2678
2679 /* synthesize a CNAME */
2680 newlen = synth_cname_buf(qname, qname_len, node->namelen,
2681 dtarg, dtarglen, buf, sizeof(buf));
2682 if(newlen == 0) {
2683 /* YXDOMAIN error */
2684 *cname = NULL;
2685 return 1;
2686 }
2687 *cname = (struct ub_packed_rrset_key*)regional_alloc(region,
2688 sizeof(struct ub_packed_rrset_key));
2689 if(!*cname)
2690 return 0; /* out of memory */
2691 memset(&(*cname)->entry, 0, sizeof((*cname)->entry));
2692 (*cname)->entry.key = (*cname);
2693 (*cname)->rk.type = htons(LDNS_RR_TYPE_CNAME);
2694 (*cname)->rk.rrset_class = htons(dclass);
2695 (*cname)->rk.flags = 0;
2696 (*cname)->rk.dname = regional_alloc_init(region, qname, qname_len);
2697 if(!(*cname)->rk.dname)
2698 return 0; /* out of memory */
2699 (*cname)->rk.dname_len = qname_len;
2700 (*cname)->entry.hash = rrset_key_hash(&(*cname)->rk);
2701 d = (struct packed_rrset_data*)regional_alloc_zero(region,
2702 sizeof(struct packed_rrset_data) + sizeof(size_t) +
2703 sizeof(uint8_t*) + sizeof(time_t) + sizeof(uint16_t)
2704 + newlen);
2705 if(!d)
2706 return 0; /* out of memory */
2707 (*cname)->entry.data = d;
2708 d->ttl = dname->data->ttl; /* RFC6672: synth CNAME TTL == DNAME TTL */
2709 d->count = 1;
2710 d->rrsig_count = 0;
2711 d->trust = rrset_trust_ans_noAA;
2712 d->rr_len = (size_t*)((uint8_t*)d +
2713 sizeof(struct packed_rrset_data));
2714 d->rr_len[0] = newlen + sizeof(uint16_t);
2715 packed_rrset_ptr_fixup(d);
2716 d->rr_ttl[0] = d->ttl;
2717 sldns_write_uint16(d->rr_data[0], newlen);
2718 memmove(d->rr_data[0] + sizeof(uint16_t), buf, newlen);
2719 return 1;
2720 }
2721
2722 /** add a synthesized CNAME to the answer section */
2723 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)2724 add_synth_cname(struct auth_zone* z, uint8_t* qname, size_t qname_len,
2725 struct regional* region, struct dns_msg* msg, struct auth_data* dname,
2726 struct auth_rrset* rrset)
2727 {
2728 struct ub_packed_rrset_key* cname;
2729 /* synthesize a CNAME */
2730 if(!create_synth_cname(qname, qname_len, region, dname, rrset,
2731 z->dclass, &cname)) {
2732 /* out of memory */
2733 return 0;
2734 }
2735 if(!cname) {
2736 /* cname cannot be create because of YXDOMAIN */
2737 msg->rep->flags |= LDNS_RCODE_YXDOMAIN;
2738 return 1;
2739 }
2740 /* add cname to message */
2741 if(!msg_grow_array(region, msg))
2742 return 0;
2743 msg->rep->rrsets[msg->rep->rrset_count] = cname;
2744 msg->rep->rrset_count++;
2745 msg->rep->an_numrrsets++;
2746 msg_ttl(msg);
2747 return 1;
2748 }
2749
2750 /** Change a dname to a different one, for wildcard namechange */
2751 static void
az_change_dnames(struct dns_msg * msg,uint8_t * oldname,uint8_t * newname,size_t newlen,int an_only)2752 az_change_dnames(struct dns_msg* msg, uint8_t* oldname, uint8_t* newname,
2753 size_t newlen, int an_only)
2754 {
2755 size_t i;
2756 size_t start = 0, end = msg->rep->rrset_count;
2757 if(!an_only) start = msg->rep->an_numrrsets;
2758 if(an_only) end = msg->rep->an_numrrsets;
2759 for(i=start; i<end; i++) {
2760 /* allocated in region so we can change the ptrs */
2761 if(query_dname_compare(msg->rep->rrsets[i]->rk.dname, oldname)
2762 == 0) {
2763 msg->rep->rrsets[i]->rk.dname = newname;
2764 msg->rep->rrsets[i]->rk.dname_len = newlen;
2765 msg->rep->rrsets[i]->entry.hash = rrset_key_hash(&msg->rep->rrsets[i]->rk);
2766 }
2767 }
2768 }
2769
2770 /** find NSEC record covering the query, with the given node in the zone */
2771 static struct auth_rrset*
az_find_nsec_cover(struct auth_zone * z,struct auth_data ** node)2772 az_find_nsec_cover(struct auth_zone* z, struct auth_data** node)
2773 {
2774 uint8_t* nm;
2775 size_t nmlen;
2776 struct auth_rrset* rrset;
2777 log_assert(*node); /* we already have a node when calling this */
2778 nm = (*node)->name;
2779 nmlen = (*node)->namelen;
2780 /* find the NSEC for the smallest-or-equal node */
2781 /* But there could be glue, and then it has no NSEC.
2782 * Go up to find nonglue (previous) NSEC-holding nodes */
2783 while((rrset=az_domain_rrset(*node, LDNS_RR_TYPE_NSEC)) == NULL) {
2784 if(nmlen == z->namelen) return NULL;
2785 if(!dname_remove_label_limit_len(&nm, &nmlen, z->namelen))
2786 return NULL; /* can't go up */
2787 /* adjust *node for the nsec rrset to find in */
2788 *node = az_find_name(z, nm, nmlen);
2789 }
2790 return rrset;
2791 }
2792
2793 /** Find NSEC and add for wildcard denial */
2794 static int
az_nsec_wildcard_denial(struct auth_zone * z,struct regional * region,struct dns_msg * msg,uint8_t * cenm,size_t cenmlen)2795 az_nsec_wildcard_denial(struct auth_zone* z, struct regional* region,
2796 struct dns_msg* msg, uint8_t* cenm, size_t cenmlen)
2797 {
2798 struct query_info qinfo;
2799 int node_exact;
2800 struct auth_data* node;
2801 struct auth_rrset* nsec;
2802 uint8_t wc[LDNS_MAX_DOMAINLEN];
2803 if(cenmlen+2 > sizeof(wc))
2804 return 0; /* result would be too long */
2805 wc[0] = 1; /* length of wildcard label */
2806 wc[1] = (uint8_t)'*'; /* wildcard label */
2807 memmove(wc+2, cenm, cenmlen);
2808
2809 /* we have '*.ce' in wc wildcard name buffer */
2810 /* get nsec cover for that */
2811 qinfo.qname = wc;
2812 qinfo.qname_len = cenmlen+2;
2813 qinfo.qtype = 0;
2814 qinfo.qclass = 0;
2815 az_find_domain(z, &qinfo, &node_exact, &node);
2816 if((nsec=az_find_nsec_cover(z, &node)) != NULL) {
2817 if(!msg_add_rrset_ns(z, region, msg, node, nsec)) return 0;
2818 }
2819 return 1;
2820 }
2821
2822 /** Find the NSEC3PARAM rrset (if any) and if true you have the parameters */
2823 static int
az_nsec3_param(struct auth_zone * z,int * algo,size_t * iter,uint8_t ** salt,size_t * saltlen)2824 az_nsec3_param(struct auth_zone* z, int* algo, size_t* iter, uint8_t** salt,
2825 size_t* saltlen)
2826 {
2827 struct auth_data* apex;
2828 struct auth_rrset* param;
2829 size_t i;
2830 apex = az_find_name(z, z->name, z->namelen);
2831 if(!apex) return 0;
2832 param = az_domain_rrset(apex, LDNS_RR_TYPE_NSEC3PARAM);
2833 if(!param || param->data->count==0)
2834 return 0; /* no RRset or no RRs in rrset */
2835 /* find out which NSEC3PARAM RR has supported parameters */
2836 /* skip unknown flags (dynamic signer is recalculating nsec3 chain) */
2837 for(i=0; i<param->data->count; i++) {
2838 uint8_t* rdata = param->data->rr_data[i]+2;
2839 size_t rdatalen = param->data->rr_len[i];
2840 if(rdatalen < 2+5)
2841 continue; /* too short */
2842 if(!nsec3_hash_algo_size_supported((int)(rdata[0])))
2843 continue; /* unsupported algo */
2844 if(rdatalen < (size_t)(2+5+(size_t)rdata[4]))
2845 continue; /* salt missing */
2846 if((rdata[1]&NSEC3_UNKNOWN_FLAGS)!=0)
2847 continue; /* unknown flags */
2848 *algo = (int)(rdata[0]);
2849 *iter = sldns_read_uint16(rdata+2);
2850 *saltlen = rdata[4];
2851 if(*saltlen == 0)
2852 *salt = NULL;
2853 else *salt = rdata+5;
2854 return 1;
2855 }
2856 /* no supported params */
2857 return 0;
2858 }
2859
2860 /** Hash a name with nsec3param into buffer, it has zone name appended.
2861 * return length of hash */
2862 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)2863 az_nsec3_hash(uint8_t* buf, size_t buflen, uint8_t* nm, size_t nmlen,
2864 int algo, size_t iter, uint8_t* salt, size_t saltlen)
2865 {
2866 size_t hlen = nsec3_hash_algo_size_supported(algo);
2867 /* buffer has domain name, nsec3hash, and 256 is for max saltlen
2868 * (salt has 0-255 length) */
2869 unsigned char p[LDNS_MAX_DOMAINLEN+1+N3HASHBUFLEN+256];
2870 size_t i;
2871 if(nmlen+saltlen > sizeof(p) || hlen+saltlen > sizeof(p))
2872 return 0;
2873 if(hlen > buflen)
2874 return 0; /* somehow too large for destination buffer */
2875 /* hashfunc(name, salt) */
2876 memmove(p, nm, nmlen);
2877 query_dname_tolower(p);
2878 if(salt && saltlen > 0)
2879 memmove(p+nmlen, salt, saltlen);
2880 (void)secalgo_nsec3_hash(algo, p, nmlen+saltlen, (unsigned char*)buf);
2881 for(i=0; i<iter; i++) {
2882 /* hashfunc(hash, salt) */
2883 memmove(p, buf, hlen);
2884 if(salt && saltlen > 0)
2885 memmove(p+hlen, salt, saltlen);
2886 (void)secalgo_nsec3_hash(algo, p, hlen+saltlen,
2887 (unsigned char*)buf);
2888 }
2889 return hlen;
2890 }
2891
2892 /** Hash name and return b32encoded hashname for lookup, zone name appended */
2893 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)2894 az_nsec3_hashname(struct auth_zone* z, uint8_t* hashname, size_t* hashnmlen,
2895 uint8_t* nm, size_t nmlen, int algo, size_t iter, uint8_t* salt,
2896 size_t saltlen)
2897 {
2898 uint8_t hash[N3HASHBUFLEN];
2899 size_t hlen;
2900 int ret;
2901 hlen = az_nsec3_hash(hash, sizeof(hash), nm, nmlen, algo, iter,
2902 salt, saltlen);
2903 if(!hlen) return 0;
2904 /* b32 encode */
2905 if(*hashnmlen < hlen*2+1+z->namelen) /* approx b32 as hexb16 */
2906 return 0;
2907 ret = sldns_b32_ntop_extended_hex(hash, hlen, (char*)(hashname+1),
2908 (*hashnmlen)-1);
2909 if(ret<1)
2910 return 0;
2911 hashname[0] = (uint8_t)ret;
2912 ret++;
2913 if((*hashnmlen) - ret < z->namelen)
2914 return 0;
2915 memmove(hashname+ret, z->name, z->namelen);
2916 *hashnmlen = z->namelen+(size_t)ret;
2917 return 1;
2918 }
2919
2920 /** Find the datanode that covers the nsec3hash-name */
2921 static struct auth_data*
az_nsec3_findnode(struct auth_zone * z,uint8_t * hashnm,size_t hashnmlen)2922 az_nsec3_findnode(struct auth_zone* z, uint8_t* hashnm, size_t hashnmlen)
2923 {
2924 struct query_info qinfo;
2925 struct auth_data* node;
2926 int node_exact;
2927 qinfo.qclass = 0;
2928 qinfo.qtype = 0;
2929 qinfo.qname = hashnm;
2930 qinfo.qname_len = hashnmlen;
2931 /* because canonical ordering and b32 nsec3 ordering are the same.
2932 * this is a good lookup to find the nsec3 name. */
2933 az_find_domain(z, &qinfo, &node_exact, &node);
2934 /* but we may have to skip non-nsec3 nodes */
2935 /* this may be a lot, the way to speed that up is to have a
2936 * separate nsec3 tree with nsec3 nodes */
2937 while(node && (rbnode_type*)node != RBTREE_NULL &&
2938 !az_domain_rrset(node, LDNS_RR_TYPE_NSEC3)) {
2939 node = (struct auth_data*)rbtree_previous(&node->node);
2940 }
2941 if((rbnode_type*)node == RBTREE_NULL)
2942 node = NULL;
2943 return node;
2944 }
2945
2946 /** Find cover for hashed(nm, nmlen) (or NULL) */
2947 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)2948 az_nsec3_find_cover(struct auth_zone* z, uint8_t* nm, size_t nmlen,
2949 int algo, size_t iter, uint8_t* salt, size_t saltlen)
2950 {
2951 struct auth_data* node;
2952 uint8_t hname[LDNS_MAX_DOMAINLEN];
2953 size_t hlen = sizeof(hname);
2954 if(!az_nsec3_hashname(z, hname, &hlen, nm, nmlen, algo, iter,
2955 salt, saltlen))
2956 return NULL;
2957 node = az_nsec3_findnode(z, hname, hlen);
2958 if(node)
2959 return node;
2960 /* we did not find any, perhaps because the NSEC3 hash is before
2961 * the first hash, we have to find the 'last hash' in the zone */
2962 node = (struct auth_data*)rbtree_last(&z->data);
2963 while(node && (rbnode_type*)node != RBTREE_NULL &&
2964 !az_domain_rrset(node, LDNS_RR_TYPE_NSEC3)) {
2965 node = (struct auth_data*)rbtree_previous(&node->node);
2966 }
2967 if((rbnode_type*)node == RBTREE_NULL)
2968 node = NULL;
2969 return node;
2970 }
2971
2972 /** Find exact match for hashed(nm, nmlen) NSEC3 record or NULL */
2973 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)2974 az_nsec3_find_exact(struct auth_zone* z, uint8_t* nm, size_t nmlen,
2975 int algo, size_t iter, uint8_t* salt, size_t saltlen)
2976 {
2977 struct auth_data* node;
2978 uint8_t hname[LDNS_MAX_DOMAINLEN];
2979 size_t hlen = sizeof(hname);
2980 if(!az_nsec3_hashname(z, hname, &hlen, nm, nmlen, algo, iter,
2981 salt, saltlen))
2982 return NULL;
2983 node = az_find_name(z, hname, hlen);
2984 if(az_domain_rrset(node, LDNS_RR_TYPE_NSEC3))
2985 return node;
2986 return NULL;
2987 }
2988
2989 /** Return nextcloser name (as a ref into the qname). This is one label
2990 * more than the cenm (cename must be a suffix of qname) */
2991 static void
az_nsec3_get_nextcloser(uint8_t * cenm,uint8_t * qname,size_t qname_len,uint8_t ** nx,size_t * nxlen)2992 az_nsec3_get_nextcloser(uint8_t* cenm, uint8_t* qname, size_t qname_len,
2993 uint8_t** nx, size_t* nxlen)
2994 {
2995 int celabs = dname_count_labels(cenm);
2996 int qlabs = dname_count_labels(qname);
2997 int strip = qlabs - celabs -1;
2998 log_assert(dname_strict_subdomain(qname, qlabs, cenm, celabs));
2999 *nx = qname;
3000 *nxlen = qname_len;
3001 if(strip>0)
3002 dname_remove_labels(nx, nxlen, strip);
3003 }
3004
3005 /** Find the closest encloser that has exact NSEC3.
3006 * updated cenm to the new name. If it went up no-exact-ce is true. */
3007 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)3008 az_nsec3_find_ce(struct auth_zone* z, uint8_t** cenm, size_t* cenmlen,
3009 int* no_exact_ce, int algo, size_t iter, uint8_t* salt, size_t saltlen)
3010 {
3011 struct auth_data* node;
3012 while((node = az_nsec3_find_exact(z, *cenm, *cenmlen,
3013 algo, iter, salt, saltlen)) == NULL) {
3014 if(!dname_remove_label_limit_len(cenm, cenmlen, z->namelen))
3015 return NULL; /* can't go up */
3016 *no_exact_ce = 1;
3017 }
3018 return node;
3019 }
3020
3021 /* Insert NSEC3 record in authority section, if NULL does nothing */
3022 static int
az_nsec3_insert(struct auth_zone * z,struct regional * region,struct dns_msg * msg,struct auth_data * node)3023 az_nsec3_insert(struct auth_zone* z, struct regional* region,
3024 struct dns_msg* msg, struct auth_data* node)
3025 {
3026 struct auth_rrset* nsec3;
3027 if(!node) return 1; /* no node, skip this */
3028 nsec3 = az_domain_rrset(node, LDNS_RR_TYPE_NSEC3);
3029 if(!nsec3) return 1; /* if no nsec3 RR, skip it */
3030 if(!msg_add_rrset_ns(z, region, msg, node, nsec3)) return 0;
3031 return 1;
3032 }
3033
3034 /** add NSEC3 records to the zone for the nsec3 proof.
3035 * Specify with the flags with parts of the proof are required.
3036 * the ce is the exact matching name (for notype) but also delegation points.
3037 * qname is the one where the nextcloser name can be derived from.
3038 * If NSEC3 is not properly there (in the zone) nothing is added.
3039 * always enabled: include nsec3 proving about the Closest Encloser.
3040 * that is an exact match that should exist for it.
3041 * If that does not exist, a higher exact match + nxproof is enabled
3042 * (for some sort of opt-out empty nonterminal cases).
3043 * nodataproof: search for exact match and include that instead.
3044 * ceproof: include ce proof NSEC3 (omitted for wildcard replies).
3045 * nxproof: include denial of the qname.
3046 * wcproof: include denial of wildcard (wildcard.ce).
3047 */
3048 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)3049 az_add_nsec3_proof(struct auth_zone* z, struct regional* region,
3050 struct dns_msg* msg, uint8_t* cenm, size_t cenmlen, uint8_t* qname,
3051 size_t qname_len, int nodataproof, int ceproof, int nxproof,
3052 int wcproof)
3053 {
3054 int algo;
3055 size_t iter, saltlen;
3056 uint8_t* salt;
3057 int no_exact_ce = 0;
3058 struct auth_data* node;
3059
3060 /* find parameters of nsec3 proof */
3061 if(!az_nsec3_param(z, &algo, &iter, &salt, &saltlen))
3062 return 1; /* no nsec3 */
3063 if(nodataproof) {
3064 /* see if the node has a hash of itself for the nodata
3065 * proof nsec3, this has to be an exact match nsec3. */
3066 struct auth_data* match;
3067 match = az_nsec3_find_exact(z, qname, qname_len, algo,
3068 iter, salt, saltlen);
3069 if(match) {
3070 if(!az_nsec3_insert(z, region, msg, match))
3071 return 0;
3072 /* only nodata NSEC3 needed, no CE or others. */
3073 return 1;
3074 }
3075 }
3076 /* find ce that has an NSEC3 */
3077 if(ceproof) {
3078 node = az_nsec3_find_ce(z, &cenm, &cenmlen, &no_exact_ce,
3079 algo, iter, salt, saltlen);
3080 if(no_exact_ce) nxproof = 1;
3081 if(!az_nsec3_insert(z, region, msg, node))
3082 return 0;
3083 }
3084
3085 if(nxproof) {
3086 uint8_t* nx;
3087 size_t nxlen;
3088 /* create nextcloser domain name */
3089 az_nsec3_get_nextcloser(cenm, qname, qname_len, &nx, &nxlen);
3090 /* find nsec3 that matches or covers it */
3091 node = az_nsec3_find_cover(z, nx, nxlen, algo, iter, salt,
3092 saltlen);
3093 if(!az_nsec3_insert(z, region, msg, node))
3094 return 0;
3095 }
3096 if(wcproof) {
3097 /* create wildcard name *.ce */
3098 uint8_t wc[LDNS_MAX_DOMAINLEN];
3099 size_t wclen;
3100 if(cenmlen+2 > sizeof(wc))
3101 return 0; /* result would be too long */
3102 wc[0] = 1; /* length of wildcard label */
3103 wc[1] = (uint8_t)'*'; /* wildcard label */
3104 memmove(wc+2, cenm, cenmlen);
3105 wclen = cenmlen+2;
3106 /* find nsec3 that matches or covers it */
3107 node = az_nsec3_find_cover(z, wc, wclen, algo, iter, salt,
3108 saltlen);
3109 if(!az_nsec3_insert(z, region, msg, node))
3110 return 0;
3111 }
3112 return 1;
3113 }
3114
3115 /** generate answer for positive answer */
3116 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)3117 az_generate_positive_answer(struct auth_zone* z, struct regional* region,
3118 struct dns_msg* msg, struct auth_data* node, struct auth_rrset* rrset)
3119 {
3120 if(!msg_add_rrset_an(z, region, msg, node, rrset)) return 0;
3121 /* see if we want additional rrs */
3122 if(rrset->type == LDNS_RR_TYPE_MX) {
3123 if(!az_add_additionals_from(z, region, msg, rrset, 2))
3124 return 0;
3125 } else if(rrset->type == LDNS_RR_TYPE_SRV) {
3126 if(!az_add_additionals_from(z, region, msg, rrset, 6))
3127 return 0;
3128 } else if(rrset->type == LDNS_RR_TYPE_NS) {
3129 if(!az_add_additionals_from(z, region, msg, rrset, 0))
3130 return 0;
3131 }
3132 return 1;
3133 }
3134
3135 /** generate answer for type ANY answer */
3136 static int
az_generate_any_answer(struct auth_zone * z,struct regional * region,struct dns_msg * msg,struct auth_data * node)3137 az_generate_any_answer(struct auth_zone* z, struct regional* region,
3138 struct dns_msg* msg, struct auth_data* node)
3139 {
3140 struct auth_rrset* rrset;
3141 int added = 0;
3142 /* add a couple (at least one) RRs */
3143 if((rrset=az_domain_rrset(node, LDNS_RR_TYPE_SOA)) != NULL) {
3144 if(!msg_add_rrset_an(z, region, msg, node, rrset)) return 0;
3145 added++;
3146 }
3147 if((rrset=az_domain_rrset(node, LDNS_RR_TYPE_MX)) != NULL) {
3148 if(!msg_add_rrset_an(z, region, msg, node, rrset)) return 0;
3149 added++;
3150 }
3151 if((rrset=az_domain_rrset(node, LDNS_RR_TYPE_A)) != NULL) {
3152 if(!msg_add_rrset_an(z, region, msg, node, rrset)) return 0;
3153 added++;
3154 }
3155 if((rrset=az_domain_rrset(node, LDNS_RR_TYPE_AAAA)) != NULL) {
3156 if(!msg_add_rrset_an(z, region, msg, node, rrset)) return 0;
3157 added++;
3158 }
3159 if(added == 0 && node && node->rrsets) {
3160 if(!msg_add_rrset_an(z, region, msg, node,
3161 node->rrsets)) return 0;
3162 }
3163 return 1;
3164 }
3165
3166 /** follow cname chain and add more data to the answer section */
3167 static int
follow_cname_chain(struct auth_zone * z,uint16_t qtype,struct regional * region,struct dns_msg * msg,struct packed_rrset_data * d)3168 follow_cname_chain(struct auth_zone* z, uint16_t qtype,
3169 struct regional* region, struct dns_msg* msg,
3170 struct packed_rrset_data* d)
3171 {
3172 int maxchain = 0;
3173 /* see if we can add the target of the CNAME into the answer */
3174 while(maxchain++ < MAX_CNAME_CHAIN) {
3175 struct auth_data* node;
3176 struct auth_rrset* rrset;
3177 size_t clen;
3178 /* d has cname rdata */
3179 if(d->count == 0) break; /* no CNAME */
3180 if(d->rr_len[0] < 2+1) break; /* too small */
3181 if((clen=dname_valid(d->rr_data[0]+2, d->rr_len[0]-2))==0)
3182 break; /* malformed */
3183 if(!dname_subdomain_c(d->rr_data[0]+2, z->name))
3184 break; /* target out of zone */
3185 if((node = az_find_name(z, d->rr_data[0]+2, clen))==NULL)
3186 break; /* no such target name */
3187 if((rrset=az_domain_rrset(node, qtype))!=NULL) {
3188 /* done we found the target */
3189 if(!msg_add_rrset_an(z, region, msg, node, rrset))
3190 return 0;
3191 break;
3192 }
3193 if((rrset=az_domain_rrset(node, LDNS_RR_TYPE_CNAME))==NULL)
3194 break; /* no further CNAME chain, notype */
3195 if(!msg_add_rrset_an(z, region, msg, node, rrset)) return 0;
3196 d = rrset->data;
3197 }
3198 return 1;
3199 }
3200
3201 /** generate answer for cname answer */
3202 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)3203 az_generate_cname_answer(struct auth_zone* z, struct query_info* qinfo,
3204 struct regional* region, struct dns_msg* msg,
3205 struct auth_data* node, struct auth_rrset* rrset)
3206 {
3207 if(!msg_add_rrset_an(z, region, msg, node, rrset)) return 0;
3208 if(!rrset) return 1;
3209 if(!follow_cname_chain(z, qinfo->qtype, region, msg, rrset->data))
3210 return 0;
3211 return 1;
3212 }
3213
3214 /** generate answer for notype answer */
3215 static int
az_generate_notype_answer(struct auth_zone * z,struct regional * region,struct dns_msg * msg,struct auth_data * node)3216 az_generate_notype_answer(struct auth_zone* z, struct regional* region,
3217 struct dns_msg* msg, struct auth_data* node)
3218 {
3219 struct auth_rrset* rrset;
3220 if(!az_add_negative_soa(z, region, msg)) return 0;
3221 /* DNSSEC denial NSEC */
3222 if((rrset=az_domain_rrset(node, LDNS_RR_TYPE_NSEC))!=NULL) {
3223 if(!msg_add_rrset_ns(z, region, msg, node, rrset)) return 0;
3224 } else if(node) {
3225 /* DNSSEC denial NSEC3 */
3226 if(!az_add_nsec3_proof(z, region, msg, node->name,
3227 node->namelen, msg->qinfo.qname,
3228 msg->qinfo.qname_len, 1, 1, 0, 0))
3229 return 0;
3230 }
3231 return 1;
3232 }
3233
3234 /** generate answer for referral answer */
3235 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)3236 az_generate_referral_answer(struct auth_zone* z, struct regional* region,
3237 struct dns_msg* msg, struct auth_data* ce, struct auth_rrset* rrset)
3238 {
3239 struct auth_rrset* ds, *nsec;
3240 /* turn off AA flag, referral is nonAA because it leaves the zone */
3241 log_assert(ce);
3242 msg->rep->flags &= ~BIT_AA;
3243 if(!msg_add_rrset_ns(z, region, msg, ce, rrset)) return 0;
3244 /* add DS or deny it */
3245 if((ds=az_domain_rrset(ce, LDNS_RR_TYPE_DS))!=NULL) {
3246 if(!msg_add_rrset_ns(z, region, msg, ce, ds)) return 0;
3247 } else {
3248 /* deny the DS */
3249 if((nsec=az_domain_rrset(ce, LDNS_RR_TYPE_NSEC))!=NULL) {
3250 if(!msg_add_rrset_ns(z, region, msg, ce, nsec))
3251 return 0;
3252 } else {
3253 if(!az_add_nsec3_proof(z, region, msg, ce->name,
3254 ce->namelen, msg->qinfo.qname,
3255 msg->qinfo.qname_len, 1, 1, 0, 0))
3256 return 0;
3257 }
3258 }
3259 /* add additional rrs for type NS */
3260 if(!az_add_additionals_from(z, region, msg, rrset, 0)) return 0;
3261 return 1;
3262 }
3263
3264 /** generate answer for DNAME answer */
3265 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)3266 az_generate_dname_answer(struct auth_zone* z, struct query_info* qinfo,
3267 struct regional* region, struct dns_msg* msg, struct auth_data* ce,
3268 struct auth_rrset* rrset)
3269 {
3270 log_assert(ce);
3271 /* add the DNAME and then a CNAME */
3272 if(!msg_add_rrset_an(z, region, msg, ce, rrset)) return 0;
3273 if(!add_synth_cname(z, qinfo->qname, qinfo->qname_len, region,
3274 msg, ce, rrset)) return 0;
3275 if(FLAGS_GET_RCODE(msg->rep->flags) == LDNS_RCODE_YXDOMAIN)
3276 return 1;
3277 if(msg->rep->rrset_count == 0 ||
3278 !msg->rep->rrsets[msg->rep->rrset_count-1])
3279 return 0;
3280 if(!follow_cname_chain(z, qinfo->qtype, region, msg,
3281 (struct packed_rrset_data*)msg->rep->rrsets[
3282 msg->rep->rrset_count-1]->entry.data))
3283 return 0;
3284 return 1;
3285 }
3286
3287 /** generate answer for wildcard answer */
3288 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)3289 az_generate_wildcard_answer(struct auth_zone* z, struct query_info* qinfo,
3290 struct regional* region, struct dns_msg* msg, struct auth_data* ce,
3291 struct auth_data* wildcard, struct auth_data* node)
3292 {
3293 struct auth_rrset* rrset, *nsec;
3294 int insert_ce = 0;
3295 if((rrset=az_domain_rrset(wildcard, qinfo->qtype)) != NULL) {
3296 /* wildcard has type, add it */
3297 if(!msg_add_rrset_an(z, region, msg, wildcard, rrset))
3298 return 0;
3299 az_change_dnames(msg, wildcard->name, msg->qinfo.qname,
3300 msg->qinfo.qname_len, 1);
3301 } else if((rrset=az_domain_rrset(wildcard, LDNS_RR_TYPE_CNAME))!=NULL) {
3302 /* wildcard has cname instead, do that */
3303 if(!msg_add_rrset_an(z, region, msg, wildcard, rrset))
3304 return 0;
3305 az_change_dnames(msg, wildcard->name, msg->qinfo.qname,
3306 msg->qinfo.qname_len, 1);
3307 if(!follow_cname_chain(z, qinfo->qtype, region, msg,
3308 rrset->data))
3309 return 0;
3310 } else if(qinfo->qtype == LDNS_RR_TYPE_ANY && wildcard->rrsets) {
3311 /* add ANY rrsets from wildcard node */
3312 if(!az_generate_any_answer(z, region, msg, wildcard))
3313 return 0;
3314 az_change_dnames(msg, wildcard->name, msg->qinfo.qname,
3315 msg->qinfo.qname_len, 1);
3316 } else {
3317 /* wildcard has nodata, notype answer */
3318 /* call other notype routine for dnssec notype denials */
3319 if(!az_generate_notype_answer(z, region, msg, wildcard))
3320 return 0;
3321 /* because the notype, there is no positive data with an
3322 * RRSIG that indicates the wildcard position. Thus the
3323 * wildcard qname denial needs to have a CE nsec3. */
3324 insert_ce = 1;
3325 }
3326
3327 /* ce and node for dnssec denial of wildcard original name */
3328 if((nsec=az_find_nsec_cover(z, &node)) != NULL) {
3329 if(!msg_add_rrset_ns(z, region, msg, node, nsec)) return 0;
3330 } else if(ce) {
3331 uint8_t* wildup = wildcard->name;
3332 size_t wilduplen= wildcard->namelen;
3333 if(!dname_remove_label_limit_len(&wildup, &wilduplen, z->namelen))
3334 return 0; /* can't go up */
3335 if(!az_add_nsec3_proof(z, region, msg, wildup,
3336 wilduplen, msg->qinfo.qname,
3337 msg->qinfo.qname_len, 0, insert_ce, 1, 0))
3338 return 0;
3339 }
3340
3341 /* fixup name of wildcard from *.zone to qname, use already allocated
3342 * pointer to msg qname */
3343 az_change_dnames(msg, wildcard->name, msg->qinfo.qname,
3344 msg->qinfo.qname_len, 0);
3345 return 1;
3346 }
3347
3348 /** generate answer for nxdomain answer */
3349 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)3350 az_generate_nxdomain_answer(struct auth_zone* z, struct regional* region,
3351 struct dns_msg* msg, struct auth_data* ce, struct auth_data* node)
3352 {
3353 struct auth_rrset* nsec;
3354 msg->rep->flags |= LDNS_RCODE_NXDOMAIN;
3355 if(!az_add_negative_soa(z, region, msg)) return 0;
3356 if((nsec=az_find_nsec_cover(z, &node)) != NULL) {
3357 if(!msg_add_rrset_ns(z, region, msg, node, nsec)) return 0;
3358 if(ce && !az_nsec_wildcard_denial(z, region, msg, ce->name,
3359 ce->namelen)) return 0;
3360 } else if(ce) {
3361 if(!az_add_nsec3_proof(z, region, msg, ce->name,
3362 ce->namelen, msg->qinfo.qname,
3363 msg->qinfo.qname_len, 0, 1, 1, 1))
3364 return 0;
3365 }
3366 return 1;
3367 }
3368
3369 /** Create answers when an exact match exists for the domain name */
3370 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)3371 az_generate_answer_with_node(struct auth_zone* z, struct query_info* qinfo,
3372 struct regional* region, struct dns_msg* msg, struct auth_data* node)
3373 {
3374 struct auth_rrset* rrset;
3375 /* positive answer, rrset we are looking for exists */
3376 if((rrset=az_domain_rrset(node, qinfo->qtype)) != NULL) {
3377 return az_generate_positive_answer(z, region, msg, node, rrset);
3378 }
3379 /* CNAME? */
3380 if((rrset=az_domain_rrset(node, LDNS_RR_TYPE_CNAME)) != NULL) {
3381 return az_generate_cname_answer(z, qinfo, region, msg,
3382 node, rrset);
3383 }
3384 /* type ANY ? */
3385 if(qinfo->qtype == LDNS_RR_TYPE_ANY) {
3386 return az_generate_any_answer(z, region, msg, node);
3387 }
3388 /* NOERROR/NODATA (no such type at domain name) */
3389 return az_generate_notype_answer(z, region, msg, node);
3390 }
3391
3392 /** Generate answer without an existing-node that we can use.
3393 * So it'll be a referral, DNAME, notype, wildcard or nxdomain */
3394 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)3395 az_generate_answer_nonexistnode(struct auth_zone* z, struct query_info* qinfo,
3396 struct regional* region, struct dns_msg* msg, struct auth_data* ce,
3397 struct auth_rrset* rrset, struct auth_data* node)
3398 {
3399 struct auth_data* wildcard;
3400
3401 /* we do not have an exact matching name (that exists) */
3402 /* see if we have a NS or DNAME in the ce */
3403 if(ce && rrset && rrset->type == LDNS_RR_TYPE_NS) {
3404 return az_generate_referral_answer(z, region, msg, ce, rrset);
3405 }
3406 if(ce && rrset && rrset->type == LDNS_RR_TYPE_DNAME) {
3407 return az_generate_dname_answer(z, qinfo, region, msg, ce,
3408 rrset);
3409 }
3410 /* if there is an empty nonterminal, wildcard and nxdomain don't
3411 * happen, it is a notype answer */
3412 if(az_empty_nonterminal(z, qinfo, node)) {
3413 return az_generate_notype_answer(z, region, msg, node);
3414 }
3415 /* see if we have a wildcard under the ce */
3416 if((wildcard=az_find_wildcard(z, qinfo, ce)) != NULL) {
3417 return az_generate_wildcard_answer(z, qinfo, region, msg,
3418 ce, wildcard, node);
3419 }
3420 /* generate nxdomain answer */
3421 return az_generate_nxdomain_answer(z, region, msg, ce, node);
3422 }
3423
3424 /** Lookup answer in a zone. */
3425 static int
auth_zone_generate_answer(struct auth_zone * z,struct query_info * qinfo,struct regional * region,struct dns_msg ** msg,int * fallback)3426 auth_zone_generate_answer(struct auth_zone* z, struct query_info* qinfo,
3427 struct regional* region, struct dns_msg** msg, int* fallback)
3428 {
3429 struct auth_data* node, *ce;
3430 struct auth_rrset* rrset;
3431 int node_exact, node_exists;
3432 /* does the zone want fallback in case of failure? */
3433 *fallback = z->fallback_enabled;
3434 if(!(*msg=msg_create(region, qinfo))) return 0;
3435
3436 /* lookup if there is a matching domain name for the query */
3437 az_find_domain(z, qinfo, &node_exact, &node);
3438
3439 /* see if node exists for generating answers from (i.e. not glue and
3440 * obscured by NS or DNAME or NSEC3-only), and also return the
3441 * closest-encloser from that, closest node that should be used
3442 * to generate answers from that is above the query */
3443 node_exists = az_find_ce(z, qinfo, node, node_exact, &ce, &rrset);
3444
3445 if(verbosity >= VERB_ALGO) {
3446 char zname[256], qname[256], nname[256], cename[256],
3447 tpstr[32], rrstr[32];
3448 sldns_wire2str_dname_buf(qinfo->qname, qinfo->qname_len, qname,
3449 sizeof(qname));
3450 sldns_wire2str_type_buf(qinfo->qtype, tpstr, sizeof(tpstr));
3451 sldns_wire2str_dname_buf(z->name, z->namelen, zname,
3452 sizeof(zname));
3453 if(node)
3454 sldns_wire2str_dname_buf(node->name, node->namelen,
3455 nname, sizeof(nname));
3456 else snprintf(nname, sizeof(nname), "NULL");
3457 if(ce)
3458 sldns_wire2str_dname_buf(ce->name, ce->namelen,
3459 cename, sizeof(cename));
3460 else snprintf(cename, sizeof(cename), "NULL");
3461 if(rrset) sldns_wire2str_type_buf(rrset->type, rrstr,
3462 sizeof(rrstr));
3463 else snprintf(rrstr, sizeof(rrstr), "NULL");
3464 log_info("auth_zone %s query %s %s, domain %s %s %s, "
3465 "ce %s, rrset %s", zname, qname, tpstr, nname,
3466 (node_exact?"exact":"notexact"),
3467 (node_exists?"exist":"notexist"), cename, rrstr);
3468 }
3469
3470 if(node_exists) {
3471 /* the node is fine, generate answer from node */
3472 return az_generate_answer_with_node(z, qinfo, region, *msg,
3473 node);
3474 }
3475 return az_generate_answer_nonexistnode(z, qinfo, region, *msg,
3476 ce, rrset, node);
3477 }
3478
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)3479 int auth_zones_lookup(struct auth_zones* az, struct query_info* qinfo,
3480 struct regional* region, struct dns_msg** msg, int* fallback,
3481 uint8_t* dp_nm, size_t dp_nmlen)
3482 {
3483 int r;
3484 struct auth_zone* z;
3485 /* find the zone that should contain the answer. */
3486 lock_rw_rdlock(&az->lock);
3487 z = auth_zone_find(az, dp_nm, dp_nmlen, qinfo->qclass);
3488 if(!z) {
3489 lock_rw_unlock(&az->lock);
3490 /* no auth zone, fallback to internet */
3491 *fallback = 1;
3492 return 0;
3493 }
3494 lock_rw_rdlock(&z->lock);
3495 lock_rw_unlock(&az->lock);
3496
3497 /* if not for upstream queries, fallback */
3498 if(!z->for_upstream) {
3499 lock_rw_unlock(&z->lock);
3500 *fallback = 1;
3501 return 0;
3502 }
3503 if(z->zone_expired) {
3504 *fallback = z->fallback_enabled;
3505 lock_rw_unlock(&z->lock);
3506 return 0;
3507 }
3508 /* see what answer that zone would generate */
3509 r = auth_zone_generate_answer(z, qinfo, region, msg, fallback);
3510 lock_rw_unlock(&z->lock);
3511 return r;
3512 }
3513
3514 /** encode auth answer */
3515 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)3516 auth_answer_encode(struct query_info* qinfo, struct module_env* env,
3517 struct edns_data* edns, struct comm_reply* repinfo, sldns_buffer* buf,
3518 struct regional* temp, struct dns_msg* msg)
3519 {
3520 uint16_t udpsize;
3521 udpsize = edns->udp_size;
3522 edns->edns_version = EDNS_ADVERTISED_VERSION;
3523 edns->udp_size = EDNS_ADVERTISED_SIZE;
3524 edns->ext_rcode = 0;
3525 edns->bits &= EDNS_DO;
3526
3527 if(!inplace_cb_reply_local_call(env, qinfo, NULL, msg->rep,
3528 (int)FLAGS_GET_RCODE(msg->rep->flags), edns, repinfo, temp, env->now_tv)
3529 || !reply_info_answer_encode(qinfo, msg->rep,
3530 *(uint16_t*)sldns_buffer_begin(buf),
3531 sldns_buffer_read_u16_at(buf, 2),
3532 buf, 0, 0, temp, udpsize, edns,
3533 (int)(edns->bits&EDNS_DO), 0)) {
3534 error_encode(buf, (LDNS_RCODE_SERVFAIL|BIT_AA), qinfo,
3535 *(uint16_t*)sldns_buffer_begin(buf),
3536 sldns_buffer_read_u16_at(buf, 2), edns);
3537 }
3538 }
3539
3540 /** encode auth error answer */
3541 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)3542 auth_error_encode(struct query_info* qinfo, struct module_env* env,
3543 struct edns_data* edns, struct comm_reply* repinfo, sldns_buffer* buf,
3544 struct regional* temp, int rcode)
3545 {
3546 edns->edns_version = EDNS_ADVERTISED_VERSION;
3547 edns->udp_size = EDNS_ADVERTISED_SIZE;
3548 edns->ext_rcode = 0;
3549 edns->bits &= EDNS_DO;
3550
3551 if(!inplace_cb_reply_local_call(env, qinfo, NULL, NULL,
3552 rcode, edns, repinfo, temp, env->now_tv))
3553 edns->opt_list_inplace_cb_out = NULL;
3554 error_encode(buf, rcode|BIT_AA, qinfo,
3555 *(uint16_t*)sldns_buffer_begin(buf),
3556 sldns_buffer_read_u16_at(buf, 2), edns);
3557 }
3558
auth_zones_downstream_answer(struct auth_zones * az,struct module_env * env,struct query_info * qinfo,struct edns_data * edns,struct comm_reply * repinfo,struct sldns_buffer * buf,struct regional * temp)3559 int auth_zones_downstream_answer(struct auth_zones* az, struct module_env* env,
3560 struct query_info* qinfo, struct edns_data* edns,
3561 struct comm_reply* repinfo, struct sldns_buffer* buf,
3562 struct regional* temp)
3563 {
3564 struct dns_msg* msg = NULL;
3565 struct auth_zone* z;
3566 int r;
3567 int fallback = 0;
3568 /* Copy the qinfo in case of cname aliasing from local-zone */
3569 struct query_info zqinfo = *qinfo;
3570
3571 lock_rw_rdlock(&az->lock);
3572 if(!az->have_downstream) {
3573 /* no downstream auth zones */
3574 lock_rw_unlock(&az->lock);
3575 return 0;
3576 }
3577
3578 if(qinfo->qtype == LDNS_RR_TYPE_DS) {
3579 uint8_t* delname = qinfo->qname;
3580 size_t delnamelen = qinfo->qname_len;
3581 dname_remove_label(&delname, &delnamelen);
3582 z = auth_zones_find_zone(az, delname, delnamelen,
3583 qinfo->qclass);
3584 } else {
3585 if(zqinfo.local_alias && !local_alias_shallow_copy_qname(
3586 zqinfo.local_alias, &zqinfo.qname,
3587 &zqinfo.qname_len)) {
3588 lock_rw_unlock(&az->lock);
3589 return 0;
3590 }
3591 z = auth_zones_find_zone(az, zqinfo.qname, zqinfo.qname_len,
3592 zqinfo.qclass);
3593 }
3594 if(!z) {
3595 /* no zone above it */
3596 lock_rw_unlock(&az->lock);
3597 return 0;
3598 }
3599 lock_rw_rdlock(&z->lock);
3600 lock_rw_unlock(&az->lock);
3601 if(!z->for_downstream) {
3602 lock_rw_unlock(&z->lock);
3603 return 0;
3604 }
3605 if(z->zone_expired) {
3606 if(z->fallback_enabled) {
3607 lock_rw_unlock(&z->lock);
3608 return 0;
3609 }
3610 lock_rw_unlock(&z->lock);
3611 env->mesh->num_query_authzone_down++;
3612 auth_error_encode(qinfo, env, edns, repinfo, buf, temp,
3613 LDNS_RCODE_SERVFAIL);
3614 return 1;
3615 }
3616
3617 /* answer it from zone z */
3618 r = auth_zone_generate_answer(z, &zqinfo, temp, &msg, &fallback);
3619 lock_rw_unlock(&z->lock);
3620 if(!r && fallback) {
3621 /* fallback to regular answering (recursive) */
3622 return 0;
3623 }
3624 env->mesh->num_query_authzone_down++;
3625
3626 /* encode answer */
3627 if(!r)
3628 auth_error_encode(qinfo, env, edns, repinfo, buf, temp,
3629 LDNS_RCODE_SERVFAIL);
3630 else auth_answer_encode(qinfo, env, edns, repinfo, buf, temp, msg);
3631
3632 return 1;
3633 }
3634
auth_zones_can_fallback(struct auth_zones * az,uint8_t * nm,size_t nmlen,uint16_t dclass)3635 int auth_zones_can_fallback(struct auth_zones* az, uint8_t* nm, size_t nmlen,
3636 uint16_t dclass)
3637 {
3638 int r;
3639 struct auth_zone* z;
3640 lock_rw_rdlock(&az->lock);
3641 z = auth_zone_find(az, nm, nmlen, dclass);
3642 if(!z) {
3643 lock_rw_unlock(&az->lock);
3644 /* no such auth zone, fallback */
3645 return 1;
3646 }
3647 lock_rw_rdlock(&z->lock);
3648 lock_rw_unlock(&az->lock);
3649 r = z->fallback_enabled || (!z->for_upstream);
3650 lock_rw_unlock(&z->lock);
3651 return r;
3652 }
3653
3654 int
auth_zone_parse_notify_serial(sldns_buffer * pkt,uint32_t * serial)3655 auth_zone_parse_notify_serial(sldns_buffer* pkt, uint32_t *serial)
3656 {
3657 struct query_info q;
3658 uint16_t rdlen;
3659 memset(&q, 0, sizeof(q));
3660 sldns_buffer_set_position(pkt, 0);
3661 if(!query_info_parse(&q, pkt)) return 0;
3662 if(LDNS_ANCOUNT(sldns_buffer_begin(pkt)) == 0) return 0;
3663 /* skip name of RR in answer section */
3664 if(sldns_buffer_remaining(pkt) < 1) return 0;
3665 if(pkt_dname_len(pkt) == 0) return 0;
3666 /* check type */
3667 if(sldns_buffer_remaining(pkt) < 10 /* type,class,ttl,rdatalen*/)
3668 return 0;
3669 if(sldns_buffer_read_u16(pkt) != LDNS_RR_TYPE_SOA) return 0;
3670 sldns_buffer_skip(pkt, 2); /* class */
3671 sldns_buffer_skip(pkt, 4); /* ttl */
3672 rdlen = sldns_buffer_read_u16(pkt); /* rdatalen */
3673 if(sldns_buffer_remaining(pkt) < rdlen) return 0;
3674 if(rdlen < 22) return 0; /* bad soa length */
3675 sldns_buffer_skip(pkt, (ssize_t)(rdlen-20));
3676 *serial = sldns_buffer_read_u32(pkt);
3677 /* return true when has serial in answer section */
3678 return 1;
3679 }
3680
3681 /** 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)3682 static void addr_port_to_str(struct sockaddr_storage* addr, socklen_t addrlen,
3683 char* buf, size_t len)
3684 {
3685 uint16_t port = 0;
3686 if(addr_is_ip6(addr, addrlen)) {
3687 struct sockaddr_in6* sa = (struct sockaddr_in6*)addr;
3688 port = ntohs((uint16_t)sa->sin6_port);
3689 } else {
3690 struct sockaddr_in* sa = (struct sockaddr_in*)addr;
3691 port = ntohs((uint16_t)sa->sin_port);
3692 }
3693 if(port == UNBOUND_DNS_PORT) {
3694 /* If it is port 53, print it plainly. */
3695 addr_to_str(addr, addrlen, buf, len);
3696 } else {
3697 char a[256];
3698 a[0]=0;
3699 addr_to_str(addr, addrlen, a, sizeof(a));
3700 snprintf(buf, len, "%s@%d", a, (int)port);
3701 }
3702 }
3703
3704 /** see if addr appears in the list */
3705 static int
addr_in_list(struct auth_addr * list,struct sockaddr_storage * addr,socklen_t addrlen)3706 addr_in_list(struct auth_addr* list, struct sockaddr_storage* addr,
3707 socklen_t addrlen)
3708 {
3709 struct auth_addr* p;
3710 for(p=list; p; p=p->next) {
3711 if(sockaddr_cmp_addr(addr, addrlen, &p->addr, p->addrlen)==0)
3712 return 1;
3713 }
3714 return 0;
3715 }
3716
3717 /** check if an address matches a master specification (or one of its
3718 * addresses in the addr list) */
3719 static int
addr_matches_master(struct auth_master * master,struct sockaddr_storage * addr,socklen_t addrlen,struct auth_master ** fromhost)3720 addr_matches_master(struct auth_master* master, struct sockaddr_storage* addr,
3721 socklen_t addrlen, struct auth_master** fromhost)
3722 {
3723 struct sockaddr_storage a;
3724 socklen_t alen = 0;
3725 int net = 0;
3726 if(addr_in_list(master->list, addr, addrlen)) {
3727 *fromhost = master;
3728 return 1;
3729 }
3730 /* compare address (but not port number, that is the destination
3731 * port of the master, the port number of the received notify is
3732 * allowed to by any port on that master) */
3733 if(extstrtoaddr(master->host, &a, &alen, UNBOUND_DNS_PORT) &&
3734 sockaddr_cmp_addr(addr, addrlen, &a, alen)==0) {
3735 *fromhost = master;
3736 return 1;
3737 }
3738 /* prefixes, addr/len, like 10.0.0.0/8 */
3739 /* not http and has a / and there is one / */
3740 if(master->allow_notify && !master->http &&
3741 strchr(master->host, '/') != NULL &&
3742 strchr(master->host, '/') == strrchr(master->host, '/') &&
3743 netblockstrtoaddr(master->host, UNBOUND_DNS_PORT, &a, &alen,
3744 &net) && alen == addrlen) {
3745 if(addr_in_common(addr, (addr_is_ip6(addr, addrlen)?128:32),
3746 &a, net, alen) >= net) {
3747 *fromhost = NULL; /* prefix does not have destination
3748 to send the probe or transfer with */
3749 return 1; /* matches the netblock */
3750 }
3751 }
3752 return 0;
3753 }
3754
3755 /** check access list for notifies */
3756 static int
az_xfr_allowed_notify(struct auth_xfer * xfr,struct sockaddr_storage * addr,socklen_t addrlen,struct auth_master ** fromhost)3757 az_xfr_allowed_notify(struct auth_xfer* xfr, struct sockaddr_storage* addr,
3758 socklen_t addrlen, struct auth_master** fromhost)
3759 {
3760 struct auth_master* p;
3761 for(p=xfr->allow_notify_list; p; p=p->next) {
3762 if(addr_matches_master(p, addr, addrlen, fromhost)) {
3763 return 1;
3764 }
3765 }
3766 return 0;
3767 }
3768
3769 /** see if the serial means the zone has to be updated, i.e. the serial
3770 * is newer than the zone serial, or we have no zone */
3771 static int
xfr_serial_means_update(struct auth_xfer * xfr,uint32_t serial)3772 xfr_serial_means_update(struct auth_xfer* xfr, uint32_t serial)
3773 {
3774 if(!xfr->have_zone)
3775 return 1; /* no zone, anything is better */
3776 if(xfr->zone_expired)
3777 return 1; /* expired, the sent serial is better than expired
3778 data */
3779 if(compare_serial(xfr->serial, serial) < 0)
3780 return 1; /* our serial is smaller than the sent serial,
3781 the data is newer, fetch it */
3782 return 0;
3783 }
3784
3785 /** note notify serial, updates the notify information in the xfr struct */
3786 static void
xfr_note_notify_serial(struct auth_xfer * xfr,int has_serial,uint32_t serial)3787 xfr_note_notify_serial(struct auth_xfer* xfr, int has_serial, uint32_t serial)
3788 {
3789 if(xfr->notify_received && xfr->notify_has_serial && has_serial) {
3790 /* see if this serial is newer */
3791 if(compare_serial(xfr->notify_serial, serial) < 0)
3792 xfr->notify_serial = serial;
3793 } else if(xfr->notify_received && xfr->notify_has_serial &&
3794 !has_serial) {
3795 /* remove serial, we have notify without serial */
3796 xfr->notify_has_serial = 0;
3797 xfr->notify_serial = 0;
3798 } else if(xfr->notify_received && !xfr->notify_has_serial) {
3799 /* we already have notify without serial, keep it
3800 * that way; no serial check when current operation
3801 * is done */
3802 } else {
3803 xfr->notify_received = 1;
3804 xfr->notify_has_serial = has_serial;
3805 xfr->notify_serial = serial;
3806 }
3807 }
3808
3809 /** process a notify serial, start new probe or note serial. xfr is locked */
3810 static void
xfr_process_notify(struct auth_xfer * xfr,struct module_env * env,int has_serial,uint32_t serial,struct auth_master * fromhost)3811 xfr_process_notify(struct auth_xfer* xfr, struct module_env* env,
3812 int has_serial, uint32_t serial, struct auth_master* fromhost)
3813 {
3814 /* if the serial of notify is older than we have, don't fetch
3815 * a zone, we already have it */
3816 if(has_serial && !xfr_serial_means_update(xfr, serial)) {
3817 lock_basic_unlock(&xfr->lock);
3818 return;
3819 }
3820 /* start new probe with this addr src, or note serial */
3821 if(!xfr_start_probe(xfr, env, fromhost)) {
3822 /* not started because already in progress, note the serial */
3823 xfr_note_notify_serial(xfr, has_serial, serial);
3824 lock_basic_unlock(&xfr->lock);
3825 }
3826 /* successful end of start_probe unlocked xfr->lock */
3827 }
3828
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)3829 int auth_zones_notify(struct auth_zones* az, struct module_env* env,
3830 uint8_t* nm, size_t nmlen, uint16_t dclass,
3831 struct sockaddr_storage* addr, socklen_t addrlen, int has_serial,
3832 uint32_t serial, int* refused)
3833 {
3834 struct auth_xfer* xfr;
3835 struct auth_master* fromhost = NULL;
3836 /* see which zone this is */
3837 lock_rw_rdlock(&az->lock);
3838 xfr = auth_xfer_find(az, nm, nmlen, dclass);
3839 if(!xfr) {
3840 lock_rw_unlock(&az->lock);
3841 /* no such zone, refuse the notify */
3842 *refused = 1;
3843 return 0;
3844 }
3845 lock_basic_lock(&xfr->lock);
3846 lock_rw_unlock(&az->lock);
3847
3848 /* check access list for notifies */
3849 if(!az_xfr_allowed_notify(xfr, addr, addrlen, &fromhost)) {
3850 lock_basic_unlock(&xfr->lock);
3851 /* notify not allowed, refuse the notify */
3852 *refused = 1;
3853 return 0;
3854 }
3855
3856 /* process the notify */
3857 xfr_process_notify(xfr, env, has_serial, serial, fromhost);
3858 return 1;
3859 }
3860
auth_zones_startprobesequence(struct auth_zones * az,struct module_env * env,uint8_t * nm,size_t nmlen,uint16_t dclass)3861 int auth_zones_startprobesequence(struct auth_zones* az,
3862 struct module_env* env, uint8_t* nm, size_t nmlen, uint16_t dclass)
3863 {
3864 struct auth_xfer* xfr;
3865 lock_rw_rdlock(&az->lock);
3866 xfr = auth_xfer_find(az, nm, nmlen, dclass);
3867 if(!xfr) {
3868 lock_rw_unlock(&az->lock);
3869 return 0;
3870 }
3871 lock_basic_lock(&xfr->lock);
3872 lock_rw_unlock(&az->lock);
3873
3874 xfr_process_notify(xfr, env, 0, 0, NULL);
3875 return 1;
3876 }
3877
3878 /** set a zone expired */
3879 static void
auth_xfer_set_expired(struct auth_xfer * xfr,struct module_env * env,int expired)3880 auth_xfer_set_expired(struct auth_xfer* xfr, struct module_env* env,
3881 int expired)
3882 {
3883 struct auth_zone* z;
3884
3885 /* expire xfr */
3886 lock_basic_lock(&xfr->lock);
3887 xfr->zone_expired = expired;
3888 lock_basic_unlock(&xfr->lock);
3889
3890 /* find auth_zone */
3891 lock_rw_rdlock(&env->auth_zones->lock);
3892 z = auth_zone_find(env->auth_zones, xfr->name, xfr->namelen,
3893 xfr->dclass);
3894 if(!z) {
3895 lock_rw_unlock(&env->auth_zones->lock);
3896 return;
3897 }
3898 lock_rw_wrlock(&z->lock);
3899 lock_rw_unlock(&env->auth_zones->lock);
3900
3901 /* expire auth_zone */
3902 z->zone_expired = expired;
3903 lock_rw_unlock(&z->lock);
3904 }
3905
3906 /** find master (from notify or probe) in list of masters */
3907 static struct auth_master*
find_master_by_host(struct auth_master * list,char * host)3908 find_master_by_host(struct auth_master* list, char* host)
3909 {
3910 struct auth_master* p;
3911 for(p=list; p; p=p->next) {
3912 if(strcmp(p->host, host) == 0)
3913 return p;
3914 }
3915 return NULL;
3916 }
3917
3918 /** delete the looked up auth_addrs for all the masters in the list */
3919 static void
xfr_masterlist_free_addrs(struct auth_master * list)3920 xfr_masterlist_free_addrs(struct auth_master* list)
3921 {
3922 struct auth_master* m;
3923 for(m=list; m; m=m->next) {
3924 if(m->list) {
3925 auth_free_master_addrs(m->list);
3926 m->list = NULL;
3927 }
3928 }
3929 }
3930
3931 /** copy a list of auth_addrs */
3932 static struct auth_addr*
auth_addr_list_copy(struct auth_addr * source)3933 auth_addr_list_copy(struct auth_addr* source)
3934 {
3935 struct auth_addr* list = NULL, *last = NULL;
3936 struct auth_addr* p;
3937 for(p=source; p; p=p->next) {
3938 struct auth_addr* a = (struct auth_addr*)memdup(p, sizeof(*p));
3939 if(!a) {
3940 log_err("malloc failure");
3941 auth_free_master_addrs(list);
3942 return NULL;
3943 }
3944 a->next = NULL;
3945 if(last) last->next = a;
3946 if(!list) list = a;
3947 last = a;
3948 }
3949 return list;
3950 }
3951
3952 /** copy a master to a new structure, NULL on alloc failure */
3953 static struct auth_master*
auth_master_copy(struct auth_master * o)3954 auth_master_copy(struct auth_master* o)
3955 {
3956 struct auth_master* m;
3957 if(!o) return NULL;
3958 m = (struct auth_master*)memdup(o, sizeof(*o));
3959 if(!m) {
3960 log_err("malloc failure");
3961 return NULL;
3962 }
3963 m->next = NULL;
3964 if(m->host) {
3965 m->host = strdup(m->host);
3966 if(!m->host) {
3967 free(m);
3968 log_err("malloc failure");
3969 return NULL;
3970 }
3971 }
3972 if(m->file) {
3973 m->file = strdup(m->file);
3974 if(!m->file) {
3975 free(m->host);
3976 free(m);
3977 log_err("malloc failure");
3978 return NULL;
3979 }
3980 }
3981 if(m->list) {
3982 m->list = auth_addr_list_copy(m->list);
3983 if(!m->list) {
3984 free(m->file);
3985 free(m->host);
3986 free(m);
3987 return NULL;
3988 }
3989 }
3990 return m;
3991 }
3992
3993 /** copy the master addresses from the task_probe lookups to the allow_notify
3994 * list of masters */
3995 static void
probe_copy_masters_for_allow_notify(struct auth_xfer * xfr)3996 probe_copy_masters_for_allow_notify(struct auth_xfer* xfr)
3997 {
3998 struct auth_master* list = NULL, *last = NULL;
3999 struct auth_master* p;
4000 /* build up new list with copies */
4001 for(p = xfr->task_transfer->masters; p; p=p->next) {
4002 struct auth_master* m = auth_master_copy(p);
4003 if(!m) {
4004 auth_free_masters(list);
4005 /* failed because of malloc failure, use old list */
4006 return;
4007 }
4008 m->next = NULL;
4009 if(last) last->next = m;
4010 if(!list) list = m;
4011 last = m;
4012 }
4013 /* success, replace list */
4014 auth_free_masters(xfr->allow_notify_list);
4015 xfr->allow_notify_list = list;
4016 }
4017
4018 /** start the lookups for task_transfer */
4019 static void
xfr_transfer_start_lookups(struct auth_xfer * xfr)4020 xfr_transfer_start_lookups(struct auth_xfer* xfr)
4021 {
4022 /* delete all the looked up addresses in the list */
4023 xfr->task_transfer->scan_addr = NULL;
4024 xfr_masterlist_free_addrs(xfr->task_transfer->masters);
4025
4026 /* start lookup at the first master */
4027 xfr->task_transfer->lookup_target = xfr->task_transfer->masters;
4028 xfr->task_transfer->lookup_aaaa = 0;
4029 }
4030
4031 /** move to the next lookup of hostname for task_transfer */
4032 static void
xfr_transfer_move_to_next_lookup(struct auth_xfer * xfr,struct module_env * env)4033 xfr_transfer_move_to_next_lookup(struct auth_xfer* xfr, struct module_env* env)
4034 {
4035 if(!xfr->task_transfer->lookup_target)
4036 return; /* already at end of list */
4037 if(!xfr->task_transfer->lookup_aaaa && env->cfg->do_ip6) {
4038 /* move to lookup AAAA */
4039 xfr->task_transfer->lookup_aaaa = 1;
4040 return;
4041 }
4042 xfr->task_transfer->lookup_target =
4043 xfr->task_transfer->lookup_target->next;
4044 xfr->task_transfer->lookup_aaaa = 0;
4045 if(!env->cfg->do_ip4 && xfr->task_transfer->lookup_target!=NULL)
4046 xfr->task_transfer->lookup_aaaa = 1;
4047 }
4048
4049 /** start the lookups for task_probe */
4050 static void
xfr_probe_start_lookups(struct auth_xfer * xfr)4051 xfr_probe_start_lookups(struct auth_xfer* xfr)
4052 {
4053 /* delete all the looked up addresses in the list */
4054 xfr->task_probe->scan_addr = NULL;
4055 xfr_masterlist_free_addrs(xfr->task_probe->masters);
4056
4057 /* start lookup at the first master */
4058 xfr->task_probe->lookup_target = xfr->task_probe->masters;
4059 xfr->task_probe->lookup_aaaa = 0;
4060 }
4061
4062 /** move to the next lookup of hostname for task_probe */
4063 static void
xfr_probe_move_to_next_lookup(struct auth_xfer * xfr,struct module_env * env)4064 xfr_probe_move_to_next_lookup(struct auth_xfer* xfr, struct module_env* env)
4065 {
4066 if(!xfr->task_probe->lookup_target)
4067 return; /* already at end of list */
4068 if(!xfr->task_probe->lookup_aaaa && env->cfg->do_ip6) {
4069 /* move to lookup AAAA */
4070 xfr->task_probe->lookup_aaaa = 1;
4071 return;
4072 }
4073 xfr->task_probe->lookup_target = xfr->task_probe->lookup_target->next;
4074 xfr->task_probe->lookup_aaaa = 0;
4075 if(!env->cfg->do_ip4 && xfr->task_probe->lookup_target!=NULL)
4076 xfr->task_probe->lookup_aaaa = 1;
4077 }
4078
4079 /** start the iteration of the task_transfer list of masters */
4080 static void
xfr_transfer_start_list(struct auth_xfer * xfr,struct auth_master * spec)4081 xfr_transfer_start_list(struct auth_xfer* xfr, struct auth_master* spec)
4082 {
4083 if(spec) {
4084 xfr->task_transfer->scan_specific = find_master_by_host(
4085 xfr->task_transfer->masters, spec->host);
4086 if(xfr->task_transfer->scan_specific) {
4087 xfr->task_transfer->scan_target = NULL;
4088 xfr->task_transfer->scan_addr = NULL;
4089 if(xfr->task_transfer->scan_specific->list)
4090 xfr->task_transfer->scan_addr =
4091 xfr->task_transfer->scan_specific->list;
4092 return;
4093 }
4094 }
4095 /* no specific (notified) host to scan */
4096 xfr->task_transfer->scan_specific = NULL;
4097 xfr->task_transfer->scan_addr = NULL;
4098 /* pick up first scan target */
4099 xfr->task_transfer->scan_target = xfr->task_transfer->masters;
4100 if(xfr->task_transfer->scan_target && xfr->task_transfer->
4101 scan_target->list)
4102 xfr->task_transfer->scan_addr =
4103 xfr->task_transfer->scan_target->list;
4104 }
4105
4106 /** start the iteration of the task_probe list of masters */
4107 static void
xfr_probe_start_list(struct auth_xfer * xfr,struct auth_master * spec)4108 xfr_probe_start_list(struct auth_xfer* xfr, struct auth_master* spec)
4109 {
4110 if(spec) {
4111 xfr->task_probe->scan_specific = find_master_by_host(
4112 xfr->task_probe->masters, spec->host);
4113 if(xfr->task_probe->scan_specific) {
4114 xfr->task_probe->scan_target = NULL;
4115 xfr->task_probe->scan_addr = NULL;
4116 if(xfr->task_probe->scan_specific->list)
4117 xfr->task_probe->scan_addr =
4118 xfr->task_probe->scan_specific->list;
4119 return;
4120 }
4121 }
4122 /* no specific (notified) host to scan */
4123 xfr->task_probe->scan_specific = NULL;
4124 xfr->task_probe->scan_addr = NULL;
4125 /* pick up first scan target */
4126 xfr->task_probe->scan_target = xfr->task_probe->masters;
4127 if(xfr->task_probe->scan_target && xfr->task_probe->scan_target->list)
4128 xfr->task_probe->scan_addr =
4129 xfr->task_probe->scan_target->list;
4130 }
4131
4132 /** pick up the master that is being scanned right now, task_transfer */
4133 static struct auth_master*
xfr_transfer_current_master(struct auth_xfer * xfr)4134 xfr_transfer_current_master(struct auth_xfer* xfr)
4135 {
4136 if(xfr->task_transfer->scan_specific)
4137 return xfr->task_transfer->scan_specific;
4138 return xfr->task_transfer->scan_target;
4139 }
4140
4141 /** pick up the master that is being scanned right now, task_probe */
4142 static struct auth_master*
xfr_probe_current_master(struct auth_xfer * xfr)4143 xfr_probe_current_master(struct auth_xfer* xfr)
4144 {
4145 if(xfr->task_probe->scan_specific)
4146 return xfr->task_probe->scan_specific;
4147 return xfr->task_probe->scan_target;
4148 }
4149
4150 /** true if at end of list, task_transfer */
4151 static int
xfr_transfer_end_of_list(struct auth_xfer * xfr)4152 xfr_transfer_end_of_list(struct auth_xfer* xfr)
4153 {
4154 return !xfr->task_transfer->scan_specific &&
4155 !xfr->task_transfer->scan_target;
4156 }
4157
4158 /** true if at end of list, task_probe */
4159 static int
xfr_probe_end_of_list(struct auth_xfer * xfr)4160 xfr_probe_end_of_list(struct auth_xfer* xfr)
4161 {
4162 return !xfr->task_probe->scan_specific && !xfr->task_probe->scan_target;
4163 }
4164
4165 /** move to next master in list, task_transfer */
4166 static void
xfr_transfer_nextmaster(struct auth_xfer * xfr)4167 xfr_transfer_nextmaster(struct auth_xfer* xfr)
4168 {
4169 if(!xfr->task_transfer->scan_specific &&
4170 !xfr->task_transfer->scan_target)
4171 return;
4172 if(xfr->task_transfer->scan_addr) {
4173 xfr->task_transfer->scan_addr =
4174 xfr->task_transfer->scan_addr->next;
4175 if(xfr->task_transfer->scan_addr)
4176 return;
4177 }
4178 if(xfr->task_transfer->scan_specific) {
4179 xfr->task_transfer->scan_specific = NULL;
4180 xfr->task_transfer->scan_target = xfr->task_transfer->masters;
4181 if(xfr->task_transfer->scan_target && xfr->task_transfer->
4182 scan_target->list)
4183 xfr->task_transfer->scan_addr =
4184 xfr->task_transfer->scan_target->list;
4185 return;
4186 }
4187 if(!xfr->task_transfer->scan_target)
4188 return;
4189 xfr->task_transfer->scan_target = xfr->task_transfer->scan_target->next;
4190 if(xfr->task_transfer->scan_target && xfr->task_transfer->
4191 scan_target->list)
4192 xfr->task_transfer->scan_addr =
4193 xfr->task_transfer->scan_target->list;
4194 return;
4195 }
4196
4197 /** move to next master in list, task_probe */
4198 static void
xfr_probe_nextmaster(struct auth_xfer * xfr)4199 xfr_probe_nextmaster(struct auth_xfer* xfr)
4200 {
4201 if(!xfr->task_probe->scan_specific && !xfr->task_probe->scan_target)
4202 return;
4203 if(xfr->task_probe->scan_addr) {
4204 xfr->task_probe->scan_addr = xfr->task_probe->scan_addr->next;
4205 if(xfr->task_probe->scan_addr)
4206 return;
4207 }
4208 if(xfr->task_probe->scan_specific) {
4209 xfr->task_probe->scan_specific = NULL;
4210 xfr->task_probe->scan_target = xfr->task_probe->masters;
4211 if(xfr->task_probe->scan_target && xfr->task_probe->
4212 scan_target->list)
4213 xfr->task_probe->scan_addr =
4214 xfr->task_probe->scan_target->list;
4215 return;
4216 }
4217 if(!xfr->task_probe->scan_target)
4218 return;
4219 xfr->task_probe->scan_target = xfr->task_probe->scan_target->next;
4220 if(xfr->task_probe->scan_target && xfr->task_probe->
4221 scan_target->list)
4222 xfr->task_probe->scan_addr =
4223 xfr->task_probe->scan_target->list;
4224 return;
4225 }
4226
4227 /** create SOA probe packet for xfr */
4228 static void
xfr_create_soa_probe_packet(struct auth_xfer * xfr,sldns_buffer * buf,uint16_t id)4229 xfr_create_soa_probe_packet(struct auth_xfer* xfr, sldns_buffer* buf,
4230 uint16_t id)
4231 {
4232 struct query_info qinfo;
4233
4234 memset(&qinfo, 0, sizeof(qinfo));
4235 qinfo.qname = xfr->name;
4236 qinfo.qname_len = xfr->namelen;
4237 qinfo.qtype = LDNS_RR_TYPE_SOA;
4238 qinfo.qclass = xfr->dclass;
4239 qinfo_query_encode(buf, &qinfo);
4240 sldns_buffer_write_u16_at(buf, 0, id);
4241 }
4242
4243 /** create IXFR/AXFR packet for xfr */
4244 static void
xfr_create_ixfr_packet(struct auth_xfer * xfr,sldns_buffer * buf,uint16_t id,struct auth_master * master)4245 xfr_create_ixfr_packet(struct auth_xfer* xfr, sldns_buffer* buf, uint16_t id,
4246 struct auth_master* master)
4247 {
4248 struct query_info qinfo;
4249 uint32_t serial;
4250 int have_zone;
4251 have_zone = xfr->have_zone;
4252 serial = xfr->serial;
4253
4254 memset(&qinfo, 0, sizeof(qinfo));
4255 qinfo.qname = xfr->name;
4256 qinfo.qname_len = xfr->namelen;
4257 xfr->task_transfer->got_xfr_serial = 0;
4258 xfr->task_transfer->rr_scan_num = 0;
4259 xfr->task_transfer->incoming_xfr_serial = 0;
4260 xfr->task_transfer->on_ixfr_is_axfr = 0;
4261 xfr->task_transfer->on_ixfr = 1;
4262 qinfo.qtype = LDNS_RR_TYPE_IXFR;
4263 if(!have_zone || xfr->task_transfer->ixfr_fail || !master->ixfr) {
4264 qinfo.qtype = LDNS_RR_TYPE_AXFR;
4265 xfr->task_transfer->ixfr_fail = 0;
4266 xfr->task_transfer->on_ixfr = 0;
4267 }
4268
4269 qinfo.qclass = xfr->dclass;
4270 qinfo_query_encode(buf, &qinfo);
4271 sldns_buffer_write_u16_at(buf, 0, id);
4272
4273 /* append serial for IXFR */
4274 if(qinfo.qtype == LDNS_RR_TYPE_IXFR) {
4275 size_t end = sldns_buffer_limit(buf);
4276 sldns_buffer_clear(buf);
4277 sldns_buffer_set_position(buf, end);
4278 /* auth section count 1 */
4279 sldns_buffer_write_u16_at(buf, LDNS_NSCOUNT_OFF, 1);
4280 /* write SOA */
4281 sldns_buffer_write_u8(buf, 0xC0); /* compressed ptr to qname */
4282 sldns_buffer_write_u8(buf, 0x0C);
4283 sldns_buffer_write_u16(buf, LDNS_RR_TYPE_SOA);
4284 sldns_buffer_write_u16(buf, qinfo.qclass);
4285 sldns_buffer_write_u32(buf, 0); /* ttl */
4286 sldns_buffer_write_u16(buf, 22); /* rdata length */
4287 sldns_buffer_write_u8(buf, 0); /* . */
4288 sldns_buffer_write_u8(buf, 0); /* . */
4289 sldns_buffer_write_u32(buf, serial); /* serial */
4290 sldns_buffer_write_u32(buf, 0); /* refresh */
4291 sldns_buffer_write_u32(buf, 0); /* retry */
4292 sldns_buffer_write_u32(buf, 0); /* expire */
4293 sldns_buffer_write_u32(buf, 0); /* minimum */
4294 sldns_buffer_flip(buf);
4295 }
4296 }
4297
4298 /** check if returned packet is OK */
4299 static int
check_packet_ok(sldns_buffer * pkt,uint16_t qtype,struct auth_xfer * xfr,uint32_t * serial)4300 check_packet_ok(sldns_buffer* pkt, uint16_t qtype, struct auth_xfer* xfr,
4301 uint32_t* serial)
4302 {
4303 /* parse to see if packet worked, valid reply */
4304
4305 /* check serial number of SOA */
4306 if(sldns_buffer_limit(pkt) < LDNS_HEADER_SIZE)
4307 return 0;
4308
4309 /* check ID */
4310 if(LDNS_ID_WIRE(sldns_buffer_begin(pkt)) != xfr->task_probe->id)
4311 return 0;
4312
4313 /* check flag bits and rcode */
4314 if(!LDNS_QR_WIRE(sldns_buffer_begin(pkt)))
4315 return 0;
4316 if(LDNS_OPCODE_WIRE(sldns_buffer_begin(pkt)) != LDNS_PACKET_QUERY)
4317 return 0;
4318 if(LDNS_RCODE_WIRE(sldns_buffer_begin(pkt)) != LDNS_RCODE_NOERROR)
4319 return 0;
4320
4321 /* check qname */
4322 if(LDNS_QDCOUNT(sldns_buffer_begin(pkt)) != 1)
4323 return 0;
4324 sldns_buffer_skip(pkt, LDNS_HEADER_SIZE);
4325 if(sldns_buffer_remaining(pkt) < xfr->namelen)
4326 return 0;
4327 if(query_dname_compare(sldns_buffer_current(pkt), xfr->name) != 0)
4328 return 0;
4329 sldns_buffer_skip(pkt, (ssize_t)xfr->namelen);
4330
4331 /* check qtype, qclass */
4332 if(sldns_buffer_remaining(pkt) < 4)
4333 return 0;
4334 if(sldns_buffer_read_u16(pkt) != qtype)
4335 return 0;
4336 if(sldns_buffer_read_u16(pkt) != xfr->dclass)
4337 return 0;
4338
4339 if(serial) {
4340 uint16_t rdlen;
4341 /* read serial number, from answer section SOA */
4342 if(LDNS_ANCOUNT(sldns_buffer_begin(pkt)) == 0)
4343 return 0;
4344 /* read from first record SOA record */
4345 if(sldns_buffer_remaining(pkt) < 1)
4346 return 0;
4347 if(dname_pkt_compare(pkt, sldns_buffer_current(pkt),
4348 xfr->name) != 0)
4349 return 0;
4350 if(!pkt_dname_len(pkt))
4351 return 0;
4352 /* type, class, ttl, rdatalen */
4353 if(sldns_buffer_remaining(pkt) < 4+4+2)
4354 return 0;
4355 if(sldns_buffer_read_u16(pkt) != qtype)
4356 return 0;
4357 if(sldns_buffer_read_u16(pkt) != xfr->dclass)
4358 return 0;
4359 sldns_buffer_skip(pkt, 4); /* ttl */
4360 rdlen = sldns_buffer_read_u16(pkt);
4361 if(sldns_buffer_remaining(pkt) < rdlen)
4362 return 0;
4363 if(sldns_buffer_remaining(pkt) < 1)
4364 return 0;
4365 if(!pkt_dname_len(pkt)) /* soa name */
4366 return 0;
4367 if(sldns_buffer_remaining(pkt) < 1)
4368 return 0;
4369 if(!pkt_dname_len(pkt)) /* soa name */
4370 return 0;
4371 if(sldns_buffer_remaining(pkt) < 20)
4372 return 0;
4373 *serial = sldns_buffer_read_u32(pkt);
4374 }
4375 return 1;
4376 }
4377
4378 /** read one line from chunks into buffer at current position */
4379 static int
chunkline_get_line(struct auth_chunk ** chunk,size_t * chunk_pos,sldns_buffer * buf)4380 chunkline_get_line(struct auth_chunk** chunk, size_t* chunk_pos,
4381 sldns_buffer* buf)
4382 {
4383 int readsome = 0;
4384 while(*chunk) {
4385 /* more text in this chunk? */
4386 if(*chunk_pos < (*chunk)->len) {
4387 readsome = 1;
4388 while(*chunk_pos < (*chunk)->len) {
4389 char c = (char)((*chunk)->data[*chunk_pos]);
4390 (*chunk_pos)++;
4391 if(sldns_buffer_remaining(buf) < 2) {
4392 /* buffer too short */
4393 verbose(VERB_ALGO, "http chunkline, "
4394 "line too long");
4395 return 0;
4396 }
4397 sldns_buffer_write_u8(buf, (uint8_t)c);
4398 if(c == '\n') {
4399 /* we are done */
4400 return 1;
4401 }
4402 }
4403 }
4404 /* move to next chunk */
4405 *chunk = (*chunk)->next;
4406 *chunk_pos = 0;
4407 }
4408 /* no more text */
4409 if(readsome) return 1;
4410 return 0;
4411 }
4412
4413 /** count number of open and closed parenthesis in a chunkline */
4414 static int
chunkline_count_parens(sldns_buffer * buf,size_t start)4415 chunkline_count_parens(sldns_buffer* buf, size_t start)
4416 {
4417 size_t end = sldns_buffer_position(buf);
4418 size_t i;
4419 int count = 0;
4420 int squote = 0, dquote = 0;
4421 for(i=start; i<end; i++) {
4422 char c = (char)sldns_buffer_read_u8_at(buf, i);
4423 if(squote && c != '\'') continue;
4424 if(dquote && c != '"') continue;
4425 if(c == '"')
4426 dquote = !dquote; /* skip quoted part */
4427 else if(c == '\'')
4428 squote = !squote; /* skip quoted part */
4429 else if(c == '(')
4430 count ++;
4431 else if(c == ')')
4432 count --;
4433 else if(c == ';') {
4434 /* rest is a comment */
4435 return count;
4436 }
4437 }
4438 return count;
4439 }
4440
4441 /** remove trailing ;... comment from a line in the chunkline buffer */
4442 static void
chunkline_remove_trailcomment(sldns_buffer * buf,size_t start)4443 chunkline_remove_trailcomment(sldns_buffer* buf, size_t start)
4444 {
4445 size_t end = sldns_buffer_position(buf);
4446 size_t i;
4447 int squote = 0, dquote = 0;
4448 for(i=start; i<end; i++) {
4449 char c = (char)sldns_buffer_read_u8_at(buf, i);
4450 if(squote && c != '\'') continue;
4451 if(dquote && c != '"') continue;
4452 if(c == '"')
4453 dquote = !dquote; /* skip quoted part */
4454 else if(c == '\'')
4455 squote = !squote; /* skip quoted part */
4456 else if(c == ';') {
4457 /* rest is a comment */
4458 sldns_buffer_set_position(buf, i);
4459 return;
4460 }
4461 }
4462 /* nothing to remove */
4463 }
4464
4465 /** see if a chunkline is a comment line (or empty line) */
4466 static int
chunkline_is_comment_line_or_empty(sldns_buffer * buf)4467 chunkline_is_comment_line_or_empty(sldns_buffer* buf)
4468 {
4469 size_t i, end = sldns_buffer_limit(buf);
4470 for(i=0; i<end; i++) {
4471 char c = (char)sldns_buffer_read_u8_at(buf, i);
4472 if(c == ';')
4473 return 1; /* comment */
4474 else if(c != ' ' && c != '\t' && c != '\r' && c != '\n')
4475 return 0; /* not a comment */
4476 }
4477 return 1; /* empty */
4478 }
4479
4480 /** find a line with ( ) collated */
4481 static int
chunkline_get_line_collated(struct auth_chunk ** chunk,size_t * chunk_pos,sldns_buffer * buf)4482 chunkline_get_line_collated(struct auth_chunk** chunk, size_t* chunk_pos,
4483 sldns_buffer* buf)
4484 {
4485 size_t pos;
4486 int parens = 0;
4487 sldns_buffer_clear(buf);
4488 pos = sldns_buffer_position(buf);
4489 if(!chunkline_get_line(chunk, chunk_pos, buf)) {
4490 if(sldns_buffer_position(buf) < sldns_buffer_limit(buf))
4491 sldns_buffer_write_u8_at(buf, sldns_buffer_position(buf), 0);
4492 else sldns_buffer_write_u8_at(buf, sldns_buffer_position(buf)-1, 0);
4493 sldns_buffer_flip(buf);
4494 return 0;
4495 }
4496 parens += chunkline_count_parens(buf, pos);
4497 while(parens > 0) {
4498 chunkline_remove_trailcomment(buf, pos);
4499 pos = sldns_buffer_position(buf);
4500 if(!chunkline_get_line(chunk, chunk_pos, buf)) {
4501 if(sldns_buffer_position(buf) < sldns_buffer_limit(buf))
4502 sldns_buffer_write_u8_at(buf, sldns_buffer_position(buf), 0);
4503 else sldns_buffer_write_u8_at(buf, sldns_buffer_position(buf)-1, 0);
4504 sldns_buffer_flip(buf);
4505 return 0;
4506 }
4507 parens += chunkline_count_parens(buf, pos);
4508 }
4509
4510 if(sldns_buffer_remaining(buf) < 1) {
4511 verbose(VERB_ALGO, "http chunkline: "
4512 "line too long");
4513 return 0;
4514 }
4515 sldns_buffer_write_u8_at(buf, sldns_buffer_position(buf), 0);
4516 sldns_buffer_flip(buf);
4517 return 1;
4518 }
4519
4520 /** process $ORIGIN for http, 0 nothing, 1 done, 2 error */
4521 static int
http_parse_origin(sldns_buffer * buf,struct sldns_file_parse_state * pstate)4522 http_parse_origin(sldns_buffer* buf, struct sldns_file_parse_state* pstate)
4523 {
4524 char* line = (char*)sldns_buffer_begin(buf);
4525 if(strncmp(line, "$ORIGIN", 7) == 0 &&
4526 isspace((unsigned char)line[7])) {
4527 int s;
4528 pstate->origin_len = sizeof(pstate->origin);
4529 s = sldns_str2wire_dname_buf(sldns_strip_ws(line+8),
4530 pstate->origin, &pstate->origin_len);
4531 if(s) {
4532 pstate->origin_len = 0;
4533 return 2;
4534 }
4535 return 1;
4536 }
4537 return 0;
4538 }
4539
4540 /** process $TTL for http, 0 nothing, 1 done, 2 error */
4541 static int
http_parse_ttl(sldns_buffer * buf,struct sldns_file_parse_state * pstate)4542 http_parse_ttl(sldns_buffer* buf, struct sldns_file_parse_state* pstate)
4543 {
4544 char* line = (char*)sldns_buffer_begin(buf);
4545 if(strncmp(line, "$TTL", 4) == 0 &&
4546 isspace((unsigned char)line[4])) {
4547 const char* end = NULL;
4548 int overflow = 0;
4549 pstate->default_ttl = sldns_str2period(
4550 sldns_strip_ws(line+5), &end, &overflow);
4551 if(overflow) {
4552 return 2;
4553 }
4554 return 1;
4555 }
4556 return 0;
4557 }
4558
4559 /** find noncomment RR line in chunks, collates lines if ( ) format */
4560 static int
chunkline_non_comment_RR(struct auth_chunk ** chunk,size_t * chunk_pos,sldns_buffer * buf,struct sldns_file_parse_state * pstate)4561 chunkline_non_comment_RR(struct auth_chunk** chunk, size_t* chunk_pos,
4562 sldns_buffer* buf, struct sldns_file_parse_state* pstate)
4563 {
4564 int ret;
4565 while(chunkline_get_line_collated(chunk, chunk_pos, buf)) {
4566 if(chunkline_is_comment_line_or_empty(buf)) {
4567 /* a comment, go to next line */
4568 continue;
4569 }
4570 if((ret=http_parse_origin(buf, pstate))!=0) {
4571 if(ret == 2)
4572 return 0;
4573 continue; /* $ORIGIN has been handled */
4574 }
4575 if((ret=http_parse_ttl(buf, pstate))!=0) {
4576 if(ret == 2)
4577 return 0;
4578 continue; /* $TTL has been handled */
4579 }
4580 return 1;
4581 }
4582 /* no noncomments, fail */
4583 return 0;
4584 }
4585
4586 /** check syntax of chunklist zonefile, parse first RR, return false on
4587 * failure and return a string in the scratch buffer (first RR string)
4588 * on failure. */
4589 static int
http_zonefile_syntax_check(struct auth_xfer * xfr,sldns_buffer * buf)4590 http_zonefile_syntax_check(struct auth_xfer* xfr, sldns_buffer* buf)
4591 {
4592 uint8_t rr[LDNS_RR_BUF_SIZE];
4593 size_t rr_len, dname_len = 0;
4594 struct sldns_file_parse_state pstate;
4595 struct auth_chunk* chunk;
4596 size_t chunk_pos;
4597 int e;
4598 memset(&pstate, 0, sizeof(pstate));
4599 pstate.default_ttl = 3600;
4600 if(xfr->namelen < sizeof(pstate.origin)) {
4601 pstate.origin_len = xfr->namelen;
4602 memmove(pstate.origin, xfr->name, xfr->namelen);
4603 }
4604 chunk = xfr->task_transfer->chunks_first;
4605 chunk_pos = 0;
4606 if(!chunkline_non_comment_RR(&chunk, &chunk_pos, buf, &pstate)) {
4607 return 0;
4608 }
4609 rr_len = sizeof(rr);
4610 e=sldns_str2wire_rr_buf((char*)sldns_buffer_begin(buf), rr, &rr_len,
4611 &dname_len, pstate.default_ttl,
4612 pstate.origin_len?pstate.origin:NULL, pstate.origin_len,
4613 pstate.prev_rr_len?pstate.prev_rr:NULL, pstate.prev_rr_len);
4614 if(e != 0) {
4615 log_err("parse failure on first RR[%d]: %s",
4616 LDNS_WIREPARSE_OFFSET(e),
4617 sldns_get_errorstr_parse(LDNS_WIREPARSE_ERROR(e)));
4618 return 0;
4619 }
4620 /* check that class is correct */
4621 if(sldns_wirerr_get_class(rr, rr_len, dname_len) != xfr->dclass) {
4622 log_err("parse failure: first record in downloaded zonefile "
4623 "from wrong RR class");
4624 return 0;
4625 }
4626 return 1;
4627 }
4628
4629 /** sum sizes of chunklist */
4630 static size_t
chunklist_sum(struct auth_chunk * list)4631 chunklist_sum(struct auth_chunk* list)
4632 {
4633 struct auth_chunk* p;
4634 size_t s = 0;
4635 for(p=list; p; p=p->next) {
4636 s += p->len;
4637 }
4638 return s;
4639 }
4640
4641 /** remove newlines from collated line */
4642 static void
chunkline_newline_removal(sldns_buffer * buf)4643 chunkline_newline_removal(sldns_buffer* buf)
4644 {
4645 size_t i, end=sldns_buffer_limit(buf);
4646 for(i=0; i<end; i++) {
4647 char c = (char)sldns_buffer_read_u8_at(buf, i);
4648 if(c == '\n' && i==end-1) {
4649 sldns_buffer_write_u8_at(buf, i, 0);
4650 sldns_buffer_set_limit(buf, end-1);
4651 return;
4652 }
4653 if(c == '\n')
4654 sldns_buffer_write_u8_at(buf, i, (uint8_t)' ');
4655 }
4656 }
4657
4658 /** for http download, parse and add RR to zone */
4659 static int
http_parse_add_rr(struct auth_xfer * xfr,struct auth_zone * z,sldns_buffer * buf,struct sldns_file_parse_state * pstate)4660 http_parse_add_rr(struct auth_xfer* xfr, struct auth_zone* z,
4661 sldns_buffer* buf, struct sldns_file_parse_state* pstate)
4662 {
4663 uint8_t rr[LDNS_RR_BUF_SIZE];
4664 size_t rr_len, dname_len = 0;
4665 int e;
4666 char* line = (char*)sldns_buffer_begin(buf);
4667 rr_len = sizeof(rr);
4668 e = sldns_str2wire_rr_buf(line, rr, &rr_len, &dname_len,
4669 pstate->default_ttl,
4670 pstate->origin_len?pstate->origin:NULL, pstate->origin_len,
4671 pstate->prev_rr_len?pstate->prev_rr:NULL, pstate->prev_rr_len);
4672 if(e != 0) {
4673 log_err("%s/%s parse failure RR[%d]: %s in '%s'",
4674 xfr->task_transfer->master->host,
4675 xfr->task_transfer->master->file,
4676 LDNS_WIREPARSE_OFFSET(e),
4677 sldns_get_errorstr_parse(LDNS_WIREPARSE_ERROR(e)),
4678 line);
4679 return 0;
4680 }
4681 if(rr_len == 0)
4682 return 1; /* empty line or so */
4683
4684 /* set prev */
4685 if(dname_len < sizeof(pstate->prev_rr)) {
4686 memmove(pstate->prev_rr, rr, dname_len);
4687 pstate->prev_rr_len = dname_len;
4688 }
4689
4690 return az_insert_rr(z, rr, rr_len, dname_len, NULL);
4691 }
4692
4693 /** RR list iterator, returns RRs from answer section one by one from the
4694 * dns packets in the chunklist */
4695 static void
chunk_rrlist_start(struct auth_xfer * xfr,struct auth_chunk ** rr_chunk,int * rr_num,size_t * rr_pos)4696 chunk_rrlist_start(struct auth_xfer* xfr, struct auth_chunk** rr_chunk,
4697 int* rr_num, size_t* rr_pos)
4698 {
4699 *rr_chunk = xfr->task_transfer->chunks_first;
4700 *rr_num = 0;
4701 *rr_pos = 0;
4702 }
4703
4704 /** RR list iterator, see if we are at the end of the list */
4705 static int
chunk_rrlist_end(struct auth_chunk * rr_chunk,int rr_num)4706 chunk_rrlist_end(struct auth_chunk* rr_chunk, int rr_num)
4707 {
4708 while(rr_chunk) {
4709 if(rr_chunk->len < LDNS_HEADER_SIZE)
4710 return 1;
4711 if(rr_num < (int)LDNS_ANCOUNT(rr_chunk->data))
4712 return 0;
4713 /* no more RRs in this chunk */
4714 /* continue with next chunk, see if it has RRs */
4715 rr_chunk = rr_chunk->next;
4716 rr_num = 0;
4717 }
4718 return 1;
4719 }
4720
4721 /** RR list iterator, move to next RR */
4722 static void
chunk_rrlist_gonext(struct auth_chunk ** rr_chunk,int * rr_num,size_t * rr_pos,size_t rr_nextpos)4723 chunk_rrlist_gonext(struct auth_chunk** rr_chunk, int* rr_num,
4724 size_t* rr_pos, size_t rr_nextpos)
4725 {
4726 /* already at end of chunks? */
4727 if(!*rr_chunk)
4728 return;
4729 /* move within this chunk */
4730 if((*rr_chunk)->len >= LDNS_HEADER_SIZE &&
4731 (*rr_num)+1 < (int)LDNS_ANCOUNT((*rr_chunk)->data)) {
4732 (*rr_num) += 1;
4733 *rr_pos = rr_nextpos;
4734 return;
4735 }
4736 /* no more RRs in this chunk */
4737 /* continue with next chunk, see if it has RRs */
4738 if(*rr_chunk)
4739 *rr_chunk = (*rr_chunk)->next;
4740 while(*rr_chunk) {
4741 *rr_num = 0;
4742 *rr_pos = 0;
4743 if((*rr_chunk)->len >= LDNS_HEADER_SIZE &&
4744 LDNS_ANCOUNT((*rr_chunk)->data) > 0) {
4745 return;
4746 }
4747 *rr_chunk = (*rr_chunk)->next;
4748 }
4749 }
4750
4751 /** RR iterator, get current RR information, false on parse error */
4752 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)4753 chunk_rrlist_get_current(struct auth_chunk* rr_chunk, int rr_num,
4754 size_t rr_pos, uint8_t** rr_dname, uint16_t* rr_type,
4755 uint16_t* rr_class, uint32_t* rr_ttl, uint16_t* rr_rdlen,
4756 uint8_t** rr_rdata, size_t* rr_nextpos)
4757 {
4758 sldns_buffer pkt;
4759 /* integrity checks on position */
4760 if(!rr_chunk) return 0;
4761 if(rr_chunk->len < LDNS_HEADER_SIZE) return 0;
4762 if(rr_num >= (int)LDNS_ANCOUNT(rr_chunk->data)) return 0;
4763 if(rr_pos >= rr_chunk->len) return 0;
4764
4765 /* fetch rr information */
4766 sldns_buffer_init_frm_data(&pkt, rr_chunk->data, rr_chunk->len);
4767 if(rr_pos == 0) {
4768 size_t i;
4769 /* skip question section */
4770 sldns_buffer_set_position(&pkt, LDNS_HEADER_SIZE);
4771 for(i=0; i<LDNS_QDCOUNT(rr_chunk->data); i++) {
4772 if(pkt_dname_len(&pkt) == 0) return 0;
4773 if(sldns_buffer_remaining(&pkt) < 4) return 0;
4774 sldns_buffer_skip(&pkt, 4); /* type and class */
4775 }
4776 } else {
4777 sldns_buffer_set_position(&pkt, rr_pos);
4778 }
4779 *rr_dname = sldns_buffer_current(&pkt);
4780 if(pkt_dname_len(&pkt) == 0) return 0;
4781 if(sldns_buffer_remaining(&pkt) < 10) return 0;
4782 *rr_type = sldns_buffer_read_u16(&pkt);
4783 *rr_class = sldns_buffer_read_u16(&pkt);
4784 *rr_ttl = sldns_buffer_read_u32(&pkt);
4785 *rr_rdlen = sldns_buffer_read_u16(&pkt);
4786 if(sldns_buffer_remaining(&pkt) < (*rr_rdlen)) return 0;
4787 *rr_rdata = sldns_buffer_current(&pkt);
4788 sldns_buffer_skip(&pkt, (ssize_t)(*rr_rdlen));
4789 *rr_nextpos = sldns_buffer_position(&pkt);
4790 return 1;
4791 }
4792
4793 /** print log message where we are in parsing the zone transfer */
4794 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)4795 log_rrlist_position(const char* label, struct auth_chunk* rr_chunk,
4796 uint8_t* rr_dname, uint16_t rr_type, size_t rr_counter)
4797 {
4798 sldns_buffer pkt;
4799 size_t dlen;
4800 uint8_t buf[LDNS_MAX_DOMAINLEN];
4801 char str[LDNS_MAX_DOMAINLEN];
4802 char typestr[32];
4803 sldns_buffer_init_frm_data(&pkt, rr_chunk->data, rr_chunk->len);
4804 sldns_buffer_set_position(&pkt, (size_t)(rr_dname -
4805 sldns_buffer_begin(&pkt)));
4806 if((dlen=pkt_dname_len(&pkt)) == 0) return;
4807 if(dlen >= sizeof(buf)) return;
4808 dname_pkt_copy(&pkt, buf, rr_dname);
4809 dname_str(buf, str);
4810 (void)sldns_wire2str_type_buf(rr_type, typestr, sizeof(typestr));
4811 verbose(VERB_ALGO, "%s at[%d] %s %s", label, (int)rr_counter,
4812 str, typestr);
4813 }
4814
4815 /** check that start serial is OK for ixfr. we are at rr_counter == 0,
4816 * and we are going to check rr_counter == 1 (has to be type SOA) serial */
4817 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)4818 ixfr_start_serial(struct auth_chunk* rr_chunk, int rr_num, size_t rr_pos,
4819 uint8_t* rr_dname, uint16_t rr_type, uint16_t rr_class,
4820 uint32_t rr_ttl, uint16_t rr_rdlen, uint8_t* rr_rdata,
4821 size_t rr_nextpos, uint32_t transfer_serial, uint32_t xfr_serial)
4822 {
4823 uint32_t startserial;
4824 /* move forward on RR */
4825 chunk_rrlist_gonext(&rr_chunk, &rr_num, &rr_pos, rr_nextpos);
4826 if(chunk_rrlist_end(rr_chunk, rr_num)) {
4827 /* no second SOA */
4828 verbose(VERB_OPS, "IXFR has no second SOA record");
4829 return 0;
4830 }
4831 if(!chunk_rrlist_get_current(rr_chunk, rr_num, rr_pos,
4832 &rr_dname, &rr_type, &rr_class, &rr_ttl, &rr_rdlen,
4833 &rr_rdata, &rr_nextpos)) {
4834 verbose(VERB_OPS, "IXFR cannot parse second SOA record");
4835 /* failed to parse RR */
4836 return 0;
4837 }
4838 if(rr_type != LDNS_RR_TYPE_SOA) {
4839 verbose(VERB_OPS, "IXFR second record is not type SOA");
4840 return 0;
4841 }
4842 if(rr_rdlen < 22) {
4843 verbose(VERB_OPS, "IXFR, second SOA has short rdlength");
4844 return 0; /* bad SOA rdlen */
4845 }
4846 startserial = sldns_read_uint32(rr_rdata+rr_rdlen-20);
4847 if(startserial == transfer_serial) {
4848 /* empty AXFR, not an IXFR */
4849 verbose(VERB_OPS, "IXFR second serial same as first");
4850 return 0;
4851 }
4852 if(startserial != xfr_serial) {
4853 /* wrong start serial, it does not match the serial in
4854 * memory */
4855 verbose(VERB_OPS, "IXFR is from serial %u to %u but %u "
4856 "in memory, rejecting the zone transfer",
4857 (unsigned)startserial, (unsigned)transfer_serial,
4858 (unsigned)xfr_serial);
4859 return 0;
4860 }
4861 /* everything OK in second SOA serial */
4862 return 1;
4863 }
4864
4865 /** apply IXFR to zone in memory. z is locked. false on failure(mallocfail) */
4866 static int
apply_ixfr(struct auth_xfer * xfr,struct auth_zone * z,struct sldns_buffer * scratch_buffer)4867 apply_ixfr(struct auth_xfer* xfr, struct auth_zone* z,
4868 struct sldns_buffer* scratch_buffer)
4869 {
4870 struct auth_chunk* rr_chunk;
4871 int rr_num;
4872 size_t rr_pos;
4873 uint8_t* rr_dname, *rr_rdata;
4874 uint16_t rr_type, rr_class, rr_rdlen;
4875 uint32_t rr_ttl;
4876 size_t rr_nextpos;
4877 int have_transfer_serial = 0;
4878 uint32_t transfer_serial = 0;
4879 size_t rr_counter = 0;
4880 int delmode = 0;
4881 int softfail = 0;
4882
4883 /* start RR iterator over chunklist of packets */
4884 chunk_rrlist_start(xfr, &rr_chunk, &rr_num, &rr_pos);
4885 while(!chunk_rrlist_end(rr_chunk, rr_num)) {
4886 if(!chunk_rrlist_get_current(rr_chunk, rr_num, rr_pos,
4887 &rr_dname, &rr_type, &rr_class, &rr_ttl, &rr_rdlen,
4888 &rr_rdata, &rr_nextpos)) {
4889 /* failed to parse RR */
4890 return 0;
4891 }
4892 if(verbosity>=7) log_rrlist_position("apply ixfr",
4893 rr_chunk, rr_dname, rr_type, rr_counter);
4894 /* twiddle add/del mode and check for start and end */
4895 if(rr_counter == 0 && rr_type != LDNS_RR_TYPE_SOA)
4896 return 0;
4897 if(rr_counter == 1 && rr_type != LDNS_RR_TYPE_SOA) {
4898 /* this is an AXFR returned from the IXFR master */
4899 /* but that should already have been detected, by
4900 * on_ixfr_is_axfr */
4901 return 0;
4902 }
4903 if(rr_type == LDNS_RR_TYPE_SOA) {
4904 uint32_t serial;
4905 if(rr_rdlen < 22) return 0; /* bad SOA rdlen */
4906 serial = sldns_read_uint32(rr_rdata+rr_rdlen-20);
4907 if(have_transfer_serial == 0) {
4908 have_transfer_serial = 1;
4909 transfer_serial = serial;
4910 delmode = 1; /* gets negated below */
4911 /* check second RR before going any further */
4912 if(!ixfr_start_serial(rr_chunk, rr_num, rr_pos,
4913 rr_dname, rr_type, rr_class, rr_ttl,
4914 rr_rdlen, rr_rdata, rr_nextpos,
4915 transfer_serial, xfr->serial)) {
4916 return 0;
4917 }
4918 } else if(transfer_serial == serial) {
4919 have_transfer_serial++;
4920 if(rr_counter == 1) {
4921 /* empty AXFR, with SOA; SOA; */
4922 /* should have been detected by
4923 * on_ixfr_is_axfr */
4924 return 0;
4925 }
4926 if(have_transfer_serial == 3) {
4927 /* see serial three times for end */
4928 /* eg. IXFR:
4929 * SOA 3 start
4930 * SOA 1 second RR, followed by del
4931 * SOA 2 followed by add
4932 * SOA 2 followed by del
4933 * SOA 3 followed by add
4934 * SOA 3 end */
4935 /* ended by SOA record */
4936 xfr->serial = transfer_serial;
4937 break;
4938 }
4939 }
4940 /* twiddle add/del mode */
4941 /* switch from delete part to add part and back again
4942 * just before the soa, it gets deleted and added too
4943 * this means we switch to delete mode for the final
4944 * SOA(so skip that one) */
4945 delmode = !delmode;
4946 }
4947 /* process this RR */
4948 /* if the RR is deleted twice or added twice, then we
4949 * softfail, and continue with the rest of the IXFR, so
4950 * that we serve something fairly nice during the refetch */
4951 if(verbosity>=7) log_rrlist_position((delmode?"del":"add"),
4952 rr_chunk, rr_dname, rr_type, rr_counter);
4953 if(delmode) {
4954 /* delete this RR */
4955 int nonexist = 0;
4956 if(!az_remove_rr_decompress(z, rr_chunk->data,
4957 rr_chunk->len, scratch_buffer, rr_dname,
4958 rr_type, rr_class, rr_ttl, rr_rdata, rr_rdlen,
4959 &nonexist)) {
4960 /* failed, malloc error or so */
4961 return 0;
4962 }
4963 if(nonexist) {
4964 /* it was removal of a nonexisting RR */
4965 if(verbosity>=4) log_rrlist_position(
4966 "IXFR error nonexistent RR",
4967 rr_chunk, rr_dname, rr_type, rr_counter);
4968 softfail = 1;
4969 }
4970 } else if(rr_counter != 0) {
4971 /* skip first SOA RR for addition, it is added in
4972 * the addition part near the end of the ixfr, when
4973 * that serial is seen the second time. */
4974 int duplicate = 0;
4975 /* add this RR */
4976 if(!az_insert_rr_decompress(z, rr_chunk->data,
4977 rr_chunk->len, scratch_buffer, rr_dname,
4978 rr_type, rr_class, rr_ttl, rr_rdata, rr_rdlen,
4979 &duplicate)) {
4980 /* failed, malloc error or so */
4981 return 0;
4982 }
4983 if(duplicate) {
4984 /* it was a duplicate */
4985 if(verbosity>=4) log_rrlist_position(
4986 "IXFR error duplicate RR",
4987 rr_chunk, rr_dname, rr_type, rr_counter);
4988 softfail = 1;
4989 }
4990 }
4991
4992 rr_counter++;
4993 chunk_rrlist_gonext(&rr_chunk, &rr_num, &rr_pos, rr_nextpos);
4994 }
4995 if(softfail) {
4996 verbose(VERB_ALGO, "IXFR did not apply cleanly, fetching full zone");
4997 return 0;
4998 }
4999 return 1;
5000 }
5001
5002 /** apply AXFR to zone in memory. z is locked. false on failure(mallocfail) */
5003 static int
apply_axfr(struct auth_xfer * xfr,struct auth_zone * z,struct sldns_buffer * scratch_buffer)5004 apply_axfr(struct auth_xfer* xfr, struct auth_zone* z,
5005 struct sldns_buffer* scratch_buffer)
5006 {
5007 struct auth_chunk* rr_chunk;
5008 int rr_num;
5009 size_t rr_pos;
5010 uint8_t* rr_dname, *rr_rdata;
5011 uint16_t rr_type, rr_class, rr_rdlen;
5012 uint32_t rr_ttl;
5013 uint32_t serial = 0;
5014 size_t rr_nextpos;
5015 size_t rr_counter = 0;
5016 int have_end_soa = 0;
5017
5018 /* clear the data tree */
5019 traverse_postorder(&z->data, auth_data_del, NULL);
5020 rbtree_init(&z->data, &auth_data_cmp);
5021 /* clear the RPZ policies */
5022 if(z->rpz)
5023 rpz_clear(z->rpz);
5024
5025 xfr->have_zone = 0;
5026 xfr->serial = 0;
5027 xfr->soa_zone_acquired = 0;
5028
5029 /* insert all RRs in to the zone */
5030 /* insert the SOA only once, skip the last one */
5031 /* start RR iterator over chunklist of packets */
5032 chunk_rrlist_start(xfr, &rr_chunk, &rr_num, &rr_pos);
5033 while(!chunk_rrlist_end(rr_chunk, rr_num)) {
5034 if(!chunk_rrlist_get_current(rr_chunk, rr_num, rr_pos,
5035 &rr_dname, &rr_type, &rr_class, &rr_ttl, &rr_rdlen,
5036 &rr_rdata, &rr_nextpos)) {
5037 /* failed to parse RR */
5038 return 0;
5039 }
5040 if(verbosity>=7) log_rrlist_position("apply_axfr",
5041 rr_chunk, rr_dname, rr_type, rr_counter);
5042 if(rr_type == LDNS_RR_TYPE_SOA) {
5043 if(rr_counter != 0) {
5044 /* end of the axfr */
5045 have_end_soa = 1;
5046 break;
5047 }
5048 if(rr_rdlen < 22) return 0; /* bad SOA rdlen */
5049 serial = sldns_read_uint32(rr_rdata+rr_rdlen-20);
5050 }
5051
5052 /* add this RR */
5053 if(!az_insert_rr_decompress(z, rr_chunk->data, rr_chunk->len,
5054 scratch_buffer, rr_dname, rr_type, rr_class, rr_ttl,
5055 rr_rdata, rr_rdlen, NULL)) {
5056 /* failed, malloc error or so */
5057 return 0;
5058 }
5059
5060 rr_counter++;
5061 chunk_rrlist_gonext(&rr_chunk, &rr_num, &rr_pos, rr_nextpos);
5062 }
5063 if(!have_end_soa) {
5064 log_err("no end SOA record for AXFR");
5065 return 0;
5066 }
5067
5068 xfr->serial = serial;
5069 xfr->have_zone = 1;
5070 return 1;
5071 }
5072
5073 /** apply HTTP to zone in memory. z is locked. false on failure(mallocfail) */
5074 static int
apply_http(struct auth_xfer * xfr,struct auth_zone * z,struct sldns_buffer * scratch_buffer)5075 apply_http(struct auth_xfer* xfr, struct auth_zone* z,
5076 struct sldns_buffer* scratch_buffer)
5077 {
5078 /* parse data in chunks */
5079 /* parse RR's and read into memory. ignore $INCLUDE from the
5080 * downloaded file*/
5081 struct sldns_file_parse_state pstate;
5082 struct auth_chunk* chunk;
5083 size_t chunk_pos;
5084 int ret;
5085 memset(&pstate, 0, sizeof(pstate));
5086 pstate.default_ttl = 3600;
5087 if(xfr->namelen < sizeof(pstate.origin)) {
5088 pstate.origin_len = xfr->namelen;
5089 memmove(pstate.origin, xfr->name, xfr->namelen);
5090 }
5091
5092 if(verbosity >= VERB_ALGO)
5093 verbose(VERB_ALGO, "http download %s of size %d",
5094 xfr->task_transfer->master->file,
5095 (int)chunklist_sum(xfr->task_transfer->chunks_first));
5096 if(xfr->task_transfer->chunks_first && verbosity >= VERB_ALGO) {
5097 char preview[1024];
5098 if(xfr->task_transfer->chunks_first->len+1 > sizeof(preview)) {
5099 memmove(preview, xfr->task_transfer->chunks_first->data,
5100 sizeof(preview)-1);
5101 preview[sizeof(preview)-1]=0;
5102 } else {
5103 memmove(preview, xfr->task_transfer->chunks_first->data,
5104 xfr->task_transfer->chunks_first->len);
5105 preview[xfr->task_transfer->chunks_first->len]=0;
5106 }
5107 log_info("auth zone http downloaded content preview: %s",
5108 preview);
5109 }
5110
5111 /* perhaps a little syntax check before we try to apply the data? */
5112 if(!http_zonefile_syntax_check(xfr, scratch_buffer)) {
5113 log_err("http download %s/%s does not contain a zonefile, "
5114 "but got '%s'", xfr->task_transfer->master->host,
5115 xfr->task_transfer->master->file,
5116 sldns_buffer_begin(scratch_buffer));
5117 return 0;
5118 }
5119
5120 /* clear the data tree */
5121 traverse_postorder(&z->data, auth_data_del, NULL);
5122 rbtree_init(&z->data, &auth_data_cmp);
5123 /* clear the RPZ policies */
5124 if(z->rpz)
5125 rpz_clear(z->rpz);
5126
5127 xfr->have_zone = 0;
5128 xfr->serial = 0;
5129 xfr->soa_zone_acquired = 0;
5130
5131 chunk = xfr->task_transfer->chunks_first;
5132 chunk_pos = 0;
5133 pstate.lineno = 0;
5134 while(chunkline_get_line_collated(&chunk, &chunk_pos, scratch_buffer)) {
5135 /* process this line */
5136 pstate.lineno++;
5137 chunkline_newline_removal(scratch_buffer);
5138 if(chunkline_is_comment_line_or_empty(scratch_buffer)) {
5139 continue;
5140 }
5141 /* parse line and add RR */
5142 if((ret=http_parse_origin(scratch_buffer, &pstate))!=0) {
5143 if(ret == 2) {
5144 verbose(VERB_ALGO, "error parsing ORIGIN on line [%s:%d] %s",
5145 xfr->task_transfer->master->file,
5146 pstate.lineno,
5147 sldns_buffer_begin(scratch_buffer));
5148 return 0;
5149 }
5150 continue; /* $ORIGIN has been handled */
5151 }
5152 if((ret=http_parse_ttl(scratch_buffer, &pstate))!=0) {
5153 if(ret == 2) {
5154 verbose(VERB_ALGO, "error parsing TTL on line [%s:%d] %s",
5155 xfr->task_transfer->master->file,
5156 pstate.lineno,
5157 sldns_buffer_begin(scratch_buffer));
5158 return 0;
5159 }
5160 continue; /* $TTL has been handled */
5161 }
5162 if(!http_parse_add_rr(xfr, z, scratch_buffer, &pstate)) {
5163 verbose(VERB_ALGO, "error parsing line [%s:%d] %s",
5164 xfr->task_transfer->master->file,
5165 pstate.lineno,
5166 sldns_buffer_begin(scratch_buffer));
5167 return 0;
5168 }
5169 }
5170 return 1;
5171 }
5172
5173 /** write http chunks to zonefile to create downloaded file */
5174 static int
auth_zone_write_chunks(struct auth_xfer * xfr,const char * fname)5175 auth_zone_write_chunks(struct auth_xfer* xfr, const char* fname)
5176 {
5177 FILE* out;
5178 struct auth_chunk* p;
5179 out = fopen(fname, "w");
5180 if(!out) {
5181 log_err("could not open %s: %s", fname, strerror(errno));
5182 return 0;
5183 }
5184 for(p = xfr->task_transfer->chunks_first; p ; p = p->next) {
5185 if(!write_out(out, (char*)p->data, p->len)) {
5186 log_err("could not write http download to %s", fname);
5187 fclose(out);
5188 return 0;
5189 }
5190 }
5191 fclose(out);
5192 return 1;
5193 }
5194
5195 /** write to zonefile after zone has been updated */
5196 static void
xfr_write_after_update(struct auth_xfer * xfr,struct module_env * env)5197 xfr_write_after_update(struct auth_xfer* xfr, struct module_env* env)
5198 {
5199 struct config_file* cfg = env->cfg;
5200 struct auth_zone* z;
5201 char tmpfile[1024];
5202 char* zfilename;
5203 lock_basic_unlock(&xfr->lock);
5204
5205 /* get lock again, so it is a readlock and concurrently queries
5206 * can be answered */
5207 lock_rw_rdlock(&env->auth_zones->lock);
5208 z = auth_zone_find(env->auth_zones, xfr->name, xfr->namelen,
5209 xfr->dclass);
5210 if(!z) {
5211 lock_rw_unlock(&env->auth_zones->lock);
5212 /* the zone is gone, ignore xfr results */
5213 lock_basic_lock(&xfr->lock);
5214 return;
5215 }
5216 lock_rw_rdlock(&z->lock);
5217 lock_basic_lock(&xfr->lock);
5218 lock_rw_unlock(&env->auth_zones->lock);
5219
5220 if(z->zonefile == NULL || z->zonefile[0] == 0) {
5221 lock_rw_unlock(&z->lock);
5222 /* no write needed, no zonefile set */
5223 return;
5224 }
5225 zfilename = z->zonefile;
5226 if(cfg->chrootdir && cfg->chrootdir[0] && strncmp(zfilename,
5227 cfg->chrootdir, strlen(cfg->chrootdir)) == 0)
5228 zfilename += strlen(cfg->chrootdir);
5229 if(verbosity >= VERB_ALGO) {
5230 char nm[LDNS_MAX_DOMAINLEN];
5231 dname_str(z->name, nm);
5232 verbose(VERB_ALGO, "write zonefile %s for %s", zfilename, nm);
5233 }
5234
5235 /* write to tempfile first */
5236 if((size_t)strlen(zfilename) + 16 > sizeof(tmpfile)) {
5237 verbose(VERB_ALGO, "tmpfilename too long, cannot update "
5238 " zonefile %s", zfilename);
5239 lock_rw_unlock(&z->lock);
5240 return;
5241 }
5242 snprintf(tmpfile, sizeof(tmpfile), "%s.tmp%u", zfilename,
5243 (unsigned)getpid());
5244 if(xfr->task_transfer->master->http) {
5245 /* use the stored chunk list to write them */
5246 if(!auth_zone_write_chunks(xfr, tmpfile)) {
5247 unlink(tmpfile);
5248 lock_rw_unlock(&z->lock);
5249 return;
5250 }
5251 } else if(!auth_zone_write_file(z, tmpfile)) {
5252 unlink(tmpfile);
5253 lock_rw_unlock(&z->lock);
5254 return;
5255 }
5256 #ifdef UB_ON_WINDOWS
5257 (void)unlink(zfilename); /* windows does not replace file with rename() */
5258 #endif
5259 if(rename(tmpfile, zfilename) < 0) {
5260 log_err("could not rename(%s, %s): %s", tmpfile, zfilename,
5261 strerror(errno));
5262 unlink(tmpfile);
5263 lock_rw_unlock(&z->lock);
5264 return;
5265 }
5266 lock_rw_unlock(&z->lock);
5267 }
5268
5269 /** reacquire locks and structures. Starts with no locks, ends
5270 * 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)5271 static int xfr_process_reacquire_locks(struct auth_xfer* xfr,
5272 struct module_env* env, struct auth_zone** z)
5273 {
5274 /* release xfr lock, then, while holding az->lock grab both
5275 * z->lock and xfr->lock */
5276 lock_rw_rdlock(&env->auth_zones->lock);
5277 *z = auth_zone_find(env->auth_zones, xfr->name, xfr->namelen,
5278 xfr->dclass);
5279 if(!*z) {
5280 lock_rw_unlock(&env->auth_zones->lock);
5281 lock_basic_lock(&xfr->lock);
5282 *z = NULL;
5283 return 0;
5284 }
5285 lock_rw_wrlock(&(*z)->lock);
5286 lock_basic_lock(&xfr->lock);
5287 lock_rw_unlock(&env->auth_zones->lock);
5288 return 1;
5289 }
5290
5291 /** process chunk list and update zone in memory,
5292 * return false if it did not work */
5293 static int
xfr_process_chunk_list(struct auth_xfer * xfr,struct module_env * env,int * ixfr_fail)5294 xfr_process_chunk_list(struct auth_xfer* xfr, struct module_env* env,
5295 int* ixfr_fail)
5296 {
5297 struct auth_zone* z;
5298
5299 /* obtain locks and structures */
5300 lock_basic_unlock(&xfr->lock);
5301 if(!xfr_process_reacquire_locks(xfr, env, &z)) {
5302 /* the zone is gone, ignore xfr results */
5303 return 0;
5304 }
5305 /* holding xfr and z locks */
5306
5307 /* apply data */
5308 if(xfr->task_transfer->master->http) {
5309 if(!apply_http(xfr, z, env->scratch_buffer)) {
5310 lock_rw_unlock(&z->lock);
5311 verbose(VERB_ALGO, "http from %s: could not store data",
5312 xfr->task_transfer->master->host);
5313 return 0;
5314 }
5315 } else if(xfr->task_transfer->on_ixfr &&
5316 !xfr->task_transfer->on_ixfr_is_axfr) {
5317 if(!apply_ixfr(xfr, z, env->scratch_buffer)) {
5318 lock_rw_unlock(&z->lock);
5319 verbose(VERB_ALGO, "xfr from %s: could not store IXFR"
5320 " data", xfr->task_transfer->master->host);
5321 *ixfr_fail = 1;
5322 return 0;
5323 }
5324 } else {
5325 if(!apply_axfr(xfr, z, env->scratch_buffer)) {
5326 lock_rw_unlock(&z->lock);
5327 verbose(VERB_ALGO, "xfr from %s: could not store AXFR"
5328 " data", xfr->task_transfer->master->host);
5329 return 0;
5330 }
5331 }
5332 xfr->zone_expired = 0;
5333 z->zone_expired = 0;
5334 if(!xfr_find_soa(z, xfr)) {
5335 lock_rw_unlock(&z->lock);
5336 verbose(VERB_ALGO, "xfr from %s: no SOA in zone after update"
5337 " (or malformed RR)", xfr->task_transfer->master->host);
5338 return 0;
5339 }
5340 z->soa_zone_acquired = *env->now;
5341 xfr->soa_zone_acquired = *env->now;
5342
5343 /* release xfr lock while verifying zonemd because it may have
5344 * to spawn lookups in the state machines */
5345 lock_basic_unlock(&xfr->lock);
5346 /* holding z lock */
5347 auth_zone_verify_zonemd(z, env, &env->mesh->mods, NULL, 0, 0);
5348 if(z->zone_expired) {
5349 char zname[LDNS_MAX_DOMAINLEN];
5350 /* ZONEMD must have failed */
5351 /* reacquire locks, so we hold xfr lock on exit of routine,
5352 * and both xfr and z again after releasing xfr for potential
5353 * state machine mesh callbacks */
5354 lock_rw_unlock(&z->lock);
5355 if(!xfr_process_reacquire_locks(xfr, env, &z))
5356 return 0;
5357 dname_str(xfr->name, zname);
5358 verbose(VERB_ALGO, "xfr from %s: ZONEMD failed for %s, transfer is failed", xfr->task_transfer->master->host, zname);
5359 xfr->zone_expired = 1;
5360 lock_rw_unlock(&z->lock);
5361 return 0;
5362 }
5363 /* reacquire locks, so we hold xfr lock on exit of routine,
5364 * and both xfr and z again after releasing xfr for potential
5365 * state machine mesh callbacks */
5366 lock_rw_unlock(&z->lock);
5367 if(!xfr_process_reacquire_locks(xfr, env, &z))
5368 return 0;
5369 /* holding xfr and z locks */
5370
5371 if(xfr->have_zone)
5372 xfr->lease_time = *env->now;
5373
5374 if(z->rpz)
5375 rpz_finish_config(z->rpz);
5376
5377 /* unlock */
5378 lock_rw_unlock(&z->lock);
5379
5380 if(verbosity >= VERB_QUERY && xfr->have_zone) {
5381 char zname[LDNS_MAX_DOMAINLEN];
5382 dname_str(xfr->name, zname);
5383 verbose(VERB_QUERY, "auth zone %s updated to serial %u", zname,
5384 (unsigned)xfr->serial);
5385 }
5386 /* see if we need to write to a zonefile */
5387 xfr_write_after_update(xfr, env);
5388 return 1;
5389 }
5390
5391 /** disown task_transfer. caller must hold xfr.lock */
5392 static void
xfr_transfer_disown(struct auth_xfer * xfr)5393 xfr_transfer_disown(struct auth_xfer* xfr)
5394 {
5395 /* remove timer (from this worker's event base) */
5396 comm_timer_delete(xfr->task_transfer->timer);
5397 xfr->task_transfer->timer = NULL;
5398 /* remove the commpoint */
5399 comm_point_delete(xfr->task_transfer->cp);
5400 xfr->task_transfer->cp = NULL;
5401 /* we don't own this item anymore */
5402 xfr->task_transfer->worker = NULL;
5403 xfr->task_transfer->env = NULL;
5404 }
5405
5406 /** lookup a host name for its addresses, if needed */
5407 static int
xfr_transfer_lookup_host(struct auth_xfer * xfr,struct module_env * env)5408 xfr_transfer_lookup_host(struct auth_xfer* xfr, struct module_env* env)
5409 {
5410 struct sockaddr_storage addr;
5411 socklen_t addrlen = 0;
5412 struct auth_master* master = xfr->task_transfer->lookup_target;
5413 struct query_info qinfo;
5414 uint16_t qflags = BIT_RD;
5415 uint8_t dname[LDNS_MAX_DOMAINLEN+1];
5416 struct edns_data edns;
5417 sldns_buffer* buf = env->scratch_buffer;
5418 if(!master) return 0;
5419 if(extstrtoaddr(master->host, &addr, &addrlen, UNBOUND_DNS_PORT)) {
5420 /* not needed, host is in IP addr format */
5421 return 0;
5422 }
5423 if(master->allow_notify)
5424 return 0; /* allow-notifies are not transferred from, no
5425 lookup is needed */
5426
5427 /* use mesh_new_callback to probe for non-addr hosts,
5428 * and then wait for them to be looked up (in cache, or query) */
5429 qinfo.qname_len = sizeof(dname);
5430 if(sldns_str2wire_dname_buf(master->host, dname, &qinfo.qname_len)
5431 != 0) {
5432 log_err("cannot parse host name of master %s", master->host);
5433 return 0;
5434 }
5435 qinfo.qname = dname;
5436 qinfo.qclass = xfr->dclass;
5437 qinfo.qtype = LDNS_RR_TYPE_A;
5438 if(xfr->task_transfer->lookup_aaaa)
5439 qinfo.qtype = LDNS_RR_TYPE_AAAA;
5440 qinfo.local_alias = NULL;
5441 if(verbosity >= VERB_ALGO) {
5442 char buf1[512];
5443 char buf2[LDNS_MAX_DOMAINLEN];
5444 dname_str(xfr->name, buf2);
5445 snprintf(buf1, sizeof(buf1), "auth zone %s: master lookup"
5446 " for task_transfer", buf2);
5447 log_query_info(VERB_ALGO, buf1, &qinfo);
5448 }
5449 edns.edns_present = 1;
5450 edns.ext_rcode = 0;
5451 edns.edns_version = 0;
5452 edns.bits = EDNS_DO;
5453 edns.opt_list_in = NULL;
5454 edns.opt_list_out = NULL;
5455 edns.opt_list_inplace_cb_out = NULL;
5456 edns.padding_block_size = 0;
5457 edns.cookie_present = 0;
5458 edns.cookie_valid = 0;
5459 if(sldns_buffer_capacity(buf) < 65535)
5460 edns.udp_size = (uint16_t)sldns_buffer_capacity(buf);
5461 else edns.udp_size = 65535;
5462
5463 /* unlock xfr during mesh_new_callback() because the callback can be
5464 * called straight away */
5465 lock_basic_unlock(&xfr->lock);
5466 if(!mesh_new_callback(env->mesh, &qinfo, qflags, &edns, buf, 0,
5467 &auth_xfer_transfer_lookup_callback, xfr, 0)) {
5468 lock_basic_lock(&xfr->lock);
5469 log_err("out of memory lookup up master %s", master->host);
5470 return 0;
5471 }
5472 lock_basic_lock(&xfr->lock);
5473 return 1;
5474 }
5475
5476 /** initiate TCP to the target and fetch zone.
5477 * returns true if that was successfully started, and timeout setup. */
5478 static int
xfr_transfer_init_fetch(struct auth_xfer * xfr,struct module_env * env)5479 xfr_transfer_init_fetch(struct auth_xfer* xfr, struct module_env* env)
5480 {
5481 struct sockaddr_storage addr;
5482 socklen_t addrlen = 0;
5483 struct auth_master* master = xfr->task_transfer->master;
5484 char *auth_name = NULL;
5485 struct timeval t;
5486 int timeout;
5487 if(!master) return 0;
5488 if(master->allow_notify) return 0; /* only for notify */
5489
5490 /* get master addr */
5491 if(xfr->task_transfer->scan_addr) {
5492 addrlen = xfr->task_transfer->scan_addr->addrlen;
5493 memmove(&addr, &xfr->task_transfer->scan_addr->addr, addrlen);
5494 } else {
5495 if(!authextstrtoaddr(master->host, &addr, &addrlen, &auth_name)) {
5496 /* the ones that are not in addr format are supposed
5497 * to be looked up. The lookup has failed however,
5498 * so skip them */
5499 char zname[LDNS_MAX_DOMAINLEN];
5500 dname_str(xfr->name, zname);
5501 log_err("%s: failed lookup, cannot transfer from master %s",
5502 zname, master->host);
5503 return 0;
5504 }
5505 }
5506
5507 /* remove previous TCP connection (if any) */
5508 if(xfr->task_transfer->cp) {
5509 comm_point_delete(xfr->task_transfer->cp);
5510 xfr->task_transfer->cp = NULL;
5511 }
5512 if(!xfr->task_transfer->timer) {
5513 xfr->task_transfer->timer = comm_timer_create(env->worker_base,
5514 auth_xfer_transfer_timer_callback, xfr);
5515 if(!xfr->task_transfer->timer) {
5516 log_err("malloc failure");
5517 return 0;
5518 }
5519 }
5520 timeout = AUTH_TRANSFER_TIMEOUT;
5521 #ifndef S_SPLINT_S
5522 t.tv_sec = timeout/1000;
5523 t.tv_usec = (timeout%1000)*1000;
5524 #endif
5525
5526 if(master->http) {
5527 /* perform http fetch */
5528 /* store http port number into sockaddr,
5529 * unless someone used unbound's host@port notation */
5530 xfr->task_transfer->on_ixfr = 0;
5531 if(strchr(master->host, '@') == NULL)
5532 sockaddr_store_port(&addr, addrlen, master->port);
5533 xfr->task_transfer->cp = outnet_comm_point_for_http(
5534 env->outnet, auth_xfer_transfer_http_callback, xfr,
5535 &addr, addrlen, -1, master->ssl, master->host,
5536 master->file, env->cfg);
5537 if(!xfr->task_transfer->cp) {
5538 char zname[LDNS_MAX_DOMAINLEN], as[256];
5539 dname_str(xfr->name, zname);
5540 addr_port_to_str(&addr, addrlen, as, sizeof(as));
5541 verbose(VERB_ALGO, "cannot create http cp "
5542 "connection for %s to %s", zname, as);
5543 return 0;
5544 }
5545 comm_timer_set(xfr->task_transfer->timer, &t);
5546 if(verbosity >= VERB_ALGO) {
5547 char zname[LDNS_MAX_DOMAINLEN], as[256];
5548 dname_str(xfr->name, zname);
5549 addr_port_to_str(&addr, addrlen, as, sizeof(as));
5550 verbose(VERB_ALGO, "auth zone %s transfer next HTTP fetch from %s started", zname, as);
5551 }
5552 /* Create or refresh the list of allow_notify addrs */
5553 probe_copy_masters_for_allow_notify(xfr);
5554 return 1;
5555 }
5556
5557 /* perform AXFR/IXFR */
5558 /* set the packet to be written */
5559 /* create new ID */
5560 xfr->task_transfer->id = GET_RANDOM_ID(env->rnd);
5561 xfr_create_ixfr_packet(xfr, env->scratch_buffer,
5562 xfr->task_transfer->id, master);
5563
5564 /* connect on fd */
5565 xfr->task_transfer->cp = outnet_comm_point_for_tcp(env->outnet,
5566 auth_xfer_transfer_tcp_callback, xfr, &addr, addrlen,
5567 env->scratch_buffer, -1,
5568 auth_name != NULL, auth_name);
5569 if(!xfr->task_transfer->cp) {
5570 char zname[LDNS_MAX_DOMAINLEN], as[256];
5571 dname_str(xfr->name, zname);
5572 addr_port_to_str(&addr, addrlen, as, sizeof(as));
5573 verbose(VERB_ALGO, "cannot create tcp cp connection for "
5574 "xfr %s to %s", zname, as);
5575 return 0;
5576 }
5577 comm_timer_set(xfr->task_transfer->timer, &t);
5578 if(verbosity >= VERB_ALGO) {
5579 char zname[LDNS_MAX_DOMAINLEN], as[256];
5580 dname_str(xfr->name, zname);
5581 addr_port_to_str(&addr, addrlen, as, sizeof(as));
5582 verbose(VERB_ALGO, "auth zone %s transfer next %s fetch from %s started", zname,
5583 (xfr->task_transfer->on_ixfr?"IXFR":"AXFR"), as);
5584 }
5585 return 1;
5586 }
5587
5588 /** perform next lookup, next transfer TCP, or end and resume wait time task */
5589 static void
xfr_transfer_nexttarget_or_end(struct auth_xfer * xfr,struct module_env * env)5590 xfr_transfer_nexttarget_or_end(struct auth_xfer* xfr, struct module_env* env)
5591 {
5592 log_assert(xfr->task_transfer->worker == env->worker);
5593
5594 /* are we performing lookups? */
5595 while(xfr->task_transfer->lookup_target) {
5596 if(xfr_transfer_lookup_host(xfr, env)) {
5597 /* wait for lookup to finish,
5598 * note that the hostname may be in unbound's cache
5599 * and we may then get an instant cache response,
5600 * and that calls the callback just like a full
5601 * lookup and lookup failures also call callback */
5602 if(verbosity >= VERB_ALGO) {
5603 char zname[LDNS_MAX_DOMAINLEN];
5604 dname_str(xfr->name, zname);
5605 verbose(VERB_ALGO, "auth zone %s transfer next target lookup", zname);
5606 }
5607 lock_basic_unlock(&xfr->lock);
5608 return;
5609 }
5610 xfr_transfer_move_to_next_lookup(xfr, env);
5611 }
5612
5613 /* initiate TCP and fetch the zone from the master */
5614 /* and set timeout on it */
5615 while(!xfr_transfer_end_of_list(xfr)) {
5616 xfr->task_transfer->master = xfr_transfer_current_master(xfr);
5617 if(xfr_transfer_init_fetch(xfr, env)) {
5618 /* successfully started, wait for callback */
5619 lock_basic_unlock(&xfr->lock);
5620 return;
5621 }
5622 /* failed to fetch, next master */
5623 xfr_transfer_nextmaster(xfr);
5624 }
5625 if(verbosity >= VERB_ALGO) {
5626 char zname[LDNS_MAX_DOMAINLEN];
5627 dname_str(xfr->name, zname);
5628 verbose(VERB_ALGO, "auth zone %s transfer failed, wait", zname);
5629 }
5630
5631 /* we failed to fetch the zone, move to wait task
5632 * use the shorter retry timeout */
5633 xfr_transfer_disown(xfr);
5634
5635 /* pick up the nextprobe task and wait */
5636 if(xfr->task_nextprobe->worker == NULL)
5637 xfr_set_timeout(xfr, env, 1, 0);
5638 lock_basic_unlock(&xfr->lock);
5639 }
5640
5641 /** add addrs from A or AAAA rrset to the master */
5642 static void
xfr_master_add_addrs(struct auth_master * m,struct ub_packed_rrset_key * rrset,uint16_t rrtype)5643 xfr_master_add_addrs(struct auth_master* m, struct ub_packed_rrset_key* rrset,
5644 uint16_t rrtype)
5645 {
5646 size_t i;
5647 struct packed_rrset_data* data;
5648 if(!m || !rrset) return;
5649 if(rrtype != LDNS_RR_TYPE_A && rrtype != LDNS_RR_TYPE_AAAA)
5650 return;
5651 data = (struct packed_rrset_data*)rrset->entry.data;
5652 for(i=0; i<data->count; i++) {
5653 struct auth_addr* a;
5654 size_t len = data->rr_len[i] - 2;
5655 uint8_t* rdata = data->rr_data[i]+2;
5656 if(rrtype == LDNS_RR_TYPE_A && len != INET_SIZE)
5657 continue; /* wrong length for A */
5658 if(rrtype == LDNS_RR_TYPE_AAAA && len != INET6_SIZE)
5659 continue; /* wrong length for AAAA */
5660
5661 /* add and alloc it */
5662 a = (struct auth_addr*)calloc(1, sizeof(*a));
5663 if(!a) {
5664 log_err("out of memory");
5665 return;
5666 }
5667 if(rrtype == LDNS_RR_TYPE_A) {
5668 struct sockaddr_in* sa;
5669 a->addrlen = (socklen_t)sizeof(*sa);
5670 sa = (struct sockaddr_in*)&a->addr;
5671 sa->sin_family = AF_INET;
5672 sa->sin_port = (in_port_t)htons(UNBOUND_DNS_PORT);
5673 memmove(&sa->sin_addr, rdata, INET_SIZE);
5674 } else {
5675 struct sockaddr_in6* sa;
5676 a->addrlen = (socklen_t)sizeof(*sa);
5677 sa = (struct sockaddr_in6*)&a->addr;
5678 sa->sin6_family = AF_INET6;
5679 sa->sin6_port = (in_port_t)htons(UNBOUND_DNS_PORT);
5680 memmove(&sa->sin6_addr, rdata, INET6_SIZE);
5681 }
5682 if(verbosity >= VERB_ALGO) {
5683 char s[64];
5684 addr_port_to_str(&a->addr, a->addrlen, s, sizeof(s));
5685 verbose(VERB_ALGO, "auth host %s lookup %s",
5686 m->host, s);
5687 }
5688 /* append to list */
5689 a->next = m->list;
5690 m->list = a;
5691 }
5692 }
5693
5694 /** 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))5695 void auth_xfer_transfer_lookup_callback(void* arg, int rcode, sldns_buffer* buf,
5696 enum sec_status ATTR_UNUSED(sec), char* ATTR_UNUSED(why_bogus),
5697 int ATTR_UNUSED(was_ratelimited))
5698 {
5699 struct auth_xfer* xfr = (struct auth_xfer*)arg;
5700 struct module_env* env;
5701 log_assert(xfr->task_transfer);
5702 lock_basic_lock(&xfr->lock);
5703 env = xfr->task_transfer->env;
5704 if(!env || env->outnet->want_to_quit) {
5705 lock_basic_unlock(&xfr->lock);
5706 return; /* stop on quit */
5707 }
5708
5709 /* process result */
5710 if(rcode == LDNS_RCODE_NOERROR) {
5711 uint16_t wanted_qtype = LDNS_RR_TYPE_A;
5712 struct regional* temp = env->scratch;
5713 struct query_info rq;
5714 struct reply_info* rep;
5715 if(xfr->task_transfer->lookup_aaaa)
5716 wanted_qtype = LDNS_RR_TYPE_AAAA;
5717 memset(&rq, 0, sizeof(rq));
5718 rep = parse_reply_in_temp_region(buf, temp, &rq);
5719 if(rep && rq.qtype == wanted_qtype &&
5720 FLAGS_GET_RCODE(rep->flags) == LDNS_RCODE_NOERROR) {
5721 /* parsed successfully */
5722 struct ub_packed_rrset_key* answer =
5723 reply_find_answer_rrset(&rq, rep);
5724 if(answer) {
5725 xfr_master_add_addrs(xfr->task_transfer->
5726 lookup_target, answer, wanted_qtype);
5727 } else {
5728 if(verbosity >= VERB_ALGO) {
5729 char zname[LDNS_MAX_DOMAINLEN];
5730 dname_str(xfr->name, zname);
5731 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"));
5732 }
5733 }
5734 } else {
5735 if(verbosity >= VERB_ALGO) {
5736 char zname[LDNS_MAX_DOMAINLEN];
5737 dname_str(xfr->name, zname);
5738 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"));
5739 }
5740 }
5741 regional_free_all(temp);
5742 } else {
5743 if(verbosity >= VERB_ALGO) {
5744 char zname[LDNS_MAX_DOMAINLEN];
5745 dname_str(xfr->name, zname);
5746 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"));
5747 }
5748 }
5749 if(xfr->task_transfer->lookup_target->list &&
5750 xfr->task_transfer->lookup_target == xfr_transfer_current_master(xfr))
5751 xfr->task_transfer->scan_addr = xfr->task_transfer->lookup_target->list;
5752
5753 /* move to lookup AAAA after A lookup, move to next hostname lookup,
5754 * or move to fetch the zone, or, if nothing to do, end task_transfer */
5755 xfr_transfer_move_to_next_lookup(xfr, env);
5756 xfr_transfer_nexttarget_or_end(xfr, env);
5757 }
5758
5759 /** check if xfer (AXFR or IXFR) packet is OK.
5760 * return false if we lost connection (SERVFAIL, or unreadable).
5761 * return false if we need to move from IXFR to AXFR, with gonextonfail
5762 * set to false, so the same master is tried again, but with AXFR.
5763 * return true if fine to link into data.
5764 * return true with transferdone=true when the transfer has ended.
5765 */
5766 static int
check_xfer_packet(sldns_buffer * pkt,struct auth_xfer * xfr,int * gonextonfail,int * transferdone)5767 check_xfer_packet(sldns_buffer* pkt, struct auth_xfer* xfr,
5768 int* gonextonfail, int* transferdone)
5769 {
5770 uint8_t* wire = sldns_buffer_begin(pkt);
5771 int i;
5772 if(sldns_buffer_limit(pkt) < LDNS_HEADER_SIZE) {
5773 verbose(VERB_ALGO, "xfr to %s failed, packet too small",
5774 xfr->task_transfer->master->host);
5775 return 0;
5776 }
5777 if(!LDNS_QR_WIRE(wire)) {
5778 verbose(VERB_ALGO, "xfr to %s failed, packet has no QR flag",
5779 xfr->task_transfer->master->host);
5780 return 0;
5781 }
5782 if(LDNS_TC_WIRE(wire)) {
5783 verbose(VERB_ALGO, "xfr to %s failed, packet has TC flag",
5784 xfr->task_transfer->master->host);
5785 return 0;
5786 }
5787 /* check ID */
5788 if(LDNS_ID_WIRE(wire) != xfr->task_transfer->id) {
5789 verbose(VERB_ALGO, "xfr to %s failed, packet wrong ID",
5790 xfr->task_transfer->master->host);
5791 return 0;
5792 }
5793 if(LDNS_RCODE_WIRE(wire) != LDNS_RCODE_NOERROR) {
5794 char rcode[32];
5795 sldns_wire2str_rcode_buf((int)LDNS_RCODE_WIRE(wire), rcode,
5796 sizeof(rcode));
5797 /* if we are doing IXFR, check for fallback */
5798 if(xfr->task_transfer->on_ixfr) {
5799 if(LDNS_RCODE_WIRE(wire) == LDNS_RCODE_NOTIMPL ||
5800 LDNS_RCODE_WIRE(wire) == LDNS_RCODE_SERVFAIL ||
5801 LDNS_RCODE_WIRE(wire) == LDNS_RCODE_REFUSED ||
5802 LDNS_RCODE_WIRE(wire) == LDNS_RCODE_FORMERR) {
5803 verbose(VERB_ALGO, "xfr to %s, fallback "
5804 "from IXFR to AXFR (with rcode %s)",
5805 xfr->task_transfer->master->host,
5806 rcode);
5807 xfr->task_transfer->ixfr_fail = 1;
5808 *gonextonfail = 0;
5809 return 0;
5810 }
5811 }
5812 verbose(VERB_ALGO, "xfr to %s failed, packet with rcode %s",
5813 xfr->task_transfer->master->host, rcode);
5814 return 0;
5815 }
5816 if(LDNS_OPCODE_WIRE(wire) != LDNS_PACKET_QUERY) {
5817 verbose(VERB_ALGO, "xfr to %s failed, packet with bad opcode",
5818 xfr->task_transfer->master->host);
5819 return 0;
5820 }
5821 if(LDNS_QDCOUNT(wire) > 1) {
5822 verbose(VERB_ALGO, "xfr to %s failed, packet has qdcount %d",
5823 xfr->task_transfer->master->host,
5824 (int)LDNS_QDCOUNT(wire));
5825 return 0;
5826 }
5827
5828 /* check qname */
5829 sldns_buffer_set_position(pkt, LDNS_HEADER_SIZE);
5830 for(i=0; i<(int)LDNS_QDCOUNT(wire); i++) {
5831 size_t pos = sldns_buffer_position(pkt);
5832 uint16_t qtype, qclass;
5833 if(pkt_dname_len(pkt) == 0) {
5834 verbose(VERB_ALGO, "xfr to %s failed, packet with "
5835 "malformed dname",
5836 xfr->task_transfer->master->host);
5837 return 0;
5838 }
5839 if(dname_pkt_compare(pkt, sldns_buffer_at(pkt, pos),
5840 xfr->name) != 0) {
5841 verbose(VERB_ALGO, "xfr to %s failed, packet with "
5842 "wrong qname",
5843 xfr->task_transfer->master->host);
5844 return 0;
5845 }
5846 if(sldns_buffer_remaining(pkt) < 4) {
5847 verbose(VERB_ALGO, "xfr to %s failed, packet with "
5848 "truncated query RR",
5849 xfr->task_transfer->master->host);
5850 return 0;
5851 }
5852 qtype = sldns_buffer_read_u16(pkt);
5853 qclass = sldns_buffer_read_u16(pkt);
5854 if(qclass != xfr->dclass) {
5855 verbose(VERB_ALGO, "xfr to %s failed, packet with "
5856 "wrong qclass",
5857 xfr->task_transfer->master->host);
5858 return 0;
5859 }
5860 if(xfr->task_transfer->on_ixfr) {
5861 if(qtype != LDNS_RR_TYPE_IXFR) {
5862 verbose(VERB_ALGO, "xfr to %s failed, packet "
5863 "with wrong qtype, expected IXFR",
5864 xfr->task_transfer->master->host);
5865 return 0;
5866 }
5867 } else {
5868 if(qtype != LDNS_RR_TYPE_AXFR) {
5869 verbose(VERB_ALGO, "xfr to %s failed, packet "
5870 "with wrong qtype, expected AXFR",
5871 xfr->task_transfer->master->host);
5872 return 0;
5873 }
5874 }
5875 }
5876
5877 /* check parse of RRs in packet, store first SOA serial
5878 * to be able to detect last SOA (with that serial) to see if done */
5879 /* also check for IXFR 'zone up to date' reply */
5880 for(i=0; i<(int)LDNS_ANCOUNT(wire); i++) {
5881 size_t pos = sldns_buffer_position(pkt);
5882 uint16_t tp, rdlen;
5883 if(pkt_dname_len(pkt) == 0) {
5884 verbose(VERB_ALGO, "xfr to %s failed, packet with "
5885 "malformed dname in answer section",
5886 xfr->task_transfer->master->host);
5887 return 0;
5888 }
5889 if(sldns_buffer_remaining(pkt) < 10) {
5890 verbose(VERB_ALGO, "xfr to %s failed, packet with "
5891 "truncated RR",
5892 xfr->task_transfer->master->host);
5893 return 0;
5894 }
5895 tp = sldns_buffer_read_u16(pkt);
5896 (void)sldns_buffer_read_u16(pkt); /* class */
5897 (void)sldns_buffer_read_u32(pkt); /* ttl */
5898 rdlen = sldns_buffer_read_u16(pkt);
5899 if(sldns_buffer_remaining(pkt) < rdlen) {
5900 verbose(VERB_ALGO, "xfr to %s failed, packet with "
5901 "truncated RR rdata",
5902 xfr->task_transfer->master->host);
5903 return 0;
5904 }
5905
5906 /* RR parses (haven't checked rdata itself), now look at
5907 * SOA records to see serial number */
5908 if(xfr->task_transfer->rr_scan_num == 0 &&
5909 tp != LDNS_RR_TYPE_SOA) {
5910 verbose(VERB_ALGO, "xfr to %s failed, packet with "
5911 "malformed zone transfer, no start SOA",
5912 xfr->task_transfer->master->host);
5913 return 0;
5914 }
5915 if(xfr->task_transfer->rr_scan_num == 1 &&
5916 tp != LDNS_RR_TYPE_SOA) {
5917 /* second RR is not a SOA record, this is not an IXFR
5918 * the master is replying with an AXFR */
5919 xfr->task_transfer->on_ixfr_is_axfr = 1;
5920 }
5921 if(tp == LDNS_RR_TYPE_SOA) {
5922 uint32_t serial;
5923 if(rdlen < 22) {
5924 verbose(VERB_ALGO, "xfr to %s failed, packet "
5925 "with SOA with malformed rdata",
5926 xfr->task_transfer->master->host);
5927 return 0;
5928 }
5929 if(dname_pkt_compare(pkt, sldns_buffer_at(pkt, pos),
5930 xfr->name) != 0) {
5931 verbose(VERB_ALGO, "xfr to %s failed, packet "
5932 "with SOA with wrong dname",
5933 xfr->task_transfer->master->host);
5934 return 0;
5935 }
5936
5937 /* read serial number of SOA */
5938 serial = sldns_buffer_read_u32_at(pkt,
5939 sldns_buffer_position(pkt)+rdlen-20);
5940
5941 /* check for IXFR 'zone has SOA x' reply */
5942 if(xfr->task_transfer->on_ixfr &&
5943 xfr->task_transfer->rr_scan_num == 0 &&
5944 LDNS_ANCOUNT(wire)==1) {
5945 verbose(VERB_ALGO, "xfr to %s ended, "
5946 "IXFR reply that zone has serial %u,"
5947 " fallback from IXFR to AXFR",
5948 xfr->task_transfer->master->host,
5949 (unsigned)serial);
5950 xfr->task_transfer->ixfr_fail = 1;
5951 *gonextonfail = 0;
5952 return 0;
5953 }
5954
5955 /* if first SOA, store serial number */
5956 if(xfr->task_transfer->got_xfr_serial == 0) {
5957 xfr->task_transfer->got_xfr_serial = 1;
5958 xfr->task_transfer->incoming_xfr_serial =
5959 serial;
5960 verbose(VERB_ALGO, "xfr %s: contains "
5961 "SOA serial %u",
5962 xfr->task_transfer->master->host,
5963 (unsigned)serial);
5964 /* see if end of AXFR */
5965 } else if(!xfr->task_transfer->on_ixfr ||
5966 xfr->task_transfer->on_ixfr_is_axfr) {
5967 /* second SOA with serial is the end
5968 * for AXFR */
5969 *transferdone = 1;
5970 verbose(VERB_ALGO, "xfr %s: last AXFR packet",
5971 xfr->task_transfer->master->host);
5972 /* for IXFR, count SOA records with that serial */
5973 } else if(xfr->task_transfer->incoming_xfr_serial ==
5974 serial && xfr->task_transfer->got_xfr_serial
5975 == 1) {
5976 xfr->task_transfer->got_xfr_serial++;
5977 /* if not first soa, if serial==firstserial, the
5978 * third time we are at the end, for IXFR */
5979 } else if(xfr->task_transfer->incoming_xfr_serial ==
5980 serial && xfr->task_transfer->got_xfr_serial
5981 == 2) {
5982 verbose(VERB_ALGO, "xfr %s: last IXFR packet",
5983 xfr->task_transfer->master->host);
5984 *transferdone = 1;
5985 /* continue parse check, if that succeeds,
5986 * transfer is done */
5987 }
5988 }
5989 xfr->task_transfer->rr_scan_num++;
5990
5991 /* skip over RR rdata to go to the next RR */
5992 sldns_buffer_skip(pkt, (ssize_t)rdlen);
5993 }
5994
5995 /* check authority section */
5996 /* we skip over the RRs checking packet format */
5997 for(i=0; i<(int)LDNS_NSCOUNT(wire); i++) {
5998 uint16_t rdlen;
5999 if(pkt_dname_len(pkt) == 0) {
6000 verbose(VERB_ALGO, "xfr to %s failed, packet with "
6001 "malformed dname in authority section",
6002 xfr->task_transfer->master->host);
6003 return 0;
6004 }
6005 if(sldns_buffer_remaining(pkt) < 10) {
6006 verbose(VERB_ALGO, "xfr to %s failed, packet with "
6007 "truncated RR",
6008 xfr->task_transfer->master->host);
6009 return 0;
6010 }
6011 (void)sldns_buffer_read_u16(pkt); /* type */
6012 (void)sldns_buffer_read_u16(pkt); /* class */
6013 (void)sldns_buffer_read_u32(pkt); /* ttl */
6014 rdlen = sldns_buffer_read_u16(pkt);
6015 if(sldns_buffer_remaining(pkt) < rdlen) {
6016 verbose(VERB_ALGO, "xfr to %s failed, packet with "
6017 "truncated RR rdata",
6018 xfr->task_transfer->master->host);
6019 return 0;
6020 }
6021 /* skip over RR rdata to go to the next RR */
6022 sldns_buffer_skip(pkt, (ssize_t)rdlen);
6023 }
6024
6025 /* check additional section */
6026 for(i=0; i<(int)LDNS_ARCOUNT(wire); i++) {
6027 uint16_t rdlen;
6028 if(pkt_dname_len(pkt) == 0) {
6029 verbose(VERB_ALGO, "xfr to %s failed, packet with "
6030 "malformed dname in additional section",
6031 xfr->task_transfer->master->host);
6032 return 0;
6033 }
6034 if(sldns_buffer_remaining(pkt) < 10) {
6035 verbose(VERB_ALGO, "xfr to %s failed, packet with "
6036 "truncated RR",
6037 xfr->task_transfer->master->host);
6038 return 0;
6039 }
6040 (void)sldns_buffer_read_u16(pkt); /* type */
6041 (void)sldns_buffer_read_u16(pkt); /* class */
6042 (void)sldns_buffer_read_u32(pkt); /* ttl */
6043 rdlen = sldns_buffer_read_u16(pkt);
6044 if(sldns_buffer_remaining(pkt) < rdlen) {
6045 verbose(VERB_ALGO, "xfr to %s failed, packet with "
6046 "truncated RR rdata",
6047 xfr->task_transfer->master->host);
6048 return 0;
6049 }
6050 /* skip over RR rdata to go to the next RR */
6051 sldns_buffer_skip(pkt, (ssize_t)rdlen);
6052 }
6053
6054 return 1;
6055 }
6056
6057 /** Link the data from this packet into the worklist of transferred data */
6058 static int
xfer_link_data(sldns_buffer * pkt,struct auth_xfer * xfr)6059 xfer_link_data(sldns_buffer* pkt, struct auth_xfer* xfr)
6060 {
6061 /* alloc it */
6062 struct auth_chunk* e;
6063 e = (struct auth_chunk*)calloc(1, sizeof(*e));
6064 if(!e) return 0;
6065 e->next = NULL;
6066 e->len = sldns_buffer_limit(pkt);
6067 e->data = memdup(sldns_buffer_begin(pkt), e->len);
6068 if(!e->data) {
6069 free(e);
6070 return 0;
6071 }
6072
6073 /* alloc succeeded, link into list */
6074 if(!xfr->task_transfer->chunks_first)
6075 xfr->task_transfer->chunks_first = e;
6076 if(xfr->task_transfer->chunks_last)
6077 xfr->task_transfer->chunks_last->next = e;
6078 xfr->task_transfer->chunks_last = e;
6079 return 1;
6080 }
6081
6082 /** task transfer. the list of data is complete. process it and if failed
6083 * move to next master, if succeeded, end the task transfer */
6084 static void
process_list_end_transfer(struct auth_xfer * xfr,struct module_env * env)6085 process_list_end_transfer(struct auth_xfer* xfr, struct module_env* env)
6086 {
6087 int ixfr_fail = 0;
6088 if(xfr_process_chunk_list(xfr, env, &ixfr_fail)) {
6089 /* it worked! */
6090 auth_chunks_delete(xfr->task_transfer);
6091
6092 /* we fetched the zone, move to wait task */
6093 xfr_transfer_disown(xfr);
6094
6095 if(xfr->notify_received && (!xfr->notify_has_serial ||
6096 (xfr->notify_has_serial &&
6097 xfr_serial_means_update(xfr, xfr->notify_serial)))) {
6098 uint32_t sr = xfr->notify_serial;
6099 int has_sr = xfr->notify_has_serial;
6100 /* we received a notify while probe/transfer was
6101 * in progress. start a new probe and transfer */
6102 xfr->notify_received = 0;
6103 xfr->notify_has_serial = 0;
6104 xfr->notify_serial = 0;
6105 if(!xfr_start_probe(xfr, env, NULL)) {
6106 /* if we couldn't start it, already in
6107 * progress; restore notify serial,
6108 * while xfr still locked */
6109 xfr->notify_received = 1;
6110 xfr->notify_has_serial = has_sr;
6111 xfr->notify_serial = sr;
6112 lock_basic_unlock(&xfr->lock);
6113 }
6114 return;
6115 } else {
6116 /* pick up the nextprobe task and wait (normail wait time) */
6117 if(xfr->task_nextprobe->worker == NULL)
6118 xfr_set_timeout(xfr, env, 0, 0);
6119 }
6120 lock_basic_unlock(&xfr->lock);
6121 return;
6122 }
6123 /* processing failed */
6124 /* when done, delete data from list */
6125 auth_chunks_delete(xfr->task_transfer);
6126 if(ixfr_fail) {
6127 xfr->task_transfer->ixfr_fail = 1;
6128 } else {
6129 xfr_transfer_nextmaster(xfr);
6130 }
6131 xfr_transfer_nexttarget_or_end(xfr, env);
6132 }
6133
6134 /** callback for the task_transfer timer */
6135 void
auth_xfer_transfer_timer_callback(void * arg)6136 auth_xfer_transfer_timer_callback(void* arg)
6137 {
6138 struct auth_xfer* xfr = (struct auth_xfer*)arg;
6139 struct module_env* env;
6140 int gonextonfail = 1;
6141 log_assert(xfr->task_transfer);
6142 lock_basic_lock(&xfr->lock);
6143 env = xfr->task_transfer->env;
6144 if(!env || env->outnet->want_to_quit) {
6145 lock_basic_unlock(&xfr->lock);
6146 return; /* stop on quit */
6147 }
6148
6149 verbose(VERB_ALGO, "xfr stopped, connection timeout to %s",
6150 xfr->task_transfer->master->host);
6151
6152 /* see if IXFR caused the failure, if so, try AXFR */
6153 if(xfr->task_transfer->on_ixfr) {
6154 xfr->task_transfer->ixfr_possible_timeout_count++;
6155 if(xfr->task_transfer->ixfr_possible_timeout_count >=
6156 NUM_TIMEOUTS_FALLBACK_IXFR) {
6157 verbose(VERB_ALGO, "xfr to %s, fallback "
6158 "from IXFR to AXFR (because of timeouts)",
6159 xfr->task_transfer->master->host);
6160 xfr->task_transfer->ixfr_fail = 1;
6161 gonextonfail = 0;
6162 }
6163 }
6164
6165 /* delete transferred data from list */
6166 auth_chunks_delete(xfr->task_transfer);
6167 comm_point_delete(xfr->task_transfer->cp);
6168 xfr->task_transfer->cp = NULL;
6169 if(gonextonfail)
6170 xfr_transfer_nextmaster(xfr);
6171 xfr_transfer_nexttarget_or_end(xfr, env);
6172 }
6173
6174 /** callback for task_transfer tcp connections */
6175 int
auth_xfer_transfer_tcp_callback(struct comm_point * c,void * arg,int err,struct comm_reply * ATTR_UNUSED (repinfo))6176 auth_xfer_transfer_tcp_callback(struct comm_point* c, void* arg, int err,
6177 struct comm_reply* ATTR_UNUSED(repinfo))
6178 {
6179 struct auth_xfer* xfr = (struct auth_xfer*)arg;
6180 struct module_env* env;
6181 int gonextonfail = 1;
6182 int transferdone = 0;
6183 log_assert(xfr->task_transfer);
6184 lock_basic_lock(&xfr->lock);
6185 env = xfr->task_transfer->env;
6186 if(!env || env->outnet->want_to_quit) {
6187 lock_basic_unlock(&xfr->lock);
6188 return 0; /* stop on quit */
6189 }
6190 /* stop the timer */
6191 comm_timer_disable(xfr->task_transfer->timer);
6192
6193 if(err != NETEVENT_NOERROR) {
6194 /* connection failed, closed, or timeout */
6195 /* stop this transfer, cleanup
6196 * and continue task_transfer*/
6197 verbose(VERB_ALGO, "xfr stopped, connection lost to %s",
6198 xfr->task_transfer->master->host);
6199
6200 /* see if IXFR caused the failure, if so, try AXFR */
6201 if(xfr->task_transfer->on_ixfr) {
6202 xfr->task_transfer->ixfr_possible_timeout_count++;
6203 if(xfr->task_transfer->ixfr_possible_timeout_count >=
6204 NUM_TIMEOUTS_FALLBACK_IXFR) {
6205 verbose(VERB_ALGO, "xfr to %s, fallback "
6206 "from IXFR to AXFR (because of timeouts)",
6207 xfr->task_transfer->master->host);
6208 xfr->task_transfer->ixfr_fail = 1;
6209 gonextonfail = 0;
6210 }
6211 }
6212
6213 failed:
6214 /* delete transferred data from list */
6215 auth_chunks_delete(xfr->task_transfer);
6216 comm_point_delete(xfr->task_transfer->cp);
6217 xfr->task_transfer->cp = NULL;
6218 if(gonextonfail)
6219 xfr_transfer_nextmaster(xfr);
6220 xfr_transfer_nexttarget_or_end(xfr, env);
6221 return 0;
6222 }
6223 /* note that IXFR worked without timeout */
6224 if(xfr->task_transfer->on_ixfr)
6225 xfr->task_transfer->ixfr_possible_timeout_count = 0;
6226
6227 /* handle returned packet */
6228 /* if it fails, cleanup and end this transfer */
6229 /* if it needs to fallback from IXFR to AXFR, do that */
6230 if(!check_xfer_packet(c->buffer, xfr, &gonextonfail, &transferdone)) {
6231 goto failed;
6232 }
6233 /* if it is good, link it into the list of data */
6234 /* if the link into list of data fails (malloc fail) cleanup and end */
6235 if(!xfer_link_data(c->buffer, xfr)) {
6236 verbose(VERB_ALGO, "xfr stopped to %s, malloc failed",
6237 xfr->task_transfer->master->host);
6238 goto failed;
6239 }
6240 /* if the transfer is done now, disconnect and process the list */
6241 if(transferdone) {
6242 comm_point_delete(xfr->task_transfer->cp);
6243 xfr->task_transfer->cp = NULL;
6244 process_list_end_transfer(xfr, env);
6245 return 0;
6246 }
6247
6248 /* if we want to read more messages, setup the commpoint to read
6249 * a DNS packet, and the timeout */
6250 lock_basic_unlock(&xfr->lock);
6251 c->tcp_is_reading = 1;
6252 sldns_buffer_clear(c->buffer);
6253 comm_point_start_listening(c, -1, AUTH_TRANSFER_TIMEOUT);
6254 return 0;
6255 }
6256
6257 /** callback for task_transfer http connections */
6258 int
auth_xfer_transfer_http_callback(struct comm_point * c,void * arg,int err,struct comm_reply * repinfo)6259 auth_xfer_transfer_http_callback(struct comm_point* c, void* arg, int err,
6260 struct comm_reply* repinfo)
6261 {
6262 struct auth_xfer* xfr = (struct auth_xfer*)arg;
6263 struct module_env* env;
6264 log_assert(xfr->task_transfer);
6265 lock_basic_lock(&xfr->lock);
6266 env = xfr->task_transfer->env;
6267 if(!env || env->outnet->want_to_quit) {
6268 lock_basic_unlock(&xfr->lock);
6269 return 0; /* stop on quit */
6270 }
6271 verbose(VERB_ALGO, "auth zone transfer http callback");
6272 /* stop the timer */
6273 comm_timer_disable(xfr->task_transfer->timer);
6274
6275 if(err != NETEVENT_NOERROR && err != NETEVENT_DONE) {
6276 /* connection failed, closed, or timeout */
6277 /* stop this transfer, cleanup
6278 * and continue task_transfer*/
6279 verbose(VERB_ALGO, "http stopped, connection lost to %s",
6280 xfr->task_transfer->master->host);
6281 failed:
6282 /* delete transferred data from list */
6283 auth_chunks_delete(xfr->task_transfer);
6284 if(repinfo) repinfo->c = NULL; /* signal cp deleted to
6285 the routine calling this callback */
6286 comm_point_delete(xfr->task_transfer->cp);
6287 xfr->task_transfer->cp = NULL;
6288 xfr_transfer_nextmaster(xfr);
6289 xfr_transfer_nexttarget_or_end(xfr, env);
6290 return 0;
6291 }
6292
6293 /* if it is good, link it into the list of data */
6294 /* if the link into list of data fails (malloc fail) cleanup and end */
6295 if(sldns_buffer_limit(c->buffer) > 0) {
6296 verbose(VERB_ALGO, "auth zone http queued up %d bytes",
6297 (int)sldns_buffer_limit(c->buffer));
6298 if(!xfer_link_data(c->buffer, xfr)) {
6299 verbose(VERB_ALGO, "http stopped to %s, malloc failed",
6300 xfr->task_transfer->master->host);
6301 goto failed;
6302 }
6303 }
6304 /* if the transfer is done now, disconnect and process the list */
6305 if(err == NETEVENT_DONE) {
6306 if(repinfo) repinfo->c = NULL; /* signal cp deleted to
6307 the routine calling this callback */
6308 comm_point_delete(xfr->task_transfer->cp);
6309 xfr->task_transfer->cp = NULL;
6310 process_list_end_transfer(xfr, env);
6311 return 0;
6312 }
6313
6314 /* if we want to read more messages, setup the commpoint to read
6315 * a DNS packet, and the timeout */
6316 lock_basic_unlock(&xfr->lock);
6317 c->tcp_is_reading = 1;
6318 sldns_buffer_clear(c->buffer);
6319 comm_point_start_listening(c, -1, AUTH_TRANSFER_TIMEOUT);
6320 return 0;
6321 }
6322
6323
6324 /** start transfer task by this worker , xfr is locked. */
6325 static void
xfr_start_transfer(struct auth_xfer * xfr,struct module_env * env,struct auth_master * master)6326 xfr_start_transfer(struct auth_xfer* xfr, struct module_env* env,
6327 struct auth_master* master)
6328 {
6329 log_assert(xfr->task_transfer != NULL);
6330 log_assert(xfr->task_transfer->worker == NULL);
6331 log_assert(xfr->task_transfer->chunks_first == NULL);
6332 log_assert(xfr->task_transfer->chunks_last == NULL);
6333 xfr->task_transfer->worker = env->worker;
6334 xfr->task_transfer->env = env;
6335
6336 /* init transfer process */
6337 /* find that master in the transfer's list of masters? */
6338 xfr_transfer_start_list(xfr, master);
6339 /* start lookup for hostnames in transfer master list */
6340 xfr_transfer_start_lookups(xfr);
6341
6342 /* initiate TCP, and set timeout on it */
6343 xfr_transfer_nexttarget_or_end(xfr, env);
6344 }
6345
6346 /** disown task_probe. caller must hold xfr.lock */
6347 static void
xfr_probe_disown(struct auth_xfer * xfr)6348 xfr_probe_disown(struct auth_xfer* xfr)
6349 {
6350 /* remove timer (from this worker's event base) */
6351 comm_timer_delete(xfr->task_probe->timer);
6352 xfr->task_probe->timer = NULL;
6353 /* remove the commpoint */
6354 comm_point_delete(xfr->task_probe->cp);
6355 xfr->task_probe->cp = NULL;
6356 /* we don't own this item anymore */
6357 xfr->task_probe->worker = NULL;
6358 xfr->task_probe->env = NULL;
6359 }
6360
6361 /** send the UDP probe to the master, this is part of task_probe */
6362 static int
xfr_probe_send_probe(struct auth_xfer * xfr,struct module_env * env,int timeout)6363 xfr_probe_send_probe(struct auth_xfer* xfr, struct module_env* env,
6364 int timeout)
6365 {
6366 struct sockaddr_storage addr;
6367 socklen_t addrlen = 0;
6368 struct timeval t;
6369 /* pick master */
6370 struct auth_master* master = xfr_probe_current_master(xfr);
6371 char *auth_name = NULL;
6372 if(!master) return 0;
6373 if(master->allow_notify) return 0; /* only for notify */
6374 if(master->http) return 0; /* only masters get SOA UDP probe,
6375 not urls, if those are in this list */
6376
6377 /* get master addr */
6378 if(xfr->task_probe->scan_addr) {
6379 addrlen = xfr->task_probe->scan_addr->addrlen;
6380 memmove(&addr, &xfr->task_probe->scan_addr->addr, addrlen);
6381 } else {
6382 if(!authextstrtoaddr(master->host, &addr, &addrlen, &auth_name)) {
6383 /* the ones that are not in addr format are supposed
6384 * to be looked up. The lookup has failed however,
6385 * so skip them */
6386 char zname[LDNS_MAX_DOMAINLEN];
6387 dname_str(xfr->name, zname);
6388 log_err("%s: failed lookup, cannot probe to master %s",
6389 zname, master->host);
6390 return 0;
6391 }
6392 if (auth_name != NULL) {
6393 if (addr.ss_family == AF_INET
6394 && (int)ntohs(((struct sockaddr_in *)&addr)->sin_port)
6395 == env->cfg->ssl_port)
6396 ((struct sockaddr_in *)&addr)->sin_port
6397 = htons((uint16_t)env->cfg->port);
6398 else if (addr.ss_family == AF_INET6
6399 && (int)ntohs(((struct sockaddr_in6 *)&addr)->sin6_port)
6400 == env->cfg->ssl_port)
6401 ((struct sockaddr_in6 *)&addr)->sin6_port
6402 = htons((uint16_t)env->cfg->port);
6403 }
6404 }
6405
6406 /* create packet */
6407 /* create new ID for new probes, but not on timeout retries,
6408 * this means we'll accept replies to previous retries to same ip */
6409 if(timeout == AUTH_PROBE_TIMEOUT)
6410 xfr->task_probe->id = GET_RANDOM_ID(env->rnd);
6411 xfr_create_soa_probe_packet(xfr, env->scratch_buffer,
6412 xfr->task_probe->id);
6413 /* we need to remove the cp if we have a different ip4/ip6 type now */
6414 if(xfr->task_probe->cp &&
6415 ((xfr->task_probe->cp_is_ip6 && !addr_is_ip6(&addr, addrlen)) ||
6416 (!xfr->task_probe->cp_is_ip6 && addr_is_ip6(&addr, addrlen)))
6417 ) {
6418 comm_point_delete(xfr->task_probe->cp);
6419 xfr->task_probe->cp = NULL;
6420 }
6421 if(!xfr->task_probe->cp) {
6422 if(addr_is_ip6(&addr, addrlen))
6423 xfr->task_probe->cp_is_ip6 = 1;
6424 else xfr->task_probe->cp_is_ip6 = 0;
6425 xfr->task_probe->cp = outnet_comm_point_for_udp(env->outnet,
6426 auth_xfer_probe_udp_callback, xfr, &addr, addrlen);
6427 if(!xfr->task_probe->cp) {
6428 char zname[LDNS_MAX_DOMAINLEN], as[256];
6429 dname_str(xfr->name, zname);
6430 addr_port_to_str(&addr, addrlen, as, sizeof(as));
6431 verbose(VERB_ALGO, "cannot create udp cp for "
6432 "probe %s to %s", zname, as);
6433 return 0;
6434 }
6435 }
6436 if(!xfr->task_probe->timer) {
6437 xfr->task_probe->timer = comm_timer_create(env->worker_base,
6438 auth_xfer_probe_timer_callback, xfr);
6439 if(!xfr->task_probe->timer) {
6440 log_err("malloc failure");
6441 return 0;
6442 }
6443 }
6444
6445 /* send udp packet */
6446 if(!comm_point_send_udp_msg(xfr->task_probe->cp, env->scratch_buffer,
6447 (struct sockaddr*)&addr, addrlen, 0)) {
6448 char zname[LDNS_MAX_DOMAINLEN], as[256];
6449 dname_str(xfr->name, zname);
6450 addr_port_to_str(&addr, addrlen, as, sizeof(as));
6451 verbose(VERB_ALGO, "failed to send soa probe for %s to %s",
6452 zname, as);
6453 return 0;
6454 }
6455 if(verbosity >= VERB_ALGO) {
6456 char zname[LDNS_MAX_DOMAINLEN], as[256];
6457 dname_str(xfr->name, zname);
6458 addr_port_to_str(&addr, addrlen, as, sizeof(as));
6459 verbose(VERB_ALGO, "auth zone %s soa probe sent to %s", zname,
6460 as);
6461 }
6462 xfr->task_probe->timeout = timeout;
6463 #ifndef S_SPLINT_S
6464 t.tv_sec = timeout/1000;
6465 t.tv_usec = (timeout%1000)*1000;
6466 #endif
6467 comm_timer_set(xfr->task_probe->timer, &t);
6468
6469 return 1;
6470 }
6471
6472 /** callback for task_probe timer */
6473 void
auth_xfer_probe_timer_callback(void * arg)6474 auth_xfer_probe_timer_callback(void* arg)
6475 {
6476 struct auth_xfer* xfr = (struct auth_xfer*)arg;
6477 struct module_env* env;
6478 log_assert(xfr->task_probe);
6479 lock_basic_lock(&xfr->lock);
6480 env = xfr->task_probe->env;
6481 if(!env || env->outnet->want_to_quit) {
6482 lock_basic_unlock(&xfr->lock);
6483 return; /* stop on quit */
6484 }
6485
6486 if(verbosity >= VERB_ALGO) {
6487 char zname[LDNS_MAX_DOMAINLEN];
6488 dname_str(xfr->name, zname);
6489 verbose(VERB_ALGO, "auth zone %s soa probe timeout", zname);
6490 }
6491 if(xfr->task_probe->timeout <= AUTH_PROBE_TIMEOUT_STOP) {
6492 /* try again with bigger timeout */
6493 if(xfr_probe_send_probe(xfr, env, xfr->task_probe->timeout*2)) {
6494 lock_basic_unlock(&xfr->lock);
6495 return;
6496 }
6497 }
6498 /* delete commpoint so a new one is created, with a fresh port nr */
6499 comm_point_delete(xfr->task_probe->cp);
6500 xfr->task_probe->cp = NULL;
6501
6502 /* too many timeouts (or fail to send), move to next or end */
6503 xfr_probe_nextmaster(xfr);
6504 xfr_probe_send_or_end(xfr, env);
6505 }
6506
6507 /** callback for task_probe udp packets */
6508 int
auth_xfer_probe_udp_callback(struct comm_point * c,void * arg,int err,struct comm_reply * repinfo)6509 auth_xfer_probe_udp_callback(struct comm_point* c, void* arg, int err,
6510 struct comm_reply* repinfo)
6511 {
6512 struct auth_xfer* xfr = (struct auth_xfer*)arg;
6513 struct module_env* env;
6514 log_assert(xfr->task_probe);
6515 lock_basic_lock(&xfr->lock);
6516 env = xfr->task_probe->env;
6517 if(!env || env->outnet->want_to_quit) {
6518 lock_basic_unlock(&xfr->lock);
6519 return 0; /* stop on quit */
6520 }
6521
6522 /* the comm_point_udp_callback is in a for loop for NUM_UDP_PER_SELECT
6523 * and we set rep.c=NULL to stop if from looking inside the commpoint*/
6524 repinfo->c = NULL;
6525 /* stop the timer */
6526 comm_timer_disable(xfr->task_probe->timer);
6527
6528 /* see if we got a packet and what that means */
6529 if(err == NETEVENT_NOERROR) {
6530 uint32_t serial = 0;
6531 if(check_packet_ok(c->buffer, LDNS_RR_TYPE_SOA, xfr,
6532 &serial)) {
6533 /* successful lookup */
6534 if(verbosity >= VERB_ALGO) {
6535 char buf[LDNS_MAX_DOMAINLEN];
6536 dname_str(xfr->name, buf);
6537 verbose(VERB_ALGO, "auth zone %s: soa probe "
6538 "serial is %u", buf, (unsigned)serial);
6539 }
6540 /* see if this serial indicates that the zone has
6541 * to be updated */
6542 if(xfr_serial_means_update(xfr, serial)) {
6543 /* if updated, start the transfer task, if needed */
6544 verbose(VERB_ALGO, "auth_zone updated, start transfer");
6545 if(xfr->task_transfer->worker == NULL) {
6546 struct auth_master* master =
6547 xfr_probe_current_master(xfr);
6548 /* if we have download URLs use them
6549 * in preference to this master we
6550 * just probed the SOA from */
6551 if(xfr->task_transfer->masters &&
6552 xfr->task_transfer->masters->http)
6553 master = NULL;
6554 xfr_probe_disown(xfr);
6555 xfr_start_transfer(xfr, env, master);
6556 return 0;
6557
6558 }
6559 /* other tasks are running, we don't do this anymore */
6560 xfr_probe_disown(xfr);
6561 lock_basic_unlock(&xfr->lock);
6562 /* return, we don't sent a reply to this udp packet,
6563 * and we setup the tasks to do next */
6564 return 0;
6565 } else {
6566 verbose(VERB_ALGO, "auth_zone master reports unchanged soa serial");
6567 /* we if cannot find updates amongst the
6568 * masters, this means we then have a new lease
6569 * on the zone */
6570 xfr->task_probe->have_new_lease = 1;
6571 }
6572 } else {
6573 if(verbosity >= VERB_ALGO) {
6574 char buf[LDNS_MAX_DOMAINLEN];
6575 dname_str(xfr->name, buf);
6576 verbose(VERB_ALGO, "auth zone %s: bad reply to soa probe", buf);
6577 }
6578 }
6579 } else {
6580 if(verbosity >= VERB_ALGO) {
6581 char buf[LDNS_MAX_DOMAINLEN];
6582 dname_str(xfr->name, buf);
6583 verbose(VERB_ALGO, "auth zone %s: soa probe failed", buf);
6584 }
6585 }
6586
6587 /* failed lookup or not an update */
6588 /* delete commpoint so a new one is created, with a fresh port nr */
6589 comm_point_delete(xfr->task_probe->cp);
6590 xfr->task_probe->cp = NULL;
6591
6592 /* if the result was not a successful probe, we need
6593 * to send the next one */
6594 xfr_probe_nextmaster(xfr);
6595 xfr_probe_send_or_end(xfr, env);
6596 return 0;
6597 }
6598
6599 /** lookup a host name for its addresses, if needed */
6600 static int
xfr_probe_lookup_host(struct auth_xfer * xfr,struct module_env * env)6601 xfr_probe_lookup_host(struct auth_xfer* xfr, struct module_env* env)
6602 {
6603 struct sockaddr_storage addr;
6604 socklen_t addrlen = 0;
6605 struct auth_master* master = xfr->task_probe->lookup_target;
6606 struct query_info qinfo;
6607 uint16_t qflags = BIT_RD;
6608 uint8_t dname[LDNS_MAX_DOMAINLEN+1];
6609 struct edns_data edns;
6610 sldns_buffer* buf = env->scratch_buffer;
6611 if(!master) return 0;
6612 if(extstrtoaddr(master->host, &addr, &addrlen, UNBOUND_DNS_PORT)) {
6613 /* not needed, host is in IP addr format */
6614 return 0;
6615 }
6616 if(master->allow_notify && !master->http &&
6617 strchr(master->host, '/') != NULL &&
6618 strchr(master->host, '/') == strrchr(master->host, '/')) {
6619 return 0; /* is IP/prefix format, not something to look up */
6620 }
6621
6622 /* use mesh_new_callback to probe for non-addr hosts,
6623 * and then wait for them to be looked up (in cache, or query) */
6624 qinfo.qname_len = sizeof(dname);
6625 if(sldns_str2wire_dname_buf(master->host, dname, &qinfo.qname_len)
6626 != 0) {
6627 log_err("cannot parse host name of master %s", master->host);
6628 return 0;
6629 }
6630 qinfo.qname = dname;
6631 qinfo.qclass = xfr->dclass;
6632 qinfo.qtype = LDNS_RR_TYPE_A;
6633 if(xfr->task_probe->lookup_aaaa)
6634 qinfo.qtype = LDNS_RR_TYPE_AAAA;
6635 qinfo.local_alias = NULL;
6636 if(verbosity >= VERB_ALGO) {
6637 char buf1[512];
6638 char buf2[LDNS_MAX_DOMAINLEN];
6639 dname_str(xfr->name, buf2);
6640 snprintf(buf1, sizeof(buf1), "auth zone %s: master lookup"
6641 " for task_probe", buf2);
6642 log_query_info(VERB_ALGO, buf1, &qinfo);
6643 }
6644 edns.edns_present = 1;
6645 edns.ext_rcode = 0;
6646 edns.edns_version = 0;
6647 edns.bits = EDNS_DO;
6648 edns.opt_list_in = NULL;
6649 edns.opt_list_out = NULL;
6650 edns.opt_list_inplace_cb_out = NULL;
6651 edns.padding_block_size = 0;
6652 edns.cookie_present = 0;
6653 edns.cookie_valid = 0;
6654 if(sldns_buffer_capacity(buf) < 65535)
6655 edns.udp_size = (uint16_t)sldns_buffer_capacity(buf);
6656 else edns.udp_size = 65535;
6657
6658 /* unlock xfr during mesh_new_callback() because the callback can be
6659 * called straight away */
6660 lock_basic_unlock(&xfr->lock);
6661 if(!mesh_new_callback(env->mesh, &qinfo, qflags, &edns, buf, 0,
6662 &auth_xfer_probe_lookup_callback, xfr, 0)) {
6663 lock_basic_lock(&xfr->lock);
6664 log_err("out of memory lookup up master %s", master->host);
6665 return 0;
6666 }
6667 lock_basic_lock(&xfr->lock);
6668 return 1;
6669 }
6670
6671 /** move to sending the probe packets, next if fails. task_probe */
6672 static void
xfr_probe_send_or_end(struct auth_xfer * xfr,struct module_env * env)6673 xfr_probe_send_or_end(struct auth_xfer* xfr, struct module_env* env)
6674 {
6675 /* are we doing hostname lookups? */
6676 while(xfr->task_probe->lookup_target) {
6677 if(xfr_probe_lookup_host(xfr, env)) {
6678 /* wait for lookup to finish,
6679 * note that the hostname may be in unbound's cache
6680 * and we may then get an instant cache response,
6681 * and that calls the callback just like a full
6682 * lookup and lookup failures also call callback */
6683 if(verbosity >= VERB_ALGO) {
6684 char zname[LDNS_MAX_DOMAINLEN];
6685 dname_str(xfr->name, zname);
6686 verbose(VERB_ALGO, "auth zone %s probe next target lookup", zname);
6687 }
6688 lock_basic_unlock(&xfr->lock);
6689 return;
6690 }
6691 xfr_probe_move_to_next_lookup(xfr, env);
6692 }
6693 /* probe of list has ended. Create or refresh the list of of
6694 * allow_notify addrs */
6695 probe_copy_masters_for_allow_notify(xfr);
6696 if(verbosity >= VERB_ALGO) {
6697 char zname[LDNS_MAX_DOMAINLEN];
6698 dname_str(xfr->name, zname);
6699 verbose(VERB_ALGO, "auth zone %s probe: notify addrs updated", zname);
6700 }
6701 if(xfr->task_probe->only_lookup) {
6702 /* only wanted lookups for copy, stop probe and start wait */
6703 xfr->task_probe->only_lookup = 0;
6704 if(verbosity >= VERB_ALGO) {
6705 char zname[LDNS_MAX_DOMAINLEN];
6706 dname_str(xfr->name, zname);
6707 verbose(VERB_ALGO, "auth zone %s probe: finished only_lookup", zname);
6708 }
6709 xfr_probe_disown(xfr);
6710 if(xfr->task_nextprobe->worker == NULL)
6711 xfr_set_timeout(xfr, env, 0, 0);
6712 lock_basic_unlock(&xfr->lock);
6713 return;
6714 }
6715
6716 /* send probe packets */
6717 while(!xfr_probe_end_of_list(xfr)) {
6718 if(xfr_probe_send_probe(xfr, env, AUTH_PROBE_TIMEOUT)) {
6719 /* successfully sent probe, wait for callback */
6720 lock_basic_unlock(&xfr->lock);
6721 return;
6722 }
6723 /* failed to send probe, next master */
6724 xfr_probe_nextmaster(xfr);
6725 }
6726
6727 /* done with probe sequence, wait */
6728 if(xfr->task_probe->have_new_lease) {
6729 /* if zone not updated, start the wait timer again */
6730 if(verbosity >= VERB_ALGO) {
6731 char zname[LDNS_MAX_DOMAINLEN];
6732 dname_str(xfr->name, zname);
6733 verbose(VERB_ALGO, "auth_zone %s unchanged, new lease, wait", zname);
6734 }
6735 xfr_probe_disown(xfr);
6736 if(xfr->have_zone)
6737 xfr->lease_time = *env->now;
6738 if(xfr->task_nextprobe->worker == NULL)
6739 xfr_set_timeout(xfr, env, 0, 0);
6740 } else {
6741 if(verbosity >= VERB_ALGO) {
6742 char zname[LDNS_MAX_DOMAINLEN];
6743 dname_str(xfr->name, zname);
6744 verbose(VERB_ALGO, "auth zone %s soa probe failed, wait to retry", zname);
6745 }
6746 /* we failed to send this as well, move to the wait task,
6747 * use the shorter retry timeout */
6748 xfr_probe_disown(xfr);
6749 /* pick up the nextprobe task and wait */
6750 if(xfr->task_nextprobe->worker == NULL)
6751 xfr_set_timeout(xfr, env, 1, 0);
6752 }
6753
6754 lock_basic_unlock(&xfr->lock);
6755 }
6756
6757 /** 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))6758 void auth_xfer_probe_lookup_callback(void* arg, int rcode, sldns_buffer* buf,
6759 enum sec_status ATTR_UNUSED(sec), char* ATTR_UNUSED(why_bogus),
6760 int ATTR_UNUSED(was_ratelimited))
6761 {
6762 struct auth_xfer* xfr = (struct auth_xfer*)arg;
6763 struct module_env* env;
6764 log_assert(xfr->task_probe);
6765 lock_basic_lock(&xfr->lock);
6766 env = xfr->task_probe->env;
6767 if(!env || env->outnet->want_to_quit) {
6768 lock_basic_unlock(&xfr->lock);
6769 return; /* stop on quit */
6770 }
6771
6772 /* process result */
6773 if(rcode == LDNS_RCODE_NOERROR) {
6774 uint16_t wanted_qtype = LDNS_RR_TYPE_A;
6775 struct regional* temp = env->scratch;
6776 struct query_info rq;
6777 struct reply_info* rep;
6778 if(xfr->task_probe->lookup_aaaa)
6779 wanted_qtype = LDNS_RR_TYPE_AAAA;
6780 memset(&rq, 0, sizeof(rq));
6781 rep = parse_reply_in_temp_region(buf, temp, &rq);
6782 if(rep && rq.qtype == wanted_qtype &&
6783 FLAGS_GET_RCODE(rep->flags) == LDNS_RCODE_NOERROR) {
6784 /* parsed successfully */
6785 struct ub_packed_rrset_key* answer =
6786 reply_find_answer_rrset(&rq, rep);
6787 if(answer) {
6788 xfr_master_add_addrs(xfr->task_probe->
6789 lookup_target, answer, wanted_qtype);
6790 } else {
6791 if(verbosity >= VERB_ALGO) {
6792 char zname[LDNS_MAX_DOMAINLEN];
6793 dname_str(xfr->name, zname);
6794 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"));
6795 }
6796 }
6797 } else {
6798 if(verbosity >= VERB_ALGO) {
6799 char zname[LDNS_MAX_DOMAINLEN];
6800 dname_str(xfr->name, zname);
6801 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"));
6802 }
6803 }
6804 regional_free_all(temp);
6805 } else {
6806 if(verbosity >= VERB_ALGO) {
6807 char zname[LDNS_MAX_DOMAINLEN];
6808 dname_str(xfr->name, zname);
6809 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"));
6810 }
6811 }
6812 if(xfr->task_probe->lookup_target->list &&
6813 xfr->task_probe->lookup_target == xfr_probe_current_master(xfr))
6814 xfr->task_probe->scan_addr = xfr->task_probe->lookup_target->list;
6815
6816 /* move to lookup AAAA after A lookup, move to next hostname lookup,
6817 * or move to send the probes, or, if nothing to do, end task_probe */
6818 xfr_probe_move_to_next_lookup(xfr, env);
6819 xfr_probe_send_or_end(xfr, env);
6820 }
6821
6822 /** disown task_nextprobe. caller must hold xfr.lock */
6823 static void
xfr_nextprobe_disown(struct auth_xfer * xfr)6824 xfr_nextprobe_disown(struct auth_xfer* xfr)
6825 {
6826 /* delete the timer, because the next worker to pick this up may
6827 * not have the same event base */
6828 comm_timer_delete(xfr->task_nextprobe->timer);
6829 xfr->task_nextprobe->timer = NULL;
6830 xfr->task_nextprobe->next_probe = 0;
6831 /* we don't own this item anymore */
6832 xfr->task_nextprobe->worker = NULL;
6833 xfr->task_nextprobe->env = NULL;
6834 }
6835
6836 /** xfer nextprobe timeout callback, this is part of task_nextprobe */
6837 void
auth_xfer_timer(void * arg)6838 auth_xfer_timer(void* arg)
6839 {
6840 struct auth_xfer* xfr = (struct auth_xfer*)arg;
6841 struct module_env* env;
6842 log_assert(xfr->task_nextprobe);
6843 lock_basic_lock(&xfr->lock);
6844 env = xfr->task_nextprobe->env;
6845 if(!env || env->outnet->want_to_quit) {
6846 lock_basic_unlock(&xfr->lock);
6847 return; /* stop on quit */
6848 }
6849
6850 /* see if zone has expired, and if so, also set auth_zone expired */
6851 if(xfr->have_zone && !xfr->zone_expired &&
6852 *env->now >= xfr->lease_time + xfr->expiry) {
6853 lock_basic_unlock(&xfr->lock);
6854 auth_xfer_set_expired(xfr, env, 1);
6855 lock_basic_lock(&xfr->lock);
6856 }
6857
6858 xfr_nextprobe_disown(xfr);
6859
6860 if(!xfr_start_probe(xfr, env, NULL)) {
6861 /* not started because already in progress */
6862 lock_basic_unlock(&xfr->lock);
6863 }
6864 }
6865
6866 /** return true if there are probe (SOA UDP query) targets in the master list*/
6867 static int
have_probe_targets(struct auth_master * list)6868 have_probe_targets(struct auth_master* list)
6869 {
6870 struct auth_master* p;
6871 for(p=list; p; p = p->next) {
6872 if(!p->allow_notify && p->host)
6873 return 1;
6874 }
6875 return 0;
6876 }
6877
6878 /** start task_probe if possible, if no masters for probe start task_transfer
6879 * returns true if task has been started, and false if the task is already
6880 * in progress. */
6881 static int
xfr_start_probe(struct auth_xfer * xfr,struct module_env * env,struct auth_master * spec)6882 xfr_start_probe(struct auth_xfer* xfr, struct module_env* env,
6883 struct auth_master* spec)
6884 {
6885 /* see if we need to start a probe (or maybe it is already in
6886 * progress (due to notify)) */
6887 if(xfr->task_probe->worker == NULL) {
6888 if(!have_probe_targets(xfr->task_probe->masters) &&
6889 !(xfr->task_probe->only_lookup &&
6890 xfr->task_probe->masters != NULL)) {
6891 /* useless to pick up task_probe, no masters to
6892 * probe. Instead attempt to pick up task transfer */
6893 if(xfr->task_transfer->worker == NULL) {
6894 xfr_start_transfer(xfr, env, spec);
6895 return 1;
6896 }
6897 /* task transfer already in progress */
6898 return 0;
6899 }
6900
6901 /* pick up the probe task ourselves */
6902 xfr->task_probe->worker = env->worker;
6903 xfr->task_probe->env = env;
6904 xfr->task_probe->cp = NULL;
6905
6906 /* start the task */
6907 /* have not seen a new lease yet, this scan */
6908 xfr->task_probe->have_new_lease = 0;
6909 /* if this was a timeout, no specific first master to scan */
6910 /* otherwise, spec is nonNULL the notified master, scan
6911 * first and also transfer first from it */
6912 xfr_probe_start_list(xfr, spec);
6913 /* setup to start the lookup of hostnames of masters afresh */
6914 xfr_probe_start_lookups(xfr);
6915 /* send the probe packet or next send, or end task */
6916 xfr_probe_send_or_end(xfr, env);
6917 return 1;
6918 }
6919 return 0;
6920 }
6921
6922 /** for task_nextprobe.
6923 * determine next timeout for auth_xfer. Also (re)sets timer.
6924 * @param xfr: task structure
6925 * @param env: module environment, with worker and time.
6926 * @param failure: set true if timer should be set for failure retry.
6927 * @param lookup_only: only perform lookups when timer done, 0 sec timeout
6928 */
6929 static void
xfr_set_timeout(struct auth_xfer * xfr,struct module_env * env,int failure,int lookup_only)6930 xfr_set_timeout(struct auth_xfer* xfr, struct module_env* env,
6931 int failure, int lookup_only)
6932 {
6933 struct timeval tv;
6934 log_assert(xfr->task_nextprobe != NULL);
6935 log_assert(xfr->task_nextprobe->worker == NULL ||
6936 xfr->task_nextprobe->worker == env->worker);
6937 /* normally, nextprobe = startoflease + refresh,
6938 * but if expiry is sooner, use that one.
6939 * after a failure, use the retry timer instead. */
6940 xfr->task_nextprobe->next_probe = *env->now;
6941 if(xfr->lease_time && !failure)
6942 xfr->task_nextprobe->next_probe = xfr->lease_time;
6943
6944 if(!failure) {
6945 xfr->task_nextprobe->backoff = 0;
6946 } else {
6947 if(xfr->task_nextprobe->backoff == 0)
6948 xfr->task_nextprobe->backoff = 3;
6949 else xfr->task_nextprobe->backoff *= 2;
6950 if(xfr->task_nextprobe->backoff > AUTH_TRANSFER_MAX_BACKOFF)
6951 xfr->task_nextprobe->backoff =
6952 AUTH_TRANSFER_MAX_BACKOFF;
6953 }
6954
6955 if(xfr->have_zone) {
6956 time_t wait = xfr->refresh;
6957 if(failure) wait = xfr->retry;
6958 if(xfr->expiry < wait)
6959 xfr->task_nextprobe->next_probe += xfr->expiry;
6960 else xfr->task_nextprobe->next_probe += wait;
6961 if(failure)
6962 xfr->task_nextprobe->next_probe +=
6963 xfr->task_nextprobe->backoff;
6964 /* put the timer exactly on expiry, if possible */
6965 if(xfr->lease_time && xfr->lease_time+xfr->expiry <
6966 xfr->task_nextprobe->next_probe &&
6967 xfr->lease_time+xfr->expiry > *env->now)
6968 xfr->task_nextprobe->next_probe =
6969 xfr->lease_time+xfr->expiry;
6970 } else {
6971 xfr->task_nextprobe->next_probe +=
6972 xfr->task_nextprobe->backoff;
6973 }
6974
6975 if(!xfr->task_nextprobe->timer) {
6976 xfr->task_nextprobe->timer = comm_timer_create(
6977 env->worker_base, auth_xfer_timer, xfr);
6978 if(!xfr->task_nextprobe->timer) {
6979 /* failed to malloc memory. likely zone transfer
6980 * also fails for that. skip the timeout */
6981 char zname[LDNS_MAX_DOMAINLEN];
6982 dname_str(xfr->name, zname);
6983 log_err("cannot allocate timer, no refresh for %s",
6984 zname);
6985 return;
6986 }
6987 }
6988 xfr->task_nextprobe->worker = env->worker;
6989 xfr->task_nextprobe->env = env;
6990 if(*(xfr->task_nextprobe->env->now) <= xfr->task_nextprobe->next_probe)
6991 tv.tv_sec = xfr->task_nextprobe->next_probe -
6992 *(xfr->task_nextprobe->env->now);
6993 else tv.tv_sec = 0;
6994 if(tv.tv_sec != 0 && lookup_only && xfr->task_probe->masters) {
6995 /* don't lookup_only, if lookup timeout is 0 anyway,
6996 * or if we don't have masters to lookup */
6997 tv.tv_sec = 0;
6998 if(xfr->task_probe->worker == NULL)
6999 xfr->task_probe->only_lookup = 1;
7000 }
7001 if(verbosity >= VERB_ALGO) {
7002 char zname[LDNS_MAX_DOMAINLEN];
7003 dname_str(xfr->name, zname);
7004 verbose(VERB_ALGO, "auth zone %s timeout in %d seconds",
7005 zname, (int)tv.tv_sec);
7006 }
7007 tv.tv_usec = 0;
7008 comm_timer_set(xfr->task_nextprobe->timer, &tv);
7009 }
7010
auth_zone_pickup_initial_zone(struct auth_zone * z,struct module_env * env)7011 void auth_zone_pickup_initial_zone(struct auth_zone* z, struct module_env* env)
7012 {
7013 /* Set the time, because we now have timestamp in env,
7014 * (not earlier during startup and apply_cfg), and this
7015 * notes the start time when the data was acquired. */
7016 z->soa_zone_acquired = *env->now;
7017 }
7018
auth_xfer_pickup_initial_zone(struct auth_xfer * x,struct module_env * env)7019 void auth_xfer_pickup_initial_zone(struct auth_xfer* x, struct module_env* env)
7020 {
7021 /* set lease_time, because we now have timestamp in env,
7022 * (not earlier during startup and apply_cfg), and this
7023 * notes the start time when the data was acquired */
7024 if(x->have_zone) {
7025 x->lease_time = *env->now;
7026 x->soa_zone_acquired = *env->now;
7027 }
7028 if(x->task_nextprobe && x->task_nextprobe->worker == NULL) {
7029 xfr_set_timeout(x, env, 0, 1);
7030 }
7031 }
7032
7033 /** initial pick up of worker timeouts, ties events to worker event loop */
7034 void
auth_xfer_pickup_initial(struct auth_zones * az,struct module_env * env)7035 auth_xfer_pickup_initial(struct auth_zones* az, struct module_env* env)
7036 {
7037 struct auth_xfer* x;
7038 struct auth_zone* z;
7039 lock_rw_wrlock(&az->lock);
7040 RBTREE_FOR(z, struct auth_zone*, &az->ztree) {
7041 lock_rw_wrlock(&z->lock);
7042 auth_zone_pickup_initial_zone(z, env);
7043 lock_rw_unlock(&z->lock);
7044 }
7045 RBTREE_FOR(x, struct auth_xfer*, &az->xtree) {
7046 lock_basic_lock(&x->lock);
7047 auth_xfer_pickup_initial_zone(x, env);
7048 lock_basic_unlock(&x->lock);
7049 }
7050 lock_rw_unlock(&az->lock);
7051 }
7052
auth_zones_cleanup(struct auth_zones * az)7053 void auth_zones_cleanup(struct auth_zones* az)
7054 {
7055 struct auth_xfer* x;
7056 lock_rw_wrlock(&az->lock);
7057 RBTREE_FOR(x, struct auth_xfer*, &az->xtree) {
7058 lock_basic_lock(&x->lock);
7059 if(x->task_nextprobe && x->task_nextprobe->worker != NULL) {
7060 xfr_nextprobe_disown(x);
7061 }
7062 if(x->task_probe && x->task_probe->worker != NULL) {
7063 xfr_probe_disown(x);
7064 }
7065 if(x->task_transfer && x->task_transfer->worker != NULL) {
7066 auth_chunks_delete(x->task_transfer);
7067 xfr_transfer_disown(x);
7068 }
7069 lock_basic_unlock(&x->lock);
7070 }
7071 lock_rw_unlock(&az->lock);
7072 }
7073
7074 /**
7075 * malloc the xfer and tasks
7076 * @param z: auth_zone with name of zone.
7077 */
7078 static struct auth_xfer*
auth_xfer_new(struct auth_zone * z)7079 auth_xfer_new(struct auth_zone* z)
7080 {
7081 struct auth_xfer* xfr;
7082 xfr = (struct auth_xfer*)calloc(1, sizeof(*xfr));
7083 if(!xfr) return NULL;
7084 xfr->name = memdup(z->name, z->namelen);
7085 if(!xfr->name) {
7086 free(xfr);
7087 return NULL;
7088 }
7089 xfr->node.key = xfr;
7090 xfr->namelen = z->namelen;
7091 xfr->namelabs = z->namelabs;
7092 xfr->dclass = z->dclass;
7093
7094 xfr->task_nextprobe = (struct auth_nextprobe*)calloc(1,
7095 sizeof(struct auth_nextprobe));
7096 if(!xfr->task_nextprobe) {
7097 free(xfr->name);
7098 free(xfr);
7099 return NULL;
7100 }
7101 xfr->task_probe = (struct auth_probe*)calloc(1,
7102 sizeof(struct auth_probe));
7103 if(!xfr->task_probe) {
7104 free(xfr->task_nextprobe);
7105 free(xfr->name);
7106 free(xfr);
7107 return NULL;
7108 }
7109 xfr->task_transfer = (struct auth_transfer*)calloc(1,
7110 sizeof(struct auth_transfer));
7111 if(!xfr->task_transfer) {
7112 free(xfr->task_probe);
7113 free(xfr->task_nextprobe);
7114 free(xfr->name);
7115 free(xfr);
7116 return NULL;
7117 }
7118
7119 lock_basic_init(&xfr->lock);
7120 lock_protect(&xfr->lock, &xfr->name, sizeof(xfr->name));
7121 lock_protect(&xfr->lock, &xfr->namelen, sizeof(xfr->namelen));
7122 lock_protect(&xfr->lock, xfr->name, xfr->namelen);
7123 lock_protect(&xfr->lock, &xfr->namelabs, sizeof(xfr->namelabs));
7124 lock_protect(&xfr->lock, &xfr->dclass, sizeof(xfr->dclass));
7125 lock_protect(&xfr->lock, &xfr->notify_received, sizeof(xfr->notify_received));
7126 lock_protect(&xfr->lock, &xfr->notify_serial, sizeof(xfr->notify_serial));
7127 lock_protect(&xfr->lock, &xfr->zone_expired, sizeof(xfr->zone_expired));
7128 lock_protect(&xfr->lock, &xfr->have_zone, sizeof(xfr->have_zone));
7129 lock_protect(&xfr->lock, &xfr->soa_zone_acquired, sizeof(xfr->soa_zone_acquired));
7130 lock_protect(&xfr->lock, &xfr->serial, sizeof(xfr->serial));
7131 lock_protect(&xfr->lock, &xfr->retry, sizeof(xfr->retry));
7132 lock_protect(&xfr->lock, &xfr->refresh, sizeof(xfr->refresh));
7133 lock_protect(&xfr->lock, &xfr->expiry, sizeof(xfr->expiry));
7134 lock_protect(&xfr->lock, &xfr->lease_time, sizeof(xfr->lease_time));
7135 lock_protect(&xfr->lock, &xfr->task_nextprobe->worker,
7136 sizeof(xfr->task_nextprobe->worker));
7137 lock_protect(&xfr->lock, &xfr->task_probe->worker,
7138 sizeof(xfr->task_probe->worker));
7139 lock_protect(&xfr->lock, &xfr->task_transfer->worker,
7140 sizeof(xfr->task_transfer->worker));
7141 lock_basic_lock(&xfr->lock);
7142 return xfr;
7143 }
7144
7145 /** Create auth_xfer structure.
7146 * This populates the have_zone, soa values, and so on times.
7147 * and sets the timeout, if a zone transfer is needed a short timeout is set.
7148 * For that the auth_zone itself must exist (and read in zonefile)
7149 * returns false on alloc failure. */
7150 struct auth_xfer*
auth_xfer_create(struct auth_zones * az,struct auth_zone * z)7151 auth_xfer_create(struct auth_zones* az, struct auth_zone* z)
7152 {
7153 struct auth_xfer* xfr;
7154
7155 /* malloc it */
7156 xfr = auth_xfer_new(z);
7157 if(!xfr) {
7158 log_err("malloc failure");
7159 return NULL;
7160 }
7161 /* insert in tree */
7162 (void)rbtree_insert(&az->xtree, &xfr->node);
7163 return xfr;
7164 }
7165
7166 /** create new auth_master structure */
7167 static struct auth_master*
auth_master_new(struct auth_master *** list)7168 auth_master_new(struct auth_master*** list)
7169 {
7170 struct auth_master *m;
7171 m = (struct auth_master*)calloc(1, sizeof(*m));
7172 if(!m) {
7173 log_err("malloc failure");
7174 return NULL;
7175 }
7176 /* set first pointer to m, or next pointer of previous element to m */
7177 (**list) = m;
7178 /* store m's next pointer as future point to store at */
7179 (*list) = &(m->next);
7180 return m;
7181 }
7182
7183 /** dup_prefix : create string from initial part of other string, malloced */
7184 static char*
dup_prefix(char * str,size_t num)7185 dup_prefix(char* str, size_t num)
7186 {
7187 char* result;
7188 size_t len = strlen(str);
7189 if(len < num) num = len; /* not more than strlen */
7190 result = (char*)malloc(num+1);
7191 if(!result) {
7192 log_err("malloc failure");
7193 return result;
7194 }
7195 memmove(result, str, num);
7196 result[num] = 0;
7197 return result;
7198 }
7199
7200 /** dup string and print error on error */
7201 static char*
dup_all(char * str)7202 dup_all(char* str)
7203 {
7204 char* result = strdup(str);
7205 if(!result) {
7206 log_err("malloc failure");
7207 return NULL;
7208 }
7209 return result;
7210 }
7211
7212 /** find first of two characters */
7213 static char*
str_find_first_of_chars(char * s,char a,char b)7214 str_find_first_of_chars(char* s, char a, char b)
7215 {
7216 char* ra = strchr(s, a);
7217 char* rb = strchr(s, b);
7218 if(!ra) return rb;
7219 if(!rb) return ra;
7220 if(ra < rb) return ra;
7221 return rb;
7222 }
7223
7224 /** parse URL into host and file parts, false on malloc or parse error */
7225 static int
parse_url(char * url,char ** host,char ** file,int * port,int * ssl)7226 parse_url(char* url, char** host, char** file, int* port, int* ssl)
7227 {
7228 char* p = url;
7229 /* parse http://www.example.com/file.htm
7230 * or http://127.0.0.1 (index.html)
7231 * or https://[::1@1234]/a/b/c/d */
7232 *ssl = 1;
7233 *port = AUTH_HTTPS_PORT;
7234
7235 /* parse http:// or https:// */
7236 if(strncmp(p, "http://", 7) == 0) {
7237 p += 7;
7238 *ssl = 0;
7239 *port = AUTH_HTTP_PORT;
7240 } else if(strncmp(p, "https://", 8) == 0) {
7241 p += 8;
7242 } else if(strstr(p, "://") && strchr(p, '/') > strstr(p, "://") &&
7243 strchr(p, ':') >= strstr(p, "://")) {
7244 char* uri = dup_prefix(p, (size_t)(strstr(p, "://")-p));
7245 log_err("protocol %s:// not supported (for url %s)",
7246 uri?uri:"", p);
7247 free(uri);
7248 return 0;
7249 }
7250
7251 /* parse hostname part */
7252 if(p[0] == '[') {
7253 char* end = strchr(p, ']');
7254 p++; /* skip over [ */
7255 if(end) {
7256 *host = dup_prefix(p, (size_t)(end-p));
7257 if(!*host) return 0;
7258 p = end+1; /* skip over ] */
7259 } else {
7260 *host = dup_all(p);
7261 if(!*host) return 0;
7262 p = end;
7263 }
7264 } else {
7265 char* end = str_find_first_of_chars(p, ':', '/');
7266 if(end) {
7267 *host = dup_prefix(p, (size_t)(end-p));
7268 if(!*host) return 0;
7269 } else {
7270 *host = dup_all(p);
7271 if(!*host) return 0;
7272 }
7273 p = end; /* at next : or / or NULL */
7274 }
7275
7276 /* parse port number */
7277 if(p && p[0] == ':') {
7278 char* end = NULL;
7279 *port = strtol(p+1, &end, 10);
7280 p = end;
7281 }
7282
7283 /* parse filename part */
7284 while(p && *p == '/')
7285 p++;
7286 if(!p || p[0] == 0)
7287 *file = strdup("/");
7288 else *file = strdup(p);
7289 if(!*file) {
7290 log_err("malloc failure");
7291 return 0;
7292 }
7293 return 1;
7294 }
7295
7296 int
xfer_set_masters(struct auth_master ** list,struct config_auth * c,int with_http)7297 xfer_set_masters(struct auth_master** list, struct config_auth* c,
7298 int with_http)
7299 {
7300 struct auth_master* m;
7301 struct config_strlist* p;
7302 /* list points to the first, or next pointer for the new element */
7303 while(*list) {
7304 list = &( (*list)->next );
7305 }
7306 if(with_http)
7307 for(p = c->urls; p; p = p->next) {
7308 m = auth_master_new(&list);
7309 if(!m) return 0;
7310 m->http = 1;
7311 if(!parse_url(p->str, &m->host, &m->file, &m->port, &m->ssl))
7312 return 0;
7313 }
7314 for(p = c->masters; p; p = p->next) {
7315 m = auth_master_new(&list);
7316 if(!m) return 0;
7317 m->ixfr = 1; /* this flag is not configurable */
7318 m->host = strdup(p->str);
7319 if(!m->host) {
7320 log_err("malloc failure");
7321 return 0;
7322 }
7323 }
7324 for(p = c->allow_notify; p; p = p->next) {
7325 m = auth_master_new(&list);
7326 if(!m) return 0;
7327 m->allow_notify = 1;
7328 m->host = strdup(p->str);
7329 if(!m->host) {
7330 log_err("malloc failure");
7331 return 0;
7332 }
7333 }
7334 return 1;
7335 }
7336
7337 #define SERIAL_BITS 32
7338 int
compare_serial(uint32_t a,uint32_t b)7339 compare_serial(uint32_t a, uint32_t b)
7340 {
7341 const uint32_t cutoff = ((uint32_t) 1 << (SERIAL_BITS - 1));
7342
7343 if (a == b) {
7344 return 0;
7345 } else if ((a < b && b - a < cutoff) || (a > b && a - b > cutoff)) {
7346 return -1;
7347 } else {
7348 return 1;
7349 }
7350 }
7351
zonemd_hashalgo_supported(int hashalgo)7352 int zonemd_hashalgo_supported(int hashalgo)
7353 {
7354 if(hashalgo == ZONEMD_ALGO_SHA384) return 1;
7355 if(hashalgo == ZONEMD_ALGO_SHA512) return 1;
7356 return 0;
7357 }
7358
zonemd_scheme_supported(int scheme)7359 int zonemd_scheme_supported(int scheme)
7360 {
7361 if(scheme == ZONEMD_SCHEME_SIMPLE) return 1;
7362 return 0;
7363 }
7364
7365 /** initialize hash for hashing with zonemd hash algo */
zonemd_digest_init(int hashalgo,char ** reason)7366 static struct secalgo_hash* zonemd_digest_init(int hashalgo, char** reason)
7367 {
7368 struct secalgo_hash *h;
7369 if(hashalgo == ZONEMD_ALGO_SHA384) {
7370 /* sha384 */
7371 h = secalgo_hash_create_sha384();
7372 if(!h)
7373 *reason = "digest sha384 could not be created";
7374 return h;
7375 } else if(hashalgo == ZONEMD_ALGO_SHA512) {
7376 /* sha512 */
7377 h = secalgo_hash_create_sha512();
7378 if(!h)
7379 *reason = "digest sha512 could not be created";
7380 return h;
7381 }
7382 /* unknown hash algo */
7383 *reason = "unsupported algorithm";
7384 return NULL;
7385 }
7386
7387 /** update the hash for zonemd */
zonemd_digest_update(int hashalgo,struct secalgo_hash * h,uint8_t * data,size_t len,char ** reason)7388 static int zonemd_digest_update(int hashalgo, struct secalgo_hash* h,
7389 uint8_t* data, size_t len, char** reason)
7390 {
7391 if(hashalgo == ZONEMD_ALGO_SHA384) {
7392 if(!secalgo_hash_update(h, data, len)) {
7393 *reason = "digest sha384 failed";
7394 return 0;
7395 }
7396 return 1;
7397 } else if(hashalgo == ZONEMD_ALGO_SHA512) {
7398 if(!secalgo_hash_update(h, data, len)) {
7399 *reason = "digest sha512 failed";
7400 return 0;
7401 }
7402 return 1;
7403 }
7404 /* unknown hash algo */
7405 *reason = "unsupported algorithm";
7406 return 0;
7407 }
7408
7409 /** 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)7410 static int zonemd_digest_finish(int hashalgo, struct secalgo_hash* h,
7411 uint8_t* result, size_t hashlen, size_t* resultlen, char** reason)
7412 {
7413 if(hashalgo == ZONEMD_ALGO_SHA384) {
7414 if(hashlen < 384/8) {
7415 *reason = "digest buffer too small for sha384";
7416 return 0;
7417 }
7418 if(!secalgo_hash_final(h, result, hashlen, resultlen)) {
7419 *reason = "digest sha384 finish failed";
7420 return 0;
7421 }
7422 return 1;
7423 } else if(hashalgo == ZONEMD_ALGO_SHA512) {
7424 if(hashlen < 512/8) {
7425 *reason = "digest buffer too small for sha512";
7426 return 0;
7427 }
7428 if(!secalgo_hash_final(h, result, hashlen, resultlen)) {
7429 *reason = "digest sha512 finish failed";
7430 return 0;
7431 }
7432 return 1;
7433 }
7434 /* unknown algo */
7435 *reason = "unsupported algorithm";
7436 return 0;
7437 }
7438
7439 /** add rrsets from node to the list */
authdata_rrsets_to_list(struct auth_rrset ** array,size_t arraysize,struct auth_rrset * first)7440 static size_t authdata_rrsets_to_list(struct auth_rrset** array,
7441 size_t arraysize, struct auth_rrset* first)
7442 {
7443 struct auth_rrset* rrset = first;
7444 size_t num = 0;
7445 while(rrset) {
7446 if(num >= arraysize)
7447 return num;
7448 array[num] = rrset;
7449 num++;
7450 rrset = rrset->next;
7451 }
7452 return num;
7453 }
7454
7455 /** compare rr list entries */
rrlist_compare(const void * arg1,const void * arg2)7456 static int rrlist_compare(const void* arg1, const void* arg2)
7457 {
7458 struct auth_rrset* r1 = *(struct auth_rrset**)arg1;
7459 struct auth_rrset* r2 = *(struct auth_rrset**)arg2;
7460 uint16_t t1, t2;
7461 if(r1 == NULL) t1 = LDNS_RR_TYPE_RRSIG;
7462 else t1 = r1->type;
7463 if(r2 == NULL) t2 = LDNS_RR_TYPE_RRSIG;
7464 else t2 = r2->type;
7465 if(t1 < t2)
7466 return -1;
7467 if(t1 > t2)
7468 return 1;
7469 return 0;
7470 }
7471
7472 /** add type RRSIG to rr list if not one there already,
7473 * 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)7474 static void addrrsigtype_if_needed(struct auth_rrset** array,
7475 size_t arraysize, size_t* rrnum, struct auth_data* node)
7476 {
7477 if(az_domain_rrset(node, LDNS_RR_TYPE_RRSIG))
7478 return; /* already one there */
7479 if((*rrnum) >= arraysize)
7480 return; /* array too small? */
7481 array[*rrnum] = NULL; /* nothing there, but need entry in list */
7482 (*rrnum)++;
7483 }
7484
7485 /** 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)7486 static int zonemd_simple_rrset(struct auth_zone* z, int hashalgo,
7487 struct secalgo_hash* h, struct auth_data* node,
7488 struct auth_rrset* rrset, struct regional* region,
7489 struct sldns_buffer* buf, char** reason)
7490 {
7491 /* canonicalize */
7492 struct ub_packed_rrset_key key;
7493 memset(&key, 0, sizeof(key));
7494 key.entry.key = &key;
7495 key.entry.data = rrset->data;
7496 key.rk.dname = node->name;
7497 key.rk.dname_len = node->namelen;
7498 key.rk.type = htons(rrset->type);
7499 key.rk.rrset_class = htons(z->dclass);
7500 if(!rrset_canonicalize_to_buffer(region, buf, &key)) {
7501 *reason = "out of memory";
7502 return 0;
7503 }
7504 regional_free_all(region);
7505
7506 /* hash */
7507 if(!zonemd_digest_update(hashalgo, h, sldns_buffer_begin(buf),
7508 sldns_buffer_limit(buf), reason)) {
7509 return 0;
7510 }
7511 return 1;
7512 }
7513
7514 /** 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)7515 static size_t zonemd_simple_count_rrsig(struct auth_rrset* rrset,
7516 struct auth_rrset** rrlist, size_t rrnum,
7517 struct auth_zone* z, struct auth_data* node)
7518 {
7519 size_t i, count = 0;
7520 if(rrset) {
7521 size_t j;
7522 for(j = 0; j<rrset->data->count; j++) {
7523 if(rrsig_rdata_get_type_covered(rrset->data->
7524 rr_data[j], rrset->data->rr_len[j]) ==
7525 LDNS_RR_TYPE_ZONEMD &&
7526 query_dname_compare(z->name, node->name)==0) {
7527 /* omit RRSIGs over type ZONEMD at apex */
7528 continue;
7529 }
7530 count++;
7531 }
7532 }
7533 for(i=0; i<rrnum; i++) {
7534 if(rrlist[i] && rrlist[i]->type == LDNS_RR_TYPE_ZONEMD &&
7535 query_dname_compare(z->name, node->name)==0) {
7536 /* omit RRSIGs over type ZONEMD at apex */
7537 continue;
7538 }
7539 count += (rrlist[i]?rrlist[i]->data->rrsig_count:0);
7540 }
7541 return count;
7542 }
7543
7544 /** 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)7545 static int zonemd_simple_rrsig_allocs(struct regional* region,
7546 struct packed_rrset_data* data, size_t count)
7547 {
7548 data->rr_len = regional_alloc(region, sizeof(*data->rr_len) * count);
7549 if(!data->rr_len) {
7550 return 0;
7551 }
7552 data->rr_ttl = regional_alloc(region, sizeof(*data->rr_ttl) * count);
7553 if(!data->rr_ttl) {
7554 return 0;
7555 }
7556 data->rr_data = regional_alloc(region, sizeof(*data->rr_data) * count);
7557 if(!data->rr_data) {
7558 return 0;
7559 }
7560 return 1;
7561 }
7562
7563 /** 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)7564 static void add_rrlist_rrsigs_into_data(struct packed_rrset_data* data,
7565 size_t* done, struct auth_rrset** rrlist, size_t rrnum,
7566 struct auth_zone* z, struct auth_data* node)
7567 {
7568 size_t i;
7569 for(i=0; i<rrnum; i++) {
7570 size_t j;
7571 if(!rrlist[i])
7572 continue;
7573 if(rrlist[i]->type == LDNS_RR_TYPE_ZONEMD &&
7574 query_dname_compare(z->name, node->name)==0) {
7575 /* omit RRSIGs over type ZONEMD at apex */
7576 continue;
7577 }
7578 for(j = 0; j<rrlist[i]->data->rrsig_count; j++) {
7579 data->rr_len[*done] = rrlist[i]->data->rr_len[rrlist[i]->data->count + j];
7580 data->rr_ttl[*done] = rrlist[i]->data->rr_ttl[rrlist[i]->data->count + j];
7581 /* reference the rdata in the rrset, no need to
7582 * copy it, it is no longer needed at the end of
7583 * the routine */
7584 data->rr_data[*done] = rrlist[i]->data->rr_data[rrlist[i]->data->count + j];
7585 (*done)++;
7586 }
7587 }
7588 }
7589
add_rrset_into_data(struct packed_rrset_data * data,size_t * done,struct auth_rrset * rrset,struct auth_zone * z,struct auth_data * node)7590 static void add_rrset_into_data(struct packed_rrset_data* data,
7591 size_t* done, struct auth_rrset* rrset,
7592 struct auth_zone* z, struct auth_data* node)
7593 {
7594 if(rrset) {
7595 size_t j;
7596 for(j = 0; j<rrset->data->count; j++) {
7597 if(rrsig_rdata_get_type_covered(rrset->data->
7598 rr_data[j], rrset->data->rr_len[j]) ==
7599 LDNS_RR_TYPE_ZONEMD &&
7600 query_dname_compare(z->name, node->name)==0) {
7601 /* omit RRSIGs over type ZONEMD at apex */
7602 continue;
7603 }
7604 data->rr_len[*done] = rrset->data->rr_len[j];
7605 data->rr_ttl[*done] = rrset->data->rr_ttl[j];
7606 /* reference the rdata in the rrset, no need to
7607 * copy it, it is no longer need at the end of
7608 * the routine */
7609 data->rr_data[*done] = rrset->data->rr_data[j];
7610 (*done)++;
7611 }
7612 }
7613 }
7614
7615 /** 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)7616 static int zonemd_simple_rrsig(struct auth_zone* z, int hashalgo,
7617 struct secalgo_hash* h, struct auth_data* node,
7618 struct auth_rrset* rrset, struct auth_rrset** rrlist, size_t rrnum,
7619 struct regional* region, struct sldns_buffer* buf, char** reason)
7620 {
7621 /* the rrset pointer can be NULL, this means it is type RRSIG and
7622 * there is no ordinary type RRSIG there. The RRSIGs are stored
7623 * with the RRsets in their data.
7624 *
7625 * The RRset pointer can be nonNULL. This happens if there is
7626 * no RR that is covered by the RRSIG for the domain. Then this
7627 * RRSIG RR is stored in an rrset of type RRSIG. The other RRSIGs
7628 * are stored in the rrset entries for the RRs in the rr list for
7629 * the domain node. We need to collate the rrset's data, if any, and
7630 * the rrlist's rrsigs */
7631 /* if this is the apex, omit RRSIGs that cover type ZONEMD */
7632 /* build rrsig rrset */
7633 size_t done = 0;
7634 struct ub_packed_rrset_key key;
7635 struct packed_rrset_data data;
7636 memset(&key, 0, sizeof(key));
7637 memset(&data, 0, sizeof(data));
7638 key.entry.key = &key;
7639 key.entry.data = &data;
7640 key.rk.dname = node->name;
7641 key.rk.dname_len = node->namelen;
7642 key.rk.type = htons(LDNS_RR_TYPE_RRSIG);
7643 key.rk.rrset_class = htons(z->dclass);
7644 data.count = zonemd_simple_count_rrsig(rrset, rrlist, rrnum, z, node);
7645 if(!zonemd_simple_rrsig_allocs(region, &data, data.count)) {
7646 *reason = "out of memory";
7647 regional_free_all(region);
7648 return 0;
7649 }
7650 /* all the RRSIGs stored in the other rrsets for this domain node */
7651 add_rrlist_rrsigs_into_data(&data, &done, rrlist, rrnum, z, node);
7652 /* plus the RRSIGs stored in an rrset of type RRSIG for this node */
7653 add_rrset_into_data(&data, &done, rrset, z, node);
7654
7655 /* canonicalize */
7656 if(!rrset_canonicalize_to_buffer(region, buf, &key)) {
7657 *reason = "out of memory";
7658 regional_free_all(region);
7659 return 0;
7660 }
7661 regional_free_all(region);
7662
7663 /* hash */
7664 if(!zonemd_digest_update(hashalgo, h, sldns_buffer_begin(buf),
7665 sldns_buffer_limit(buf), reason)) {
7666 return 0;
7667 }
7668 return 1;
7669 }
7670
7671 /** 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)7672 static int zonemd_simple_domain(struct auth_zone* z, int hashalgo,
7673 struct secalgo_hash* h, struct auth_data* node,
7674 struct regional* region, struct sldns_buffer* buf, char** reason)
7675 {
7676 const size_t rrlistsize = 65536;
7677 struct auth_rrset* rrlist[rrlistsize];
7678 size_t i, rrnum = 0;
7679 /* see if the domain is out of scope, the zone origin,
7680 * that would be omitted */
7681 if(!dname_subdomain_c(node->name, z->name))
7682 return 1; /* continue */
7683 /* loop over the rrsets in ascending order. */
7684 rrnum = authdata_rrsets_to_list(rrlist, rrlistsize, node->rrsets);
7685 addrrsigtype_if_needed(rrlist, rrlistsize, &rrnum, node);
7686 qsort(rrlist, rrnum, sizeof(*rrlist), rrlist_compare);
7687 for(i=0; i<rrnum; i++) {
7688 if(rrlist[i] && rrlist[i]->type == LDNS_RR_TYPE_ZONEMD &&
7689 query_dname_compare(z->name, node->name) == 0) {
7690 /* omit type ZONEMD at apex */
7691 continue;
7692 }
7693 if(rrlist[i] == NULL || rrlist[i]->type ==
7694 LDNS_RR_TYPE_RRSIG) {
7695 if(!zonemd_simple_rrsig(z, hashalgo, h, node,
7696 rrlist[i], rrlist, rrnum, region, buf, reason))
7697 return 0;
7698 } else if(!zonemd_simple_rrset(z, hashalgo, h, node,
7699 rrlist[i], region, buf, reason)) {
7700 return 0;
7701 }
7702 }
7703 return 1;
7704 }
7705
7706 /** 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)7707 static int zonemd_simple_collate(struct auth_zone* z, int hashalgo,
7708 struct secalgo_hash* h, struct regional* region,
7709 struct sldns_buffer* buf, char** reason)
7710 {
7711 /* our tree is sorted in canonical order, so we can just loop over
7712 * the tree */
7713 struct auth_data* n;
7714 RBTREE_FOR(n, struct auth_data*, &z->data) {
7715 if(!zonemd_simple_domain(z, hashalgo, h, n, region, buf,
7716 reason))
7717 return 0;
7718 }
7719 return 1;
7720 }
7721
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)7722 int auth_zone_generate_zonemd_hash(struct auth_zone* z, int scheme,
7723 int hashalgo, uint8_t* hash, size_t hashlen, size_t* resultlen,
7724 struct regional* region, struct sldns_buffer* buf, char** reason)
7725 {
7726 struct secalgo_hash* h = zonemd_digest_init(hashalgo, reason);
7727 if(!h) {
7728 if(!*reason)
7729 *reason = "digest init fail";
7730 return 0;
7731 }
7732 if(scheme == ZONEMD_SCHEME_SIMPLE) {
7733 if(!zonemd_simple_collate(z, hashalgo, h, region, buf, reason)) {
7734 if(!*reason) *reason = "scheme simple collate fail";
7735 secalgo_hash_delete(h);
7736 return 0;
7737 }
7738 }
7739 if(!zonemd_digest_finish(hashalgo, h, hash, hashlen, resultlen,
7740 reason)) {
7741 secalgo_hash_delete(h);
7742 *reason = "digest finish fail";
7743 return 0;
7744 }
7745 secalgo_hash_delete(h);
7746 return 1;
7747 }
7748
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)7749 int auth_zone_generate_zonemd_check(struct auth_zone* z, int scheme,
7750 int hashalgo, uint8_t* hash, size_t hashlen, struct regional* region,
7751 struct sldns_buffer* buf, char** reason)
7752 {
7753 uint8_t gen[512];
7754 size_t genlen = 0;
7755 *reason = NULL;
7756 if(!zonemd_hashalgo_supported(hashalgo)) {
7757 /* allow it */
7758 *reason = "unsupported algorithm";
7759 return 1;
7760 }
7761 if(!zonemd_scheme_supported(scheme)) {
7762 /* allow it */
7763 *reason = "unsupported scheme";
7764 return 1;
7765 }
7766 if(hashlen < 12) {
7767 /* the ZONEMD draft requires digests to fail if too small */
7768 *reason = "digest length too small, less than 12";
7769 return 0;
7770 }
7771 /* generate digest */
7772 if(!auth_zone_generate_zonemd_hash(z, scheme, hashalgo, gen,
7773 sizeof(gen), &genlen, region, buf, reason)) {
7774 /* reason filled in by zonemd hash routine */
7775 return 0;
7776 }
7777 /* check digest length */
7778 if(hashlen != genlen) {
7779 *reason = "incorrect digest length";
7780 if(verbosity >= VERB_ALGO) {
7781 verbose(VERB_ALGO, "zonemd scheme=%d hashalgo=%d",
7782 scheme, hashalgo);
7783 log_hex("ZONEMD should be ", gen, genlen);
7784 log_hex("ZONEMD to check is", hash, hashlen);
7785 }
7786 return 0;
7787 }
7788 /* check digest */
7789 if(memcmp(hash, gen, genlen) != 0) {
7790 *reason = "incorrect digest";
7791 if(verbosity >= VERB_ALGO) {
7792 verbose(VERB_ALGO, "zonemd scheme=%d hashalgo=%d",
7793 scheme, hashalgo);
7794 log_hex("ZONEMD should be ", gen, genlen);
7795 log_hex("ZONEMD to check is", hash, hashlen);
7796 }
7797 return 0;
7798 }
7799 return 1;
7800 }
7801
7802 /** log auth zone message with zone name in front. */
7803 static void auth_zone_log(uint8_t* name, enum verbosity_value level,
7804 const char* format, ...) ATTR_FORMAT(printf, 3, 4);
auth_zone_log(uint8_t * name,enum verbosity_value level,const char * format,...)7805 static void auth_zone_log(uint8_t* name, enum verbosity_value level,
7806 const char* format, ...)
7807 {
7808 va_list args;
7809 va_start(args, format);
7810 if(verbosity >= level) {
7811 char str[LDNS_MAX_DOMAINLEN];
7812 char msg[MAXSYSLOGMSGLEN];
7813 dname_str(name, str);
7814 vsnprintf(msg, sizeof(msg), format, args);
7815 verbose(level, "auth zone %s %s", str, msg);
7816 }
7817 va_end(args);
7818 }
7819
7820 /** 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)7821 static int zonemd_dnssec_verify_rrset(struct auth_zone* z,
7822 struct module_env* env, struct module_stack* mods,
7823 struct ub_packed_rrset_key* dnskey, struct auth_data* node,
7824 struct auth_rrset* rrset, char** why_bogus, uint8_t* sigalg,
7825 char* reasonbuf, size_t reasonlen)
7826 {
7827 struct ub_packed_rrset_key pk;
7828 enum sec_status sec;
7829 struct val_env* ve;
7830 int m;
7831 int verified = 0;
7832 m = modstack_find(mods, "validator");
7833 if(m == -1) {
7834 auth_zone_log(z->name, VERB_ALGO, "zonemd dnssec verify: have "
7835 "DNSKEY chain of trust, but no validator module");
7836 return 0;
7837 }
7838 ve = (struct val_env*)env->modinfo[m];
7839
7840 memset(&pk, 0, sizeof(pk));
7841 pk.entry.key = &pk;
7842 pk.entry.data = rrset->data;
7843 pk.rk.dname = node->name;
7844 pk.rk.dname_len = node->namelen;
7845 pk.rk.type = htons(rrset->type);
7846 pk.rk.rrset_class = htons(z->dclass);
7847 if(verbosity >= VERB_ALGO) {
7848 char typestr[32];
7849 typestr[0]=0;
7850 sldns_wire2str_type_buf(rrset->type, typestr, sizeof(typestr));
7851 auth_zone_log(z->name, VERB_ALGO,
7852 "zonemd: verify %s RRset with DNSKEY", typestr);
7853 }
7854 sec = dnskeyset_verify_rrset(env, ve, &pk, dnskey, sigalg, why_bogus, NULL,
7855 LDNS_SECTION_ANSWER, NULL, &verified, reasonbuf, reasonlen);
7856 if(sec == sec_status_secure) {
7857 return 1;
7858 }
7859 if(why_bogus)
7860 auth_zone_log(z->name, VERB_ALGO, "DNSSEC verify was bogus: %s", *why_bogus);
7861 return 0;
7862 }
7863
7864 /** 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)7865 static int nsec3_of_param_has_type(struct auth_rrset* nsec3, int algo,
7866 size_t iter, uint8_t* salt, size_t saltlen, uint16_t rrtype)
7867 {
7868 int i, count = (int)nsec3->data->count;
7869 struct ub_packed_rrset_key pk;
7870 memset(&pk, 0, sizeof(pk));
7871 pk.entry.data = nsec3->data;
7872 for(i=0; i<count; i++) {
7873 int rralgo;
7874 size_t rriter, rrsaltlen;
7875 uint8_t* rrsalt;
7876 if(!nsec3_get_params(&pk, i, &rralgo, &rriter, &rrsalt,
7877 &rrsaltlen))
7878 continue; /* no parameters, malformed */
7879 if(rralgo != algo || rriter != iter || rrsaltlen != saltlen)
7880 continue; /* different parameters */
7881 if(saltlen != 0) {
7882 if(rrsalt == NULL || salt == NULL)
7883 continue;
7884 if(memcmp(rrsalt, salt, saltlen) != 0)
7885 continue; /* different salt parameters */
7886 }
7887 if(nsec3_has_type(&pk, i, rrtype))
7888 return 1;
7889 }
7890 return 0;
7891 }
7892
7893 /** Verify the absence of ZONEMD with DNSSEC by checking NSEC, NSEC3 type flag.
7894 * 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)7895 static int zonemd_check_dnssec_absence(struct auth_zone* z,
7896 struct module_env* env, struct module_stack* mods,
7897 struct ub_packed_rrset_key* dnskey, struct auth_data* apex,
7898 char** reason, char** why_bogus, uint8_t* sigalg, char* reasonbuf,
7899 size_t reasonlen)
7900 {
7901 struct auth_rrset* nsec = NULL;
7902 if(!apex) {
7903 *reason = "zone has no apex domain but ZONEMD missing";
7904 return 0;
7905 }
7906 nsec = az_domain_rrset(apex, LDNS_RR_TYPE_NSEC);
7907 if(nsec) {
7908 struct ub_packed_rrset_key pk;
7909 /* dnssec verify the NSEC */
7910 if(!zonemd_dnssec_verify_rrset(z, env, mods, dnskey, apex,
7911 nsec, why_bogus, sigalg, reasonbuf, reasonlen)) {
7912 *reason = "DNSSEC verify failed for NSEC RRset";
7913 return 0;
7914 }
7915 /* check type bitmap */
7916 memset(&pk, 0, sizeof(pk));
7917 pk.entry.data = nsec->data;
7918 if(nsec_has_type(&pk, LDNS_RR_TYPE_ZONEMD)) {
7919 *reason = "DNSSEC NSEC bitmap says type ZONEMD exists";
7920 return 0;
7921 }
7922 auth_zone_log(z->name, VERB_ALGO, "zonemd DNSSEC NSEC verification of absence of ZONEMD secure");
7923 } else {
7924 /* NSEC3 perhaps ? */
7925 int algo;
7926 size_t iter, saltlen;
7927 uint8_t* salt;
7928 struct auth_rrset* nsec3param = az_domain_rrset(apex,
7929 LDNS_RR_TYPE_NSEC3PARAM);
7930 struct auth_data* match;
7931 struct auth_rrset* nsec3;
7932 if(!nsec3param) {
7933 *reason = "zone has no NSEC information but ZONEMD missing";
7934 return 0;
7935 }
7936 if(!az_nsec3_param(z, &algo, &iter, &salt, &saltlen)) {
7937 *reason = "zone has no NSEC information but ZONEMD missing";
7938 return 0;
7939 }
7940 /* find the NSEC3 record */
7941 match = az_nsec3_find_exact(z, z->name, z->namelen, algo,
7942 iter, salt, saltlen);
7943 if(!match) {
7944 *reason = "zone has no NSEC3 domain for the apex but ZONEMD missing";
7945 return 0;
7946 }
7947 nsec3 = az_domain_rrset(match, LDNS_RR_TYPE_NSEC3);
7948 if(!nsec3) {
7949 *reason = "zone has no NSEC3 RRset for the apex but ZONEMD missing";
7950 return 0;
7951 }
7952 /* dnssec verify the NSEC3 */
7953 if(!zonemd_dnssec_verify_rrset(z, env, mods, dnskey, match,
7954 nsec3, why_bogus, sigalg, reasonbuf, reasonlen)) {
7955 *reason = "DNSSEC verify failed for NSEC3 RRset";
7956 return 0;
7957 }
7958 /* check type bitmap */
7959 if(nsec3_of_param_has_type(nsec3, algo, iter, salt, saltlen,
7960 LDNS_RR_TYPE_ZONEMD)) {
7961 *reason = "DNSSEC NSEC3 bitmap says type ZONEMD exists";
7962 return 0;
7963 }
7964 auth_zone_log(z->name, VERB_ALGO, "zonemd DNSSEC NSEC3 verification of absence of ZONEMD secure");
7965 }
7966
7967 return 1;
7968 }
7969
7970 /** Verify the SOA and ZONEMD DNSSEC signatures.
7971 * 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)7972 static int zonemd_check_dnssec_soazonemd(struct auth_zone* z,
7973 struct module_env* env, struct module_stack* mods,
7974 struct ub_packed_rrset_key* dnskey, struct auth_data* apex,
7975 struct auth_rrset* zonemd_rrset, char** reason, char** why_bogus,
7976 uint8_t* sigalg, char* reasonbuf, size_t reasonlen)
7977 {
7978 struct auth_rrset* soa;
7979 if(!apex) {
7980 *reason = "zone has no apex domain";
7981 return 0;
7982 }
7983 soa = az_domain_rrset(apex, LDNS_RR_TYPE_SOA);
7984 if(!soa) {
7985 *reason = "zone has no SOA RRset";
7986 return 0;
7987 }
7988 if(!zonemd_dnssec_verify_rrset(z, env, mods, dnskey, apex, soa,
7989 why_bogus, sigalg, reasonbuf, reasonlen)) {
7990 *reason = "DNSSEC verify failed for SOA RRset";
7991 return 0;
7992 }
7993 if(!zonemd_dnssec_verify_rrset(z, env, mods, dnskey, apex,
7994 zonemd_rrset, why_bogus, sigalg, reasonbuf, reasonlen)) {
7995 *reason = "DNSSEC verify failed for ZONEMD RRset";
7996 return 0;
7997 }
7998 auth_zone_log(z->name, VERB_ALGO, "zonemd DNSSEC verification of SOA and ZONEMD RRsets secure");
7999 return 1;
8000 }
8001
8002 /**
8003 * Fail the ZONEMD verification.
8004 * @param z: auth zone that fails.
8005 * @param env: environment with config, to ignore failure or not.
8006 * @param reason: failure string description.
8007 * @param why_bogus: failure string for DNSSEC verification failure.
8008 * @param result: strdup result in here if not NULL.
8009 */
auth_zone_zonemd_fail(struct auth_zone * z,struct module_env * env,char * reason,char * why_bogus,char ** result)8010 static void auth_zone_zonemd_fail(struct auth_zone* z, struct module_env* env,
8011 char* reason, char* why_bogus, char** result)
8012 {
8013 char zstr[LDNS_MAX_DOMAINLEN];
8014 /* if fail: log reason, and depending on config also take action
8015 * and drop the zone, eg. it is gone from memory, set zone_expired */
8016 dname_str(z->name, zstr);
8017 if(!reason) reason = "verification failed";
8018 if(result) {
8019 if(why_bogus) {
8020 char res[1024];
8021 snprintf(res, sizeof(res), "%s: %s", reason,
8022 why_bogus);
8023 *result = strdup(res);
8024 } else {
8025 *result = strdup(reason);
8026 }
8027 if(!*result) log_err("out of memory");
8028 } else {
8029 log_warn("auth zone %s: ZONEMD verification failed: %s", zstr, reason);
8030 }
8031
8032 if(env->cfg->zonemd_permissive_mode) {
8033 verbose(VERB_ALGO, "zonemd-permissive-mode enabled, "
8034 "not blocking zone %s", zstr);
8035 return;
8036 }
8037
8038 /* expired means the zone gives servfail and is not used by
8039 * lookup if fallback_enabled*/
8040 z->zone_expired = 1;
8041 }
8042
8043 /**
8044 * Verify the zonemd with DNSSEC and hash check, with given key.
8045 * @param z: auth zone.
8046 * @param env: environment with config and temp buffers.
8047 * @param mods: module stack with validator env for verification.
8048 * @param dnskey: dnskey that we can use, or NULL. If nonnull, the key
8049 * has been verified and is the start of the chain of trust.
8050 * @param is_insecure: if true, the dnskey is not used, the zone is insecure.
8051 * And dnssec is not used. It is DNSSEC secure insecure or not under
8052 * a trust anchor.
8053 * @param sigalg: if nonNULL provide algorithm downgrade protection.
8054 * Otherwise one algorithm is enough. Must have space of ALGO_NEEDS_MAX+1.
8055 * @param result: if not NULL result reason copied here.
8056 */
8057 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)8058 auth_zone_verify_zonemd_with_key(struct auth_zone* z, struct module_env* env,
8059 struct module_stack* mods, struct ub_packed_rrset_key* dnskey,
8060 int is_insecure, char** result, uint8_t* sigalg)
8061 {
8062 char reasonbuf[256];
8063 char* reason = NULL, *why_bogus = NULL;
8064 struct auth_data* apex = NULL;
8065 struct auth_rrset* zonemd_rrset = NULL;
8066 int zonemd_absent = 0, zonemd_absence_dnssecok = 0;
8067
8068 /* see if ZONEMD is present or absent. */
8069 apex = az_find_name(z, z->name, z->namelen);
8070 if(!apex) {
8071 zonemd_absent = 1;
8072 } else {
8073 zonemd_rrset = az_domain_rrset(apex, LDNS_RR_TYPE_ZONEMD);
8074 if(!zonemd_rrset || zonemd_rrset->data->count==0) {
8075 zonemd_absent = 1;
8076 zonemd_rrset = NULL;
8077 }
8078 }
8079
8080 /* if no DNSSEC, done. */
8081 /* if no ZONEMD, and DNSSEC, use DNSKEY to verify NSEC or NSEC3 for
8082 * zone apex. Check ZONEMD bit is turned off or else fail */
8083 /* if ZONEMD, and DNSSEC, check DNSSEC signature on SOA and ZONEMD,
8084 * or else fail */
8085 if(!dnskey && !is_insecure) {
8086 auth_zone_zonemd_fail(z, env, "DNSKEY missing", NULL, result);
8087 return;
8088 } else if(!zonemd_rrset && dnskey && !is_insecure) {
8089 /* fetch, DNSSEC verify, and check NSEC/NSEC3 */
8090 if(!zonemd_check_dnssec_absence(z, env, mods, dnskey, apex,
8091 &reason, &why_bogus, sigalg, reasonbuf,
8092 sizeof(reasonbuf))) {
8093 auth_zone_zonemd_fail(z, env, reason, why_bogus, result);
8094 return;
8095 }
8096 zonemd_absence_dnssecok = 1;
8097 } else if(zonemd_rrset && dnskey && !is_insecure) {
8098 /* check DNSSEC verify of SOA and ZONEMD */
8099 if(!zonemd_check_dnssec_soazonemd(z, env, mods, dnskey, apex,
8100 zonemd_rrset, &reason, &why_bogus, sigalg, reasonbuf,
8101 sizeof(reasonbuf))) {
8102 auth_zone_zonemd_fail(z, env, reason, why_bogus, result);
8103 return;
8104 }
8105 }
8106
8107 if(zonemd_absent && z->zonemd_reject_absence) {
8108 auth_zone_zonemd_fail(z, env, "ZONEMD absent and that is not allowed by config", NULL, result);
8109 return;
8110 }
8111 if(zonemd_absent && zonemd_absence_dnssecok) {
8112 auth_zone_log(z->name, VERB_ALGO, "DNSSEC verified nonexistence of ZONEMD");
8113 if(result) {
8114 *result = strdup("DNSSEC verified nonexistence of ZONEMD");
8115 if(!*result) log_err("out of memory");
8116 }
8117 return;
8118 }
8119 if(zonemd_absent) {
8120 auth_zone_log(z->name, VERB_ALGO, "no ZONEMD present");
8121 if(result) {
8122 *result = strdup("no ZONEMD present");
8123 if(!*result) log_err("out of memory");
8124 }
8125 return;
8126 }
8127
8128 /* check ZONEMD checksum and report or else fail. */
8129 if(!auth_zone_zonemd_check_hash(z, env, &reason)) {
8130 auth_zone_zonemd_fail(z, env, reason, NULL, result);
8131 return;
8132 }
8133
8134 /* success! log the success */
8135 if(reason)
8136 auth_zone_log(z->name, VERB_ALGO, "ZONEMD %s", reason);
8137 else auth_zone_log(z->name, VERB_ALGO, "ZONEMD verification successful");
8138 if(result) {
8139 if(reason)
8140 *result = strdup(reason);
8141 else *result = strdup("ZONEMD verification successful");
8142 if(!*result) log_err("out of memory");
8143 }
8144 }
8145
8146 /**
8147 * verify the zone DNSKEY rrset from the trust anchor
8148 * This is possible because the anchor is for the zone itself, and can
8149 * thus apply straight to the zone DNSKEY set.
8150 * @param z: the auth zone.
8151 * @param env: environment with time and temp buffers.
8152 * @param mods: module stack for validator environment for dnssec validation.
8153 * @param anchor: trust anchor to use
8154 * @param is_insecure: returned, true if the zone is securely insecure.
8155 * @param why_bogus: if the routine fails, returns the failure reason.
8156 * @param keystorage: where to store the ub_packed_rrset_key that is created
8157 * on success. A pointer to it is returned on success.
8158 * @param reasonbuf: buffer to use for fail reason string print.
8159 * @param reasonlen: length of reasonbuf.
8160 * @return the dnskey RRset, reference to zone data and keystorage, or
8161 * NULL on failure.
8162 */
8163 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)8164 zonemd_get_dnskey_from_anchor(struct auth_zone* z, struct module_env* env,
8165 struct module_stack* mods, struct trust_anchor* anchor,
8166 int* is_insecure, char** why_bogus,
8167 struct ub_packed_rrset_key* keystorage, char* reasonbuf,
8168 size_t reasonlen)
8169 {
8170 struct auth_data* apex;
8171 struct auth_rrset* dnskey_rrset;
8172 enum sec_status sec;
8173 struct val_env* ve;
8174 int m;
8175
8176 apex = az_find_name(z, z->name, z->namelen);
8177 if(!apex) {
8178 *why_bogus = "have trust anchor, but zone has no apex domain for DNSKEY";
8179 return 0;
8180 }
8181 dnskey_rrset = az_domain_rrset(apex, LDNS_RR_TYPE_DNSKEY);
8182 if(!dnskey_rrset || dnskey_rrset->data->count==0) {
8183 *why_bogus = "have trust anchor, but zone has no DNSKEY";
8184 return 0;
8185 }
8186
8187 m = modstack_find(mods, "validator");
8188 if(m == -1) {
8189 *why_bogus = "have trust anchor, but no validator module";
8190 return 0;
8191 }
8192 ve = (struct val_env*)env->modinfo[m];
8193
8194 memset(keystorage, 0, sizeof(*keystorage));
8195 keystorage->entry.key = keystorage;
8196 keystorage->entry.data = dnskey_rrset->data;
8197 keystorage->rk.dname = apex->name;
8198 keystorage->rk.dname_len = apex->namelen;
8199 keystorage->rk.type = htons(LDNS_RR_TYPE_DNSKEY);
8200 keystorage->rk.rrset_class = htons(z->dclass);
8201 auth_zone_log(z->name, VERB_QUERY,
8202 "zonemd: verify DNSKEY RRset with trust anchor");
8203 sec = val_verify_DNSKEY_with_TA(env, ve, keystorage, anchor->ds_rrset,
8204 anchor->dnskey_rrset, NULL, why_bogus, NULL, NULL, reasonbuf,
8205 reasonlen);
8206 regional_free_all(env->scratch);
8207 if(sec == sec_status_secure) {
8208 /* success */
8209 *is_insecure = 0;
8210 return keystorage;
8211 } else if(sec == sec_status_insecure) {
8212 /* insecure */
8213 *is_insecure = 1;
8214 } else {
8215 /* bogus */
8216 *is_insecure = 0;
8217 auth_zone_log(z->name, VERB_ALGO,
8218 "zonemd: verify DNSKEY RRset with trust anchor failed: %s", *why_bogus);
8219 }
8220 return NULL;
8221 }
8222
8223 /** verify the DNSKEY from the zone with looked up DS record */
8224 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)8225 auth_zone_verify_zonemd_key_with_ds(struct auth_zone* z,
8226 struct module_env* env, struct module_stack* mods,
8227 struct ub_packed_rrset_key* ds, int* is_insecure, char** why_bogus,
8228 struct ub_packed_rrset_key* keystorage, uint8_t* sigalg,
8229 char* reasonbuf, size_t reasonlen)
8230 {
8231 struct auth_data* apex;
8232 struct auth_rrset* dnskey_rrset;
8233 enum sec_status sec;
8234 struct val_env* ve;
8235 int m;
8236
8237 /* fetch DNSKEY from zone data */
8238 apex = az_find_name(z, z->name, z->namelen);
8239 if(!apex) {
8240 *why_bogus = "in verifywithDS, zone has no apex";
8241 return NULL;
8242 }
8243 dnskey_rrset = az_domain_rrset(apex, LDNS_RR_TYPE_DNSKEY);
8244 if(!dnskey_rrset || dnskey_rrset->data->count==0) {
8245 *why_bogus = "in verifywithDS, zone has no DNSKEY";
8246 return NULL;
8247 }
8248
8249 m = modstack_find(mods, "validator");
8250 if(m == -1) {
8251 *why_bogus = "in verifywithDS, have no validator module";
8252 return NULL;
8253 }
8254 ve = (struct val_env*)env->modinfo[m];
8255
8256 memset(keystorage, 0, sizeof(*keystorage));
8257 keystorage->entry.key = keystorage;
8258 keystorage->entry.data = dnskey_rrset->data;
8259 keystorage->rk.dname = apex->name;
8260 keystorage->rk.dname_len = apex->namelen;
8261 keystorage->rk.type = htons(LDNS_RR_TYPE_DNSKEY);
8262 keystorage->rk.rrset_class = htons(z->dclass);
8263 auth_zone_log(z->name, VERB_QUERY, "zonemd: verify zone DNSKEY with DS");
8264 sec = val_verify_DNSKEY_with_DS(env, ve, keystorage, ds, sigalg,
8265 why_bogus, NULL, NULL, reasonbuf, reasonlen);
8266 regional_free_all(env->scratch);
8267 if(sec == sec_status_secure) {
8268 /* success */
8269 return keystorage;
8270 } else if(sec == sec_status_insecure) {
8271 /* insecure */
8272 *is_insecure = 1;
8273 } else {
8274 /* bogus */
8275 *is_insecure = 0;
8276 if(*why_bogus == NULL)
8277 *why_bogus = "verify failed";
8278 auth_zone_log(z->name, VERB_ALGO,
8279 "zonemd: verify DNSKEY RRset with DS failed: %s",
8280 *why_bogus);
8281 }
8282 return NULL;
8283 }
8284
8285 /** 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))8286 void auth_zonemd_dnskey_lookup_callback(void* arg, int rcode, sldns_buffer* buf,
8287 enum sec_status sec, char* why_bogus, int ATTR_UNUSED(was_ratelimited))
8288 {
8289 struct auth_zone* z = (struct auth_zone*)arg;
8290 struct module_env* env;
8291 char reasonbuf[256];
8292 char* reason = NULL, *ds_bogus = NULL, *typestr="DNSKEY";
8293 struct ub_packed_rrset_key* dnskey = NULL, *ds = NULL;
8294 int is_insecure = 0, downprot;
8295 struct ub_packed_rrset_key keystorage;
8296 uint8_t sigalg[ALGO_NEEDS_MAX+1];
8297
8298 lock_rw_wrlock(&z->lock);
8299 env = z->zonemd_callback_env;
8300 /* release the env variable so another worker can pick up the
8301 * ZONEMD verification task if it wants to */
8302 z->zonemd_callback_env = NULL;
8303 if(!env || env->outnet->want_to_quit || z->zone_deleted) {
8304 lock_rw_unlock(&z->lock);
8305 return; /* stop on quit */
8306 }
8307 if(z->zonemd_callback_qtype == LDNS_RR_TYPE_DS)
8308 typestr = "DS";
8309 downprot = env->cfg->harden_algo_downgrade;
8310
8311 /* process result */
8312 if(sec == sec_status_bogus) {
8313 reason = why_bogus;
8314 if(!reason) {
8315 if(z->zonemd_callback_qtype == LDNS_RR_TYPE_DNSKEY)
8316 reason = "lookup of DNSKEY was bogus";
8317 else reason = "lookup of DS was bogus";
8318 }
8319 auth_zone_log(z->name, VERB_ALGO,
8320 "zonemd lookup of %s was bogus: %s", typestr, reason);
8321 } else if(rcode == LDNS_RCODE_NOERROR) {
8322 uint16_t wanted_qtype = z->zonemd_callback_qtype;
8323 struct regional* temp = env->scratch;
8324 struct query_info rq;
8325 struct reply_info* rep;
8326 memset(&rq, 0, sizeof(rq));
8327 rep = parse_reply_in_temp_region(buf, temp, &rq);
8328 if(rep && rq.qtype == wanted_qtype &&
8329 query_dname_compare(z->name, rq.qname) == 0 &&
8330 FLAGS_GET_RCODE(rep->flags) == LDNS_RCODE_NOERROR) {
8331 /* parsed successfully */
8332 struct ub_packed_rrset_key* answer =
8333 reply_find_answer_rrset(&rq, rep);
8334 if(answer && sec == sec_status_secure) {
8335 if(z->zonemd_callback_qtype == LDNS_RR_TYPE_DNSKEY)
8336 dnskey = answer;
8337 else ds = answer;
8338 auth_zone_log(z->name, VERB_ALGO,
8339 "zonemd lookup of %s was secure", typestr);
8340 } else if(sec == sec_status_secure && !answer) {
8341 is_insecure = 1;
8342 auth_zone_log(z->name, VERB_ALGO,
8343 "zonemd lookup of %s has no content, but is secure, treat as insecure", typestr);
8344 } else if(sec == sec_status_insecure) {
8345 is_insecure = 1;
8346 auth_zone_log(z->name, VERB_ALGO,
8347 "zonemd lookup of %s was insecure", typestr);
8348 } else if(sec == sec_status_indeterminate) {
8349 is_insecure = 1;
8350 auth_zone_log(z->name, VERB_ALGO,
8351 "zonemd lookup of %s was indeterminate, treat as insecure", typestr);
8352 } else {
8353 auth_zone_log(z->name, VERB_ALGO,
8354 "zonemd lookup of %s has nodata", typestr);
8355 if(z->zonemd_callback_qtype == LDNS_RR_TYPE_DNSKEY)
8356 reason = "lookup of DNSKEY has nodata";
8357 else reason = "lookup of DS has nodata";
8358 }
8359 } else if(rep && rq.qtype == wanted_qtype &&
8360 query_dname_compare(z->name, rq.qname) == 0 &&
8361 FLAGS_GET_RCODE(rep->flags) == LDNS_RCODE_NXDOMAIN &&
8362 sec == sec_status_secure) {
8363 /* secure nxdomain, so the zone is like some RPZ zone
8364 * that does not exist in the wider internet, with
8365 * a secure nxdomain answer outside of it. So we
8366 * treat the zonemd zone without a dnssec chain of
8367 * trust, as insecure. */
8368 is_insecure = 1;
8369 auth_zone_log(z->name, VERB_ALGO,
8370 "zonemd lookup of %s was secure NXDOMAIN, treat as insecure", typestr);
8371 } else if(rep && rq.qtype == wanted_qtype &&
8372 query_dname_compare(z->name, rq.qname) == 0 &&
8373 FLAGS_GET_RCODE(rep->flags) == LDNS_RCODE_NXDOMAIN &&
8374 sec == sec_status_insecure) {
8375 is_insecure = 1;
8376 auth_zone_log(z->name, VERB_ALGO,
8377 "zonemd lookup of %s was insecure NXDOMAIN, treat as insecure", typestr);
8378 } else if(rep && rq.qtype == wanted_qtype &&
8379 query_dname_compare(z->name, rq.qname) == 0 &&
8380 FLAGS_GET_RCODE(rep->flags) == LDNS_RCODE_NXDOMAIN &&
8381 sec == sec_status_indeterminate) {
8382 is_insecure = 1;
8383 auth_zone_log(z->name, VERB_ALGO,
8384 "zonemd lookup of %s was indeterminate NXDOMAIN, treat as insecure", typestr);
8385 } else {
8386 auth_zone_log(z->name, VERB_ALGO,
8387 "zonemd lookup of %s has no answer", typestr);
8388 if(z->zonemd_callback_qtype == LDNS_RR_TYPE_DNSKEY)
8389 reason = "lookup of DNSKEY has no answer";
8390 else reason = "lookup of DS has no answer";
8391 }
8392 } else {
8393 auth_zone_log(z->name, VERB_ALGO,
8394 "zonemd lookup of %s failed", typestr);
8395 if(z->zonemd_callback_qtype == LDNS_RR_TYPE_DNSKEY)
8396 reason = "lookup of DNSKEY failed";
8397 else reason = "lookup of DS failed";
8398 }
8399
8400 if(!reason && !is_insecure && !dnskey && ds) {
8401 dnskey = auth_zone_verify_zonemd_key_with_ds(z, env,
8402 &env->mesh->mods, ds, &is_insecure, &ds_bogus,
8403 &keystorage, downprot?sigalg:NULL, reasonbuf,
8404 sizeof(reasonbuf));
8405 if(!dnskey && !is_insecure && !reason)
8406 reason = "DNSKEY verify with DS failed";
8407 }
8408
8409 if(reason) {
8410 auth_zone_zonemd_fail(z, env, reason, ds_bogus, NULL);
8411 lock_rw_unlock(&z->lock);
8412 regional_free_all(env->scratch);
8413 return;
8414 }
8415
8416 auth_zone_verify_zonemd_with_key(z, env, &env->mesh->mods, dnskey,
8417 is_insecure, NULL, downprot?sigalg:NULL);
8418 regional_free_all(env->scratch);
8419 lock_rw_unlock(&z->lock);
8420 }
8421
8422 /** lookup DNSKEY for ZONEMD verification */
8423 static int
zonemd_lookup_dnskey(struct auth_zone * z,struct module_env * env)8424 zonemd_lookup_dnskey(struct auth_zone* z, struct module_env* env)
8425 {
8426 struct query_info qinfo;
8427 uint16_t qflags = BIT_RD;
8428 struct edns_data edns;
8429 sldns_buffer* buf = env->scratch_buffer;
8430 int fetch_ds = 0;
8431
8432 if(!z->fallback_enabled) {
8433 /* we cannot actually get the DNSKEY, because it is in the
8434 * zone we have ourselves, and it is not served yet
8435 * (possibly), so fetch type DS */
8436 fetch_ds = 1;
8437 }
8438 if(z->zonemd_callback_env) {
8439 /* another worker is already working on the callback
8440 * for the DNSKEY lookup for ZONEMD verification.
8441 * We do not also have to do ZONEMD verification, let that
8442 * worker do it */
8443 auth_zone_log(z->name, VERB_ALGO,
8444 "zonemd needs lookup of %s and that already is worked on by another worker", (fetch_ds?"DS":"DNSKEY"));
8445 return 1;
8446 }
8447
8448 /* use mesh_new_callback to lookup the DNSKEY,
8449 * and then wait for them to be looked up (in cache, or query) */
8450 qinfo.qname_len = z->namelen;
8451 qinfo.qname = z->name;
8452 qinfo.qclass = z->dclass;
8453 if(fetch_ds)
8454 qinfo.qtype = LDNS_RR_TYPE_DS;
8455 else qinfo.qtype = LDNS_RR_TYPE_DNSKEY;
8456 qinfo.local_alias = NULL;
8457 if(verbosity >= VERB_ALGO) {
8458 char buf1[512];
8459 char buf2[LDNS_MAX_DOMAINLEN];
8460 dname_str(z->name, buf2);
8461 snprintf(buf1, sizeof(buf1), "auth zone %s: lookup %s "
8462 "for zonemd verification", buf2,
8463 (fetch_ds?"DS":"DNSKEY"));
8464 log_query_info(VERB_ALGO, buf1, &qinfo);
8465 }
8466 edns.edns_present = 1;
8467 edns.ext_rcode = 0;
8468 edns.edns_version = 0;
8469 edns.bits = EDNS_DO;
8470 edns.opt_list_in = NULL;
8471 edns.opt_list_out = NULL;
8472 edns.opt_list_inplace_cb_out = NULL;
8473 if(sldns_buffer_capacity(buf) < 65535)
8474 edns.udp_size = (uint16_t)sldns_buffer_capacity(buf);
8475 else edns.udp_size = 65535;
8476
8477 /* store the worker-specific module env for the callback.
8478 * We can then reference this when the callback executes */
8479 z->zonemd_callback_env = env;
8480 z->zonemd_callback_qtype = qinfo.qtype;
8481 /* the callback can be called straight away */
8482 lock_rw_unlock(&z->lock);
8483 if(!mesh_new_callback(env->mesh, &qinfo, qflags, &edns, buf, 0,
8484 &auth_zonemd_dnskey_lookup_callback, z, 0)) {
8485 lock_rw_wrlock(&z->lock);
8486 log_err("out of memory lookup of %s for zonemd",
8487 (fetch_ds?"DS":"DNSKEY"));
8488 return 0;
8489 }
8490 lock_rw_wrlock(&z->lock);
8491 return 1;
8492 }
8493
auth_zone_verify_zonemd(struct auth_zone * z,struct module_env * env,struct module_stack * mods,char ** result,int offline,int only_online)8494 void auth_zone_verify_zonemd(struct auth_zone* z, struct module_env* env,
8495 struct module_stack* mods, char** result, int offline, int only_online)
8496 {
8497 char reasonbuf[256];
8498 char* reason = NULL, *why_bogus = NULL;
8499 struct trust_anchor* anchor = NULL;
8500 struct ub_packed_rrset_key* dnskey = NULL;
8501 struct ub_packed_rrset_key keystorage;
8502 int is_insecure = 0;
8503 /* verify the ZONEMD if present.
8504 * If not present check if absence is allowed by DNSSEC */
8505 if(!z->zonemd_check)
8506 return;
8507 if(z->data.count == 0)
8508 return; /* no data */
8509
8510 /* if zone is under a trustanchor */
8511 /* is it equal to trustanchor - get dnskey's verified */
8512 /* else, find chain of trust by fetching DNSKEYs lookup for zone */
8513 /* result if that, if insecure, means no DNSSEC for the ZONEMD,
8514 * otherwise we have the zone DNSKEY for the DNSSEC verification. */
8515 if(env->anchors)
8516 anchor = anchors_lookup(env->anchors, z->name, z->namelen,
8517 z->dclass);
8518 if(anchor && anchor->numDS == 0 && anchor->numDNSKEY == 0) {
8519 /* domain-insecure trust anchor for unsigned zones */
8520 lock_basic_unlock(&anchor->lock);
8521 if(only_online)
8522 return;
8523 dnskey = NULL;
8524 is_insecure = 1;
8525 } else if(anchor && query_dname_compare(z->name, anchor->name) == 0) {
8526 if(only_online) {
8527 lock_basic_unlock(&anchor->lock);
8528 return;
8529 }
8530 /* equal to trustanchor, no need for online lookups */
8531 dnskey = zonemd_get_dnskey_from_anchor(z, env, mods, anchor,
8532 &is_insecure, &why_bogus, &keystorage, reasonbuf,
8533 sizeof(reasonbuf));
8534 lock_basic_unlock(&anchor->lock);
8535 if(!dnskey && !reason && !is_insecure) {
8536 reason = "verify DNSKEY RRset with trust anchor failed";
8537 }
8538 } else if(anchor) {
8539 lock_basic_unlock(&anchor->lock);
8540 /* perform online lookups */
8541 if(offline)
8542 return;
8543 /* setup online lookups, and wait for them */
8544 if(zonemd_lookup_dnskey(z, env)) {
8545 /* wait for the lookup */
8546 return;
8547 }
8548 reason = "could not lookup DNSKEY for chain of trust";
8549 } else {
8550 /* the zone is not under a trust anchor */
8551 if(only_online)
8552 return;
8553 dnskey = NULL;
8554 is_insecure = 1;
8555 }
8556
8557 if(reason) {
8558 auth_zone_zonemd_fail(z, env, reason, why_bogus, result);
8559 regional_free_all(env->scratch);
8560 return;
8561 }
8562
8563 auth_zone_verify_zonemd_with_key(z, env, mods, dnskey, is_insecure,
8564 result, NULL);
8565 regional_free_all(env->scratch);
8566 }
8567
auth_zones_pickup_zonemd_verify(struct auth_zones * az,struct module_env * env)8568 void auth_zones_pickup_zonemd_verify(struct auth_zones* az,
8569 struct module_env* env)
8570 {
8571 struct auth_zone key;
8572 uint8_t savezname[255+1];
8573 size_t savezname_len;
8574 struct auth_zone* z;
8575 key.node.key = &key;
8576 lock_rw_rdlock(&az->lock);
8577 RBTREE_FOR(z, struct auth_zone*, &az->ztree) {
8578 lock_rw_wrlock(&z->lock);
8579 if(!z->zonemd_check) {
8580 lock_rw_unlock(&z->lock);
8581 continue;
8582 }
8583 key.dclass = z->dclass;
8584 key.namelabs = z->namelabs;
8585 if(z->namelen > sizeof(savezname)) {
8586 lock_rw_unlock(&z->lock);
8587 log_err("auth_zones_pickup_zonemd_verify: zone name too long");
8588 continue;
8589 }
8590 savezname_len = z->namelen;
8591 memmove(savezname, z->name, z->namelen);
8592 lock_rw_unlock(&az->lock);
8593 auth_zone_verify_zonemd(z, env, &env->mesh->mods, NULL, 0, 1);
8594 lock_rw_unlock(&z->lock);
8595 lock_rw_rdlock(&az->lock);
8596 /* find the zone we had before, it is not deleted,
8597 * because we have a flag for that that is processed at
8598 * apply_cfg time */
8599 key.namelen = savezname_len;
8600 key.name = savezname;
8601 z = (struct auth_zone*)rbtree_search(&az->ztree, &key);
8602 if(!z)
8603 break;
8604 }
8605 lock_rw_unlock(&az->lock);
8606 }
8607
8608 /** Get memory usage of auth rrset */
8609 static size_t
auth_rrset_get_mem(struct auth_rrset * rrset)8610 auth_rrset_get_mem(struct auth_rrset* rrset)
8611 {
8612 size_t m = sizeof(*rrset) + packed_rrset_sizeof(rrset->data);
8613 return m;
8614 }
8615
8616 /** Get memory usage of auth data */
8617 static size_t
auth_data_get_mem(struct auth_data * node)8618 auth_data_get_mem(struct auth_data* node)
8619 {
8620 size_t m = sizeof(*node) + node->namelen;
8621 struct auth_rrset* rrset;
8622 for(rrset = node->rrsets; rrset; rrset = rrset->next) {
8623 m += auth_rrset_get_mem(rrset);
8624 }
8625 return m;
8626 }
8627
8628 /** Get memory usage of auth zone */
8629 static size_t
auth_zone_get_mem(struct auth_zone * z)8630 auth_zone_get_mem(struct auth_zone* z)
8631 {
8632 size_t m = sizeof(*z) + z->namelen;
8633 struct auth_data* node;
8634 if(z->zonefile)
8635 m += strlen(z->zonefile)+1;
8636 RBTREE_FOR(node, struct auth_data*, &z->data) {
8637 m += auth_data_get_mem(node);
8638 }
8639 if(z->rpz)
8640 m += rpz_get_mem(z->rpz);
8641 return m;
8642 }
8643
8644 /** Get memory usage of list of auth addr */
8645 static size_t
auth_addrs_get_mem(struct auth_addr * list)8646 auth_addrs_get_mem(struct auth_addr* list)
8647 {
8648 size_t m = 0;
8649 struct auth_addr* a;
8650 for(a = list; a; a = a->next) {
8651 m += sizeof(*a);
8652 }
8653 return m;
8654 }
8655
8656 /** Get memory usage of list of primaries for auth xfer */
8657 static size_t
auth_primaries_get_mem(struct auth_master * list)8658 auth_primaries_get_mem(struct auth_master* list)
8659 {
8660 size_t m = 0;
8661 struct auth_master* n;
8662 for(n = list; n; n = n->next) {
8663 m += sizeof(*n);
8664 m += auth_addrs_get_mem(n->list);
8665 if(n->host)
8666 m += strlen(n->host)+1;
8667 if(n->file)
8668 m += strlen(n->file)+1;
8669 }
8670 return m;
8671 }
8672
8673 /** Get memory usage or list of auth chunks */
8674 static size_t
auth_chunks_get_mem(struct auth_chunk * list)8675 auth_chunks_get_mem(struct auth_chunk* list)
8676 {
8677 size_t m = 0;
8678 struct auth_chunk* chunk;
8679 for(chunk = list; chunk; chunk = chunk->next) {
8680 m += sizeof(*chunk) + chunk->len;
8681 }
8682 return m;
8683 }
8684
8685 /** Get memory usage of auth xfer */
8686 static size_t
auth_xfer_get_mem(struct auth_xfer * xfr)8687 auth_xfer_get_mem(struct auth_xfer* xfr)
8688 {
8689 size_t m = sizeof(*xfr) + xfr->namelen;
8690
8691 /* auth_nextprobe */
8692 m += comm_timer_get_mem(xfr->task_nextprobe->timer);
8693
8694 /* auth_probe */
8695 m += auth_primaries_get_mem(xfr->task_probe->masters);
8696 m += comm_point_get_mem(xfr->task_probe->cp);
8697 m += comm_timer_get_mem(xfr->task_probe->timer);
8698
8699 /* auth_transfer */
8700 m += auth_chunks_get_mem(xfr->task_transfer->chunks_first);
8701 m += auth_primaries_get_mem(xfr->task_transfer->masters);
8702 m += comm_point_get_mem(xfr->task_transfer->cp);
8703 m += comm_timer_get_mem(xfr->task_transfer->timer);
8704
8705 /* allow_notify_list */
8706 m += auth_primaries_get_mem(xfr->allow_notify_list);
8707
8708 return m;
8709 }
8710
8711 /** Get memory usage of auth zones ztree */
8712 static size_t
az_ztree_get_mem(struct auth_zones * az)8713 az_ztree_get_mem(struct auth_zones* az)
8714 {
8715 size_t m = 0;
8716 struct auth_zone* z;
8717 RBTREE_FOR(z, struct auth_zone*, &az->ztree) {
8718 lock_rw_rdlock(&z->lock);
8719 m += auth_zone_get_mem(z);
8720 lock_rw_unlock(&z->lock);
8721 }
8722 return m;
8723 }
8724
8725 /** Get memory usage of auth zones xtree */
8726 static size_t
az_xtree_get_mem(struct auth_zones * az)8727 az_xtree_get_mem(struct auth_zones* az)
8728 {
8729 size_t m = 0;
8730 struct auth_xfer* xfr;
8731 RBTREE_FOR(xfr, struct auth_xfer*, &az->xtree) {
8732 lock_basic_lock(&xfr->lock);
8733 m += auth_xfer_get_mem(xfr);
8734 lock_basic_unlock(&xfr->lock);
8735 }
8736 return m;
8737 }
8738
auth_zones_get_mem(struct auth_zones * zones)8739 size_t auth_zones_get_mem(struct auth_zones* zones)
8740 {
8741 size_t m;
8742 if(!zones) return 0;
8743 m = sizeof(*zones);
8744 lock_rw_rdlock(&zones->rpz_lock);
8745 lock_rw_rdlock(&zones->lock);
8746 m += az_ztree_get_mem(zones);
8747 m += az_xtree_get_mem(zones);
8748 lock_rw_unlock(&zones->lock);
8749 lock_rw_unlock(&zones->rpz_lock);
8750 return m;
8751 }
8752
xfr_disown_tasks(struct auth_xfer * xfr,struct worker * worker)8753 void xfr_disown_tasks(struct auth_xfer* xfr, struct worker* worker)
8754 {
8755 if(xfr->task_nextprobe->worker == worker) {
8756 xfr_nextprobe_disown(xfr);
8757 }
8758 if(xfr->task_probe->worker == worker) {
8759 xfr_probe_disown(xfr);
8760 }
8761 if(xfr->task_transfer->worker == worker) {
8762 xfr_transfer_disown(xfr);
8763 }
8764 }
8765