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