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