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/cache/dns.h"
16 #include "sldns/str2wire.h"
17 #include "util/config_file.h"
18 #include "util/fptr_wlist.h"
19 #include "util/module.h"
20 #include "util/net_help.h"
21 #include "util/regional.h"
22 #include "util/data/msgreply.h"
23 #include "util/storage/dnstree.h"
24 #include "respip/respip.h"
25 #include "services/view.h"
26 #include "sldns/rrdef.h"
29 * Conceptual set of IP addresses for response AAAA or A records that should
30 * trigger special actions.
33 struct regional* region;
34 struct rbtree_type ip_tree;
35 char* const* tagname; /* shallow copy of tag names, for logging */
36 int num_tags; /* number of tagname entries */
39 /** An address span with response control information */
41 /** node in address tree */
42 struct addr_tree_node node;
45 /** length of the taglist (in bytes) */
47 /** action for this address span */
48 enum respip_action action;
49 /** "local data" for this node */
50 struct ub_packed_rrset_key* data;
53 /** Subset of resp_addr.node, used for inform-variant logging */
54 struct respip_addr_info {
55 struct sockaddr_storage addr;
60 /** Query state regarding the response-ip module. */
63 * The general state. Unless CNAME chasing takes place, all processing
64 * is completed in this state without any other asynchronous event.
69 * A subquery for CNAME chasing is completed.
71 RESPIP_SUBQUERY_FINISHED
74 /** Per query state for the response-ip module. */
75 struct respip_qstate {
76 enum respip_state state;
80 respip_set_create(void)
82 struct respip_set* set = calloc(1, sizeof(*set));
85 set->region = regional_create();
90 addr_tree_init(&set->ip_tree);
95 respip_set_delete(struct respip_set* set)
99 regional_destroy(set->region);
104 respip_set_get_tree(struct respip_set* set)
108 return &set->ip_tree;
111 /** returns the node in the address tree for the specified netblock string;
112 * non-existent node will be created if 'create' is true */
113 static struct resp_addr*
114 respip_find_or_create(struct respip_set* set, const char* ipstr, int create)
116 struct resp_addr* node;
117 struct sockaddr_storage addr;
121 if(!netblockstrtoaddr(ipstr, 0, &addr, &addrlen, &net)) {
122 log_err("cannot parse netblock: '%s'", ipstr);
125 node = (struct resp_addr*)addr_tree_find(&set->ip_tree, &addr, addrlen, net);
126 if(!node && create) {
127 node = regional_alloc_zero(set->region, sizeof(*node));
129 log_err("out of memory");
132 node->action = respip_none;
133 if(!addr_tree_insert(&set->ip_tree, &node->node, &addr,
135 /* We know we didn't find it, so this should be
137 log_warn("unexpected: duplicate address: %s", ipstr);
144 respip_tag_cfg(struct respip_set* set, const char* ipstr,
145 const uint8_t* taglist, size_t taglen)
147 struct resp_addr* node;
149 if(!(node=respip_find_or_create(set, ipstr, 1)))
152 log_warn("duplicate response-address-tag for '%s', overridden.",
155 node->taglist = regional_alloc_init(set->region, taglist, taglen);
157 log_err("out of memory");
160 node->taglen = taglen;
164 /** set action for the node specified by the netblock string */
166 respip_action_cfg(struct respip_set* set, const char* ipstr,
169 struct resp_addr* node;
170 enum respip_action action;
172 if(!(node=respip_find_or_create(set, ipstr, 1)))
174 if(node->action != respip_none) {
175 log_warn("duplicate response-ip action for '%s', overridden.",
178 if(strcmp(actnstr, "deny") == 0)
179 action = respip_deny;
180 else if(strcmp(actnstr, "redirect") == 0)
181 action = respip_redirect;
182 else if(strcmp(actnstr, "inform") == 0)
183 action = respip_inform;
184 else if(strcmp(actnstr, "inform_deny") == 0)
185 action = respip_inform_deny;
186 else if(strcmp(actnstr, "always_transparent") == 0)
187 action = respip_always_transparent;
188 else if(strcmp(actnstr, "always_refuse") == 0)
189 action = respip_always_refuse;
190 else if(strcmp(actnstr, "always_nxdomain") == 0)
191 action = respip_always_nxdomain;
193 log_err("unknown response-ip action %s", actnstr);
196 node->action = action;
200 /** allocate and initialize an rrset structure; this function is based
201 * on new_local_rrset() from the localzone.c module */
202 static struct ub_packed_rrset_key*
203 new_rrset(struct regional* region, uint16_t rrtype, uint16_t rrclass)
205 struct packed_rrset_data* pd;
206 struct ub_packed_rrset_key* rrset = regional_alloc_zero(
207 region, sizeof(*rrset));
209 log_err("out of memory");
212 rrset->entry.key = rrset;
213 pd = regional_alloc_zero(region, sizeof(*pd));
215 log_err("out of memory");
218 pd->trust = rrset_trust_prim_noglue;
219 pd->security = sec_status_insecure;
220 rrset->entry.data = pd;
221 rrset->rk.dname = regional_alloc_zero(region, 1);
222 if(!rrset->rk.dname) {
223 log_err("out of memory");
226 rrset->rk.dname_len = 1;
227 rrset->rk.type = htons(rrtype);
228 rrset->rk.rrset_class = htons(rrclass);
232 /** enter local data as resource records into a response-ip node */
234 respip_enter_rr(struct regional* region, struct resp_addr* raddr,
235 const char* rrstr, const char* netblock)
238 uint16_t rrtype = 0, rrclass = 0;
240 uint8_t rr[LDNS_RR_BUF_SIZE];
241 uint8_t* rdata = NULL;
242 size_t rdata_len = 0;
245 struct packed_rrset_data* pd;
248 if(raddr->action != respip_redirect) {
249 log_err("cannot parse response-ip-data %s: response-ip "
250 "action for %s is not redirect", rrstr, netblock);
253 ret = snprintf(buf, sizeof(buf), ". %s", rrstr);
254 if(ret < 0 || ret >= (int)sizeof(buf)) {
255 strlcpy(bufshort, rrstr, sizeof(bufshort));
256 log_err("bad response-ip-data: %s...", bufshort);
259 if(!rrstr_get_rr_content(buf, &nm, &rrtype, &rrclass, &ttl, rr, sizeof(rr),
260 &rdata, &rdata_len)) {
261 log_err("bad response-ip-data: %s", rrstr);
264 sa = (struct sockaddr*)&raddr->node.addr;
265 if (rrtype == LDNS_RR_TYPE_CNAME && raddr->data) {
266 log_err("CNAME response-ip data (%s) can not co-exist with other "
267 "response-ip data for netblock %s", rrstr, netblock);
269 } else if (raddr->data &&
270 raddr->data->rk.type == htons(LDNS_RR_TYPE_CNAME)) {
271 log_err("response-ip data (%s) can not be added; CNAME response-ip "
272 "data already in place for netblock %s", rrstr, netblock);
274 } else if((rrtype != LDNS_RR_TYPE_CNAME) &&
275 ((sa->sa_family == AF_INET && rrtype != LDNS_RR_TYPE_A) ||
276 (sa->sa_family == AF_INET6 && rrtype != LDNS_RR_TYPE_AAAA))) {
277 log_err("response-ip data %s record type does not correspond "
278 "to netblock %s address family", rrstr, netblock);
283 raddr->data = new_rrset(region, rrtype, rrclass);
287 pd = raddr->data->entry.data;
288 return rrset_insert_rr(region, pd, rdata, rdata_len, ttl, rrstr);
292 respip_data_cfg(struct respip_set* set, const char* ipstr, const char* rrstr)
294 struct resp_addr* node;
296 node=respip_find_or_create(set, ipstr, 0);
297 if(!node || node->action == respip_none) {
298 log_err("cannot parse response-ip-data %s: "
299 "response-ip node for %s not found", rrstr, ipstr);
302 return respip_enter_rr(set->region, node, rrstr, ipstr);
306 respip_set_apply_cfg(struct respip_set* set, char* const* tagname, int num_tags,
307 struct config_strbytelist* respip_tags,
308 struct config_str2list* respip_actions,
309 struct config_str2list* respip_data)
311 struct config_strbytelist* p;
312 struct config_str2list* pa;
313 struct config_str2list* pd;
315 set->tagname = tagname;
316 set->num_tags = num_tags;
320 struct config_strbytelist* np = p->next;
322 log_assert(p->str && p->str2);
323 if(!respip_tag_cfg(set, p->str, p->str2, p->str2len)) {
324 config_del_strbytelist(p);
335 struct config_str2list* np = pa->next;
336 log_assert(pa->str && pa->str2);
337 if(!respip_action_cfg(set, pa->str, pa->str2)) {
338 config_deldblstrlist(pa);
349 struct config_str2list* np = pd->next;
350 log_assert(pd->str && pd->str2);
351 if(!respip_data_cfg(set, pd->str, pd->str2)) {
352 config_deldblstrlist(pd);
365 respip_global_apply_cfg(struct respip_set* set, struct config_file* cfg)
367 int ret = respip_set_apply_cfg(set, cfg->tagname, cfg->num_tags,
368 cfg->respip_tags, cfg->respip_actions, cfg->respip_data);
369 cfg->respip_data = NULL;
370 cfg->respip_actions = NULL;
371 cfg->respip_tags = NULL;
375 /** Iterate through raw view data and apply the view-specific respip
376 * configuration; at this point we should have already seen all the views,
377 * so if any of the views that respip data refer to does not exist, that's
378 * an error. This additional iteration through view configuration data
379 * is expected to not have significant performance impact (or rather, its
380 * performance impact is not expected to be prohibitive in the configuration
384 respip_views_apply_cfg(struct views* vs, struct config_file* cfg,
385 int* have_view_respip_cfg)
387 struct config_view* cv;
391 for(cv = cfg->views; cv; cv = cv->next) {
393 /** if no respip config for this view then there's
394 * nothing to do; note that even though respip data must go
395 * with respip action, we're checking for both here because
396 * we want to catch the case where the respip action is missing
397 * while the data is present */
398 if(!cv->respip_actions && !cv->respip_data)
401 if(!(v = views_find_view(vs, cv->name, 1))) {
402 log_err("view '%s' unexpectedly missing", cv->name);
406 v->respip_set = respip_set_create();
408 log_err("out of memory");
409 lock_rw_unlock(&v->lock);
413 ret = respip_set_apply_cfg(v->respip_set, NULL, 0, NULL,
414 cv->respip_actions, cv->respip_data);
415 lock_rw_unlock(&v->lock);
417 log_err("Error while applying respip configuration "
418 "for view '%s'", cv->name);
421 *have_view_respip_cfg = (*have_view_respip_cfg ||
422 v->respip_set->ip_tree.count);
423 cv->respip_actions = NULL;
424 cv->respip_data = NULL;
430 * make a deep copy of 'key' in 'region'.
431 * This is largely derived from packed_rrset_copy_region() and
432 * packed_rrset_ptr_fixup(), but differs in the following points:
434 * - It doesn't assume all data in 'key' are in a contiguous memory region.
435 * Although that would be the case in most cases, 'key' can be passed from
436 * a lower-level module and it might not build the rrset to meet the
437 * assumption. In fact, an rrset specified as response-ip-data or generated
438 * in local_data_find_tag_datas() breaks the assumption. So it would be
439 * safer not to naively rely on the assumption. On the other hand, this
440 * function ensures the copied rrset data are in a contiguous region so
441 * that it won't cause a disruption even if an upper layer module naively
442 * assumes the memory layout.
443 * - It doesn't copy RRSIGs (if any) in 'key'. The rrset will be used in
444 * a reply that was already faked, so it doesn't make much sense to provide
445 * partial sigs even if they are valid themselves.
446 * - It doesn't adjust TTLs as it basically has to be a verbatim copy of 'key'
447 * just allocated in 'region' (the assumption is necessary TTL adjustment
448 * has been already done in 'key').
450 * This function returns the copied rrset key on success, and NULL on memory
451 * allocation failure.
453 struct ub_packed_rrset_key*
454 copy_rrset(const struct ub_packed_rrset_key* key, struct regional* region)
456 struct ub_packed_rrset_key* ck = regional_alloc(region,
457 sizeof(struct ub_packed_rrset_key));
458 struct packed_rrset_data* d;
459 struct packed_rrset_data* data = key->entry.data;
463 /* derived from packed_rrset_copy_region(), but don't use
464 * packed_rrset_sizeof() and do exclude RRSIGs */
468 memset(&ck->entry, 0, sizeof(ck->entry));
469 ck->entry.hash = key->entry.hash;
472 ck->rk.dname = regional_alloc_init(region, key->rk.dname,
477 dsize = sizeof(struct packed_rrset_data) + data->count *
478 (sizeof(size_t)+sizeof(uint8_t*)+sizeof(time_t));
479 for(i=0; i<data->count; i++)
480 dsize += data->rr_len[i];
481 d = regional_alloc(region, dsize);
488 /* derived from packed_rrset_ptr_fixup() with copying the data */
489 d->rr_len = (size_t*)((uint8_t*)d + sizeof(struct packed_rrset_data));
490 d->rr_data = (uint8_t**)&(d->rr_len[d->count]);
491 d->rr_ttl = (time_t*)&(d->rr_data[d->count]);
492 nextrdata = (uint8_t*)&(d->rr_ttl[d->count]);
493 for(i=0; i<d->count; i++) {
494 d->rr_len[i] = data->rr_len[i];
495 d->rr_ttl[i] = data->rr_ttl[i];
496 d->rr_data[i] = nextrdata;
497 memcpy(d->rr_data[i], data->rr_data[i], data->rr_len[i]);
498 nextrdata += d->rr_len[i];
505 respip_init(struct module_env* env, int id)
513 respip_deinit(struct module_env* env, int id)
519 /** Convert a packed AAAA or A RRset to sockaddr. */
521 rdata2sockaddr(const struct packed_rrset_data* rd, uint16_t rtype, size_t i,
522 struct sockaddr_storage* ss, socklen_t* addrlenp)
524 /* unbound can accept and cache odd-length AAAA/A records, so we have
525 * to validate the length. */
526 if(rtype == LDNS_RR_TYPE_A && rd->rr_len[i] == 6) {
527 struct sockaddr_in* sa4 = (struct sockaddr_in*)ss;
529 memset(sa4, 0, sizeof(*sa4));
530 sa4->sin_family = AF_INET;
531 memcpy(&sa4->sin_addr, rd->rr_data[i] + 2,
532 sizeof(sa4->sin_addr));
533 *addrlenp = sizeof(*sa4);
535 } else if(rtype == LDNS_RR_TYPE_AAAA && rd->rr_len[i] == 18) {
536 struct sockaddr_in6* sa6 = (struct sockaddr_in6*)ss;
538 memset(sa6, 0, sizeof(*sa6));
539 sa6->sin6_family = AF_INET6;
540 memcpy(&sa6->sin6_addr, rd->rr_data[i] + 2,
541 sizeof(sa6->sin6_addr));
542 *addrlenp = sizeof(*sa6);
549 * Search the given 'iptree' for response address information that matches
550 * any of the IP addresses in an AAAA or A in the answer section of the
551 * response (stored in 'rep'). If found, a pointer to the matched resp_addr
552 * structure will be returned, and '*rrset_id' is set to the index in
553 * rep->rrsets for the RRset that contains the matching IP address record
554 * (the index is normally 0, but can be larger than that if this is a CNAME
555 * chain or type-ANY response).
557 static const struct resp_addr*
558 respip_addr_lookup(const struct reply_info *rep, struct rbtree_type* iptree,
562 struct resp_addr* ra;
563 struct sockaddr_storage ss;
566 for(i=0; i<rep->an_numrrsets; i++) {
568 const struct packed_rrset_data* rd;
569 uint16_t rtype = ntohs(rep->rrsets[i]->rk.type);
571 if(rtype != LDNS_RR_TYPE_A && rtype != LDNS_RR_TYPE_AAAA)
573 rd = rep->rrsets[i]->entry.data;
574 for(j = 0; j < rd->count; j++) {
575 if(!rdata2sockaddr(rd, rtype, j, &ss, &addrlen))
577 ra = (struct resp_addr*)addr_tree_lookup(iptree, &ss,
590 * Create a new reply_info based on 'rep'. The new info is based on
591 * the passed 'rep', but ignores any rrsets except for the first 'an_numrrsets'
592 * RRsets in the answer section. These answer rrsets are copied to the
593 * new info, up to 'copy_rrsets' rrsets (which must not be larger than
594 * 'an_numrrsets'). If an_numrrsets > copy_rrsets, the remaining rrsets array
595 * entries will be kept empty so the caller can fill them later. When rrsets
596 * are copied, they are shallow copied. The caller must ensure that the
597 * copied rrsets are valid throughout its lifetime and must provide appropriate
598 * mutex if it can be shared by multiple threads.
600 static struct reply_info *
601 make_new_reply_info(const struct reply_info* rep, struct regional* region,
602 size_t an_numrrsets, size_t copy_rrsets)
604 struct reply_info* new_rep;
607 /* create a base struct. we specify 'insecure' security status as
608 * the modified response won't be DNSSEC-valid. In our faked response
609 * the authority and additional sections will be empty (except possible
610 * EDNS0 OPT RR in the additional section appended on sending it out),
611 * so the total number of RRsets is an_numrrsets. */
612 new_rep = construct_reply_info_base(region, rep->flags,
613 rep->qdcount, rep->ttl, rep->prefetch_ttl, an_numrrsets,
614 0, 0, an_numrrsets, sec_status_insecure);
617 if(!reply_info_alloc_rrset_keys(new_rep, NULL, region))
619 for(i=0; i<copy_rrsets; i++)
620 new_rep->rrsets[i] = rep->rrsets[i];
626 * See if response-ip or tag data should override the original answer rrset
627 * (which is rep->rrsets[rrset_id]) and if so override it.
628 * This is (mostly) equivalent to localzone.c:local_data_answer() but for
629 * response-ip actions.
630 * Note that this function distinguishes error conditions from "success but
631 * not overridden". This is because we want to avoid accidentally applying
632 * the "no data" action in case of error.
633 * @param raddr: address span that requires an action
634 * @param action: action to apply
635 * @param qtype: original query type
636 * @param rep: original reply message
637 * @param rrset_id: the rrset ID in 'rep' to which the action should apply
638 * @param new_repp: see respip_rewrite_reply
639 * @param tag: if >= 0 the tag ID used to determine the action and data
640 * @param tag_datas: data corresponding to 'tag'.
641 * @param tag_datas_size: size of 'tag_datas'
642 * @param tagname: array of tag names, used for logging
643 * @param num_tags: size of 'tagname', used for logging
644 * @param redirect_rrsetp: ptr to redirect record
645 * @param region: region for building new reply
646 * @return 1 if overridden, 0 if not overridden, -1 on error.
649 respip_data_answer(const struct resp_addr* raddr, enum respip_action action,
650 uint16_t qtype, const struct reply_info* rep,
651 size_t rrset_id, struct reply_info** new_repp, int tag,
652 struct config_strlist** tag_datas, size_t tag_datas_size,
653 char* const* tagname, int num_tags,
654 struct ub_packed_rrset_key** redirect_rrsetp, struct regional* region)
656 struct ub_packed_rrset_key* rp = raddr->data;
657 struct reply_info* new_rep;
658 *redirect_rrsetp = NULL;
660 if(action == respip_redirect && tag != -1 &&
661 (size_t)tag<tag_datas_size && tag_datas[tag]) {
662 struct query_info dataqinfo;
663 struct ub_packed_rrset_key r;
665 /* Extract parameters of the original answer rrset that can be
666 * rewritten below, in the form of query_info. Note that these
667 * can be different from the info of the original query if the
668 * rrset is a CNAME target.*/
669 memset(&dataqinfo, 0, sizeof(dataqinfo));
670 dataqinfo.qname = rep->rrsets[rrset_id]->rk.dname;
671 dataqinfo.qname_len = rep->rrsets[rrset_id]->rk.dname_len;
672 dataqinfo.qtype = ntohs(rep->rrsets[rrset_id]->rk.type);
673 dataqinfo.qclass = ntohs(rep->rrsets[rrset_id]->rk.rrset_class);
675 memset(&r, 0, sizeof(r));
676 if(local_data_find_tag_datas(&dataqinfo, tag_datas[tag], &r,
679 "response-ip redirect with tag data [%d] %s",
680 tag, (tag<num_tags?tagname[tag]:"null"));
681 /* use copy_rrset() to 'normalize' memory layout */
682 rp = copy_rrset(&r, region);
690 /* If we are using response-ip-data, we need to make a copy of rrset
691 * to replace the rrset's dname. Note that, unlike local data, we
692 * rename the dname for other actions than redirect. This is because
693 * response-ip-data isn't associated to any specific name. */
694 if(rp == raddr->data) {
695 rp = copy_rrset(rp, region);
698 rp->rk.dname = rep->rrsets[rrset_id]->rk.dname;
699 rp->rk.dname_len = rep->rrsets[rrset_id]->rk.dname_len;
702 /* Build a new reply with redirect rrset. We keep any preceding CNAMEs
703 * and replace the address rrset that triggers the action. If it's
704 * type ANY query, however, no other answer records should be kept
705 * (note that it can't be a CNAME chain in this case due to
707 if(qtype == LDNS_RR_TYPE_ANY)
709 new_rep = make_new_reply_info(rep, region, rrset_id + 1, rrset_id);
712 rp->rk.flags |= PACKED_RRSET_FIXEDTTL; /* avoid adjusting TTL */
713 new_rep->rrsets[rrset_id] = rp;
715 *redirect_rrsetp = rp;
721 * apply response ip action in case where no action data is provided.
722 * this is similar to localzone.c:lz_zone_answer() but simplified due to
723 * the characteristics of response ip:
724 * - 'deny' variants will be handled at the caller side
725 * - no specific processing for 'transparent' variants: unlike local zones,
726 * there is no such a case of 'no data but name existing'. so all variants
727 * just mean 'transparent if no data'.
728 * @param qtype: query type
729 * @param action: found action
733 * @param region: region for building new reply
734 * @return 1 on success, 0 on error.
737 respip_nodata_answer(uint16_t qtype, enum respip_action action,
738 const struct reply_info *rep, size_t rrset_id,
739 struct reply_info** new_repp, struct regional* region)
741 struct reply_info* new_rep;
743 if(action == respip_refuse || action == respip_always_refuse) {
744 new_rep = make_new_reply_info(rep, region, 0, 0);
747 FLAGS_SET_RCODE(new_rep->flags, LDNS_RCODE_REFUSED);
750 } else if(action == respip_static || action == respip_redirect ||
751 action == respip_always_nxdomain) {
752 /* Since we don't know about other types of the owner name,
753 * we generally return NOERROR/NODATA unless an NXDOMAIN action
754 * is explicitly specified. */
755 int rcode = (action == respip_always_nxdomain)?
756 LDNS_RCODE_NXDOMAIN:LDNS_RCODE_NOERROR;
758 /* We should empty the answer section except for any preceding
759 * CNAMEs (in that case rrset_id > 0). Type-ANY case is
760 * special as noted in respip_data_answer(). */
761 if(qtype == LDNS_RR_TYPE_ANY)
763 new_rep = make_new_reply_info(rep, region, rrset_id, rrset_id);
766 FLAGS_SET_RCODE(new_rep->flags, rcode);
774 /** Populate action info structure with the results of response-ip action
775 * processing, iff as the result of response-ip processing we are actually
776 * taking some action. Only action is set if action_only is true.
777 * Returns true on success, false on failure.
780 populate_action_info(struct respip_action_info* actinfo,
781 enum respip_action action, const struct resp_addr* raddr,
782 const struct ub_packed_rrset_key* ATTR_UNUSED(rrset),
783 int ATTR_UNUSED(tag), const struct respip_set* ATTR_UNUSED(ipset),
784 int ATTR_UNUSED(action_only), struct regional* region)
786 if(action == respip_none || !raddr)
788 actinfo->action = action;
790 /* for inform variants, make a copy of the matched address block for
791 * later logging. We make a copy to proactively avoid disruption if
792 * and when we allow a dynamic update to the respip tree. */
793 if(action == respip_inform || action == respip_inform_deny) {
794 struct respip_addr_info* a =
795 regional_alloc_zero(region, sizeof(*a));
797 log_err("out of memory");
800 a->addr = raddr->node.addr;
801 a->addrlen = raddr->node.addrlen;
802 a->net = raddr->node.net;
803 actinfo->addrinfo = a;
810 respip_rewrite_reply(const struct query_info* qinfo,
811 const struct respip_client_info* cinfo, const struct reply_info* rep,
812 struct reply_info** new_repp, struct respip_action_info* actinfo,
813 struct ub_packed_rrset_key** alias_rrset, int search_only,
814 struct regional* region)
816 const uint8_t* ctaglist;
818 const uint8_t* tag_actions;
819 size_t tag_actions_size;
820 struct config_strlist** tag_datas;
821 size_t tag_datas_size;
822 struct view* view = NULL;
823 struct respip_set* ipset = NULL;
825 enum respip_action action = respip_none;
827 const struct resp_addr* raddr = NULL;
829 struct ub_packed_rrset_key* redirect_rrset = NULL;
833 ctaglist = cinfo->taglist;
834 ctaglen = cinfo->taglen;
835 tag_actions = cinfo->tag_actions;
836 tag_actions_size = cinfo->tag_actions_size;
837 tag_datas = cinfo->tag_datas;
838 tag_datas_size = cinfo->tag_datas_size;
840 ipset = cinfo->respip_set;
842 /** Try to use response-ip config from the view first; use
843 * global response-ip config if we don't have the view or we don't
844 * have the matching per-view config (and the view allows the use
845 * of global data in this case).
846 * Note that we lock the view even if we only use view members that
847 * currently don't change after creation. This is for safety for
848 * future possible changes as the view documentation seems to expect
849 * any of its member can change in the view's lifetime.
850 * Note also that we assume 'view' is valid in this function, which
851 * should be safe (see unbound bug #1191) */
853 lock_rw_rdlock(&view->lock);
854 if(view->respip_set) {
855 if((raddr = respip_addr_lookup(rep,
856 &view->respip_set->ip_tree, &rrset_id))) {
857 /** for per-view respip directives the action
858 * can only be direct (i.e. not tag-based) */
859 action = raddr->action;
862 if(!raddr && !view->isfirst)
865 if(!raddr && ipset && (raddr = respip_addr_lookup(rep, &ipset->ip_tree,
867 action = (enum respip_action)local_data_find_tag_action(
868 raddr->taglist, raddr->taglen, ctaglist, ctaglen,
869 tag_actions, tag_actions_size,
870 (enum localzone_type)raddr->action, &tag,
871 ipset->tagname, ipset->num_tags);
873 if(raddr && !search_only) {
876 /* first, see if we have response-ip or tag action for the
877 * action except for 'always' variants. */
878 if(action != respip_always_refuse
879 && action != respip_always_transparent
880 && action != respip_always_nxdomain
881 && (result = respip_data_answer(raddr, action,
882 qinfo->qtype, rep, rrset_id, new_repp, tag, tag_datas,
883 tag_datas_size, ipset->tagname, ipset->num_tags,
884 &redirect_rrset, region)) < 0) {
889 /* if no action data applied, take action specific to the
890 * action without data. */
891 if(!result && !respip_nodata_answer(qinfo->qtype, action, rep,
892 rrset_id, new_repp, region)) {
899 lock_rw_unlock(&view->lock);
902 /* If we're redirecting the original answer to a
903 * CNAME, record the CNAME rrset so the caller can take
904 * the appropriate action. Note that we don't check the
905 * action type; it should normally be 'redirect', but it
906 * can be of other type when a data-dependent tag action
907 * uses redirect response-ip data.
910 redirect_rrset->rk.type == ntohs(LDNS_RR_TYPE_CNAME) &&
911 qinfo->qtype != LDNS_RR_TYPE_ANY)
912 *alias_rrset = redirect_rrset;
913 /* on success, populate respip result structure */
914 ret = populate_action_info(actinfo, action, raddr,
915 redirect_rrset, tag, ipset, search_only, region);
921 generate_cname_request(struct module_qstate* qstate,
922 struct ub_packed_rrset_key* alias_rrset)
924 struct module_qstate* subq = NULL;
925 struct query_info subqi;
927 memset(&subqi, 0, sizeof(subqi));
928 get_cname_target(alias_rrset, &subqi.qname, &subqi.qname_len);
930 return 0; /* unexpected: not a valid CNAME RDATA */
931 subqi.qtype = qstate->qinfo.qtype;
932 subqi.qclass = qstate->qinfo.qclass;
933 fptr_ok(fptr_whitelist_modenv_attach_sub(qstate->env->attach_sub));
934 return (*qstate->env->attach_sub)(qstate, &subqi, BIT_RD, 0, 0, &subq);
938 respip_operate(struct module_qstate* qstate, enum module_ev event, int id,
939 struct outbound_entry* outbound)
941 struct respip_qstate* rq = (struct respip_qstate*)qstate->minfo[id];
943 log_query_info(VERB_QUERY, "respip operate: query", &qstate->qinfo);
946 if(event == module_event_new || event == module_event_pass) {
948 rq = regional_alloc_zero(qstate->region, sizeof(*rq));
951 rq->state = RESPIP_INIT;
952 qstate->minfo[id] = rq;
954 if(rq->state == RESPIP_SUBQUERY_FINISHED) {
955 qstate->ext_state[id] = module_finished;
958 verbose(VERB_ALGO, "respip: pass to next module");
959 qstate->ext_state[id] = module_wait_module;
960 } else if(event == module_event_moddone) {
961 /* If the reply may be subject to response-ip rewriting
962 * according to the query type, check the actions. If a
963 * rewrite is necessary, we'll replace the reply in qstate
964 * with the new one. */
965 enum module_ext_state next_state = module_finished;
967 if((qstate->qinfo.qtype == LDNS_RR_TYPE_A ||
968 qstate->qinfo.qtype == LDNS_RR_TYPE_AAAA ||
969 qstate->qinfo.qtype == LDNS_RR_TYPE_ANY) &&
970 qstate->return_msg && qstate->return_msg->rep) {
971 struct respip_action_info actinfo = {respip_none, NULL};
972 struct reply_info* new_rep = qstate->return_msg->rep;
973 struct ub_packed_rrset_key* alias_rrset = NULL;
975 if(!respip_rewrite_reply(&qstate->qinfo,
976 qstate->client_info, qstate->return_msg->rep,
977 &new_rep, &actinfo, &alias_rrset, 0,
981 if(actinfo.action != respip_none) {
982 /* save action info for logging on a
983 * per-front-end-query basis */
984 if(!(qstate->respip_action_info =
985 regional_alloc_init(qstate->region,
986 &actinfo, sizeof(actinfo))))
988 log_err("out of memory");
992 qstate->respip_action_info = NULL;
994 if (new_rep == qstate->return_msg->rep &&
995 (actinfo.action == respip_deny ||
996 actinfo.action == respip_inform_deny)) {
997 /* for deny-variant actions (unless response-ip
998 * data is applied), mark the query state so
999 * the response will be dropped for all
1001 qstate->is_drop = 1;
1002 } else if(alias_rrset) {
1003 if(!generate_cname_request(qstate, alias_rrset))
1005 next_state = module_wait_subquery;
1007 qstate->return_msg->rep = new_rep;
1009 qstate->ext_state[id] = next_state;
1011 qstate->ext_state[id] = module_finished;
1016 qstate->return_rcode = LDNS_RCODE_SERVFAIL;
1017 qstate->return_msg = NULL;
1021 respip_merge_cname(struct reply_info* base_rep,
1022 const struct query_info* qinfo, const struct reply_info* tgt_rep,
1023 const struct respip_client_info* cinfo, int must_validate,
1024 struct reply_info** new_repp, struct regional* region)
1026 struct reply_info* new_rep;
1027 struct reply_info* tmp_rep = NULL; /* just a placeholder */
1028 struct ub_packed_rrset_key* alias_rrset = NULL; /* ditto */
1031 struct respip_action_info actinfo = {respip_none, NULL};
1033 /* If the query for the CNAME target would result in an unusual rcode,
1034 * we generally translate it as a failure for the base query
1035 * (which would then be translated into SERVFAIL). The only exception
1036 * is NXDOMAIN and YXDOMAIN, which are passed to the end client(s).
1037 * The YXDOMAIN case would be rare but still possible (when
1038 * DNSSEC-validated DNAME has been cached but synthesizing CNAME
1039 * can't be generated due to length limitation) */
1040 tgt_rcode = FLAGS_GET_RCODE(tgt_rep->flags);
1041 if((tgt_rcode != LDNS_RCODE_NOERROR &&
1042 tgt_rcode != LDNS_RCODE_NXDOMAIN &&
1043 tgt_rcode != LDNS_RCODE_YXDOMAIN) ||
1044 (must_validate && tgt_rep->security <= sec_status_bogus)) {
1048 /* see if the target reply would be subject to a response-ip action. */
1049 if(!respip_rewrite_reply(qinfo, cinfo, tgt_rep, &tmp_rep, &actinfo,
1050 &alias_rrset, 1, region))
1052 if(actinfo.action != respip_none) {
1053 log_info("CNAME target of redirect response-ip action would "
1054 "be subject to response-ip action, too; stripped");
1055 *new_repp = base_rep;
1059 /* Append target reply to the base. Since we cannot assume
1060 * tgt_rep->rrsets is valid throughout the lifetime of new_rep
1061 * or it can be safely shared by multiple threads, we need to make a
1063 new_rep = make_new_reply_info(base_rep, region,
1064 base_rep->an_numrrsets + tgt_rep->an_numrrsets,
1065 base_rep->an_numrrsets);
1068 for(i=0,j=base_rep->an_numrrsets; i<tgt_rep->an_numrrsets; i++,j++) {
1069 new_rep->rrsets[j] = copy_rrset(tgt_rep->rrsets[i], region);
1070 if(!new_rep->rrsets[j])
1074 FLAGS_SET_RCODE(new_rep->flags, tgt_rcode);
1075 *new_repp = new_rep;
1080 respip_inform_super(struct module_qstate* qstate, int id,
1081 struct module_qstate* super)
1083 struct respip_qstate* rq = (struct respip_qstate*)super->minfo[id];
1084 struct reply_info* new_rep = NULL;
1086 rq->state = RESPIP_SUBQUERY_FINISHED;
1088 /* respip subquery should have always been created with a valid reply
1090 log_assert(super->return_msg && super->return_msg->rep);
1092 /* return_msg can be NULL when, e.g., the sub query resulted in
1093 * SERVFAIL, in which case we regard it as a failure of the original
1094 * query. Other checks are probably redundant, but we check them
1096 if(!qstate->return_msg || !qstate->return_msg->rep ||
1097 qstate->return_rcode != LDNS_RCODE_NOERROR)
1100 if(!respip_merge_cname(super->return_msg->rep, &qstate->qinfo,
1101 qstate->return_msg->rep, super->client_info,
1102 super->env->need_to_validate, &new_rep, super->region))
1104 super->return_msg->rep = new_rep;
1108 super->return_rcode = LDNS_RCODE_SERVFAIL;
1109 super->return_msg = NULL;
1114 respip_clear(struct module_qstate* qstate, int id)
1116 qstate->minfo[id] = NULL;
1120 respip_get_mem(struct module_env* env, int id)
1128 * The response-ip function block
1130 static struct module_func_block respip_block = {
1132 &respip_init, &respip_deinit, &respip_operate, &respip_inform_super,
1133 &respip_clear, &respip_get_mem
1136 struct module_func_block*
1137 respip_get_funcblock(void)
1139 return &respip_block;
1143 resp_addr_get_action(const struct resp_addr* addr)
1145 return addr ? addr->action : respip_none;
1148 struct ub_packed_rrset_key*
1149 resp_addr_get_rrset(struct resp_addr* addr)
1151 return addr ? addr->data : NULL;
1155 respip_set_is_empty(const struct respip_set* set)
1157 return set ? set->ip_tree.count == 0 : 1;
1161 respip_inform_print(struct respip_addr_info* respip_addr, uint8_t* qname,
1162 uint16_t qtype, uint16_t qclass, struct local_rrset* local_alias,
1163 struct comm_reply* repinfo)
1165 char srcip[128], respip[128], txt[512];
1169 qname = local_alias->rrset->rk.dname;
1170 port = (unsigned)((repinfo->addr.ss_family == AF_INET) ?
1171 ntohs(((struct sockaddr_in*)&repinfo->addr)->sin_port) :
1172 ntohs(((struct sockaddr_in6*)&repinfo->addr)->sin6_port));
1173 addr_to_str(&repinfo->addr, repinfo->addrlen, srcip, sizeof(srcip));
1174 addr_to_str(&respip_addr->addr, respip_addr->addrlen,
1175 respip, sizeof(respip));
1176 snprintf(txt, sizeof(txt), "%s/%d inform %s@%u", respip,
1177 respip_addr->net, srcip, port);
1178 log_nametypeclass(0, txt, qname, qtype, qclass);