blob: 57f24f3404326195a9afbdb107db67486023a72d [file] [log] [blame]
Daniel Drown0da73fc2012-06-20 16:51:39 -05001/*
2 * Copyright (C) 2008 The Android Open Source Project
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 */
Bernie Innocenti51a0e0f2018-10-05 20:24:06 +090016
17#include "ClatdController.h"
18
Lorenzo Colittiac7fefc2014-10-20 17:14:13 +090019#include <map>
20#include <string>
21
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +090022#include <arpa/inet.h>
Daniel Drown0da73fc2012-06-20 16:51:39 -050023#include <errno.h>
Maciej Żenczykowskic8c38aa2019-03-29 01:24:51 -070024#include <net/if.h>
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +090025#include <netinet/in.h>
Luke Huang94c43a12019-02-14 19:51:38 +080026#include <spawn.h>
Daniel Drown0da73fc2012-06-20 16:51:39 -050027#include <sys/types.h>
28#include <sys/wait.h>
Luke Huang94c43a12019-02-14 19:51:38 +080029#include <unistd.h>
Daniel Drown0da73fc2012-06-20 16:51:39 -050030
31#define LOG_TAG "ClatdController"
Logan Chien3f461482018-04-23 14:31:32 +080032#include <log/log.h>
Daniel Drown0da73fc2012-06-20 16:51:39 -050033
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +090034#include "android-base/unique_fd.h"
Maciej Żenczykowski55262712019-03-29 23:44:56 -070035#include "bpf/BpfMap.h"
36#include "netdbpf/bpf_shared.h"
37#include "netdutils/DumpWriter.h"
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +090038
39extern "C" {
40#include "netutils/checksum.h"
41}
42
Maciej Żenczykowski55262712019-03-29 23:44:56 -070043#include "ClatUtils.h"
Lorenzo Colitti45d3dd02014-06-09 14:09:20 +090044#include "Fwmark.h"
Paul Jensen84c1d032014-05-30 13:29:41 -040045#include "NetdConstants.h"
46#include "NetworkController.h"
Bernie Innocenti189eb502018-10-01 23:10:18 +090047#include "netid_client.h"
Daniel Drown0da73fc2012-06-20 16:51:39 -050048
Lorenzo Colittiac7fefc2014-10-20 17:14:13 +090049static const char* kClatdPath = "/system/bin/clatd";
50
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +090051// For historical reasons, start with 192.0.0.4, and after that, use all subsequent addresses in
52// 192.0.0.0/29 (RFC 7335).
53static const char* kV4AddrString = "192.0.0.4";
54static const in_addr kV4Addr = {inet_addr(kV4AddrString)};
55static const int kV4AddrLen = 29;
56
57using android::base::unique_fd;
Maciej Żenczykowski55262712019-03-29 23:44:56 -070058using android::bpf::BpfMap;
59using android::netdutils::DumpWriter;
60using android::netdutils::ScopedIndent;
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +090061
Lorenzo Colitti7035f222017-02-13 18:29:00 +090062namespace android {
63namespace net {
64
Paul Jensen84c1d032014-05-30 13:29:41 -040065ClatdController::ClatdController(NetworkController* controller)
Lorenzo Colittiac7fefc2014-10-20 17:14:13 +090066 : mNetCtrl(controller) {
Daniel Drown0da73fc2012-06-20 16:51:39 -050067}
68
69ClatdController::~ClatdController() {
70}
71
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +090072bool ClatdController::isIpv4AddressFree(in_addr_t addr) {
73 int s = socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0);
74 if (s == -1) {
75 return 0;
76 }
77
78 // Attempt to connect to the address. If the connection succeeds and getsockname returns the
79 // same then the address is already assigned to the system and we can't use it.
80 struct sockaddr_in sin = {.sin_family = AF_INET, .sin_addr = {addr}, .sin_port = 53};
81 socklen_t len = sizeof(sin);
82 bool inuse = connect(s, (struct sockaddr*)&sin, sizeof(sin)) == 0 &&
83 getsockname(s, (struct sockaddr*)&sin, &len) == 0 && (size_t)len >= sizeof(sin) &&
84 sin.sin_addr.s_addr == addr;
85
86 close(s);
87 return !inuse;
Lorenzo Colittiac7fefc2014-10-20 17:14:13 +090088}
Daniel Drown0da73fc2012-06-20 16:51:39 -050089
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +090090// Picks a free IPv4 address, starting from ip and trying all addresses in the prefix in order.
91// ip - the IP address from the configuration file
92// prefixlen - the length of the prefix from which addresses may be selected.
93// returns: the IPv4 address, or INADDR_NONE if no addresses were available
94in_addr_t ClatdController::selectIpv4Address(const in_addr ip, int16_t prefixlen) {
95 // Don't accept prefixes that are too large because we scan addresses one by one.
96 if (prefixlen < 16 || prefixlen > 32) {
97 return INADDR_NONE;
98 }
Lorenzo Colittiac7fefc2014-10-20 17:14:13 +090099
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +0900100 // All these are in host byte order.
101 in_addr_t mask = 0xffffffff >> (32 - prefixlen) << (32 - prefixlen);
102 in_addr_t ipv4 = ntohl(ip.s_addr);
103 in_addr_t first_ipv4 = ipv4;
104 in_addr_t prefix = ipv4 & mask;
105
106 // Pick the first IPv4 address in the pool, wrapping around if necessary.
107 // So, for example, 192.0.0.4 -> 192.0.0.5 -> 192.0.0.6 -> 192.0.0.7 -> 192.0.0.0.
108 do {
109 if (isIpv4AddressFreeFunc(htonl(ipv4))) {
110 return htonl(ipv4);
111 }
112 ipv4 = prefix | ((ipv4 + 1) & ~mask);
113 } while (ipv4 != first_ipv4);
114
115 return INADDR_NONE;
116}
117
118// Alters the bits in the IPv6 address to make them checksum neutral with v4 and nat64Prefix.
119void ClatdController::makeChecksumNeutral(in6_addr* v6, const in_addr v4,
120 const in6_addr& nat64Prefix) {
121 // Fill last 8 bytes of IPv6 address with random bits.
122 arc4random_buf(&v6->s6_addr[8], 8);
123
124 // Make the IID checksum-neutral. That is, make it so that:
125 // checksum(Local IPv4 | Remote IPv4) = checksum(Local IPv6 | Remote IPv6)
126 // in other words (because remote IPv6 = NAT64 prefix | Remote IPv4):
127 // checksum(Local IPv4) = checksum(Local IPv6 | NAT64 prefix)
128 // Do this by adjusting the two bytes in the middle of the IID.
129
130 uint16_t middlebytes = (v6->s6_addr[11] << 8) + v6->s6_addr[12];
131
132 uint32_t c1 = ip_checksum_add(0, &v4, sizeof(v4));
133 uint32_t c2 = ip_checksum_add(0, &nat64Prefix, sizeof(nat64Prefix)) +
134 ip_checksum_add(0, v6, sizeof(*v6));
135
136 uint16_t delta = ip_checksum_adjust(middlebytes, c1, c2);
137 v6->s6_addr[11] = delta >> 8;
138 v6->s6_addr[12] = delta & 0xff;
139}
140
141// Picks a random interface ID that is checksum neutral with the IPv4 address and the NAT64 prefix.
142int ClatdController::generateIpv6Address(const char* iface, const in_addr v4,
143 const in6_addr& nat64Prefix, in6_addr* v6) {
144 unique_fd s(socket(AF_INET6, SOCK_DGRAM | SOCK_CLOEXEC, 0));
145 if (s == -1) return -errno;
146
147 if (setsockopt(s, SOL_SOCKET, SO_BINDTODEVICE, iface, strlen(iface) + 1) == -1) {
Luke Huang6d301232018-08-01 14:05:18 +0800148 return -errno;
Daniel Drown0da73fc2012-06-20 16:51:39 -0500149 }
150
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +0900151 sockaddr_in6 sin6 = {.sin6_family = AF_INET6, .sin6_addr = nat64Prefix};
152 if (connect(s, reinterpret_cast<struct sockaddr*>(&sin6), sizeof(sin6)) == -1) {
153 return -errno;
154 }
155
156 socklen_t len = sizeof(sin6);
157 if (getsockname(s, reinterpret_cast<struct sockaddr*>(&sin6), &len) == -1) {
158 return -errno;
159 }
160
161 *v6 = sin6.sin6_addr;
162
163 if (IN6_IS_ADDR_UNSPECIFIED(v6) || IN6_IS_ADDR_LOOPBACK(v6) || IN6_IS_ADDR_LINKLOCAL(v6) ||
164 IN6_IS_ADDR_SITELOCAL(v6) || IN6_IS_ADDR_ULA(v6)) {
165 return -ENETUNREACH;
166 }
167
168 makeChecksumNeutral(v6, v4, nat64Prefix);
169
170 return 0;
171}
172
173// Finds the tracker of the clatd running on interface |interface|, or nullptr if clatd has not been
174// started on |interface|.
175ClatdController::ClatdTracker* ClatdController::getClatdTracker(const std::string& interface) {
176 auto it = mClatdTrackers.find(interface);
177 return (it == mClatdTrackers.end() ? nullptr : &it->second);
178}
179
180// Initializes a ClatdTracker for the specified interface.
181int ClatdController::ClatdTracker::init(const std::string& interface,
182 const std::string& nat64Prefix) {
183 netId = netCtrl->getNetworkForInterface(interface.c_str());
Lorenzo Colitti32b2e792015-01-07 15:11:30 +0900184 if (netId == NETID_UNSET) {
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +0900185 ALOGE("Interface %s not assigned to any netId", interface.c_str());
Lorenzo Colitti32b2e792015-01-07 15:11:30 +0900186 errno = ENODEV;
Luke Huang6d301232018-08-01 14:05:18 +0800187 return -errno;
Lorenzo Colitti32b2e792015-01-07 15:11:30 +0900188 }
189
Lorenzo Colitti32b2e792015-01-07 15:11:30 +0900190 fwmark.netId = netId;
191 fwmark.explicitlySelected = true;
192 fwmark.protectedFromVpn = true;
193 fwmark.permission = PERMISSION_SYSTEM;
194
Lorenzo Colitti32b2e792015-01-07 15:11:30 +0900195 snprintf(fwmarkString, sizeof(fwmarkString), "0x%x", fwmark.intValue);
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +0900196 snprintf(netIdString, sizeof(netIdString), "%u", netId);
Maciej Żenczykowskic8c38aa2019-03-29 01:24:51 -0700197 ifIndex = if_nametoindex(interface.c_str());
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +0900198 strlcpy(iface, interface.c_str(), sizeof(iface));
Lorenzo Colitti32b2e792015-01-07 15:11:30 +0900199
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +0900200 // Pass in everything that clatd needs: interface, a netid to use for DNS lookups, a fwmark for
201 // outgoing packets, the NAT64 prefix, and the IPv4 and IPv6 addresses.
202 // Validate the prefix and strip off the prefix length.
203 uint8_t family;
204 uint8_t prefixLen;
Maciej Żenczykowski1c06f9c2019-03-29 23:19:19 -0700205 int res = parsePrefix(nat64Prefix.c_str(), &family, &pfx96, sizeof(pfx96), &prefixLen);
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +0900206 // clatd only supports /96 prefixes.
Maciej Żenczykowski1c06f9c2019-03-29 23:19:19 -0700207 if (res != sizeof(pfx96)) return res;
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +0900208 if (family != AF_INET6) return -EAFNOSUPPORT;
209 if (prefixLen != 96) return -EINVAL;
Maciej Żenczykowski1c06f9c2019-03-29 23:19:19 -0700210 if (!inet_ntop(AF_INET6, &pfx96, pfx96String, sizeof(pfx96String))) return -errno;
Luke Huang6d301232018-08-01 14:05:18 +0800211
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +0900212 // Pick an IPv4 address.
213 // TODO: this picks the address based on other addresses that are assigned to interfaces, but
214 // the address is only actually assigned to an interface once clatd starts up. So we could end
215 // up with two clatd instances with the same IPv4 address.
216 // Stop doing this and instead pick a free one from the kV4Addr pool.
Maciej Żenczykowski55cacfb2019-03-30 02:01:35 -0700217 v4 = {selectIpv4Address(kV4Addr, kV4AddrLen)};
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +0900218 if (v4.s_addr == INADDR_NONE) {
219 ALOGE("No free IPv4 address in %s/%d", kV4AddrString, kV4AddrLen);
220 return -EADDRNOTAVAIL;
221 }
222 if (!inet_ntop(AF_INET, &v4, v4Str, sizeof(v4Str))) return -errno;
223
224 // Generate a checksum-neutral IID.
Maciej Żenczykowski1c06f9c2019-03-29 23:19:19 -0700225 if (generateIpv6Address(iface, v4, pfx96, &v6)) {
226 ALOGE("Unable to find global source address on %s for %s", iface, pfx96String);
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +0900227 return -EADDRNOTAVAIL;
228 }
229 if (!inet_ntop(AF_INET6, &v6, v6Str, sizeof(v6Str))) return -errno;
230
Maciej Żenczykowski1c06f9c2019-03-29 23:19:19 -0700231 ALOGD("starting clatd on %s v4=%s v6=%s pfx96=%s", iface, v4Str, v6Str, pfx96String);
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +0900232 return 0;
233}
234
235int ClatdController::startClatd(const std::string& interface, const std::string& nat64Prefix,
236 std::string* v6Str) {
237 ClatdTracker* existing = getClatdTracker(interface);
238 if (existing != nullptr) {
239 ALOGE("clatd pid=%d already started on %s", existing->pid, interface.c_str());
240 errno = EBUSY;
241 return -errno;
242 }
243
244 ClatdTracker tracker(mNetCtrl);
245 if (int ret = tracker.init(interface, nat64Prefix)) {
246 return ret;
247 }
JP Abgrall69261cb2014-06-19 18:35:24 -0700248
Lorenzo Colittiac7fefc2014-10-20 17:14:13 +0900249 std::string progname("clatd-");
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +0900250 progname += tracker.iface;
Daniel Drown0da73fc2012-06-20 16:51:39 -0500251
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +0900252 // clang-format off
253 char* args[] = {(char*) progname.c_str(),
254 (char*) "-i", tracker.iface,
255 (char*) "-n", tracker.netIdString,
256 (char*) "-m", tracker.fwmarkString,
Maciej Żenczykowski1c06f9c2019-03-29 23:19:19 -0700257 (char*) "-p", tracker.pfx96String,
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +0900258 (char*) "-4", tracker.v4Str,
259 (char*) "-6", tracker.v6Str,
Luke Huang94c43a12019-02-14 19:51:38 +0800260 nullptr};
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +0900261 // clang-format on
262
Luke Huang94c43a12019-02-14 19:51:38 +0800263 // Specify no flags and no actions, posix_spawn will use vfork and is
264 // guaranteed to return only once exec has been called.
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +0900265 int res = posix_spawn(&tracker.pid, kClatdPath, nullptr, nullptr, args, nullptr);
Luke Huang40962442019-02-26 11:46:10 +0800266 if (res) {
267 ALOGE("posix_spawn failed (%s)", strerror(res));
Luke Huang6d301232018-08-01 14:05:18 +0800268 return -res;
Daniel Drown0da73fc2012-06-20 16:51:39 -0500269 }
270
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +0900271 mClatdTrackers[interface] = tracker;
272 ALOGD("clatd started on %s", interface.c_str());
Daniel Drown0da73fc2012-06-20 16:51:39 -0500273
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +0900274 *v6Str = tracker.v6Str;
Daniel Drown0da73fc2012-06-20 16:51:39 -0500275 return 0;
276}
277
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +0900278int ClatdController::stopClatd(const std::string& interface) {
279 ClatdTracker* tracker = getClatdTracker(interface);
Lorenzo Colittiac7fefc2014-10-20 17:14:13 +0900280
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +0900281 if (tracker == nullptr) {
Daniel Drown0da73fc2012-06-20 16:51:39 -0500282 ALOGE("clatd already stopped");
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +0900283 return -ENODEV;
Daniel Drown0da73fc2012-06-20 16:51:39 -0500284 }
285
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +0900286 ALOGD("Stopping clatd pid=%d on %s", tracker->pid, interface.c_str());
Daniel Drown0da73fc2012-06-20 16:51:39 -0500287
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +0900288 kill(tracker->pid, SIGTERM);
289 waitpid(tracker->pid, nullptr, 0);
290 mClatdTrackers.erase(interface);
Daniel Drown0da73fc2012-06-20 16:51:39 -0500291
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +0900292 ALOGD("clatd on %s stopped", interface.c_str());
Daniel Drown0da73fc2012-06-20 16:51:39 -0500293
294 return 0;
295}
296
Maciej Żenczykowski55262712019-03-29 23:44:56 -0700297void ClatdController::dump(DumpWriter& dw) {
298 std::lock_guard guard(mutex);
299
300 ScopedIndent clatdIndent(dw);
301 dw.println("ClatdController");
302
303 {
304 ScopedIndent trackerIndent(dw);
305 dw.println("Trackers: iif[iface] nat64Prefix v6Addr -> v4Addr [netId]");
306
307 ScopedIndent trackerDetailIndent(dw);
308 for (const auto& pair : mClatdTrackers) {
309 const ClatdTracker& tracker = pair.second;
310 dw.println("%u[%s] %s/96 %s -> %s [%u]", tracker.ifIndex, tracker.iface,
311 tracker.pfx96String, tracker.v6Str, tracker.v4Str, tracker.netId);
312 }
313 }
314
315 int fd = getClatIngressMapFd();
316 if (fd < 0) return; // if unsupported just don't dump anything
317 unique_fd mapFd(fd);
318
319 ScopedIndent bpfIndent(dw);
320 dw.println("BPF ingress map: iif(iface) nat64Prefix v6Addr -> v4Addr oif(iface)");
321
322 ScopedIndent bpfDetailIndent(dw);
323 BpfMap<ClatIngressKey, ClatIngressValue> configMap(mapFd);
324 const auto printClatMap = [&dw](const ClatIngressKey& key, const ClatIngressValue& value,
325 const BpfMap<ClatIngressKey, ClatIngressValue>&) {
326 char iifStr[IFNAMSIZ] = "?";
327 char pfx96Str[INET6_ADDRSTRLEN] = "?";
328 char local6Str[INET6_ADDRSTRLEN] = "?";
329 char local4Str[INET_ADDRSTRLEN] = "?";
330 char oifStr[IFNAMSIZ] = "?";
331
332 if_indextoname(key.iif, iifStr);
333 inet_ntop(AF_INET6, &key.pfx96, pfx96Str, sizeof(pfx96Str));
334 inet_ntop(AF_INET6, &key.local6, local6Str, sizeof(local6Str));
335 inet_ntop(AF_INET, &value.local4, local4Str, sizeof(local4Str));
336 if_indextoname(value.oif, oifStr);
337
338 dw.println("%u(%s) %s/96 %s -> %s %u(%s)", key.iif, iifStr, pfx96Str, local6Str, local4Str,
339 value.oif, oifStr);
340 return netdutils::status::ok;
341 };
342 auto res = configMap.iterateWithValue(printClatMap);
343 if (!isOk(res)) {
344 dw.println("Error printing BPF map: %s", res.msg().c_str());
345 }
346}
347
Lorenzo Colitti7ef8c0f2019-01-11 22:34:58 +0900348auto ClatdController::isIpv4AddressFreeFunc = isIpv4AddressFree;
349
Lorenzo Colitti7035f222017-02-13 18:29:00 +0900350} // namespace net
351} // namespace android