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