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