1 /*
2  * Copyright 2011 Daniel Drown
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  *
16  * config.c - configuration settings
17  */
18 
19 #include <string.h>
20 #include <stdlib.h>
21 #include <arpa/inet.h>
22 #include <stdio.h>
23 #include <limits.h>
24 #include <errno.h>
25 #include <unistd.h>
26 
27 #include <cutils/config_utils.h>
28 #include <netutils/ifc.h>
29 
30 #include "config.h"
31 #include "dns64.h"
32 #include "logging.h"
33 #include "getaddr.h"
34 #include "clatd.h"
35 #include "checksum.h"
36 
37 struct clat_config Global_Clatd_Config;
38 
39 /* function: config_item_str
40  * locates the config item and returns the pointer to a string, or NULL on failure.  Caller frees pointer
41  * root       - parsed configuration
42  * item_name  - name of config item to locate
43  * defaultvar - value to use if config item isn't present
44  */
config_item_str(cnode * root,const char * item_name,const char * defaultvar)45 char *config_item_str(cnode *root, const char *item_name, const char *defaultvar) {
46   const char *tmp;
47 
48   if(!(tmp = config_str(root, item_name, defaultvar))) {
49     logmsg(ANDROID_LOG_FATAL,"%s config item needed",item_name);
50     return NULL;
51   }
52   return strdup(tmp);
53 }
54 
55 /* function: config_item_int16_t
56  * locates the config item, parses the integer, and returns the pointer ret_val_ptr, or NULL on failure
57  * root        - parsed configuration
58  * item_name   - name of config item to locate
59  * defaultvar  - value to use if config item isn't present
60  * ret_val_ptr - pointer for return value storage
61  */
config_item_int16_t(cnode * root,const char * item_name,const char * defaultvar,int16_t * ret_val_ptr)62 int16_t *config_item_int16_t(cnode *root, const char *item_name, const char *defaultvar, int16_t *ret_val_ptr) {
63   const char *tmp;
64   char *endptr;
65   long int conf_int;
66 
67   if(!(tmp = config_str(root, item_name, defaultvar))) {
68     logmsg(ANDROID_LOG_FATAL,"%s config item needed",item_name);
69     return NULL;
70   }
71 
72   errno = 0;
73   conf_int = strtol(tmp,&endptr,10);
74   if(errno > 0) {
75     logmsg(ANDROID_LOG_FATAL,"%s config item is not numeric: %s (error=%s)",item_name,tmp,strerror(errno));
76     return NULL;
77   }
78   if(endptr == tmp || *tmp == '\0') {
79     logmsg(ANDROID_LOG_FATAL,"%s config item is not numeric: %s",item_name,tmp);
80     return NULL;
81   }
82   if(*endptr != '\0') {
83     logmsg(ANDROID_LOG_FATAL,"%s config item contains non-numeric characters: %s",item_name,endptr);
84     return NULL;
85   }
86   if(conf_int > INT16_MAX || conf_int < INT16_MIN) {
87     logmsg(ANDROID_LOG_FATAL,"%s config item is too big/small: %d",item_name,conf_int);
88     return NULL;
89   }
90   *ret_val_ptr = conf_int;
91   return ret_val_ptr;
92 }
93 
94 /* function: config_item_ip
95  * locates the config item, parses the ipv4 address, and returns the pointer ret_val_ptr, or NULL on failure
96  * root        - parsed configuration
97  * item_name   - name of config item to locate
98  * defaultvar  - value to use if config item isn't present
99  * ret_val_ptr - pointer for return value storage
100  */
config_item_ip(cnode * root,const char * item_name,const char * defaultvar,struct in_addr * ret_val_ptr)101 struct in_addr *config_item_ip(cnode *root, const char *item_name, const char *defaultvar, struct in_addr *ret_val_ptr) {
102   const char *tmp;
103   int status;
104 
105   if(!(tmp = config_str(root, item_name, defaultvar))) {
106     logmsg(ANDROID_LOG_FATAL,"%s config item needed",item_name);
107     return NULL;
108   }
109 
110   status = inet_pton(AF_INET, tmp, ret_val_ptr);
111   if(status <= 0) {
112     logmsg(ANDROID_LOG_FATAL,"invalid IPv4 address specified for %s: %s", item_name, tmp);
113     return NULL;
114   }
115 
116   return ret_val_ptr;
117 }
118 
119 /* function: config_item_ip6
120  * locates the config item, parses the ipv6 address, and returns the pointer ret_val_ptr, or NULL on failure
121  * root        - parsed configuration
122  * item_name   - name of config item to locate
123  * defaultvar  - value to use if config item isn't present
124  * ret_val_ptr - pointer for return value storage
125  */
config_item_ip6(cnode * root,const char * item_name,const char * defaultvar,struct in6_addr * ret_val_ptr)126 struct in6_addr *config_item_ip6(cnode *root, const char *item_name, const char *defaultvar, struct in6_addr *ret_val_ptr) {
127   const char *tmp;
128   int status;
129 
130   if(!(tmp = config_str(root, item_name, defaultvar))) {
131     logmsg(ANDROID_LOG_FATAL,"%s config item needed",item_name);
132     return NULL;
133   }
134 
135   status = inet_pton(AF_INET6, tmp, ret_val_ptr);
136   if(status <= 0) {
137     logmsg(ANDROID_LOG_FATAL,"invalid IPv6 address specified for %s: %s", item_name, tmp);
138     return NULL;
139   }
140 
141   return ret_val_ptr;
142 }
143 
144 /* function: free_config
145  * frees the memory used by the global config variable
146  */
free_config()147 void free_config() {
148   if(Global_Clatd_Config.plat_from_dns64_hostname) {
149     free(Global_Clatd_Config.plat_from_dns64_hostname);
150     Global_Clatd_Config.plat_from_dns64_hostname = NULL;
151   }
152 }
153 
154 /* function: ipv6_prefix_equal
155  * compares the prefixes two ipv6 addresses. assumes the prefix lengths are both /64.
156  * a1 - first address
157  * a2 - second address
158  * returns: 0 if the subnets are different, 1 if they are the same.
159  */
ipv6_prefix_equal(struct in6_addr * a1,struct in6_addr * a2)160 int ipv6_prefix_equal(struct in6_addr *a1, struct in6_addr *a2) {
161     return !memcmp(a1, a2, 8);
162 }
163 
164 /* function: dns64_detection
165  * does dns lookups to set the plat subnet or exits on failure, waits forever for a dns response with a query backoff timer
166  * net_id - (optional) netId to use, NETID_UNSET indicates use of default network
167  */
dns64_detection(unsigned net_id)168 void dns64_detection(unsigned net_id) {
169   int backoff_sleep, status;
170   struct in6_addr tmp_ptr;
171 
172   backoff_sleep = 1;
173 
174   while(1) {
175     status = plat_prefix(Global_Clatd_Config.plat_from_dns64_hostname,net_id,&tmp_ptr);
176     if(status > 0) {
177       memcpy(&Global_Clatd_Config.plat_subnet, &tmp_ptr, sizeof(struct in6_addr));
178       return;
179     }
180     logmsg(ANDROID_LOG_WARN, "dns64_detection -- error, sleeping for %d seconds", backoff_sleep);
181     sleep(backoff_sleep);
182     backoff_sleep *= 2;
183     if(backoff_sleep >= 120) {
184       backoff_sleep = 120;
185     }
186   }
187 }
188 
189 /* function: gen_random_iid
190  * picks a random interface ID that is checksum neutral with the IPv4 address and the NAT64 prefix
191  * myaddr            - IPv6 address to write to
192  * ipv4_local_subnet - clat IPv4 address
193  * plat_subnet       - NAT64 prefix
194  */
gen_random_iid(struct in6_addr * myaddr,struct in_addr * ipv4_local_subnet,struct in6_addr * plat_subnet)195 void gen_random_iid(struct in6_addr *myaddr, struct in_addr *ipv4_local_subnet,
196                     struct in6_addr *plat_subnet) {
197   // Fill last 8 bytes of IPv6 address with random bits.
198   arc4random_buf(&myaddr->s6_addr[8], 8);
199 
200   // Make the IID checksum-neutral. That is, make it so that:
201   //   checksum(Local IPv4 | Remote IPv4) = checksum(Local IPv6 | Remote IPv6)
202   // in other words (because remote IPv6 = NAT64 prefix | Remote IPv4):
203   //   checksum(Local IPv4) = checksum(Local IPv6 | NAT64 prefix)
204   // Do this by adjusting the two bytes in the middle of the IID.
205 
206   uint16_t middlebytes = (myaddr->s6_addr[11] << 8) + myaddr->s6_addr[12];
207 
208   uint32_t c1 = ip_checksum_add(0, ipv4_local_subnet, sizeof(*ipv4_local_subnet));
209   uint32_t c2 = ip_checksum_add(0, plat_subnet, sizeof(*plat_subnet)) +
210                 ip_checksum_add(0, myaddr, sizeof(*myaddr));
211 
212   uint16_t delta = ip_checksum_adjust(middlebytes, c1, c2);
213   myaddr->s6_addr[11] = delta >> 8;
214   myaddr->s6_addr[12] = delta & 0xff;
215 }
216 
217 // Factored out to a separate function for testability.
connect_is_ipv4_address_free(in_addr_t addr)218 int connect_is_ipv4_address_free(in_addr_t addr) {
219   int s = socket(AF_INET, SOCK_DGRAM, 0);
220   if (s == -1) {
221     return 0;
222   }
223 
224   // Attempt to connect to the address. If the connection succeeds and getsockname returns the same
225   // the address then the address is already assigned to the system and we can't use it.
226   struct sockaddr_in sin = { .sin_family = AF_INET, .sin_addr = { addr }, .sin_port = 53 };
227   socklen_t len = sizeof(sin);
228   int inuse = connect(s, (struct sockaddr *) &sin, sizeof(sin)) == 0 &&
229               getsockname(s, (struct sockaddr *) &sin, &len) == 0 &&
230               (size_t) len >= sizeof(sin) &&
231               sin.sin_addr.s_addr == addr;
232 
233   close(s);
234   return !inuse;
235 }
236 
237 addr_free_func config_is_ipv4_address_free = connect_is_ipv4_address_free;
238 
239 /* function: config_select_ipv4_address
240  * picks a free IPv4 address, starting from ip and trying all addresses in the prefix in order
241  * ip        - the IP address from the configuration file
242  * prefixlen - the length of the prefix from which addresses may be selected.
243  * returns: the IPv4 address, or INADDR_NONE if no addresses were available
244  */
config_select_ipv4_address(const struct in_addr * ip,int16_t prefixlen)245 in_addr_t config_select_ipv4_address(const struct in_addr *ip, int16_t prefixlen) {
246   in_addr_t chosen = INADDR_NONE;
247 
248   // Don't accept prefixes that are too large because we scan addresses one by one.
249   if (prefixlen < 16 || prefixlen > 32) {
250       return chosen;
251   }
252 
253   // All these are in host byte order.
254   in_addr_t mask = 0xffffffff >> (32 - prefixlen) << (32 - prefixlen);
255   in_addr_t ipv4 = ntohl(ip->s_addr);
256   in_addr_t first_ipv4 = ipv4;
257   in_addr_t prefix = ipv4 & mask;
258 
259   // Pick the first IPv4 address in the pool, wrapping around if necessary.
260   // So, for example, 192.0.0.4 -> 192.0.0.5 -> 192.0.0.6 -> 192.0.0.7 -> 192.0.0.0.
261   do {
262      if (config_is_ipv4_address_free(htonl(ipv4))) {
263        chosen = htonl(ipv4);
264        break;
265      }
266      ipv4 = prefix | ((ipv4 + 1) & ~mask);
267   } while (ipv4 != first_ipv4);
268 
269   return chosen;
270 }
271 
272 /* function: config_generate_local_ipv6_subnet
273  * generates the local ipv6 subnet when given the interface ip
274  * requires config.ipv6_host_id
275  * interface_ip - in: interface ip, out: local ipv6 host address
276  */
config_generate_local_ipv6_subnet(struct in6_addr * interface_ip)277 void config_generate_local_ipv6_subnet(struct in6_addr *interface_ip) {
278   int i;
279 
280   if (Global_Clatd_Config.use_dynamic_iid) {
281     /* Generate a random interface ID. */
282     gen_random_iid(interface_ip,
283                    &Global_Clatd_Config.ipv4_local_subnet,
284                    &Global_Clatd_Config.plat_subnet);
285   } else {
286     /* Use the specified interface ID. */
287     for(i = 2; i < 4; i++) {
288       interface_ip->s6_addr32[i] = Global_Clatd_Config.ipv6_host_id.s6_addr32[i];
289     }
290   }
291 }
292 
293 /* function: read_config
294  * reads the config file and parses it into the global variable Global_Clatd_Config. returns 0 on failure, 1 on success
295  * file             - filename to parse
296  * uplink_interface - interface to use to reach the internet and supplier of address space
297  * plat_prefix      - (optional) plat prefix to use, otherwise follow config file
298  * net_id           - (optional) netId to use, NETID_UNSET indicates use of default network
299  */
read_config(const char * file,const char * uplink_interface,const char * plat_prefix,unsigned net_id)300 int read_config(const char *file, const char *uplink_interface, const char *plat_prefix,
301         unsigned net_id) {
302   cnode *root = config_node("", "");
303   void *tmp_ptr = NULL;
304   unsigned flags;
305 
306   if(!root) {
307     logmsg(ANDROID_LOG_FATAL,"out of memory");
308     return 0;
309   }
310 
311   memset(&Global_Clatd_Config, '\0', sizeof(Global_Clatd_Config));
312 
313   config_load_file(root, file);
314   if(root->first_child == NULL) {
315     logmsg(ANDROID_LOG_FATAL,"Could not read config file %s", file);
316     goto failed;
317   }
318 
319   Global_Clatd_Config.default_pdp_interface = strdup(uplink_interface);
320   if (!Global_Clatd_Config.default_pdp_interface)
321     goto failed;
322 
323   if(!config_item_int16_t(root, "mtu", "-1", &Global_Clatd_Config.mtu))
324     goto failed;
325 
326   if(!config_item_int16_t(root, "ipv4mtu", "-1", &Global_Clatd_Config.ipv4mtu))
327     goto failed;
328 
329   if(!config_item_ip(root, "ipv4_local_subnet", DEFAULT_IPV4_LOCAL_SUBNET,
330                      &Global_Clatd_Config.ipv4_local_subnet))
331     goto failed;
332 
333   if(!config_item_int16_t(root, "ipv4_local_prefixlen", DEFAULT_IPV4_LOCAL_PREFIXLEN,
334                           &Global_Clatd_Config.ipv4_local_prefixlen))
335     goto failed;
336 
337   if(plat_prefix) { // plat subnet is coming from the command line
338     if(inet_pton(AF_INET6, plat_prefix, &Global_Clatd_Config.plat_subnet) <= 0) {
339       logmsg(ANDROID_LOG_FATAL,"invalid IPv6 address specified for plat prefix: %s", plat_prefix);
340       goto failed;
341     }
342   } else {
343     tmp_ptr = (void *)config_item_str(root, "plat_from_dns64", "yes");
344     if(!tmp_ptr || strcmp(tmp_ptr, "no") == 0) {
345       free(tmp_ptr);
346 
347       if(!config_item_ip6(root, "plat_subnet", NULL, &Global_Clatd_Config.plat_subnet)) {
348         logmsg(ANDROID_LOG_FATAL, "plat_from_dns64 disabled, but no plat_subnet specified");
349         goto failed;
350       }
351     } else {
352       free(tmp_ptr);
353 
354       if(!(Global_Clatd_Config.plat_from_dns64_hostname = config_item_str(root, "plat_from_dns64_hostname", DEFAULT_DNS64_DETECTION_HOSTNAME)))
355         goto failed;
356       dns64_detection(net_id);
357     }
358   }
359 
360   if (!config_item_ip6(root, "ipv6_host_id", "::", &Global_Clatd_Config.ipv6_host_id))
361     goto failed;
362 
363   /* In order to prevent multiple devices attempting to use the same clat address, never use a
364      statically-configured interface ID on a broadcast interface such as wifi. */
365   if (!IN6_IS_ADDR_UNSPECIFIED(&Global_Clatd_Config.ipv6_host_id)) {
366     ifc_init();
367     ifc_get_info(Global_Clatd_Config.default_pdp_interface, NULL, NULL, &flags);
368     ifc_close();
369     Global_Clatd_Config.use_dynamic_iid = (flags & IFF_BROADCAST) != 0;
370   } else {
371     Global_Clatd_Config.use_dynamic_iid = 1;
372   }
373 
374   return 1;
375 
376 failed:
377   free(root);
378   free_config();
379   return 0;
380 }
381 
382 /* function; dump_config
383  * prints the current config
384  */
dump_config()385 void dump_config() {
386   char charbuffer[INET6_ADDRSTRLEN];
387 
388   logmsg(ANDROID_LOG_DEBUG,"mtu = %d",Global_Clatd_Config.mtu);
389   logmsg(ANDROID_LOG_DEBUG,"ipv4mtu = %d",Global_Clatd_Config.ipv4mtu);
390   logmsg(ANDROID_LOG_DEBUG,"ipv6_local_subnet = %s",inet_ntop(AF_INET6, &Global_Clatd_Config.ipv6_local_subnet, charbuffer, sizeof(charbuffer)));
391   logmsg(ANDROID_LOG_DEBUG,"ipv4_local_subnet = %s",inet_ntop(AF_INET, &Global_Clatd_Config.ipv4_local_subnet, charbuffer, sizeof(charbuffer)));
392   logmsg(ANDROID_LOG_DEBUG,"ipv4_local_prefixlen = %d", Global_Clatd_Config.ipv4_local_prefixlen);
393   logmsg(ANDROID_LOG_DEBUG,"plat_subnet = %s",inet_ntop(AF_INET6, &Global_Clatd_Config.plat_subnet, charbuffer, sizeof(charbuffer)));
394   logmsg(ANDROID_LOG_DEBUG,"default_pdp_interface = %s",Global_Clatd_Config.default_pdp_interface);
395 }
396