blob: 02418caf623e35462e9872512460a81b4a60a63b [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
Luke Huang94658ac2018-10-18 19:35:12 +090030#define LOG_TAG "Netd"
31
Lorenzo Colitti7035f222017-02-13 18:29:00 +090032#include "DummyNetwork.h"
Sreeram Ramachandran5c181bf2014-04-07 14:10:04 -070033#include "Fwmark.h"
Lorenzo Colittic1306ea2017-03-27 05:52:31 +090034#include "NetdConstants.h"
Lorenzo Colitti1ef549d2017-02-13 18:32:09 +090035#include "NetlinkCommands.h"
Hungming Chen7f725432020-02-07 17:47:23 +080036#include "OffloadUtils.h"
Sreeram Ramachandranb1425cc2014-06-23 18:54:27 -070037#include "UidRanges.h"
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -070038
Bernie Innocenti189eb502018-10-01 23:10:18 +090039#include <android-base/file.h>
Lorenzo Colittic1306ea2017-03-27 05:52:31 +090040#include <android-base/stringprintf.h>
Hungming Chen7f725432020-02-07 17:47:23 +080041#include <android-base/strings.h>
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -070042#include "log/log.h"
Bernie Innocenti189eb502018-10-01 23:10:18 +090043#include "netid_client.h"
Lorenzo Colitti36679362015-02-25 10:26:19 +090044#include "netutils/ifc.h"
Sreeram Ramachandran5c181bf2014-04-07 14:10:04 -070045
Hungming Chen7f725432020-02-07 17:47:23 +080046using android::base::StartsWith;
Lorenzo Colittic1306ea2017-03-27 05:52:31 +090047using android::base::StringPrintf;
Dan Albert5407e142015-03-16 10:05:59 -070048using android::base::WriteStringToFile;
Luke Huang94658ac2018-10-18 19:35:12 +090049using android::net::UidRangeParcel;
Dan Albert5407e142015-03-16 10:05:59 -070050
Bernie Innocenti762dcf42019-06-14 19:52:49 +090051namespace android::net {
Lorenzo Colitti7035f222017-02-13 18:29:00 +090052
Lorenzo Colittic1306ea2017-03-27 05:52:31 +090053auto RouteController::iptablesRestoreCommandFunction = execIptablesRestoreCommand;
54
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -070055// BEGIN CONSTANTS --------------------------------------------------------------------------------
56
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -070057const uint32_t RULE_PRIORITY_VPN_OVERRIDE_SYSTEM = 10000;
Lorenzo Colitti57947f02015-02-27 16:45:55 +090058const uint32_t RULE_PRIORITY_VPN_OVERRIDE_OIF = 10500;
Sreeram Ramachandran111bec22014-07-22 18:51:06 -070059const uint32_t RULE_PRIORITY_VPN_OUTPUT_TO_LOCAL = 11000;
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -070060const uint32_t RULE_PRIORITY_SECURE_VPN = 12000;
Robin Lee6c84ef62016-05-03 13:17:58 +010061const uint32_t RULE_PRIORITY_PROHIBIT_NON_VPN = 12500;
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -070062const uint32_t RULE_PRIORITY_EXPLICIT_NETWORK = 13000;
63const uint32_t RULE_PRIORITY_OUTPUT_INTERFACE = 14000;
64const uint32_t RULE_PRIORITY_LEGACY_SYSTEM = 15000;
65const uint32_t RULE_PRIORITY_LEGACY_NETWORK = 16000;
Sreeram Ramachandran6a773532014-07-11 09:10:20 -070066const uint32_t RULE_PRIORITY_LOCAL_NETWORK = 17000;
Sreeram Ramachandran87475a12014-07-15 16:20:28 -070067const uint32_t RULE_PRIORITY_TETHERING = 18000;
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -070068const uint32_t RULE_PRIORITY_IMPLICIT_NETWORK = 19000;
Sreeram Ramachandran95684ba2014-07-23 13:27:31 -070069const uint32_t RULE_PRIORITY_BYPASSABLE_VPN = 20000;
Sreeram Ramachandran48e19b02014-07-22 22:23:20 -070070const uint32_t RULE_PRIORITY_VPN_FALLTHROUGH = 21000;
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -070071const uint32_t RULE_PRIORITY_DEFAULT_NETWORK = 22000;
Lukas06100a2d4322018-09-01 12:16:45 +020072#ifdef NEEDS_NETD_DIRECT_CONNECT_RULE
73const uint32_t RULE_PRIORITY_DIRECTLY_CONNECTED = 23000;
74#endif
Lorenzo Colittidb74dba2014-07-29 18:26:21 +090075const uint32_t RULE_PRIORITY_UNREACHABLE = 32000;
Sreeram Ramachandran5c181bf2014-04-07 14:10:04 -070076
Sreeram Ramachandran87475a12014-07-15 16:20:28 -070077const uint32_t ROUTE_TABLE_LOCAL_NETWORK = 97;
Sreeram Ramachandran4acd34a2014-07-07 22:11:37 -070078const uint32_t ROUTE_TABLE_LEGACY_NETWORK = 98;
79const uint32_t ROUTE_TABLE_LEGACY_SYSTEM = 99;
80
Sreeram Ramachandran87475a12014-07-15 16:20:28 -070081const char* const ROUTE_TABLE_NAME_LOCAL_NETWORK = "local_network";
Sreeram Ramachandran4acd34a2014-07-07 22:11:37 -070082const char* const ROUTE_TABLE_NAME_LEGACY_NETWORK = "legacy_network";
83const char* const ROUTE_TABLE_NAME_LEGACY_SYSTEM = "legacy_system";
84
Sreeram Ramachandranbb40d512014-07-11 11:45:14 -070085const char* const ROUTE_TABLE_NAME_LOCAL = "local";
86const char* const ROUTE_TABLE_NAME_MAIN = "main";
87
Lorenzo Colittib5d19e92017-09-25 18:39:33 +090088// None of our regular routes specify priority, which causes them to have the default priority.
89// For default throw routes, we use a fixed priority of 100000.
Lorenzo Colitti5e03a892017-09-08 11:31:59 +090090uint32_t PRIO_THROW = 100000;
91
Lorenzo Colittid78843e2017-03-27 05:52:31 +090092const char* const RouteController::LOCAL_MANGLE_INPUT = "routectrl_mangle_INPUT";
93
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -070094const uint8_t AF_FAMILIES[] = {AF_INET, AF_INET6};
95
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -070096const uid_t UID_ROOT = 0;
Lorenzo Colitti3093f562017-09-25 14:17:38 +090097const uint32_t FWMARK_NONE = 0;
98const uint32_t MASK_NONE = 0;
Lorenzo Colitti5ad4e982015-02-26 17:34:32 +090099const char* const IIF_LOOPBACK = "lo";
Yi Kongbdfd57e2018-07-25 13:26:10 -0700100const char* const IIF_NONE = nullptr;
101const char* const OIF_NONE = nullptr;
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -0700102const bool ACTION_ADD = true;
103const bool ACTION_DEL = false;
104const bool MODIFY_NON_UID_BASED_RULES = true;
105
Sreeram Ramachandran4acd34a2014-07-07 22:11:37 -0700106const char* const RT_TABLES_PATH = "/data/misc/net/rt_tables";
Sreeram Ramachandranc7d804c2014-07-09 07:39:30 -0700107const 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 -0700108
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700109// Avoids "non-constant-expression cannot be narrowed from type 'unsigned int' to 'unsigned short'"
110// warnings when using RTA_LENGTH(x) inside static initializers (even when x is already uint16_t).
Bernie Innocenti762dcf42019-06-14 19:52:49 +0900111static constexpr uint16_t U16_RTA_LENGTH(uint16_t x) {
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700112 return RTA_LENGTH(x);
113}
114
115// These are practically const, but can't be declared so, because they are used to initialize
116// non-const pointers ("void* iov_base") in iovec arrays.
Lorenzo Colitti2b078672016-12-16 18:45:03 +0900117rtattr FRATTR_PRIORITY = { U16_RTA_LENGTH(sizeof(uint32_t)), FRA_PRIORITY };
118rtattr FRATTR_TABLE = { U16_RTA_LENGTH(sizeof(uint32_t)), FRA_TABLE };
119rtattr FRATTR_FWMARK = { U16_RTA_LENGTH(sizeof(uint32_t)), FRA_FWMARK };
120rtattr FRATTR_FWMASK = { U16_RTA_LENGTH(sizeof(uint32_t)), FRA_FWMASK };
Lorenzo Colitti2b078672016-12-16 18:45:03 +0900121rtattr FRATTR_UID_RANGE = { U16_RTA_LENGTH(sizeof(fib_rule_uid_range)), FRA_UID_RANGE };
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700122
Lorenzo Colitti2b078672016-12-16 18:45:03 +0900123rtattr RTATTR_TABLE = { U16_RTA_LENGTH(sizeof(uint32_t)), RTA_TABLE };
124rtattr RTATTR_OIF = { U16_RTA_LENGTH(sizeof(uint32_t)), RTA_OIF };
Lorenzo Colitti5e03a892017-09-08 11:31:59 +0900125rtattr RTATTR_PRIO = { U16_RTA_LENGTH(sizeof(uint32_t)), RTA_PRIORITY };
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700126
Tyler Wearfa94a272019-12-05 15:01:48 -0800127// One or more nested attributes in the RTA_METRICS attribute.
128rtattr RTATTRX_MTU = { U16_RTA_LENGTH(sizeof(uint32_t)), RTAX_MTU};
Lorenzo Colitti57d54682020-01-24 09:18:13 +0900129constexpr size_t RTATTRX_MTU_SIZE = RTA_SPACE(sizeof(uint32_t));
Tyler Wearfa94a272019-12-05 15:01:48 -0800130
131// The RTA_METRICS attribute itself.
Lorenzo Colitti57d54682020-01-24 09:18:13 +0900132constexpr size_t RTATTR_METRICS_SIZE = RTATTRX_MTU_SIZE;
Tyler Wearfa94a272019-12-05 15:01:48 -0800133rtattr RTATTR_METRICS = { U16_RTA_LENGTH(RTATTR_METRICS_SIZE), RTA_METRICS };
134
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700135uint8_t PADDING_BUFFER[RTA_ALIGNTO] = {0, 0, 0, 0};
136
137// END CONSTANTS ----------------------------------------------------------------------------------
138
Bernie Innocenti762dcf42019-06-14 19:52:49 +0900139static const char* actionName(uint16_t action) {
Lorenzo Colitti0b073fb2017-02-10 07:49:12 +0900140 static const char *ops[4] = {"adding", "deleting", "getting", "???"};
141 return ops[action % 4];
142}
143
Bernie Innocenti762dcf42019-06-14 19:52:49 +0900144static const char* familyName(uint8_t family) {
Lorenzo Colitti0b073fb2017-02-10 07:49:12 +0900145 switch (family) {
146 case AF_INET: return "IPv4";
147 case AF_INET6: return "IPv6";
148 default: return "???";
149 }
150}
151
Lorenzo Colitti107075a2017-10-30 19:24:46 +0900152// Caller must hold sInterfaceToTableLock.
153uint32_t RouteController::getRouteTableForInterfaceLocked(const char* interface) {
mtk137999f2913e2019-02-25 19:39:36 +0800154 // If we already know the routing table for this interface name, use it.
155 // This ensures we can remove rules and routes for an interface that has been removed,
156 // or has been removed and re-added with a different interface index.
157 //
158 // The caller is responsible for ensuring that an interface is never added to a network
159 // until it has been removed from any network it was previously in. This ensures that
160 // if the same interface disconnects and then reconnects with a different interface ID
161 // when the reconnect happens the interface will not be in the map, and the code will
162 // determine the new routing table from the interface ID, below.
Lorenzo Colitti02cb80a2017-10-30 19:21:06 +0900163 auto iter = sInterfaceToTable.find(interface);
mtk137999f2913e2019-02-25 19:39:36 +0800164 if (iter != sInterfaceToTable.end()) {
165 return iter->second;
166 }
167
168 uint32_t index = if_nametoindex(interface);
169 if (index == 0) {
Treehugger Robot484d02e2020-04-29 14:55:21 +0000170 ALOGE("cannot find interface %s: %s", interface, strerror(errno));
Sreeram Ramachandran4acd34a2014-07-07 22:11:37 -0700171 return RT_TABLE_UNSPEC;
172 }
mtk137999f2913e2019-02-25 19:39:36 +0800173 index += RouteController::ROUTE_TABLE_OFFSET_FROM_INDEX;
174 sInterfaceToTable[interface] = index;
175 return index;
Sreeram Ramachandran4acd34a2014-07-07 22:11:37 -0700176}
177
Rubin Xu6c00b612018-04-27 14:27:59 +0100178uint32_t RouteController::getIfIndex(const char* interface) {
Bernie Innocentiabf8a342018-08-10 15:17:16 +0900179 std::lock_guard lock(sInterfaceToTableLock);
Rubin Xu6c00b612018-04-27 14:27:59 +0100180
181 auto iter = sInterfaceToTable.find(interface);
182 if (iter == sInterfaceToTable.end()) {
183 ALOGE("getIfIndex: cannot find interface %s", interface);
184 return 0;
185 }
186
Treehugger Robot484d02e2020-04-29 14:55:21 +0000187 // For interfaces that are not in the local network, the routing table is always the interface
188 // index plus ROUTE_TABLE_OFFSET_FROM_INDEX. But for interfaces in the local network, there's no
189 // way to know the interface index from this table. Return 0 here so callers of this method do
190 // not get confused.
191 // TODO: stop calling this method from any caller that only wants interfaces in client mode.
192 int ifindex = iter->second;
193 if (ifindex == ROUTE_TABLE_LOCAL_NETWORK) {
194 return 0;
195 }
196
197 return ifindex - ROUTE_TABLE_OFFSET_FROM_INDEX;
Rubin Xu6c00b612018-04-27 14:27:59 +0100198}
199
Lorenzo Colitti107075a2017-10-30 19:24:46 +0900200uint32_t RouteController::getRouteTableForInterface(const char* interface) {
Bernie Innocentiabf8a342018-08-10 15:17:16 +0900201 std::lock_guard lock(sInterfaceToTableLock);
Lorenzo Colitti107075a2017-10-30 19:24:46 +0900202 return getRouteTableForInterfaceLocked(interface);
203}
204
Sreeram Ramachandran4acd34a2014-07-07 22:11:37 -0700205void addTableName(uint32_t table, const std::string& name, std::string* contents) {
206 char tableString[UINT32_STRLEN];
207 snprintf(tableString, sizeof(tableString), "%u", table);
208 *contents += tableString;
209 *contents += " ";
210 *contents += name;
211 *contents += "\n";
212}
213
214// 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 +0900215void RouteController::updateTableNamesFile() {
Sreeram Ramachandran4acd34a2014-07-07 22:11:37 -0700216 std::string contents;
Sreeram Ramachandranbb40d512014-07-11 11:45:14 -0700217
218 addTableName(RT_TABLE_LOCAL, ROUTE_TABLE_NAME_LOCAL, &contents);
219 addTableName(RT_TABLE_MAIN, ROUTE_TABLE_NAME_MAIN, &contents);
220
Sreeram Ramachandran87475a12014-07-15 16:20:28 -0700221 addTableName(ROUTE_TABLE_LOCAL_NETWORK, ROUTE_TABLE_NAME_LOCAL_NETWORK, &contents);
Sreeram Ramachandran4acd34a2014-07-07 22:11:37 -0700222 addTableName(ROUTE_TABLE_LEGACY_NETWORK, ROUTE_TABLE_NAME_LEGACY_NETWORK, &contents);
223 addTableName(ROUTE_TABLE_LEGACY_SYSTEM, ROUTE_TABLE_NAME_LEGACY_SYSTEM, &contents);
Sreeram Ramachandranbb40d512014-07-11 11:45:14 -0700224
Bernie Innocentiabf8a342018-08-10 15:17:16 +0900225 std::lock_guard lock(sInterfaceToTableLock);
Lorenzo Colitti02cb80a2017-10-30 19:21:06 +0900226 for (const auto& entry : sInterfaceToTable) {
Sreeram Ramachandran4acd34a2014-07-07 22:11:37 -0700227 addTableName(entry.second, entry.first, &contents);
228 }
229
Dan Albert5407e142015-03-16 10:05:59 -0700230 if (!WriteStringToFile(contents, RT_TABLES_PATH, RT_TABLES_MODE, AID_SYSTEM, AID_WIFI)) {
Elliott Hughesbd378322015-02-04 13:25:14 -0800231 ALOGE("failed to write to %s (%s)", RT_TABLES_PATH, strerror(errno));
Sreeram Ramachandran4acd34a2014-07-07 22:11:37 -0700232 return;
233 }
Sreeram Ramachandran5c181bf2014-04-07 14:10:04 -0700234}
235
Sreeram Ramachandran87475a12014-07-15 16:20:28 -0700236// Returns 0 on success or negative errno on failure.
237int padInterfaceName(const char* input, char* name, size_t* length, uint16_t* padding) {
238 if (!input) {
239 *length = 0;
240 *padding = 0;
241 return 0;
242 }
243 *length = strlcpy(name, input, IFNAMSIZ) + 1;
244 if (*length > IFNAMSIZ) {
245 ALOGE("interface name too long (%zu > %u)", *length, IFNAMSIZ);
246 return -ENAMETOOLONG;
247 }
248 *padding = RTA_SPACE(*length) - RTA_LENGTH(*length);
249 return 0;
250}
251
Sreeram Ramachandran8fe9c8e2014-04-16 12:08:05 -0700252// Adds or removes a routing rule for IPv4 and IPv6.
253//
Lorenzo Colitti6b6f25f2015-03-03 17:22:57 +0900254// + If |table| is non-zero, the rule points at the specified routing table. Otherwise, the table is
Robin Lee4ef94642016-04-01 11:50:49 +0100255// unspecified. An unspecified table is not allowed when creating an FR_ACT_TO_TBL rule.
Sreeram Ramachandran8fe9c8e2014-04-16 12:08:05 -0700256// + If |mask| is non-zero, the rule matches the specified fwmark and mask. Otherwise, |fwmark| is
257// ignored.
Sreeram Ramachandran87475a12014-07-15 16:20:28 -0700258// + If |iif| is non-NULL, the rule matches the specified incoming interface.
259// + If |oif| is non-NULL, the rule matches the specified outgoing interface.
260// + If |uidStart| and |uidEnd| are not INVALID_UID, the rule matches packets from UIDs in that
261// range (inclusive). Otherwise, the rule matches packets from all UIDs.
Lorenzo Colitti96f261e2014-06-23 15:09:54 +0900262//
263// Returns 0 on success or negative errno on failure.
Bernie Innocenti762dcf42019-06-14 19:52:49 +0900264[[nodiscard]] static int modifyIpRule(uint16_t action, uint32_t priority, uint8_t ruleType,
265 uint32_t table, uint32_t fwmark, uint32_t mask,
266 const char* iif, const char* oif, uid_t uidStart,
267 uid_t uidEnd) {
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700268 // Ensure that if you set a bit in the fwmark, it's not being ignored by the mask.
269 if (fwmark & ~mask) {
270 ALOGE("mask 0x%x does not select all the bits set in fwmark 0x%x", mask, fwmark);
271 return -ERANGE;
272 }
273
Sreeram Ramachandran87475a12014-07-15 16:20:28 -0700274 // Interface names must include exactly one terminating NULL and be properly padded, or older
Lorenzo Colitti4753afd2014-06-20 23:03:29 +0900275 // kernels will refuse to delete rules.
Sreeram Ramachandran87475a12014-07-15 16:20:28 -0700276 char iifName[IFNAMSIZ], oifName[IFNAMSIZ];
277 size_t iifLength, oifLength;
278 uint16_t iifPadding, oifPadding;
279 if (int ret = padInterfaceName(iif, iifName, &iifLength, &iifPadding)) {
280 return ret;
281 }
282 if (int ret = padInterfaceName(oif, oifName, &oifLength, &oifPadding)) {
283 return ret;
Lorenzo Colitti4753afd2014-06-20 23:03:29 +0900284 }
285
Lorenzo Colitti59656512014-06-25 03:20:29 +0900286 // Either both start and end UID must be specified, or neither.
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700287 if ((uidStart == INVALID_UID) != (uidEnd == INVALID_UID)) {
Sreeram Ramachandrancf891382014-07-01 15:49:20 -0700288 ALOGE("incompatible start and end UIDs (%u vs %u)", uidStart, uidEnd);
Lorenzo Colitti59656512014-06-25 03:20:29 +0900289 return -EUSERS;
290 }
Robin Lee4ef94642016-04-01 11:50:49 +0100291
Lorenzo Colitti72723682014-06-26 13:51:10 +0900292 bool isUidRule = (uidStart != INVALID_UID);
Lorenzo Colitti59656512014-06-25 03:20:29 +0900293
Lorenzo Colitti4753afd2014-06-20 23:03:29 +0900294 // Assemble a rule request and put it in an array of iovec structures.
295 fib_rule_hdr rule = {
Robin Lee4ef94642016-04-01 11:50:49 +0100296 .action = ruleType,
Lorenzo Colitti6b6f25f2015-03-03 17:22:57 +0900297 // Note that here we're implicitly setting rule.table to 0. When we want to specify a
298 // non-zero table, we do this via the FRATTR_TABLE attribute.
Lorenzo Colitti4753afd2014-06-20 23:03:29 +0900299 };
300
Lorenzo Colitti6b6f25f2015-03-03 17:22:57 +0900301 // Don't ever create a rule that looks up table 0, because table 0 is the local table.
302 // It's OK to specify a table ID of 0 when deleting a rule, because that doesn't actually select
303 // table 0, it's a wildcard that matches anything.
304 if (table == RT_TABLE_UNSPEC && rule.action == FR_ACT_TO_TBL && action != RTM_DELRULE) {
305 ALOGE("RT_TABLE_UNSPEC only allowed when deleting rules");
306 return -ENOTUNIQ;
307 }
308
Sreeram Ramachandran87475a12014-07-15 16:20:28 -0700309 rtattr fraIifName = { U16_RTA_LENGTH(iifLength), FRA_IIFNAME };
310 rtattr fraOifName = { U16_RTA_LENGTH(oifLength), FRA_OIFNAME };
Lorenzo Colitti2b078672016-12-16 18:45:03 +0900311 struct fib_rule_uid_range uidRange = { uidStart, uidEnd };
Lorenzo Colitti4753afd2014-06-20 23:03:29 +0900312
313 iovec iov[] = {
Yi Kongbdfd57e2018-07-25 13:26:10 -0700314 { nullptr, 0 },
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700315 { &rule, sizeof(rule) },
316 { &FRATTR_PRIORITY, sizeof(FRATTR_PRIORITY) },
317 { &priority, sizeof(priority) },
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -0700318 { &FRATTR_TABLE, table != RT_TABLE_UNSPEC ? sizeof(FRATTR_TABLE) : 0 },
319 { &table, table != RT_TABLE_UNSPEC ? sizeof(table) : 0 },
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700320 { &FRATTR_FWMARK, mask ? sizeof(FRATTR_FWMARK) : 0 },
321 { &fwmark, mask ? sizeof(fwmark) : 0 },
322 { &FRATTR_FWMASK, mask ? sizeof(FRATTR_FWMASK) : 0 },
323 { &mask, mask ? sizeof(mask) : 0 },
Lorenzo Colitti2b078672016-12-16 18:45:03 +0900324 { &FRATTR_UID_RANGE, isUidRule ? sizeof(FRATTR_UID_RANGE) : 0 },
325 { &uidRange, isUidRule ? sizeof(uidRange) : 0 },
Sreeram Ramachandran87475a12014-07-15 16:20:28 -0700326 { &fraIifName, iif != IIF_NONE ? sizeof(fraIifName) : 0 },
327 { iifName, iifLength },
328 { PADDING_BUFFER, iifPadding },
329 { &fraOifName, oif != OIF_NONE ? sizeof(fraOifName) : 0 },
330 { oifName, oifLength },
331 { PADDING_BUFFER, oifPadding },
Lorenzo Colitti4753afd2014-06-20 23:03:29 +0900332 };
333
Lorenzo Colitti5c437992017-11-28 01:26:02 +0900334 uint16_t flags = (action == RTM_NEWRULE) ? NETLINK_RULE_CREATE_FLAGS : NETLINK_REQUEST_FLAGS;
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700335 for (size_t i = 0; i < ARRAY_SIZE(AF_FAMILIES); ++i) {
336 rule.family = AF_FAMILIES[i];
Lorenzo Colittif3e299a2017-02-14 17:24:28 +0900337 if (int ret = sendNetlinkRequest(action, flags, iov, ARRAY_SIZE(iov), nullptr)) {
Lorenzo Colitti220ca732017-02-14 17:57:55 +0900338 if (!(action == RTM_DELRULE && ret == -ENOENT && priority == RULE_PRIORITY_TETHERING)) {
339 // Don't log when deleting a tethering rule that's not there. This matches the
340 // behaviour of clearTetheringRules, which ignores ENOENT in this case.
341 ALOGE("Error %s %s rule: %s", actionName(action), familyName(rule.family),
342 strerror(-ret));
343 }
Lorenzo Colitti96f261e2014-06-23 15:09:54 +0900344 return ret;
Sreeram Ramachandran5c181bf2014-04-07 14:10:04 -0700345 }
346 }
347
Lorenzo Colitti96f261e2014-06-23 15:09:54 +0900348 return 0;
Sreeram Ramachandran5c181bf2014-04-07 14:10:04 -0700349}
350
Bernie Innocenti762dcf42019-06-14 19:52:49 +0900351[[nodiscard]] static int modifyIpRule(uint16_t action, uint32_t priority, uint32_t table,
352 uint32_t fwmark, uint32_t mask, const char* iif,
353 const char* oif, uid_t uidStart, uid_t uidEnd) {
Robin Lee4ef94642016-04-01 11:50:49 +0100354 return modifyIpRule(action, priority, FR_ACT_TO_TBL, table, fwmark, mask, iif, oif, uidStart,
355 uidEnd);
356}
357
Bernie Innocenti762dcf42019-06-14 19:52:49 +0900358[[nodiscard]] static int modifyIpRule(uint16_t action, uint32_t priority, uint32_t table,
359 uint32_t fwmark, uint32_t mask) {
Sreeram Ramachandran87475a12014-07-15 16:20:28 -0700360 return modifyIpRule(action, priority, table, fwmark, mask, IIF_NONE, OIF_NONE, INVALID_UID,
361 INVALID_UID);
362}
363
Lorenzo Colittiba25df92014-06-18 00:22:17 +0900364// Adds or deletes an IPv4 or IPv6 route.
365// Returns 0 on success or negative errno on failure.
Tyler Wearfa94a272019-12-05 15:01:48 -0800366int modifyIpRoute(uint16_t action, uint16_t flags, uint32_t table, const char* interface,
367 const char* destination, const char* nexthop, uint32_t mtu) {
Lorenzo Colittiba25df92014-06-18 00:22:17 +0900368 // At least the destination must be non-null.
369 if (!destination) {
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700370 ALOGE("null destination");
Lorenzo Colittiba25df92014-06-18 00:22:17 +0900371 return -EFAULT;
372 }
Sreeram Ramachandran7619e1b2014-04-15 14:23:08 -0700373
Lorenzo Colittiba25df92014-06-18 00:22:17 +0900374 // Parse the prefix.
375 uint8_t rawAddress[sizeof(in6_addr)];
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700376 uint8_t family;
377 uint8_t prefixLength;
Lorenzo Colittiba25df92014-06-18 00:22:17 +0900378 int rawLength = parsePrefix(destination, &family, rawAddress, sizeof(rawAddress),
379 &prefixLength);
380 if (rawLength < 0) {
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700381 ALOGE("parsePrefix failed for destination %s (%s)", destination, strerror(-rawLength));
Lorenzo Colittiba25df92014-06-18 00:22:17 +0900382 return rawLength;
383 }
Sreeram Ramachandran7619e1b2014-04-15 14:23:08 -0700384
Lorenzo Colittiba25df92014-06-18 00:22:17 +0900385 if (static_cast<size_t>(rawLength) > sizeof(rawAddress)) {
Sreeram Ramachandran1201e842014-07-01 15:06:05 -0700386 ALOGE("impossible! address too long (%d vs %zu)", rawLength, sizeof(rawAddress));
Lorenzo Colittiba25df92014-06-18 00:22:17 +0900387 return -ENOBUFS; // Cannot happen; parsePrefix only supports IPv4 and IPv6.
388 }
389
Sreeram Ramachandrande5d5df2014-07-26 18:43:25 -0700390 uint8_t type = RTN_UNICAST;
Lorenzo Colittiba25df92014-06-18 00:22:17 +0900391 uint32_t ifindex;
Lorenzo Colittiba25df92014-06-18 00:22:17 +0900392 uint8_t rawNexthop[sizeof(in6_addr)];
Sreeram Ramachandrande5d5df2014-07-26 18:43:25 -0700393
394 if (nexthop && !strcmp(nexthop, "unreachable")) {
395 type = RTN_UNREACHABLE;
396 // 'interface' is likely non-NULL, as the caller (modifyRoute()) likely used it to lookup
397 // the table number. But it's an error to specify an interface ("dev ...") or a nexthop for
398 // unreachable routes, so nuke them. (IPv6 allows them to be specified; IPv4 doesn't.)
399 interface = OIF_NONE;
Yi Kongbdfd57e2018-07-25 13:26:10 -0700400 nexthop = nullptr;
Lorenzo Colitti4c95a122014-09-18 16:01:50 +0900401 } else if (nexthop && !strcmp(nexthop, "throw")) {
402 type = RTN_THROW;
403 interface = OIF_NONE;
Yi Kongbdfd57e2018-07-25 13:26:10 -0700404 nexthop = nullptr;
Sreeram Ramachandrande5d5df2014-07-26 18:43:25 -0700405 } else {
406 // If an interface was specified, find the ifindex.
407 if (interface != OIF_NONE) {
408 ifindex = if_nametoindex(interface);
409 if (!ifindex) {
410 ALOGE("cannot find interface %s", interface);
411 return -ENODEV;
412 }
413 }
414
415 // If a nexthop was specified, parse it as the same family as the prefix.
416 if (nexthop && inet_pton(family, nexthop, rawNexthop) <= 0) {
417 ALOGE("inet_pton failed for nexthop %s", nexthop);
418 return -EINVAL;
419 }
Lorenzo Colittiba25df92014-06-18 00:22:17 +0900420 }
421
Lorenzo Colitti5e03a892017-09-08 11:31:59 +0900422 bool isDefaultThrowRoute = (type == RTN_THROW && prefixLength == 0);
423
Lorenzo Colitti4753afd2014-06-20 23:03:29 +0900424 // Assemble a rtmsg and put it in an array of iovec structures.
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700425 rtmsg route = {
Nick Desaulniers6b357502019-10-11 09:26:44 -0700426 .rtm_family = family,
427 .rtm_dst_len = prefixLength,
428 .rtm_protocol = RTPROT_STATIC,
429 .rtm_scope = static_cast<uint8_t>(nexthop ? RT_SCOPE_UNIVERSE : RT_SCOPE_LINK),
430 .rtm_type = type,
Lorenzo Colittiba25df92014-06-18 00:22:17 +0900431 };
Lorenzo Colitti4753afd2014-06-20 23:03:29 +0900432
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700433 rtattr rtaDst = { U16_RTA_LENGTH(rawLength), RTA_DST };
434 rtattr rtaGateway = { U16_RTA_LENGTH(rawLength), RTA_GATEWAY };
Lorenzo Colittiba25df92014-06-18 00:22:17 +0900435
436 iovec iov[] = {
Tyler Wearfa94a272019-12-05 15:01:48 -0800437 { nullptr, 0 },
438 { &route, sizeof(route) },
439 { &RTATTR_TABLE, sizeof(RTATTR_TABLE) },
440 { &table, sizeof(table) },
441 { &rtaDst, sizeof(rtaDst) },
442 { rawAddress, static_cast<size_t>(rawLength) },
443 { &RTATTR_OIF, interface != OIF_NONE ? sizeof(RTATTR_OIF) : 0 },
444 { &ifindex, interface != OIF_NONE ? sizeof(ifindex) : 0 },
445 { &rtaGateway, nexthop ? sizeof(rtaGateway) : 0 },
446 { rawNexthop, nexthop ? static_cast<size_t>(rawLength) : 0 },
447 { &RTATTR_METRICS, mtu != 0 ? sizeof(RTATTR_METRICS) : 0 },
448 { &RTATTRX_MTU, mtu != 0 ? sizeof(RTATTRX_MTU) : 0 },
449 { &mtu, mtu != 0 ? sizeof(mtu) : 0 },
450 { &RTATTR_PRIO, isDefaultThrowRoute ? sizeof(RTATTR_PRIO) : 0 },
451 { &PRIO_THROW, isDefaultThrowRoute ? sizeof(PRIO_THROW) : 0 },
Lorenzo Colittiba25df92014-06-18 00:22:17 +0900452 };
Lorenzo Colittiba25df92014-06-18 00:22:17 +0900453
Jimmy Chence9e5782019-03-08 16:12:55 +0800454 // Allow creating multiple link-local routes in the same table, so we can make IPv6
455 // work on all interfaces in the local_network table.
456 if (family == AF_INET6 && IN6_IS_ADDR_LINKLOCAL(reinterpret_cast<in6_addr*>(rawAddress))) {
457 flags &= ~NLM_F_EXCL;
458 }
459
Lorenzo Colittif3e299a2017-02-14 17:24:28 +0900460 int ret = sendNetlinkRequest(action, flags, iov, ARRAY_SIZE(iov), nullptr);
Lorenzo Colitti0b073fb2017-02-10 07:49:12 +0900461 if (ret) {
462 ALOGE("Error %s route %s -> %s %s to table %u: %s",
463 actionName(action), destination, nexthop, interface, table, strerror(-ret));
464 }
465 return ret;
Sreeram Ramachandran7619e1b2014-04-15 14:23:08 -0700466}
467
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -0700468// An iptables rule to mark incoming packets on a network with the netId of the network.
469//
470// This is so that the kernel can:
471// + Use the right fwmark for (and thus correctly route) replies (e.g.: TCP RST, ICMP errors, ping
472// replies, SYN-ACKs, etc).
473// + Mark sockets that accept connections from this interface so that the connection stays on the
474// same interface.
Bernie Innocenti762dcf42019-06-14 19:52:49 +0900475int modifyIncomingPacketMark(unsigned netId, const char* interface, Permission permission,
476 bool add) {
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -0700477 Fwmark fwmark;
478
479 fwmark.netId = netId;
480 fwmark.explicitlySelected = true;
481 fwmark.protectedFromVpn = true;
482 fwmark.permission = permission;
483
Benedict Wongb9baf262017-12-03 15:43:08 -0800484 const uint32_t mask = ~Fwmark::getUidBillingMask();
485
486 std::string cmd = StringPrintf(
487 "%s %s -i %s -j MARK --set-mark 0x%x/0x%x", add ? "-A" : "-D",
488 RouteController::LOCAL_MANGLE_INPUT, interface, fwmark.intValue, mask);
Lorenzo Colittic1306ea2017-03-27 05:52:31 +0900489 if (RouteController::iptablesRestoreCommandFunction(V4V6, "mangle", cmd, nullptr) != 0) {
Sreeram Ramachandranb1425cc2014-06-23 18:54:27 -0700490 ALOGE("failed to change iptables rule that sets incoming packet mark");
491 return -EREMOTEIO;
492 }
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -0700493
Sreeram Ramachandranb1425cc2014-06-23 18:54:27 -0700494 return 0;
495}
496
Sreeram Ramachandran111bec22014-07-22 18:51:06 -0700497// A rule to route responses to the local network forwarded via the VPN.
498//
499// When a VPN is in effect, packets from the local network to upstream networks are forwarded into
500// the VPN's tunnel interface. When the VPN forwards the responses, they emerge out of the tunnel.
Bernie Innocenti762dcf42019-06-14 19:52:49 +0900501[[nodiscard]] static int modifyVpnOutputToLocalRule(const char* vpnInterface, bool add) {
Sreeram Ramachandran111bec22014-07-22 18:51:06 -0700502 return modifyIpRule(add ? RTM_NEWRULE : RTM_DELRULE, RULE_PRIORITY_VPN_OUTPUT_TO_LOCAL,
503 ROUTE_TABLE_LOCAL_NETWORK, MARK_UNSET, MARK_UNSET, vpnInterface, OIF_NONE,
504 INVALID_UID, INVALID_UID);
505}
506
Sreeram Ramachandranfa9f4dc2014-07-22 18:16:44 -0700507// A rule to route all traffic from a given set of UIDs to go over the VPN.
508//
509// Notice that this rule doesn't use the netId. I.e., no matter what netId the user's socket may
510// have, if they are subject to this VPN, their traffic has to go through it. Allows the traffic to
511// bypass the VPN if the protectedFromVpn bit is set.
Bernie Innocenti762dcf42019-06-14 19:52:49 +0900512[[nodiscard]] static int modifyVpnUidRangeRule(uint32_t table, uid_t uidStart, uid_t uidEnd,
513 bool secure, bool add) {
Sreeram Ramachandranfa9f4dc2014-07-22 18:16:44 -0700514 Fwmark fwmark;
515 Fwmark mask;
516
517 fwmark.protectedFromVpn = false;
518 mask.protectedFromVpn = true;
519
Sreeram Ramachandran95684ba2014-07-23 13:27:31 -0700520 uint32_t priority;
521
522 if (secure) {
523 priority = RULE_PRIORITY_SECURE_VPN;
524 } else {
525 priority = RULE_PRIORITY_BYPASSABLE_VPN;
526
527 fwmark.explicitlySelected = false;
528 mask.explicitlySelected = true;
529 }
530
531 return modifyIpRule(add ? RTM_NEWRULE : RTM_DELRULE, priority, table, fwmark.intValue,
Lorenzo Colitti5ad4e982015-02-26 17:34:32 +0900532 mask.intValue, IIF_LOOPBACK, OIF_NONE, uidStart, uidEnd);
Sreeram Ramachandranfa9f4dc2014-07-22 18:16:44 -0700533}
534
535// A rule to allow system apps to send traffic over this VPN even if they are not part of the target
536// set of UIDs.
537//
538// This is needed for DnsProxyListener to correctly resolve a request for a user who is in the
539// target set, but where the DnsProxyListener itself is not.
Bernie Innocenti762dcf42019-06-14 19:52:49 +0900540[[nodiscard]] static int modifyVpnSystemPermissionRule(unsigned netId, uint32_t table, bool secure,
541 bool add) {
Sreeram Ramachandranfa9f4dc2014-07-22 18:16:44 -0700542 Fwmark fwmark;
543 Fwmark mask;
544
545 fwmark.netId = netId;
546 mask.netId = FWMARK_NET_ID_MASK;
547
548 fwmark.permission = PERMISSION_SYSTEM;
549 mask.permission = PERMISSION_SYSTEM;
550
Sreeram Ramachandran95684ba2014-07-23 13:27:31 -0700551 uint32_t priority = secure ? RULE_PRIORITY_SECURE_VPN : RULE_PRIORITY_BYPASSABLE_VPN;
552
553 return modifyIpRule(add ? RTM_NEWRULE : RTM_DELRULE, priority, table, fwmark.intValue,
554 mask.intValue);
Sreeram Ramachandranfa9f4dc2014-07-22 18:16:44 -0700555}
556
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -0700557// A rule to route traffic based on an explicitly chosen network.
558//
559// Supports apps that use the multinetwork APIs to restrict their traffic to a network.
560//
561// Even though we check permissions at the time we set a netId into the fwmark of a socket, we need
562// to check it again in the rules here, because a network's permissions may have been updated via
563// modifyNetworkPermission().
Bernie Innocenti762dcf42019-06-14 19:52:49 +0900564[[nodiscard]] static int modifyExplicitNetworkRule(unsigned netId, uint32_t table,
565 Permission permission, uid_t uidStart,
566 uid_t uidEnd, bool add) {
Sreeram Ramachandraneb27b7e2014-07-01 14:30:30 -0700567 Fwmark fwmark;
568 Fwmark mask;
569
570 fwmark.netId = netId;
571 mask.netId = FWMARK_NET_ID_MASK;
572
Sreeram Ramachandran122f5812014-05-11 20:29:49 -0700573 fwmark.explicitlySelected = true;
574 mask.explicitlySelected = true;
Sreeram Ramachandran5c181bf2014-04-07 14:10:04 -0700575
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -0700576 fwmark.permission = permission;
577 mask.permission = permission;
Sreeram Ramachandraneb27b7e2014-07-01 14:30:30 -0700578
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -0700579 return modifyIpRule(add ? RTM_NEWRULE : RTM_DELRULE, RULE_PRIORITY_EXPLICIT_NETWORK, table,
Lorenzo Colitti758627c2018-03-15 01:49:20 +0900580 fwmark.intValue, mask.intValue, IIF_LOOPBACK, OIF_NONE, uidStart, uidEnd);
Sreeram Ramachandran5c181bf2014-04-07 14:10:04 -0700581}
582
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -0700583// A rule to route traffic based on a chosen outgoing interface.
584//
585// Supports apps that use SO_BINDTODEVICE or IP_PKTINFO options and the kernel that already knows
586// the outgoing interface (typically for link-local communications).
Bernie Innocenti762dcf42019-06-14 19:52:49 +0900587[[nodiscard]] static int modifyOutputInterfaceRules(const char* interface, uint32_t table,
588 Permission permission, uid_t uidStart,
589 uid_t uidEnd, bool add) {
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -0700590 Fwmark fwmark;
591 Fwmark mask;
Sreeram Ramachandran4043f012014-06-23 12:41:37 -0700592
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -0700593 fwmark.permission = permission;
594 mask.permission = permission;
Sreeram Ramachandranb1425cc2014-06-23 18:54:27 -0700595
Lorenzo Colitti57947f02015-02-27 16:45:55 +0900596 // If this rule does not specify a UID range, then also add a corresponding high-priority rule
Lorenzo Colitti758627c2018-03-15 01:49:20 +0900597 // for root. This covers kernel-originated packets, TEEd packets and any local daemons that open
598 // sockets as root.
Lorenzo Colitti57947f02015-02-27 16:45:55 +0900599 if (uidStart == INVALID_UID && uidEnd == INVALID_UID) {
600 if (int ret = modifyIpRule(add ? RTM_NEWRULE : RTM_DELRULE, RULE_PRIORITY_VPN_OVERRIDE_OIF,
Lorenzo Colitti758627c2018-03-15 01:49:20 +0900601 table, FWMARK_NONE, MASK_NONE, IIF_LOOPBACK, interface,
Lorenzo Colitti57947f02015-02-27 16:45:55 +0900602 UID_ROOT, UID_ROOT)) {
603 return ret;
604 }
605 }
606
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -0700607 return modifyIpRule(add ? RTM_NEWRULE : RTM_DELRULE, RULE_PRIORITY_OUTPUT_INTERFACE, table,
Lorenzo Colitti758627c2018-03-15 01:49:20 +0900608 fwmark.intValue, mask.intValue, IIF_LOOPBACK, interface, uidStart, uidEnd);
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -0700609}
610
611// A rule to route traffic based on the chosen network.
612//
613// This is for sockets that have not explicitly requested a particular network, but have been
614// bound to one when they called connect(). This ensures that sockets connected on a particular
615// network stay on that network even if the default network changes.
Bernie Innocenti762dcf42019-06-14 19:52:49 +0900616[[nodiscard]] static int modifyImplicitNetworkRule(unsigned netId, uint32_t table, bool add) {
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -0700617 Fwmark fwmark;
618 Fwmark mask;
619
620 fwmark.netId = netId;
621 mask.netId = FWMARK_NET_ID_MASK;
622
623 fwmark.explicitlySelected = false;
624 mask.explicitlySelected = true;
625
Lorenzo Colittibe0c7c32017-09-06 16:07:02 +0900626 fwmark.permission = PERMISSION_NONE;
627 mask.permission = PERMISSION_NONE;
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -0700628
629 return modifyIpRule(add ? RTM_NEWRULE : RTM_DELRULE, RULE_PRIORITY_IMPLICIT_NETWORK, table,
Lorenzo Colitti758627c2018-03-15 01:49:20 +0900630 fwmark.intValue, mask.intValue, IIF_LOOPBACK, OIF_NONE, INVALID_UID,
631 INVALID_UID);
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -0700632}
633
Sreeram Ramachandran48e19b02014-07-22 22:23:20 -0700634// A rule to enable split tunnel VPNs.
635//
636// 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 +0800637// go over the default network, provided it has the permissions required by the default network.
Bernie Innocenti762dcf42019-06-14 19:52:49 +0900638int RouteController::modifyVpnFallthroughRule(uint16_t action, unsigned vpnNetId,
639 const char* physicalInterface,
640 Permission permission) {
Sreeram Ramachandran48e19b02014-07-22 22:23:20 -0700641 uint32_t table = getRouteTableForInterface(physicalInterface);
642 if (table == RT_TABLE_UNSPEC) {
643 return -ESRCH;
644 }
645
646 Fwmark fwmark;
647 Fwmark mask;
648
649 fwmark.netId = vpnNetId;
650 mask.netId = FWMARK_NET_ID_MASK;
651
Sreeram Ramachandran48e19b02014-07-22 22:23:20 -0700652 fwmark.permission = permission;
653 mask.permission = permission;
654
655 return modifyIpRule(action, RULE_PRIORITY_VPN_FALLTHROUGH, table, fwmark.intValue,
656 mask.intValue);
657}
658
Sreeram Ramachandranfa9f4dc2014-07-22 18:16:44 -0700659// Add rules to allow legacy routes added through the requestRouteToHost() API.
Bernie Innocenti762dcf42019-06-14 19:52:49 +0900660[[nodiscard]] static int addLegacyRouteRules() {
Sreeram Ramachandran4043f012014-06-23 12:41:37 -0700661 Fwmark fwmark;
662 Fwmark mask;
663
Sreeram Ramachandranfa9f4dc2014-07-22 18:16:44 -0700664 fwmark.explicitlySelected = false;
665 mask.explicitlySelected = true;
Sreeram Ramachandranb1425cc2014-06-23 18:54:27 -0700666
Sreeram Ramachandranfa9f4dc2014-07-22 18:16:44 -0700667 // Rules to allow legacy routes to override the default network.
668 if (int ret = modifyIpRule(RTM_NEWRULE, RULE_PRIORITY_LEGACY_SYSTEM, ROUTE_TABLE_LEGACY_SYSTEM,
669 fwmark.intValue, mask.intValue)) {
670 return ret;
671 }
672 if (int ret = modifyIpRule(RTM_NEWRULE, RULE_PRIORITY_LEGACY_NETWORK,
673 ROUTE_TABLE_LEGACY_NETWORK, fwmark.intValue, mask.intValue)) {
674 return ret;
675 }
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -0700676
677 fwmark.permission = PERMISSION_SYSTEM;
678 mask.permission = PERMISSION_SYSTEM;
679
Sreeram Ramachandranfa9f4dc2014-07-22 18:16:44 -0700680 // A rule to allow legacy routes from system apps to override VPNs.
681 return modifyIpRule(RTM_NEWRULE, RULE_PRIORITY_VPN_OVERRIDE_SYSTEM, ROUTE_TABLE_LEGACY_SYSTEM,
Sreeram Ramachandran87475a12014-07-15 16:20:28 -0700682 fwmark.intValue, mask.intValue);
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -0700683}
684
Sreeram Ramachandranfa9f4dc2014-07-22 18:16:44 -0700685// Add rules to lookup the local network when specified explicitly or otherwise.
Bernie Innocenti762dcf42019-06-14 19:52:49 +0900686[[nodiscard]] static int addLocalNetworkRules(unsigned localNetId) {
Sreeram Ramachandranfa9f4dc2014-07-22 18:16:44 -0700687 if (int ret = modifyExplicitNetworkRule(localNetId, ROUTE_TABLE_LOCAL_NETWORK, PERMISSION_NONE,
688 INVALID_UID, INVALID_UID, ACTION_ADD)) {
689 return ret;
Sreeram Ramachandran6a773532014-07-11 09:10:20 -0700690 }
691
Sreeram Ramachandranfa9f4dc2014-07-22 18:16:44 -0700692 Fwmark fwmark;
693 Fwmark mask;
694
695 fwmark.explicitlySelected = false;
696 mask.explicitlySelected = true;
697
698 return modifyIpRule(RTM_NEWRULE, RULE_PRIORITY_LOCAL_NETWORK, ROUTE_TABLE_LOCAL_NETWORK,
699 fwmark.intValue, mask.intValue);
700}
701
Lorenzo Colitti02cb80a2017-10-30 19:21:06 +0900702/* static */
703int RouteController::configureDummyNetwork() {
Lorenzo Colitti36679362015-02-25 10:26:19 +0900704 const char *interface = DummyNetwork::INTERFACE_NAME;
705 uint32_t table = getRouteTableForInterface(interface);
706 if (table == RT_TABLE_UNSPEC) {
Hungming Chen7f725432020-02-07 17:47:23 +0800707 // getRouteTableForInterface has already logged an error.
Lorenzo Colitti36679362015-02-25 10:26:19 +0900708 return -ESRCH;
709 }
710
711 ifc_init();
712 int ret = ifc_up(interface);
713 ifc_close();
714 if (ret) {
715 ALOGE("Can't bring up %s: %s", interface, strerror(errno));
716 return -errno;
717 }
718
Lorenzo Colitti57947f02015-02-27 16:45:55 +0900719 if ((ret = modifyOutputInterfaceRules(interface, table, PERMISSION_NONE,
720 INVALID_UID, INVALID_UID, ACTION_ADD))) {
721 ALOGE("Can't create oif rules for %s: %s", interface, strerror(-ret));
Lorenzo Colitti36679362015-02-25 10:26:19 +0900722 return ret;
723 }
724
Tyler Wearfa94a272019-12-05 15:01:48 -0800725 if ((ret = modifyIpRoute(RTM_NEWROUTE, NETLINK_ROUTE_CREATE_FLAGS, table, interface,
726 "0.0.0.0/0", nullptr, 0 /* mtu */))) {
Lorenzo Colitti36679362015-02-25 10:26:19 +0900727 return ret;
728 }
729
Tyler Wearfa94a272019-12-05 15:01:48 -0800730 if ((ret = modifyIpRoute(RTM_NEWROUTE, NETLINK_ROUTE_CREATE_FLAGS, table, interface, "::/0",
731 nullptr, 0 /* mtu */))) {
Lorenzo Colitti36679362015-02-25 10:26:19 +0900732 return ret;
733 }
734
735 return 0;
736}
737
Lukas06100a2d4322018-09-01 12:16:45 +0200738#ifdef NEEDS_NETD_DIRECT_CONNECT_RULE
739// Add a new rule to look up the 'main' table, with the same selectors as the "default network"
740// rule, but with a lower priority. We will never create routes in the main table; it should only be
741// used for directly-connected routes implicitly created by the kernel when adding IP addresses.
742// This is necessary, for example, when adding a route through a directly-connected gateway: in
743// order to add the route, there must already be a directly-connected route that covers the gateway.
744[[nodiscard]] int addDirectlyConnectedRule() {
745 Fwmark fwmark;
746 Fwmark mask;
747
748 fwmark.netId = NETID_UNSET;
749 mask.netId = FWMARK_NET_ID_MASK;
750
751 return modifyIpRule(RTM_NEWRULE, RULE_PRIORITY_DIRECTLY_CONNECTED, RT_TABLE_MAIN,
752 fwmark.intValue, mask.intValue, IIF_NONE, OIF_NONE, UID_ROOT, UID_ROOT);
753}
754#endif
755
Lorenzo Colittidb74dba2014-07-29 18:26:21 +0900756// Add an explicit unreachable rule close to the end of the prioriy list to make it clear that
757// relying on the kernel-default "from all lookup main" rule at priority 32766 is not intended
758// behaviour. We do flush the kernel-default rules at startup, but having an explicit unreachable
759// rule will hopefully make things even clearer.
Bernie Innocenti762dcf42019-06-14 19:52:49 +0900760[[nodiscard]] static int addUnreachableRule() {
Robin Leec125fe42016-05-02 08:53:34 +0100761 return modifyIpRule(RTM_NEWRULE, RULE_PRIORITY_UNREACHABLE, FR_ACT_UNREACHABLE, RT_TABLE_UNSPEC,
762 MARK_UNSET, MARK_UNSET, IIF_NONE, OIF_NONE, INVALID_UID, INVALID_UID);
Sreeram Ramachandran87475a12014-07-15 16:20:28 -0700763}
764
Bernie Innocenti762dcf42019-06-14 19:52:49 +0900765[[nodiscard]] static int modifyLocalNetwork(unsigned netId, const char* interface, bool add) {
Sreeram Ramachandran6a773532014-07-11 09:10:20 -0700766 if (int ret = modifyIncomingPacketMark(netId, interface, PERMISSION_NONE, add)) {
767 return ret;
768 }
Lorenzo Colitti57947f02015-02-27 16:45:55 +0900769 return modifyOutputInterfaceRules(interface, ROUTE_TABLE_LOCAL_NETWORK, PERMISSION_NONE,
770 INVALID_UID, INVALID_UID, add);
Sreeram Ramachandran6a773532014-07-11 09:10:20 -0700771}
772
Lorenzo Colitti02cb80a2017-10-30 19:21:06 +0900773/* static */
Bernie Innocenti762dcf42019-06-14 19:52:49 +0900774int RouteController::modifyPhysicalNetwork(unsigned netId, const char* interface,
775 Permission permission, bool add) {
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -0700776 uint32_t table = getRouteTableForInterface(interface);
777 if (table == RT_TABLE_UNSPEC) {
778 return -ESRCH;
779 }
780
781 if (int ret = modifyIncomingPacketMark(netId, interface, permission, add)) {
782 return ret;
783 }
784 if (int ret = modifyExplicitNetworkRule(netId, table, permission, INVALID_UID, INVALID_UID,
785 add)) {
786 return ret;
787 }
Lorenzo Colitti57947f02015-02-27 16:45:55 +0900788 if (int ret = modifyOutputInterfaceRules(interface, table, permission, INVALID_UID, INVALID_UID,
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -0700789 add)) {
790 return ret;
791 }
Lorenzo Colittibe0c7c32017-09-06 16:07:02 +0900792
793 // Only set implicit rules for networks that don't require permissions.
794 //
795 // This is so that if the default network ceases to be the default network and then switches
796 // from requiring no permissions to requiring permissions, we ensure that apps only use the
797 // network if they explicitly select it. This is consistent with destroySocketsLackingPermission
798 // - it closes all sockets on the network except sockets that are explicitly selected.
799 //
800 // The lack of this rule only affects the special case above, because:
801 // - The only cases where we implicitly bind a socket to a network are the default network and
802 // the bypassable VPN that applies to the app, if any.
803 // - This rule doesn't affect VPNs because they don't support permissions at all.
804 // - The default network doesn't require permissions. While we support doing this, the framework
805 // never does it (partly because we'd end up in the situation where we tell apps that there is
806 // a default network, but they can't use it).
807 // - If the network is still the default network, the presence or absence of this rule does not
808 // matter.
809 //
810 // Therefore, for the lack of this rule to affect a socket, the socket has to have been
811 // implicitly bound to a network because at the time of connect() it was the default, and that
812 // network must no longer be the default, and must now require permissions.
813 if (permission == PERMISSION_NONE) {
814 return modifyImplicitNetworkRule(netId, table, add);
815 }
816 return 0;
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -0700817}
818
Bernie Innocenti762dcf42019-06-14 19:52:49 +0900819[[nodiscard]] static int modifyRejectNonSecureNetworkRule(const UidRanges& uidRanges, bool add) {
Robin Leeb8087362016-03-30 18:43:08 +0100820 Fwmark fwmark;
821 Fwmark mask;
822 fwmark.protectedFromVpn = false;
823 mask.protectedFromVpn = true;
824
Luke Huang94658ac2018-10-18 19:35:12 +0900825 for (const UidRangeParcel& range : uidRanges.getRanges()) {
826 if (int ret = modifyIpRule(add ? RTM_NEWRULE : RTM_DELRULE, RULE_PRIORITY_PROHIBIT_NON_VPN,
827 FR_ACT_PROHIBIT, RT_TABLE_UNSPEC, fwmark.intValue, mask.intValue,
828 IIF_LOOPBACK, OIF_NONE, range.start, range.stop)) {
Robin Leeb8087362016-03-30 18:43:08 +0100829 return ret;
830 }
831 }
832
833 return 0;
834}
835
Bernie Innocenti762dcf42019-06-14 19:52:49 +0900836int RouteController::modifyVirtualNetwork(unsigned netId, const char* interface,
837 const UidRanges& uidRanges, bool secure, bool add,
838 bool modifyNonUidBasedRules) {
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -0700839 uint32_t table = getRouteTableForInterface(interface);
840 if (table == RT_TABLE_UNSPEC) {
841 return -ESRCH;
842 }
843
Luke Huang94658ac2018-10-18 19:35:12 +0900844 for (const UidRangeParcel& range : uidRanges.getRanges()) {
845 if (int ret = modifyVpnUidRangeRule(table, range.start, range.stop, secure, add)) {
Sreeram Ramachandranfa9f4dc2014-07-22 18:16:44 -0700846 return ret;
847 }
Luke Huang94658ac2018-10-18 19:35:12 +0900848 if (int ret = modifyExplicitNetworkRule(netId, table, PERMISSION_NONE, range.start,
849 range.stop, add)) {
Sreeram Ramachandranb1425cc2014-06-23 18:54:27 -0700850 return ret;
851 }
Luke Huang94658ac2018-10-18 19:35:12 +0900852 if (int ret = modifyOutputInterfaceRules(interface, table, PERMISSION_NONE, range.start,
853 range.stop, add)) {
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -0700854 return ret;
855 }
Sreeram Ramachandran4043f012014-06-23 12:41:37 -0700856 }
857
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -0700858 if (modifyNonUidBasedRules) {
859 if (int ret = modifyIncomingPacketMark(netId, interface, PERMISSION_NONE, add)) {
Sreeram Ramachandraneb27b7e2014-07-01 14:30:30 -0700860 return ret;
861 }
Sreeram Ramachandran111bec22014-07-22 18:51:06 -0700862 if (int ret = modifyVpnOutputToLocalRule(interface, add)) {
863 return ret;
864 }
Sreeram Ramachandran95684ba2014-07-23 13:27:31 -0700865 if (int ret = modifyVpnSystemPermissionRule(netId, table, secure, add)) {
Sreeram Ramachandranb1425cc2014-06-23 18:54:27 -0700866 return ret;
867 }
Sreeram Ramachandranfa9f4dc2014-07-22 18:16:44 -0700868 return modifyExplicitNetworkRule(netId, table, PERMISSION_NONE, UID_ROOT, UID_ROOT, add);
Sreeram Ramachandranb1425cc2014-06-23 18:54:27 -0700869 }
870
871 return 0;
Sreeram Ramachandran4043f012014-06-23 12:41:37 -0700872}
873
Bernie Innocenti762dcf42019-06-14 19:52:49 +0900874int RouteController::modifyDefaultNetwork(uint16_t action, const char* interface,
875 Permission permission) {
Sreeram Ramachandran9c0d3132014-04-10 20:35:04 -0700876 uint32_t table = getRouteTableForInterface(interface);
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -0700877 if (table == RT_TABLE_UNSPEC) {
Lorenzo Colitti96f261e2014-06-23 15:09:54 +0900878 return -ESRCH;
Sreeram Ramachandran9c0d3132014-04-10 20:35:04 -0700879 }
880
Sreeram Ramachandran122f5812014-05-11 20:29:49 -0700881 Fwmark fwmark;
Sreeram Ramachandran122f5812014-05-11 20:29:49 -0700882 Fwmark mask;
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700883
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -0700884 fwmark.netId = NETID_UNSET;
Sreeram Ramachandran122f5812014-05-11 20:29:49 -0700885 mask.netId = FWMARK_NET_ID_MASK;
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700886
887 fwmark.permission = permission;
Sreeram Ramachandran122f5812014-05-11 20:29:49 -0700888 mask.permission = permission;
889
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -0700890 return modifyIpRule(action, RULE_PRIORITY_DEFAULT_NETWORK, table, fwmark.intValue,
Lorenzo Colitti758627c2018-03-15 01:49:20 +0900891 mask.intValue, IIF_LOOPBACK, OIF_NONE, INVALID_UID, INVALID_UID);
Sreeram Ramachandran7619e1b2014-04-15 14:23:08 -0700892}
893
Bernie Innocenti762dcf42019-06-14 19:52:49 +0900894int RouteController::modifyTetheredNetwork(uint16_t action, const char* inputInterface,
895 const char* outputInterface) {
Sreeram Ramachandranfa9f4dc2014-07-22 18:16:44 -0700896 uint32_t table = getRouteTableForInterface(outputInterface);
897 if (table == RT_TABLE_UNSPEC) {
898 return -ESRCH;
899 }
900
901 return modifyIpRule(action, RULE_PRIORITY_TETHERING, table, MARK_UNSET, MARK_UNSET,
902 inputInterface, OIF_NONE, INVALID_UID, INVALID_UID);
903}
904
Lorenzo Colitti92e8f962017-09-26 19:13:50 +0900905// Adds or removes an IPv4 or IPv6 route to the specified table.
Lorenzo Colittif7fc8ec2014-06-18 00:41:58 +0900906// Returns 0 on success or negative errno on failure.
Tyler Wearfa94a272019-12-05 15:01:48 -0800907int RouteController::modifyRoute(uint16_t action, uint16_t flags, const char* interface,
908 const char* destination, const char* nexthop, TableType tableType,
909 int mtu) {
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -0700910 uint32_t table;
Sreeram Ramachandran38b7af12014-05-22 14:21:49 -0700911 switch (tableType) {
912 case RouteController::INTERFACE: {
913 table = getRouteTableForInterface(interface);
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -0700914 if (table == RT_TABLE_UNSPEC) {
915 return -ESRCH;
916 }
Sreeram Ramachandran38b7af12014-05-22 14:21:49 -0700917 break;
918 }
Sreeram Ramachandran87475a12014-07-15 16:20:28 -0700919 case RouteController::LOCAL_NETWORK: {
920 table = ROUTE_TABLE_LOCAL_NETWORK;
921 break;
922 }
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -0700923 case RouteController::LEGACY_NETWORK: {
Sreeram Ramachandran4acd34a2014-07-07 22:11:37 -0700924 table = ROUTE_TABLE_LEGACY_NETWORK;
Sreeram Ramachandran38b7af12014-05-22 14:21:49 -0700925 break;
926 }
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -0700927 case RouteController::LEGACY_SYSTEM: {
Sreeram Ramachandran4acd34a2014-07-07 22:11:37 -0700928 table = ROUTE_TABLE_LEGACY_SYSTEM;
Sreeram Ramachandran38b7af12014-05-22 14:21:49 -0700929 break;
930 }
931 }
Sreeram Ramachandran9c0d3132014-04-10 20:35:04 -0700932
Tyler Wearfa94a272019-12-05 15:01:48 -0800933 int ret = modifyIpRoute(action, flags, table, interface, destination, nexthop, mtu);
Sreeram Ramachandran03213152014-10-30 10:01:07 -0700934 // Trying to add a route that already exists shouldn't cause an error.
935 if (ret && !(action == RTM_NEWROUTE && ret == -EEXIST)) {
Lorenzo Colittif7fc8ec2014-06-18 00:41:58 +0900936 return ret;
Sreeram Ramachandranc9213372014-04-16 12:32:18 -0700937 }
938
Lorenzo Colittif7fc8ec2014-06-18 00:41:58 +0900939 return 0;
Sreeram Ramachandran9c0d3132014-04-10 20:35:04 -0700940}
941
Hungming Chen7f725432020-02-07 17:47:23 +0800942void maybeModifyQdiscClsact(const char* interface, bool add) {
943 if (!bpf::isBpfSupported()) return;
944
945 // The clsact attaching of v4- tun interface is triggered by ClatdController::maybeStartBpf
946 // because the clat is started before the v4- interface is added to the network and the
947 // clat startup needs to add {in, e}gress filters.
948 // TODO: remove this workaround once v4- tun interface clsact attaching is moved out from
949 // ClatdController::maybeStartBpf.
950 if (StartsWith(interface, "v4-") && add) return;
951
952 // The interface may have already gone away in the delete case.
953 uint32_t ifindex = if_nametoindex(interface);
954 if (!ifindex) {
955 ALOGE("cannot find interface %s", interface);
956 return;
957 }
958
959 if (add) {
960 if (int ret = tcQdiscAddDevClsact(ifindex)) {
961 ALOGE("tcQdiscAddDevClsact(%d[%s]) failure: %s", ifindex, interface, strerror(-ret));
962 return;
963 }
964 } else {
965 if (int ret = tcQdiscDelDevClsact(ifindex)) {
966 ALOGE("tcQdiscDelDevClsact(%d[%s]) failure: %s", ifindex, interface, strerror(-ret));
967 return;
968 }
969 }
970
971 return;
972}
973
Bernie Innocenti762dcf42019-06-14 19:52:49 +0900974[[nodiscard]] static int clearTetheringRules(const char* inputInterface) {
Lorenzo Colitti6b6f25f2015-03-03 17:22:57 +0900975 int ret = 0;
976 while (ret == 0) {
977 ret = modifyIpRule(RTM_DELRULE, RULE_PRIORITY_TETHERING, 0, MARK_UNSET, MARK_UNSET,
978 inputInterface, OIF_NONE, INVALID_UID, INVALID_UID);
979 }
980
981 if (ret == -ENOENT) {
982 return 0;
983 } else {
984 return ret;
985 }
986}
987
Lorenzo Colittif3e299a2017-02-14 17:24:28 +0900988uint32_t getRulePriority(const nlmsghdr *nlh) {
989 return getRtmU32Attribute(nlh, FRA_PRIORITY);
990}
991
992uint32_t getRouteTable(const nlmsghdr *nlh) {
993 return getRtmU32Attribute(nlh, RTA_TABLE);
994}
995
Bernie Innocenti762dcf42019-06-14 19:52:49 +0900996[[nodiscard]] static int flushRules() {
Lorenzo Colittif3e299a2017-02-14 17:24:28 +0900997 NetlinkDumpFilter shouldDelete = [] (nlmsghdr *nlh) {
998 // Don't touch rules at priority 0 because by default they are used for local input.
999 return getRulePriority(nlh) != 0;
1000 };
1001 return rtNetlinkFlush(RTM_GETRULE, RTM_DELRULE, "rules", shouldDelete);
1002}
1003
Bernie Innocenti762dcf42019-06-14 19:52:49 +09001004int RouteController::flushRoutes(uint32_t table) {
Lorenzo Colittif3e299a2017-02-14 17:24:28 +09001005 NetlinkDumpFilter shouldDelete = [table] (nlmsghdr *nlh) {
1006 return getRouteTable(nlh) == table;
1007 };
1008
1009 return rtNetlinkFlush(RTM_GETROUTE, RTM_DELROUTE, "routes", shouldDelete);
1010}
1011
1012// Returns 0 on success or negative errno on failure.
Bernie Innocenti762dcf42019-06-14 19:52:49 +09001013int RouteController::flushRoutes(const char* interface) {
Bernie Innocentiabf8a342018-08-10 15:17:16 +09001014 std::lock_guard lock(sInterfaceToTableLock);
Lorenzo Colitti107075a2017-10-30 19:24:46 +09001015
1016 uint32_t table = getRouteTableForInterfaceLocked(interface);
Lorenzo Colittif3e299a2017-02-14 17:24:28 +09001017 if (table == RT_TABLE_UNSPEC) {
1018 return -ESRCH;
1019 }
1020
1021 int ret = flushRoutes(table);
1022
1023 // If we failed to flush routes, the caller may elect to keep this interface around, so keep
1024 // track of its name.
1025 if (ret == 0) {
Lorenzo Colitti02cb80a2017-10-30 19:21:06 +09001026 sInterfaceToTable.erase(interface);
Lorenzo Colittif3e299a2017-02-14 17:24:28 +09001027 }
1028
1029 return ret;
1030}
1031
Sreeram Ramachandran87475a12014-07-15 16:20:28 -07001032int RouteController::Init(unsigned localNetId) {
Sreeram Ramachandranb717e742014-07-19 00:22:15 -07001033 if (int ret = flushRules()) {
1034 return ret;
1035 }
Sreeram Ramachandran87475a12014-07-15 16:20:28 -07001036 if (int ret = addLegacyRouteRules()) {
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -07001037 return ret;
1038 }
Sreeram Ramachandranfa9f4dc2014-07-22 18:16:44 -07001039 if (int ret = addLocalNetworkRules(localNetId)) {
1040 return ret;
1041 }
Lukas06100a2d4322018-09-01 12:16:45 +02001042#ifdef NEEDS_NETD_DIRECT_CONNECT_RULE
1043 if (int ret = addDirectlyConnectedRule()) {
1044 return ret;
1045 }
1046#endif
Sreeram Ramachandranb717e742014-07-19 00:22:15 -07001047 if (int ret = addUnreachableRule()) {
1048 return ret;
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -07001049 }
Lorenzo Colitti36679362015-02-25 10:26:19 +09001050 // Don't complain if we can't add the dummy network, since not all devices support it.
1051 configureDummyNetwork();
1052
Sreeram Ramachandran4acd34a2014-07-07 22:11:37 -07001053 updateTableNamesFile();
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -07001054 return 0;
Sreeram Ramachandran8fe9c8e2014-04-16 12:08:05 -07001055}
1056
Sreeram Ramachandran6a773532014-07-11 09:10:20 -07001057int RouteController::addInterfaceToLocalNetwork(unsigned netId, const char* interface) {
Treehugger Robot484d02e2020-04-29 14:55:21 +00001058 if (int ret = modifyLocalNetwork(netId, interface, ACTION_ADD)) {
1059 return ret;
1060 }
1061 std::lock_guard lock(sInterfaceToTableLock);
1062 sInterfaceToTable[interface] = ROUTE_TABLE_LOCAL_NETWORK;
1063 return 0;
Sreeram Ramachandran6a773532014-07-11 09:10:20 -07001064}
1065
1066int RouteController::removeInterfaceFromLocalNetwork(unsigned netId, const char* interface) {
Treehugger Robot484d02e2020-04-29 14:55:21 +00001067 if (int ret = modifyLocalNetwork(netId, interface, ACTION_DEL)) {
1068 return ret;
1069 }
1070 std::lock_guard lock(sInterfaceToTableLock);
1071 sInterfaceToTable.erase(interface);
1072 return 0;
Sreeram Ramachandran6a773532014-07-11 09:10:20 -07001073}
1074
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -07001075int RouteController::addInterfaceToPhysicalNetwork(unsigned netId, const char* interface,
1076 Permission permission) {
Sreeram Ramachandran4acd34a2014-07-07 22:11:37 -07001077 if (int ret = modifyPhysicalNetwork(netId, interface, permission, ACTION_ADD)) {
1078 return ret;
1079 }
Hungming Chen7f725432020-02-07 17:47:23 +08001080 maybeModifyQdiscClsact(interface, ACTION_ADD);
Sreeram Ramachandran4acd34a2014-07-07 22:11:37 -07001081 updateTableNamesFile();
1082 return 0;
Sreeram Ramachandran5c181bf2014-04-07 14:10:04 -07001083}
1084
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -07001085int RouteController::removeInterfaceFromPhysicalNetwork(unsigned netId, const char* interface,
1086 Permission permission) {
1087 if (int ret = modifyPhysicalNetwork(netId, interface, permission, ACTION_DEL)) {
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -07001088 return ret;
1089 }
Sreeram Ramachandran4acd34a2014-07-07 22:11:37 -07001090 if (int ret = flushRoutes(interface)) {
1091 return ret;
1092 }
Lorenzo Colitti6b6f25f2015-03-03 17:22:57 +09001093 if (int ret = clearTetheringRules(interface)) {
1094 return ret;
1095 }
Hungming Chen7f725432020-02-07 17:47:23 +08001096 maybeModifyQdiscClsact(interface, ACTION_DEL);
Sreeram Ramachandran4acd34a2014-07-07 22:11:37 -07001097 updateTableNamesFile();
1098 return 0;
Sreeram Ramachandran379bd332014-04-10 19:58:06 -07001099}
1100
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -07001101int RouteController::addInterfaceToVirtualNetwork(unsigned netId, const char* interface,
Sreeram Ramachandran95684ba2014-07-23 13:27:31 -07001102 bool secure, const UidRanges& uidRanges) {
1103 if (int ret = modifyVirtualNetwork(netId, interface, uidRanges, secure, ACTION_ADD,
Sreeram Ramachandran4acd34a2014-07-07 22:11:37 -07001104 MODIFY_NON_UID_BASED_RULES)) {
1105 return ret;
1106 }
1107 updateTableNamesFile();
1108 return 0;
Sreeram Ramachandran4043f012014-06-23 12:41:37 -07001109}
1110
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -07001111int RouteController::removeInterfaceFromVirtualNetwork(unsigned netId, const char* interface,
Sreeram Ramachandran95684ba2014-07-23 13:27:31 -07001112 bool secure, const UidRanges& uidRanges) {
1113 if (int ret = modifyVirtualNetwork(netId, interface, uidRanges, secure, ACTION_DEL,
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -07001114 MODIFY_NON_UID_BASED_RULES)) {
Sreeram Ramachandran4043f012014-06-23 12:41:37 -07001115 return ret;
1116 }
Sreeram Ramachandran4acd34a2014-07-07 22:11:37 -07001117 if (int ret = flushRoutes(interface)) {
1118 return ret;
1119 }
1120 updateTableNamesFile();
1121 return 0;
Sreeram Ramachandran4043f012014-06-23 12:41:37 -07001122}
1123
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -07001124int RouteController::modifyPhysicalNetworkPermission(unsigned netId, const char* interface,
1125 Permission oldPermission,
1126 Permission newPermission) {
Sreeram Ramachandran379bd332014-04-10 19:58:06 -07001127 // Add the new rules before deleting the old ones, to avoid race conditions.
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -07001128 if (int ret = modifyPhysicalNetwork(netId, interface, newPermission, ACTION_ADD)) {
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -07001129 return ret;
1130 }
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -07001131 return modifyPhysicalNetwork(netId, interface, oldPermission, ACTION_DEL);
Sreeram Ramachandranb1425cc2014-06-23 18:54:27 -07001132}
1133
Robin Leeb8087362016-03-30 18:43:08 +01001134int RouteController::addUsersToRejectNonSecureNetworkRule(const UidRanges& uidRanges) {
1135 return modifyRejectNonSecureNetworkRule(uidRanges, true);
1136}
1137
1138int RouteController::removeUsersFromRejectNonSecureNetworkRule(const UidRanges& uidRanges) {
1139 return modifyRejectNonSecureNetworkRule(uidRanges, false);
1140}
1141
Sreeram Ramachandran95684ba2014-07-23 13:27:31 -07001142int RouteController::addUsersToVirtualNetwork(unsigned netId, const char* interface, bool secure,
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -07001143 const UidRanges& uidRanges) {
Sreeram Ramachandran95684ba2014-07-23 13:27:31 -07001144 return modifyVirtualNetwork(netId, interface, uidRanges, secure, ACTION_ADD,
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -07001145 !MODIFY_NON_UID_BASED_RULES);
Sreeram Ramachandranb1425cc2014-06-23 18:54:27 -07001146}
1147
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -07001148int RouteController::removeUsersFromVirtualNetwork(unsigned netId, const char* interface,
Sreeram Ramachandran95684ba2014-07-23 13:27:31 -07001149 bool secure, const UidRanges& uidRanges) {
1150 return modifyVirtualNetwork(netId, interface, uidRanges, secure, ACTION_DEL,
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -07001151 !MODIFY_NON_UID_BASED_RULES);
Sreeram Ramachandran9c0d3132014-04-10 20:35:04 -07001152}
1153
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -07001154int RouteController::addInterfaceToDefaultNetwork(const char* interface, Permission permission) {
1155 return modifyDefaultNetwork(RTM_NEWRULE, interface, permission);
Sreeram Ramachandran9c0d3132014-04-10 20:35:04 -07001156}
1157
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -07001158int RouteController::removeInterfaceFromDefaultNetwork(const char* interface,
1159 Permission permission) {
1160 return modifyDefaultNetwork(RTM_DELRULE, interface, permission);
Sreeram Ramachandran5c181bf2014-04-07 14:10:04 -07001161}
Sreeram Ramachandran7619e1b2014-04-15 14:23:08 -07001162
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -07001163int RouteController::addRoute(const char* interface, const char* destination, const char* nexthop,
Tyler Wearfa94a272019-12-05 15:01:48 -08001164 TableType tableType, int mtu) {
1165 return modifyRoute(RTM_NEWROUTE, NETLINK_ROUTE_CREATE_FLAGS, interface, destination, nexthop,
1166 tableType, mtu);
Sreeram Ramachandran7619e1b2014-04-15 14:23:08 -07001167}
1168
Lorenzo Colittif7fc8ec2014-06-18 00:41:58 +09001169int RouteController::removeRoute(const char* interface, const char* destination,
Sreeram Ramachandraneb27b7e2014-07-01 14:30:30 -07001170 const char* nexthop, TableType tableType) {
Tyler Wearfa94a272019-12-05 15:01:48 -08001171 return modifyRoute(RTM_DELROUTE, NETLINK_REQUEST_FLAGS, interface, destination, nexthop,
1172 tableType, 0);
1173}
1174
1175int RouteController::updateRoute(const char* interface, const char* destination,
1176 const char* nexthop, TableType tableType, int mtu) {
1177 return modifyRoute(RTM_NEWROUTE, NETLINK_ROUTE_REPLACE_FLAGS, interface, destination, nexthop,
1178 tableType, mtu);
Sreeram Ramachandran7619e1b2014-04-15 14:23:08 -07001179}
Sreeram Ramachandran87475a12014-07-15 16:20:28 -07001180
1181int RouteController::enableTethering(const char* inputInterface, const char* outputInterface) {
Sreeram Ramachandranfa9f4dc2014-07-22 18:16:44 -07001182 return modifyTetheredNetwork(RTM_NEWRULE, inputInterface, outputInterface);
Sreeram Ramachandran87475a12014-07-15 16:20:28 -07001183}
1184
1185int RouteController::disableTethering(const char* inputInterface, const char* outputInterface) {
Sreeram Ramachandranfa9f4dc2014-07-22 18:16:44 -07001186 return modifyTetheredNetwork(RTM_DELRULE, inputInterface, outputInterface);
Sreeram Ramachandran87475a12014-07-15 16:20:28 -07001187}
Sreeram Ramachandran48e19b02014-07-22 22:23:20 -07001188
1189int RouteController::addVirtualNetworkFallthrough(unsigned vpnNetId, const char* physicalInterface,
1190 Permission permission) {
1191 return modifyVpnFallthroughRule(RTM_NEWRULE, vpnNetId, physicalInterface, permission);
1192}
1193
1194int RouteController::removeVirtualNetworkFallthrough(unsigned vpnNetId,
1195 const char* physicalInterface,
1196 Permission permission) {
1197 return modifyVpnFallthroughRule(RTM_DELRULE, vpnNetId, physicalInterface, permission);
1198}
Lorenzo Colitti7035f222017-02-13 18:29:00 +09001199
Lorenzo Colitti107075a2017-10-30 19:24:46 +09001200// Protects sInterfaceToTable.
Luke Huang534980c2018-07-06 17:50:11 +08001201std::mutex RouteController::sInterfaceToTableLock;
Lorenzo Colitti02cb80a2017-10-30 19:21:06 +09001202std::map<std::string, uint32_t> RouteController::sInterfaceToTable;
1203
Bernie Innocenti762dcf42019-06-14 19:52:49 +09001204} // namespace android::net