/*
* respip/respip.c - filtering response IP module
*/
/**
* \file
*
* This file contains a module that inspects a result of recursive resolution
* to see if any IP address record should trigger a special action.
* If applicable these actions can modify the original response.
*/
#include "config.h"
/** Subset of resp_addr.node, used for inform-variant logging */
struct respip_addr_info {
struct sockaddr_storage addr;
socklen_t addrlen;
int net;
};
/** Query state regarding the response-ip module. */
enum respip_state {
/**
* The general state. Unless CNAME chasing takes place, all processing
* is completed in this state without any other asynchronous event.
*/
RESPIP_INIT = 0,
/**
* A subquery for CNAME chasing is completed.
*/
RESPIP_SUBQUERY_FINISHED
};
/** Per query state for the response-ip module. */
struct respip_qstate {
enum respip_state state;
};
struct resp_addr*
respip_sockaddr_find_or_create(struct respip_set* set, struct sockaddr_storage* addr,
socklen_t addrlen, int net, int create, const char* ipstr)
{
struct resp_addr* node;
log_assert(set);
node = (struct resp_addr*)addr_tree_find(&set->ip_tree, addr, addrlen, net);
if(!node && create) {
node = regional_alloc_zero(set->region, sizeof(*node));
if(!node) {
log_err("out of memory");
return NULL;
}
lock_rw_init(&node->lock);
node->action = respip_none;
if(!addr_tree_insert(&set->ip_tree, &node->node, addr,
addrlen, net)) {
/* We know we didn't find it, so this should be
* impossible. */
log_warn("unexpected: duplicate address: %s", ipstr);
}
}
return node;
}
void
respip_sockaddr_delete(struct respip_set* set, struct resp_addr* node)
{
struct resp_addr* prev;
log_assert(set);
prev = (struct resp_addr*)rbtree_previous((struct rbnode_type*)node);
lock_rw_destroy(&node->lock);
(void)rbtree_delete(&set->ip_tree, node);
/* no free'ing, all allocated in region */
if(!prev)
addr_tree_init_parents((rbtree_type*)set);
else
addr_tree_init_parents_node(&prev->node);
}
/** returns the node in the address tree for the specified netblock string;
* non-existent node will be created if 'create' is true */
static struct resp_addr*
respip_find_or_create(struct respip_set* set, const char* ipstr, int create)
{
struct sockaddr_storage addr;
int net;
socklen_t addrlen;
log_assert(set);
int
respip_global_apply_cfg(struct respip_set* set, struct config_file* cfg)
{
int ret = respip_set_apply_cfg(set, cfg->tagname, cfg->num_tags,
cfg->respip_tags, cfg->respip_actions, cfg->respip_data);
cfg->respip_data = NULL;
cfg->respip_actions = NULL;
cfg->respip_tags = NULL;
return ret;
}
/** Iterate through raw view data and apply the view-specific respip
* configuration; at this point we should have already seen all the views,
* so if any of the views that respip data refer to does not exist, that's
* an error. This additional iteration through view configuration data
* is expected to not have significant performance impact (or rather, its
* performance impact is not expected to be prohibitive in the configuration
* processing phase).
*/
int
respip_views_apply_cfg(struct views* vs, struct config_file* cfg,
int* have_view_respip_cfg)
{
struct config_view* cv;
struct view* v;
int ret;
for(cv = cfg->views; cv; cv = cv->next) {
/** if no respip config for this view then there's
* nothing to do; note that even though respip data must go
* with respip action, we're checking for both here because
* we want to catch the case where the respip action is missing
* while the data is present */
if(!cv->respip_actions && !cv->respip_data)
continue;
/**
* make a deep copy of 'key' in 'region'.
* This is largely derived from packed_rrset_copy_region() and
* packed_rrset_ptr_fixup(), but differs in the following points:
*
* - It doesn't assume all data in 'key' are in a contiguous memory region.
* Although that would be the case in most cases, 'key' can be passed from
* a lower-level module and it might not build the rrset to meet the
* assumption. In fact, an rrset specified as response-ip-data or generated
* in local_data_find_tag_datas() breaks the assumption. So it would be
* safer not to naively rely on the assumption. On the other hand, this
* function ensures the copied rrset data are in a contiguous region so
* that it won't cause a disruption even if an upper layer module naively
* assumes the memory layout.
* - It doesn't copy RRSIGs (if any) in 'key'. The rrset will be used in
* a reply that was already faked, so it doesn't make much sense to provide
* partial sigs even if they are valid themselves.
* - It doesn't adjust TTLs as it basically has to be a verbatim copy of 'key'
* just allocated in 'region' (the assumption is necessary TTL adjustment
* has been already done in 'key').
*
* This function returns the copied rrset key on success, and NULL on memory
* allocation failure.
*/
struct ub_packed_rrset_key*
respip_copy_rrset(const struct ub_packed_rrset_key* key, struct regional* region)
{
struct ub_packed_rrset_key* ck = regional_alloc(region,
sizeof(struct ub_packed_rrset_key));
struct packed_rrset_data* d;
struct packed_rrset_data* data = key->entry.data;
size_t dsize, i;
uint8_t* nextrdata;
int
respip_init(struct module_env* env, int id)
{
(void)env;
(void)id;
return 1;
}
void
respip_deinit(struct module_env* env, int id)
{
(void)env;
(void)id;
}
/** Convert a packed AAAA or A RRset to sockaddr. */
static int
rdata2sockaddr(const struct packed_rrset_data* rd, uint16_t rtype, size_t i,
struct sockaddr_storage* ss, socklen_t* addrlenp)
{
/* unbound can accept and cache odd-length AAAA/A records, so we have
* to validate the length. */
if(rtype == LDNS_RR_TYPE_A && rd->rr_len[i] == 6) {
struct sockaddr_in* sa4 = (struct sockaddr_in*)ss;
/**
* Search the given 'iptree' for response address information that matches
* any of the IP addresses in an AAAA or A in the answer section of the
* response (stored in 'rep'). If found, a pointer to the matched resp_addr
* structure will be returned, and '*rrset_id' is set to the index in
* rep->rrsets for the RRset that contains the matching IP address record
* (the index is normally 0, but can be larger than that if this is a CNAME
* chain or type-ANY response).
* Returns resp_addr holding read lock.
*/
static struct resp_addr*
respip_addr_lookup(const struct reply_info *rep, struct respip_set* rs,
size_t* rrset_id, size_t* rr_id)
{
size_t i;
struct resp_addr* ra;
struct sockaddr_storage ss;
socklen_t addrlen;
log_assert(rs);
/**
* See if response-ip or tag data should override the original answer rrset
* (which is rep->rrsets[rrset_id]) and if so override it.
* This is (mostly) equivalent to localzone.c:local_data_answer() but for
* response-ip actions.
* Note that this function distinguishes error conditions from "success but
* not overridden". This is because we want to avoid accidentally applying
* the "no data" action in case of error.
* @param action: action to apply
* @param data: RRset to use for override
* @param qtype: original query type
* @param rep: original reply message
* @param rrset_id: the rrset ID in 'rep' to which the action should apply
* @param new_repp: see respip_rewrite_reply
* @param tag: if >= 0 the tag ID used to determine the action and data
* @param tag_datas: data corresponding to 'tag'.
* @param tag_datas_size: size of 'tag_datas'
* @param tagname: array of tag names, used for logging
* @param num_tags: size of 'tagname', used for logging
* @param redirect_rrsetp: ptr to redirect record
* @param region: region for building new reply
* @return 1 if overridden, 0 if not overridden, -1 on error.
*/
static int
respip_data_answer(enum respip_action action,
struct ub_packed_rrset_key* data,
uint16_t qtype, const struct reply_info* rep,
size_t rrset_id, struct reply_info** new_repp, int tag,
struct config_strlist** tag_datas, size_t tag_datas_size,
char* const* tagname, int num_tags,
struct ub_packed_rrset_key** redirect_rrsetp, struct regional* region)
{
struct ub_packed_rrset_key* rp = data;
struct reply_info* new_rep;
*redirect_rrsetp = NULL;
/* Extract parameters of the original answer rrset that can be
* rewritten below, in the form of query_info. Note that these
* can be different from the info of the original query if the
* rrset is a CNAME target.*/
memset(&dataqinfo, 0, sizeof(dataqinfo));
dataqinfo.qname = rep->rrsets[rrset_id]->rk.dname;
dataqinfo.qname_len = rep->rrsets[rrset_id]->rk.dname_len;
dataqinfo.qtype = ntohs(rep->rrsets[rrset_id]->rk.type);
dataqinfo.qclass = ntohs(rep->rrsets[rrset_id]->rk.rrset_class);
memset(&r, 0, sizeof(r));
if(local_data_find_tag_datas(&dataqinfo, tag_datas[tag], &r,
region)) {
verbose(VERB_ALGO,
"response-ip redirect with tag data [%d] %s",
tag, (tag<num_tags?tagname[tag]:"null"));
/* use copy_rrset() to 'normalize' memory layout */
rp = respip_copy_rrset(&r, region);
if(!rp)
return -1;
}
}
if(!rp)
return 0;
/* If we are using response-ip-data, we need to make a copy of rrset
* to replace the rrset's dname. Note that, unlike local data, we
* rename the dname for other actions than redirect. This is because
* response-ip-data isn't associated to any specific name. */
if(rp == data) {
rp = respip_copy_rrset(rp, region);
if(!rp)
return -1;
rp->rk.dname = rep->rrsets[rrset_id]->rk.dname;
rp->rk.dname_len = rep->rrsets[rrset_id]->rk.dname_len;
}
/* Build a new reply with redirect rrset. We keep any preceding CNAMEs
* and replace the address rrset that triggers the action. If it's
* type ANY query, however, no other answer records should be kept
* (note that it can't be a CNAME chain in this case due to
* sanitizing). */
if(qtype == LDNS_RR_TYPE_ANY)
rrset_id = 0;
new_rep = make_new_reply_info(rep, region, rrset_id + 1, rrset_id);
if(!new_rep)
return -1;
rp->rk.flags |= PACKED_RRSET_FIXEDTTL; /* avoid adjusting TTL */
new_rep->rrsets[rrset_id] = rp;
/**
* apply response ip action in case where no action data is provided.
* this is similar to localzone.c:lz_zone_answer() but simplified due to
* the characteristics of response ip:
* - 'deny' variants will be handled at the caller side
* - no specific processing for 'transparent' variants: unlike local zones,
* there is no such a case of 'no data but name existing'. so all variants
* just mean 'transparent if no data'.
* @param qtype: query type
* @param action: found action
* @param rep:
* @param new_repp
* @param rrset_id
* @param region: region for building new reply
* @return 1 on success, 0 on error.
*/
static int
respip_nodata_answer(uint16_t qtype, enum respip_action action,
const struct reply_info *rep, size_t rrset_id,
struct reply_info** new_repp, struct regional* region)
{
struct reply_info* new_rep;
if(action == respip_refuse || action == respip_always_refuse) {
new_rep = make_new_reply_info(rep, region, 0, 0);
if(!new_rep)
return 0;
FLAGS_SET_RCODE(new_rep->flags, LDNS_RCODE_REFUSED);
*new_repp = new_rep;
return 1;
} else if(action == respip_static || action == respip_redirect ||
action == respip_always_nxdomain ||
action == respip_always_nodata ||
action == respip_inform_redirect) {
/* Since we don't know about other types of the owner name,
* we generally return NOERROR/NODATA unless an NXDOMAIN action
* is explicitly specified. */
int rcode = (action == respip_always_nxdomain)?
LDNS_RCODE_NXDOMAIN:LDNS_RCODE_NOERROR;
/* We should empty the answer section except for any preceding
* CNAMEs (in that case rrset_id > 0). Type-ANY case is
* special as noted in respip_data_answer(). */
if(qtype == LDNS_RR_TYPE_ANY)
rrset_id = 0;
new_rep = make_new_reply_info(rep, region, rrset_id, rrset_id);
if(!new_rep)
return 0;
FLAGS_SET_RCODE(new_rep->flags, rcode);
*new_repp = new_rep;
return 1;
}
return 1;
}
/** Populate action info structure with the results of response-ip action
* processing, iff as the result of response-ip processing we are actually
* taking some action. Only action is set if action_only is true.
* Returns true on success, false on failure.
*/
static int
populate_action_info(struct respip_action_info* actinfo,
enum respip_action action, const struct resp_addr* raddr,
const struct ub_packed_rrset_key* ATTR_UNUSED(rrset),
int ATTR_UNUSED(tag), const struct respip_set* ATTR_UNUSED(ipset),
int ATTR_UNUSED(action_only), struct regional* region, int rpz_used,
int rpz_log, char* log_name, int rpz_cname_override)
{
if(action == respip_none || !raddr)
return 1;
actinfo->action = action;
actinfo->rpz_used = rpz_used;
actinfo->rpz_log = rpz_log;
actinfo->log_name = log_name;
actinfo->rpz_cname_override = rpz_cname_override;
/* for inform variants, make a copy of the matched address block for
* later logging. We make a copy to proactively avoid disruption if
* and when we allow a dynamic update to the respip tree. */
if(action == respip_inform || action == respip_inform_deny ||
rpz_used) {
struct respip_addr_info* a =
regional_alloc_zero(region, sizeof(*a));
if(!a) {
log_err("out of memory");
return 0;
}
a->addr = raddr->node.addr;
a->addrlen = raddr->node.addrlen;
a->net = raddr->node.net;
actinfo->addrinfo = a;
}
int
respip_rewrite_reply(const struct query_info* qinfo,
const struct respip_client_info* cinfo, const struct reply_info* rep,
struct reply_info** new_repp, struct respip_action_info* actinfo,
struct ub_packed_rrset_key** alias_rrset, int search_only,
struct regional* region, struct auth_zones* az, int* rpz_passthru,
struct views* views, struct respip_set* ipset)
{
const uint8_t* ctaglist;
size_t ctaglen;
const uint8_t* tag_actions;
size_t tag_actions_size;
struct config_strlist** tag_datas;
size_t tag_datas_size;
struct view* view = NULL;
size_t rrset_id = 0, rr_id = 0;
enum respip_action action = respip_none;
int tag = -1;
struct resp_addr* raddr = NULL;
int ret = 1;
struct ub_packed_rrset_key* redirect_rrset = NULL;
struct rpz* r;
struct auth_zone* a = NULL;
struct ub_packed_rrset_key* data = NULL;
int rpz_used = 0;
int rpz_log = 0;
int rpz_cname_override = 0;
char* log_name = NULL;
if(!cinfo)
goto done;
ctaglist = cinfo->taglist;
ctaglen = cinfo->taglen;
tag_actions = cinfo->tag_actions;
tag_actions_size = cinfo->tag_actions_size;
tag_datas = cinfo->tag_datas;
tag_datas_size = cinfo->tag_datas_size;
if(cinfo->view) {
view = cinfo->view;
lock_rw_rdlock(&view->lock);
} else if(cinfo->view_name) {
view = views_find_view(views, cinfo->view_name, 0);
if(!view) {
/* If the view no longer exists, the rewrite can not
* be processed further. */
verbose(VERB_ALGO, "respip: failed because view %s no "
"longer exists", cinfo->view_name);
return 0;
}
/* The view is rdlocked by views_find_view. */
}
log_assert(ipset);
/** Try to use response-ip config from the view first; use
* global response-ip config if we don't have the view or we don't
* have the matching per-view config (and the view allows the use
* of global data in this case).
* Note that we lock the view even if we only use view members that
* currently don't change after creation. This is for safety for
* future possible changes as the view documentation seems to expect
* any of its member can change in the view's lifetime.
* Note also that we assume 'view' is valid in this function, which
* should be safe (see unbound bug #1191) */
if(view) {
if(view->respip_set) {
if((raddr = respip_addr_lookup(rep,
view->respip_set, &rrset_id, &rr_id))) {
/** for per-view respip directives the action
* can only be direct (i.e. not tag-based) */
action = raddr->action;
}
}
if(!raddr && !view->isfirst)
goto done;
if(!raddr && view->isfirst) {
lock_rw_unlock(&view->lock);
view = NULL;
}
}
if(!raddr && (raddr = respip_addr_lookup(rep, ipset,
&rrset_id, &rr_id))) {
action = (enum respip_action)local_data_find_tag_action(
raddr->taglist, raddr->taglen, ctaglist, ctaglen,
tag_actions, tag_actions_size,
(enum localzone_type)raddr->action, &tag,
ipset->tagname, ipset->num_tags);
}
lock_rw_rdlock(&az->rpz_lock);
for(a = az->rpz_first; a && !raddr && !(rpz_passthru && *rpz_passthru); a = a->rpz_az_next) {
lock_rw_rdlock(&a->lock);
r = a->rpz;
if(!r->taglist || taglist_intersect(r->taglist,
r->taglistlen, ctaglist, ctaglen)) {
if((raddr = respip_addr_lookup(rep,
r->respip_set, &rrset_id, &rr_id))) {
if(!respip_use_rpz(raddr, r, &action, &data,
&rpz_log, &log_name, &rpz_cname_override,
region, &rpz_used, rpz_passthru)) {
log_err("out of memory");
lock_rw_unlock(&raddr->lock);
lock_rw_unlock(&a->lock);
lock_rw_unlock(&az->rpz_lock);
return 0;
}
if(rpz_used) {
if(verbosity >= VERB_ALGO) {
struct sockaddr_storage ss;
socklen_t ss_len = 0;
char nm[256], ip[256];
char qn[LDNS_MAX_DOMAINLEN];
if(!rdata2sockaddr(rep->rrsets[rrset_id]->entry.data, ntohs(rep->rrsets[rrset_id]->rk.type), rr_id, &ss, &ss_len))
snprintf(ip, sizeof(ip), "invalidRRdata");
else
addr_to_str(&ss, ss_len, ip, sizeof(ip));
dname_str(qinfo->qname, qn);
addr_to_str(&raddr->node.addr,
raddr->node.addrlen,
nm, sizeof(nm));
verbose(VERB_ALGO, "respip: rpz: response-ip trigger %s/%d on %s %s with action %s", nm, raddr->node.net, qn, ip, rpz_action_to_string(respip_action_to_rpz_action(action)));
}
/* break to make sure 'a' stays pointed
* to used auth_zone, and keeps lock */
break;
}
lock_rw_unlock(&raddr->lock);
raddr = NULL;
actinfo->rpz_disabled++;
}
}
lock_rw_unlock(&a->lock);
}
lock_rw_unlock(&az->rpz_lock);
if(raddr && !search_only) {
int result = 0;
/* first, see if we have response-ip or tag action for the
* action except for 'always' variants. */
if(action != respip_always_refuse
&& action != respip_always_transparent
&& action != respip_always_nxdomain
&& action != respip_always_nodata
&& action != respip_always_deny
&& (result = respip_data_answer(action,
(data) ? data : raddr->data, qinfo->qtype, rep,
rrset_id, new_repp, tag, tag_datas, tag_datas_size,
ipset->tagname, ipset->num_tags, &redirect_rrset,
region)) < 0) {
ret = 0;
goto done;
}
/* if no action data applied, take action specific to the
* action without data. */
if(!result && !respip_nodata_answer(qinfo->qtype, action, rep,
rrset_id, new_repp, region)) {
ret = 0;
goto done;
}
}
done:
if(view) {
lock_rw_unlock(&view->lock);
}
if(ret) {
/* If we're redirecting the original answer to a
* CNAME, record the CNAME rrset so the caller can take
* the appropriate action. Note that we don't check the
* action type; it should normally be 'redirect', but it
* can be of other type when a data-dependent tag action
* uses redirect response-ip data.
*/
if(redirect_rrset &&
redirect_rrset->rk.type == ntohs(LDNS_RR_TYPE_CNAME) &&
qinfo->qtype != LDNS_RR_TYPE_ANY)
*alias_rrset = redirect_rrset;
/* on success, populate respip result structure */
ret = populate_action_info(actinfo, action, raddr,
redirect_rrset, tag, ipset, search_only, region,
rpz_used, rpz_log, log_name, rpz_cname_override);
}
if(raddr) {
lock_rw_unlock(&raddr->lock);
}
if(rpz_used) {
lock_rw_unlock(&a->lock);
}
return ret;
}
if(event == module_event_new || event == module_event_pass) {
if(!rq) {
rq = regional_alloc_zero(qstate->region, sizeof(*rq));
if(!rq)
goto servfail;
rq->state = RESPIP_INIT;
qstate->minfo[id] = rq;
}
if(rq->state == RESPIP_SUBQUERY_FINISHED) {
qstate->ext_state[id] = module_finished;
return;
}
verbose(VERB_ALGO, "respip: pass to next module");
qstate->ext_state[id] = module_wait_module;
} else if(event == module_event_moddone) {
/* If the reply may be subject to response-ip rewriting
* according to the query type, check the actions. If a
* rewrite is necessary, we'll replace the reply in qstate
* with the new one. */
enum module_ext_state next_state = module_finished;
/* If the query for the CNAME target would result in an unusual rcode,
* we generally translate it as a failure for the base query
* (which would then be translated into SERVFAIL). The only exception
* is NXDOMAIN and YXDOMAIN, which are passed to the end client(s).
* The YXDOMAIN case would be rare but still possible (when
* DNSSEC-validated DNAME has been cached but synthesizing CNAME
* can't be generated due to length limitation) */
tgt_rcode = FLAGS_GET_RCODE(tgt_rep->flags);
if((tgt_rcode != LDNS_RCODE_NOERROR &&
tgt_rcode != LDNS_RCODE_NXDOMAIN &&
tgt_rcode != LDNS_RCODE_YXDOMAIN) ||
(must_validate && tgt_rep->security <= sec_status_bogus)) {
return 0;
}
/* see if the target reply would be subject to a response-ip action. */
if(!respip_rewrite_reply(qinfo, cinfo, tgt_rep, &tmp_rep, &actinfo,
&alias_rrset, 1, region, az, NULL, views, respip_set))
return 0;
if(actinfo.action != respip_none) {
log_info("CNAME target of redirect response-ip action would "
"be subject to response-ip action, too; stripped");
*new_repp = base_rep;
return 1;
}
/* Append target reply to the base. Since we cannot assume
* tgt_rep->rrsets is valid throughout the lifetime of new_rep
* or it can be safely shared by multiple threads, we need to make a
* deep copy. */
new_rep = make_new_reply_info(base_rep, region,
base_rep->an_numrrsets + tgt_rep->an_numrrsets,
base_rep->an_numrrsets);
if(!new_rep)
return 0;
for(i=0,j=base_rep->an_numrrsets; i<tgt_rep->an_numrrsets; i++,j++) {
new_rep->rrsets[j] = respip_copy_rrset(tgt_rep->rrsets[i], region);
if(!new_rep->rrsets[j])
return 0;
}
/* respip subquery should have always been created with a valid reply
* in super. */
log_assert(super->return_msg && super->return_msg->rep);
/* return_msg can be NULL when, e.g., the sub query resulted in
* SERVFAIL, in which case we regard it as a failure of the original
* query. Other checks are probably redundant, but we check them
* for safety. */
if(!qstate->return_msg || !qstate->return_msg->rep ||
qstate->return_rcode != LDNS_RCODE_NOERROR)
goto fail;