• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #pragma once
18 
19 #include <android-base/thread_annotations.h>
20 #include <android/multinetwork.h>
21 
22 
23 #include "NetdConstants.h"
24 #include "Permission.h"
25 #include "PhysicalNetwork.h"
26 #include "UnreachableNetwork.h"
27 #include "android/net/INetd.h"
28 #include "netdutils/DumpWriter.h"
29 
30 #include <sys/types.h>
31 #include <list>
32 #include <map>
33 #include <set>
34 #include <shared_mutex>
35 #include <unordered_map>
36 #include <unordered_set>
37 #include <vector>
38 
39 struct android_net_context;
40 
41 namespace android::net {
42 
43 typedef std::shared_lock<std::shared_mutex> ScopedRLock;
44 typedef std::lock_guard<std::shared_mutex> ScopedWLock;
45 
46 constexpr uint32_t kHandleMagic = 0xcafed00d;
47 
48 // Utility to convert from netId to net_handle_t. Doing this here as opposed to exporting
49 // from net.c as it may have NDK implications. Besides no conversion available in net.c for
50 // obtaining handle given netId.
51 // TODO: Use getnetidfromhandle() in net.c.
netHandleToNetId(net_handle_t fromNetHandle)52 static inline unsigned netHandleToNetId(net_handle_t fromNetHandle) {
53     const uint32_t k32BitMask = 0xffffffff;
54     // This value MUST be kept in sync with the corresponding value in
55     // the android.net.Network#getNetworkHandle() implementation.
56 
57     // Check for minimum acceptable version of the API in the low bits.
58     if (fromNetHandle != NETWORK_UNSPECIFIED &&
59         (fromNetHandle & k32BitMask) != kHandleMagic) {
60         return 0;
61     }
62 
63     return ((fromNetHandle >> (CHAR_BIT * sizeof(k32BitMask))) & k32BitMask);
64 }
65 
66 // Utility to convert from nethandle to netid, keep in sync with getNetworkHandle
67 // in Network.java.
netIdToNetHandle(unsigned fromNetId)68 static inline net_handle_t netIdToNetHandle(unsigned fromNetId) {
69     if (!fromNetId) {
70         return NETWORK_UNSPECIFIED;
71     }
72     return (((net_handle_t)fromNetId << 32) | kHandleMagic);
73 }
74 
75 class Network;
76 class UidRanges;
77 class VirtualNetwork;
78 
79 /*
80  * Keeps track of default, per-pid, and per-uid-range network selection, as
81  * well as the mark associated with each network. Networks are identified
82  * by netid. In all set* commands netid == 0 means "unspecified" and is
83  * equivalent to clearing the mapping.
84  */
85 class NetworkController {
86 public:
87     // NetIds 53..98 are reserved for future use.
88     static constexpr int MIN_OEM_ID = 1;
89     static constexpr int MAX_OEM_ID = 50;
90     static constexpr int LOCAL_NET_ID = INetd::LOCAL_NET_ID;
91     static constexpr int DUMMY_NET_ID = INetd::DUMMY_NET_ID;
92     static constexpr int UNREACHABLE_NET_ID = INetd::UNREACHABLE_NET_ID;
93 
94     // Route mode for modify route
95     enum RouteOperation { ROUTE_ADD, ROUTE_UPDATE, ROUTE_REMOVE };
96 
97     NetworkController();
98 
99     unsigned getDefaultNetwork() const;
100     [[nodiscard]] int setDefaultNetwork(unsigned netId);
101 
102     unsigned getNetworkForUser(uid_t uid) const;
103     unsigned getNetworkForConnect(uid_t uid) const;
104     void getNetworkContext(unsigned netId, uid_t uid, struct android_net_context* netcontext) const;
105     unsigned getNetworkForInterface(const char* interface) const;
106     bool isVirtualNetwork(unsigned netId) const;
107 
108     [[nodiscard]] int createPhysicalNetwork(unsigned netId, Permission permission);
109     [[nodiscard]] int createPhysicalOemNetwork(Permission permission, unsigned* netId);
110     [[nodiscard]] int createVirtualNetwork(unsigned netId, bool secure, NativeVpnType vpnType);
111     [[nodiscard]] int destroyNetwork(unsigned netId);
112 
113     [[nodiscard]] int addInterfaceToNetwork(unsigned netId, const char* interface);
114     [[nodiscard]] int removeInterfaceFromNetwork(unsigned netId, const char* interface);
115 
116     Permission getPermissionForUser(uid_t uid) const;
117     void setPermissionForUsers(Permission permission, const std::vector<uid_t>& uids);
118     int checkUserNetworkAccess(uid_t uid, unsigned netId) const;
119     [[nodiscard]] int setPermissionForNetworks(Permission permission,
120                                                const std::vector<unsigned>& netIds);
121 
122     [[nodiscard]] int addUsersToNetwork(unsigned netId, const UidRanges& uidRanges,
123                                         uint32_t subPriority);
124     [[nodiscard]] int removeUsersFromNetwork(unsigned netId, const UidRanges& uidRanges,
125                                              uint32_t subPriority);
126 
127     // |nexthop| can be NULL (to indicate a directly-connected route), "unreachable" (to indicate a
128     // route that's blocked), "throw" (to indicate the lack of a match), or a regular IP address.
129     //
130     // Routes are added to tables determined by the interface, so only |interface| is actually used.
131     // |netId| is given only to sanity check that the interface has the correct netId.
132     [[nodiscard]] int addRoute(unsigned netId, const char* interface, const char* destination,
133                                const char* nexthop, bool legacy, uid_t uid, int mtu);
134     [[nodiscard]] int updateRoute(unsigned netId, const char* interface, const char* destination,
135                                   const char* nexthop, bool legacy, uid_t uid, int mtu);
136     [[nodiscard]] int removeRoute(unsigned netId, const char* interface, const char* destination,
137                                   const char* nexthop, bool legacy, uid_t uid);
138 
139     // Notes that the specified address has appeared on the specified interface.
140     void addInterfaceAddress(unsigned ifIndex, const char* address);
141     // Notes that the specified address has been removed from the specified interface.
142     // Returns true if we should destroy sockets on this address.
143     bool removeInterfaceAddress(unsigned ifIndex, const char* address);
144 
145     bool canProtect(uid_t uid) const;
146     void allowProtect(const std::vector<uid_t>& uids);
147     void denyProtect(const std::vector<uid_t>& uids);
148 
149     void dump(netdutils::DumpWriter& dw);
150 
151   private:
152     bool isValidNetworkLocked(unsigned netId) const;
153     Network* getNetworkLocked(unsigned netId) const;
154 
155     // Sets |*netId| to an appropriate NetId to use for DNS for the given user. Call with |*netId|
156     // set to a non-NETID_UNSET value if the user already has indicated a preference. Returns the
157     // fwmark value to set on the socket when performing the DNS request.
158     uint32_t getNetworkForDnsLocked(unsigned* netId, uid_t uid) const;
159     unsigned getNetworkForConnectLocked(uid_t uid) const;
160     unsigned getNetworkForInterfaceLocked(const char* interface) const;
161     bool canProtectLocked(uid_t uid) const;
162     bool isVirtualNetworkLocked(unsigned netId) const;
163     VirtualNetwork* getVirtualNetworkForUserLocked(uid_t uid) const;
164     Network* getPhysicalOrUnreachableNetworkForUserLocked(uid_t uid) const;
165     Permission getPermissionForUserLocked(uid_t uid) const;
166     int checkUserNetworkAccessLocked(uid_t uid, unsigned netId) const;
167     [[nodiscard]] int createPhysicalNetworkLocked(unsigned netId, Permission permission);
168 
169     [[nodiscard]] int modifyRoute(unsigned netId, const char* interface, const char* destination,
170                                   const char* nexthop, RouteOperation op, bool legacy, uid_t uid,
171                                   int mtu);
172     [[nodiscard]] int modifyFallthroughLocked(unsigned vpnNetId, bool add);
173     void updateTcpSocketMonitorPolling();
174 
175     class DelegateImpl;
176     DelegateImpl* const mDelegateImpl;
177 
178     // mRWLock guards all accesses to mDefaultNetId, mNetworks, mUsers, mProtectableUsers,
179     // mIfindexToLastNetId and mAddressToIfindices.
180     mutable std::shared_mutex mRWLock;
181     unsigned mDefaultNetId;
182     std::map<unsigned, Network*> mNetworks;  // Map keys are NetIds.
183     std::map<uid_t, Permission> mUsers;
184     std::set<uid_t> mProtectableUsers;
185     // Map interface (ifIndex) to its current NetId, or the last NetId if the interface was removed
186     // from the network and not added to another network. This state facilitates the interface to
187     // NetId lookup during RTM_DELADDR (NetworkController::removeInterfaceAddress), when the
188     // interface in question might already have been removed from the network.
189     // An interface is added to this map when it is added to a network and removed from this map
190     // when its network is destroyed.
191     std::unordered_map<unsigned, unsigned> mIfindexToLastNetId;
192     // Map IP address to the list of active interfaces (ifIndex) that have that address.
193     // Also contains IP addresses configured on interfaces that have not been added to any network.
194     // TODO: Does not track IP addresses present when netd is started or restarts after a crash.
195     // This is not a problem for its intended use (tracking IP addresses on VPN interfaces), but
196     // we should fix it.
197     std::unordered_map<std::string, std::unordered_set<unsigned>> mAddressToIfindices;
198 
199 };
200 
201 }  // namespace android::net
202