• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 // In some cases, a single non-const method acquires and releases the lock several times, like so:
23 //     if (isValidNetwork(...)) {  // isValidNetwork() acquires and releases the lock.
24 //        setDefaultNetwork(...);  // setDefaultNetwork() also acquires and releases the lock.
25 //
26 // It might seem that this allows races where the state changes between the two statements, but in
27 // fact there are no races because:
28 //     1. This pattern only occurs in non-const methods (i.e., those that mutate state).
29 //     2. Only CommandListener calls these non-const methods. The others call only const methods.
30 //     3. CommandListener only processes one command at a time. I.e., it's serialized.
31 // Thus, no other mutation can occur in between the two statements above.
32 
33 #include "NetworkController.h"
34 
35 #define LOG_TAG "Netd"
36 #include "log/log.h"
37 
38 #include "cutils/misc.h"
39 #include "resolv_netid.h"
40 
41 #include "Controllers.h"
42 #include "DummyNetwork.h"
43 #include "DumpWriter.h"
44 #include "Fwmark.h"
45 #include "LocalNetwork.h"
46 #include "PhysicalNetwork.h"
47 #include "RouteController.h"
48 #include "VirtualNetwork.h"
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 class NetworkController::DelegateImpl : public PhysicalNetwork::Delegate {
66 public:
67     explicit DelegateImpl(NetworkController* networkController);
68     virtual ~DelegateImpl();
69 
70     int modifyFallthrough(unsigned vpnNetId, const std::string& physicalInterface,
71                           Permission permission, bool add) WARN_UNUSED_RESULT;
72 
73 private:
74     int addFallthrough(const std::string& physicalInterface,
75                        Permission permission) override WARN_UNUSED_RESULT;
76     int removeFallthrough(const std::string& physicalInterface,
77                           Permission permission) override WARN_UNUSED_RESULT;
78 
79     int modifyFallthrough(const std::string& physicalInterface, Permission permission,
80                           bool add) WARN_UNUSED_RESULT;
81 
82     NetworkController* const mNetworkController;
83 };
84 
DelegateImpl(NetworkController * networkController)85 NetworkController::DelegateImpl::DelegateImpl(NetworkController* networkController) :
86         mNetworkController(networkController) {
87 }
88 
~DelegateImpl()89 NetworkController::DelegateImpl::~DelegateImpl() {
90 }
91 
modifyFallthrough(unsigned vpnNetId,const std::string & physicalInterface,Permission permission,bool add)92 int NetworkController::DelegateImpl::modifyFallthrough(unsigned vpnNetId,
93                                                        const std::string& physicalInterface,
94                                                        Permission permission, bool add) {
95     if (add) {
96         if (int ret = RouteController::addVirtualNetworkFallthrough(vpnNetId,
97                                                                     physicalInterface.c_str(),
98                                                                     permission)) {
99             ALOGE("failed to add fallthrough to %s for VPN netId %u", physicalInterface.c_str(),
100                   vpnNetId);
101             return ret;
102         }
103     } else {
104         if (int ret = RouteController::removeVirtualNetworkFallthrough(vpnNetId,
105                                                                        physicalInterface.c_str(),
106                                                                        permission)) {
107             ALOGE("failed to remove fallthrough to %s for VPN netId %u", physicalInterface.c_str(),
108                   vpnNetId);
109             return ret;
110         }
111     }
112     return 0;
113 }
114 
addFallthrough(const std::string & physicalInterface,Permission permission)115 int NetworkController::DelegateImpl::addFallthrough(const std::string& physicalInterface,
116                                                     Permission permission) {
117     return modifyFallthrough(physicalInterface, permission, true);
118 }
119 
removeFallthrough(const std::string & physicalInterface,Permission permission)120 int NetworkController::DelegateImpl::removeFallthrough(const std::string& physicalInterface,
121                                                        Permission permission) {
122     return modifyFallthrough(physicalInterface, permission, false);
123 }
124 
modifyFallthrough(const std::string & physicalInterface,Permission permission,bool add)125 int NetworkController::DelegateImpl::modifyFallthrough(const std::string& physicalInterface,
126                                                        Permission permission, bool add) {
127     for (const auto& entry : mNetworkController->mNetworks) {
128         if (entry.second->getType() == Network::VIRTUAL) {
129             if (int ret = modifyFallthrough(entry.first, physicalInterface, permission, add)) {
130                 return ret;
131             }
132         }
133     }
134     return 0;
135 }
136 
NetworkController()137 NetworkController::NetworkController() :
138         mDelegateImpl(new NetworkController::DelegateImpl(this)), mDefaultNetId(NETID_UNSET),
139         mProtectableUsers({AID_VPN}) {
140     mNetworks[LOCAL_NET_ID] = new LocalNetwork(LOCAL_NET_ID);
141     mNetworks[DUMMY_NET_ID] = new DummyNetwork(DUMMY_NET_ID);
142 }
143 
getDefaultNetwork() const144 unsigned NetworkController::getDefaultNetwork() const {
145     android::RWLock::AutoRLock lock(mRWLock);
146     return mDefaultNetId;
147 }
148 
setDefaultNetwork(unsigned netId)149 int NetworkController::setDefaultNetwork(unsigned netId) {
150     android::RWLock::AutoWLock lock(mRWLock);
151 
152     if (netId == mDefaultNetId) {
153         return 0;
154     }
155 
156     if (netId != NETID_UNSET) {
157         Network* network = getNetworkLocked(netId);
158         if (!network) {
159             ALOGE("no such netId %u", netId);
160             return -ENONET;
161         }
162         if (network->getType() != Network::PHYSICAL) {
163             ALOGE("cannot set default to non-physical network with netId %u", netId);
164             return -EINVAL;
165         }
166         if (int ret = static_cast<PhysicalNetwork*>(network)->addAsDefault()) {
167             return ret;
168         }
169     }
170 
171     if (mDefaultNetId != NETID_UNSET) {
172         Network* network = getNetworkLocked(mDefaultNetId);
173         if (!network || network->getType() != Network::PHYSICAL) {
174             ALOGE("cannot find previously set default network with netId %u", mDefaultNetId);
175             return -ESRCH;
176         }
177         if (int ret = static_cast<PhysicalNetwork*>(network)->removeAsDefault()) {
178             return ret;
179         }
180     }
181 
182     mDefaultNetId = netId;
183     return 0;
184 }
185 
getNetworkForDns(unsigned * netId,uid_t uid) const186 uint32_t NetworkController::getNetworkForDns(unsigned* netId, uid_t uid) const {
187     android::RWLock::AutoRLock lock(mRWLock);
188     Fwmark fwmark;
189     fwmark.protectedFromVpn = true;
190     fwmark.permission = PERMISSION_SYSTEM;
191     if (checkUserNetworkAccessLocked(uid, *netId) == 0) {
192         // If a non-zero NetId was explicitly specified, and the user has permission for that
193         // network, use that network's DNS servers. Do not fall through to the default network even
194         // if the explicitly selected network is a split tunnel VPN: the explicitlySelected bit
195         // ensures that the VPN fallthrough rule does not match.
196         fwmark.explicitlySelected = true;
197 
198         // If the network is a VPN and it doesn't have DNS servers, use the default network's DNS
199         // servers (through the default network). Otherwise, the query is guaranteed to fail.
200         // http://b/29498052
201         Network *network = getNetworkLocked(*netId);
202         if (network && network->getType() == Network::VIRTUAL &&
203                 !static_cast<VirtualNetwork *>(network)->getHasDns()) {
204             *netId = mDefaultNetId;
205         }
206     } else {
207         // If the user is subject to a VPN and the VPN provides DNS servers, use those servers
208         // (possibly falling through to the default network if the VPN doesn't provide a route to
209         // them). Otherwise, use the default network's DNS servers.
210         VirtualNetwork* virtualNetwork = getVirtualNetworkForUserLocked(uid);
211         if (virtualNetwork && virtualNetwork->getHasDns()) {
212             *netId = virtualNetwork->getNetId();
213         } else {
214             // TODO: return an error instead of silently doing the DNS lookup on the wrong network.
215             // http://b/27560555
216             *netId = mDefaultNetId;
217         }
218     }
219     fwmark.netId = *netId;
220     return fwmark.intValue;
221 }
222 
223 // Returns the NetId that a given UID would use if no network is explicitly selected. Specifically,
224 // the VPN that applies to the UID if any; otherwise, the default network.
getNetworkForUser(uid_t uid) const225 unsigned NetworkController::getNetworkForUser(uid_t uid) const {
226     android::RWLock::AutoRLock lock(mRWLock);
227     if (VirtualNetwork* virtualNetwork = getVirtualNetworkForUserLocked(uid)) {
228         return virtualNetwork->getNetId();
229     }
230     return mDefaultNetId;
231 }
232 
233 // Returns the NetId that will be set when a socket connect()s. This is the bypassable VPN that
234 // applies to the user if any; otherwise, the default network.
235 //
236 // In general, we prefer to always set the default network's NetId in connect(), so that if the VPN
237 // is a split-tunnel and disappears later, the socket continues working (since the default network's
238 // NetId is still valid). Secure VPNs will correctly grab the socket's traffic since they have a
239 // high-priority routing rule that doesn't care what NetId the socket has.
240 //
241 // But bypassable VPNs have a very low priority rule, so we need to mark the socket with the
242 // bypassable VPN's NetId if we expect it to get any traffic at all. If the bypassable VPN is a
243 // split-tunnel, that's okay, because we have fallthrough rules that will direct the fallthrough
244 // traffic to the default network. But it does mean that if the bypassable VPN goes away (and thus
245 // the fallthrough rules also go away), the socket that used to fallthrough to the default network
246 // will stop working.
getNetworkForConnect(uid_t uid) const247 unsigned NetworkController::getNetworkForConnect(uid_t uid) const {
248     android::RWLock::AutoRLock lock(mRWLock);
249     VirtualNetwork* virtualNetwork = getVirtualNetworkForUserLocked(uid);
250     if (virtualNetwork && !virtualNetwork->isSecure()) {
251         return virtualNetwork->getNetId();
252     }
253     return mDefaultNetId;
254 }
255 
getNetworkContext(unsigned netId,uid_t uid,struct android_net_context * netcontext) const256 void NetworkController::getNetworkContext(
257         unsigned netId, uid_t uid, struct android_net_context* netcontext) const {
258     struct android_net_context nc = {
259             .app_netid = netId,
260             .app_mark = MARK_UNSET,
261             .dns_netid = netId,
262             .dns_mark = MARK_UNSET,
263             .uid = uid,
264     };
265 
266     // |netId| comes directly (via dnsproxyd) from the value returned by netIdForResolv() in the
267     // client process. This value is nonzero iff.:
268     //
269     // 1. The app specified a netid/nethandle to a DNS resolution method such as:
270     //        - [Java] android.net.Network#getAllByName()
271     //        - [C/++] android_getaddrinfofornetwork()
272     // 2. The app specified a netid/nethandle to be used as a process default via:
273     //        - [Java] android.net.ConnectivityManager#bindProcessToNetwork()
274     //        - [C/++] android_setprocnetwork()
275     // 3. The app called android.net.ConnectivityManager#startUsingNetworkFeature().
276     //
277     // In all these cases (with the possible exception of #3), the right thing to do is to treat
278     // such cases as explicitlySelected.
279     const bool explicitlySelected = (nc.app_netid != NETID_UNSET);
280     if (!explicitlySelected) {
281         nc.app_netid = getNetworkForConnect(uid);
282     }
283 
284     Fwmark fwmark;
285     fwmark.netId = nc.app_netid;
286     fwmark.explicitlySelected = explicitlySelected;
287     fwmark.protectedFromVpn = canProtect(uid);
288     fwmark.permission = getPermissionForUser(uid);
289     nc.app_mark = fwmark.intValue;
290 
291     nc.dns_mark = getNetworkForDns(&(nc.dns_netid), uid);
292 
293     if (netcontext) {
294         *netcontext = nc;
295     }
296 }
297 
getNetworkForInterface(const char * interface) const298 unsigned NetworkController::getNetworkForInterface(const char* interface) const {
299     android::RWLock::AutoRLock lock(mRWLock);
300     for (const auto& entry : mNetworks) {
301         if (entry.second->hasInterface(interface)) {
302             return entry.first;
303         }
304     }
305     return NETID_UNSET;
306 }
307 
isVirtualNetwork(unsigned netId) const308 bool NetworkController::isVirtualNetwork(unsigned netId) const {
309     android::RWLock::AutoRLock lock(mRWLock);
310     Network* network = getNetworkLocked(netId);
311     return network && network->getType() == Network::VIRTUAL;
312 }
313 
createPhysicalNetwork(unsigned netId,Permission permission)314 int NetworkController::createPhysicalNetwork(unsigned netId, Permission permission) {
315     if (!((MIN_NET_ID <= netId && netId <= MAX_NET_ID) ||
316           (MIN_OEM_ID <= netId && netId <= MAX_OEM_ID))) {
317         ALOGE("invalid netId %u", netId);
318         return -EINVAL;
319     }
320 
321     if (isValidNetwork(netId)) {
322         ALOGE("duplicate netId %u", netId);
323         return -EEXIST;
324     }
325 
326     PhysicalNetwork* physicalNetwork = new PhysicalNetwork(netId, mDelegateImpl);
327     if (int ret = physicalNetwork->setPermission(permission)) {
328         ALOGE("inconceivable! setPermission cannot fail on an empty network");
329         delete physicalNetwork;
330         return ret;
331     }
332 
333     android::RWLock::AutoWLock lock(mRWLock);
334     mNetworks[netId] = physicalNetwork;
335     return 0;
336 }
337 
createVirtualNetwork(unsigned netId,bool hasDns,bool secure)338 int NetworkController::createVirtualNetwork(unsigned netId, bool hasDns, bool secure) {
339     if (!(MIN_NET_ID <= netId && netId <= MAX_NET_ID)) {
340         ALOGE("invalid netId %u", netId);
341         return -EINVAL;
342     }
343 
344     if (isValidNetwork(netId)) {
345         ALOGE("duplicate netId %u", netId);
346         return -EEXIST;
347     }
348 
349     android::RWLock::AutoWLock lock(mRWLock);
350     if (int ret = modifyFallthroughLocked(netId, true)) {
351         return ret;
352     }
353     mNetworks[netId] = new VirtualNetwork(netId, hasDns, secure);
354     return 0;
355 }
356 
destroyNetwork(unsigned netId)357 int NetworkController::destroyNetwork(unsigned netId) {
358     if (netId == LOCAL_NET_ID) {
359         ALOGE("cannot destroy local network");
360         return -EINVAL;
361     }
362     if (!isValidNetwork(netId)) {
363         ALOGE("no such netId %u", netId);
364         return -ENONET;
365     }
366 
367     // TODO: ioctl(SIOCKILLADDR, ...) to kill all sockets on the old network.
368 
369     android::RWLock::AutoWLock lock(mRWLock);
370     Network* network = getNetworkLocked(netId);
371 
372     // If we fail to destroy a network, things will get stuck badly. Therefore, unlike most of the
373     // other network code, ignore failures and attempt to clear out as much state as possible, even
374     // if we hit an error on the way. Return the first error that we see.
375     int ret = network->clearInterfaces();
376 
377     if (mDefaultNetId == netId) {
378         if (int err = static_cast<PhysicalNetwork*>(network)->removeAsDefault()) {
379             ALOGE("inconceivable! removeAsDefault cannot fail on an empty network");
380             if (!ret) {
381                 ret = err;
382             }
383         }
384         mDefaultNetId = NETID_UNSET;
385     } else if (network->getType() == Network::VIRTUAL) {
386         if (int err = modifyFallthroughLocked(netId, false)) {
387             if (!ret) {
388                 ret = err;
389             }
390         }
391     }
392     mNetworks.erase(netId);
393     delete network;
394     _resolv_delete_cache_for_net(netId);
395     return ret;
396 }
397 
addInterfaceToNetwork(unsigned netId,const char * interface)398 int NetworkController::addInterfaceToNetwork(unsigned netId, const char* interface) {
399     if (!isValidNetwork(netId)) {
400         ALOGE("no such netId %u", netId);
401         return -ENONET;
402     }
403 
404     unsigned existingNetId = getNetworkForInterface(interface);
405     if (existingNetId != NETID_UNSET && existingNetId != netId) {
406         ALOGE("interface %s already assigned to netId %u", interface, existingNetId);
407         return -EBUSY;
408     }
409 
410     android::RWLock::AutoWLock lock(mRWLock);
411     return getNetworkLocked(netId)->addInterface(interface);
412 }
413 
removeInterfaceFromNetwork(unsigned netId,const char * interface)414 int NetworkController::removeInterfaceFromNetwork(unsigned netId, const char* interface) {
415     if (!isValidNetwork(netId)) {
416         ALOGE("no such netId %u", netId);
417         return -ENONET;
418     }
419 
420     android::RWLock::AutoWLock lock(mRWLock);
421     return getNetworkLocked(netId)->removeInterface(interface);
422 }
423 
getPermissionForUser(uid_t uid) const424 Permission NetworkController::getPermissionForUser(uid_t uid) const {
425     android::RWLock::AutoRLock lock(mRWLock);
426     return getPermissionForUserLocked(uid);
427 }
428 
setPermissionForUsers(Permission permission,const std::vector<uid_t> & uids)429 void NetworkController::setPermissionForUsers(Permission permission,
430                                               const std::vector<uid_t>& uids) {
431     android::RWLock::AutoWLock lock(mRWLock);
432     for (uid_t uid : uids) {
433         mUsers[uid] = permission;
434     }
435 }
436 
checkUserNetworkAccess(uid_t uid,unsigned netId) const437 int NetworkController::checkUserNetworkAccess(uid_t uid, unsigned netId) const {
438     android::RWLock::AutoRLock lock(mRWLock);
439     return checkUserNetworkAccessLocked(uid, netId);
440 }
441 
setPermissionForNetworks(Permission permission,const std::vector<unsigned> & netIds)442 int NetworkController::setPermissionForNetworks(Permission permission,
443                                                 const std::vector<unsigned>& netIds) {
444     android::RWLock::AutoWLock lock(mRWLock);
445     for (unsigned netId : netIds) {
446         Network* network = getNetworkLocked(netId);
447         if (!network) {
448             ALOGE("no such netId %u", netId);
449             return -ENONET;
450         }
451         if (network->getType() != Network::PHYSICAL) {
452             ALOGE("cannot set permissions on non-physical network with netId %u", netId);
453             return -EINVAL;
454         }
455 
456         // TODO: ioctl(SIOCKILLADDR, ...) to kill socets on the network that don't have permission.
457 
458         if (int ret = static_cast<PhysicalNetwork*>(network)->setPermission(permission)) {
459             return ret;
460         }
461     }
462     return 0;
463 }
464 
addUsersToNetwork(unsigned netId,const UidRanges & uidRanges)465 int NetworkController::addUsersToNetwork(unsigned netId, const UidRanges& uidRanges) {
466     android::RWLock::AutoWLock lock(mRWLock);
467     Network* network = getNetworkLocked(netId);
468     if (!network) {
469         ALOGE("no such netId %u", netId);
470         return -ENONET;
471     }
472     if (network->getType() != Network::VIRTUAL) {
473         ALOGE("cannot add users to non-virtual network with netId %u", netId);
474         return -EINVAL;
475     }
476     if (int ret = static_cast<VirtualNetwork*>(network)->addUsers(uidRanges, mProtectableUsers)) {
477         return ret;
478     }
479     return 0;
480 }
481 
removeUsersFromNetwork(unsigned netId,const UidRanges & uidRanges)482 int NetworkController::removeUsersFromNetwork(unsigned netId, const UidRanges& uidRanges) {
483     android::RWLock::AutoWLock lock(mRWLock);
484     Network* network = getNetworkLocked(netId);
485     if (!network) {
486         ALOGE("no such netId %u", netId);
487         return -ENONET;
488     }
489     if (network->getType() != Network::VIRTUAL) {
490         ALOGE("cannot remove users from non-virtual network with netId %u", netId);
491         return -EINVAL;
492     }
493     if (int ret = static_cast<VirtualNetwork*>(network)->removeUsers(uidRanges,
494                                                                      mProtectableUsers)) {
495         return ret;
496     }
497     return 0;
498 }
499 
addRoute(unsigned netId,const char * interface,const char * destination,const char * nexthop,bool legacy,uid_t uid)500 int NetworkController::addRoute(unsigned netId, const char* interface, const char* destination,
501                                 const char* nexthop, bool legacy, uid_t uid) {
502     return modifyRoute(netId, interface, destination, nexthop, true, legacy, uid);
503 }
504 
removeRoute(unsigned netId,const char * interface,const char * destination,const char * nexthop,bool legacy,uid_t uid)505 int NetworkController::removeRoute(unsigned netId, const char* interface, const char* destination,
506                                    const char* nexthop, bool legacy, uid_t uid) {
507     return modifyRoute(netId, interface, destination, nexthop, false, legacy, uid);
508 }
509 
canProtect(uid_t uid) const510 bool NetworkController::canProtect(uid_t uid) const {
511     android::RWLock::AutoRLock lock(mRWLock);
512     return ((getPermissionForUserLocked(uid) & PERMISSION_SYSTEM) == PERMISSION_SYSTEM) ||
513            mProtectableUsers.find(uid) != mProtectableUsers.end();
514 }
515 
allowProtect(const std::vector<uid_t> & uids)516 void NetworkController::allowProtect(const std::vector<uid_t>& uids) {
517     android::RWLock::AutoWLock lock(mRWLock);
518     mProtectableUsers.insert(uids.begin(), uids.end());
519 }
520 
denyProtect(const std::vector<uid_t> & uids)521 void NetworkController::denyProtect(const std::vector<uid_t>& uids) {
522     android::RWLock::AutoWLock lock(mRWLock);
523     for (uid_t uid : uids) {
524         mProtectableUsers.erase(uid);
525     }
526 }
527 
dump(DumpWriter & dw)528 void NetworkController::dump(DumpWriter& dw) {
529     android::RWLock::AutoRLock lock(mRWLock);
530 
531     dw.incIndent();
532     dw.println("NetworkController");
533 
534     dw.incIndent();
535     dw.println("Default network: %u", mDefaultNetId);
536 
537     dw.blankline();
538     dw.println("Networks:");
539     dw.incIndent();
540     for (const auto& i : mNetworks) {
541         dw.println(i.second->toString().c_str());
542         android::net::gCtls->resolverCtrl.dump(dw, i.first);
543         dw.blankline();
544     }
545     dw.decIndent();
546 
547     dw.decIndent();
548 
549     dw.decIndent();
550 }
551 
isValidNetwork(unsigned netId) const552 bool NetworkController::isValidNetwork(unsigned netId) const {
553     android::RWLock::AutoRLock lock(mRWLock);
554     return getNetworkLocked(netId);
555 }
556 
getNetworkLocked(unsigned netId) const557 Network* NetworkController::getNetworkLocked(unsigned netId) const {
558     auto iter = mNetworks.find(netId);
559     return iter == mNetworks.end() ? NULL : iter->second;
560 }
561 
getVirtualNetworkForUserLocked(uid_t uid) const562 VirtualNetwork* NetworkController::getVirtualNetworkForUserLocked(uid_t uid) const {
563     for (const auto& entry : mNetworks) {
564         if (entry.second->getType() == Network::VIRTUAL) {
565             VirtualNetwork* virtualNetwork = static_cast<VirtualNetwork*>(entry.second);
566             if (virtualNetwork->appliesToUser(uid)) {
567                 return virtualNetwork;
568             }
569         }
570     }
571     return NULL;
572 }
573 
getPermissionForUserLocked(uid_t uid) const574 Permission NetworkController::getPermissionForUserLocked(uid_t uid) const {
575     auto iter = mUsers.find(uid);
576     if (iter != mUsers.end()) {
577         return iter->second;
578     }
579     return uid < FIRST_APPLICATION_UID ? PERMISSION_SYSTEM : PERMISSION_NONE;
580 }
581 
checkUserNetworkAccessLocked(uid_t uid,unsigned netId) const582 int NetworkController::checkUserNetworkAccessLocked(uid_t uid, unsigned netId) const {
583     Network* network = getNetworkLocked(netId);
584     if (!network) {
585         return -ENONET;
586     }
587 
588     // If uid is INVALID_UID, this likely means that we were unable to retrieve the UID of the peer
589     // (using SO_PEERCRED). Be safe and deny access to the network, even if it's valid.
590     if (uid == INVALID_UID) {
591         return -EREMOTEIO;
592     }
593     Permission userPermission = getPermissionForUserLocked(uid);
594     if ((userPermission & PERMISSION_SYSTEM) == PERMISSION_SYSTEM) {
595         return 0;
596     }
597     if (network->getType() == Network::VIRTUAL) {
598         return static_cast<VirtualNetwork*>(network)->appliesToUser(uid) ? 0 : -EPERM;
599     }
600     VirtualNetwork* virtualNetwork = getVirtualNetworkForUserLocked(uid);
601     if (virtualNetwork && virtualNetwork->isSecure() &&
602             mProtectableUsers.find(uid) == mProtectableUsers.end()) {
603         return -EPERM;
604     }
605     Permission networkPermission = static_cast<PhysicalNetwork*>(network)->getPermission();
606     return ((userPermission & networkPermission) == networkPermission) ? 0 : -EACCES;
607 }
608 
modifyRoute(unsigned netId,const char * interface,const char * destination,const char * nexthop,bool add,bool legacy,uid_t uid)609 int NetworkController::modifyRoute(unsigned netId, const char* interface, const char* destination,
610                                    const char* nexthop, bool add, bool legacy, uid_t uid) {
611     if (!isValidNetwork(netId)) {
612         ALOGE("no such netId %u", netId);
613         return -ENONET;
614     }
615     unsigned existingNetId = getNetworkForInterface(interface);
616     if (existingNetId == NETID_UNSET) {
617         ALOGE("interface %s not assigned to any netId", interface);
618         return -ENODEV;
619     }
620     if (existingNetId != netId) {
621         ALOGE("interface %s assigned to netId %u, not %u", interface, existingNetId, netId);
622         return -ENOENT;
623     }
624 
625     RouteController::TableType tableType;
626     if (netId == LOCAL_NET_ID) {
627         tableType = RouteController::LOCAL_NETWORK;
628     } else if (legacy) {
629         if ((getPermissionForUser(uid) & PERMISSION_SYSTEM) == PERMISSION_SYSTEM) {
630             tableType = RouteController::LEGACY_SYSTEM;
631         } else {
632             tableType = RouteController::LEGACY_NETWORK;
633         }
634     } else {
635         tableType = RouteController::INTERFACE;
636     }
637 
638     return add ? RouteController::addRoute(interface, destination, nexthop, tableType) :
639                  RouteController::removeRoute(interface, destination, nexthop, tableType);
640 }
641 
modifyFallthroughLocked(unsigned vpnNetId,bool add)642 int NetworkController::modifyFallthroughLocked(unsigned vpnNetId, bool add) {
643     if (mDefaultNetId == NETID_UNSET) {
644         return 0;
645     }
646     Network* network = getNetworkLocked(mDefaultNetId);
647     if (!network) {
648         ALOGE("cannot find previously set default network with netId %u", mDefaultNetId);
649         return -ESRCH;
650     }
651     if (network->getType() != Network::PHYSICAL) {
652         ALOGE("inconceivable! default network must be a physical network");
653         return -EINVAL;
654     }
655     Permission permission = static_cast<PhysicalNetwork*>(network)->getPermission();
656     for (const auto& physicalInterface : network->getInterfaces()) {
657         if (int ret = mDelegateImpl->modifyFallthrough(vpnNetId, physicalInterface, permission,
658                                                        add)) {
659             return ret;
660         }
661     }
662     return 0;
663 }
664