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 #include "FwmarkServer.h"
18
19 #include <net/if.h>
20 #include <netinet/in.h>
21 #include <selinux/selinux.h>
22 #include <sys/socket.h>
23 #include <unistd.h>
24 #include <utils/String16.h>
25
26 #include <android-base/cmsg.h>
27 #include <android-base/logging.h>
28 #include <android-base/properties.h>
29 #include <binder/IServiceManager.h>
30 #include <netd_resolv/resolv.h> // NETID_UNSET
31
32 #include "Fwmark.h"
33 #include "FwmarkCommand.h"
34 #include "NetdConstants.h"
35 #include "NetworkController.h"
36
37 #include "NetdUpdatablePublic.h"
38
39 using android::base::ReceiveFileDescriptorVector;
40 using android::base::unique_fd;
41 using android::net::metrics::INetdEventListener;
42
43 namespace android {
44 namespace net {
45
46 constexpr const char *SYSTEM_SERVER_CONTEXT = "u:r:system_server:s0";
47
isSystemServer(SocketClient * client)48 bool isSystemServer(SocketClient* client) {
49 if (client->getUid() != AID_SYSTEM) {
50 return false;
51 }
52
53 char *context;
54 if (getpeercon(client->getSocket(), &context)) {
55 return false;
56 }
57
58 // We can't use context_new and context_type_get as they're private to libselinux. So just do
59 // a string match instead.
60 bool ret = !strcmp(context, SYSTEM_SERVER_CONTEXT);
61 freecon(context);
62
63 return ret;
64 }
65
FwmarkServer(NetworkController * networkController,EventReporter * eventReporter)66 FwmarkServer::FwmarkServer(NetworkController* networkController, EventReporter* eventReporter)
67 : SocketListener(SOCKET_NAME, true),
68 mNetworkController(networkController),
69 mEventReporter(eventReporter),
70 mRedirectSocketCalls(
71 android::base::GetBoolProperty("ro.vendor.redirect_socket_calls", false)) {}
72
onDataAvailable(SocketClient * client)73 bool FwmarkServer::onDataAvailable(SocketClient* client) {
74 int socketFd = -1;
75 int error = processClient(client, &socketFd);
76 if (socketFd >= 0) {
77 close(socketFd);
78 }
79
80 // Always send a response even if there were connection errors or read errors, so that we don't
81 // inadvertently cause the client to hang (which always waits for a response).
82 client->sendData(&error, sizeof(error));
83
84 // Always close the client connection (by returning false). This prevents a DoS attack where
85 // the client issues multiple commands on the same connection, never reading the responses,
86 // causing its receive buffer to fill up, and thus causing our client->sendData() to block.
87 return false;
88 }
89
hasDestinationAddress(FwmarkCommand::CmdId cmdId,bool redirectSocketCalls)90 static bool hasDestinationAddress(FwmarkCommand::CmdId cmdId, bool redirectSocketCalls) {
91 if (redirectSocketCalls) {
92 return (cmdId == FwmarkCommand::ON_SENDTO || cmdId == FwmarkCommand::ON_CONNECT ||
93 cmdId == FwmarkCommand::ON_SENDMSG || cmdId == FwmarkCommand::ON_SENDMMSG ||
94 cmdId == FwmarkCommand::ON_CONNECT_COMPLETE);
95 } else {
96 return (cmdId == FwmarkCommand::ON_CONNECT || cmdId == FwmarkCommand::ON_CONNECT_COMPLETE);
97 }
98 }
99
processClient(SocketClient * client,int * socketFd)100 int FwmarkServer::processClient(SocketClient* client, int* socketFd) {
101 FwmarkCommand command;
102 FwmarkConnectInfo connectInfo;
103
104 char buf[sizeof(command) + sizeof(connectInfo)];
105 std::vector<unique_fd> received_fds;
106 ssize_t messageLength =
107 ReceiveFileDescriptorVector(client->getSocket(), buf, sizeof(buf), 1, &received_fds);
108
109 if (messageLength < 0) {
110 return -errno;
111 } else if (messageLength == 0) {
112 return -ESHUTDOWN;
113 }
114
115 memcpy(&command, buf, sizeof(command));
116 memcpy(&connectInfo, buf + sizeof(command), sizeof(connectInfo));
117
118 size_t expectedLen = sizeof(command);
119 if (hasDestinationAddress(command.cmdId, mRedirectSocketCalls)) {
120 expectedLen += sizeof(connectInfo);
121 }
122
123 if (messageLength != static_cast<ssize_t>(expectedLen)) {
124 return -EBADMSG;
125 }
126
127 Permission permission = mNetworkController->getPermissionForUser(client->getUid());
128
129 if (command.cmdId == FwmarkCommand::QUERY_USER_ACCESS) {
130 if ((permission & PERMISSION_SYSTEM) != PERMISSION_SYSTEM) {
131 return -EPERM;
132 }
133 return mNetworkController->checkUserNetworkAccess(command.uid, command.netId);
134 }
135
136 if (received_fds.size() != 1) {
137 LOG(ERROR) << "FwmarkServer received " << received_fds.size() << " fds from client?";
138 return -EBADF;
139 } else if (received_fds[0] < 0) {
140 LOG(ERROR) << "FwmarkServer received fd -1 from ReceiveFileDescriptorVector?";
141 return -EBADF;
142 }
143
144 *socketFd = received_fds[0].release();
145
146 int family;
147 socklen_t familyLen = sizeof(family);
148 if (getsockopt(*socketFd, SOL_SOCKET, SO_DOMAIN, &family, &familyLen) == -1) {
149 return -errno;
150 }
151 if (!FwmarkCommand::isSupportedFamily(family)) {
152 return -EAFNOSUPPORT;
153 }
154
155 Fwmark fwmark;
156 socklen_t fwmarkLen = sizeof(fwmark.intValue);
157 if (getsockopt(*socketFd, SOL_SOCKET, SO_MARK, &fwmark.intValue, &fwmarkLen) == -1) {
158 return -errno;
159 }
160
161 switch (command.cmdId) {
162 case FwmarkCommand::ON_ACCEPT: {
163 // Called after a socket accept(). The kernel would've marked the NetId and necessary
164 // permissions bits, so we just add the rest of the user's permissions here.
165 permission = static_cast<Permission>(permission | fwmark.permission);
166 break;
167 }
168
169 case FwmarkCommand::ON_CONNECT: {
170 // Called before a socket connect() happens. Set an appropriate NetId into the fwmark so
171 // that the socket routes consistently over that network. Do this even if the socket
172 // already has a NetId, so that calling connect() multiple times still works.
173 //
174 // But if the explicit bit was set, the existing NetId was explicitly preferred (and not
175 // a case of connect() being called multiple times). Don't reset the NetId in that case.
176 //
177 // An "appropriate" NetId is the NetId of a bypassable VPN that applies to the user, or
178 // failing that, the default network. We'll never set the NetId of a secure VPN here.
179 // See the comments in the implementation of getNetworkForConnect() for more details.
180 //
181 // If the protect bit is set, this could be either a system proxy (e.g.: the dns proxy
182 // or the download manager) acting on behalf of another user, or a VPN provider. If it's
183 // a proxy, we shouldn't reset the NetId. If it's a VPN provider, we should set the
184 // default network's NetId.
185 //
186 // There's no easy way to tell the difference between a proxy and a VPN app. We can't
187 // use PERMISSION_SYSTEM to identify the proxy because a VPN app may also have those
188 // permissions. So we use the following heuristic:
189 //
190 // If it's a proxy, but the existing NetId is not a VPN, that means the user (that the
191 // proxy is acting on behalf of) is not subject to a VPN, so the proxy must have picked
192 // the default network's NetId. So, it's okay to replace that with the current default
193 // network's NetId (which in all likelihood is the same).
194 //
195 // Conversely, if it's a VPN provider, the existing NetId cannot be a VPN. The only time
196 // we set a VPN's NetId into a socket without setting the explicit bit is here, in
197 // ON_CONNECT, but we won't do that if the socket has the protect bit set. If the VPN
198 // provider connect()ed (and got the VPN NetId set) and then called protect(), we
199 // would've unset the NetId in PROTECT_FROM_VPN below.
200 //
201 // So, overall (when the explicit bit is not set but the protect bit is set), if the
202 // existing NetId is a VPN, don't reset it. Else, set the default network's NetId.
203 if (!fwmark.explicitlySelected) {
204 if (family == AF_INET6 && connectInfo.addr.sin6.sin6_scope_id &&
205 IN6_IS_ADDR_LINKLOCAL(&connectInfo.addr.sin6.sin6_addr)) {
206 fwmark.netId = mNetworkController->getNetworkForInterface(
207 connectInfo.addr.sin6.sin6_scope_id);
208 } else if (!fwmark.protectedFromVpn) {
209 fwmark.netId = mNetworkController->getNetworkForConnect(client->getUid());
210 } else if (!mNetworkController->isVirtualNetwork(fwmark.netId)) {
211 fwmark.netId = mNetworkController->getDefaultNetwork();
212 }
213 }
214 break;
215 }
216
217 case FwmarkCommand::ON_CONNECT_COMPLETE: {
218 // Called after a socket connect() completes.
219 // This reports connect event including netId, destination IP address, destination port,
220 // uid, connect latency, and connect errno if any.
221
222 // Skip reporting if connect() happened on a UDP socket.
223 int socketProto;
224 socklen_t intSize = sizeof(socketProto);
225 const int ret = getsockopt(*socketFd, SOL_SOCKET, SO_PROTOCOL, &socketProto, &intSize);
226 if ((ret != 0) || (socketProto == IPPROTO_UDP)) {
227 break;
228 }
229
230 android::sp<android::net::metrics::INetdEventListener> netdEventListener =
231 mEventReporter->getNetdEventListener();
232
233 if (netdEventListener != nullptr) {
234 char addrstr[INET6_ADDRSTRLEN];
235 char portstr[sizeof("65536")];
236 const int ret = getnameinfo((sockaddr*) &connectInfo.addr, sizeof(connectInfo.addr),
237 addrstr, sizeof(addrstr), portstr, sizeof(portstr),
238 NI_NUMERICHOST | NI_NUMERICSERV);
239
240 netdEventListener->onConnectEvent(fwmark.netId, connectInfo.error,
241 connectInfo.latencyMs,
242 (ret == 0) ? String16(addrstr) : String16(""),
243 (ret == 0) ? strtoul(portstr, nullptr, 10) : 0, client->getUid());
244 }
245 break;
246 }
247
248 case FwmarkCommand::ON_SENDMMSG:
249 case FwmarkCommand::ON_SENDMSG:
250 case FwmarkCommand::ON_SENDTO: {
251 return 0;
252 }
253
254 case FwmarkCommand::SELECT_NETWORK: {
255 fwmark.netId = command.netId;
256 if (command.netId == NETID_UNSET) {
257 fwmark.explicitlySelected = false;
258 fwmark.protectedFromVpn = false;
259 permission = PERMISSION_NONE;
260 } else {
261 if (int ret = mNetworkController->checkUserNetworkAccess(client->getUid(),
262 command.netId)) {
263 return ret;
264 }
265 fwmark.explicitlySelected = true;
266 fwmark.protectedFromVpn = mNetworkController->canProtect(client->getUid());
267 }
268 break;
269 }
270
271 case FwmarkCommand::PROTECT_FROM_VPN: {
272 if (!mNetworkController->canProtect(client->getUid())) {
273 return -EPERM;
274 }
275 // If a bypassable VPN's provider app calls connect() and then protect(), it will end up
276 // with a socket that looks like that of a system proxy but is not (see comments for
277 // ON_CONNECT above). So, reset the NetId.
278 //
279 // In any case, it's appropriate that if the socket has an implicit VPN NetId mark, the
280 // PROTECT_FROM_VPN command should unset it.
281 if (!fwmark.explicitlySelected && mNetworkController->isVirtualNetwork(fwmark.netId)) {
282 fwmark.netId = mNetworkController->getDefaultNetwork();
283 }
284 fwmark.protectedFromVpn = true;
285 permission = static_cast<Permission>(permission | fwmark.permission);
286 break;
287 }
288
289 case FwmarkCommand::SELECT_FOR_USER: {
290 if ((permission & PERMISSION_SYSTEM) != PERMISSION_SYSTEM) {
291 return -EPERM;
292 }
293 fwmark.netId = mNetworkController->getNetworkForUser(command.uid);
294 fwmark.protectedFromVpn = true;
295 break;
296 }
297
298 case FwmarkCommand::TAG_SOCKET: {
299 // If the UID is -1, tag as the caller's UID:
300 // - TrafficStats and NetworkManagementSocketTagger use -1 to indicate "use the
301 // caller's UID".
302 // - xt_qtaguid will see -1 on the command line, fail to parse it as a uint32_t, and
303 // fall back to current_fsuid().
304 if (static_cast<int>(command.uid) == -1) {
305 command.uid = client->getUid();
306 }
307 return libnetd_updatable_tagSocket(*socketFd, command.trafficCtrlInfo, command.uid,
308 client->getUid());
309 }
310
311 case FwmarkCommand::UNTAG_SOCKET: {
312 // Any process can untag a socket it has an fd for.
313 return libnetd_updatable_untagSocket(*socketFd);
314 }
315
316 default: {
317 // unknown command
318 return -EPROTO;
319 }
320 }
321
322 fwmark.permission = permission;
323
324 if (setsockopt(*socketFd, SOL_SOCKET, SO_MARK, &fwmark.intValue,
325 sizeof(fwmark.intValue)) == -1) {
326 return -errno;
327 }
328
329 return 0;
330 }
331
332 } // namespace net
333 } // namespace android
334