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 #include "DummyNetwork.h"
37 #include "LocalNetwork.h"
38 #include "PhysicalNetwork.h"
39 #include "RouteController.h"
40 #include "VirtualNetwork.h"
42 #include "cutils/misc.h"
43 #define LOG_TAG "Netd"
45 #include "resolv_netid.h"
49 // Keep these in sync with ConnectivityService.java.
50 const unsigned MIN_NET_ID = 100;
51 const unsigned MAX_NET_ID = 65535;
55 const unsigned NetworkController::MIN_OEM_ID = 1;
56 const unsigned NetworkController::MAX_OEM_ID = 50;
57 const unsigned NetworkController::DUMMY_NET_ID = 51;
58 // NetIds 52..98 are reserved for future use.
59 const unsigned NetworkController::LOCAL_NET_ID = 99;
61 // All calls to methods here are made while holding a write lock on mRWLock.
62 class NetworkController::DelegateImpl : public PhysicalNetwork::Delegate {
64 explicit DelegateImpl(NetworkController* networkController);
65 virtual ~DelegateImpl();
67 int modifyFallthrough(unsigned vpnNetId, const std::string& physicalInterface,
68 Permission permission, bool add) WARN_UNUSED_RESULT;
71 int addFallthrough(const std::string& physicalInterface,
72 Permission permission) override WARN_UNUSED_RESULT;
73 int removeFallthrough(const std::string& physicalInterface,
74 Permission permission) override WARN_UNUSED_RESULT;
76 int modifyFallthrough(const std::string& physicalInterface, Permission permission,
77 bool add) WARN_UNUSED_RESULT;
79 NetworkController* const mNetworkController;
82 NetworkController::DelegateImpl::DelegateImpl(NetworkController* networkController) :
83 mNetworkController(networkController) {
86 NetworkController::DelegateImpl::~DelegateImpl() {
89 int NetworkController::DelegateImpl::modifyFallthrough(unsigned vpnNetId,
90 const std::string& physicalInterface,
91 Permission permission, bool add) {
93 if (int ret = RouteController::addVirtualNetworkFallthrough(vpnNetId,
94 physicalInterface.c_str(),
96 ALOGE("failed to add fallthrough to %s for VPN netId %u", physicalInterface.c_str(),
101 if (int ret = RouteController::removeVirtualNetworkFallthrough(vpnNetId,
102 physicalInterface.c_str(),
104 ALOGE("failed to remove fallthrough to %s for VPN netId %u", physicalInterface.c_str(),
112 int NetworkController::DelegateImpl::addFallthrough(const std::string& physicalInterface,
113 Permission permission) {
114 return modifyFallthrough(physicalInterface, permission, true);
117 int NetworkController::DelegateImpl::removeFallthrough(const std::string& physicalInterface,
118 Permission permission) {
119 return modifyFallthrough(physicalInterface, permission, false);
122 int NetworkController::DelegateImpl::modifyFallthrough(const std::string& physicalInterface,
123 Permission permission, bool add) {
124 for (const auto& entry : mNetworkController->mNetworks) {
125 if (entry.second->getType() == Network::VIRTUAL) {
126 if (int ret = modifyFallthrough(entry.first, physicalInterface, permission, add)) {
134 NetworkController::NetworkController() :
135 mDelegateImpl(new NetworkController::DelegateImpl(this)), mDefaultNetId(NETID_UNSET) {
136 mNetworks[LOCAL_NET_ID] = new LocalNetwork(LOCAL_NET_ID);
137 mNetworks[DUMMY_NET_ID] = new DummyNetwork(DUMMY_NET_ID);
140 unsigned NetworkController::getDefaultNetwork() const {
141 android::RWLock::AutoRLock lock(mRWLock);
142 return mDefaultNetId;
145 int NetworkController::setDefaultNetwork(unsigned netId) {
146 android::RWLock::AutoWLock lock(mRWLock);
148 if (netId == mDefaultNetId) {
152 if (netId != NETID_UNSET) {
153 Network* network = getNetworkLocked(netId);
155 ALOGE("no such netId %u", netId);
158 if (network->getType() != Network::PHYSICAL) {
159 ALOGE("cannot set default to non-physical network with netId %u", netId);
162 if (int ret = static_cast<PhysicalNetwork*>(network)->addAsDefault()) {
167 if (mDefaultNetId != NETID_UNSET) {
168 Network* network = getNetworkLocked(mDefaultNetId);
169 if (!network || network->getType() != Network::PHYSICAL) {
170 ALOGE("cannot find previously set default network with netId %u", mDefaultNetId);
173 if (int ret = static_cast<PhysicalNetwork*>(network)->removeAsDefault()) {
178 mDefaultNetId = netId;
182 uint32_t NetworkController::getNetworkForDns(unsigned* netId, uid_t uid) const {
183 android::RWLock::AutoRLock lock(mRWLock);
185 fwmark.protectedFromVpn = true;
186 fwmark.permission = PERMISSION_SYSTEM;
187 if (checkUserNetworkAccessLocked(uid, *netId) == 0) {
188 // If a non-zero NetId was explicitly specified, and the user has permission for that
189 // network, use that network's DNS servers. Do not fall through to the default network even
190 // if the explicitly selected network is a split tunnel VPN or a VPN without DNS servers.
191 fwmark.explicitlySelected = true;
193 // If the user is subject to a VPN and the VPN provides DNS servers, use those servers
194 // (possibly falling through to the default network if the VPN doesn't provide a route to
195 // them). Otherwise, use the default network's DNS servers.
196 VirtualNetwork* virtualNetwork = getVirtualNetworkForUserLocked(uid);
197 if (virtualNetwork && virtualNetwork->getHasDns()) {
198 *netId = virtualNetwork->getNetId();
200 *netId = mDefaultNetId;
203 fwmark.netId = *netId;
204 return fwmark.intValue;
207 // Returns the NetId that a given UID would use if no network is explicitly selected. Specifically,
208 // the VPN that applies to the UID if any; otherwise, the default network.
209 unsigned NetworkController::getNetworkForUser(uid_t uid) const {
210 android::RWLock::AutoRLock lock(mRWLock);
211 if (VirtualNetwork* virtualNetwork = getVirtualNetworkForUserLocked(uid)) {
212 return virtualNetwork->getNetId();
214 return mDefaultNetId;
217 // Returns the NetId that will be set when a socket connect()s. This is the bypassable VPN that
218 // applies to the user if any; otherwise, the default network.
220 // In general, we prefer to always set the default network's NetId in connect(), so that if the VPN
221 // is a split-tunnel and disappears later, the socket continues working (since the default network's
222 // NetId is still valid). Secure VPNs will correctly grab the socket's traffic since they have a
223 // high-priority routing rule that doesn't care what NetId the socket has.
225 // But bypassable VPNs have a very low priority rule, so we need to mark the socket with the
226 // bypassable VPN's NetId if we expect it to get any traffic at all. If the bypassable VPN is a
227 // split-tunnel, that's okay, because we have fallthrough rules that will direct the fallthrough
228 // traffic to the default network. But it does mean that if the bypassable VPN goes away (and thus
229 // the fallthrough rules also go away), the socket that used to fallthrough to the default network
230 // will stop working.
231 unsigned NetworkController::getNetworkForConnect(uid_t uid) const {
232 android::RWLock::AutoRLock lock(mRWLock);
233 VirtualNetwork* virtualNetwork = getVirtualNetworkForUserLocked(uid);
234 if (virtualNetwork && !virtualNetwork->isSecure()) {
235 return virtualNetwork->getNetId();
237 return mDefaultNetId;
240 void NetworkController::getNetworkContext(
241 unsigned netId, uid_t uid, struct android_net_context* netcontext) const {
242 struct android_net_context nc = {
244 .app_mark = MARK_UNSET,
246 .dns_mark = MARK_UNSET,
250 // |netId| comes directly (via dnsproxyd) from the value returned by netIdForResolv() in the
251 // client process. This value is nonzero iff.:
253 // 1. The app specified a netid/nethandle to a DNS resolution method such as:
254 // - [Java] android.net.Network#getAllByName()
255 // - [C/++] android_getaddrinfofornetwork()
256 // 2. The app specified a netid/nethandle to be used as a process default via:
257 // - [Java] android.net.ConnectivityManager#bindProcessToNetwork()
258 // - [C/++] android_setprocnetwork()
259 // 3. The app called android.net.ConnectivityManager#startUsingNetworkFeature().
261 // In all these cases (with the possible exception of #3), the right thing to do is to treat
262 // such cases as explicitlySelected.
263 const bool explicitlySelected = (nc.app_netid != NETID_UNSET);
264 if (!explicitlySelected) {
265 nc.app_netid = getNetworkForConnect(uid);
269 fwmark.netId = nc.app_netid;
270 fwmark.explicitlySelected = explicitlySelected;
271 fwmark.protectedFromVpn = canProtect(uid);
272 fwmark.permission = getPermissionForUser(uid);
273 nc.app_mark = fwmark.intValue;
275 nc.dns_mark = getNetworkForDns(&(nc.dns_netid), uid);
282 unsigned NetworkController::getNetworkForInterface(const char* interface) const {
283 android::RWLock::AutoRLock lock(mRWLock);
284 for (const auto& entry : mNetworks) {
285 if (entry.second->hasInterface(interface)) {
292 bool NetworkController::isVirtualNetwork(unsigned netId) const {
293 android::RWLock::AutoRLock lock(mRWLock);
294 Network* network = getNetworkLocked(netId);
295 return network && network->getType() == Network::VIRTUAL;
298 int NetworkController::createPhysicalNetwork(unsigned netId, Permission permission) {
299 if (!((MIN_NET_ID <= netId && netId <= MAX_NET_ID) ||
300 (MIN_OEM_ID <= netId && netId <= MAX_OEM_ID))) {
301 ALOGE("invalid netId %u", netId);
305 if (isValidNetwork(netId)) {
306 ALOGE("duplicate netId %u", netId);
310 PhysicalNetwork* physicalNetwork = new PhysicalNetwork(netId, mDelegateImpl);
311 if (int ret = physicalNetwork->setPermission(permission)) {
312 ALOGE("inconceivable! setPermission cannot fail on an empty network");
313 delete physicalNetwork;
317 android::RWLock::AutoWLock lock(mRWLock);
318 mNetworks[netId] = physicalNetwork;
322 int NetworkController::createVirtualNetwork(unsigned netId, bool hasDns, bool secure) {
323 if (!(MIN_NET_ID <= netId && netId <= MAX_NET_ID)) {
324 ALOGE("invalid netId %u", netId);
328 if (isValidNetwork(netId)) {
329 ALOGE("duplicate netId %u", netId);
333 android::RWLock::AutoWLock lock(mRWLock);
334 if (int ret = modifyFallthroughLocked(netId, true)) {
337 mNetworks[netId] = new VirtualNetwork(netId, hasDns, secure);
341 int NetworkController::destroyNetwork(unsigned netId) {
342 if (netId == LOCAL_NET_ID) {
343 ALOGE("cannot destroy local network");
346 if (!isValidNetwork(netId)) {
347 ALOGE("no such netId %u", netId);
351 // TODO: ioctl(SIOCKILLADDR, ...) to kill all sockets on the old network.
353 android::RWLock::AutoWLock lock(mRWLock);
354 Network* network = getNetworkLocked(netId);
356 // If we fail to destroy a network, things will get stuck badly. Therefore, unlike most of the
357 // other network code, ignore failures and attempt to clear out as much state as possible, even
358 // if we hit an error on the way. Return the first error that we see.
359 int ret = network->clearInterfaces();
361 if (mDefaultNetId == netId) {
362 if (int err = static_cast<PhysicalNetwork*>(network)->removeAsDefault()) {
363 ALOGE("inconceivable! removeAsDefault cannot fail on an empty network");
368 mDefaultNetId = NETID_UNSET;
369 } else if (network->getType() == Network::VIRTUAL) {
370 if (int err = modifyFallthroughLocked(netId, false)) {
376 mNetworks.erase(netId);
378 _resolv_delete_cache_for_net(netId);
382 int NetworkController::addInterfaceToNetwork(unsigned netId, const char* interface) {
383 if (!isValidNetwork(netId)) {
384 ALOGE("no such netId %u", netId);
388 unsigned existingNetId = getNetworkForInterface(interface);
389 if (existingNetId != NETID_UNSET && existingNetId != netId) {
390 ALOGE("interface %s already assigned to netId %u", interface, existingNetId);
394 android::RWLock::AutoWLock lock(mRWLock);
395 return getNetworkLocked(netId)->addInterface(interface);
398 int NetworkController::removeInterfaceFromNetwork(unsigned netId, const char* interface) {
399 if (!isValidNetwork(netId)) {
400 ALOGE("no such netId %u", netId);
404 android::RWLock::AutoWLock lock(mRWLock);
405 return getNetworkLocked(netId)->removeInterface(interface);
408 Permission NetworkController::getPermissionForUser(uid_t uid) const {
409 android::RWLock::AutoRLock lock(mRWLock);
410 return getPermissionForUserLocked(uid);
413 void NetworkController::setPermissionForUsers(Permission permission,
414 const std::vector<uid_t>& uids) {
415 android::RWLock::AutoWLock lock(mRWLock);
416 for (uid_t uid : uids) {
417 mUsers[uid] = permission;
421 int NetworkController::checkUserNetworkAccess(uid_t uid, unsigned netId) const {
422 android::RWLock::AutoRLock lock(mRWLock);
423 return checkUserNetworkAccessLocked(uid, netId);
426 int NetworkController::setPermissionForNetworks(Permission permission,
427 const std::vector<unsigned>& netIds) {
428 android::RWLock::AutoWLock lock(mRWLock);
429 for (unsigned netId : netIds) {
430 Network* network = getNetworkLocked(netId);
432 ALOGE("no such netId %u", netId);
435 if (network->getType() != Network::PHYSICAL) {
436 ALOGE("cannot set permissions on non-physical network with netId %u", netId);
440 // TODO: ioctl(SIOCKILLADDR, ...) to kill socets on the network that don't have permission.
442 if (int ret = static_cast<PhysicalNetwork*>(network)->setPermission(permission)) {
449 int NetworkController::addUsersToNetwork(unsigned netId, const UidRanges& uidRanges) {
450 android::RWLock::AutoWLock lock(mRWLock);
451 Network* network = getNetworkLocked(netId);
453 ALOGE("no such netId %u", netId);
456 if (network->getType() != Network::VIRTUAL) {
457 ALOGE("cannot add users to non-virtual network with netId %u", netId);
460 if (int ret = static_cast<VirtualNetwork*>(network)->addUsers(uidRanges)) {
466 int NetworkController::removeUsersFromNetwork(unsigned netId, const UidRanges& uidRanges) {
467 android::RWLock::AutoWLock lock(mRWLock);
468 Network* network = getNetworkLocked(netId);
470 ALOGE("no such netId %u", netId);
473 if (network->getType() != Network::VIRTUAL) {
474 ALOGE("cannot remove users from non-virtual network with netId %u", netId);
477 if (int ret = static_cast<VirtualNetwork*>(network)->removeUsers(uidRanges)) {
483 int NetworkController::addRoute(unsigned netId, const char* interface, const char* destination,
484 const char* nexthop, bool legacy, uid_t uid) {
485 return modifyRoute(netId, interface, destination, nexthop, true, legacy, uid);
488 int NetworkController::removeRoute(unsigned netId, const char* interface, const char* destination,
489 const char* nexthop, bool legacy, uid_t uid) {
490 return modifyRoute(netId, interface, destination, nexthop, false, legacy, uid);
493 bool NetworkController::canProtect(uid_t uid) const {
494 android::RWLock::AutoRLock lock(mRWLock);
495 return ((getPermissionForUserLocked(uid) & PERMISSION_SYSTEM) == PERMISSION_SYSTEM) ||
496 mProtectableUsers.find(uid) != mProtectableUsers.end();
499 void NetworkController::allowProtect(const std::vector<uid_t>& uids) {
500 android::RWLock::AutoWLock lock(mRWLock);
501 mProtectableUsers.insert(uids.begin(), uids.end());
504 void NetworkController::denyProtect(const std::vector<uid_t>& uids) {
505 android::RWLock::AutoWLock lock(mRWLock);
506 for (uid_t uid : uids) {
507 mProtectableUsers.erase(uid);
511 bool NetworkController::isValidNetwork(unsigned netId) const {
512 android::RWLock::AutoRLock lock(mRWLock);
513 return getNetworkLocked(netId);
516 Network* NetworkController::getNetworkLocked(unsigned netId) const {
517 auto iter = mNetworks.find(netId);
518 return iter == mNetworks.end() ? NULL : iter->second;
521 VirtualNetwork* NetworkController::getVirtualNetworkForUserLocked(uid_t uid) const {
522 for (const auto& entry : mNetworks) {
523 if (entry.second->getType() == Network::VIRTUAL) {
524 VirtualNetwork* virtualNetwork = static_cast<VirtualNetwork*>(entry.second);
525 if (virtualNetwork->appliesToUser(uid)) {
526 return virtualNetwork;
533 Permission NetworkController::getPermissionForUserLocked(uid_t uid) const {
534 auto iter = mUsers.find(uid);
535 if (iter != mUsers.end()) {
538 return uid < FIRST_APPLICATION_UID ? PERMISSION_SYSTEM : PERMISSION_NONE;
541 int NetworkController::checkUserNetworkAccessLocked(uid_t uid, unsigned netId) const {
542 Network* network = getNetworkLocked(netId);
547 // If uid is INVALID_UID, this likely means that we were unable to retrieve the UID of the peer
548 // (using SO_PEERCRED). Be safe and deny access to the network, even if it's valid.
549 if (uid == INVALID_UID) {
552 Permission userPermission = getPermissionForUserLocked(uid);
553 if ((userPermission & PERMISSION_SYSTEM) == PERMISSION_SYSTEM) {
556 if (network->getType() == Network::VIRTUAL) {
557 return static_cast<VirtualNetwork*>(network)->appliesToUser(uid) ? 0 : -EPERM;
559 VirtualNetwork* virtualNetwork = getVirtualNetworkForUserLocked(uid);
560 if (virtualNetwork && virtualNetwork->isSecure() &&
561 mProtectableUsers.find(uid) == mProtectableUsers.end()) {
564 Permission networkPermission = static_cast<PhysicalNetwork*>(network)->getPermission();
565 return ((userPermission & networkPermission) == networkPermission) ? 0 : -EACCES;
568 int NetworkController::modifyRoute(unsigned netId, const char* interface, const char* destination,
569 const char* nexthop, bool add, bool legacy, uid_t uid) {
570 if (!isValidNetwork(netId)) {
571 ALOGE("no such netId %u", netId);
574 unsigned existingNetId = getNetworkForInterface(interface);
575 if (existingNetId == NETID_UNSET) {
576 ALOGE("interface %s not assigned to any netId", interface);
579 if (existingNetId != netId) {
580 ALOGE("interface %s assigned to netId %u, not %u", interface, existingNetId, netId);
584 RouteController::TableType tableType;
585 if (netId == LOCAL_NET_ID) {
586 tableType = RouteController::LOCAL_NETWORK;
588 if ((getPermissionForUser(uid) & PERMISSION_SYSTEM) == PERMISSION_SYSTEM) {
589 tableType = RouteController::LEGACY_SYSTEM;
591 tableType = RouteController::LEGACY_NETWORK;
594 tableType = RouteController::INTERFACE;
597 return add ? RouteController::addRoute(interface, destination, nexthop, tableType) :
598 RouteController::removeRoute(interface, destination, nexthop, tableType);
601 int NetworkController::modifyFallthroughLocked(unsigned vpnNetId, bool add) {
602 if (mDefaultNetId == NETID_UNSET) {
605 Network* network = getNetworkLocked(mDefaultNetId);
607 ALOGE("cannot find previously set default network with netId %u", mDefaultNetId);
610 if (network->getType() != Network::PHYSICAL) {
611 ALOGE("inconceivable! default network must be a physical network");
614 Permission permission = static_cast<PhysicalNetwork*>(network)->getPermission();
615 for (const auto& physicalInterface : network->getInterfaces()) {
616 if (int ret = mDelegateImpl->modifyFallthrough(vpnNetId, physicalInterface, permission,