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