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