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