• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright (C) 2022 The Android Open Source Project
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //      http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #define LOG_TAG "clatutils"
16 
17 #include "libclat/clatutils.h"
18 
19 #include <errno.h>
20 #include <linux/filter.h>
21 #include <linux/if_packet.h>
22 #include <linux/if_tun.h>
23 #include <log/log.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <unistd.h>
27 
28 extern "C" {
29 #include "checksum.h"
30 }
31 
32 // Sync from external/android-clat/clatd.h
33 #define MAXMTU 65536
34 #define PACKETLEN (MAXMTU + sizeof(struct tun_pi))
35 
36 // Sync from system/netd/include/netid_client.h.
37 #define MARK_UNSET 0u
38 
39 namespace android {
40 namespace net {
41 namespace clat {
42 
isIpv4AddressFree(in_addr_t addr)43 bool isIpv4AddressFree(in_addr_t addr) {
44     int s = socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0);
45     if (s == -1) {
46         return 0;
47     }
48 
49     // Attempt to connect to the address. If the connection succeeds and getsockname returns the
50     // same then the address is already assigned to the system and we can't use it.
51     struct sockaddr_in sin = {
52             .sin_family = AF_INET,
53             .sin_port = htons(53),
54             .sin_addr = {addr},
55     };
56     socklen_t len = sizeof(sin);
57     bool inuse = connect(s, (struct sockaddr*)&sin, sizeof(sin)) == 0 &&
58                  getsockname(s, (struct sockaddr*)&sin, &len) == 0 && (size_t)len >= sizeof(sin) &&
59                  sin.sin_addr.s_addr == addr;
60 
61     close(s);
62     return !inuse;
63 }
64 
65 // Picks a free IPv4 address, starting from ip and trying all addresses in the prefix in order.
66 //   ip        - the IP address from the configuration file
67 //   prefixlen - the length of the prefix from which addresses may be selected.
68 //   returns: the IPv4 address, or INADDR_NONE if no addresses were available
selectIpv4Address(const in_addr ip,int16_t prefixlen)69 in_addr_t selectIpv4Address(const in_addr ip, int16_t prefixlen) {
70     return selectIpv4AddressInternal(ip, prefixlen, isIpv4AddressFree);
71 }
72 
73 // Only allow testing to use this function directly. Otherwise call selectIpv4Address(ip, pfxlen)
74 // which has applied valid isIpv4AddressFree function pointer.
selectIpv4AddressInternal(const in_addr ip,int16_t prefixlen,isIpv4AddrFreeFn isIpv4AddressFreeFunc)75 in_addr_t selectIpv4AddressInternal(const in_addr ip, int16_t prefixlen,
76                                     isIpv4AddrFreeFn isIpv4AddressFreeFunc) {
77     // Impossible! Only test allows to apply fn.
78     if (isIpv4AddressFreeFunc == nullptr) {
79         return INADDR_NONE;
80     }
81 
82     // Don't accept prefixes that are too large because we scan addresses one by one.
83     if (prefixlen < 16 || prefixlen > 32) {
84         return INADDR_NONE;
85     }
86 
87     // All these are in host byte order.
88     in_addr_t mask = 0xffffffff >> (32 - prefixlen) << (32 - prefixlen);
89     in_addr_t ipv4 = ntohl(ip.s_addr);
90     in_addr_t first_ipv4 = ipv4;
91     in_addr_t prefix = ipv4 & mask;
92 
93     // Pick the first IPv4 address in the pool, wrapping around if necessary.
94     // So, for example, 192.0.0.4 -> 192.0.0.5 -> 192.0.0.6 -> 192.0.0.7 -> 192.0.0.0.
95     do {
96         if (isIpv4AddressFreeFunc(htonl(ipv4))) {
97             return htonl(ipv4);
98         }
99         ipv4 = prefix | ((ipv4 + 1) & ~mask);
100     } while (ipv4 != first_ipv4);
101 
102     return INADDR_NONE;
103 }
104 
105 // Alters the bits in the IPv6 address to make them checksum neutral with v4 and nat64Prefix.
makeChecksumNeutral(in6_addr * v6,const in_addr v4,const in6_addr & nat64Prefix)106 void makeChecksumNeutral(in6_addr* v6, const in_addr v4, const in6_addr& nat64Prefix) {
107     // Fill last 8 bytes of IPv6 address with random bits.
108     arc4random_buf(&v6->s6_addr[8], 8);
109 
110     // Make the IID checksum-neutral. That is, make it so that:
111     //   checksum(Local IPv4 | Remote IPv4) = checksum(Local IPv6 | Remote IPv6)
112     // in other words (because remote IPv6 = NAT64 prefix | Remote IPv4):
113     //   checksum(Local IPv4) = checksum(Local IPv6 | NAT64 prefix)
114     // Do this by adjusting the two bytes in the middle of the IID.
115 
116     uint16_t middlebytes = (v6->s6_addr[11] << 8) + v6->s6_addr[12];
117 
118     uint32_t c1 = ip_checksum_add(0, &v4, sizeof(v4));
119     uint32_t c2 = ip_checksum_add(0, &nat64Prefix, sizeof(nat64Prefix)) +
120                   ip_checksum_add(0, v6, sizeof(*v6));
121 
122     uint16_t delta = ip_checksum_adjust(middlebytes, c1, c2);
123     v6->s6_addr[11] = delta >> 8;
124     v6->s6_addr[12] = delta & 0xff;
125 }
126 
127 // Picks a random interface ID that is checksum neutral with the IPv4 address and the NAT64 prefix.
generateIpv6Address(const char * iface,const in_addr v4,const in6_addr & nat64Prefix,in6_addr * v6)128 int generateIpv6Address(const char* iface, const in_addr v4, const in6_addr& nat64Prefix,
129                         in6_addr* v6) {
130     int s = socket(AF_INET6, SOCK_DGRAM | SOCK_CLOEXEC, 0);
131     if (s == -1) return -errno;
132 
133     if (setsockopt(s, SOL_SOCKET, SO_BINDTODEVICE, iface, strlen(iface) + 1) == -1) {
134         close(s);
135         return -errno;
136     }
137 
138     sockaddr_in6 sin6 = {.sin6_family = AF_INET6, .sin6_addr = nat64Prefix};
139     if (connect(s, reinterpret_cast<struct sockaddr*>(&sin6), sizeof(sin6)) == -1) {
140         close(s);
141         return -errno;
142     }
143 
144     socklen_t len = sizeof(sin6);
145     if (getsockname(s, reinterpret_cast<struct sockaddr*>(&sin6), &len) == -1) {
146         close(s);
147         return -errno;
148     }
149 
150     *v6 = sin6.sin6_addr;
151 
152     if (IN6_IS_ADDR_UNSPECIFIED(v6) || IN6_IS_ADDR_LOOPBACK(v6) || IN6_IS_ADDR_LINKLOCAL(v6) ||
153         IN6_IS_ADDR_SITELOCAL(v6) || IN6_IS_ADDR_ULA(v6)) {
154         close(s);
155         return -ENETUNREACH;
156     }
157 
158     makeChecksumNeutral(v6, v4, nat64Prefix);
159     close(s);
160 
161     return 0;
162 }
163 
detect_mtu(const struct in6_addr * plat_subnet,uint32_t plat_suffix,uint32_t mark)164 int detect_mtu(const struct in6_addr* plat_subnet, uint32_t plat_suffix, uint32_t mark) {
165     // Create an IPv6 UDP socket.
166     int s = socket(AF_INET6, SOCK_DGRAM | SOCK_CLOEXEC, 0);
167     if (s < 0) {
168         int ret = errno;
169         ALOGE("socket(AF_INET6, SOCK_DGRAM, 0) failed: %s", strerror(errno));
170         return -ret;
171     }
172 
173     // Socket's mark affects routing decisions (network selection)
174     if ((mark != MARK_UNSET) && setsockopt(s, SOL_SOCKET, SO_MARK, &mark, sizeof(mark))) {
175         int ret = errno;
176         ALOGE("setsockopt(SOL_SOCKET, SO_MARK) failed: %s", strerror(errno));
177         close(s);
178         return -ret;
179     }
180 
181     // Try to connect udp socket to plat_subnet(96 bits):plat_suffix(32 bits)
182     struct sockaddr_in6 dst = {
183             .sin6_family = AF_INET6,
184             .sin6_addr = *plat_subnet,
185     };
186     dst.sin6_addr.s6_addr32[3] = plat_suffix;
187     if (connect(s, (struct sockaddr*)&dst, sizeof(dst))) {
188         int ret = errno;
189         ALOGE("connect() failed: %s", strerror(errno));
190         close(s);
191         return -ret;
192     }
193 
194     // Fetch the socket's IPv6 mtu - this is effectively fetching mtu from routing table
195     int mtu;
196     socklen_t sz_mtu = sizeof(mtu);
197     if (getsockopt(s, SOL_IPV6, IPV6_MTU, &mtu, &sz_mtu)) {
198         int ret = errno;
199         ALOGE("getsockopt(SOL_IPV6, IPV6_MTU) failed: %s", strerror(errno));
200         close(s);
201         return -ret;
202     }
203     if (sz_mtu != sizeof(mtu)) {
204         ALOGE("getsockopt(SOL_IPV6, IPV6_MTU) returned unexpected size: %d", sz_mtu);
205         close(s);
206         return -EFAULT;
207     }
208     close(s);
209 
210     return mtu;
211 }
212 
213 /* function: configure_packet_socket
214  * Binds the packet socket and attaches the receive filter to it.
215  *   sock    - the socket to configure
216  *   addr    - the IP address to filter
217  *   ifindex - index of interface to add the filter to
218  * returns: 0 on success, -errno on failure
219  */
configure_packet_socket(int sock,in6_addr * addr,int ifindex)220 int configure_packet_socket(int sock, in6_addr* addr, int ifindex) {
221     uint32_t* ipv6 = addr->s6_addr32;
222 
223     // clang-format off
224     struct sock_filter filter_code[] = {
225     // Load the first four bytes of the IPv6 destination address (starts 24 bytes in).
226     // Compare it against the first four bytes of our IPv6 address, in host byte order (BPF loads
227     // are always in host byte order). If it matches, continue with next instruction (JMP 0). If it
228     // doesn't match, jump ahead to statement that returns 0 (ignore packet). Repeat for the other
229     // three words of the IPv6 address, and if they all match, return PACKETLEN (accept packet).
230         BPF_STMT(BPF_LD  | BPF_W   | BPF_ABS,  24),
231         BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K,    htonl(ipv6[0]), 0, 7),
232         BPF_STMT(BPF_LD  | BPF_W   | BPF_ABS,  28),
233         BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K,    htonl(ipv6[1]), 0, 5),
234         BPF_STMT(BPF_LD  | BPF_W   | BPF_ABS,  32),
235         BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K,    htonl(ipv6[2]), 0, 3),
236         BPF_STMT(BPF_LD  | BPF_W   | BPF_ABS,  36),
237         BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K,    htonl(ipv6[3]), 0, 1),
238         BPF_STMT(BPF_RET | BPF_K,              PACKETLEN),
239         BPF_STMT(BPF_RET | BPF_K,              0),
240     };
241     // clang-format on
242     struct sock_fprog filter = {sizeof(filter_code) / sizeof(filter_code[0]), filter_code};
243 
244     if (setsockopt(sock, SOL_SOCKET, SO_ATTACH_FILTER, &filter, sizeof(filter))) {
245         int res = errno;
246         ALOGE("attach packet filter failed: %s", strerror(errno));
247         return -res;
248     }
249 
250     struct sockaddr_ll sll = {
251             .sll_family = AF_PACKET,
252             .sll_protocol = htons(ETH_P_IPV6),
253             .sll_ifindex = ifindex,
254             .sll_pkttype =
255                     PACKET_OTHERHOST,  // The 464xlat IPv6 address is not assigned to the kernel.
256     };
257     if (bind(sock, (struct sockaddr*)&sll, sizeof(sll))) {
258         int res = errno;
259         ALOGE("binding packet socket: %s", strerror(errno));
260         return -res;
261     }
262 
263     return 0;
264 }
265 
266 }  // namespace clat
267 }  // namespace net
268 }  // namespace android
269