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