2 * respip/respip.c - filtering response IP module
8 * This file contains a module that inspects a result of recursive resolution
9 * to see if any IP address record should trigger a special action.
10 * If applicable these actions can modify the original response.
14 #include "services/localzone.h"
15 #include "services/authzone.h"
16 #include "services/cache/dns.h"
17 #include "sldns/str2wire.h"
18 #include "util/config_file.h"
19 #include "util/fptr_wlist.h"
20 #include "util/module.h"
21 #include "util/net_help.h"
22 #include "util/regional.h"
23 #include "util/data/msgreply.h"
24 #include "util/storage/dnstree.h"
25 #include "respip/respip.h"
26 #include "services/view.h"
27 #include "sldns/rrdef.h"
30 /** Subset of resp_addr.node, used for inform-variant logging */
31 struct respip_addr_info {
32 struct sockaddr_storage addr;
37 /** Query state regarding the response-ip module. */
40 * The general state. Unless CNAME chasing takes place, all processing
41 * is completed in this state without any other asynchronous event.
46 * A subquery for CNAME chasing is completed.
48 RESPIP_SUBQUERY_FINISHED
51 /** Per query state for the response-ip module. */
52 struct respip_qstate {
53 enum respip_state state;
57 respip_set_create(void)
59 struct respip_set* set = calloc(1, sizeof(*set));
62 set->region = regional_create();
67 addr_tree_init(&set->ip_tree);
68 lock_rw_init(&set->lock);
72 /** helper traverse to delete resp_addr nodes */
74 resp_addr_del(rbnode_type* n, void* ATTR_UNUSED(arg))
76 struct resp_addr* r = (struct resp_addr*)n->key;
77 lock_rw_destroy(&r->lock);
78 #ifdef THREADS_DISABLED
84 respip_set_delete(struct respip_set* set)
88 lock_rw_destroy(&set->lock);
89 traverse_postorder(&set->ip_tree, resp_addr_del, NULL);
90 regional_destroy(set->region);
95 respip_set_get_tree(struct respip_set* set)
103 respip_sockaddr_find_or_create(struct respip_set* set, struct sockaddr_storage* addr,
104 socklen_t addrlen, int net, int create, const char* ipstr)
106 struct resp_addr* node;
107 node = (struct resp_addr*)addr_tree_find(&set->ip_tree, addr, addrlen, net);
108 if(!node && create) {
109 node = regional_alloc_zero(set->region, sizeof(*node));
111 log_err("out of memory");
114 lock_rw_init(&node->lock);
115 node->action = respip_none;
116 if(!addr_tree_insert(&set->ip_tree, &node->node, addr,
118 /* We know we didn't find it, so this should be
120 log_warn("unexpected: duplicate address: %s", ipstr);
127 respip_sockaddr_delete(struct respip_set* set, struct resp_addr* node)
129 struct resp_addr* prev;
130 prev = (struct resp_addr*)rbtree_previous((struct rbnode_type*)node);
131 lock_rw_destroy(&node->lock);
132 rbtree_delete(&set->ip_tree, node);
133 /* no free'ing, all allocated in region */
135 addr_tree_init_parents((rbtree_type*)set);
137 addr_tree_init_parents_node(&prev->node);
140 /** returns the node in the address tree for the specified netblock string;
141 * non-existent node will be created if 'create' is true */
142 static struct resp_addr*
143 respip_find_or_create(struct respip_set* set, const char* ipstr, int create)
145 struct sockaddr_storage addr;
149 if(!netblockstrtoaddr(ipstr, 0, &addr, &addrlen, &net)) {
150 log_err("cannot parse netblock: '%s'", ipstr);
153 return respip_sockaddr_find_or_create(set, &addr, addrlen, net, create,
158 respip_tag_cfg(struct respip_set* set, const char* ipstr,
159 const uint8_t* taglist, size_t taglen)
161 struct resp_addr* node;
163 if(!(node=respip_find_or_create(set, ipstr, 1)))
166 log_warn("duplicate response-address-tag for '%s', overridden.",
169 node->taglist = regional_alloc_init(set->region, taglist, taglen);
171 log_err("out of memory");
174 node->taglen = taglen;
178 /** set action for the node specified by the netblock string */
180 respip_action_cfg(struct respip_set* set, const char* ipstr,
183 struct resp_addr* node;
184 enum respip_action action;
186 if(!(node=respip_find_or_create(set, ipstr, 1)))
188 if(node->action != respip_none) {
189 verbose(VERB_QUERY, "duplicate response-ip action for '%s', overridden.",
192 if(strcmp(actnstr, "deny") == 0)
193 action = respip_deny;
194 else if(strcmp(actnstr, "redirect") == 0)
195 action = respip_redirect;
196 else if(strcmp(actnstr, "inform") == 0)
197 action = respip_inform;
198 else if(strcmp(actnstr, "inform_deny") == 0)
199 action = respip_inform_deny;
200 else if(strcmp(actnstr, "inform_redirect") == 0)
201 action = respip_inform_redirect;
202 else if(strcmp(actnstr, "always_transparent") == 0)
203 action = respip_always_transparent;
204 else if(strcmp(actnstr, "always_refuse") == 0)
205 action = respip_always_refuse;
206 else if(strcmp(actnstr, "always_nxdomain") == 0)
207 action = respip_always_nxdomain;
208 else if(strcmp(actnstr, "always_nodata") == 0)
209 action = respip_always_nodata;
210 else if(strcmp(actnstr, "always_deny") == 0)
211 action = respip_always_deny;
213 log_err("unknown response-ip action %s", actnstr);
216 node->action = action;
220 /** allocate and initialize an rrset structure; this function is based
221 * on new_local_rrset() from the localzone.c module */
222 static struct ub_packed_rrset_key*
223 new_rrset(struct regional* region, uint16_t rrtype, uint16_t rrclass)
225 struct packed_rrset_data* pd;
226 struct ub_packed_rrset_key* rrset = regional_alloc_zero(
227 region, sizeof(*rrset));
229 log_err("out of memory");
232 rrset->entry.key = rrset;
233 pd = regional_alloc_zero(region, sizeof(*pd));
235 log_err("out of memory");
238 pd->trust = rrset_trust_prim_noglue;
239 pd->security = sec_status_insecure;
240 rrset->entry.data = pd;
241 rrset->rk.dname = regional_alloc_zero(region, 1);
242 if(!rrset->rk.dname) {
243 log_err("out of memory");
246 rrset->rk.dname_len = 1;
247 rrset->rk.type = htons(rrtype);
248 rrset->rk.rrset_class = htons(rrclass);
252 /** enter local data as resource records into a response-ip node */
255 respip_enter_rr(struct regional* region, struct resp_addr* raddr,
256 uint16_t rrtype, uint16_t rrclass, time_t ttl, uint8_t* rdata,
257 size_t rdata_len, const char* rrstr, const char* netblockstr)
259 struct packed_rrset_data* pd;
261 sa = (struct sockaddr*)&raddr->node.addr;
262 if (rrtype == LDNS_RR_TYPE_CNAME && raddr->data) {
263 log_err("CNAME response-ip data (%s) can not co-exist with other "
264 "response-ip data for netblock %s", rrstr, netblockstr);
266 } else if (raddr->data &&
267 raddr->data->rk.type == htons(LDNS_RR_TYPE_CNAME)) {
268 log_err("response-ip data (%s) can not be added; CNAME response-ip "
269 "data already in place for netblock %s", rrstr, netblockstr);
271 } else if((rrtype != LDNS_RR_TYPE_CNAME) &&
272 ((sa->sa_family == AF_INET && rrtype != LDNS_RR_TYPE_A) ||
273 (sa->sa_family == AF_INET6 && rrtype != LDNS_RR_TYPE_AAAA))) {
274 log_err("response-ip data %s record type does not correspond "
275 "to netblock %s address family", rrstr, netblockstr);
280 raddr->data = new_rrset(region, rrtype, rrclass);
284 pd = raddr->data->entry.data;
285 return rrset_insert_rr(region, pd, rdata, rdata_len, ttl, rrstr);
289 respip_enter_rrstr(struct regional* region, struct resp_addr* raddr,
290 const char* rrstr, const char* netblock)
293 uint16_t rrtype = 0, rrclass = 0;
295 uint8_t rr[LDNS_RR_BUF_SIZE];
296 uint8_t* rdata = NULL;
297 size_t rdata_len = 0;
301 if(raddr->action != respip_redirect
302 && raddr->action != respip_inform_redirect) {
303 log_err("cannot parse response-ip-data %s: response-ip "
304 "action for %s is not redirect", rrstr, netblock);
307 ret = snprintf(buf, sizeof(buf), ". %s", rrstr);
308 if(ret < 0 || ret >= (int)sizeof(buf)) {
309 strlcpy(bufshort, rrstr, sizeof(bufshort));
310 log_err("bad response-ip-data: %s...", bufshort);
313 if(!rrstr_get_rr_content(buf, &nm, &rrtype, &rrclass, &ttl, rr, sizeof(rr),
314 &rdata, &rdata_len)) {
315 log_err("bad response-ip-data: %s", rrstr);
319 return respip_enter_rr(region, raddr, rrtype, rrclass, ttl, rdata,
320 rdata_len, rrstr, netblock);
324 respip_data_cfg(struct respip_set* set, const char* ipstr, const char* rrstr)
326 struct resp_addr* node;
328 node=respip_find_or_create(set, ipstr, 0);
329 if(!node || node->action == respip_none) {
330 log_err("cannot parse response-ip-data %s: "
331 "response-ip node for %s not found", rrstr, ipstr);
334 return respip_enter_rrstr(set->region, node, rrstr, ipstr);
338 respip_set_apply_cfg(struct respip_set* set, char* const* tagname, int num_tags,
339 struct config_strbytelist* respip_tags,
340 struct config_str2list* respip_actions,
341 struct config_str2list* respip_data)
343 struct config_strbytelist* p;
344 struct config_str2list* pa;
345 struct config_str2list* pd;
347 set->tagname = tagname;
348 set->num_tags = num_tags;
352 struct config_strbytelist* np = p->next;
354 log_assert(p->str && p->str2);
355 if(!respip_tag_cfg(set, p->str, p->str2, p->str2len)) {
356 config_del_strbytelist(p);
367 struct config_str2list* np = pa->next;
368 log_assert(pa->str && pa->str2);
369 if(!respip_action_cfg(set, pa->str, pa->str2)) {
370 config_deldblstrlist(pa);
381 struct config_str2list* np = pd->next;
382 log_assert(pd->str && pd->str2);
383 if(!respip_data_cfg(set, pd->str, pd->str2)) {
384 config_deldblstrlist(pd);
392 addr_tree_init_parents(&set->ip_tree);
398 respip_global_apply_cfg(struct respip_set* set, struct config_file* cfg)
400 int ret = respip_set_apply_cfg(set, cfg->tagname, cfg->num_tags,
401 cfg->respip_tags, cfg->respip_actions, cfg->respip_data);
402 cfg->respip_data = NULL;
403 cfg->respip_actions = NULL;
404 cfg->respip_tags = NULL;
408 /** Iterate through raw view data and apply the view-specific respip
409 * configuration; at this point we should have already seen all the views,
410 * so if any of the views that respip data refer to does not exist, that's
411 * an error. This additional iteration through view configuration data
412 * is expected to not have significant performance impact (or rather, its
413 * performance impact is not expected to be prohibitive in the configuration
417 respip_views_apply_cfg(struct views* vs, struct config_file* cfg,
418 int* have_view_respip_cfg)
420 struct config_view* cv;
424 for(cv = cfg->views; cv; cv = cv->next) {
426 /** if no respip config for this view then there's
427 * nothing to do; note that even though respip data must go
428 * with respip action, we're checking for both here because
429 * we want to catch the case where the respip action is missing
430 * while the data is present */
431 if(!cv->respip_actions && !cv->respip_data)
434 if(!(v = views_find_view(vs, cv->name, 1))) {
435 log_err("view '%s' unexpectedly missing", cv->name);
439 v->respip_set = respip_set_create();
441 log_err("out of memory");
442 lock_rw_unlock(&v->lock);
446 ret = respip_set_apply_cfg(v->respip_set, NULL, 0, NULL,
447 cv->respip_actions, cv->respip_data);
448 lock_rw_unlock(&v->lock);
450 log_err("Error while applying respip configuration "
451 "for view '%s'", cv->name);
454 *have_view_respip_cfg = (*have_view_respip_cfg ||
455 v->respip_set->ip_tree.count);
456 cv->respip_actions = NULL;
457 cv->respip_data = NULL;
463 * make a deep copy of 'key' in 'region'.
464 * This is largely derived from packed_rrset_copy_region() and
465 * packed_rrset_ptr_fixup(), but differs in the following points:
467 * - It doesn't assume all data in 'key' are in a contiguous memory region.
468 * Although that would be the case in most cases, 'key' can be passed from
469 * a lower-level module and it might not build the rrset to meet the
470 * assumption. In fact, an rrset specified as response-ip-data or generated
471 * in local_data_find_tag_datas() breaks the assumption. So it would be
472 * safer not to naively rely on the assumption. On the other hand, this
473 * function ensures the copied rrset data are in a contiguous region so
474 * that it won't cause a disruption even if an upper layer module naively
475 * assumes the memory layout.
476 * - It doesn't copy RRSIGs (if any) in 'key'. The rrset will be used in
477 * a reply that was already faked, so it doesn't make much sense to provide
478 * partial sigs even if they are valid themselves.
479 * - It doesn't adjust TTLs as it basically has to be a verbatim copy of 'key'
480 * just allocated in 'region' (the assumption is necessary TTL adjustment
481 * has been already done in 'key').
483 * This function returns the copied rrset key on success, and NULL on memory
484 * allocation failure.
486 static struct ub_packed_rrset_key*
487 copy_rrset(const struct ub_packed_rrset_key* key, struct regional* region)
489 struct ub_packed_rrset_key* ck = regional_alloc(region,
490 sizeof(struct ub_packed_rrset_key));
491 struct packed_rrset_data* d;
492 struct packed_rrset_data* data = key->entry.data;
496 /* derived from packed_rrset_copy_region(), but don't use
497 * packed_rrset_sizeof() and do exclude RRSIGs */
501 memset(&ck->entry, 0, sizeof(ck->entry));
502 ck->entry.hash = key->entry.hash;
505 ck->rk.dname = regional_alloc_init(region, key->rk.dname,
510 if((unsigned)data->count >= 0xffff00U)
511 return NULL; /* guard against integer overflow in dsize */
512 dsize = sizeof(struct packed_rrset_data) + data->count *
513 (sizeof(size_t)+sizeof(uint8_t*)+sizeof(time_t));
514 for(i=0; i<data->count; i++) {
515 if((unsigned)dsize >= 0x0fffffffU ||
516 (unsigned)data->rr_len[i] >= 0x0fffffffU)
517 return NULL; /* guard against integer overflow */
518 dsize += data->rr_len[i];
520 d = regional_alloc(region, dsize);
527 /* derived from packed_rrset_ptr_fixup() with copying the data */
528 d->rr_len = (size_t*)((uint8_t*)d + sizeof(struct packed_rrset_data));
529 d->rr_data = (uint8_t**)&(d->rr_len[d->count]);
530 d->rr_ttl = (time_t*)&(d->rr_data[d->count]);
531 nextrdata = (uint8_t*)&(d->rr_ttl[d->count]);
532 for(i=0; i<d->count; i++) {
533 d->rr_len[i] = data->rr_len[i];
534 d->rr_ttl[i] = data->rr_ttl[i];
535 d->rr_data[i] = nextrdata;
536 memcpy(d->rr_data[i], data->rr_data[i], data->rr_len[i]);
537 nextrdata += d->rr_len[i];
544 respip_init(struct module_env* env, int id)
552 respip_deinit(struct module_env* env, int id)
558 /** Convert a packed AAAA or A RRset to sockaddr. */
560 rdata2sockaddr(const struct packed_rrset_data* rd, uint16_t rtype, size_t i,
561 struct sockaddr_storage* ss, socklen_t* addrlenp)
563 /* unbound can accept and cache odd-length AAAA/A records, so we have
564 * to validate the length. */
565 if(rtype == LDNS_RR_TYPE_A && rd->rr_len[i] == 6) {
566 struct sockaddr_in* sa4 = (struct sockaddr_in*)ss;
568 memset(sa4, 0, sizeof(*sa4));
569 sa4->sin_family = AF_INET;
570 memcpy(&sa4->sin_addr, rd->rr_data[i] + 2,
571 sizeof(sa4->sin_addr));
572 *addrlenp = sizeof(*sa4);
574 } else if(rtype == LDNS_RR_TYPE_AAAA && rd->rr_len[i] == 18) {
575 struct sockaddr_in6* sa6 = (struct sockaddr_in6*)ss;
577 memset(sa6, 0, sizeof(*sa6));
578 sa6->sin6_family = AF_INET6;
579 memcpy(&sa6->sin6_addr, rd->rr_data[i] + 2,
580 sizeof(sa6->sin6_addr));
581 *addrlenp = sizeof(*sa6);
588 * Search the given 'iptree' for response address information that matches
589 * any of the IP addresses in an AAAA or A in the answer section of the
590 * response (stored in 'rep'). If found, a pointer to the matched resp_addr
591 * structure will be returned, and '*rrset_id' is set to the index in
592 * rep->rrsets for the RRset that contains the matching IP address record
593 * (the index is normally 0, but can be larger than that if this is a CNAME
594 * chain or type-ANY response).
595 * Returns resp_addr holding read lock.
597 static struct resp_addr*
598 respip_addr_lookup(const struct reply_info *rep, struct respip_set* rs,
602 struct resp_addr* ra;
603 struct sockaddr_storage ss;
606 lock_rw_rdlock(&rs->lock);
607 for(i=0; i<rep->an_numrrsets; i++) {
609 const struct packed_rrset_data* rd;
610 uint16_t rtype = ntohs(rep->rrsets[i]->rk.type);
612 if(rtype != LDNS_RR_TYPE_A && rtype != LDNS_RR_TYPE_AAAA)
614 rd = rep->rrsets[i]->entry.data;
615 for(j = 0; j < rd->count; j++) {
616 if(!rdata2sockaddr(rd, rtype, j, &ss, &addrlen))
618 ra = (struct resp_addr*)addr_tree_lookup(&rs->ip_tree,
622 lock_rw_rdlock(&ra->lock);
623 lock_rw_unlock(&rs->lock);
628 lock_rw_unlock(&rs->lock);
633 * Create a new reply_info based on 'rep'. The new info is based on
634 * the passed 'rep', but ignores any rrsets except for the first 'an_numrrsets'
635 * RRsets in the answer section. These answer rrsets are copied to the
636 * new info, up to 'copy_rrsets' rrsets (which must not be larger than
637 * 'an_numrrsets'). If an_numrrsets > copy_rrsets, the remaining rrsets array
638 * entries will be kept empty so the caller can fill them later. When rrsets
639 * are copied, they are shallow copied. The caller must ensure that the
640 * copied rrsets are valid throughout its lifetime and must provide appropriate
641 * mutex if it can be shared by multiple threads.
643 static struct reply_info *
644 make_new_reply_info(const struct reply_info* rep, struct regional* region,
645 size_t an_numrrsets, size_t copy_rrsets)
647 struct reply_info* new_rep;
650 /* create a base struct. we specify 'insecure' security status as
651 * the modified response won't be DNSSEC-valid. In our faked response
652 * the authority and additional sections will be empty (except possible
653 * EDNS0 OPT RR in the additional section appended on sending it out),
654 * so the total number of RRsets is an_numrrsets. */
655 new_rep = construct_reply_info_base(region, rep->flags,
656 rep->qdcount, rep->ttl, rep->prefetch_ttl,
657 rep->serve_expired_ttl, an_numrrsets, 0, 0, an_numrrsets,
658 sec_status_insecure);
661 if(!reply_info_alloc_rrset_keys(new_rep, NULL, region))
663 for(i=0; i<copy_rrsets; i++)
664 new_rep->rrsets[i] = rep->rrsets[i];
670 * See if response-ip or tag data should override the original answer rrset
671 * (which is rep->rrsets[rrset_id]) and if so override it.
672 * This is (mostly) equivalent to localzone.c:local_data_answer() but for
673 * response-ip actions.
674 * Note that this function distinguishes error conditions from "success but
675 * not overridden". This is because we want to avoid accidentally applying
676 * the "no data" action in case of error.
677 * @param action: action to apply
678 * @param data: RRset to use for override
679 * @param qtype: original query type
680 * @param rep: original reply message
681 * @param rrset_id: the rrset ID in 'rep' to which the action should apply
682 * @param new_repp: see respip_rewrite_reply
683 * @param tag: if >= 0 the tag ID used to determine the action and data
684 * @param tag_datas: data corresponding to 'tag'.
685 * @param tag_datas_size: size of 'tag_datas'
686 * @param tagname: array of tag names, used for logging
687 * @param num_tags: size of 'tagname', used for logging
688 * @param redirect_rrsetp: ptr to redirect record
689 * @param region: region for building new reply
690 * @return 1 if overridden, 0 if not overridden, -1 on error.
693 respip_data_answer(enum respip_action action,
694 struct ub_packed_rrset_key* data,
695 uint16_t qtype, const struct reply_info* rep,
696 size_t rrset_id, struct reply_info** new_repp, int tag,
697 struct config_strlist** tag_datas, size_t tag_datas_size,
698 char* const* tagname, int num_tags,
699 struct ub_packed_rrset_key** redirect_rrsetp, struct regional* region)
701 struct ub_packed_rrset_key* rp = data;
702 struct reply_info* new_rep;
703 *redirect_rrsetp = NULL;
705 if(action == respip_redirect && tag != -1 &&
706 (size_t)tag<tag_datas_size && tag_datas[tag]) {
707 struct query_info dataqinfo;
708 struct ub_packed_rrset_key r;
710 /* Extract parameters of the original answer rrset that can be
711 * rewritten below, in the form of query_info. Note that these
712 * can be different from the info of the original query if the
713 * rrset is a CNAME target.*/
714 memset(&dataqinfo, 0, sizeof(dataqinfo));
715 dataqinfo.qname = rep->rrsets[rrset_id]->rk.dname;
716 dataqinfo.qname_len = rep->rrsets[rrset_id]->rk.dname_len;
717 dataqinfo.qtype = ntohs(rep->rrsets[rrset_id]->rk.type);
718 dataqinfo.qclass = ntohs(rep->rrsets[rrset_id]->rk.rrset_class);
720 memset(&r, 0, sizeof(r));
721 if(local_data_find_tag_datas(&dataqinfo, tag_datas[tag], &r,
724 "response-ip redirect with tag data [%d] %s",
725 tag, (tag<num_tags?tagname[tag]:"null"));
726 /* use copy_rrset() to 'normalize' memory layout */
727 rp = copy_rrset(&r, region);
735 /* If we are using response-ip-data, we need to make a copy of rrset
736 * to replace the rrset's dname. Note that, unlike local data, we
737 * rename the dname for other actions than redirect. This is because
738 * response-ip-data isn't associated to any specific name. */
740 rp = copy_rrset(rp, region);
743 rp->rk.dname = rep->rrsets[rrset_id]->rk.dname;
744 rp->rk.dname_len = rep->rrsets[rrset_id]->rk.dname_len;
747 /* Build a new reply with redirect rrset. We keep any preceding CNAMEs
748 * and replace the address rrset that triggers the action. If it's
749 * type ANY query, however, no other answer records should be kept
750 * (note that it can't be a CNAME chain in this case due to
752 if(qtype == LDNS_RR_TYPE_ANY)
754 new_rep = make_new_reply_info(rep, region, rrset_id + 1, rrset_id);
757 rp->rk.flags |= PACKED_RRSET_FIXEDTTL; /* avoid adjusting TTL */
758 new_rep->rrsets[rrset_id] = rp;
760 *redirect_rrsetp = rp;
766 * apply response ip action in case where no action data is provided.
767 * this is similar to localzone.c:lz_zone_answer() but simplified due to
768 * the characteristics of response ip:
769 * - 'deny' variants will be handled at the caller side
770 * - no specific processing for 'transparent' variants: unlike local zones,
771 * there is no such a case of 'no data but name existing'. so all variants
772 * just mean 'transparent if no data'.
773 * @param qtype: query type
774 * @param action: found action
778 * @param region: region for building new reply
779 * @return 1 on success, 0 on error.
782 respip_nodata_answer(uint16_t qtype, enum respip_action action,
783 const struct reply_info *rep, size_t rrset_id,
784 struct reply_info** new_repp, struct regional* region)
786 struct reply_info* new_rep;
788 if(action == respip_refuse || action == respip_always_refuse) {
789 new_rep = make_new_reply_info(rep, region, 0, 0);
792 FLAGS_SET_RCODE(new_rep->flags, LDNS_RCODE_REFUSED);
795 } else if(action == respip_static || action == respip_redirect ||
796 action == respip_always_nxdomain ||
797 action == respip_always_nodata ||
798 action == respip_inform_redirect) {
799 /* Since we don't know about other types of the owner name,
800 * we generally return NOERROR/NODATA unless an NXDOMAIN action
801 * is explicitly specified. */
802 int rcode = (action == respip_always_nxdomain)?
803 LDNS_RCODE_NXDOMAIN:LDNS_RCODE_NOERROR;
805 /* We should empty the answer section except for any preceding
806 * CNAMEs (in that case rrset_id > 0). Type-ANY case is
807 * special as noted in respip_data_answer(). */
808 if(qtype == LDNS_RR_TYPE_ANY)
810 new_rep = make_new_reply_info(rep, region, rrset_id, rrset_id);
813 FLAGS_SET_RCODE(new_rep->flags, rcode);
821 /** Populate action info structure with the results of response-ip action
822 * processing, iff as the result of response-ip processing we are actually
823 * taking some action. Only action is set if action_only is true.
824 * Returns true on success, false on failure.
827 populate_action_info(struct respip_action_info* actinfo,
828 enum respip_action action, const struct resp_addr* raddr,
829 const struct ub_packed_rrset_key* ATTR_UNUSED(rrset),
830 int ATTR_UNUSED(tag), const struct respip_set* ATTR_UNUSED(ipset),
831 int ATTR_UNUSED(action_only), struct regional* region, int rpz_used,
832 int rpz_log, char* log_name, int rpz_cname_override)
834 if(action == respip_none || !raddr)
836 actinfo->action = action;
837 actinfo->rpz_used = rpz_used;
838 actinfo->rpz_log = rpz_log;
839 actinfo->log_name = log_name;
840 actinfo->rpz_cname_override = rpz_cname_override;
842 /* for inform variants, make a copy of the matched address block for
843 * later logging. We make a copy to proactively avoid disruption if
844 * and when we allow a dynamic update to the respip tree. */
845 if(action == respip_inform || action == respip_inform_deny ||
847 struct respip_addr_info* a =
848 regional_alloc_zero(region, sizeof(*a));
850 log_err("out of memory");
853 a->addr = raddr->node.addr;
854 a->addrlen = raddr->node.addrlen;
855 a->net = raddr->node.net;
856 actinfo->addrinfo = a;
863 respip_use_rpz(struct resp_addr* raddr, struct rpz* r,
864 enum respip_action* action,
865 struct ub_packed_rrset_key** data, int* rpz_log, char** log_name,
866 int* rpz_cname_override, struct regional* region, int* is_rpz)
868 if(r->action_override == RPZ_DISABLED_ACTION) {
872 else if(r->action_override == RPZ_NO_OVERRIDE_ACTION)
873 *action = raddr->action;
875 *action = rpz_action_to_respip_action(r->action_override);
876 if(r->action_override == RPZ_CNAME_OVERRIDE_ACTION &&
878 *data = r->cname_override;
879 *rpz_cname_override = 1;
883 if(!(*log_name = regional_strdup(region, r->log_name)))
890 respip_rewrite_reply(const struct query_info* qinfo,
891 const struct respip_client_info* cinfo, const struct reply_info* rep,
892 struct reply_info** new_repp, struct respip_action_info* actinfo,
893 struct ub_packed_rrset_key** alias_rrset, int search_only,
894 struct regional* region, struct auth_zones* az)
896 const uint8_t* ctaglist;
898 const uint8_t* tag_actions;
899 size_t tag_actions_size;
900 struct config_strlist** tag_datas;
901 size_t tag_datas_size;
902 struct view* view = NULL;
903 struct respip_set* ipset = NULL;
905 enum respip_action action = respip_none;
907 struct resp_addr* raddr = NULL;
909 struct ub_packed_rrset_key* redirect_rrset = NULL;
911 struct ub_packed_rrset_key* data = NULL;
914 int rpz_cname_override = 0;
915 char* log_name = NULL;
919 ctaglist = cinfo->taglist;
920 ctaglen = cinfo->taglen;
921 tag_actions = cinfo->tag_actions;
922 tag_actions_size = cinfo->tag_actions_size;
923 tag_datas = cinfo->tag_datas;
924 tag_datas_size = cinfo->tag_datas_size;
926 ipset = cinfo->respip_set;
930 /** Try to use response-ip config from the view first; use
931 * global response-ip config if we don't have the view or we don't
932 * have the matching per-view config (and the view allows the use
933 * of global data in this case).
934 * Note that we lock the view even if we only use view members that
935 * currently don't change after creation. This is for safety for
936 * future possible changes as the view documentation seems to expect
937 * any of its member can change in the view's lifetime.
938 * Note also that we assume 'view' is valid in this function, which
939 * should be safe (see unbound bug #1191) */
941 lock_rw_rdlock(&view->lock);
942 if(view->respip_set) {
943 if((raddr = respip_addr_lookup(rep,
944 view->respip_set, &rrset_id))) {
945 /** for per-view respip directives the action
946 * can only be direct (i.e. not tag-based) */
947 action = raddr->action;
950 if(!raddr && !view->isfirst)
953 if(!raddr && (raddr = respip_addr_lookup(rep, ipset,
955 action = (enum respip_action)local_data_find_tag_action(
956 raddr->taglist, raddr->taglen, ctaglist, ctaglen,
957 tag_actions, tag_actions_size,
958 (enum localzone_type)raddr->action, &tag,
959 ipset->tagname, ipset->num_tags);
961 lock_rw_rdlock(&az->rpz_lock);
962 for(r = az->rpz_first; r && !raddr; r = r->next) {
963 if(!r->taglist || taglist_intersect(r->taglist,
964 r->taglistlen, ctaglist, ctaglen)) {
965 if((raddr = respip_addr_lookup(rep,
966 r->respip_set, &rrset_id))) {
967 if(!respip_use_rpz(raddr, r, &action, &data,
968 &rpz_log, &log_name, &rpz_cname_override,
969 region, &rpz_used)) {
970 log_err("out of memory");
971 lock_rw_unlock(&raddr->lock);
972 lock_rw_unlock(&az->rpz_lock);
976 lock_rw_unlock(&raddr->lock);
978 actinfo->rpz_disabled++;
983 lock_rw_unlock(&az->rpz_lock);
984 if(raddr && !search_only) {
987 /* first, see if we have response-ip or tag action for the
988 * action except for 'always' variants. */
989 if(action != respip_always_refuse
990 && action != respip_always_transparent
991 && action != respip_always_nxdomain
992 && action != respip_always_nodata
993 && action != respip_always_deny
994 && (result = respip_data_answer(action,
995 (data) ? data : raddr->data, qinfo->qtype, rep,
996 rrset_id, new_repp, tag, tag_datas, tag_datas_size,
997 ipset->tagname, ipset->num_tags, &redirect_rrset,
1003 /* if no action data applied, take action specific to the
1004 * action without data. */
1005 if(!result && !respip_nodata_answer(qinfo->qtype, action, rep,
1006 rrset_id, new_repp, region)) {
1013 lock_rw_unlock(&view->lock);
1016 /* If we're redirecting the original answer to a
1017 * CNAME, record the CNAME rrset so the caller can take
1018 * the appropriate action. Note that we don't check the
1019 * action type; it should normally be 'redirect', but it
1020 * can be of other type when a data-dependent tag action
1021 * uses redirect response-ip data.
1023 if(redirect_rrset &&
1024 redirect_rrset->rk.type == ntohs(LDNS_RR_TYPE_CNAME) &&
1025 qinfo->qtype != LDNS_RR_TYPE_ANY)
1026 *alias_rrset = redirect_rrset;
1027 /* on success, populate respip result structure */
1028 ret = populate_action_info(actinfo, action, raddr,
1029 redirect_rrset, tag, ipset, search_only, region,
1030 rpz_used, rpz_log, log_name, rpz_cname_override);
1033 lock_rw_unlock(&raddr->lock);
1039 generate_cname_request(struct module_qstate* qstate,
1040 struct ub_packed_rrset_key* alias_rrset)
1042 struct module_qstate* subq = NULL;
1043 struct query_info subqi;
1045 memset(&subqi, 0, sizeof(subqi));
1046 get_cname_target(alias_rrset, &subqi.qname, &subqi.qname_len);
1048 return 0; /* unexpected: not a valid CNAME RDATA */
1049 subqi.qtype = qstate->qinfo.qtype;
1050 subqi.qclass = qstate->qinfo.qclass;
1051 fptr_ok(fptr_whitelist_modenv_attach_sub(qstate->env->attach_sub));
1052 return (*qstate->env->attach_sub)(qstate, &subqi, BIT_RD, 0, 0, &subq);
1056 respip_operate(struct module_qstate* qstate, enum module_ev event, int id,
1057 struct outbound_entry* outbound)
1059 struct respip_qstate* rq = (struct respip_qstate*)qstate->minfo[id];
1061 log_query_info(VERB_QUERY, "respip operate: query", &qstate->qinfo);
1064 if(event == module_event_new || event == module_event_pass) {
1066 rq = regional_alloc_zero(qstate->region, sizeof(*rq));
1069 rq->state = RESPIP_INIT;
1070 qstate->minfo[id] = rq;
1072 if(rq->state == RESPIP_SUBQUERY_FINISHED) {
1073 qstate->ext_state[id] = module_finished;
1076 verbose(VERB_ALGO, "respip: pass to next module");
1077 qstate->ext_state[id] = module_wait_module;
1078 } else if(event == module_event_moddone) {
1079 /* If the reply may be subject to response-ip rewriting
1080 * according to the query type, check the actions. If a
1081 * rewrite is necessary, we'll replace the reply in qstate
1082 * with the new one. */
1083 enum module_ext_state next_state = module_finished;
1085 if((qstate->qinfo.qtype == LDNS_RR_TYPE_A ||
1086 qstate->qinfo.qtype == LDNS_RR_TYPE_AAAA ||
1087 qstate->qinfo.qtype == LDNS_RR_TYPE_ANY) &&
1088 qstate->return_msg && qstate->return_msg->rep) {
1089 struct reply_info* new_rep = qstate->return_msg->rep;
1090 struct ub_packed_rrset_key* alias_rrset = NULL;
1091 struct respip_action_info actinfo = {0};
1092 actinfo.action = respip_none;
1094 if(!respip_rewrite_reply(&qstate->qinfo,
1095 qstate->client_info, qstate->return_msg->rep,
1096 &new_rep, &actinfo, &alias_rrset, 0,
1097 qstate->region, qstate->env->auth_zones)) {
1100 if(actinfo.action != respip_none) {
1101 /* save action info for logging on a
1102 * per-front-end-query basis */
1103 if(!(qstate->respip_action_info =
1104 regional_alloc_init(qstate->region,
1105 &actinfo, sizeof(actinfo))))
1107 log_err("out of memory");
1111 qstate->respip_action_info = NULL;
1113 if (actinfo.action == respip_always_deny ||
1114 (new_rep == qstate->return_msg->rep &&
1115 (actinfo.action == respip_deny ||
1116 actinfo.action == respip_inform_deny))) {
1117 /* for deny-variant actions (unless response-ip
1118 * data is applied), mark the query state so
1119 * the response will be dropped for all
1121 qstate->is_drop = 1;
1122 } else if(alias_rrset) {
1123 if(!generate_cname_request(qstate, alias_rrset))
1125 next_state = module_wait_subquery;
1127 qstate->return_msg->rep = new_rep;
1129 qstate->ext_state[id] = next_state;
1131 qstate->ext_state[id] = module_finished;
1136 qstate->return_rcode = LDNS_RCODE_SERVFAIL;
1137 qstate->return_msg = NULL;
1141 respip_merge_cname(struct reply_info* base_rep,
1142 const struct query_info* qinfo, const struct reply_info* tgt_rep,
1143 const struct respip_client_info* cinfo, int must_validate,
1144 struct reply_info** new_repp, struct regional* region,
1145 struct auth_zones* az)
1147 struct reply_info* new_rep;
1148 struct reply_info* tmp_rep = NULL; /* just a placeholder */
1149 struct ub_packed_rrset_key* alias_rrset = NULL; /* ditto */
1152 struct respip_action_info actinfo = {0};
1153 actinfo.action = respip_none;
1155 /* If the query for the CNAME target would result in an unusual rcode,
1156 * we generally translate it as a failure for the base query
1157 * (which would then be translated into SERVFAIL). The only exception
1158 * is NXDOMAIN and YXDOMAIN, which are passed to the end client(s).
1159 * The YXDOMAIN case would be rare but still possible (when
1160 * DNSSEC-validated DNAME has been cached but synthesizing CNAME
1161 * can't be generated due to length limitation) */
1162 tgt_rcode = FLAGS_GET_RCODE(tgt_rep->flags);
1163 if((tgt_rcode != LDNS_RCODE_NOERROR &&
1164 tgt_rcode != LDNS_RCODE_NXDOMAIN &&
1165 tgt_rcode != LDNS_RCODE_YXDOMAIN) ||
1166 (must_validate && tgt_rep->security <= sec_status_bogus)) {
1170 /* see if the target reply would be subject to a response-ip action. */
1171 if(!respip_rewrite_reply(qinfo, cinfo, tgt_rep, &tmp_rep, &actinfo,
1172 &alias_rrset, 1, region, az))
1174 if(actinfo.action != respip_none) {
1175 log_info("CNAME target of redirect response-ip action would "
1176 "be subject to response-ip action, too; stripped");
1177 *new_repp = base_rep;
1181 /* Append target reply to the base. Since we cannot assume
1182 * tgt_rep->rrsets is valid throughout the lifetime of new_rep
1183 * or it can be safely shared by multiple threads, we need to make a
1185 new_rep = make_new_reply_info(base_rep, region,
1186 base_rep->an_numrrsets + tgt_rep->an_numrrsets,
1187 base_rep->an_numrrsets);
1190 for(i=0,j=base_rep->an_numrrsets; i<tgt_rep->an_numrrsets; i++,j++) {
1191 new_rep->rrsets[j] = copy_rrset(tgt_rep->rrsets[i], region);
1192 if(!new_rep->rrsets[j])
1196 FLAGS_SET_RCODE(new_rep->flags, tgt_rcode);
1197 *new_repp = new_rep;
1202 respip_inform_super(struct module_qstate* qstate, int id,
1203 struct module_qstate* super)
1205 struct respip_qstate* rq = (struct respip_qstate*)super->minfo[id];
1206 struct reply_info* new_rep = NULL;
1208 rq->state = RESPIP_SUBQUERY_FINISHED;
1210 /* respip subquery should have always been created with a valid reply
1212 log_assert(super->return_msg && super->return_msg->rep);
1214 /* return_msg can be NULL when, e.g., the sub query resulted in
1215 * SERVFAIL, in which case we regard it as a failure of the original
1216 * query. Other checks are probably redundant, but we check them
1218 if(!qstate->return_msg || !qstate->return_msg->rep ||
1219 qstate->return_rcode != LDNS_RCODE_NOERROR)
1222 if(!respip_merge_cname(super->return_msg->rep, &qstate->qinfo,
1223 qstate->return_msg->rep, super->client_info,
1224 super->env->need_to_validate, &new_rep, super->region,
1225 qstate->env->auth_zones))
1227 super->return_msg->rep = new_rep;
1231 super->return_rcode = LDNS_RCODE_SERVFAIL;
1232 super->return_msg = NULL;
1237 respip_clear(struct module_qstate* qstate, int id)
1239 qstate->minfo[id] = NULL;
1243 respip_get_mem(struct module_env* env, int id)
1251 * The response-ip function block
1253 static struct module_func_block respip_block = {
1255 &respip_init, &respip_deinit, &respip_operate, &respip_inform_super,
1256 &respip_clear, &respip_get_mem
1259 struct module_func_block*
1260 respip_get_funcblock(void)
1262 return &respip_block;
1266 resp_addr_get_action(const struct resp_addr* addr)
1268 return addr ? addr->action : respip_none;
1271 struct ub_packed_rrset_key*
1272 resp_addr_get_rrset(struct resp_addr* addr)
1274 return addr ? addr->data : NULL;
1278 respip_set_is_empty(const struct respip_set* set)
1280 return set ? set->ip_tree.count == 0 : 1;
1284 respip_inform_print(struct respip_action_info* respip_actinfo, uint8_t* qname,
1285 uint16_t qtype, uint16_t qclass, struct local_rrset* local_alias,
1286 struct comm_reply* repinfo)
1288 char srcip[128], respip[128], txt[512];
1290 struct respip_addr_info* respip_addr = respip_actinfo->addrinfo;
1292 const char* actionstr = NULL;
1295 qname = local_alias->rrset->rk.dname;
1296 port = (unsigned)((repinfo->addr.ss_family == AF_INET) ?
1297 ntohs(((struct sockaddr_in*)&repinfo->addr)->sin_port) :
1298 ntohs(((struct sockaddr_in6*)&repinfo->addr)->sin6_port));
1299 addr_to_str(&repinfo->addr, repinfo->addrlen, srcip, sizeof(srcip));
1300 addr_to_str(&respip_addr->addr, respip_addr->addrlen,
1301 respip, sizeof(respip));
1302 if(respip_actinfo->rpz_log) {
1303 txtlen += snprintf(txt+txtlen, sizeof(txt)-txtlen, "%s",
1305 if(respip_actinfo->rpz_cname_override)
1306 actionstr = rpz_action_to_string(
1307 RPZ_CNAME_OVERRIDE_ACTION);
1309 actionstr = rpz_action_to_string(
1310 respip_action_to_rpz_action(
1311 respip_actinfo->action));
1313 if(respip_actinfo->log_name) {
1314 txtlen += snprintf(txt+txtlen, sizeof(txt)-txtlen,
1315 "[%s] ", respip_actinfo->log_name);
1317 snprintf(txt+txtlen, sizeof(txt)-txtlen,
1318 "%s/%d %s %s@%u", respip, respip_addr->net,
1319 (actionstr) ? actionstr : "inform", srcip, port);
1320 log_nametypeclass(NO_VERBOSE, txt, qname, qtype, qclass);