2 * Copyright (C) 2014 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
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.
22 // In some cases, a single non-const method acquires and releases the lock several times, like so:
23 // if (isValidNetwork(...)) { // isValidNetwork() acquires and releases the lock.
24 // setDefaultNetwork(...); // setDefaultNetwork() also acquires and releases the lock.
26 // It might seem that this allows races where the state changes between the two statements, but in
27 // fact there are no races because:
28 // 1. This pattern only occurs in non-const methods (i.e., those that mutate state).
29 // 2. Only CommandListener calls these non-const methods. The others call only const methods.
30 // 3. CommandListener only processes one command at a time. I.e., it's serialized.
31 // Thus, no other mutation can occur in between the two statements above.
33 #include "NetworkController.h"
35 #define LOG_TAG "Netd"
38 #include "cutils/misc.h"
39 #include "resolv_netid.h"
41 #include "Controllers.h"
42 #include "DummyNetwork.h"
43 #include "DumpWriter.h"
45 #include "LocalNetwork.h"
46 #include "PhysicalNetwork.h"
47 #include "RouteController.h"
48 #include "VirtualNetwork.h"
52 // Keep these in sync with ConnectivityService.java.
53 const unsigned MIN_NET_ID = 100;
54 const unsigned MAX_NET_ID = 65535;
58 const unsigned NetworkController::MIN_OEM_ID = 1;
59 const unsigned NetworkController::MAX_OEM_ID = 50;
60 const unsigned NetworkController::DUMMY_NET_ID = 51;
61 // NetIds 52..98 are reserved for future use.
62 const unsigned NetworkController::LOCAL_NET_ID = 99;
64 // All calls to methods here are made while holding a write lock on mRWLock.
65 class NetworkController::DelegateImpl : public PhysicalNetwork::Delegate {
67 explicit DelegateImpl(NetworkController* networkController);
68 virtual ~DelegateImpl();
70 int modifyFallthrough(unsigned vpnNetId, const std::string& physicalInterface,
71 Permission permission, bool add) WARN_UNUSED_RESULT;
74 int addFallthrough(const std::string& physicalInterface,
75 Permission permission) override WARN_UNUSED_RESULT;
76 int removeFallthrough(const std::string& physicalInterface,
77 Permission permission) override WARN_UNUSED_RESULT;
79 int modifyFallthrough(const std::string& physicalInterface, Permission permission,
80 bool add) WARN_UNUSED_RESULT;
82 NetworkController* const mNetworkController;
85 NetworkController::DelegateImpl::DelegateImpl(NetworkController* networkController) :
86 mNetworkController(networkController) {
89 NetworkController::DelegateImpl::~DelegateImpl() {
92 int NetworkController::DelegateImpl::modifyFallthrough(unsigned vpnNetId,
93 const std::string& physicalInterface,
94 Permission permission, bool add) {
96 if (int ret = RouteController::addVirtualNetworkFallthrough(vpnNetId,
97 physicalInterface.c_str(),
99 ALOGE("failed to add fallthrough to %s for VPN netId %u", physicalInterface.c_str(),
104 if (int ret = RouteController::removeVirtualNetworkFallthrough(vpnNetId,
105 physicalInterface.c_str(),
107 ALOGE("failed to remove fallthrough to %s for VPN netId %u", physicalInterface.c_str(),
115 int NetworkController::DelegateImpl::addFallthrough(const std::string& physicalInterface,
116 Permission permission) {
117 return modifyFallthrough(physicalInterface, permission, true);
120 int NetworkController::DelegateImpl::removeFallthrough(const std::string& physicalInterface,
121 Permission permission) {
122 return modifyFallthrough(physicalInterface, permission, false);
125 int NetworkController::DelegateImpl::modifyFallthrough(const std::string& physicalInterface,
126 Permission permission, bool add) {
127 for (const auto& entry : mNetworkController->mNetworks) {
128 if (entry.second->getType() == Network::VIRTUAL) {
129 if (int ret = modifyFallthrough(entry.first, physicalInterface, permission, add)) {
137 NetworkController::NetworkController() :
138 mDelegateImpl(new NetworkController::DelegateImpl(this)), mDefaultNetId(NETID_UNSET) {
139 mNetworks[LOCAL_NET_ID] = new LocalNetwork(LOCAL_NET_ID);
140 mNetworks[DUMMY_NET_ID] = new DummyNetwork(DUMMY_NET_ID);
143 unsigned NetworkController::getDefaultNetwork() const {
144 android::RWLock::AutoRLock lock(mRWLock);
145 return mDefaultNetId;
148 int NetworkController::setDefaultNetwork(unsigned netId) {
149 android::RWLock::AutoWLock lock(mRWLock);
151 if (netId == mDefaultNetId) {
155 if (netId != NETID_UNSET) {
156 Network* network = getNetworkLocked(netId);
158 ALOGE("no such netId %u", netId);
161 if (network->getType() != Network::PHYSICAL) {
162 ALOGE("cannot set default to non-physical network with netId %u", netId);
165 if (int ret = static_cast<PhysicalNetwork*>(network)->addAsDefault()) {
170 if (mDefaultNetId != NETID_UNSET) {
171 Network* network = getNetworkLocked(mDefaultNetId);
172 if (!network || network->getType() != Network::PHYSICAL) {
173 ALOGE("cannot find previously set default network with netId %u", mDefaultNetId);
176 if (int ret = static_cast<PhysicalNetwork*>(network)->removeAsDefault()) {
181 mDefaultNetId = netId;
185 uint32_t NetworkController::getNetworkForDns(unsigned* netId, uid_t uid) const {
186 android::RWLock::AutoRLock lock(mRWLock);
188 fwmark.protectedFromVpn = true;
189 fwmark.permission = PERMISSION_SYSTEM;
190 if (checkUserNetworkAccessLocked(uid, *netId) == 0) {
191 // If a non-zero NetId was explicitly specified, and the user has permission for that
192 // network, use that network's DNS servers. Do not fall through to the default network even
193 // if the explicitly selected network is a split tunnel VPN or a VPN without DNS servers.
194 fwmark.explicitlySelected = true;
196 // If the user is subject to a VPN and the VPN provides DNS servers, use those servers
197 // (possibly falling through to the default network if the VPN doesn't provide a route to
198 // them). Otherwise, use the default network's DNS servers.
199 VirtualNetwork* virtualNetwork = getVirtualNetworkForUserLocked(uid);
200 if (virtualNetwork && virtualNetwork->getHasDns()) {
201 *netId = virtualNetwork->getNetId();
203 *netId = mDefaultNetId;
206 fwmark.netId = *netId;
207 return fwmark.intValue;
210 // Returns the NetId that a given UID would use if no network is explicitly selected. Specifically,
211 // the VPN that applies to the UID if any; otherwise, the default network.
212 unsigned NetworkController::getNetworkForUser(uid_t uid) const {
213 android::RWLock::AutoRLock lock(mRWLock);
214 if (VirtualNetwork* virtualNetwork = getVirtualNetworkForUserLocked(uid)) {
215 return virtualNetwork->getNetId();
217 return mDefaultNetId;
220 // Returns the NetId that will be set when a socket connect()s. This is the bypassable VPN that
221 // applies to the user if any; otherwise, the default network.
223 // In general, we prefer to always set the default network's NetId in connect(), so that if the VPN
224 // is a split-tunnel and disappears later, the socket continues working (since the default network's
225 // NetId is still valid). Secure VPNs will correctly grab the socket's traffic since they have a
226 // high-priority routing rule that doesn't care what NetId the socket has.
228 // But bypassable VPNs have a very low priority rule, so we need to mark the socket with the
229 // bypassable VPN's NetId if we expect it to get any traffic at all. If the bypassable VPN is a
230 // split-tunnel, that's okay, because we have fallthrough rules that will direct the fallthrough
231 // traffic to the default network. But it does mean that if the bypassable VPN goes away (and thus
232 // the fallthrough rules also go away), the socket that used to fallthrough to the default network
233 // will stop working.
234 unsigned NetworkController::getNetworkForConnect(uid_t uid) const {
235 android::RWLock::AutoRLock lock(mRWLock);
236 VirtualNetwork* virtualNetwork = getVirtualNetworkForUserLocked(uid);
237 if (virtualNetwork && !virtualNetwork->isSecure()) {
238 return virtualNetwork->getNetId();
240 return mDefaultNetId;
243 void NetworkController::getNetworkContext(
244 unsigned netId, uid_t uid, struct android_net_context* netcontext) const {
245 struct android_net_context nc = {
247 .app_mark = MARK_UNSET,
249 .dns_mark = MARK_UNSET,
253 // |netId| comes directly (via dnsproxyd) from the value returned by netIdForResolv() in the
254 // client process. This value is nonzero iff.:
256 // 1. The app specified a netid/nethandle to a DNS resolution method such as:
257 // - [Java] android.net.Network#getAllByName()
258 // - [C/++] android_getaddrinfofornetwork()
259 // 2. The app specified a netid/nethandle to be used as a process default via:
260 // - [Java] android.net.ConnectivityManager#bindProcessToNetwork()
261 // - [C/++] android_setprocnetwork()
262 // 3. The app called android.net.ConnectivityManager#startUsingNetworkFeature().
264 // In all these cases (with the possible exception of #3), the right thing to do is to treat
265 // such cases as explicitlySelected.
266 const bool explicitlySelected = (nc.app_netid != NETID_UNSET);
267 if (!explicitlySelected) {
268 nc.app_netid = getNetworkForConnect(uid);
272 fwmark.netId = nc.app_netid;
273 fwmark.explicitlySelected = explicitlySelected;
274 fwmark.protectedFromVpn = canProtect(uid);
275 fwmark.permission = getPermissionForUser(uid);
276 nc.app_mark = fwmark.intValue;
278 nc.dns_mark = getNetworkForDns(&(nc.dns_netid), uid);
285 unsigned NetworkController::getNetworkForInterface(const char* interface) const {
286 android::RWLock::AutoRLock lock(mRWLock);
287 for (const auto& entry : mNetworks) {
288 if (entry.second->hasInterface(interface)) {
295 bool NetworkController::isVirtualNetwork(unsigned netId) const {
296 android::RWLock::AutoRLock lock(mRWLock);
297 Network* network = getNetworkLocked(netId);
298 return network && network->getType() == Network::VIRTUAL;
301 int NetworkController::createPhysicalNetwork(unsigned netId, Permission permission) {
302 if (!((MIN_NET_ID <= netId && netId <= MAX_NET_ID) ||
303 (MIN_OEM_ID <= netId && netId <= MAX_OEM_ID))) {
304 ALOGE("invalid netId %u", netId);
308 if (isValidNetwork(netId)) {
309 ALOGE("duplicate netId %u", netId);
313 PhysicalNetwork* physicalNetwork = new PhysicalNetwork(netId, mDelegateImpl);
314 if (int ret = physicalNetwork->setPermission(permission)) {
315 ALOGE("inconceivable! setPermission cannot fail on an empty network");
316 delete physicalNetwork;
320 android::RWLock::AutoWLock lock(mRWLock);
321 mNetworks[netId] = physicalNetwork;
325 int NetworkController::createVirtualNetwork(unsigned netId, bool hasDns, bool secure) {
326 if (!(MIN_NET_ID <= netId && netId <= MAX_NET_ID)) {
327 ALOGE("invalid netId %u", netId);
331 if (isValidNetwork(netId)) {
332 ALOGE("duplicate netId %u", netId);
336 android::RWLock::AutoWLock lock(mRWLock);
337 if (int ret = modifyFallthroughLocked(netId, true)) {
340 mNetworks[netId] = new VirtualNetwork(netId, hasDns, secure);
344 int NetworkController::destroyNetwork(unsigned netId) {
345 if (netId == LOCAL_NET_ID) {
346 ALOGE("cannot destroy local network");
349 if (!isValidNetwork(netId)) {
350 ALOGE("no such netId %u", netId);
354 // TODO: ioctl(SIOCKILLADDR, ...) to kill all sockets on the old network.
356 android::RWLock::AutoWLock lock(mRWLock);
357 Network* network = getNetworkLocked(netId);
359 // If we fail to destroy a network, things will get stuck badly. Therefore, unlike most of the
360 // other network code, ignore failures and attempt to clear out as much state as possible, even
361 // if we hit an error on the way. Return the first error that we see.
362 int ret = network->clearInterfaces();
364 if (mDefaultNetId == netId) {
365 if (int err = static_cast<PhysicalNetwork*>(network)->removeAsDefault()) {
366 ALOGE("inconceivable! removeAsDefault cannot fail on an empty network");
371 mDefaultNetId = NETID_UNSET;
372 } else if (network->getType() == Network::VIRTUAL) {
373 if (int err = modifyFallthroughLocked(netId, false)) {
379 mNetworks.erase(netId);
381 _resolv_delete_cache_for_net(netId);
385 int NetworkController::addInterfaceToNetwork(unsigned netId, const char* interface) {
386 if (!isValidNetwork(netId)) {
387 ALOGE("no such netId %u", netId);
391 unsigned existingNetId = getNetworkForInterface(interface);
392 if (existingNetId != NETID_UNSET && existingNetId != netId) {
393 ALOGE("interface %s already assigned to netId %u", interface, existingNetId);
397 android::RWLock::AutoWLock lock(mRWLock);
398 return getNetworkLocked(netId)->addInterface(interface);
401 int NetworkController::removeInterfaceFromNetwork(unsigned netId, const char* interface) {
402 if (!isValidNetwork(netId)) {
403 ALOGE("no such netId %u", netId);
407 android::RWLock::AutoWLock lock(mRWLock);
408 return getNetworkLocked(netId)->removeInterface(interface);
411 Permission NetworkController::getPermissionForUser(uid_t uid) const {
412 android::RWLock::AutoRLock lock(mRWLock);
413 return getPermissionForUserLocked(uid);
416 void NetworkController::setPermissionForUsers(Permission permission,
417 const std::vector<uid_t>& uids) {
418 android::RWLock::AutoWLock lock(mRWLock);
419 for (uid_t uid : uids) {
420 mUsers[uid] = permission;
424 int NetworkController::checkUserNetworkAccess(uid_t uid, unsigned netId) const {
425 android::RWLock::AutoRLock lock(mRWLock);
426 return checkUserNetworkAccessLocked(uid, netId);
429 int NetworkController::setPermissionForNetworks(Permission permission,
430 const std::vector<unsigned>& netIds) {
431 android::RWLock::AutoWLock lock(mRWLock);
432 for (unsigned netId : netIds) {
433 Network* network = getNetworkLocked(netId);
435 ALOGE("no such netId %u", netId);
438 if (network->getType() != Network::PHYSICAL) {
439 ALOGE("cannot set permissions on non-physical network with netId %u", netId);
443 // TODO: ioctl(SIOCKILLADDR, ...) to kill socets on the network that don't have permission.
445 if (int ret = static_cast<PhysicalNetwork*>(network)->setPermission(permission)) {
452 int NetworkController::addUsersToNetwork(unsigned netId, const UidRanges& uidRanges) {
453 android::RWLock::AutoWLock lock(mRWLock);
454 Network* network = getNetworkLocked(netId);
456 ALOGE("no such netId %u", netId);
459 if (network->getType() != Network::VIRTUAL) {
460 ALOGE("cannot add users to non-virtual network with netId %u", netId);
463 if (int ret = static_cast<VirtualNetwork*>(network)->addUsers(uidRanges, mProtectableUsers)) {
469 int NetworkController::removeUsersFromNetwork(unsigned netId, const UidRanges& uidRanges) {
470 android::RWLock::AutoWLock lock(mRWLock);
471 Network* network = getNetworkLocked(netId);
473 ALOGE("no such netId %u", netId);
476 if (network->getType() != Network::VIRTUAL) {
477 ALOGE("cannot remove users from non-virtual network with netId %u", netId);
480 if (int ret = static_cast<VirtualNetwork*>(network)->removeUsers(uidRanges,
481 mProtectableUsers)) {
487 int NetworkController::addRoute(unsigned netId, const char* interface, const char* destination,
488 const char* nexthop, bool legacy, uid_t uid) {
489 return modifyRoute(netId, interface, destination, nexthop, true, legacy, uid);
492 int NetworkController::removeRoute(unsigned netId, const char* interface, const char* destination,
493 const char* nexthop, bool legacy, uid_t uid) {
494 return modifyRoute(netId, interface, destination, nexthop, false, legacy, uid);
497 bool NetworkController::canProtect(uid_t uid) const {
498 android::RWLock::AutoRLock lock(mRWLock);
499 return ((getPermissionForUserLocked(uid) & PERMISSION_SYSTEM) == PERMISSION_SYSTEM) ||
500 mProtectableUsers.find(uid) != mProtectableUsers.end();
503 void NetworkController::allowProtect(const std::vector<uid_t>& uids) {
504 android::RWLock::AutoWLock lock(mRWLock);
505 mProtectableUsers.insert(uids.begin(), uids.end());
508 void NetworkController::denyProtect(const std::vector<uid_t>& uids) {
509 android::RWLock::AutoWLock lock(mRWLock);
510 for (uid_t uid : uids) {
511 mProtectableUsers.erase(uid);
515 void NetworkController::dump(DumpWriter& dw) {
516 android::RWLock::AutoRLock lock(mRWLock);
519 dw.println("NetworkController");
522 dw.println("Default network: %u", mDefaultNetId);
525 dw.println("Networks:");
527 for (const auto& i : mNetworks) {
528 dw.println(i.second->toString().c_str());
529 android::net::gCtls->resolverCtrl.dump(dw, i.first);
539 bool NetworkController::isValidNetwork(unsigned netId) const {
540 android::RWLock::AutoRLock lock(mRWLock);
541 return getNetworkLocked(netId);
544 Network* NetworkController::getNetworkLocked(unsigned netId) const {
545 auto iter = mNetworks.find(netId);
546 return iter == mNetworks.end() ? NULL : iter->second;
549 VirtualNetwork* NetworkController::getVirtualNetworkForUserLocked(uid_t uid) const {
550 for (const auto& entry : mNetworks) {
551 if (entry.second->getType() == Network::VIRTUAL) {
552 VirtualNetwork* virtualNetwork = static_cast<VirtualNetwork*>(entry.second);
553 if (virtualNetwork->appliesToUser(uid)) {
554 return virtualNetwork;
561 Permission NetworkController::getPermissionForUserLocked(uid_t uid) const {
562 auto iter = mUsers.find(uid);
563 if (iter != mUsers.end()) {
566 return uid < FIRST_APPLICATION_UID ? PERMISSION_SYSTEM : PERMISSION_NONE;
569 int NetworkController::checkUserNetworkAccessLocked(uid_t uid, unsigned netId) const {
570 Network* network = getNetworkLocked(netId);
575 // If uid is INVALID_UID, this likely means that we were unable to retrieve the UID of the peer
576 // (using SO_PEERCRED). Be safe and deny access to the network, even if it's valid.
577 if (uid == INVALID_UID) {
580 Permission userPermission = getPermissionForUserLocked(uid);
581 if ((userPermission & PERMISSION_SYSTEM) == PERMISSION_SYSTEM) {
584 if (network->getType() == Network::VIRTUAL) {
585 return static_cast<VirtualNetwork*>(network)->appliesToUser(uid) ? 0 : -EPERM;
587 VirtualNetwork* virtualNetwork = getVirtualNetworkForUserLocked(uid);
588 if (virtualNetwork && virtualNetwork->isSecure() &&
589 mProtectableUsers.find(uid) == mProtectableUsers.end()) {
592 Permission networkPermission = static_cast<PhysicalNetwork*>(network)->getPermission();
593 return ((userPermission & networkPermission) == networkPermission) ? 0 : -EACCES;
596 int NetworkController::modifyRoute(unsigned netId, const char* interface, const char* destination,
597 const char* nexthop, bool add, bool legacy, uid_t uid) {
598 if (!isValidNetwork(netId)) {
599 ALOGE("no such netId %u", netId);
602 unsigned existingNetId = getNetworkForInterface(interface);
603 if (existingNetId == NETID_UNSET) {
604 ALOGE("interface %s not assigned to any netId", interface);
607 if (existingNetId != netId) {
608 ALOGE("interface %s assigned to netId %u, not %u", interface, existingNetId, netId);
612 RouteController::TableType tableType;
613 if (netId == LOCAL_NET_ID) {
614 tableType = RouteController::LOCAL_NETWORK;
616 if ((getPermissionForUser(uid) & PERMISSION_SYSTEM) == PERMISSION_SYSTEM) {
617 tableType = RouteController::LEGACY_SYSTEM;
619 tableType = RouteController::LEGACY_NETWORK;
622 tableType = RouteController::INTERFACE;
625 return add ? RouteController::addRoute(interface, destination, nexthop, tableType) :
626 RouteController::removeRoute(interface, destination, nexthop, tableType);
629 int NetworkController::modifyFallthroughLocked(unsigned vpnNetId, bool add) {
630 if (mDefaultNetId == NETID_UNSET) {
633 Network* network = getNetworkLocked(mDefaultNetId);
635 ALOGE("cannot find previously set default network with netId %u", mDefaultNetId);
638 if (network->getType() != Network::PHYSICAL) {
639 ALOGE("inconceivable! default network must be a physical network");
642 Permission permission = static_cast<PhysicalNetwork*>(network)->getPermission();
643 for (const auto& physicalInterface : network->getInterfaces()) {
644 if (int ret = mDelegateImpl->modifyFallthrough(vpnNetId, physicalInterface, permission,