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({std::make_pair(AID_VPN, NETID_UNSET)}) {
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, nc.app_netid);
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
isProtectableLocked(uid_t uid,unsigned netId) const720 bool NetworkController::isProtectableLocked(uid_t uid, unsigned netId) const {
721 return mProtectableUsers.find({uid, NETID_UNSET}) != mProtectableUsers.cend() ||
722 mProtectableUsers.find({uid, netId}) != mProtectableUsers.cend();
723 }
724
canProtectLocked(uid_t uid,unsigned netId) const725 bool NetworkController::canProtectLocked(uid_t uid, unsigned netId) const {
726 if ((getPermissionForUserLocked(uid) & PERMISSION_SYSTEM) == PERMISSION_SYSTEM) {
727 return true;
728 }
729 return isProtectableLocked(uid, netId);
730 }
731
canProtect(uid_t uid,unsigned netId) const732 bool NetworkController::canProtect(uid_t uid, unsigned netId) const {
733 ScopedRLock lock(mRWLock);
734 return canProtectLocked(uid, netId);
735 }
736
allowProtect(uid_t uid,unsigned netId)737 int NetworkController::allowProtect(uid_t uid, unsigned netId) {
738 ScopedWLock lock(mRWLock);
739 return mProtectableUsers.emplace(std::make_pair(uid, netId)).second ? 0 : -EEXIST;
740 }
741
denyProtect(uid_t uid,unsigned netId)742 int NetworkController::denyProtect(uid_t uid, unsigned netId) {
743 ScopedWLock lock(mRWLock);
744 return mProtectableUsers.erase(std::make_pair(uid, netId)) ? 0 : -ENOENT;
745 }
746
dump(DumpWriter & dw)747 void NetworkController::dump(DumpWriter& dw) {
748 ScopedRLock lock(mRWLock);
749
750 dw.incIndent();
751 dw.println("NetworkController");
752
753 dw.incIndent();
754 dw.println("Default network: %u", mDefaultNetId);
755
756 dw.blankline();
757 dw.println("Networks:");
758 dw.incIndent();
759 for (const auto& i : mNetworks) {
760 Network* network = i.second;
761 dw.println(network->toString());
762 if (network->isPhysical()) {
763 dw.incIndent();
764 Permission permission = reinterpret_cast<PhysicalNetwork*>(network)->getPermission();
765 dw.println("Required permission: %s", permissionToName(permission));
766 dw.decIndent();
767 }
768 if (const auto& str = network->uidRangesToString(); !str.empty()) {
769 dw.incIndent();
770 dw.println("Per-app UID ranges: %s", str.c_str());
771 dw.decIndent();
772 }
773 if (const auto& str = network->allowedUidsToString(); !str.empty()) {
774 dw.incIndent();
775 dw.println("Allowed UID ranges: %s", str.c_str());
776 dw.decIndent();
777 }
778 dw.blankline();
779 }
780 dw.decIndent();
781
782 dw.blankline();
783 dw.println("Interface <-> last network map:");
784 dw.incIndent();
785 for (const auto& i : mIfindexToLastNetId) {
786 dw.println("Ifindex: %u NetId: %u", i.first, i.second);
787 }
788 dw.decIndent();
789
790 dw.blankline();
791 dw.println("Interface addresses:");
792 dw.incIndent();
793 for (const auto& i : mAddressToIfindices) {
794 dw.println("address: %s ifindices: [%s]", i.first.c_str(),
795 android::base::Join(i.second, ", ").c_str());
796 }
797 dw.decIndent();
798
799 dw.blankline();
800 dw.println("Permission of users:");
801 dw.incIndent();
802 std::vector<uid_t> systemUids;
803 std::vector<uid_t> networkUids;
804 for (const auto& [uid, permission] : mUsers) {
805 if ((permission & PERMISSION_SYSTEM) == PERMISSION_SYSTEM) {
806 systemUids.push_back(uid);
807 } else if ((permission & PERMISSION_NETWORK) == PERMISSION_NETWORK) {
808 networkUids.push_back(uid);
809 }
810 }
811 dw.println("NETWORK: %s", android::base::Join(networkUids, ", ").c_str());
812 dw.println("SYSTEM: %s", android::base::Join(systemUids, ", ").c_str());
813 dw.decIndent();
814
815 dw.blankline();
816 dw.println("Protectable users:");
817 for (auto it : mProtectableUsers) {
818 dw.println("[uid: %u : netId: %u]", it.first, it.second);
819 }
820
821 dw.decIndent();
822
823 dw.decIndent();
824 }
825
clearAllowedUidsForAllNetworksLocked()826 void NetworkController::clearAllowedUidsForAllNetworksLocked() {
827 for (const auto& [_, network] : mNetworks) {
828 network->clearAllowedUids();
829 }
830 }
831
setNetworkAllowlist(const std::vector<netd::aidl::NativeUidRangeConfig> & rangeConfigs)832 int NetworkController::setNetworkAllowlist(
833 const std::vector<netd::aidl::NativeUidRangeConfig>& rangeConfigs) {
834 const ScopedWLock lock(mRWLock);
835
836 for (const auto& config : rangeConfigs) {
837 Network* network = getNetworkLocked(config.netId);
838 if (!network) return -ENONET;
839 }
840
841 clearAllowedUidsForAllNetworksLocked();
842 for (const auto& config : rangeConfigs) {
843 Network* network = getNetworkLocked(config.netId);
844 network->setAllowedUids(UidRanges(config.uidRanges));
845 }
846 return 0;
847 }
848
isUidAllowed(unsigned netId,uid_t uid) const849 bool NetworkController::isUidAllowed(unsigned netId, uid_t uid) const {
850 const ScopedRLock lock(mRWLock);
851 Network* network = getNetworkLocked(netId);
852 // Exempt when no netId is specified and there is no default network, so that apps or tests can
853 // do DNS lookups for hostnames in etc/hosts.
854 if (netId == NETID_UNSET && mDefaultNetId == NETID_UNSET) {
855 return true;
856 }
857 return network && network->isUidAllowed(uid);
858 }
859
isValidNetworkLocked(unsigned netId) const860 bool NetworkController::isValidNetworkLocked(unsigned netId) const {
861 return getNetworkLocked(netId);
862 }
863
getNetworkLocked(unsigned netId) const864 Network* NetworkController::getNetworkLocked(unsigned netId) const {
865 auto iter = mNetworks.find(netId);
866 return iter == mNetworks.end() ? nullptr : iter->second;
867 }
868
getVirtualNetworkForUserLocked(uid_t uid) const869 VirtualNetwork* NetworkController::getVirtualNetworkForUserLocked(uid_t uid) const {
870 int32_t subPriority;
871 for (const auto& [_, network] : mNetworks) {
872 if (network->isVirtual() && network->appliesToUser(uid, &subPriority)) {
873 return static_cast<VirtualNetwork*>(network);
874 }
875 }
876 return nullptr;
877 }
878
879 // Returns the default network with the highest subsidiary priority among physical and unreachable
880 // networks that applies to uid. For a single subsidiary priority, an uid should belong to only one
881 // network. If the uid apply to different network with the same priority at the same time, the
882 // behavior is undefined. That is a configuration error.
getPhysicalOrUnreachableNetworkForUserLocked(uid_t uid) const883 Network* NetworkController::getPhysicalOrUnreachableNetworkForUserLocked(uid_t uid) const {
884 Network* bestNetwork = nullptr;
885
886 // In this function, appliesToUser() is used to figure out if this network is the user's default
887 // network (not just if the user has access to this network). Rules at SUB_PRIORITY_NO_DEFAULT
888 // "apply to the user" but do not include a default network rule. Since their subpriority (999)
889 // is greater than SUB_PRIORITY_LOWEST (998), these rules never trump any subpriority that
890 // includes a default network rule (appliesToUser returns the "highest" (=lowest value)
891 // subPriority that includes the uid), and they get filtered out in the if-statement below.
892 int32_t bestSubPriority = UidRanges::SUB_PRIORITY_NO_DEFAULT;
893 for (const auto& [netId, network] : mNetworks) {
894 int32_t subPriority;
895 if (!network->isPhysical() && !network->isUnreachable()) continue;
896 if (!network->appliesToUser(uid, &subPriority)) continue;
897 if (subPriority == UidRanges::SUB_PRIORITY_NO_DEFAULT) continue;
898
899 if (subPriority < bestSubPriority) {
900 bestNetwork = network;
901 bestSubPriority = subPriority;
902 }
903 }
904 return bestNetwork;
905 }
906
getPermissionForUserLocked(uid_t uid) const907 Permission NetworkController::getPermissionForUserLocked(uid_t uid) const {
908 auto iter = mUsers.find(uid);
909 if (iter != mUsers.end()) {
910 return iter->second;
911 }
912 return uid < FIRST_APPLICATION_UID ? PERMISSION_SYSTEM : PERMISSION_NONE;
913 }
914
checkUserNetworkAccessLocked(uid_t uid,unsigned netId) const915 int NetworkController::checkUserNetworkAccessLocked(uid_t uid, unsigned netId) const {
916 Network* network = getNetworkLocked(netId);
917 if (!network) {
918 return -ENONET;
919 }
920
921 // If uid is INVALID_UID, this likely means that we were unable to retrieve the UID of the peer
922 // (using SO_PEERCRED). Be safe and deny access to the network, even if it's valid.
923 if (uid == INVALID_UID) {
924 return -EREMOTEIO;
925 }
926 // If the UID has PERMISSION_SYSTEM, it can use whatever network it wants.
927 Permission userPermission = getPermissionForUserLocked(uid);
928 if ((userPermission & PERMISSION_SYSTEM) == PERMISSION_SYSTEM) {
929 return 0;
930 }
931 // If the UID wants to use a VPN, it can do so if and only if the VPN applies to the UID.
932 int32_t subPriority;
933 if (network->isVirtual()) {
934 return network->appliesToUser(uid, &subPriority) ? 0 : -EPERM;
935 }
936 // If a VPN applies to the UID, and the VPN is secure (i.e., not bypassable), then the UID can
937 // only select a different network if it has the ability to protect its sockets.
938 VirtualNetwork* virtualNetwork = getVirtualNetworkForUserLocked(uid);
939 if (virtualNetwork && virtualNetwork->isSecure() && !isProtectableLocked(uid, netId)) {
940 ALOGE("uid %u can't select networks other than %u.", uid, virtualNetwork->getNetId());
941 return -EPERM;
942 }
943 // If the UID wants to use a physical network and it has a UID range that includes the UID, the
944 // UID has permission to use it regardless of whether the permission bits match.
945 if (network->isPhysical() && network->appliesToUser(uid, &subPriority)) {
946 return 0;
947 }
948 // Only apps that are configured as "no default network" can use the unreachable network.
949 if (network->isUnreachable()) {
950 return network->appliesToUser(uid, &subPriority) ? 0 : -EPERM;
951 }
952
953 if (!network->isUidAllowed(uid)) {
954 return -EACCES;
955 }
956 // Check whether the UID's permission bits are sufficient to use the network.
957 // Because the permission of the system default network is PERMISSION_NONE(0x0), apps can always
958 // pass the check here when using the system default network.
959 const Permission networkPermission = network->getPermission();
960 return ((userPermission & networkPermission) == networkPermission) ? 0 : -EACCES;
961 }
962
modifyRoute(unsigned netId,const char * interface,const char * destination,const char * nexthop,enum RouteOperation op,bool legacy,uid_t uid,int mtu)963 int NetworkController::modifyRoute(unsigned netId, const char* interface, const char* destination,
964 const char* nexthop, enum RouteOperation op, bool legacy,
965 uid_t uid, int mtu) {
966 ScopedRLock lock(mRWLock);
967
968 if (!isValidNetworkLocked(netId)) {
969 ALOGE("no such netId %u", netId);
970 return -ENONET;
971 }
972 unsigned existingNetId = getNetworkForInterfaceLocked(interface);
973 if (existingNetId == NETID_UNSET) {
974 ALOGE("interface %s not assigned to any netId", interface);
975 return -ENODEV;
976 }
977 if (existingNetId != netId) {
978 ALOGE("interface %s assigned to netId %u, not %u", interface, existingNetId, netId);
979 return -ENOENT;
980 }
981
982 RouteController::TableType tableType;
983 if (netId == LOCAL_NET_ID) {
984 tableType = RouteController::LOCAL_NETWORK;
985 } else if (legacy) {
986 if ((getPermissionForUserLocked(uid) & PERMISSION_SYSTEM) == PERMISSION_SYSTEM) {
987 tableType = RouteController::LEGACY_SYSTEM;
988 } else {
989 tableType = RouteController::LEGACY_NETWORK;
990 }
991 } else {
992 tableType = RouteController::INTERFACE;
993 }
994
995 switch (op) {
996 case ROUTE_ADD:
997 return RouteController::addRoute(interface, destination, nexthop, tableType, mtu,
998 0 /* priority */);
999 case ROUTE_UPDATE:
1000 return RouteController::updateRoute(interface, destination, nexthop, tableType, mtu);
1001 case ROUTE_REMOVE:
1002 return RouteController::removeRoute(interface, destination, nexthop, tableType,
1003 0 /* priority */);
1004 }
1005 return -EINVAL;
1006 }
1007
modifyFallthroughLocked(unsigned vpnNetId,bool add)1008 int NetworkController::modifyFallthroughLocked(unsigned vpnNetId, bool add) {
1009 if (mDefaultNetId == NETID_UNSET) {
1010 return 0;
1011 }
1012 Network* network = getNetworkLocked(mDefaultNetId);
1013 if (!network) {
1014 ALOGE("cannot find previously set default network with netId %u", mDefaultNetId);
1015 return -ESRCH;
1016 }
1017 if (!network->isPhysical()) {
1018 ALOGE("inconceivable! default network must be a physical network");
1019 return -EINVAL;
1020 }
1021 Permission permission = static_cast<PhysicalNetwork*>(network)->getPermission();
1022 for (const auto& physicalInterface : network->getInterfaces()) {
1023 if (int ret = mDelegateImpl->modifyFallthrough(vpnNetId, physicalInterface, permission,
1024 add)) {
1025 return ret;
1026 }
1027 }
1028 return 0;
1029 }
1030
updateTcpSocketMonitorPolling()1031 void NetworkController::updateTcpSocketMonitorPolling() {
1032 bool physicalNetworkExists = false;
1033 for (const auto& entry : mNetworks) {
1034 const auto& network = entry.second;
1035 if (network->isPhysical() && network->getNetId() >= MIN_NET_ID) {
1036 physicalNetworkExists = true;
1037 break;
1038 }
1039 }
1040
1041 if (physicalNetworkExists) {
1042 android::net::gCtls->tcpSocketMonitor.resumePolling();
1043 } else {
1044 android::net::gCtls->tcpSocketMonitor.suspendPolling();
1045 }
1046 }
1047
1048 } // namespace android::net
1049