blob: d2af9a375a2e9575f1dcdc52ff7024d6b03eaac5 [file] [log] [blame]
Sreeram Ramachandran5c181bf2014-04-07 14:10:04 -07001/*
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
Dan Albertaa1be2b2015-01-06 09:36:17 -080019#include <arpa/inet.h>
20#include <errno.h>
21#include <fcntl.h>
22#include <linux/fib_rules.h>
23#include <net/if.h>
Chiachang89e504e2022-05-12 05:21:20 +000024#include <netdutils/InternetAddresses.h>
Elliott Hughesbd378322015-02-04 13:25:14 -080025#include <private/android_filesystem_config.h>
Chiachang89e504e2022-05-12 05:21:20 +000026#include <sys/stat.h>
Elliott Hughesbd378322015-02-04 13:25:14 -080027
Dan Albertaa1be2b2015-01-06 09:36:17 -080028#include <map>
29
Lorenzo Colitti7035f222017-02-13 18:29:00 +090030#include "DummyNetwork.h"
Sreeram Ramachandran5c181bf2014-04-07 14:10:04 -070031#include "Fwmark.h"
Lorenzo Colittic1306ea2017-03-27 05:52:31 +090032#include "NetdConstants.h"
Lorenzo Colitti1ef549d2017-02-13 18:32:09 +090033#include "NetlinkCommands.h"
Patrick Rohr70d42502021-10-12 18:24:10 +020034#include "TcUtils.h"
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -070035
Bernie Innocenti189eb502018-10-01 23:10:18 +090036#include <android-base/file.h>
Lorenzo Colittic1306ea2017-03-27 05:52:31 +090037#include <android-base/stringprintf.h>
Hungming Chen7f725432020-02-07 17:47:23 +080038#include <android-base/strings.h>
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -070039#include "log/log.h"
Bernie Innocenti189eb502018-10-01 23:10:18 +090040#include "netid_client.h"
Lorenzo Colitti36679362015-02-25 10:26:19 +090041#include "netutils/ifc.h"
Sreeram Ramachandran5c181bf2014-04-07 14:10:04 -070042
Hungming Chen7f725432020-02-07 17:47:23 +080043using android::base::StartsWith;
Lorenzo Colittic1306ea2017-03-27 05:52:31 +090044using android::base::StringPrintf;
Dan Albert5407e142015-03-16 10:05:59 -070045using android::base::WriteStringToFile;
Chiachang89e504e2022-05-12 05:21:20 +000046using android::netdutils::IPPrefix;
Dan Albert5407e142015-03-16 10:05:59 -070047
Bernie Innocenti762dcf42019-06-14 19:52:49 +090048namespace android::net {
Lorenzo Colitti7035f222017-02-13 18:29:00 +090049
Lorenzo Colittic1306ea2017-03-27 05:52:31 +090050auto RouteController::iptablesRestoreCommandFunction = execIptablesRestoreCommand;
Chiachang Wangf79e3562022-01-15 13:31:04 +080051auto RouteController::ifNameToIndexFunction = if_nametoindex;
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -070052// BEGIN CONSTANTS --------------------------------------------------------------------------------
53
Sreeram Ramachandran87475a12014-07-15 16:20:28 -070054const uint32_t ROUTE_TABLE_LOCAL_NETWORK = 97;
Sreeram Ramachandran4acd34a2014-07-07 22:11:37 -070055const uint32_t ROUTE_TABLE_LEGACY_NETWORK = 98;
56const uint32_t ROUTE_TABLE_LEGACY_SYSTEM = 99;
57
Sreeram Ramachandran87475a12014-07-15 16:20:28 -070058const char* const ROUTE_TABLE_NAME_LOCAL_NETWORK = "local_network";
Sreeram Ramachandran4acd34a2014-07-07 22:11:37 -070059const char* const ROUTE_TABLE_NAME_LEGACY_NETWORK = "legacy_network";
60const char* const ROUTE_TABLE_NAME_LEGACY_SYSTEM = "legacy_system";
61
Sreeram Ramachandranbb40d512014-07-11 11:45:14 -070062const char* const ROUTE_TABLE_NAME_LOCAL = "local";
63const char* const ROUTE_TABLE_NAME_MAIN = "main";
64
Lorenzo Colittid78843e2017-03-27 05:52:31 +090065const char* const RouteController::LOCAL_MANGLE_INPUT = "routectrl_mangle_INPUT";
66
Chiachang3aa56612022-05-12 05:55:45 +000067const IPPrefix V4_LOCAL_ADDR[] = {
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
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -070075const uint8_t AF_FAMILIES[] = {AF_INET, AF_INET6};
76
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -070077const uid_t UID_ROOT = 0;
Lorenzo Colitti3093f562017-09-25 14:17:38 +090078const uint32_t FWMARK_NONE = 0;
79const uint32_t MASK_NONE = 0;
Lorenzo Colitti5ad4e982015-02-26 17:34:32 +090080const char* const IIF_LOOPBACK = "lo";
Yi Kongbdfd57e2018-07-25 13:26:10 -070081const char* const IIF_NONE = nullptr;
82const char* const OIF_NONE = nullptr;
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -070083const bool ACTION_ADD = true;
84const bool ACTION_DEL = false;
85const bool MODIFY_NON_UID_BASED_RULES = true;
86
Sreeram Ramachandranc7d804c2014-07-09 07:39:30 -070087const mode_t RT_TABLES_MODE = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH; // mode 0644, rw-r--r--
Sreeram Ramachandran4acd34a2014-07-07 22:11:37 -070088
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -070089// 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).
Bernie Innocenti762dcf42019-06-14 19:52:49 +090091static constexpr uint16_t U16_RTA_LENGTH(uint16_t x) {
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -070092 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.
Lorenzo Colitti2b078672016-12-16 18:45:03 +090097rtattr FRATTR_PRIORITY = { U16_RTA_LENGTH(sizeof(uint32_t)), FRA_PRIORITY };
98rtattr FRATTR_TABLE = { U16_RTA_LENGTH(sizeof(uint32_t)), FRA_TABLE };
99rtattr FRATTR_FWMARK = { U16_RTA_LENGTH(sizeof(uint32_t)), FRA_FWMARK };
100rtattr FRATTR_FWMASK = { U16_RTA_LENGTH(sizeof(uint32_t)), FRA_FWMASK };
Lorenzo Colitti2b078672016-12-16 18:45:03 +0900101rtattr FRATTR_UID_RANGE = { U16_RTA_LENGTH(sizeof(fib_rule_uid_range)), FRA_UID_RANGE };
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700102
Lorenzo Colitti2b078672016-12-16 18:45:03 +0900103rtattr RTATTR_TABLE = { U16_RTA_LENGTH(sizeof(uint32_t)), RTA_TABLE };
104rtattr RTATTR_OIF = { U16_RTA_LENGTH(sizeof(uint32_t)), RTA_OIF };
Lorenzo Colitti5e03a892017-09-08 11:31:59 +0900105rtattr RTATTR_PRIO = { U16_RTA_LENGTH(sizeof(uint32_t)), RTA_PRIORITY };
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700106
Tyler Wearfa94a272019-12-05 15:01:48 -0800107// One or more nested attributes in the RTA_METRICS attribute.
108rtattr RTATTRX_MTU = { U16_RTA_LENGTH(sizeof(uint32_t)), RTAX_MTU};
Lorenzo Colitti57d54682020-01-24 09:18:13 +0900109constexpr size_t RTATTRX_MTU_SIZE = RTA_SPACE(sizeof(uint32_t));
Tyler Wearfa94a272019-12-05 15:01:48 -0800110
111// The RTA_METRICS attribute itself.
Lorenzo Colitti57d54682020-01-24 09:18:13 +0900112constexpr size_t RTATTR_METRICS_SIZE = RTATTRX_MTU_SIZE;
Tyler Wearfa94a272019-12-05 15:01:48 -0800113rtattr RTATTR_METRICS = { U16_RTA_LENGTH(RTATTR_METRICS_SIZE), RTA_METRICS };
114
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700115uint8_t PADDING_BUFFER[RTA_ALIGNTO] = {0, 0, 0, 0};
116
Ken Chena2206ec2021-03-24 17:15:44 +0800117constexpr bool EXPLICIT = true;
118constexpr bool IMPLICIT = false;
119
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700120// END CONSTANTS ----------------------------------------------------------------------------------
121
Bernie Innocenti762dcf42019-06-14 19:52:49 +0900122static const char* actionName(uint16_t action) {
Lorenzo Colitti0b073fb2017-02-10 07:49:12 +0900123 static const char *ops[4] = {"adding", "deleting", "getting", "???"};
124 return ops[action % 4];
125}
126
Bernie Innocenti762dcf42019-06-14 19:52:49 +0900127static const char* familyName(uint8_t family) {
Lorenzo Colitti0b073fb2017-02-10 07:49:12 +0900128 switch (family) {
129 case AF_INET: return "IPv4";
130 case AF_INET6: return "IPv6";
131 default: return "???";
132 }
133}
134
Lorenzo Colitti3810c972021-01-06 11:44:02 +0900135static void maybeModifyQdiscClsact(const char* interface, bool add);
136
Chiachang Wangf79e3562022-01-15 13:31:04 +0800137static 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
Lorenzo Colitti107075a2017-10-30 19:24:46 +0900145// Caller must hold sInterfaceToTableLock.
Chiachang Wangf79e3562022-01-15 13:31:04 +0800146uint32_t RouteController::getRouteTableForInterfaceLocked(const char* interface, bool local) {
mtk137999f2913e2019-02-25 19:39:36 +0800147 // 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.
Chiachang Wangf79e3562022-01-15 13:31:04 +0800156 //
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"
Lorenzo Colitti02cb80a2017-10-30 19:21:06 +0900159 auto iter = sInterfaceToTable.find(interface);
mtk137999f2913e2019-02-25 19:39:36 +0800160 if (iter != sInterfaceToTable.end()) {
Chiachang Wangf79e3562022-01-15 13:31:04 +0800161 return getRouteTableIndexFromGlobalRouteTableIndex(iter->second, local);
mtk137999f2913e2019-02-25 19:39:36 +0800162 }
163
Chiachang Wangf79e3562022-01-15 13:31:04 +0800164 uint32_t index = RouteController::ifNameToIndexFunction(interface);
mtk137999f2913e2019-02-25 19:39:36 +0800165 if (index == 0) {
Lorenzo Colittib6dc40a2020-03-24 00:58:50 +0900166 ALOGE("cannot find interface %s: %s", interface, strerror(errno));
Sreeram Ramachandran4acd34a2014-07-07 22:11:37 -0700167 return RT_TABLE_UNSPEC;
168 }
mtk137999f2913e2019-02-25 19:39:36 +0800169 index += RouteController::ROUTE_TABLE_OFFSET_FROM_INDEX;
170 sInterfaceToTable[interface] = index;
Chiachang Wangf79e3562022-01-15 13:31:04 +0800171 return getRouteTableIndexFromGlobalRouteTableIndex(index, local);
Sreeram Ramachandran4acd34a2014-07-07 22:11:37 -0700172}
173
Rubin Xu6c00b612018-04-27 14:27:59 +0100174uint32_t RouteController::getIfIndex(const char* interface) {
Bernie Innocentiabf8a342018-08-10 15:17:16 +0900175 std::lock_guard lock(sInterfaceToTableLock);
Rubin Xu6c00b612018-04-27 14:27:59 +0100176
177 auto iter = sInterfaceToTable.find(interface);
178 if (iter == sInterfaceToTable.end()) {
179 ALOGE("getIfIndex: cannot find interface %s", interface);
180 return 0;
181 }
182
Lorenzo Colittib6dc40a2020-03-24 00:58:50 +0900183 // 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;
Rubin Xu6c00b612018-04-27 14:27:59 +0100194}
195
Chiachang Wangf79e3562022-01-15 13:31:04 +0800196uint32_t RouteController::getRouteTableForInterface(const char* interface, bool local) {
Bernie Innocentiabf8a342018-08-10 15:17:16 +0900197 std::lock_guard lock(sInterfaceToTableLock);
Chiachang Wangf79e3562022-01-15 13:31:04 +0800198 return getRouteTableForInterfaceLocked(interface, local);
Lorenzo Colitti107075a2017-10-30 19:24:46 +0900199}
200
Sreeram Ramachandran4acd34a2014-07-07 22:11:37 -0700201void 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.
Lorenzo Colitti02cb80a2017-10-30 19:21:06 +0900211void RouteController::updateTableNamesFile() {
Sreeram Ramachandran4acd34a2014-07-07 22:11:37 -0700212 std::string contents;
Sreeram Ramachandranbb40d512014-07-11 11:45:14 -0700213
214 addTableName(RT_TABLE_LOCAL, ROUTE_TABLE_NAME_LOCAL, &contents);
215 addTableName(RT_TABLE_MAIN, ROUTE_TABLE_NAME_MAIN, &contents);
216
Sreeram Ramachandran87475a12014-07-15 16:20:28 -0700217 addTableName(ROUTE_TABLE_LOCAL_NETWORK, ROUTE_TABLE_NAME_LOCAL_NETWORK, &contents);
Sreeram Ramachandran4acd34a2014-07-07 22:11:37 -0700218 addTableName(ROUTE_TABLE_LEGACY_NETWORK, ROUTE_TABLE_NAME_LEGACY_NETWORK, &contents);
219 addTableName(ROUTE_TABLE_LEGACY_SYSTEM, ROUTE_TABLE_NAME_LEGACY_SYSTEM, &contents);
Sreeram Ramachandranbb40d512014-07-11 11:45:14 -0700220
Bernie Innocentiabf8a342018-08-10 15:17:16 +0900221 std::lock_guard lock(sInterfaceToTableLock);
Chiachang Wangf79e3562022-01-15 13:31:04 +0800222 for (const auto& [ifName, ifIndex] : sInterfaceToTable) {
223 addTableName(ifIndex, ifName, &contents);
224 // Add table for the local route of the network. It's expected to be used for excluding the
225 // local traffic in the VPN network.
226 // Start from ROUTE_TABLE_OFFSET_FROM_INDEX_FOR_LOCAL plus with the interface table index.
227 uint32_t offset = ROUTE_TABLE_OFFSET_FROM_INDEX_FOR_LOCAL - ROUTE_TABLE_OFFSET_FROM_INDEX;
228 addTableName(offset + ifIndex, ifName + INTERFACE_LOCAL_SUFFIX, &contents);
Sreeram Ramachandran4acd34a2014-07-07 22:11:37 -0700229 }
230
Dan Albert5407e142015-03-16 10:05:59 -0700231 if (!WriteStringToFile(contents, RT_TABLES_PATH, RT_TABLES_MODE, AID_SYSTEM, AID_WIFI)) {
Elliott Hughesbd378322015-02-04 13:25:14 -0800232 ALOGE("failed to write to %s (%s)", RT_TABLES_PATH, strerror(errno));
Sreeram Ramachandran4acd34a2014-07-07 22:11:37 -0700233 return;
234 }
Sreeram Ramachandran5c181bf2014-04-07 14:10:04 -0700235}
236
Sreeram Ramachandran87475a12014-07-15 16:20:28 -0700237// Returns 0 on success or negative errno on failure.
238int padInterfaceName(const char* input, char* name, size_t* length, uint16_t* padding) {
239 if (!input) {
240 *length = 0;
241 *padding = 0;
242 return 0;
243 }
244 *length = strlcpy(name, input, IFNAMSIZ) + 1;
245 if (*length > IFNAMSIZ) {
246 ALOGE("interface name too long (%zu > %u)", *length, IFNAMSIZ);
247 return -ENAMETOOLONG;
248 }
249 *padding = RTA_SPACE(*length) - RTA_LENGTH(*length);
250 return 0;
251}
252
Sreeram Ramachandran8fe9c8e2014-04-16 12:08:05 -0700253// Adds or removes a routing rule for IPv4 and IPv6.
254//
Lorenzo Colitti6b6f25f2015-03-03 17:22:57 +0900255// + If |table| is non-zero, the rule points at the specified routing table. Otherwise, the table is
Robin Lee4ef94642016-04-01 11:50:49 +0100256// unspecified. An unspecified table is not allowed when creating an FR_ACT_TO_TBL rule.
Sreeram Ramachandran8fe9c8e2014-04-16 12:08:05 -0700257// + If |mask| is non-zero, the rule matches the specified fwmark and mask. Otherwise, |fwmark| is
258// ignored.
Sreeram Ramachandran87475a12014-07-15 16:20:28 -0700259// + If |iif| is non-NULL, the rule matches the specified incoming interface.
260// + If |oif| is non-NULL, the rule matches the specified outgoing interface.
261// + If |uidStart| and |uidEnd| are not INVALID_UID, the rule matches packets from UIDs in that
262// range (inclusive). Otherwise, the rule matches packets from all UIDs.
Lorenzo Colitti96f261e2014-06-23 15:09:54 +0900263//
264// Returns 0 on success or negative errno on failure.
Ken Chen53360bf2021-12-10 02:41:05 +0800265[[nodiscard]] static int modifyIpRule(uint16_t action, int32_t priority, uint8_t ruleType,
Bernie Innocenti762dcf42019-06-14 19:52:49 +0900266 uint32_t table, uint32_t fwmark, uint32_t mask,
267 const char* iif, const char* oif, uid_t uidStart,
268 uid_t uidEnd) {
Ken Chen53360bf2021-12-10 02:41:05 +0800269 if (priority < 0) {
270 ALOGE("invalid IP-rule priority %d", priority);
271 return -ERANGE;
272 }
273
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700274 // Ensure that if you set a bit in the fwmark, it's not being ignored by the mask.
275 if (fwmark & ~mask) {
276 ALOGE("mask 0x%x does not select all the bits set in fwmark 0x%x", mask, fwmark);
277 return -ERANGE;
278 }
279
Sreeram Ramachandran87475a12014-07-15 16:20:28 -0700280 // Interface names must include exactly one terminating NULL and be properly padded, or older
Lorenzo Colitti4753afd2014-06-20 23:03:29 +0900281 // kernels will refuse to delete rules.
Sreeram Ramachandran87475a12014-07-15 16:20:28 -0700282 char iifName[IFNAMSIZ], oifName[IFNAMSIZ];
283 size_t iifLength, oifLength;
284 uint16_t iifPadding, oifPadding;
285 if (int ret = padInterfaceName(iif, iifName, &iifLength, &iifPadding)) {
286 return ret;
287 }
288 if (int ret = padInterfaceName(oif, oifName, &oifLength, &oifPadding)) {
289 return ret;
Lorenzo Colitti4753afd2014-06-20 23:03:29 +0900290 }
291
Lorenzo Colitti59656512014-06-25 03:20:29 +0900292 // Either both start and end UID must be specified, or neither.
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700293 if ((uidStart == INVALID_UID) != (uidEnd == INVALID_UID)) {
Sreeram Ramachandrancf891382014-07-01 15:49:20 -0700294 ALOGE("incompatible start and end UIDs (%u vs %u)", uidStart, uidEnd);
Lorenzo Colitti59656512014-06-25 03:20:29 +0900295 return -EUSERS;
296 }
Robin Lee4ef94642016-04-01 11:50:49 +0100297
Lorenzo Colitti72723682014-06-26 13:51:10 +0900298 bool isUidRule = (uidStart != INVALID_UID);
Lorenzo Colitti59656512014-06-25 03:20:29 +0900299
Lorenzo Colitti4753afd2014-06-20 23:03:29 +0900300 // Assemble a rule request and put it in an array of iovec structures.
301 fib_rule_hdr rule = {
Robin Lee4ef94642016-04-01 11:50:49 +0100302 .action = ruleType,
Lorenzo Colitti6b6f25f2015-03-03 17:22:57 +0900303 // Note that here we're implicitly setting rule.table to 0. When we want to specify a
304 // non-zero table, we do this via the FRATTR_TABLE attribute.
Lorenzo Colitti4753afd2014-06-20 23:03:29 +0900305 };
306
Lorenzo Colitti6b6f25f2015-03-03 17:22:57 +0900307 // Don't ever create a rule that looks up table 0, because table 0 is the local table.
308 // It's OK to specify a table ID of 0 when deleting a rule, because that doesn't actually select
309 // table 0, it's a wildcard that matches anything.
310 if (table == RT_TABLE_UNSPEC && rule.action == FR_ACT_TO_TBL && action != RTM_DELRULE) {
311 ALOGE("RT_TABLE_UNSPEC only allowed when deleting rules");
312 return -ENOTUNIQ;
313 }
314
Sreeram Ramachandran87475a12014-07-15 16:20:28 -0700315 rtattr fraIifName = { U16_RTA_LENGTH(iifLength), FRA_IIFNAME };
316 rtattr fraOifName = { U16_RTA_LENGTH(oifLength), FRA_OIFNAME };
Lorenzo Colitti2b078672016-12-16 18:45:03 +0900317 struct fib_rule_uid_range uidRange = { uidStart, uidEnd };
Lorenzo Colitti4753afd2014-06-20 23:03:29 +0900318
319 iovec iov[] = {
Yi Kongbdfd57e2018-07-25 13:26:10 -0700320 { nullptr, 0 },
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700321 { &rule, sizeof(rule) },
322 { &FRATTR_PRIORITY, sizeof(FRATTR_PRIORITY) },
323 { &priority, sizeof(priority) },
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -0700324 { &FRATTR_TABLE, table != RT_TABLE_UNSPEC ? sizeof(FRATTR_TABLE) : 0 },
325 { &table, table != RT_TABLE_UNSPEC ? sizeof(table) : 0 },
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700326 { &FRATTR_FWMARK, mask ? sizeof(FRATTR_FWMARK) : 0 },
327 { &fwmark, mask ? sizeof(fwmark) : 0 },
328 { &FRATTR_FWMASK, mask ? sizeof(FRATTR_FWMASK) : 0 },
329 { &mask, mask ? sizeof(mask) : 0 },
Lorenzo Colitti2b078672016-12-16 18:45:03 +0900330 { &FRATTR_UID_RANGE, isUidRule ? sizeof(FRATTR_UID_RANGE) : 0 },
331 { &uidRange, isUidRule ? sizeof(uidRange) : 0 },
Sreeram Ramachandran87475a12014-07-15 16:20:28 -0700332 { &fraIifName, iif != IIF_NONE ? sizeof(fraIifName) : 0 },
333 { iifName, iifLength },
334 { PADDING_BUFFER, iifPadding },
335 { &fraOifName, oif != OIF_NONE ? sizeof(fraOifName) : 0 },
336 { oifName, oifLength },
337 { PADDING_BUFFER, oifPadding },
Lorenzo Colitti4753afd2014-06-20 23:03:29 +0900338 };
339
Lorenzo Colitti5c437992017-11-28 01:26:02 +0900340 uint16_t flags = (action == RTM_NEWRULE) ? NETLINK_RULE_CREATE_FLAGS : NETLINK_REQUEST_FLAGS;
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700341 for (size_t i = 0; i < ARRAY_SIZE(AF_FAMILIES); ++i) {
342 rule.family = AF_FAMILIES[i];
Lorenzo Colittif3e299a2017-02-14 17:24:28 +0900343 if (int ret = sendNetlinkRequest(action, flags, iov, ARRAY_SIZE(iov), nullptr)) {
Lorenzo Colitti220ca732017-02-14 17:57:55 +0900344 if (!(action == RTM_DELRULE && ret == -ENOENT && priority == RULE_PRIORITY_TETHERING)) {
345 // Don't log when deleting a tethering rule that's not there. This matches the
346 // behaviour of clearTetheringRules, which ignores ENOENT in this case.
347 ALOGE("Error %s %s rule: %s", actionName(action), familyName(rule.family),
348 strerror(-ret));
349 }
Lorenzo Colitti96f261e2014-06-23 15:09:54 +0900350 return ret;
Sreeram Ramachandran5c181bf2014-04-07 14:10:04 -0700351 }
352 }
353
Lorenzo Colitti96f261e2014-06-23 15:09:54 +0900354 return 0;
Sreeram Ramachandran5c181bf2014-04-07 14:10:04 -0700355}
356
Ken Chen53360bf2021-12-10 02:41:05 +0800357[[nodiscard]] static int modifyIpRule(uint16_t action, int32_t priority, uint32_t table,
Bernie Innocenti762dcf42019-06-14 19:52:49 +0900358 uint32_t fwmark, uint32_t mask, const char* iif,
359 const char* oif, uid_t uidStart, uid_t uidEnd) {
Robin Lee4ef94642016-04-01 11:50:49 +0100360 return modifyIpRule(action, priority, FR_ACT_TO_TBL, table, fwmark, mask, iif, oif, uidStart,
361 uidEnd);
362}
363
Ken Chen53360bf2021-12-10 02:41:05 +0800364[[nodiscard]] static int modifyIpRule(uint16_t action, int32_t priority, uint32_t table,
Bernie Innocenti762dcf42019-06-14 19:52:49 +0900365 uint32_t fwmark, uint32_t mask) {
Sreeram Ramachandran87475a12014-07-15 16:20:28 -0700366 return modifyIpRule(action, priority, table, fwmark, mask, IIF_NONE, OIF_NONE, INVALID_UID,
367 INVALID_UID);
368}
369
Lorenzo Colittiba25df92014-06-18 00:22:17 +0900370// Adds or deletes an IPv4 or IPv6 route.
371// Returns 0 on success or negative errno on failure.
Tyler Wearfa94a272019-12-05 15:01:48 -0800372int modifyIpRoute(uint16_t action, uint16_t flags, uint32_t table, const char* interface,
Taras Antoshchuk0cceda22021-09-24 18:40:03 +0200373 const char* destination, const char* nexthop, uint32_t mtu, uint32_t priority) {
Lorenzo Colittiba25df92014-06-18 00:22:17 +0900374 // At least the destination must be non-null.
375 if (!destination) {
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700376 ALOGE("null destination");
Lorenzo Colittiba25df92014-06-18 00:22:17 +0900377 return -EFAULT;
378 }
Sreeram Ramachandran7619e1b2014-04-15 14:23:08 -0700379
Lorenzo Colittiba25df92014-06-18 00:22:17 +0900380 // Parse the prefix.
381 uint8_t rawAddress[sizeof(in6_addr)];
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700382 uint8_t family;
383 uint8_t prefixLength;
Lorenzo Colittiba25df92014-06-18 00:22:17 +0900384 int rawLength = parsePrefix(destination, &family, rawAddress, sizeof(rawAddress),
385 &prefixLength);
386 if (rawLength < 0) {
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700387 ALOGE("parsePrefix failed for destination %s (%s)", destination, strerror(-rawLength));
Lorenzo Colittiba25df92014-06-18 00:22:17 +0900388 return rawLength;
389 }
Sreeram Ramachandran7619e1b2014-04-15 14:23:08 -0700390
Lorenzo Colittiba25df92014-06-18 00:22:17 +0900391 if (static_cast<size_t>(rawLength) > sizeof(rawAddress)) {
Sreeram Ramachandran1201e842014-07-01 15:06:05 -0700392 ALOGE("impossible! address too long (%d vs %zu)", rawLength, sizeof(rawAddress));
Lorenzo Colittiba25df92014-06-18 00:22:17 +0900393 return -ENOBUFS; // Cannot happen; parsePrefix only supports IPv4 and IPv6.
394 }
395
Sreeram Ramachandrande5d5df2014-07-26 18:43:25 -0700396 uint8_t type = RTN_UNICAST;
Lorenzo Colittiba25df92014-06-18 00:22:17 +0900397 uint32_t ifindex;
Lorenzo Colittiba25df92014-06-18 00:22:17 +0900398 uint8_t rawNexthop[sizeof(in6_addr)];
Sreeram Ramachandrande5d5df2014-07-26 18:43:25 -0700399
400 if (nexthop && !strcmp(nexthop, "unreachable")) {
401 type = RTN_UNREACHABLE;
402 // 'interface' is likely non-NULL, as the caller (modifyRoute()) likely used it to lookup
403 // the table number. But it's an error to specify an interface ("dev ...") or a nexthop for
404 // unreachable routes, so nuke them. (IPv6 allows them to be specified; IPv4 doesn't.)
405 interface = OIF_NONE;
Yi Kongbdfd57e2018-07-25 13:26:10 -0700406 nexthop = nullptr;
Lorenzo Colitti4c95a122014-09-18 16:01:50 +0900407 } else if (nexthop && !strcmp(nexthop, "throw")) {
408 type = RTN_THROW;
409 interface = OIF_NONE;
Yi Kongbdfd57e2018-07-25 13:26:10 -0700410 nexthop = nullptr;
Sreeram Ramachandrande5d5df2014-07-26 18:43:25 -0700411 } else {
412 // If an interface was specified, find the ifindex.
413 if (interface != OIF_NONE) {
Chiachang Wangf79e3562022-01-15 13:31:04 +0800414 ifindex = RouteController::ifNameToIndexFunction(interface);
415
Sreeram Ramachandrande5d5df2014-07-26 18:43:25 -0700416 if (!ifindex) {
417 ALOGE("cannot find interface %s", interface);
418 return -ENODEV;
419 }
420 }
421
422 // If a nexthop was specified, parse it as the same family as the prefix.
423 if (nexthop && inet_pton(family, nexthop, rawNexthop) <= 0) {
424 ALOGE("inet_pton failed for nexthop %s", nexthop);
425 return -EINVAL;
426 }
Lorenzo Colittiba25df92014-06-18 00:22:17 +0900427 }
428
Lorenzo Colitti4753afd2014-06-20 23:03:29 +0900429 // Assemble a rtmsg and put it in an array of iovec structures.
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700430 rtmsg route = {
Nick Desaulniers6b357502019-10-11 09:26:44 -0700431 .rtm_family = family,
432 .rtm_dst_len = prefixLength,
433 .rtm_protocol = RTPROT_STATIC,
434 .rtm_scope = static_cast<uint8_t>(nexthop ? RT_SCOPE_UNIVERSE : RT_SCOPE_LINK),
435 .rtm_type = type,
Lorenzo Colittiba25df92014-06-18 00:22:17 +0900436 };
Lorenzo Colitti4753afd2014-06-20 23:03:29 +0900437
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700438 rtattr rtaDst = { U16_RTA_LENGTH(rawLength), RTA_DST };
439 rtattr rtaGateway = { U16_RTA_LENGTH(rawLength), RTA_GATEWAY };
Lorenzo Colittiba25df92014-06-18 00:22:17 +0900440
441 iovec iov[] = {
Taras Antoshchuk0cceda22021-09-24 18:40:03 +0200442 {nullptr, 0},
443 {&route, sizeof(route)},
444 {&RTATTR_TABLE, sizeof(RTATTR_TABLE)},
445 {&table, sizeof(table)},
446 {&rtaDst, sizeof(rtaDst)},
447 {rawAddress, static_cast<size_t>(rawLength)},
448 {&RTATTR_OIF, interface != OIF_NONE ? sizeof(RTATTR_OIF) : 0},
449 {&ifindex, interface != OIF_NONE ? sizeof(ifindex) : 0},
450 {&rtaGateway, nexthop ? sizeof(rtaGateway) : 0},
451 {rawNexthop, nexthop ? static_cast<size_t>(rawLength) : 0},
452 {&RTATTR_METRICS, mtu != 0 ? sizeof(RTATTR_METRICS) : 0},
453 {&RTATTRX_MTU, mtu != 0 ? sizeof(RTATTRX_MTU) : 0},
454 {&mtu, mtu != 0 ? sizeof(mtu) : 0},
455 {&RTATTR_PRIO, priority != 0 ? sizeof(RTATTR_PRIO) : 0},
456 {&priority, priority != 0 ? sizeof(priority) : 0},
Lorenzo Colittiba25df92014-06-18 00:22:17 +0900457 };
Lorenzo Colittiba25df92014-06-18 00:22:17 +0900458
Jimmy Chence9e5782019-03-08 16:12:55 +0800459 // Allow creating multiple link-local routes in the same table, so we can make IPv6
460 // work on all interfaces in the local_network table.
461 if (family == AF_INET6 && IN6_IS_ADDR_LINKLOCAL(reinterpret_cast<in6_addr*>(rawAddress))) {
462 flags &= ~NLM_F_EXCL;
463 }
464
Lorenzo Colittif3e299a2017-02-14 17:24:28 +0900465 int ret = sendNetlinkRequest(action, flags, iov, ARRAY_SIZE(iov), nullptr);
Lorenzo Colitti0b073fb2017-02-10 07:49:12 +0900466 if (ret) {
467 ALOGE("Error %s route %s -> %s %s to table %u: %s",
468 actionName(action), destination, nexthop, interface, table, strerror(-ret));
469 }
470 return ret;
Sreeram Ramachandran7619e1b2014-04-15 14:23:08 -0700471}
472
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -0700473// An iptables rule to mark incoming packets on a network with the netId of the network.
474//
475// This is so that the kernel can:
476// + Use the right fwmark for (and thus correctly route) replies (e.g.: TCP RST, ICMP errors, ping
477// replies, SYN-ACKs, etc).
478// + Mark sockets that accept connections from this interface so that the connection stays on the
479// same interface.
Bernie Innocenti762dcf42019-06-14 19:52:49 +0900480int modifyIncomingPacketMark(unsigned netId, const char* interface, Permission permission,
481 bool add) {
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -0700482 Fwmark fwmark;
483
484 fwmark.netId = netId;
485 fwmark.explicitlySelected = true;
486 fwmark.protectedFromVpn = true;
487 fwmark.permission = permission;
488
Benedict Wongb9baf262017-12-03 15:43:08 -0800489 const uint32_t mask = ~Fwmark::getUidBillingMask();
490
491 std::string cmd = StringPrintf(
492 "%s %s -i %s -j MARK --set-mark 0x%x/0x%x", add ? "-A" : "-D",
493 RouteController::LOCAL_MANGLE_INPUT, interface, fwmark.intValue, mask);
Lorenzo Colittic1306ea2017-03-27 05:52:31 +0900494 if (RouteController::iptablesRestoreCommandFunction(V4V6, "mangle", cmd, nullptr) != 0) {
Sreeram Ramachandranb1425cc2014-06-23 18:54:27 -0700495 ALOGE("failed to change iptables rule that sets incoming packet mark");
496 return -EREMOTEIO;
497 }
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -0700498
Sreeram Ramachandranb1425cc2014-06-23 18:54:27 -0700499 return 0;
500}
501
Sreeram Ramachandran111bec22014-07-22 18:51:06 -0700502// A rule to route responses to the local network forwarded via the VPN.
503//
504// When a VPN is in effect, packets from the local network to upstream networks are forwarded into
505// the VPN's tunnel interface. When the VPN forwards the responses, they emerge out of the tunnel.
Bernie Innocenti762dcf42019-06-14 19:52:49 +0900506[[nodiscard]] static int modifyVpnOutputToLocalRule(const char* vpnInterface, bool add) {
Sreeram Ramachandran111bec22014-07-22 18:51:06 -0700507 return modifyIpRule(add ? RTM_NEWRULE : RTM_DELRULE, RULE_PRIORITY_VPN_OUTPUT_TO_LOCAL,
508 ROUTE_TABLE_LOCAL_NETWORK, MARK_UNSET, MARK_UNSET, vpnInterface, OIF_NONE,
509 INVALID_UID, INVALID_UID);
510}
511
Sreeram Ramachandranfa9f4dc2014-07-22 18:16:44 -0700512// A rule to route all traffic from a given set of UIDs to go over the VPN.
513//
514// Notice that this rule doesn't use the netId. I.e., no matter what netId the user's socket may
515// have, if they are subject to this VPN, their traffic has to go through it. Allows the traffic to
516// bypass the VPN if the protectedFromVpn bit is set.
Bernie Innocenti762dcf42019-06-14 19:52:49 +0900517[[nodiscard]] static int modifyVpnUidRangeRule(uint32_t table, uid_t uidStart, uid_t uidEnd,
Chiachang Wang2e9443f2022-01-14 22:55:36 +0800518 int32_t subPriority, bool secure, bool add,
519 bool excludeLocalRoutes) {
Sreeram Ramachandranfa9f4dc2014-07-22 18:16:44 -0700520 Fwmark fwmark;
521 Fwmark mask;
522
523 fwmark.protectedFromVpn = false;
524 mask.protectedFromVpn = true;
525
Ken Chen53360bf2021-12-10 02:41:05 +0800526 int32_t priority;
Sreeram Ramachandran95684ba2014-07-23 13:27:31 -0700527
528 if (secure) {
529 priority = RULE_PRIORITY_SECURE_VPN;
530 } else {
Chiachang Wang2e9443f2022-01-14 22:55:36 +0800531 priority = excludeLocalRoutes ? RULE_PRIORITY_BYPASSABLE_VPN_LOCAL_EXCLUSION
532 : RULE_PRIORITY_BYPASSABLE_VPN_NO_LOCAL_EXCLUSION;
Sreeram Ramachandran95684ba2014-07-23 13:27:31 -0700533
534 fwmark.explicitlySelected = false;
535 mask.explicitlySelected = true;
536 }
537
Ken Chen4ea88462021-05-23 14:56:43 +0800538 return modifyIpRule(add ? RTM_NEWRULE : RTM_DELRULE, priority + subPriority, table,
539 fwmark.intValue, mask.intValue, IIF_LOOPBACK, OIF_NONE, uidStart, uidEnd);
Sreeram Ramachandranfa9f4dc2014-07-22 18:16:44 -0700540}
541
542// A rule to allow system apps to send traffic over this VPN even if they are not part of the target
543// set of UIDs.
544//
545// This is needed for DnsProxyListener to correctly resolve a request for a user who is in the
546// target set, but where the DnsProxyListener itself is not.
Bernie Innocenti762dcf42019-06-14 19:52:49 +0900547[[nodiscard]] static int modifyVpnSystemPermissionRule(unsigned netId, uint32_t table, bool secure,
Chiachang Wang2e9443f2022-01-14 22:55:36 +0800548 bool add, bool excludeLocalRoutes) {
Sreeram Ramachandranfa9f4dc2014-07-22 18:16:44 -0700549 Fwmark fwmark;
550 Fwmark mask;
551
552 fwmark.netId = netId;
553 mask.netId = FWMARK_NET_ID_MASK;
554
555 fwmark.permission = PERMISSION_SYSTEM;
556 mask.permission = PERMISSION_SYSTEM;
557
Chiachang Wang2e9443f2022-01-14 22:55:36 +0800558 uint32_t priority;
559
560 if (secure) {
561 priority = RULE_PRIORITY_SECURE_VPN;
562 } else {
563 priority = excludeLocalRoutes ? RULE_PRIORITY_BYPASSABLE_VPN_LOCAL_EXCLUSION
564 : RULE_PRIORITY_BYPASSABLE_VPN_NO_LOCAL_EXCLUSION;
565 }
Sreeram Ramachandran95684ba2014-07-23 13:27:31 -0700566
567 return modifyIpRule(add ? RTM_NEWRULE : RTM_DELRULE, priority, table, fwmark.intValue,
568 mask.intValue);
Sreeram Ramachandranfa9f4dc2014-07-22 18:16:44 -0700569}
570
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -0700571// A rule to route traffic based on an explicitly chosen network.
572//
573// Supports apps that use the multinetwork APIs to restrict their traffic to a network.
574//
575// Even though we check permissions at the time we set a netId into the fwmark of a socket, we need
576// to check it again in the rules here, because a network's permissions may have been updated via
577// modifyNetworkPermission().
Bernie Innocenti762dcf42019-06-14 19:52:49 +0900578[[nodiscard]] static int modifyExplicitNetworkRule(unsigned netId, uint32_t table,
579 Permission permission, uid_t uidStart,
Ken Chen53360bf2021-12-10 02:41:05 +0800580 uid_t uidEnd, int32_t subPriority, bool add) {
Sreeram Ramachandraneb27b7e2014-07-01 14:30:30 -0700581 Fwmark fwmark;
582 Fwmark mask;
583
584 fwmark.netId = netId;
585 mask.netId = FWMARK_NET_ID_MASK;
586
Sreeram Ramachandran122f5812014-05-11 20:29:49 -0700587 fwmark.explicitlySelected = true;
588 mask.explicitlySelected = true;
Sreeram Ramachandran5c181bf2014-04-07 14:10:04 -0700589
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -0700590 fwmark.permission = permission;
591 mask.permission = permission;
Sreeram Ramachandraneb27b7e2014-07-01 14:30:30 -0700592
Ken Chen4ea88462021-05-23 14:56:43 +0800593 return modifyIpRule(add ? RTM_NEWRULE : RTM_DELRULE,
594 RULE_PRIORITY_EXPLICIT_NETWORK + subPriority, table, fwmark.intValue,
595 mask.intValue, IIF_LOOPBACK, OIF_NONE, uidStart, uidEnd);
Sreeram Ramachandran5c181bf2014-04-07 14:10:04 -0700596}
597
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -0700598// A rule to route traffic based on a chosen outgoing interface.
599//
600// Supports apps that use SO_BINDTODEVICE or IP_PKTINFO options and the kernel that already knows
601// the outgoing interface (typically for link-local communications).
Bernie Innocenti762dcf42019-06-14 19:52:49 +0900602[[nodiscard]] static int modifyOutputInterfaceRules(const char* interface, uint32_t table,
603 Permission permission, uid_t uidStart,
Ken Chen53360bf2021-12-10 02:41:05 +0800604 uid_t uidEnd, int32_t subPriority, bool add) {
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -0700605 Fwmark fwmark;
606 Fwmark mask;
Sreeram Ramachandran4043f012014-06-23 12:41:37 -0700607
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -0700608 fwmark.permission = permission;
609 mask.permission = permission;
Sreeram Ramachandranb1425cc2014-06-23 18:54:27 -0700610
Lorenzo Colitti57947f02015-02-27 16:45:55 +0900611 // If this rule does not specify a UID range, then also add a corresponding high-priority rule
Lorenzo Colitti758627c2018-03-15 01:49:20 +0900612 // for root. This covers kernel-originated packets, TEEd packets and any local daemons that open
613 // sockets as root.
Lorenzo Colitti57947f02015-02-27 16:45:55 +0900614 if (uidStart == INVALID_UID && uidEnd == INVALID_UID) {
615 if (int ret = modifyIpRule(add ? RTM_NEWRULE : RTM_DELRULE, RULE_PRIORITY_VPN_OVERRIDE_OIF,
Lorenzo Colitti758627c2018-03-15 01:49:20 +0900616 table, FWMARK_NONE, MASK_NONE, IIF_LOOPBACK, interface,
Lorenzo Colitti57947f02015-02-27 16:45:55 +0900617 UID_ROOT, UID_ROOT)) {
618 return ret;
619 }
620 }
621
Ken Chen4ea88462021-05-23 14:56:43 +0800622 return modifyIpRule(add ? RTM_NEWRULE : RTM_DELRULE,
623 RULE_PRIORITY_OUTPUT_INTERFACE + subPriority, table, fwmark.intValue,
624 mask.intValue, IIF_LOOPBACK, interface, uidStart, uidEnd);
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -0700625}
626
627// A rule to route traffic based on the chosen network.
628//
629// This is for sockets that have not explicitly requested a particular network, but have been
630// bound to one when they called connect(). This ensures that sockets connected on a particular
631// network stay on that network even if the default network changes.
Bernie Innocenti762dcf42019-06-14 19:52:49 +0900632[[nodiscard]] static int modifyImplicitNetworkRule(unsigned netId, uint32_t table, bool add) {
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -0700633 Fwmark fwmark;
634 Fwmark mask;
635
636 fwmark.netId = netId;
637 mask.netId = FWMARK_NET_ID_MASK;
638
639 fwmark.explicitlySelected = false;
640 mask.explicitlySelected = true;
641
Lorenzo Colittibe0c7c32017-09-06 16:07:02 +0900642 fwmark.permission = PERMISSION_NONE;
643 mask.permission = PERMISSION_NONE;
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -0700644
645 return modifyIpRule(add ? RTM_NEWRULE : RTM_DELRULE, RULE_PRIORITY_IMPLICIT_NETWORK, table,
Lorenzo Colitti758627c2018-03-15 01:49:20 +0900646 fwmark.intValue, mask.intValue, IIF_LOOPBACK, OIF_NONE, INVALID_UID,
647 INVALID_UID);
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -0700648}
649
Chiachang Wang8b9cdd22022-01-27 10:43:28 +0800650int RouteController::modifyVpnLocalExclusionRule(bool add, const char* physicalInterface) {
Chiachang Wange7bf5f52022-01-17 11:37:39 +0800651 uint32_t table = getRouteTableForInterface(physicalInterface, true /* local */);
652 if (table == RT_TABLE_UNSPEC) {
653 return -ESRCH;
654 }
655
656 Fwmark fwmark;
657 Fwmark mask;
658
659 fwmark.explicitlySelected = false;
660 mask.explicitlySelected = true;
661
662 fwmark.permission = PERMISSION_NONE;
663 mask.permission = PERMISSION_NONE;
664
chiachangwang31902a42022-04-15 20:06:27 +0800665 return modifyIpRule(add ? RTM_NEWRULE : RTM_DELRULE, RULE_PRIORITY_LOCAL_ROUTES, table,
666 fwmark.intValue, mask.intValue, IIF_LOOPBACK, OIF_NONE, INVALID_UID,
667 INVALID_UID);
Chiachang Wange7bf5f52022-01-17 11:37:39 +0800668}
669
Sreeram Ramachandran48e19b02014-07-22 22:23:20 -0700670// A rule to enable split tunnel VPNs.
671//
672// If a packet with a VPN's netId doesn't find a route in the VPN's routing table, it's allowed to
Luke Huangd2861982019-05-17 19:47:28 +0800673// go over the default network, provided it has the permissions required by the default network.
Bernie Innocenti762dcf42019-06-14 19:52:49 +0900674int RouteController::modifyVpnFallthroughRule(uint16_t action, unsigned vpnNetId,
675 const char* physicalInterface,
676 Permission permission) {
Chiachang Wangf79e3562022-01-15 13:31:04 +0800677 uint32_t table = getRouteTableForInterface(physicalInterface, false /* local */);
Sreeram Ramachandran48e19b02014-07-22 22:23:20 -0700678 if (table == RT_TABLE_UNSPEC) {
679 return -ESRCH;
680 }
681
682 Fwmark fwmark;
683 Fwmark mask;
684
685 fwmark.netId = vpnNetId;
686 mask.netId = FWMARK_NET_ID_MASK;
687
Sreeram Ramachandran48e19b02014-07-22 22:23:20 -0700688 fwmark.permission = permission;
689 mask.permission = permission;
690
691 return modifyIpRule(action, RULE_PRIORITY_VPN_FALLTHROUGH, table, fwmark.intValue,
692 mask.intValue);
693}
694
Sreeram Ramachandranfa9f4dc2014-07-22 18:16:44 -0700695// Add rules to allow legacy routes added through the requestRouteToHost() API.
Bernie Innocenti762dcf42019-06-14 19:52:49 +0900696[[nodiscard]] static int addLegacyRouteRules() {
Sreeram Ramachandran4043f012014-06-23 12:41:37 -0700697 Fwmark fwmark;
698 Fwmark mask;
699
Sreeram Ramachandranfa9f4dc2014-07-22 18:16:44 -0700700 fwmark.explicitlySelected = false;
701 mask.explicitlySelected = true;
Sreeram Ramachandranb1425cc2014-06-23 18:54:27 -0700702
Sreeram Ramachandranfa9f4dc2014-07-22 18:16:44 -0700703 // Rules to allow legacy routes to override the default network.
704 if (int ret = modifyIpRule(RTM_NEWRULE, RULE_PRIORITY_LEGACY_SYSTEM, ROUTE_TABLE_LEGACY_SYSTEM,
705 fwmark.intValue, mask.intValue)) {
706 return ret;
707 }
708 if (int ret = modifyIpRule(RTM_NEWRULE, RULE_PRIORITY_LEGACY_NETWORK,
709 ROUTE_TABLE_LEGACY_NETWORK, fwmark.intValue, mask.intValue)) {
710 return ret;
711 }
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -0700712
713 fwmark.permission = PERMISSION_SYSTEM;
714 mask.permission = PERMISSION_SYSTEM;
715
Sreeram Ramachandranfa9f4dc2014-07-22 18:16:44 -0700716 // A rule to allow legacy routes from system apps to override VPNs.
717 return modifyIpRule(RTM_NEWRULE, RULE_PRIORITY_VPN_OVERRIDE_SYSTEM, ROUTE_TABLE_LEGACY_SYSTEM,
Sreeram Ramachandran87475a12014-07-15 16:20:28 -0700718 fwmark.intValue, mask.intValue);
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -0700719}
720
Sreeram Ramachandranfa9f4dc2014-07-22 18:16:44 -0700721// Add rules to lookup the local network when specified explicitly or otherwise.
Bernie Innocenti762dcf42019-06-14 19:52:49 +0900722[[nodiscard]] static int addLocalNetworkRules(unsigned localNetId) {
Sreeram Ramachandranfa9f4dc2014-07-22 18:16:44 -0700723 if (int ret = modifyExplicitNetworkRule(localNetId, ROUTE_TABLE_LOCAL_NETWORK, PERMISSION_NONE,
Ken Chen4ea88462021-05-23 14:56:43 +0800724 INVALID_UID, INVALID_UID,
Patrick Rohre2f1b5a2022-01-25 21:36:50 +0100725 UidRanges::SUB_PRIORITY_HIGHEST, ACTION_ADD)) {
Sreeram Ramachandranfa9f4dc2014-07-22 18:16:44 -0700726 return ret;
Sreeram Ramachandran6a773532014-07-11 09:10:20 -0700727 }
728
Sreeram Ramachandranfa9f4dc2014-07-22 18:16:44 -0700729 Fwmark fwmark;
730 Fwmark mask;
731
732 fwmark.explicitlySelected = false;
733 mask.explicitlySelected = true;
734
735 return modifyIpRule(RTM_NEWRULE, RULE_PRIORITY_LOCAL_NETWORK, ROUTE_TABLE_LOCAL_NETWORK,
736 fwmark.intValue, mask.intValue);
737}
738
Lorenzo Colitti02cb80a2017-10-30 19:21:06 +0900739/* static */
740int RouteController::configureDummyNetwork() {
Lorenzo Colitti36679362015-02-25 10:26:19 +0900741 const char *interface = DummyNetwork::INTERFACE_NAME;
Chiachang Wangf79e3562022-01-15 13:31:04 +0800742 uint32_t table = getRouteTableForInterface(interface, false /* local */);
Lorenzo Colitti36679362015-02-25 10:26:19 +0900743 if (table == RT_TABLE_UNSPEC) {
Hungming Chen7f725432020-02-07 17:47:23 +0800744 // getRouteTableForInterface has already logged an error.
Lorenzo Colitti36679362015-02-25 10:26:19 +0900745 return -ESRCH;
746 }
747
748 ifc_init();
749 int ret = ifc_up(interface);
750 ifc_close();
751 if (ret) {
752 ALOGE("Can't bring up %s: %s", interface, strerror(errno));
753 return -errno;
754 }
755
Ken Chen4ea88462021-05-23 14:56:43 +0800756 if ((ret = modifyOutputInterfaceRules(interface, table, PERMISSION_NONE, INVALID_UID,
Patrick Rohre2f1b5a2022-01-25 21:36:50 +0100757 INVALID_UID, UidRanges::SUB_PRIORITY_HIGHEST,
Ken Chen4ea88462021-05-23 14:56:43 +0800758 ACTION_ADD))) {
Lorenzo Colitti57947f02015-02-27 16:45:55 +0900759 ALOGE("Can't create oif rules for %s: %s", interface, strerror(-ret));
Lorenzo Colitti36679362015-02-25 10:26:19 +0900760 return ret;
761 }
762
Tyler Wearfa94a272019-12-05 15:01:48 -0800763 if ((ret = modifyIpRoute(RTM_NEWROUTE, NETLINK_ROUTE_CREATE_FLAGS, table, interface,
Taras Antoshchuk0cceda22021-09-24 18:40:03 +0200764 "0.0.0.0/0", nullptr, 0 /* mtu */, 0 /* priority */))) {
Lorenzo Colitti36679362015-02-25 10:26:19 +0900765 return ret;
766 }
767
Tyler Wearfa94a272019-12-05 15:01:48 -0800768 if ((ret = modifyIpRoute(RTM_NEWROUTE, NETLINK_ROUTE_CREATE_FLAGS, table, interface, "::/0",
Taras Antoshchuk0cceda22021-09-24 18:40:03 +0200769 nullptr, 0 /* mtu */, 0 /* priority */))) {
Lorenzo Colitti36679362015-02-25 10:26:19 +0900770 return ret;
771 }
772
773 return 0;
774}
775
Lorenzo Colittidb74dba2014-07-29 18:26:21 +0900776// Add an explicit unreachable rule close to the end of the prioriy list to make it clear that
777// relying on the kernel-default "from all lookup main" rule at priority 32766 is not intended
778// behaviour. We do flush the kernel-default rules at startup, but having an explicit unreachable
779// rule will hopefully make things even clearer.
Bernie Innocenti762dcf42019-06-14 19:52:49 +0900780[[nodiscard]] static int addUnreachableRule() {
Robin Leec125fe42016-05-02 08:53:34 +0100781 return modifyIpRule(RTM_NEWRULE, RULE_PRIORITY_UNREACHABLE, FR_ACT_UNREACHABLE, RT_TABLE_UNSPEC,
782 MARK_UNSET, MARK_UNSET, IIF_NONE, OIF_NONE, INVALID_UID, INVALID_UID);
Sreeram Ramachandran87475a12014-07-15 16:20:28 -0700783}
784
Bernie Innocenti762dcf42019-06-14 19:52:49 +0900785[[nodiscard]] static int modifyLocalNetwork(unsigned netId, const char* interface, bool add) {
Sreeram Ramachandran6a773532014-07-11 09:10:20 -0700786 if (int ret = modifyIncomingPacketMark(netId, interface, PERMISSION_NONE, add)) {
787 return ret;
788 }
Lorenzo Colitti3810c972021-01-06 11:44:02 +0900789 maybeModifyQdiscClsact(interface, add);
Lorenzo Colitti57947f02015-02-27 16:45:55 +0900790 return modifyOutputInterfaceRules(interface, ROUTE_TABLE_LOCAL_NETWORK, PERMISSION_NONE,
Patrick Rohre2f1b5a2022-01-25 21:36:50 +0100791 INVALID_UID, INVALID_UID, UidRanges::SUB_PRIORITY_HIGHEST,
Ken Chen4ea88462021-05-23 14:56:43 +0800792 add);
Sreeram Ramachandran6a773532014-07-11 09:10:20 -0700793}
794
Ken Chena2206ec2021-03-24 17:15:44 +0800795[[nodiscard]] static int modifyUidNetworkRule(unsigned netId, uint32_t table, uid_t uidStart,
Ken Chen53360bf2021-12-10 02:41:05 +0800796 uid_t uidEnd, int32_t subPriority, bool add,
Ken Chen4ea88462021-05-23 14:56:43 +0800797 bool explicitSelect) {
Ken Chen8738e1c2020-11-24 11:38:54 +0800798 if ((uidStart == INVALID_UID) || (uidEnd == INVALID_UID)) {
Ken Chena2206ec2021-03-24 17:15:44 +0800799 ALOGE("modifyUidNetworkRule, invalid UIDs (%u, %u)", uidStart, uidEnd);
Ken Chen8738e1c2020-11-24 11:38:54 +0800800 return -EUSERS;
801 }
802
803 Fwmark fwmark;
804 Fwmark mask;
805
806 fwmark.netId = netId;
807 mask.netId = FWMARK_NET_ID_MASK;
808
Ken Chena2206ec2021-03-24 17:15:44 +0800809 fwmark.explicitlySelected = explicitSelect;
Ken Chen8738e1c2020-11-24 11:38:54 +0800810 mask.explicitlySelected = true;
811
812 // Access to this network is controlled by UID rules, not permission bits.
813 fwmark.permission = PERMISSION_NONE;
814 mask.permission = PERMISSION_NONE;
815
Ken Chena2206ec2021-03-24 17:15:44 +0800816 return modifyIpRule(add ? RTM_NEWRULE : RTM_DELRULE,
Ken Chen4ea88462021-05-23 14:56:43 +0800817 explicitSelect ? (RULE_PRIORITY_UID_EXPLICIT_NETWORK + subPriority)
818 : (RULE_PRIORITY_UID_IMPLICIT_NETWORK + subPriority),
Ken Chena2206ec2021-03-24 17:15:44 +0800819 table, fwmark.intValue, mask.intValue, IIF_LOOPBACK, OIF_NONE, uidStart,
820 uidEnd);
Ken Chen8738e1c2020-11-24 11:38:54 +0800821}
822
823[[nodiscard]] static int modifyUidDefaultNetworkRule(uint32_t table, uid_t uidStart, uid_t uidEnd,
Ken Chen53360bf2021-12-10 02:41:05 +0800824 int32_t subPriority, bool add) {
Ken Chen8738e1c2020-11-24 11:38:54 +0800825 if ((uidStart == INVALID_UID) || (uidEnd == INVALID_UID)) {
826 ALOGE("modifyUidDefaultNetworkRule, invalid UIDs (%u, %u)", uidStart, uidEnd);
827 return -EUSERS;
828 }
829
830 Fwmark fwmark;
831 Fwmark mask;
832
833 fwmark.netId = NETID_UNSET;
834 mask.netId = FWMARK_NET_ID_MASK;
835
836 // Access to this network is controlled by UID rules, not permission bits.
837 fwmark.permission = PERMISSION_NONE;
838 mask.permission = PERMISSION_NONE;
839
Ken Chen4ea88462021-05-23 14:56:43 +0800840 return modifyIpRule(add ? RTM_NEWRULE : RTM_DELRULE,
841 RULE_PRIORITY_UID_DEFAULT_NETWORK + subPriority, table, fwmark.intValue,
842 mask.intValue, IIF_LOOPBACK, OIF_NONE, uidStart, uidEnd);
Ken Chen8738e1c2020-11-24 11:38:54 +0800843}
844
Lorenzo Colitti02cb80a2017-10-30 19:21:06 +0900845/* static */
Bernie Innocenti762dcf42019-06-14 19:52:49 +0900846int RouteController::modifyPhysicalNetwork(unsigned netId, const char* interface,
Ken Chen4ea88462021-05-23 14:56:43 +0800847 const UidRangeMap& uidRangeMap, Permission permission,
Ken Chen8738e1c2020-11-24 11:38:54 +0800848 bool add, bool modifyNonUidBasedRules) {
Chiachang Wangf79e3562022-01-15 13:31:04 +0800849 uint32_t table = getRouteTableForInterface(interface, false /* local */);
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -0700850 if (table == RT_TABLE_UNSPEC) {
851 return -ESRCH;
852 }
853
Ken Chen4ea88462021-05-23 14:56:43 +0800854 for (const auto& [subPriority, uidRanges] : uidRangeMap) {
855 for (const UidRangeParcel& range : uidRanges.getRanges()) {
856 if (int ret = modifyUidNetworkRule(netId, table, range.start, range.stop, subPriority,
857 add, EXPLICIT)) {
858 return ret;
859 }
860 if (int ret = modifyUidNetworkRule(netId, table, range.start, range.stop, subPriority,
861 add, IMPLICIT)) {
862 return ret;
863 }
Patrick Rohre6f198c2022-01-25 13:50:31 +0100864 // SUB_PRIORITY_NO_DEFAULT is "special" and does not require a
865 // default network rule, see UidRanges.h.
866 if (subPriority != UidRanges::SUB_PRIORITY_NO_DEFAULT) {
867 if (int ret = modifyUidDefaultNetworkRule(table, range.start, range.stop,
868 subPriority, add)) {
869 return ret;
870 }
chiachangwang776b68c2022-05-17 05:16:16 +0000871
872 // Per-UID local network rules must always match per-app default network rules,
873 // because their purpose is to allow the UIDs to use the default network for
874 // local destinations within it.
875 if (int ret = modifyUidLocalNetworkRule(interface, range.start, range.stop, add)) {
876 return ret;
877 }
Ken Chen4ea88462021-05-23 14:56:43 +0800878 }
Ken Chen8738e1c2020-11-24 11:38:54 +0800879 }
880 }
881
882 if (!modifyNonUidBasedRules) {
883 // we are done.
884 return 0;
885 }
886
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -0700887 if (int ret = modifyIncomingPacketMark(netId, interface, permission, add)) {
888 return ret;
889 }
890 if (int ret = modifyExplicitNetworkRule(netId, table, permission, INVALID_UID, INVALID_UID,
Patrick Rohre2f1b5a2022-01-25 21:36:50 +0100891 UidRanges::SUB_PRIORITY_HIGHEST, add)) {
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -0700892 return ret;
893 }
Lorenzo Colitti57947f02015-02-27 16:45:55 +0900894 if (int ret = modifyOutputInterfaceRules(interface, table, permission, INVALID_UID, INVALID_UID,
Patrick Rohre2f1b5a2022-01-25 21:36:50 +0100895 UidRanges::SUB_PRIORITY_HIGHEST, add)) {
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -0700896 return ret;
897 }
Lorenzo Colittibe0c7c32017-09-06 16:07:02 +0900898
899 // Only set implicit rules for networks that don't require permissions.
900 //
901 // This is so that if the default network ceases to be the default network and then switches
902 // from requiring no permissions to requiring permissions, we ensure that apps only use the
903 // network if they explicitly select it. This is consistent with destroySocketsLackingPermission
904 // - it closes all sockets on the network except sockets that are explicitly selected.
905 //
906 // The lack of this rule only affects the special case above, because:
907 // - The only cases where we implicitly bind a socket to a network are the default network and
908 // the bypassable VPN that applies to the app, if any.
909 // - This rule doesn't affect VPNs because they don't support permissions at all.
910 // - The default network doesn't require permissions. While we support doing this, the framework
911 // never does it (partly because we'd end up in the situation where we tell apps that there is
912 // a default network, but they can't use it).
913 // - If the network is still the default network, the presence or absence of this rule does not
914 // matter.
915 //
916 // Therefore, for the lack of this rule to affect a socket, the socket has to have been
917 // implicitly bound to a network because at the time of connect() it was the default, and that
918 // network must no longer be the default, and must now require permissions.
919 if (permission == PERMISSION_NONE) {
920 return modifyImplicitNetworkRule(netId, table, add);
921 }
922 return 0;
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -0700923}
924
chiachangwang776b68c2022-05-17 05:16:16 +0000925int RouteController::modifyUidLocalNetworkRule(const char* interface, uid_t uidStart, uid_t uidEnd,
926 bool add) {
927 uint32_t table = getRouteTableForInterface(interface, true /* local */);
928 if (table == RT_TABLE_UNSPEC) {
929 return -ESRCH;
930 }
931
932 if ((uidStart == INVALID_UID) || (uidEnd == INVALID_UID)) {
933 ALOGE("modifyUidLocalNetworkRule, invalid UIDs (%u, %u)", uidStart, uidEnd);
934 return -EUSERS;
935 }
936
937 Fwmark fwmark;
938 Fwmark mask;
939
940 fwmark.explicitlySelected = false;
941 mask.explicitlySelected = true;
942
943 // Access to this network is controlled by UID rules, not permission bits.
944 fwmark.permission = PERMISSION_NONE;
945 mask.permission = PERMISSION_NONE;
946
947 return modifyIpRule(add ? RTM_NEWRULE : RTM_DELRULE, RULE_PRIORITY_UID_LOCAL_ROUTES, table,
948 fwmark.intValue, mask.intValue, IIF_LOOPBACK, OIF_NONE, uidStart, uidEnd);
949}
950
Ken Chen4e8ef9b2021-03-17 01:57:19 +0800951[[nodiscard]] static int modifyUidUnreachableRule(unsigned netId, uid_t uidStart, uid_t uidEnd,
Ken Chen53360bf2021-12-10 02:41:05 +0800952 int32_t subPriority, bool add,
Ken Chen4ea88462021-05-23 14:56:43 +0800953 bool explicitSelect) {
Ken Chen4e8ef9b2021-03-17 01:57:19 +0800954 if ((uidStart == INVALID_UID) || (uidEnd == INVALID_UID)) {
955 ALOGE("modifyUidUnreachableRule, invalid UIDs (%u, %u)", uidStart, uidEnd);
956 return -EUSERS;
957 }
958
959 Fwmark fwmark;
960 Fwmark mask;
961
962 fwmark.netId = netId;
963 mask.netId = FWMARK_NET_ID_MASK;
964
965 fwmark.explicitlySelected = explicitSelect;
966 mask.explicitlySelected = true;
967
968 // Access to this network is controlled by UID rules, not permission bits.
969 fwmark.permission = PERMISSION_NONE;
970 mask.permission = PERMISSION_NONE;
971
972 return modifyIpRule(add ? RTM_NEWRULE : RTM_DELRULE,
Ken Chen4ea88462021-05-23 14:56:43 +0800973 explicitSelect ? (RULE_PRIORITY_UID_EXPLICIT_NETWORK + subPriority)
974 : (RULE_PRIORITY_UID_IMPLICIT_NETWORK + subPriority),
Ken Chen4e8ef9b2021-03-17 01:57:19 +0800975 FR_ACT_UNREACHABLE, RT_TABLE_UNSPEC, fwmark.intValue, mask.intValue,
976 IIF_LOOPBACK, OIF_NONE, uidStart, uidEnd);
977}
978
Ken Chen4ea88462021-05-23 14:56:43 +0800979[[nodiscard]] static int modifyUidDefaultUnreachableRule(uid_t uidStart, uid_t uidEnd,
Ken Chen53360bf2021-12-10 02:41:05 +0800980 int32_t subPriority, bool add) {
Ken Chen4e8ef9b2021-03-17 01:57:19 +0800981 if ((uidStart == INVALID_UID) || (uidEnd == INVALID_UID)) {
Ken Chen4ea88462021-05-23 14:56:43 +0800982 ALOGE("modifyUidDefaultUnreachableRule, invalid UIDs (%u, %u)", uidStart, uidEnd);
Ken Chen4e8ef9b2021-03-17 01:57:19 +0800983 return -EUSERS;
984 }
985
986 Fwmark fwmark;
987 Fwmark mask;
988
989 fwmark.netId = NETID_UNSET;
990 mask.netId = FWMARK_NET_ID_MASK;
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
Ken Chen4ea88462021-05-23 14:56:43 +0800996 return modifyIpRule(add ? RTM_NEWRULE : RTM_DELRULE,
997 RULE_PRIORITY_UID_DEFAULT_UNREACHABLE + subPriority, FR_ACT_UNREACHABLE,
998 RT_TABLE_UNSPEC, fwmark.intValue, mask.intValue, IIF_LOOPBACK, OIF_NONE,
999 uidStart, uidEnd);
Ken Chen4e8ef9b2021-03-17 01:57:19 +08001000}
1001
Ken Chen4ea88462021-05-23 14:56:43 +08001002int RouteController::modifyUnreachableNetwork(unsigned netId, const UidRangeMap& uidRangeMap,
Ken Chen4e8ef9b2021-03-17 01:57:19 +08001003 bool add) {
Ken Chen4ea88462021-05-23 14:56:43 +08001004 for (const auto& [subPriority, uidRanges] : uidRangeMap) {
1005 for (const UidRangeParcel& range : uidRanges.getRanges()) {
1006 if (int ret = modifyUidUnreachableRule(netId, range.start, range.stop, subPriority, add,
1007 EXPLICIT)) {
1008 return ret;
1009 }
1010 if (int ret = modifyUidUnreachableRule(netId, range.start, range.stop, subPriority, add,
1011 IMPLICIT)) {
1012 return ret;
1013 }
1014 if (int ret = modifyUidDefaultUnreachableRule(range.start, range.stop, subPriority,
1015 add)) {
1016 return ret;
1017 }
Ken Chen4e8ef9b2021-03-17 01:57:19 +08001018 }
1019 }
1020
1021 return 0;
1022}
1023
Bernie Innocenti762dcf42019-06-14 19:52:49 +09001024[[nodiscard]] static int modifyRejectNonSecureNetworkRule(const UidRanges& uidRanges, bool add) {
Robin Leeb8087362016-03-30 18:43:08 +01001025 Fwmark fwmark;
1026 Fwmark mask;
1027 fwmark.protectedFromVpn = false;
1028 mask.protectedFromVpn = true;
1029
Luke Huang94658ac2018-10-18 19:35:12 +09001030 for (const UidRangeParcel& range : uidRanges.getRanges()) {
1031 if (int ret = modifyIpRule(add ? RTM_NEWRULE : RTM_DELRULE, RULE_PRIORITY_PROHIBIT_NON_VPN,
1032 FR_ACT_PROHIBIT, RT_TABLE_UNSPEC, fwmark.intValue, mask.intValue,
1033 IIF_LOOPBACK, OIF_NONE, range.start, range.stop)) {
Robin Leeb8087362016-03-30 18:43:08 +01001034 return ret;
1035 }
1036 }
1037
1038 return 0;
1039}
1040
Bernie Innocenti762dcf42019-06-14 19:52:49 +09001041int RouteController::modifyVirtualNetwork(unsigned netId, const char* interface,
Ken Chen4ea88462021-05-23 14:56:43 +08001042 const UidRangeMap& uidRangeMap, bool secure, bool add,
Chiachang Wang2e9443f2022-01-14 22:55:36 +08001043 bool modifyNonUidBasedRules, bool excludeLocalRoutes) {
Chiachang Wangf79e3562022-01-15 13:31:04 +08001044 uint32_t table = getRouteTableForInterface(interface, false /* false */);
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -07001045 if (table == RT_TABLE_UNSPEC) {
1046 return -ESRCH;
1047 }
1048
Ken Chen4ea88462021-05-23 14:56:43 +08001049 for (const auto& [subPriority, uidRanges] : uidRangeMap) {
1050 for (const UidRangeParcel& range : uidRanges.getRanges()) {
1051 if (int ret = modifyVpnUidRangeRule(table, range.start, range.stop, subPriority, secure,
Chiachang Wang2e9443f2022-01-14 22:55:36 +08001052 add, excludeLocalRoutes)) {
Ken Chen4ea88462021-05-23 14:56:43 +08001053 return ret;
1054 }
1055 if (int ret = modifyExplicitNetworkRule(netId, table, PERMISSION_NONE, range.start,
1056 range.stop, subPriority, add)) {
1057 return ret;
1058 }
1059 if (int ret = modifyOutputInterfaceRules(interface, table, PERMISSION_NONE, range.start,
1060 range.stop, subPriority, add)) {
1061 return ret;
1062 }
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -07001063 }
Sreeram Ramachandran4043f012014-06-23 12:41:37 -07001064 }
1065
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -07001066 if (modifyNonUidBasedRules) {
1067 if (int ret = modifyIncomingPacketMark(netId, interface, PERMISSION_NONE, add)) {
Sreeram Ramachandraneb27b7e2014-07-01 14:30:30 -07001068 return ret;
1069 }
Sreeram Ramachandran111bec22014-07-22 18:51:06 -07001070 if (int ret = modifyVpnOutputToLocalRule(interface, add)) {
1071 return ret;
1072 }
Chiachang Wang2e9443f2022-01-14 22:55:36 +08001073 if (int ret =
1074 modifyVpnSystemPermissionRule(netId, table, secure, add, excludeLocalRoutes)) {
Sreeram Ramachandranb1425cc2014-06-23 18:54:27 -07001075 return ret;
1076 }
Ken Chen4ea88462021-05-23 14:56:43 +08001077 return modifyExplicitNetworkRule(netId, table, PERMISSION_NONE, UID_ROOT, UID_ROOT,
Patrick Rohre2f1b5a2022-01-25 21:36:50 +01001078 UidRanges::SUB_PRIORITY_HIGHEST, add);
Sreeram Ramachandranb1425cc2014-06-23 18:54:27 -07001079 }
1080
1081 return 0;
Sreeram Ramachandran4043f012014-06-23 12:41:37 -07001082}
1083
Bernie Innocenti762dcf42019-06-14 19:52:49 +09001084int RouteController::modifyDefaultNetwork(uint16_t action, const char* interface,
1085 Permission permission) {
Chiachang Wangf79e3562022-01-15 13:31:04 +08001086 uint32_t table = getRouteTableForInterface(interface, false /* local */);
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -07001087 if (table == RT_TABLE_UNSPEC) {
Lorenzo Colitti96f261e2014-06-23 15:09:54 +09001088 return -ESRCH;
Sreeram Ramachandran9c0d3132014-04-10 20:35:04 -07001089 }
1090
Sreeram Ramachandran122f5812014-05-11 20:29:49 -07001091 Fwmark fwmark;
Sreeram Ramachandran122f5812014-05-11 20:29:49 -07001092 Fwmark mask;
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -07001093
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -07001094 fwmark.netId = NETID_UNSET;
Sreeram Ramachandran122f5812014-05-11 20:29:49 -07001095 mask.netId = FWMARK_NET_ID_MASK;
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -07001096
1097 fwmark.permission = permission;
Sreeram Ramachandran122f5812014-05-11 20:29:49 -07001098 mask.permission = permission;
1099
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -07001100 return modifyIpRule(action, RULE_PRIORITY_DEFAULT_NETWORK, table, fwmark.intValue,
Lorenzo Colitti758627c2018-03-15 01:49:20 +09001101 mask.intValue, IIF_LOOPBACK, OIF_NONE, INVALID_UID, INVALID_UID);
Sreeram Ramachandran7619e1b2014-04-15 14:23:08 -07001102}
1103
Bernie Innocenti762dcf42019-06-14 19:52:49 +09001104int RouteController::modifyTetheredNetwork(uint16_t action, const char* inputInterface,
1105 const char* outputInterface) {
Chiachang Wangf79e3562022-01-15 13:31:04 +08001106 uint32_t table = getRouteTableForInterface(outputInterface, false /* local */);
Sreeram Ramachandranfa9f4dc2014-07-22 18:16:44 -07001107 if (table == RT_TABLE_UNSPEC) {
1108 return -ESRCH;
1109 }
1110
1111 return modifyIpRule(action, RULE_PRIORITY_TETHERING, table, MARK_UNSET, MARK_UNSET,
1112 inputInterface, OIF_NONE, INVALID_UID, INVALID_UID);
1113}
1114
Lorenzo Colitti92e8f962017-09-26 19:13:50 +09001115// Adds or removes an IPv4 or IPv6 route to the specified table.
Lorenzo Colittif7fc8ec2014-06-18 00:41:58 +09001116// Returns 0 on success or negative errno on failure.
Tyler Wearfa94a272019-12-05 15:01:48 -08001117int RouteController::modifyRoute(uint16_t action, uint16_t flags, const char* interface,
1118 const char* destination, const char* nexthop, TableType tableType,
Chiachang89e504e2022-05-12 05:21:20 +00001119 int mtu, int priority, bool isLocal) {
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -07001120 uint32_t table;
Sreeram Ramachandran38b7af12014-05-22 14:21:49 -07001121 switch (tableType) {
1122 case RouteController::INTERFACE: {
Chiachang89e504e2022-05-12 05:21:20 +00001123 table = getRouteTableForInterface(interface, isLocal);
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -07001124 if (table == RT_TABLE_UNSPEC) {
1125 return -ESRCH;
1126 }
Sreeram Ramachandran38b7af12014-05-22 14:21:49 -07001127 break;
1128 }
Sreeram Ramachandran87475a12014-07-15 16:20:28 -07001129 case RouteController::LOCAL_NETWORK: {
1130 table = ROUTE_TABLE_LOCAL_NETWORK;
1131 break;
1132 }
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -07001133 case RouteController::LEGACY_NETWORK: {
Sreeram Ramachandran4acd34a2014-07-07 22:11:37 -07001134 table = ROUTE_TABLE_LEGACY_NETWORK;
Sreeram Ramachandran38b7af12014-05-22 14:21:49 -07001135 break;
1136 }
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -07001137 case RouteController::LEGACY_SYSTEM: {
Sreeram Ramachandran4acd34a2014-07-07 22:11:37 -07001138 table = ROUTE_TABLE_LEGACY_SYSTEM;
Sreeram Ramachandran38b7af12014-05-22 14:21:49 -07001139 break;
1140 }
1141 }
Sreeram Ramachandran9c0d3132014-04-10 20:35:04 -07001142
Taras Antoshchuk0cceda22021-09-24 18:40:03 +02001143 int ret = modifyIpRoute(action, flags, table, interface, destination, nexthop, mtu, priority);
Sreeram Ramachandran03213152014-10-30 10:01:07 -07001144 // Trying to add a route that already exists shouldn't cause an error.
1145 if (ret && !(action == RTM_NEWROUTE && ret == -EEXIST)) {
Lorenzo Colittif7fc8ec2014-06-18 00:41:58 +09001146 return ret;
Sreeram Ramachandranc9213372014-04-16 12:32:18 -07001147 }
1148
Lorenzo Colittif7fc8ec2014-06-18 00:41:58 +09001149 return 0;
Sreeram Ramachandran9c0d3132014-04-10 20:35:04 -07001150}
1151
Lorenzo Colitti3810c972021-01-06 11:44:02 +09001152static void maybeModifyQdiscClsact(const char* interface, bool add) {
Hungming Chen7f725432020-02-07 17:47:23 +08001153 // The clsact attaching of v4- tun interface is triggered by ClatdController::maybeStartBpf
1154 // because the clat is started before the v4- interface is added to the network and the
1155 // clat startup needs to add {in, e}gress filters.
1156 // TODO: remove this workaround once v4- tun interface clsact attaching is moved out from
1157 // ClatdController::maybeStartBpf.
1158 if (StartsWith(interface, "v4-") && add) return;
1159
1160 // The interface may have already gone away in the delete case.
Chiachang Wangf79e3562022-01-15 13:31:04 +08001161 uint32_t ifindex = RouteController::ifNameToIndexFunction(interface);
Hungming Chen7f725432020-02-07 17:47:23 +08001162 if (!ifindex) {
1163 ALOGE("cannot find interface %s", interface);
1164 return;
1165 }
1166
1167 if (add) {
1168 if (int ret = tcQdiscAddDevClsact(ifindex)) {
1169 ALOGE("tcQdiscAddDevClsact(%d[%s]) failure: %s", ifindex, interface, strerror(-ret));
1170 return;
1171 }
1172 } else {
1173 if (int ret = tcQdiscDelDevClsact(ifindex)) {
1174 ALOGE("tcQdiscDelDevClsact(%d[%s]) failure: %s", ifindex, interface, strerror(-ret));
1175 return;
1176 }
1177 }
1178
1179 return;
1180}
1181
Bernie Innocenti762dcf42019-06-14 19:52:49 +09001182[[nodiscard]] static int clearTetheringRules(const char* inputInterface) {
Lorenzo Colitti6b6f25f2015-03-03 17:22:57 +09001183 int ret = 0;
1184 while (ret == 0) {
1185 ret = modifyIpRule(RTM_DELRULE, RULE_PRIORITY_TETHERING, 0, MARK_UNSET, MARK_UNSET,
1186 inputInterface, OIF_NONE, INVALID_UID, INVALID_UID);
1187 }
1188
1189 if (ret == -ENOENT) {
1190 return 0;
1191 } else {
1192 return ret;
1193 }
1194}
1195
Lorenzo Colittif3e299a2017-02-14 17:24:28 +09001196uint32_t getRulePriority(const nlmsghdr *nlh) {
1197 return getRtmU32Attribute(nlh, FRA_PRIORITY);
1198}
1199
1200uint32_t getRouteTable(const nlmsghdr *nlh) {
1201 return getRtmU32Attribute(nlh, RTA_TABLE);
1202}
1203
Bernie Innocenti762dcf42019-06-14 19:52:49 +09001204[[nodiscard]] static int flushRules() {
Lorenzo Colittif3e299a2017-02-14 17:24:28 +09001205 NetlinkDumpFilter shouldDelete = [] (nlmsghdr *nlh) {
1206 // Don't touch rules at priority 0 because by default they are used for local input.
1207 return getRulePriority(nlh) != 0;
1208 };
1209 return rtNetlinkFlush(RTM_GETRULE, RTM_DELRULE, "rules", shouldDelete);
1210}
1211
Bernie Innocenti762dcf42019-06-14 19:52:49 +09001212int RouteController::flushRoutes(uint32_t table) {
Lorenzo Colittif3e299a2017-02-14 17:24:28 +09001213 NetlinkDumpFilter shouldDelete = [table] (nlmsghdr *nlh) {
1214 return getRouteTable(nlh) == table;
1215 };
1216
1217 return rtNetlinkFlush(RTM_GETROUTE, RTM_DELROUTE, "routes", shouldDelete);
1218}
1219
Bernie Innocenti762dcf42019-06-14 19:52:49 +09001220int RouteController::flushRoutes(const char* interface) {
Chiachang Wangf79e3562022-01-15 13:31:04 +08001221 // Try to flush both local and global routing tables.
1222 //
1223 // Flush local first because flush global routing tables may erase the sInterfaceToTable map.
1224 // Then the fake <iface>_local interface will be unable to find the index because the local
1225 // interface depends physical interface to find the correct index.
1226 int ret = flushRoutes(interface, true);
1227 ret |= flushRoutes(interface, false);
1228 return ret;
1229}
1230
1231// Returns 0 on success or negative errno on failure.
1232int RouteController::flushRoutes(const char* interface, bool local) {
Bernie Innocentiabf8a342018-08-10 15:17:16 +09001233 std::lock_guard lock(sInterfaceToTableLock);
Lorenzo Colitti107075a2017-10-30 19:24:46 +09001234
Chiachang Wangf79e3562022-01-15 13:31:04 +08001235 uint32_t table = getRouteTableForInterfaceLocked(interface, local);
Lorenzo Colittif3e299a2017-02-14 17:24:28 +09001236 if (table == RT_TABLE_UNSPEC) {
1237 return -ESRCH;
1238 }
1239
1240 int ret = flushRoutes(table);
1241
1242 // If we failed to flush routes, the caller may elect to keep this interface around, so keep
1243 // track of its name.
Chiachang Wangf79e3562022-01-15 13:31:04 +08001244 // Skip erasing local fake interface since it does not exist in sInterfaceToTable.
1245 if (ret == 0 && !local) {
Lorenzo Colitti02cb80a2017-10-30 19:21:06 +09001246 sInterfaceToTable.erase(interface);
Lorenzo Colittif3e299a2017-02-14 17:24:28 +09001247 }
1248
1249 return ret;
1250}
1251
Sreeram Ramachandran87475a12014-07-15 16:20:28 -07001252int RouteController::Init(unsigned localNetId) {
Sreeram Ramachandranb717e742014-07-19 00:22:15 -07001253 if (int ret = flushRules()) {
1254 return ret;
1255 }
Sreeram Ramachandran87475a12014-07-15 16:20:28 -07001256 if (int ret = addLegacyRouteRules()) {
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -07001257 return ret;
1258 }
Sreeram Ramachandranfa9f4dc2014-07-22 18:16:44 -07001259 if (int ret = addLocalNetworkRules(localNetId)) {
1260 return ret;
1261 }
Sreeram Ramachandranb717e742014-07-19 00:22:15 -07001262 if (int ret = addUnreachableRule()) {
1263 return ret;
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -07001264 }
Lorenzo Colitti36679362015-02-25 10:26:19 +09001265 // Don't complain if we can't add the dummy network, since not all devices support it.
1266 configureDummyNetwork();
1267
Sreeram Ramachandran4acd34a2014-07-07 22:11:37 -07001268 updateTableNamesFile();
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -07001269 return 0;
Sreeram Ramachandran8fe9c8e2014-04-16 12:08:05 -07001270}
1271
Sreeram Ramachandran6a773532014-07-11 09:10:20 -07001272int RouteController::addInterfaceToLocalNetwork(unsigned netId, const char* interface) {
Lorenzo Colittib6dc40a2020-03-24 00:58:50 +09001273 if (int ret = modifyLocalNetwork(netId, interface, ACTION_ADD)) {
1274 return ret;
1275 }
1276 std::lock_guard lock(sInterfaceToTableLock);
1277 sInterfaceToTable[interface] = ROUTE_TABLE_LOCAL_NETWORK;
1278 return 0;
Sreeram Ramachandran6a773532014-07-11 09:10:20 -07001279}
1280
1281int RouteController::removeInterfaceFromLocalNetwork(unsigned netId, const char* interface) {
Lorenzo Colittib6dc40a2020-03-24 00:58:50 +09001282 if (int ret = modifyLocalNetwork(netId, interface, ACTION_DEL)) {
1283 return ret;
1284 }
1285 std::lock_guard lock(sInterfaceToTableLock);
1286 sInterfaceToTable.erase(interface);
1287 return 0;
Sreeram Ramachandran6a773532014-07-11 09:10:20 -07001288}
1289
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -07001290int RouteController::addInterfaceToPhysicalNetwork(unsigned netId, const char* interface,
Ken Chen8738e1c2020-11-24 11:38:54 +08001291 Permission permission,
Ken Chen4ea88462021-05-23 14:56:43 +08001292 const UidRangeMap& uidRangeMap) {
1293 if (int ret = modifyPhysicalNetwork(netId, interface, uidRangeMap, permission, ACTION_ADD,
Ken Chen8738e1c2020-11-24 11:38:54 +08001294 MODIFY_NON_UID_BASED_RULES)) {
Sreeram Ramachandran4acd34a2014-07-07 22:11:37 -07001295 return ret;
1296 }
Chiachang Wange7bf5f52022-01-17 11:37:39 +08001297
Hungming Chen7f725432020-02-07 17:47:23 +08001298 maybeModifyQdiscClsact(interface, ACTION_ADD);
Sreeram Ramachandran4acd34a2014-07-07 22:11:37 -07001299 updateTableNamesFile();
1300 return 0;
Sreeram Ramachandran5c181bf2014-04-07 14:10:04 -07001301}
1302
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -07001303int RouteController::removeInterfaceFromPhysicalNetwork(unsigned netId, const char* interface,
Ken Chen8738e1c2020-11-24 11:38:54 +08001304 Permission permission,
Ken Chen4ea88462021-05-23 14:56:43 +08001305 const UidRangeMap& uidRangeMap) {
1306 if (int ret = modifyPhysicalNetwork(netId, interface, uidRangeMap, permission, ACTION_DEL,
Ken Chen8738e1c2020-11-24 11:38:54 +08001307 MODIFY_NON_UID_BASED_RULES)) {
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -07001308 return ret;
1309 }
Chiachang Wange7bf5f52022-01-17 11:37:39 +08001310
Chiachang8a03faa2022-05-04 07:45:37 +00001311 if (int ret = flushRoutes(interface)) {
Sreeram Ramachandran4acd34a2014-07-07 22:11:37 -07001312 return ret;
1313 }
Chiachang Wange7bf5f52022-01-17 11:37:39 +08001314
Lorenzo Colitti6b6f25f2015-03-03 17:22:57 +09001315 if (int ret = clearTetheringRules(interface)) {
1316 return ret;
1317 }
Chiachang Wange7bf5f52022-01-17 11:37:39 +08001318
Hungming Chen7f725432020-02-07 17:47:23 +08001319 maybeModifyQdiscClsact(interface, ACTION_DEL);
Sreeram Ramachandran4acd34a2014-07-07 22:11:37 -07001320 updateTableNamesFile();
1321 return 0;
Sreeram Ramachandran379bd332014-04-10 19:58:06 -07001322}
1323
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -07001324int RouteController::addInterfaceToVirtualNetwork(unsigned netId, const char* interface,
Chiachang Wang2e9443f2022-01-14 22:55:36 +08001325 bool secure, const UidRangeMap& uidRangeMap,
1326 bool excludeLocalRoutes) {
Ken Chen4ea88462021-05-23 14:56:43 +08001327 if (int ret = modifyVirtualNetwork(netId, interface, uidRangeMap, secure, ACTION_ADD,
Chiachang Wang2e9443f2022-01-14 22:55:36 +08001328 MODIFY_NON_UID_BASED_RULES, excludeLocalRoutes)) {
Sreeram Ramachandran4acd34a2014-07-07 22:11:37 -07001329 return ret;
1330 }
1331 updateTableNamesFile();
1332 return 0;
Sreeram Ramachandran4043f012014-06-23 12:41:37 -07001333}
1334
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -07001335int RouteController::removeInterfaceFromVirtualNetwork(unsigned netId, const char* interface,
Chiachang Wang2e9443f2022-01-14 22:55:36 +08001336 bool secure, const UidRangeMap& uidRangeMap,
1337 bool excludeLocalRoutes) {
Ken Chen4ea88462021-05-23 14:56:43 +08001338 if (int ret = modifyVirtualNetwork(netId, interface, uidRangeMap, secure, ACTION_DEL,
Chiachang Wang2e9443f2022-01-14 22:55:36 +08001339 MODIFY_NON_UID_BASED_RULES, excludeLocalRoutes)) {
Sreeram Ramachandran4043f012014-06-23 12:41:37 -07001340 return ret;
1341 }
Sreeram Ramachandran4acd34a2014-07-07 22:11:37 -07001342 if (int ret = flushRoutes(interface)) {
1343 return ret;
1344 }
1345 updateTableNamesFile();
1346 return 0;
Sreeram Ramachandran4043f012014-06-23 12:41:37 -07001347}
1348
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -07001349int RouteController::modifyPhysicalNetworkPermission(unsigned netId, const char* interface,
1350 Permission oldPermission,
1351 Permission newPermission) {
Ken Chen4ea88462021-05-23 14:56:43 +08001352 // Physical network rules either use permission bits or UIDs, but not both.
1353 // So permission changes don't affect any UID-based rules.
1354 UidRangeMap emptyUidRangeMap;
Sreeram Ramachandran379bd332014-04-10 19:58:06 -07001355 // Add the new rules before deleting the old ones, to avoid race conditions.
Ken Chen4ea88462021-05-23 14:56:43 +08001356 if (int ret = modifyPhysicalNetwork(netId, interface, emptyUidRangeMap, newPermission,
1357 ACTION_ADD, MODIFY_NON_UID_BASED_RULES)) {
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -07001358 return ret;
1359 }
Ken Chen4ea88462021-05-23 14:56:43 +08001360 return modifyPhysicalNetwork(netId, interface, emptyUidRangeMap, oldPermission, ACTION_DEL,
Ken Chen8738e1c2020-11-24 11:38:54 +08001361 MODIFY_NON_UID_BASED_RULES);
Sreeram Ramachandranb1425cc2014-06-23 18:54:27 -07001362}
1363
Robin Leeb8087362016-03-30 18:43:08 +01001364int RouteController::addUsersToRejectNonSecureNetworkRule(const UidRanges& uidRanges) {
1365 return modifyRejectNonSecureNetworkRule(uidRanges, true);
1366}
1367
1368int RouteController::removeUsersFromRejectNonSecureNetworkRule(const UidRanges& uidRanges) {
1369 return modifyRejectNonSecureNetworkRule(uidRanges, false);
1370}
1371
Sreeram Ramachandran95684ba2014-07-23 13:27:31 -07001372int RouteController::addUsersToVirtualNetwork(unsigned netId, const char* interface, bool secure,
Chiachang Wang2e9443f2022-01-14 22:55:36 +08001373 const UidRangeMap& uidRangeMap,
1374 bool excludeLocalRoutes) {
Ken Chen4ea88462021-05-23 14:56:43 +08001375 return modifyVirtualNetwork(netId, interface, uidRangeMap, secure, ACTION_ADD,
Chiachang Wang2e9443f2022-01-14 22:55:36 +08001376 !MODIFY_NON_UID_BASED_RULES, excludeLocalRoutes);
Sreeram Ramachandranb1425cc2014-06-23 18:54:27 -07001377}
1378
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -07001379int RouteController::removeUsersFromVirtualNetwork(unsigned netId, const char* interface,
Chiachang Wang2e9443f2022-01-14 22:55:36 +08001380 bool secure, const UidRangeMap& uidRangeMap,
1381 bool excludeLocalRoutes) {
Ken Chen4ea88462021-05-23 14:56:43 +08001382 return modifyVirtualNetwork(netId, interface, uidRangeMap, secure, ACTION_DEL,
Chiachang Wang2e9443f2022-01-14 22:55:36 +08001383 !MODIFY_NON_UID_BASED_RULES, excludeLocalRoutes);
Sreeram Ramachandran9c0d3132014-04-10 20:35:04 -07001384}
1385
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -07001386int RouteController::addInterfaceToDefaultNetwork(const char* interface, Permission permission) {
1387 return modifyDefaultNetwork(RTM_NEWRULE, interface, permission);
Sreeram Ramachandran9c0d3132014-04-10 20:35:04 -07001388}
1389
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -07001390int RouteController::removeInterfaceFromDefaultNetwork(const char* interface,
1391 Permission permission) {
1392 return modifyDefaultNetwork(RTM_DELRULE, interface, permission);
Sreeram Ramachandran5c181bf2014-04-07 14:10:04 -07001393}
Sreeram Ramachandran7619e1b2014-04-15 14:23:08 -07001394
Chiachang3aa56612022-05-12 05:55:45 +00001395bool RouteController::isTargetV4LocalRange(const char* dst) {
1396 for (IPPrefix addr : V4_LOCAL_ADDR) {
1397 if (addr.contains(IPPrefix::forString(dst))) {
1398 return true;
1399 }
1400 }
1401 return false;
1402}
1403
Chiachang89e504e2022-05-12 05:21:20 +00001404bool RouteController::isLocalAddress(TableType tableType, const char* destination,
1405 const char* nexthop) {
1406 IPPrefix prefix = IPPrefix::forString(destination);
Chiachang89e504e2022-05-12 05:21:20 +00001407 return nexthop == nullptr && tableType == RouteController::INTERFACE &&
1408 // Skip default route to prevent network being modeled as point-to-point interfaces.
Chiachang3aa56612022-05-12 05:55:45 +00001409 ((prefix.family() == AF_INET6 && prefix != IPPrefix::forString("::/0")) ||
1410 // Skip adding non-target local network range.
1411 (prefix.family() == AF_INET && isTargetV4LocalRange(destination)));
Chiachang89e504e2022-05-12 05:21:20 +00001412}
1413
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -07001414int RouteController::addRoute(const char* interface, const char* destination, const char* nexthop,
Taras Antoshchuk0cceda22021-09-24 18:40:03 +02001415 TableType tableType, int mtu, int priority) {
Chiachang89e504e2022-05-12 05:21:20 +00001416 if (int ret = modifyRoute(RTM_NEWROUTE, NETLINK_ROUTE_CREATE_FLAGS, interface, destination,
1417 nexthop, tableType, mtu, priority, false /* isLocal */)) {
1418 return ret;
1419 }
1420
1421 if (isLocalAddress(tableType, destination, nexthop)) {
1422 return modifyRoute(RTM_NEWROUTE, NETLINK_ROUTE_CREATE_FLAGS, interface, destination,
1423 nexthop, tableType, mtu, priority, true /* isLocal */);
1424 }
1425
1426 return 0;
Sreeram Ramachandran7619e1b2014-04-15 14:23:08 -07001427}
1428
Lorenzo Colittif7fc8ec2014-06-18 00:41:58 +09001429int RouteController::removeRoute(const char* interface, const char* destination,
Taras Antoshchuk0cceda22021-09-24 18:40:03 +02001430 const char* nexthop, TableType tableType, int priority) {
Chiachang89e504e2022-05-12 05:21:20 +00001431 if (int ret = modifyRoute(RTM_DELROUTE, NETLINK_REQUEST_FLAGS, interface, destination, nexthop,
1432 tableType, 0 /* mtu */, priority, false /* isLocal */)) {
1433 return ret;
1434 }
1435
1436 if (isLocalAddress(tableType, destination, nexthop)) {
1437 return modifyRoute(RTM_DELROUTE, NETLINK_REQUEST_FLAGS, interface, destination, nexthop,
1438 tableType, 0 /* mtu */, priority, true /* isLocal */);
1439 }
1440 return 0;
Tyler Wearfa94a272019-12-05 15:01:48 -08001441}
1442
1443int RouteController::updateRoute(const char* interface, const char* destination,
1444 const char* nexthop, TableType tableType, int mtu) {
Chiachang89e504e2022-05-12 05:21:20 +00001445 if (int ret = modifyRoute(RTM_NEWROUTE, NETLINK_ROUTE_REPLACE_FLAGS, interface, destination,
1446 nexthop, tableType, mtu, 0 /* priority */, false /* isLocal */)) {
1447 return ret;
1448 }
1449
1450 if (isLocalAddress(tableType, destination, nexthop)) {
1451 return modifyRoute(RTM_NEWROUTE, NETLINK_ROUTE_REPLACE_FLAGS, interface, destination,
1452 nexthop, tableType, mtu, 0 /* priority */, true /* isLocal */);
1453 }
1454 return 0;
Sreeram Ramachandran7619e1b2014-04-15 14:23:08 -07001455}
Sreeram Ramachandran87475a12014-07-15 16:20:28 -07001456
1457int RouteController::enableTethering(const char* inputInterface, const char* outputInterface) {
Sreeram Ramachandranfa9f4dc2014-07-22 18:16:44 -07001458 return modifyTetheredNetwork(RTM_NEWRULE, inputInterface, outputInterface);
Sreeram Ramachandran87475a12014-07-15 16:20:28 -07001459}
1460
1461int RouteController::disableTethering(const char* inputInterface, const char* outputInterface) {
Sreeram Ramachandranfa9f4dc2014-07-22 18:16:44 -07001462 return modifyTetheredNetwork(RTM_DELRULE, inputInterface, outputInterface);
Sreeram Ramachandran87475a12014-07-15 16:20:28 -07001463}
Sreeram Ramachandran48e19b02014-07-22 22:23:20 -07001464
1465int RouteController::addVirtualNetworkFallthrough(unsigned vpnNetId, const char* physicalInterface,
1466 Permission permission) {
Chiachang8a03faa2022-05-04 07:45:37 +00001467 if (int ret = modifyVpnFallthroughRule(RTM_NEWRULE, vpnNetId, physicalInterface, permission)) {
1468 return ret;
1469 }
1470
1471 return modifyVpnLocalExclusionRule(true /* add */, physicalInterface);
Sreeram Ramachandran48e19b02014-07-22 22:23:20 -07001472}
1473
1474int RouteController::removeVirtualNetworkFallthrough(unsigned vpnNetId,
1475 const char* physicalInterface,
1476 Permission permission) {
Chiachang8a03faa2022-05-04 07:45:37 +00001477 if (int ret = modifyVpnFallthroughRule(RTM_DELRULE, vpnNetId, physicalInterface, permission)) {
1478 return ret;
1479 }
1480
1481 return modifyVpnLocalExclusionRule(false /* add */, physicalInterface);
Sreeram Ramachandran48e19b02014-07-22 22:23:20 -07001482}
Lorenzo Colitti7035f222017-02-13 18:29:00 +09001483
Ken Chen8738e1c2020-11-24 11:38:54 +08001484int RouteController::addUsersToPhysicalNetwork(unsigned netId, const char* interface,
Ken Chen4ea88462021-05-23 14:56:43 +08001485 const UidRangeMap& uidRangeMap) {
1486 return modifyPhysicalNetwork(netId, interface, uidRangeMap, PERMISSION_NONE, ACTION_ADD,
Ken Chen8738e1c2020-11-24 11:38:54 +08001487 !MODIFY_NON_UID_BASED_RULES);
1488}
1489
1490int RouteController::removeUsersFromPhysicalNetwork(unsigned netId, const char* interface,
Ken Chen4ea88462021-05-23 14:56:43 +08001491 const UidRangeMap& uidRangeMap) {
1492 return modifyPhysicalNetwork(netId, interface, uidRangeMap, PERMISSION_NONE, ACTION_DEL,
Ken Chen8738e1c2020-11-24 11:38:54 +08001493 !MODIFY_NON_UID_BASED_RULES);
1494}
1495
Ken Chen4ea88462021-05-23 14:56:43 +08001496int RouteController::addUsersToUnreachableNetwork(unsigned netId, const UidRangeMap& uidRangeMap) {
1497 return modifyUnreachableNetwork(netId, uidRangeMap, ACTION_ADD);
Ken Chen4e8ef9b2021-03-17 01:57:19 +08001498}
1499
Ken Chen4ea88462021-05-23 14:56:43 +08001500int RouteController::removeUsersFromUnreachableNetwork(unsigned netId,
1501 const UidRangeMap& uidRangeMap) {
1502 return modifyUnreachableNetwork(netId, uidRangeMap, ACTION_DEL);
Ken Chen4e8ef9b2021-03-17 01:57:19 +08001503}
1504
Lorenzo Colitti107075a2017-10-30 19:24:46 +09001505// Protects sInterfaceToTable.
Luke Huang534980c2018-07-06 17:50:11 +08001506std::mutex RouteController::sInterfaceToTableLock;
Lorenzo Colitti02cb80a2017-10-30 19:21:06 +09001507std::map<std::string, uint32_t> RouteController::sInterfaceToTable;
1508
Bernie Innocenti762dcf42019-06-14 19:52:49 +09001509} // namespace android::net