xref: /freebsd/contrib/unbound/dns64/dns64.c (revision 7a789145f88a6aceacc59029a0cafe7de7aeefea)
1 /*
2  * dns64/dns64.c - DNS64 module
3  *
4  * Copyright (c) 2009, Viagénie. All rights reserved.
5  *
6  * This software is open source.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  *
12  * Redistributions of source code must retain the above copyright notice,
13  * this list of conditions and the following disclaimer.
14  *
15  * Redistributions in binary form must reproduce the above copyright notice,
16  * this list of conditions and the following disclaimer in the documentation
17  * and/or other materials provided with the distribution.
18  *
19  * Neither the name of Viagénie nor the names of its contributors may
20  * be used to endorse or promote products derived from this software without
21  * specific prior written permission.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
25  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
26  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE
27  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
28  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
29  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
30  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
31  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
32  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
33  * POSSIBILITY OF SUCH DAMAGE.
34  */
35 
36 /**
37  * \file
38  *
39  * This file contains a module that performs DNS64 query processing.
40  */
41 
42 #include "config.h"
43 #include "dns64/dns64.h"
44 #include "services/cache/dns.h"
45 #include "services/cache/rrset.h"
46 #include "util/config_file.h"
47 #include "util/data/msgreply.h"
48 #include "util/fptr_wlist.h"
49 #include "util/net_help.h"
50 #include "util/regional.h"
51 #include "util/storage/dnstree.h"
52 #include "util/data/dname.h"
53 #include "sldns/str2wire.h"
54 
55 /******************************************************************************
56  *                                                                            *
57  *                             STATIC CONSTANTS                               *
58  *                                                                            *
59  ******************************************************************************/
60 
61 /**
62  * This is the default DNS64 prefix that is used when the dns64 module is listed
63  * in module-config but when the dns64-prefix variable is not present.
64  */
65 static const char DEFAULT_DNS64_PREFIX[] = "64:ff9b::/96";
66 
67 /**
68  * Maximum length of a domain name in a PTR query in the .in-addr.arpa tree.
69  */
70 #define MAX_PTR_QNAME_IPV4 30
71 
72 /**
73  * State of DNS64 processing for a query.
74  */
75 enum dns64_state {
76     DNS64_INTERNAL_QUERY,    /**< Internally-generated query, no DNS64
77                                   processing. */
78     DNS64_NEW_QUERY,         /**< Query for which we're the first module in
79                                   line. */
80     DNS64_SUBQUERY_FINISHED  /**< Query for which we generated a sub-query, and
81                                   for which this sub-query is finished. */
82 };
83 
84 /**
85  * Per-query module-specific state.  For the DNS64 module.
86  */
87 struct dns64_qstate {
88 	/** State of the DNS64 module. */
89 	enum dns64_state state;
90 	/** If the dns64 module started with no_cache bool set in the qstate,
91 	 * a message to tell it to not modify the cache contents, then this
92 	 * is true.  The dns64 module is then free to modify that flag for
93 	 * its own purposes.
94 	 * Otherwise, it is false, the dns64 module was not told to no_cache */
95 	int started_no_cache_store;
96 };
97 
98 /******************************************************************************
99  *                                                                            *
100  *                                 STRUCTURES                                 *
101  *                                                                            *
102  ******************************************************************************/
103 
104 /**
105  * This structure contains module configuration information. One instance of
106  * this structure exists per instance of the module. Normally there is only one
107  * instance of the module.
108  */
109 struct dns64_env {
110     /**
111      * DNS64 prefix address. We're using a full sockaddr instead of just an
112      * in6_addr because we can reuse Unbound's generic string parsing functions.
113      * It will always contain a sockaddr_in6, and only the sin6_addr member will
114      * ever be used.
115      */
116     struct sockaddr_storage prefix_addr;
117 
118     /**
119      * This is always sizeof(sockaddr_in6).
120      */
121     socklen_t prefix_addrlen;
122 
123     /**
124      * This is the CIDR length of the prefix. It needs to be between 0 and 96.
125      */
126     int prefix_net;
127 
128     /**
129      * Tree of names for which AAAA is ignored. always synthesize from A.
130      */
131     rbtree_type ignore_aaaa;
132 };
133 
134 
135 /******************************************************************************
136  *                                                                            *
137  *                             UTILITY FUNCTIONS                              *
138  *                                                                            *
139  ******************************************************************************/
140 
141 /**
142  * Generic macro for swapping two variables.
143  *
144  * \param t Type of the variables. (e.g. int)
145  * \param a First variable.
146  * \param b Second variable.
147  *
148  * \warning Do not attempt something foolish such as swap(int,a++,b++)!
149  */
150 #define swap(t,a,b) do {t x = a; a = b; b = x;} while(0)
151 
152 /**
153  * Reverses a string.
154  *
155  * \param begin Points to the first character of the string.
156  * \param end   Points one past the last character of the string.
157  */
158 static void
reverse(char * begin,char * end)159 reverse(char* begin, char* end)
160 {
161     while ( begin < --end ) {
162         swap(char, *begin, *end);
163         ++begin;
164     }
165 }
166 
167 /**
168  * Convert an unsigned integer to a string. The point of this function is that
169  * of being faster than sprintf().
170  *
171  * \param n The number to be converted.
172  * \param s The result will be written here. Must be large enough, be careful!
173  *
174  * \return The number of characters written.
175  */
176 static int
uitoa(unsigned n,char * s)177 uitoa(unsigned n, char* s)
178 {
179     char* ss = s;
180     do {
181         *ss++ = '0' + n % 10;
182     } while (n /= 10);
183     reverse(s, ss);
184     return ss - s;
185 }
186 
187 /**
188  * Extract an IPv4 address embedded in the IPv6 address \a ipv6 at offset \a
189  * offset (in bits). Note that bits are not necessarily aligned on bytes so we
190  * need to be careful.
191  *
192  * \param ipv6   IPv6 address represented as a 128-bit array in big-endian
193  *               order.
194  * \param ipv6_len length of the ipv6 byte array.
195  * \param offset Index of the MSB of the IPv4 address embedded in the IPv6
196  *               address.
197  */
198 static uint32_t
extract_ipv4(const uint8_t ipv6[],size_t ipv6_len,const int offset)199 extract_ipv4(const uint8_t ipv6[], size_t ipv6_len, const int offset)
200 {
201     uint32_t ipv4 = 0;
202     int i, pos;
203     log_assert(ipv6_len == 16); (void)ipv6_len;
204     log_assert(offset == 32 || offset == 40 || offset == 48 || offset == 56 ||
205         offset == 64 || offset == 96);
206     for(i = 0, pos = offset / 8; i < 4; i++, pos++) {
207         if (pos == 8)
208             pos++;
209         ipv4 = ipv4 << 8;
210         ipv4 |= ipv6[pos];
211     }
212     return ipv4;
213 }
214 
215 /**
216  * Builds the PTR query name corresponding to an IPv4 address. For example,
217  * given the number 3,464,175,361, this will build the string
218  * "\03206\03123\0231\011\07in-addr\04arpa".
219  *
220  * \param ipv4 IPv4 address represented as an unsigned 32-bit number.
221  * \param ptr  The result will be written here. Must be large enough, be
222  *             careful!
223  * \param nm_len length of the ptr buffer.
224  *
225  * \return The number of characters written.
226  */
227 static size_t
ipv4_to_ptr(uint32_t ipv4,char ptr[],size_t nm_len)228 ipv4_to_ptr(uint32_t ipv4, char ptr[], size_t nm_len)
229 {
230     static const char IPV4_PTR_SUFFIX[] = "\07in-addr\04arpa";
231     int i;
232     char* c = ptr;
233     log_assert(nm_len == MAX_PTR_QNAME_IPV4); (void)nm_len;
234 
235     for (i = 0; i < 4; ++i) {
236         *c = uitoa((unsigned int)(ipv4 % 256), c + 1);
237         c += *c + 1;
238 	log_assert(c < ptr+nm_len);
239         ipv4 /= 256;
240     }
241 
242     log_assert(c + sizeof(IPV4_PTR_SUFFIX) <= ptr+nm_len);
243     memmove(c, IPV4_PTR_SUFFIX, sizeof(IPV4_PTR_SUFFIX));
244 
245     return c + sizeof(IPV4_PTR_SUFFIX) - ptr;
246 }
247 
248 /**
249  * Converts an IPv6-related domain name string from a PTR query into an IPv6
250  * address represented as a 128-bit array.
251  *
252  * \param ptr  The domain name. (e.g. "\011[...]\010\012\016\012\03ip6\04arpa")
253  * \param ipv6 The result will be written here, in network byte order.
254  * \param ipv6_len length of the ipv6 byte array.
255  *
256  * \return 1 on success, 0 on failure.
257  */
258 static int
ptr_to_ipv6(const char * ptr,uint8_t ipv6[],size_t ipv6_len)259 ptr_to_ipv6(const char* ptr, uint8_t ipv6[], size_t ipv6_len)
260 {
261     int i;
262     log_assert(ipv6_len == 16); (void)ipv6_len;
263 
264     for (i = 0; i < 64; i++) {
265         int x;
266 
267         if (ptr[i++] != 1)
268             return 0;
269 
270         if (ptr[i] >= '0' && ptr[i] <= '9') {
271             x = ptr[i] - '0';
272         } else if (ptr[i] >= 'a' && ptr[i] <= 'f') {
273             x = ptr[i] - 'a' + 10;
274         } else if (ptr[i] >= 'A' && ptr[i] <= 'F') {
275             x = ptr[i] - 'A' + 10;
276         } else {
277             return 0;
278         }
279 
280         ipv6[15-i/4] |= x << (2 * ((i-1) % 4));
281     }
282 
283     return 1;
284 }
285 
286 /**
287  * Synthesize an IPv6 address based on an IPv4 address and the DNS64 prefix.
288  *
289  * \param prefix_addr DNS64 prefix address.
290  * \param prefix_addr_len length of the prefix_addr buffer.
291  * \param prefix_net  CIDR length of the DNS64 prefix. Must be between 0 and 96.
292  * \param a           IPv4 address.
293  * \param a_len       length of the a buffer.
294  * \param aaaa        IPv6 address. The result will be written here.
295  * \param aaaa_len    length of the aaaa buffer.
296  */
297 static void
synthesize_aaaa(const uint8_t prefix_addr[],size_t prefix_addr_len,int prefix_net,const uint8_t a[],size_t a_len,uint8_t aaaa[],size_t aaaa_len)298 synthesize_aaaa(const uint8_t prefix_addr[], size_t prefix_addr_len,
299 	int prefix_net, const uint8_t a[], size_t a_len, uint8_t aaaa[],
300 	size_t aaaa_len)
301 {
302     size_t i;
303     int pos;
304     log_assert(prefix_addr_len == 16 && a_len == 4 && aaaa_len == 16);
305     log_assert(prefix_net == 32 || prefix_net == 40 || prefix_net == 48 ||
306         prefix_net == 56 || prefix_net == 64 || prefix_net == 96);
307     (void)prefix_addr_len; (void)a_len; (void)aaaa_len;
308     memcpy(aaaa, prefix_addr, 16);
309     for(i = 0, pos = prefix_net / 8; i < a_len; i++, pos++) {
310         if(pos == 8)
311             aaaa[pos++] = 0;
312         aaaa[pos] = a[i];
313     }
314 }
315 
316 
317 /******************************************************************************
318  *                                                                            *
319  *                           DNS64 MODULE FUNCTIONS                           *
320  *                                                                            *
321  ******************************************************************************/
322 
323 /**
324  * insert ignore_aaaa element into the tree
325  * @param dns64_env: module env.
326  * @param str: string with domain name.
327  * @return false on failure.
328  */
329 static int
dns64_insert_ignore_aaaa(struct dns64_env * dns64_env,char * str)330 dns64_insert_ignore_aaaa(struct dns64_env* dns64_env, char* str)
331 {
332 	/* parse and insert element */
333 	struct name_tree_node* node;
334 	node = (struct name_tree_node*)calloc(1, sizeof(*node));
335 	if(!node) {
336 		log_err("out of memory");
337 		return 0;
338 	}
339 	node->name = sldns_str2wire_dname(str, &node->len);
340 	if(!node->name) {
341 		free(node);
342 		log_err("cannot parse dns64-ignore-aaaa: %s", str);
343 		return 0;
344 	}
345 	node->labs = dname_count_labels(node->name);
346 	node->dclass = LDNS_RR_CLASS_IN;
347 	if(!name_tree_insert(&dns64_env->ignore_aaaa, node,
348 		node->name, node->len, node->labs, node->dclass)) {
349 		/* ignore duplicate element */
350 		free(node->name);
351 		free(node);
352 		return 1;
353 	}
354 	return 1;
355 }
356 
357 /**
358  * This function applies the configuration found in the parsed configuration
359  * file \a cfg to this instance of the dns64 module. Currently only the DNS64
360  * prefix (a.k.a. Pref64) is configurable.
361  *
362  * \param dns64_env Module-specific global parameters.
363  * \param cfg       Parsed configuration file.
364  */
365 static int
dns64_apply_cfg(struct dns64_env * dns64_env,struct config_file * cfg)366 dns64_apply_cfg(struct dns64_env* dns64_env, struct config_file* cfg)
367 {
368     struct config_strlist* s;
369     const char* dns64_prefix = cfg->dns64_prefix ?
370 	cfg->dns64_prefix : DEFAULT_DNS64_PREFIX;
371     verbose(VERB_ALGO, "dns64-prefix: %s", dns64_prefix);
372     if (!netblockstrtoaddr(dns64_prefix, 0, &dns64_env->prefix_addr,
373                 &dns64_env->prefix_addrlen, &dns64_env->prefix_net)) {
374         log_err("cannot parse dns64-prefix netblock: %s", dns64_prefix);
375         return 0;
376     }
377     if (!addr_is_ip6(&dns64_env->prefix_addr, dns64_env->prefix_addrlen)) {
378         log_err("dns64_prefix is not IPv6: %s", dns64_prefix);
379         return 0;
380     }
381     if (dns64_env->prefix_net != 32 && dns64_env->prefix_net != 40 &&
382             dns64_env->prefix_net != 48 && dns64_env->prefix_net != 56 &&
383             dns64_env->prefix_net != 64 && dns64_env->prefix_net != 96 ) {
384         log_err("dns64-prefix length is not 32, 40, 48, 56, 64 or 96: %s",
385                 dns64_prefix);
386         return 0;
387     }
388     for(s = cfg->dns64_ignore_aaaa; s; s = s->next) {
389 	    if(!dns64_insert_ignore_aaaa(dns64_env, s->str))
390 		    return 0;
391     }
392     name_tree_init_parents(&dns64_env->ignore_aaaa);
393     return 1;
394 }
395 
396 /**
397  * Initializes this instance of the dns64 module.
398  *
399  * \param env Global state of all module instances.
400  * \param id  This instance's ID number.
401  */
402 int
dns64_init(struct module_env * env,int id)403 dns64_init(struct module_env* env, int id)
404 {
405     struct dns64_env* dns64_env =
406         (struct dns64_env*)calloc(1, sizeof(struct dns64_env));
407     if (!dns64_env) {
408         log_err("malloc failure");
409         return 0;
410     }
411     env->modinfo[id] = (void*)dns64_env;
412     name_tree_init(&dns64_env->ignore_aaaa);
413     if (!dns64_apply_cfg(dns64_env, env->cfg)) {
414         log_err("dns64: could not apply configuration settings.");
415         return 0;
416     }
417     return 1;
418 }
419 
420 /** free ignore AAAA elements */
421 static void
free_ignore_aaaa_node(rbnode_type * node,void * ATTR_UNUSED (arg))422 free_ignore_aaaa_node(rbnode_type* node, void* ATTR_UNUSED(arg))
423 {
424 	struct name_tree_node* n = (struct name_tree_node*)node;
425 	if(!n) return;
426 	free(n->name);
427 	free(n);
428 }
429 
430 /**
431  * Deinitializes this instance of the dns64 module.
432  *
433  * \param env Global state of all module instances.
434  * \param id  This instance's ID number.
435  */
436 void
dns64_deinit(struct module_env * env,int id)437 dns64_deinit(struct module_env* env, int id)
438 {
439     struct dns64_env* dns64_env;
440     if (!env)
441         return;
442     dns64_env = (struct dns64_env*)env->modinfo[id];
443     if(dns64_env) {
444 	    traverse_postorder(&dns64_env->ignore_aaaa, free_ignore_aaaa_node,
445 	    	NULL);
446     }
447     free(env->modinfo[id]);
448     env->modinfo[id] = NULL;
449 }
450 
451 /**
452  * Handle PTR queries for IPv6 addresses. If the address belongs to the DNS64
453  * prefix, we must do a PTR query for the corresponding IPv4 address instead.
454  *
455  * \param qstate Query state structure.
456  * \param id     This module instance's ID number.
457  *
458  * \return The new state of the query.
459  */
460 static enum module_ext_state
handle_ipv6_ptr(struct module_qstate * qstate,int id)461 handle_ipv6_ptr(struct module_qstate* qstate, int id)
462 {
463     struct dns64_env* dns64_env = (struct dns64_env*)qstate->env->modinfo[id];
464     struct module_qstate* subq = NULL;
465     struct query_info qinfo;
466     struct sockaddr_in6 sin6;
467 
468     /* Convert the PTR query string to an IPv6 address. */
469     memset(&sin6, 0, sizeof(sin6));
470     sin6.sin6_family = AF_INET6;
471     if (!ptr_to_ipv6((char*)qstate->qinfo.qname, sin6.sin6_addr.s6_addr,
472 	sizeof(sin6.sin6_addr.s6_addr)))
473         return module_wait_module;  /* Let other module handle this. */
474 
475     /*
476      * If this IPv6 address is not part of our DNS64 prefix, then we don't need
477      * to do anything. Let another module handle the query.
478      */
479     if (addr_in_common((struct sockaddr_storage*)&sin6, 128,
480                 &dns64_env->prefix_addr, dns64_env->prefix_net,
481                 (socklen_t)sizeof(sin6)) != dns64_env->prefix_net)
482         return module_wait_module;
483 
484     verbose(VERB_ALGO, "dns64: rewrite PTR record");
485 
486     /*
487      * Create a new PTR query info for the domain name corresponding to the IPv4
488      * address corresponding to the IPv6 address corresponding to the original
489      * PTR query domain name.
490      */
491     qinfo = qstate->qinfo;
492     if (!(qinfo.qname = regional_alloc(qstate->region, MAX_PTR_QNAME_IPV4)))
493         return module_error;
494     qinfo.qname_len = ipv4_to_ptr(extract_ipv4(sin6.sin6_addr.s6_addr,
495 		sizeof(sin6.sin6_addr.s6_addr), dns64_env->prefix_net),
496 		(char*)qinfo.qname, MAX_PTR_QNAME_IPV4);
497 
498     /* Create the new sub-query. */
499     fptr_ok(fptr_whitelist_modenv_attach_sub(qstate->env->attach_sub));
500     if(!(*qstate->env->attach_sub)(qstate, &qinfo, qstate->client_info,
501 	    qstate->query_flags, 0, 0, &subq))
502         return module_error;
503     if (subq) {
504         subq->curmod = id;
505         subq->ext_state[id] = module_state_initial;
506 	subq->minfo[id] = NULL;
507     }
508 
509     return module_wait_subquery;
510 }
511 
512 static enum module_ext_state
generate_type_A_query(struct module_qstate * qstate,int id)513 generate_type_A_query(struct module_qstate* qstate, int id)
514 {
515 	struct module_qstate* subq = NULL;
516 	struct query_info qinfo;
517 
518 	verbose(VERB_ALGO, "dns64: query A record");
519 
520 	/* Create a new query info. */
521 	qinfo = qstate->qinfo;
522 	qinfo.qtype = LDNS_RR_TYPE_A;
523 
524 	/* Start the sub-query. */
525 	fptr_ok(fptr_whitelist_modenv_attach_sub(qstate->env->attach_sub));
526 	if(!(*qstate->env->attach_sub)(qstate, &qinfo, qstate->client_info,
527 		qstate->query_flags, 0, 0, &subq))
528 	{
529 		verbose(VERB_ALGO, "dns64: sub-query creation failed");
530 		return module_error;
531 	}
532 	if (subq) {
533 		subq->curmod = id;
534 		subq->ext_state[id] = module_state_initial;
535 		subq->minfo[id] = NULL;
536 	}
537 
538 	return module_wait_subquery;
539 }
540 
541 /**
542  * See if query name is in the always synth config.
543  * The ignore-aaaa list has names for which the AAAA for the domain is
544  * ignored and the A is always used to create the answer.
545  * @param qstate: query state.
546  * @param id: module id.
547  * @return true if the name is covered by ignore-aaaa.
548  */
549 static int
dns64_always_synth_for_qname(struct module_qstate * qstate,int id)550 dns64_always_synth_for_qname(struct module_qstate* qstate, int id)
551 {
552 	struct dns64_env* dns64_env = (struct dns64_env*)qstate->env->modinfo[id];
553 	int labs = dname_count_labels(qstate->qinfo.qname);
554 	struct name_tree_node* node = name_tree_lookup(&dns64_env->ignore_aaaa,
555 		qstate->qinfo.qname, qstate->qinfo.qname_len, labs,
556 		qstate->qinfo.qclass);
557 	return (node != NULL);
558 }
559 
560 /**
561  * Handles the "pass" event for a query. This event is received when a new query
562  * is received by this module. The query may have been generated internally by
563  * another module, in which case we don't want to do any special processing
564  * (this is an interesting discussion topic),  or it may be brand new, e.g.
565  * received over a socket, in which case we do want to apply DNS64 processing.
566  *
567  * \param qstate A structure representing the state of the query that has just
568  *               received the "pass" event.
569  * \param id     This module's instance ID.
570  *
571  * \return The new state of the query.
572  */
573 static enum module_ext_state
handle_event_pass(struct module_qstate * qstate,int id)574 handle_event_pass(struct module_qstate* qstate, int id)
575 {
576 	struct dns64_qstate* iq = (struct dns64_qstate*)qstate->minfo[id];
577 	int synth_all_cfg = qstate->env->cfg->dns64_synthall;
578 	int synth_qname = 0;
579 
580 	if(iq && iq->state == DNS64_NEW_QUERY
581 		&& qstate->qinfo.qtype == LDNS_RR_TYPE_PTR
582 		&& qstate->qinfo.qname_len == 74
583 		&& !strcmp((char*)&qstate->qinfo.qname[64], "\03ip6\04arpa")) {
584 		/* Handle PTR queries for IPv6 addresses. */
585 		return handle_ipv6_ptr(qstate, id);
586 	}
587 
588 	if(iq && iq->state == DNS64_NEW_QUERY &&
589 		qstate->qinfo.qtype == LDNS_RR_TYPE_AAAA &&
590 		(synth_all_cfg ||
591 		(synth_qname=(dns64_always_synth_for_qname(qstate, id)
592 			&& !(qstate->query_flags & BIT_CD))))) {
593 		if(synth_qname)
594 			verbose(VERB_ALGO, "dns64: ignore-aaaa and synthesize anyway");
595 		return generate_type_A_query(qstate, id);
596 	}
597 
598 	/* We are finished when our sub-query is finished. */
599 	if(iq && iq->state == DNS64_SUBQUERY_FINISHED)
600 		return module_finished;
601 
602 	/* Otherwise, pass request to next module. */
603 	verbose(VERB_ALGO, "dns64: pass to next module");
604 	return module_wait_module;
605 }
606 
607 /**
608  * Handles the "done" event for a query. We need to analyze the response and
609  * maybe issue a new sub-query for the A record.
610  *
611  * \param qstate A structure representing the state of the query that has just
612  *               received the "pass" event.
613  * \param id     This module's instance ID.
614  *
615  * \return The new state of the query.
616  */
617 static enum module_ext_state
handle_event_moddone(struct module_qstate * qstate,int id)618 handle_event_moddone(struct module_qstate* qstate, int id)
619 {
620 	struct dns64_qstate* iq = (struct dns64_qstate*)qstate->minfo[id];
621     /*
622      * In many cases we have nothing special to do. From most to least common:
623      *
624      *   - An internal query.
625      *   - A query for a record type other than AAAA.
626      *   - CD FLAG was set on querier
627      *   - An AAAA query for which an error was returned.(qstate.return_rcode)
628      *     -> treated as servfail thus synthesize (sec 5.1.3 6147), thus
629      *        synthesize in (sec 5.1.2 of RFC6147).
630      *   - A successful AAAA query with an answer.
631      */
632 
633 	/* When an AAAA query completes check if we want to perform DNS64
634 	 * synthesis. We skip queries with DNSSEC enabled (!CD) and
635 	 * ones generated by us to retrieve the A/PTR record to use for
636 	 * synth. */
637 	int could_synth =
638 		qstate->qinfo.qtype == LDNS_RR_TYPE_AAAA &&
639 		(!iq || iq->state != DNS64_INTERNAL_QUERY) &&
640 		!(qstate->query_flags & BIT_CD);
641 	int has_data = /* whether query returned non-empty rrset */
642 		qstate->return_msg &&
643 		qstate->return_msg->rep &&
644 		reply_find_answer_rrset(&qstate->qinfo, qstate->return_msg->rep);
645 	int synth_qname = 0;
646 	if(could_synth && !has_data && qstate->env->need_to_validate &&
647 		qstate->return_msg && qstate->return_msg->rep &&
648 		qstate->return_msg->rep->security == sec_status_bogus) {
649 		verbose(VERB_ALGO, "dns64: bogus AAAA reply not synthesized");
650 		could_synth = 0;
651 	}
652 
653 	if(could_synth &&
654 		(!has_data ||
655 		(synth_qname=dns64_always_synth_for_qname(qstate, id)))) {
656 		if(synth_qname)
657 			verbose(VERB_ALGO, "dns64: ignore-aaaa and synthesize anyway");
658 		return generate_type_A_query(qstate, id);
659 	}
660 
661 	/* Store the response in cache. */
662 	if( (!iq || !iq->started_no_cache_store) &&
663 		!qstate->rpz_applied && !qstate->rpz_passthru &&
664 		!qstate->is_subnet_answer &&
665 		qstate->return_msg &&
666 		qstate->return_msg->rep &&
667 		!qstate->fwd_stub_no_cache &&
668 		!dns_cache_store(
669 			qstate->env, &qstate->qinfo, qstate->return_msg->rep,
670 			0, qstate->prefetch_leeway, 0, NULL,
671 			qstate->query_flags, qstate->qstarttime,
672 			qstate->is_valrec))
673 		log_err("out of memory");
674 
675 	/* do nothing */
676 	return module_finished;
677 }
678 
679 /**
680  * This is the module's main() function. It gets called each time a query
681  * receives an event which we may need to handle. We respond by updating the
682  * state of the query.
683  *
684  * \param qstate   Structure containing the state of the query.
685  * \param event    Event that has just been received.
686  * \param id       This module's instance ID.
687  * \param outbound State of a DNS query on an authoritative server. We never do
688  *                 our own queries ourselves (other modules do it for us), so
689  *                 this is unused.
690  */
691 void
dns64_operate(struct module_qstate * qstate,enum module_ev event,int id,struct outbound_entry * outbound)692 dns64_operate(struct module_qstate* qstate, enum module_ev event, int id,
693 		struct outbound_entry* outbound)
694 {
695 	struct dns64_qstate* iq;
696 	(void)outbound;
697 	verbose(VERB_QUERY, "dns64[module %d] operate: extstate:%s event:%s",
698 			id, strextstate(qstate->ext_state[id]),
699 			strmodulevent(event));
700 	log_query_info(VERB_QUERY, "dns64 operate: query", &qstate->qinfo);
701 
702 	switch(event) {
703 		case module_event_new:
704 			/* Tag this query as being new and fall through. */
705 			if (!(iq = (struct dns64_qstate*)regional_alloc(
706 				qstate->region, sizeof(*iq)))) {
707 				log_err("out of memory");
708 				qstate->ext_state[id] = module_error;
709 				return;
710 			}
711 			qstate->minfo[id] = iq;
712 			iq->state = DNS64_NEW_QUERY;
713 			iq->started_no_cache_store = qstate->no_cache_store;
714 			qstate->no_cache_store = 1;
715 			ATTR_FALLTHROUGH
716   			/* fallthrough */
717 		case module_event_pass:
718 			qstate->ext_state[id] = handle_event_pass(qstate, id);
719 			break;
720 		case module_event_moddone:
721 			qstate->ext_state[id] = handle_event_moddone(qstate, id);
722 			break;
723 		default:
724 			qstate->ext_state[id] = module_finished;
725 			break;
726 	}
727 	if(qstate->ext_state[id] == module_finished) {
728 		iq = (struct dns64_qstate*)qstate->minfo[id];
729 		if(iq && iq->state != DNS64_INTERNAL_QUERY) {
730 			if(qstate->fwd_stub_no_cache) {
731 				/* If the forward/stub has no cache, then
732 				 * continue with the query with no cache. */
733 				qstate->no_cache_store = qstate->fwd_stub_no_cache;
734 			} else {
735 				qstate->no_cache_store = iq->started_no_cache_store;
736 			}
737 		}
738 	}
739 }
740 
741 static void
dns64_synth_aaaa_data(const struct ub_packed_rrset_key * fk,const struct packed_rrset_data * fd,struct ub_packed_rrset_key * dk,struct packed_rrset_data ** dd_out,struct regional * region,struct dns64_env * dns64_env)742 dns64_synth_aaaa_data(const struct ub_packed_rrset_key* fk,
743 		      const struct packed_rrset_data* fd,
744 		      struct ub_packed_rrset_key *dk,
745 		      struct packed_rrset_data **dd_out, struct regional *region,
746 		      struct dns64_env* dns64_env )
747 {
748 	struct packed_rrset_data *dd;
749 	size_t i;
750 	/*
751 	 * Create synthesized AAAA RR set data. We need to allocated extra memory
752 	 * for the RRs themselves. Each RR has a length, TTL, pointer to wireformat
753 	 * data, 2 bytes of data length, and 16 bytes of IPv6 address.
754 	 */
755 	if(fd->count > RR_COUNT_MAX) {
756 		*dd_out = NULL;
757 		return; /* integer overflow protection in alloc */
758 	}
759 	if (!(dd = *dd_out = regional_alloc_zero(region,
760 		  sizeof(struct packed_rrset_data)
761 		  + fd->count * (sizeof(size_t) + sizeof(time_t) +
762 			     sizeof(uint8_t*) + 2 + 16)))) {
763 		log_err("out of memory");
764 		return;
765 	}
766 
767 	/* Copy attributes from A RR set. */
768 	dd->ttl = fd->ttl;
769 	dd->count = fd->count;
770 	dd->rrsig_count = 0;
771 	dd->trust = fd->trust;
772 	dd->security = fd->security;
773 
774 	/*
775 	 * Synthesize AAAA records. Adjust pointers in structure.
776 	 */
777 	dd->rr_len =
778 	    (size_t*)((uint8_t*)dd + sizeof(struct packed_rrset_data));
779 	dd->rr_data = (uint8_t**)&dd->rr_len[dd->count];
780 	dd->rr_ttl = (time_t*)&dd->rr_data[dd->count];
781 	for(i = 0; i < fd->count; ++i) {
782 		if (fd->rr_len[i] != 6 || fd->rr_data[i][0] != 0
783 		    || fd->rr_data[i][1] != 4) {
784 			*dd_out = NULL;
785 			return;
786 		}
787 		dd->rr_len[i] = 18;
788 		dd->rr_data[i] =
789 		    (uint8_t*)&dd->rr_ttl[dd->count] + 18*i;
790 		dd->rr_data[i][0] = 0;
791 		dd->rr_data[i][1] = 16;
792 		synthesize_aaaa(
793 				((struct sockaddr_in6*)&dns64_env->prefix_addr)->sin6_addr.s6_addr,
794 				sizeof(((struct sockaddr_in6*)&dns64_env->prefix_addr)->sin6_addr.s6_addr),
795 				dns64_env->prefix_net, &fd->rr_data[i][2],
796 				fd->rr_len[i]-2, &dd->rr_data[i][2],
797 				dd->rr_len[i]-2);
798 		dd->rr_ttl[i] = fd->rr_ttl[i];
799 	}
800 
801 	/*
802 	 * Create synthesized AAAA RR set key. This is mostly just bookkeeping,
803 	 * nothing interesting here.
804 	 */
805 	if(!dk) {
806 		log_err("no key");
807 		*dd_out = NULL;
808 		return;
809 	}
810 
811 	dk->rk.dname = (uint8_t*)regional_alloc_init(region,
812 		     fk->rk.dname, fk->rk.dname_len);
813 
814 	if(!dk->rk.dname) {
815 		log_err("out of memory");
816 		*dd_out = NULL;
817 		return;
818 	}
819 
820 	dk->rk.type = htons(LDNS_RR_TYPE_AAAA);
821 	memset(&dk->entry, 0, sizeof(dk->entry));
822 	dk->entry.key = dk;
823 	dk->entry.hash = rrset_key_hash(&dk->rk);
824 	dk->entry.data = dd;
825 
826 }
827 
828 /**
829  * Synthesize an AAAA RR set from an A sub-query's answer and add it to the
830  * original empty response.
831  *
832  * \param id     This module's instance ID.
833  * \param super  Original AAAA query.
834  * \param qstate A query.
835  */
836 static void
dns64_adjust_a(int id,struct module_qstate * super,struct module_qstate * qstate)837 dns64_adjust_a(int id, struct module_qstate* super, struct module_qstate* qstate)
838 {
839 	struct dns64_env* dns64_env = (struct dns64_env*)super->env->modinfo[id];
840 	struct reply_info *rep, *cp;
841 	size_t i, s;
842 	struct packed_rrset_data* fd, *dd;
843 	struct ub_packed_rrset_key* fk, *dk;
844 	int allocated_return_msg = 0;
845 
846 	verbose(VERB_ALGO, "converting A answers to AAAA answers");
847 
848 	log_assert(super->region);
849 	log_assert(qstate->return_msg);
850 	log_assert(qstate->return_msg->rep);
851 
852 	/* If dns64-synthall is enabled, return_msg is not initialized */
853 	if(!super->return_msg) {
854 		super->return_msg = (struct dns_msg*)regional_alloc(
855 		    super->region, sizeof(struct dns_msg));
856 		if(!super->return_msg)
857 			return;
858 		memset(super->return_msg, 0, sizeof(*super->return_msg));
859 		super->return_msg->qinfo = super->qinfo;
860 		allocated_return_msg = 1;
861 	}
862 
863 	rep = qstate->return_msg->rep;
864 
865 	/*
866 	 * Build the actual reply.
867 	 */
868 	cp = construct_reply_info_base(super->region, rep->flags, rep->qdcount,
869 		rep->ttl, rep->prefetch_ttl, rep->serve_expired_ttl,
870 		rep->serve_expired_norec_ttl,
871 		rep->an_numrrsets, rep->ns_numrrsets, rep->ar_numrrsets,
872 		rep->rrset_count, rep->security, LDNS_EDE_NONE);
873 	if(!cp) {
874 		if(allocated_return_msg) super->return_msg = NULL;
875 		return;
876 	}
877 
878 	/* allocate ub_key structures special or not */
879 	if(!reply_info_alloc_rrset_keys(cp, NULL, super->region)) {
880 		if(allocated_return_msg) super->return_msg = NULL;
881 		return;
882 	}
883 
884 	/* copy everything and replace A by AAAA */
885 	for(i=0; i<cp->rrset_count; i++) {
886 		fk = rep->rrsets[i];
887 		dk = cp->rrsets[i];
888 		fd = (struct packed_rrset_data*)fk->entry.data;
889 		dk->rk = fk->rk;
890 		dk->id = fk->id;
891 
892 		if(i<rep->an_numrrsets && fk->rk.type == htons(LDNS_RR_TYPE_A)) {
893 			/* also sets dk->entry.hash */
894 			dns64_synth_aaaa_data(fk, fd, dk, &dd, super->region, dns64_env);
895 			if(!dd) {
896 				if(allocated_return_msg) super->return_msg = NULL;
897 				return;
898 			}
899 			/* Delete negative AAAA record from cache stored by
900 			 * the iterator module */
901 			rrset_cache_remove(super->env->rrset_cache, dk->rk.dname,
902 					   dk->rk.dname_len, LDNS_RR_TYPE_AAAA,
903 					   LDNS_RR_CLASS_IN, 0);
904 			/* Delete negative AAAA in msg cache for CNAMEs,
905 			 * stored by the iterator module */
906 			if(i != 0) /* if not the first RR */
907 			    msg_cache_remove(super->env, dk->rk.dname,
908 				dk->rk.dname_len, LDNS_RR_TYPE_AAAA,
909 				LDNS_RR_CLASS_IN, 0);
910 		} else {
911 			dk->entry.hash = fk->entry.hash;
912 			dk->rk.dname = (uint8_t*)regional_alloc_init(super->region,
913 				fk->rk.dname, fk->rk.dname_len);
914 
915 			if(!dk->rk.dname) {
916 				if(allocated_return_msg) super->return_msg = NULL;
917 				return;
918 			}
919 
920 			s = packed_rrset_sizeof(fd);
921 			dd = (struct packed_rrset_data*)regional_alloc_init(
922 				super->region, fd, s);
923 
924 			if(!dd) {
925 				if(allocated_return_msg) super->return_msg = NULL;
926 				return;
927 			}
928 		}
929 
930 		packed_rrset_ptr_fixup(dd);
931 		dk->entry.data = (void*)dd;
932 	}
933 
934 	/* Commit changes. */
935 	super->return_msg->rep = cp;
936 }
937 
938 /**
939  * Generate a response for the original IPv6 PTR query based on an IPv4 PTR
940  * sub-query's response.
941  *
942  * \param qstate IPv4 PTR sub-query.
943  * \param super  Original IPv6 PTR query.
944  */
945 static void
dns64_adjust_ptr(struct module_qstate * qstate,struct module_qstate * super)946 dns64_adjust_ptr(struct module_qstate* qstate, struct module_qstate* super)
947 {
948     struct ub_packed_rrset_key* answer;
949 
950     verbose(VERB_ALGO, "adjusting PTR reply");
951 
952     /* Copy the sub-query's reply to the parent. */
953     if (!(super->return_msg = (struct dns_msg*)regional_alloc(super->region,
954                     sizeof(struct dns_msg))))
955         return;
956     super->return_msg->qinfo = super->qinfo;
957     if (!(super->return_msg->rep = reply_info_copy(qstate->return_msg->rep,
958                     NULL, super->region))) {
959 	super->return_msg = NULL;
960         return;
961     }
962 
963     /*
964      * Adjust the domain name of the answer RR set so that it matches the
965      * initial query's domain name.
966      */
967     answer = reply_find_answer_rrset(&qstate->qinfo, super->return_msg->rep);
968     if(answer) {
969 	    answer->rk.dname = super->qinfo.qname;
970 	    answer->rk.dname_len = super->qinfo.qname_len;
971     }
972 }
973 
974 /**
975  * This function is called when a sub-query finishes to inform the parent query.
976  *
977  * We issue two kinds of sub-queries: PTR and A.
978  *
979  * \param qstate State of the sub-query.
980  * \param id     This module's instance ID.
981  * \param super  State of the super-query.
982  */
983 void
dns64_inform_super(struct module_qstate * qstate,int id,struct module_qstate * super)984 dns64_inform_super(struct module_qstate* qstate, int id,
985 		struct module_qstate* super)
986 {
987 	struct dns64_qstate* super_dq = (struct dns64_qstate*)super->minfo[id];
988 	log_query_info(VERB_ALGO, "dns64: inform_super, sub is",
989 		       &qstate->qinfo);
990 	log_query_info(VERB_ALGO, "super is", &super->qinfo);
991 
992 	/*
993 	 * Signal that the sub-query is finished, no matter whether we are
994 	 * successful or not. This lets the state machine terminate.
995 	 */
996 	if(!super_dq) {
997 		super_dq = (struct dns64_qstate*)regional_alloc(super->region,
998 			sizeof(*super_dq));
999 		if(!super_dq) {
1000 			log_err("out of memory");
1001 			super->return_rcode = LDNS_RCODE_SERVFAIL;
1002 			super->return_msg = NULL;
1003 			return;
1004 		}
1005 		super->minfo[id] = super_dq;
1006 		memset(super_dq, 0, sizeof(*super_dq));
1007 		super_dq->started_no_cache_store = super->no_cache_store;
1008 	}
1009 	super_dq->state = DNS64_SUBQUERY_FINISHED;
1010 
1011 	/* If there is no successful answer, we're done.
1012 	 * Guarantee that we have at least a NOERROR reply further on. */
1013 	if(qstate->return_rcode != LDNS_RCODE_NOERROR
1014 		|| !qstate->return_msg
1015 		|| !qstate->return_msg->rep) {
1016 		return;
1017 	}
1018 
1019 	/* When no A record is found for synthesis fall back to AAAA again. */
1020 	if(qstate->qinfo.qtype == LDNS_RR_TYPE_A &&
1021 		!reply_find_answer_rrset(&qstate->qinfo,
1022 			qstate->return_msg->rep)) {
1023 		super_dq->state = DNS64_INTERNAL_QUERY;
1024 		return;
1025 	}
1026 
1027 	/* Use return code from A query in response to client. */
1028 	if (super->return_rcode != LDNS_RCODE_NOERROR)
1029 		super->return_rcode = qstate->return_rcode;
1030 	/* RPZ applied to the subquery need to then change (not cache)
1031 	 * the super query. With the super query not cached, it is
1032 	 * going to run the state machine modules on incoming queries,
1033 	 * that fetch the subquery (cache) response, and modify it
1034 	 * according to the rpz policy. That makes the synthesized
1035 	 * super query also adjusted by rpz policies. But loses cache
1036 	 * hits. Even though the subquery likely is answered from cache,
1037 	 * internally in its state machine process. */
1038 	if(qstate->rpz_applied)
1039 		super->rpz_applied = 1;
1040 	if(qstate->rpz_passthru)
1041 		super->rpz_passthru = 1;
1042 
1043 	/* Since the super qstate has a new response, its errinf is removed. */
1044 	super->errinf = NULL;
1045 
1046 	/* Generate a response suitable for the original query. */
1047 	if (qstate->qinfo.qtype == LDNS_RR_TYPE_A) {
1048 		dns64_adjust_a(id, super, qstate);
1049 	} else {
1050 		log_assert(qstate->qinfo.qtype == LDNS_RR_TYPE_PTR);
1051 		dns64_adjust_ptr(qstate, super);
1052 	}
1053 	/* If the sub-query has no cache store, then also the super query. */
1054 	if(qstate->fwd_stub_no_cache)
1055 		super->fwd_stub_no_cache = 1;
1056 
1057 	/* Store the generated response in cache. */
1058 	if ( super->return_msg && super->return_msg->rep &&
1059 		(!super_dq || !super_dq->started_no_cache_store) &&
1060 		!qstate->fwd_stub_no_cache &&
1061 		!super->rpz_applied && !super->rpz_passthru &&
1062 		!super->is_subnet_answer &&
1063 		!dns_cache_store(super->env, &super->qinfo, super->return_msg->rep,
1064 		0, super->prefetch_leeway, 0, NULL, super->query_flags,
1065 		qstate->qstarttime, qstate->is_valrec))
1066 		log_err("out of memory");
1067 }
1068 
1069 /**
1070  * Clear module-specific data from query state. Since we do not allocate memory,
1071  * it's just a matter of setting a pointer to NULL.
1072  *
1073  * \param qstate Query state.
1074  * \param id     This module's instance ID.
1075  */
1076 void
dns64_clear(struct module_qstate * qstate,int id)1077 dns64_clear(struct module_qstate* qstate, int id)
1078 {
1079     qstate->minfo[id] = NULL;
1080 }
1081 
1082 /**
1083  * Returns the amount of global memory that this module uses, not including
1084  * per-query data.
1085  *
1086  * \param env Module environment.
1087  * \param id  This module's instance ID.
1088  */
1089 size_t
dns64_get_mem(struct module_env * env,int id)1090 dns64_get_mem(struct module_env* env, int id)
1091 {
1092     struct dns64_env* dns64_env = (struct dns64_env*)env->modinfo[id];
1093     if (!dns64_env)
1094         return 0;
1095     return sizeof(*dns64_env);
1096 }
1097 
1098 /**
1099  * The dns64 function block.
1100  */
1101 static struct module_func_block dns64_block = {
1102 	"dns64",
1103 	NULL, NULL, &dns64_init, &dns64_deinit, &dns64_operate,
1104 	&dns64_inform_super, &dns64_clear, &dns64_get_mem
1105 };
1106 
1107 /**
1108  * Function for returning the above function block.
1109  */
1110 struct module_func_block *
dns64_get_funcblock(void)1111 dns64_get_funcblock(void)
1112 {
1113 	return &dns64_block;
1114 }
1115