1 /*
2  * Copyright (C) 2014 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 // 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 //
22 // 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.
25 
26 #include "NetworkController.h"
27 
28 #define LOG_TAG "Netd"
29 #include "log/log.h"
30 
31 #include <android-base/strings.h>
32 
33 #include "cutils/misc.h"
34 #include "resolv_netid.h"
35 
36 #include "Controllers.h"
37 #include "DummyNetwork.h"
38 #include "DumpWriter.h"
39 #include "Fwmark.h"
40 #include "LocalNetwork.h"
41 #include "PhysicalNetwork.h"
42 #include "RouteController.h"
43 #include "VirtualNetwork.h"
44 
45 #define DBG 0
46 
47 namespace android {
48 namespace net {
49 
50 namespace {
51 
52 // Keep these in sync with ConnectivityService.java.
53 const unsigned MIN_NET_ID = 100;
54 const unsigned MAX_NET_ID = 65535;
55 
56 }  // namespace
57 
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;
63 
64 // All calls to methods here are made while holding a write lock on mRWLock.
65 // 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.
72 class NetworkController::DelegateImpl : public PhysicalNetwork::Delegate {
73 public:
74     explicit DelegateImpl(NetworkController* networkController);
75     virtual ~DelegateImpl();
76 
77     int modifyFallthrough(unsigned vpnNetId, const std::string& physicalInterface,
78                           Permission permission, bool add) WARN_UNUSED_RESULT;
79 
80 private:
81     int addFallthrough(const std::string& physicalInterface,
82                        Permission permission) override WARN_UNUSED_RESULT;
83     int removeFallthrough(const std::string& physicalInterface,
84                           Permission permission) override WARN_UNUSED_RESULT;
85 
86     int modifyFallthrough(const std::string& physicalInterface, Permission permission,
87                           bool add) WARN_UNUSED_RESULT;
88 
89     NetworkController* const mNetworkController;
90 };
91 
DelegateImpl(NetworkController * networkController)92 NetworkController::DelegateImpl::DelegateImpl(NetworkController* networkController) :
93         mNetworkController(networkController) {
94 }
95 
~DelegateImpl()96 NetworkController::DelegateImpl::~DelegateImpl() {
97 }
98 
modifyFallthrough(unsigned vpnNetId,const std::string & physicalInterface,Permission permission,bool add)99 int 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 
addFallthrough(const std::string & physicalInterface,Permission permission)122 int NetworkController::DelegateImpl::addFallthrough(const std::string& physicalInterface,
123                                                     Permission permission) {
124     return modifyFallthrough(physicalInterface, permission, true);
125 }
126 
removeFallthrough(const std::string & physicalInterface,Permission permission)127 int NetworkController::DelegateImpl::removeFallthrough(const std::string& physicalInterface,
128                                                        Permission permission) {
129     return modifyFallthrough(physicalInterface, permission, false);
130 }
131 
modifyFallthrough(const std::string & physicalInterface,Permission permission,bool add)132 int NetworkController::DelegateImpl::modifyFallthrough(const std::string& physicalInterface,
133                                                        Permission permission, bool add) {
134     for (const auto& entry : mNetworkController->mNetworks) {
135         if (entry.second->getType() == Network::VIRTUAL) {
136             if (int ret = modifyFallthrough(entry.first, physicalInterface, permission, add)) {
137                 return ret;
138             }
139         }
140     }
141     return 0;
142 }
143 
NetworkController()144 NetworkController::NetworkController() :
145         mDelegateImpl(new NetworkController::DelegateImpl(this)), mDefaultNetId(NETID_UNSET),
146         mProtectableUsers({AID_VPN}) {
147     mNetworks[LOCAL_NET_ID] = new LocalNetwork(LOCAL_NET_ID);
148     mNetworks[DUMMY_NET_ID] = new DummyNetwork(DUMMY_NET_ID);
149 }
150 
getDefaultNetwork() const151 unsigned NetworkController::getDefaultNetwork() const {
152     android::RWLock::AutoRLock lock(mRWLock);
153     return mDefaultNetId;
154 }
155 
setDefaultNetwork(unsigned netId)156 int NetworkController::setDefaultNetwork(unsigned netId) {
157     android::RWLock::AutoWLock lock(mRWLock);
158 
159     if (netId == mDefaultNetId) {
160         return 0;
161     }
162 
163     if (netId != NETID_UNSET) {
164         Network* network = getNetworkLocked(netId);
165         if (!network) {
166             ALOGE("no such netId %u", netId);
167             return -ENONET;
168         }
169         if (network->getType() != Network::PHYSICAL) {
170             ALOGE("cannot set default to non-physical network with netId %u", netId);
171             return -EINVAL;
172         }
173         if (int ret = static_cast<PhysicalNetwork*>(network)->addAsDefault()) {
174             return ret;
175         }
176     }
177 
178     if (mDefaultNetId != NETID_UNSET) {
179         Network* network = getNetworkLocked(mDefaultNetId);
180         if (!network || network->getType() != Network::PHYSICAL) {
181             ALOGE("cannot find previously set default network with netId %u", mDefaultNetId);
182             return -ESRCH;
183         }
184         if (int ret = static_cast<PhysicalNetwork*>(network)->removeAsDefault()) {
185             return ret;
186         }
187     }
188 
189     mDefaultNetId = netId;
190     return 0;
191 }
192 
getNetworkForDnsLocked(unsigned * netId,uid_t uid) const193 uint32_t NetworkController::getNetworkForDnsLocked(unsigned* netId, uid_t uid) const {
194     Fwmark fwmark;
195     fwmark.protectedFromVpn = true;
196     fwmark.permission = PERMISSION_SYSTEM;
197 
198     // Common case: there is no VPN that applies to the user, and the query did not specify a netId.
199     // Therefore, it is safe to set the explicit bit on this query and skip all the complex logic
200     // below. While this looks like a special case, it is actually the one that handles the vast
201     // majority of DNS queries.
202     // TODO: untangle this code.
203     if (*netId == NETID_UNSET && getVirtualNetworkForUserLocked(uid) == nullptr) {
204         *netId = mDefaultNetId;
205         fwmark.netId = *netId;
206         fwmark.explicitlySelected = true;
207         return fwmark.intValue;
208     }
209 
210     if (checkUserNetworkAccessLocked(uid, *netId) == 0) {
211         // If a non-zero NetId was explicitly specified, and the user has permission for that
212         // network, use that network's DNS servers. Do not fall through to the default network even
213         // if the explicitly selected network is a split tunnel VPN: the explicitlySelected bit
214         // ensures that the VPN fallthrough rule does not match.
215         fwmark.explicitlySelected = true;
216 
217         // If the network is a VPN and it doesn't have DNS servers, use the default network's DNS
218         // servers (through the default network). Otherwise, the query is guaranteed to fail.
219         // http://b/29498052
220         Network *network = getNetworkLocked(*netId);
221         if (network && network->getType() == Network::VIRTUAL &&
222                 !static_cast<VirtualNetwork *>(network)->getHasDns()) {
223             *netId = mDefaultNetId;
224         }
225     } else {
226         // If the user is subject to a VPN and the VPN provides DNS servers, use those servers
227         // (possibly falling through to the default network if the VPN doesn't provide a route to
228         // them). Otherwise, use the default network's DNS servers. We cannot set the explicit bit
229         // because we need to be able to fall through a split tunnel to the default network.
230         VirtualNetwork* virtualNetwork = getVirtualNetworkForUserLocked(uid);
231         if (virtualNetwork && virtualNetwork->getHasDns()) {
232             *netId = virtualNetwork->getNetId();
233         } else {
234             // TODO: return an error instead of silently doing the DNS lookup on the wrong network.
235             // http://b/27560555
236             *netId = mDefaultNetId;
237         }
238     }
239     fwmark.netId = *netId;
240     return fwmark.intValue;
241 }
242 
getNetworkForDns(unsigned * netId,uid_t uid) const243 uint32_t NetworkController::getNetworkForDns(unsigned* netId, uid_t uid) const {
244     android::RWLock::AutoRLock lock(mRWLock);
245     return getNetworkForDnsLocked(netId, uid);
246 }
247 
248 // Returns the NetId that a given UID would use if no network is explicitly selected. Specifically,
249 // the VPN that applies to the UID if any; otherwise, the default network.
getNetworkForUser(uid_t uid) const250 unsigned NetworkController::getNetworkForUser(uid_t uid) const {
251     android::RWLock::AutoRLock lock(mRWLock);
252     if (VirtualNetwork* virtualNetwork = getVirtualNetworkForUserLocked(uid)) {
253         return virtualNetwork->getNetId();
254     }
255     return mDefaultNetId;
256 }
257 
258 // Returns the NetId that will be set when a socket connect()s. This is the bypassable VPN that
259 // applies to the user if any; otherwise, the default network.
260 //
261 // In general, we prefer to always set the default network's NetId in connect(), so that if the VPN
262 // is a split-tunnel and disappears later, the socket continues working (since the default network's
263 // NetId is still valid). Secure VPNs will correctly grab the socket's traffic since they have a
264 // high-priority routing rule that doesn't care what NetId the socket has.
265 //
266 // But bypassable VPNs have a very low priority rule, so we need to mark the socket with the
267 // bypassable VPN's NetId if we expect it to get any traffic at all. If the bypassable VPN is a
268 // split-tunnel, that's okay, because we have fallthrough rules that will direct the fallthrough
269 // traffic to the default network. But it does mean that if the bypassable VPN goes away (and thus
270 // the fallthrough rules also go away), the socket that used to fallthrough to the default network
271 // will stop working.
getNetworkForConnectLocked(uid_t uid) const272 unsigned NetworkController::getNetworkForConnectLocked(uid_t uid) const {
273     VirtualNetwork* virtualNetwork = getVirtualNetworkForUserLocked(uid);
274     if (virtualNetwork && !virtualNetwork->isSecure()) {
275         return virtualNetwork->getNetId();
276     }
277     return mDefaultNetId;
278 }
279 
getNetworkForConnect(uid_t uid) const280 unsigned NetworkController::getNetworkForConnect(uid_t uid) const {
281     android::RWLock::AutoRLock lock(mRWLock);
282     return getNetworkForConnectLocked(uid);
283 }
284 
getNetworkContext(unsigned netId,uid_t uid,struct android_net_context * netcontext) const285 void NetworkController::getNetworkContext(
286         unsigned netId, uid_t uid, struct android_net_context* netcontext) const {
287     android::RWLock::AutoRLock lock(mRWLock);
288 
289     struct android_net_context nc = {
290             .app_netid = netId,
291             .app_mark = MARK_UNSET,
292             .dns_netid = netId,
293             .dns_mark = MARK_UNSET,
294             .uid = uid,
295     };
296 
297     // |netId| comes directly (via dnsproxyd) from the value returned by netIdForResolv() in the
298     // client process. This value is nonzero iff.:
299     //
300     // 1. The app specified a netid/nethandle to a DNS resolution method such as:
301     //        - [Java] android.net.Network#getAllByName()
302     //        - [C/++] android_getaddrinfofornetwork()
303     // 2. The app specified a netid/nethandle to be used as a process default via:
304     //        - [Java] android.net.ConnectivityManager#bindProcessToNetwork()
305     //        - [C/++] android_setprocnetwork()
306     // 3. The app called android.net.ConnectivityManager#startUsingNetworkFeature().
307     //
308     // In all these cases (with the possible exception of #3), the right thing to do is to treat
309     // such cases as explicitlySelected.
310     const bool explicitlySelected = (nc.app_netid != NETID_UNSET);
311     if (!explicitlySelected) {
312         nc.app_netid = getNetworkForConnectLocked(uid);
313     }
314 
315     Fwmark fwmark;
316     fwmark.netId = nc.app_netid;
317     fwmark.explicitlySelected = explicitlySelected;
318     fwmark.protectedFromVpn = explicitlySelected && canProtectLocked(uid);
319     fwmark.permission = getPermissionForUserLocked(uid);
320     nc.app_mark = fwmark.intValue;
321 
322     nc.dns_mark = getNetworkForDnsLocked(&(nc.dns_netid), uid);
323 
324     if (DBG) {
325         ALOGD("app_netid:0x%x app_mark:0x%x dns_netid:0x%x dns_mark:0x%x uid:%d",
326               nc.app_netid, nc.app_mark, nc.dns_netid, nc.dns_mark, uid);
327     }
328 
329     if (netcontext) {
330         *netcontext = nc;
331     }
332 }
333 
getNetworkForInterfaceLocked(const char * interface) const334 unsigned NetworkController::getNetworkForInterfaceLocked(const char* interface) const {
335     for (const auto& entry : mNetworks) {
336         if (entry.second->hasInterface(interface)) {
337             return entry.first;
338         }
339     }
340     return NETID_UNSET;
341 }
342 
getNetworkForInterface(const char * interface) const343 unsigned NetworkController::getNetworkForInterface(const char* interface) const {
344     android::RWLock::AutoRLock lock(mRWLock);
345     return getNetworkForInterfaceLocked(interface);
346 }
347 
isVirtualNetwork(unsigned netId) const348 bool NetworkController::isVirtualNetwork(unsigned netId) const {
349     android::RWLock::AutoRLock lock(mRWLock);
350     return isVirtualNetworkLocked(netId);
351 }
352 
isVirtualNetworkLocked(unsigned netId) const353 bool NetworkController::isVirtualNetworkLocked(unsigned netId) const {
354     Network* network = getNetworkLocked(netId);
355     return network && network->getType() == Network::VIRTUAL;
356 }
357 
createPhysicalNetworkLocked(unsigned netId,Permission permission)358 int NetworkController::createPhysicalNetworkLocked(unsigned netId, Permission permission) {
359     if (!((MIN_NET_ID <= netId && netId <= MAX_NET_ID) ||
360           (MIN_OEM_ID <= netId && netId <= MAX_OEM_ID))) {
361         ALOGE("invalid netId %u", netId);
362         return -EINVAL;
363     }
364 
365     if (isValidNetworkLocked(netId)) {
366         ALOGE("duplicate netId %u", netId);
367         return -EEXIST;
368     }
369 
370     PhysicalNetwork* physicalNetwork = new PhysicalNetwork(netId, mDelegateImpl);
371     if (int ret = physicalNetwork->setPermission(permission)) {
372         ALOGE("inconceivable! setPermission cannot fail on an empty network");
373         delete physicalNetwork;
374         return ret;
375     }
376 
377     mNetworks[netId] = physicalNetwork;
378 
379     updateTcpSocketMonitorPolling();
380 
381     return 0;
382 }
383 
createPhysicalNetwork(unsigned netId,Permission permission)384 int NetworkController::createPhysicalNetwork(unsigned netId, Permission permission) {
385     android::RWLock::AutoWLock lock(mRWLock);
386     return createPhysicalNetworkLocked(netId, permission);
387 }
388 
createPhysicalOemNetwork(Permission permission,unsigned * pNetId)389 int NetworkController::createPhysicalOemNetwork(Permission permission, unsigned *pNetId) {
390     if (pNetId == NULL) {
391         return -EINVAL;
392     }
393 
394     android::RWLock::AutoWLock lock(mRWLock);
395     for (*pNetId = MIN_OEM_ID; *pNetId <= MAX_OEM_ID; (*pNetId)++) {
396         if (!isValidNetworkLocked(*pNetId)) {
397             break;
398         }
399     }
400 
401     if (*pNetId > MAX_OEM_ID) {
402         ALOGE("No free network ID");
403         *pNetId = 0;
404         return -ENONET;
405     }
406 
407     int ret = createPhysicalNetworkLocked(*pNetId, permission);
408     if (ret) {
409         *pNetId = 0;
410     }
411 
412     return ret;
413 }
414 
createVirtualNetwork(unsigned netId,bool hasDns,bool secure)415 int NetworkController::createVirtualNetwork(unsigned netId, bool hasDns, bool secure) {
416     android::RWLock::AutoWLock lock(mRWLock);
417 
418     if (!(MIN_NET_ID <= netId && netId <= MAX_NET_ID)) {
419         ALOGE("invalid netId %u", netId);
420         return -EINVAL;
421     }
422 
423     if (isValidNetworkLocked(netId)) {
424         ALOGE("duplicate netId %u", netId);
425         return -EEXIST;
426     }
427 
428     if (int ret = modifyFallthroughLocked(netId, true)) {
429         return ret;
430     }
431     mNetworks[netId] = new VirtualNetwork(netId, hasDns, secure);
432     return 0;
433 }
434 
destroyNetwork(unsigned netId)435 int NetworkController::destroyNetwork(unsigned netId) {
436     android::RWLock::AutoWLock lock(mRWLock);
437 
438     if (netId == LOCAL_NET_ID) {
439         ALOGE("cannot destroy local network");
440         return -EINVAL;
441     }
442     if (!isValidNetworkLocked(netId)) {
443         ALOGE("no such netId %u", netId);
444         return -ENONET;
445     }
446 
447     // TODO: ioctl(SIOCKILLADDR, ...) to kill all sockets on the old network.
448 
449     Network* network = getNetworkLocked(netId);
450 
451     // If we fail to destroy a network, things will get stuck badly. Therefore, unlike most of the
452     // other network code, ignore failures and attempt to clear out as much state as possible, even
453     // if we hit an error on the way. Return the first error that we see.
454     int ret = network->clearInterfaces();
455 
456     if (mDefaultNetId == netId) {
457         if (int err = static_cast<PhysicalNetwork*>(network)->removeAsDefault()) {
458             ALOGE("inconceivable! removeAsDefault cannot fail on an empty network");
459             if (!ret) {
460                 ret = err;
461             }
462         }
463         mDefaultNetId = NETID_UNSET;
464     } else if (network->getType() == Network::VIRTUAL) {
465         if (int err = modifyFallthroughLocked(netId, false)) {
466             if (!ret) {
467                 ret = err;
468             }
469         }
470     }
471     mNetworks.erase(netId);
472     delete network;
473     _resolv_delete_cache_for_net(netId);
474 
475     for (auto iter = mIfindexToLastNetId.begin(); iter != mIfindexToLastNetId.end();) {
476         if (iter->second == netId) {
477             iter = mIfindexToLastNetId.erase(iter);
478         } else {
479             ++iter;
480         }
481     }
482 
483     updateTcpSocketMonitorPolling();
484 
485     return ret;
486 }
487 
addInterfaceToNetwork(unsigned netId,const char * interface)488 int NetworkController::addInterfaceToNetwork(unsigned netId, const char* interface) {
489     android::RWLock::AutoWLock lock(mRWLock);
490 
491     if (!isValidNetworkLocked(netId)) {
492         ALOGE("no such netId %u", netId);
493         return -ENONET;
494     }
495 
496     unsigned existingNetId = getNetworkForInterfaceLocked(interface);
497     if (existingNetId != NETID_UNSET && existingNetId != netId) {
498         ALOGE("interface %s already assigned to netId %u", interface, existingNetId);
499         return -EBUSY;
500     }
501     if (int ret = getNetworkLocked(netId)->addInterface(interface)) {
502         return ret;
503     }
504 
505     int ifIndex = RouteController::getIfIndex(interface);
506     if (ifIndex) {
507         mIfindexToLastNetId[ifIndex] = netId;
508     } else {
509         // Cannot happen, since addInterface() above will have failed.
510         ALOGE("inconceivable! added interface %s with no index", interface);
511     }
512     return 0;
513 }
514 
removeInterfaceFromNetwork(unsigned netId,const char * interface)515 int NetworkController::removeInterfaceFromNetwork(unsigned netId, const char* interface) {
516     android::RWLock::AutoWLock lock(mRWLock);
517 
518     if (!isValidNetworkLocked(netId)) {
519         ALOGE("no such netId %u", netId);
520         return -ENONET;
521     }
522 
523     return getNetworkLocked(netId)->removeInterface(interface);
524 }
525 
getPermissionForUser(uid_t uid) const526 Permission NetworkController::getPermissionForUser(uid_t uid) const {
527     android::RWLock::AutoRLock lock(mRWLock);
528     return getPermissionForUserLocked(uid);
529 }
530 
setPermissionForUsers(Permission permission,const std::vector<uid_t> & uids)531 void NetworkController::setPermissionForUsers(Permission permission,
532                                               const std::vector<uid_t>& uids) {
533     android::RWLock::AutoWLock lock(mRWLock);
534     for (uid_t uid : uids) {
535         mUsers[uid] = permission;
536     }
537 }
538 
checkUserNetworkAccess(uid_t uid,unsigned netId) const539 int NetworkController::checkUserNetworkAccess(uid_t uid, unsigned netId) const {
540     android::RWLock::AutoRLock lock(mRWLock);
541     return checkUserNetworkAccessLocked(uid, netId);
542 }
543 
setPermissionForNetworks(Permission permission,const std::vector<unsigned> & netIds)544 int NetworkController::setPermissionForNetworks(Permission permission,
545                                                 const std::vector<unsigned>& netIds) {
546     android::RWLock::AutoWLock lock(mRWLock);
547     for (unsigned netId : netIds) {
548         Network* network = getNetworkLocked(netId);
549         if (!network) {
550             ALOGE("no such netId %u", netId);
551             return -ENONET;
552         }
553         if (network->getType() != Network::PHYSICAL) {
554             ALOGE("cannot set permissions on non-physical network with netId %u", netId);
555             return -EINVAL;
556         }
557 
558         if (int ret = static_cast<PhysicalNetwork*>(network)->setPermission(permission)) {
559             return ret;
560         }
561     }
562     return 0;
563 }
564 
addUsersToNetwork(unsigned netId,const UidRanges & uidRanges)565 int NetworkController::addUsersToNetwork(unsigned netId, const UidRanges& uidRanges) {
566     android::RWLock::AutoWLock lock(mRWLock);
567     Network* network = getNetworkLocked(netId);
568     if (!network) {
569         ALOGE("no such netId %u", netId);
570         return -ENONET;
571     }
572     if (network->getType() != Network::VIRTUAL) {
573         ALOGE("cannot add users to non-virtual network with netId %u", netId);
574         return -EINVAL;
575     }
576     if (int ret = static_cast<VirtualNetwork*>(network)->addUsers(uidRanges, mProtectableUsers)) {
577         return ret;
578     }
579     return 0;
580 }
581 
removeUsersFromNetwork(unsigned netId,const UidRanges & uidRanges)582 int NetworkController::removeUsersFromNetwork(unsigned netId, const UidRanges& uidRanges) {
583     android::RWLock::AutoWLock lock(mRWLock);
584     Network* network = getNetworkLocked(netId);
585     if (!network) {
586         ALOGE("no such netId %u", netId);
587         return -ENONET;
588     }
589     if (network->getType() != Network::VIRTUAL) {
590         ALOGE("cannot remove users from non-virtual network with netId %u", netId);
591         return -EINVAL;
592     }
593     if (int ret = static_cast<VirtualNetwork*>(network)->removeUsers(uidRanges,
594                                                                      mProtectableUsers)) {
595         return ret;
596     }
597     return 0;
598 }
599 
addRoute(unsigned netId,const char * interface,const char * destination,const char * nexthop,bool legacy,uid_t uid)600 int NetworkController::addRoute(unsigned netId, const char* interface, const char* destination,
601                                 const char* nexthop, bool legacy, uid_t uid) {
602     return modifyRoute(netId, interface, destination, nexthop, true, legacy, uid);
603 }
604 
removeRoute(unsigned netId,const char * interface,const char * destination,const char * nexthop,bool legacy,uid_t uid)605 int NetworkController::removeRoute(unsigned netId, const char* interface, const char* destination,
606                                    const char* nexthop, bool legacy, uid_t uid) {
607     return modifyRoute(netId, interface, destination, nexthop, false, legacy, uid);
608 }
609 
addInterfaceAddress(unsigned ifIndex,const char * address)610 void NetworkController::addInterfaceAddress(unsigned ifIndex, const char* address) {
611     android::RWLock::AutoWLock lock(mRWLock);
612 
613     if (ifIndex == 0) {
614         ALOGE("Attempting to add address %s without ifindex", address);
615         return;
616     }
617     mAddressToIfindices[address].insert(ifIndex);
618 }
619 
620 // Returns whether we should call SOCK_DESTROY on the removed address.
removeInterfaceAddress(unsigned ifindex,const char * address)621 bool NetworkController::removeInterfaceAddress(unsigned ifindex, const char* address) {
622     android::RWLock::AutoWLock lock(mRWLock);
623     // First, update mAddressToIfindices map
624     auto ifindicesIter = mAddressToIfindices.find(address);
625     if (ifindicesIter == mAddressToIfindices.end()) {
626         ALOGE("Removing unknown address %s from ifindex %u", address, ifindex);
627         return true;
628     }
629     std::unordered_set<unsigned>& ifindices = ifindicesIter->second;
630     if (ifindices.erase(ifindex) > 0) {
631         if (ifindices.size() == 0) {
632             mAddressToIfindices.erase(ifindicesIter);
633         }
634     } else {
635         ALOGE("No record of address %s on interface %u", address, ifindex);
636         return true;
637     }
638     // Then, check for VPN handover condition
639     if (mIfindexToLastNetId.find(ifindex) == mIfindexToLastNetId.end()) {
640         ALOGE("Interface index %u was never in a currently-connected netId", ifindex);
641         return true;
642     }
643     unsigned lastNetId = mIfindexToLastNetId[ifindex];
644     for (unsigned idx : ifindices) {
645         unsigned activeNetId = mIfindexToLastNetId[idx];
646         // If this IP address is still assigned to another interface in the same network,
647         // then we don't need to destroy sockets on it because they are likely still valid.
648         // For now we do this only on VPNs.
649         // TODO: evaluate extending this to all network types.
650         if (lastNetId == activeNetId && isVirtualNetworkLocked(activeNetId)) {
651             return false;
652         }
653     }
654     return true;
655 }
656 
canProtectLocked(uid_t uid) const657 bool NetworkController::canProtectLocked(uid_t uid) const {
658     return ((getPermissionForUserLocked(uid) & PERMISSION_SYSTEM) == PERMISSION_SYSTEM) ||
659            mProtectableUsers.find(uid) != mProtectableUsers.end();
660 }
661 
canProtect(uid_t uid) const662 bool NetworkController::canProtect(uid_t uid) const {
663     android::RWLock::AutoRLock lock(mRWLock);
664     return canProtectLocked(uid);
665 }
666 
allowProtect(const std::vector<uid_t> & uids)667 void NetworkController::allowProtect(const std::vector<uid_t>& uids) {
668     android::RWLock::AutoWLock lock(mRWLock);
669     mProtectableUsers.insert(uids.begin(), uids.end());
670 }
671 
denyProtect(const std::vector<uid_t> & uids)672 void NetworkController::denyProtect(const std::vector<uid_t>& uids) {
673     android::RWLock::AutoWLock lock(mRWLock);
674     for (uid_t uid : uids) {
675         mProtectableUsers.erase(uid);
676     }
677 }
678 
dump(DumpWriter & dw)679 void NetworkController::dump(DumpWriter& dw) {
680     android::RWLock::AutoRLock lock(mRWLock);
681 
682     dw.incIndent();
683     dw.println("NetworkController");
684 
685     dw.incIndent();
686     dw.println("Default network: %u", mDefaultNetId);
687 
688     dw.blankline();
689     dw.println("Networks:");
690     dw.incIndent();
691     for (const auto& i : mNetworks) {
692         Network* network = i.second;
693         dw.println(network->toString().c_str());
694         if (network->getType() == Network::PHYSICAL) {
695             dw.incIndent();
696             Permission permission = reinterpret_cast<PhysicalNetwork*>(network)->getPermission();
697             dw.println("Required permission: %s", permissionToName(permission));
698             dw.decIndent();
699         }
700         android::net::gCtls->resolverCtrl.dump(dw, i.first);
701         dw.blankline();
702     }
703     dw.decIndent();
704 
705     dw.blankline();
706     dw.println("Interface <-> last network map:");
707     dw.incIndent();
708     for (const auto& i : mIfindexToLastNetId) {
709         dw.println("Ifindex: %u NetId: %u", i.first, i.second);
710     }
711     dw.decIndent();
712 
713     dw.blankline();
714     dw.println("Interface addresses:");
715     dw.incIndent();
716     for (const auto& i : mAddressToIfindices) {
717         dw.println("address: %s ifindices: [%s]", i.first.c_str(),
718                 android::base::Join(i.second, ", ").c_str());
719     }
720     dw.decIndent();
721 
722     dw.decIndent();
723 
724     dw.decIndent();
725 }
726 
isValidNetworkLocked(unsigned netId) const727 bool NetworkController::isValidNetworkLocked(unsigned netId) const {
728     return getNetworkLocked(netId);
729 }
730 
getNetworkLocked(unsigned netId) const731 Network* NetworkController::getNetworkLocked(unsigned netId) const {
732     auto iter = mNetworks.find(netId);
733     return iter == mNetworks.end() ? NULL : iter->second;
734 }
735 
getVirtualNetworkForUserLocked(uid_t uid) const736 VirtualNetwork* NetworkController::getVirtualNetworkForUserLocked(uid_t uid) const {
737     for (const auto& entry : mNetworks) {
738         if (entry.second->getType() == Network::VIRTUAL) {
739             VirtualNetwork* virtualNetwork = static_cast<VirtualNetwork*>(entry.second);
740             if (virtualNetwork->appliesToUser(uid)) {
741                 return virtualNetwork;
742             }
743         }
744     }
745     return NULL;
746 }
747 
getPermissionForUserLocked(uid_t uid) const748 Permission NetworkController::getPermissionForUserLocked(uid_t uid) const {
749     auto iter = mUsers.find(uid);
750     if (iter != mUsers.end()) {
751         return iter->second;
752     }
753     return uid < FIRST_APPLICATION_UID ? PERMISSION_SYSTEM : PERMISSION_NONE;
754 }
755 
checkUserNetworkAccessLocked(uid_t uid,unsigned netId) const756 int NetworkController::checkUserNetworkAccessLocked(uid_t uid, unsigned netId) const {
757     Network* network = getNetworkLocked(netId);
758     if (!network) {
759         return -ENONET;
760     }
761 
762     // If uid is INVALID_UID, this likely means that we were unable to retrieve the UID of the peer
763     // (using SO_PEERCRED). Be safe and deny access to the network, even if it's valid.
764     if (uid == INVALID_UID) {
765         return -EREMOTEIO;
766     }
767     Permission userPermission = getPermissionForUserLocked(uid);
768     if ((userPermission & PERMISSION_SYSTEM) == PERMISSION_SYSTEM) {
769         return 0;
770     }
771     if (network->getType() == Network::VIRTUAL) {
772         return static_cast<VirtualNetwork*>(network)->appliesToUser(uid) ? 0 : -EPERM;
773     }
774     VirtualNetwork* virtualNetwork = getVirtualNetworkForUserLocked(uid);
775     if (virtualNetwork && virtualNetwork->isSecure() &&
776             mProtectableUsers.find(uid) == mProtectableUsers.end()) {
777         return -EPERM;
778     }
779     Permission networkPermission = static_cast<PhysicalNetwork*>(network)->getPermission();
780     return ((userPermission & networkPermission) == networkPermission) ? 0 : -EACCES;
781 }
782 
modifyRoute(unsigned netId,const char * interface,const char * destination,const char * nexthop,bool add,bool legacy,uid_t uid)783 int NetworkController::modifyRoute(unsigned netId, const char* interface, const char* destination,
784                                    const char* nexthop, bool add, bool legacy, uid_t uid) {
785     android::RWLock::AutoRLock lock(mRWLock);
786 
787     if (!isValidNetworkLocked(netId)) {
788         ALOGE("no such netId %u", netId);
789         return -ENONET;
790     }
791     unsigned existingNetId = getNetworkForInterfaceLocked(interface);
792     if (existingNetId == NETID_UNSET) {
793         ALOGE("interface %s not assigned to any netId", interface);
794         return -ENODEV;
795     }
796     if (existingNetId != netId) {
797         ALOGE("interface %s assigned to netId %u, not %u", interface, existingNetId, netId);
798         return -ENOENT;
799     }
800 
801     RouteController::TableType tableType;
802     if (netId == LOCAL_NET_ID) {
803         tableType = RouteController::LOCAL_NETWORK;
804     } else if (legacy) {
805         if ((getPermissionForUserLocked(uid) & PERMISSION_SYSTEM) == PERMISSION_SYSTEM) {
806             tableType = RouteController::LEGACY_SYSTEM;
807         } else {
808             tableType = RouteController::LEGACY_NETWORK;
809         }
810     } else {
811         tableType = RouteController::INTERFACE;
812     }
813 
814     return add ? RouteController::addRoute(interface, destination, nexthop, tableType) :
815                  RouteController::removeRoute(interface, destination, nexthop, tableType);
816 }
817 
modifyFallthroughLocked(unsigned vpnNetId,bool add)818 int NetworkController::modifyFallthroughLocked(unsigned vpnNetId, bool add) {
819     if (mDefaultNetId == NETID_UNSET) {
820         return 0;
821     }
822     Network* network = getNetworkLocked(mDefaultNetId);
823     if (!network) {
824         ALOGE("cannot find previously set default network with netId %u", mDefaultNetId);
825         return -ESRCH;
826     }
827     if (network->getType() != Network::PHYSICAL) {
828         ALOGE("inconceivable! default network must be a physical network");
829         return -EINVAL;
830     }
831     Permission permission = static_cast<PhysicalNetwork*>(network)->getPermission();
832     for (const auto& physicalInterface : network->getInterfaces()) {
833         if (int ret = mDelegateImpl->modifyFallthrough(vpnNetId, physicalInterface, permission,
834                                                        add)) {
835             return ret;
836         }
837     }
838     return 0;
839 }
840 
updateTcpSocketMonitorPolling()841 void NetworkController::updateTcpSocketMonitorPolling() {
842     bool physicalNetworkExists = false;
843     for (const auto& entry : mNetworks) {
844         const auto& network = entry.second;
845         if (network->getType() == Network::PHYSICAL && network->getNetId() >= MIN_NET_ID) {
846             physicalNetworkExists = true;
847             break;
848         }
849     }
850 
851     if (physicalNetworkExists) {
852         android::net::gCtls->tcpSocketMonitor.resumePolling();
853     } else {
854         android::net::gCtls->tcpSocketMonitor.suspendPolling();
855     }
856 }
857 
858 }  // namespace net
859 }  // namespace android
860