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