Home | History | Annotate | Line # | Download | only in respip
respip.c revision 1.1.1.3
      1      1.1  christos /*
      2      1.1  christos  * respip/respip.c - filtering response IP module
      3      1.1  christos  */
      4      1.1  christos 
      5      1.1  christos /**
      6      1.1  christos  * \file
      7      1.1  christos  *
      8      1.1  christos  * This file contains a module that inspects a result of recursive resolution
      9      1.1  christos  * to see if any IP address record should trigger a special action.
     10      1.1  christos  * If applicable these actions can modify the original response.
     11      1.1  christos  */
     12      1.1  christos #include "config.h"
     13      1.1  christos 
     14      1.1  christos #include "services/localzone.h"
     15      1.1  christos #include "services/cache/dns.h"
     16      1.1  christos #include "sldns/str2wire.h"
     17      1.1  christos #include "util/config_file.h"
     18      1.1  christos #include "util/fptr_wlist.h"
     19      1.1  christos #include "util/module.h"
     20      1.1  christos #include "util/net_help.h"
     21      1.1  christos #include "util/regional.h"
     22      1.1  christos #include "util/data/msgreply.h"
     23      1.1  christos #include "util/storage/dnstree.h"
     24      1.1  christos #include "respip/respip.h"
     25      1.1  christos #include "services/view.h"
     26      1.1  christos #include "sldns/rrdef.h"
     27      1.1  christos 
     28      1.1  christos /**
     29      1.1  christos  * Conceptual set of IP addresses for response AAAA or A records that should
     30      1.1  christos  * trigger special actions.
     31      1.1  christos  */
     32      1.1  christos struct respip_set {
     33      1.1  christos 	struct regional* region;
     34      1.1  christos 	struct rbtree_type ip_tree;
     35      1.1  christos 	char* const* tagname;	/* shallow copy of tag names, for logging */
     36      1.1  christos 	int num_tags;		/* number of tagname entries */
     37      1.1  christos };
     38      1.1  christos 
     39      1.1  christos /** An address span with response control information */
     40      1.1  christos struct resp_addr {
     41      1.1  christos 	/** node in address tree */
     42      1.1  christos 	struct addr_tree_node node;
     43      1.1  christos 	/** tag bitlist */
     44      1.1  christos 	uint8_t* taglist;
     45      1.1  christos 	/** length of the taglist (in bytes) */
     46      1.1  christos 	size_t taglen;
     47      1.1  christos 	/** action for this address span */
     48      1.1  christos 	enum respip_action action;
     49      1.1  christos         /** "local data" for this node */
     50      1.1  christos 	struct ub_packed_rrset_key* data;
     51      1.1  christos };
     52      1.1  christos 
     53      1.1  christos /** Subset of resp_addr.node, used for inform-variant logging */
     54      1.1  christos struct respip_addr_info {
     55      1.1  christos 	struct sockaddr_storage addr;
     56      1.1  christos 	socklen_t addrlen;
     57      1.1  christos 	int net;
     58      1.1  christos };
     59      1.1  christos 
     60      1.1  christos /** Query state regarding the response-ip module. */
     61      1.1  christos enum respip_state {
     62      1.1  christos 	/**
     63      1.1  christos 	 * The general state.  Unless CNAME chasing takes place, all processing
     64      1.1  christos 	 * is completed in this state without any other asynchronous event.
     65      1.1  christos 	 */
     66      1.1  christos 	RESPIP_INIT = 0,
     67      1.1  christos 
     68      1.1  christos 	/**
     69      1.1  christos 	 * A subquery for CNAME chasing is completed.
     70      1.1  christos 	 */
     71      1.1  christos 	RESPIP_SUBQUERY_FINISHED
     72      1.1  christos };
     73      1.1  christos 
     74      1.1  christos /** Per query state for the response-ip module. */
     75      1.1  christos struct respip_qstate {
     76      1.1  christos 	enum respip_state state;
     77      1.1  christos };
     78      1.1  christos 
     79      1.1  christos struct respip_set*
     80      1.1  christos respip_set_create(void)
     81      1.1  christos {
     82      1.1  christos 	struct respip_set* set = calloc(1, sizeof(*set));
     83      1.1  christos 	if(!set)
     84      1.1  christos 		return NULL;
     85      1.1  christos 	set->region = regional_create();
     86      1.1  christos 	if(!set->region) {
     87      1.1  christos 		free(set);
     88      1.1  christos 		return NULL;
     89      1.1  christos 	}
     90      1.1  christos 	addr_tree_init(&set->ip_tree);
     91      1.1  christos 	return set;
     92      1.1  christos }
     93      1.1  christos 
     94      1.1  christos void
     95      1.1  christos respip_set_delete(struct respip_set* set)
     96      1.1  christos {
     97      1.1  christos 	if(!set)
     98      1.1  christos 		return;
     99      1.1  christos 	regional_destroy(set->region);
    100      1.1  christos 	free(set);
    101      1.1  christos }
    102      1.1  christos 
    103      1.1  christos struct rbtree_type*
    104      1.1  christos respip_set_get_tree(struct respip_set* set)
    105      1.1  christos {
    106      1.1  christos 	if(!set)
    107      1.1  christos 		return NULL;
    108      1.1  christos 	return &set->ip_tree;
    109      1.1  christos }
    110      1.1  christos 
    111      1.1  christos /** returns the node in the address tree for the specified netblock string;
    112      1.1  christos  * non-existent node will be created if 'create' is true */
    113      1.1  christos static struct resp_addr*
    114      1.1  christos respip_find_or_create(struct respip_set* set, const char* ipstr, int create)
    115      1.1  christos {
    116      1.1  christos 	struct resp_addr* node;
    117      1.1  christos 	struct sockaddr_storage addr;
    118      1.1  christos 	int net;
    119      1.1  christos 	socklen_t addrlen;
    120      1.1  christos 
    121      1.1  christos 	if(!netblockstrtoaddr(ipstr, 0, &addr, &addrlen, &net)) {
    122      1.1  christos 		log_err("cannot parse netblock: '%s'", ipstr);
    123      1.1  christos 		return NULL;
    124      1.1  christos 	}
    125      1.1  christos 	node = (struct resp_addr*)addr_tree_find(&set->ip_tree, &addr, addrlen, net);
    126      1.1  christos 	if(!node && create) {
    127      1.1  christos 		node = regional_alloc_zero(set->region, sizeof(*node));
    128      1.1  christos 		if(!node) {
    129      1.1  christos 			log_err("out of memory");
    130      1.1  christos 			return NULL;
    131      1.1  christos 		}
    132      1.1  christos 		node->action = respip_none;
    133      1.1  christos 		if(!addr_tree_insert(&set->ip_tree, &node->node, &addr,
    134      1.1  christos 			addrlen, net)) {
    135      1.1  christos 			/* We know we didn't find it, so this should be
    136      1.1  christos 			 * impossible. */
    137      1.1  christos 			log_warn("unexpected: duplicate address: %s", ipstr);
    138      1.1  christos 		}
    139      1.1  christos 	}
    140      1.1  christos 	return node;
    141      1.1  christos }
    142      1.1  christos 
    143      1.1  christos static int
    144      1.1  christos respip_tag_cfg(struct respip_set* set, const char* ipstr,
    145      1.1  christos 	const uint8_t* taglist, size_t taglen)
    146      1.1  christos {
    147      1.1  christos 	struct resp_addr* node;
    148      1.1  christos 
    149      1.1  christos 	if(!(node=respip_find_or_create(set, ipstr, 1)))
    150      1.1  christos 		return 0;
    151      1.1  christos 	if(node->taglist) {
    152      1.1  christos 		log_warn("duplicate response-address-tag for '%s', overridden.",
    153      1.1  christos 			ipstr);
    154      1.1  christos 	}
    155      1.1  christos 	node->taglist = regional_alloc_init(set->region, taglist, taglen);
    156      1.1  christos 	if(!node->taglist) {
    157      1.1  christos 		log_err("out of memory");
    158      1.1  christos 		return 0;
    159      1.1  christos 	}
    160      1.1  christos 	node->taglen = taglen;
    161      1.1  christos 	return 1;
    162      1.1  christos }
    163      1.1  christos 
    164      1.1  christos /** set action for the node specified by the netblock string */
    165      1.1  christos static int
    166      1.1  christos respip_action_cfg(struct respip_set* set, const char* ipstr,
    167      1.1  christos 	const char* actnstr)
    168      1.1  christos {
    169      1.1  christos 	struct resp_addr* node;
    170      1.1  christos 	enum respip_action action;
    171      1.1  christos 
    172      1.1  christos 	if(!(node=respip_find_or_create(set, ipstr, 1)))
    173      1.1  christos 		return 0;
    174      1.1  christos 	if(node->action != respip_none) {
    175  1.1.1.2  christos 		verbose(VERB_QUERY, "duplicate response-ip action for '%s', overridden.",
    176      1.1  christos 			ipstr);
    177      1.1  christos 	}
    178      1.1  christos         if(strcmp(actnstr, "deny") == 0)
    179      1.1  christos                 action = respip_deny;
    180      1.1  christos         else if(strcmp(actnstr, "redirect") == 0)
    181      1.1  christos                 action = respip_redirect;
    182      1.1  christos         else if(strcmp(actnstr, "inform") == 0)
    183      1.1  christos                 action = respip_inform;
    184      1.1  christos         else if(strcmp(actnstr, "inform_deny") == 0)
    185      1.1  christos                 action = respip_inform_deny;
    186  1.1.1.2  christos         else if(strcmp(actnstr, "inform_redirect") == 0)
    187  1.1.1.2  christos                 action = respip_inform_redirect;
    188      1.1  christos         else if(strcmp(actnstr, "always_transparent") == 0)
    189      1.1  christos                 action = respip_always_transparent;
    190      1.1  christos         else if(strcmp(actnstr, "always_refuse") == 0)
    191      1.1  christos                 action = respip_always_refuse;
    192      1.1  christos         else if(strcmp(actnstr, "always_nxdomain") == 0)
    193      1.1  christos                 action = respip_always_nxdomain;
    194      1.1  christos         else {
    195      1.1  christos                 log_err("unknown response-ip action %s", actnstr);
    196      1.1  christos                 return 0;
    197      1.1  christos         }
    198      1.1  christos 	node->action = action;
    199      1.1  christos 	return 1;
    200      1.1  christos }
    201      1.1  christos 
    202      1.1  christos /** allocate and initialize an rrset structure; this function is based
    203      1.1  christos  * on new_local_rrset() from the localzone.c module */
    204      1.1  christos static struct ub_packed_rrset_key*
    205      1.1  christos new_rrset(struct regional* region, uint16_t rrtype, uint16_t rrclass)
    206      1.1  christos {
    207      1.1  christos 	struct packed_rrset_data* pd;
    208      1.1  christos 	struct ub_packed_rrset_key* rrset = regional_alloc_zero(
    209      1.1  christos 		region, sizeof(*rrset));
    210      1.1  christos 	if(!rrset) {
    211      1.1  christos 		log_err("out of memory");
    212      1.1  christos 		return NULL;
    213      1.1  christos 	}
    214      1.1  christos 	rrset->entry.key = rrset;
    215      1.1  christos 	pd = regional_alloc_zero(region, sizeof(*pd));
    216      1.1  christos 	if(!pd) {
    217      1.1  christos 		log_err("out of memory");
    218      1.1  christos 		return NULL;
    219      1.1  christos 	}
    220      1.1  christos 	pd->trust = rrset_trust_prim_noglue;
    221      1.1  christos 	pd->security = sec_status_insecure;
    222      1.1  christos 	rrset->entry.data = pd;
    223      1.1  christos 	rrset->rk.dname = regional_alloc_zero(region, 1);
    224      1.1  christos 	if(!rrset->rk.dname) {
    225      1.1  christos 		log_err("out of memory");
    226      1.1  christos 		return NULL;
    227      1.1  christos 	}
    228      1.1  christos 	rrset->rk.dname_len = 1;
    229      1.1  christos 	rrset->rk.type = htons(rrtype);
    230      1.1  christos 	rrset->rk.rrset_class = htons(rrclass);
    231      1.1  christos 	return rrset;
    232      1.1  christos }
    233      1.1  christos 
    234      1.1  christos /** enter local data as resource records into a response-ip node */
    235      1.1  christos static int
    236      1.1  christos respip_enter_rr(struct regional* region, struct resp_addr* raddr,
    237      1.1  christos 		const char* rrstr, const char* netblock)
    238      1.1  christos {
    239      1.1  christos 	uint8_t* nm;
    240      1.1  christos 	uint16_t rrtype = 0, rrclass = 0;
    241      1.1  christos 	time_t ttl = 0;
    242      1.1  christos 	uint8_t rr[LDNS_RR_BUF_SIZE];
    243      1.1  christos 	uint8_t* rdata = NULL;
    244      1.1  christos 	size_t rdata_len = 0;
    245      1.1  christos 	char buf[65536];
    246      1.1  christos 	char bufshort[64];
    247      1.1  christos 	struct packed_rrset_data* pd;
    248      1.1  christos 	struct sockaddr* sa;
    249      1.1  christos 	int ret;
    250  1.1.1.2  christos 	if(raddr->action != respip_redirect
    251  1.1.1.2  christos 		&& raddr->action != respip_inform_redirect) {
    252      1.1  christos 		log_err("cannot parse response-ip-data %s: response-ip "
    253      1.1  christos 			"action for %s is not redirect", rrstr, netblock);
    254      1.1  christos 		return 0;
    255      1.1  christos 	}
    256      1.1  christos 	ret = snprintf(buf, sizeof(buf), ". %s", rrstr);
    257      1.1  christos 	if(ret < 0 || ret >= (int)sizeof(buf)) {
    258      1.1  christos 		strlcpy(bufshort, rrstr, sizeof(bufshort));
    259      1.1  christos 		log_err("bad response-ip-data: %s...", bufshort);
    260      1.1  christos 		return 0;
    261      1.1  christos 	}
    262      1.1  christos 	if(!rrstr_get_rr_content(buf, &nm, &rrtype, &rrclass, &ttl, rr, sizeof(rr),
    263      1.1  christos 		&rdata, &rdata_len)) {
    264      1.1  christos 		log_err("bad response-ip-data: %s", rrstr);
    265      1.1  christos 		return 0;
    266      1.1  christos 	}
    267      1.1  christos 	free(nm);
    268      1.1  christos 	sa = (struct sockaddr*)&raddr->node.addr;
    269      1.1  christos 	if (rrtype == LDNS_RR_TYPE_CNAME && raddr->data) {
    270      1.1  christos 		log_err("CNAME response-ip data (%s) can not co-exist with other "
    271      1.1  christos 			"response-ip data for netblock %s", rrstr, netblock);
    272      1.1  christos 		return 0;
    273      1.1  christos 	} else if (raddr->data &&
    274      1.1  christos 		raddr->data->rk.type == htons(LDNS_RR_TYPE_CNAME)) {
    275      1.1  christos 		log_err("response-ip data (%s) can not be added; CNAME response-ip "
    276      1.1  christos 			"data already in place for netblock %s", rrstr, netblock);
    277      1.1  christos 		return 0;
    278      1.1  christos 	} else if((rrtype != LDNS_RR_TYPE_CNAME) &&
    279      1.1  christos 		((sa->sa_family == AF_INET && rrtype != LDNS_RR_TYPE_A) ||
    280      1.1  christos 		(sa->sa_family == AF_INET6 && rrtype != LDNS_RR_TYPE_AAAA))) {
    281      1.1  christos 		log_err("response-ip data %s record type does not correspond "
    282      1.1  christos 			"to netblock %s address family", rrstr, netblock);
    283      1.1  christos 		return 0;
    284      1.1  christos 	}
    285      1.1  christos 
    286      1.1  christos 	if(!raddr->data) {
    287      1.1  christos 		raddr->data = new_rrset(region, rrtype, rrclass);
    288      1.1  christos 		if(!raddr->data)
    289      1.1  christos 			return 0;
    290      1.1  christos 	}
    291      1.1  christos 	pd = raddr->data->entry.data;
    292      1.1  christos 	return rrset_insert_rr(region, pd, rdata, rdata_len, ttl, rrstr);
    293      1.1  christos }
    294      1.1  christos 
    295      1.1  christos static int
    296      1.1  christos respip_data_cfg(struct respip_set* set, const char* ipstr, const char* rrstr)
    297      1.1  christos {
    298      1.1  christos 	struct resp_addr* node;
    299      1.1  christos 
    300      1.1  christos 	node=respip_find_or_create(set, ipstr, 0);
    301      1.1  christos 	if(!node || node->action == respip_none) {
    302      1.1  christos 		log_err("cannot parse response-ip-data %s: "
    303      1.1  christos 			"response-ip node for %s not found", rrstr, ipstr);
    304      1.1  christos 		return 0;
    305      1.1  christos 	}
    306      1.1  christos 	return respip_enter_rr(set->region, node, rrstr, ipstr);
    307      1.1  christos }
    308      1.1  christos 
    309      1.1  christos static int
    310      1.1  christos respip_set_apply_cfg(struct respip_set* set, char* const* tagname, int num_tags,
    311      1.1  christos 	struct config_strbytelist* respip_tags,
    312      1.1  christos 	struct config_str2list* respip_actions,
    313      1.1  christos 	struct config_str2list* respip_data)
    314      1.1  christos {
    315      1.1  christos 	struct config_strbytelist* p;
    316      1.1  christos 	struct config_str2list* pa;
    317      1.1  christos 	struct config_str2list* pd;
    318      1.1  christos 
    319      1.1  christos 	set->tagname = tagname;
    320      1.1  christos 	set->num_tags = num_tags;
    321      1.1  christos 
    322      1.1  christos 	p = respip_tags;
    323      1.1  christos 	while(p) {
    324      1.1  christos 		struct config_strbytelist* np = p->next;
    325      1.1  christos 
    326      1.1  christos 		log_assert(p->str && p->str2);
    327      1.1  christos 		if(!respip_tag_cfg(set, p->str, p->str2, p->str2len)) {
    328      1.1  christos 			config_del_strbytelist(p);
    329      1.1  christos 			return 0;
    330      1.1  christos 		}
    331      1.1  christos 		free(p->str);
    332      1.1  christos 		free(p->str2);
    333      1.1  christos 		free(p);
    334      1.1  christos 		p = np;
    335      1.1  christos 	}
    336      1.1  christos 
    337      1.1  christos 	pa = respip_actions;
    338      1.1  christos 	while(pa) {
    339      1.1  christos 		struct config_str2list* np = pa->next;
    340      1.1  christos 		log_assert(pa->str && pa->str2);
    341      1.1  christos 		if(!respip_action_cfg(set, pa->str, pa->str2)) {
    342      1.1  christos 			config_deldblstrlist(pa);
    343      1.1  christos 			return 0;
    344      1.1  christos 		}
    345      1.1  christos 		free(pa->str);
    346      1.1  christos 		free(pa->str2);
    347      1.1  christos 		free(pa);
    348      1.1  christos 		pa = np;
    349      1.1  christos 	}
    350      1.1  christos 
    351      1.1  christos 	pd = respip_data;
    352      1.1  christos 	while(pd) {
    353      1.1  christos 		struct config_str2list* np = pd->next;
    354      1.1  christos 		log_assert(pd->str && pd->str2);
    355      1.1  christos 		if(!respip_data_cfg(set, pd->str, pd->str2)) {
    356      1.1  christos 			config_deldblstrlist(pd);
    357      1.1  christos 			return 0;
    358      1.1  christos 		}
    359      1.1  christos 		free(pd->str);
    360      1.1  christos 		free(pd->str2);
    361      1.1  christos 		free(pd);
    362      1.1  christos 		pd = np;
    363      1.1  christos 	}
    364  1.1.1.3  christos 	addr_tree_init_parents(&set->ip_tree);
    365      1.1  christos 
    366      1.1  christos 	return 1;
    367      1.1  christos }
    368      1.1  christos 
    369      1.1  christos int
    370      1.1  christos respip_global_apply_cfg(struct respip_set* set, struct config_file* cfg)
    371      1.1  christos {
    372      1.1  christos 	int ret = respip_set_apply_cfg(set, cfg->tagname, cfg->num_tags,
    373      1.1  christos 		cfg->respip_tags, cfg->respip_actions, cfg->respip_data);
    374      1.1  christos 	cfg->respip_data = NULL;
    375      1.1  christos 	cfg->respip_actions = NULL;
    376      1.1  christos 	cfg->respip_tags = NULL;
    377      1.1  christos 	return ret;
    378      1.1  christos }
    379      1.1  christos 
    380      1.1  christos /** Iterate through raw view data and apply the view-specific respip
    381      1.1  christos  * configuration; at this point we should have already seen all the views,
    382      1.1  christos  * so if any of the views that respip data refer to does not exist, that's
    383      1.1  christos  * an error.  This additional iteration through view configuration data
    384      1.1  christos  * is expected to not have significant performance impact (or rather, its
    385      1.1  christos  * performance impact is not expected to be prohibitive in the configuration
    386      1.1  christos  * processing phase).
    387      1.1  christos  */
    388      1.1  christos int
    389      1.1  christos respip_views_apply_cfg(struct views* vs, struct config_file* cfg,
    390      1.1  christos 	int* have_view_respip_cfg)
    391      1.1  christos {
    392      1.1  christos 	struct config_view* cv;
    393      1.1  christos 	struct view* v;
    394      1.1  christos 	int ret;
    395      1.1  christos 
    396      1.1  christos 	for(cv = cfg->views; cv; cv = cv->next) {
    397      1.1  christos 
    398      1.1  christos 		/** if no respip config for this view then there's
    399      1.1  christos 		  * nothing to do; note that even though respip data must go
    400      1.1  christos 		  * with respip action, we're checking for both here because
    401      1.1  christos 		  * we want to catch the case where the respip action is missing
    402      1.1  christos 		  * while the data is present */
    403      1.1  christos 		if(!cv->respip_actions && !cv->respip_data)
    404      1.1  christos 			continue;
    405      1.1  christos 
    406      1.1  christos 		if(!(v = views_find_view(vs, cv->name, 1))) {
    407      1.1  christos 			log_err("view '%s' unexpectedly missing", cv->name);
    408      1.1  christos 			return 0;
    409      1.1  christos 		}
    410      1.1  christos 		if(!v->respip_set) {
    411      1.1  christos 			v->respip_set = respip_set_create();
    412      1.1  christos 			if(!v->respip_set) {
    413      1.1  christos 				log_err("out of memory");
    414      1.1  christos 				lock_rw_unlock(&v->lock);
    415      1.1  christos 				return 0;
    416      1.1  christos 			}
    417      1.1  christos 		}
    418      1.1  christos 		ret = respip_set_apply_cfg(v->respip_set, NULL, 0, NULL,
    419      1.1  christos 			cv->respip_actions, cv->respip_data);
    420      1.1  christos 		lock_rw_unlock(&v->lock);
    421      1.1  christos 		if(!ret) {
    422      1.1  christos 			log_err("Error while applying respip configuration "
    423      1.1  christos 				"for view '%s'", cv->name);
    424      1.1  christos 			return 0;
    425      1.1  christos 		}
    426      1.1  christos 		*have_view_respip_cfg = (*have_view_respip_cfg ||
    427      1.1  christos 			v->respip_set->ip_tree.count);
    428      1.1  christos 		cv->respip_actions = NULL;
    429      1.1  christos 		cv->respip_data = NULL;
    430      1.1  christos 	}
    431      1.1  christos 	return 1;
    432      1.1  christos }
    433      1.1  christos 
    434      1.1  christos /**
    435      1.1  christos  * make a deep copy of 'key' in 'region'.
    436      1.1  christos  * This is largely derived from packed_rrset_copy_region() and
    437      1.1  christos  * packed_rrset_ptr_fixup(), but differs in the following points:
    438      1.1  christos  *
    439      1.1  christos  * - It doesn't assume all data in 'key' are in a contiguous memory region.
    440      1.1  christos  *   Although that would be the case in most cases, 'key' can be passed from
    441      1.1  christos  *   a lower-level module and it might not build the rrset to meet the
    442      1.1  christos  *   assumption.  In fact, an rrset specified as response-ip-data or generated
    443      1.1  christos  *   in local_data_find_tag_datas() breaks the assumption.  So it would be
    444      1.1  christos  *   safer not to naively rely on the assumption.  On the other hand, this
    445      1.1  christos  *   function ensures the copied rrset data are in a contiguous region so
    446      1.1  christos  *   that it won't cause a disruption even if an upper layer module naively
    447      1.1  christos  *   assumes the memory layout.
    448      1.1  christos  * - It doesn't copy RRSIGs (if any) in 'key'.  The rrset will be used in
    449      1.1  christos  *   a reply that was already faked, so it doesn't make much sense to provide
    450      1.1  christos  *   partial sigs even if they are valid themselves.
    451      1.1  christos  * - It doesn't adjust TTLs as it basically has to be a verbatim copy of 'key'
    452      1.1  christos  *   just allocated in 'region' (the assumption is necessary TTL adjustment
    453      1.1  christos  *   has been already done in 'key').
    454      1.1  christos  *
    455      1.1  christos  * This function returns the copied rrset key on success, and NULL on memory
    456      1.1  christos  * allocation failure.
    457      1.1  christos  */
    458  1.1.1.2  christos static struct ub_packed_rrset_key*
    459      1.1  christos copy_rrset(const struct ub_packed_rrset_key* key, struct regional* region)
    460      1.1  christos {
    461      1.1  christos 	struct ub_packed_rrset_key* ck = regional_alloc(region,
    462      1.1  christos 		sizeof(struct ub_packed_rrset_key));
    463      1.1  christos 	struct packed_rrset_data* d;
    464      1.1  christos 	struct packed_rrset_data* data = key->entry.data;
    465      1.1  christos 	size_t dsize, i;
    466      1.1  christos 	uint8_t* nextrdata;
    467      1.1  christos 
    468      1.1  christos 	/* derived from packed_rrset_copy_region(), but don't use
    469      1.1  christos 	 * packed_rrset_sizeof() and do exclude RRSIGs */
    470      1.1  christos 	if(!ck)
    471      1.1  christos 		return NULL;
    472      1.1  christos 	ck->id = key->id;
    473      1.1  christos 	memset(&ck->entry, 0, sizeof(ck->entry));
    474      1.1  christos 	ck->entry.hash = key->entry.hash;
    475      1.1  christos 	ck->entry.key = ck;
    476      1.1  christos 	ck->rk = key->rk;
    477      1.1  christos 	ck->rk.dname = regional_alloc_init(region, key->rk.dname,
    478      1.1  christos 		key->rk.dname_len);
    479      1.1  christos 	if(!ck->rk.dname)
    480      1.1  christos 		return NULL;
    481      1.1  christos 
    482  1.1.1.3  christos 	if((unsigned)data->count >= 0xffff00U)
    483  1.1.1.3  christos 		return NULL; /* guard against integer overflow in dsize */
    484      1.1  christos 	dsize = sizeof(struct packed_rrset_data) + data->count *
    485      1.1  christos 		(sizeof(size_t)+sizeof(uint8_t*)+sizeof(time_t));
    486  1.1.1.3  christos 	for(i=0; i<data->count; i++) {
    487  1.1.1.3  christos 		if((unsigned)dsize >= 0x0fffffffU ||
    488  1.1.1.3  christos 			(unsigned)data->rr_len[i] >= 0x0fffffffU)
    489  1.1.1.3  christos 			return NULL; /* guard against integer overflow */
    490      1.1  christos 		dsize += data->rr_len[i];
    491  1.1.1.3  christos 	}
    492      1.1  christos 	d = regional_alloc(region, dsize);
    493      1.1  christos 	if(!d)
    494      1.1  christos 		return NULL;
    495      1.1  christos 	*d = *data;
    496      1.1  christos 	d->rrsig_count = 0;
    497      1.1  christos 	ck->entry.data = d;
    498      1.1  christos 
    499      1.1  christos 	/* derived from packed_rrset_ptr_fixup() with copying the data */
    500      1.1  christos 	d->rr_len = (size_t*)((uint8_t*)d + sizeof(struct packed_rrset_data));
    501      1.1  christos 	d->rr_data = (uint8_t**)&(d->rr_len[d->count]);
    502      1.1  christos 	d->rr_ttl = (time_t*)&(d->rr_data[d->count]);
    503      1.1  christos 	nextrdata = (uint8_t*)&(d->rr_ttl[d->count]);
    504      1.1  christos 	for(i=0; i<d->count; i++) {
    505      1.1  christos 		d->rr_len[i] = data->rr_len[i];
    506      1.1  christos 		d->rr_ttl[i] = data->rr_ttl[i];
    507      1.1  christos 		d->rr_data[i] = nextrdata;
    508      1.1  christos 		memcpy(d->rr_data[i], data->rr_data[i], data->rr_len[i]);
    509      1.1  christos 		nextrdata += d->rr_len[i];
    510      1.1  christos 	}
    511      1.1  christos 
    512      1.1  christos 	return ck;
    513      1.1  christos }
    514      1.1  christos 
    515      1.1  christos int
    516      1.1  christos respip_init(struct module_env* env, int id)
    517      1.1  christos {
    518      1.1  christos 	(void)env;
    519      1.1  christos 	(void)id;
    520      1.1  christos 	return 1;
    521      1.1  christos }
    522      1.1  christos 
    523      1.1  christos void
    524      1.1  christos respip_deinit(struct module_env* env, int id)
    525      1.1  christos {
    526      1.1  christos 	(void)env;
    527      1.1  christos 	(void)id;
    528      1.1  christos }
    529      1.1  christos 
    530      1.1  christos /** Convert a packed AAAA or A RRset to sockaddr. */
    531      1.1  christos static int
    532      1.1  christos rdata2sockaddr(const struct packed_rrset_data* rd, uint16_t rtype, size_t i,
    533      1.1  christos 	struct sockaddr_storage* ss, socklen_t* addrlenp)
    534      1.1  christos {
    535      1.1  christos 	/* unbound can accept and cache odd-length AAAA/A records, so we have
    536      1.1  christos 	 * to validate the length. */
    537      1.1  christos 	if(rtype == LDNS_RR_TYPE_A && rd->rr_len[i] == 6) {
    538      1.1  christos 		struct sockaddr_in* sa4 = (struct sockaddr_in*)ss;
    539      1.1  christos 
    540      1.1  christos 		memset(sa4, 0, sizeof(*sa4));
    541      1.1  christos 		sa4->sin_family = AF_INET;
    542      1.1  christos 		memcpy(&sa4->sin_addr, rd->rr_data[i] + 2,
    543      1.1  christos 			sizeof(sa4->sin_addr));
    544      1.1  christos 		*addrlenp = sizeof(*sa4);
    545      1.1  christos 		return 1;
    546      1.1  christos 	} else if(rtype == LDNS_RR_TYPE_AAAA && rd->rr_len[i] == 18) {
    547      1.1  christos 		struct sockaddr_in6* sa6 = (struct sockaddr_in6*)ss;
    548      1.1  christos 
    549      1.1  christos 		memset(sa6, 0, sizeof(*sa6));
    550      1.1  christos 		sa6->sin6_family = AF_INET6;
    551      1.1  christos 		memcpy(&sa6->sin6_addr, rd->rr_data[i] + 2,
    552      1.1  christos 			sizeof(sa6->sin6_addr));
    553      1.1  christos 		*addrlenp = sizeof(*sa6);
    554      1.1  christos 		return 1;
    555      1.1  christos 	}
    556      1.1  christos 	return 0;
    557      1.1  christos }
    558      1.1  christos 
    559      1.1  christos /**
    560      1.1  christos  * Search the given 'iptree' for response address information that matches
    561      1.1  christos  * any of the IP addresses in an AAAA or A in the answer section of the
    562      1.1  christos  * response (stored in 'rep').  If found, a pointer to the matched resp_addr
    563      1.1  christos  * structure will be returned, and '*rrset_id' is set to the index in
    564      1.1  christos  * rep->rrsets for the RRset that contains the matching IP address record
    565      1.1  christos  * (the index is normally 0, but can be larger than that if this is a CNAME
    566      1.1  christos  * chain or type-ANY response).
    567      1.1  christos  */
    568      1.1  christos static const struct resp_addr*
    569      1.1  christos respip_addr_lookup(const struct reply_info *rep, struct rbtree_type* iptree,
    570      1.1  christos 	size_t* rrset_id)
    571      1.1  christos {
    572      1.1  christos 	size_t i;
    573      1.1  christos 	struct resp_addr* ra;
    574      1.1  christos 	struct sockaddr_storage ss;
    575      1.1  christos 	socklen_t addrlen;
    576      1.1  christos 
    577      1.1  christos 	for(i=0; i<rep->an_numrrsets; i++) {
    578      1.1  christos 		size_t j;
    579      1.1  christos 		const struct packed_rrset_data* rd;
    580      1.1  christos 		uint16_t rtype = ntohs(rep->rrsets[i]->rk.type);
    581      1.1  christos 
    582      1.1  christos 		if(rtype != LDNS_RR_TYPE_A && rtype != LDNS_RR_TYPE_AAAA)
    583      1.1  christos 			continue;
    584      1.1  christos 		rd = rep->rrsets[i]->entry.data;
    585      1.1  christos 		for(j = 0; j < rd->count; j++) {
    586      1.1  christos 			if(!rdata2sockaddr(rd, rtype, j, &ss, &addrlen))
    587      1.1  christos 				continue;
    588      1.1  christos 			ra = (struct resp_addr*)addr_tree_lookup(iptree, &ss,
    589      1.1  christos 				addrlen);
    590      1.1  christos 			if(ra) {
    591      1.1  christos 				*rrset_id = i;
    592      1.1  christos 				return ra;
    593      1.1  christos 			}
    594      1.1  christos 		}
    595      1.1  christos 	}
    596      1.1  christos 
    597      1.1  christos 	return NULL;
    598      1.1  christos }
    599      1.1  christos 
    600      1.1  christos /*
    601      1.1  christos  * Create a new reply_info based on 'rep'.  The new info is based on
    602      1.1  christos  * the passed 'rep', but ignores any rrsets except for the first 'an_numrrsets'
    603      1.1  christos  * RRsets in the answer section.  These answer rrsets are copied to the
    604      1.1  christos  * new info, up to 'copy_rrsets' rrsets (which must not be larger than
    605      1.1  christos  * 'an_numrrsets').  If an_numrrsets > copy_rrsets, the remaining rrsets array
    606      1.1  christos  * entries will be kept empty so the caller can fill them later.  When rrsets
    607      1.1  christos  * are copied, they are shallow copied.  The caller must ensure that the
    608      1.1  christos  * copied rrsets are valid throughout its lifetime and must provide appropriate
    609      1.1  christos  * mutex if it can be shared by multiple threads.
    610      1.1  christos  */
    611      1.1  christos static struct reply_info *
    612      1.1  christos make_new_reply_info(const struct reply_info* rep, struct regional* region,
    613      1.1  christos 	size_t an_numrrsets, size_t copy_rrsets)
    614      1.1  christos {
    615      1.1  christos 	struct reply_info* new_rep;
    616      1.1  christos 	size_t i;
    617      1.1  christos 
    618      1.1  christos 	/* create a base struct.  we specify 'insecure' security status as
    619      1.1  christos 	 * the modified response won't be DNSSEC-valid.  In our faked response
    620      1.1  christos 	 * the authority and additional sections will be empty (except possible
    621      1.1  christos 	 * EDNS0 OPT RR in the additional section appended on sending it out),
    622      1.1  christos 	 * so the total number of RRsets is an_numrrsets. */
    623      1.1  christos 	new_rep = construct_reply_info_base(region, rep->flags,
    624  1.1.1.2  christos 		rep->qdcount, rep->ttl, rep->prefetch_ttl,
    625  1.1.1.2  christos 		rep->serve_expired_ttl, an_numrrsets, 0, 0, an_numrrsets,
    626  1.1.1.2  christos 		sec_status_insecure);
    627      1.1  christos 	if(!new_rep)
    628      1.1  christos 		return NULL;
    629      1.1  christos 	if(!reply_info_alloc_rrset_keys(new_rep, NULL, region))
    630      1.1  christos 		return NULL;
    631      1.1  christos 	for(i=0; i<copy_rrsets; i++)
    632      1.1  christos 		new_rep->rrsets[i] = rep->rrsets[i];
    633      1.1  christos 
    634      1.1  christos 	return new_rep;
    635      1.1  christos }
    636      1.1  christos 
    637      1.1  christos /**
    638      1.1  christos  * See if response-ip or tag data should override the original answer rrset
    639      1.1  christos  * (which is rep->rrsets[rrset_id]) and if so override it.
    640      1.1  christos  * This is (mostly) equivalent to localzone.c:local_data_answer() but for
    641      1.1  christos  * response-ip actions.
    642      1.1  christos  * Note that this function distinguishes error conditions from "success but
    643      1.1  christos  * not overridden".  This is because we want to avoid accidentally applying
    644      1.1  christos  * the "no data" action in case of error.
    645      1.1  christos  * @param raddr: address span that requires an action
    646      1.1  christos  * @param action: action to apply
    647      1.1  christos  * @param qtype: original query type
    648      1.1  christos  * @param rep: original reply message
    649      1.1  christos  * @param rrset_id: the rrset ID in 'rep' to which the action should apply
    650      1.1  christos  * @param new_repp: see respip_rewrite_reply
    651      1.1  christos  * @param tag: if >= 0 the tag ID used to determine the action and data
    652      1.1  christos  * @param tag_datas: data corresponding to 'tag'.
    653      1.1  christos  * @param tag_datas_size: size of 'tag_datas'
    654      1.1  christos  * @param tagname: array of tag names, used for logging
    655      1.1  christos  * @param num_tags: size of 'tagname', used for logging
    656      1.1  christos  * @param redirect_rrsetp: ptr to redirect record
    657      1.1  christos  * @param region: region for building new reply
    658      1.1  christos  * @return 1 if overridden, 0 if not overridden, -1 on error.
    659      1.1  christos  */
    660      1.1  christos static int
    661      1.1  christos respip_data_answer(const struct resp_addr* raddr, enum respip_action action,
    662      1.1  christos 	uint16_t qtype, const struct reply_info* rep,
    663      1.1  christos 	size_t rrset_id, struct reply_info** new_repp, int tag,
    664      1.1  christos 	struct config_strlist** tag_datas, size_t tag_datas_size,
    665      1.1  christos 	char* const* tagname, int num_tags,
    666      1.1  christos 	struct ub_packed_rrset_key** redirect_rrsetp, struct regional* region)
    667      1.1  christos {
    668      1.1  christos 	struct ub_packed_rrset_key* rp = raddr->data;
    669      1.1  christos 	struct reply_info* new_rep;
    670      1.1  christos 	*redirect_rrsetp = NULL;
    671      1.1  christos 
    672      1.1  christos 	if(action == respip_redirect && tag != -1 &&
    673      1.1  christos 		(size_t)tag<tag_datas_size && tag_datas[tag]) {
    674      1.1  christos 		struct query_info dataqinfo;
    675      1.1  christos 		struct ub_packed_rrset_key r;
    676      1.1  christos 
    677      1.1  christos 		/* Extract parameters of the original answer rrset that can be
    678      1.1  christos 		 * rewritten below, in the form of query_info.  Note that these
    679      1.1  christos 		 * can be different from the info of the original query if the
    680      1.1  christos 		 * rrset is a CNAME target.*/
    681      1.1  christos 		memset(&dataqinfo, 0, sizeof(dataqinfo));
    682      1.1  christos 		dataqinfo.qname = rep->rrsets[rrset_id]->rk.dname;
    683      1.1  christos 		dataqinfo.qname_len = rep->rrsets[rrset_id]->rk.dname_len;
    684      1.1  christos 		dataqinfo.qtype = ntohs(rep->rrsets[rrset_id]->rk.type);
    685      1.1  christos 		dataqinfo.qclass = ntohs(rep->rrsets[rrset_id]->rk.rrset_class);
    686      1.1  christos 
    687      1.1  christos 		memset(&r, 0, sizeof(r));
    688      1.1  christos 		if(local_data_find_tag_datas(&dataqinfo, tag_datas[tag], &r,
    689      1.1  christos 			region)) {
    690      1.1  christos 			verbose(VERB_ALGO,
    691      1.1  christos 				"response-ip redirect with tag data [%d] %s",
    692      1.1  christos 				tag, (tag<num_tags?tagname[tag]:"null"));
    693      1.1  christos 			/* use copy_rrset() to 'normalize' memory layout */
    694      1.1  christos 			rp = copy_rrset(&r, region);
    695      1.1  christos 			if(!rp)
    696      1.1  christos 				return -1;
    697      1.1  christos 		}
    698      1.1  christos 	}
    699      1.1  christos 	if(!rp)
    700      1.1  christos 		return 0;
    701      1.1  christos 
    702      1.1  christos 	/* If we are using response-ip-data, we need to make a copy of rrset
    703      1.1  christos 	 * to replace the rrset's dname.  Note that, unlike local data, we
    704      1.1  christos 	 * rename the dname for other actions than redirect.  This is because
    705      1.1  christos 	 * response-ip-data isn't associated to any specific name. */
    706      1.1  christos 	if(rp == raddr->data) {
    707      1.1  christos 		rp = copy_rrset(rp, region);
    708      1.1  christos 		if(!rp)
    709      1.1  christos 			return -1;
    710      1.1  christos 		rp->rk.dname = rep->rrsets[rrset_id]->rk.dname;
    711      1.1  christos 		rp->rk.dname_len = rep->rrsets[rrset_id]->rk.dname_len;
    712      1.1  christos 	}
    713      1.1  christos 
    714      1.1  christos 	/* Build a new reply with redirect rrset.  We keep any preceding CNAMEs
    715      1.1  christos 	 * and replace the address rrset that triggers the action.  If it's
    716      1.1  christos 	 * type ANY query, however, no other answer records should be kept
    717      1.1  christos 	 * (note that it can't be a CNAME chain in this case due to
    718      1.1  christos 	 * sanitizing). */
    719      1.1  christos 	if(qtype == LDNS_RR_TYPE_ANY)
    720      1.1  christos 		rrset_id = 0;
    721      1.1  christos 	new_rep = make_new_reply_info(rep, region, rrset_id + 1, rrset_id);
    722      1.1  christos 	if(!new_rep)
    723      1.1  christos 		return -1;
    724      1.1  christos 	rp->rk.flags |= PACKED_RRSET_FIXEDTTL; /* avoid adjusting TTL */
    725      1.1  christos 	new_rep->rrsets[rrset_id] = rp;
    726      1.1  christos 
    727      1.1  christos 	*redirect_rrsetp = rp;
    728      1.1  christos 	*new_repp = new_rep;
    729      1.1  christos 	return 1;
    730      1.1  christos }
    731      1.1  christos 
    732      1.1  christos /**
    733      1.1  christos  * apply response ip action in case where no action data is provided.
    734      1.1  christos  * this is similar to localzone.c:lz_zone_answer() but simplified due to
    735      1.1  christos  * the characteristics of response ip:
    736      1.1  christos  * - 'deny' variants will be handled at the caller side
    737      1.1  christos  * - no specific processing for 'transparent' variants: unlike local zones,
    738      1.1  christos  *   there is no such a case of 'no data but name existing'.  so all variants
    739      1.1  christos  *   just mean 'transparent if no data'.
    740      1.1  christos  * @param qtype: query type
    741      1.1  christos  * @param action: found action
    742      1.1  christos  * @param rep:
    743      1.1  christos  * @param new_repp
    744      1.1  christos  * @param rrset_id
    745      1.1  christos  * @param region: region for building new reply
    746      1.1  christos  * @return 1 on success, 0 on error.
    747      1.1  christos  */
    748      1.1  christos static int
    749      1.1  christos respip_nodata_answer(uint16_t qtype, enum respip_action action,
    750      1.1  christos 	const struct reply_info *rep, size_t rrset_id,
    751      1.1  christos 	struct reply_info** new_repp, struct regional* region)
    752      1.1  christos {
    753      1.1  christos 	struct reply_info* new_rep;
    754      1.1  christos 
    755      1.1  christos 	if(action == respip_refuse || action == respip_always_refuse) {
    756      1.1  christos 		new_rep = make_new_reply_info(rep, region, 0, 0);
    757      1.1  christos 		if(!new_rep)
    758      1.1  christos 			return 0;
    759      1.1  christos 		FLAGS_SET_RCODE(new_rep->flags, LDNS_RCODE_REFUSED);
    760      1.1  christos 		*new_repp = new_rep;
    761      1.1  christos 		return 1;
    762      1.1  christos 	} else if(action == respip_static || action == respip_redirect ||
    763  1.1.1.2  christos 		action == respip_always_nxdomain ||
    764  1.1.1.2  christos 		action == respip_inform_redirect) {
    765      1.1  christos 		/* Since we don't know about other types of the owner name,
    766      1.1  christos 		 * we generally return NOERROR/NODATA unless an NXDOMAIN action
    767      1.1  christos 		 * is explicitly specified. */
    768      1.1  christos 		int rcode = (action == respip_always_nxdomain)?
    769      1.1  christos 			LDNS_RCODE_NXDOMAIN:LDNS_RCODE_NOERROR;
    770      1.1  christos 
    771      1.1  christos 		/* We should empty the answer section except for any preceding
    772      1.1  christos 		 * CNAMEs (in that case rrset_id > 0).  Type-ANY case is
    773      1.1  christos 		 * special as noted in respip_data_answer(). */
    774      1.1  christos 		if(qtype == LDNS_RR_TYPE_ANY)
    775      1.1  christos 			rrset_id = 0;
    776      1.1  christos 		new_rep = make_new_reply_info(rep, region, rrset_id, rrset_id);
    777      1.1  christos 		if(!new_rep)
    778      1.1  christos 			return 0;
    779      1.1  christos 		FLAGS_SET_RCODE(new_rep->flags, rcode);
    780      1.1  christos 		*new_repp = new_rep;
    781      1.1  christos 		return 1;
    782      1.1  christos 	}
    783      1.1  christos 
    784      1.1  christos 	return 1;
    785      1.1  christos }
    786      1.1  christos 
    787      1.1  christos /** Populate action info structure with the results of response-ip action
    788      1.1  christos  *  processing, iff as the result of response-ip processing we are actually
    789      1.1  christos  *  taking some action. Only action is set if action_only is true.
    790      1.1  christos  *  Returns true on success, false on failure.
    791      1.1  christos  */
    792      1.1  christos static int
    793      1.1  christos populate_action_info(struct respip_action_info* actinfo,
    794      1.1  christos 	enum respip_action action, const struct resp_addr* raddr,
    795      1.1  christos 	const struct ub_packed_rrset_key* ATTR_UNUSED(rrset),
    796      1.1  christos 	int ATTR_UNUSED(tag), const struct respip_set* ATTR_UNUSED(ipset),
    797      1.1  christos 	int ATTR_UNUSED(action_only), struct regional* region)
    798      1.1  christos {
    799      1.1  christos 	if(action == respip_none || !raddr)
    800      1.1  christos 		return 1;
    801      1.1  christos 	actinfo->action = action;
    802      1.1  christos 
    803      1.1  christos 	/* for inform variants, make a copy of the matched address block for
    804      1.1  christos 	 * later logging.  We make a copy to proactively avoid disruption if
    805      1.1  christos 	 *  and when we allow a dynamic update to the respip tree. */
    806      1.1  christos 	if(action == respip_inform || action == respip_inform_deny) {
    807      1.1  christos 		struct respip_addr_info* a =
    808      1.1  christos 			regional_alloc_zero(region, sizeof(*a));
    809      1.1  christos 		if(!a) {
    810      1.1  christos 			log_err("out of memory");
    811      1.1  christos 			return 0;
    812      1.1  christos 		}
    813      1.1  christos 		a->addr = raddr->node.addr;
    814      1.1  christos 		a->addrlen = raddr->node.addrlen;
    815      1.1  christos 		a->net = raddr->node.net;
    816      1.1  christos 		actinfo->addrinfo = a;
    817      1.1  christos 	}
    818      1.1  christos 
    819      1.1  christos 	return 1;
    820      1.1  christos }
    821      1.1  christos 
    822      1.1  christos int
    823      1.1  christos respip_rewrite_reply(const struct query_info* qinfo,
    824      1.1  christos 	const struct respip_client_info* cinfo, const struct reply_info* rep,
    825      1.1  christos 	struct reply_info** new_repp, struct respip_action_info* actinfo,
    826      1.1  christos 	struct ub_packed_rrset_key** alias_rrset, int search_only,
    827      1.1  christos 	struct regional* region)
    828      1.1  christos {
    829      1.1  christos 	const uint8_t* ctaglist;
    830      1.1  christos 	size_t ctaglen;
    831      1.1  christos 	const uint8_t* tag_actions;
    832      1.1  christos 	size_t tag_actions_size;
    833      1.1  christos 	struct config_strlist** tag_datas;
    834      1.1  christos 	size_t tag_datas_size;
    835      1.1  christos 	struct view* view = NULL;
    836      1.1  christos 	struct respip_set* ipset = NULL;
    837      1.1  christos 	size_t rrset_id = 0;
    838      1.1  christos 	enum respip_action action = respip_none;
    839      1.1  christos 	int tag = -1;
    840      1.1  christos 	const struct resp_addr* raddr = NULL;
    841      1.1  christos 	int ret = 1;
    842      1.1  christos 	struct ub_packed_rrset_key* redirect_rrset = NULL;
    843      1.1  christos 
    844      1.1  christos 	if(!cinfo)
    845      1.1  christos 		goto done;
    846      1.1  christos 	ctaglist = cinfo->taglist;
    847      1.1  christos 	ctaglen = cinfo->taglen;
    848      1.1  christos 	tag_actions = cinfo->tag_actions;
    849      1.1  christos 	tag_actions_size = cinfo->tag_actions_size;
    850      1.1  christos 	tag_datas = cinfo->tag_datas;
    851      1.1  christos 	tag_datas_size = cinfo->tag_datas_size;
    852      1.1  christos 	view = cinfo->view;
    853      1.1  christos 	ipset = cinfo->respip_set;
    854      1.1  christos 
    855      1.1  christos 	/** Try to use response-ip config from the view first; use
    856      1.1  christos 	  * global response-ip config if we don't have the view or we don't
    857      1.1  christos 	  * have the matching per-view config (and the view allows the use
    858      1.1  christos 	  * of global data in this case).
    859      1.1  christos 	  * Note that we lock the view even if we only use view members that
    860      1.1  christos 	  * currently don't change after creation.  This is for safety for
    861      1.1  christos 	  * future possible changes as the view documentation seems to expect
    862      1.1  christos 	  * any of its member can change in the view's lifetime.
    863      1.1  christos 	  * Note also that we assume 'view' is valid in this function, which
    864      1.1  christos 	  * should be safe (see unbound bug #1191) */
    865      1.1  christos 	if(view) {
    866      1.1  christos 		lock_rw_rdlock(&view->lock);
    867      1.1  christos 		if(view->respip_set) {
    868      1.1  christos 			if((raddr = respip_addr_lookup(rep,
    869      1.1  christos 				&view->respip_set->ip_tree, &rrset_id))) {
    870      1.1  christos 				/** for per-view respip directives the action
    871      1.1  christos 				 * can only be direct (i.e. not tag-based) */
    872      1.1  christos 				action = raddr->action;
    873      1.1  christos 			}
    874      1.1  christos 		}
    875      1.1  christos 		if(!raddr && !view->isfirst)
    876      1.1  christos 			goto done;
    877      1.1  christos 	}
    878      1.1  christos 	if(!raddr && ipset && (raddr = respip_addr_lookup(rep, &ipset->ip_tree,
    879      1.1  christos 		&rrset_id))) {
    880      1.1  christos 		action = (enum respip_action)local_data_find_tag_action(
    881      1.1  christos 			raddr->taglist, raddr->taglen, ctaglist, ctaglen,
    882      1.1  christos 			tag_actions, tag_actions_size,
    883      1.1  christos 			(enum localzone_type)raddr->action, &tag,
    884      1.1  christos 			ipset->tagname, ipset->num_tags);
    885      1.1  christos 	}
    886      1.1  christos 	if(raddr && !search_only) {
    887      1.1  christos 		int result = 0;
    888      1.1  christos 
    889      1.1  christos 		/* first, see if we have response-ip or tag action for the
    890      1.1  christos 		 * action except for 'always' variants. */
    891      1.1  christos 		if(action != respip_always_refuse
    892      1.1  christos 			&& action != respip_always_transparent
    893      1.1  christos 			&& action != respip_always_nxdomain
    894      1.1  christos 			&& (result = respip_data_answer(raddr, action,
    895      1.1  christos 			qinfo->qtype, rep, rrset_id, new_repp, tag, tag_datas,
    896      1.1  christos 			tag_datas_size, ipset->tagname, ipset->num_tags,
    897      1.1  christos 			&redirect_rrset, region)) < 0) {
    898      1.1  christos 			ret = 0;
    899      1.1  christos 			goto done;
    900      1.1  christos 		}
    901      1.1  christos 
    902      1.1  christos 		/* if no action data applied, take action specific to the
    903      1.1  christos 		 * action without data. */
    904      1.1  christos 		if(!result && !respip_nodata_answer(qinfo->qtype, action, rep,
    905      1.1  christos 			rrset_id, new_repp, region)) {
    906      1.1  christos 			ret = 0;
    907      1.1  christos 			goto done;
    908      1.1  christos 		}
    909      1.1  christos 	}
    910      1.1  christos   done:
    911      1.1  christos 	if(view) {
    912      1.1  christos 		lock_rw_unlock(&view->lock);
    913      1.1  christos 	}
    914      1.1  christos 	if(ret) {
    915      1.1  christos 		/* If we're redirecting the original answer to a
    916      1.1  christos 		 * CNAME, record the CNAME rrset so the caller can take
    917      1.1  christos 		 * the appropriate action.  Note that we don't check the
    918      1.1  christos 		 * action type; it should normally be 'redirect', but it
    919      1.1  christos 		 * can be of other type when a data-dependent tag action
    920      1.1  christos 		 * uses redirect response-ip data.
    921      1.1  christos 		 */
    922      1.1  christos 		if(redirect_rrset &&
    923      1.1  christos 			redirect_rrset->rk.type == ntohs(LDNS_RR_TYPE_CNAME) &&
    924      1.1  christos 			qinfo->qtype != LDNS_RR_TYPE_ANY)
    925      1.1  christos 			*alias_rrset = redirect_rrset;
    926      1.1  christos 		/* on success, populate respip result structure */
    927      1.1  christos 		ret = populate_action_info(actinfo, action, raddr,
    928      1.1  christos 			redirect_rrset, tag, ipset, search_only, region);
    929      1.1  christos 	}
    930      1.1  christos 	return ret;
    931      1.1  christos }
    932      1.1  christos 
    933      1.1  christos static int
    934      1.1  christos generate_cname_request(struct module_qstate* qstate,
    935      1.1  christos 	struct ub_packed_rrset_key* alias_rrset)
    936      1.1  christos {
    937      1.1  christos 	struct module_qstate* subq = NULL;
    938      1.1  christos 	struct query_info subqi;
    939      1.1  christos 
    940      1.1  christos 	memset(&subqi, 0, sizeof(subqi));
    941      1.1  christos 	get_cname_target(alias_rrset, &subqi.qname, &subqi.qname_len);
    942      1.1  christos 	if(!subqi.qname)
    943      1.1  christos 		return 0;    /* unexpected: not a valid CNAME RDATA */
    944      1.1  christos 	subqi.qtype = qstate->qinfo.qtype;
    945      1.1  christos 	subqi.qclass = qstate->qinfo.qclass;
    946      1.1  christos 	fptr_ok(fptr_whitelist_modenv_attach_sub(qstate->env->attach_sub));
    947      1.1  christos 	return (*qstate->env->attach_sub)(qstate, &subqi, BIT_RD, 0, 0, &subq);
    948      1.1  christos }
    949      1.1  christos 
    950      1.1  christos void
    951      1.1  christos respip_operate(struct module_qstate* qstate, enum module_ev event, int id,
    952      1.1  christos 	struct outbound_entry* outbound)
    953      1.1  christos {
    954      1.1  christos 	struct respip_qstate* rq = (struct respip_qstate*)qstate->minfo[id];
    955      1.1  christos 
    956      1.1  christos 	log_query_info(VERB_QUERY, "respip operate: query", &qstate->qinfo);
    957      1.1  christos 	(void)outbound;
    958      1.1  christos 
    959      1.1  christos 	if(event == module_event_new || event == module_event_pass) {
    960      1.1  christos 		if(!rq) {
    961      1.1  christos 			rq = regional_alloc_zero(qstate->region, sizeof(*rq));
    962      1.1  christos 			if(!rq)
    963      1.1  christos 				goto servfail;
    964      1.1  christos 			rq->state = RESPIP_INIT;
    965      1.1  christos 			qstate->minfo[id] = rq;
    966      1.1  christos 		}
    967      1.1  christos 		if(rq->state == RESPIP_SUBQUERY_FINISHED) {
    968      1.1  christos 			qstate->ext_state[id] = module_finished;
    969      1.1  christos 			return;
    970      1.1  christos 		}
    971      1.1  christos 		verbose(VERB_ALGO, "respip: pass to next module");
    972      1.1  christos 		qstate->ext_state[id] = module_wait_module;
    973      1.1  christos 	} else if(event == module_event_moddone) {
    974      1.1  christos 		/* If the reply may be subject to response-ip rewriting
    975      1.1  christos 		 * according to the query type, check the actions.  If a
    976      1.1  christos 		 * rewrite is necessary, we'll replace the reply in qstate
    977      1.1  christos 		 * with the new one. */
    978      1.1  christos 		enum module_ext_state next_state = module_finished;
    979      1.1  christos 
    980      1.1  christos 		if((qstate->qinfo.qtype == LDNS_RR_TYPE_A ||
    981      1.1  christos 			qstate->qinfo.qtype == LDNS_RR_TYPE_AAAA ||
    982      1.1  christos 			qstate->qinfo.qtype == LDNS_RR_TYPE_ANY) &&
    983      1.1  christos 			qstate->return_msg && qstate->return_msg->rep) {
    984      1.1  christos 			struct respip_action_info actinfo = {respip_none, NULL};
    985      1.1  christos 			struct reply_info* new_rep = qstate->return_msg->rep;
    986      1.1  christos 			struct ub_packed_rrset_key* alias_rrset = NULL;
    987      1.1  christos 
    988      1.1  christos 			if(!respip_rewrite_reply(&qstate->qinfo,
    989      1.1  christos 				qstate->client_info, qstate->return_msg->rep,
    990      1.1  christos 				&new_rep, &actinfo, &alias_rrset, 0,
    991      1.1  christos 				qstate->region)) {
    992      1.1  christos 				goto servfail;
    993      1.1  christos 			}
    994      1.1  christos 			if(actinfo.action != respip_none) {
    995      1.1  christos 				/* save action info for logging on a
    996      1.1  christos 				 * per-front-end-query basis */
    997      1.1  christos 				if(!(qstate->respip_action_info =
    998      1.1  christos 					regional_alloc_init(qstate->region,
    999      1.1  christos 						&actinfo, sizeof(actinfo))))
   1000      1.1  christos 				{
   1001      1.1  christos 					log_err("out of memory");
   1002      1.1  christos 					goto servfail;
   1003      1.1  christos 				}
   1004      1.1  christos 			} else {
   1005      1.1  christos 				qstate->respip_action_info = NULL;
   1006      1.1  christos 			}
   1007      1.1  christos 			if (new_rep == qstate->return_msg->rep &&
   1008      1.1  christos 				(actinfo.action == respip_deny ||
   1009      1.1  christos 				actinfo.action == respip_inform_deny)) {
   1010      1.1  christos 				/* for deny-variant actions (unless response-ip
   1011      1.1  christos 				 * data is applied), mark the query state so
   1012      1.1  christos 				 * the response will be dropped for all
   1013      1.1  christos 				 * clients. */
   1014      1.1  christos 				qstate->is_drop = 1;
   1015      1.1  christos 			} else if(alias_rrset) {
   1016      1.1  christos 				if(!generate_cname_request(qstate, alias_rrset))
   1017      1.1  christos 					goto servfail;
   1018      1.1  christos 				next_state = module_wait_subquery;
   1019      1.1  christos 			}
   1020      1.1  christos 			qstate->return_msg->rep = new_rep;
   1021      1.1  christos 		}
   1022      1.1  christos 		qstate->ext_state[id] = next_state;
   1023      1.1  christos 	} else
   1024      1.1  christos 		qstate->ext_state[id] = module_finished;
   1025      1.1  christos 
   1026      1.1  christos 	return;
   1027      1.1  christos 
   1028      1.1  christos   servfail:
   1029      1.1  christos 	qstate->return_rcode = LDNS_RCODE_SERVFAIL;
   1030      1.1  christos 	qstate->return_msg = NULL;
   1031      1.1  christos }
   1032      1.1  christos 
   1033      1.1  christos int
   1034      1.1  christos respip_merge_cname(struct reply_info* base_rep,
   1035      1.1  christos 	const struct query_info* qinfo, const struct reply_info* tgt_rep,
   1036      1.1  christos 	const struct respip_client_info* cinfo, int must_validate,
   1037      1.1  christos 	struct reply_info** new_repp, struct regional* region)
   1038      1.1  christos {
   1039      1.1  christos 	struct reply_info* new_rep;
   1040      1.1  christos 	struct reply_info* tmp_rep = NULL; /* just a placeholder */
   1041      1.1  christos 	struct ub_packed_rrset_key* alias_rrset = NULL; /* ditto */
   1042      1.1  christos 	uint16_t tgt_rcode;
   1043      1.1  christos 	size_t i, j;
   1044      1.1  christos 	struct respip_action_info actinfo = {respip_none, NULL};
   1045      1.1  christos 
   1046      1.1  christos 	/* If the query for the CNAME target would result in an unusual rcode,
   1047      1.1  christos 	 * we generally translate it as a failure for the base query
   1048      1.1  christos 	 * (which would then be translated into SERVFAIL).  The only exception
   1049      1.1  christos 	 * is NXDOMAIN and YXDOMAIN, which are passed to the end client(s).
   1050      1.1  christos 	 * The YXDOMAIN case would be rare but still possible (when
   1051      1.1  christos 	 * DNSSEC-validated DNAME has been cached but synthesizing CNAME
   1052      1.1  christos 	 * can't be generated due to length limitation) */
   1053      1.1  christos 	tgt_rcode = FLAGS_GET_RCODE(tgt_rep->flags);
   1054      1.1  christos 	if((tgt_rcode != LDNS_RCODE_NOERROR &&
   1055      1.1  christos 		tgt_rcode != LDNS_RCODE_NXDOMAIN &&
   1056      1.1  christos 		tgt_rcode != LDNS_RCODE_YXDOMAIN) ||
   1057      1.1  christos 		(must_validate && tgt_rep->security <= sec_status_bogus)) {
   1058      1.1  christos 		return 0;
   1059      1.1  christos 	}
   1060      1.1  christos 
   1061      1.1  christos 	/* see if the target reply would be subject to a response-ip action. */
   1062      1.1  christos 	if(!respip_rewrite_reply(qinfo, cinfo, tgt_rep, &tmp_rep, &actinfo,
   1063      1.1  christos 		&alias_rrset, 1, region))
   1064      1.1  christos 		return 0;
   1065      1.1  christos 	if(actinfo.action != respip_none) {
   1066      1.1  christos 		log_info("CNAME target of redirect response-ip action would "
   1067      1.1  christos 			"be subject to response-ip action, too; stripped");
   1068      1.1  christos 		*new_repp = base_rep;
   1069      1.1  christos 		return 1;
   1070      1.1  christos 	}
   1071      1.1  christos 
   1072      1.1  christos 	/* Append target reply to the base.  Since we cannot assume
   1073      1.1  christos 	 * tgt_rep->rrsets is valid throughout the lifetime of new_rep
   1074      1.1  christos 	 * or it can be safely shared by multiple threads, we need to make a
   1075      1.1  christos 	 * deep copy. */
   1076      1.1  christos 	new_rep = make_new_reply_info(base_rep, region,
   1077      1.1  christos 		base_rep->an_numrrsets + tgt_rep->an_numrrsets,
   1078      1.1  christos 		base_rep->an_numrrsets);
   1079      1.1  christos 	if(!new_rep)
   1080      1.1  christos 		return 0;
   1081      1.1  christos 	for(i=0,j=base_rep->an_numrrsets; i<tgt_rep->an_numrrsets; i++,j++) {
   1082      1.1  christos 		new_rep->rrsets[j] = copy_rrset(tgt_rep->rrsets[i], region);
   1083      1.1  christos 		if(!new_rep->rrsets[j])
   1084      1.1  christos 			return 0;
   1085      1.1  christos 	}
   1086      1.1  christos 
   1087      1.1  christos 	FLAGS_SET_RCODE(new_rep->flags, tgt_rcode);
   1088      1.1  christos 	*new_repp = new_rep;
   1089      1.1  christos 	return 1;
   1090      1.1  christos }
   1091      1.1  christos 
   1092      1.1  christos void
   1093      1.1  christos respip_inform_super(struct module_qstate* qstate, int id,
   1094      1.1  christos 	struct module_qstate* super)
   1095      1.1  christos {
   1096      1.1  christos 	struct respip_qstate* rq = (struct respip_qstate*)super->minfo[id];
   1097      1.1  christos 	struct reply_info* new_rep = NULL;
   1098      1.1  christos 
   1099      1.1  christos 	rq->state = RESPIP_SUBQUERY_FINISHED;
   1100      1.1  christos 
   1101      1.1  christos 	/* respip subquery should have always been created with a valid reply
   1102      1.1  christos 	 * in super. */
   1103      1.1  christos 	log_assert(super->return_msg && super->return_msg->rep);
   1104      1.1  christos 
   1105      1.1  christos 	/* return_msg can be NULL when, e.g., the sub query resulted in
   1106      1.1  christos 	 * SERVFAIL, in which case we regard it as a failure of the original
   1107      1.1  christos 	 * query.  Other checks are probably redundant, but we check them
   1108      1.1  christos 	 * for safety. */
   1109      1.1  christos 	if(!qstate->return_msg || !qstate->return_msg->rep ||
   1110      1.1  christos 		qstate->return_rcode != LDNS_RCODE_NOERROR)
   1111      1.1  christos 		goto fail;
   1112      1.1  christos 
   1113      1.1  christos 	if(!respip_merge_cname(super->return_msg->rep, &qstate->qinfo,
   1114      1.1  christos 		qstate->return_msg->rep, super->client_info,
   1115      1.1  christos 		super->env->need_to_validate, &new_rep, super->region))
   1116      1.1  christos 		goto fail;
   1117      1.1  christos 	super->return_msg->rep = new_rep;
   1118      1.1  christos 	return;
   1119      1.1  christos 
   1120      1.1  christos   fail:
   1121      1.1  christos 	super->return_rcode = LDNS_RCODE_SERVFAIL;
   1122      1.1  christos 	super->return_msg = NULL;
   1123      1.1  christos 	return;
   1124      1.1  christos }
   1125      1.1  christos 
   1126      1.1  christos void
   1127      1.1  christos respip_clear(struct module_qstate* qstate, int id)
   1128      1.1  christos {
   1129      1.1  christos 	qstate->minfo[id] = NULL;
   1130      1.1  christos }
   1131      1.1  christos 
   1132      1.1  christos size_t
   1133      1.1  christos respip_get_mem(struct module_env* env, int id)
   1134      1.1  christos {
   1135      1.1  christos 	(void)env;
   1136      1.1  christos 	(void)id;
   1137      1.1  christos 	return 0;
   1138      1.1  christos }
   1139      1.1  christos 
   1140      1.1  christos /**
   1141      1.1  christos  * The response-ip function block
   1142      1.1  christos  */
   1143      1.1  christos static struct module_func_block respip_block = {
   1144      1.1  christos 	"respip",
   1145      1.1  christos 	&respip_init, &respip_deinit, &respip_operate, &respip_inform_super,
   1146      1.1  christos 	&respip_clear, &respip_get_mem
   1147      1.1  christos };
   1148      1.1  christos 
   1149      1.1  christos struct module_func_block*
   1150      1.1  christos respip_get_funcblock(void)
   1151      1.1  christos {
   1152      1.1  christos 	return &respip_block;
   1153      1.1  christos }
   1154      1.1  christos 
   1155      1.1  christos enum respip_action
   1156      1.1  christos resp_addr_get_action(const struct resp_addr* addr)
   1157      1.1  christos {
   1158      1.1  christos 	return addr ? addr->action : respip_none;
   1159      1.1  christos }
   1160      1.1  christos 
   1161      1.1  christos struct ub_packed_rrset_key*
   1162      1.1  christos resp_addr_get_rrset(struct resp_addr* addr)
   1163      1.1  christos {
   1164      1.1  christos 	return addr ? addr->data : NULL;
   1165      1.1  christos }
   1166      1.1  christos 
   1167      1.1  christos int
   1168      1.1  christos respip_set_is_empty(const struct respip_set* set)
   1169      1.1  christos {
   1170      1.1  christos 	return set ? set->ip_tree.count == 0 : 1;
   1171      1.1  christos }
   1172      1.1  christos 
   1173      1.1  christos void
   1174      1.1  christos respip_inform_print(struct respip_addr_info* respip_addr, uint8_t* qname,
   1175      1.1  christos 	uint16_t qtype, uint16_t qclass, struct local_rrset* local_alias,
   1176      1.1  christos 	struct comm_reply* repinfo)
   1177      1.1  christos {
   1178      1.1  christos 	char srcip[128], respip[128], txt[512];
   1179      1.1  christos 	unsigned port;
   1180      1.1  christos 
   1181      1.1  christos 	if(local_alias)
   1182      1.1  christos 		qname = local_alias->rrset->rk.dname;
   1183      1.1  christos 	port = (unsigned)((repinfo->addr.ss_family == AF_INET) ?
   1184      1.1  christos 		ntohs(((struct sockaddr_in*)&repinfo->addr)->sin_port) :
   1185      1.1  christos 		ntohs(((struct sockaddr_in6*)&repinfo->addr)->sin6_port));
   1186      1.1  christos 	addr_to_str(&repinfo->addr, repinfo->addrlen, srcip, sizeof(srcip));
   1187      1.1  christos 	addr_to_str(&respip_addr->addr, respip_addr->addrlen,
   1188      1.1  christos 		respip, sizeof(respip));
   1189      1.1  christos 	snprintf(txt, sizeof(txt), "%s/%d inform %s@%u", respip,
   1190      1.1  christos 		respip_addr->net, srcip, port);
   1191  1.1.1.3  christos 	log_nametypeclass(NO_VERBOSE, txt, qname, qtype, qclass);
   1192      1.1  christos }
   1193