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