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