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