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