blob: d7a6e8349c361bfe94ab3ec04e9316be3805b4de [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
658// A rule to route traffic based on the chosen network.
659//
660// This is for sockets that have not explicitly requested a particular network, but have been
661// bound to one when they called connect(). This ensures that sockets connected on a particular
662// network stay on that network even if the default network changes.
Bernie Innocenti762dcf42019-06-14 19:52:49 +0900663[[nodiscard]] static int modifyImplicitNetworkRule(unsigned netId, uint32_t table, bool add) {
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -0700664 Fwmark fwmark;
665 Fwmark mask;
666
667 fwmark.netId = netId;
668 mask.netId = FWMARK_NET_ID_MASK;
669
670 fwmark.explicitlySelected = false;
671 mask.explicitlySelected = true;
672
Lorenzo Colittibe0c7c32017-09-06 16:07:02 +0900673 fwmark.permission = PERMISSION_NONE;
674 mask.permission = PERMISSION_NONE;
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -0700675
676 return modifyIpRule(add ? RTM_NEWRULE : RTM_DELRULE, RULE_PRIORITY_IMPLICIT_NETWORK, table,
Lorenzo Colitti758627c2018-03-15 01:49:20 +0900677 fwmark.intValue, mask.intValue, IIF_LOOPBACK, OIF_NONE, INVALID_UID,
678 INVALID_UID);
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -0700679}
680
Chiachang Wang8b9cdd22022-01-27 10:43:28 +0800681int RouteController::modifyVpnLocalExclusionRule(bool add, const char* physicalInterface) {
Chiachang Wange7bf5f52022-01-17 11:37:39 +0800682 uint32_t table = getRouteTableForInterface(physicalInterface, true /* local */);
683 if (table == RT_TABLE_UNSPEC) {
684 return -ESRCH;
685 }
686
687 Fwmark fwmark;
688 Fwmark mask;
689
690 fwmark.explicitlySelected = false;
691 mask.explicitlySelected = true;
692
693 fwmark.permission = PERMISSION_NONE;
694 mask.permission = PERMISSION_NONE;
695
chiachangwang31902a42022-04-15 20:06:27 +0800696 return modifyIpRule(add ? RTM_NEWRULE : RTM_DELRULE, RULE_PRIORITY_LOCAL_ROUTES, table,
697 fwmark.intValue, mask.intValue, IIF_LOOPBACK, OIF_NONE, INVALID_UID,
698 INVALID_UID);
Chiachang Wange7bf5f52022-01-17 11:37:39 +0800699}
700
chiachangwangb7a60992022-08-25 06:55:19 +0000701int RouteController::addFixedLocalRoutes(const char* interface) {
702 for (size_t i = 0; i < ARRAY_SIZE(V4_FIXED_LOCAL_PREFIXES); ++i) {
703 if (int ret = modifyRoute(RTM_NEWROUTE, NETLINK_ROUTE_CREATE_FLAGS, interface,
704 V4_FIXED_LOCAL_PREFIXES[i], nullptr /* nexthop */,
705 RouteController::INTERFACE, 0 /* mtu */, 0 /* priority */,
706 true /* isLocal */)) {
707 return ret;
708 }
709 }
710
711 return 0;
712}
713
Sreeram Ramachandran48e19b02014-07-22 22:23:20 -0700714// A rule to enable split tunnel VPNs.
715//
716// If a packet with a VPN's netId doesn't find a route in the VPN's routing table, it's allowed to
Luke Huangd2861982019-05-17 19:47:28 +0800717// go over the default network, provided it has the permissions required by the default network.
Bernie Innocenti762dcf42019-06-14 19:52:49 +0900718int RouteController::modifyVpnFallthroughRule(uint16_t action, unsigned vpnNetId,
719 const char* physicalInterface,
720 Permission permission) {
Chiachang Wangf79e3562022-01-15 13:31:04 +0800721 uint32_t table = getRouteTableForInterface(physicalInterface, false /* local */);
Sreeram Ramachandran48e19b02014-07-22 22:23:20 -0700722 if (table == RT_TABLE_UNSPEC) {
723 return -ESRCH;
724 }
725
726 Fwmark fwmark;
727 Fwmark mask;
728
729 fwmark.netId = vpnNetId;
730 mask.netId = FWMARK_NET_ID_MASK;
731
Sreeram Ramachandran48e19b02014-07-22 22:23:20 -0700732 fwmark.permission = permission;
733 mask.permission = permission;
734
735 return modifyIpRule(action, RULE_PRIORITY_VPN_FALLTHROUGH, table, fwmark.intValue,
736 mask.intValue);
737}
738
Sreeram Ramachandranfa9f4dc2014-07-22 18:16:44 -0700739// Add rules to allow legacy routes added through the requestRouteToHost() API.
Bernie Innocenti762dcf42019-06-14 19:52:49 +0900740[[nodiscard]] static int addLegacyRouteRules() {
Sreeram Ramachandran4043f012014-06-23 12:41:37 -0700741 Fwmark fwmark;
742 Fwmark mask;
743
Sreeram Ramachandranfa9f4dc2014-07-22 18:16:44 -0700744 fwmark.explicitlySelected = false;
745 mask.explicitlySelected = true;
Sreeram Ramachandranb1425cc2014-06-23 18:54:27 -0700746
Sreeram Ramachandranfa9f4dc2014-07-22 18:16:44 -0700747 // Rules to allow legacy routes to override the default network.
748 if (int ret = modifyIpRule(RTM_NEWRULE, RULE_PRIORITY_LEGACY_SYSTEM, ROUTE_TABLE_LEGACY_SYSTEM,
749 fwmark.intValue, mask.intValue)) {
750 return ret;
751 }
752 if (int ret = modifyIpRule(RTM_NEWRULE, RULE_PRIORITY_LEGACY_NETWORK,
753 ROUTE_TABLE_LEGACY_NETWORK, fwmark.intValue, mask.intValue)) {
754 return ret;
755 }
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -0700756
757 fwmark.permission = PERMISSION_SYSTEM;
758 mask.permission = PERMISSION_SYSTEM;
759
Sreeram Ramachandranfa9f4dc2014-07-22 18:16:44 -0700760 // A rule to allow legacy routes from system apps to override VPNs.
761 return modifyIpRule(RTM_NEWRULE, RULE_PRIORITY_VPN_OVERRIDE_SYSTEM, ROUTE_TABLE_LEGACY_SYSTEM,
Sreeram Ramachandran87475a12014-07-15 16:20:28 -0700762 fwmark.intValue, mask.intValue);
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -0700763}
764
Sreeram Ramachandranfa9f4dc2014-07-22 18:16:44 -0700765// Add rules to lookup the local network when specified explicitly or otherwise.
Bernie Innocenti762dcf42019-06-14 19:52:49 +0900766[[nodiscard]] static int addLocalNetworkRules(unsigned localNetId) {
Sreeram Ramachandranfa9f4dc2014-07-22 18:16:44 -0700767 if (int ret = modifyExplicitNetworkRule(localNetId, ROUTE_TABLE_LOCAL_NETWORK, PERMISSION_NONE,
Ken Chen4ea88462021-05-23 14:56:43 +0800768 INVALID_UID, INVALID_UID,
Patrick Rohre2f1b5a2022-01-25 21:36:50 +0100769 UidRanges::SUB_PRIORITY_HIGHEST, ACTION_ADD)) {
Sreeram Ramachandranfa9f4dc2014-07-22 18:16:44 -0700770 return ret;
Sreeram Ramachandran6a773532014-07-11 09:10:20 -0700771 }
772
Sreeram Ramachandranfa9f4dc2014-07-22 18:16:44 -0700773 Fwmark fwmark;
774 Fwmark mask;
775
776 fwmark.explicitlySelected = false;
777 mask.explicitlySelected = true;
778
779 return modifyIpRule(RTM_NEWRULE, RULE_PRIORITY_LOCAL_NETWORK, ROUTE_TABLE_LOCAL_NETWORK,
780 fwmark.intValue, mask.intValue);
781}
782
Lorenzo Colitti02cb80a2017-10-30 19:21:06 +0900783/* static */
784int RouteController::configureDummyNetwork() {
Lorenzo Colitti36679362015-02-25 10:26:19 +0900785 const char *interface = DummyNetwork::INTERFACE_NAME;
Chiachang Wangf79e3562022-01-15 13:31:04 +0800786 uint32_t table = getRouteTableForInterface(interface, false /* local */);
Lorenzo Colitti36679362015-02-25 10:26:19 +0900787 if (table == RT_TABLE_UNSPEC) {
Hungming Chen7f725432020-02-07 17:47:23 +0800788 // getRouteTableForInterface has already logged an error.
Lorenzo Colitti36679362015-02-25 10:26:19 +0900789 return -ESRCH;
790 }
791
792 ifc_init();
793 int ret = ifc_up(interface);
794 ifc_close();
795 if (ret) {
796 ALOGE("Can't bring up %s: %s", interface, strerror(errno));
797 return -errno;
798 }
799
Ken Chen4ea88462021-05-23 14:56:43 +0800800 if ((ret = modifyOutputInterfaceRules(interface, table, PERMISSION_NONE, INVALID_UID,
Patrick Rohre2f1b5a2022-01-25 21:36:50 +0100801 INVALID_UID, UidRanges::SUB_PRIORITY_HIGHEST,
Ken Chen4ea88462021-05-23 14:56:43 +0800802 ACTION_ADD))) {
Lorenzo Colitti57947f02015-02-27 16:45:55 +0900803 ALOGE("Can't create oif rules for %s: %s", interface, strerror(-ret));
Lorenzo Colitti36679362015-02-25 10:26:19 +0900804 return ret;
805 }
806
Tyler Wearfa94a272019-12-05 15:01:48 -0800807 if ((ret = modifyIpRoute(RTM_NEWROUTE, NETLINK_ROUTE_CREATE_FLAGS, table, interface,
Taras Antoshchuk0cceda22021-09-24 18:40:03 +0200808 "0.0.0.0/0", nullptr, 0 /* mtu */, 0 /* priority */))) {
Lorenzo Colitti36679362015-02-25 10:26:19 +0900809 return ret;
810 }
811
Tyler Wearfa94a272019-12-05 15:01:48 -0800812 if ((ret = modifyIpRoute(RTM_NEWROUTE, NETLINK_ROUTE_CREATE_FLAGS, table, interface, "::/0",
Taras Antoshchuk0cceda22021-09-24 18:40:03 +0200813 nullptr, 0 /* mtu */, 0 /* priority */))) {
Lorenzo Colitti36679362015-02-25 10:26:19 +0900814 return ret;
815 }
816
817 return 0;
818}
819
Lorenzo Colittidb74dba2014-07-29 18:26:21 +0900820// Add an explicit unreachable rule close to the end of the prioriy list to make it clear that
821// relying on the kernel-default "from all lookup main" rule at priority 32766 is not intended
822// behaviour. We do flush the kernel-default rules at startup, but having an explicit unreachable
823// rule will hopefully make things even clearer.
Bernie Innocenti762dcf42019-06-14 19:52:49 +0900824[[nodiscard]] static int addUnreachableRule() {
Robin Leec125fe42016-05-02 08:53:34 +0100825 return modifyIpRule(RTM_NEWRULE, RULE_PRIORITY_UNREACHABLE, FR_ACT_UNREACHABLE, RT_TABLE_UNSPEC,
826 MARK_UNSET, MARK_UNSET, IIF_NONE, OIF_NONE, INVALID_UID, INVALID_UID);
Sreeram Ramachandran87475a12014-07-15 16:20:28 -0700827}
828
Bernie Innocenti762dcf42019-06-14 19:52:49 +0900829[[nodiscard]] static int modifyLocalNetwork(unsigned netId, const char* interface, bool add) {
Sreeram Ramachandran6a773532014-07-11 09:10:20 -0700830 if (int ret = modifyIncomingPacketMark(netId, interface, PERMISSION_NONE, add)) {
831 return ret;
832 }
Lorenzo Colitti3810c972021-01-06 11:44:02 +0900833 maybeModifyQdiscClsact(interface, add);
Lorenzo Colitti57947f02015-02-27 16:45:55 +0900834 return modifyOutputInterfaceRules(interface, ROUTE_TABLE_LOCAL_NETWORK, PERMISSION_NONE,
Patrick Rohre2f1b5a2022-01-25 21:36:50 +0100835 INVALID_UID, INVALID_UID, UidRanges::SUB_PRIORITY_HIGHEST,
Ken Chen4ea88462021-05-23 14:56:43 +0800836 add);
Sreeram Ramachandran6a773532014-07-11 09:10:20 -0700837}
838
Ken Chena2206ec2021-03-24 17:15:44 +0800839[[nodiscard]] static int modifyUidNetworkRule(unsigned netId, uint32_t table, uid_t uidStart,
Ken Chen53360bf2021-12-10 02:41:05 +0800840 uid_t uidEnd, int32_t subPriority, bool add,
Ken Chen4ea88462021-05-23 14:56:43 +0800841 bool explicitSelect) {
Ken Chen8738e1c2020-11-24 11:38:54 +0800842 if ((uidStart == INVALID_UID) || (uidEnd == INVALID_UID)) {
Ken Chena2206ec2021-03-24 17:15:44 +0800843 ALOGE("modifyUidNetworkRule, invalid UIDs (%u, %u)", uidStart, uidEnd);
Ken Chen8738e1c2020-11-24 11:38:54 +0800844 return -EUSERS;
845 }
846
847 Fwmark fwmark;
848 Fwmark mask;
849
850 fwmark.netId = netId;
851 mask.netId = FWMARK_NET_ID_MASK;
852
Ken Chena2206ec2021-03-24 17:15:44 +0800853 fwmark.explicitlySelected = explicitSelect;
Ken Chen8738e1c2020-11-24 11:38:54 +0800854 mask.explicitlySelected = true;
855
856 // Access to this network is controlled by UID rules, not permission bits.
857 fwmark.permission = PERMISSION_NONE;
858 mask.permission = PERMISSION_NONE;
859
Ken Chena2206ec2021-03-24 17:15:44 +0800860 return modifyIpRule(add ? RTM_NEWRULE : RTM_DELRULE,
Ken Chen4ea88462021-05-23 14:56:43 +0800861 explicitSelect ? (RULE_PRIORITY_UID_EXPLICIT_NETWORK + subPriority)
862 : (RULE_PRIORITY_UID_IMPLICIT_NETWORK + subPriority),
Ken Chena2206ec2021-03-24 17:15:44 +0800863 table, fwmark.intValue, mask.intValue, IIF_LOOPBACK, OIF_NONE, uidStart,
864 uidEnd);
Ken Chen8738e1c2020-11-24 11:38:54 +0800865}
866
867[[nodiscard]] static int modifyUidDefaultNetworkRule(uint32_t table, uid_t uidStart, uid_t uidEnd,
Ken Chen53360bf2021-12-10 02:41:05 +0800868 int32_t subPriority, bool add) {
Ken Chen8738e1c2020-11-24 11:38:54 +0800869 if ((uidStart == INVALID_UID) || (uidEnd == INVALID_UID)) {
870 ALOGE("modifyUidDefaultNetworkRule, invalid UIDs (%u, %u)", uidStart, uidEnd);
871 return -EUSERS;
872 }
873
874 Fwmark fwmark;
875 Fwmark mask;
876
877 fwmark.netId = NETID_UNSET;
878 mask.netId = FWMARK_NET_ID_MASK;
879
880 // Access to this network is controlled by UID rules, not permission bits.
881 fwmark.permission = PERMISSION_NONE;
882 mask.permission = PERMISSION_NONE;
883
Ken Chen4ea88462021-05-23 14:56:43 +0800884 return modifyIpRule(add ? RTM_NEWRULE : RTM_DELRULE,
885 RULE_PRIORITY_UID_DEFAULT_NETWORK + subPriority, table, fwmark.intValue,
886 mask.intValue, IIF_LOOPBACK, OIF_NONE, uidStart, uidEnd);
Ken Chen8738e1c2020-11-24 11:38:54 +0800887}
888
Lorenzo Colitti02cb80a2017-10-30 19:21:06 +0900889/* static */
Bernie Innocenti762dcf42019-06-14 19:52:49 +0900890int RouteController::modifyPhysicalNetwork(unsigned netId, const char* interface,
Ken Chen4ea88462021-05-23 14:56:43 +0800891 const UidRangeMap& uidRangeMap, Permission permission,
Chalard Jeane479f312022-12-12 18:27:49 +0900892 bool add, bool modifyNonUidBasedRules, bool local) {
Chiachang Wangf79e3562022-01-15 13:31:04 +0800893 uint32_t table = getRouteTableForInterface(interface, false /* local */);
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -0700894 if (table == RT_TABLE_UNSPEC) {
895 return -ESRCH;
896 }
897
Ken Chen4ea88462021-05-23 14:56:43 +0800898 for (const auto& [subPriority, uidRanges] : uidRangeMap) {
899 for (const UidRangeParcel& range : uidRanges.getRanges()) {
900 if (int ret = modifyUidNetworkRule(netId, table, range.start, range.stop, subPriority,
901 add, EXPLICIT)) {
902 return ret;
903 }
904 if (int ret = modifyUidNetworkRule(netId, table, range.start, range.stop, subPriority,
905 add, IMPLICIT)) {
906 return ret;
907 }
Patrick Rohre6f198c2022-01-25 13:50:31 +0100908 // SUB_PRIORITY_NO_DEFAULT is "special" and does not require a
909 // default network rule, see UidRanges.h.
910 if (subPriority != UidRanges::SUB_PRIORITY_NO_DEFAULT) {
911 if (int ret = modifyUidDefaultNetworkRule(table, range.start, range.stop,
912 subPriority, add)) {
913 return ret;
914 }
chiachangwang776b68c2022-05-17 05:16:16 +0000915
916 // Per-UID local network rules must always match per-app default network rules,
917 // because their purpose is to allow the UIDs to use the default network for
918 // local destinations within it.
919 if (int ret = modifyUidLocalNetworkRule(interface, range.start, range.stop, add)) {
920 return ret;
921 }
Ken Chen4ea88462021-05-23 14:56:43 +0800922 }
Ken Chen8738e1c2020-11-24 11:38:54 +0800923 }
924 }
925
926 if (!modifyNonUidBasedRules) {
927 // we are done.
928 return 0;
929 }
930
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -0700931 if (int ret = modifyIncomingPacketMark(netId, interface, permission, add)) {
932 return ret;
933 }
934 if (int ret = modifyExplicitNetworkRule(netId, table, permission, INVALID_UID, INVALID_UID,
Patrick Rohre2f1b5a2022-01-25 21:36:50 +0100935 UidRanges::SUB_PRIORITY_HIGHEST, add)) {
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -0700936 return ret;
937 }
Chalard Jeane479f312022-12-12 18:27:49 +0900938 if (local) {
939 if (const int ret = modifyLocalNetworkRule(table, add)) {
940 return ret;
941 }
942 }
Lorenzo Colitti57947f02015-02-27 16:45:55 +0900943 if (int ret = modifyOutputInterfaceRules(interface, table, permission, INVALID_UID, INVALID_UID,
Patrick Rohre2f1b5a2022-01-25 21:36:50 +0100944 UidRanges::SUB_PRIORITY_HIGHEST, add)) {
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -0700945 return ret;
946 }
Lorenzo Colittibe0c7c32017-09-06 16:07:02 +0900947
948 // Only set implicit rules for networks that don't require permissions.
949 //
950 // This is so that if the default network ceases to be the default network and then switches
951 // from requiring no permissions to requiring permissions, we ensure that apps only use the
952 // network if they explicitly select it. This is consistent with destroySocketsLackingPermission
953 // - it closes all sockets on the network except sockets that are explicitly selected.
954 //
955 // The lack of this rule only affects the special case above, because:
956 // - The only cases where we implicitly bind a socket to a network are the default network and
957 // the bypassable VPN that applies to the app, if any.
958 // - This rule doesn't affect VPNs because they don't support permissions at all.
959 // - The default network doesn't require permissions. While we support doing this, the framework
960 // never does it (partly because we'd end up in the situation where we tell apps that there is
961 // a default network, but they can't use it).
962 // - If the network is still the default network, the presence or absence of this rule does not
963 // matter.
964 //
965 // Therefore, for the lack of this rule to affect a socket, the socket has to have been
966 // implicitly bound to a network because at the time of connect() it was the default, and that
967 // network must no longer be the default, and must now require permissions.
968 if (permission == PERMISSION_NONE) {
969 return modifyImplicitNetworkRule(netId, table, add);
970 }
971 return 0;
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -0700972}
973
chiachangwang776b68c2022-05-17 05:16:16 +0000974int RouteController::modifyUidLocalNetworkRule(const char* interface, uid_t uidStart, uid_t uidEnd,
975 bool add) {
976 uint32_t table = getRouteTableForInterface(interface, true /* local */);
977 if (table == RT_TABLE_UNSPEC) {
978 return -ESRCH;
979 }
980
981 if ((uidStart == INVALID_UID) || (uidEnd == INVALID_UID)) {
982 ALOGE("modifyUidLocalNetworkRule, invalid UIDs (%u, %u)", uidStart, uidEnd);
983 return -EUSERS;
984 }
985
986 Fwmark fwmark;
987 Fwmark mask;
988
989 fwmark.explicitlySelected = false;
990 mask.explicitlySelected = true;
991
992 // Access to this network is controlled by UID rules, not permission bits.
993 fwmark.permission = PERMISSION_NONE;
994 mask.permission = PERMISSION_NONE;
995
996 return modifyIpRule(add ? RTM_NEWRULE : RTM_DELRULE, RULE_PRIORITY_UID_LOCAL_ROUTES, table,
997 fwmark.intValue, mask.intValue, IIF_LOOPBACK, OIF_NONE, uidStart, uidEnd);
998}
999
Ken Chen4e8ef9b2021-03-17 01:57:19 +08001000[[nodiscard]] static int modifyUidUnreachableRule(unsigned netId, uid_t uidStart, uid_t uidEnd,
Ken Chen53360bf2021-12-10 02:41:05 +08001001 int32_t subPriority, bool add,
Ken Chen4ea88462021-05-23 14:56:43 +08001002 bool explicitSelect) {
Ken Chen4e8ef9b2021-03-17 01:57:19 +08001003 if ((uidStart == INVALID_UID) || (uidEnd == INVALID_UID)) {
1004 ALOGE("modifyUidUnreachableRule, invalid UIDs (%u, %u)", uidStart, uidEnd);
1005 return -EUSERS;
1006 }
1007
1008 Fwmark fwmark;
1009 Fwmark mask;
1010
1011 fwmark.netId = netId;
1012 mask.netId = FWMARK_NET_ID_MASK;
1013
1014 fwmark.explicitlySelected = explicitSelect;
1015 mask.explicitlySelected = true;
1016
1017 // Access to this network is controlled by UID rules, not permission bits.
1018 fwmark.permission = PERMISSION_NONE;
1019 mask.permission = PERMISSION_NONE;
1020
1021 return modifyIpRule(add ? RTM_NEWRULE : RTM_DELRULE,
Ken Chen4ea88462021-05-23 14:56:43 +08001022 explicitSelect ? (RULE_PRIORITY_UID_EXPLICIT_NETWORK + subPriority)
1023 : (RULE_PRIORITY_UID_IMPLICIT_NETWORK + subPriority),
Ken Chen4e8ef9b2021-03-17 01:57:19 +08001024 FR_ACT_UNREACHABLE, RT_TABLE_UNSPEC, fwmark.intValue, mask.intValue,
1025 IIF_LOOPBACK, OIF_NONE, uidStart, uidEnd);
1026}
1027
Ken Chen4ea88462021-05-23 14:56:43 +08001028[[nodiscard]] static int modifyUidDefaultUnreachableRule(uid_t uidStart, uid_t uidEnd,
Ken Chen53360bf2021-12-10 02:41:05 +08001029 int32_t subPriority, bool add) {
Ken Chen4e8ef9b2021-03-17 01:57:19 +08001030 if ((uidStart == INVALID_UID) || (uidEnd == INVALID_UID)) {
Ken Chen4ea88462021-05-23 14:56:43 +08001031 ALOGE("modifyUidDefaultUnreachableRule, invalid UIDs (%u, %u)", uidStart, uidEnd);
Ken Chen4e8ef9b2021-03-17 01:57:19 +08001032 return -EUSERS;
1033 }
1034
1035 Fwmark fwmark;
1036 Fwmark mask;
1037
1038 fwmark.netId = NETID_UNSET;
1039 mask.netId = FWMARK_NET_ID_MASK;
1040
1041 // Access to this network is controlled by UID rules, not permission bits.
1042 fwmark.permission = PERMISSION_NONE;
1043 mask.permission = PERMISSION_NONE;
1044
Ken Chen4ea88462021-05-23 14:56:43 +08001045 return modifyIpRule(add ? RTM_NEWRULE : RTM_DELRULE,
1046 RULE_PRIORITY_UID_DEFAULT_UNREACHABLE + subPriority, FR_ACT_UNREACHABLE,
1047 RT_TABLE_UNSPEC, fwmark.intValue, mask.intValue, IIF_LOOPBACK, OIF_NONE,
1048 uidStart, uidEnd);
Ken Chen4e8ef9b2021-03-17 01:57:19 +08001049}
1050
Ken Chen4ea88462021-05-23 14:56:43 +08001051int RouteController::modifyUnreachableNetwork(unsigned netId, const UidRangeMap& uidRangeMap,
Ken Chen4e8ef9b2021-03-17 01:57:19 +08001052 bool add) {
Ken Chen4ea88462021-05-23 14:56:43 +08001053 for (const auto& [subPriority, uidRanges] : uidRangeMap) {
1054 for (const UidRangeParcel& range : uidRanges.getRanges()) {
1055 if (int ret = modifyUidUnreachableRule(netId, range.start, range.stop, subPriority, add,
1056 EXPLICIT)) {
1057 return ret;
1058 }
1059 if (int ret = modifyUidUnreachableRule(netId, range.start, range.stop, subPriority, add,
1060 IMPLICIT)) {
1061 return ret;
1062 }
1063 if (int ret = modifyUidDefaultUnreachableRule(range.start, range.stop, subPriority,
1064 add)) {
1065 return ret;
1066 }
Ken Chen4e8ef9b2021-03-17 01:57:19 +08001067 }
1068 }
1069
1070 return 0;
1071}
1072
Bernie Innocenti762dcf42019-06-14 19:52:49 +09001073[[nodiscard]] static int modifyRejectNonSecureNetworkRule(const UidRanges& uidRanges, bool add) {
Robin Leeb8087362016-03-30 18:43:08 +01001074 Fwmark fwmark;
1075 Fwmark mask;
1076 fwmark.protectedFromVpn = false;
1077 mask.protectedFromVpn = true;
1078
Luke Huang94658ac2018-10-18 19:35:12 +09001079 for (const UidRangeParcel& range : uidRanges.getRanges()) {
1080 if (int ret = modifyIpRule(add ? RTM_NEWRULE : RTM_DELRULE, RULE_PRIORITY_PROHIBIT_NON_VPN,
1081 FR_ACT_PROHIBIT, RT_TABLE_UNSPEC, fwmark.intValue, mask.intValue,
1082 IIF_LOOPBACK, OIF_NONE, range.start, range.stop)) {
Robin Leeb8087362016-03-30 18:43:08 +01001083 return ret;
1084 }
1085 }
1086
1087 return 0;
1088}
1089
Bernie Innocenti762dcf42019-06-14 19:52:49 +09001090int RouteController::modifyVirtualNetwork(unsigned netId, const char* interface,
Ken Chen4ea88462021-05-23 14:56:43 +08001091 const UidRangeMap& uidRangeMap, bool secure, bool add,
Chiachang Wang2e9443f2022-01-14 22:55:36 +08001092 bool modifyNonUidBasedRules, bool excludeLocalRoutes) {
Chiachang Wangf79e3562022-01-15 13:31:04 +08001093 uint32_t table = getRouteTableForInterface(interface, false /* false */);
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -07001094 if (table == RT_TABLE_UNSPEC) {
1095 return -ESRCH;
1096 }
1097
Ken Chen4ea88462021-05-23 14:56:43 +08001098 for (const auto& [subPriority, uidRanges] : uidRangeMap) {
1099 for (const UidRangeParcel& range : uidRanges.getRanges()) {
1100 if (int ret = modifyVpnUidRangeRule(table, range.start, range.stop, subPriority, secure,
Chiachang Wang2e9443f2022-01-14 22:55:36 +08001101 add, excludeLocalRoutes)) {
Ken Chen4ea88462021-05-23 14:56:43 +08001102 return ret;
1103 }
1104 if (int ret = modifyExplicitNetworkRule(netId, table, PERMISSION_NONE, range.start,
1105 range.stop, subPriority, add)) {
1106 return ret;
1107 }
1108 if (int ret = modifyOutputInterfaceRules(interface, table, PERMISSION_NONE, range.start,
1109 range.stop, subPriority, add)) {
1110 return ret;
1111 }
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -07001112 }
Sreeram Ramachandran4043f012014-06-23 12:41:37 -07001113 }
1114
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -07001115 if (modifyNonUidBasedRules) {
1116 if (int ret = modifyIncomingPacketMark(netId, interface, PERMISSION_NONE, add)) {
Sreeram Ramachandraneb27b7e2014-07-01 14:30:30 -07001117 return ret;
1118 }
Sreeram Ramachandran111bec22014-07-22 18:51:06 -07001119 if (int ret = modifyVpnOutputToLocalRule(interface, add)) {
1120 return ret;
1121 }
Chiachang Wang2e9443f2022-01-14 22:55:36 +08001122 if (int ret =
1123 modifyVpnSystemPermissionRule(netId, table, secure, add, excludeLocalRoutes)) {
Sreeram Ramachandranb1425cc2014-06-23 18:54:27 -07001124 return ret;
1125 }
Ken Chen4ea88462021-05-23 14:56:43 +08001126 return modifyExplicitNetworkRule(netId, table, PERMISSION_NONE, UID_ROOT, UID_ROOT,
Patrick Rohre2f1b5a2022-01-25 21:36:50 +01001127 UidRanges::SUB_PRIORITY_HIGHEST, add);
Sreeram Ramachandranb1425cc2014-06-23 18:54:27 -07001128 }
1129
1130 return 0;
Sreeram Ramachandran4043f012014-06-23 12:41:37 -07001131}
1132
Bernie Innocenti762dcf42019-06-14 19:52:49 +09001133int RouteController::modifyDefaultNetwork(uint16_t action, const char* interface,
1134 Permission permission) {
Chiachang Wangf79e3562022-01-15 13:31:04 +08001135 uint32_t table = getRouteTableForInterface(interface, false /* local */);
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -07001136 if (table == RT_TABLE_UNSPEC) {
Lorenzo Colitti96f261e2014-06-23 15:09:54 +09001137 return -ESRCH;
Sreeram Ramachandran9c0d3132014-04-10 20:35:04 -07001138 }
1139
Sreeram Ramachandran122f5812014-05-11 20:29:49 -07001140 Fwmark fwmark;
Sreeram Ramachandran122f5812014-05-11 20:29:49 -07001141 Fwmark mask;
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -07001142
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -07001143 fwmark.netId = NETID_UNSET;
Sreeram Ramachandran122f5812014-05-11 20:29:49 -07001144 mask.netId = FWMARK_NET_ID_MASK;
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -07001145
1146 fwmark.permission = permission;
Sreeram Ramachandran122f5812014-05-11 20:29:49 -07001147 mask.permission = permission;
1148
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -07001149 return modifyIpRule(action, RULE_PRIORITY_DEFAULT_NETWORK, table, fwmark.intValue,
Lorenzo Colitti758627c2018-03-15 01:49:20 +09001150 mask.intValue, IIF_LOOPBACK, OIF_NONE, INVALID_UID, INVALID_UID);
Sreeram Ramachandran7619e1b2014-04-15 14:23:08 -07001151}
1152
Bernie Innocenti762dcf42019-06-14 19:52:49 +09001153int RouteController::modifyTetheredNetwork(uint16_t action, const char* inputInterface,
1154 const char* outputInterface) {
Chiachang Wangf79e3562022-01-15 13:31:04 +08001155 uint32_t table = getRouteTableForInterface(outputInterface, false /* local */);
Sreeram Ramachandranfa9f4dc2014-07-22 18:16:44 -07001156 if (table == RT_TABLE_UNSPEC) {
1157 return -ESRCH;
1158 }
1159
1160 return modifyIpRule(action, RULE_PRIORITY_TETHERING, table, MARK_UNSET, MARK_UNSET,
1161 inputInterface, OIF_NONE, INVALID_UID, INVALID_UID);
1162}
1163
Lorenzo Colitti92e8f962017-09-26 19:13:50 +09001164// Adds or removes an IPv4 or IPv6 route to the specified table.
Lorenzo Colittif7fc8ec2014-06-18 00:41:58 +09001165// Returns 0 on success or negative errno on failure.
Tyler Wearfa94a272019-12-05 15:01:48 -08001166int RouteController::modifyRoute(uint16_t action, uint16_t flags, const char* interface,
1167 const char* destination, const char* nexthop, TableType tableType,
Chiachang89e504e2022-05-12 05:21:20 +00001168 int mtu, int priority, bool isLocal) {
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -07001169 uint32_t table;
Sreeram Ramachandran38b7af12014-05-22 14:21:49 -07001170 switch (tableType) {
1171 case RouteController::INTERFACE: {
Chiachang89e504e2022-05-12 05:21:20 +00001172 table = getRouteTableForInterface(interface, isLocal);
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -07001173 if (table == RT_TABLE_UNSPEC) {
1174 return -ESRCH;
1175 }
Sreeram Ramachandran38b7af12014-05-22 14:21:49 -07001176 break;
1177 }
Sreeram Ramachandran87475a12014-07-15 16:20:28 -07001178 case RouteController::LOCAL_NETWORK: {
1179 table = ROUTE_TABLE_LOCAL_NETWORK;
1180 break;
1181 }
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -07001182 case RouteController::LEGACY_NETWORK: {
Sreeram Ramachandran4acd34a2014-07-07 22:11:37 -07001183 table = ROUTE_TABLE_LEGACY_NETWORK;
Sreeram Ramachandran38b7af12014-05-22 14:21:49 -07001184 break;
1185 }
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -07001186 case RouteController::LEGACY_SYSTEM: {
Sreeram Ramachandran4acd34a2014-07-07 22:11:37 -07001187 table = ROUTE_TABLE_LEGACY_SYSTEM;
Sreeram Ramachandran38b7af12014-05-22 14:21:49 -07001188 break;
1189 }
1190 }
Sreeram Ramachandran9c0d3132014-04-10 20:35:04 -07001191
Taras Antoshchuk0cceda22021-09-24 18:40:03 +02001192 int ret = modifyIpRoute(action, flags, table, interface, destination, nexthop, mtu, priority);
Sreeram Ramachandran03213152014-10-30 10:01:07 -07001193 // Trying to add a route that already exists shouldn't cause an error.
1194 if (ret && !(action == RTM_NEWROUTE && ret == -EEXIST)) {
Lorenzo Colittif7fc8ec2014-06-18 00:41:58 +09001195 return ret;
Sreeram Ramachandranc9213372014-04-16 12:32:18 -07001196 }
1197
Lorenzo Colittif7fc8ec2014-06-18 00:41:58 +09001198 return 0;
Sreeram Ramachandran9c0d3132014-04-10 20:35:04 -07001199}
1200
Lorenzo Colitti3810c972021-01-06 11:44:02 +09001201static void maybeModifyQdiscClsact(const char* interface, bool add) {
Hungming Chen7f725432020-02-07 17:47:23 +08001202 // The clsact attaching of v4- tun interface is triggered by ClatdController::maybeStartBpf
1203 // because the clat is started before the v4- interface is added to the network and the
1204 // clat startup needs to add {in, e}gress filters.
1205 // TODO: remove this workaround once v4- tun interface clsact attaching is moved out from
1206 // ClatdController::maybeStartBpf.
1207 if (StartsWith(interface, "v4-") && add) return;
1208
1209 // The interface may have already gone away in the delete case.
Chiachang Wangf79e3562022-01-15 13:31:04 +08001210 uint32_t ifindex = RouteController::ifNameToIndexFunction(interface);
Hungming Chen7f725432020-02-07 17:47:23 +08001211 if (!ifindex) {
1212 ALOGE("cannot find interface %s", interface);
1213 return;
1214 }
1215
1216 if (add) {
1217 if (int ret = tcQdiscAddDevClsact(ifindex)) {
1218 ALOGE("tcQdiscAddDevClsact(%d[%s]) failure: %s", ifindex, interface, strerror(-ret));
1219 return;
1220 }
1221 } else {
1222 if (int ret = tcQdiscDelDevClsact(ifindex)) {
1223 ALOGE("tcQdiscDelDevClsact(%d[%s]) failure: %s", ifindex, interface, strerror(-ret));
1224 return;
1225 }
1226 }
1227
1228 return;
1229}
1230
Bernie Innocenti762dcf42019-06-14 19:52:49 +09001231[[nodiscard]] static int clearTetheringRules(const char* inputInterface) {
Lorenzo Colitti6b6f25f2015-03-03 17:22:57 +09001232 int ret = 0;
1233 while (ret == 0) {
1234 ret = modifyIpRule(RTM_DELRULE, RULE_PRIORITY_TETHERING, 0, MARK_UNSET, MARK_UNSET,
1235 inputInterface, OIF_NONE, INVALID_UID, INVALID_UID);
1236 }
1237
1238 if (ret == -ENOENT) {
1239 return 0;
1240 } else {
1241 return ret;
1242 }
1243}
1244
Lorenzo Colittif3e299a2017-02-14 17:24:28 +09001245uint32_t getRulePriority(const nlmsghdr *nlh) {
1246 return getRtmU32Attribute(nlh, FRA_PRIORITY);
1247}
1248
1249uint32_t getRouteTable(const nlmsghdr *nlh) {
1250 return getRtmU32Attribute(nlh, RTA_TABLE);
1251}
1252
Bernie Innocenti762dcf42019-06-14 19:52:49 +09001253[[nodiscard]] static int flushRules() {
Lorenzo Colittif3e299a2017-02-14 17:24:28 +09001254 NetlinkDumpFilter shouldDelete = [] (nlmsghdr *nlh) {
1255 // Don't touch rules at priority 0 because by default they are used for local input.
1256 return getRulePriority(nlh) != 0;
1257 };
1258 return rtNetlinkFlush(RTM_GETRULE, RTM_DELRULE, "rules", shouldDelete);
1259}
1260
Bernie Innocenti762dcf42019-06-14 19:52:49 +09001261int RouteController::flushRoutes(uint32_t table) {
Lorenzo Colittif3e299a2017-02-14 17:24:28 +09001262 NetlinkDumpFilter shouldDelete = [table] (nlmsghdr *nlh) {
1263 return getRouteTable(nlh) == table;
1264 };
1265
1266 return rtNetlinkFlush(RTM_GETROUTE, RTM_DELROUTE, "routes", shouldDelete);
1267}
1268
Bernie Innocenti762dcf42019-06-14 19:52:49 +09001269int RouteController::flushRoutes(const char* interface) {
Chiachang Wangf79e3562022-01-15 13:31:04 +08001270 // Try to flush both local and global routing tables.
1271 //
1272 // Flush local first because flush global routing tables may erase the sInterfaceToTable map.
1273 // Then the fake <iface>_local interface will be unable to find the index because the local
1274 // interface depends physical interface to find the correct index.
1275 int ret = flushRoutes(interface, true);
1276 ret |= flushRoutes(interface, false);
1277 return ret;
1278}
1279
1280// Returns 0 on success or negative errno on failure.
1281int RouteController::flushRoutes(const char* interface, bool local) {
Bernie Innocentiabf8a342018-08-10 15:17:16 +09001282 std::lock_guard lock(sInterfaceToTableLock);
Lorenzo Colitti107075a2017-10-30 19:24:46 +09001283
Chiachang Wangf79e3562022-01-15 13:31:04 +08001284 uint32_t table = getRouteTableForInterfaceLocked(interface, local);
Lorenzo Colittif3e299a2017-02-14 17:24:28 +09001285 if (table == RT_TABLE_UNSPEC) {
1286 return -ESRCH;
1287 }
1288
1289 int ret = flushRoutes(table);
1290
1291 // If we failed to flush routes, the caller may elect to keep this interface around, so keep
1292 // track of its name.
Chiachang Wangf79e3562022-01-15 13:31:04 +08001293 // Skip erasing local fake interface since it does not exist in sInterfaceToTable.
1294 if (ret == 0 && !local) {
Lorenzo Colitti02cb80a2017-10-30 19:21:06 +09001295 sInterfaceToTable.erase(interface);
Lorenzo Colittif3e299a2017-02-14 17:24:28 +09001296 }
1297
1298 return ret;
1299}
1300
Sreeram Ramachandran87475a12014-07-15 16:20:28 -07001301int RouteController::Init(unsigned localNetId) {
Sreeram Ramachandranb717e742014-07-19 00:22:15 -07001302 if (int ret = flushRules()) {
1303 return ret;
1304 }
Sreeram Ramachandran87475a12014-07-15 16:20:28 -07001305 if (int ret = addLegacyRouteRules()) {
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -07001306 return ret;
1307 }
Sreeram Ramachandranfa9f4dc2014-07-22 18:16:44 -07001308 if (int ret = addLocalNetworkRules(localNetId)) {
1309 return ret;
1310 }
Sreeram Ramachandranb717e742014-07-19 00:22:15 -07001311 if (int ret = addUnreachableRule()) {
1312 return ret;
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -07001313 }
Lorenzo Colitti36679362015-02-25 10:26:19 +09001314 // Don't complain if we can't add the dummy network, since not all devices support it.
1315 configureDummyNetwork();
1316
Sreeram Ramachandran4acd34a2014-07-07 22:11:37 -07001317 updateTableNamesFile();
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -07001318 return 0;
Sreeram Ramachandran8fe9c8e2014-04-16 12:08:05 -07001319}
1320
Sreeram Ramachandran6a773532014-07-11 09:10:20 -07001321int RouteController::addInterfaceToLocalNetwork(unsigned netId, const char* interface) {
Lorenzo Colittib6dc40a2020-03-24 00:58:50 +09001322 if (int ret = modifyLocalNetwork(netId, interface, ACTION_ADD)) {
1323 return ret;
1324 }
1325 std::lock_guard lock(sInterfaceToTableLock);
1326 sInterfaceToTable[interface] = ROUTE_TABLE_LOCAL_NETWORK;
1327 return 0;
Sreeram Ramachandran6a773532014-07-11 09:10:20 -07001328}
1329
1330int RouteController::removeInterfaceFromLocalNetwork(unsigned netId, const char* interface) {
Lorenzo Colittib6dc40a2020-03-24 00:58:50 +09001331 if (int ret = modifyLocalNetwork(netId, interface, ACTION_DEL)) {
1332 return ret;
1333 }
1334 std::lock_guard lock(sInterfaceToTableLock);
1335 sInterfaceToTable.erase(interface);
1336 return 0;
Sreeram Ramachandran6a773532014-07-11 09:10:20 -07001337}
1338
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -07001339int RouteController::addInterfaceToPhysicalNetwork(unsigned netId, const char* interface,
Ken Chen8738e1c2020-11-24 11:38:54 +08001340 Permission permission,
Chalard Jeane479f312022-12-12 18:27:49 +09001341 const UidRangeMap& uidRangeMap, bool local) {
Ken Chen4ea88462021-05-23 14:56:43 +08001342 if (int ret = modifyPhysicalNetwork(netId, interface, uidRangeMap, permission, ACTION_ADD,
Chalard Jeane479f312022-12-12 18:27:49 +09001343 MODIFY_NON_UID_BASED_RULES, local)) {
Sreeram Ramachandran4acd34a2014-07-07 22:11:37 -07001344 return ret;
1345 }
Chiachang Wange7bf5f52022-01-17 11:37:39 +08001346
Hungming Chen7f725432020-02-07 17:47:23 +08001347 maybeModifyQdiscClsact(interface, ACTION_ADD);
Sreeram Ramachandran4acd34a2014-07-07 22:11:37 -07001348 updateTableNamesFile();
chiachangwangb7a60992022-08-25 06:55:19 +00001349
1350 if (int ret = addFixedLocalRoutes(interface)) {
1351 return ret;
1352 }
1353
Sreeram Ramachandran4acd34a2014-07-07 22:11:37 -07001354 return 0;
Sreeram Ramachandran5c181bf2014-04-07 14:10:04 -07001355}
1356
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -07001357int RouteController::removeInterfaceFromPhysicalNetwork(unsigned netId, const char* interface,
Ken Chen8738e1c2020-11-24 11:38:54 +08001358 Permission permission,
Chalard Jeane479f312022-12-12 18:27:49 +09001359 const UidRangeMap& uidRangeMap,
1360 bool local) {
Ken Chen4ea88462021-05-23 14:56:43 +08001361 if (int ret = modifyPhysicalNetwork(netId, interface, uidRangeMap, permission, ACTION_DEL,
Chalard Jeane479f312022-12-12 18:27:49 +09001362 MODIFY_NON_UID_BASED_RULES, local)) {
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -07001363 return ret;
1364 }
Chiachang Wange7bf5f52022-01-17 11:37:39 +08001365
Chiachang8a03faa2022-05-04 07:45:37 +00001366 if (int ret = flushRoutes(interface)) {
Sreeram Ramachandran4acd34a2014-07-07 22:11:37 -07001367 return ret;
1368 }
Chiachang Wange7bf5f52022-01-17 11:37:39 +08001369
Lorenzo Colitti6b6f25f2015-03-03 17:22:57 +09001370 if (int ret = clearTetheringRules(interface)) {
1371 return ret;
1372 }
Chiachang Wange7bf5f52022-01-17 11:37:39 +08001373
Hungming Chen7f725432020-02-07 17:47:23 +08001374 maybeModifyQdiscClsact(interface, ACTION_DEL);
Sreeram Ramachandran4acd34a2014-07-07 22:11:37 -07001375 updateTableNamesFile();
1376 return 0;
Sreeram Ramachandran379bd332014-04-10 19:58:06 -07001377}
1378
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -07001379int RouteController::addInterfaceToVirtualNetwork(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 if (int ret = modifyVirtualNetwork(netId, interface, uidRangeMap, secure, ACTION_ADD,
Chiachang Wang2e9443f2022-01-14 22:55:36 +08001383 MODIFY_NON_UID_BASED_RULES, excludeLocalRoutes)) {
Sreeram Ramachandran4acd34a2014-07-07 22:11:37 -07001384 return ret;
1385 }
1386 updateTableNamesFile();
1387 return 0;
Sreeram Ramachandran4043f012014-06-23 12:41:37 -07001388}
1389
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -07001390int RouteController::removeInterfaceFromVirtualNetwork(unsigned netId, const char* interface,
Chiachang Wang2e9443f2022-01-14 22:55:36 +08001391 bool secure, const UidRangeMap& uidRangeMap,
1392 bool excludeLocalRoutes) {
Ken Chen4ea88462021-05-23 14:56:43 +08001393 if (int ret = modifyVirtualNetwork(netId, interface, uidRangeMap, secure, ACTION_DEL,
Chiachang Wang2e9443f2022-01-14 22:55:36 +08001394 MODIFY_NON_UID_BASED_RULES, excludeLocalRoutes)) {
Sreeram Ramachandran4043f012014-06-23 12:41:37 -07001395 return ret;
1396 }
Sreeram Ramachandran4acd34a2014-07-07 22:11:37 -07001397 if (int ret = flushRoutes(interface)) {
1398 return ret;
1399 }
1400 updateTableNamesFile();
1401 return 0;
Sreeram Ramachandran4043f012014-06-23 12:41:37 -07001402}
1403
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -07001404int RouteController::modifyPhysicalNetworkPermission(unsigned netId, const char* interface,
1405 Permission oldPermission,
Chalard Jeane479f312022-12-12 18:27:49 +09001406 Permission newPermission, bool local) {
Ken Chen4ea88462021-05-23 14:56:43 +08001407 // Physical network rules either use permission bits or UIDs, but not both.
1408 // So permission changes don't affect any UID-based rules.
1409 UidRangeMap emptyUidRangeMap;
Sreeram Ramachandran379bd332014-04-10 19:58:06 -07001410 // Add the new rules before deleting the old ones, to avoid race conditions.
Ken Chen4ea88462021-05-23 14:56:43 +08001411 if (int ret = modifyPhysicalNetwork(netId, interface, emptyUidRangeMap, newPermission,
Chalard Jeane479f312022-12-12 18:27:49 +09001412 ACTION_ADD, MODIFY_NON_UID_BASED_RULES, local)) {
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -07001413 return ret;
1414 }
Ken Chen4ea88462021-05-23 14:56:43 +08001415 return modifyPhysicalNetwork(netId, interface, emptyUidRangeMap, oldPermission, ACTION_DEL,
Chalard Jeane479f312022-12-12 18:27:49 +09001416 MODIFY_NON_UID_BASED_RULES, local);
Sreeram Ramachandranb1425cc2014-06-23 18:54:27 -07001417}
1418
Robin Leeb8087362016-03-30 18:43:08 +01001419int RouteController::addUsersToRejectNonSecureNetworkRule(const UidRanges& uidRanges) {
1420 return modifyRejectNonSecureNetworkRule(uidRanges, true);
1421}
1422
1423int RouteController::removeUsersFromRejectNonSecureNetworkRule(const UidRanges& uidRanges) {
1424 return modifyRejectNonSecureNetworkRule(uidRanges, false);
1425}
1426
Sreeram Ramachandran95684ba2014-07-23 13:27:31 -07001427int RouteController::addUsersToVirtualNetwork(unsigned netId, const char* interface, bool secure,
Chiachang Wang2e9443f2022-01-14 22:55:36 +08001428 const UidRangeMap& uidRangeMap,
1429 bool excludeLocalRoutes) {
Ken Chen4ea88462021-05-23 14:56:43 +08001430 return modifyVirtualNetwork(netId, interface, uidRangeMap, secure, ACTION_ADD,
Chiachang Wang2e9443f2022-01-14 22:55:36 +08001431 !MODIFY_NON_UID_BASED_RULES, excludeLocalRoutes);
Sreeram Ramachandranb1425cc2014-06-23 18:54:27 -07001432}
1433
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -07001434int RouteController::removeUsersFromVirtualNetwork(unsigned netId, const char* interface,
Chiachang Wang2e9443f2022-01-14 22:55:36 +08001435 bool secure, const UidRangeMap& uidRangeMap,
1436 bool excludeLocalRoutes) {
Ken Chen4ea88462021-05-23 14:56:43 +08001437 return modifyVirtualNetwork(netId, interface, uidRangeMap, secure, ACTION_DEL,
Chiachang Wang2e9443f2022-01-14 22:55:36 +08001438 !MODIFY_NON_UID_BASED_RULES, excludeLocalRoutes);
Sreeram Ramachandran9c0d3132014-04-10 20:35:04 -07001439}
1440
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -07001441int RouteController::addInterfaceToDefaultNetwork(const char* interface, Permission permission) {
1442 return modifyDefaultNetwork(RTM_NEWRULE, interface, permission);
Sreeram Ramachandran9c0d3132014-04-10 20:35:04 -07001443}
1444
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -07001445int RouteController::removeInterfaceFromDefaultNetwork(const char* interface,
1446 Permission permission) {
1447 return modifyDefaultNetwork(RTM_DELRULE, interface, permission);
Sreeram Ramachandran5c181bf2014-04-07 14:10:04 -07001448}
Sreeram Ramachandran7619e1b2014-04-15 14:23:08 -07001449
chiachangwang9542a1e2022-06-15 02:42:44 +00001450bool RouteController::isWithinIpv4LocalPrefix(const char* dst) {
1451 for (IPPrefix addr : V4_LOCAL_PREFIXES) {
Chiachang3aa56612022-05-12 05:55:45 +00001452 if (addr.contains(IPPrefix::forString(dst))) {
1453 return true;
1454 }
1455 }
1456 return false;
1457}
1458
chiachangwang9542a1e2022-06-15 02:42:44 +00001459bool RouteController::isLocalRoute(TableType tableType, const char* destination,
1460 const char* nexthop) {
Chiachang89e504e2022-05-12 05:21:20 +00001461 IPPrefix prefix = IPPrefix::forString(destination);
Chiachang89e504e2022-05-12 05:21:20 +00001462 return nexthop == nullptr && tableType == RouteController::INTERFACE &&
1463 // Skip default route to prevent network being modeled as point-to-point interfaces.
Chiachang3aa56612022-05-12 05:55:45 +00001464 ((prefix.family() == AF_INET6 && prefix != IPPrefix::forString("::/0")) ||
1465 // Skip adding non-target local network range.
chiachangwang9542a1e2022-06-15 02:42:44 +00001466 (prefix.family() == AF_INET && isWithinIpv4LocalPrefix(destination)));
Chiachang89e504e2022-05-12 05:21:20 +00001467}
1468
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -07001469int RouteController::addRoute(const char* interface, const char* destination, const char* nexthop,
Taras Antoshchuk0cceda22021-09-24 18:40:03 +02001470 TableType tableType, int mtu, int priority) {
Chiachang89e504e2022-05-12 05:21:20 +00001471 if (int ret = modifyRoute(RTM_NEWROUTE, NETLINK_ROUTE_CREATE_FLAGS, interface, destination,
1472 nexthop, tableType, mtu, priority, false /* isLocal */)) {
1473 return ret;
1474 }
1475
chiachangwang9542a1e2022-06-15 02:42:44 +00001476 if (isLocalRoute(tableType, destination, nexthop)) {
Chiachang89e504e2022-05-12 05:21:20 +00001477 return modifyRoute(RTM_NEWROUTE, NETLINK_ROUTE_CREATE_FLAGS, interface, destination,
1478 nexthop, tableType, mtu, priority, true /* isLocal */);
1479 }
1480
1481 return 0;
Sreeram Ramachandran7619e1b2014-04-15 14:23:08 -07001482}
1483
Lorenzo Colittif7fc8ec2014-06-18 00:41:58 +09001484int RouteController::removeRoute(const char* interface, const char* destination,
Taras Antoshchuk0cceda22021-09-24 18:40:03 +02001485 const char* nexthop, TableType tableType, int priority) {
Chiachang89e504e2022-05-12 05:21:20 +00001486 if (int ret = modifyRoute(RTM_DELROUTE, NETLINK_REQUEST_FLAGS, interface, destination, nexthop,
1487 tableType, 0 /* mtu */, priority, false /* isLocal */)) {
1488 return ret;
1489 }
1490
chiachangwang9542a1e2022-06-15 02:42:44 +00001491 if (isLocalRoute(tableType, destination, nexthop)) {
Chiachang89e504e2022-05-12 05:21:20 +00001492 return modifyRoute(RTM_DELROUTE, NETLINK_REQUEST_FLAGS, interface, destination, nexthop,
1493 tableType, 0 /* mtu */, priority, true /* isLocal */);
1494 }
1495 return 0;
Tyler Wearfa94a272019-12-05 15:01:48 -08001496}
1497
1498int RouteController::updateRoute(const char* interface, const char* destination,
1499 const char* nexthop, TableType tableType, int mtu) {
Chiachang89e504e2022-05-12 05:21:20 +00001500 if (int ret = modifyRoute(RTM_NEWROUTE, NETLINK_ROUTE_REPLACE_FLAGS, interface, destination,
1501 nexthop, tableType, mtu, 0 /* priority */, false /* isLocal */)) {
1502 return ret;
1503 }
1504
chiachangwang9542a1e2022-06-15 02:42:44 +00001505 if (isLocalRoute(tableType, destination, nexthop)) {
Chiachang89e504e2022-05-12 05:21:20 +00001506 return modifyRoute(RTM_NEWROUTE, NETLINK_ROUTE_REPLACE_FLAGS, interface, destination,
1507 nexthop, tableType, mtu, 0 /* priority */, true /* isLocal */);
1508 }
1509 return 0;
Sreeram Ramachandran7619e1b2014-04-15 14:23:08 -07001510}
Sreeram Ramachandran87475a12014-07-15 16:20:28 -07001511
1512int RouteController::enableTethering(const char* inputInterface, const char* outputInterface) {
Sreeram Ramachandranfa9f4dc2014-07-22 18:16:44 -07001513 return modifyTetheredNetwork(RTM_NEWRULE, inputInterface, outputInterface);
Sreeram Ramachandran87475a12014-07-15 16:20:28 -07001514}
1515
1516int RouteController::disableTethering(const char* inputInterface, const char* outputInterface) {
Sreeram Ramachandranfa9f4dc2014-07-22 18:16:44 -07001517 return modifyTetheredNetwork(RTM_DELRULE, inputInterface, outputInterface);
Sreeram Ramachandran87475a12014-07-15 16:20:28 -07001518}
Sreeram Ramachandran48e19b02014-07-22 22:23:20 -07001519
1520int RouteController::addVirtualNetworkFallthrough(unsigned vpnNetId, const char* physicalInterface,
1521 Permission permission) {
Chiachang8a03faa2022-05-04 07:45:37 +00001522 if (int ret = modifyVpnFallthroughRule(RTM_NEWRULE, vpnNetId, physicalInterface, permission)) {
1523 return ret;
1524 }
1525
1526 return modifyVpnLocalExclusionRule(true /* add */, physicalInterface);
Sreeram Ramachandran48e19b02014-07-22 22:23:20 -07001527}
1528
1529int RouteController::removeVirtualNetworkFallthrough(unsigned vpnNetId,
1530 const char* physicalInterface,
1531 Permission permission) {
Chiachang8a03faa2022-05-04 07:45:37 +00001532 if (int ret = modifyVpnFallthroughRule(RTM_DELRULE, vpnNetId, physicalInterface, permission)) {
1533 return ret;
1534 }
1535
1536 return modifyVpnLocalExclusionRule(false /* add */, physicalInterface);
Sreeram Ramachandran48e19b02014-07-22 22:23:20 -07001537}
Lorenzo Colitti7035f222017-02-13 18:29:00 +09001538
Ken Chen8738e1c2020-11-24 11:38:54 +08001539int RouteController::addUsersToPhysicalNetwork(unsigned netId, const char* interface,
Chalard Jeane479f312022-12-12 18:27:49 +09001540 const UidRangeMap& uidRangeMap, bool local) {
Ken Chen4ea88462021-05-23 14:56:43 +08001541 return modifyPhysicalNetwork(netId, interface, uidRangeMap, PERMISSION_NONE, ACTION_ADD,
Chalard Jeane479f312022-12-12 18:27:49 +09001542 !MODIFY_NON_UID_BASED_RULES, local);
Ken Chen8738e1c2020-11-24 11:38:54 +08001543}
1544
1545int RouteController::removeUsersFromPhysicalNetwork(unsigned netId, const char* interface,
Chalard Jeane479f312022-12-12 18:27:49 +09001546 const UidRangeMap& uidRangeMap, bool local) {
Ken Chen4ea88462021-05-23 14:56:43 +08001547 return modifyPhysicalNetwork(netId, interface, uidRangeMap, PERMISSION_NONE, ACTION_DEL,
Chalard Jeane479f312022-12-12 18:27:49 +09001548 !MODIFY_NON_UID_BASED_RULES, local);
Ken Chen8738e1c2020-11-24 11:38:54 +08001549}
1550
Ken Chen4ea88462021-05-23 14:56:43 +08001551int RouteController::addUsersToUnreachableNetwork(unsigned netId, const UidRangeMap& uidRangeMap) {
1552 return modifyUnreachableNetwork(netId, uidRangeMap, ACTION_ADD);
Ken Chen4e8ef9b2021-03-17 01:57:19 +08001553}
1554
Ken Chen4ea88462021-05-23 14:56:43 +08001555int RouteController::removeUsersFromUnreachableNetwork(unsigned netId,
1556 const UidRangeMap& uidRangeMap) {
1557 return modifyUnreachableNetwork(netId, uidRangeMap, ACTION_DEL);
Ken Chen4e8ef9b2021-03-17 01:57:19 +08001558}
1559
Lorenzo Colitti107075a2017-10-30 19:24:46 +09001560// Protects sInterfaceToTable.
Luke Huang534980c2018-07-06 17:50:11 +08001561std::mutex RouteController::sInterfaceToTableLock;
Lorenzo Colitti02cb80a2017-10-30 19:21:06 +09001562std::map<std::string, uint32_t> RouteController::sInterfaceToTable;
1563
Bernie Innocenti762dcf42019-06-14 19:52:49 +09001564} // namespace android::net