blob: ba305e69a0d5583bbc6ad88afa7b255257008a03 [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>
24#include <sys/stat.h>
25
Elliott Hughesbd378322015-02-04 13:25:14 -080026#include <private/android_filesystem_config.h>
27
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"
Hungming Chen7f725432020-02-07 17:47:23 +080034#include "OffloadUtils.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;
Luke Huang94658ac2018-10-18 19:35:12 +090046using android::net::UidRangeParcel;
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;
51
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 Colittib5d19e92017-09-25 18:39:33 +090065// None of our regular routes specify priority, which causes them to have the default priority.
66// For default throw routes, we use a fixed priority of 100000.
Lorenzo Colitti5e03a892017-09-08 11:31:59 +090067uint32_t PRIO_THROW = 100000;
68
Lorenzo Colittid78843e2017-03-27 05:52:31 +090069const char* const RouteController::LOCAL_MANGLE_INPUT = "routectrl_mangle_INPUT";
70
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -070071const uint8_t AF_FAMILIES[] = {AF_INET, AF_INET6};
72
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -070073const uid_t UID_ROOT = 0;
Lorenzo Colitti3093f562017-09-25 14:17:38 +090074const uint32_t FWMARK_NONE = 0;
75const uint32_t MASK_NONE = 0;
Lorenzo Colitti5ad4e982015-02-26 17:34:32 +090076const char* const IIF_LOOPBACK = "lo";
Yi Kongbdfd57e2018-07-25 13:26:10 -070077const char* const IIF_NONE = nullptr;
78const char* const OIF_NONE = nullptr;
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -070079const bool ACTION_ADD = true;
80const bool ACTION_DEL = false;
81const bool MODIFY_NON_UID_BASED_RULES = true;
82
Sreeram Ramachandran4acd34a2014-07-07 22:11:37 -070083const char* const RT_TABLES_PATH = "/data/misc/net/rt_tables";
Sreeram Ramachandranc7d804c2014-07-09 07:39:30 -070084const 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 -070085
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -070086// Avoids "non-constant-expression cannot be narrowed from type 'unsigned int' to 'unsigned short'"
87// warnings when using RTA_LENGTH(x) inside static initializers (even when x is already uint16_t).
Bernie Innocenti762dcf42019-06-14 19:52:49 +090088static constexpr uint16_t U16_RTA_LENGTH(uint16_t x) {
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -070089 return RTA_LENGTH(x);
90}
91
92// These are practically const, but can't be declared so, because they are used to initialize
93// non-const pointers ("void* iov_base") in iovec arrays.
Lorenzo Colitti2b078672016-12-16 18:45:03 +090094rtattr FRATTR_PRIORITY = { U16_RTA_LENGTH(sizeof(uint32_t)), FRA_PRIORITY };
95rtattr FRATTR_TABLE = { U16_RTA_LENGTH(sizeof(uint32_t)), FRA_TABLE };
96rtattr FRATTR_FWMARK = { U16_RTA_LENGTH(sizeof(uint32_t)), FRA_FWMARK };
97rtattr FRATTR_FWMASK = { U16_RTA_LENGTH(sizeof(uint32_t)), FRA_FWMASK };
Lorenzo Colitti2b078672016-12-16 18:45:03 +090098rtattr FRATTR_UID_RANGE = { U16_RTA_LENGTH(sizeof(fib_rule_uid_range)), FRA_UID_RANGE };
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -070099
Lorenzo Colitti2b078672016-12-16 18:45:03 +0900100rtattr RTATTR_TABLE = { U16_RTA_LENGTH(sizeof(uint32_t)), RTA_TABLE };
101rtattr RTATTR_OIF = { U16_RTA_LENGTH(sizeof(uint32_t)), RTA_OIF };
Lorenzo Colitti5e03a892017-09-08 11:31:59 +0900102rtattr RTATTR_PRIO = { U16_RTA_LENGTH(sizeof(uint32_t)), RTA_PRIORITY };
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700103
Tyler Wearfa94a272019-12-05 15:01:48 -0800104// One or more nested attributes in the RTA_METRICS attribute.
105rtattr RTATTRX_MTU = { U16_RTA_LENGTH(sizeof(uint32_t)), RTAX_MTU};
Lorenzo Colitti57d54682020-01-24 09:18:13 +0900106constexpr size_t RTATTRX_MTU_SIZE = RTA_SPACE(sizeof(uint32_t));
Tyler Wearfa94a272019-12-05 15:01:48 -0800107
108// The RTA_METRICS attribute itself.
Lorenzo Colitti57d54682020-01-24 09:18:13 +0900109constexpr size_t RTATTR_METRICS_SIZE = RTATTRX_MTU_SIZE;
Tyler Wearfa94a272019-12-05 15:01:48 -0800110rtattr RTATTR_METRICS = { U16_RTA_LENGTH(RTATTR_METRICS_SIZE), RTA_METRICS };
111
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700112uint8_t PADDING_BUFFER[RTA_ALIGNTO] = {0, 0, 0, 0};
113
Ken Chena2206ec2021-03-24 17:15:44 +0800114constexpr bool EXPLICIT = true;
115constexpr bool IMPLICIT = false;
116
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700117// END CONSTANTS ----------------------------------------------------------------------------------
118
Bernie Innocenti762dcf42019-06-14 19:52:49 +0900119static const char* actionName(uint16_t action) {
Lorenzo Colitti0b073fb2017-02-10 07:49:12 +0900120 static const char *ops[4] = {"adding", "deleting", "getting", "???"};
121 return ops[action % 4];
122}
123
Bernie Innocenti762dcf42019-06-14 19:52:49 +0900124static const char* familyName(uint8_t family) {
Lorenzo Colitti0b073fb2017-02-10 07:49:12 +0900125 switch (family) {
126 case AF_INET: return "IPv4";
127 case AF_INET6: return "IPv6";
128 default: return "???";
129 }
130}
131
Lorenzo Colitti3810c972021-01-06 11:44:02 +0900132static void maybeModifyQdiscClsact(const char* interface, bool add);
133
Lorenzo Colitti107075a2017-10-30 19:24:46 +0900134// Caller must hold sInterfaceToTableLock.
135uint32_t RouteController::getRouteTableForInterfaceLocked(const char* interface) {
mtk137999f2913e2019-02-25 19:39:36 +0800136 // If we already know the routing table for this interface name, use it.
137 // This ensures we can remove rules and routes for an interface that has been removed,
138 // or has been removed and re-added with a different interface index.
139 //
140 // The caller is responsible for ensuring that an interface is never added to a network
141 // until it has been removed from any network it was previously in. This ensures that
142 // if the same interface disconnects and then reconnects with a different interface ID
143 // when the reconnect happens the interface will not be in the map, and the code will
144 // determine the new routing table from the interface ID, below.
Lorenzo Colitti02cb80a2017-10-30 19:21:06 +0900145 auto iter = sInterfaceToTable.find(interface);
mtk137999f2913e2019-02-25 19:39:36 +0800146 if (iter != sInterfaceToTable.end()) {
147 return iter->second;
148 }
149
150 uint32_t index = if_nametoindex(interface);
151 if (index == 0) {
Lorenzo Colittib6dc40a2020-03-24 00:58:50 +0900152 ALOGE("cannot find interface %s: %s", interface, strerror(errno));
Sreeram Ramachandran4acd34a2014-07-07 22:11:37 -0700153 return RT_TABLE_UNSPEC;
154 }
mtk137999f2913e2019-02-25 19:39:36 +0800155 index += RouteController::ROUTE_TABLE_OFFSET_FROM_INDEX;
156 sInterfaceToTable[interface] = index;
157 return index;
Sreeram Ramachandran4acd34a2014-07-07 22:11:37 -0700158}
159
Rubin Xu6c00b612018-04-27 14:27:59 +0100160uint32_t RouteController::getIfIndex(const char* interface) {
Bernie Innocentiabf8a342018-08-10 15:17:16 +0900161 std::lock_guard lock(sInterfaceToTableLock);
Rubin Xu6c00b612018-04-27 14:27:59 +0100162
163 auto iter = sInterfaceToTable.find(interface);
164 if (iter == sInterfaceToTable.end()) {
165 ALOGE("getIfIndex: cannot find interface %s", interface);
166 return 0;
167 }
168
Lorenzo Colittib6dc40a2020-03-24 00:58:50 +0900169 // For interfaces that are not in the local network, the routing table is always the interface
170 // index plus ROUTE_TABLE_OFFSET_FROM_INDEX. But for interfaces in the local network, there's no
171 // way to know the interface index from this table. Return 0 here so callers of this method do
172 // not get confused.
173 // TODO: stop calling this method from any caller that only wants interfaces in client mode.
174 int ifindex = iter->second;
175 if (ifindex == ROUTE_TABLE_LOCAL_NETWORK) {
176 return 0;
177 }
178
179 return ifindex - ROUTE_TABLE_OFFSET_FROM_INDEX;
Rubin Xu6c00b612018-04-27 14:27:59 +0100180}
181
Lorenzo Colitti107075a2017-10-30 19:24:46 +0900182uint32_t RouteController::getRouteTableForInterface(const char* interface) {
Bernie Innocentiabf8a342018-08-10 15:17:16 +0900183 std::lock_guard lock(sInterfaceToTableLock);
Lorenzo Colitti107075a2017-10-30 19:24:46 +0900184 return getRouteTableForInterfaceLocked(interface);
185}
186
Sreeram Ramachandran4acd34a2014-07-07 22:11:37 -0700187void addTableName(uint32_t table, const std::string& name, std::string* contents) {
188 char tableString[UINT32_STRLEN];
189 snprintf(tableString, sizeof(tableString), "%u", table);
190 *contents += tableString;
191 *contents += " ";
192 *contents += name;
193 *contents += "\n";
194}
195
196// 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 +0900197void RouteController::updateTableNamesFile() {
Sreeram Ramachandran4acd34a2014-07-07 22:11:37 -0700198 std::string contents;
Sreeram Ramachandranbb40d512014-07-11 11:45:14 -0700199
200 addTableName(RT_TABLE_LOCAL, ROUTE_TABLE_NAME_LOCAL, &contents);
201 addTableName(RT_TABLE_MAIN, ROUTE_TABLE_NAME_MAIN, &contents);
202
Sreeram Ramachandran87475a12014-07-15 16:20:28 -0700203 addTableName(ROUTE_TABLE_LOCAL_NETWORK, ROUTE_TABLE_NAME_LOCAL_NETWORK, &contents);
Sreeram Ramachandran4acd34a2014-07-07 22:11:37 -0700204 addTableName(ROUTE_TABLE_LEGACY_NETWORK, ROUTE_TABLE_NAME_LEGACY_NETWORK, &contents);
205 addTableName(ROUTE_TABLE_LEGACY_SYSTEM, ROUTE_TABLE_NAME_LEGACY_SYSTEM, &contents);
Sreeram Ramachandranbb40d512014-07-11 11:45:14 -0700206
Bernie Innocentiabf8a342018-08-10 15:17:16 +0900207 std::lock_guard lock(sInterfaceToTableLock);
Lorenzo Colitti02cb80a2017-10-30 19:21:06 +0900208 for (const auto& entry : sInterfaceToTable) {
Sreeram Ramachandran4acd34a2014-07-07 22:11:37 -0700209 addTableName(entry.second, entry.first, &contents);
210 }
211
Dan Albert5407e142015-03-16 10:05:59 -0700212 if (!WriteStringToFile(contents, RT_TABLES_PATH, RT_TABLES_MODE, AID_SYSTEM, AID_WIFI)) {
Elliott Hughesbd378322015-02-04 13:25:14 -0800213 ALOGE("failed to write to %s (%s)", RT_TABLES_PATH, strerror(errno));
Sreeram Ramachandran4acd34a2014-07-07 22:11:37 -0700214 return;
215 }
Sreeram Ramachandran5c181bf2014-04-07 14:10:04 -0700216}
217
Sreeram Ramachandran87475a12014-07-15 16:20:28 -0700218// Returns 0 on success or negative errno on failure.
219int padInterfaceName(const char* input, char* name, size_t* length, uint16_t* padding) {
220 if (!input) {
221 *length = 0;
222 *padding = 0;
223 return 0;
224 }
225 *length = strlcpy(name, input, IFNAMSIZ) + 1;
226 if (*length > IFNAMSIZ) {
227 ALOGE("interface name too long (%zu > %u)", *length, IFNAMSIZ);
228 return -ENAMETOOLONG;
229 }
230 *padding = RTA_SPACE(*length) - RTA_LENGTH(*length);
231 return 0;
232}
233
Sreeram Ramachandran8fe9c8e2014-04-16 12:08:05 -0700234// Adds or removes a routing rule for IPv4 and IPv6.
235//
Lorenzo Colitti6b6f25f2015-03-03 17:22:57 +0900236// + If |table| is non-zero, the rule points at the specified routing table. Otherwise, the table is
Robin Lee4ef94642016-04-01 11:50:49 +0100237// unspecified. An unspecified table is not allowed when creating an FR_ACT_TO_TBL rule.
Sreeram Ramachandran8fe9c8e2014-04-16 12:08:05 -0700238// + If |mask| is non-zero, the rule matches the specified fwmark and mask. Otherwise, |fwmark| is
239// ignored.
Sreeram Ramachandran87475a12014-07-15 16:20:28 -0700240// + If |iif| is non-NULL, the rule matches the specified incoming interface.
241// + If |oif| is non-NULL, the rule matches the specified outgoing interface.
242// + If |uidStart| and |uidEnd| are not INVALID_UID, the rule matches packets from UIDs in that
243// range (inclusive). Otherwise, the rule matches packets from all UIDs.
Lorenzo Colitti96f261e2014-06-23 15:09:54 +0900244//
245// Returns 0 on success or negative errno on failure.
Bernie Innocenti762dcf42019-06-14 19:52:49 +0900246[[nodiscard]] static int modifyIpRule(uint16_t action, uint32_t priority, uint8_t ruleType,
247 uint32_t table, uint32_t fwmark, uint32_t mask,
248 const char* iif, const char* oif, uid_t uidStart,
249 uid_t uidEnd) {
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700250 // Ensure that if you set a bit in the fwmark, it's not being ignored by the mask.
251 if (fwmark & ~mask) {
252 ALOGE("mask 0x%x does not select all the bits set in fwmark 0x%x", mask, fwmark);
253 return -ERANGE;
254 }
255
Sreeram Ramachandran87475a12014-07-15 16:20:28 -0700256 // Interface names must include exactly one terminating NULL and be properly padded, or older
Lorenzo Colitti4753afd2014-06-20 23:03:29 +0900257 // kernels will refuse to delete rules.
Sreeram Ramachandran87475a12014-07-15 16:20:28 -0700258 char iifName[IFNAMSIZ], oifName[IFNAMSIZ];
259 size_t iifLength, oifLength;
260 uint16_t iifPadding, oifPadding;
261 if (int ret = padInterfaceName(iif, iifName, &iifLength, &iifPadding)) {
262 return ret;
263 }
264 if (int ret = padInterfaceName(oif, oifName, &oifLength, &oifPadding)) {
265 return ret;
Lorenzo Colitti4753afd2014-06-20 23:03:29 +0900266 }
267
Lorenzo Colitti59656512014-06-25 03:20:29 +0900268 // Either both start and end UID must be specified, or neither.
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700269 if ((uidStart == INVALID_UID) != (uidEnd == INVALID_UID)) {
Sreeram Ramachandrancf891382014-07-01 15:49:20 -0700270 ALOGE("incompatible start and end UIDs (%u vs %u)", uidStart, uidEnd);
Lorenzo Colitti59656512014-06-25 03:20:29 +0900271 return -EUSERS;
272 }
Robin Lee4ef94642016-04-01 11:50:49 +0100273
Lorenzo Colitti72723682014-06-26 13:51:10 +0900274 bool isUidRule = (uidStart != INVALID_UID);
Lorenzo Colitti59656512014-06-25 03:20:29 +0900275
Lorenzo Colitti4753afd2014-06-20 23:03:29 +0900276 // Assemble a rule request and put it in an array of iovec structures.
277 fib_rule_hdr rule = {
Robin Lee4ef94642016-04-01 11:50:49 +0100278 .action = ruleType,
Lorenzo Colitti6b6f25f2015-03-03 17:22:57 +0900279 // Note that here we're implicitly setting rule.table to 0. When we want to specify a
280 // non-zero table, we do this via the FRATTR_TABLE attribute.
Lorenzo Colitti4753afd2014-06-20 23:03:29 +0900281 };
282
Lorenzo Colitti6b6f25f2015-03-03 17:22:57 +0900283 // Don't ever create a rule that looks up table 0, because table 0 is the local table.
284 // It's OK to specify a table ID of 0 when deleting a rule, because that doesn't actually select
285 // table 0, it's a wildcard that matches anything.
286 if (table == RT_TABLE_UNSPEC && rule.action == FR_ACT_TO_TBL && action != RTM_DELRULE) {
287 ALOGE("RT_TABLE_UNSPEC only allowed when deleting rules");
288 return -ENOTUNIQ;
289 }
290
Sreeram Ramachandran87475a12014-07-15 16:20:28 -0700291 rtattr fraIifName = { U16_RTA_LENGTH(iifLength), FRA_IIFNAME };
292 rtattr fraOifName = { U16_RTA_LENGTH(oifLength), FRA_OIFNAME };
Lorenzo Colitti2b078672016-12-16 18:45:03 +0900293 struct fib_rule_uid_range uidRange = { uidStart, uidEnd };
Lorenzo Colitti4753afd2014-06-20 23:03:29 +0900294
295 iovec iov[] = {
Yi Kongbdfd57e2018-07-25 13:26:10 -0700296 { nullptr, 0 },
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700297 { &rule, sizeof(rule) },
298 { &FRATTR_PRIORITY, sizeof(FRATTR_PRIORITY) },
299 { &priority, sizeof(priority) },
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -0700300 { &FRATTR_TABLE, table != RT_TABLE_UNSPEC ? sizeof(FRATTR_TABLE) : 0 },
301 { &table, table != RT_TABLE_UNSPEC ? sizeof(table) : 0 },
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700302 { &FRATTR_FWMARK, mask ? sizeof(FRATTR_FWMARK) : 0 },
303 { &fwmark, mask ? sizeof(fwmark) : 0 },
304 { &FRATTR_FWMASK, mask ? sizeof(FRATTR_FWMASK) : 0 },
305 { &mask, mask ? sizeof(mask) : 0 },
Lorenzo Colitti2b078672016-12-16 18:45:03 +0900306 { &FRATTR_UID_RANGE, isUidRule ? sizeof(FRATTR_UID_RANGE) : 0 },
307 { &uidRange, isUidRule ? sizeof(uidRange) : 0 },
Sreeram Ramachandran87475a12014-07-15 16:20:28 -0700308 { &fraIifName, iif != IIF_NONE ? sizeof(fraIifName) : 0 },
309 { iifName, iifLength },
310 { PADDING_BUFFER, iifPadding },
311 { &fraOifName, oif != OIF_NONE ? sizeof(fraOifName) : 0 },
312 { oifName, oifLength },
313 { PADDING_BUFFER, oifPadding },
Lorenzo Colitti4753afd2014-06-20 23:03:29 +0900314 };
315
Lorenzo Colitti5c437992017-11-28 01:26:02 +0900316 uint16_t flags = (action == RTM_NEWRULE) ? NETLINK_RULE_CREATE_FLAGS : NETLINK_REQUEST_FLAGS;
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700317 for (size_t i = 0; i < ARRAY_SIZE(AF_FAMILIES); ++i) {
318 rule.family = AF_FAMILIES[i];
Lorenzo Colittif3e299a2017-02-14 17:24:28 +0900319 if (int ret = sendNetlinkRequest(action, flags, iov, ARRAY_SIZE(iov), nullptr)) {
Lorenzo Colitti220ca732017-02-14 17:57:55 +0900320 if (!(action == RTM_DELRULE && ret == -ENOENT && priority == RULE_PRIORITY_TETHERING)) {
321 // Don't log when deleting a tethering rule that's not there. This matches the
322 // behaviour of clearTetheringRules, which ignores ENOENT in this case.
323 ALOGE("Error %s %s rule: %s", actionName(action), familyName(rule.family),
324 strerror(-ret));
325 }
Lorenzo Colitti96f261e2014-06-23 15:09:54 +0900326 return ret;
Sreeram Ramachandran5c181bf2014-04-07 14:10:04 -0700327 }
328 }
329
Lorenzo Colitti96f261e2014-06-23 15:09:54 +0900330 return 0;
Sreeram Ramachandran5c181bf2014-04-07 14:10:04 -0700331}
332
Bernie Innocenti762dcf42019-06-14 19:52:49 +0900333[[nodiscard]] static int modifyIpRule(uint16_t action, uint32_t priority, uint32_t table,
334 uint32_t fwmark, uint32_t mask, const char* iif,
335 const char* oif, uid_t uidStart, uid_t uidEnd) {
Robin Lee4ef94642016-04-01 11:50:49 +0100336 return modifyIpRule(action, priority, FR_ACT_TO_TBL, table, fwmark, mask, iif, oif, uidStart,
337 uidEnd);
338}
339
Bernie Innocenti762dcf42019-06-14 19:52:49 +0900340[[nodiscard]] static int modifyIpRule(uint16_t action, uint32_t priority, uint32_t table,
341 uint32_t fwmark, uint32_t mask) {
Sreeram Ramachandran87475a12014-07-15 16:20:28 -0700342 return modifyIpRule(action, priority, table, fwmark, mask, IIF_NONE, OIF_NONE, INVALID_UID,
343 INVALID_UID);
344}
345
Lorenzo Colittiba25df92014-06-18 00:22:17 +0900346// Adds or deletes an IPv4 or IPv6 route.
347// Returns 0 on success or negative errno on failure.
Tyler Wearfa94a272019-12-05 15:01:48 -0800348int modifyIpRoute(uint16_t action, uint16_t flags, uint32_t table, const char* interface,
349 const char* destination, const char* nexthop, uint32_t mtu) {
Lorenzo Colittiba25df92014-06-18 00:22:17 +0900350 // At least the destination must be non-null.
351 if (!destination) {
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700352 ALOGE("null destination");
Lorenzo Colittiba25df92014-06-18 00:22:17 +0900353 return -EFAULT;
354 }
Sreeram Ramachandran7619e1b2014-04-15 14:23:08 -0700355
Lorenzo Colittiba25df92014-06-18 00:22:17 +0900356 // Parse the prefix.
357 uint8_t rawAddress[sizeof(in6_addr)];
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700358 uint8_t family;
359 uint8_t prefixLength;
Lorenzo Colittiba25df92014-06-18 00:22:17 +0900360 int rawLength = parsePrefix(destination, &family, rawAddress, sizeof(rawAddress),
361 &prefixLength);
362 if (rawLength < 0) {
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700363 ALOGE("parsePrefix failed for destination %s (%s)", destination, strerror(-rawLength));
Lorenzo Colittiba25df92014-06-18 00:22:17 +0900364 return rawLength;
365 }
Sreeram Ramachandran7619e1b2014-04-15 14:23:08 -0700366
Lorenzo Colittiba25df92014-06-18 00:22:17 +0900367 if (static_cast<size_t>(rawLength) > sizeof(rawAddress)) {
Sreeram Ramachandran1201e842014-07-01 15:06:05 -0700368 ALOGE("impossible! address too long (%d vs %zu)", rawLength, sizeof(rawAddress));
Lorenzo Colittiba25df92014-06-18 00:22:17 +0900369 return -ENOBUFS; // Cannot happen; parsePrefix only supports IPv4 and IPv6.
370 }
371
Sreeram Ramachandrande5d5df2014-07-26 18:43:25 -0700372 uint8_t type = RTN_UNICAST;
Lorenzo Colittiba25df92014-06-18 00:22:17 +0900373 uint32_t ifindex;
Lorenzo Colittiba25df92014-06-18 00:22:17 +0900374 uint8_t rawNexthop[sizeof(in6_addr)];
Sreeram Ramachandrande5d5df2014-07-26 18:43:25 -0700375
376 if (nexthop && !strcmp(nexthop, "unreachable")) {
377 type = RTN_UNREACHABLE;
378 // 'interface' is likely non-NULL, as the caller (modifyRoute()) likely used it to lookup
379 // the table number. But it's an error to specify an interface ("dev ...") or a nexthop for
380 // unreachable routes, so nuke them. (IPv6 allows them to be specified; IPv4 doesn't.)
381 interface = OIF_NONE;
Yi Kongbdfd57e2018-07-25 13:26:10 -0700382 nexthop = nullptr;
Lorenzo Colitti4c95a122014-09-18 16:01:50 +0900383 } else if (nexthop && !strcmp(nexthop, "throw")) {
384 type = RTN_THROW;
385 interface = OIF_NONE;
Yi Kongbdfd57e2018-07-25 13:26:10 -0700386 nexthop = nullptr;
Sreeram Ramachandrande5d5df2014-07-26 18:43:25 -0700387 } else {
388 // If an interface was specified, find the ifindex.
389 if (interface != OIF_NONE) {
390 ifindex = if_nametoindex(interface);
391 if (!ifindex) {
392 ALOGE("cannot find interface %s", interface);
393 return -ENODEV;
394 }
395 }
396
397 // If a nexthop was specified, parse it as the same family as the prefix.
398 if (nexthop && inet_pton(family, nexthop, rawNexthop) <= 0) {
399 ALOGE("inet_pton failed for nexthop %s", nexthop);
400 return -EINVAL;
401 }
Lorenzo Colittiba25df92014-06-18 00:22:17 +0900402 }
403
Lorenzo Colitti5e03a892017-09-08 11:31:59 +0900404 bool isDefaultThrowRoute = (type == RTN_THROW && prefixLength == 0);
405
Lorenzo Colitti4753afd2014-06-20 23:03:29 +0900406 // Assemble a rtmsg and put it in an array of iovec structures.
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700407 rtmsg route = {
Nick Desaulniers6b357502019-10-11 09:26:44 -0700408 .rtm_family = family,
409 .rtm_dst_len = prefixLength,
410 .rtm_protocol = RTPROT_STATIC,
411 .rtm_scope = static_cast<uint8_t>(nexthop ? RT_SCOPE_UNIVERSE : RT_SCOPE_LINK),
412 .rtm_type = type,
Lorenzo Colittiba25df92014-06-18 00:22:17 +0900413 };
Lorenzo Colitti4753afd2014-06-20 23:03:29 +0900414
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700415 rtattr rtaDst = { U16_RTA_LENGTH(rawLength), RTA_DST };
416 rtattr rtaGateway = { U16_RTA_LENGTH(rawLength), RTA_GATEWAY };
Lorenzo Colittiba25df92014-06-18 00:22:17 +0900417
418 iovec iov[] = {
Tyler Wearfa94a272019-12-05 15:01:48 -0800419 { nullptr, 0 },
420 { &route, sizeof(route) },
421 { &RTATTR_TABLE, sizeof(RTATTR_TABLE) },
422 { &table, sizeof(table) },
423 { &rtaDst, sizeof(rtaDst) },
424 { rawAddress, static_cast<size_t>(rawLength) },
425 { &RTATTR_OIF, interface != OIF_NONE ? sizeof(RTATTR_OIF) : 0 },
426 { &ifindex, interface != OIF_NONE ? sizeof(ifindex) : 0 },
427 { &rtaGateway, nexthop ? sizeof(rtaGateway) : 0 },
428 { rawNexthop, nexthop ? static_cast<size_t>(rawLength) : 0 },
429 { &RTATTR_METRICS, mtu != 0 ? sizeof(RTATTR_METRICS) : 0 },
430 { &RTATTRX_MTU, mtu != 0 ? sizeof(RTATTRX_MTU) : 0 },
431 { &mtu, mtu != 0 ? sizeof(mtu) : 0 },
432 { &RTATTR_PRIO, isDefaultThrowRoute ? sizeof(RTATTR_PRIO) : 0 },
433 { &PRIO_THROW, isDefaultThrowRoute ? sizeof(PRIO_THROW) : 0 },
Lorenzo Colittiba25df92014-06-18 00:22:17 +0900434 };
Lorenzo Colittiba25df92014-06-18 00:22:17 +0900435
Jimmy Chence9e5782019-03-08 16:12:55 +0800436 // Allow creating multiple link-local routes in the same table, so we can make IPv6
437 // work on all interfaces in the local_network table.
438 if (family == AF_INET6 && IN6_IS_ADDR_LINKLOCAL(reinterpret_cast<in6_addr*>(rawAddress))) {
439 flags &= ~NLM_F_EXCL;
440 }
441
Lorenzo Colittif3e299a2017-02-14 17:24:28 +0900442 int ret = sendNetlinkRequest(action, flags, iov, ARRAY_SIZE(iov), nullptr);
Lorenzo Colitti0b073fb2017-02-10 07:49:12 +0900443 if (ret) {
444 ALOGE("Error %s route %s -> %s %s to table %u: %s",
445 actionName(action), destination, nexthop, interface, table, strerror(-ret));
446 }
447 return ret;
Sreeram Ramachandran7619e1b2014-04-15 14:23:08 -0700448}
449
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -0700450// An iptables rule to mark incoming packets on a network with the netId of the network.
451//
452// This is so that the kernel can:
453// + Use the right fwmark for (and thus correctly route) replies (e.g.: TCP RST, ICMP errors, ping
454// replies, SYN-ACKs, etc).
455// + Mark sockets that accept connections from this interface so that the connection stays on the
456// same interface.
Bernie Innocenti762dcf42019-06-14 19:52:49 +0900457int modifyIncomingPacketMark(unsigned netId, const char* interface, Permission permission,
458 bool add) {
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -0700459 Fwmark fwmark;
460
461 fwmark.netId = netId;
462 fwmark.explicitlySelected = true;
463 fwmark.protectedFromVpn = true;
464 fwmark.permission = permission;
465
Benedict Wongb9baf262017-12-03 15:43:08 -0800466 const uint32_t mask = ~Fwmark::getUidBillingMask();
467
468 std::string cmd = StringPrintf(
469 "%s %s -i %s -j MARK --set-mark 0x%x/0x%x", add ? "-A" : "-D",
470 RouteController::LOCAL_MANGLE_INPUT, interface, fwmark.intValue, mask);
Lorenzo Colittic1306ea2017-03-27 05:52:31 +0900471 if (RouteController::iptablesRestoreCommandFunction(V4V6, "mangle", cmd, nullptr) != 0) {
Sreeram Ramachandranb1425cc2014-06-23 18:54:27 -0700472 ALOGE("failed to change iptables rule that sets incoming packet mark");
473 return -EREMOTEIO;
474 }
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -0700475
Sreeram Ramachandranb1425cc2014-06-23 18:54:27 -0700476 return 0;
477}
478
Sreeram Ramachandran111bec22014-07-22 18:51:06 -0700479// A rule to route responses to the local network forwarded via the VPN.
480//
481// When a VPN is in effect, packets from the local network to upstream networks are forwarded into
482// the VPN's tunnel interface. When the VPN forwards the responses, they emerge out of the tunnel.
Bernie Innocenti762dcf42019-06-14 19:52:49 +0900483[[nodiscard]] static int modifyVpnOutputToLocalRule(const char* vpnInterface, bool add) {
Sreeram Ramachandran111bec22014-07-22 18:51:06 -0700484 return modifyIpRule(add ? RTM_NEWRULE : RTM_DELRULE, RULE_PRIORITY_VPN_OUTPUT_TO_LOCAL,
485 ROUTE_TABLE_LOCAL_NETWORK, MARK_UNSET, MARK_UNSET, vpnInterface, OIF_NONE,
486 INVALID_UID, INVALID_UID);
487}
488
Sreeram Ramachandranfa9f4dc2014-07-22 18:16:44 -0700489// A rule to route all traffic from a given set of UIDs to go over the VPN.
490//
491// Notice that this rule doesn't use the netId. I.e., no matter what netId the user's socket may
492// have, if they are subject to this VPN, their traffic has to go through it. Allows the traffic to
493// bypass the VPN if the protectedFromVpn bit is set.
Bernie Innocenti762dcf42019-06-14 19:52:49 +0900494[[nodiscard]] static int modifyVpnUidRangeRule(uint32_t table, uid_t uidStart, uid_t uidEnd,
Ken Chend9aa98a2021-05-23 14:56:43 +0800495 uint32_t subPriority, bool secure, bool add) {
Sreeram Ramachandranfa9f4dc2014-07-22 18:16:44 -0700496 Fwmark fwmark;
497 Fwmark mask;
498
499 fwmark.protectedFromVpn = false;
500 mask.protectedFromVpn = true;
501
Sreeram Ramachandran95684ba2014-07-23 13:27:31 -0700502 uint32_t priority;
503
504 if (secure) {
505 priority = RULE_PRIORITY_SECURE_VPN;
506 } else {
507 priority = RULE_PRIORITY_BYPASSABLE_VPN;
508
509 fwmark.explicitlySelected = false;
510 mask.explicitlySelected = true;
511 }
512
Ken Chend9aa98a2021-05-23 14:56:43 +0800513 return modifyIpRule(add ? RTM_NEWRULE : RTM_DELRULE, priority + subPriority, table,
514 fwmark.intValue, mask.intValue, IIF_LOOPBACK, OIF_NONE, uidStart, uidEnd);
Sreeram Ramachandranfa9f4dc2014-07-22 18:16:44 -0700515}
516
517// A rule to allow system apps to send traffic over this VPN even if they are not part of the target
518// set of UIDs.
519//
520// This is needed for DnsProxyListener to correctly resolve a request for a user who is in the
521// target set, but where the DnsProxyListener itself is not.
Bernie Innocenti762dcf42019-06-14 19:52:49 +0900522[[nodiscard]] static int modifyVpnSystemPermissionRule(unsigned netId, uint32_t table, bool secure,
523 bool add) {
Sreeram Ramachandranfa9f4dc2014-07-22 18:16:44 -0700524 Fwmark fwmark;
525 Fwmark mask;
526
527 fwmark.netId = netId;
528 mask.netId = FWMARK_NET_ID_MASK;
529
530 fwmark.permission = PERMISSION_SYSTEM;
531 mask.permission = PERMISSION_SYSTEM;
532
Sreeram Ramachandran95684ba2014-07-23 13:27:31 -0700533 uint32_t priority = secure ? RULE_PRIORITY_SECURE_VPN : RULE_PRIORITY_BYPASSABLE_VPN;
534
535 return modifyIpRule(add ? RTM_NEWRULE : RTM_DELRULE, priority, table, fwmark.intValue,
536 mask.intValue);
Sreeram Ramachandranfa9f4dc2014-07-22 18:16:44 -0700537}
538
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -0700539// A rule to route traffic based on an explicitly chosen network.
540//
541// Supports apps that use the multinetwork APIs to restrict their traffic to a network.
542//
543// Even though we check permissions at the time we set a netId into the fwmark of a socket, we need
544// to check it again in the rules here, because a network's permissions may have been updated via
545// modifyNetworkPermission().
Bernie Innocenti762dcf42019-06-14 19:52:49 +0900546[[nodiscard]] static int modifyExplicitNetworkRule(unsigned netId, uint32_t table,
547 Permission permission, uid_t uidStart,
Ken Chend9aa98a2021-05-23 14:56:43 +0800548 uid_t uidEnd, uint32_t subPriority, bool add) {
Sreeram Ramachandraneb27b7e2014-07-01 14:30:30 -0700549 Fwmark fwmark;
550 Fwmark mask;
551
552 fwmark.netId = netId;
553 mask.netId = FWMARK_NET_ID_MASK;
554
Sreeram Ramachandran122f5812014-05-11 20:29:49 -0700555 fwmark.explicitlySelected = true;
556 mask.explicitlySelected = true;
Sreeram Ramachandran5c181bf2014-04-07 14:10:04 -0700557
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -0700558 fwmark.permission = permission;
559 mask.permission = permission;
Sreeram Ramachandraneb27b7e2014-07-01 14:30:30 -0700560
Ken Chend9aa98a2021-05-23 14:56:43 +0800561 return modifyIpRule(add ? RTM_NEWRULE : RTM_DELRULE,
562 RULE_PRIORITY_EXPLICIT_NETWORK + subPriority, table, fwmark.intValue,
563 mask.intValue, IIF_LOOPBACK, OIF_NONE, uidStart, uidEnd);
Sreeram Ramachandran5c181bf2014-04-07 14:10:04 -0700564}
565
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -0700566// A rule to route traffic based on a chosen outgoing interface.
567//
568// Supports apps that use SO_BINDTODEVICE or IP_PKTINFO options and the kernel that already knows
569// the outgoing interface (typically for link-local communications).
Bernie Innocenti762dcf42019-06-14 19:52:49 +0900570[[nodiscard]] static int modifyOutputInterfaceRules(const char* interface, uint32_t table,
571 Permission permission, uid_t uidStart,
Ken Chend9aa98a2021-05-23 14:56:43 +0800572 uid_t uidEnd, uint32_t subPriority, bool add) {
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -0700573 Fwmark fwmark;
574 Fwmark mask;
Sreeram Ramachandran4043f012014-06-23 12:41:37 -0700575
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -0700576 fwmark.permission = permission;
577 mask.permission = permission;
Sreeram Ramachandranb1425cc2014-06-23 18:54:27 -0700578
Lorenzo Colitti57947f02015-02-27 16:45:55 +0900579 // If this rule does not specify a UID range, then also add a corresponding high-priority rule
Lorenzo Colitti758627c2018-03-15 01:49:20 +0900580 // for root. This covers kernel-originated packets, TEEd packets and any local daemons that open
581 // sockets as root.
Lorenzo Colitti57947f02015-02-27 16:45:55 +0900582 if (uidStart == INVALID_UID && uidEnd == INVALID_UID) {
583 if (int ret = modifyIpRule(add ? RTM_NEWRULE : RTM_DELRULE, RULE_PRIORITY_VPN_OVERRIDE_OIF,
Lorenzo Colitti758627c2018-03-15 01:49:20 +0900584 table, FWMARK_NONE, MASK_NONE, IIF_LOOPBACK, interface,
Lorenzo Colitti57947f02015-02-27 16:45:55 +0900585 UID_ROOT, UID_ROOT)) {
586 return ret;
587 }
588 }
589
Ken Chend9aa98a2021-05-23 14:56:43 +0800590 return modifyIpRule(add ? RTM_NEWRULE : RTM_DELRULE,
591 RULE_PRIORITY_OUTPUT_INTERFACE + subPriority, table, fwmark.intValue,
592 mask.intValue, IIF_LOOPBACK, interface, uidStart, uidEnd);
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -0700593}
594
595// A rule to route traffic based on the chosen network.
596//
597// This is for sockets that have not explicitly requested a particular network, but have been
598// bound to one when they called connect(). This ensures that sockets connected on a particular
599// network stay on that network even if the default network changes.
Bernie Innocenti762dcf42019-06-14 19:52:49 +0900600[[nodiscard]] static int modifyImplicitNetworkRule(unsigned netId, uint32_t table, bool add) {
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -0700601 Fwmark fwmark;
602 Fwmark mask;
603
604 fwmark.netId = netId;
605 mask.netId = FWMARK_NET_ID_MASK;
606
607 fwmark.explicitlySelected = false;
608 mask.explicitlySelected = true;
609
Lorenzo Colittibe0c7c32017-09-06 16:07:02 +0900610 fwmark.permission = PERMISSION_NONE;
611 mask.permission = PERMISSION_NONE;
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -0700612
613 return modifyIpRule(add ? RTM_NEWRULE : RTM_DELRULE, RULE_PRIORITY_IMPLICIT_NETWORK, table,
Lorenzo Colitti758627c2018-03-15 01:49:20 +0900614 fwmark.intValue, mask.intValue, IIF_LOOPBACK, OIF_NONE, INVALID_UID,
615 INVALID_UID);
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -0700616}
617
Sreeram Ramachandran48e19b02014-07-22 22:23:20 -0700618// A rule to enable split tunnel VPNs.
619//
620// 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 +0800621// go over the default network, provided it has the permissions required by the default network.
Bernie Innocenti762dcf42019-06-14 19:52:49 +0900622int RouteController::modifyVpnFallthroughRule(uint16_t action, unsigned vpnNetId,
623 const char* physicalInterface,
624 Permission permission) {
Sreeram Ramachandran48e19b02014-07-22 22:23:20 -0700625 uint32_t table = getRouteTableForInterface(physicalInterface);
626 if (table == RT_TABLE_UNSPEC) {
627 return -ESRCH;
628 }
629
630 Fwmark fwmark;
631 Fwmark mask;
632
633 fwmark.netId = vpnNetId;
634 mask.netId = FWMARK_NET_ID_MASK;
635
Sreeram Ramachandran48e19b02014-07-22 22:23:20 -0700636 fwmark.permission = permission;
637 mask.permission = permission;
638
639 return modifyIpRule(action, RULE_PRIORITY_VPN_FALLTHROUGH, table, fwmark.intValue,
640 mask.intValue);
641}
642
Sreeram Ramachandranfa9f4dc2014-07-22 18:16:44 -0700643// Add rules to allow legacy routes added through the requestRouteToHost() API.
Bernie Innocenti762dcf42019-06-14 19:52:49 +0900644[[nodiscard]] static int addLegacyRouteRules() {
Sreeram Ramachandran4043f012014-06-23 12:41:37 -0700645 Fwmark fwmark;
646 Fwmark mask;
647
Sreeram Ramachandranfa9f4dc2014-07-22 18:16:44 -0700648 fwmark.explicitlySelected = false;
649 mask.explicitlySelected = true;
Sreeram Ramachandranb1425cc2014-06-23 18:54:27 -0700650
Sreeram Ramachandranfa9f4dc2014-07-22 18:16:44 -0700651 // Rules to allow legacy routes to override the default network.
652 if (int ret = modifyIpRule(RTM_NEWRULE, RULE_PRIORITY_LEGACY_SYSTEM, ROUTE_TABLE_LEGACY_SYSTEM,
653 fwmark.intValue, mask.intValue)) {
654 return ret;
655 }
656 if (int ret = modifyIpRule(RTM_NEWRULE, RULE_PRIORITY_LEGACY_NETWORK,
657 ROUTE_TABLE_LEGACY_NETWORK, fwmark.intValue, mask.intValue)) {
658 return ret;
659 }
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -0700660
661 fwmark.permission = PERMISSION_SYSTEM;
662 mask.permission = PERMISSION_SYSTEM;
663
Sreeram Ramachandranfa9f4dc2014-07-22 18:16:44 -0700664 // A rule to allow legacy routes from system apps to override VPNs.
665 return modifyIpRule(RTM_NEWRULE, RULE_PRIORITY_VPN_OVERRIDE_SYSTEM, ROUTE_TABLE_LEGACY_SYSTEM,
Sreeram Ramachandran87475a12014-07-15 16:20:28 -0700666 fwmark.intValue, mask.intValue);
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -0700667}
668
Sreeram Ramachandranfa9f4dc2014-07-22 18:16:44 -0700669// Add rules to lookup the local network when specified explicitly or otherwise.
Bernie Innocenti762dcf42019-06-14 19:52:49 +0900670[[nodiscard]] static int addLocalNetworkRules(unsigned localNetId) {
Sreeram Ramachandranfa9f4dc2014-07-22 18:16:44 -0700671 if (int ret = modifyExplicitNetworkRule(localNetId, ROUTE_TABLE_LOCAL_NETWORK, PERMISSION_NONE,
Ken Chend9aa98a2021-05-23 14:56:43 +0800672 INVALID_UID, INVALID_UID,
673 UidRanges::DEFAULT_SUB_PRIORITY, ACTION_ADD)) {
Sreeram Ramachandranfa9f4dc2014-07-22 18:16:44 -0700674 return ret;
Sreeram Ramachandran6a773532014-07-11 09:10:20 -0700675 }
676
Sreeram Ramachandranfa9f4dc2014-07-22 18:16:44 -0700677 Fwmark fwmark;
678 Fwmark mask;
679
680 fwmark.explicitlySelected = false;
681 mask.explicitlySelected = true;
682
683 return modifyIpRule(RTM_NEWRULE, RULE_PRIORITY_LOCAL_NETWORK, ROUTE_TABLE_LOCAL_NETWORK,
684 fwmark.intValue, mask.intValue);
685}
686
Lorenzo Colitti02cb80a2017-10-30 19:21:06 +0900687/* static */
688int RouteController::configureDummyNetwork() {
Lorenzo Colitti36679362015-02-25 10:26:19 +0900689 const char *interface = DummyNetwork::INTERFACE_NAME;
690 uint32_t table = getRouteTableForInterface(interface);
691 if (table == RT_TABLE_UNSPEC) {
Hungming Chen7f725432020-02-07 17:47:23 +0800692 // getRouteTableForInterface has already logged an error.
Lorenzo Colitti36679362015-02-25 10:26:19 +0900693 return -ESRCH;
694 }
695
696 ifc_init();
697 int ret = ifc_up(interface);
698 ifc_close();
699 if (ret) {
700 ALOGE("Can't bring up %s: %s", interface, strerror(errno));
701 return -errno;
702 }
703
Ken Chend9aa98a2021-05-23 14:56:43 +0800704 if ((ret = modifyOutputInterfaceRules(interface, table, PERMISSION_NONE, INVALID_UID,
705 INVALID_UID, UidRanges::DEFAULT_SUB_PRIORITY,
706 ACTION_ADD))) {
Lorenzo Colitti57947f02015-02-27 16:45:55 +0900707 ALOGE("Can't create oif rules for %s: %s", interface, strerror(-ret));
Lorenzo Colitti36679362015-02-25 10:26:19 +0900708 return ret;
709 }
710
Tyler Wearfa94a272019-12-05 15:01:48 -0800711 if ((ret = modifyIpRoute(RTM_NEWROUTE, NETLINK_ROUTE_CREATE_FLAGS, table, interface,
712 "0.0.0.0/0", nullptr, 0 /* mtu */))) {
Lorenzo Colitti36679362015-02-25 10:26:19 +0900713 return ret;
714 }
715
Tyler Wearfa94a272019-12-05 15:01:48 -0800716 if ((ret = modifyIpRoute(RTM_NEWROUTE, NETLINK_ROUTE_CREATE_FLAGS, table, interface, "::/0",
717 nullptr, 0 /* mtu */))) {
Lorenzo Colitti36679362015-02-25 10:26:19 +0900718 return ret;
719 }
720
721 return 0;
722}
723
Lorenzo Colittidb74dba2014-07-29 18:26:21 +0900724// Add an explicit unreachable rule close to the end of the prioriy list to make it clear that
725// relying on the kernel-default "from all lookup main" rule at priority 32766 is not intended
726// behaviour. We do flush the kernel-default rules at startup, but having an explicit unreachable
727// rule will hopefully make things even clearer.
Bernie Innocenti762dcf42019-06-14 19:52:49 +0900728[[nodiscard]] static int addUnreachableRule() {
Robin Leec125fe42016-05-02 08:53:34 +0100729 return modifyIpRule(RTM_NEWRULE, RULE_PRIORITY_UNREACHABLE, FR_ACT_UNREACHABLE, RT_TABLE_UNSPEC,
730 MARK_UNSET, MARK_UNSET, IIF_NONE, OIF_NONE, INVALID_UID, INVALID_UID);
Sreeram Ramachandran87475a12014-07-15 16:20:28 -0700731}
732
Bernie Innocenti762dcf42019-06-14 19:52:49 +0900733[[nodiscard]] static int modifyLocalNetwork(unsigned netId, const char* interface, bool add) {
Sreeram Ramachandran6a773532014-07-11 09:10:20 -0700734 if (int ret = modifyIncomingPacketMark(netId, interface, PERMISSION_NONE, add)) {
735 return ret;
736 }
Lorenzo Colitti3810c972021-01-06 11:44:02 +0900737 maybeModifyQdiscClsact(interface, add);
Lorenzo Colitti57947f02015-02-27 16:45:55 +0900738 return modifyOutputInterfaceRules(interface, ROUTE_TABLE_LOCAL_NETWORK, PERMISSION_NONE,
Ken Chend9aa98a2021-05-23 14:56:43 +0800739 INVALID_UID, INVALID_UID, UidRanges::DEFAULT_SUB_PRIORITY,
740 add);
Sreeram Ramachandran6a773532014-07-11 09:10:20 -0700741}
742
Ken Chena2206ec2021-03-24 17:15:44 +0800743[[nodiscard]] static int modifyUidNetworkRule(unsigned netId, uint32_t table, uid_t uidStart,
Ken Chend9aa98a2021-05-23 14:56:43 +0800744 uid_t uidEnd, uint32_t subPriority, bool add,
745 bool explicitSelect) {
Ken Chen8738e1c2020-11-24 11:38:54 +0800746 if ((uidStart == INVALID_UID) || (uidEnd == INVALID_UID)) {
Ken Chena2206ec2021-03-24 17:15:44 +0800747 ALOGE("modifyUidNetworkRule, invalid UIDs (%u, %u)", uidStart, uidEnd);
Ken Chen8738e1c2020-11-24 11:38:54 +0800748 return -EUSERS;
749 }
750
751 Fwmark fwmark;
752 Fwmark mask;
753
754 fwmark.netId = netId;
755 mask.netId = FWMARK_NET_ID_MASK;
756
Ken Chena2206ec2021-03-24 17:15:44 +0800757 fwmark.explicitlySelected = explicitSelect;
Ken Chen8738e1c2020-11-24 11:38:54 +0800758 mask.explicitlySelected = true;
759
760 // Access to this network is controlled by UID rules, not permission bits.
761 fwmark.permission = PERMISSION_NONE;
762 mask.permission = PERMISSION_NONE;
763
Ken Chena2206ec2021-03-24 17:15:44 +0800764 return modifyIpRule(add ? RTM_NEWRULE : RTM_DELRULE,
Ken Chend9aa98a2021-05-23 14:56:43 +0800765 explicitSelect ? (RULE_PRIORITY_UID_EXPLICIT_NETWORK + subPriority)
766 : (RULE_PRIORITY_UID_IMPLICIT_NETWORK + subPriority),
Ken Chena2206ec2021-03-24 17:15:44 +0800767 table, fwmark.intValue, mask.intValue, IIF_LOOPBACK, OIF_NONE, uidStart,
768 uidEnd);
Ken Chen8738e1c2020-11-24 11:38:54 +0800769}
770
771[[nodiscard]] static int modifyUidDefaultNetworkRule(uint32_t table, uid_t uidStart, uid_t uidEnd,
Ken Chend9aa98a2021-05-23 14:56:43 +0800772 uint32_t subPriority, bool add) {
Ken Chen8738e1c2020-11-24 11:38:54 +0800773 if ((uidStart == INVALID_UID) || (uidEnd == INVALID_UID)) {
774 ALOGE("modifyUidDefaultNetworkRule, invalid UIDs (%u, %u)", uidStart, uidEnd);
775 return -EUSERS;
776 }
777
778 Fwmark fwmark;
779 Fwmark mask;
780
781 fwmark.netId = NETID_UNSET;
782 mask.netId = FWMARK_NET_ID_MASK;
783
784 // Access to this network is controlled by UID rules, not permission bits.
785 fwmark.permission = PERMISSION_NONE;
786 mask.permission = PERMISSION_NONE;
787
Ken Chend9aa98a2021-05-23 14:56:43 +0800788 return modifyIpRule(add ? RTM_NEWRULE : RTM_DELRULE,
789 RULE_PRIORITY_UID_DEFAULT_NETWORK + subPriority, table, fwmark.intValue,
790 mask.intValue, IIF_LOOPBACK, OIF_NONE, uidStart, uidEnd);
Ken Chen8738e1c2020-11-24 11:38:54 +0800791}
792
Lorenzo Colitti02cb80a2017-10-30 19:21:06 +0900793/* static */
Bernie Innocenti762dcf42019-06-14 19:52:49 +0900794int RouteController::modifyPhysicalNetwork(unsigned netId, const char* interface,
Ken Chend9aa98a2021-05-23 14:56:43 +0800795 const UidRangeMap& uidRangeMap, Permission permission,
Ken Chen8738e1c2020-11-24 11:38:54 +0800796 bool add, bool modifyNonUidBasedRules) {
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -0700797 uint32_t table = getRouteTableForInterface(interface);
798 if (table == RT_TABLE_UNSPEC) {
799 return -ESRCH;
800 }
801
Ken Chend9aa98a2021-05-23 14:56:43 +0800802 for (const auto& [subPriority, uidRanges] : uidRangeMap) {
803 for (const UidRangeParcel& range : uidRanges.getRanges()) {
804 if (int ret = modifyUidNetworkRule(netId, table, range.start, range.stop, subPriority,
805 add, EXPLICIT)) {
806 return ret;
807 }
808 if (int ret = modifyUidNetworkRule(netId, table, range.start, range.stop, subPriority,
809 add, IMPLICIT)) {
810 return ret;
811 }
812 if (int ret = modifyUidDefaultNetworkRule(table, range.start, range.stop, subPriority,
813 add)) {
814 return ret;
815 }
Ken Chen8738e1c2020-11-24 11:38:54 +0800816 }
817 }
818
819 if (!modifyNonUidBasedRules) {
820 // we are done.
821 return 0;
822 }
823
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -0700824 if (int ret = modifyIncomingPacketMark(netId, interface, permission, add)) {
825 return ret;
826 }
827 if (int ret = modifyExplicitNetworkRule(netId, table, permission, INVALID_UID, INVALID_UID,
Ken Chend9aa98a2021-05-23 14:56:43 +0800828 UidRanges::DEFAULT_SUB_PRIORITY, add)) {
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -0700829 return ret;
830 }
Lorenzo Colitti57947f02015-02-27 16:45:55 +0900831 if (int ret = modifyOutputInterfaceRules(interface, table, permission, INVALID_UID, INVALID_UID,
Ken Chend9aa98a2021-05-23 14:56:43 +0800832 UidRanges::DEFAULT_SUB_PRIORITY, add)) {
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -0700833 return ret;
834 }
Lorenzo Colittibe0c7c32017-09-06 16:07:02 +0900835
836 // Only set implicit rules for networks that don't require permissions.
837 //
838 // This is so that if the default network ceases to be the default network and then switches
839 // from requiring no permissions to requiring permissions, we ensure that apps only use the
840 // network if they explicitly select it. This is consistent with destroySocketsLackingPermission
841 // - it closes all sockets on the network except sockets that are explicitly selected.
842 //
843 // The lack of this rule only affects the special case above, because:
844 // - The only cases where we implicitly bind a socket to a network are the default network and
845 // the bypassable VPN that applies to the app, if any.
846 // - This rule doesn't affect VPNs because they don't support permissions at all.
847 // - The default network doesn't require permissions. While we support doing this, the framework
848 // never does it (partly because we'd end up in the situation where we tell apps that there is
849 // a default network, but they can't use it).
850 // - If the network is still the default network, the presence or absence of this rule does not
851 // matter.
852 //
853 // Therefore, for the lack of this rule to affect a socket, the socket has to have been
854 // implicitly bound to a network because at the time of connect() it was the default, and that
855 // network must no longer be the default, and must now require permissions.
856 if (permission == PERMISSION_NONE) {
857 return modifyImplicitNetworkRule(netId, table, add);
858 }
859 return 0;
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -0700860}
861
Ken Chen4e8ef9b2021-03-17 01:57:19 +0800862[[nodiscard]] static int modifyUidUnreachableRule(unsigned netId, uid_t uidStart, uid_t uidEnd,
Ken Chend9aa98a2021-05-23 14:56:43 +0800863 uint32_t subPriority, bool add,
864 bool explicitSelect) {
Ken Chen4e8ef9b2021-03-17 01:57:19 +0800865 if ((uidStart == INVALID_UID) || (uidEnd == INVALID_UID)) {
866 ALOGE("modifyUidUnreachableRule, invalid UIDs (%u, %u)", uidStart, uidEnd);
867 return -EUSERS;
868 }
869
870 Fwmark fwmark;
871 Fwmark mask;
872
873 fwmark.netId = netId;
874 mask.netId = FWMARK_NET_ID_MASK;
875
876 fwmark.explicitlySelected = explicitSelect;
877 mask.explicitlySelected = true;
878
879 // Access to this network is controlled by UID rules, not permission bits.
880 fwmark.permission = PERMISSION_NONE;
881 mask.permission = PERMISSION_NONE;
882
883 return modifyIpRule(add ? RTM_NEWRULE : RTM_DELRULE,
Ken Chend9aa98a2021-05-23 14:56:43 +0800884 explicitSelect ? (RULE_PRIORITY_UID_EXPLICIT_NETWORK + subPriority)
885 : (RULE_PRIORITY_UID_IMPLICIT_NETWORK + subPriority),
Ken Chen4e8ef9b2021-03-17 01:57:19 +0800886 FR_ACT_UNREACHABLE, RT_TABLE_UNSPEC, fwmark.intValue, mask.intValue,
887 IIF_LOOPBACK, OIF_NONE, uidStart, uidEnd);
888}
889
Ken Chend9aa98a2021-05-23 14:56:43 +0800890[[nodiscard]] static int modifyUidDefaultUnreachableRule(uid_t uidStart, uid_t uidEnd,
891 uint32_t subPriority, bool add) {
Ken Chen4e8ef9b2021-03-17 01:57:19 +0800892 if ((uidStart == INVALID_UID) || (uidEnd == INVALID_UID)) {
Ken Chend9aa98a2021-05-23 14:56:43 +0800893 ALOGE("modifyUidDefaultUnreachableRule, invalid UIDs (%u, %u)", uidStart, uidEnd);
Ken Chen4e8ef9b2021-03-17 01:57:19 +0800894 return -EUSERS;
895 }
896
897 Fwmark fwmark;
898 Fwmark mask;
899
900 fwmark.netId = NETID_UNSET;
901 mask.netId = FWMARK_NET_ID_MASK;
902
903 // Access to this network is controlled by UID rules, not permission bits.
904 fwmark.permission = PERMISSION_NONE;
905 mask.permission = PERMISSION_NONE;
906
Ken Chend9aa98a2021-05-23 14:56:43 +0800907 return modifyIpRule(add ? RTM_NEWRULE : RTM_DELRULE,
908 RULE_PRIORITY_UID_DEFAULT_UNREACHABLE + subPriority, FR_ACT_UNREACHABLE,
909 RT_TABLE_UNSPEC, fwmark.intValue, mask.intValue, IIF_LOOPBACK, OIF_NONE,
910 uidStart, uidEnd);
Ken Chen4e8ef9b2021-03-17 01:57:19 +0800911}
912
Ken Chend9aa98a2021-05-23 14:56:43 +0800913int RouteController::modifyUnreachableNetwork(unsigned netId, const UidRangeMap& uidRangeMap,
Ken Chen4e8ef9b2021-03-17 01:57:19 +0800914 bool add) {
Ken Chend9aa98a2021-05-23 14:56:43 +0800915 for (const auto& [subPriority, uidRanges] : uidRangeMap) {
916 for (const UidRangeParcel& range : uidRanges.getRanges()) {
917 if (int ret = modifyUidUnreachableRule(netId, range.start, range.stop, subPriority, add,
918 EXPLICIT)) {
919 return ret;
920 }
921 if (int ret = modifyUidUnreachableRule(netId, range.start, range.stop, subPriority, add,
922 IMPLICIT)) {
923 return ret;
924 }
925 if (int ret = modifyUidDefaultUnreachableRule(range.start, range.stop, subPriority,
926 add)) {
927 return ret;
928 }
Ken Chen4e8ef9b2021-03-17 01:57:19 +0800929 }
930 }
931
932 return 0;
933}
934
Bernie Innocenti762dcf42019-06-14 19:52:49 +0900935[[nodiscard]] static int modifyRejectNonSecureNetworkRule(const UidRanges& uidRanges, bool add) {
Robin Leeb8087362016-03-30 18:43:08 +0100936 Fwmark fwmark;
937 Fwmark mask;
938 fwmark.protectedFromVpn = false;
939 mask.protectedFromVpn = true;
940
Luke Huang94658ac2018-10-18 19:35:12 +0900941 for (const UidRangeParcel& range : uidRanges.getRanges()) {
942 if (int ret = modifyIpRule(add ? RTM_NEWRULE : RTM_DELRULE, RULE_PRIORITY_PROHIBIT_NON_VPN,
943 FR_ACT_PROHIBIT, RT_TABLE_UNSPEC, fwmark.intValue, mask.intValue,
944 IIF_LOOPBACK, OIF_NONE, range.start, range.stop)) {
Robin Leeb8087362016-03-30 18:43:08 +0100945 return ret;
946 }
947 }
948
949 return 0;
950}
951
Bernie Innocenti762dcf42019-06-14 19:52:49 +0900952int RouteController::modifyVirtualNetwork(unsigned netId, const char* interface,
Ken Chend9aa98a2021-05-23 14:56:43 +0800953 const UidRangeMap& uidRangeMap, bool secure, bool add,
Bernie Innocenti762dcf42019-06-14 19:52:49 +0900954 bool modifyNonUidBasedRules) {
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -0700955 uint32_t table = getRouteTableForInterface(interface);
956 if (table == RT_TABLE_UNSPEC) {
957 return -ESRCH;
958 }
959
Ken Chend9aa98a2021-05-23 14:56:43 +0800960 for (const auto& [subPriority, uidRanges] : uidRangeMap) {
961 for (const UidRangeParcel& range : uidRanges.getRanges()) {
962 if (int ret = modifyVpnUidRangeRule(table, range.start, range.stop, subPriority, secure,
963 add)) {
964 return ret;
965 }
966 if (int ret = modifyExplicitNetworkRule(netId, table, PERMISSION_NONE, range.start,
967 range.stop, subPriority, add)) {
968 return ret;
969 }
970 if (int ret = modifyOutputInterfaceRules(interface, table, PERMISSION_NONE, range.start,
971 range.stop, subPriority, add)) {
972 return ret;
973 }
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -0700974 }
Sreeram Ramachandran4043f012014-06-23 12:41:37 -0700975 }
976
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -0700977 if (modifyNonUidBasedRules) {
978 if (int ret = modifyIncomingPacketMark(netId, interface, PERMISSION_NONE, add)) {
Sreeram Ramachandraneb27b7e2014-07-01 14:30:30 -0700979 return ret;
980 }
Sreeram Ramachandran111bec22014-07-22 18:51:06 -0700981 if (int ret = modifyVpnOutputToLocalRule(interface, add)) {
982 return ret;
983 }
Sreeram Ramachandran95684ba2014-07-23 13:27:31 -0700984 if (int ret = modifyVpnSystemPermissionRule(netId, table, secure, add)) {
Sreeram Ramachandranb1425cc2014-06-23 18:54:27 -0700985 return ret;
986 }
Ken Chend9aa98a2021-05-23 14:56:43 +0800987 return modifyExplicitNetworkRule(netId, table, PERMISSION_NONE, UID_ROOT, UID_ROOT,
988 UidRanges::DEFAULT_SUB_PRIORITY, add);
Sreeram Ramachandranb1425cc2014-06-23 18:54:27 -0700989 }
990
991 return 0;
Sreeram Ramachandran4043f012014-06-23 12:41:37 -0700992}
993
Bernie Innocenti762dcf42019-06-14 19:52:49 +0900994int RouteController::modifyDefaultNetwork(uint16_t action, const char* interface,
995 Permission permission) {
Sreeram Ramachandran9c0d3132014-04-10 20:35:04 -0700996 uint32_t table = getRouteTableForInterface(interface);
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -0700997 if (table == RT_TABLE_UNSPEC) {
Lorenzo Colitti96f261e2014-06-23 15:09:54 +0900998 return -ESRCH;
Sreeram Ramachandran9c0d3132014-04-10 20:35:04 -0700999 }
1000
Sreeram Ramachandran122f5812014-05-11 20:29:49 -07001001 Fwmark fwmark;
Sreeram Ramachandran122f5812014-05-11 20:29:49 -07001002 Fwmark mask;
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -07001003
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -07001004 fwmark.netId = NETID_UNSET;
Sreeram Ramachandran122f5812014-05-11 20:29:49 -07001005 mask.netId = FWMARK_NET_ID_MASK;
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -07001006
1007 fwmark.permission = permission;
Sreeram Ramachandran122f5812014-05-11 20:29:49 -07001008 mask.permission = permission;
1009
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -07001010 return modifyIpRule(action, RULE_PRIORITY_DEFAULT_NETWORK, table, fwmark.intValue,
Lorenzo Colitti758627c2018-03-15 01:49:20 +09001011 mask.intValue, IIF_LOOPBACK, OIF_NONE, INVALID_UID, INVALID_UID);
Sreeram Ramachandran7619e1b2014-04-15 14:23:08 -07001012}
1013
Bernie Innocenti762dcf42019-06-14 19:52:49 +09001014int RouteController::modifyTetheredNetwork(uint16_t action, const char* inputInterface,
1015 const char* outputInterface) {
Sreeram Ramachandranfa9f4dc2014-07-22 18:16:44 -07001016 uint32_t table = getRouteTableForInterface(outputInterface);
1017 if (table == RT_TABLE_UNSPEC) {
1018 return -ESRCH;
1019 }
1020
1021 return modifyIpRule(action, RULE_PRIORITY_TETHERING, table, MARK_UNSET, MARK_UNSET,
1022 inputInterface, OIF_NONE, INVALID_UID, INVALID_UID);
1023}
1024
Lorenzo Colitti92e8f962017-09-26 19:13:50 +09001025// Adds or removes an IPv4 or IPv6 route to the specified table.
Lorenzo Colittif7fc8ec2014-06-18 00:41:58 +09001026// Returns 0 on success or negative errno on failure.
Tyler Wearfa94a272019-12-05 15:01:48 -08001027int RouteController::modifyRoute(uint16_t action, uint16_t flags, const char* interface,
1028 const char* destination, const char* nexthop, TableType tableType,
1029 int mtu) {
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -07001030 uint32_t table;
Sreeram Ramachandran38b7af12014-05-22 14:21:49 -07001031 switch (tableType) {
1032 case RouteController::INTERFACE: {
1033 table = getRouteTableForInterface(interface);
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -07001034 if (table == RT_TABLE_UNSPEC) {
1035 return -ESRCH;
1036 }
Sreeram Ramachandran38b7af12014-05-22 14:21:49 -07001037 break;
1038 }
Sreeram Ramachandran87475a12014-07-15 16:20:28 -07001039 case RouteController::LOCAL_NETWORK: {
1040 table = ROUTE_TABLE_LOCAL_NETWORK;
1041 break;
1042 }
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -07001043 case RouteController::LEGACY_NETWORK: {
Sreeram Ramachandran4acd34a2014-07-07 22:11:37 -07001044 table = ROUTE_TABLE_LEGACY_NETWORK;
Sreeram Ramachandran38b7af12014-05-22 14:21:49 -07001045 break;
1046 }
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -07001047 case RouteController::LEGACY_SYSTEM: {
Sreeram Ramachandran4acd34a2014-07-07 22:11:37 -07001048 table = ROUTE_TABLE_LEGACY_SYSTEM;
Sreeram Ramachandran38b7af12014-05-22 14:21:49 -07001049 break;
1050 }
1051 }
Sreeram Ramachandran9c0d3132014-04-10 20:35:04 -07001052
Tyler Wearfa94a272019-12-05 15:01:48 -08001053 int ret = modifyIpRoute(action, flags, table, interface, destination, nexthop, mtu);
Sreeram Ramachandran03213152014-10-30 10:01:07 -07001054 // Trying to add a route that already exists shouldn't cause an error.
1055 if (ret && !(action == RTM_NEWROUTE && ret == -EEXIST)) {
Lorenzo Colittif7fc8ec2014-06-18 00:41:58 +09001056 return ret;
Sreeram Ramachandranc9213372014-04-16 12:32:18 -07001057 }
1058
Lorenzo Colittif7fc8ec2014-06-18 00:41:58 +09001059 return 0;
Sreeram Ramachandran9c0d3132014-04-10 20:35:04 -07001060}
1061
Lorenzo Colitti3810c972021-01-06 11:44:02 +09001062static void maybeModifyQdiscClsact(const char* interface, bool add) {
Hungming Chen7f725432020-02-07 17:47:23 +08001063 // The clsact attaching of v4- tun interface is triggered by ClatdController::maybeStartBpf
1064 // because the clat is started before the v4- interface is added to the network and the
1065 // clat startup needs to add {in, e}gress filters.
1066 // TODO: remove this workaround once v4- tun interface clsact attaching is moved out from
1067 // ClatdController::maybeStartBpf.
1068 if (StartsWith(interface, "v4-") && add) return;
1069
1070 // The interface may have already gone away in the delete case.
1071 uint32_t ifindex = if_nametoindex(interface);
1072 if (!ifindex) {
1073 ALOGE("cannot find interface %s", interface);
1074 return;
1075 }
1076
1077 if (add) {
1078 if (int ret = tcQdiscAddDevClsact(ifindex)) {
1079 ALOGE("tcQdiscAddDevClsact(%d[%s]) failure: %s", ifindex, interface, strerror(-ret));
1080 return;
1081 }
1082 } else {
1083 if (int ret = tcQdiscDelDevClsact(ifindex)) {
1084 ALOGE("tcQdiscDelDevClsact(%d[%s]) failure: %s", ifindex, interface, strerror(-ret));
1085 return;
1086 }
1087 }
1088
1089 return;
1090}
1091
Bernie Innocenti762dcf42019-06-14 19:52:49 +09001092[[nodiscard]] static int clearTetheringRules(const char* inputInterface) {
Lorenzo Colitti6b6f25f2015-03-03 17:22:57 +09001093 int ret = 0;
1094 while (ret == 0) {
1095 ret = modifyIpRule(RTM_DELRULE, RULE_PRIORITY_TETHERING, 0, MARK_UNSET, MARK_UNSET,
1096 inputInterface, OIF_NONE, INVALID_UID, INVALID_UID);
1097 }
1098
1099 if (ret == -ENOENT) {
1100 return 0;
1101 } else {
1102 return ret;
1103 }
1104}
1105
Lorenzo Colittif3e299a2017-02-14 17:24:28 +09001106uint32_t getRulePriority(const nlmsghdr *nlh) {
1107 return getRtmU32Attribute(nlh, FRA_PRIORITY);
1108}
1109
1110uint32_t getRouteTable(const nlmsghdr *nlh) {
1111 return getRtmU32Attribute(nlh, RTA_TABLE);
1112}
1113
Bernie Innocenti762dcf42019-06-14 19:52:49 +09001114[[nodiscard]] static int flushRules() {
Lorenzo Colittif3e299a2017-02-14 17:24:28 +09001115 NetlinkDumpFilter shouldDelete = [] (nlmsghdr *nlh) {
1116 // Don't touch rules at priority 0 because by default they are used for local input.
1117 return getRulePriority(nlh) != 0;
1118 };
1119 return rtNetlinkFlush(RTM_GETRULE, RTM_DELRULE, "rules", shouldDelete);
1120}
1121
Bernie Innocenti762dcf42019-06-14 19:52:49 +09001122int RouteController::flushRoutes(uint32_t table) {
Lorenzo Colittif3e299a2017-02-14 17:24:28 +09001123 NetlinkDumpFilter shouldDelete = [table] (nlmsghdr *nlh) {
1124 return getRouteTable(nlh) == table;
1125 };
1126
1127 return rtNetlinkFlush(RTM_GETROUTE, RTM_DELROUTE, "routes", shouldDelete);
1128}
1129
1130// Returns 0 on success or negative errno on failure.
Bernie Innocenti762dcf42019-06-14 19:52:49 +09001131int RouteController::flushRoutes(const char* interface) {
Bernie Innocentiabf8a342018-08-10 15:17:16 +09001132 std::lock_guard lock(sInterfaceToTableLock);
Lorenzo Colitti107075a2017-10-30 19:24:46 +09001133
1134 uint32_t table = getRouteTableForInterfaceLocked(interface);
Lorenzo Colittif3e299a2017-02-14 17:24:28 +09001135 if (table == RT_TABLE_UNSPEC) {
1136 return -ESRCH;
1137 }
1138
1139 int ret = flushRoutes(table);
1140
1141 // If we failed to flush routes, the caller may elect to keep this interface around, so keep
1142 // track of its name.
1143 if (ret == 0) {
Lorenzo Colitti02cb80a2017-10-30 19:21:06 +09001144 sInterfaceToTable.erase(interface);
Lorenzo Colittif3e299a2017-02-14 17:24:28 +09001145 }
1146
1147 return ret;
1148}
1149
Sreeram Ramachandran87475a12014-07-15 16:20:28 -07001150int RouteController::Init(unsigned localNetId) {
Sreeram Ramachandranb717e742014-07-19 00:22:15 -07001151 if (int ret = flushRules()) {
1152 return ret;
1153 }
Sreeram Ramachandran87475a12014-07-15 16:20:28 -07001154 if (int ret = addLegacyRouteRules()) {
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -07001155 return ret;
1156 }
Sreeram Ramachandranfa9f4dc2014-07-22 18:16:44 -07001157 if (int ret = addLocalNetworkRules(localNetId)) {
1158 return ret;
1159 }
Sreeram Ramachandranb717e742014-07-19 00:22:15 -07001160 if (int ret = addUnreachableRule()) {
1161 return ret;
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -07001162 }
Lorenzo Colitti36679362015-02-25 10:26:19 +09001163 // Don't complain if we can't add the dummy network, since not all devices support it.
1164 configureDummyNetwork();
1165
Sreeram Ramachandran4acd34a2014-07-07 22:11:37 -07001166 updateTableNamesFile();
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -07001167 return 0;
Sreeram Ramachandran8fe9c8e2014-04-16 12:08:05 -07001168}
1169
Sreeram Ramachandran6a773532014-07-11 09:10:20 -07001170int RouteController::addInterfaceToLocalNetwork(unsigned netId, const char* interface) {
Lorenzo Colittib6dc40a2020-03-24 00:58:50 +09001171 if (int ret = modifyLocalNetwork(netId, interface, ACTION_ADD)) {
1172 return ret;
1173 }
1174 std::lock_guard lock(sInterfaceToTableLock);
1175 sInterfaceToTable[interface] = ROUTE_TABLE_LOCAL_NETWORK;
1176 return 0;
Sreeram Ramachandran6a773532014-07-11 09:10:20 -07001177}
1178
1179int RouteController::removeInterfaceFromLocalNetwork(unsigned netId, const char* interface) {
Lorenzo Colittib6dc40a2020-03-24 00:58:50 +09001180 if (int ret = modifyLocalNetwork(netId, interface, ACTION_DEL)) {
1181 return ret;
1182 }
1183 std::lock_guard lock(sInterfaceToTableLock);
1184 sInterfaceToTable.erase(interface);
1185 return 0;
Sreeram Ramachandran6a773532014-07-11 09:10:20 -07001186}
1187
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -07001188int RouteController::addInterfaceToPhysicalNetwork(unsigned netId, const char* interface,
Ken Chen8738e1c2020-11-24 11:38:54 +08001189 Permission permission,
Ken Chend9aa98a2021-05-23 14:56:43 +08001190 const UidRangeMap& uidRangeMap) {
1191 if (int ret = modifyPhysicalNetwork(netId, interface, uidRangeMap, permission, ACTION_ADD,
Ken Chen8738e1c2020-11-24 11:38:54 +08001192 MODIFY_NON_UID_BASED_RULES)) {
Sreeram Ramachandran4acd34a2014-07-07 22:11:37 -07001193 return ret;
1194 }
Hungming Chen7f725432020-02-07 17:47:23 +08001195 maybeModifyQdiscClsact(interface, ACTION_ADD);
Sreeram Ramachandran4acd34a2014-07-07 22:11:37 -07001196 updateTableNamesFile();
1197 return 0;
Sreeram Ramachandran5c181bf2014-04-07 14:10:04 -07001198}
1199
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -07001200int RouteController::removeInterfaceFromPhysicalNetwork(unsigned netId, const char* interface,
Ken Chen8738e1c2020-11-24 11:38:54 +08001201 Permission permission,
Ken Chend9aa98a2021-05-23 14:56:43 +08001202 const UidRangeMap& uidRangeMap) {
1203 if (int ret = modifyPhysicalNetwork(netId, interface, uidRangeMap, permission, ACTION_DEL,
Ken Chen8738e1c2020-11-24 11:38:54 +08001204 MODIFY_NON_UID_BASED_RULES)) {
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -07001205 return ret;
1206 }
Sreeram Ramachandran4acd34a2014-07-07 22:11:37 -07001207 if (int ret = flushRoutes(interface)) {
1208 return ret;
1209 }
Lorenzo Colitti6b6f25f2015-03-03 17:22:57 +09001210 if (int ret = clearTetheringRules(interface)) {
1211 return ret;
1212 }
Hungming Chen7f725432020-02-07 17:47:23 +08001213 maybeModifyQdiscClsact(interface, ACTION_DEL);
Sreeram Ramachandran4acd34a2014-07-07 22:11:37 -07001214 updateTableNamesFile();
1215 return 0;
Sreeram Ramachandran379bd332014-04-10 19:58:06 -07001216}
1217
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -07001218int RouteController::addInterfaceToVirtualNetwork(unsigned netId, const char* interface,
Ken Chend9aa98a2021-05-23 14:56:43 +08001219 bool secure, const UidRangeMap& uidRangeMap) {
1220 if (int ret = modifyVirtualNetwork(netId, interface, uidRangeMap, secure, ACTION_ADD,
Sreeram Ramachandran4acd34a2014-07-07 22:11:37 -07001221 MODIFY_NON_UID_BASED_RULES)) {
1222 return ret;
1223 }
1224 updateTableNamesFile();
1225 return 0;
Sreeram Ramachandran4043f012014-06-23 12:41:37 -07001226}
1227
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -07001228int RouteController::removeInterfaceFromVirtualNetwork(unsigned netId, const char* interface,
Ken Chend9aa98a2021-05-23 14:56:43 +08001229 bool secure,
1230 const UidRangeMap& uidRangeMap) {
1231 if (int ret = modifyVirtualNetwork(netId, interface, uidRangeMap, secure, ACTION_DEL,
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -07001232 MODIFY_NON_UID_BASED_RULES)) {
Sreeram Ramachandran4043f012014-06-23 12:41:37 -07001233 return ret;
1234 }
Sreeram Ramachandran4acd34a2014-07-07 22:11:37 -07001235 if (int ret = flushRoutes(interface)) {
1236 return ret;
1237 }
1238 updateTableNamesFile();
1239 return 0;
Sreeram Ramachandran4043f012014-06-23 12:41:37 -07001240}
1241
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -07001242int RouteController::modifyPhysicalNetworkPermission(unsigned netId, const char* interface,
1243 Permission oldPermission,
1244 Permission newPermission) {
Ken Chend9aa98a2021-05-23 14:56:43 +08001245 // Physical network rules either use permission bits or UIDs, but not both.
1246 // So permission changes don't affect any UID-based rules.
1247 UidRangeMap emptyUidRangeMap;
Sreeram Ramachandran379bd332014-04-10 19:58:06 -07001248 // Add the new rules before deleting the old ones, to avoid race conditions.
Ken Chend9aa98a2021-05-23 14:56:43 +08001249 if (int ret = modifyPhysicalNetwork(netId, interface, emptyUidRangeMap, newPermission,
1250 ACTION_ADD, MODIFY_NON_UID_BASED_RULES)) {
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -07001251 return ret;
1252 }
Ken Chend9aa98a2021-05-23 14:56:43 +08001253 return modifyPhysicalNetwork(netId, interface, emptyUidRangeMap, oldPermission, ACTION_DEL,
Ken Chen8738e1c2020-11-24 11:38:54 +08001254 MODIFY_NON_UID_BASED_RULES);
Sreeram Ramachandranb1425cc2014-06-23 18:54:27 -07001255}
1256
Robin Leeb8087362016-03-30 18:43:08 +01001257int RouteController::addUsersToRejectNonSecureNetworkRule(const UidRanges& uidRanges) {
1258 return modifyRejectNonSecureNetworkRule(uidRanges, true);
1259}
1260
1261int RouteController::removeUsersFromRejectNonSecureNetworkRule(const UidRanges& uidRanges) {
1262 return modifyRejectNonSecureNetworkRule(uidRanges, false);
1263}
1264
Sreeram Ramachandran95684ba2014-07-23 13:27:31 -07001265int RouteController::addUsersToVirtualNetwork(unsigned netId, const char* interface, bool secure,
Ken Chend9aa98a2021-05-23 14:56:43 +08001266 const UidRangeMap& uidRangeMap) {
1267 return modifyVirtualNetwork(netId, interface, uidRangeMap, secure, ACTION_ADD,
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -07001268 !MODIFY_NON_UID_BASED_RULES);
Sreeram Ramachandranb1425cc2014-06-23 18:54:27 -07001269}
1270
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -07001271int RouteController::removeUsersFromVirtualNetwork(unsigned netId, const char* interface,
Ken Chend9aa98a2021-05-23 14:56:43 +08001272 bool secure, const UidRangeMap& uidRangeMap) {
1273 return modifyVirtualNetwork(netId, interface, uidRangeMap, secure, ACTION_DEL,
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -07001274 !MODIFY_NON_UID_BASED_RULES);
Sreeram Ramachandran9c0d3132014-04-10 20:35:04 -07001275}
1276
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -07001277int RouteController::addInterfaceToDefaultNetwork(const char* interface, Permission permission) {
1278 return modifyDefaultNetwork(RTM_NEWRULE, interface, permission);
Sreeram Ramachandran9c0d3132014-04-10 20:35:04 -07001279}
1280
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -07001281int RouteController::removeInterfaceFromDefaultNetwork(const char* interface,
1282 Permission permission) {
1283 return modifyDefaultNetwork(RTM_DELRULE, interface, permission);
Sreeram Ramachandran5c181bf2014-04-07 14:10:04 -07001284}
Sreeram Ramachandran7619e1b2014-04-15 14:23:08 -07001285
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -07001286int RouteController::addRoute(const char* interface, const char* destination, const char* nexthop,
Tyler Wearfa94a272019-12-05 15:01:48 -08001287 TableType tableType, int mtu) {
1288 return modifyRoute(RTM_NEWROUTE, NETLINK_ROUTE_CREATE_FLAGS, interface, destination, nexthop,
1289 tableType, mtu);
Sreeram Ramachandran7619e1b2014-04-15 14:23:08 -07001290}
1291
Lorenzo Colittif7fc8ec2014-06-18 00:41:58 +09001292int RouteController::removeRoute(const char* interface, const char* destination,
Sreeram Ramachandraneb27b7e2014-07-01 14:30:30 -07001293 const char* nexthop, TableType tableType) {
Tyler Wearfa94a272019-12-05 15:01:48 -08001294 return modifyRoute(RTM_DELROUTE, NETLINK_REQUEST_FLAGS, interface, destination, nexthop,
1295 tableType, 0);
1296}
1297
1298int RouteController::updateRoute(const char* interface, const char* destination,
1299 const char* nexthop, TableType tableType, int mtu) {
1300 return modifyRoute(RTM_NEWROUTE, NETLINK_ROUTE_REPLACE_FLAGS, interface, destination, nexthop,
1301 tableType, mtu);
Sreeram Ramachandran7619e1b2014-04-15 14:23:08 -07001302}
Sreeram Ramachandran87475a12014-07-15 16:20:28 -07001303
1304int RouteController::enableTethering(const char* inputInterface, const char* outputInterface) {
Sreeram Ramachandranfa9f4dc2014-07-22 18:16:44 -07001305 return modifyTetheredNetwork(RTM_NEWRULE, inputInterface, outputInterface);
Sreeram Ramachandran87475a12014-07-15 16:20:28 -07001306}
1307
1308int RouteController::disableTethering(const char* inputInterface, const char* outputInterface) {
Sreeram Ramachandranfa9f4dc2014-07-22 18:16:44 -07001309 return modifyTetheredNetwork(RTM_DELRULE, inputInterface, outputInterface);
Sreeram Ramachandran87475a12014-07-15 16:20:28 -07001310}
Sreeram Ramachandran48e19b02014-07-22 22:23:20 -07001311
1312int RouteController::addVirtualNetworkFallthrough(unsigned vpnNetId, const char* physicalInterface,
1313 Permission permission) {
1314 return modifyVpnFallthroughRule(RTM_NEWRULE, vpnNetId, physicalInterface, permission);
1315}
1316
1317int RouteController::removeVirtualNetworkFallthrough(unsigned vpnNetId,
1318 const char* physicalInterface,
1319 Permission permission) {
1320 return modifyVpnFallthroughRule(RTM_DELRULE, vpnNetId, physicalInterface, permission);
1321}
Lorenzo Colitti7035f222017-02-13 18:29:00 +09001322
Ken Chen8738e1c2020-11-24 11:38:54 +08001323int RouteController::addUsersToPhysicalNetwork(unsigned netId, const char* interface,
Ken Chend9aa98a2021-05-23 14:56:43 +08001324 const UidRangeMap& uidRangeMap) {
1325 return modifyPhysicalNetwork(netId, interface, uidRangeMap, PERMISSION_NONE, ACTION_ADD,
Ken Chen8738e1c2020-11-24 11:38:54 +08001326 !MODIFY_NON_UID_BASED_RULES);
1327}
1328
1329int RouteController::removeUsersFromPhysicalNetwork(unsigned netId, const char* interface,
Ken Chend9aa98a2021-05-23 14:56:43 +08001330 const UidRangeMap& uidRangeMap) {
1331 return modifyPhysicalNetwork(netId, interface, uidRangeMap, PERMISSION_NONE, ACTION_DEL,
Ken Chen8738e1c2020-11-24 11:38:54 +08001332 !MODIFY_NON_UID_BASED_RULES);
1333}
1334
Ken Chend9aa98a2021-05-23 14:56:43 +08001335int RouteController::addUsersToUnreachableNetwork(unsigned netId, const UidRangeMap& uidRangeMap) {
1336 return modifyUnreachableNetwork(netId, uidRangeMap, ACTION_ADD);
Ken Chen4e8ef9b2021-03-17 01:57:19 +08001337}
1338
Ken Chend9aa98a2021-05-23 14:56:43 +08001339int RouteController::removeUsersFromUnreachableNetwork(unsigned netId,
1340 const UidRangeMap& uidRangeMap) {
1341 return modifyUnreachableNetwork(netId, uidRangeMap, ACTION_DEL);
Ken Chen4e8ef9b2021-03-17 01:57:19 +08001342}
1343
Lorenzo Colitti107075a2017-10-30 19:24:46 +09001344// Protects sInterfaceToTable.
Luke Huang534980c2018-07-06 17:50:11 +08001345std::mutex RouteController::sInterfaceToTableLock;
Lorenzo Colitti02cb80a2017-10-30 19:21:06 +09001346std::map<std::string, uint32_t> RouteController::sInterfaceToTable;
1347
Bernie Innocenti762dcf42019-06-14 19:52:49 +09001348} // namespace android::net