1 /*
2 * Copyright (C) 2014 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 */
16
17 #include "RouteController.h"
18
19 #include <arpa/inet.h>
20 #include <errno.h>
21 #include <fcntl.h>
22 #include <linux/fib_rules.h>
23 #include <net/if.h>
24 #include <netdutils/InternetAddresses.h>
25 #include <private/android_filesystem_config.h>
26 #include <sys/stat.h>
27
28 #include <map>
29
30 #include "DummyNetwork.h"
31 #include "Fwmark.h"
32 #include "NetdConstants.h"
33 #include "NetlinkCommands.h"
34 #include "TcUtils.h"
35
36 #include <android-base/file.h>
37 #include <android-base/stringprintf.h>
38 #include <android-base/strings.h>
39 #include "log/log.h"
40 #include "netid_client.h"
41 #include "netutils/ifc.h"
42
43 using android::base::StartsWith;
44 using android::base::StringPrintf;
45 using android::base::WriteStringToFile;
46 using android::netdutils::IPPrefix;
47
48 namespace android::net {
49
50 auto RouteController::iptablesRestoreCommandFunction = execIptablesRestoreCommand;
51 auto RouteController::ifNameToIndexFunction = if_nametoindex;
52 // BEGIN CONSTANTS --------------------------------------------------------------------------------
53
54 const uint32_t ROUTE_TABLE_LOCAL_NETWORK = 97;
55 const uint32_t ROUTE_TABLE_LEGACY_NETWORK = 98;
56 const uint32_t ROUTE_TABLE_LEGACY_SYSTEM = 99;
57
58 const char* const ROUTE_TABLE_NAME_LOCAL_NETWORK = "local_network";
59 const char* const ROUTE_TABLE_NAME_LEGACY_NETWORK = "legacy_network";
60 const char* const ROUTE_TABLE_NAME_LEGACY_SYSTEM = "legacy_system";
61
62 const char* const ROUTE_TABLE_NAME_LOCAL = "local";
63 const char* const ROUTE_TABLE_NAME_MAIN = "main";
64
65 const char* const RouteController::LOCAL_MANGLE_INPUT = "routectrl_mangle_INPUT";
66
67 const IPPrefix V4_LOCAL_PREFIXES[] = {
68 IPPrefix::forString("169.254.0.0/16"), // Link Local
69 IPPrefix::forString("100.64.0.0/10"), // CGNAT
70 IPPrefix::forString("10.0.0.0/8"), // RFC1918
71 IPPrefix::forString("172.16.0.0/12"), // RFC1918
72 IPPrefix::forString("192.168.0.0/16") // RFC1918
73 };
74
75 const uint8_t AF_FAMILIES[] = {AF_INET, AF_INET6};
76
77 const uid_t UID_ROOT = 0;
78 const uint32_t FWMARK_NONE = 0;
79 const uint32_t MASK_NONE = 0;
80 const char* const IIF_LOOPBACK = "lo";
81 const char* const IIF_NONE = nullptr;
82 const char* const OIF_NONE = nullptr;
83 const bool ACTION_ADD = true;
84 const bool ACTION_DEL = false;
85 const bool MODIFY_NON_UID_BASED_RULES = true;
86
87 const mode_t RT_TABLES_MODE = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH; // mode 0644, rw-r--r--
88
89 // Avoids "non-constant-expression cannot be narrowed from type 'unsigned int' to 'unsigned short'"
90 // warnings when using RTA_LENGTH(x) inside static initializers (even when x is already uint16_t).
U16_RTA_LENGTH(uint16_t x)91 static constexpr uint16_t U16_RTA_LENGTH(uint16_t x) {
92 return RTA_LENGTH(x);
93 }
94
95 // These are practically const, but can't be declared so, because they are used to initialize
96 // non-const pointers ("void* iov_base") in iovec arrays.
97 rtattr FRATTR_PRIORITY = { U16_RTA_LENGTH(sizeof(uint32_t)), FRA_PRIORITY };
98 rtattr FRATTR_TABLE = { U16_RTA_LENGTH(sizeof(uint32_t)), FRA_TABLE };
99 rtattr FRATTR_FWMARK = { U16_RTA_LENGTH(sizeof(uint32_t)), FRA_FWMARK };
100 rtattr FRATTR_FWMASK = { U16_RTA_LENGTH(sizeof(uint32_t)), FRA_FWMASK };
101 rtattr FRATTR_UID_RANGE = { U16_RTA_LENGTH(sizeof(fib_rule_uid_range)), FRA_UID_RANGE };
102
103 rtattr RTATTR_TABLE = { U16_RTA_LENGTH(sizeof(uint32_t)), RTA_TABLE };
104 rtattr RTATTR_OIF = { U16_RTA_LENGTH(sizeof(uint32_t)), RTA_OIF };
105 rtattr RTATTR_PRIO = { U16_RTA_LENGTH(sizeof(uint32_t)), RTA_PRIORITY };
106
107 // One or more nested attributes in the RTA_METRICS attribute.
108 rtattr RTATTRX_MTU = { U16_RTA_LENGTH(sizeof(uint32_t)), RTAX_MTU};
109 constexpr size_t RTATTRX_MTU_SIZE = RTA_SPACE(sizeof(uint32_t));
110
111 // The RTA_METRICS attribute itself.
112 constexpr size_t RTATTR_METRICS_SIZE = RTATTRX_MTU_SIZE;
113 rtattr RTATTR_METRICS = { U16_RTA_LENGTH(RTATTR_METRICS_SIZE), RTA_METRICS };
114
115 uint8_t PADDING_BUFFER[RTA_ALIGNTO] = {0, 0, 0, 0};
116
117 constexpr bool EXPLICIT = true;
118 constexpr bool IMPLICIT = false;
119
120 // END CONSTANTS ----------------------------------------------------------------------------------
121
actionName(uint16_t action)122 static const char* actionName(uint16_t action) {
123 static const char *ops[4] = {"adding", "deleting", "getting", "???"};
124 return ops[action % 4];
125 }
126
familyName(uint8_t family)127 static const char* familyName(uint8_t family) {
128 switch (family) {
129 case AF_INET: return "IPv4";
130 case AF_INET6: return "IPv6";
131 default: return "???";
132 }
133 }
134
135 static void maybeModifyQdiscClsact(const char* interface, bool add);
136
getRouteTableIndexFromGlobalRouteTableIndex(uint32_t index,bool local)137 static uint32_t getRouteTableIndexFromGlobalRouteTableIndex(uint32_t index, bool local) {
138 // The local table is
139 // "global table - ROUTE_TABLE_OFFSET_FROM_INDEX + ROUTE_TABLE_OFFSET_FROM_INDEX_FOR_LOCAL"
140 const uint32_t localTableOffset = RouteController::ROUTE_TABLE_OFFSET_FROM_INDEX_FOR_LOCAL -
141 RouteController::ROUTE_TABLE_OFFSET_FROM_INDEX;
142 return local ? index + localTableOffset : index;
143 }
144
145 // Caller must hold sInterfaceToTableLock.
getRouteTableForInterfaceLocked(const char * interface,bool local)146 uint32_t RouteController::getRouteTableForInterfaceLocked(const char* interface, bool local) {
147 // If we already know the routing table for this interface name, use it.
148 // This ensures we can remove rules and routes for an interface that has been removed,
149 // or has been removed and re-added with a different interface index.
150 //
151 // The caller is responsible for ensuring that an interface is never added to a network
152 // until it has been removed from any network it was previously in. This ensures that
153 // if the same interface disconnects and then reconnects with a different interface ID
154 // when the reconnect happens the interface will not be in the map, and the code will
155 // determine the new routing table from the interface ID, below.
156 //
157 // sInterfaceToTable stores the *global* routing table for the interface, and the local table is
158 // "global table - ROUTE_TABLE_OFFSET_FROM_INDEX + ROUTE_TABLE_OFFSET_FROM_INDEX_FOR_LOCAL"
159 auto iter = sInterfaceToTable.find(interface);
160 if (iter != sInterfaceToTable.end()) {
161 return getRouteTableIndexFromGlobalRouteTableIndex(iter->second, local);
162 }
163
164 uint32_t index = RouteController::ifNameToIndexFunction(interface);
165 if (index == 0) {
166 ALOGE("cannot find interface %s: %s", interface, strerror(errno));
167 return RT_TABLE_UNSPEC;
168 }
169 index += RouteController::ROUTE_TABLE_OFFSET_FROM_INDEX;
170 sInterfaceToTable[interface] = index;
171 return getRouteTableIndexFromGlobalRouteTableIndex(index, local);
172 }
173
getIfIndex(const char * interface)174 uint32_t RouteController::getIfIndex(const char* interface) {
175 std::lock_guard lock(sInterfaceToTableLock);
176
177 auto iter = sInterfaceToTable.find(interface);
178 if (iter == sInterfaceToTable.end()) {
179 ALOGE("getIfIndex: cannot find interface %s", interface);
180 return 0;
181 }
182
183 // For interfaces that are not in the local network, the routing table is always the interface
184 // index plus ROUTE_TABLE_OFFSET_FROM_INDEX. But for interfaces in the local network, there's no
185 // way to know the interface index from this table. Return 0 here so callers of this method do
186 // not get confused.
187 // TODO: stop calling this method from any caller that only wants interfaces in client mode.
188 int ifindex = iter->second;
189 if (ifindex == ROUTE_TABLE_LOCAL_NETWORK) {
190 return 0;
191 }
192
193 return ifindex - ROUTE_TABLE_OFFSET_FROM_INDEX;
194 }
195
getRouteTableForInterface(const char * interface,bool local)196 uint32_t RouteController::getRouteTableForInterface(const char* interface, bool local) {
197 std::lock_guard lock(sInterfaceToTableLock);
198 return getRouteTableForInterfaceLocked(interface, local);
199 }
200
addTableName(uint32_t table,const std::string & name,std::string * contents)201 void addTableName(uint32_t table, const std::string& name, std::string* contents) {
202 char tableString[UINT32_STRLEN];
203 snprintf(tableString, sizeof(tableString), "%u", table);
204 *contents += tableString;
205 *contents += " ";
206 *contents += name;
207 *contents += "\n";
208 }
209
210 // Doesn't return success/failure as the file is optional; it's okay if we fail to update it.
updateTableNamesFile()211 void RouteController::updateTableNamesFile() {
212 std::string contents;
213
214 addTableName(RT_TABLE_LOCAL, ROUTE_TABLE_NAME_LOCAL, &contents);
215 addTableName(RT_TABLE_MAIN, ROUTE_TABLE_NAME_MAIN, &contents);
216
217 addTableName(ROUTE_TABLE_LOCAL_NETWORK, ROUTE_TABLE_NAME_LOCAL_NETWORK, &contents);
218 addTableName(ROUTE_TABLE_LEGACY_NETWORK, ROUTE_TABLE_NAME_LEGACY_NETWORK, &contents);
219 addTableName(ROUTE_TABLE_LEGACY_SYSTEM, ROUTE_TABLE_NAME_LEGACY_SYSTEM, &contents);
220
221 std::lock_guard lock(sInterfaceToTableLock);
222 for (const auto& [ifName, ifIndex] : sInterfaceToTable) {
223 addTableName(ifIndex, ifName, &contents);
224 // Add table for the local route of the network. It's expected to be used for excluding the
225 // local traffic in the VPN network.
226 // Start from ROUTE_TABLE_OFFSET_FROM_INDEX_FOR_LOCAL plus with the interface table index.
227 uint32_t offset = ROUTE_TABLE_OFFSET_FROM_INDEX_FOR_LOCAL - ROUTE_TABLE_OFFSET_FROM_INDEX;
228 addTableName(offset + ifIndex, ifName + INTERFACE_LOCAL_SUFFIX, &contents);
229 }
230
231 if (!WriteStringToFile(contents, RT_TABLES_PATH, RT_TABLES_MODE, AID_SYSTEM, AID_WIFI)) {
232 ALOGE("failed to write to %s (%s)", RT_TABLES_PATH, strerror(errno));
233 return;
234 }
235 }
236
237 // Returns 0 on success or negative errno on failure.
padInterfaceName(const char * input,char * name,size_t * length,uint16_t * padding)238 int padInterfaceName(const char* input, char* name, size_t* length, uint16_t* padding) {
239 if (!input) {
240 *length = 0;
241 *padding = 0;
242 return 0;
243 }
244 *length = strlcpy(name, input, IFNAMSIZ) + 1;
245 if (*length > IFNAMSIZ) {
246 ALOGE("interface name too long (%zu > %u)", *length, IFNAMSIZ);
247 return -ENAMETOOLONG;
248 }
249 *padding = RTA_SPACE(*length) - RTA_LENGTH(*length);
250 return 0;
251 }
252
253 // Adds or removes a routing rule for IPv4 and IPv6.
254 //
255 // + If |table| is non-zero, the rule points at the specified routing table. Otherwise, the table is
256 // unspecified. An unspecified table is not allowed when creating an FR_ACT_TO_TBL rule.
257 // + If |mask| is non-zero, the rule matches the specified fwmark and mask. Otherwise, |fwmark| is
258 // ignored.
259 // + If |iif| is non-NULL, the rule matches the specified incoming interface.
260 // + If |oif| is non-NULL, the rule matches the specified outgoing interface.
261 // + If |uidStart| and |uidEnd| are not INVALID_UID, the rule matches packets from UIDs in that
262 // range (inclusive). Otherwise, the rule matches packets from all UIDs.
263 //
264 // Returns 0 on success or negative errno on failure.
modifyIpRule(uint16_t action,int32_t priority,uint8_t ruleType,uint32_t table,uint32_t fwmark,uint32_t mask,const char * iif,const char * oif,uid_t uidStart,uid_t uidEnd)265 [[nodiscard]] static int modifyIpRule(uint16_t action, int32_t priority, uint8_t ruleType,
266 uint32_t table, uint32_t fwmark, uint32_t mask,
267 const char* iif, const char* oif, uid_t uidStart,
268 uid_t uidEnd) {
269 if (priority < 0) {
270 ALOGE("invalid IP-rule priority %d", priority);
271 return -ERANGE;
272 }
273
274 // Ensure that if you set a bit in the fwmark, it's not being ignored by the mask.
275 if (fwmark & ~mask) {
276 ALOGE("mask 0x%x does not select all the bits set in fwmark 0x%x", mask, fwmark);
277 return -ERANGE;
278 }
279
280 // Interface names must include exactly one terminating NULL and be properly padded, or older
281 // kernels will refuse to delete rules.
282 char iifName[IFNAMSIZ], oifName[IFNAMSIZ];
283 size_t iifLength, oifLength;
284 uint16_t iifPadding, oifPadding;
285 if (int ret = padInterfaceName(iif, iifName, &iifLength, &iifPadding)) {
286 return ret;
287 }
288 if (int ret = padInterfaceName(oif, oifName, &oifLength, &oifPadding)) {
289 return ret;
290 }
291
292 // Either both start and end UID must be specified, or neither.
293 if ((uidStart == INVALID_UID) != (uidEnd == INVALID_UID)) {
294 ALOGE("incompatible start and end UIDs (%u vs %u)", uidStart, uidEnd);
295 return -EUSERS;
296 }
297
298 bool isUidRule = (uidStart != INVALID_UID);
299
300 // Assemble a rule request and put it in an array of iovec structures.
301 fib_rule_hdr rule = {
302 .action = ruleType,
303 // Note that here we're implicitly setting rule.table to 0. When we want to specify a
304 // non-zero table, we do this via the FRATTR_TABLE attribute.
305 };
306
307 // Don't ever create a rule that looks up table 0, because table 0 is the local table.
308 // It's OK to specify a table ID of 0 when deleting a rule, because that doesn't actually select
309 // table 0, it's a wildcard that matches anything.
310 if (table == RT_TABLE_UNSPEC && rule.action == FR_ACT_TO_TBL && action != RTM_DELRULE) {
311 ALOGE("RT_TABLE_UNSPEC only allowed when deleting rules");
312 return -ENOTUNIQ;
313 }
314
315 rtattr fraIifName = { U16_RTA_LENGTH(iifLength), FRA_IIFNAME };
316 rtattr fraOifName = { U16_RTA_LENGTH(oifLength), FRA_OIFNAME };
317 struct fib_rule_uid_range uidRange = { uidStart, uidEnd };
318
319 iovec iov[] = {
320 { nullptr, 0 },
321 { &rule, sizeof(rule) },
322 { &FRATTR_PRIORITY, sizeof(FRATTR_PRIORITY) },
323 { &priority, sizeof(priority) },
324 { &FRATTR_TABLE, table != RT_TABLE_UNSPEC ? sizeof(FRATTR_TABLE) : 0 },
325 { &table, table != RT_TABLE_UNSPEC ? sizeof(table) : 0 },
326 { &FRATTR_FWMARK, mask ? sizeof(FRATTR_FWMARK) : 0 },
327 { &fwmark, mask ? sizeof(fwmark) : 0 },
328 { &FRATTR_FWMASK, mask ? sizeof(FRATTR_FWMASK) : 0 },
329 { &mask, mask ? sizeof(mask) : 0 },
330 { &FRATTR_UID_RANGE, isUidRule ? sizeof(FRATTR_UID_RANGE) : 0 },
331 { &uidRange, isUidRule ? sizeof(uidRange) : 0 },
332 { &fraIifName, iif != IIF_NONE ? sizeof(fraIifName) : 0 },
333 { iifName, iifLength },
334 { PADDING_BUFFER, iifPadding },
335 { &fraOifName, oif != OIF_NONE ? sizeof(fraOifName) : 0 },
336 { oifName, oifLength },
337 { PADDING_BUFFER, oifPadding },
338 };
339
340 uint16_t flags = (action == RTM_NEWRULE) ? NETLINK_RULE_CREATE_FLAGS : NETLINK_REQUEST_FLAGS;
341 for (size_t i = 0; i < ARRAY_SIZE(AF_FAMILIES); ++i) {
342 rule.family = AF_FAMILIES[i];
343 if (int ret = sendNetlinkRequest(action, flags, iov, ARRAY_SIZE(iov), nullptr)) {
344 if (!(action == RTM_DELRULE && ret == -ENOENT && priority == RULE_PRIORITY_TETHERING)) {
345 // Don't log when deleting a tethering rule that's not there. This matches the
346 // behaviour of clearTetheringRules, which ignores ENOENT in this case.
347 ALOGE("Error %s %s rule: %s", actionName(action), familyName(rule.family),
348 strerror(-ret));
349 }
350 return ret;
351 }
352 }
353
354 return 0;
355 }
356
modifyIpRule(uint16_t action,int32_t priority,uint32_t table,uint32_t fwmark,uint32_t mask,const char * iif,const char * oif,uid_t uidStart,uid_t uidEnd)357 [[nodiscard]] static int modifyIpRule(uint16_t action, int32_t priority, uint32_t table,
358 uint32_t fwmark, uint32_t mask, const char* iif,
359 const char* oif, uid_t uidStart, uid_t uidEnd) {
360 return modifyIpRule(action, priority, FR_ACT_TO_TBL, table, fwmark, mask, iif, oif, uidStart,
361 uidEnd);
362 }
363
modifyIpRule(uint16_t action,int32_t priority,uint32_t table,uint32_t fwmark,uint32_t mask)364 [[nodiscard]] static int modifyIpRule(uint16_t action, int32_t priority, uint32_t table,
365 uint32_t fwmark, uint32_t mask) {
366 return modifyIpRule(action, priority, table, fwmark, mask, IIF_NONE, OIF_NONE, INVALID_UID,
367 INVALID_UID);
368 }
369
370 // Adds or deletes an IPv4 or IPv6 route.
371 // Returns 0 on success or negative errno on failure.
modifyIpRoute(uint16_t action,uint16_t flags,uint32_t table,const char * interface,const char * destination,const char * nexthop,uint32_t mtu,uint32_t priority)372 int modifyIpRoute(uint16_t action, uint16_t flags, uint32_t table, const char* interface,
373 const char* destination, const char* nexthop, uint32_t mtu, uint32_t priority) {
374 // At least the destination must be non-null.
375 if (!destination) {
376 ALOGE("null destination");
377 return -EFAULT;
378 }
379
380 // Parse the prefix.
381 uint8_t rawAddress[sizeof(in6_addr)];
382 uint8_t family;
383 uint8_t prefixLength;
384 int rawLength = parsePrefix(destination, &family, rawAddress, sizeof(rawAddress),
385 &prefixLength);
386 if (rawLength < 0) {
387 ALOGE("parsePrefix failed for destination %s (%s)", destination, strerror(-rawLength));
388 return rawLength;
389 }
390
391 if (static_cast<size_t>(rawLength) > sizeof(rawAddress)) {
392 ALOGE("impossible! address too long (%d vs %zu)", rawLength, sizeof(rawAddress));
393 return -ENOBUFS; // Cannot happen; parsePrefix only supports IPv4 and IPv6.
394 }
395
396 uint8_t type = RTN_UNICAST;
397 uint32_t ifindex;
398 uint8_t rawNexthop[sizeof(in6_addr)];
399
400 if (nexthop && !strcmp(nexthop, "unreachable")) {
401 type = RTN_UNREACHABLE;
402 // 'interface' is likely non-NULL, as the caller (modifyRoute()) likely used it to lookup
403 // the table number. But it's an error to specify an interface ("dev ...") or a nexthop for
404 // unreachable routes, so nuke them. (IPv6 allows them to be specified; IPv4 doesn't.)
405 interface = OIF_NONE;
406 nexthop = nullptr;
407 } else if (nexthop && !strcmp(nexthop, "throw")) {
408 type = RTN_THROW;
409 interface = OIF_NONE;
410 nexthop = nullptr;
411 } else {
412 // If an interface was specified, find the ifindex.
413 if (interface != OIF_NONE) {
414 ifindex = RouteController::ifNameToIndexFunction(interface);
415
416 if (!ifindex) {
417 ALOGE("cannot find interface %s", interface);
418 return -ENODEV;
419 }
420 }
421
422 // If a nexthop was specified, parse it as the same family as the prefix.
423 if (nexthop && inet_pton(family, nexthop, rawNexthop) <= 0) {
424 ALOGE("inet_pton failed for nexthop %s", nexthop);
425 return -EINVAL;
426 }
427 }
428
429 // Assemble a rtmsg and put it in an array of iovec structures.
430 rtmsg route = {
431 .rtm_family = family,
432 .rtm_dst_len = prefixLength,
433 .rtm_protocol = RTPROT_STATIC,
434 .rtm_scope = static_cast<uint8_t>(nexthop ? RT_SCOPE_UNIVERSE : RT_SCOPE_LINK),
435 .rtm_type = type,
436 };
437
438 rtattr rtaDst = { U16_RTA_LENGTH(rawLength), RTA_DST };
439 rtattr rtaGateway = { U16_RTA_LENGTH(rawLength), RTA_GATEWAY };
440
441 iovec iov[] = {
442 {nullptr, 0},
443 {&route, sizeof(route)},
444 {&RTATTR_TABLE, sizeof(RTATTR_TABLE)},
445 {&table, sizeof(table)},
446 {&rtaDst, sizeof(rtaDst)},
447 {rawAddress, static_cast<size_t>(rawLength)},
448 {&RTATTR_OIF, interface != OIF_NONE ? sizeof(RTATTR_OIF) : 0},
449 {&ifindex, interface != OIF_NONE ? sizeof(ifindex) : 0},
450 {&rtaGateway, nexthop ? sizeof(rtaGateway) : 0},
451 {rawNexthop, nexthop ? static_cast<size_t>(rawLength) : 0},
452 {&RTATTR_METRICS, mtu != 0 ? sizeof(RTATTR_METRICS) : 0},
453 {&RTATTRX_MTU, mtu != 0 ? sizeof(RTATTRX_MTU) : 0},
454 {&mtu, mtu != 0 ? sizeof(mtu) : 0},
455 {&RTATTR_PRIO, priority != 0 ? sizeof(RTATTR_PRIO) : 0},
456 {&priority, priority != 0 ? sizeof(priority) : 0},
457 };
458
459 // Allow creating multiple link-local routes in the same table, so we can make IPv6
460 // work on all interfaces in the local_network table.
461 if (family == AF_INET6 && IN6_IS_ADDR_LINKLOCAL(reinterpret_cast<in6_addr*>(rawAddress))) {
462 flags &= ~NLM_F_EXCL;
463 }
464
465 int ret = sendNetlinkRequest(action, flags, iov, ARRAY_SIZE(iov), nullptr);
466 if (ret) {
467 ALOGE("Error %s route %s -> %s %s to table %u: %s",
468 actionName(action), destination, nexthop, interface, table, strerror(-ret));
469 }
470 return ret;
471 }
472
473 // An iptables rule to mark incoming packets on a network with the netId of the network.
474 //
475 // This is so that the kernel can:
476 // + Use the right fwmark for (and thus correctly route) replies (e.g.: TCP RST, ICMP errors, ping
477 // replies, SYN-ACKs, etc).
478 // + Mark sockets that accept connections from this interface so that the connection stays on the
479 // same interface.
modifyIncomingPacketMark(unsigned netId,const char * interface,Permission permission,bool add)480 int modifyIncomingPacketMark(unsigned netId, const char* interface, Permission permission,
481 bool add) {
482 Fwmark fwmark;
483
484 fwmark.netId = netId;
485 fwmark.explicitlySelected = true;
486 fwmark.protectedFromVpn = true;
487 fwmark.permission = permission;
488
489 const uint32_t mask = ~Fwmark::getUidBillingMask();
490
491 std::string cmd = StringPrintf(
492 "%s %s -i %s -j MARK --set-mark 0x%x/0x%x", add ? "-A" : "-D",
493 RouteController::LOCAL_MANGLE_INPUT, interface, fwmark.intValue, mask);
494 if (RouteController::iptablesRestoreCommandFunction(V4V6, "mangle", cmd, nullptr) != 0) {
495 ALOGE("failed to change iptables rule that sets incoming packet mark");
496 return -EREMOTEIO;
497 }
498
499 return 0;
500 }
501
502 // A rule to route responses to the local network forwarded via the VPN.
503 //
504 // When a VPN is in effect, packets from the local network to upstream networks are forwarded into
505 // the VPN's tunnel interface. When the VPN forwards the responses, they emerge out of the tunnel.
modifyVpnOutputToLocalRule(const char * vpnInterface,bool add)506 [[nodiscard]] static int modifyVpnOutputToLocalRule(const char* vpnInterface, bool add) {
507 return modifyIpRule(add ? RTM_NEWRULE : RTM_DELRULE, RULE_PRIORITY_VPN_OUTPUT_TO_LOCAL,
508 ROUTE_TABLE_LOCAL_NETWORK, MARK_UNSET, MARK_UNSET, vpnInterface, OIF_NONE,
509 INVALID_UID, INVALID_UID);
510 }
511
512 // A rule to route all traffic from a given set of UIDs to go over the VPN.
513 //
514 // Notice that this rule doesn't use the netId. I.e., no matter what netId the user's socket may
515 // have, if they are subject to this VPN, their traffic has to go through it. Allows the traffic to
516 // bypass the VPN if the protectedFromVpn bit is set.
modifyVpnUidRangeRule(uint32_t table,uid_t uidStart,uid_t uidEnd,int32_t subPriority,bool secure,bool add,bool excludeLocalRoutes)517 [[nodiscard]] static int modifyVpnUidRangeRule(uint32_t table, uid_t uidStart, uid_t uidEnd,
518 int32_t subPriority, bool secure, bool add,
519 bool excludeLocalRoutes) {
520 Fwmark fwmark;
521 Fwmark mask;
522
523 fwmark.protectedFromVpn = false;
524 mask.protectedFromVpn = true;
525
526 int32_t priority;
527
528 if (secure) {
529 priority = RULE_PRIORITY_SECURE_VPN;
530 } else {
531 priority = excludeLocalRoutes ? RULE_PRIORITY_BYPASSABLE_VPN_LOCAL_EXCLUSION
532 : RULE_PRIORITY_BYPASSABLE_VPN_NO_LOCAL_EXCLUSION;
533
534 fwmark.explicitlySelected = false;
535 mask.explicitlySelected = true;
536 }
537
538 return modifyIpRule(add ? RTM_NEWRULE : RTM_DELRULE, priority + subPriority, table,
539 fwmark.intValue, mask.intValue, IIF_LOOPBACK, OIF_NONE, uidStart, uidEnd);
540 }
541
542 // A rule to allow system apps to send traffic over this VPN even if they are not part of the target
543 // set of UIDs.
544 //
545 // This is needed for DnsProxyListener to correctly resolve a request for a user who is in the
546 // target set, but where the DnsProxyListener itself is not.
modifyVpnSystemPermissionRule(unsigned netId,uint32_t table,bool secure,bool add,bool excludeLocalRoutes)547 [[nodiscard]] static int modifyVpnSystemPermissionRule(unsigned netId, uint32_t table, bool secure,
548 bool add, bool excludeLocalRoutes) {
549 Fwmark fwmark;
550 Fwmark mask;
551
552 fwmark.netId = netId;
553 mask.netId = FWMARK_NET_ID_MASK;
554
555 fwmark.permission = PERMISSION_SYSTEM;
556 mask.permission = PERMISSION_SYSTEM;
557
558 uint32_t priority;
559
560 if (secure) {
561 priority = RULE_PRIORITY_SECURE_VPN;
562 } else {
563 priority = excludeLocalRoutes ? RULE_PRIORITY_BYPASSABLE_VPN_LOCAL_EXCLUSION
564 : RULE_PRIORITY_BYPASSABLE_VPN_NO_LOCAL_EXCLUSION;
565 }
566
567 return modifyIpRule(add ? RTM_NEWRULE : RTM_DELRULE, priority, table, fwmark.intValue,
568 mask.intValue);
569 }
570
571 // A rule to route traffic based on an explicitly chosen network.
572 //
573 // Supports apps that use the multinetwork APIs to restrict their traffic to a network.
574 //
575 // Even though we check permissions at the time we set a netId into the fwmark of a socket, we need
576 // to check it again in the rules here, because a network's permissions may have been updated via
577 // modifyNetworkPermission().
modifyExplicitNetworkRule(unsigned netId,uint32_t table,Permission permission,uid_t uidStart,uid_t uidEnd,int32_t subPriority,bool add)578 [[nodiscard]] static int modifyExplicitNetworkRule(unsigned netId, uint32_t table,
579 Permission permission, uid_t uidStart,
580 uid_t uidEnd, int32_t subPriority, bool add) {
581 Fwmark fwmark;
582 Fwmark mask;
583
584 fwmark.netId = netId;
585 mask.netId = FWMARK_NET_ID_MASK;
586
587 fwmark.explicitlySelected = true;
588 mask.explicitlySelected = true;
589
590 fwmark.permission = permission;
591 mask.permission = permission;
592
593 return modifyIpRule(add ? RTM_NEWRULE : RTM_DELRULE,
594 RULE_PRIORITY_EXPLICIT_NETWORK + subPriority, table, fwmark.intValue,
595 mask.intValue, IIF_LOOPBACK, OIF_NONE, uidStart, uidEnd);
596 }
597
598 // A rule to route traffic based on a chosen outgoing interface.
599 //
600 // Supports apps that use SO_BINDTODEVICE or IP_PKTINFO options and the kernel that already knows
601 // the outgoing interface (typically for link-local communications).
modifyOutputInterfaceRules(const char * interface,uint32_t table,Permission permission,uid_t uidStart,uid_t uidEnd,int32_t subPriority,bool add)602 [[nodiscard]] static int modifyOutputInterfaceRules(const char* interface, uint32_t table,
603 Permission permission, uid_t uidStart,
604 uid_t uidEnd, int32_t subPriority, bool add) {
605 Fwmark fwmark;
606 Fwmark mask;
607
608 fwmark.permission = permission;
609 mask.permission = permission;
610
611 // If this rule does not specify a UID range, then also add a corresponding high-priority rule
612 // for root. This covers kernel-originated packets, TEEd packets and any local daemons that open
613 // sockets as root.
614 if (uidStart == INVALID_UID && uidEnd == INVALID_UID) {
615 if (int ret = modifyIpRule(add ? RTM_NEWRULE : RTM_DELRULE, RULE_PRIORITY_VPN_OVERRIDE_OIF,
616 table, FWMARK_NONE, MASK_NONE, IIF_LOOPBACK, interface,
617 UID_ROOT, UID_ROOT)) {
618 return ret;
619 }
620 }
621
622 return modifyIpRule(add ? RTM_NEWRULE : RTM_DELRULE,
623 RULE_PRIORITY_OUTPUT_INTERFACE + subPriority, table, fwmark.intValue,
624 mask.intValue, IIF_LOOPBACK, interface, uidStart, uidEnd);
625 }
626
627 // A rule to route traffic based on the chosen network.
628 //
629 // This is for sockets that have not explicitly requested a particular network, but have been
630 // bound to one when they called connect(). This ensures that sockets connected on a particular
631 // network stay on that network even if the default network changes.
modifyImplicitNetworkRule(unsigned netId,uint32_t table,bool add)632 [[nodiscard]] static int modifyImplicitNetworkRule(unsigned netId, uint32_t table, bool add) {
633 Fwmark fwmark;
634 Fwmark mask;
635
636 fwmark.netId = netId;
637 mask.netId = FWMARK_NET_ID_MASK;
638
639 fwmark.explicitlySelected = false;
640 mask.explicitlySelected = true;
641
642 fwmark.permission = PERMISSION_NONE;
643 mask.permission = PERMISSION_NONE;
644
645 return modifyIpRule(add ? RTM_NEWRULE : RTM_DELRULE, RULE_PRIORITY_IMPLICIT_NETWORK, table,
646 fwmark.intValue, mask.intValue, IIF_LOOPBACK, OIF_NONE, INVALID_UID,
647 INVALID_UID);
648 }
649
modifyVpnLocalExclusionRule(bool add,const char * physicalInterface)650 int RouteController::modifyVpnLocalExclusionRule(bool add, const char* physicalInterface) {
651 uint32_t table = getRouteTableForInterface(physicalInterface, true /* local */);
652 if (table == RT_TABLE_UNSPEC) {
653 return -ESRCH;
654 }
655
656 Fwmark fwmark;
657 Fwmark mask;
658
659 fwmark.explicitlySelected = false;
660 mask.explicitlySelected = true;
661
662 fwmark.permission = PERMISSION_NONE;
663 mask.permission = PERMISSION_NONE;
664
665 return modifyIpRule(add ? RTM_NEWRULE : RTM_DELRULE, RULE_PRIORITY_LOCAL_ROUTES, table,
666 fwmark.intValue, mask.intValue, IIF_LOOPBACK, OIF_NONE, INVALID_UID,
667 INVALID_UID);
668 }
669
addFixedLocalRoutes(const char * interface)670 int RouteController::addFixedLocalRoutes(const char* interface) {
671 for (size_t i = 0; i < ARRAY_SIZE(V4_FIXED_LOCAL_PREFIXES); ++i) {
672 if (int ret = modifyRoute(RTM_NEWROUTE, NETLINK_ROUTE_CREATE_FLAGS, interface,
673 V4_FIXED_LOCAL_PREFIXES[i], nullptr /* nexthop */,
674 RouteController::INTERFACE, 0 /* mtu */, 0 /* priority */,
675 true /* isLocal */)) {
676 return ret;
677 }
678 }
679
680 return 0;
681 }
682
683 // A rule to enable split tunnel VPNs.
684 //
685 // If a packet with a VPN's netId doesn't find a route in the VPN's routing table, it's allowed to
686 // go over the default network, provided it has the permissions required by the default network.
modifyVpnFallthroughRule(uint16_t action,unsigned vpnNetId,const char * physicalInterface,Permission permission)687 int RouteController::modifyVpnFallthroughRule(uint16_t action, unsigned vpnNetId,
688 const char* physicalInterface,
689 Permission permission) {
690 uint32_t table = getRouteTableForInterface(physicalInterface, false /* local */);
691 if (table == RT_TABLE_UNSPEC) {
692 return -ESRCH;
693 }
694
695 Fwmark fwmark;
696 Fwmark mask;
697
698 fwmark.netId = vpnNetId;
699 mask.netId = FWMARK_NET_ID_MASK;
700
701 fwmark.permission = permission;
702 mask.permission = permission;
703
704 return modifyIpRule(action, RULE_PRIORITY_VPN_FALLTHROUGH, table, fwmark.intValue,
705 mask.intValue);
706 }
707
708 // Add rules to allow legacy routes added through the requestRouteToHost() API.
addLegacyRouteRules()709 [[nodiscard]] static int addLegacyRouteRules() {
710 Fwmark fwmark;
711 Fwmark mask;
712
713 fwmark.explicitlySelected = false;
714 mask.explicitlySelected = true;
715
716 // Rules to allow legacy routes to override the default network.
717 if (int ret = modifyIpRule(RTM_NEWRULE, RULE_PRIORITY_LEGACY_SYSTEM, ROUTE_TABLE_LEGACY_SYSTEM,
718 fwmark.intValue, mask.intValue)) {
719 return ret;
720 }
721 if (int ret = modifyIpRule(RTM_NEWRULE, RULE_PRIORITY_LEGACY_NETWORK,
722 ROUTE_TABLE_LEGACY_NETWORK, fwmark.intValue, mask.intValue)) {
723 return ret;
724 }
725
726 fwmark.permission = PERMISSION_SYSTEM;
727 mask.permission = PERMISSION_SYSTEM;
728
729 // A rule to allow legacy routes from system apps to override VPNs.
730 return modifyIpRule(RTM_NEWRULE, RULE_PRIORITY_VPN_OVERRIDE_SYSTEM, ROUTE_TABLE_LEGACY_SYSTEM,
731 fwmark.intValue, mask.intValue);
732 }
733
734 // Add rules to lookup the local network when specified explicitly or otherwise.
addLocalNetworkRules(unsigned localNetId)735 [[nodiscard]] static int addLocalNetworkRules(unsigned localNetId) {
736 if (int ret = modifyExplicitNetworkRule(localNetId, ROUTE_TABLE_LOCAL_NETWORK, PERMISSION_NONE,
737 INVALID_UID, INVALID_UID,
738 UidRanges::SUB_PRIORITY_HIGHEST, ACTION_ADD)) {
739 return ret;
740 }
741
742 Fwmark fwmark;
743 Fwmark mask;
744
745 fwmark.explicitlySelected = false;
746 mask.explicitlySelected = true;
747
748 return modifyIpRule(RTM_NEWRULE, RULE_PRIORITY_LOCAL_NETWORK, ROUTE_TABLE_LOCAL_NETWORK,
749 fwmark.intValue, mask.intValue);
750 }
751
752 /* static */
configureDummyNetwork()753 int RouteController::configureDummyNetwork() {
754 const char *interface = DummyNetwork::INTERFACE_NAME;
755 uint32_t table = getRouteTableForInterface(interface, false /* local */);
756 if (table == RT_TABLE_UNSPEC) {
757 // getRouteTableForInterface has already logged an error.
758 return -ESRCH;
759 }
760
761 ifc_init();
762 int ret = ifc_up(interface);
763 ifc_close();
764 if (ret) {
765 ALOGE("Can't bring up %s: %s", interface, strerror(errno));
766 return -errno;
767 }
768
769 if ((ret = modifyOutputInterfaceRules(interface, table, PERMISSION_NONE, INVALID_UID,
770 INVALID_UID, UidRanges::SUB_PRIORITY_HIGHEST,
771 ACTION_ADD))) {
772 ALOGE("Can't create oif rules for %s: %s", interface, strerror(-ret));
773 return ret;
774 }
775
776 if ((ret = modifyIpRoute(RTM_NEWROUTE, NETLINK_ROUTE_CREATE_FLAGS, table, interface,
777 "0.0.0.0/0", nullptr, 0 /* mtu */, 0 /* priority */))) {
778 return ret;
779 }
780
781 if ((ret = modifyIpRoute(RTM_NEWROUTE, NETLINK_ROUTE_CREATE_FLAGS, table, interface, "::/0",
782 nullptr, 0 /* mtu */, 0 /* priority */))) {
783 return ret;
784 }
785
786 return 0;
787 }
788
789 // Add an explicit unreachable rule close to the end of the prioriy list to make it clear that
790 // relying on the kernel-default "from all lookup main" rule at priority 32766 is not intended
791 // behaviour. We do flush the kernel-default rules at startup, but having an explicit unreachable
792 // rule will hopefully make things even clearer.
addUnreachableRule()793 [[nodiscard]] static int addUnreachableRule() {
794 return modifyIpRule(RTM_NEWRULE, RULE_PRIORITY_UNREACHABLE, FR_ACT_UNREACHABLE, RT_TABLE_UNSPEC,
795 MARK_UNSET, MARK_UNSET, IIF_NONE, OIF_NONE, INVALID_UID, INVALID_UID);
796 }
797
modifyLocalNetwork(unsigned netId,const char * interface,bool add)798 [[nodiscard]] static int modifyLocalNetwork(unsigned netId, const char* interface, bool add) {
799 if (int ret = modifyIncomingPacketMark(netId, interface, PERMISSION_NONE, add)) {
800 return ret;
801 }
802 maybeModifyQdiscClsact(interface, add);
803 return modifyOutputInterfaceRules(interface, ROUTE_TABLE_LOCAL_NETWORK, PERMISSION_NONE,
804 INVALID_UID, INVALID_UID, UidRanges::SUB_PRIORITY_HIGHEST,
805 add);
806 }
807
modifyUidNetworkRule(unsigned netId,uint32_t table,uid_t uidStart,uid_t uidEnd,int32_t subPriority,bool add,bool explicitSelect)808 [[nodiscard]] static int modifyUidNetworkRule(unsigned netId, uint32_t table, uid_t uidStart,
809 uid_t uidEnd, int32_t subPriority, bool add,
810 bool explicitSelect) {
811 if ((uidStart == INVALID_UID) || (uidEnd == INVALID_UID)) {
812 ALOGE("modifyUidNetworkRule, invalid UIDs (%u, %u)", uidStart, uidEnd);
813 return -EUSERS;
814 }
815
816 Fwmark fwmark;
817 Fwmark mask;
818
819 fwmark.netId = netId;
820 mask.netId = FWMARK_NET_ID_MASK;
821
822 fwmark.explicitlySelected = explicitSelect;
823 mask.explicitlySelected = true;
824
825 // Access to this network is controlled by UID rules, not permission bits.
826 fwmark.permission = PERMISSION_NONE;
827 mask.permission = PERMISSION_NONE;
828
829 return modifyIpRule(add ? RTM_NEWRULE : RTM_DELRULE,
830 explicitSelect ? (RULE_PRIORITY_UID_EXPLICIT_NETWORK + subPriority)
831 : (RULE_PRIORITY_UID_IMPLICIT_NETWORK + subPriority),
832 table, fwmark.intValue, mask.intValue, IIF_LOOPBACK, OIF_NONE, uidStart,
833 uidEnd);
834 }
835
modifyUidDefaultNetworkRule(uint32_t table,uid_t uidStart,uid_t uidEnd,int32_t subPriority,bool add)836 [[nodiscard]] static int modifyUidDefaultNetworkRule(uint32_t table, uid_t uidStart, uid_t uidEnd,
837 int32_t subPriority, bool add) {
838 if ((uidStart == INVALID_UID) || (uidEnd == INVALID_UID)) {
839 ALOGE("modifyUidDefaultNetworkRule, invalid UIDs (%u, %u)", uidStart, uidEnd);
840 return -EUSERS;
841 }
842
843 Fwmark fwmark;
844 Fwmark mask;
845
846 fwmark.netId = NETID_UNSET;
847 mask.netId = FWMARK_NET_ID_MASK;
848
849 // Access to this network is controlled by UID rules, not permission bits.
850 fwmark.permission = PERMISSION_NONE;
851 mask.permission = PERMISSION_NONE;
852
853 return modifyIpRule(add ? RTM_NEWRULE : RTM_DELRULE,
854 RULE_PRIORITY_UID_DEFAULT_NETWORK + subPriority, table, fwmark.intValue,
855 mask.intValue, IIF_LOOPBACK, OIF_NONE, uidStart, uidEnd);
856 }
857
858 /* static */
modifyPhysicalNetwork(unsigned netId,const char * interface,const UidRangeMap & uidRangeMap,Permission permission,bool add,bool modifyNonUidBasedRules)859 int RouteController::modifyPhysicalNetwork(unsigned netId, const char* interface,
860 const UidRangeMap& uidRangeMap, Permission permission,
861 bool add, bool modifyNonUidBasedRules) {
862 uint32_t table = getRouteTableForInterface(interface, false /* local */);
863 if (table == RT_TABLE_UNSPEC) {
864 return -ESRCH;
865 }
866
867 for (const auto& [subPriority, uidRanges] : uidRangeMap) {
868 for (const UidRangeParcel& range : uidRanges.getRanges()) {
869 if (int ret = modifyUidNetworkRule(netId, table, range.start, range.stop, subPriority,
870 add, EXPLICIT)) {
871 return ret;
872 }
873 if (int ret = modifyUidNetworkRule(netId, table, range.start, range.stop, subPriority,
874 add, IMPLICIT)) {
875 return ret;
876 }
877 // SUB_PRIORITY_NO_DEFAULT is "special" and does not require a
878 // default network rule, see UidRanges.h.
879 if (subPriority != UidRanges::SUB_PRIORITY_NO_DEFAULT) {
880 if (int ret = modifyUidDefaultNetworkRule(table, range.start, range.stop,
881 subPriority, add)) {
882 return ret;
883 }
884
885 // Per-UID local network rules must always match per-app default network rules,
886 // because their purpose is to allow the UIDs to use the default network for
887 // local destinations within it.
888 if (int ret = modifyUidLocalNetworkRule(interface, range.start, range.stop, add)) {
889 return ret;
890 }
891 }
892 }
893 }
894
895 if (!modifyNonUidBasedRules) {
896 // we are done.
897 return 0;
898 }
899
900 if (int ret = modifyIncomingPacketMark(netId, interface, permission, add)) {
901 return ret;
902 }
903 if (int ret = modifyExplicitNetworkRule(netId, table, permission, INVALID_UID, INVALID_UID,
904 UidRanges::SUB_PRIORITY_HIGHEST, add)) {
905 return ret;
906 }
907 if (int ret = modifyOutputInterfaceRules(interface, table, permission, INVALID_UID, INVALID_UID,
908 UidRanges::SUB_PRIORITY_HIGHEST, add)) {
909 return ret;
910 }
911
912 // Only set implicit rules for networks that don't require permissions.
913 //
914 // This is so that if the default network ceases to be the default network and then switches
915 // from requiring no permissions to requiring permissions, we ensure that apps only use the
916 // network if they explicitly select it. This is consistent with destroySocketsLackingPermission
917 // - it closes all sockets on the network except sockets that are explicitly selected.
918 //
919 // The lack of this rule only affects the special case above, because:
920 // - The only cases where we implicitly bind a socket to a network are the default network and
921 // the bypassable VPN that applies to the app, if any.
922 // - This rule doesn't affect VPNs because they don't support permissions at all.
923 // - The default network doesn't require permissions. While we support doing this, the framework
924 // never does it (partly because we'd end up in the situation where we tell apps that there is
925 // a default network, but they can't use it).
926 // - If the network is still the default network, the presence or absence of this rule does not
927 // matter.
928 //
929 // Therefore, for the lack of this rule to affect a socket, the socket has to have been
930 // implicitly bound to a network because at the time of connect() it was the default, and that
931 // network must no longer be the default, and must now require permissions.
932 if (permission == PERMISSION_NONE) {
933 return modifyImplicitNetworkRule(netId, table, add);
934 }
935 return 0;
936 }
937
modifyUidLocalNetworkRule(const char * interface,uid_t uidStart,uid_t uidEnd,bool add)938 int RouteController::modifyUidLocalNetworkRule(const char* interface, uid_t uidStart, uid_t uidEnd,
939 bool add) {
940 uint32_t table = getRouteTableForInterface(interface, true /* local */);
941 if (table == RT_TABLE_UNSPEC) {
942 return -ESRCH;
943 }
944
945 if ((uidStart == INVALID_UID) || (uidEnd == INVALID_UID)) {
946 ALOGE("modifyUidLocalNetworkRule, invalid UIDs (%u, %u)", uidStart, uidEnd);
947 return -EUSERS;
948 }
949
950 Fwmark fwmark;
951 Fwmark mask;
952
953 fwmark.explicitlySelected = false;
954 mask.explicitlySelected = true;
955
956 // Access to this network is controlled by UID rules, not permission bits.
957 fwmark.permission = PERMISSION_NONE;
958 mask.permission = PERMISSION_NONE;
959
960 return modifyIpRule(add ? RTM_NEWRULE : RTM_DELRULE, RULE_PRIORITY_UID_LOCAL_ROUTES, table,
961 fwmark.intValue, mask.intValue, IIF_LOOPBACK, OIF_NONE, uidStart, uidEnd);
962 }
963
modifyUidUnreachableRule(unsigned netId,uid_t uidStart,uid_t uidEnd,int32_t subPriority,bool add,bool explicitSelect)964 [[nodiscard]] static int modifyUidUnreachableRule(unsigned netId, uid_t uidStart, uid_t uidEnd,
965 int32_t subPriority, bool add,
966 bool explicitSelect) {
967 if ((uidStart == INVALID_UID) || (uidEnd == INVALID_UID)) {
968 ALOGE("modifyUidUnreachableRule, invalid UIDs (%u, %u)", uidStart, uidEnd);
969 return -EUSERS;
970 }
971
972 Fwmark fwmark;
973 Fwmark mask;
974
975 fwmark.netId = netId;
976 mask.netId = FWMARK_NET_ID_MASK;
977
978 fwmark.explicitlySelected = explicitSelect;
979 mask.explicitlySelected = true;
980
981 // Access to this network is controlled by UID rules, not permission bits.
982 fwmark.permission = PERMISSION_NONE;
983 mask.permission = PERMISSION_NONE;
984
985 return modifyIpRule(add ? RTM_NEWRULE : RTM_DELRULE,
986 explicitSelect ? (RULE_PRIORITY_UID_EXPLICIT_NETWORK + subPriority)
987 : (RULE_PRIORITY_UID_IMPLICIT_NETWORK + subPriority),
988 FR_ACT_UNREACHABLE, RT_TABLE_UNSPEC, fwmark.intValue, mask.intValue,
989 IIF_LOOPBACK, OIF_NONE, uidStart, uidEnd);
990 }
991
modifyUidDefaultUnreachableRule(uid_t uidStart,uid_t uidEnd,int32_t subPriority,bool add)992 [[nodiscard]] static int modifyUidDefaultUnreachableRule(uid_t uidStart, uid_t uidEnd,
993 int32_t subPriority, bool add) {
994 if ((uidStart == INVALID_UID) || (uidEnd == INVALID_UID)) {
995 ALOGE("modifyUidDefaultUnreachableRule, invalid UIDs (%u, %u)", uidStart, uidEnd);
996 return -EUSERS;
997 }
998
999 Fwmark fwmark;
1000 Fwmark mask;
1001
1002 fwmark.netId = NETID_UNSET;
1003 mask.netId = FWMARK_NET_ID_MASK;
1004
1005 // Access to this network is controlled by UID rules, not permission bits.
1006 fwmark.permission = PERMISSION_NONE;
1007 mask.permission = PERMISSION_NONE;
1008
1009 return modifyIpRule(add ? RTM_NEWRULE : RTM_DELRULE,
1010 RULE_PRIORITY_UID_DEFAULT_UNREACHABLE + subPriority, FR_ACT_UNREACHABLE,
1011 RT_TABLE_UNSPEC, fwmark.intValue, mask.intValue, IIF_LOOPBACK, OIF_NONE,
1012 uidStart, uidEnd);
1013 }
1014
modifyUnreachableNetwork(unsigned netId,const UidRangeMap & uidRangeMap,bool add)1015 int RouteController::modifyUnreachableNetwork(unsigned netId, const UidRangeMap& uidRangeMap,
1016 bool add) {
1017 for (const auto& [subPriority, uidRanges] : uidRangeMap) {
1018 for (const UidRangeParcel& range : uidRanges.getRanges()) {
1019 if (int ret = modifyUidUnreachableRule(netId, range.start, range.stop, subPriority, add,
1020 EXPLICIT)) {
1021 return ret;
1022 }
1023 if (int ret = modifyUidUnreachableRule(netId, range.start, range.stop, subPriority, add,
1024 IMPLICIT)) {
1025 return ret;
1026 }
1027 if (int ret = modifyUidDefaultUnreachableRule(range.start, range.stop, subPriority,
1028 add)) {
1029 return ret;
1030 }
1031 }
1032 }
1033
1034 return 0;
1035 }
1036
modifyRejectNonSecureNetworkRule(const UidRanges & uidRanges,bool add)1037 [[nodiscard]] static int modifyRejectNonSecureNetworkRule(const UidRanges& uidRanges, bool add) {
1038 Fwmark fwmark;
1039 Fwmark mask;
1040 fwmark.protectedFromVpn = false;
1041 mask.protectedFromVpn = true;
1042
1043 for (const UidRangeParcel& range : uidRanges.getRanges()) {
1044 if (int ret = modifyIpRule(add ? RTM_NEWRULE : RTM_DELRULE, RULE_PRIORITY_PROHIBIT_NON_VPN,
1045 FR_ACT_PROHIBIT, RT_TABLE_UNSPEC, fwmark.intValue, mask.intValue,
1046 IIF_LOOPBACK, OIF_NONE, range.start, range.stop)) {
1047 return ret;
1048 }
1049 }
1050
1051 return 0;
1052 }
1053
modifyVirtualNetwork(unsigned netId,const char * interface,const UidRangeMap & uidRangeMap,bool secure,bool add,bool modifyNonUidBasedRules,bool excludeLocalRoutes)1054 int RouteController::modifyVirtualNetwork(unsigned netId, const char* interface,
1055 const UidRangeMap& uidRangeMap, bool secure, bool add,
1056 bool modifyNonUidBasedRules, bool excludeLocalRoutes) {
1057 uint32_t table = getRouteTableForInterface(interface, false /* false */);
1058 if (table == RT_TABLE_UNSPEC) {
1059 return -ESRCH;
1060 }
1061
1062 for (const auto& [subPriority, uidRanges] : uidRangeMap) {
1063 for (const UidRangeParcel& range : uidRanges.getRanges()) {
1064 if (int ret = modifyVpnUidRangeRule(table, range.start, range.stop, subPriority, secure,
1065 add, excludeLocalRoutes)) {
1066 return ret;
1067 }
1068 if (int ret = modifyExplicitNetworkRule(netId, table, PERMISSION_NONE, range.start,
1069 range.stop, subPriority, add)) {
1070 return ret;
1071 }
1072 if (int ret = modifyOutputInterfaceRules(interface, table, PERMISSION_NONE, range.start,
1073 range.stop, subPriority, add)) {
1074 return ret;
1075 }
1076 }
1077 }
1078
1079 if (modifyNonUidBasedRules) {
1080 if (int ret = modifyIncomingPacketMark(netId, interface, PERMISSION_NONE, add)) {
1081 return ret;
1082 }
1083 if (int ret = modifyVpnOutputToLocalRule(interface, add)) {
1084 return ret;
1085 }
1086 if (int ret =
1087 modifyVpnSystemPermissionRule(netId, table, secure, add, excludeLocalRoutes)) {
1088 return ret;
1089 }
1090 return modifyExplicitNetworkRule(netId, table, PERMISSION_NONE, UID_ROOT, UID_ROOT,
1091 UidRanges::SUB_PRIORITY_HIGHEST, add);
1092 }
1093
1094 return 0;
1095 }
1096
modifyDefaultNetwork(uint16_t action,const char * interface,Permission permission)1097 int RouteController::modifyDefaultNetwork(uint16_t action, const char* interface,
1098 Permission permission) {
1099 uint32_t table = getRouteTableForInterface(interface, false /* local */);
1100 if (table == RT_TABLE_UNSPEC) {
1101 return -ESRCH;
1102 }
1103
1104 Fwmark fwmark;
1105 Fwmark mask;
1106
1107 fwmark.netId = NETID_UNSET;
1108 mask.netId = FWMARK_NET_ID_MASK;
1109
1110 fwmark.permission = permission;
1111 mask.permission = permission;
1112
1113 return modifyIpRule(action, RULE_PRIORITY_DEFAULT_NETWORK, table, fwmark.intValue,
1114 mask.intValue, IIF_LOOPBACK, OIF_NONE, INVALID_UID, INVALID_UID);
1115 }
1116
modifyTetheredNetwork(uint16_t action,const char * inputInterface,const char * outputInterface)1117 int RouteController::modifyTetheredNetwork(uint16_t action, const char* inputInterface,
1118 const char* outputInterface) {
1119 uint32_t table = getRouteTableForInterface(outputInterface, false /* local */);
1120 if (table == RT_TABLE_UNSPEC) {
1121 return -ESRCH;
1122 }
1123
1124 return modifyIpRule(action, RULE_PRIORITY_TETHERING, table, MARK_UNSET, MARK_UNSET,
1125 inputInterface, OIF_NONE, INVALID_UID, INVALID_UID);
1126 }
1127
1128 // Adds or removes an IPv4 or IPv6 route to the specified table.
1129 // Returns 0 on success or negative errno on failure.
modifyRoute(uint16_t action,uint16_t flags,const char * interface,const char * destination,const char * nexthop,TableType tableType,int mtu,int priority,bool isLocal)1130 int RouteController::modifyRoute(uint16_t action, uint16_t flags, const char* interface,
1131 const char* destination, const char* nexthop, TableType tableType,
1132 int mtu, int priority, bool isLocal) {
1133 uint32_t table;
1134 switch (tableType) {
1135 case RouteController::INTERFACE: {
1136 table = getRouteTableForInterface(interface, isLocal);
1137 if (table == RT_TABLE_UNSPEC) {
1138 return -ESRCH;
1139 }
1140 break;
1141 }
1142 case RouteController::LOCAL_NETWORK: {
1143 table = ROUTE_TABLE_LOCAL_NETWORK;
1144 break;
1145 }
1146 case RouteController::LEGACY_NETWORK: {
1147 table = ROUTE_TABLE_LEGACY_NETWORK;
1148 break;
1149 }
1150 case RouteController::LEGACY_SYSTEM: {
1151 table = ROUTE_TABLE_LEGACY_SYSTEM;
1152 break;
1153 }
1154 }
1155
1156 int ret = modifyIpRoute(action, flags, table, interface, destination, nexthop, mtu, priority);
1157 // Trying to add a route that already exists shouldn't cause an error.
1158 if (ret && !(action == RTM_NEWROUTE && ret == -EEXIST)) {
1159 return ret;
1160 }
1161
1162 return 0;
1163 }
1164
maybeModifyQdiscClsact(const char * interface,bool add)1165 static void maybeModifyQdiscClsact(const char* interface, bool add) {
1166 // The clsact attaching of v4- tun interface is triggered by ClatdController::maybeStartBpf
1167 // because the clat is started before the v4- interface is added to the network and the
1168 // clat startup needs to add {in, e}gress filters.
1169 // TODO: remove this workaround once v4- tun interface clsact attaching is moved out from
1170 // ClatdController::maybeStartBpf.
1171 if (StartsWith(interface, "v4-") && add) return;
1172
1173 // The interface may have already gone away in the delete case.
1174 uint32_t ifindex = RouteController::ifNameToIndexFunction(interface);
1175 if (!ifindex) {
1176 ALOGE("cannot find interface %s", interface);
1177 return;
1178 }
1179
1180 if (add) {
1181 if (int ret = tcQdiscAddDevClsact(ifindex)) {
1182 ALOGE("tcQdiscAddDevClsact(%d[%s]) failure: %s", ifindex, interface, strerror(-ret));
1183 return;
1184 }
1185 } else {
1186 if (int ret = tcQdiscDelDevClsact(ifindex)) {
1187 ALOGE("tcQdiscDelDevClsact(%d[%s]) failure: %s", ifindex, interface, strerror(-ret));
1188 return;
1189 }
1190 }
1191
1192 return;
1193 }
1194
clearTetheringRules(const char * inputInterface)1195 [[nodiscard]] static int clearTetheringRules(const char* inputInterface) {
1196 int ret = 0;
1197 while (ret == 0) {
1198 ret = modifyIpRule(RTM_DELRULE, RULE_PRIORITY_TETHERING, 0, MARK_UNSET, MARK_UNSET,
1199 inputInterface, OIF_NONE, INVALID_UID, INVALID_UID);
1200 }
1201
1202 if (ret == -ENOENT) {
1203 return 0;
1204 } else {
1205 return ret;
1206 }
1207 }
1208
getRulePriority(const nlmsghdr * nlh)1209 uint32_t getRulePriority(const nlmsghdr *nlh) {
1210 return getRtmU32Attribute(nlh, FRA_PRIORITY);
1211 }
1212
getRouteTable(const nlmsghdr * nlh)1213 uint32_t getRouteTable(const nlmsghdr *nlh) {
1214 return getRtmU32Attribute(nlh, RTA_TABLE);
1215 }
1216
flushRules()1217 [[nodiscard]] static int flushRules() {
1218 NetlinkDumpFilter shouldDelete = [] (nlmsghdr *nlh) {
1219 // Don't touch rules at priority 0 because by default they are used for local input.
1220 return getRulePriority(nlh) != 0;
1221 };
1222 return rtNetlinkFlush(RTM_GETRULE, RTM_DELRULE, "rules", shouldDelete);
1223 }
1224
flushRoutes(uint32_t table)1225 int RouteController::flushRoutes(uint32_t table) {
1226 NetlinkDumpFilter shouldDelete = [table] (nlmsghdr *nlh) {
1227 return getRouteTable(nlh) == table;
1228 };
1229
1230 return rtNetlinkFlush(RTM_GETROUTE, RTM_DELROUTE, "routes", shouldDelete);
1231 }
1232
flushRoutes(const char * interface)1233 int RouteController::flushRoutes(const char* interface) {
1234 // Try to flush both local and global routing tables.
1235 //
1236 // Flush local first because flush global routing tables may erase the sInterfaceToTable map.
1237 // Then the fake <iface>_local interface will be unable to find the index because the local
1238 // interface depends physical interface to find the correct index.
1239 int ret = flushRoutes(interface, true);
1240 ret |= flushRoutes(interface, false);
1241 return ret;
1242 }
1243
1244 // Returns 0 on success or negative errno on failure.
flushRoutes(const char * interface,bool local)1245 int RouteController::flushRoutes(const char* interface, bool local) {
1246 std::lock_guard lock(sInterfaceToTableLock);
1247
1248 uint32_t table = getRouteTableForInterfaceLocked(interface, local);
1249 if (table == RT_TABLE_UNSPEC) {
1250 return -ESRCH;
1251 }
1252
1253 int ret = flushRoutes(table);
1254
1255 // If we failed to flush routes, the caller may elect to keep this interface around, so keep
1256 // track of its name.
1257 // Skip erasing local fake interface since it does not exist in sInterfaceToTable.
1258 if (ret == 0 && !local) {
1259 sInterfaceToTable.erase(interface);
1260 }
1261
1262 return ret;
1263 }
1264
Init(unsigned localNetId)1265 int RouteController::Init(unsigned localNetId) {
1266 if (int ret = flushRules()) {
1267 return ret;
1268 }
1269 if (int ret = addLegacyRouteRules()) {
1270 return ret;
1271 }
1272 if (int ret = addLocalNetworkRules(localNetId)) {
1273 return ret;
1274 }
1275 if (int ret = addUnreachableRule()) {
1276 return ret;
1277 }
1278 // Don't complain if we can't add the dummy network, since not all devices support it.
1279 configureDummyNetwork();
1280
1281 updateTableNamesFile();
1282 return 0;
1283 }
1284
addInterfaceToLocalNetwork(unsigned netId,const char * interface)1285 int RouteController::addInterfaceToLocalNetwork(unsigned netId, const char* interface) {
1286 if (int ret = modifyLocalNetwork(netId, interface, ACTION_ADD)) {
1287 return ret;
1288 }
1289 std::lock_guard lock(sInterfaceToTableLock);
1290 sInterfaceToTable[interface] = ROUTE_TABLE_LOCAL_NETWORK;
1291 return 0;
1292 }
1293
removeInterfaceFromLocalNetwork(unsigned netId,const char * interface)1294 int RouteController::removeInterfaceFromLocalNetwork(unsigned netId, const char* interface) {
1295 if (int ret = modifyLocalNetwork(netId, interface, ACTION_DEL)) {
1296 return ret;
1297 }
1298 std::lock_guard lock(sInterfaceToTableLock);
1299 sInterfaceToTable.erase(interface);
1300 return 0;
1301 }
1302
addInterfaceToPhysicalNetwork(unsigned netId,const char * interface,Permission permission,const UidRangeMap & uidRangeMap)1303 int RouteController::addInterfaceToPhysicalNetwork(unsigned netId, const char* interface,
1304 Permission permission,
1305 const UidRangeMap& uidRangeMap) {
1306 if (int ret = modifyPhysicalNetwork(netId, interface, uidRangeMap, permission, ACTION_ADD,
1307 MODIFY_NON_UID_BASED_RULES)) {
1308 return ret;
1309 }
1310
1311 maybeModifyQdiscClsact(interface, ACTION_ADD);
1312 updateTableNamesFile();
1313
1314 if (int ret = addFixedLocalRoutes(interface)) {
1315 return ret;
1316 }
1317
1318 return 0;
1319 }
1320
removeInterfaceFromPhysicalNetwork(unsigned netId,const char * interface,Permission permission,const UidRangeMap & uidRangeMap)1321 int RouteController::removeInterfaceFromPhysicalNetwork(unsigned netId, const char* interface,
1322 Permission permission,
1323 const UidRangeMap& uidRangeMap) {
1324 if (int ret = modifyPhysicalNetwork(netId, interface, uidRangeMap, permission, ACTION_DEL,
1325 MODIFY_NON_UID_BASED_RULES)) {
1326 return ret;
1327 }
1328
1329 if (int ret = flushRoutes(interface)) {
1330 return ret;
1331 }
1332
1333 if (int ret = clearTetheringRules(interface)) {
1334 return ret;
1335 }
1336
1337 maybeModifyQdiscClsact(interface, ACTION_DEL);
1338 updateTableNamesFile();
1339 return 0;
1340 }
1341
addInterfaceToVirtualNetwork(unsigned netId,const char * interface,bool secure,const UidRangeMap & uidRangeMap,bool excludeLocalRoutes)1342 int RouteController::addInterfaceToVirtualNetwork(unsigned netId, const char* interface,
1343 bool secure, const UidRangeMap& uidRangeMap,
1344 bool excludeLocalRoutes) {
1345 if (int ret = modifyVirtualNetwork(netId, interface, uidRangeMap, secure, ACTION_ADD,
1346 MODIFY_NON_UID_BASED_RULES, excludeLocalRoutes)) {
1347 return ret;
1348 }
1349 updateTableNamesFile();
1350 return 0;
1351 }
1352
removeInterfaceFromVirtualNetwork(unsigned netId,const char * interface,bool secure,const UidRangeMap & uidRangeMap,bool excludeLocalRoutes)1353 int RouteController::removeInterfaceFromVirtualNetwork(unsigned netId, const char* interface,
1354 bool secure, const UidRangeMap& uidRangeMap,
1355 bool excludeLocalRoutes) {
1356 if (int ret = modifyVirtualNetwork(netId, interface, uidRangeMap, secure, ACTION_DEL,
1357 MODIFY_NON_UID_BASED_RULES, excludeLocalRoutes)) {
1358 return ret;
1359 }
1360 if (int ret = flushRoutes(interface)) {
1361 return ret;
1362 }
1363 updateTableNamesFile();
1364 return 0;
1365 }
1366
modifyPhysicalNetworkPermission(unsigned netId,const char * interface,Permission oldPermission,Permission newPermission)1367 int RouteController::modifyPhysicalNetworkPermission(unsigned netId, const char* interface,
1368 Permission oldPermission,
1369 Permission newPermission) {
1370 // Physical network rules either use permission bits or UIDs, but not both.
1371 // So permission changes don't affect any UID-based rules.
1372 UidRangeMap emptyUidRangeMap;
1373 // Add the new rules before deleting the old ones, to avoid race conditions.
1374 if (int ret = modifyPhysicalNetwork(netId, interface, emptyUidRangeMap, newPermission,
1375 ACTION_ADD, MODIFY_NON_UID_BASED_RULES)) {
1376 return ret;
1377 }
1378 return modifyPhysicalNetwork(netId, interface, emptyUidRangeMap, oldPermission, ACTION_DEL,
1379 MODIFY_NON_UID_BASED_RULES);
1380 }
1381
addUsersToRejectNonSecureNetworkRule(const UidRanges & uidRanges)1382 int RouteController::addUsersToRejectNonSecureNetworkRule(const UidRanges& uidRanges) {
1383 return modifyRejectNonSecureNetworkRule(uidRanges, true);
1384 }
1385
removeUsersFromRejectNonSecureNetworkRule(const UidRanges & uidRanges)1386 int RouteController::removeUsersFromRejectNonSecureNetworkRule(const UidRanges& uidRanges) {
1387 return modifyRejectNonSecureNetworkRule(uidRanges, false);
1388 }
1389
addUsersToVirtualNetwork(unsigned netId,const char * interface,bool secure,const UidRangeMap & uidRangeMap,bool excludeLocalRoutes)1390 int RouteController::addUsersToVirtualNetwork(unsigned netId, const char* interface, bool secure,
1391 const UidRangeMap& uidRangeMap,
1392 bool excludeLocalRoutes) {
1393 return modifyVirtualNetwork(netId, interface, uidRangeMap, secure, ACTION_ADD,
1394 !MODIFY_NON_UID_BASED_RULES, excludeLocalRoutes);
1395 }
1396
removeUsersFromVirtualNetwork(unsigned netId,const char * interface,bool secure,const UidRangeMap & uidRangeMap,bool excludeLocalRoutes)1397 int RouteController::removeUsersFromVirtualNetwork(unsigned netId, const char* interface,
1398 bool secure, const UidRangeMap& uidRangeMap,
1399 bool excludeLocalRoutes) {
1400 return modifyVirtualNetwork(netId, interface, uidRangeMap, secure, ACTION_DEL,
1401 !MODIFY_NON_UID_BASED_RULES, excludeLocalRoutes);
1402 }
1403
addInterfaceToDefaultNetwork(const char * interface,Permission permission)1404 int RouteController::addInterfaceToDefaultNetwork(const char* interface, Permission permission) {
1405 return modifyDefaultNetwork(RTM_NEWRULE, interface, permission);
1406 }
1407
removeInterfaceFromDefaultNetwork(const char * interface,Permission permission)1408 int RouteController::removeInterfaceFromDefaultNetwork(const char* interface,
1409 Permission permission) {
1410 return modifyDefaultNetwork(RTM_DELRULE, interface, permission);
1411 }
1412
isWithinIpv4LocalPrefix(const char * dst)1413 bool RouteController::isWithinIpv4LocalPrefix(const char* dst) {
1414 for (IPPrefix addr : V4_LOCAL_PREFIXES) {
1415 if (addr.contains(IPPrefix::forString(dst))) {
1416 return true;
1417 }
1418 }
1419 return false;
1420 }
1421
isLocalRoute(TableType tableType,const char * destination,const char * nexthop)1422 bool RouteController::isLocalRoute(TableType tableType, const char* destination,
1423 const char* nexthop) {
1424 IPPrefix prefix = IPPrefix::forString(destination);
1425 return nexthop == nullptr && tableType == RouteController::INTERFACE &&
1426 // Skip default route to prevent network being modeled as point-to-point interfaces.
1427 ((prefix.family() == AF_INET6 && prefix != IPPrefix::forString("::/0")) ||
1428 // Skip adding non-target local network range.
1429 (prefix.family() == AF_INET && isWithinIpv4LocalPrefix(destination)));
1430 }
1431
addRoute(const char * interface,const char * destination,const char * nexthop,TableType tableType,int mtu,int priority)1432 int RouteController::addRoute(const char* interface, const char* destination, const char* nexthop,
1433 TableType tableType, int mtu, int priority) {
1434 if (int ret = modifyRoute(RTM_NEWROUTE, NETLINK_ROUTE_CREATE_FLAGS, interface, destination,
1435 nexthop, tableType, mtu, priority, false /* isLocal */)) {
1436 return ret;
1437 }
1438
1439 if (isLocalRoute(tableType, destination, nexthop)) {
1440 return modifyRoute(RTM_NEWROUTE, NETLINK_ROUTE_CREATE_FLAGS, interface, destination,
1441 nexthop, tableType, mtu, priority, true /* isLocal */);
1442 }
1443
1444 return 0;
1445 }
1446
removeRoute(const char * interface,const char * destination,const char * nexthop,TableType tableType,int priority)1447 int RouteController::removeRoute(const char* interface, const char* destination,
1448 const char* nexthop, TableType tableType, int priority) {
1449 if (int ret = modifyRoute(RTM_DELROUTE, NETLINK_REQUEST_FLAGS, interface, destination, nexthop,
1450 tableType, 0 /* mtu */, priority, false /* isLocal */)) {
1451 return ret;
1452 }
1453
1454 if (isLocalRoute(tableType, destination, nexthop)) {
1455 return modifyRoute(RTM_DELROUTE, NETLINK_REQUEST_FLAGS, interface, destination, nexthop,
1456 tableType, 0 /* mtu */, priority, true /* isLocal */);
1457 }
1458 return 0;
1459 }
1460
updateRoute(const char * interface,const char * destination,const char * nexthop,TableType tableType,int mtu)1461 int RouteController::updateRoute(const char* interface, const char* destination,
1462 const char* nexthop, TableType tableType, int mtu) {
1463 if (int ret = modifyRoute(RTM_NEWROUTE, NETLINK_ROUTE_REPLACE_FLAGS, interface, destination,
1464 nexthop, tableType, mtu, 0 /* priority */, false /* isLocal */)) {
1465 return ret;
1466 }
1467
1468 if (isLocalRoute(tableType, destination, nexthop)) {
1469 return modifyRoute(RTM_NEWROUTE, NETLINK_ROUTE_REPLACE_FLAGS, interface, destination,
1470 nexthop, tableType, mtu, 0 /* priority */, true /* isLocal */);
1471 }
1472 return 0;
1473 }
1474
enableTethering(const char * inputInterface,const char * outputInterface)1475 int RouteController::enableTethering(const char* inputInterface, const char* outputInterface) {
1476 return modifyTetheredNetwork(RTM_NEWRULE, inputInterface, outputInterface);
1477 }
1478
disableTethering(const char * inputInterface,const char * outputInterface)1479 int RouteController::disableTethering(const char* inputInterface, const char* outputInterface) {
1480 return modifyTetheredNetwork(RTM_DELRULE, inputInterface, outputInterface);
1481 }
1482
addVirtualNetworkFallthrough(unsigned vpnNetId,const char * physicalInterface,Permission permission)1483 int RouteController::addVirtualNetworkFallthrough(unsigned vpnNetId, const char* physicalInterface,
1484 Permission permission) {
1485 if (int ret = modifyVpnFallthroughRule(RTM_NEWRULE, vpnNetId, physicalInterface, permission)) {
1486 return ret;
1487 }
1488
1489 return modifyVpnLocalExclusionRule(true /* add */, physicalInterface);
1490 }
1491
removeVirtualNetworkFallthrough(unsigned vpnNetId,const char * physicalInterface,Permission permission)1492 int RouteController::removeVirtualNetworkFallthrough(unsigned vpnNetId,
1493 const char* physicalInterface,
1494 Permission permission) {
1495 if (int ret = modifyVpnFallthroughRule(RTM_DELRULE, vpnNetId, physicalInterface, permission)) {
1496 return ret;
1497 }
1498
1499 return modifyVpnLocalExclusionRule(false /* add */, physicalInterface);
1500 }
1501
addUsersToPhysicalNetwork(unsigned netId,const char * interface,const UidRangeMap & uidRangeMap)1502 int RouteController::addUsersToPhysicalNetwork(unsigned netId, const char* interface,
1503 const UidRangeMap& uidRangeMap) {
1504 return modifyPhysicalNetwork(netId, interface, uidRangeMap, PERMISSION_NONE, ACTION_ADD,
1505 !MODIFY_NON_UID_BASED_RULES);
1506 }
1507
removeUsersFromPhysicalNetwork(unsigned netId,const char * interface,const UidRangeMap & uidRangeMap)1508 int RouteController::removeUsersFromPhysicalNetwork(unsigned netId, const char* interface,
1509 const UidRangeMap& uidRangeMap) {
1510 return modifyPhysicalNetwork(netId, interface, uidRangeMap, PERMISSION_NONE, ACTION_DEL,
1511 !MODIFY_NON_UID_BASED_RULES);
1512 }
1513
addUsersToUnreachableNetwork(unsigned netId,const UidRangeMap & uidRangeMap)1514 int RouteController::addUsersToUnreachableNetwork(unsigned netId, const UidRangeMap& uidRangeMap) {
1515 return modifyUnreachableNetwork(netId, uidRangeMap, ACTION_ADD);
1516 }
1517
removeUsersFromUnreachableNetwork(unsigned netId,const UidRangeMap & uidRangeMap)1518 int RouteController::removeUsersFromUnreachableNetwork(unsigned netId,
1519 const UidRangeMap& uidRangeMap) {
1520 return modifyUnreachableNetwork(netId, uidRangeMap, ACTION_DEL);
1521 }
1522
1523 // Protects sInterfaceToTable.
1524 std::mutex RouteController::sInterfaceToTableLock;
1525 std::map<std::string, uint32_t> RouteController::sInterfaceToTable;
1526
1527 } // namespace android::net
1528