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