blob: a5cd0a9c1a4164fbba03a068b468b31336bfe3b4 [file] [log] [blame]
xf.lif1aed282024-02-06 00:31:51 -08001/*
2 * Copyright 2012 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 * clatd.c - tun interface setup and main event loop
17 */
18#include <poll.h>
19#include <signal.h>
20#include <time.h>
21#include <stdio.h>
22#include <sys/types.h>
23#include <sys/ioctl.h>
24#include <sys/prctl.h>
25#include <sys/stat.h>
26#include <string.h>
27#include <errno.h>
28#include <stdlib.h>
29#include <unistd.h>
30#include <arpa/inet.h>
31#include <fcntl.h>
32
33#include <linux/capability.h>
34#include <sys/uio.h>
35#include <linux/filter.h>
36#include <linux/if.h>
37#include <linux/if_tun.h>
38#include <linux/if_ether.h>
39#include <linux/if_packet.h>
40//#include <net/if.h>
41
42#include <grp.h>
43
44#include "translate.h"
45#include "clatd.h"
46#include "config.h"
47#include "logging.h"
48//#include "resolv_netid.h"
49#include "setif.h"
50#include "mtu.h"
51#include "getaddr.h"
52#include "dump.h"
53#include "tun.h"
54#include "ring.h"
55#include <asm/unistd.h>
56#include "my_header.h"
57
58#define DEVICEPREFIX "v4-"
59
60/* 40 bytes IPv6 header - 20 bytes IPv4 header + 8 bytes fragment header */
61#define MTU_DELTA 28
62
63volatile sig_atomic_t running = 1;
64
65/* function: stop_loop
66 * signal handler: stop the event loop
67 */
68void stop_loop() {
69 running = 0;
70}
71
72/* function: configure_packet_socket
73 * Binds the packet socket and attaches the receive filter to it.
74 * sock - the socket to configure
75 */
76int configure_packet_socket(int sock) {
77 struct sockaddr_ll sll = {
78 .sll_family = AF_PACKET,
79 .sll_protocol = htons(ETH_P_IPV6),
80 .sll_ifindex = if_nametoindex(Global_Clatd_Config.default_pdp_interface),
81 .sll_pkttype = PACKET_OTHERHOST, // The 464xlat IPv6 address is not assigned to the kernel.
82 };
83 if (bind(sock, (struct sockaddr *) &sll, sizeof(sll))) {
84 logmsg(ANDROID_LOG_FATAL, "binding packet socket: %s", strerror(errno));
85 return 0;
86 }
87
88 uint32_t *ipv6 = Global_Clatd_Config.ipv6_local_subnet.s6_addr32;
89 struct sock_filter filter_code[] = {
90 // Load the first four bytes of the IPv6 destination address (starts 24 bytes in).
91 // Compare it against the first four bytes of our IPv6 address, in host byte order (BPF loads
92 // are always in host byte order). If it matches, continue with next instruction (JMP 0). If it
93 // doesn't match, jump ahead to statement that returns 0 (ignore packet). Repeat for the other
94 // three words of the IPv6 address, and if they all match, return PACKETLEN (accept packet).
95 BPF_STMT(BPF_LD | BPF_W | BPF_ABS, 24),
96 BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, htonl(ipv6[0]), 0, 7),
97 BPF_STMT(BPF_LD | BPF_W | BPF_ABS, 28),
98 BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, htonl(ipv6[1]), 0, 5),
99 BPF_STMT(BPF_LD | BPF_W | BPF_ABS, 32),
100 BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, htonl(ipv6[2]), 0, 3),
101 BPF_STMT(BPF_LD | BPF_W | BPF_ABS, 36),
102 BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, htonl(ipv6[3]), 0, 1),
103 BPF_STMT(BPF_RET | BPF_K, PACKETLEN),
104 BPF_STMT(BPF_RET | BPF_K, 0)
105 };
106 struct sock_fprog filter = {
107 sizeof(filter_code) / sizeof(filter_code[0]),
108 filter_code
109 };
110
111 if (setsockopt(sock, SOL_SOCKET, SO_ATTACH_FILTER, &filter, sizeof(filter))) {
112 logmsg(ANDROID_LOG_FATAL, "attach packet filter failed: %s", strerror(errno));
113 return 0;
114 }
115
116 return 1;
117}
118
119/* function: configure_tun_ip
120 * configures the ipv4 and ipv6 addresses on the tunnel interface
121 * tunnel - tun device data
122 */
123void configure_tun_ip(const struct tun_data *tunnel) {
124 int status;
125
126 // Pick an IPv4 address to use by finding a free address in the configured prefix. Technically,
127 // there is a race here - if another clatd calls config_select_ipv4_address after we do, but
128 // before we call add_address, it can end up having the same IP address as we do. But the time
129 // window in which this can happen is extremely small, and even if we end up with a duplicate
130 // address, the only damage is that IPv4 TCP connections won't be reset until both interfaces go
131 // down.
132 in_addr_t localaddr = config_select_ipv4_address(&Global_Clatd_Config.ipv4_local_subnet,
133 Global_Clatd_Config.ipv4_local_prefixlen);
134 if (localaddr == INADDR_NONE) {
135 logmsg(ANDROID_LOG_FATAL,"No free IPv4 address in %s/%d",
136 inet_ntoa(Global_Clatd_Config.ipv4_local_subnet),
137 Global_Clatd_Config.ipv4_local_prefixlen);
138 exit(1);
139 }
140 Global_Clatd_Config.ipv4_local_subnet.s_addr = localaddr;
141
142 // Configure the interface before bringing it up. As soon as we bring the interface up, the
143 // framework will be notified and will assume the interface's configuration has been finalized.
144 status = add_address(tunnel->device4, AF_INET, &Global_Clatd_Config.ipv4_local_subnet,
145 32, &Global_Clatd_Config.ipv4_local_subnet);
146 if(status < 0) {
147 logmsg(ANDROID_LOG_FATAL,"configure_tun_ip/if_address(4) failed: %s",strerror(-status));
148 exit(1);
149 }
150
151 char addrstr[INET_ADDRSTRLEN];
152 inet_ntop(AF_INET, &Global_Clatd_Config.ipv4_local_subnet, addrstr, sizeof(addrstr));
153 logmsg(ANDROID_LOG_INFO, "Using IPv4 address %s on %s", addrstr, tunnel->device4);
154
155 if((status = if_up(tunnel->device4, Global_Clatd_Config.ipv4mtu)) < 0) {
156 logmsg(ANDROID_LOG_FATAL,"configure_tun_ip/if_up(4) failed: %s",strerror(-status));
157 exit(1);
158 }
159}
160
161/* function: drop_root
162 * drops root privs but keeps the needed capability
163 */
164void drop_root() {
165 gid_t groups[] = { AID_INET, AID_VPN };
166 if(setgroups(sizeof(groups)/sizeof(groups[0]), groups) < 0) {
167 logmsg(ANDROID_LOG_FATAL,"drop_root/setgroups failed: %s",strerror(errno));
168 exit(1);
169 }
170
171 prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0);
172
173 if(setgid(AID_CLAT) < 0) {
174 logmsg(ANDROID_LOG_FATAL,"drop_root/setgid failed: %s",strerror(errno));
175 exit(1);
176 }
177 if(setuid(AID_CLAT) < 0) {
178 logmsg(ANDROID_LOG_FATAL,"drop_root/setuid failed: %s",strerror(errno));
179 exit(1);
180 }
181
182 struct __user_cap_header_struct header;
183 struct __user_cap_data_struct cap;
184 memset(&header, 0, sizeof(header));
185 memset(&cap, 0, sizeof(cap));
186
187 header.version = _LINUX_CAPABILITY_VERSION;
188 header.pid = 0; // 0 = change myself
189 cap.effective = cap.permitted = (1 << CAP_NET_ADMIN);
190
191 if(capset(&header, &cap) < 0) {
192 logmsg(ANDROID_LOG_FATAL,"drop_root/capset failed: %s",strerror(errno));
193 exit(1);
194 }
195}
196
197/* function: open_sockets
198 * opens a packet socket to receive IPv6 packets and a raw socket to send them
199 * tunnel - tun device data
200 * mark - the socket mark to use for the sending raw socket
201 */
202void open_sockets(struct tun_data *tunnel, uint32_t mark) {
203 int rawsock = socket(AF_INET6, SOCK_RAW | SOCK_NONBLOCK, IPPROTO_RAW);
204 if (rawsock < 0) {
205 logmsg(ANDROID_LOG_FATAL, "raw socket failed: %s", strerror(errno));
206 exit(1);
207 }
208
209 int off = 0;
210 if (setsockopt(rawsock, SOL_IPV6, IPV6_CHECKSUM, &off, sizeof(off)) < 0) {
211 logmsg(ANDROID_LOG_WARN, "could not disable checksum on raw socket: %s", strerror(errno));
212 }
213 if (mark != MARK_UNSET && setsockopt(rawsock, SOL_SOCKET, SO_MARK, &mark, sizeof(mark)) < 0) {
214 logmsg(ANDROID_LOG_ERROR, "could not set mark on raw socket: %s", strerror(errno));
215 }
216
217 tunnel->write_fd6 = rawsock;
218
219 tunnel->read_fd6 = ring_create(tunnel);
220 if (tunnel->read_fd6 < 0) {
221 exit(1);
222 }
223}
224
225/* function: update_clat_ipv6_address
226 * picks the clat IPv6 address and configures packet translation to use it.
227 * tunnel - tun device data
228 * interface - uplink interface name
229 * returns: 1 on success, 0 on failure
230 */
231int update_clat_ipv6_address(const struct tun_data *tunnel, const char *interface) {
232 union anyip *interface_ip;
233 char addrstr[INET6_ADDRSTRLEN];
234
235 // TODO: check that the prefix length is /64.
236 interface_ip = getinterface_ip(interface, AF_INET6);
237 if (!interface_ip) {
238 logmsg(ANDROID_LOG_ERROR, "Unable to find an IPv6 address on interface %s", interface);
239 return 0;
240 }
241
242 // If our prefix hasn't changed, do nothing. (If this is the first time we configure an IPv6
243 // address, Global_Clatd_Config.ipv6_local_subnet will be ::, which won't match our new prefix.)
244 if (ipv6_prefix_equal(&interface_ip->ip6, &Global_Clatd_Config.ipv6_local_subnet)) {
245 free(interface_ip);
246 return 1;
247 }
248
249 // Generate an interface ID.
250 config_generate_local_ipv6_subnet(&interface_ip->ip6);
251 inet_ntop(AF_INET6, &interface_ip->ip6, addrstr, sizeof(addrstr));
252
253 if (IN6_IS_ADDR_UNSPECIFIED(&Global_Clatd_Config.ipv6_local_subnet)) {
254 // Startup.
255 logmsg(ANDROID_LOG_INFO, "Using IPv6 address %s on %s", addrstr, interface);
256 } else {
257 // Prefix change.
258 char from_addr[INET6_ADDRSTRLEN];
259 inet_ntop(AF_INET6, &Global_Clatd_Config.ipv6_local_subnet, from_addr, sizeof(from_addr));
260 logmsg(ANDROID_LOG_INFO, "clat IPv6 address changed from %s to %s", from_addr, addrstr);
261 del_anycast_address(tunnel->write_fd6, &Global_Clatd_Config.ipv6_local_subnet);
262 }
263
264 // Start translating packets to the new prefix.
265 Global_Clatd_Config.ipv6_local_subnet = interface_ip->ip6;
266 add_anycast_address(tunnel->write_fd6, &Global_Clatd_Config.ipv6_local_subnet, interface);
267 free(interface_ip);
268
269 // Update our packet socket filter to reflect the new 464xlat IP address.
270 if (!configure_packet_socket(tunnel->read_fd6)) {
271 // Things aren't going to work. Bail out and hope we have better luck next time.
272 // We don't log an error here because configure_packet_socket has already done so.
273 exit(1);
274 }
275 unsigned char info[40] = {0};
276 unsigned char *pinfo = info;
277 memcpy(pinfo, &Global_Clatd_Config.plat_subnet, sizeof(struct in6_addr));
278 pinfo = pinfo + sizeof(struct in6_addr);
279 memcpy(pinfo, &Global_Clatd_Config.ipv6_local_subnet, sizeof(struct in6_addr));
280 pinfo = pinfo + sizeof(struct in6_addr);
281 memcpy(pinfo, &Global_Clatd_Config.ipv4_local_subnet, sizeof(struct in_addr));
282 syscall(__NR_set_xlat, (char *)info, Global_Clatd_Config.default_pdp_interface);
283 return 1;
284}
285
286/* function: configure_interface
287 * reads the configuration and applies it to the interface
288 * uplink_interface - network interface to use to reach the ipv6 internet
289 * plat_prefix - PLAT prefix to use
290 * tunnel - tun device data
291 * net_id - NetID to use, NETID_UNSET indicates use of default network
292 */
293void configure_interface(const char *uplink_interface, const char *plat_prefix, struct tun_data *tunnel, unsigned net_id) {
294 int error;
295
296 if(!read_config("/etc/clatd.conf", uplink_interface, plat_prefix, net_id)) {
297 logmsg(ANDROID_LOG_FATAL,"read_config failed");
298 exit(1);
299 }
300
301 if(Global_Clatd_Config.mtu > MAXMTU) {
302 logmsg(ANDROID_LOG_WARN,"Max MTU is %d, requested %d", MAXMTU, Global_Clatd_Config.mtu);
303 Global_Clatd_Config.mtu = MAXMTU;
304 }
305 if(Global_Clatd_Config.mtu <= 0) {
306 Global_Clatd_Config.mtu = getifmtu(Global_Clatd_Config.default_pdp_interface);
307 logmsg(ANDROID_LOG_WARN,"ifmtu=%d",Global_Clatd_Config.mtu);
308 }
309 if(Global_Clatd_Config.mtu < 1280) {
310 logmsg(ANDROID_LOG_WARN,"mtu too small = %d", Global_Clatd_Config.mtu);
311 Global_Clatd_Config.mtu = 1280;
312 }
313
314 if(Global_Clatd_Config.ipv4mtu <= 0 ||
315 Global_Clatd_Config.ipv4mtu > Global_Clatd_Config.mtu - MTU_DELTA) {
316 Global_Clatd_Config.ipv4mtu = Global_Clatd_Config.mtu - MTU_DELTA;
317 logmsg(ANDROID_LOG_WARN,"ipv4mtu now set to = %d",Global_Clatd_Config.ipv4mtu);
318 }
319
320 error = tun_alloc(tunnel->device4, tunnel->fd4);
321 if(error < 0) {
322 logmsg(ANDROID_LOG_FATAL,"tun_alloc/4 failed: %s",strerror(errno));
323 exit(1);
324 }
325
326 error = set_nonblocking(tunnel->fd4);
327 if (error < 0) {
328 logmsg(ANDROID_LOG_FATAL, "set_nonblocking failed: %s", strerror(errno));
329 exit(1);
330 }
331
332 configure_tun_ip(tunnel);
333}
334
335/* function: read_packet
336 * reads a packet from the tunnel fd and translates it
337 * read_fd - file descriptor to read original packet from
338 * write_fd - file descriptor to write translated packet to
339 * to_ipv6 - whether the packet is to be translated to ipv6 or ipv4
340 */
341void read_packet(int read_fd, int write_fd, int to_ipv6) {
342 ssize_t readlen;
343 uint8_t buf[PACKETLEN], *packet;
344
345 readlen = read(read_fd, buf, PACKETLEN);
346
347 if(readlen < 0) {
348 if (errno != EAGAIN) {
349 logmsg(ANDROID_LOG_WARN,"read_packet/read error: %s", strerror(errno));
350 }
351 return;
352 } else if(readlen == 0) {
353 logmsg(ANDROID_LOG_WARN,"read_packet/tun interface removed");
354 running = 0;
355 return;
356 }
357
358 struct tun_pi *tun_header = (struct tun_pi *) buf;
359 if (readlen < (ssize_t) sizeof(*tun_header)) {
360 logmsg(ANDROID_LOG_WARN,"read_packet/short read: got %ld bytes", readlen);
361 return;
362 }
363
364 uint16_t proto = ntohs(tun_header->proto);
365 if (proto != ETH_P_IP) {
366 logmsg(ANDROID_LOG_WARN, "%s: unknown packet type = 0x%x", __func__, proto);
367 return;
368 }
369
370 if(tun_header->flags != 0) {
371 logmsg(ANDROID_LOG_WARN, "%s: unexpected flags = %d", __func__, tun_header->flags);
372 }
373
374 packet = (uint8_t *) (tun_header + 1);
375 readlen -= sizeof(*tun_header);
376 translate_packet(write_fd, to_ipv6, packet, readlen);
377}
378
379/* function: event_loop
380 * reads packets from the tun network interface and passes them down the stack
381 * tunnel - tun device data
382 */
383void event_loop(struct tun_data *tunnel) {
384 time_t last_interface_poll;
385 struct pollfd wait_fd[] = {
386 { tunnel->read_fd6, POLLIN, 0 },
387 { tunnel->fd4, POLLIN, 0 },
388 };
389
390 // start the poll timer
391 last_interface_poll = time(NULL);
392
393 while(running) {
394 if (poll(wait_fd, ARRAY_SIZE(wait_fd),
395 NO_TRAFFIC_INTERFACE_POLL_FREQUENCY * 1000) == -1) {
396 if (errno != EINTR) {
397 logmsg(ANDROID_LOG_WARN,"event_loop/poll returned an error: %s", strerror(errno));
398 }
399 } else {
400 if (wait_fd[0].revents & POLLIN) {
401 ring_read(&tunnel->ring, tunnel->fd4, 0 /* to_ipv6 */);
402 }
403 // If any other bit is set, assume it's due to an error (i.e. POLLERR).
404 if (wait_fd[0].revents & ~POLLIN) {
405 // ring_read doesn't clear the error indication on the socket.
xf.li7ccf8372024-03-07 00:08:02 -0800406 if(recv(tunnel->read_fd6, NULL, 0, MSG_PEEK) == -1)
407 {
408 logmsg_dbg(ANDROID_LOG_ERROR,"recv fd6 failed");
409 }
xf.lif1aed282024-02-06 00:31:51 -0800410 logmsg(ANDROID_LOG_WARN, "event_loop: clearing error on read_fd6: %s",
411 strerror(errno));
412 }
413
414 // Call read_packet if the socket has data to be read, but also if an
415 // error is waiting. If we don't call read() after getting POLLERR, a
416 // subsequent poll() will return immediately with POLLERR again,
417 // causing this code to spin in a loop. Calling read() will clear the
418 // socket error flag instead.
419 if (wait_fd[1].revents) {
420 read_packet(tunnel->fd4, tunnel->write_fd6, 1 /* to_ipv6 */);
421 }
422 }
423
424 time_t now = time(NULL);
425 if(last_interface_poll < (now - INTERFACE_POLL_FREQUENCY)) {
426 update_clat_ipv6_address(tunnel, Global_Clatd_Config.default_pdp_interface);
427 last_interface_poll = now;
428 }
429 }
430}
431
432/* function: print_help
433 * in case the user is running this on the command line
434 */
435void print_help() {
436 printf("clat arguments:\n");
437 printf("-i [uplink interface]\n");
438 printf("-p [plat prefix]\n");
439 printf("-n [NetId]\n");
440 printf("-m [socket mark]\n");
441}
442
443/* function: parse_unsigned
444 * parses a string as a decimal/hex/octal unsigned integer
445 * str - the string to parse
446 * out - the unsigned integer to write to, gets clobbered on failure
447 */
448int parse_unsigned(const char *str, unsigned *out) {
449 char *end_ptr;
450 *out = strtoul(str, &end_ptr, 0);
451 return *str && !*end_ptr;
452}
453
454/* function: main
455 * allocate and setup the tun device, then run the event loop
456 */
457int main(int argc, char **argv) {
458 struct tun_data tunnel;
459 int opt;
460 char *uplink_interface = NULL, *plat_prefix = NULL, *net_id_str = NULL, *mark_str = NULL;
461 unsigned net_id = NETID_UNSET;
462 uint32_t mark = MARK_UNSET;
463 unsigned len;
464
465 while((opt = getopt(argc, argv, "i:p:n:m:h")) != -1) {
466 switch(opt) {
467 case 'i':
468 uplink_interface = optarg;
469 break;
470 case 'p':
471 plat_prefix = optarg;
472 break;
473 case 'n':
474 net_id_str = optarg;
475 break;
476 case 'm':
477 mark_str = optarg;
478 break;
479 case 'h':
480 print_help();
481 exit(0);
482 default:
483 logmsg(ANDROID_LOG_FATAL, "Unknown option -%c. Exiting.", (char) optopt);
484 exit(1);
485 }
486 }
487
488 if(uplink_interface == NULL) {
489 logmsg(ANDROID_LOG_FATAL, "clatd called without an interface");
490 exit(1);
491 }
492
493 if (net_id_str != NULL && !parse_unsigned(net_id_str, &net_id)) {
494 logmsg(ANDROID_LOG_FATAL, "invalid NetID %s", net_id_str);
495 exit(1);
496 }
497
498 if (mark_str != NULL && !parse_unsigned(mark_str, &mark)) {
499 logmsg(ANDROID_LOG_FATAL, "invalid mark %s", mark_str);
500 exit(1);
501 }
502
503 len = snprintf(tunnel.device4, sizeof(tunnel.device4), "%s%s", DEVICEPREFIX, uplink_interface);
504 if (len >= sizeof(tunnel.device4)) {
505 logmsg(ANDROID_LOG_FATAL, "interface name too long '%s'", tunnel.device4);
506 exit(1);
507 }
508
509 logmsg(ANDROID_LOG_INFO, "Starting clat version %s on %s netid=%s mark=%s",
510 CLATD_VERSION, uplink_interface,
511 net_id_str ? net_id_str : "(none)",
512 mark_str ? mark_str : "(none)");
513
514 // open our raw sockets before dropping privs
515 open_sockets(&tunnel, mark);
516
517 // run under a regular user
518 //drop_root();
519
520 // we can create tun devices as non-root because we're in the VPN group.
521 tunnel.fd4 = tun_open();
522 if(tunnel.fd4 < 0) {
523 logmsg(ANDROID_LOG_FATAL, "tun_open4 failed: %s", strerror(errno));
524 exit(1);
525 }
526
527 // When run from netd, the environment variable ANDROID_DNS_MODE is set to
528 // "local", but that only works for the netd process itself. Removing the
529 // following line causes XLAT failure in permissive mode.
530 //unsetenv("ANDROID_DNS_MODE");
531
532 configure_interface(uplink_interface, plat_prefix, &tunnel, net_id);
533
534 update_clat_ipv6_address(&tunnel, uplink_interface);
535
536 // Loop until someone sends us a signal or brings down the tun interface.
537 if(signal(SIGTERM, stop_loop) == SIG_ERR) {
538 logmsg(ANDROID_LOG_FATAL, "sigterm handler failed: %s", strerror(errno));
539 exit(1);
540 }
541
542 event_loop(&tunnel);
543
544 logmsg(ANDROID_LOG_INFO,"Shutting down clat on %s", uplink_interface);
545 del_anycast_address(tunnel.write_fd6, &Global_Clatd_Config.ipv6_local_subnet);
546
547 return 0;
548}