• 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 #include <bpf/BpfClassic.h>
29 
30 extern "C" {
31 #include "checksum.h"
32 }
33 
34 namespace android {
35 namespace net {
36 namespace clat {
37 
isIpv4AddressFree(const in_addr_t addr)38 bool isIpv4AddressFree(const in_addr_t addr) {
39     const int s = socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0);
40     if (s == -1) return 0;
41 
42     // Attempt to connect to the address. If the connection succeeds and getsockname returns the
43     // same then the address is already assigned to the system and we can't use it.
44     struct sockaddr_in sin = {
45             .sin_family = AF_INET,
46             .sin_port = htons(53),
47             .sin_addr = {addr},
48     };
49     socklen_t len = sizeof(sin);
50     const bool inuse = !connect(s, (struct sockaddr*)&sin, sizeof(sin)) &&
51                        !getsockname(s, (struct sockaddr*)&sin, &len) &&
52                        len == (socklen_t)sizeof(sin) &&
53                        sin.sin_addr.s_addr == addr;
54 
55     close(s);
56     return !inuse;
57 }
58 
59 // Picks a free IPv4 address, starting from ip and trying all addresses in the prefix in order.
60 //   ip        - the IP address from the configuration file
61 //   prefixlen - the length of the prefix from which addresses may be selected.
62 //   returns: the IPv4 address, or INADDR_NONE if no addresses were available
selectIpv4Address(const in_addr ip,const int16_t prefixlen)63 in_addr_t selectIpv4Address(const in_addr ip, const int16_t prefixlen) {
64     return selectIpv4AddressInternal(ip, prefixlen, isIpv4AddressFree);
65 }
66 
67 // Only allow testing to use this function directly. Otherwise call selectIpv4Address(ip, pfxlen)
68 // which has applied valid isIpv4AddressFree function pointer.
selectIpv4AddressInternal(const in_addr ip,const int16_t prefixlen,const isIpv4AddrFreeFn isIpv4AddressFreeFunc)69 in_addr_t selectIpv4AddressInternal(const in_addr ip, const int16_t prefixlen,
70                                     const isIpv4AddrFreeFn isIpv4AddressFreeFunc) {
71     // Impossible! Only test allows to apply fn.
72     if (isIpv4AddressFreeFunc == nullptr) return INADDR_NONE;
73 
74     // Don't accept prefixes that are too large because we scan addresses one by one.
75     if (prefixlen < 16 || prefixlen > 32) return INADDR_NONE;
76 
77     // All these are in host byte order.
78     const uint32_t mask = 0xffffffff >> (32 - prefixlen) << (32 - prefixlen);
79     uint32_t ipv4 = ntohl(ip.s_addr);
80     const uint32_t first_ipv4 = ipv4;
81     const uint32_t prefix = ipv4 & mask;
82 
83     // Pick the first IPv4 address in the pool, wrapping around if necessary.
84     // So, for example, 192.0.0.4 -> 192.0.0.5 -> 192.0.0.6 -> 192.0.0.7 -> 192.0.0.0.
85     do {
86         if (isIpv4AddressFreeFunc(htonl(ipv4))) return htonl(ipv4);
87         ipv4 = prefix | ((ipv4 + 1) & ~mask);
88     } while (ipv4 != first_ipv4);
89 
90     return INADDR_NONE;
91 }
92 
93 // Alters the bits in the IPv6 address to make them checksum neutral with v4 and nat64Prefix.
makeChecksumNeutral(in6_addr * const v6,const in_addr v4,const in6_addr & nat64Prefix)94 void makeChecksumNeutral(in6_addr* const v6, const in_addr v4, const in6_addr& nat64Prefix) {
95     // Fill last 8 bytes of IPv6 address with random bits.
96     arc4random_buf(&v6->s6_addr[8], 8);
97 
98     // Make the IID checksum-neutral. That is, make it so that:
99     //   checksum(Local IPv4 | Remote IPv4) = checksum(Local IPv6 | Remote IPv6)
100     // in other words (because remote IPv6 = NAT64 prefix | Remote IPv4):
101     //   checksum(Local IPv4) = checksum(Local IPv6 | NAT64 prefix)
102     // Do this by adjusting the two bytes in the middle of the IID.
103 
104     uint16_t middlebytes = (v6->s6_addr[11] << 8) + v6->s6_addr[12];
105 
106     uint32_t c1 = ip_checksum_add(0, &v4, sizeof(v4));
107     uint32_t c2 = ip_checksum_add(0, &nat64Prefix, sizeof(nat64Prefix)) +
108                   ip_checksum_add(0, v6, sizeof(*v6));
109 
110     uint16_t delta = ip_checksum_adjust(middlebytes, c1, c2);
111     v6->s6_addr[11] = delta >> 8;
112     v6->s6_addr[12] = delta & 0xff;
113 }
114 
115 // Picks a random interface ID that is checksum neutral with the IPv4 address and the NAT64 prefix.
generateIpv6Address(const char * const iface,const in_addr v4,const in6_addr & nat64Prefix,in6_addr * const v6,const uint32_t mark)116 int generateIpv6Address(const char* const iface, const in_addr v4, const in6_addr& nat64Prefix,
117                         in6_addr* const v6, const uint32_t mark) {
118     const int s = socket(AF_INET6, SOCK_DGRAM | SOCK_CLOEXEC, 0);
119     if (s == -1) return -errno;
120 
121     // Socket's mark affects routing decisions (network selection)
122     // An fwmark is necessary for clat to bypass the VPN during initialization.
123     if (setsockopt(s, SOL_SOCKET, SO_MARK, &mark, sizeof(mark))) {
124         const int err = errno;
125         ALOGE("setsockopt(SOL_SOCKET, SO_MARK) failed: %s", strerror(err));
126         close(s);
127         return -err;
128     }
129 
130     if (setsockopt(s, SOL_SOCKET, SO_BINDTODEVICE, iface, strlen(iface) + 1)) {
131         const int err = errno;
132         ALOGE("setsockopt(SOL_SOCKET, SO_BINDTODEVICE, '%s') failed: %s", iface, strerror(err));
133         close(s);
134         return -err;
135     }
136 
137     sockaddr_in6 sin6 = {.sin6_family = AF_INET6, .sin6_addr = nat64Prefix};
138     if (connect(s, reinterpret_cast<struct sockaddr*>(&sin6), sizeof(sin6))) {
139         close(s);
140         return -errno;
141     }
142 
143     socklen_t len = sizeof(sin6);
144     if (getsockname(s, reinterpret_cast<struct sockaddr*>(&sin6), &len)) {
145         close(s);
146         return -errno;
147     }
148 
149     *v6 = sin6.sin6_addr;
150 
151     if (IN6_IS_ADDR_UNSPECIFIED(v6) || IN6_IS_ADDR_LOOPBACK(v6) || IN6_IS_ADDR_LINKLOCAL(v6) ||
152         IN6_IS_ADDR_SITELOCAL(v6) || IN6_IS_ADDR_ULA(v6)) {
153         close(s);
154         return -ENETUNREACH;
155     }
156 
157     makeChecksumNeutral(v6, v4, nat64Prefix);
158     close(s);
159 
160     return 0;
161 }
162 
detect_mtu(const struct in6_addr * const plat_subnet,const uint32_t plat_suffix,const uint32_t mark)163 int detect_mtu(const struct in6_addr* const plat_subnet, const uint32_t plat_suffix,
164                const uint32_t mark) {
165     // Create an IPv6 UDP socket.
166     const int s = socket(AF_INET6, SOCK_DGRAM | SOCK_CLOEXEC, 0);
167     if (s < 0) {
168         const int err = errno;
169         ALOGE("socket(AF_INET6, SOCK_DGRAM, 0) failed: %s", strerror(err));
170         return -err;
171     }
172 
173     // Socket's mark affects routing decisions (network selection)
174     if (setsockopt(s, SOL_SOCKET, SO_MARK, &mark, sizeof(mark))) {
175         const int err = errno;
176         ALOGE("setsockopt(SOL_SOCKET, SO_MARK) failed: %s", strerror(err));
177         close(s);
178         return -err;
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         const int err = errno;
189         ALOGE("connect() failed: %s", strerror(err));
190         close(s);
191         return -err;
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         const int err = errno;
199         ALOGE("getsockopt(SOL_IPV6, IPV6_MTU) failed: %s", strerror(err));
200         close(s);
201         return -err;
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(const int sock,const in6_addr * const addr,const int ifindex)220 int configure_packet_socket(const int sock, const in6_addr* const addr, const int ifindex) {
221     // clang-format off
222     struct sock_filter filter_code[] = {
223         BPF_LOAD_IPV6_BE32(daddr.s6_addr32[0]),
224         BPF2_REJECT_IF_NOT_EQUAL(ntohl(addr->s6_addr32[0])),
225         BPF_LOAD_IPV6_BE32(daddr.s6_addr32[1]),
226         BPF2_REJECT_IF_NOT_EQUAL(ntohl(addr->s6_addr32[1])),
227         BPF_LOAD_IPV6_BE32(daddr.s6_addr32[2]),
228         BPF2_REJECT_IF_NOT_EQUAL(ntohl(addr->s6_addr32[2])),
229         BPF_LOAD_IPV6_BE32(daddr.s6_addr32[3]),
230         BPF2_REJECT_IF_NOT_EQUAL(ntohl(addr->s6_addr32[3])),
231         BPF_ACCEPT,
232     };
233     // clang-format on
234     struct sock_fprog filter = {sizeof(filter_code) / sizeof(filter_code[0]), filter_code};
235 
236     if (setsockopt(sock, SOL_SOCKET, SO_ATTACH_FILTER, &filter, sizeof(filter))) {
237         const int err = errno;
238         ALOGE("attach packet filter failed: %s", strerror(err));
239         return -err;
240     }
241 
242     struct sockaddr_ll sll = {
243             .sll_family = AF_PACKET,
244             .sll_protocol = htons(ETH_P_IPV6),
245             .sll_ifindex = ifindex,
246             .sll_pkttype =
247                     PACKET_OTHERHOST,  // The 464xlat IPv6 address is not assigned to the kernel.
248     };
249     if (bind(sock, (struct sockaddr*)&sll, sizeof(sll))) {
250         const int err = errno;
251         ALOGE("binding packet socket: %s", strerror(err));
252         return -err;
253     }
254 
255     return 0;
256 }
257 
258 }  // namespace clat
259 }  // namespace net
260 }  // namespace android
261