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 verbose(VERB_QUERY, "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, "inform_redirect") == 0)
187 action = respip_inform_redirect;
188 else if(strcmp(actnstr, "always_transparent") == 0)
189 action = respip_always_transparent;
190 else if(strcmp(actnstr, "always_refuse") == 0)
191 action = respip_always_refuse;
192 else if(strcmp(actnstr, "always_nxdomain") == 0)
193 action = respip_always_nxdomain;
195 log_err("unknown response-ip action %s", actnstr);
198 node->action = action;
202 /** allocate and initialize an rrset structure; this function is based
203 * on new_local_rrset() from the localzone.c module */
204 static struct ub_packed_rrset_key*
205 new_rrset(struct regional* region, uint16_t rrtype, uint16_t rrclass)
207 struct packed_rrset_data* pd;
208 struct ub_packed_rrset_key* rrset = regional_alloc_zero(
209 region, sizeof(*rrset));
211 log_err("out of memory");
214 rrset->entry.key = rrset;
215 pd = regional_alloc_zero(region, sizeof(*pd));
217 log_err("out of memory");
220 pd->trust = rrset_trust_prim_noglue;
221 pd->security = sec_status_insecure;
222 rrset->entry.data = pd;
223 rrset->rk.dname = regional_alloc_zero(region, 1);
224 if(!rrset->rk.dname) {
225 log_err("out of memory");
228 rrset->rk.dname_len = 1;
229 rrset->rk.type = htons(rrtype);
230 rrset->rk.rrset_class = htons(rrclass);
234 /** enter local data as resource records into a response-ip node */
236 respip_enter_rr(struct regional* region, struct resp_addr* raddr,
237 const char* rrstr, const char* netblock)
240 uint16_t rrtype = 0, rrclass = 0;
242 uint8_t rr[LDNS_RR_BUF_SIZE];
243 uint8_t* rdata = NULL;
244 size_t rdata_len = 0;
247 struct packed_rrset_data* pd;
250 if(raddr->action != respip_redirect
251 && raddr->action != respip_inform_redirect) {
252 log_err("cannot parse response-ip-data %s: response-ip "
253 "action for %s is not redirect", rrstr, netblock);
256 ret = snprintf(buf, sizeof(buf), ". %s", rrstr);
257 if(ret < 0 || ret >= (int)sizeof(buf)) {
258 strlcpy(bufshort, rrstr, sizeof(bufshort));
259 log_err("bad response-ip-data: %s...", bufshort);
262 if(!rrstr_get_rr_content(buf, &nm, &rrtype, &rrclass, &ttl, rr, sizeof(rr),
263 &rdata, &rdata_len)) {
264 log_err("bad response-ip-data: %s", rrstr);
268 sa = (struct sockaddr*)&raddr->node.addr;
269 if (rrtype == LDNS_RR_TYPE_CNAME && raddr->data) {
270 log_err("CNAME response-ip data (%s) can not co-exist with other "
271 "response-ip data for netblock %s", rrstr, netblock);
273 } else if (raddr->data &&
274 raddr->data->rk.type == htons(LDNS_RR_TYPE_CNAME)) {
275 log_err("response-ip data (%s) can not be added; CNAME response-ip "
276 "data already in place for netblock %s", rrstr, netblock);
278 } else if((rrtype != LDNS_RR_TYPE_CNAME) &&
279 ((sa->sa_family == AF_INET && rrtype != LDNS_RR_TYPE_A) ||
280 (sa->sa_family == AF_INET6 && rrtype != LDNS_RR_TYPE_AAAA))) {
281 log_err("response-ip data %s record type does not correspond "
282 "to netblock %s address family", rrstr, netblock);
287 raddr->data = new_rrset(region, rrtype, rrclass);
291 pd = raddr->data->entry.data;
292 return rrset_insert_rr(region, pd, rdata, rdata_len, ttl, rrstr);
296 respip_data_cfg(struct respip_set* set, const char* ipstr, const char* rrstr)
298 struct resp_addr* node;
300 node=respip_find_or_create(set, ipstr, 0);
301 if(!node || node->action == respip_none) {
302 log_err("cannot parse response-ip-data %s: "
303 "response-ip node for %s not found", rrstr, ipstr);
306 return respip_enter_rr(set->region, node, rrstr, ipstr);
310 respip_set_apply_cfg(struct respip_set* set, char* const* tagname, int num_tags,
311 struct config_strbytelist* respip_tags,
312 struct config_str2list* respip_actions,
313 struct config_str2list* respip_data)
315 struct config_strbytelist* p;
316 struct config_str2list* pa;
317 struct config_str2list* pd;
319 set->tagname = tagname;
320 set->num_tags = num_tags;
324 struct config_strbytelist* np = p->next;
326 log_assert(p->str && p->str2);
327 if(!respip_tag_cfg(set, p->str, p->str2, p->str2len)) {
328 config_del_strbytelist(p);
339 struct config_str2list* np = pa->next;
340 log_assert(pa->str && pa->str2);
341 if(!respip_action_cfg(set, pa->str, pa->str2)) {
342 config_deldblstrlist(pa);
353 struct config_str2list* np = pd->next;
354 log_assert(pd->str && pd->str2);
355 if(!respip_data_cfg(set, pd->str, pd->str2)) {
356 config_deldblstrlist(pd);
364 addr_tree_init_parents(&set->ip_tree);
370 respip_global_apply_cfg(struct respip_set* set, struct config_file* cfg)
372 int ret = respip_set_apply_cfg(set, cfg->tagname, cfg->num_tags,
373 cfg->respip_tags, cfg->respip_actions, cfg->respip_data);
374 cfg->respip_data = NULL;
375 cfg->respip_actions = NULL;
376 cfg->respip_tags = NULL;
380 /** Iterate through raw view data and apply the view-specific respip
381 * configuration; at this point we should have already seen all the views,
382 * so if any of the views that respip data refer to does not exist, that's
383 * an error. This additional iteration through view configuration data
384 * is expected to not have significant performance impact (or rather, its
385 * performance impact is not expected to be prohibitive in the configuration
389 respip_views_apply_cfg(struct views* vs, struct config_file* cfg,
390 int* have_view_respip_cfg)
392 struct config_view* cv;
396 for(cv = cfg->views; cv; cv = cv->next) {
398 /** if no respip config for this view then there's
399 * nothing to do; note that even though respip data must go
400 * with respip action, we're checking for both here because
401 * we want to catch the case where the respip action is missing
402 * while the data is present */
403 if(!cv->respip_actions && !cv->respip_data)
406 if(!(v = views_find_view(vs, cv->name, 1))) {
407 log_err("view '%s' unexpectedly missing", cv->name);
411 v->respip_set = respip_set_create();
413 log_err("out of memory");
414 lock_rw_unlock(&v->lock);
418 ret = respip_set_apply_cfg(v->respip_set, NULL, 0, NULL,
419 cv->respip_actions, cv->respip_data);
420 lock_rw_unlock(&v->lock);
422 log_err("Error while applying respip configuration "
423 "for view '%s'", cv->name);
426 *have_view_respip_cfg = (*have_view_respip_cfg ||
427 v->respip_set->ip_tree.count);
428 cv->respip_actions = NULL;
429 cv->respip_data = NULL;
435 * make a deep copy of 'key' in 'region'.
436 * This is largely derived from packed_rrset_copy_region() and
437 * packed_rrset_ptr_fixup(), but differs in the following points:
439 * - It doesn't assume all data in 'key' are in a contiguous memory region.
440 * Although that would be the case in most cases, 'key' can be passed from
441 * a lower-level module and it might not build the rrset to meet the
442 * assumption. In fact, an rrset specified as response-ip-data or generated
443 * in local_data_find_tag_datas() breaks the assumption. So it would be
444 * safer not to naively rely on the assumption. On the other hand, this
445 * function ensures the copied rrset data are in a contiguous region so
446 * that it won't cause a disruption even if an upper layer module naively
447 * assumes the memory layout.
448 * - It doesn't copy RRSIGs (if any) in 'key'. The rrset will be used in
449 * a reply that was already faked, so it doesn't make much sense to provide
450 * partial sigs even if they are valid themselves.
451 * - It doesn't adjust TTLs as it basically has to be a verbatim copy of 'key'
452 * just allocated in 'region' (the assumption is necessary TTL adjustment
453 * has been already done in 'key').
455 * This function returns the copied rrset key on success, and NULL on memory
456 * allocation failure.
458 static struct ub_packed_rrset_key*
459 copy_rrset(const struct ub_packed_rrset_key* key, struct regional* region)
461 struct ub_packed_rrset_key* ck = regional_alloc(region,
462 sizeof(struct ub_packed_rrset_key));
463 struct packed_rrset_data* d;
464 struct packed_rrset_data* data = key->entry.data;
468 /* derived from packed_rrset_copy_region(), but don't use
469 * packed_rrset_sizeof() and do exclude RRSIGs */
473 memset(&ck->entry, 0, sizeof(ck->entry));
474 ck->entry.hash = key->entry.hash;
477 ck->rk.dname = regional_alloc_init(region, key->rk.dname,
482 if((unsigned)data->count >= 0xffff00U)
483 return NULL; /* guard against integer overflow in dsize */
484 dsize = sizeof(struct packed_rrset_data) + data->count *
485 (sizeof(size_t)+sizeof(uint8_t*)+sizeof(time_t));
486 for(i=0; i<data->count; i++) {
487 if((unsigned)dsize >= 0x0fffffffU ||
488 (unsigned)data->rr_len[i] >= 0x0fffffffU)
489 return NULL; /* guard against integer overflow */
490 dsize += data->rr_len[i];
492 d = regional_alloc(region, dsize);
499 /* derived from packed_rrset_ptr_fixup() with copying the data */
500 d->rr_len = (size_t*)((uint8_t*)d + sizeof(struct packed_rrset_data));
501 d->rr_data = (uint8_t**)&(d->rr_len[d->count]);
502 d->rr_ttl = (time_t*)&(d->rr_data[d->count]);
503 nextrdata = (uint8_t*)&(d->rr_ttl[d->count]);
504 for(i=0; i<d->count; i++) {
505 d->rr_len[i] = data->rr_len[i];
506 d->rr_ttl[i] = data->rr_ttl[i];
507 d->rr_data[i] = nextrdata;
508 memcpy(d->rr_data[i], data->rr_data[i], data->rr_len[i]);
509 nextrdata += d->rr_len[i];
516 respip_init(struct module_env* env, int id)
524 respip_deinit(struct module_env* env, int id)
530 /** Convert a packed AAAA or A RRset to sockaddr. */
532 rdata2sockaddr(const struct packed_rrset_data* rd, uint16_t rtype, size_t i,
533 struct sockaddr_storage* ss, socklen_t* addrlenp)
535 /* unbound can accept and cache odd-length AAAA/A records, so we have
536 * to validate the length. */
537 if(rtype == LDNS_RR_TYPE_A && rd->rr_len[i] == 6) {
538 struct sockaddr_in* sa4 = (struct sockaddr_in*)ss;
540 memset(sa4, 0, sizeof(*sa4));
541 sa4->sin_family = AF_INET;
542 memcpy(&sa4->sin_addr, rd->rr_data[i] + 2,
543 sizeof(sa4->sin_addr));
544 *addrlenp = sizeof(*sa4);
546 } else if(rtype == LDNS_RR_TYPE_AAAA && rd->rr_len[i] == 18) {
547 struct sockaddr_in6* sa6 = (struct sockaddr_in6*)ss;
549 memset(sa6, 0, sizeof(*sa6));
550 sa6->sin6_family = AF_INET6;
551 memcpy(&sa6->sin6_addr, rd->rr_data[i] + 2,
552 sizeof(sa6->sin6_addr));
553 *addrlenp = sizeof(*sa6);
560 * Search the given 'iptree' for response address information that matches
561 * any of the IP addresses in an AAAA or A in the answer section of the
562 * response (stored in 'rep'). If found, a pointer to the matched resp_addr
563 * structure will be returned, and '*rrset_id' is set to the index in
564 * rep->rrsets for the RRset that contains the matching IP address record
565 * (the index is normally 0, but can be larger than that if this is a CNAME
566 * chain or type-ANY response).
568 static const struct resp_addr*
569 respip_addr_lookup(const struct reply_info *rep, struct rbtree_type* iptree,
573 struct resp_addr* ra;
574 struct sockaddr_storage ss;
577 for(i=0; i<rep->an_numrrsets; i++) {
579 const struct packed_rrset_data* rd;
580 uint16_t rtype = ntohs(rep->rrsets[i]->rk.type);
582 if(rtype != LDNS_RR_TYPE_A && rtype != LDNS_RR_TYPE_AAAA)
584 rd = rep->rrsets[i]->entry.data;
585 for(j = 0; j < rd->count; j++) {
586 if(!rdata2sockaddr(rd, rtype, j, &ss, &addrlen))
588 ra = (struct resp_addr*)addr_tree_lookup(iptree, &ss,
601 * Create a new reply_info based on 'rep'. The new info is based on
602 * the passed 'rep', but ignores any rrsets except for the first 'an_numrrsets'
603 * RRsets in the answer section. These answer rrsets are copied to the
604 * new info, up to 'copy_rrsets' rrsets (which must not be larger than
605 * 'an_numrrsets'). If an_numrrsets > copy_rrsets, the remaining rrsets array
606 * entries will be kept empty so the caller can fill them later. When rrsets
607 * are copied, they are shallow copied. The caller must ensure that the
608 * copied rrsets are valid throughout its lifetime and must provide appropriate
609 * mutex if it can be shared by multiple threads.
611 static struct reply_info *
612 make_new_reply_info(const struct reply_info* rep, struct regional* region,
613 size_t an_numrrsets, size_t copy_rrsets)
615 struct reply_info* new_rep;
618 /* create a base struct. we specify 'insecure' security status as
619 * the modified response won't be DNSSEC-valid. In our faked response
620 * the authority and additional sections will be empty (except possible
621 * EDNS0 OPT RR in the additional section appended on sending it out),
622 * so the total number of RRsets is an_numrrsets. */
623 new_rep = construct_reply_info_base(region, rep->flags,
624 rep->qdcount, rep->ttl, rep->prefetch_ttl,
625 rep->serve_expired_ttl, an_numrrsets, 0, 0, an_numrrsets,
626 sec_status_insecure);
629 if(!reply_info_alloc_rrset_keys(new_rep, NULL, region))
631 for(i=0; i<copy_rrsets; i++)
632 new_rep->rrsets[i] = rep->rrsets[i];
638 * See if response-ip or tag data should override the original answer rrset
639 * (which is rep->rrsets[rrset_id]) and if so override it.
640 * This is (mostly) equivalent to localzone.c:local_data_answer() but for
641 * response-ip actions.
642 * Note that this function distinguishes error conditions from "success but
643 * not overridden". This is because we want to avoid accidentally applying
644 * the "no data" action in case of error.
645 * @param raddr: address span that requires an action
646 * @param action: action to apply
647 * @param qtype: original query type
648 * @param rep: original reply message
649 * @param rrset_id: the rrset ID in 'rep' to which the action should apply
650 * @param new_repp: see respip_rewrite_reply
651 * @param tag: if >= 0 the tag ID used to determine the action and data
652 * @param tag_datas: data corresponding to 'tag'.
653 * @param tag_datas_size: size of 'tag_datas'
654 * @param tagname: array of tag names, used for logging
655 * @param num_tags: size of 'tagname', used for logging
656 * @param redirect_rrsetp: ptr to redirect record
657 * @param region: region for building new reply
658 * @return 1 if overridden, 0 if not overridden, -1 on error.
661 respip_data_answer(const struct resp_addr* raddr, enum respip_action action,
662 uint16_t qtype, const struct reply_info* rep,
663 size_t rrset_id, struct reply_info** new_repp, int tag,
664 struct config_strlist** tag_datas, size_t tag_datas_size,
665 char* const* tagname, int num_tags,
666 struct ub_packed_rrset_key** redirect_rrsetp, struct regional* region)
668 struct ub_packed_rrset_key* rp = raddr->data;
669 struct reply_info* new_rep;
670 *redirect_rrsetp = NULL;
672 if(action == respip_redirect && tag != -1 &&
673 (size_t)tag<tag_datas_size && tag_datas[tag]) {
674 struct query_info dataqinfo;
675 struct ub_packed_rrset_key r;
677 /* Extract parameters of the original answer rrset that can be
678 * rewritten below, in the form of query_info. Note that these
679 * can be different from the info of the original query if the
680 * rrset is a CNAME target.*/
681 memset(&dataqinfo, 0, sizeof(dataqinfo));
682 dataqinfo.qname = rep->rrsets[rrset_id]->rk.dname;
683 dataqinfo.qname_len = rep->rrsets[rrset_id]->rk.dname_len;
684 dataqinfo.qtype = ntohs(rep->rrsets[rrset_id]->rk.type);
685 dataqinfo.qclass = ntohs(rep->rrsets[rrset_id]->rk.rrset_class);
687 memset(&r, 0, sizeof(r));
688 if(local_data_find_tag_datas(&dataqinfo, tag_datas[tag], &r,
691 "response-ip redirect with tag data [%d] %s",
692 tag, (tag<num_tags?tagname[tag]:"null"));
693 /* use copy_rrset() to 'normalize' memory layout */
694 rp = copy_rrset(&r, region);
702 /* If we are using response-ip-data, we need to make a copy of rrset
703 * to replace the rrset's dname. Note that, unlike local data, we
704 * rename the dname for other actions than redirect. This is because
705 * response-ip-data isn't associated to any specific name. */
706 if(rp == raddr->data) {
707 rp = copy_rrset(rp, region);
710 rp->rk.dname = rep->rrsets[rrset_id]->rk.dname;
711 rp->rk.dname_len = rep->rrsets[rrset_id]->rk.dname_len;
714 /* Build a new reply with redirect rrset. We keep any preceding CNAMEs
715 * and replace the address rrset that triggers the action. If it's
716 * type ANY query, however, no other answer records should be kept
717 * (note that it can't be a CNAME chain in this case due to
719 if(qtype == LDNS_RR_TYPE_ANY)
721 new_rep = make_new_reply_info(rep, region, rrset_id + 1, rrset_id);
724 rp->rk.flags |= PACKED_RRSET_FIXEDTTL; /* avoid adjusting TTL */
725 new_rep->rrsets[rrset_id] = rp;
727 *redirect_rrsetp = rp;
733 * apply response ip action in case where no action data is provided.
734 * this is similar to localzone.c:lz_zone_answer() but simplified due to
735 * the characteristics of response ip:
736 * - 'deny' variants will be handled at the caller side
737 * - no specific processing for 'transparent' variants: unlike local zones,
738 * there is no such a case of 'no data but name existing'. so all variants
739 * just mean 'transparent if no data'.
740 * @param qtype: query type
741 * @param action: found action
745 * @param region: region for building new reply
746 * @return 1 on success, 0 on error.
749 respip_nodata_answer(uint16_t qtype, enum respip_action action,
750 const struct reply_info *rep, size_t rrset_id,
751 struct reply_info** new_repp, struct regional* region)
753 struct reply_info* new_rep;
755 if(action == respip_refuse || action == respip_always_refuse) {
756 new_rep = make_new_reply_info(rep, region, 0, 0);
759 FLAGS_SET_RCODE(new_rep->flags, LDNS_RCODE_REFUSED);
762 } else if(action == respip_static || action == respip_redirect ||
763 action == respip_always_nxdomain ||
764 action == respip_inform_redirect) {
765 /* Since we don't know about other types of the owner name,
766 * we generally return NOERROR/NODATA unless an NXDOMAIN action
767 * is explicitly specified. */
768 int rcode = (action == respip_always_nxdomain)?
769 LDNS_RCODE_NXDOMAIN:LDNS_RCODE_NOERROR;
771 /* We should empty the answer section except for any preceding
772 * CNAMEs (in that case rrset_id > 0). Type-ANY case is
773 * special as noted in respip_data_answer(). */
774 if(qtype == LDNS_RR_TYPE_ANY)
776 new_rep = make_new_reply_info(rep, region, rrset_id, rrset_id);
779 FLAGS_SET_RCODE(new_rep->flags, rcode);
787 /** Populate action info structure with the results of response-ip action
788 * processing, iff as the result of response-ip processing we are actually
789 * taking some action. Only action is set if action_only is true.
790 * Returns true on success, false on failure.
793 populate_action_info(struct respip_action_info* actinfo,
794 enum respip_action action, const struct resp_addr* raddr,
795 const struct ub_packed_rrset_key* ATTR_UNUSED(rrset),
796 int ATTR_UNUSED(tag), const struct respip_set* ATTR_UNUSED(ipset),
797 int ATTR_UNUSED(action_only), struct regional* region)
799 if(action == respip_none || !raddr)
801 actinfo->action = action;
803 /* for inform variants, make a copy of the matched address block for
804 * later logging. We make a copy to proactively avoid disruption if
805 * and when we allow a dynamic update to the respip tree. */
806 if(action == respip_inform || action == respip_inform_deny) {
807 struct respip_addr_info* a =
808 regional_alloc_zero(region, sizeof(*a));
810 log_err("out of memory");
813 a->addr = raddr->node.addr;
814 a->addrlen = raddr->node.addrlen;
815 a->net = raddr->node.net;
816 actinfo->addrinfo = a;
823 respip_rewrite_reply(const struct query_info* qinfo,
824 const struct respip_client_info* cinfo, const struct reply_info* rep,
825 struct reply_info** new_repp, struct respip_action_info* actinfo,
826 struct ub_packed_rrset_key** alias_rrset, int search_only,
827 struct regional* region)
829 const uint8_t* ctaglist;
831 const uint8_t* tag_actions;
832 size_t tag_actions_size;
833 struct config_strlist** tag_datas;
834 size_t tag_datas_size;
835 struct view* view = NULL;
836 struct respip_set* ipset = NULL;
838 enum respip_action action = respip_none;
840 const struct resp_addr* raddr = NULL;
842 struct ub_packed_rrset_key* redirect_rrset = NULL;
846 ctaglist = cinfo->taglist;
847 ctaglen = cinfo->taglen;
848 tag_actions = cinfo->tag_actions;
849 tag_actions_size = cinfo->tag_actions_size;
850 tag_datas = cinfo->tag_datas;
851 tag_datas_size = cinfo->tag_datas_size;
853 ipset = cinfo->respip_set;
855 /** Try to use response-ip config from the view first; use
856 * global response-ip config if we don't have the view or we don't
857 * have the matching per-view config (and the view allows the use
858 * of global data in this case).
859 * Note that we lock the view even if we only use view members that
860 * currently don't change after creation. This is for safety for
861 * future possible changes as the view documentation seems to expect
862 * any of its member can change in the view's lifetime.
863 * Note also that we assume 'view' is valid in this function, which
864 * should be safe (see unbound bug #1191) */
866 lock_rw_rdlock(&view->lock);
867 if(view->respip_set) {
868 if((raddr = respip_addr_lookup(rep,
869 &view->respip_set->ip_tree, &rrset_id))) {
870 /** for per-view respip directives the action
871 * can only be direct (i.e. not tag-based) */
872 action = raddr->action;
875 if(!raddr && !view->isfirst)
878 if(!raddr && ipset && (raddr = respip_addr_lookup(rep, &ipset->ip_tree,
880 action = (enum respip_action)local_data_find_tag_action(
881 raddr->taglist, raddr->taglen, ctaglist, ctaglen,
882 tag_actions, tag_actions_size,
883 (enum localzone_type)raddr->action, &tag,
884 ipset->tagname, ipset->num_tags);
886 if(raddr && !search_only) {
889 /* first, see if we have response-ip or tag action for the
890 * action except for 'always' variants. */
891 if(action != respip_always_refuse
892 && action != respip_always_transparent
893 && action != respip_always_nxdomain
894 && (result = respip_data_answer(raddr, action,
895 qinfo->qtype, rep, rrset_id, new_repp, tag, tag_datas,
896 tag_datas_size, ipset->tagname, ipset->num_tags,
897 &redirect_rrset, region)) < 0) {
902 /* if no action data applied, take action specific to the
903 * action without data. */
904 if(!result && !respip_nodata_answer(qinfo->qtype, action, rep,
905 rrset_id, new_repp, region)) {
912 lock_rw_unlock(&view->lock);
915 /* If we're redirecting the original answer to a
916 * CNAME, record the CNAME rrset so the caller can take
917 * the appropriate action. Note that we don't check the
918 * action type; it should normally be 'redirect', but it
919 * can be of other type when a data-dependent tag action
920 * uses redirect response-ip data.
923 redirect_rrset->rk.type == ntohs(LDNS_RR_TYPE_CNAME) &&
924 qinfo->qtype != LDNS_RR_TYPE_ANY)
925 *alias_rrset = redirect_rrset;
926 /* on success, populate respip result structure */
927 ret = populate_action_info(actinfo, action, raddr,
928 redirect_rrset, tag, ipset, search_only, region);
934 generate_cname_request(struct module_qstate* qstate,
935 struct ub_packed_rrset_key* alias_rrset)
937 struct module_qstate* subq = NULL;
938 struct query_info subqi;
940 memset(&subqi, 0, sizeof(subqi));
941 get_cname_target(alias_rrset, &subqi.qname, &subqi.qname_len);
943 return 0; /* unexpected: not a valid CNAME RDATA */
944 subqi.qtype = qstate->qinfo.qtype;
945 subqi.qclass = qstate->qinfo.qclass;
946 fptr_ok(fptr_whitelist_modenv_attach_sub(qstate->env->attach_sub));
947 return (*qstate->env->attach_sub)(qstate, &subqi, BIT_RD, 0, 0, &subq);
951 respip_operate(struct module_qstate* qstate, enum module_ev event, int id,
952 struct outbound_entry* outbound)
954 struct respip_qstate* rq = (struct respip_qstate*)qstate->minfo[id];
956 log_query_info(VERB_QUERY, "respip operate: query", &qstate->qinfo);
959 if(event == module_event_new || event == module_event_pass) {
961 rq = regional_alloc_zero(qstate->region, sizeof(*rq));
964 rq->state = RESPIP_INIT;
965 qstate->minfo[id] = rq;
967 if(rq->state == RESPIP_SUBQUERY_FINISHED) {
968 qstate->ext_state[id] = module_finished;
971 verbose(VERB_ALGO, "respip: pass to next module");
972 qstate->ext_state[id] = module_wait_module;
973 } else if(event == module_event_moddone) {
974 /* If the reply may be subject to response-ip rewriting
975 * according to the query type, check the actions. If a
976 * rewrite is necessary, we'll replace the reply in qstate
977 * with the new one. */
978 enum module_ext_state next_state = module_finished;
980 if((qstate->qinfo.qtype == LDNS_RR_TYPE_A ||
981 qstate->qinfo.qtype == LDNS_RR_TYPE_AAAA ||
982 qstate->qinfo.qtype == LDNS_RR_TYPE_ANY) &&
983 qstate->return_msg && qstate->return_msg->rep) {
984 struct respip_action_info actinfo = {respip_none, NULL};
985 struct reply_info* new_rep = qstate->return_msg->rep;
986 struct ub_packed_rrset_key* alias_rrset = NULL;
988 if(!respip_rewrite_reply(&qstate->qinfo,
989 qstate->client_info, qstate->return_msg->rep,
990 &new_rep, &actinfo, &alias_rrset, 0,
994 if(actinfo.action != respip_none) {
995 /* save action info for logging on a
996 * per-front-end-query basis */
997 if(!(qstate->respip_action_info =
998 regional_alloc_init(qstate->region,
999 &actinfo, sizeof(actinfo))))
1001 log_err("out of memory");
1005 qstate->respip_action_info = NULL;
1007 if (new_rep == qstate->return_msg->rep &&
1008 (actinfo.action == respip_deny ||
1009 actinfo.action == respip_inform_deny)) {
1010 /* for deny-variant actions (unless response-ip
1011 * data is applied), mark the query state so
1012 * the response will be dropped for all
1014 qstate->is_drop = 1;
1015 } else if(alias_rrset) {
1016 if(!generate_cname_request(qstate, alias_rrset))
1018 next_state = module_wait_subquery;
1020 qstate->return_msg->rep = new_rep;
1022 qstate->ext_state[id] = next_state;
1024 qstate->ext_state[id] = module_finished;
1029 qstate->return_rcode = LDNS_RCODE_SERVFAIL;
1030 qstate->return_msg = NULL;
1034 respip_merge_cname(struct reply_info* base_rep,
1035 const struct query_info* qinfo, const struct reply_info* tgt_rep,
1036 const struct respip_client_info* cinfo, int must_validate,
1037 struct reply_info** new_repp, struct regional* region)
1039 struct reply_info* new_rep;
1040 struct reply_info* tmp_rep = NULL; /* just a placeholder */
1041 struct ub_packed_rrset_key* alias_rrset = NULL; /* ditto */
1044 struct respip_action_info actinfo = {respip_none, NULL};
1046 /* If the query for the CNAME target would result in an unusual rcode,
1047 * we generally translate it as a failure for the base query
1048 * (which would then be translated into SERVFAIL). The only exception
1049 * is NXDOMAIN and YXDOMAIN, which are passed to the end client(s).
1050 * The YXDOMAIN case would be rare but still possible (when
1051 * DNSSEC-validated DNAME has been cached but synthesizing CNAME
1052 * can't be generated due to length limitation) */
1053 tgt_rcode = FLAGS_GET_RCODE(tgt_rep->flags);
1054 if((tgt_rcode != LDNS_RCODE_NOERROR &&
1055 tgt_rcode != LDNS_RCODE_NXDOMAIN &&
1056 tgt_rcode != LDNS_RCODE_YXDOMAIN) ||
1057 (must_validate && tgt_rep->security <= sec_status_bogus)) {
1061 /* see if the target reply would be subject to a response-ip action. */
1062 if(!respip_rewrite_reply(qinfo, cinfo, tgt_rep, &tmp_rep, &actinfo,
1063 &alias_rrset, 1, region))
1065 if(actinfo.action != respip_none) {
1066 log_info("CNAME target of redirect response-ip action would "
1067 "be subject to response-ip action, too; stripped");
1068 *new_repp = base_rep;
1072 /* Append target reply to the base. Since we cannot assume
1073 * tgt_rep->rrsets is valid throughout the lifetime of new_rep
1074 * or it can be safely shared by multiple threads, we need to make a
1076 new_rep = make_new_reply_info(base_rep, region,
1077 base_rep->an_numrrsets + tgt_rep->an_numrrsets,
1078 base_rep->an_numrrsets);
1081 for(i=0,j=base_rep->an_numrrsets; i<tgt_rep->an_numrrsets; i++,j++) {
1082 new_rep->rrsets[j] = copy_rrset(tgt_rep->rrsets[i], region);
1083 if(!new_rep->rrsets[j])
1087 FLAGS_SET_RCODE(new_rep->flags, tgt_rcode);
1088 *new_repp = new_rep;
1093 respip_inform_super(struct module_qstate* qstate, int id,
1094 struct module_qstate* super)
1096 struct respip_qstate* rq = (struct respip_qstate*)super->minfo[id];
1097 struct reply_info* new_rep = NULL;
1099 rq->state = RESPIP_SUBQUERY_FINISHED;
1101 /* respip subquery should have always been created with a valid reply
1103 log_assert(super->return_msg && super->return_msg->rep);
1105 /* return_msg can be NULL when, e.g., the sub query resulted in
1106 * SERVFAIL, in which case we regard it as a failure of the original
1107 * query. Other checks are probably redundant, but we check them
1109 if(!qstate->return_msg || !qstate->return_msg->rep ||
1110 qstate->return_rcode != LDNS_RCODE_NOERROR)
1113 if(!respip_merge_cname(super->return_msg->rep, &qstate->qinfo,
1114 qstate->return_msg->rep, super->client_info,
1115 super->env->need_to_validate, &new_rep, super->region))
1117 super->return_msg->rep = new_rep;
1121 super->return_rcode = LDNS_RCODE_SERVFAIL;
1122 super->return_msg = NULL;
1127 respip_clear(struct module_qstate* qstate, int id)
1129 qstate->minfo[id] = NULL;
1133 respip_get_mem(struct module_env* env, int id)
1141 * The response-ip function block
1143 static struct module_func_block respip_block = {
1145 &respip_init, &respip_deinit, &respip_operate, &respip_inform_super,
1146 &respip_clear, &respip_get_mem
1149 struct module_func_block*
1150 respip_get_funcblock(void)
1152 return &respip_block;
1156 resp_addr_get_action(const struct resp_addr* addr)
1158 return addr ? addr->action : respip_none;
1161 struct ub_packed_rrset_key*
1162 resp_addr_get_rrset(struct resp_addr* addr)
1164 return addr ? addr->data : NULL;
1168 respip_set_is_empty(const struct respip_set* set)
1170 return set ? set->ip_tree.count == 0 : 1;
1174 respip_inform_print(struct respip_addr_info* respip_addr, uint8_t* qname,
1175 uint16_t qtype, uint16_t qclass, struct local_rrset* local_alias,
1176 struct comm_reply* repinfo)
1178 char srcip[128], respip[128], txt[512];
1182 qname = local_alias->rrset->rk.dname;
1183 port = (unsigned)((repinfo->addr.ss_family == AF_INET) ?
1184 ntohs(((struct sockaddr_in*)&repinfo->addr)->sin_port) :
1185 ntohs(((struct sockaddr_in6*)&repinfo->addr)->sin6_port));
1186 addr_to_str(&repinfo->addr, repinfo->addrlen, srcip, sizeof(srcip));
1187 addr_to_str(&respip_addr->addr, respip_addr->addrlen,
1188 respip, sizeof(respip));
1189 snprintf(txt, sizeof(txt), "%s/%d inform %s@%u", respip,
1190 respip_addr->net, srcip, port);
1191 log_nametypeclass(NO_VERBOSE, txt, qname, qtype, qclass);