xref: /freebsd/contrib/unbound/respip/respip.c (revision 0bd5d367989b3d2de0e8d8ceaa2e31d3f0d96536)
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 
365 	return 1;
366 }
367 
368 int
369 respip_global_apply_cfg(struct respip_set* set, struct config_file* cfg)
370 {
371 	int ret = respip_set_apply_cfg(set, cfg->tagname, cfg->num_tags,
372 		cfg->respip_tags, cfg->respip_actions, cfg->respip_data);
373 	cfg->respip_data = NULL;
374 	cfg->respip_actions = NULL;
375 	cfg->respip_tags = NULL;
376 	return ret;
377 }
378 
379 /** Iterate through raw view data and apply the view-specific respip
380  * configuration; at this point we should have already seen all the views,
381  * so if any of the views that respip data refer to does not exist, that's
382  * an error.  This additional iteration through view configuration data
383  * is expected to not have significant performance impact (or rather, its
384  * performance impact is not expected to be prohibitive in the configuration
385  * processing phase).
386  */
387 int
388 respip_views_apply_cfg(struct views* vs, struct config_file* cfg,
389 	int* have_view_respip_cfg)
390 {
391 	struct config_view* cv;
392 	struct view* v;
393 	int ret;
394 
395 	for(cv = cfg->views; cv; cv = cv->next) {
396 
397 		/** if no respip config for this view then there's
398 		  * nothing to do; note that even though respip data must go
399 		  * with respip action, we're checking for both here because
400 		  * we want to catch the case where the respip action is missing
401 		  * while the data is present */
402 		if(!cv->respip_actions && !cv->respip_data)
403 			continue;
404 
405 		if(!(v = views_find_view(vs, cv->name, 1))) {
406 			log_err("view '%s' unexpectedly missing", cv->name);
407 			return 0;
408 		}
409 		if(!v->respip_set) {
410 			v->respip_set = respip_set_create();
411 			if(!v->respip_set) {
412 				log_err("out of memory");
413 				lock_rw_unlock(&v->lock);
414 				return 0;
415 			}
416 		}
417 		ret = respip_set_apply_cfg(v->respip_set, NULL, 0, NULL,
418 			cv->respip_actions, cv->respip_data);
419 		lock_rw_unlock(&v->lock);
420 		if(!ret) {
421 			log_err("Error while applying respip configuration "
422 				"for view '%s'", cv->name);
423 			return 0;
424 		}
425 		*have_view_respip_cfg = (*have_view_respip_cfg ||
426 			v->respip_set->ip_tree.count);
427 		cv->respip_actions = NULL;
428 		cv->respip_data = NULL;
429 	}
430 	return 1;
431 }
432 
433 /**
434  * make a deep copy of 'key' in 'region'.
435  * This is largely derived from packed_rrset_copy_region() and
436  * packed_rrset_ptr_fixup(), but differs in the following points:
437  *
438  * - It doesn't assume all data in 'key' are in a contiguous memory region.
439  *   Although that would be the case in most cases, 'key' can be passed from
440  *   a lower-level module and it might not build the rrset to meet the
441  *   assumption.  In fact, an rrset specified as response-ip-data or generated
442  *   in local_data_find_tag_datas() breaks the assumption.  So it would be
443  *   safer not to naively rely on the assumption.  On the other hand, this
444  *   function ensures the copied rrset data are in a contiguous region so
445  *   that it won't cause a disruption even if an upper layer module naively
446  *   assumes the memory layout.
447  * - It doesn't copy RRSIGs (if any) in 'key'.  The rrset will be used in
448  *   a reply that was already faked, so it doesn't make much sense to provide
449  *   partial sigs even if they are valid themselves.
450  * - It doesn't adjust TTLs as it basically has to be a verbatim copy of 'key'
451  *   just allocated in 'region' (the assumption is necessary TTL adjustment
452  *   has been already done in 'key').
453  *
454  * This function returns the copied rrset key on success, and NULL on memory
455  * allocation failure.
456  */
457 static struct ub_packed_rrset_key*
458 copy_rrset(const struct ub_packed_rrset_key* key, struct regional* region)
459 {
460 	struct ub_packed_rrset_key* ck = regional_alloc(region,
461 		sizeof(struct ub_packed_rrset_key));
462 	struct packed_rrset_data* d;
463 	struct packed_rrset_data* data = key->entry.data;
464 	size_t dsize, i;
465 	uint8_t* nextrdata;
466 
467 	/* derived from packed_rrset_copy_region(), but don't use
468 	 * packed_rrset_sizeof() and do exclude RRSIGs */
469 	if(!ck)
470 		return NULL;
471 	ck->id = key->id;
472 	memset(&ck->entry, 0, sizeof(ck->entry));
473 	ck->entry.hash = key->entry.hash;
474 	ck->entry.key = ck;
475 	ck->rk = key->rk;
476 	ck->rk.dname = regional_alloc_init(region, key->rk.dname,
477 		key->rk.dname_len);
478 	if(!ck->rk.dname)
479 		return NULL;
480 
481 	dsize = sizeof(struct packed_rrset_data) + data->count *
482 		(sizeof(size_t)+sizeof(uint8_t*)+sizeof(time_t));
483 	for(i=0; i<data->count; i++)
484 		dsize += data->rr_len[i];
485 	d = regional_alloc(region, dsize);
486 	if(!d)
487 		return NULL;
488 	*d = *data;
489 	d->rrsig_count = 0;
490 	ck->entry.data = d;
491 
492 	/* derived from packed_rrset_ptr_fixup() with copying the data */
493 	d->rr_len = (size_t*)((uint8_t*)d + sizeof(struct packed_rrset_data));
494 	d->rr_data = (uint8_t**)&(d->rr_len[d->count]);
495 	d->rr_ttl = (time_t*)&(d->rr_data[d->count]);
496 	nextrdata = (uint8_t*)&(d->rr_ttl[d->count]);
497 	for(i=0; i<d->count; i++) {
498 		d->rr_len[i] = data->rr_len[i];
499 		d->rr_ttl[i] = data->rr_ttl[i];
500 		d->rr_data[i] = nextrdata;
501 		memcpy(d->rr_data[i], data->rr_data[i], data->rr_len[i]);
502 		nextrdata += d->rr_len[i];
503 	}
504 
505 	return ck;
506 }
507 
508 int
509 respip_init(struct module_env* env, int id)
510 {
511 	(void)env;
512 	(void)id;
513 	return 1;
514 }
515 
516 void
517 respip_deinit(struct module_env* env, int id)
518 {
519 	(void)env;
520 	(void)id;
521 }
522 
523 /** Convert a packed AAAA or A RRset to sockaddr. */
524 static int
525 rdata2sockaddr(const struct packed_rrset_data* rd, uint16_t rtype, size_t i,
526 	struct sockaddr_storage* ss, socklen_t* addrlenp)
527 {
528 	/* unbound can accept and cache odd-length AAAA/A records, so we have
529 	 * to validate the length. */
530 	if(rtype == LDNS_RR_TYPE_A && rd->rr_len[i] == 6) {
531 		struct sockaddr_in* sa4 = (struct sockaddr_in*)ss;
532 
533 		memset(sa4, 0, sizeof(*sa4));
534 		sa4->sin_family = AF_INET;
535 		memcpy(&sa4->sin_addr, rd->rr_data[i] + 2,
536 			sizeof(sa4->sin_addr));
537 		*addrlenp = sizeof(*sa4);
538 		return 1;
539 	} else if(rtype == LDNS_RR_TYPE_AAAA && rd->rr_len[i] == 18) {
540 		struct sockaddr_in6* sa6 = (struct sockaddr_in6*)ss;
541 
542 		memset(sa6, 0, sizeof(*sa6));
543 		sa6->sin6_family = AF_INET6;
544 		memcpy(&sa6->sin6_addr, rd->rr_data[i] + 2,
545 			sizeof(sa6->sin6_addr));
546 		*addrlenp = sizeof(*sa6);
547 		return 1;
548 	}
549 	return 0;
550 }
551 
552 /**
553  * Search the given 'iptree' for response address information that matches
554  * any of the IP addresses in an AAAA or A in the answer section of the
555  * response (stored in 'rep').  If found, a pointer to the matched resp_addr
556  * structure will be returned, and '*rrset_id' is set to the index in
557  * rep->rrsets for the RRset that contains the matching IP address record
558  * (the index is normally 0, but can be larger than that if this is a CNAME
559  * chain or type-ANY response).
560  */
561 static const struct resp_addr*
562 respip_addr_lookup(const struct reply_info *rep, struct rbtree_type* iptree,
563 	size_t* rrset_id)
564 {
565 	size_t i;
566 	struct resp_addr* ra;
567 	struct sockaddr_storage ss;
568 	socklen_t addrlen;
569 
570 	for(i=0; i<rep->an_numrrsets; i++) {
571 		size_t j;
572 		const struct packed_rrset_data* rd;
573 		uint16_t rtype = ntohs(rep->rrsets[i]->rk.type);
574 
575 		if(rtype != LDNS_RR_TYPE_A && rtype != LDNS_RR_TYPE_AAAA)
576 			continue;
577 		rd = rep->rrsets[i]->entry.data;
578 		for(j = 0; j < rd->count; j++) {
579 			if(!rdata2sockaddr(rd, rtype, j, &ss, &addrlen))
580 				continue;
581 			ra = (struct resp_addr*)addr_tree_lookup(iptree, &ss,
582 				addrlen);
583 			if(ra) {
584 				*rrset_id = i;
585 				return ra;
586 			}
587 		}
588 	}
589 
590 	return NULL;
591 }
592 
593 /*
594  * Create a new reply_info based on 'rep'.  The new info is based on
595  * the passed 'rep', but ignores any rrsets except for the first 'an_numrrsets'
596  * RRsets in the answer section.  These answer rrsets are copied to the
597  * new info, up to 'copy_rrsets' rrsets (which must not be larger than
598  * 'an_numrrsets').  If an_numrrsets > copy_rrsets, the remaining rrsets array
599  * entries will be kept empty so the caller can fill them later.  When rrsets
600  * are copied, they are shallow copied.  The caller must ensure that the
601  * copied rrsets are valid throughout its lifetime and must provide appropriate
602  * mutex if it can be shared by multiple threads.
603  */
604 static struct reply_info *
605 make_new_reply_info(const struct reply_info* rep, struct regional* region,
606 	size_t an_numrrsets, size_t copy_rrsets)
607 {
608 	struct reply_info* new_rep;
609 	size_t i;
610 
611 	/* create a base struct.  we specify 'insecure' security status as
612 	 * the modified response won't be DNSSEC-valid.  In our faked response
613 	 * the authority and additional sections will be empty (except possible
614 	 * EDNS0 OPT RR in the additional section appended on sending it out),
615 	 * so the total number of RRsets is an_numrrsets. */
616 	new_rep = construct_reply_info_base(region, rep->flags,
617 		rep->qdcount, rep->ttl, rep->prefetch_ttl,
618 		rep->serve_expired_ttl, an_numrrsets, 0, 0, an_numrrsets,
619 		sec_status_insecure);
620 	if(!new_rep)
621 		return NULL;
622 	if(!reply_info_alloc_rrset_keys(new_rep, NULL, region))
623 		return NULL;
624 	for(i=0; i<copy_rrsets; i++)
625 		new_rep->rrsets[i] = rep->rrsets[i];
626 
627 	return new_rep;
628 }
629 
630 /**
631  * See if response-ip or tag data should override the original answer rrset
632  * (which is rep->rrsets[rrset_id]) and if so override it.
633  * This is (mostly) equivalent to localzone.c:local_data_answer() but for
634  * response-ip actions.
635  * Note that this function distinguishes error conditions from "success but
636  * not overridden".  This is because we want to avoid accidentally applying
637  * the "no data" action in case of error.
638  * @param raddr: address span that requires an action
639  * @param action: action to apply
640  * @param qtype: original query type
641  * @param rep: original reply message
642  * @param rrset_id: the rrset ID in 'rep' to which the action should apply
643  * @param new_repp: see respip_rewrite_reply
644  * @param tag: if >= 0 the tag ID used to determine the action and data
645  * @param tag_datas: data corresponding to 'tag'.
646  * @param tag_datas_size: size of 'tag_datas'
647  * @param tagname: array of tag names, used for logging
648  * @param num_tags: size of 'tagname', used for logging
649  * @param redirect_rrsetp: ptr to redirect record
650  * @param region: region for building new reply
651  * @return 1 if overridden, 0 if not overridden, -1 on error.
652  */
653 static int
654 respip_data_answer(const struct resp_addr* raddr, enum respip_action action,
655 	uint16_t qtype, const struct reply_info* rep,
656 	size_t rrset_id, struct reply_info** new_repp, int tag,
657 	struct config_strlist** tag_datas, size_t tag_datas_size,
658 	char* const* tagname, int num_tags,
659 	struct ub_packed_rrset_key** redirect_rrsetp, struct regional* region)
660 {
661 	struct ub_packed_rrset_key* rp = raddr->data;
662 	struct reply_info* new_rep;
663 	*redirect_rrsetp = NULL;
664 
665 	if(action == respip_redirect && tag != -1 &&
666 		(size_t)tag<tag_datas_size && tag_datas[tag]) {
667 		struct query_info dataqinfo;
668 		struct ub_packed_rrset_key r;
669 
670 		/* Extract parameters of the original answer rrset that can be
671 		 * rewritten below, in the form of query_info.  Note that these
672 		 * can be different from the info of the original query if the
673 		 * rrset is a CNAME target.*/
674 		memset(&dataqinfo, 0, sizeof(dataqinfo));
675 		dataqinfo.qname = rep->rrsets[rrset_id]->rk.dname;
676 		dataqinfo.qname_len = rep->rrsets[rrset_id]->rk.dname_len;
677 		dataqinfo.qtype = ntohs(rep->rrsets[rrset_id]->rk.type);
678 		dataqinfo.qclass = ntohs(rep->rrsets[rrset_id]->rk.rrset_class);
679 
680 		memset(&r, 0, sizeof(r));
681 		if(local_data_find_tag_datas(&dataqinfo, tag_datas[tag], &r,
682 			region)) {
683 			verbose(VERB_ALGO,
684 				"response-ip redirect with tag data [%d] %s",
685 				tag, (tag<num_tags?tagname[tag]:"null"));
686 			/* use copy_rrset() to 'normalize' memory layout */
687 			rp = copy_rrset(&r, region);
688 			if(!rp)
689 				return -1;
690 		}
691 	}
692 	if(!rp)
693 		return 0;
694 
695 	/* If we are using response-ip-data, we need to make a copy of rrset
696 	 * to replace the rrset's dname.  Note that, unlike local data, we
697 	 * rename the dname for other actions than redirect.  This is because
698 	 * response-ip-data isn't associated to any specific name. */
699 	if(rp == raddr->data) {
700 		rp = copy_rrset(rp, region);
701 		if(!rp)
702 			return -1;
703 		rp->rk.dname = rep->rrsets[rrset_id]->rk.dname;
704 		rp->rk.dname_len = rep->rrsets[rrset_id]->rk.dname_len;
705 	}
706 
707 	/* Build a new reply with redirect rrset.  We keep any preceding CNAMEs
708 	 * and replace the address rrset that triggers the action.  If it's
709 	 * type ANY query, however, no other answer records should be kept
710 	 * (note that it can't be a CNAME chain in this case due to
711 	 * sanitizing). */
712 	if(qtype == LDNS_RR_TYPE_ANY)
713 		rrset_id = 0;
714 	new_rep = make_new_reply_info(rep, region, rrset_id + 1, rrset_id);
715 	if(!new_rep)
716 		return -1;
717 	rp->rk.flags |= PACKED_RRSET_FIXEDTTL; /* avoid adjusting TTL */
718 	new_rep->rrsets[rrset_id] = rp;
719 
720 	*redirect_rrsetp = rp;
721 	*new_repp = new_rep;
722 	return 1;
723 }
724 
725 /**
726  * apply response ip action in case where no action data is provided.
727  * this is similar to localzone.c:lz_zone_answer() but simplified due to
728  * the characteristics of response ip:
729  * - 'deny' variants will be handled at the caller side
730  * - no specific processing for 'transparent' variants: unlike local zones,
731  *   there is no such a case of 'no data but name existing'.  so all variants
732  *   just mean 'transparent if no data'.
733  * @param qtype: query type
734  * @param action: found action
735  * @param rep:
736  * @param new_repp
737  * @param rrset_id
738  * @param region: region for building new reply
739  * @return 1 on success, 0 on error.
740  */
741 static int
742 respip_nodata_answer(uint16_t qtype, enum respip_action action,
743 	const struct reply_info *rep, size_t rrset_id,
744 	struct reply_info** new_repp, struct regional* region)
745 {
746 	struct reply_info* new_rep;
747 
748 	if(action == respip_refuse || action == respip_always_refuse) {
749 		new_rep = make_new_reply_info(rep, region, 0, 0);
750 		if(!new_rep)
751 			return 0;
752 		FLAGS_SET_RCODE(new_rep->flags, LDNS_RCODE_REFUSED);
753 		*new_repp = new_rep;
754 		return 1;
755 	} else if(action == respip_static || action == respip_redirect ||
756 		action == respip_always_nxdomain ||
757 		action == respip_inform_redirect) {
758 		/* Since we don't know about other types of the owner name,
759 		 * we generally return NOERROR/NODATA unless an NXDOMAIN action
760 		 * is explicitly specified. */
761 		int rcode = (action == respip_always_nxdomain)?
762 			LDNS_RCODE_NXDOMAIN:LDNS_RCODE_NOERROR;
763 
764 		/* We should empty the answer section except for any preceding
765 		 * CNAMEs (in that case rrset_id > 0).  Type-ANY case is
766 		 * special as noted in respip_data_answer(). */
767 		if(qtype == LDNS_RR_TYPE_ANY)
768 			rrset_id = 0;
769 		new_rep = make_new_reply_info(rep, region, rrset_id, rrset_id);
770 		if(!new_rep)
771 			return 0;
772 		FLAGS_SET_RCODE(new_rep->flags, rcode);
773 		*new_repp = new_rep;
774 		return 1;
775 	}
776 
777 	return 1;
778 }
779 
780 /** Populate action info structure with the results of response-ip action
781  *  processing, iff as the result of response-ip processing we are actually
782  *  taking some action. Only action is set if action_only is true.
783  *  Returns true on success, false on failure.
784  */
785 static int
786 populate_action_info(struct respip_action_info* actinfo,
787 	enum respip_action action, const struct resp_addr* raddr,
788 	const struct ub_packed_rrset_key* ATTR_UNUSED(rrset),
789 	int ATTR_UNUSED(tag), const struct respip_set* ATTR_UNUSED(ipset),
790 	int ATTR_UNUSED(action_only), struct regional* region)
791 {
792 	if(action == respip_none || !raddr)
793 		return 1;
794 	actinfo->action = action;
795 
796 	/* for inform variants, make a copy of the matched address block for
797 	 * later logging.  We make a copy to proactively avoid disruption if
798 	 *  and when we allow a dynamic update to the respip tree. */
799 	if(action == respip_inform || action == respip_inform_deny) {
800 		struct respip_addr_info* a =
801 			regional_alloc_zero(region, sizeof(*a));
802 		if(!a) {
803 			log_err("out of memory");
804 			return 0;
805 		}
806 		a->addr = raddr->node.addr;
807 		a->addrlen = raddr->node.addrlen;
808 		a->net = raddr->node.net;
809 		actinfo->addrinfo = a;
810 	}
811 
812 	return 1;
813 }
814 
815 int
816 respip_rewrite_reply(const struct query_info* qinfo,
817 	const struct respip_client_info* cinfo, const struct reply_info* rep,
818 	struct reply_info** new_repp, struct respip_action_info* actinfo,
819 	struct ub_packed_rrset_key** alias_rrset, int search_only,
820 	struct regional* region)
821 {
822 	const uint8_t* ctaglist;
823 	size_t ctaglen;
824 	const uint8_t* tag_actions;
825 	size_t tag_actions_size;
826 	struct config_strlist** tag_datas;
827 	size_t tag_datas_size;
828 	struct view* view = NULL;
829 	struct respip_set* ipset = NULL;
830 	size_t rrset_id = 0;
831 	enum respip_action action = respip_none;
832 	int tag = -1;
833 	const struct resp_addr* raddr = NULL;
834 	int ret = 1;
835 	struct ub_packed_rrset_key* redirect_rrset = NULL;
836 
837 	if(!cinfo)
838 		goto done;
839 	ctaglist = cinfo->taglist;
840 	ctaglen = cinfo->taglen;
841 	tag_actions = cinfo->tag_actions;
842 	tag_actions_size = cinfo->tag_actions_size;
843 	tag_datas = cinfo->tag_datas;
844 	tag_datas_size = cinfo->tag_datas_size;
845 	view = cinfo->view;
846 	ipset = cinfo->respip_set;
847 
848 	/** Try to use response-ip config from the view first; use
849 	  * global response-ip config if we don't have the view or we don't
850 	  * have the matching per-view config (and the view allows the use
851 	  * of global data in this case).
852 	  * Note that we lock the view even if we only use view members that
853 	  * currently don't change after creation.  This is for safety for
854 	  * future possible changes as the view documentation seems to expect
855 	  * any of its member can change in the view's lifetime.
856 	  * Note also that we assume 'view' is valid in this function, which
857 	  * should be safe (see unbound bug #1191) */
858 	if(view) {
859 		lock_rw_rdlock(&view->lock);
860 		if(view->respip_set) {
861 			if((raddr = respip_addr_lookup(rep,
862 				&view->respip_set->ip_tree, &rrset_id))) {
863 				/** for per-view respip directives the action
864 				 * can only be direct (i.e. not tag-based) */
865 				action = raddr->action;
866 			}
867 		}
868 		if(!raddr && !view->isfirst)
869 			goto done;
870 	}
871 	if(!raddr && ipset && (raddr = respip_addr_lookup(rep, &ipset->ip_tree,
872 		&rrset_id))) {
873 		action = (enum respip_action)local_data_find_tag_action(
874 			raddr->taglist, raddr->taglen, ctaglist, ctaglen,
875 			tag_actions, tag_actions_size,
876 			(enum localzone_type)raddr->action, &tag,
877 			ipset->tagname, ipset->num_tags);
878 	}
879 	if(raddr && !search_only) {
880 		int result = 0;
881 
882 		/* first, see if we have response-ip or tag action for the
883 		 * action except for 'always' variants. */
884 		if(action != respip_always_refuse
885 			&& action != respip_always_transparent
886 			&& action != respip_always_nxdomain
887 			&& (result = respip_data_answer(raddr, action,
888 			qinfo->qtype, rep, rrset_id, new_repp, tag, tag_datas,
889 			tag_datas_size, ipset->tagname, ipset->num_tags,
890 			&redirect_rrset, region)) < 0) {
891 			ret = 0;
892 			goto done;
893 		}
894 
895 		/* if no action data applied, take action specific to the
896 		 * action without data. */
897 		if(!result && !respip_nodata_answer(qinfo->qtype, action, rep,
898 			rrset_id, new_repp, region)) {
899 			ret = 0;
900 			goto done;
901 		}
902 	}
903   done:
904 	if(view) {
905 		lock_rw_unlock(&view->lock);
906 	}
907 	if(ret) {
908 		/* If we're redirecting the original answer to a
909 		 * CNAME, record the CNAME rrset so the caller can take
910 		 * the appropriate action.  Note that we don't check the
911 		 * action type; it should normally be 'redirect', but it
912 		 * can be of other type when a data-dependent tag action
913 		 * uses redirect response-ip data.
914 		 */
915 		if(redirect_rrset &&
916 			redirect_rrset->rk.type == ntohs(LDNS_RR_TYPE_CNAME) &&
917 			qinfo->qtype != LDNS_RR_TYPE_ANY)
918 			*alias_rrset = redirect_rrset;
919 		/* on success, populate respip result structure */
920 		ret = populate_action_info(actinfo, action, raddr,
921 			redirect_rrset, tag, ipset, search_only, region);
922 	}
923 	return ret;
924 }
925 
926 static int
927 generate_cname_request(struct module_qstate* qstate,
928 	struct ub_packed_rrset_key* alias_rrset)
929 {
930 	struct module_qstate* subq = NULL;
931 	struct query_info subqi;
932 
933 	memset(&subqi, 0, sizeof(subqi));
934 	get_cname_target(alias_rrset, &subqi.qname, &subqi.qname_len);
935 	if(!subqi.qname)
936 		return 0;    /* unexpected: not a valid CNAME RDATA */
937 	subqi.qtype = qstate->qinfo.qtype;
938 	subqi.qclass = qstate->qinfo.qclass;
939 	fptr_ok(fptr_whitelist_modenv_attach_sub(qstate->env->attach_sub));
940 	return (*qstate->env->attach_sub)(qstate, &subqi, BIT_RD, 0, 0, &subq);
941 }
942 
943 void
944 respip_operate(struct module_qstate* qstate, enum module_ev event, int id,
945 	struct outbound_entry* outbound)
946 {
947 	struct respip_qstate* rq = (struct respip_qstate*)qstate->minfo[id];
948 
949 	log_query_info(VERB_QUERY, "respip operate: query", &qstate->qinfo);
950 	(void)outbound;
951 
952 	if(event == module_event_new || event == module_event_pass) {
953 		if(!rq) {
954 			rq = regional_alloc_zero(qstate->region, sizeof(*rq));
955 			if(!rq)
956 				goto servfail;
957 			rq->state = RESPIP_INIT;
958 			qstate->minfo[id] = rq;
959 		}
960 		if(rq->state == RESPIP_SUBQUERY_FINISHED) {
961 			qstate->ext_state[id] = module_finished;
962 			return;
963 		}
964 		verbose(VERB_ALGO, "respip: pass to next module");
965 		qstate->ext_state[id] = module_wait_module;
966 	} else if(event == module_event_moddone) {
967 		/* If the reply may be subject to response-ip rewriting
968 		 * according to the query type, check the actions.  If a
969 		 * rewrite is necessary, we'll replace the reply in qstate
970 		 * with the new one. */
971 		enum module_ext_state next_state = module_finished;
972 
973 		if((qstate->qinfo.qtype == LDNS_RR_TYPE_A ||
974 			qstate->qinfo.qtype == LDNS_RR_TYPE_AAAA ||
975 			qstate->qinfo.qtype == LDNS_RR_TYPE_ANY) &&
976 			qstate->return_msg && qstate->return_msg->rep) {
977 			struct respip_action_info actinfo = {respip_none, NULL};
978 			struct reply_info* new_rep = qstate->return_msg->rep;
979 			struct ub_packed_rrset_key* alias_rrset = NULL;
980 
981 			if(!respip_rewrite_reply(&qstate->qinfo,
982 				qstate->client_info, qstate->return_msg->rep,
983 				&new_rep, &actinfo, &alias_rrset, 0,
984 				qstate->region)) {
985 				goto servfail;
986 			}
987 			if(actinfo.action != respip_none) {
988 				/* save action info for logging on a
989 				 * per-front-end-query basis */
990 				if(!(qstate->respip_action_info =
991 					regional_alloc_init(qstate->region,
992 						&actinfo, sizeof(actinfo))))
993 				{
994 					log_err("out of memory");
995 					goto servfail;
996 				}
997 			} else {
998 				qstate->respip_action_info = NULL;
999 			}
1000 			if (new_rep == qstate->return_msg->rep &&
1001 				(actinfo.action == respip_deny ||
1002 				actinfo.action == respip_inform_deny)) {
1003 				/* for deny-variant actions (unless response-ip
1004 				 * data is applied), mark the query state so
1005 				 * the response will be dropped for all
1006 				 * clients. */
1007 				qstate->is_drop = 1;
1008 			} else if(alias_rrset) {
1009 				if(!generate_cname_request(qstate, alias_rrset))
1010 					goto servfail;
1011 				next_state = module_wait_subquery;
1012 			}
1013 			qstate->return_msg->rep = new_rep;
1014 		}
1015 		qstate->ext_state[id] = next_state;
1016 	} else
1017 		qstate->ext_state[id] = module_finished;
1018 
1019 	return;
1020 
1021   servfail:
1022 	qstate->return_rcode = LDNS_RCODE_SERVFAIL;
1023 	qstate->return_msg = NULL;
1024 }
1025 
1026 int
1027 respip_merge_cname(struct reply_info* base_rep,
1028 	const struct query_info* qinfo, const struct reply_info* tgt_rep,
1029 	const struct respip_client_info* cinfo, int must_validate,
1030 	struct reply_info** new_repp, struct regional* region)
1031 {
1032 	struct reply_info* new_rep;
1033 	struct reply_info* tmp_rep = NULL; /* just a placeholder */
1034 	struct ub_packed_rrset_key* alias_rrset = NULL; /* ditto */
1035 	uint16_t tgt_rcode;
1036 	size_t i, j;
1037 	struct respip_action_info actinfo = {respip_none, NULL};
1038 
1039 	/* If the query for the CNAME target would result in an unusual rcode,
1040 	 * we generally translate it as a failure for the base query
1041 	 * (which would then be translated into SERVFAIL).  The only exception
1042 	 * is NXDOMAIN and YXDOMAIN, which are passed to the end client(s).
1043 	 * The YXDOMAIN case would be rare but still possible (when
1044 	 * DNSSEC-validated DNAME has been cached but synthesizing CNAME
1045 	 * can't be generated due to length limitation) */
1046 	tgt_rcode = FLAGS_GET_RCODE(tgt_rep->flags);
1047 	if((tgt_rcode != LDNS_RCODE_NOERROR &&
1048 		tgt_rcode != LDNS_RCODE_NXDOMAIN &&
1049 		tgt_rcode != LDNS_RCODE_YXDOMAIN) ||
1050 		(must_validate && tgt_rep->security <= sec_status_bogus)) {
1051 		return 0;
1052 	}
1053 
1054 	/* see if the target reply would be subject to a response-ip action. */
1055 	if(!respip_rewrite_reply(qinfo, cinfo, tgt_rep, &tmp_rep, &actinfo,
1056 		&alias_rrset, 1, region))
1057 		return 0;
1058 	if(actinfo.action != respip_none) {
1059 		log_info("CNAME target of redirect response-ip action would "
1060 			"be subject to response-ip action, too; stripped");
1061 		*new_repp = base_rep;
1062 		return 1;
1063 	}
1064 
1065 	/* Append target reply to the base.  Since we cannot assume
1066 	 * tgt_rep->rrsets is valid throughout the lifetime of new_rep
1067 	 * or it can be safely shared by multiple threads, we need to make a
1068 	 * deep copy. */
1069 	new_rep = make_new_reply_info(base_rep, region,
1070 		base_rep->an_numrrsets + tgt_rep->an_numrrsets,
1071 		base_rep->an_numrrsets);
1072 	if(!new_rep)
1073 		return 0;
1074 	for(i=0,j=base_rep->an_numrrsets; i<tgt_rep->an_numrrsets; i++,j++) {
1075 		new_rep->rrsets[j] = copy_rrset(tgt_rep->rrsets[i], region);
1076 		if(!new_rep->rrsets[j])
1077 			return 0;
1078 	}
1079 
1080 	FLAGS_SET_RCODE(new_rep->flags, tgt_rcode);
1081 	*new_repp = new_rep;
1082 	return 1;
1083 }
1084 
1085 void
1086 respip_inform_super(struct module_qstate* qstate, int id,
1087 	struct module_qstate* super)
1088 {
1089 	struct respip_qstate* rq = (struct respip_qstate*)super->minfo[id];
1090 	struct reply_info* new_rep = NULL;
1091 
1092 	rq->state = RESPIP_SUBQUERY_FINISHED;
1093 
1094 	/* respip subquery should have always been created with a valid reply
1095 	 * in super. */
1096 	log_assert(super->return_msg && super->return_msg->rep);
1097 
1098 	/* return_msg can be NULL when, e.g., the sub query resulted in
1099 	 * SERVFAIL, in which case we regard it as a failure of the original
1100 	 * query.  Other checks are probably redundant, but we check them
1101 	 * for safety. */
1102 	if(!qstate->return_msg || !qstate->return_msg->rep ||
1103 		qstate->return_rcode != LDNS_RCODE_NOERROR)
1104 		goto fail;
1105 
1106 	if(!respip_merge_cname(super->return_msg->rep, &qstate->qinfo,
1107 		qstate->return_msg->rep, super->client_info,
1108 		super->env->need_to_validate, &new_rep, super->region))
1109 		goto fail;
1110 	super->return_msg->rep = new_rep;
1111 	return;
1112 
1113   fail:
1114 	super->return_rcode = LDNS_RCODE_SERVFAIL;
1115 	super->return_msg = NULL;
1116 	return;
1117 }
1118 
1119 void
1120 respip_clear(struct module_qstate* qstate, int id)
1121 {
1122 	qstate->minfo[id] = NULL;
1123 }
1124 
1125 size_t
1126 respip_get_mem(struct module_env* env, int id)
1127 {
1128 	(void)env;
1129 	(void)id;
1130 	return 0;
1131 }
1132 
1133 /**
1134  * The response-ip function block
1135  */
1136 static struct module_func_block respip_block = {
1137 	"respip",
1138 	&respip_init, &respip_deinit, &respip_operate, &respip_inform_super,
1139 	&respip_clear, &respip_get_mem
1140 };
1141 
1142 struct module_func_block*
1143 respip_get_funcblock(void)
1144 {
1145 	return &respip_block;
1146 }
1147 
1148 enum respip_action
1149 resp_addr_get_action(const struct resp_addr* addr)
1150 {
1151 	return addr ? addr->action : respip_none;
1152 }
1153 
1154 struct ub_packed_rrset_key*
1155 resp_addr_get_rrset(struct resp_addr* addr)
1156 {
1157 	return addr ? addr->data : NULL;
1158 }
1159 
1160 int
1161 respip_set_is_empty(const struct respip_set* set)
1162 {
1163 	return set ? set->ip_tree.count == 0 : 1;
1164 }
1165 
1166 void
1167 respip_inform_print(struct respip_addr_info* respip_addr, uint8_t* qname,
1168 	uint16_t qtype, uint16_t qclass, struct local_rrset* local_alias,
1169 	struct comm_reply* repinfo)
1170 {
1171 	char srcip[128], respip[128], txt[512];
1172 	unsigned port;
1173 
1174 	if(local_alias)
1175 		qname = local_alias->rrset->rk.dname;
1176 	port = (unsigned)((repinfo->addr.ss_family == AF_INET) ?
1177 		ntohs(((struct sockaddr_in*)&repinfo->addr)->sin_port) :
1178 		ntohs(((struct sockaddr_in6*)&repinfo->addr)->sin6_port));
1179 	addr_to_str(&repinfo->addr, repinfo->addrlen, srcip, sizeof(srcip));
1180 	addr_to_str(&respip_addr->addr, respip_addr->addrlen,
1181 		respip, sizeof(respip));
1182 	snprintf(txt, sizeof(txt), "%s/%d inform %s@%u", respip,
1183 		respip_addr->net, srcip, port);
1184 	log_nametypeclass(0, txt, qname, qtype, qclass);
1185 }
1186