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