blob: 85112bb61da6a52350f69750dcf56075664baa95 [file] [log] [blame]
Szymon Jakubczaka0efaec2014-02-14 17:09:43 -05001/*
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
Sreeram Ramachandran72604072014-05-21 13:19:43 -070017// THREAD-SAFETY
18// -------------
19// The methods in this file are called from multiple threads (from CommandListener, FwmarkServer
20// and DnsProxyListener). So, all accesses to shared state are guarded by a lock.
21//
Lorenzo Colittibbd0aff2016-12-15 22:53:24 +090022// Public functions accessible by external callers should be thread-safe and are responsible for
23// acquiring the lock. Private functions in this file should call xxxLocked() methods and access
24// internal state directly.
Szymon Jakubczaka0efaec2014-02-14 17:09:43 -050025
Erik Kline2d3a1632016-03-15 16:33:48 +090026#define LOG_TAG "Netd"
Luke Huangcfd04b22019-03-18 15:53:21 +080027
28#include "NetworkController.h"
Erik Kline2d3a1632016-03-15 16:33:48 +090029
Rubin Xu6c00b612018-04-27 14:27:59 +010030#include <android-base/strings.h>
Bernie Innocenti34de3ba2019-02-19 18:08:36 +090031#include <cutils/misc.h> // FIRST_APPLICATION_UID
Bernie Innocenti189eb502018-10-01 23:10:18 +090032#include <netd_resolv/resolv.h>
Maciej Żenczykowski4d913bb2022-12-14 04:10:14 -080033#include <net/if.h>
Luke Huangcfd04b22019-03-18 15:53:21 +080034#include "log/log.h"
Rubin Xu6c00b612018-04-27 14:27:59 +010035
Pierre Imai3a272072016-04-19 16:17:07 +090036#include "Controllers.h"
Lorenzo Colitti36679362015-02-25 10:26:19 +090037#include "DummyNetwork.h"
Sreeram Ramachandran1011b492014-07-24 19:04:32 -070038#include "Fwmark.h"
Sreeram Ramachandran6a773532014-07-11 09:10:20 -070039#include "LocalNetwork.h"
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -070040#include "PhysicalNetwork.h"
Sreeram Ramachandran5c181bf2014-04-07 14:10:04 -070041#include "RouteController.h"
Patrick Rohr70d42502021-10-12 18:24:10 +020042#include "TcUtils.h"
Ken Chen4e8ef9b2021-03-17 01:57:19 +080043#include "UnreachableNetwork.h"
Sreeram Ramachandran4043f012014-06-23 12:41:37 -070044#include "VirtualNetwork.h"
Luke Huangb257d612019-03-14 21:19:13 +080045#include "netdutils/DumpWriter.h"
waynema5851b032021-11-24 17:08:25 +080046#include "netdutils/Utils.h"
Bernie Innocenti189eb502018-10-01 23:10:18 +090047#include "netid_client.h"
Sreeram Ramachandran5c181bf2014-04-07 14:10:04 -070048
Erik Kline6d4669f2017-05-25 17:03:31 +090049#define DBG 0
50
Luke Huangb257d612019-03-14 21:19:13 +080051using android::netdutils::DumpWriter;
waynema5851b032021-11-24 17:08:25 +080052using android::netdutils::getIfaceNames;
Luke Huangb257d612019-03-14 21:19:13 +080053
Bernie Innocenti762dcf42019-06-14 19:52:49 +090054namespace android::net {
Lorenzo Colitti7035f222017-02-13 18:29:00 +090055
Sreeram Ramachandran5c181bf2014-04-07 14:10:04 -070056namespace {
57
58// Keep these in sync with ConnectivityService.java.
Sreeram Ramachandranbbdde992014-09-05 16:05:03 -070059const unsigned MIN_NET_ID = 100;
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -070060const unsigned MAX_NET_ID = 65535;
Sreeram Ramachandran5c181bf2014-04-07 14:10:04 -070061
62} // namespace
63
Sreeram Ramachandran48e19b02014-07-22 22:23:20 -070064// All calls to methods here are made while holding a write lock on mRWLock.
Lorenzo Colitti2d014e72018-01-10 22:12:29 +090065// They are mostly not called directly from this class, but from methods in PhysicalNetwork.cpp.
66// However, we're the only user of that class, so all calls to those methods come from here and are
67// made under lock.
68// For example, PhysicalNetwork::setPermission ends up calling addFallthrough and removeFallthrough,
69// but it's only called from here under lock (specifically, from createPhysicalNetworkLocked and
70// setPermissionForNetworks).
71// TODO: use std::mutex and GUARDED_BY instead of manual inspection.
Sreeram Ramachandran48e19b02014-07-22 22:23:20 -070072class NetworkController::DelegateImpl : public PhysicalNetwork::Delegate {
Bernie Innocenti762dcf42019-06-14 19:52:49 +090073 public:
Sreeram Ramachandran48e19b02014-07-22 22:23:20 -070074 explicit DelegateImpl(NetworkController* networkController);
75 virtual ~DelegateImpl();
76
Bernie Innocenti762dcf42019-06-14 19:52:49 +090077 [[nodiscard]] int modifyFallthrough(unsigned vpnNetId, const std::string& physicalInterface,
78 Permission permission, bool add);
Sreeram Ramachandran48e19b02014-07-22 22:23:20 -070079
Bernie Innocenti762dcf42019-06-14 19:52:49 +090080 private:
81 [[nodiscard]] int addFallthrough(const std::string& physicalInterface,
82 Permission permission) override;
83 [[nodiscard]] int removeFallthrough(const std::string& physicalInterface,
84 Permission permission) override;
Sreeram Ramachandran48e19b02014-07-22 22:23:20 -070085
Bernie Innocenti762dcf42019-06-14 19:52:49 +090086 [[nodiscard]] int modifyFallthrough(const std::string& physicalInterface, Permission permission,
87 bool add);
Sreeram Ramachandran48e19b02014-07-22 22:23:20 -070088
89 NetworkController* const mNetworkController;
90};
91
92NetworkController::DelegateImpl::DelegateImpl(NetworkController* networkController) :
93 mNetworkController(networkController) {
94}
95
96NetworkController::DelegateImpl::~DelegateImpl() {
97}
98
99int NetworkController::DelegateImpl::modifyFallthrough(unsigned vpnNetId,
100 const std::string& physicalInterface,
101 Permission permission, bool add) {
102 if (add) {
103 if (int ret = RouteController::addVirtualNetworkFallthrough(vpnNetId,
104 physicalInterface.c_str(),
105 permission)) {
106 ALOGE("failed to add fallthrough to %s for VPN netId %u", physicalInterface.c_str(),
107 vpnNetId);
108 return ret;
109 }
110 } else {
111 if (int ret = RouteController::removeVirtualNetworkFallthrough(vpnNetId,
112 physicalInterface.c_str(),
113 permission)) {
114 ALOGE("failed to remove fallthrough to %s for VPN netId %u", physicalInterface.c_str(),
115 vpnNetId);
116 return ret;
117 }
118 }
119 return 0;
120}
121
122int NetworkController::DelegateImpl::addFallthrough(const std::string& physicalInterface,
123 Permission permission) {
124 return modifyFallthrough(physicalInterface, permission, true);
125}
126
127int NetworkController::DelegateImpl::removeFallthrough(const std::string& physicalInterface,
128 Permission permission) {
129 return modifyFallthrough(physicalInterface, permission, false);
130}
131
132int NetworkController::DelegateImpl::modifyFallthrough(const std::string& physicalInterface,
133 Permission permission, bool add) {
134 for (const auto& entry : mNetworkController->mNetworks) {
Ken Chen7ad712f2021-01-05 01:14:20 +0800135 if (entry.second->isVirtual()) {
Sreeram Ramachandran48e19b02014-07-22 22:23:20 -0700136 if (int ret = modifyFallthrough(entry.first, physicalInterface, permission, add)) {
137 return ret;
138 }
139 }
140 }
141 return 0;
142}
143
144NetworkController::NetworkController() :
Patrick Rohrbecb94c2024-04-26 11:17:22 -0700145 mDelegateImpl(new NetworkController::DelegateImpl(this)), mDefaultNetId(NETID_UNSET),
146 mProtectableUsers({std::make_pair(AID_VPN, NETID_UNSET)}) {
Ken Chen66e860f2021-04-01 15:50:28 +0800147 gLog.info("enter NetworkController ctor");
Sreeram Ramachandran87475a12014-07-15 16:20:28 -0700148 mNetworks[LOCAL_NET_ID] = new LocalNetwork(LOCAL_NET_ID);
Lorenzo Colitti36679362015-02-25 10:26:19 +0900149 mNetworks[DUMMY_NET_ID] = new DummyNetwork(DUMMY_NET_ID);
Ken Chen4e8ef9b2021-03-17 01:57:19 +0800150 mNetworks[UNREACHABLE_NET_ID] = new UnreachableNetwork(UNREACHABLE_NET_ID);
Hungming Chen228cffa2020-02-18 17:11:18 +0800151
152 // Clear all clsact stubs on all interfaces.
153 // TODO: perhaps only remove the clsact on the interface which is added by
154 // RouteController::addInterfaceToPhysicalNetwork. Currently, the netd only
155 // attach the clsact to the interface for the physical network.
waynema5851b032021-11-24 17:08:25 +0800156 const auto& ifaces = getIfaceNames();
Maciej Żenczykowski0e5d26f2021-01-17 03:14:20 -0800157 if (isOk(ifaces)) {
158 for (const std::string& iface : ifaces.value()) {
159 if (int ifIndex = if_nametoindex(iface.c_str())) {
160 // Ignore the error because the interface might not have a clsact.
161 tcQdiscDelDevClsact(ifIndex);
Hungming Chen228cffa2020-02-18 17:11:18 +0800162 }
163 }
164 }
Ken Chen66e860f2021-04-01 15:50:28 +0800165 gLog.info("leave NetworkController ctor");
Szymon Jakubczaka0efaec2014-02-14 17:09:43 -0500166}
167
168unsigned NetworkController::getDefaultNetwork() const {
Luke Huangd1ee4622018-06-29 13:49:58 +0800169 ScopedRLock lock(mRWLock);
Szymon Jakubczaka0efaec2014-02-14 17:09:43 -0500170 return mDefaultNetId;
171}
172
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700173int NetworkController::setDefaultNetwork(unsigned netId) {
Luke Huangd1ee4622018-06-29 13:49:58 +0800174 ScopedWLock lock(mRWLock);
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700175
176 if (netId == mDefaultNetId) {
177 return 0;
Sreeram Ramachandran72604072014-05-21 13:19:43 -0700178 }
179
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700180 if (netId != NETID_UNSET) {
Sreeram Ramachandran36ed53e2014-07-01 19:01:56 -0700181 Network* network = getNetworkLocked(netId);
Lorenzo Colitti738c93e2014-07-30 17:46:08 +0900182 if (!network) {
183 ALOGE("no such netId %u", netId);
184 return -ENONET;
185 }
Ken Chen7ad712f2021-01-05 01:14:20 +0800186 if (!network->isPhysical()) {
Lorenzo Colitti738c93e2014-07-30 17:46:08 +0900187 ALOGE("cannot set default to non-physical network with netId %u", netId);
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700188 return -EINVAL;
189 }
Sreeram Ramachandran36ed53e2014-07-01 19:01:56 -0700190 if (int ret = static_cast<PhysicalNetwork*>(network)->addAsDefault()) {
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700191 return ret;
Sreeram Ramachandran9c0d3132014-04-10 20:35:04 -0700192 }
193 }
194
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700195 if (mDefaultNetId != NETID_UNSET) {
Sreeram Ramachandran36ed53e2014-07-01 19:01:56 -0700196 Network* network = getNetworkLocked(mDefaultNetId);
Ken Chen7ad712f2021-01-05 01:14:20 +0800197 if (!network || !network->isPhysical()) {
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700198 ALOGE("cannot find previously set default network with netId %u", mDefaultNetId);
199 return -ESRCH;
200 }
Sreeram Ramachandran36ed53e2014-07-01 19:01:56 -0700201 if (int ret = static_cast<PhysicalNetwork*>(network)->removeAsDefault()) {
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700202 return ret;
Sreeram Ramachandran9c0d3132014-04-10 20:35:04 -0700203 }
204 }
205
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700206 mDefaultNetId = netId;
207 return 0;
Szymon Jakubczaka0efaec2014-02-14 17:09:43 -0500208}
209
Lorenzo Colittibbd0aff2016-12-15 22:53:24 +0900210uint32_t NetworkController::getNetworkForDnsLocked(unsigned* netId, uid_t uid) const {
Sreeram Ramachandran1011b492014-07-24 19:04:32 -0700211 Fwmark fwmark;
212 fwmark.protectedFromVpn = true;
213 fwmark.permission = PERMISSION_SYSTEM;
Lorenzo Colitti95f1bcb2018-05-30 16:14:18 +0900214
Ken Chen4e8ef9b2021-03-17 01:57:19 +0800215 Network* appDefaultNetwork = getPhysicalOrUnreachableNetworkForUserLocked(uid);
Ken Chen8738e1c2020-11-24 11:38:54 +0800216 unsigned defaultNetId = appDefaultNetwork ? appDefaultNetwork->getNetId() : mDefaultNetId;
217
Lorenzo Colitti95f1bcb2018-05-30 16:14:18 +0900218 // Common case: there is no VPN that applies to the user, and the query did not specify a netId.
219 // Therefore, it is safe to set the explicit bit on this query and skip all the complex logic
220 // below. While this looks like a special case, it is actually the one that handles the vast
221 // majority of DNS queries.
222 // TODO: untangle this code.
223 if (*netId == NETID_UNSET && getVirtualNetworkForUserLocked(uid) == nullptr) {
Ken Chen8738e1c2020-11-24 11:38:54 +0800224 *netId = defaultNetId;
Lorenzo Colitti95f1bcb2018-05-30 16:14:18 +0900225 fwmark.netId = *netId;
226 fwmark.explicitlySelected = true;
227 return fwmark.intValue;
228 }
229
Lorenzo Colittia1067c82014-10-02 22:47:41 +0900230 if (checkUserNetworkAccessLocked(uid, *netId) == 0) {
Sreeram Ramachandran1011b492014-07-24 19:04:32 -0700231 // If a non-zero NetId was explicitly specified, and the user has permission for that
Luke Huangd2861982019-05-17 19:47:28 +0800232 // network, use that network's DNS servers. (possibly falling through the to the default
233 // network if the VPN doesn't provide a route to them).
Sreeram Ramachandran1011b492014-07-24 19:04:32 -0700234 fwmark.explicitlySelected = true;
Lorenzo Colittic63059c2016-06-21 23:54:12 +0900235
236 // If the network is a VPN and it doesn't have DNS servers, use the default network's DNS
237 // servers (through the default network). Otherwise, the query is guaranteed to fail.
238 // http://b/29498052
239 Network *network = getNetworkLocked(*netId);
Ken Chen7ad712f2021-01-05 01:14:20 +0800240 if (network && network->isVirtual() && !resolv_has_nameservers(*netId)) {
Ken Chen8738e1c2020-11-24 11:38:54 +0800241 *netId = defaultNetId;
Lorenzo Colittic63059c2016-06-21 23:54:12 +0900242 }
Sreeram Ramachandran1011b492014-07-24 19:04:32 -0700243 } else {
244 // If the user is subject to a VPN and the VPN provides DNS servers, use those servers
245 // (possibly falling through to the default network if the VPN doesn't provide a route to
Luke Huangd2861982019-05-17 19:47:28 +0800246 // them). Otherwise, use the default network's DNS servers.
247 // TODO: Consider if we should set the explicit bit here.
Sreeram Ramachandran1011b492014-07-24 19:04:32 -0700248 VirtualNetwork* virtualNetwork = getVirtualNetworkForUserLocked(uid);
Jooyung Han3e64aa12019-11-27 15:36:29 +0900249 if (virtualNetwork && resolv_has_nameservers(virtualNetwork->getNetId())) {
Sreeram Ramachandran1011b492014-07-24 19:04:32 -0700250 *netId = virtualNetwork->getNetId();
251 } else {
Lorenzo Colittic63059c2016-06-21 23:54:12 +0900252 // TODO: return an error instead of silently doing the DNS lookup on the wrong network.
253 // http://b/27560555
Ken Chen8738e1c2020-11-24 11:38:54 +0800254 *netId = defaultNetId;
Sreeram Ramachandran1011b492014-07-24 19:04:32 -0700255 }
256 }
257 fwmark.netId = *netId;
258 return fwmark.intValue;
259}
260
261// Returns the NetId that a given UID would use if no network is explicitly selected. Specifically,
Ken Chen55db3802021-03-30 13:47:49 +0800262// the VPN that applies to the UID if any; Otherwise, the default network for UID; Otherwise the
263// unreachable network that applies to the UID; lastly, the default network.
Sreeram Ramachandran1011b492014-07-24 19:04:32 -0700264unsigned NetworkController::getNetworkForUser(uid_t uid) const {
Luke Huangd1ee4622018-06-29 13:49:58 +0800265 ScopedRLock lock(mRWLock);
Sreeram Ramachandran1011b492014-07-24 19:04:32 -0700266 if (VirtualNetwork* virtualNetwork = getVirtualNetworkForUserLocked(uid)) {
Sreeram Ramachandrane09b20a2014-07-05 17:15:14 -0700267 return virtualNetwork->getNetId();
Szymon Jakubczaka0efaec2014-02-14 17:09:43 -0500268 }
Ken Chen4e8ef9b2021-03-17 01:57:19 +0800269 if (Network* network = getPhysicalOrUnreachableNetworkForUserLocked(uid)) {
270 return network->getNetId();
Ken Chen8738e1c2020-11-24 11:38:54 +0800271 }
Sreeram Ramachandran1011b492014-07-24 19:04:32 -0700272 return mDefaultNetId;
273}
274
275// Returns the NetId that will be set when a socket connect()s. This is the bypassable VPN that
Ken Chen8738e1c2020-11-24 11:38:54 +0800276// applies to the user if any; otherwise, the default network that applies to user if any; lastly,
277// the default network.
Sreeram Ramachandran1011b492014-07-24 19:04:32 -0700278//
279// In general, we prefer to always set the default network's NetId in connect(), so that if the VPN
280// is a split-tunnel and disappears later, the socket continues working (since the default network's
281// NetId is still valid). Secure VPNs will correctly grab the socket's traffic since they have a
282// high-priority routing rule that doesn't care what NetId the socket has.
283//
284// But bypassable VPNs have a very low priority rule, so we need to mark the socket with the
285// bypassable VPN's NetId if we expect it to get any traffic at all. If the bypassable VPN is a
286// split-tunnel, that's okay, because we have fallthrough rules that will direct the fallthrough
287// traffic to the default network. But it does mean that if the bypassable VPN goes away (and thus
288// the fallthrough rules also go away), the socket that used to fallthrough to the default network
289// will stop working.
Ken Chen8738e1c2020-11-24 11:38:54 +0800290//
291// Per-app physical default networks behave the same as bypassable VPNs: when a socket is connected
292// on one of these networks, we mark the socket with the netId of the network. This ensures that if
293// the per-app default network changes, sockets established on the previous network are still
294// routed to that network, assuming the network's UID ranges still apply to the UID. While this
295// means that fallthrough to the default network does not work, physical networks not expected
296// ever to be split tunnels.
Lorenzo Colittibbd0aff2016-12-15 22:53:24 +0900297unsigned NetworkController::getNetworkForConnectLocked(uid_t uid) const {
Sreeram Ramachandran1011b492014-07-24 19:04:32 -0700298 VirtualNetwork* virtualNetwork = getVirtualNetworkForUserLocked(uid);
299 if (virtualNetwork && !virtualNetwork->isSecure()) {
300 return virtualNetwork->getNetId();
301 }
Ken Chen4e8ef9b2021-03-17 01:57:19 +0800302 if (Network* network = getPhysicalOrUnreachableNetworkForUserLocked(uid)) {
303 return network->getNetId();
Ken Chen8738e1c2020-11-24 11:38:54 +0800304 }
Sreeram Ramachandran1011b492014-07-24 19:04:32 -0700305 return mDefaultNetId;
Szymon Jakubczaka0efaec2014-02-14 17:09:43 -0500306}
307
Lorenzo Colittibbd0aff2016-12-15 22:53:24 +0900308unsigned NetworkController::getNetworkForConnect(uid_t uid) const {
Luke Huangd1ee4622018-06-29 13:49:58 +0800309 ScopedRLock lock(mRWLock);
Lorenzo Colittibbd0aff2016-12-15 22:53:24 +0900310 return getNetworkForConnectLocked(uid);
311}
312
Erik Klinecea2d342015-06-25 18:24:46 +0900313void NetworkController::getNetworkContext(
314 unsigned netId, uid_t uid, struct android_net_context* netcontext) const {
Luke Huangd1ee4622018-06-29 13:49:58 +0800315 ScopedRLock lock(mRWLock);
Lorenzo Colittibbd0aff2016-12-15 22:53:24 +0900316
Erik Klinecea2d342015-06-25 18:24:46 +0900317 struct android_net_context nc = {
318 .app_netid = netId,
319 .app_mark = MARK_UNSET,
320 .dns_netid = netId,
321 .dns_mark = MARK_UNSET,
322 .uid = uid,
323 };
324
Erik Kline492ca5b2016-03-09 14:56:00 +0900325 // |netId| comes directly (via dnsproxyd) from the value returned by netIdForResolv() in the
326 // client process. This value is nonzero iff.:
327 //
328 // 1. The app specified a netid/nethandle to a DNS resolution method such as:
329 // - [Java] android.net.Network#getAllByName()
330 // - [C/++] android_getaddrinfofornetwork()
331 // 2. The app specified a netid/nethandle to be used as a process default via:
332 // - [Java] android.net.ConnectivityManager#bindProcessToNetwork()
333 // - [C/++] android_setprocnetwork()
334 // 3. The app called android.net.ConnectivityManager#startUsingNetworkFeature().
335 //
336 // In all these cases (with the possible exception of #3), the right thing to do is to treat
337 // such cases as explicitlySelected.
338 const bool explicitlySelected = (nc.app_netid != NETID_UNSET);
339 if (!explicitlySelected) {
Lorenzo Colittibbd0aff2016-12-15 22:53:24 +0900340 nc.app_netid = getNetworkForConnectLocked(uid);
Erik Klinecea2d342015-06-25 18:24:46 +0900341 }
Erik Kline492ca5b2016-03-09 14:56:00 +0900342
Erik Klinecea2d342015-06-25 18:24:46 +0900343 Fwmark fwmark;
344 fwmark.netId = nc.app_netid;
Erik Kline492ca5b2016-03-09 14:56:00 +0900345 fwmark.explicitlySelected = explicitlySelected;
Patrick Rohr4fafa6f2024-04-23 11:36:21 -0700346 fwmark.protectedFromVpn = explicitlySelected && canProtectLocked(uid, nc.app_netid);
Lorenzo Colittibbd0aff2016-12-15 22:53:24 +0900347 fwmark.permission = getPermissionForUserLocked(uid);
Erik Klinecea2d342015-06-25 18:24:46 +0900348 nc.app_mark = fwmark.intValue;
349
Lorenzo Colittibbd0aff2016-12-15 22:53:24 +0900350 nc.dns_mark = getNetworkForDnsLocked(&(nc.dns_netid), uid);
Erik Klinecea2d342015-06-25 18:24:46 +0900351
Erik Kline6d4669f2017-05-25 17:03:31 +0900352 if (DBG) {
353 ALOGD("app_netid:0x%x app_mark:0x%x dns_netid:0x%x dns_mark:0x%x uid:%d",
354 nc.app_netid, nc.app_mark, nc.dns_netid, nc.dns_mark, uid);
355 }
356
Erik Klinecea2d342015-06-25 18:24:46 +0900357 if (netcontext) {
358 *netcontext = nc;
359 }
360}
361
Lorenzo Colittibbd0aff2016-12-15 22:53:24 +0900362unsigned NetworkController::getNetworkForInterfaceLocked(const char* interface) const {
Sreeram Ramachandran36ed53e2014-07-01 19:01:56 -0700363 for (const auto& entry : mNetworks) {
Sreeram Ramachandran4043f012014-06-23 12:41:37 -0700364 if (entry.second->hasInterface(interface)) {
365 return entry.first;
366 }
367 }
Paul Jensen35c77e32014-04-10 14:57:54 -0400368 return NETID_UNSET;
Szymon Jakubczaka0efaec2014-02-14 17:09:43 -0500369}
370
Lorenzo Colittibbd0aff2016-12-15 22:53:24 +0900371unsigned NetworkController::getNetworkForInterface(const char* interface) const {
Luke Huangd1ee4622018-06-29 13:49:58 +0800372 ScopedRLock lock(mRWLock);
Lorenzo Colittibbd0aff2016-12-15 22:53:24 +0900373 return getNetworkForInterfaceLocked(interface);
374}
375
Ken Chenedc647f2023-08-31 17:33:15 +0800376unsigned NetworkController::getNetworkForInterfaceLocked(const int ifIndex) const {
377 char interfaceName[IFNAMSIZ] = {};
378 if (if_indextoname(ifIndex, interfaceName)) {
379 return getNetworkForInterfaceLocked(interfaceName);
380 }
381 return NETID_UNSET;
382}
383
384unsigned NetworkController::getNetworkForInterface(const int ifIndex) const {
385 ScopedRLock lock(mRWLock);
386 return getNetworkForInterfaceLocked(ifIndex);
387}
388
Sreeram Ramachandran070b2d22014-07-11 17:06:12 -0700389bool NetworkController::isVirtualNetwork(unsigned netId) const {
Luke Huangd1ee4622018-06-29 13:49:58 +0800390 ScopedRLock lock(mRWLock);
Rubin Xu6c00b612018-04-27 14:27:59 +0100391 return isVirtualNetworkLocked(netId);
392}
393
394bool NetworkController::isVirtualNetworkLocked(unsigned netId) const {
Sreeram Ramachandran070b2d22014-07-11 17:06:12 -0700395 Network* network = getNetworkLocked(netId);
Ken Chen7ad712f2021-01-05 01:14:20 +0800396 return network && network->isVirtual();
Sreeram Ramachandran070b2d22014-07-11 17:06:12 -0700397}
398
Chalard Jean04845142022-12-02 19:39:36 +0900399int NetworkController::createPhysicalNetworkLocked(unsigned netId, Permission permission,
400 bool local) {
Sreeram Ramachandranbbdde992014-09-05 16:05:03 -0700401 if (!((MIN_NET_ID <= netId && netId <= MAX_NET_ID) ||
402 (MIN_OEM_ID <= netId && netId <= MAX_OEM_ID))) {
Paul Jensenae37e8a2014-04-28 10:35:51 -0400403 ALOGE("invalid netId %u", netId);
Lorenzo Colitti96f261e2014-06-23 15:09:54 +0900404 return -EINVAL;
Sreeram Ramachandran5c181bf2014-04-07 14:10:04 -0700405 }
406
Niranjan Pendharkar7e08f852017-07-24 11:40:05 -0700407 if (isValidNetworkLocked(netId)) {
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700408 ALOGE("duplicate netId %u", netId);
409 return -EEXIST;
Sreeram Ramachandran5c181bf2014-04-07 14:10:04 -0700410 }
411
Chalard Jean04845142022-12-02 19:39:36 +0900412 PhysicalNetwork* physicalNetwork = new PhysicalNetwork(netId, mDelegateImpl, local);
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700413 if (int ret = physicalNetwork->setPermission(permission)) {
414 ALOGE("inconceivable! setPermission cannot fail on an empty network");
415 delete physicalNetwork;
Lorenzo Colitti96f261e2014-06-23 15:09:54 +0900416 return ret;
Sreeram Ramachandran5c181bf2014-04-07 14:10:04 -0700417 }
418
Sreeram Ramachandran36ed53e2014-07-01 19:01:56 -0700419 mNetworks[netId] = physicalNetwork;
Hugo Benichia9e3c5d2018-01-18 10:33:22 +0900420
421 updateTcpSocketMonitorPolling();
422
Lorenzo Colitti96f261e2014-06-23 15:09:54 +0900423 return 0;
Sreeram Ramachandran5c181bf2014-04-07 14:10:04 -0700424}
425
Chalard Jean04845142022-12-02 19:39:36 +0900426int NetworkController::createPhysicalNetwork(unsigned netId, Permission permission, bool local) {
Luke Huangd1ee4622018-06-29 13:49:58 +0800427 ScopedWLock lock(mRWLock);
Chalard Jean04845142022-12-02 19:39:36 +0900428 return createPhysicalNetworkLocked(netId, permission, local);
Niranjan Pendharkar7e08f852017-07-24 11:40:05 -0700429}
430
431int NetworkController::createPhysicalOemNetwork(Permission permission, unsigned *pNetId) {
Yi Kongbdfd57e2018-07-25 13:26:10 -0700432 if (pNetId == nullptr) {
Niranjan Pendharkar7e08f852017-07-24 11:40:05 -0700433 return -EINVAL;
434 }
435
Luke Huangd1ee4622018-06-29 13:49:58 +0800436 ScopedWLock lock(mRWLock);
Niranjan Pendharkar7e08f852017-07-24 11:40:05 -0700437 for (*pNetId = MIN_OEM_ID; *pNetId <= MAX_OEM_ID; (*pNetId)++) {
438 if (!isValidNetworkLocked(*pNetId)) {
439 break;
440 }
441 }
442
443 if (*pNetId > MAX_OEM_ID) {
444 ALOGE("No free network ID");
445 *pNetId = 0;
446 return -ENONET;
447 }
448
Chalard Jean04845142022-12-02 19:39:36 +0900449 int ret = createPhysicalNetworkLocked(*pNetId, permission, false /* local */);
Niranjan Pendharkar7e08f852017-07-24 11:40:05 -0700450 if (ret) {
451 *pNetId = 0;
452 }
453
454 return ret;
455}
456
Chiachang Wang2b0abee2022-01-12 10:03:17 +0800457int NetworkController::createVirtualNetwork(unsigned netId, bool secure, NativeVpnType vpnType,
458 bool excludeLocalRoutes) {
Luke Huangd1ee4622018-06-29 13:49:58 +0800459 ScopedWLock lock(mRWLock);
Lorenzo Colittibbd0aff2016-12-15 22:53:24 +0900460
Sreeram Ramachandranbbdde992014-09-05 16:05:03 -0700461 if (!(MIN_NET_ID <= netId && netId <= MAX_NET_ID)) {
Sreeram Ramachandran4043f012014-06-23 12:41:37 -0700462 ALOGE("invalid netId %u", netId);
463 return -EINVAL;
464 }
465
Lorenzo Colittibbd0aff2016-12-15 22:53:24 +0900466 if (isValidNetworkLocked(netId)) {
Sreeram Ramachandran4043f012014-06-23 12:41:37 -0700467 ALOGE("duplicate netId %u", netId);
468 return -EEXIST;
469 }
470
Ken Chenab5f3472021-04-04 11:28:06 +0800471 if (vpnType < NativeVpnType::SERVICE || NativeVpnType::OEM < vpnType) {
472 ALOGE("invalid vpnType %d", static_cast<int>(vpnType));
473 return -EINVAL;
474 }
475
Sreeram Ramachandran48e19b02014-07-22 22:23:20 -0700476 if (int ret = modifyFallthroughLocked(netId, true)) {
477 return ret;
478 }
Chiachang Wang2b0abee2022-01-12 10:03:17 +0800479 mNetworks[netId] = new VirtualNetwork(netId, secure, excludeLocalRoutes);
Sreeram Ramachandran4043f012014-06-23 12:41:37 -0700480 return 0;
481}
482
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700483int NetworkController::destroyNetwork(unsigned netId) {
Luke Huangd1ee4622018-06-29 13:49:58 +0800484 ScopedWLock lock(mRWLock);
Lorenzo Colittibbd0aff2016-12-15 22:53:24 +0900485
Ken Chen4e8ef9b2021-03-17 01:57:19 +0800486 if (netId == LOCAL_NET_ID || netId == UNREACHABLE_NET_ID) {
487 ALOGE("cannot destroy local or unreachable network");
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700488 return -EINVAL;
Sreeram Ramachandran5c181bf2014-04-07 14:10:04 -0700489 }
Lorenzo Colittibbd0aff2016-12-15 22:53:24 +0900490 if (!isValidNetworkLocked(netId)) {
Lorenzo Colitti738c93e2014-07-30 17:46:08 +0900491 ALOGE("no such netId %u", netId);
492 return -ENONET;
493 }
Sreeram Ramachandran5c181bf2014-04-07 14:10:04 -0700494
Sreeram Ramachandran379bd332014-04-10 19:58:06 -0700495 // TODO: ioctl(SIOCKILLADDR, ...) to kill all sockets on the old network.
Sreeram Ramachandran5c181bf2014-04-07 14:10:04 -0700496
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700497 Network* network = getNetworkLocked(netId);
Lorenzo Colitti99286fe2014-08-12 15:08:00 +0900498
499 // If we fail to destroy a network, things will get stuck badly. Therefore, unlike most of the
500 // other network code, ignore failures and attempt to clear out as much state as possible, even
501 // if we hit an error on the way. Return the first error that we see.
502 int ret = network->clearInterfaces();
503
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700504 if (mDefaultNetId == netId) {
Lorenzo Colitti99286fe2014-08-12 15:08:00 +0900505 if (int err = static_cast<PhysicalNetwork*>(network)->removeAsDefault()) {
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700506 ALOGE("inconceivable! removeAsDefault cannot fail on an empty network");
Lorenzo Colitti99286fe2014-08-12 15:08:00 +0900507 if (!ret) {
508 ret = err;
509 }
Sreeram Ramachandran5c181bf2014-04-07 14:10:04 -0700510 }
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700511 mDefaultNetId = NETID_UNSET;
Ken Chen7ad712f2021-01-05 01:14:20 +0800512 } else if (network->isVirtual()) {
Lorenzo Colitti99286fe2014-08-12 15:08:00 +0900513 if (int err = modifyFallthroughLocked(netId, false)) {
514 if (!ret) {
515 ret = err;
516 }
Sreeram Ramachandran48e19b02014-07-22 22:23:20 -0700517 }
Sreeram Ramachandran5c181bf2014-04-07 14:10:04 -0700518 }
Sreeram Ramachandran36ed53e2014-07-01 19:01:56 -0700519 mNetworks.erase(netId);
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700520 delete network;
Hugo Benichia9e3c5d2018-01-18 10:33:22 +0900521
Rubin Xu6c00b612018-04-27 14:27:59 +0100522 for (auto iter = mIfindexToLastNetId.begin(); iter != mIfindexToLastNetId.end();) {
523 if (iter->second == netId) {
524 iter = mIfindexToLastNetId.erase(iter);
525 } else {
526 ++iter;
527 }
528 }
529
Hugo Benichia9e3c5d2018-01-18 10:33:22 +0900530 updateTcpSocketMonitorPolling();
531
Lorenzo Colitti99286fe2014-08-12 15:08:00 +0900532 return ret;
Sreeram Ramachandran379bd332014-04-10 19:58:06 -0700533}
534
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700535int NetworkController::addInterfaceToNetwork(unsigned netId, const char* interface) {
Luke Huangd1ee4622018-06-29 13:49:58 +0800536 ScopedWLock lock(mRWLock);
Lorenzo Colittibbd0aff2016-12-15 22:53:24 +0900537
538 if (!isValidNetworkLocked(netId)) {
Lorenzo Colitti738c93e2014-07-30 17:46:08 +0900539 ALOGE("no such netId %u", netId);
540 return -ENONET;
Sreeram Ramachandran7619e1b2014-04-15 14:23:08 -0700541 }
542
Lorenzo Colittibbd0aff2016-12-15 22:53:24 +0900543 unsigned existingNetId = getNetworkForInterfaceLocked(interface);
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700544 if (existingNetId != NETID_UNSET && existingNetId != netId) {
545 ALOGE("interface %s already assigned to netId %u", interface, existingNetId);
546 return -EBUSY;
547 }
Rubin Xu6c00b612018-04-27 14:27:59 +0100548 if (int ret = getNetworkLocked(netId)->addInterface(interface)) {
549 return ret;
550 }
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700551
Lorenzo Colittib6dc40a2020-03-24 00:58:50 +0900552 // Only populate mIfindexToLastNetId for non-local networks, because for these getIfIndex will
553 // return 0. That's fine though, because that map is only used to prevent force-closing sockets
554 // when the same IP address is handed over from one interface to another interface that is in
555 // the same network but not in the same netId (for now this is done only on VPNs). That is not
556 // useful for the local network because IP addresses in the local network are always assigned by
557 // the device itself and never meaningful on any other network.
558 if (netId != LOCAL_NET_ID) {
559 int ifIndex = RouteController::getIfIndex(interface);
560 if (ifIndex) {
561 mIfindexToLastNetId[ifIndex] = netId;
562 } else {
563 // Cannot happen, since addInterface() above will have failed.
564 ALOGE("inconceivable! added interface %s with no index", interface);
565 }
Rubin Xu6c00b612018-04-27 14:27:59 +0100566 }
567 return 0;
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700568}
569
570int NetworkController::removeInterfaceFromNetwork(unsigned netId, const char* interface) {
Luke Huangd1ee4622018-06-29 13:49:58 +0800571 ScopedWLock lock(mRWLock);
Lorenzo Colittibbd0aff2016-12-15 22:53:24 +0900572
573 if (!isValidNetworkLocked(netId)) {
Lorenzo Colitti738c93e2014-07-30 17:46:08 +0900574 ALOGE("no such netId %u", netId);
575 return -ENONET;
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700576 }
577
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700578 return getNetworkLocked(netId)->removeInterface(interface);
579}
580
581Permission NetworkController::getPermissionForUser(uid_t uid) const {
Luke Huangd1ee4622018-06-29 13:49:58 +0800582 ScopedRLock lock(mRWLock);
Sreeram Ramachandraned4bd1f2014-07-05 12:31:05 -0700583 return getPermissionForUserLocked(uid);
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700584}
585
586void NetworkController::setPermissionForUsers(Permission permission,
587 const std::vector<uid_t>& uids) {
Luke Huangd1ee4622018-06-29 13:49:58 +0800588 ScopedWLock lock(mRWLock);
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700589 for (uid_t uid : uids) {
Sreeram Ramachandraned4bd1f2014-07-05 12:31:05 -0700590 mUsers[uid] = permission;
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700591 }
592}
593
Lorenzo Colittia1067c82014-10-02 22:47:41 +0900594int NetworkController::checkUserNetworkAccess(uid_t uid, unsigned netId) const {
Luke Huangd1ee4622018-06-29 13:49:58 +0800595 ScopedRLock lock(mRWLock);
Lorenzo Colittia1067c82014-10-02 22:47:41 +0900596 return checkUserNetworkAccessLocked(uid, netId);
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700597}
598
599int NetworkController::setPermissionForNetworks(Permission permission,
600 const std::vector<unsigned>& netIds) {
Luke Huangd1ee4622018-06-29 13:49:58 +0800601 ScopedWLock lock(mRWLock);
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700602 for (unsigned netId : netIds) {
Sreeram Ramachandran36ed53e2014-07-01 19:01:56 -0700603 Network* network = getNetworkLocked(netId);
Lorenzo Colitti738c93e2014-07-30 17:46:08 +0900604 if (!network) {
605 ALOGE("no such netId %u", netId);
606 return -ENONET;
607 }
Ken Chen7ad712f2021-01-05 01:14:20 +0800608 if (!network->isPhysical()) {
Lorenzo Colitti738c93e2014-07-30 17:46:08 +0900609 ALOGE("cannot set permissions on non-physical network with netId %u", netId);
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700610 return -EINVAL;
611 }
612
Sreeram Ramachandran36ed53e2014-07-01 19:01:56 -0700613 if (int ret = static_cast<PhysicalNetwork*>(network)->setPermission(permission)) {
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700614 return ret;
615 }
616 }
617 return 0;
618}
619
Ken Chene99b8cb2020-12-09 07:33:06 +0800620namespace {
621
622int isWrongNetworkForUidRanges(unsigned netId, Network* network) {
Lorenzo Colitti738c93e2014-07-30 17:46:08 +0900623 if (!network) {
624 ALOGE("no such netId %u", netId);
625 return -ENONET;
626 }
Ken Chen4e8ef9b2021-03-17 01:57:19 +0800627 if (!network->canAddUsers()) {
Ken Chen2f661522021-03-30 19:41:49 +0800628 ALOGE("cannot add/remove users to/from %s network %u", network->getTypeString().c_str(),
629 netId);
Sreeram Ramachandranb1425cc2014-06-23 18:54:27 -0700630 return -EINVAL;
631 }
Ken Chene99b8cb2020-12-09 07:33:06 +0800632 return 0;
633}
634
635} // namespace
636
Ken Chen4ea88462021-05-23 14:56:43 +0800637int NetworkController::addUsersToNetwork(unsigned netId, const UidRanges& uidRanges,
Ken Chen53360bf2021-12-10 02:41:05 +0800638 int32_t subPriority) {
Ken Chene99b8cb2020-12-09 07:33:06 +0800639 ScopedWLock lock(mRWLock);
640 Network* network = getNetworkLocked(netId);
641 if (int ret = isWrongNetworkForUidRanges(netId, network)) {
Sreeram Ramachandranb1425cc2014-06-23 18:54:27 -0700642 return ret;
643 }
Ken Chen4ea88462021-05-23 14:56:43 +0800644 return network->addUsers(uidRanges, subPriority);
Sreeram Ramachandranb1425cc2014-06-23 18:54:27 -0700645}
646
Ken Chen4ea88462021-05-23 14:56:43 +0800647int NetworkController::removeUsersFromNetwork(unsigned netId, const UidRanges& uidRanges,
Ken Chen53360bf2021-12-10 02:41:05 +0800648 int32_t subPriority) {
Luke Huangd1ee4622018-06-29 13:49:58 +0800649 ScopedWLock lock(mRWLock);
Sreeram Ramachandran36ed53e2014-07-01 19:01:56 -0700650 Network* network = getNetworkLocked(netId);
Ken Chene99b8cb2020-12-09 07:33:06 +0800651 if (int ret = isWrongNetworkForUidRanges(netId, network)) {
Sreeram Ramachandranb1425cc2014-06-23 18:54:27 -0700652 return ret;
653 }
Ken Chen4ea88462021-05-23 14:56:43 +0800654 return network->removeUsers(uidRanges, subPriority);
Sreeram Ramachandranb1425cc2014-06-23 18:54:27 -0700655}
656
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700657int NetworkController::addRoute(unsigned netId, const char* interface, const char* destination,
Tyler Wearfa94a272019-12-05 15:01:48 -0800658 const char* nexthop, bool legacy, uid_t uid, int mtu) {
659 return modifyRoute(netId, interface, destination, nexthop, ROUTE_ADD, legacy, uid, mtu);
660}
661
662int NetworkController::updateRoute(unsigned netId, const char* interface, const char* destination,
663 const char* nexthop, bool legacy, uid_t uid, int mtu) {
664 return modifyRoute(netId, interface, destination, nexthop, ROUTE_UPDATE, legacy, uid, mtu);
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700665}
666
667int NetworkController::removeRoute(unsigned netId, const char* interface, const char* destination,
668 const char* nexthop, bool legacy, uid_t uid) {
Tyler Wearfa94a272019-12-05 15:01:48 -0800669 return modifyRoute(netId, interface, destination, nexthop, ROUTE_REMOVE, legacy, uid, 0);
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700670}
671
Rubin Xu6c00b612018-04-27 14:27:59 +0100672void NetworkController::addInterfaceAddress(unsigned ifIndex, const char* address) {
Luke Huangd1ee4622018-06-29 13:49:58 +0800673 ScopedWLock lock(mRWLock);
Rubin Xu6c00b612018-04-27 14:27:59 +0100674 if (ifIndex == 0) {
675 ALOGE("Attempting to add address %s without ifindex", address);
676 return;
677 }
678 mAddressToIfindices[address].insert(ifIndex);
679}
680
681// Returns whether we should call SOCK_DESTROY on the removed address.
682bool NetworkController::removeInterfaceAddress(unsigned ifindex, const char* address) {
Luke Huangd1ee4622018-06-29 13:49:58 +0800683 ScopedWLock lock(mRWLock);
Rubin Xu6c00b612018-04-27 14:27:59 +0100684 // First, update mAddressToIfindices map
685 auto ifindicesIter = mAddressToIfindices.find(address);
686 if (ifindicesIter == mAddressToIfindices.end()) {
687 ALOGE("Removing unknown address %s from ifindex %u", address, ifindex);
688 return true;
689 }
690 std::unordered_set<unsigned>& ifindices = ifindicesIter->second;
691 if (ifindices.erase(ifindex) > 0) {
692 if (ifindices.size() == 0) {
Bernie Innocentidd5a4f02018-07-19 18:06:52 +0900693 mAddressToIfindices.erase(ifindicesIter); // Invalidates ifindices
694 // The address is no longer configured on any interface.
695 return true;
Rubin Xu6c00b612018-04-27 14:27:59 +0100696 }
697 } else {
698 ALOGE("No record of address %s on interface %u", address, ifindex);
699 return true;
700 }
701 // Then, check for VPN handover condition
702 if (mIfindexToLastNetId.find(ifindex) == mIfindexToLastNetId.end()) {
Lorenzo Colittib6dc40a2020-03-24 00:58:50 +0900703 ALOGW("Interface index %u was never in a currently-connected non-local netId", ifindex);
Rubin Xu6c00b612018-04-27 14:27:59 +0100704 return true;
705 }
706 unsigned lastNetId = mIfindexToLastNetId[ifindex];
707 for (unsigned idx : ifindices) {
708 unsigned activeNetId = mIfindexToLastNetId[idx];
709 // If this IP address is still assigned to another interface in the same network,
710 // then we don't need to destroy sockets on it because they are likely still valid.
711 // For now we do this only on VPNs.
712 // TODO: evaluate extending this to all network types.
713 if (lastNetId == activeNetId && isVirtualNetworkLocked(activeNetId)) {
714 return false;
715 }
716 }
717 return true;
718}
719
Patrick Rohr4fafa6f2024-04-23 11:36:21 -0700720bool NetworkController::isProtectableLocked(uid_t uid, unsigned netId) const {
721 return mProtectableUsers.find({uid, NETID_UNSET}) != mProtectableUsers.cend() ||
722 mProtectableUsers.find({uid, netId}) != mProtectableUsers.cend();
Sreeram Ramachandrane09b20a2014-07-05 17:15:14 -0700723}
724
Patrick Rohr4fafa6f2024-04-23 11:36:21 -0700725bool NetworkController::canProtectLocked(uid_t uid, unsigned netId) const {
726 if ((getPermissionForUserLocked(uid) & PERMISSION_SYSTEM) == PERMISSION_SYSTEM) {
727 return true;
728 }
729 return isProtectableLocked(uid, netId);
730}
731
732bool NetworkController::canProtect(uid_t uid, unsigned netId) const {
Luke Huangd1ee4622018-06-29 13:49:58 +0800733 ScopedRLock lock(mRWLock);
Patrick Rohr4fafa6f2024-04-23 11:36:21 -0700734 return canProtectLocked(uid, netId);
Lorenzo Colittibbd0aff2016-12-15 22:53:24 +0900735}
736
Patrick Rohrbecb94c2024-04-26 11:17:22 -0700737int NetworkController::allowProtect(uid_t uid, unsigned netId) {
Luke Huangd1ee4622018-06-29 13:49:58 +0800738 ScopedWLock lock(mRWLock);
Patrick Rohrbecb94c2024-04-26 11:17:22 -0700739 return mProtectableUsers.emplace(std::make_pair(uid, netId)).second ? 0 : -EEXIST;
Sreeram Ramachandran89dad012014-07-02 10:09:49 -0700740}
741
Patrick Rohrbecb94c2024-04-26 11:17:22 -0700742int NetworkController::denyProtect(uid_t uid, unsigned netId) {
Luke Huangd1ee4622018-06-29 13:49:58 +0800743 ScopedWLock lock(mRWLock);
Patrick Rohrbecb94c2024-04-26 11:17:22 -0700744 return mProtectableUsers.erase(std::make_pair(uid, netId)) ? 0 : -ENOENT;
Sreeram Ramachandran89dad012014-07-02 10:09:49 -0700745}
746
Erik Kline2d3a1632016-03-15 16:33:48 +0900747void NetworkController::dump(DumpWriter& dw) {
Luke Huangd1ee4622018-06-29 13:49:58 +0800748 ScopedRLock lock(mRWLock);
Erik Kline2d3a1632016-03-15 16:33:48 +0900749
750 dw.incIndent();
751 dw.println("NetworkController");
752
753 dw.incIndent();
754 dw.println("Default network: %u", mDefaultNetId);
755
756 dw.blankline();
757 dw.println("Networks:");
758 dw.incIndent();
759 for (const auto& i : mNetworks) {
Lorenzo Colittid1029652016-09-26 17:17:40 +0900760 Network* network = i.second;
Erik Klineb31fd692018-06-06 20:50:11 +0900761 dw.println(network->toString());
Ken Chen7ad712f2021-01-05 01:14:20 +0800762 if (network->isPhysical()) {
Lorenzo Colittid1029652016-09-26 17:17:40 +0900763 dw.incIndent();
764 Permission permission = reinterpret_cast<PhysicalNetwork*>(network)->getPermission();
765 dw.println("Required permission: %s", permissionToName(permission));
766 dw.decIndent();
767 }
Ken Chen8e0ba5a2021-06-11 03:29:45 +0800768 if (const auto& str = network->uidRangesToString(); !str.empty()) {
769 dw.incIndent();
Ken Chen0c209f82022-12-22 15:11:39 +0800770 dw.println("Per-app UID ranges: %s", str.c_str());
771 dw.decIndent();
772 }
773 if (const auto& str = network->allowedUidsToString(); !str.empty()) {
774 dw.incIndent();
775 dw.println("Allowed UID ranges: %s", str.c_str());
Ken Chen8e0ba5a2021-06-11 03:29:45 +0800776 dw.decIndent();
777 }
Pierre Imai3a272072016-04-19 16:17:07 +0900778 dw.blankline();
Erik Kline2d3a1632016-03-15 16:33:48 +0900779 }
780 dw.decIndent();
781
Rubin Xu6c00b612018-04-27 14:27:59 +0100782 dw.blankline();
783 dw.println("Interface <-> last network map:");
784 dw.incIndent();
785 for (const auto& i : mIfindexToLastNetId) {
786 dw.println("Ifindex: %u NetId: %u", i.first, i.second);
787 }
788 dw.decIndent();
789
790 dw.blankline();
791 dw.println("Interface addresses:");
792 dw.incIndent();
793 for (const auto& i : mAddressToIfindices) {
794 dw.println("address: %s ifindices: [%s]", i.first.c_str(),
795 android::base::Join(i.second, ", ").c_str());
796 }
797 dw.decIndent();
798
paulhu28582b72021-10-27 13:55:27 +0800799 dw.blankline();
800 dw.println("Permission of users:");
801 dw.incIndent();
802 std::vector<uid_t> systemUids;
803 std::vector<uid_t> networkUids;
804 for (const auto& [uid, permission] : mUsers) {
805 if ((permission & PERMISSION_SYSTEM) == PERMISSION_SYSTEM) {
806 systemUids.push_back(uid);
807 } else if ((permission & PERMISSION_NETWORK) == PERMISSION_NETWORK) {
808 networkUids.push_back(uid);
809 }
810 }
811 dw.println("NETWORK: %s", android::base::Join(networkUids, ", ").c_str());
812 dw.println("SYSTEM: %s", android::base::Join(systemUids, ", ").c_str());
813 dw.decIndent();
814
Ken Chen6acc2bf2023-06-10 18:23:33 +0800815 dw.blankline();
Patrick Rohr4fafa6f2024-04-23 11:36:21 -0700816 dw.println("Protectable users:");
817 for (auto it : mProtectableUsers) {
818 dw.println("[uid: %u : netId: %u]", it.first, it.second);
819 }
Ken Chen6acc2bf2023-06-10 18:23:33 +0800820
Erik Kline2d3a1632016-03-15 16:33:48 +0900821 dw.decIndent();
822
823 dw.decIndent();
824}
825
Ken Chen0c209f82022-12-22 15:11:39 +0800826void NetworkController::clearAllowedUidsForAllNetworksLocked() {
827 for (const auto& [_, network] : mNetworks) {
Ken Chen0c209f82022-12-22 15:11:39 +0800828 network->clearAllowedUids();
829 }
830}
831
832int NetworkController::setNetworkAllowlist(
Ken Chen04ee6092022-12-26 17:35:33 +0800833 const std::vector<netd::aidl::NativeUidRangeConfig>& rangeConfigs) {
Ken Chen0c209f82022-12-22 15:11:39 +0800834 const ScopedWLock lock(mRWLock);
835
Ken Chen04ee6092022-12-26 17:35:33 +0800836 for (const auto& config : rangeConfigs) {
837 Network* network = getNetworkLocked(config.netId);
Ken Chen0c209f82022-12-22 15:11:39 +0800838 if (!network) return -ENONET;
Ken Chen0c209f82022-12-22 15:11:39 +0800839 }
840
Ken Chen04ee6092022-12-26 17:35:33 +0800841 clearAllowedUidsForAllNetworksLocked();
842 for (const auto& config : rangeConfigs) {
843 Network* network = getNetworkLocked(config.netId);
844 network->setAllowedUids(UidRanges(config.uidRanges));
Ken Chen0c209f82022-12-22 15:11:39 +0800845 }
846 return 0;
847}
848
Ken Chene22ac8d2022-12-24 09:24:56 +0800849bool NetworkController::isUidAllowed(unsigned netId, uid_t uid) const {
850 const ScopedRLock lock(mRWLock);
851 Network* network = getNetworkLocked(netId);
Ken Chenfd22f382023-01-16 19:00:43 +0800852 // Exempt when no netId is specified and there is no default network, so that apps or tests can
853 // do DNS lookups for hostnames in etc/hosts.
Ken Chen26bc3d12023-01-30 18:01:56 +0800854 if (netId == NETID_UNSET && mDefaultNetId == NETID_UNSET) {
Ken Chene22ac8d2022-12-24 09:24:56 +0800855 return true;
856 }
Ken Chen26bc3d12023-01-30 18:01:56 +0800857 return network && network->isUidAllowed(uid);
Ken Chene22ac8d2022-12-24 09:24:56 +0800858}
859
Niranjan Pendharkar7e08f852017-07-24 11:40:05 -0700860bool NetworkController::isValidNetworkLocked(unsigned netId) const {
861 return getNetworkLocked(netId);
862}
863
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700864Network* NetworkController::getNetworkLocked(unsigned netId) const {
Sreeram Ramachandran36ed53e2014-07-01 19:01:56 -0700865 auto iter = mNetworks.find(netId);
Yi Kongbdfd57e2018-07-25 13:26:10 -0700866 return iter == mNetworks.end() ? nullptr : iter->second;
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700867}
868
Sreeram Ramachandrane09b20a2014-07-05 17:15:14 -0700869VirtualNetwork* NetworkController::getVirtualNetworkForUserLocked(uid_t uid) const {
Ken Chen53360bf2021-12-10 02:41:05 +0800870 int32_t subPriority;
Ken Chend15bcfc2020-12-04 00:08:54 +0800871 for (const auto& [_, network] : mNetworks) {
Ken Chen4ea88462021-05-23 14:56:43 +0800872 if (network->isVirtual() && network->appliesToUser(uid, &subPriority)) {
Ken Chen7ad712f2021-01-05 01:14:20 +0800873 return static_cast<VirtualNetwork*>(network);
Sreeram Ramachandrane09b20a2014-07-05 17:15:14 -0700874 }
875 }
Yi Kongbdfd57e2018-07-25 13:26:10 -0700876 return nullptr;
Sreeram Ramachandrane09b20a2014-07-05 17:15:14 -0700877}
878
Patrick Rohre6f198c2022-01-25 13:50:31 +0100879// Returns the default network with the highest subsidiary priority among physical and unreachable
880// networks that applies to uid. For a single subsidiary priority, an uid should belong to only one
881// network. If the uid apply to different network with the same priority at the same time, the
882// behavior is undefined. That is a configuration error.
Ken Chen4e8ef9b2021-03-17 01:57:19 +0800883Network* NetworkController::getPhysicalOrUnreachableNetworkForUserLocked(uid_t uid) const {
Ken Chen4ea88462021-05-23 14:56:43 +0800884 Network* bestNetwork = nullptr;
Patrick Rohre6f198c2022-01-25 13:50:31 +0100885
886 // In this function, appliesToUser() is used to figure out if this network is the user's default
887 // network (not just if the user has access to this network). Rules at SUB_PRIORITY_NO_DEFAULT
888 // "apply to the user" but do not include a default network rule. Since their subpriority (999)
889 // is greater than SUB_PRIORITY_LOWEST (998), these rules never trump any subpriority that
890 // includes a default network rule (appliesToUser returns the "highest" (=lowest value)
891 // subPriority that includes the uid), and they get filtered out in the if-statement below.
892 int32_t bestSubPriority = UidRanges::SUB_PRIORITY_NO_DEFAULT;
Ken Chen4ea88462021-05-23 14:56:43 +0800893 for (const auto& [netId, network] : mNetworks) {
Ken Chen53360bf2021-12-10 02:41:05 +0800894 int32_t subPriority;
Ken Chen4ea88462021-05-23 14:56:43 +0800895 if (!network->isPhysical() && !network->isUnreachable()) continue;
896 if (!network->appliesToUser(uid, &subPriority)) continue;
Patrick Rohre6f198c2022-01-25 13:50:31 +0100897 if (subPriority == UidRanges::SUB_PRIORITY_NO_DEFAULT) continue;
898
Ken Chen4ea88462021-05-23 14:56:43 +0800899 if (subPriority < bestSubPriority) {
900 bestNetwork = network;
901 bestSubPriority = subPriority;
Ken Chen8738e1c2020-11-24 11:38:54 +0800902 }
903 }
Ken Chen4ea88462021-05-23 14:56:43 +0800904 return bestNetwork;
Ken Chen8738e1c2020-11-24 11:38:54 +0800905}
906
Sreeram Ramachandraned4bd1f2014-07-05 12:31:05 -0700907Permission NetworkController::getPermissionForUserLocked(uid_t uid) const {
908 auto iter = mUsers.find(uid);
909 if (iter != mUsers.end()) {
910 return iter->second;
911 }
912 return uid < FIRST_APPLICATION_UID ? PERMISSION_SYSTEM : PERMISSION_NONE;
913}
914
Lorenzo Colittia1067c82014-10-02 22:47:41 +0900915int NetworkController::checkUserNetworkAccessLocked(uid_t uid, unsigned netId) const {
Sreeram Ramachandran1011b492014-07-24 19:04:32 -0700916 Network* network = getNetworkLocked(netId);
Lorenzo Colittia1067c82014-10-02 22:47:41 +0900917 if (!network) {
918 return -ENONET;
919 }
920
Sreeram Ramachandran1011b492014-07-24 19:04:32 -0700921 // If uid is INVALID_UID, this likely means that we were unable to retrieve the UID of the peer
922 // (using SO_PEERCRED). Be safe and deny access to the network, even if it's valid.
Lorenzo Colittia1067c82014-10-02 22:47:41 +0900923 if (uid == INVALID_UID) {
924 return -EREMOTEIO;
Sreeram Ramachandran1011b492014-07-24 19:04:32 -0700925 }
Ken Chenf875b522020-12-03 19:05:02 +0800926 // If the UID has PERMISSION_SYSTEM, it can use whatever network it wants.
Sreeram Ramachandran1011b492014-07-24 19:04:32 -0700927 Permission userPermission = getPermissionForUserLocked(uid);
928 if ((userPermission & PERMISSION_SYSTEM) == PERMISSION_SYSTEM) {
Lorenzo Colittia1067c82014-10-02 22:47:41 +0900929 return 0;
Sreeram Ramachandran1011b492014-07-24 19:04:32 -0700930 }
Ken Chenf875b522020-12-03 19:05:02 +0800931 // If the UID wants to use a VPN, it can do so if and only if the VPN applies to the UID.
Ken Chen53360bf2021-12-10 02:41:05 +0800932 int32_t subPriority;
Ken Chen7ad712f2021-01-05 01:14:20 +0800933 if (network->isVirtual()) {
Ken Chen4ea88462021-05-23 14:56:43 +0800934 return network->appliesToUser(uid, &subPriority) ? 0 : -EPERM;
Sreeram Ramachandran1011b492014-07-24 19:04:32 -0700935 }
Ken Chenf875b522020-12-03 19:05:02 +0800936 // If a VPN applies to the UID, and the VPN is secure (i.e., not bypassable), then the UID can
937 // only select a different network if it has the ability to protect its sockets.
Sreeram Ramachandran1011b492014-07-24 19:04:32 -0700938 VirtualNetwork* virtualNetwork = getVirtualNetworkForUserLocked(uid);
Patrick Rohr4fafa6f2024-04-23 11:36:21 -0700939 if (virtualNetwork && virtualNetwork->isSecure() && !isProtectableLocked(uid, netId)) {
Ken Chen6acc2bf2023-06-10 18:23:33 +0800940 ALOGE("uid %u can't select networks other than %u.", uid, virtualNetwork->getNetId());
Lorenzo Colittia1067c82014-10-02 22:47:41 +0900941 return -EPERM;
Sreeram Ramachandran1011b492014-07-24 19:04:32 -0700942 }
Ken Chen8738e1c2020-11-24 11:38:54 +0800943 // If the UID wants to use a physical network and it has a UID range that includes the UID, the
944 // UID has permission to use it regardless of whether the permission bits match.
Ken Chen4ea88462021-05-23 14:56:43 +0800945 if (network->isPhysical() && network->appliesToUser(uid, &subPriority)) {
Ken Chen8738e1c2020-11-24 11:38:54 +0800946 return 0;
947 }
Ken Chen55db3802021-03-30 13:47:49 +0800948 // Only apps that are configured as "no default network" can use the unreachable network.
949 if (network->isUnreachable()) {
Ken Chen4ea88462021-05-23 14:56:43 +0800950 return network->appliesToUser(uid, &subPriority) ? 0 : -EPERM;
Ken Chen55db3802021-03-30 13:47:49 +0800951 }
Ken Chen0c209f82022-12-22 15:11:39 +0800952
953 if (!network->isUidAllowed(uid)) {
954 return -EACCES;
955 }
Ken Chenf875b522020-12-03 19:05:02 +0800956 // Check whether the UID's permission bits are sufficient to use the network.
Ken Chen8738e1c2020-11-24 11:38:54 +0800957 // Because the permission of the system default network is PERMISSION_NONE(0x0), apps can always
958 // pass the check here when using the system default network.
Ken Chen1a028a72022-10-27 17:54:38 +0800959 const Permission networkPermission = network->getPermission();
Lorenzo Colittia1067c82014-10-02 22:47:41 +0900960 return ((userPermission & networkPermission) == networkPermission) ? 0 : -EACCES;
Sreeram Ramachandran1011b492014-07-24 19:04:32 -0700961}
962
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700963int NetworkController::modifyRoute(unsigned netId, const char* interface, const char* destination,
Tyler Wearfa94a272019-12-05 15:01:48 -0800964 const char* nexthop, enum RouteOperation op, bool legacy,
965 uid_t uid, int mtu) {
Luke Huangd1ee4622018-06-29 13:49:58 +0800966 ScopedRLock lock(mRWLock);
Lorenzo Colittibbd0aff2016-12-15 22:53:24 +0900967
968 if (!isValidNetworkLocked(netId)) {
Lorenzo Colitti738c93e2014-07-30 17:46:08 +0900969 ALOGE("no such netId %u", netId);
970 return -ENONET;
971 }
Lorenzo Colittibbd0aff2016-12-15 22:53:24 +0900972 unsigned existingNetId = getNetworkForInterfaceLocked(interface);
Lorenzo Colitti738c93e2014-07-30 17:46:08 +0900973 if (existingNetId == NETID_UNSET) {
974 ALOGE("interface %s not assigned to any netId", interface);
975 return -ENODEV;
976 }
977 if (existingNetId != netId) {
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700978 ALOGE("interface %s assigned to netId %u, not %u", interface, existingNetId, netId);
Lorenzo Colittif7fc8ec2014-06-18 00:41:58 +0900979 return -ENOENT;
Sreeram Ramachandran7619e1b2014-04-15 14:23:08 -0700980 }
981
Sreeram Ramachandran38b7af12014-05-22 14:21:49 -0700982 RouteController::TableType tableType;
Sreeram Ramachandran87475a12014-07-15 16:20:28 -0700983 if (netId == LOCAL_NET_ID) {
984 tableType = RouteController::LOCAL_NETWORK;
985 } else if (legacy) {
Lorenzo Colittibbd0aff2016-12-15 22:53:24 +0900986 if ((getPermissionForUserLocked(uid) & PERMISSION_SYSTEM) == PERMISSION_SYSTEM) {
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -0700987 tableType = RouteController::LEGACY_SYSTEM;
Sreeram Ramachandran38b7af12014-05-22 14:21:49 -0700988 } else {
Sreeram Ramachandran5009d5e2014-07-03 12:20:48 -0700989 tableType = RouteController::LEGACY_NETWORK;
Sreeram Ramachandran38b7af12014-05-22 14:21:49 -0700990 }
991 } else {
992 tableType = RouteController::INTERFACE;
993 }
994
Tyler Wearfa94a272019-12-05 15:01:48 -0800995 switch (op) {
996 case ROUTE_ADD:
Taras Antoshchuk0cceda22021-09-24 18:40:03 +0200997 return RouteController::addRoute(interface, destination, nexthop, tableType, mtu,
998 0 /* priority */);
Tyler Wearfa94a272019-12-05 15:01:48 -0800999 case ROUTE_UPDATE:
1000 return RouteController::updateRoute(interface, destination, nexthop, tableType, mtu);
1001 case ROUTE_REMOVE:
Taras Antoshchuk0cceda22021-09-24 18:40:03 +02001002 return RouteController::removeRoute(interface, destination, nexthop, tableType,
1003 0 /* priority */);
Tyler Wearfa94a272019-12-05 15:01:48 -08001004 }
1005 return -EINVAL;
Sreeram Ramachandran7619e1b2014-04-15 14:23:08 -07001006}
Sreeram Ramachandran48e19b02014-07-22 22:23:20 -07001007
1008int NetworkController::modifyFallthroughLocked(unsigned vpnNetId, bool add) {
1009 if (mDefaultNetId == NETID_UNSET) {
1010 return 0;
1011 }
1012 Network* network = getNetworkLocked(mDefaultNetId);
Lorenzo Colitti738c93e2014-07-30 17:46:08 +09001013 if (!network) {
Sreeram Ramachandran48e19b02014-07-22 22:23:20 -07001014 ALOGE("cannot find previously set default network with netId %u", mDefaultNetId);
1015 return -ESRCH;
1016 }
Ken Chen7ad712f2021-01-05 01:14:20 +08001017 if (!network->isPhysical()) {
Lorenzo Colitti738c93e2014-07-30 17:46:08 +09001018 ALOGE("inconceivable! default network must be a physical network");
1019 return -EINVAL;
1020 }
Sreeram Ramachandran48e19b02014-07-22 22:23:20 -07001021 Permission permission = static_cast<PhysicalNetwork*>(network)->getPermission();
1022 for (const auto& physicalInterface : network->getInterfaces()) {
1023 if (int ret = mDelegateImpl->modifyFallthrough(vpnNetId, physicalInterface, permission,
1024 add)) {
1025 return ret;
1026 }
1027 }
1028 return 0;
1029}
Lorenzo Colitti7035f222017-02-13 18:29:00 +09001030
Hugo Benichia9e3c5d2018-01-18 10:33:22 +09001031void NetworkController::updateTcpSocketMonitorPolling() {
1032 bool physicalNetworkExists = false;
1033 for (const auto& entry : mNetworks) {
1034 const auto& network = entry.second;
Ken Chen7ad712f2021-01-05 01:14:20 +08001035 if (network->isPhysical() && network->getNetId() >= MIN_NET_ID) {
Hugo Benichia9e3c5d2018-01-18 10:33:22 +09001036 physicalNetworkExists = true;
1037 break;
1038 }
1039 }
1040
1041 if (physicalNetworkExists) {
1042 android::net::gCtls->tcpSocketMonitor.resumePolling();
1043 } else {
1044 android::net::gCtls->tcpSocketMonitor.suspendPolling();
1045 }
1046}
1047
Bernie Innocenti762dcf42019-06-14 19:52:49 +09001048} // namespace android::net