blob: edb046c4669cb453e4a7f97d1d161402feb5b496 [file] [log] [blame]
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +09001/*
2 * Copyright (C) 2016 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 <errno.h>
18#include <netdb.h>
19#include <string.h>
20#include <netinet/in.h>
21#include <netinet/tcp.h>
22#include <sys/socket.h>
23#include <sys/uio.h>
24
25#include <linux/netlink.h>
26#include <linux/sock_diag.h>
27#include <linux/inet_diag.h>
28
29#define LOG_TAG "Netd"
30
Lorenzo Colittifff4bd32016-04-14 00:56:01 +090031#include <android-base/strings.h>
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +090032#include <cutils/log.h>
33
Lorenzo Colittifbe76b92016-09-14 02:25:05 +090034#include "Fwmark.h"
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +090035#include "NetdConstants.h"
Lorenzo Colittifbe76b92016-09-14 02:25:05 +090036#include "Permission.h"
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +090037#include "SockDiag.h"
Robin Lee7e05cc92016-09-21 16:31:33 +090038#include "Stopwatch.h"
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +090039
Lorenzo Colittif32fc592016-02-15 01:09:14 +090040#include <chrono>
41
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +090042#ifndef SOCK_DESTROY
43#define SOCK_DESTROY 21
44#endif
45
Lorenzo Colittifbe76b92016-09-14 02:25:05 +090046#define INET_DIAG_BC_MARK_COND 10
47
Lorenzo Colitti7035f222017-02-13 18:29:00 +090048namespace android {
49namespace net {
50
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +090051namespace {
52
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +090053int checkError(int fd) {
54 struct {
55 nlmsghdr h;
56 nlmsgerr err;
57 } __attribute__((__packed__)) ack;
58 ssize_t bytesread = recv(fd, &ack, sizeof(ack), MSG_DONTWAIT | MSG_PEEK);
59 if (bytesread == -1) {
60 // Read failed (error), or nothing to read (good).
61 return (errno == EAGAIN) ? 0 : -errno;
62 } else if (bytesread == (ssize_t) sizeof(ack) && ack.h.nlmsg_type == NLMSG_ERROR) {
63 // We got an error. Consume it.
64 recv(fd, &ack, sizeof(ack), 0);
65 return ack.err.error;
66 } else {
67 // The kernel replied with something. Leave it to the caller.
68 return 0;
69 }
70}
71
72} // namespace
73
74bool SockDiag::open() {
75 if (hasSocks()) {
76 return false;
77 }
78
Nick Kralevichaf02b552016-12-20 08:40:35 -080079 mSock = socket(PF_NETLINK, SOCK_DGRAM | SOCK_CLOEXEC, NETLINK_INET_DIAG);
80 mWriteSock = socket(PF_NETLINK, SOCK_DGRAM | SOCK_CLOEXEC, NETLINK_INET_DIAG);
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +090081 if (!hasSocks()) {
82 closeSocks();
83 return false;
84 }
85
86 sockaddr_nl nl = { .nl_family = AF_NETLINK };
87 if ((connect(mSock, reinterpret_cast<sockaddr *>(&nl), sizeof(nl)) == -1) ||
88 (connect(mWriteSock, reinterpret_cast<sockaddr *>(&nl), sizeof(nl)) == -1)) {
89 closeSocks();
90 return false;
91 }
92
93 return true;
94}
95
Lorenzo Colitti94a7b432016-03-24 16:47:12 +090096int SockDiag::sendDumpRequest(uint8_t proto, uint8_t family, uint32_t states,
97 iovec *iov, int iovcnt) {
98 struct {
99 nlmsghdr nlh;
100 inet_diag_req_v2 req;
101 } __attribute__((__packed__)) request = {
102 .nlh = {
103 .nlmsg_type = SOCK_DIAG_BY_FAMILY,
104 .nlmsg_flags = NLM_F_REQUEST | NLM_F_DUMP,
105 },
106 .req = {
107 .sdiag_family = family,
108 .sdiag_protocol = proto,
109 .idiag_states = states,
110 },
111 };
112
113 size_t len = 0;
114 iov[0].iov_base = &request;
115 iov[0].iov_len = sizeof(request);
116 for (int i = 0; i < iovcnt; i++) {
117 len += iov[i].iov_len;
118 }
119 request.nlh.nlmsg_len = len;
120
121 if (writev(mSock, iov, iovcnt) != (ssize_t) len) {
122 return -errno;
123 }
124
125 return checkError(mSock);
126}
127
128int SockDiag::sendDumpRequest(uint8_t proto, uint8_t family, uint32_t states) {
129 iovec iov[] = {
130 { nullptr, 0 },
131 };
132 return sendDumpRequest(proto, family, states, iov, ARRAY_SIZE(iov));
133}
134
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +0900135int SockDiag::sendDumpRequest(uint8_t proto, uint8_t family, const char *addrstr) {
136 addrinfo hints = { .ai_flags = AI_NUMERICHOST };
137 addrinfo *res;
138 in6_addr mapped = { .s6_addr32 = { 0, 0, htonl(0xffff), 0 } };
139 int ret;
140
141 // TODO: refactor the netlink parsing code out of system/core, bring it into netd, and stop
142 // doing string conversions when they're not necessary.
143 if ((ret = getaddrinfo(addrstr, nullptr, &hints, &res)) != 0) {
144 return -EINVAL;
145 }
146
147 // So we don't have to call freeaddrinfo on every failure path.
148 ScopedAddrinfo resP(res);
149
150 void *addr;
151 uint8_t addrlen;
152 if (res->ai_family == AF_INET && family == AF_INET) {
153 in_addr& ina = reinterpret_cast<sockaddr_in*>(res->ai_addr)->sin_addr;
154 addr = &ina;
155 addrlen = sizeof(ina);
156 } else if (res->ai_family == AF_INET && family == AF_INET6) {
157 in_addr& ina = reinterpret_cast<sockaddr_in*>(res->ai_addr)->sin_addr;
158 mapped.s6_addr32[3] = ina.s_addr;
159 addr = &mapped;
160 addrlen = sizeof(mapped);
161 } else if (res->ai_family == AF_INET6 && family == AF_INET6) {
162 in6_addr& in6a = reinterpret_cast<sockaddr_in6*>(res->ai_addr)->sin6_addr;
163 addr = &in6a;
164 addrlen = sizeof(in6a);
165 } else {
166 return -EAFNOSUPPORT;
167 }
168
169 uint8_t prefixlen = addrlen * 8;
170 uint8_t yesjump = sizeof(inet_diag_bc_op) + sizeof(inet_diag_hostcond) + addrlen;
171 uint8_t nojump = yesjump + 4;
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +0900172
173 struct {
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +0900174 nlattr nla;
175 inet_diag_bc_op op;
176 inet_diag_hostcond cond;
Lorenzo Colitti94a7b432016-03-24 16:47:12 +0900177 } __attribute__((__packed__)) attrs = {
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +0900178 .nla = {
179 .nla_type = INET_DIAG_REQ_BYTECODE,
180 },
181 .op = {
182 INET_DIAG_BC_S_COND,
183 yesjump,
184 nojump,
185 },
186 .cond = {
187 family,
188 prefixlen,
189 -1,
190 {}
191 },
192 };
193
Lorenzo Colitti94a7b432016-03-24 16:47:12 +0900194 attrs.nla.nla_len = sizeof(attrs) + addrlen;
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +0900195
Lorenzo Colitti94a7b432016-03-24 16:47:12 +0900196 iovec iov[] = {
Lorenzo Colittifbe76b92016-09-14 02:25:05 +0900197 { nullptr, 0 },
198 { &attrs, sizeof(attrs) },
199 { addr, addrlen },
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +0900200 };
201
Lorenzo Colitti94a7b432016-03-24 16:47:12 +0900202 uint32_t states = ~(1 << TCP_TIME_WAIT);
203 return sendDumpRequest(proto, family, states, iov, ARRAY_SIZE(iov));
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +0900204}
205
Lorenzo Colitti0b733e42017-02-13 16:29:00 +0900206int SockDiag::readDiagMsg(uint8_t proto, const SockDiag::DestroyFilter& shouldDestroy) {
207 NetlinkDumpCallback callback = [this, proto, shouldDestroy] (nlmsghdr *nlh) {
208 if (nlh == nullptr) return;
209 const inet_diag_msg *msg = reinterpret_cast<inet_diag_msg *>(NLMSG_DATA(nlh));
210 if (shouldDestroy(proto, msg)) {
211 sockDestroy(proto, msg);
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +0900212 }
Lorenzo Colitti0b733e42017-02-13 16:29:00 +0900213 };
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +0900214
Lorenzo Colitti0b733e42017-02-13 16:29:00 +0900215 return processNetlinkDump(mSock, callback);
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +0900216}
217
Lorenzo Colittie5c3c992016-07-26 17:53:50 +0900218// Determines whether a socket is a loopback socket. Does not check socket state.
219bool SockDiag::isLoopbackSocket(const inet_diag_msg *msg) {
220 switch (msg->idiag_family) {
221 case AF_INET:
222 // Old kernels only copy the IPv4 address and leave the other 12 bytes uninitialized.
223 return IN_LOOPBACK(htonl(msg->id.idiag_src[0])) ||
224 IN_LOOPBACK(htonl(msg->id.idiag_dst[0])) ||
225 msg->id.idiag_src[0] == msg->id.idiag_dst[0];
226
227 case AF_INET6: {
228 const struct in6_addr *src = (const struct in6_addr *) &msg->id.idiag_src;
229 const struct in6_addr *dst = (const struct in6_addr *) &msg->id.idiag_dst;
230 return (IN6_IS_ADDR_V4MAPPED(src) && IN_LOOPBACK(src->s6_addr32[3])) ||
231 (IN6_IS_ADDR_V4MAPPED(dst) && IN_LOOPBACK(dst->s6_addr32[3])) ||
232 IN6_IS_ADDR_LOOPBACK(src) || IN6_IS_ADDR_LOOPBACK(dst) ||
233 !memcmp(src, dst, sizeof(*src));
234 }
235 default:
236 return false;
237 }
238}
239
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +0900240int SockDiag::sockDestroy(uint8_t proto, const inet_diag_msg *msg) {
Lorenzo Colittif32fc592016-02-15 01:09:14 +0900241 if (msg == nullptr) {
242 return 0;
243 }
244
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +0900245 DestroyRequest request = {
246 .nlh = {
247 .nlmsg_type = SOCK_DESTROY,
248 .nlmsg_flags = NLM_F_REQUEST,
249 },
250 .req = {
251 .sdiag_family = msg->idiag_family,
252 .sdiag_protocol = proto,
253 .idiag_states = (uint32_t) (1 << msg->idiag_state),
254 .id = msg->id,
255 },
256 };
257 request.nlh.nlmsg_len = sizeof(request);
258
259 if (write(mWriteSock, &request, sizeof(request)) < (ssize_t) sizeof(request)) {
260 return -errno;
261 }
262
Lorenzo Colittif32fc592016-02-15 01:09:14 +0900263 int ret = checkError(mWriteSock);
264 if (!ret) mSocketsDestroyed++;
265 return ret;
266}
267
268int SockDiag::destroySockets(uint8_t proto, int family, const char *addrstr) {
269 if (!hasSocks()) {
270 return -EBADFD;
271 }
272
273 if (int ret = sendDumpRequest(proto, family, addrstr)) {
274 return ret;
275 }
276
Lorenzo Colittifff4bd32016-04-14 00:56:01 +0900277 auto destroyAll = [] (uint8_t, const inet_diag_msg*) { return true; };
Lorenzo Colittif32fc592016-02-15 01:09:14 +0900278
Lorenzo Colittifff4bd32016-04-14 00:56:01 +0900279 return readDiagMsg(proto, destroyAll);
Lorenzo Colittif32fc592016-02-15 01:09:14 +0900280}
281
282int SockDiag::destroySockets(const char *addrstr) {
Lorenzo Colitti94a7b432016-03-24 16:47:12 +0900283 Stopwatch s;
Lorenzo Colittif32fc592016-02-15 01:09:14 +0900284 mSocketsDestroyed = 0;
Lorenzo Colitti94a7b432016-03-24 16:47:12 +0900285
Lorenzo Colittif32fc592016-02-15 01:09:14 +0900286 if (!strchr(addrstr, ':')) {
287 if (int ret = destroySockets(IPPROTO_TCP, AF_INET, addrstr)) {
288 ALOGE("Failed to destroy IPv4 sockets on %s: %s", addrstr, strerror(-ret));
289 return ret;
290 }
291 }
292 if (int ret = destroySockets(IPPROTO_TCP, AF_INET6, addrstr)) {
293 ALOGE("Failed to destroy IPv6 sockets on %s: %s", addrstr, strerror(-ret));
294 return ret;
295 }
Lorenzo Colittif32fc592016-02-15 01:09:14 +0900296
297 if (mSocketsDestroyed > 0) {
Lorenzo Colitti94a7b432016-03-24 16:47:12 +0900298 ALOGI("Destroyed %d sockets on %s in %.1f ms", mSocketsDestroyed, addrstr, s.timeTaken());
Lorenzo Colittif32fc592016-02-15 01:09:14 +0900299 }
300
301 return mSocketsDestroyed;
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +0900302}
Lorenzo Colitti94a7b432016-03-24 16:47:12 +0900303
Lorenzo Colitti0b733e42017-02-13 16:29:00 +0900304int SockDiag::destroyLiveSockets(DestroyFilter destroyFilter, const char *what,
Lorenzo Colittifbe76b92016-09-14 02:25:05 +0900305 iovec *iov, int iovcnt) {
Lorenzo Colittifff4bd32016-04-14 00:56:01 +0900306 int proto = IPPROTO_TCP;
307
308 for (const int family : {AF_INET, AF_INET6}) {
309 const char *familyName = (family == AF_INET) ? "IPv4" : "IPv6";
310 uint32_t states = (1 << TCP_ESTABLISHED) | (1 << TCP_SYN_SENT) | (1 << TCP_SYN_RECV);
Lorenzo Colittifbe76b92016-09-14 02:25:05 +0900311 if (int ret = sendDumpRequest(proto, family, states, iov, iovcnt)) {
312 ALOGE("Failed to dump %s sockets for %s: %s", familyName, what, strerror(-ret));
Lorenzo Colittifff4bd32016-04-14 00:56:01 +0900313 return ret;
314 }
315 if (int ret = readDiagMsg(proto, destroyFilter)) {
Lorenzo Colittifbe76b92016-09-14 02:25:05 +0900316 ALOGE("Failed to destroy %s sockets for %s: %s", familyName, what, strerror(-ret));
Lorenzo Colittifff4bd32016-04-14 00:56:01 +0900317 return ret;
318 }
319 }
320
321 return 0;
322}
323
Lorenzo Colittie5c3c992016-07-26 17:53:50 +0900324int SockDiag::destroySockets(uint8_t proto, const uid_t uid, bool excludeLoopback) {
Lorenzo Colitti94a7b432016-03-24 16:47:12 +0900325 mSocketsDestroyed = 0;
326 Stopwatch s;
327
Lorenzo Colittie5c3c992016-07-26 17:53:50 +0900328 auto shouldDestroy = [uid, excludeLoopback] (uint8_t, const inet_diag_msg *msg) {
329 return msg != nullptr &&
330 msg->idiag_uid == uid &&
331 !(excludeLoopback && isLoopbackSocket(msg));
Lorenzo Colitti94a7b432016-03-24 16:47:12 +0900332 };
333
334 for (const int family : {AF_INET, AF_INET6}) {
335 const char *familyName = family == AF_INET ? "IPv4" : "IPv6";
336 uint32_t states = (1 << TCP_ESTABLISHED) | (1 << TCP_SYN_SENT) | (1 << TCP_SYN_RECV);
337 if (int ret = sendDumpRequest(proto, family, states)) {
338 ALOGE("Failed to dump %s sockets for UID: %s", familyName, strerror(-ret));
339 return ret;
340 }
Lorenzo Colittifff4bd32016-04-14 00:56:01 +0900341 if (int ret = readDiagMsg(proto, shouldDestroy)) {
Lorenzo Colitti94a7b432016-03-24 16:47:12 +0900342 ALOGE("Failed to destroy %s sockets for UID: %s", familyName, strerror(-ret));
343 return ret;
344 }
345 }
346
347 if (mSocketsDestroyed > 0) {
348 ALOGI("Destroyed %d sockets for UID in %.1f ms", mSocketsDestroyed, s.timeTaken());
349 }
350
351 return 0;
352}
Lorenzo Colittifff4bd32016-04-14 00:56:01 +0900353
Lorenzo Colittie5c3c992016-07-26 17:53:50 +0900354int SockDiag::destroySockets(const UidRanges& uidRanges, const std::set<uid_t>& skipUids,
355 bool excludeLoopback) {
Lorenzo Colittifff4bd32016-04-14 00:56:01 +0900356 mSocketsDestroyed = 0;
357 Stopwatch s;
358
359 auto shouldDestroy = [&] (uint8_t, const inet_diag_msg *msg) {
360 return msg != nullptr &&
361 uidRanges.hasUid(msg->idiag_uid) &&
Lorenzo Colittie5c3c992016-07-26 17:53:50 +0900362 skipUids.find(msg->idiag_uid) == skipUids.end() &&
363 !(excludeLoopback && isLoopbackSocket(msg));
Lorenzo Colittifff4bd32016-04-14 00:56:01 +0900364 };
365
Lorenzo Colittifbe76b92016-09-14 02:25:05 +0900366 iovec iov[] = {
367 { nullptr, 0 },
368 };
369
370 if (int ret = destroyLiveSockets(shouldDestroy, "UID", iov, ARRAY_SIZE(iov))) {
Lorenzo Colittifff4bd32016-04-14 00:56:01 +0900371 return ret;
372 }
373
374 std::vector<uid_t> skipUidStrings;
375 for (uid_t uid : skipUids) {
376 skipUidStrings.push_back(uid);
377 }
378 std::sort(skipUidStrings.begin(), skipUidStrings.end());
379
380 if (mSocketsDestroyed > 0) {
381 ALOGI("Destroyed %d sockets for %s skip={%s} in %.1f ms",
382 mSocketsDestroyed, uidRanges.toString().c_str(),
383 android::base::Join(skipUidStrings, " ").c_str(), s.timeTaken());
384 }
385
386 return 0;
387}
Lorenzo Colittifbe76b92016-09-14 02:25:05 +0900388
389// Destroys all "live" (CONNECTED, SYN_SENT, SYN_RECV) TCP sockets on the specified netId where:
390// 1. The opening app no longer has permission to use this network, or:
391// 2. The opening app does have permission, but did not explicitly select this network.
392//
393// We destroy sockets without the explicit bit because we want to avoid the situation where a
394// privileged app uses its privileges without knowing it is doing so. For example, a privileged app
395// might have opened a socket on this network just because it was the default network at the
396// time. If we don't kill these sockets, those apps could continue to use them without realizing
397// that they are now sending and receiving traffic on a network that is now restricted.
398int SockDiag::destroySocketsLackingPermission(unsigned netId, Permission permission,
399 bool excludeLoopback) {
400 struct markmatch {
401 inet_diag_bc_op op;
402 // TODO: switch to inet_diag_markcond
403 __u32 mark;
404 __u32 mask;
405 } __attribute__((packed));
406 constexpr uint8_t matchlen = sizeof(markmatch);
407
408 Fwmark netIdMark, netIdMask;
409 netIdMark.netId = netId;
410 netIdMask.netId = 0xffff;
411
412 Fwmark controlMark;
413 controlMark.explicitlySelected = true;
414 controlMark.permission = permission;
415
416 // A SOCK_DIAG bytecode program that accepts the sockets we intend to destroy.
417 struct bytecode {
418 markmatch netIdMatch;
419 markmatch controlMatch;
420 inet_diag_bc_op controlJump;
421 } __attribute__((packed)) bytecode;
422
423 // The length of the INET_DIAG_BC_JMP instruction.
424 constexpr uint8_t jmplen = sizeof(inet_diag_bc_op);
425 // Jump exactly this far past the end of the program to reject.
426 constexpr uint8_t rejectoffset = sizeof(inet_diag_bc_op);
427 // Total length of the program.
428 constexpr uint8_t bytecodelen = sizeof(bytecode);
429
430 bytecode = (struct bytecode) {
431 // If netId matches, continue, otherwise, reject (i.e., leave socket alone).
432 { { INET_DIAG_BC_MARK_COND, matchlen, bytecodelen + rejectoffset },
433 netIdMark.intValue, netIdMask.intValue },
434
435 // If explicit and permission bits match, go to the JMP below which rejects the socket
436 // (i.e., we leave it alone). Otherwise, jump to the end of the program, which accepts the
437 // socket (so we destroy it).
438 { { INET_DIAG_BC_MARK_COND, matchlen, matchlen + jmplen },
439 controlMark.intValue, controlMark.intValue },
440
441 // This JMP unconditionally rejects the packet by jumping to the reject target. It is
442 // necessary to keep the kernel bytecode verifier happy. If we don't have a JMP the bytecode
443 // is invalid because the target of every no jump must always be reachable by yes jumps.
444 // Without this JMP, the accept target is not reachable by yes jumps and the program will
445 // be rejected by the validator.
446 { INET_DIAG_BC_JMP, jmplen, jmplen + rejectoffset },
447
448 // We have reached the end of the program. Accept the socket, and destroy it below.
449 };
450
451 struct nlattr nla = {
452 .nla_type = INET_DIAG_REQ_BYTECODE,
453 .nla_len = sizeof(struct nlattr) + bytecodelen,
454 };
455
456 iovec iov[] = {
457 { nullptr, 0 },
458 { &nla, sizeof(nla) },
459 { &bytecode, bytecodelen },
460 };
461
462 mSocketsDestroyed = 0;
463 Stopwatch s;
464
465 auto shouldDestroy = [&] (uint8_t, const inet_diag_msg *msg) {
466 return msg != nullptr && !(excludeLoopback && isLoopbackSocket(msg));
467 };
468
469 if (int ret = destroyLiveSockets(shouldDestroy, "permission change", iov, ARRAY_SIZE(iov))) {
470 return ret;
471 }
472
473 if (mSocketsDestroyed > 0) {
474 ALOGI("Destroyed %d sockets for netId %d permission=%d in %.1f ms",
475 mSocketsDestroyed, netId, permission, s.timeTaken());
476 }
477
478 return 0;
479}
Lorenzo Colitti7035f222017-02-13 18:29:00 +0900480
481} // namespace net
482} // namespace android