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// In some cases, a single non-const method acquires and releases the lock several times, like so:
23//     if (isValidNetwork(...)) {  // isValidNetwork() acquires and releases the lock.
24//        setDefaultNetwork(...);  // setDefaultNetwork() also acquires and releases the lock.
25//
26// It might seem that this allows races where the state changes between the two statements, but in
27// fact there are no races because:
28//     1. This pattern only occurs in non-const methods (i.e., those that mutate state).
29//     2. Only CommandListener calls these non-const methods. The others call only const methods.
30//     3. CommandListener only processes one command at a time. I.e., it's serialized.
31// Thus, no other mutation can occur in between the two statements above.
32
33#include "NetworkController.h"
34
35#include "DummyNetwork.h"
36#include "Fwmark.h"
37#include "LocalNetwork.h"
38#include "PhysicalNetwork.h"
39#include "RouteController.h"
40#include "VirtualNetwork.h"
41
42#include "cutils/misc.h"
43#define LOG_TAG "Netd"
44#include "log/log.h"
45#include "resolv_netid.h"
46
47namespace {
48
49// Keep these in sync with ConnectivityService.java.
50const unsigned MIN_NET_ID = 100;
51const unsigned MAX_NET_ID = 65535;
52
53}  // namespace
54
55const unsigned NetworkController::MIN_OEM_ID   =  1;
56const unsigned NetworkController::MAX_OEM_ID   = 50;
57const unsigned NetworkController::DUMMY_NET_ID = 51;
58// NetIds 52..98 are reserved for future use.
59const unsigned NetworkController::LOCAL_NET_ID = 99;
60
61// All calls to methods here are made while holding a write lock on mRWLock.
62class NetworkController::DelegateImpl : public PhysicalNetwork::Delegate {
63public:
64    explicit DelegateImpl(NetworkController* networkController);
65    virtual ~DelegateImpl();
66
67    int modifyFallthrough(unsigned vpnNetId, const std::string& physicalInterface,
68                          Permission permission, bool add) WARN_UNUSED_RESULT;
69
70private:
71    int addFallthrough(const std::string& physicalInterface,
72                       Permission permission) override WARN_UNUSED_RESULT;
73    int removeFallthrough(const std::string& physicalInterface,
74                          Permission permission) override WARN_UNUSED_RESULT;
75
76    int modifyFallthrough(const std::string& physicalInterface, Permission permission,
77                          bool add) WARN_UNUSED_RESULT;
78
79    NetworkController* const mNetworkController;
80};
81
82NetworkController::DelegateImpl::DelegateImpl(NetworkController* networkController) :
83        mNetworkController(networkController) {
84}
85
86NetworkController::DelegateImpl::~DelegateImpl() {
87}
88
89int NetworkController::DelegateImpl::modifyFallthrough(unsigned vpnNetId,
90                                                       const std::string& physicalInterface,
91                                                       Permission permission, bool add) {
92    if (add) {
93        if (int ret = RouteController::addVirtualNetworkFallthrough(vpnNetId,
94                                                                    physicalInterface.c_str(),
95                                                                    permission)) {
96            ALOGE("failed to add fallthrough to %s for VPN netId %u", physicalInterface.c_str(),
97                  vpnNetId);
98            return ret;
99        }
100    } else {
101        if (int ret = RouteController::removeVirtualNetworkFallthrough(vpnNetId,
102                                                                       physicalInterface.c_str(),
103                                                                       permission)) {
104            ALOGE("failed to remove fallthrough to %s for VPN netId %u", physicalInterface.c_str(),
105                  vpnNetId);
106            return ret;
107        }
108    }
109    return 0;
110}
111
112int NetworkController::DelegateImpl::addFallthrough(const std::string& physicalInterface,
113                                                    Permission permission) {
114    return modifyFallthrough(physicalInterface, permission, true);
115}
116
117int NetworkController::DelegateImpl::removeFallthrough(const std::string& physicalInterface,
118                                                       Permission permission) {
119    return modifyFallthrough(physicalInterface, permission, false);
120}
121
122int NetworkController::DelegateImpl::modifyFallthrough(const std::string& physicalInterface,
123                                                       Permission permission, bool add) {
124    for (const auto& entry : mNetworkController->mNetworks) {
125        if (entry.second->getType() == Network::VIRTUAL) {
126            if (int ret = modifyFallthrough(entry.first, physicalInterface, permission, add)) {
127                return ret;
128            }
129        }
130    }
131    return 0;
132}
133
134NetworkController::NetworkController() :
135        mDelegateImpl(new NetworkController::DelegateImpl(this)), mDefaultNetId(NETID_UNSET) {
136    mNetworks[LOCAL_NET_ID] = new LocalNetwork(LOCAL_NET_ID);
137    mNetworks[DUMMY_NET_ID] = new DummyNetwork(DUMMY_NET_ID);
138}
139
140unsigned NetworkController::getDefaultNetwork() const {
141    android::RWLock::AutoRLock lock(mRWLock);
142    return mDefaultNetId;
143}
144
145int NetworkController::setDefaultNetwork(unsigned netId) {
146    android::RWLock::AutoWLock lock(mRWLock);
147
148    if (netId == mDefaultNetId) {
149        return 0;
150    }
151
152    if (netId != NETID_UNSET) {
153        Network* network = getNetworkLocked(netId);
154        if (!network) {
155            ALOGE("no such netId %u", netId);
156            return -ENONET;
157        }
158        if (network->getType() != Network::PHYSICAL) {
159            ALOGE("cannot set default to non-physical network with netId %u", netId);
160            return -EINVAL;
161        }
162        if (int ret = static_cast<PhysicalNetwork*>(network)->addAsDefault()) {
163            return ret;
164        }
165    }
166
167    if (mDefaultNetId != NETID_UNSET) {
168        Network* network = getNetworkLocked(mDefaultNetId);
169        if (!network || network->getType() != Network::PHYSICAL) {
170            ALOGE("cannot find previously set default network with netId %u", mDefaultNetId);
171            return -ESRCH;
172        }
173        if (int ret = static_cast<PhysicalNetwork*>(network)->removeAsDefault()) {
174            return ret;
175        }
176    }
177
178    mDefaultNetId = netId;
179    return 0;
180}
181
182uint32_t NetworkController::getNetworkForDns(unsigned* netId, uid_t uid) const {
183    android::RWLock::AutoRLock lock(mRWLock);
184    Fwmark fwmark;
185    fwmark.protectedFromVpn = true;
186    fwmark.permission = PERMISSION_SYSTEM;
187    if (checkUserNetworkAccessLocked(uid, *netId) == 0) {
188        // If a non-zero NetId was explicitly specified, and the user has permission for that
189        // network, use that network's DNS servers. Do not fall through to the default network even
190        // if the explicitly selected network is a split tunnel VPN or a VPN without DNS servers.
191        fwmark.explicitlySelected = true;
192    } else {
193        // If the user is subject to a VPN and the VPN provides DNS servers, use those servers
194        // (possibly falling through to the default network if the VPN doesn't provide a route to
195        // them). Otherwise, use the default network's DNS servers.
196        VirtualNetwork* virtualNetwork = getVirtualNetworkForUserLocked(uid);
197        if (virtualNetwork && virtualNetwork->getHasDns()) {
198            *netId = virtualNetwork->getNetId();
199        } else {
200            *netId = mDefaultNetId;
201        }
202    }
203    fwmark.netId = *netId;
204    return fwmark.intValue;
205}
206
207// Returns the NetId that a given UID would use if no network is explicitly selected. Specifically,
208// the VPN that applies to the UID if any; otherwise, the default network.
209unsigned NetworkController::getNetworkForUser(uid_t uid) const {
210    android::RWLock::AutoRLock lock(mRWLock);
211    if (VirtualNetwork* virtualNetwork = getVirtualNetworkForUserLocked(uid)) {
212        return virtualNetwork->getNetId();
213    }
214    return mDefaultNetId;
215}
216
217// Returns the NetId that will be set when a socket connect()s. This is the bypassable VPN that
218// applies to the user if any; otherwise, the default network.
219//
220// In general, we prefer to always set the default network's NetId in connect(), so that if the VPN
221// is a split-tunnel and disappears later, the socket continues working (since the default network's
222// NetId is still valid). Secure VPNs will correctly grab the socket's traffic since they have a
223// high-priority routing rule that doesn't care what NetId the socket has.
224//
225// But bypassable VPNs have a very low priority rule, so we need to mark the socket with the
226// bypassable VPN's NetId if we expect it to get any traffic at all. If the bypassable VPN is a
227// split-tunnel, that's okay, because we have fallthrough rules that will direct the fallthrough
228// traffic to the default network. But it does mean that if the bypassable VPN goes away (and thus
229// the fallthrough rules also go away), the socket that used to fallthrough to the default network
230// will stop working.
231unsigned NetworkController::getNetworkForConnect(uid_t uid) const {
232    android::RWLock::AutoRLock lock(mRWLock);
233    VirtualNetwork* virtualNetwork = getVirtualNetworkForUserLocked(uid);
234    if (virtualNetwork && !virtualNetwork->isSecure()) {
235        return virtualNetwork->getNetId();
236    }
237    return mDefaultNetId;
238}
239
240void NetworkController::getNetworkContext(
241        unsigned netId, uid_t uid, struct android_net_context* netcontext) const {
242    struct android_net_context nc = {
243            .app_netid = netId,
244            .app_mark = MARK_UNSET,
245            .dns_netid = netId,
246            .dns_mark = MARK_UNSET,
247            .uid = uid,
248    };
249
250    if (nc.app_netid == NETID_UNSET) {
251        nc.app_netid = getNetworkForConnect(uid);
252    }
253    Fwmark fwmark;
254    fwmark.netId = nc.app_netid;
255    nc.app_mark = fwmark.intValue;
256
257    nc.dns_mark = getNetworkForDns(&(nc.dns_netid), uid);
258
259    if (netcontext) {
260        *netcontext = nc;
261    }
262}
263
264unsigned NetworkController::getNetworkForInterface(const char* interface) const {
265    android::RWLock::AutoRLock lock(mRWLock);
266    for (const auto& entry : mNetworks) {
267        if (entry.second->hasInterface(interface)) {
268            return entry.first;
269        }
270    }
271    return NETID_UNSET;
272}
273
274bool NetworkController::isVirtualNetwork(unsigned netId) const {
275    android::RWLock::AutoRLock lock(mRWLock);
276    Network* network = getNetworkLocked(netId);
277    return network && network->getType() == Network::VIRTUAL;
278}
279
280int NetworkController::createPhysicalNetwork(unsigned netId, Permission permission) {
281    if (!((MIN_NET_ID <= netId && netId <= MAX_NET_ID) ||
282          (MIN_OEM_ID <= netId && netId <= MAX_OEM_ID))) {
283        ALOGE("invalid netId %u", netId);
284        return -EINVAL;
285    }
286
287    if (isValidNetwork(netId)) {
288        ALOGE("duplicate netId %u", netId);
289        return -EEXIST;
290    }
291
292    PhysicalNetwork* physicalNetwork = new PhysicalNetwork(netId, mDelegateImpl);
293    if (int ret = physicalNetwork->setPermission(permission)) {
294        ALOGE("inconceivable! setPermission cannot fail on an empty network");
295        delete physicalNetwork;
296        return ret;
297    }
298
299    android::RWLock::AutoWLock lock(mRWLock);
300    mNetworks[netId] = physicalNetwork;
301    return 0;
302}
303
304int NetworkController::createVirtualNetwork(unsigned netId, bool hasDns, bool secure) {
305    if (!(MIN_NET_ID <= netId && netId <= MAX_NET_ID)) {
306        ALOGE("invalid netId %u", netId);
307        return -EINVAL;
308    }
309
310    if (isValidNetwork(netId)) {
311        ALOGE("duplicate netId %u", netId);
312        return -EEXIST;
313    }
314
315    android::RWLock::AutoWLock lock(mRWLock);
316    if (int ret = modifyFallthroughLocked(netId, true)) {
317        return ret;
318    }
319    mNetworks[netId] = new VirtualNetwork(netId, hasDns, secure);
320    return 0;
321}
322
323int NetworkController::destroyNetwork(unsigned netId) {
324    if (netId == LOCAL_NET_ID) {
325        ALOGE("cannot destroy local network");
326        return -EINVAL;
327    }
328    if (!isValidNetwork(netId)) {
329        ALOGE("no such netId %u", netId);
330        return -ENONET;
331    }
332
333    // TODO: ioctl(SIOCKILLADDR, ...) to kill all sockets on the old network.
334
335    android::RWLock::AutoWLock lock(mRWLock);
336    Network* network = getNetworkLocked(netId);
337
338    // If we fail to destroy a network, things will get stuck badly. Therefore, unlike most of the
339    // other network code, ignore failures and attempt to clear out as much state as possible, even
340    // if we hit an error on the way. Return the first error that we see.
341    int ret = network->clearInterfaces();
342
343    if (mDefaultNetId == netId) {
344        if (int err = static_cast<PhysicalNetwork*>(network)->removeAsDefault()) {
345            ALOGE("inconceivable! removeAsDefault cannot fail on an empty network");
346            if (!ret) {
347                ret = err;
348            }
349        }
350        mDefaultNetId = NETID_UNSET;
351    } else if (network->getType() == Network::VIRTUAL) {
352        if (int err = modifyFallthroughLocked(netId, false)) {
353            if (!ret) {
354                ret = err;
355            }
356        }
357    }
358    mNetworks.erase(netId);
359    delete network;
360    _resolv_delete_cache_for_net(netId);
361    return ret;
362}
363
364int NetworkController::addInterfaceToNetwork(unsigned netId, const char* interface) {
365    if (!isValidNetwork(netId)) {
366        ALOGE("no such netId %u", netId);
367        return -ENONET;
368    }
369
370    unsigned existingNetId = getNetworkForInterface(interface);
371    if (existingNetId != NETID_UNSET && existingNetId != netId) {
372        ALOGE("interface %s already assigned to netId %u", interface, existingNetId);
373        return -EBUSY;
374    }
375
376    android::RWLock::AutoWLock lock(mRWLock);
377    return getNetworkLocked(netId)->addInterface(interface);
378}
379
380int NetworkController::removeInterfaceFromNetwork(unsigned netId, const char* interface) {
381    if (!isValidNetwork(netId)) {
382        ALOGE("no such netId %u", netId);
383        return -ENONET;
384    }
385
386    android::RWLock::AutoWLock lock(mRWLock);
387    return getNetworkLocked(netId)->removeInterface(interface);
388}
389
390Permission NetworkController::getPermissionForUser(uid_t uid) const {
391    android::RWLock::AutoRLock lock(mRWLock);
392    return getPermissionForUserLocked(uid);
393}
394
395void NetworkController::setPermissionForUsers(Permission permission,
396                                              const std::vector<uid_t>& uids) {
397    android::RWLock::AutoWLock lock(mRWLock);
398    for (uid_t uid : uids) {
399        mUsers[uid] = permission;
400    }
401}
402
403int NetworkController::checkUserNetworkAccess(uid_t uid, unsigned netId) const {
404    android::RWLock::AutoRLock lock(mRWLock);
405    return checkUserNetworkAccessLocked(uid, netId);
406}
407
408int NetworkController::setPermissionForNetworks(Permission permission,
409                                                const std::vector<unsigned>& netIds) {
410    android::RWLock::AutoWLock lock(mRWLock);
411    for (unsigned netId : netIds) {
412        Network* network = getNetworkLocked(netId);
413        if (!network) {
414            ALOGE("no such netId %u", netId);
415            return -ENONET;
416        }
417        if (network->getType() != Network::PHYSICAL) {
418            ALOGE("cannot set permissions on non-physical network with netId %u", netId);
419            return -EINVAL;
420        }
421
422        // TODO: ioctl(SIOCKILLADDR, ...) to kill socets on the network that don't have permission.
423
424        if (int ret = static_cast<PhysicalNetwork*>(network)->setPermission(permission)) {
425            return ret;
426        }
427    }
428    return 0;
429}
430
431int NetworkController::addUsersToNetwork(unsigned netId, const UidRanges& uidRanges) {
432    android::RWLock::AutoWLock lock(mRWLock);
433    Network* network = getNetworkLocked(netId);
434    if (!network) {
435        ALOGE("no such netId %u", netId);
436        return -ENONET;
437    }
438    if (network->getType() != Network::VIRTUAL) {
439        ALOGE("cannot add users to non-virtual network with netId %u", netId);
440        return -EINVAL;
441    }
442    if (int ret = static_cast<VirtualNetwork*>(network)->addUsers(uidRanges)) {
443        return ret;
444    }
445    return 0;
446}
447
448int NetworkController::removeUsersFromNetwork(unsigned netId, const UidRanges& uidRanges) {
449    android::RWLock::AutoWLock lock(mRWLock);
450    Network* network = getNetworkLocked(netId);
451    if (!network) {
452        ALOGE("no such netId %u", netId);
453        return -ENONET;
454    }
455    if (network->getType() != Network::VIRTUAL) {
456        ALOGE("cannot remove users from non-virtual network with netId %u", netId);
457        return -EINVAL;
458    }
459    if (int ret = static_cast<VirtualNetwork*>(network)->removeUsers(uidRanges)) {
460        return ret;
461    }
462    return 0;
463}
464
465int NetworkController::addRoute(unsigned netId, const char* interface, const char* destination,
466                                const char* nexthop, bool legacy, uid_t uid) {
467    return modifyRoute(netId, interface, destination, nexthop, true, legacy, uid);
468}
469
470int NetworkController::removeRoute(unsigned netId, const char* interface, const char* destination,
471                                   const char* nexthop, bool legacy, uid_t uid) {
472    return modifyRoute(netId, interface, destination, nexthop, false, legacy, uid);
473}
474
475bool NetworkController::canProtect(uid_t uid) const {
476    android::RWLock::AutoRLock lock(mRWLock);
477    return ((getPermissionForUserLocked(uid) & PERMISSION_SYSTEM) == PERMISSION_SYSTEM) ||
478           mProtectableUsers.find(uid) != mProtectableUsers.end();
479}
480
481void NetworkController::allowProtect(const std::vector<uid_t>& uids) {
482    android::RWLock::AutoWLock lock(mRWLock);
483    mProtectableUsers.insert(uids.begin(), uids.end());
484}
485
486void NetworkController::denyProtect(const std::vector<uid_t>& uids) {
487    android::RWLock::AutoWLock lock(mRWLock);
488    for (uid_t uid : uids) {
489        mProtectableUsers.erase(uid);
490    }
491}
492
493bool NetworkController::isValidNetwork(unsigned netId) const {
494    android::RWLock::AutoRLock lock(mRWLock);
495    return getNetworkLocked(netId);
496}
497
498Network* NetworkController::getNetworkLocked(unsigned netId) const {
499    auto iter = mNetworks.find(netId);
500    return iter == mNetworks.end() ? NULL : iter->second;
501}
502
503VirtualNetwork* NetworkController::getVirtualNetworkForUserLocked(uid_t uid) const {
504    for (const auto& entry : mNetworks) {
505        if (entry.second->getType() == Network::VIRTUAL) {
506            VirtualNetwork* virtualNetwork = static_cast<VirtualNetwork*>(entry.second);
507            if (virtualNetwork->appliesToUser(uid)) {
508                return virtualNetwork;
509            }
510        }
511    }
512    return NULL;
513}
514
515Permission NetworkController::getPermissionForUserLocked(uid_t uid) const {
516    auto iter = mUsers.find(uid);
517    if (iter != mUsers.end()) {
518        return iter->second;
519    }
520    return uid < FIRST_APPLICATION_UID ? PERMISSION_SYSTEM : PERMISSION_NONE;
521}
522
523int NetworkController::checkUserNetworkAccessLocked(uid_t uid, unsigned netId) const {
524    Network* network = getNetworkLocked(netId);
525    if (!network) {
526        return -ENONET;
527    }
528
529    // If uid is INVALID_UID, this likely means that we were unable to retrieve the UID of the peer
530    // (using SO_PEERCRED). Be safe and deny access to the network, even if it's valid.
531    if (uid == INVALID_UID) {
532        return -EREMOTEIO;
533    }
534    Permission userPermission = getPermissionForUserLocked(uid);
535    if ((userPermission & PERMISSION_SYSTEM) == PERMISSION_SYSTEM) {
536        return 0;
537    }
538    if (network->getType() == Network::VIRTUAL) {
539        return static_cast<VirtualNetwork*>(network)->appliesToUser(uid) ? 0 : -EPERM;
540    }
541    VirtualNetwork* virtualNetwork = getVirtualNetworkForUserLocked(uid);
542    if (virtualNetwork && virtualNetwork->isSecure() &&
543            mProtectableUsers.find(uid) == mProtectableUsers.end()) {
544        return -EPERM;
545    }
546    Permission networkPermission = static_cast<PhysicalNetwork*>(network)->getPermission();
547    return ((userPermission & networkPermission) == networkPermission) ? 0 : -EACCES;
548}
549
550int NetworkController::modifyRoute(unsigned netId, const char* interface, const char* destination,
551                                   const char* nexthop, bool add, bool legacy, uid_t uid) {
552    if (!isValidNetwork(netId)) {
553        ALOGE("no such netId %u", netId);
554        return -ENONET;
555    }
556    unsigned existingNetId = getNetworkForInterface(interface);
557    if (existingNetId == NETID_UNSET) {
558        ALOGE("interface %s not assigned to any netId", interface);
559        return -ENODEV;
560    }
561    if (existingNetId != netId) {
562        ALOGE("interface %s assigned to netId %u, not %u", interface, existingNetId, netId);
563        return -ENOENT;
564    }
565
566    RouteController::TableType tableType;
567    if (netId == LOCAL_NET_ID) {
568        tableType = RouteController::LOCAL_NETWORK;
569    } else if (legacy) {
570        if ((getPermissionForUser(uid) & PERMISSION_SYSTEM) == PERMISSION_SYSTEM) {
571            tableType = RouteController::LEGACY_SYSTEM;
572        } else {
573            tableType = RouteController::LEGACY_NETWORK;
574        }
575    } else {
576        tableType = RouteController::INTERFACE;
577    }
578
579    return add ? RouteController::addRoute(interface, destination, nexthop, tableType) :
580                 RouteController::removeRoute(interface, destination, nexthop, tableType);
581}
582
583int NetworkController::modifyFallthroughLocked(unsigned vpnNetId, bool add) {
584    if (mDefaultNetId == NETID_UNSET) {
585        return 0;
586    }
587    Network* network = getNetworkLocked(mDefaultNetId);
588    if (!network) {
589        ALOGE("cannot find previously set default network with netId %u", mDefaultNetId);
590        return -ESRCH;
591    }
592    if (network->getType() != Network::PHYSICAL) {
593        ALOGE("inconceivable! default network must be a physical network");
594        return -EINVAL;
595    }
596    Permission permission = static_cast<PhysicalNetwork*>(network)->getPermission();
597    for (const auto& physicalInterface : network->getInterfaces()) {
598        if (int ret = mDelegateImpl->modifyFallthrough(vpnNetId, physicalInterface, permission,
599                                                       add)) {
600            return ret;
601        }
602    }
603    return 0;
604}
605