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