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 <sys/stat.h>
25
26 #include <private/android_filesystem_config.h>
27
28 #include <map>
29
30 #include "DummyNetwork.h"
31 #include "Fwmark.h"
32 #include "NetdConstants.h"
33 #include "NetlinkCommands.h"
34 #include "UidRanges.h"
35
36 #include "android-base/file.h"
37 #include <android-base/stringprintf.h>
38 #define LOG_TAG "Netd"
39 #include "log/log.h"
40 #include "logwrap/logwrap.h"
41 #include "netutils/ifc.h"
42 #include "resolv_netid.h"
43
44 using android::base::StringPrintf;
45 using android::base::WriteStringToFile;
46 using android::net::UidRange;
47
48 namespace android {
49 namespace net {
50
51 auto RouteController::iptablesRestoreCommandFunction = execIptablesRestoreCommand;
52
53 // BEGIN CONSTANTS --------------------------------------------------------------------------------
54
55 const uint32_t RULE_PRIORITY_VPN_OVERRIDE_SYSTEM = 10000;
56 const uint32_t RULE_PRIORITY_VPN_OVERRIDE_OIF = 10500;
57 const uint32_t RULE_PRIORITY_VPN_OUTPUT_TO_LOCAL = 11000;
58 const uint32_t RULE_PRIORITY_SECURE_VPN = 12000;
59 const uint32_t RULE_PRIORITY_PROHIBIT_NON_VPN = 12500;
60 const uint32_t RULE_PRIORITY_EXPLICIT_NETWORK = 13000;
61 const uint32_t RULE_PRIORITY_OUTPUT_INTERFACE = 14000;
62 const uint32_t RULE_PRIORITY_LEGACY_SYSTEM = 15000;
63 const uint32_t RULE_PRIORITY_LEGACY_NETWORK = 16000;
64 const uint32_t RULE_PRIORITY_LOCAL_NETWORK = 17000;
65 const uint32_t RULE_PRIORITY_TETHERING = 18000;
66 const uint32_t RULE_PRIORITY_IMPLICIT_NETWORK = 19000;
67 const uint32_t RULE_PRIORITY_BYPASSABLE_VPN = 20000;
68 const uint32_t RULE_PRIORITY_VPN_FALLTHROUGH = 21000;
69 const uint32_t RULE_PRIORITY_DEFAULT_NETWORK = 22000;
70 const uint32_t RULE_PRIORITY_DIRECTLY_CONNECTED = 23000;
71 const uint32_t RULE_PRIORITY_UNREACHABLE = 32000;
72
73 const uint32_t ROUTE_TABLE_LOCAL_NETWORK = 97;
74 const uint32_t ROUTE_TABLE_LEGACY_NETWORK = 98;
75 const uint32_t ROUTE_TABLE_LEGACY_SYSTEM = 99;
76
77 const char* const ROUTE_TABLE_NAME_LOCAL_NETWORK = "local_network";
78 const char* const ROUTE_TABLE_NAME_LEGACY_NETWORK = "legacy_network";
79 const char* const ROUTE_TABLE_NAME_LEGACY_SYSTEM = "legacy_system";
80
81 const char* const ROUTE_TABLE_NAME_LOCAL = "local";
82 const char* const ROUTE_TABLE_NAME_MAIN = "main";
83
84 // None of our routes specify priority, which causes them to have the default
85 // priority. For throw routes, we use a fixed priority of 100000. This is
86 // because we use throw routes either for maximum-length routes (/32 for IPv4,
87 // /128 for IPv6), which we never create with any other priority, or for
88 // purposely-low-priority default routes that should never match if there is
89 // any other route in the table.
90 uint32_t PRIO_THROW = 100000;
91
92 // These values are upstream, but not yet in our headers.
93 // TODO: delete these definitions when updating the headers.
94 const uint16_t FRA_UID_RANGE = 20;
95 struct fib_rule_uid_range {
96 __u32 start;
97 __u32 end;
98 };
99
100 const uint8_t AF_FAMILIES[] = {AF_INET, AF_INET6};
101
102 const uid_t UID_ROOT = 0;
103 const char* const IIF_LOOPBACK = "lo";
104 const char* const IIF_NONE = NULL;
105 const char* const OIF_NONE = NULL;
106 const bool ACTION_ADD = true;
107 const bool ACTION_DEL = false;
108 const bool MODIFY_NON_UID_BASED_RULES = true;
109
110 const char* const RT_TABLES_PATH = "/data/misc/net/rt_tables";
111 const mode_t RT_TABLES_MODE = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH; // mode 0644, rw-r--r--
112
113 // Avoids "non-constant-expression cannot be narrowed from type 'unsigned int' to 'unsigned short'"
114 // warnings when using RTA_LENGTH(x) inside static initializers (even when x is already uint16_t).
U16_RTA_LENGTH(uint16_t x)115 constexpr uint16_t U16_RTA_LENGTH(uint16_t x) {
116 return RTA_LENGTH(x);
117 }
118
119 // These are practically const, but can't be declared so, because they are used to initialize
120 // non-const pointers ("void* iov_base") in iovec arrays.
121 rtattr FRATTR_PRIORITY = { U16_RTA_LENGTH(sizeof(uint32_t)), FRA_PRIORITY };
122 rtattr FRATTR_TABLE = { U16_RTA_LENGTH(sizeof(uint32_t)), FRA_TABLE };
123 rtattr FRATTR_FWMARK = { U16_RTA_LENGTH(sizeof(uint32_t)), FRA_FWMARK };
124 rtattr FRATTR_FWMASK = { U16_RTA_LENGTH(sizeof(uint32_t)), FRA_FWMASK };
125 rtattr FRATTR_UID_RANGE = { U16_RTA_LENGTH(sizeof(fib_rule_uid_range)), FRA_UID_RANGE };
126
127 rtattr RTATTR_TABLE = { U16_RTA_LENGTH(sizeof(uint32_t)), RTA_TABLE };
128 rtattr RTATTR_OIF = { U16_RTA_LENGTH(sizeof(uint32_t)), RTA_OIF };
129 rtattr RTATTR_PRIO = { U16_RTA_LENGTH(sizeof(uint32_t)), RTA_PRIORITY };
130
131 uint8_t PADDING_BUFFER[RTA_ALIGNTO] = {0, 0, 0, 0};
132
133 // END CONSTANTS ----------------------------------------------------------------------------------
134
actionName(uint16_t action)135 const char *actionName(uint16_t action) {
136 static const char *ops[4] = {"adding", "deleting", "getting", "???"};
137 return ops[action % 4];
138 }
139
familyName(uint8_t family)140 const char *familyName(uint8_t family) {
141 switch (family) {
142 case AF_INET: return "IPv4";
143 case AF_INET6: return "IPv6";
144 default: return "???";
145 }
146 }
147
148 // No locks needed because RouteController is accessed only from one thread (in CommandListener).
149 std::map<std::string, uint32_t> interfaceToTable;
150
getRouteTableForInterface(const char * interface)151 uint32_t getRouteTableForInterface(const char* interface) {
152 uint32_t index = if_nametoindex(interface);
153 if (index) {
154 index += RouteController::ROUTE_TABLE_OFFSET_FROM_INDEX;
155 interfaceToTable[interface] = index;
156 return index;
157 }
158 // If the interface goes away if_nametoindex() will return 0 but we still need to know
159 // the index so we can remove the rules and routes.
160 auto iter = interfaceToTable.find(interface);
161 if (iter == interfaceToTable.end()) {
162 ALOGE("cannot find interface %s", interface);
163 return RT_TABLE_UNSPEC;
164 }
165 return iter->second;
166 }
167
addTableName(uint32_t table,const std::string & name,std::string * contents)168 void addTableName(uint32_t table, const std::string& name, std::string* contents) {
169 char tableString[UINT32_STRLEN];
170 snprintf(tableString, sizeof(tableString), "%u", table);
171 *contents += tableString;
172 *contents += " ";
173 *contents += name;
174 *contents += "\n";
175 }
176
177 // Doesn't return success/failure as the file is optional; it's okay if we fail to update it.
updateTableNamesFile()178 void updateTableNamesFile() {
179 std::string contents;
180
181 addTableName(RT_TABLE_LOCAL, ROUTE_TABLE_NAME_LOCAL, &contents);
182 addTableName(RT_TABLE_MAIN, ROUTE_TABLE_NAME_MAIN, &contents);
183
184 addTableName(ROUTE_TABLE_LOCAL_NETWORK, ROUTE_TABLE_NAME_LOCAL_NETWORK, &contents);
185 addTableName(ROUTE_TABLE_LEGACY_NETWORK, ROUTE_TABLE_NAME_LEGACY_NETWORK, &contents);
186 addTableName(ROUTE_TABLE_LEGACY_SYSTEM, ROUTE_TABLE_NAME_LEGACY_SYSTEM, &contents);
187
188 for (const auto& entry : interfaceToTable) {
189 addTableName(entry.second, entry.first, &contents);
190 }
191
192 if (!WriteStringToFile(contents, RT_TABLES_PATH, RT_TABLES_MODE, AID_SYSTEM, AID_WIFI)) {
193 ALOGE("failed to write to %s (%s)", RT_TABLES_PATH, strerror(errno));
194 return;
195 }
196 }
197
198 // Returns 0 on success or negative errno on failure.
padInterfaceName(const char * input,char * name,size_t * length,uint16_t * padding)199 int padInterfaceName(const char* input, char* name, size_t* length, uint16_t* padding) {
200 if (!input) {
201 *length = 0;
202 *padding = 0;
203 return 0;
204 }
205 *length = strlcpy(name, input, IFNAMSIZ) + 1;
206 if (*length > IFNAMSIZ) {
207 ALOGE("interface name too long (%zu > %u)", *length, IFNAMSIZ);
208 return -ENAMETOOLONG;
209 }
210 *padding = RTA_SPACE(*length) - RTA_LENGTH(*length);
211 return 0;
212 }
213
214 // Adds or removes a routing rule for IPv4 and IPv6.
215 //
216 // + If |table| is non-zero, the rule points at the specified routing table. Otherwise, the table is
217 // unspecified. An unspecified table is not allowed when creating an FR_ACT_TO_TBL rule.
218 // + If |mask| is non-zero, the rule matches the specified fwmark and mask. Otherwise, |fwmark| is
219 // ignored.
220 // + If |iif| is non-NULL, the rule matches the specified incoming interface.
221 // + If |oif| is non-NULL, the rule matches the specified outgoing interface.
222 // + If |uidStart| and |uidEnd| are not INVALID_UID, the rule matches packets from UIDs in that
223 // range (inclusive). Otherwise, the rule matches packets from all UIDs.
224 //
225 // Returns 0 on success or negative errno on failure.
modifyIpRule(uint16_t action,uint32_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)226 WARN_UNUSED_RESULT int modifyIpRule(uint16_t action, uint32_t priority, uint8_t ruleType,
227 uint32_t table, uint32_t fwmark, uint32_t mask, const char* iif,
228 const char* oif, uid_t uidStart, uid_t uidEnd) {
229 // Ensure that if you set a bit in the fwmark, it's not being ignored by the mask.
230 if (fwmark & ~mask) {
231 ALOGE("mask 0x%x does not select all the bits set in fwmark 0x%x", mask, fwmark);
232 return -ERANGE;
233 }
234
235 // Interface names must include exactly one terminating NULL and be properly padded, or older
236 // kernels will refuse to delete rules.
237 char iifName[IFNAMSIZ], oifName[IFNAMSIZ];
238 size_t iifLength, oifLength;
239 uint16_t iifPadding, oifPadding;
240 if (int ret = padInterfaceName(iif, iifName, &iifLength, &iifPadding)) {
241 return ret;
242 }
243 if (int ret = padInterfaceName(oif, oifName, &oifLength, &oifPadding)) {
244 return ret;
245 }
246
247 // Either both start and end UID must be specified, or neither.
248 if ((uidStart == INVALID_UID) != (uidEnd == INVALID_UID)) {
249 ALOGE("incompatible start and end UIDs (%u vs %u)", uidStart, uidEnd);
250 return -EUSERS;
251 }
252
253 bool isUidRule = (uidStart != INVALID_UID);
254
255 // Assemble a rule request and put it in an array of iovec structures.
256 fib_rule_hdr rule = {
257 .action = ruleType,
258 // Note that here we're implicitly setting rule.table to 0. When we want to specify a
259 // non-zero table, we do this via the FRATTR_TABLE attribute.
260 };
261
262 // Don't ever create a rule that looks up table 0, because table 0 is the local table.
263 // It's OK to specify a table ID of 0 when deleting a rule, because that doesn't actually select
264 // table 0, it's a wildcard that matches anything.
265 if (table == RT_TABLE_UNSPEC && rule.action == FR_ACT_TO_TBL && action != RTM_DELRULE) {
266 ALOGE("RT_TABLE_UNSPEC only allowed when deleting rules");
267 return -ENOTUNIQ;
268 }
269
270 rtattr fraIifName = { U16_RTA_LENGTH(iifLength), FRA_IIFNAME };
271 rtattr fraOifName = { U16_RTA_LENGTH(oifLength), FRA_OIFNAME };
272 struct fib_rule_uid_range uidRange = { uidStart, uidEnd };
273
274 iovec iov[] = {
275 { NULL, 0 },
276 { &rule, sizeof(rule) },
277 { &FRATTR_PRIORITY, sizeof(FRATTR_PRIORITY) },
278 { &priority, sizeof(priority) },
279 { &FRATTR_TABLE, table != RT_TABLE_UNSPEC ? sizeof(FRATTR_TABLE) : 0 },
280 { &table, table != RT_TABLE_UNSPEC ? sizeof(table) : 0 },
281 { &FRATTR_FWMARK, mask ? sizeof(FRATTR_FWMARK) : 0 },
282 { &fwmark, mask ? sizeof(fwmark) : 0 },
283 { &FRATTR_FWMASK, mask ? sizeof(FRATTR_FWMASK) : 0 },
284 { &mask, mask ? sizeof(mask) : 0 },
285 { &FRATTR_UID_RANGE, isUidRule ? sizeof(FRATTR_UID_RANGE) : 0 },
286 { &uidRange, isUidRule ? sizeof(uidRange) : 0 },
287 { &fraIifName, iif != IIF_NONE ? sizeof(fraIifName) : 0 },
288 { iifName, iifLength },
289 { PADDING_BUFFER, iifPadding },
290 { &fraOifName, oif != OIF_NONE ? sizeof(fraOifName) : 0 },
291 { oifName, oifLength },
292 { PADDING_BUFFER, oifPadding },
293 };
294
295 uint16_t flags = (action == RTM_NEWRULE) ? NETLINK_CREATE_REQUEST_FLAGS : NETLINK_REQUEST_FLAGS;
296 for (size_t i = 0; i < ARRAY_SIZE(AF_FAMILIES); ++i) {
297 rule.family = AF_FAMILIES[i];
298 if (int ret = sendNetlinkRequest(action, flags, iov, ARRAY_SIZE(iov), nullptr)) {
299 if (!(action == RTM_DELRULE && ret == -ENOENT && priority == RULE_PRIORITY_TETHERING)) {
300 // Don't log when deleting a tethering rule that's not there. This matches the
301 // behaviour of clearTetheringRules, which ignores ENOENT in this case.
302 ALOGE("Error %s %s rule: %s", actionName(action), familyName(rule.family),
303 strerror(-ret));
304 }
305 return ret;
306 }
307 }
308
309 return 0;
310 }
311
modifyIpRule(uint16_t action,uint32_t priority,uint32_t table,uint32_t fwmark,uint32_t mask,const char * iif,const char * oif,uid_t uidStart,uid_t uidEnd)312 WARN_UNUSED_RESULT int modifyIpRule(uint16_t action, uint32_t priority, uint32_t table,
313 uint32_t fwmark, uint32_t mask, const char* iif,
314 const char* oif, uid_t uidStart, uid_t uidEnd) {
315 return modifyIpRule(action, priority, FR_ACT_TO_TBL, table, fwmark, mask, iif, oif, uidStart,
316 uidEnd);
317 }
318
modifyIpRule(uint16_t action,uint32_t priority,uint32_t table,uint32_t fwmark,uint32_t mask)319 WARN_UNUSED_RESULT int modifyIpRule(uint16_t action, uint32_t priority, uint32_t table,
320 uint32_t fwmark, uint32_t mask) {
321 return modifyIpRule(action, priority, table, fwmark, mask, IIF_NONE, OIF_NONE, INVALID_UID,
322 INVALID_UID);
323 }
324
325 // Adds or deletes an IPv4 or IPv6 route.
326 // Returns 0 on success or negative errno on failure.
modifyIpRoute(uint16_t action,uint32_t table,const char * interface,const char * destination,const char * nexthop)327 WARN_UNUSED_RESULT int modifyIpRoute(uint16_t action, uint32_t table, const char* interface,
328 const char* destination, const char* nexthop) {
329 // At least the destination must be non-null.
330 if (!destination) {
331 ALOGE("null destination");
332 return -EFAULT;
333 }
334
335 // Parse the prefix.
336 uint8_t rawAddress[sizeof(in6_addr)];
337 uint8_t family;
338 uint8_t prefixLength;
339 int rawLength = parsePrefix(destination, &family, rawAddress, sizeof(rawAddress),
340 &prefixLength);
341 if (rawLength < 0) {
342 ALOGE("parsePrefix failed for destination %s (%s)", destination, strerror(-rawLength));
343 return rawLength;
344 }
345
346 if (static_cast<size_t>(rawLength) > sizeof(rawAddress)) {
347 ALOGE("impossible! address too long (%d vs %zu)", rawLength, sizeof(rawAddress));
348 return -ENOBUFS; // Cannot happen; parsePrefix only supports IPv4 and IPv6.
349 }
350
351 uint8_t type = RTN_UNICAST;
352 uint32_t ifindex;
353 uint8_t rawNexthop[sizeof(in6_addr)];
354
355 if (nexthop && !strcmp(nexthop, "unreachable")) {
356 type = RTN_UNREACHABLE;
357 // 'interface' is likely non-NULL, as the caller (modifyRoute()) likely used it to lookup
358 // the table number. But it's an error to specify an interface ("dev ...") or a nexthop for
359 // unreachable routes, so nuke them. (IPv6 allows them to be specified; IPv4 doesn't.)
360 interface = OIF_NONE;
361 nexthop = NULL;
362 } else if (nexthop && !strcmp(nexthop, "throw")) {
363 type = RTN_THROW;
364 interface = OIF_NONE;
365 nexthop = NULL;
366 } else {
367 // If an interface was specified, find the ifindex.
368 if (interface != OIF_NONE) {
369 ifindex = if_nametoindex(interface);
370 if (!ifindex) {
371 ALOGE("cannot find interface %s", interface);
372 return -ENODEV;
373 }
374 }
375
376 // If a nexthop was specified, parse it as the same family as the prefix.
377 if (nexthop && inet_pton(family, nexthop, rawNexthop) <= 0) {
378 ALOGE("inet_pton failed for nexthop %s", nexthop);
379 return -EINVAL;
380 }
381 }
382
383 bool isDefaultThrowRoute = (type == RTN_THROW && prefixLength == 0);
384
385 // Assemble a rtmsg and put it in an array of iovec structures.
386 rtmsg route = {
387 .rtm_protocol = RTPROT_STATIC,
388 .rtm_type = type,
389 .rtm_family = family,
390 .rtm_dst_len = prefixLength,
391 .rtm_scope = static_cast<uint8_t>(nexthop ? RT_SCOPE_UNIVERSE : RT_SCOPE_LINK),
392 };
393
394 rtattr rtaDst = { U16_RTA_LENGTH(rawLength), RTA_DST };
395 rtattr rtaGateway = { U16_RTA_LENGTH(rawLength), RTA_GATEWAY };
396
397 iovec iov[] = {
398 { NULL, 0 },
399 { &route, sizeof(route) },
400 { &RTATTR_TABLE, sizeof(RTATTR_TABLE) },
401 { &table, sizeof(table) },
402 { &rtaDst, sizeof(rtaDst) },
403 { rawAddress, static_cast<size_t>(rawLength) },
404 { &RTATTR_OIF, interface != OIF_NONE ? sizeof(RTATTR_OIF) : 0 },
405 { &ifindex, interface != OIF_NONE ? sizeof(ifindex) : 0 },
406 { &rtaGateway, nexthop ? sizeof(rtaGateway) : 0 },
407 { rawNexthop, nexthop ? static_cast<size_t>(rawLength) : 0 },
408 { &RTATTR_PRIO, isDefaultThrowRoute ? sizeof(RTATTR_PRIO) : 0 },
409 { &PRIO_THROW, isDefaultThrowRoute ? sizeof(PRIO_THROW) : 0 },
410 };
411
412 uint16_t flags = (action == RTM_NEWROUTE) ? NETLINK_CREATE_REQUEST_FLAGS :
413 NETLINK_REQUEST_FLAGS;
414 int ret = sendNetlinkRequest(action, flags, iov, ARRAY_SIZE(iov), nullptr);
415 if (ret) {
416 ALOGE("Error %s route %s -> %s %s to table %u: %s",
417 actionName(action), destination, nexthop, interface, table, strerror(-ret));
418 }
419 return ret;
420 }
421
422 // An iptables rule to mark incoming packets on a network with the netId of the network.
423 //
424 // This is so that the kernel can:
425 // + Use the right fwmark for (and thus correctly route) replies (e.g.: TCP RST, ICMP errors, ping
426 // replies, SYN-ACKs, etc).
427 // + Mark sockets that accept connections from this interface so that the connection stays on the
428 // same interface.
modifyIncomingPacketMark(unsigned netId,const char * interface,Permission permission,bool add)429 WARN_UNUSED_RESULT int modifyIncomingPacketMark(unsigned netId, const char* interface,
430 Permission permission, bool add) {
431 Fwmark fwmark;
432
433 fwmark.netId = netId;
434 fwmark.explicitlySelected = true;
435 fwmark.protectedFromVpn = true;
436 fwmark.permission = permission;
437
438 std::string cmd = StringPrintf("%s INPUT -i %s -j MARK --set-mark 0x%x",
439 add ? "-A" : "-D", interface, fwmark.intValue);
440 if (RouteController::iptablesRestoreCommandFunction(V4V6, "mangle", cmd, nullptr) != 0) {
441 ALOGE("failed to change iptables rule that sets incoming packet mark");
442 return -EREMOTEIO;
443 }
444
445 return 0;
446 }
447
448 // A rule to route responses to the local network forwarded via the VPN.
449 //
450 // When a VPN is in effect, packets from the local network to upstream networks are forwarded into
451 // the VPN's tunnel interface. When the VPN forwards the responses, they emerge out of the tunnel.
modifyVpnOutputToLocalRule(const char * vpnInterface,bool add)452 WARN_UNUSED_RESULT int modifyVpnOutputToLocalRule(const char* vpnInterface, bool add) {
453 return modifyIpRule(add ? RTM_NEWRULE : RTM_DELRULE, RULE_PRIORITY_VPN_OUTPUT_TO_LOCAL,
454 ROUTE_TABLE_LOCAL_NETWORK, MARK_UNSET, MARK_UNSET, vpnInterface, OIF_NONE,
455 INVALID_UID, INVALID_UID);
456 }
457
458 // A rule to route all traffic from a given set of UIDs to go over the VPN.
459 //
460 // Notice that this rule doesn't use the netId. I.e., no matter what netId the user's socket may
461 // have, if they are subject to this VPN, their traffic has to go through it. Allows the traffic to
462 // bypass the VPN if the protectedFromVpn bit is set.
modifyVpnUidRangeRule(uint32_t table,uid_t uidStart,uid_t uidEnd,bool secure,bool add)463 WARN_UNUSED_RESULT int modifyVpnUidRangeRule(uint32_t table, uid_t uidStart, uid_t uidEnd,
464 bool secure, bool add) {
465 Fwmark fwmark;
466 Fwmark mask;
467
468 fwmark.protectedFromVpn = false;
469 mask.protectedFromVpn = true;
470
471 uint32_t priority;
472
473 if (secure) {
474 priority = RULE_PRIORITY_SECURE_VPN;
475 } else {
476 priority = RULE_PRIORITY_BYPASSABLE_VPN;
477
478 fwmark.explicitlySelected = false;
479 mask.explicitlySelected = true;
480 }
481
482 return modifyIpRule(add ? RTM_NEWRULE : RTM_DELRULE, priority, table, fwmark.intValue,
483 mask.intValue, IIF_LOOPBACK, OIF_NONE, uidStart, uidEnd);
484 }
485
486 // A rule to allow system apps to send traffic over this VPN even if they are not part of the target
487 // set of UIDs.
488 //
489 // This is needed for DnsProxyListener to correctly resolve a request for a user who is in the
490 // target set, but where the DnsProxyListener itself is not.
modifyVpnSystemPermissionRule(unsigned netId,uint32_t table,bool secure,bool add)491 WARN_UNUSED_RESULT int modifyVpnSystemPermissionRule(unsigned netId, uint32_t table, bool secure,
492 bool add) {
493 Fwmark fwmark;
494 Fwmark mask;
495
496 fwmark.netId = netId;
497 mask.netId = FWMARK_NET_ID_MASK;
498
499 fwmark.permission = PERMISSION_SYSTEM;
500 mask.permission = PERMISSION_SYSTEM;
501
502 uint32_t priority = secure ? RULE_PRIORITY_SECURE_VPN : RULE_PRIORITY_BYPASSABLE_VPN;
503
504 return modifyIpRule(add ? RTM_NEWRULE : RTM_DELRULE, priority, table, fwmark.intValue,
505 mask.intValue);
506 }
507
508 // A rule to route traffic based on an explicitly chosen network.
509 //
510 // Supports apps that use the multinetwork APIs to restrict their traffic to a network.
511 //
512 // Even though we check permissions at the time we set a netId into the fwmark of a socket, we need
513 // to check it again in the rules here, because a network's permissions may have been updated via
514 // modifyNetworkPermission().
modifyExplicitNetworkRule(unsigned netId,uint32_t table,Permission permission,uid_t uidStart,uid_t uidEnd,bool add)515 WARN_UNUSED_RESULT int modifyExplicitNetworkRule(unsigned netId, uint32_t table,
516 Permission permission, uid_t uidStart,
517 uid_t uidEnd, bool add) {
518 Fwmark fwmark;
519 Fwmark mask;
520
521 fwmark.netId = netId;
522 mask.netId = FWMARK_NET_ID_MASK;
523
524 fwmark.explicitlySelected = true;
525 mask.explicitlySelected = true;
526
527 fwmark.permission = permission;
528 mask.permission = permission;
529
530 return modifyIpRule(add ? RTM_NEWRULE : RTM_DELRULE, RULE_PRIORITY_EXPLICIT_NETWORK, table,
531 fwmark.intValue, mask.intValue, IIF_NONE, OIF_NONE, uidStart, uidEnd);
532 }
533
534 // A rule to route traffic based on a chosen outgoing interface.
535 //
536 // Supports apps that use SO_BINDTODEVICE or IP_PKTINFO options and the kernel that already knows
537 // the outgoing interface (typically for link-local communications).
modifyOutputInterfaceRules(const char * interface,uint32_t table,Permission permission,uid_t uidStart,uid_t uidEnd,bool add)538 WARN_UNUSED_RESULT int modifyOutputInterfaceRules(const char* interface, uint32_t table,
539 Permission permission, uid_t uidStart,
540 uid_t uidEnd, bool add) {
541 Fwmark fwmark;
542 Fwmark mask;
543
544 fwmark.permission = permission;
545 mask.permission = permission;
546
547 // If this rule does not specify a UID range, then also add a corresponding high-priority rule
548 // for UID. This covers forwarded packets and system daemons such as the tethering DHCP server.
549 if (uidStart == INVALID_UID && uidEnd == INVALID_UID) {
550 if (int ret = modifyIpRule(add ? RTM_NEWRULE : RTM_DELRULE, RULE_PRIORITY_VPN_OVERRIDE_OIF,
551 table, fwmark.intValue, mask.intValue, IIF_NONE, interface,
552 UID_ROOT, UID_ROOT)) {
553 return ret;
554 }
555 }
556
557 return modifyIpRule(add ? RTM_NEWRULE : RTM_DELRULE, RULE_PRIORITY_OUTPUT_INTERFACE, table,
558 fwmark.intValue, mask.intValue, IIF_NONE, interface, uidStart, uidEnd);
559 }
560
561 // A rule to route traffic based on the chosen network.
562 //
563 // This is for sockets that have not explicitly requested a particular network, but have been
564 // bound to one when they called connect(). This ensures that sockets connected on a particular
565 // network stay on that network even if the default network changes.
modifyImplicitNetworkRule(unsigned netId,uint32_t table,bool add)566 WARN_UNUSED_RESULT int modifyImplicitNetworkRule(unsigned netId, uint32_t table, bool add) {
567 Fwmark fwmark;
568 Fwmark mask;
569
570 fwmark.netId = netId;
571 mask.netId = FWMARK_NET_ID_MASK;
572
573 fwmark.explicitlySelected = false;
574 mask.explicitlySelected = true;
575
576 fwmark.permission = PERMISSION_NONE;
577 mask.permission = PERMISSION_NONE;
578
579 return modifyIpRule(add ? RTM_NEWRULE : RTM_DELRULE, RULE_PRIORITY_IMPLICIT_NETWORK, table,
580 fwmark.intValue, mask.intValue);
581 }
582
583 // A rule to enable split tunnel VPNs.
584 //
585 // If a packet with a VPN's netId doesn't find a route in the VPN's routing table, it's allowed to
586 // go over the default network, provided it wasn't explicitly restricted to the VPN and has the
587 // permissions required by the default network.
modifyVpnFallthroughRule(uint16_t action,unsigned vpnNetId,const char * physicalInterface,Permission permission)588 WARN_UNUSED_RESULT int modifyVpnFallthroughRule(uint16_t action, unsigned vpnNetId,
589 const char* physicalInterface,
590 Permission permission) {
591 uint32_t table = getRouteTableForInterface(physicalInterface);
592 if (table == RT_TABLE_UNSPEC) {
593 return -ESRCH;
594 }
595
596 Fwmark fwmark;
597 Fwmark mask;
598
599 fwmark.netId = vpnNetId;
600 mask.netId = FWMARK_NET_ID_MASK;
601
602 fwmark.explicitlySelected = false;
603 mask.explicitlySelected = true;
604
605 fwmark.permission = permission;
606 mask.permission = permission;
607
608 return modifyIpRule(action, RULE_PRIORITY_VPN_FALLTHROUGH, table, fwmark.intValue,
609 mask.intValue);
610 }
611
612 // Add rules to allow legacy routes added through the requestRouteToHost() API.
addLegacyRouteRules()613 WARN_UNUSED_RESULT int addLegacyRouteRules() {
614 Fwmark fwmark;
615 Fwmark mask;
616
617 fwmark.explicitlySelected = false;
618 mask.explicitlySelected = true;
619
620 // Rules to allow legacy routes to override the default network.
621 if (int ret = modifyIpRule(RTM_NEWRULE, RULE_PRIORITY_LEGACY_SYSTEM, ROUTE_TABLE_LEGACY_SYSTEM,
622 fwmark.intValue, mask.intValue)) {
623 return ret;
624 }
625 if (int ret = modifyIpRule(RTM_NEWRULE, RULE_PRIORITY_LEGACY_NETWORK,
626 ROUTE_TABLE_LEGACY_NETWORK, fwmark.intValue, mask.intValue)) {
627 return ret;
628 }
629
630 fwmark.permission = PERMISSION_SYSTEM;
631 mask.permission = PERMISSION_SYSTEM;
632
633 // A rule to allow legacy routes from system apps to override VPNs.
634 return modifyIpRule(RTM_NEWRULE, RULE_PRIORITY_VPN_OVERRIDE_SYSTEM, ROUTE_TABLE_LEGACY_SYSTEM,
635 fwmark.intValue, mask.intValue);
636 }
637
638 // Add rules to lookup the local network when specified explicitly or otherwise.
addLocalNetworkRules(unsigned localNetId)639 WARN_UNUSED_RESULT int addLocalNetworkRules(unsigned localNetId) {
640 if (int ret = modifyExplicitNetworkRule(localNetId, ROUTE_TABLE_LOCAL_NETWORK, PERMISSION_NONE,
641 INVALID_UID, INVALID_UID, ACTION_ADD)) {
642 return ret;
643 }
644
645 Fwmark fwmark;
646 Fwmark mask;
647
648 fwmark.explicitlySelected = false;
649 mask.explicitlySelected = true;
650
651 return modifyIpRule(RTM_NEWRULE, RULE_PRIORITY_LOCAL_NETWORK, ROUTE_TABLE_LOCAL_NETWORK,
652 fwmark.intValue, mask.intValue);
653 }
654
configureDummyNetwork()655 int configureDummyNetwork() {
656 const char *interface = DummyNetwork::INTERFACE_NAME;
657 uint32_t table = getRouteTableForInterface(interface);
658 if (table == RT_TABLE_UNSPEC) {
659 // getRouteTableForInterface has already looged an error.
660 return -ESRCH;
661 }
662
663 ifc_init();
664 int ret = ifc_up(interface);
665 ifc_close();
666 if (ret) {
667 ALOGE("Can't bring up %s: %s", interface, strerror(errno));
668 return -errno;
669 }
670
671 if ((ret = modifyOutputInterfaceRules(interface, table, PERMISSION_NONE,
672 INVALID_UID, INVALID_UID, ACTION_ADD))) {
673 ALOGE("Can't create oif rules for %s: %s", interface, strerror(-ret));
674 return ret;
675 }
676
677 if ((ret = modifyIpRoute(RTM_NEWROUTE, table, interface, "0.0.0.0/0", NULL))) {
678 return ret;
679 }
680
681 if ((ret = modifyIpRoute(RTM_NEWROUTE, table, interface, "::/0", NULL))) {
682 return ret;
683 }
684
685 return 0;
686 }
687
688 // Add a new rule to look up the 'main' table, with the same selectors as the "default network"
689 // rule, but with a lower priority. We will never create routes in the main table; it should only be
690 // used for directly-connected routes implicitly created by the kernel when adding IP addresses.
691 // This is necessary, for example, when adding a route through a directly-connected gateway: in
692 // order to add the route, there must already be a directly-connected route that covers the gateway.
addDirectlyConnectedRule()693 WARN_UNUSED_RESULT int addDirectlyConnectedRule() {
694 Fwmark fwmark;
695 Fwmark mask;
696
697 fwmark.netId = NETID_UNSET;
698 mask.netId = FWMARK_NET_ID_MASK;
699
700 return modifyIpRule(RTM_NEWRULE, RULE_PRIORITY_DIRECTLY_CONNECTED, RT_TABLE_MAIN,
701 fwmark.intValue, mask.intValue, IIF_NONE, OIF_NONE, UID_ROOT, UID_ROOT);
702 }
703
704 // Add an explicit unreachable rule close to the end of the prioriy list to make it clear that
705 // relying on the kernel-default "from all lookup main" rule at priority 32766 is not intended
706 // behaviour. We do flush the kernel-default rules at startup, but having an explicit unreachable
707 // rule will hopefully make things even clearer.
addUnreachableRule()708 WARN_UNUSED_RESULT int addUnreachableRule() {
709 return modifyIpRule(RTM_NEWRULE, RULE_PRIORITY_UNREACHABLE, FR_ACT_UNREACHABLE, RT_TABLE_UNSPEC,
710 MARK_UNSET, MARK_UNSET, IIF_NONE, OIF_NONE, INVALID_UID, INVALID_UID);
711 }
712
modifyLocalNetwork(unsigned netId,const char * interface,bool add)713 WARN_UNUSED_RESULT int modifyLocalNetwork(unsigned netId, const char* interface, bool add) {
714 if (int ret = modifyIncomingPacketMark(netId, interface, PERMISSION_NONE, add)) {
715 return ret;
716 }
717 return modifyOutputInterfaceRules(interface, ROUTE_TABLE_LOCAL_NETWORK, PERMISSION_NONE,
718 INVALID_UID, INVALID_UID, add);
719 }
720
modifyPhysicalNetwork(unsigned netId,const char * interface,Permission permission,bool add)721 WARN_UNUSED_RESULT int modifyPhysicalNetwork(unsigned netId, const char* interface,
722 Permission permission, bool add) {
723 uint32_t table = getRouteTableForInterface(interface);
724 if (table == RT_TABLE_UNSPEC) {
725 return -ESRCH;
726 }
727
728 if (int ret = modifyIncomingPacketMark(netId, interface, permission, add)) {
729 return ret;
730 }
731 if (int ret = modifyExplicitNetworkRule(netId, table, permission, INVALID_UID, INVALID_UID,
732 add)) {
733 return ret;
734 }
735 if (int ret = modifyOutputInterfaceRules(interface, table, permission, INVALID_UID, INVALID_UID,
736 add)) {
737 return ret;
738 }
739
740 // Only set implicit rules for networks that don't require permissions.
741 //
742 // This is so that if the default network ceases to be the default network and then switches
743 // from requiring no permissions to requiring permissions, we ensure that apps only use the
744 // network if they explicitly select it. This is consistent with destroySocketsLackingPermission
745 // - it closes all sockets on the network except sockets that are explicitly selected.
746 //
747 // The lack of this rule only affects the special case above, because:
748 // - The only cases where we implicitly bind a socket to a network are the default network and
749 // the bypassable VPN that applies to the app, if any.
750 // - This rule doesn't affect VPNs because they don't support permissions at all.
751 // - The default network doesn't require permissions. While we support doing this, the framework
752 // never does it (partly because we'd end up in the situation where we tell apps that there is
753 // a default network, but they can't use it).
754 // - If the network is still the default network, the presence or absence of this rule does not
755 // matter.
756 //
757 // Therefore, for the lack of this rule to affect a socket, the socket has to have been
758 // implicitly bound to a network because at the time of connect() it was the default, and that
759 // network must no longer be the default, and must now require permissions.
760 if (permission == PERMISSION_NONE) {
761 return modifyImplicitNetworkRule(netId, table, add);
762 }
763 return 0;
764 }
765
modifyRejectNonSecureNetworkRule(const UidRanges & uidRanges,bool add)766 WARN_UNUSED_RESULT int modifyRejectNonSecureNetworkRule(const UidRanges& uidRanges, bool add) {
767 Fwmark fwmark;
768 Fwmark mask;
769 fwmark.protectedFromVpn = false;
770 mask.protectedFromVpn = true;
771
772 for (const UidRange& range : uidRanges.getRanges()) {
773 if (int ret = modifyIpRule(add ? RTM_NEWRULE : RTM_DELRULE,
774 RULE_PRIORITY_PROHIBIT_NON_VPN, FR_ACT_PROHIBIT, RT_TABLE_UNSPEC,
775 fwmark.intValue, mask.intValue, IIF_LOOPBACK, OIF_NONE,
776 range.getStart(), range.getStop())) {
777 return ret;
778 }
779 }
780
781 return 0;
782 }
783
modifyVirtualNetwork(unsigned netId,const char * interface,const UidRanges & uidRanges,bool secure,bool add,bool modifyNonUidBasedRules)784 WARN_UNUSED_RESULT int modifyVirtualNetwork(unsigned netId, const char* interface,
785 const UidRanges& uidRanges, bool secure, bool add,
786 bool modifyNonUidBasedRules) {
787 uint32_t table = getRouteTableForInterface(interface);
788 if (table == RT_TABLE_UNSPEC) {
789 return -ESRCH;
790 }
791
792 for (const UidRange& range : uidRanges.getRanges()) {
793 if (int ret = modifyVpnUidRangeRule(table, range.getStart(), range.getStop(), secure, add))
794 {
795 return ret;
796 }
797 if (int ret = modifyExplicitNetworkRule(netId, table, PERMISSION_NONE, range.getStart(),
798 range.getStop(), add)) {
799 return ret;
800 }
801 if (int ret = modifyOutputInterfaceRules(interface, table, PERMISSION_NONE,
802 range.getStart(), range.getStop(), add)) {
803 return ret;
804 }
805 }
806
807 if (modifyNonUidBasedRules) {
808 if (int ret = modifyIncomingPacketMark(netId, interface, PERMISSION_NONE, add)) {
809 return ret;
810 }
811 if (int ret = modifyVpnOutputToLocalRule(interface, add)) {
812 return ret;
813 }
814 if (int ret = modifyVpnSystemPermissionRule(netId, table, secure, add)) {
815 return ret;
816 }
817 return modifyExplicitNetworkRule(netId, table, PERMISSION_NONE, UID_ROOT, UID_ROOT, add);
818 }
819
820 return 0;
821 }
822
modifyDefaultNetwork(uint16_t action,const char * interface,Permission permission)823 WARN_UNUSED_RESULT int modifyDefaultNetwork(uint16_t action, const char* interface,
824 Permission permission) {
825 uint32_t table = getRouteTableForInterface(interface);
826 if (table == RT_TABLE_UNSPEC) {
827 return -ESRCH;
828 }
829
830 Fwmark fwmark;
831 Fwmark mask;
832
833 fwmark.netId = NETID_UNSET;
834 mask.netId = FWMARK_NET_ID_MASK;
835
836 fwmark.permission = permission;
837 mask.permission = permission;
838
839 return modifyIpRule(action, RULE_PRIORITY_DEFAULT_NETWORK, table, fwmark.intValue,
840 mask.intValue);
841 }
842
modifyTetheredNetwork(uint16_t action,const char * inputInterface,const char * outputInterface)843 WARN_UNUSED_RESULT int modifyTetheredNetwork(uint16_t action, const char* inputInterface,
844 const char* outputInterface) {
845 uint32_t table = getRouteTableForInterface(outputInterface);
846 if (table == RT_TABLE_UNSPEC) {
847 return -ESRCH;
848 }
849
850 return modifyIpRule(action, RULE_PRIORITY_TETHERING, table, MARK_UNSET, MARK_UNSET,
851 inputInterface, OIF_NONE, INVALID_UID, INVALID_UID);
852 }
853
854 // Adds or removes an IPv4 or IPv6 route to the specified table and, if it's a directly-connected
855 // route, to the main table as well.
856 // Returns 0 on success or negative errno on failure.
modifyRoute(uint16_t action,const char * interface,const char * destination,const char * nexthop,RouteController::TableType tableType)857 WARN_UNUSED_RESULT int modifyRoute(uint16_t action, const char* interface, const char* destination,
858 const char* nexthop, RouteController::TableType tableType) {
859 uint32_t table;
860 switch (tableType) {
861 case RouteController::INTERFACE: {
862 table = getRouteTableForInterface(interface);
863 if (table == RT_TABLE_UNSPEC) {
864 return -ESRCH;
865 }
866 break;
867 }
868 case RouteController::LOCAL_NETWORK: {
869 table = ROUTE_TABLE_LOCAL_NETWORK;
870 break;
871 }
872 case RouteController::LEGACY_NETWORK: {
873 table = ROUTE_TABLE_LEGACY_NETWORK;
874 break;
875 }
876 case RouteController::LEGACY_SYSTEM: {
877 table = ROUTE_TABLE_LEGACY_SYSTEM;
878 break;
879 }
880 }
881
882 int ret = modifyIpRoute(action, table, interface, destination, nexthop);
883 // Trying to add a route that already exists shouldn't cause an error.
884 if (ret && !(action == RTM_NEWROUTE && ret == -EEXIST)) {
885 return ret;
886 }
887
888 return 0;
889 }
890
clearTetheringRules(const char * inputInterface)891 WARN_UNUSED_RESULT int clearTetheringRules(const char* inputInterface) {
892 int ret = 0;
893 while (ret == 0) {
894 ret = modifyIpRule(RTM_DELRULE, RULE_PRIORITY_TETHERING, 0, MARK_UNSET, MARK_UNSET,
895 inputInterface, OIF_NONE, INVALID_UID, INVALID_UID);
896 }
897
898 if (ret == -ENOENT) {
899 return 0;
900 } else {
901 return ret;
902 }
903 }
904
getRulePriority(const nlmsghdr * nlh)905 uint32_t getRulePriority(const nlmsghdr *nlh) {
906 return getRtmU32Attribute(nlh, FRA_PRIORITY);
907 }
908
getRouteTable(const nlmsghdr * nlh)909 uint32_t getRouteTable(const nlmsghdr *nlh) {
910 return getRtmU32Attribute(nlh, RTA_TABLE);
911 }
912
flushRules()913 WARN_UNUSED_RESULT int flushRules() {
914 NetlinkDumpFilter shouldDelete = [] (nlmsghdr *nlh) {
915 // Don't touch rules at priority 0 because by default they are used for local input.
916 return getRulePriority(nlh) != 0;
917 };
918 return rtNetlinkFlush(RTM_GETRULE, RTM_DELRULE, "rules", shouldDelete);
919 }
920
flushRoutes(uint32_t table)921 WARN_UNUSED_RESULT int flushRoutes(uint32_t table) {
922 NetlinkDumpFilter shouldDelete = [table] (nlmsghdr *nlh) {
923 return getRouteTable(nlh) == table;
924 };
925
926 return rtNetlinkFlush(RTM_GETROUTE, RTM_DELROUTE, "routes", shouldDelete);
927 }
928
929 // Returns 0 on success or negative errno on failure.
flushRoutes(const char * interface)930 WARN_UNUSED_RESULT int flushRoutes(const char* interface) {
931 uint32_t table = getRouteTableForInterface(interface);
932 if (table == RT_TABLE_UNSPEC) {
933 return -ESRCH;
934 }
935
936 int ret = flushRoutes(table);
937
938 // If we failed to flush routes, the caller may elect to keep this interface around, so keep
939 // track of its name.
940 if (ret == 0) {
941 interfaceToTable.erase(interface);
942 }
943
944 return ret;
945 }
946
Init(unsigned localNetId)947 int RouteController::Init(unsigned localNetId) {
948 if (int ret = flushRules()) {
949 return ret;
950 }
951 if (int ret = addLegacyRouteRules()) {
952 return ret;
953 }
954 if (int ret = addLocalNetworkRules(localNetId)) {
955 return ret;
956 }
957 if (int ret = addDirectlyConnectedRule()) {
958 return ret;
959 }
960 if (int ret = addUnreachableRule()) {
961 return ret;
962 }
963 // Don't complain if we can't add the dummy network, since not all devices support it.
964 configureDummyNetwork();
965
966 updateTableNamesFile();
967 return 0;
968 }
969
addInterfaceToLocalNetwork(unsigned netId,const char * interface)970 int RouteController::addInterfaceToLocalNetwork(unsigned netId, const char* interface) {
971 return modifyLocalNetwork(netId, interface, ACTION_ADD);
972 }
973
removeInterfaceFromLocalNetwork(unsigned netId,const char * interface)974 int RouteController::removeInterfaceFromLocalNetwork(unsigned netId, const char* interface) {
975 return modifyLocalNetwork(netId, interface, ACTION_DEL);
976 }
977
addInterfaceToPhysicalNetwork(unsigned netId,const char * interface,Permission permission)978 int RouteController::addInterfaceToPhysicalNetwork(unsigned netId, const char* interface,
979 Permission permission) {
980 if (int ret = modifyPhysicalNetwork(netId, interface, permission, ACTION_ADD)) {
981 return ret;
982 }
983 updateTableNamesFile();
984 return 0;
985 }
986
removeInterfaceFromPhysicalNetwork(unsigned netId,const char * interface,Permission permission)987 int RouteController::removeInterfaceFromPhysicalNetwork(unsigned netId, const char* interface,
988 Permission permission) {
989 if (int ret = modifyPhysicalNetwork(netId, interface, permission, ACTION_DEL)) {
990 return ret;
991 }
992 if (int ret = flushRoutes(interface)) {
993 return ret;
994 }
995 if (int ret = clearTetheringRules(interface)) {
996 return ret;
997 }
998 updateTableNamesFile();
999 return 0;
1000 }
1001
addInterfaceToVirtualNetwork(unsigned netId,const char * interface,bool secure,const UidRanges & uidRanges)1002 int RouteController::addInterfaceToVirtualNetwork(unsigned netId, const char* interface,
1003 bool secure, const UidRanges& uidRanges) {
1004 if (int ret = modifyVirtualNetwork(netId, interface, uidRanges, secure, ACTION_ADD,
1005 MODIFY_NON_UID_BASED_RULES)) {
1006 return ret;
1007 }
1008 updateTableNamesFile();
1009 return 0;
1010 }
1011
removeInterfaceFromVirtualNetwork(unsigned netId,const char * interface,bool secure,const UidRanges & uidRanges)1012 int RouteController::removeInterfaceFromVirtualNetwork(unsigned netId, const char* interface,
1013 bool secure, const UidRanges& uidRanges) {
1014 if (int ret = modifyVirtualNetwork(netId, interface, uidRanges, secure, ACTION_DEL,
1015 MODIFY_NON_UID_BASED_RULES)) {
1016 return ret;
1017 }
1018 if (int ret = flushRoutes(interface)) {
1019 return ret;
1020 }
1021 updateTableNamesFile();
1022 return 0;
1023 }
1024
modifyPhysicalNetworkPermission(unsigned netId,const char * interface,Permission oldPermission,Permission newPermission)1025 int RouteController::modifyPhysicalNetworkPermission(unsigned netId, const char* interface,
1026 Permission oldPermission,
1027 Permission newPermission) {
1028 // Add the new rules before deleting the old ones, to avoid race conditions.
1029 if (int ret = modifyPhysicalNetwork(netId, interface, newPermission, ACTION_ADD)) {
1030 return ret;
1031 }
1032 return modifyPhysicalNetwork(netId, interface, oldPermission, ACTION_DEL);
1033 }
1034
addUsersToRejectNonSecureNetworkRule(const UidRanges & uidRanges)1035 int RouteController::addUsersToRejectNonSecureNetworkRule(const UidRanges& uidRanges) {
1036 return modifyRejectNonSecureNetworkRule(uidRanges, true);
1037 }
1038
removeUsersFromRejectNonSecureNetworkRule(const UidRanges & uidRanges)1039 int RouteController::removeUsersFromRejectNonSecureNetworkRule(const UidRanges& uidRanges) {
1040 return modifyRejectNonSecureNetworkRule(uidRanges, false);
1041 }
1042
addUsersToVirtualNetwork(unsigned netId,const char * interface,bool secure,const UidRanges & uidRanges)1043 int RouteController::addUsersToVirtualNetwork(unsigned netId, const char* interface, bool secure,
1044 const UidRanges& uidRanges) {
1045 return modifyVirtualNetwork(netId, interface, uidRanges, secure, ACTION_ADD,
1046 !MODIFY_NON_UID_BASED_RULES);
1047 }
1048
removeUsersFromVirtualNetwork(unsigned netId,const char * interface,bool secure,const UidRanges & uidRanges)1049 int RouteController::removeUsersFromVirtualNetwork(unsigned netId, const char* interface,
1050 bool secure, const UidRanges& uidRanges) {
1051 return modifyVirtualNetwork(netId, interface, uidRanges, secure, ACTION_DEL,
1052 !MODIFY_NON_UID_BASED_RULES);
1053 }
1054
addInterfaceToDefaultNetwork(const char * interface,Permission permission)1055 int RouteController::addInterfaceToDefaultNetwork(const char* interface, Permission permission) {
1056 return modifyDefaultNetwork(RTM_NEWRULE, interface, permission);
1057 }
1058
removeInterfaceFromDefaultNetwork(const char * interface,Permission permission)1059 int RouteController::removeInterfaceFromDefaultNetwork(const char* interface,
1060 Permission permission) {
1061 return modifyDefaultNetwork(RTM_DELRULE, interface, permission);
1062 }
1063
addRoute(const char * interface,const char * destination,const char * nexthop,TableType tableType)1064 int RouteController::addRoute(const char* interface, const char* destination, const char* nexthop,
1065 TableType tableType) {
1066 return modifyRoute(RTM_NEWROUTE, interface, destination, nexthop, tableType);
1067 }
1068
removeRoute(const char * interface,const char * destination,const char * nexthop,TableType tableType)1069 int RouteController::removeRoute(const char* interface, const char* destination,
1070 const char* nexthop, TableType tableType) {
1071 return modifyRoute(RTM_DELROUTE, interface, destination, nexthop, tableType);
1072 }
1073
enableTethering(const char * inputInterface,const char * outputInterface)1074 int RouteController::enableTethering(const char* inputInterface, const char* outputInterface) {
1075 return modifyTetheredNetwork(RTM_NEWRULE, inputInterface, outputInterface);
1076 }
1077
disableTethering(const char * inputInterface,const char * outputInterface)1078 int RouteController::disableTethering(const char* inputInterface, const char* outputInterface) {
1079 return modifyTetheredNetwork(RTM_DELRULE, inputInterface, outputInterface);
1080 }
1081
addVirtualNetworkFallthrough(unsigned vpnNetId,const char * physicalInterface,Permission permission)1082 int RouteController::addVirtualNetworkFallthrough(unsigned vpnNetId, const char* physicalInterface,
1083 Permission permission) {
1084 return modifyVpnFallthroughRule(RTM_NEWRULE, vpnNetId, physicalInterface, permission);
1085 }
1086
removeVirtualNetworkFallthrough(unsigned vpnNetId,const char * physicalInterface,Permission permission)1087 int RouteController::removeVirtualNetworkFallthrough(unsigned vpnNetId,
1088 const char* physicalInterface,
1089 Permission permission) {
1090 return modifyVpnFallthroughRule(RTM_DELRULE, vpnNetId, physicalInterface, permission);
1091 }
1092
1093 } // namespace net
1094 } // namespace android
1095