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