blob: be3017349eb984d530c7deb4f654760544abfdac [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
chiachangwang9542a1e2022-06-15 02:42:44 +000067const IPPrefix V4_LOCAL_PREFIXES[] = {
Chiachang3aa56612022-05-12 05:55:45 +000068 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);
dongziqi107f0162023-10-31 16:17:42 +0800222 for (const auto& [ifName, table] : sInterfaceToTable) {
223 if (table <= ROUTE_TABLE_OFFSET_FROM_INDEX) {
224 continue;
225 }
226 addTableName(table, ifName, &contents);
Chiachang Wangf79e3562022-01-15 13:31:04 +0800227 // 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;
dongziqi107f0162023-10-31 16:17:42 +0800231 addTableName(offset + table, ifName + INTERFACE_LOCAL_SUFFIX, &contents);
Sreeram Ramachandran4acd34a2014-07-07 22:11:37 -0700232 }
233
Dan Albert5407e142015-03-16 10:05:59 -0700234 if (!WriteStringToFile(contents, RT_TABLES_PATH, RT_TABLES_MODE, AID_SYSTEM, AID_WIFI)) {
Elliott Hughesbd378322015-02-04 13:25:14 -0800235 ALOGE("failed to write to %s (%s)", RT_TABLES_PATH, strerror(errno));
Sreeram Ramachandran4acd34a2014-07-07 22:11:37 -0700236 return;
237 }
Sreeram Ramachandran5c181bf2014-04-07 14:10:04 -0700238}
239
Sreeram Ramachandran87475a12014-07-15 16:20:28 -0700240// Returns 0 on success or negative errno on failure.
241int 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
Sreeram Ramachandran8fe9c8e2014-04-16 12:08:05 -0700256// Adds or removes a routing rule for IPv4 and IPv6.
257//
Lorenzo Colitti6b6f25f2015-03-03 17:22:57 +0900258// + If |table| is non-zero, the rule points at the specified routing table. Otherwise, the table is
Robin Lee4ef94642016-04-01 11:50:49 +0100259// unspecified. An unspecified table is not allowed when creating an FR_ACT_TO_TBL rule.
Sreeram Ramachandran8fe9c8e2014-04-16 12:08:05 -0700260// + If |mask| is non-zero, the rule matches the specified fwmark and mask. Otherwise, |fwmark| is
261// ignored.
Sreeram Ramachandran87475a12014-07-15 16:20:28 -0700262// + 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.
Lorenzo Colitti96f261e2014-06-23 15:09:54 +0900266//
267// Returns 0 on success or negative errno on failure.
Ken Chen53360bf2021-12-10 02:41:05 +0800268[[nodiscard]] static int modifyIpRule(uint16_t action, int32_t priority, uint8_t ruleType,
Bernie Innocenti762dcf42019-06-14 19:52:49 +0900269 uint32_t table, uint32_t fwmark, uint32_t mask,
270 const char* iif, const char* oif, uid_t uidStart,
271 uid_t uidEnd) {
Ken Chen53360bf2021-12-10 02:41:05 +0800272 if (priority < 0) {
273 ALOGE("invalid IP-rule priority %d", priority);
274 return -ERANGE;
275 }
276
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700277 // 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
Sreeram Ramachandran87475a12014-07-15 16:20:28 -0700283 // Interface names must include exactly one terminating NULL and be properly padded, or older
Lorenzo Colitti4753afd2014-06-20 23:03:29 +0900284 // kernels will refuse to delete rules.
Sreeram Ramachandran87475a12014-07-15 16:20:28 -0700285 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;
Lorenzo Colitti4753afd2014-06-20 23:03:29 +0900293 }
294
Lorenzo Colitti59656512014-06-25 03:20:29 +0900295 // Either both start and end UID must be specified, or neither.
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700296 if ((uidStart == INVALID_UID) != (uidEnd == INVALID_UID)) {
Sreeram Ramachandrancf891382014-07-01 15:49:20 -0700297 ALOGE("incompatible start and end UIDs (%u vs %u)", uidStart, uidEnd);
Lorenzo Colitti59656512014-06-25 03:20:29 +0900298 return -EUSERS;
299 }
Robin Lee4ef94642016-04-01 11:50:49 +0100300
Lorenzo Colitti72723682014-06-26 13:51:10 +0900301 bool isUidRule = (uidStart != INVALID_UID);
Lorenzo Colitti59656512014-06-25 03:20:29 +0900302
Lorenzo Colitti4753afd2014-06-20 23:03:29 +0900303 // Assemble a rule request and put it in an array of iovec structures.
304 fib_rule_hdr rule = {
Robin Lee4ef94642016-04-01 11:50:49 +0100305 .action = ruleType,
Lorenzo Colitti6b6f25f2015-03-03 17:22:57 +0900306 // 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.
Lorenzo Colitti4753afd2014-06-20 23:03:29 +0900308 };
309
Lorenzo Colitti6b6f25f2015-03-03 17:22:57 +0900310 // 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
Sreeram Ramachandran87475a12014-07-15 16:20:28 -0700318 rtattr fraIifName = { U16_RTA_LENGTH(iifLength), FRA_IIFNAME };
319 rtattr fraOifName = { U16_RTA_LENGTH(oifLength), FRA_OIFNAME };
Lorenzo Colitti2b078672016-12-16 18:45:03 +0900320 struct fib_rule_uid_range uidRange = { uidStart, uidEnd };
Lorenzo Colitti4753afd2014-06-20 23:03:29 +0900321
322 iovec iov[] = {
Yi Kongbdfd57e2018-07-25 13:26:10 -0700323 { nullptr, 0 },
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700324 { &rule, sizeof(rule) },
325 { &FRATTR_PRIORITY, sizeof(FRATTR_PRIORITY) },
326 { &priority, sizeof(priority) },
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -0700327 { &FRATTR_TABLE, table != RT_TABLE_UNSPEC ? sizeof(FRATTR_TABLE) : 0 },
328 { &table, table != RT_TABLE_UNSPEC ? sizeof(table) : 0 },
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700329 { &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 },
Lorenzo Colitti2b078672016-12-16 18:45:03 +0900333 { &FRATTR_UID_RANGE, isUidRule ? sizeof(FRATTR_UID_RANGE) : 0 },
334 { &uidRange, isUidRule ? sizeof(uidRange) : 0 },
Sreeram Ramachandran87475a12014-07-15 16:20:28 -0700335 { &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 },
Lorenzo Colitti4753afd2014-06-20 23:03:29 +0900341 };
342
Lorenzo Colitti5c437992017-11-28 01:26:02 +0900343 uint16_t flags = (action == RTM_NEWRULE) ? NETLINK_RULE_CREATE_FLAGS : NETLINK_REQUEST_FLAGS;
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700344 for (size_t i = 0; i < ARRAY_SIZE(AF_FAMILIES); ++i) {
345 rule.family = AF_FAMILIES[i];
Lorenzo Colittif3e299a2017-02-14 17:24:28 +0900346 if (int ret = sendNetlinkRequest(action, flags, iov, ARRAY_SIZE(iov), nullptr)) {
Lorenzo Colitti220ca732017-02-14 17:57:55 +0900347 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 }
Lorenzo Colitti96f261e2014-06-23 15:09:54 +0900353 return ret;
Sreeram Ramachandran5c181bf2014-04-07 14:10:04 -0700354 }
355 }
356
Lorenzo Colitti96f261e2014-06-23 15:09:54 +0900357 return 0;
Sreeram Ramachandran5c181bf2014-04-07 14:10:04 -0700358}
359
Ken Chen53360bf2021-12-10 02:41:05 +0800360[[nodiscard]] static int modifyIpRule(uint16_t action, int32_t priority, uint32_t table,
Bernie Innocenti762dcf42019-06-14 19:52:49 +0900361 uint32_t fwmark, uint32_t mask, const char* iif,
362 const char* oif, uid_t uidStart, uid_t uidEnd) {
Robin Lee4ef94642016-04-01 11:50:49 +0100363 return modifyIpRule(action, priority, FR_ACT_TO_TBL, table, fwmark, mask, iif, oif, uidStart,
364 uidEnd);
365}
366
Ken Chen53360bf2021-12-10 02:41:05 +0800367[[nodiscard]] static int modifyIpRule(uint16_t action, int32_t priority, uint32_t table,
Bernie Innocenti762dcf42019-06-14 19:52:49 +0900368 uint32_t fwmark, uint32_t mask) {
Sreeram Ramachandran87475a12014-07-15 16:20:28 -0700369 return modifyIpRule(action, priority, table, fwmark, mask, IIF_NONE, OIF_NONE, INVALID_UID,
370 INVALID_UID);
371}
372
Lorenzo Colittiba25df92014-06-18 00:22:17 +0900373// Adds or deletes an IPv4 or IPv6 route.
374// Returns 0 on success or negative errno on failure.
Tyler Wearfa94a272019-12-05 15:01:48 -0800375int modifyIpRoute(uint16_t action, uint16_t flags, uint32_t table, const char* interface,
Taras Antoshchuk0cceda22021-09-24 18:40:03 +0200376 const char* destination, const char* nexthop, uint32_t mtu, uint32_t priority) {
Lorenzo Colittiba25df92014-06-18 00:22:17 +0900377 // At least the destination must be non-null.
378 if (!destination) {
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700379 ALOGE("null destination");
Lorenzo Colittiba25df92014-06-18 00:22:17 +0900380 return -EFAULT;
381 }
Sreeram Ramachandran7619e1b2014-04-15 14:23:08 -0700382
Lorenzo Colittiba25df92014-06-18 00:22:17 +0900383 // Parse the prefix.
384 uint8_t rawAddress[sizeof(in6_addr)];
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700385 uint8_t family;
386 uint8_t prefixLength;
Lorenzo Colittiba25df92014-06-18 00:22:17 +0900387 int rawLength = parsePrefix(destination, &family, rawAddress, sizeof(rawAddress),
388 &prefixLength);
389 if (rawLength < 0) {
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700390 ALOGE("parsePrefix failed for destination %s (%s)", destination, strerror(-rawLength));
Lorenzo Colittiba25df92014-06-18 00:22:17 +0900391 return rawLength;
392 }
Sreeram Ramachandran7619e1b2014-04-15 14:23:08 -0700393
Lorenzo Colittiba25df92014-06-18 00:22:17 +0900394 if (static_cast<size_t>(rawLength) > sizeof(rawAddress)) {
Sreeram Ramachandran1201e842014-07-01 15:06:05 -0700395 ALOGE("impossible! address too long (%d vs %zu)", rawLength, sizeof(rawAddress));
Lorenzo Colittiba25df92014-06-18 00:22:17 +0900396 return -ENOBUFS; // Cannot happen; parsePrefix only supports IPv4 and IPv6.
397 }
398
Sreeram Ramachandrande5d5df2014-07-26 18:43:25 -0700399 uint8_t type = RTN_UNICAST;
Lorenzo Colittiba25df92014-06-18 00:22:17 +0900400 uint32_t ifindex;
Lorenzo Colittiba25df92014-06-18 00:22:17 +0900401 uint8_t rawNexthop[sizeof(in6_addr)];
Sreeram Ramachandrande5d5df2014-07-26 18:43:25 -0700402
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;
Yi Kongbdfd57e2018-07-25 13:26:10 -0700409 nexthop = nullptr;
Lorenzo Colitti4c95a122014-09-18 16:01:50 +0900410 } else if (nexthop && !strcmp(nexthop, "throw")) {
411 type = RTN_THROW;
412 interface = OIF_NONE;
Yi Kongbdfd57e2018-07-25 13:26:10 -0700413 nexthop = nullptr;
Sreeram Ramachandrande5d5df2014-07-26 18:43:25 -0700414 } else {
415 // If an interface was specified, find the ifindex.
416 if (interface != OIF_NONE) {
Chiachang Wangf79e3562022-01-15 13:31:04 +0800417 ifindex = RouteController::ifNameToIndexFunction(interface);
418
Sreeram Ramachandrande5d5df2014-07-26 18:43:25 -0700419 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 }
Lorenzo Colittiba25df92014-06-18 00:22:17 +0900430 }
431
Lorenzo Colitti4753afd2014-06-20 23:03:29 +0900432 // Assemble a rtmsg and put it in an array of iovec structures.
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700433 rtmsg route = {
Nick Desaulniers6b357502019-10-11 09:26:44 -0700434 .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,
Lorenzo Colittiba25df92014-06-18 00:22:17 +0900439 };
Lorenzo Colitti4753afd2014-06-20 23:03:29 +0900440
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700441 rtattr rtaDst = { U16_RTA_LENGTH(rawLength), RTA_DST };
442 rtattr rtaGateway = { U16_RTA_LENGTH(rawLength), RTA_GATEWAY };
Lorenzo Colittiba25df92014-06-18 00:22:17 +0900443
444 iovec iov[] = {
Taras Antoshchuk0cceda22021-09-24 18:40:03 +0200445 {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},
Lorenzo Colittiba25df92014-06-18 00:22:17 +0900460 };
Lorenzo Colittiba25df92014-06-18 00:22:17 +0900461
Jimmy Chence9e5782019-03-08 16:12:55 +0800462 // 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
Lorenzo Colittif3e299a2017-02-14 17:24:28 +0900468 int ret = sendNetlinkRequest(action, flags, iov, ARRAY_SIZE(iov), nullptr);
Lorenzo Colitti0b073fb2017-02-10 07:49:12 +0900469 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;
Sreeram Ramachandran7619e1b2014-04-15 14:23:08 -0700474}
475
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -0700476// 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.
Bernie Innocenti762dcf42019-06-14 19:52:49 +0900483int modifyIncomingPacketMark(unsigned netId, const char* interface, Permission permission,
484 bool add) {
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -0700485 Fwmark fwmark;
486
487 fwmark.netId = netId;
488 fwmark.explicitlySelected = true;
489 fwmark.protectedFromVpn = true;
490 fwmark.permission = permission;
491
Maciej Żenczykowski0a47ca42023-11-15 08:00:03 +0000492 const uint32_t mask = Fwmark::getUidBillingMask() | Fwmark::getIngressCpuWakeupMask();
Benedict Wongb9baf262017-12-03 15:43:08 -0800493
494 std::string cmd = StringPrintf(
495 "%s %s -i %s -j MARK --set-mark 0x%x/0x%x", add ? "-A" : "-D",
Maciej Żenczykowski0a47ca42023-11-15 08:00:03 +0000496 RouteController::LOCAL_MANGLE_INPUT, interface, fwmark.intValue, ~mask);
Lorenzo Colittic1306ea2017-03-27 05:52:31 +0900497 if (RouteController::iptablesRestoreCommandFunction(V4V6, "mangle", cmd, nullptr) != 0) {
Sreeram Ramachandranb1425cc2014-06-23 18:54:27 -0700498 ALOGE("failed to change iptables rule that sets incoming packet mark");
499 return -EREMOTEIO;
500 }
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -0700501
Sreeram Ramachandranb1425cc2014-06-23 18:54:27 -0700502 return 0;
503}
504
Sreeram Ramachandran111bec22014-07-22 18:51:06 -0700505// 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.
Bernie Innocenti762dcf42019-06-14 19:52:49 +0900509[[nodiscard]] static int modifyVpnOutputToLocalRule(const char* vpnInterface, bool add) {
Sreeram Ramachandran111bec22014-07-22 18:51:06 -0700510 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
Sreeram Ramachandranfa9f4dc2014-07-22 18:16:44 -0700515// 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.
Bernie Innocenti762dcf42019-06-14 19:52:49 +0900520[[nodiscard]] static int modifyVpnUidRangeRule(uint32_t table, uid_t uidStart, uid_t uidEnd,
Chiachang Wang2e9443f2022-01-14 22:55:36 +0800521 int32_t subPriority, bool secure, bool add,
522 bool excludeLocalRoutes) {
Sreeram Ramachandranfa9f4dc2014-07-22 18:16:44 -0700523 Fwmark fwmark;
524 Fwmark mask;
525
526 fwmark.protectedFromVpn = false;
527 mask.protectedFromVpn = true;
528
Ken Chen53360bf2021-12-10 02:41:05 +0800529 int32_t priority;
Sreeram Ramachandran95684ba2014-07-23 13:27:31 -0700530
531 if (secure) {
532 priority = RULE_PRIORITY_SECURE_VPN;
533 } else {
Chiachang Wang2e9443f2022-01-14 22:55:36 +0800534 priority = excludeLocalRoutes ? RULE_PRIORITY_BYPASSABLE_VPN_LOCAL_EXCLUSION
535 : RULE_PRIORITY_BYPASSABLE_VPN_NO_LOCAL_EXCLUSION;
Sreeram Ramachandran95684ba2014-07-23 13:27:31 -0700536
537 fwmark.explicitlySelected = false;
538 mask.explicitlySelected = true;
539 }
540
Ken Chen4ea88462021-05-23 14:56:43 +0800541 return modifyIpRule(add ? RTM_NEWRULE : RTM_DELRULE, priority + subPriority, table,
542 fwmark.intValue, mask.intValue, IIF_LOOPBACK, OIF_NONE, uidStart, uidEnd);
Sreeram Ramachandranfa9f4dc2014-07-22 18:16:44 -0700543}
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.
Bernie Innocenti762dcf42019-06-14 19:52:49 +0900550[[nodiscard]] static int modifyVpnSystemPermissionRule(unsigned netId, uint32_t table, bool secure,
Chiachang Wang2e9443f2022-01-14 22:55:36 +0800551 bool add, bool excludeLocalRoutes) {
Sreeram Ramachandranfa9f4dc2014-07-22 18:16:44 -0700552 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
Chiachang Wang2e9443f2022-01-14 22:55:36 +0800561 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 }
Sreeram Ramachandran95684ba2014-07-23 13:27:31 -0700569
570 return modifyIpRule(add ? RTM_NEWRULE : RTM_DELRULE, priority, table, fwmark.intValue,
571 mask.intValue);
Sreeram Ramachandranfa9f4dc2014-07-22 18:16:44 -0700572}
573
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -0700574// 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().
Bernie Innocenti762dcf42019-06-14 19:52:49 +0900581[[nodiscard]] static int modifyExplicitNetworkRule(unsigned netId, uint32_t table,
582 Permission permission, uid_t uidStart,
Ken Chen53360bf2021-12-10 02:41:05 +0800583 uid_t uidEnd, int32_t subPriority, bool add) {
Sreeram Ramachandraneb27b7e2014-07-01 14:30:30 -0700584 Fwmark fwmark;
585 Fwmark mask;
586
587 fwmark.netId = netId;
588 mask.netId = FWMARK_NET_ID_MASK;
589
Sreeram Ramachandran122f5812014-05-11 20:29:49 -0700590 fwmark.explicitlySelected = true;
591 mask.explicitlySelected = true;
Sreeram Ramachandran5c181bf2014-04-07 14:10:04 -0700592
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -0700593 fwmark.permission = permission;
594 mask.permission = permission;
Sreeram Ramachandraneb27b7e2014-07-01 14:30:30 -0700595
Ken Chen4ea88462021-05-23 14:56:43 +0800596 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);
Sreeram Ramachandran5c181bf2014-04-07 14:10:04 -0700599}
600
Chalard Jeane479f312022-12-12 18:27:49 +0900601// 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//
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
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -0700629// 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).
Bernie Innocenti762dcf42019-06-14 19:52:49 +0900633[[nodiscard]] static int modifyOutputInterfaceRules(const char* interface, uint32_t table,
634 Permission permission, uid_t uidStart,
Ken Chen53360bf2021-12-10 02:41:05 +0800635 uid_t uidEnd, int32_t subPriority, bool add) {
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -0700636 Fwmark fwmark;
637 Fwmark mask;
Sreeram Ramachandran4043f012014-06-23 12:41:37 -0700638
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -0700639 fwmark.permission = permission;
640 mask.permission = permission;
Sreeram Ramachandranb1425cc2014-06-23 18:54:27 -0700641
Lorenzo Colitti57947f02015-02-27 16:45:55 +0900642 // If this rule does not specify a UID range, then also add a corresponding high-priority rule
Lorenzo Colitti758627c2018-03-15 01:49:20 +0900643 // for root. This covers kernel-originated packets, TEEd packets and any local daemons that open
644 // sockets as root.
Lorenzo Colitti57947f02015-02-27 16:45:55 +0900645 if (uidStart == INVALID_UID && uidEnd == INVALID_UID) {
646 if (int ret = modifyIpRule(add ? RTM_NEWRULE : RTM_DELRULE, RULE_PRIORITY_VPN_OVERRIDE_OIF,
Lorenzo Colitti758627c2018-03-15 01:49:20 +0900647 table, FWMARK_NONE, MASK_NONE, IIF_LOOPBACK, interface,
Lorenzo Colitti57947f02015-02-27 16:45:55 +0900648 UID_ROOT, UID_ROOT)) {
649 return ret;
650 }
651 }
652
Ken Chen4ea88462021-05-23 14:56:43 +0800653 return modifyIpRule(add ? RTM_NEWRULE : RTM_DELRULE,
654 RULE_PRIORITY_OUTPUT_INTERFACE + subPriority, table, fwmark.intValue,
655 mask.intValue, IIF_LOOPBACK, interface, uidStart, uidEnd);
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -0700656}
657
Chiachang Wang8b9cdd22022-01-27 10:43:28 +0800658int RouteController::modifyVpnLocalExclusionRule(bool add, const char* physicalInterface) {
Chiachang Wange7bf5f52022-01-17 11:37:39 +0800659 uint32_t table = getRouteTableForInterface(physicalInterface, true /* local */);
660 if (table == RT_TABLE_UNSPEC) {
661 return -ESRCH;
662 }
663
664 Fwmark fwmark;
665 Fwmark mask;
666
667 fwmark.explicitlySelected = false;
668 mask.explicitlySelected = true;
669
670 fwmark.permission = PERMISSION_NONE;
671 mask.permission = PERMISSION_NONE;
672
chiachangwang31902a42022-04-15 20:06:27 +0800673 return modifyIpRule(add ? RTM_NEWRULE : RTM_DELRULE, RULE_PRIORITY_LOCAL_ROUTES, table,
674 fwmark.intValue, mask.intValue, IIF_LOOPBACK, OIF_NONE, INVALID_UID,
675 INVALID_UID);
Chiachang Wange7bf5f52022-01-17 11:37:39 +0800676}
677
chiachangwangb7a60992022-08-25 06:55:19 +0000678int RouteController::addFixedLocalRoutes(const char* interface) {
679 for (size_t i = 0; i < ARRAY_SIZE(V4_FIXED_LOCAL_PREFIXES); ++i) {
680 if (int ret = modifyRoute(RTM_NEWROUTE, NETLINK_ROUTE_CREATE_FLAGS, interface,
681 V4_FIXED_LOCAL_PREFIXES[i], nullptr /* nexthop */,
682 RouteController::INTERFACE, 0 /* mtu */, 0 /* priority */,
683 true /* isLocal */)) {
684 return ret;
685 }
686 }
687
688 return 0;
689}
690
Sreeram Ramachandran48e19b02014-07-22 22:23:20 -0700691// A rule to enable split tunnel VPNs.
692//
693// 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 +0800694// go over the default network, provided it has the permissions required by the default network.
Bernie Innocenti762dcf42019-06-14 19:52:49 +0900695int RouteController::modifyVpnFallthroughRule(uint16_t action, unsigned vpnNetId,
696 const char* physicalInterface,
697 Permission permission) {
Chiachang Wangf79e3562022-01-15 13:31:04 +0800698 uint32_t table = getRouteTableForInterface(physicalInterface, false /* local */);
Sreeram Ramachandran48e19b02014-07-22 22:23:20 -0700699 if (table == RT_TABLE_UNSPEC) {
700 return -ESRCH;
701 }
702
703 Fwmark fwmark;
704 Fwmark mask;
705
706 fwmark.netId = vpnNetId;
707 mask.netId = FWMARK_NET_ID_MASK;
708
Tommy Webb9ed91ab2023-02-28 10:46:05 -0500709 // This fallthrough rule does not consider allowed UIDs at all, so limit it to system perm.
710 permission = PERMISSION_SYSTEM;
711
Sreeram Ramachandran48e19b02014-07-22 22:23:20 -0700712 fwmark.permission = permission;
713 mask.permission = permission;
714
715 return modifyIpRule(action, RULE_PRIORITY_VPN_FALLTHROUGH, table, fwmark.intValue,
716 mask.intValue);
717}
718
Sreeram Ramachandranfa9f4dc2014-07-22 18:16:44 -0700719// Add rules to allow legacy routes added through the requestRouteToHost() API.
Bernie Innocenti762dcf42019-06-14 19:52:49 +0900720[[nodiscard]] static int addLegacyRouteRules() {
Sreeram Ramachandran4043f012014-06-23 12:41:37 -0700721 Fwmark fwmark;
722 Fwmark mask;
723
Sreeram Ramachandranfa9f4dc2014-07-22 18:16:44 -0700724 fwmark.explicitlySelected = false;
725 mask.explicitlySelected = true;
Sreeram Ramachandranb1425cc2014-06-23 18:54:27 -0700726
Sreeram Ramachandranfa9f4dc2014-07-22 18:16:44 -0700727 // Rules to allow legacy routes to override the default network.
728 if (int ret = modifyIpRule(RTM_NEWRULE, RULE_PRIORITY_LEGACY_SYSTEM, ROUTE_TABLE_LEGACY_SYSTEM,
729 fwmark.intValue, mask.intValue)) {
730 return ret;
731 }
732 if (int ret = modifyIpRule(RTM_NEWRULE, RULE_PRIORITY_LEGACY_NETWORK,
733 ROUTE_TABLE_LEGACY_NETWORK, fwmark.intValue, mask.intValue)) {
734 return ret;
735 }
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -0700736
737 fwmark.permission = PERMISSION_SYSTEM;
738 mask.permission = PERMISSION_SYSTEM;
739
Sreeram Ramachandranfa9f4dc2014-07-22 18:16:44 -0700740 // A rule to allow legacy routes from system apps to override VPNs.
741 return modifyIpRule(RTM_NEWRULE, RULE_PRIORITY_VPN_OVERRIDE_SYSTEM, ROUTE_TABLE_LEGACY_SYSTEM,
Sreeram Ramachandran87475a12014-07-15 16:20:28 -0700742 fwmark.intValue, mask.intValue);
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -0700743}
744
Sreeram Ramachandranfa9f4dc2014-07-22 18:16:44 -0700745// Add rules to lookup the local network when specified explicitly or otherwise.
Bernie Innocenti762dcf42019-06-14 19:52:49 +0900746[[nodiscard]] static int addLocalNetworkRules(unsigned localNetId) {
Sreeram Ramachandranfa9f4dc2014-07-22 18:16:44 -0700747 if (int ret = modifyExplicitNetworkRule(localNetId, ROUTE_TABLE_LOCAL_NETWORK, PERMISSION_NONE,
Ken Chen4ea88462021-05-23 14:56:43 +0800748 INVALID_UID, INVALID_UID,
Patrick Rohre2f1b5a2022-01-25 21:36:50 +0100749 UidRanges::SUB_PRIORITY_HIGHEST, ACTION_ADD)) {
Sreeram Ramachandranfa9f4dc2014-07-22 18:16:44 -0700750 return ret;
Sreeram Ramachandran6a773532014-07-11 09:10:20 -0700751 }
752
Sreeram Ramachandranfa9f4dc2014-07-22 18:16:44 -0700753 Fwmark fwmark;
754 Fwmark mask;
755
756 fwmark.explicitlySelected = false;
757 mask.explicitlySelected = true;
758
759 return modifyIpRule(RTM_NEWRULE, RULE_PRIORITY_LOCAL_NETWORK, ROUTE_TABLE_LOCAL_NETWORK,
760 fwmark.intValue, mask.intValue);
761}
762
Lorenzo Colitti02cb80a2017-10-30 19:21:06 +0900763/* static */
764int RouteController::configureDummyNetwork() {
Lorenzo Colitti36679362015-02-25 10:26:19 +0900765 const char *interface = DummyNetwork::INTERFACE_NAME;
Chiachang Wangf79e3562022-01-15 13:31:04 +0800766 uint32_t table = getRouteTableForInterface(interface, false /* local */);
Lorenzo Colitti36679362015-02-25 10:26:19 +0900767 if (table == RT_TABLE_UNSPEC) {
Hungming Chen7f725432020-02-07 17:47:23 +0800768 // getRouteTableForInterface has already logged an error.
Lorenzo Colitti36679362015-02-25 10:26:19 +0900769 return -ESRCH;
770 }
771
772 ifc_init();
773 int ret = ifc_up(interface);
774 ifc_close();
775 if (ret) {
776 ALOGE("Can't bring up %s: %s", interface, strerror(errno));
777 return -errno;
778 }
779
Ken Chen4ea88462021-05-23 14:56:43 +0800780 if ((ret = modifyOutputInterfaceRules(interface, table, PERMISSION_NONE, INVALID_UID,
Patrick Rohre2f1b5a2022-01-25 21:36:50 +0100781 INVALID_UID, UidRanges::SUB_PRIORITY_HIGHEST,
Ken Chen4ea88462021-05-23 14:56:43 +0800782 ACTION_ADD))) {
Lorenzo Colitti57947f02015-02-27 16:45:55 +0900783 ALOGE("Can't create oif rules for %s: %s", interface, strerror(-ret));
Lorenzo Colitti36679362015-02-25 10:26:19 +0900784 return ret;
785 }
786
Tyler Wearfa94a272019-12-05 15:01:48 -0800787 if ((ret = modifyIpRoute(RTM_NEWROUTE, NETLINK_ROUTE_CREATE_FLAGS, table, interface,
Taras Antoshchuk0cceda22021-09-24 18:40:03 +0200788 "0.0.0.0/0", nullptr, 0 /* mtu */, 0 /* priority */))) {
Lorenzo Colitti36679362015-02-25 10:26:19 +0900789 return ret;
790 }
791
Tyler Wearfa94a272019-12-05 15:01:48 -0800792 if ((ret = modifyIpRoute(RTM_NEWROUTE, NETLINK_ROUTE_CREATE_FLAGS, table, interface, "::/0",
Taras Antoshchuk0cceda22021-09-24 18:40:03 +0200793 nullptr, 0 /* mtu */, 0 /* priority */))) {
Lorenzo Colitti36679362015-02-25 10:26:19 +0900794 return ret;
795 }
796
797 return 0;
798}
799
Lorenzo Colittidb74dba2014-07-29 18:26:21 +0900800// Add an explicit unreachable rule close to the end of the prioriy list to make it clear that
801// relying on the kernel-default "from all lookup main" rule at priority 32766 is not intended
802// behaviour. We do flush the kernel-default rules at startup, but having an explicit unreachable
803// rule will hopefully make things even clearer.
Bernie Innocenti762dcf42019-06-14 19:52:49 +0900804[[nodiscard]] static int addUnreachableRule() {
Robin Leec125fe42016-05-02 08:53:34 +0100805 return modifyIpRule(RTM_NEWRULE, RULE_PRIORITY_UNREACHABLE, FR_ACT_UNREACHABLE, RT_TABLE_UNSPEC,
806 MARK_UNSET, MARK_UNSET, IIF_NONE, OIF_NONE, INVALID_UID, INVALID_UID);
Sreeram Ramachandran87475a12014-07-15 16:20:28 -0700807}
808
Bernie Innocenti762dcf42019-06-14 19:52:49 +0900809[[nodiscard]] static int modifyLocalNetwork(unsigned netId, const char* interface, bool add) {
Sreeram Ramachandran6a773532014-07-11 09:10:20 -0700810 if (int ret = modifyIncomingPacketMark(netId, interface, PERMISSION_NONE, add)) {
811 return ret;
812 }
Lorenzo Colitti3810c972021-01-06 11:44:02 +0900813 maybeModifyQdiscClsact(interface, add);
Lorenzo Colitti57947f02015-02-27 16:45:55 +0900814 return modifyOutputInterfaceRules(interface, ROUTE_TABLE_LOCAL_NETWORK, PERMISSION_NONE,
Patrick Rohre2f1b5a2022-01-25 21:36:50 +0100815 INVALID_UID, INVALID_UID, UidRanges::SUB_PRIORITY_HIGHEST,
Ken Chen4ea88462021-05-23 14:56:43 +0800816 add);
Sreeram Ramachandran6a773532014-07-11 09:10:20 -0700817}
818
Ken Chena2206ec2021-03-24 17:15:44 +0800819[[nodiscard]] static int modifyUidNetworkRule(unsigned netId, uint32_t table, uid_t uidStart,
Ken Chen53360bf2021-12-10 02:41:05 +0800820 uid_t uidEnd, int32_t subPriority, bool add,
Ken Chen4ea88462021-05-23 14:56:43 +0800821 bool explicitSelect) {
Ken Chen8738e1c2020-11-24 11:38:54 +0800822 if ((uidStart == INVALID_UID) || (uidEnd == INVALID_UID)) {
Ken Chena2206ec2021-03-24 17:15:44 +0800823 ALOGE("modifyUidNetworkRule, invalid UIDs (%u, %u)", uidStart, uidEnd);
Ken Chen8738e1c2020-11-24 11:38:54 +0800824 return -EUSERS;
825 }
826
827 Fwmark fwmark;
828 Fwmark mask;
829
830 fwmark.netId = netId;
831 mask.netId = FWMARK_NET_ID_MASK;
832
Ken Chena2206ec2021-03-24 17:15:44 +0800833 fwmark.explicitlySelected = explicitSelect;
Ken Chen8738e1c2020-11-24 11:38:54 +0800834 mask.explicitlySelected = true;
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 Chena2206ec2021-03-24 17:15:44 +0800840 return modifyIpRule(add ? RTM_NEWRULE : RTM_DELRULE,
Ken Chen4ea88462021-05-23 14:56:43 +0800841 explicitSelect ? (RULE_PRIORITY_UID_EXPLICIT_NETWORK + subPriority)
842 : (RULE_PRIORITY_UID_IMPLICIT_NETWORK + subPriority),
Ken Chena2206ec2021-03-24 17:15:44 +0800843 table, fwmark.intValue, mask.intValue, IIF_LOOPBACK, OIF_NONE, uidStart,
844 uidEnd);
Ken Chen8738e1c2020-11-24 11:38:54 +0800845}
846
847[[nodiscard]] static int modifyUidDefaultNetworkRule(uint32_t table, uid_t uidStart, uid_t uidEnd,
Ken Chen53360bf2021-12-10 02:41:05 +0800848 int32_t subPriority, bool add) {
Ken Chen8738e1c2020-11-24 11:38:54 +0800849 if ((uidStart == INVALID_UID) || (uidEnd == INVALID_UID)) {
850 ALOGE("modifyUidDefaultNetworkRule, invalid UIDs (%u, %u)", uidStart, uidEnd);
851 return -EUSERS;
852 }
853
854 Fwmark fwmark;
855 Fwmark mask;
856
857 fwmark.netId = NETID_UNSET;
858 mask.netId = FWMARK_NET_ID_MASK;
859
860 // Access to this network is controlled by UID rules, not permission bits.
861 fwmark.permission = PERMISSION_NONE;
862 mask.permission = PERMISSION_NONE;
863
Ken Chen4ea88462021-05-23 14:56:43 +0800864 return modifyIpRule(add ? RTM_NEWRULE : RTM_DELRULE,
865 RULE_PRIORITY_UID_DEFAULT_NETWORK + subPriority, table, fwmark.intValue,
866 mask.intValue, IIF_LOOPBACK, OIF_NONE, uidStart, uidEnd);
Ken Chen8738e1c2020-11-24 11:38:54 +0800867}
868
Lorenzo Colitti02cb80a2017-10-30 19:21:06 +0900869/* static */
Bernie Innocenti762dcf42019-06-14 19:52:49 +0900870int RouteController::modifyPhysicalNetwork(unsigned netId, const char* interface,
Ken Chen4ea88462021-05-23 14:56:43 +0800871 const UidRangeMap& uidRangeMap, Permission permission,
Chalard Jeane479f312022-12-12 18:27:49 +0900872 bool add, bool modifyNonUidBasedRules, bool local) {
Chiachang Wangf79e3562022-01-15 13:31:04 +0800873 uint32_t table = getRouteTableForInterface(interface, false /* local */);
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -0700874 if (table == RT_TABLE_UNSPEC) {
875 return -ESRCH;
876 }
877
Ken Chen4ea88462021-05-23 14:56:43 +0800878 for (const auto& [subPriority, uidRanges] : uidRangeMap) {
879 for (const UidRangeParcel& range : uidRanges.getRanges()) {
880 if (int ret = modifyUidNetworkRule(netId, table, range.start, range.stop, subPriority,
881 add, EXPLICIT)) {
882 return ret;
883 }
884 if (int ret = modifyUidNetworkRule(netId, table, range.start, range.stop, subPriority,
885 add, IMPLICIT)) {
886 return ret;
887 }
Patrick Rohre6f198c2022-01-25 13:50:31 +0100888 // SUB_PRIORITY_NO_DEFAULT is "special" and does not require a
889 // default network rule, see UidRanges.h.
890 if (subPriority != UidRanges::SUB_PRIORITY_NO_DEFAULT) {
891 if (int ret = modifyUidDefaultNetworkRule(table, range.start, range.stop,
892 subPriority, add)) {
893 return ret;
894 }
chiachangwang776b68c2022-05-17 05:16:16 +0000895
896 // Per-UID local network rules must always match per-app default network rules,
897 // because their purpose is to allow the UIDs to use the default network for
898 // local destinations within it.
899 if (int ret = modifyUidLocalNetworkRule(interface, range.start, range.stop, add)) {
900 return ret;
901 }
Ken Chen4ea88462021-05-23 14:56:43 +0800902 }
Ken Chen8738e1c2020-11-24 11:38:54 +0800903 }
904 }
905
906 if (!modifyNonUidBasedRules) {
907 // we are done.
908 return 0;
909 }
910
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -0700911 if (int ret = modifyIncomingPacketMark(netId, interface, permission, add)) {
912 return ret;
913 }
914 if (int ret = modifyExplicitNetworkRule(netId, table, permission, INVALID_UID, INVALID_UID,
Patrick Rohre2f1b5a2022-01-25 21:36:50 +0100915 UidRanges::SUB_PRIORITY_HIGHEST, add)) {
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -0700916 return ret;
917 }
Chalard Jeane479f312022-12-12 18:27:49 +0900918 if (local) {
919 if (const int ret = modifyLocalNetworkRule(table, add)) {
920 return ret;
921 }
922 }
Tommy Webb9ed91ab2023-02-28 10:46:05 -0500923 if (int ret = modifyOutputInterfaceRules(interface, table, PERMISSION_SYSTEM, INVALID_UID,
924 INVALID_UID,
Patrick Rohre2f1b5a2022-01-25 21:36:50 +0100925 UidRanges::SUB_PRIORITY_HIGHEST, add)) {
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -0700926 return ret;
927 }
Lorenzo Colittibe0c7c32017-09-06 16:07:02 +0900928
Lorenzo Colittibe0c7c32017-09-06 16:07:02 +0900929 return 0;
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -0700930}
931
chiachangwang776b68c2022-05-17 05:16:16 +0000932int RouteController::modifyUidLocalNetworkRule(const char* interface, uid_t uidStart, uid_t uidEnd,
933 bool add) {
934 uint32_t table = getRouteTableForInterface(interface, true /* local */);
935 if (table == RT_TABLE_UNSPEC) {
936 return -ESRCH;
937 }
938
939 if ((uidStart == INVALID_UID) || (uidEnd == INVALID_UID)) {
940 ALOGE("modifyUidLocalNetworkRule, invalid UIDs (%u, %u)", uidStart, uidEnd);
941 return -EUSERS;
942 }
943
944 Fwmark fwmark;
945 Fwmark mask;
946
947 fwmark.explicitlySelected = false;
948 mask.explicitlySelected = true;
949
950 // Access to this network is controlled by UID rules, not permission bits.
951 fwmark.permission = PERMISSION_NONE;
952 mask.permission = PERMISSION_NONE;
953
954 return modifyIpRule(add ? RTM_NEWRULE : RTM_DELRULE, RULE_PRIORITY_UID_LOCAL_ROUTES, table,
955 fwmark.intValue, mask.intValue, IIF_LOOPBACK, OIF_NONE, uidStart, uidEnd);
956}
957
Ken Chen4e8ef9b2021-03-17 01:57:19 +0800958[[nodiscard]] static int modifyUidUnreachableRule(unsigned netId, uid_t uidStart, uid_t uidEnd,
Ken Chen53360bf2021-12-10 02:41:05 +0800959 int32_t subPriority, bool add,
Ken Chen4ea88462021-05-23 14:56:43 +0800960 bool explicitSelect) {
Ken Chen4e8ef9b2021-03-17 01:57:19 +0800961 if ((uidStart == INVALID_UID) || (uidEnd == INVALID_UID)) {
962 ALOGE("modifyUidUnreachableRule, invalid UIDs (%u, %u)", uidStart, uidEnd);
963 return -EUSERS;
964 }
965
966 Fwmark fwmark;
967 Fwmark mask;
968
969 fwmark.netId = netId;
970 mask.netId = FWMARK_NET_ID_MASK;
971
972 fwmark.explicitlySelected = explicitSelect;
973 mask.explicitlySelected = true;
974
975 // Access to this network is controlled by UID rules, not permission bits.
976 fwmark.permission = PERMISSION_NONE;
977 mask.permission = PERMISSION_NONE;
978
979 return modifyIpRule(add ? RTM_NEWRULE : RTM_DELRULE,
Ken Chen4ea88462021-05-23 14:56:43 +0800980 explicitSelect ? (RULE_PRIORITY_UID_EXPLICIT_NETWORK + subPriority)
981 : (RULE_PRIORITY_UID_IMPLICIT_NETWORK + subPriority),
Ken Chen4e8ef9b2021-03-17 01:57:19 +0800982 FR_ACT_UNREACHABLE, RT_TABLE_UNSPEC, fwmark.intValue, mask.intValue,
983 IIF_LOOPBACK, OIF_NONE, uidStart, uidEnd);
984}
985
Ken Chen4ea88462021-05-23 14:56:43 +0800986[[nodiscard]] static int modifyUidDefaultUnreachableRule(uid_t uidStart, uid_t uidEnd,
Ken Chen53360bf2021-12-10 02:41:05 +0800987 int32_t subPriority, bool add) {
Ken Chen4e8ef9b2021-03-17 01:57:19 +0800988 if ((uidStart == INVALID_UID) || (uidEnd == INVALID_UID)) {
Ken Chen4ea88462021-05-23 14:56:43 +0800989 ALOGE("modifyUidDefaultUnreachableRule, invalid UIDs (%u, %u)", uidStart, uidEnd);
Ken Chen4e8ef9b2021-03-17 01:57:19 +0800990 return -EUSERS;
991 }
992
993 Fwmark fwmark;
994 Fwmark mask;
995
996 fwmark.netId = NETID_UNSET;
997 mask.netId = FWMARK_NET_ID_MASK;
998
999 // Access to this network is controlled by UID rules, not permission bits.
1000 fwmark.permission = PERMISSION_NONE;
1001 mask.permission = PERMISSION_NONE;
1002
Ken Chen4ea88462021-05-23 14:56:43 +08001003 return modifyIpRule(add ? RTM_NEWRULE : RTM_DELRULE,
1004 RULE_PRIORITY_UID_DEFAULT_UNREACHABLE + subPriority, FR_ACT_UNREACHABLE,
1005 RT_TABLE_UNSPEC, fwmark.intValue, mask.intValue, IIF_LOOPBACK, OIF_NONE,
1006 uidStart, uidEnd);
Ken Chen4e8ef9b2021-03-17 01:57:19 +08001007}
1008
Ken Chen4ea88462021-05-23 14:56:43 +08001009int RouteController::modifyUnreachableNetwork(unsigned netId, const UidRangeMap& uidRangeMap,
Ken Chen4e8ef9b2021-03-17 01:57:19 +08001010 bool add) {
Ken Chen4ea88462021-05-23 14:56:43 +08001011 for (const auto& [subPriority, uidRanges] : uidRangeMap) {
1012 for (const UidRangeParcel& range : uidRanges.getRanges()) {
1013 if (int ret = modifyUidUnreachableRule(netId, range.start, range.stop, subPriority, add,
1014 EXPLICIT)) {
1015 return ret;
1016 }
1017 if (int ret = modifyUidUnreachableRule(netId, range.start, range.stop, subPriority, add,
1018 IMPLICIT)) {
1019 return ret;
1020 }
1021 if (int ret = modifyUidDefaultUnreachableRule(range.start, range.stop, subPriority,
1022 add)) {
1023 return ret;
1024 }
Ken Chen4e8ef9b2021-03-17 01:57:19 +08001025 }
1026 }
1027
1028 return 0;
1029}
1030
Bernie Innocenti762dcf42019-06-14 19:52:49 +09001031[[nodiscard]] static int modifyRejectNonSecureNetworkRule(const UidRanges& uidRanges, bool add) {
Robin Leeb8087362016-03-30 18:43:08 +01001032 Fwmark fwmark;
1033 Fwmark mask;
1034 fwmark.protectedFromVpn = false;
1035 mask.protectedFromVpn = true;
1036
Luke Huang94658ac2018-10-18 19:35:12 +09001037 for (const UidRangeParcel& range : uidRanges.getRanges()) {
1038 if (int ret = modifyIpRule(add ? RTM_NEWRULE : RTM_DELRULE, RULE_PRIORITY_PROHIBIT_NON_VPN,
1039 FR_ACT_PROHIBIT, RT_TABLE_UNSPEC, fwmark.intValue, mask.intValue,
1040 IIF_LOOPBACK, OIF_NONE, range.start, range.stop)) {
Robin Leeb8087362016-03-30 18:43:08 +01001041 return ret;
1042 }
1043 }
1044
1045 return 0;
1046}
1047
Bernie Innocenti762dcf42019-06-14 19:52:49 +09001048int RouteController::modifyVirtualNetwork(unsigned netId, const char* interface,
Ken Chen4ea88462021-05-23 14:56:43 +08001049 const UidRangeMap& uidRangeMap, bool secure, bool add,
Chiachang Wang2e9443f2022-01-14 22:55:36 +08001050 bool modifyNonUidBasedRules, bool excludeLocalRoutes) {
Chiachang Wangf79e3562022-01-15 13:31:04 +08001051 uint32_t table = getRouteTableForInterface(interface, false /* false */);
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -07001052 if (table == RT_TABLE_UNSPEC) {
1053 return -ESRCH;
1054 }
1055
Ken Chen4ea88462021-05-23 14:56:43 +08001056 for (const auto& [subPriority, uidRanges] : uidRangeMap) {
1057 for (const UidRangeParcel& range : uidRanges.getRanges()) {
1058 if (int ret = modifyVpnUidRangeRule(table, range.start, range.stop, subPriority, secure,
Chiachang Wang2e9443f2022-01-14 22:55:36 +08001059 add, excludeLocalRoutes)) {
Ken Chen4ea88462021-05-23 14:56:43 +08001060 return ret;
1061 }
1062 if (int ret = modifyExplicitNetworkRule(netId, table, PERMISSION_NONE, range.start,
1063 range.stop, subPriority, add)) {
1064 return ret;
1065 }
1066 if (int ret = modifyOutputInterfaceRules(interface, table, PERMISSION_NONE, range.start,
1067 range.stop, subPriority, add)) {
1068 return ret;
1069 }
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -07001070 }
Sreeram Ramachandran4043f012014-06-23 12:41:37 -07001071 }
1072
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -07001073 if (modifyNonUidBasedRules) {
1074 if (int ret = modifyIncomingPacketMark(netId, interface, PERMISSION_NONE, add)) {
Sreeram Ramachandraneb27b7e2014-07-01 14:30:30 -07001075 return ret;
1076 }
Sreeram Ramachandran111bec22014-07-22 18:51:06 -07001077 if (int ret = modifyVpnOutputToLocalRule(interface, add)) {
1078 return ret;
1079 }
Chiachang Wang2e9443f2022-01-14 22:55:36 +08001080 if (int ret =
1081 modifyVpnSystemPermissionRule(netId, table, secure, add, excludeLocalRoutes)) {
Sreeram Ramachandranb1425cc2014-06-23 18:54:27 -07001082 return ret;
1083 }
Ken Chen4ea88462021-05-23 14:56:43 +08001084 return modifyExplicitNetworkRule(netId, table, PERMISSION_NONE, UID_ROOT, UID_ROOT,
Patrick Rohre2f1b5a2022-01-25 21:36:50 +01001085 UidRanges::SUB_PRIORITY_HIGHEST, add);
Sreeram Ramachandranb1425cc2014-06-23 18:54:27 -07001086 }
1087
1088 return 0;
Sreeram Ramachandran4043f012014-06-23 12:41:37 -07001089}
1090
Bernie Innocenti762dcf42019-06-14 19:52:49 +09001091int RouteController::modifyDefaultNetwork(uint16_t action, const char* interface,
1092 Permission permission) {
Chiachang Wangf79e3562022-01-15 13:31:04 +08001093 uint32_t table = getRouteTableForInterface(interface, false /* local */);
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -07001094 if (table == RT_TABLE_UNSPEC) {
Lorenzo Colitti96f261e2014-06-23 15:09:54 +09001095 return -ESRCH;
Sreeram Ramachandran9c0d3132014-04-10 20:35:04 -07001096 }
1097
Sreeram Ramachandran122f5812014-05-11 20:29:49 -07001098 Fwmark fwmark;
Sreeram Ramachandran122f5812014-05-11 20:29:49 -07001099 Fwmark mask;
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -07001100
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -07001101 fwmark.netId = NETID_UNSET;
Sreeram Ramachandran122f5812014-05-11 20:29:49 -07001102 mask.netId = FWMARK_NET_ID_MASK;
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -07001103
Tommy Webb9ed91ab2023-02-28 10:46:05 -05001104 // This default network rule does not consider allowed UIDs at all, so limit it to system perm.
1105 permission = PERMISSION_SYSTEM;
1106
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -07001107 fwmark.permission = permission;
Sreeram Ramachandran122f5812014-05-11 20:29:49 -07001108 mask.permission = permission;
1109
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -07001110 return modifyIpRule(action, RULE_PRIORITY_DEFAULT_NETWORK, table, fwmark.intValue,
Lorenzo Colitti758627c2018-03-15 01:49:20 +09001111 mask.intValue, IIF_LOOPBACK, OIF_NONE, INVALID_UID, INVALID_UID);
Sreeram Ramachandran7619e1b2014-04-15 14:23:08 -07001112}
1113
Bernie Innocenti762dcf42019-06-14 19:52:49 +09001114int RouteController::modifyTetheredNetwork(uint16_t action, const char* inputInterface,
1115 const char* outputInterface) {
Chiachang Wangf79e3562022-01-15 13:31:04 +08001116 uint32_t table = getRouteTableForInterface(outputInterface, false /* local */);
Sreeram Ramachandranfa9f4dc2014-07-22 18:16:44 -07001117 if (table == RT_TABLE_UNSPEC) {
1118 return -ESRCH;
1119 }
1120
1121 return modifyIpRule(action, RULE_PRIORITY_TETHERING, table, MARK_UNSET, MARK_UNSET,
1122 inputInterface, OIF_NONE, INVALID_UID, INVALID_UID);
1123}
1124
Lorenzo Colitti92e8f962017-09-26 19:13:50 +09001125// Adds or removes an IPv4 or IPv6 route to the specified table.
Lorenzo Colittif7fc8ec2014-06-18 00:41:58 +09001126// Returns 0 on success or negative errno on failure.
Tyler Wearfa94a272019-12-05 15:01:48 -08001127int RouteController::modifyRoute(uint16_t action, uint16_t flags, const char* interface,
1128 const char* destination, const char* nexthop, TableType tableType,
Chiachang89e504e2022-05-12 05:21:20 +00001129 int mtu, int priority, bool isLocal) {
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -07001130 uint32_t table;
Sreeram Ramachandran38b7af12014-05-22 14:21:49 -07001131 switch (tableType) {
1132 case RouteController::INTERFACE: {
Chiachang89e504e2022-05-12 05:21:20 +00001133 table = getRouteTableForInterface(interface, isLocal);
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -07001134 if (table == RT_TABLE_UNSPEC) {
1135 return -ESRCH;
1136 }
Sreeram Ramachandran38b7af12014-05-22 14:21:49 -07001137 break;
1138 }
Sreeram Ramachandran87475a12014-07-15 16:20:28 -07001139 case RouteController::LOCAL_NETWORK: {
1140 table = ROUTE_TABLE_LOCAL_NETWORK;
1141 break;
1142 }
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -07001143 case RouteController::LEGACY_NETWORK: {
Sreeram Ramachandran4acd34a2014-07-07 22:11:37 -07001144 table = ROUTE_TABLE_LEGACY_NETWORK;
Sreeram Ramachandran38b7af12014-05-22 14:21:49 -07001145 break;
1146 }
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -07001147 case RouteController::LEGACY_SYSTEM: {
Sreeram Ramachandran4acd34a2014-07-07 22:11:37 -07001148 table = ROUTE_TABLE_LEGACY_SYSTEM;
Sreeram Ramachandran38b7af12014-05-22 14:21:49 -07001149 break;
1150 }
1151 }
Sreeram Ramachandran9c0d3132014-04-10 20:35:04 -07001152
Taras Antoshchuk0cceda22021-09-24 18:40:03 +02001153 int ret = modifyIpRoute(action, flags, table, interface, destination, nexthop, mtu, priority);
Sreeram Ramachandran03213152014-10-30 10:01:07 -07001154 // Trying to add a route that already exists shouldn't cause an error.
1155 if (ret && !(action == RTM_NEWROUTE && ret == -EEXIST)) {
Lorenzo Colittif7fc8ec2014-06-18 00:41:58 +09001156 return ret;
Sreeram Ramachandranc9213372014-04-16 12:32:18 -07001157 }
1158
Lorenzo Colittif7fc8ec2014-06-18 00:41:58 +09001159 return 0;
Sreeram Ramachandran9c0d3132014-04-10 20:35:04 -07001160}
1161
Lorenzo Colitti3810c972021-01-06 11:44:02 +09001162static void maybeModifyQdiscClsact(const char* interface, bool add) {
Hungming Chen7f725432020-02-07 17:47:23 +08001163 // The clsact attaching of v4- tun interface is triggered by ClatdController::maybeStartBpf
1164 // because the clat is started before the v4- interface is added to the network and the
1165 // clat startup needs to add {in, e}gress filters.
1166 // TODO: remove this workaround once v4- tun interface clsact attaching is moved out from
1167 // ClatdController::maybeStartBpf.
1168 if (StartsWith(interface, "v4-") && add) return;
1169
1170 // The interface may have already gone away in the delete case.
Chiachang Wangf79e3562022-01-15 13:31:04 +08001171 uint32_t ifindex = RouteController::ifNameToIndexFunction(interface);
Hungming Chen7f725432020-02-07 17:47:23 +08001172 if (!ifindex) {
1173 ALOGE("cannot find interface %s", interface);
1174 return;
1175 }
1176
1177 if (add) {
1178 if (int ret = tcQdiscAddDevClsact(ifindex)) {
1179 ALOGE("tcQdiscAddDevClsact(%d[%s]) failure: %s", ifindex, interface, strerror(-ret));
1180 return;
1181 }
1182 } else {
1183 if (int ret = tcQdiscDelDevClsact(ifindex)) {
1184 ALOGE("tcQdiscDelDevClsact(%d[%s]) failure: %s", ifindex, interface, strerror(-ret));
1185 return;
1186 }
1187 }
1188
1189 return;
1190}
1191
Bernie Innocenti762dcf42019-06-14 19:52:49 +09001192[[nodiscard]] static int clearTetheringRules(const char* inputInterface) {
Lorenzo Colitti6b6f25f2015-03-03 17:22:57 +09001193 int ret = 0;
1194 while (ret == 0) {
1195 ret = modifyIpRule(RTM_DELRULE, RULE_PRIORITY_TETHERING, 0, MARK_UNSET, MARK_UNSET,
1196 inputInterface, OIF_NONE, INVALID_UID, INVALID_UID);
1197 }
1198
1199 if (ret == -ENOENT) {
1200 return 0;
1201 } else {
1202 return ret;
1203 }
1204}
1205
Lorenzo Colittif3e299a2017-02-14 17:24:28 +09001206uint32_t getRulePriority(const nlmsghdr *nlh) {
1207 return getRtmU32Attribute(nlh, FRA_PRIORITY);
1208}
1209
1210uint32_t getRouteTable(const nlmsghdr *nlh) {
1211 return getRtmU32Attribute(nlh, RTA_TABLE);
1212}
1213
Bernie Innocenti762dcf42019-06-14 19:52:49 +09001214[[nodiscard]] static int flushRules() {
Lorenzo Colittif3e299a2017-02-14 17:24:28 +09001215 NetlinkDumpFilter shouldDelete = [] (nlmsghdr *nlh) {
1216 // Don't touch rules at priority 0 because by default they are used for local input.
1217 return getRulePriority(nlh) != 0;
1218 };
1219 return rtNetlinkFlush(RTM_GETRULE, RTM_DELRULE, "rules", shouldDelete);
1220}
1221
Bernie Innocenti762dcf42019-06-14 19:52:49 +09001222int RouteController::flushRoutes(uint32_t table) {
Lorenzo Colittif3e299a2017-02-14 17:24:28 +09001223 NetlinkDumpFilter shouldDelete = [table] (nlmsghdr *nlh) {
1224 return getRouteTable(nlh) == table;
1225 };
1226
1227 return rtNetlinkFlush(RTM_GETROUTE, RTM_DELROUTE, "routes", shouldDelete);
1228}
1229
Bernie Innocenti762dcf42019-06-14 19:52:49 +09001230int RouteController::flushRoutes(const char* interface) {
Chiachang Wangf79e3562022-01-15 13:31:04 +08001231 // Try to flush both local and global routing tables.
1232 //
1233 // Flush local first because flush global routing tables may erase the sInterfaceToTable map.
1234 // Then the fake <iface>_local interface will be unable to find the index because the local
1235 // interface depends physical interface to find the correct index.
1236 int ret = flushRoutes(interface, true);
1237 ret |= flushRoutes(interface, false);
1238 return ret;
1239}
1240
1241// Returns 0 on success or negative errno on failure.
1242int RouteController::flushRoutes(const char* interface, bool local) {
Bernie Innocentiabf8a342018-08-10 15:17:16 +09001243 std::lock_guard lock(sInterfaceToTableLock);
Lorenzo Colitti107075a2017-10-30 19:24:46 +09001244
Chiachang Wangf79e3562022-01-15 13:31:04 +08001245 uint32_t table = getRouteTableForInterfaceLocked(interface, local);
Lorenzo Colittif3e299a2017-02-14 17:24:28 +09001246 if (table == RT_TABLE_UNSPEC) {
1247 return -ESRCH;
1248 }
1249
1250 int ret = flushRoutes(table);
1251
1252 // If we failed to flush routes, the caller may elect to keep this interface around, so keep
1253 // track of its name.
Chiachang Wangf79e3562022-01-15 13:31:04 +08001254 // Skip erasing local fake interface since it does not exist in sInterfaceToTable.
1255 if (ret == 0 && !local) {
Lorenzo Colitti02cb80a2017-10-30 19:21:06 +09001256 sInterfaceToTable.erase(interface);
Lorenzo Colittif3e299a2017-02-14 17:24:28 +09001257 }
1258
1259 return ret;
1260}
1261
Sreeram Ramachandran87475a12014-07-15 16:20:28 -07001262int RouteController::Init(unsigned localNetId) {
Sreeram Ramachandranb717e742014-07-19 00:22:15 -07001263 if (int ret = flushRules()) {
1264 return ret;
1265 }
Sreeram Ramachandran87475a12014-07-15 16:20:28 -07001266 if (int ret = addLegacyRouteRules()) {
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -07001267 return ret;
1268 }
Sreeram Ramachandranfa9f4dc2014-07-22 18:16:44 -07001269 if (int ret = addLocalNetworkRules(localNetId)) {
1270 return ret;
1271 }
Sreeram Ramachandranb717e742014-07-19 00:22:15 -07001272 if (int ret = addUnreachableRule()) {
1273 return ret;
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -07001274 }
Lorenzo Colitti36679362015-02-25 10:26:19 +09001275 // Don't complain if we can't add the dummy network, since not all devices support it.
1276 configureDummyNetwork();
1277
Sreeram Ramachandran4acd34a2014-07-07 22:11:37 -07001278 updateTableNamesFile();
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -07001279 return 0;
Sreeram Ramachandran8fe9c8e2014-04-16 12:08:05 -07001280}
1281
Sreeram Ramachandran6a773532014-07-11 09:10:20 -07001282int RouteController::addInterfaceToLocalNetwork(unsigned netId, const char* interface) {
Lorenzo Colittib6dc40a2020-03-24 00:58:50 +09001283 if (int ret = modifyLocalNetwork(netId, interface, ACTION_ADD)) {
1284 return ret;
1285 }
1286 std::lock_guard lock(sInterfaceToTableLock);
1287 sInterfaceToTable[interface] = ROUTE_TABLE_LOCAL_NETWORK;
1288 return 0;
Sreeram Ramachandran6a773532014-07-11 09:10:20 -07001289}
1290
1291int RouteController::removeInterfaceFromLocalNetwork(unsigned netId, const char* interface) {
Lorenzo Colittib6dc40a2020-03-24 00:58:50 +09001292 if (int ret = modifyLocalNetwork(netId, interface, ACTION_DEL)) {
1293 return ret;
1294 }
1295 std::lock_guard lock(sInterfaceToTableLock);
1296 sInterfaceToTable.erase(interface);
1297 return 0;
Sreeram Ramachandran6a773532014-07-11 09:10:20 -07001298}
1299
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -07001300int RouteController::addInterfaceToPhysicalNetwork(unsigned netId, const char* interface,
Ken Chen8738e1c2020-11-24 11:38:54 +08001301 Permission permission,
Chalard Jeane479f312022-12-12 18:27:49 +09001302 const UidRangeMap& uidRangeMap, bool local) {
Ken Chen4ea88462021-05-23 14:56:43 +08001303 if (int ret = modifyPhysicalNetwork(netId, interface, uidRangeMap, permission, ACTION_ADD,
Chalard Jeane479f312022-12-12 18:27:49 +09001304 MODIFY_NON_UID_BASED_RULES, local)) {
Sreeram Ramachandran4acd34a2014-07-07 22:11:37 -07001305 return ret;
1306 }
Chiachang Wange7bf5f52022-01-17 11:37:39 +08001307
Hungming Chen7f725432020-02-07 17:47:23 +08001308 maybeModifyQdiscClsact(interface, ACTION_ADD);
Sreeram Ramachandran4acd34a2014-07-07 22:11:37 -07001309 updateTableNamesFile();
chiachangwangb7a60992022-08-25 06:55:19 +00001310
1311 if (int ret = addFixedLocalRoutes(interface)) {
1312 return ret;
1313 }
1314
Sreeram Ramachandran4acd34a2014-07-07 22:11:37 -07001315 return 0;
Sreeram Ramachandran5c181bf2014-04-07 14:10:04 -07001316}
1317
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -07001318int RouteController::removeInterfaceFromPhysicalNetwork(unsigned netId, const char* interface,
Ken Chen8738e1c2020-11-24 11:38:54 +08001319 Permission permission,
Chalard Jeane479f312022-12-12 18:27:49 +09001320 const UidRangeMap& uidRangeMap,
1321 bool local) {
Ken Chen4ea88462021-05-23 14:56:43 +08001322 if (int ret = modifyPhysicalNetwork(netId, interface, uidRangeMap, permission, ACTION_DEL,
Chalard Jeane479f312022-12-12 18:27:49 +09001323 MODIFY_NON_UID_BASED_RULES, local)) {
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -07001324 return ret;
1325 }
Chiachang Wange7bf5f52022-01-17 11:37:39 +08001326
Chiachang8a03faa2022-05-04 07:45:37 +00001327 if (int ret = flushRoutes(interface)) {
Sreeram Ramachandran4acd34a2014-07-07 22:11:37 -07001328 return ret;
1329 }
Chiachang Wange7bf5f52022-01-17 11:37:39 +08001330
Lorenzo Colitti6b6f25f2015-03-03 17:22:57 +09001331 if (int ret = clearTetheringRules(interface)) {
1332 return ret;
1333 }
Chiachang Wange7bf5f52022-01-17 11:37:39 +08001334
Hungming Chen7f725432020-02-07 17:47:23 +08001335 maybeModifyQdiscClsact(interface, ACTION_DEL);
Sreeram Ramachandran4acd34a2014-07-07 22:11:37 -07001336 updateTableNamesFile();
1337 return 0;
Sreeram Ramachandran379bd332014-04-10 19:58:06 -07001338}
1339
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -07001340int RouteController::addInterfaceToVirtualNetwork(unsigned netId, const char* interface,
Chiachang Wang2e9443f2022-01-14 22:55:36 +08001341 bool secure, const UidRangeMap& uidRangeMap,
1342 bool excludeLocalRoutes) {
Ken Chen4ea88462021-05-23 14:56:43 +08001343 if (int ret = modifyVirtualNetwork(netId, interface, uidRangeMap, secure, ACTION_ADD,
Chiachang Wang2e9443f2022-01-14 22:55:36 +08001344 MODIFY_NON_UID_BASED_RULES, excludeLocalRoutes)) {
Sreeram Ramachandran4acd34a2014-07-07 22:11:37 -07001345 return ret;
1346 }
1347 updateTableNamesFile();
1348 return 0;
Sreeram Ramachandran4043f012014-06-23 12:41:37 -07001349}
1350
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -07001351int RouteController::removeInterfaceFromVirtualNetwork(unsigned netId, const char* interface,
Chiachang Wang2e9443f2022-01-14 22:55:36 +08001352 bool secure, const UidRangeMap& uidRangeMap,
1353 bool excludeLocalRoutes) {
Ken Chen4ea88462021-05-23 14:56:43 +08001354 if (int ret = modifyVirtualNetwork(netId, interface, uidRangeMap, secure, ACTION_DEL,
Chiachang Wang2e9443f2022-01-14 22:55:36 +08001355 MODIFY_NON_UID_BASED_RULES, excludeLocalRoutes)) {
Sreeram Ramachandran4043f012014-06-23 12:41:37 -07001356 return ret;
1357 }
Sreeram Ramachandran4acd34a2014-07-07 22:11:37 -07001358 if (int ret = flushRoutes(interface)) {
1359 return ret;
1360 }
1361 updateTableNamesFile();
1362 return 0;
Sreeram Ramachandran4043f012014-06-23 12:41:37 -07001363}
1364
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -07001365int RouteController::modifyPhysicalNetworkPermission(unsigned netId, const char* interface,
1366 Permission oldPermission,
Chalard Jeane479f312022-12-12 18:27:49 +09001367 Permission newPermission, bool local) {
Ken Chen4ea88462021-05-23 14:56:43 +08001368 // Physical network rules either use permission bits or UIDs, but not both.
1369 // So permission changes don't affect any UID-based rules.
1370 UidRangeMap emptyUidRangeMap;
Sreeram Ramachandran379bd332014-04-10 19:58:06 -07001371 // Add the new rules before deleting the old ones, to avoid race conditions.
Ken Chen4ea88462021-05-23 14:56:43 +08001372 if (int ret = modifyPhysicalNetwork(netId, interface, emptyUidRangeMap, newPermission,
Chalard Jeane479f312022-12-12 18:27:49 +09001373 ACTION_ADD, MODIFY_NON_UID_BASED_RULES, local)) {
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -07001374 return ret;
1375 }
Ken Chen4ea88462021-05-23 14:56:43 +08001376 return modifyPhysicalNetwork(netId, interface, emptyUidRangeMap, oldPermission, ACTION_DEL,
Chalard Jeane479f312022-12-12 18:27:49 +09001377 MODIFY_NON_UID_BASED_RULES, local);
Sreeram Ramachandranb1425cc2014-06-23 18:54:27 -07001378}
1379
Robin Leeb8087362016-03-30 18:43:08 +01001380int RouteController::addUsersToRejectNonSecureNetworkRule(const UidRanges& uidRanges) {
1381 return modifyRejectNonSecureNetworkRule(uidRanges, true);
1382}
1383
1384int RouteController::removeUsersFromRejectNonSecureNetworkRule(const UidRanges& uidRanges) {
1385 return modifyRejectNonSecureNetworkRule(uidRanges, false);
1386}
1387
Sreeram Ramachandran95684ba2014-07-23 13:27:31 -07001388int RouteController::addUsersToVirtualNetwork(unsigned netId, const char* interface, bool secure,
Chiachang Wang2e9443f2022-01-14 22:55:36 +08001389 const UidRangeMap& uidRangeMap,
1390 bool excludeLocalRoutes) {
Ken Chen4ea88462021-05-23 14:56:43 +08001391 return modifyVirtualNetwork(netId, interface, uidRangeMap, secure, ACTION_ADD,
Chiachang Wang2e9443f2022-01-14 22:55:36 +08001392 !MODIFY_NON_UID_BASED_RULES, excludeLocalRoutes);
Sreeram Ramachandranb1425cc2014-06-23 18:54:27 -07001393}
1394
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -07001395int RouteController::removeUsersFromVirtualNetwork(unsigned netId, const char* interface,
Chiachang Wang2e9443f2022-01-14 22:55:36 +08001396 bool secure, const UidRangeMap& uidRangeMap,
1397 bool excludeLocalRoutes) {
Ken Chen4ea88462021-05-23 14:56:43 +08001398 return modifyVirtualNetwork(netId, interface, uidRangeMap, secure, ACTION_DEL,
Chiachang Wang2e9443f2022-01-14 22:55:36 +08001399 !MODIFY_NON_UID_BASED_RULES, excludeLocalRoutes);
Sreeram Ramachandran9c0d3132014-04-10 20:35:04 -07001400}
1401
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -07001402int RouteController::addInterfaceToDefaultNetwork(const char* interface, Permission permission) {
1403 return modifyDefaultNetwork(RTM_NEWRULE, interface, permission);
Sreeram Ramachandran9c0d3132014-04-10 20:35:04 -07001404}
1405
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -07001406int RouteController::removeInterfaceFromDefaultNetwork(const char* interface,
1407 Permission permission) {
1408 return modifyDefaultNetwork(RTM_DELRULE, interface, permission);
Sreeram Ramachandran5c181bf2014-04-07 14:10:04 -07001409}
Sreeram Ramachandran7619e1b2014-04-15 14:23:08 -07001410
chiachangwang9542a1e2022-06-15 02:42:44 +00001411bool RouteController::isWithinIpv4LocalPrefix(const char* dst) {
1412 for (IPPrefix addr : V4_LOCAL_PREFIXES) {
Chiachang3aa56612022-05-12 05:55:45 +00001413 if (addr.contains(IPPrefix::forString(dst))) {
1414 return true;
1415 }
1416 }
1417 return false;
1418}
1419
chiachangwang9542a1e2022-06-15 02:42:44 +00001420bool RouteController::isLocalRoute(TableType tableType, const char* destination,
1421 const char* nexthop) {
Chiachang89e504e2022-05-12 05:21:20 +00001422 IPPrefix prefix = IPPrefix::forString(destination);
Chiachang89e504e2022-05-12 05:21:20 +00001423 return nexthop == nullptr && tableType == RouteController::INTERFACE &&
1424 // Skip default route to prevent network being modeled as point-to-point interfaces.
Chiachang3aa56612022-05-12 05:55:45 +00001425 ((prefix.family() == AF_INET6 && prefix != IPPrefix::forString("::/0")) ||
1426 // Skip adding non-target local network range.
chiachangwang9542a1e2022-06-15 02:42:44 +00001427 (prefix.family() == AF_INET && isWithinIpv4LocalPrefix(destination)));
Chiachang89e504e2022-05-12 05:21:20 +00001428}
1429
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -07001430int RouteController::addRoute(const char* interface, const char* destination, const char* nexthop,
Taras Antoshchuk0cceda22021-09-24 18:40:03 +02001431 TableType tableType, int mtu, int priority) {
Chiachang89e504e2022-05-12 05:21:20 +00001432 if (int ret = modifyRoute(RTM_NEWROUTE, NETLINK_ROUTE_CREATE_FLAGS, interface, destination,
1433 nexthop, tableType, mtu, priority, false /* isLocal */)) {
1434 return ret;
1435 }
1436
chiachangwang9542a1e2022-06-15 02:42:44 +00001437 if (isLocalRoute(tableType, destination, nexthop)) {
Chiachang89e504e2022-05-12 05:21:20 +00001438 return modifyRoute(RTM_NEWROUTE, NETLINK_ROUTE_CREATE_FLAGS, interface, destination,
1439 nexthop, tableType, mtu, priority, true /* isLocal */);
1440 }
1441
1442 return 0;
Sreeram Ramachandran7619e1b2014-04-15 14:23:08 -07001443}
1444
Lorenzo Colittif7fc8ec2014-06-18 00:41:58 +09001445int RouteController::removeRoute(const char* interface, const char* destination,
Taras Antoshchuk0cceda22021-09-24 18:40:03 +02001446 const char* nexthop, TableType tableType, int priority) {
Chiachang89e504e2022-05-12 05:21:20 +00001447 if (int ret = modifyRoute(RTM_DELROUTE, NETLINK_REQUEST_FLAGS, interface, destination, nexthop,
1448 tableType, 0 /* mtu */, priority, false /* isLocal */)) {
1449 return ret;
1450 }
1451
chiachangwang9542a1e2022-06-15 02:42:44 +00001452 if (isLocalRoute(tableType, destination, nexthop)) {
Chiachang89e504e2022-05-12 05:21:20 +00001453 return modifyRoute(RTM_DELROUTE, NETLINK_REQUEST_FLAGS, interface, destination, nexthop,
1454 tableType, 0 /* mtu */, priority, true /* isLocal */);
1455 }
1456 return 0;
Tyler Wearfa94a272019-12-05 15:01:48 -08001457}
1458
1459int RouteController::updateRoute(const char* interface, const char* destination,
1460 const char* nexthop, TableType tableType, int mtu) {
Chiachang89e504e2022-05-12 05:21:20 +00001461 if (int ret = modifyRoute(RTM_NEWROUTE, NETLINK_ROUTE_REPLACE_FLAGS, interface, destination,
1462 nexthop, tableType, mtu, 0 /* priority */, false /* isLocal */)) {
1463 return ret;
1464 }
1465
chiachangwang9542a1e2022-06-15 02:42:44 +00001466 if (isLocalRoute(tableType, destination, nexthop)) {
Chiachang89e504e2022-05-12 05:21:20 +00001467 return modifyRoute(RTM_NEWROUTE, NETLINK_ROUTE_REPLACE_FLAGS, interface, destination,
1468 nexthop, tableType, mtu, 0 /* priority */, true /* isLocal */);
1469 }
1470 return 0;
Sreeram Ramachandran7619e1b2014-04-15 14:23:08 -07001471}
Sreeram Ramachandran87475a12014-07-15 16:20:28 -07001472
1473int RouteController::enableTethering(const char* inputInterface, const char* outputInterface) {
Sreeram Ramachandranfa9f4dc2014-07-22 18:16:44 -07001474 return modifyTetheredNetwork(RTM_NEWRULE, inputInterface, outputInterface);
Sreeram Ramachandran87475a12014-07-15 16:20:28 -07001475}
1476
1477int RouteController::disableTethering(const char* inputInterface, const char* outputInterface) {
Sreeram Ramachandranfa9f4dc2014-07-22 18:16:44 -07001478 return modifyTetheredNetwork(RTM_DELRULE, inputInterface, outputInterface);
Sreeram Ramachandran87475a12014-07-15 16:20:28 -07001479}
Sreeram Ramachandran48e19b02014-07-22 22:23:20 -07001480
1481int RouteController::addVirtualNetworkFallthrough(unsigned vpnNetId, const char* physicalInterface,
1482 Permission permission) {
Chiachang8a03faa2022-05-04 07:45:37 +00001483 if (int ret = modifyVpnFallthroughRule(RTM_NEWRULE, vpnNetId, physicalInterface, permission)) {
1484 return ret;
1485 }
1486
Tommy Webb9ed91ab2023-02-28 10:46:05 -05001487 return 0;
Sreeram Ramachandran48e19b02014-07-22 22:23:20 -07001488}
1489
1490int RouteController::removeVirtualNetworkFallthrough(unsigned vpnNetId,
1491 const char* physicalInterface,
1492 Permission permission) {
Chiachang8a03faa2022-05-04 07:45:37 +00001493 if (int ret = modifyVpnFallthroughRule(RTM_DELRULE, vpnNetId, physicalInterface, permission)) {
1494 return ret;
1495 }
1496
Tommy Webb9ed91ab2023-02-28 10:46:05 -05001497 return 0;
Sreeram Ramachandran48e19b02014-07-22 22:23:20 -07001498}
Lorenzo Colitti7035f222017-02-13 18:29:00 +09001499
Ken Chen8738e1c2020-11-24 11:38:54 +08001500int RouteController::addUsersToPhysicalNetwork(unsigned netId, const char* interface,
Chalard Jeane479f312022-12-12 18:27:49 +09001501 const UidRangeMap& uidRangeMap, bool local) {
Ken Chen4ea88462021-05-23 14:56:43 +08001502 return modifyPhysicalNetwork(netId, interface, uidRangeMap, PERMISSION_NONE, ACTION_ADD,
Chalard Jeane479f312022-12-12 18:27:49 +09001503 !MODIFY_NON_UID_BASED_RULES, local);
Ken Chen8738e1c2020-11-24 11:38:54 +08001504}
1505
1506int RouteController::removeUsersFromPhysicalNetwork(unsigned netId, const char* interface,
Chalard Jeane479f312022-12-12 18:27:49 +09001507 const UidRangeMap& uidRangeMap, bool local) {
Ken Chen4ea88462021-05-23 14:56:43 +08001508 return modifyPhysicalNetwork(netId, interface, uidRangeMap, PERMISSION_NONE, ACTION_DEL,
Chalard Jeane479f312022-12-12 18:27:49 +09001509 !MODIFY_NON_UID_BASED_RULES, local);
Ken Chen8738e1c2020-11-24 11:38:54 +08001510}
1511
Ken Chen4ea88462021-05-23 14:56:43 +08001512int RouteController::addUsersToUnreachableNetwork(unsigned netId, const UidRangeMap& uidRangeMap) {
1513 return modifyUnreachableNetwork(netId, uidRangeMap, ACTION_ADD);
Ken Chen4e8ef9b2021-03-17 01:57:19 +08001514}
1515
Ken Chen4ea88462021-05-23 14:56:43 +08001516int RouteController::removeUsersFromUnreachableNetwork(unsigned netId,
1517 const UidRangeMap& uidRangeMap) {
1518 return modifyUnreachableNetwork(netId, uidRangeMap, ACTION_DEL);
Ken Chen4e8ef9b2021-03-17 01:57:19 +08001519}
1520
Lorenzo Colitti107075a2017-10-30 19:24:46 +09001521// Protects sInterfaceToTable.
Luke Huang534980c2018-07-06 17:50:11 +08001522std::mutex RouteController::sInterfaceToTableLock;
Lorenzo Colitti02cb80a2017-10-30 19:21:06 +09001523std::map<std::string, uint32_t> RouteController::sInterfaceToTable;
1524
Bernie Innocenti762dcf42019-06-14 19:52:49 +09001525} // namespace android::net