blob: b3ffc8735a62e782f1a68f5a3bc45b572cf6bd2e [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
Bernie Innocenti196f1b82019-05-20 16:34:16 +090017#define LOG_TAG "Netd"
18
19#include "SockDiag.h"
20
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +090021#include <errno.h>
Bernie Innocenti196f1b82019-05-20 16:34:16 +090022#include <linux/inet_diag.h>
23#include <linux/netlink.h>
24#include <linux/sock_diag.h>
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +090025#include <netdb.h>
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +090026#include <netinet/in.h>
27#include <netinet/tcp.h>
Bernie Innocenti196f1b82019-05-20 16:34:16 +090028#include <string.h>
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +090029#include <sys/socket.h>
30#include <sys/uio.h>
31
Bernie Innocenti196f1b82019-05-20 16:34:16 +090032#include <cinttypes>
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +090033
Lorenzo Colittifff4bd32016-04-14 00:56:01 +090034#include <android-base/strings.h>
Logan Chien3f461482018-04-23 14:31:32 +080035#include <log/log.h>
Mike Yue7e332f2019-03-13 17:15:48 +080036#include <netdutils/Stopwatch.h>
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +090037
38#include "NetdConstants.h"
Lorenzo Colittifbe76b92016-09-14 02:25:05 +090039#include "Permission.h"
Lorenzo Colittif32fc592016-02-15 01:09:14 +090040
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +090041#ifndef SOCK_DESTROY
42#define SOCK_DESTROY 21
43#endif
44
Lorenzo Colittifbe76b92016-09-14 02:25:05 +090045#define INET_DIAG_BC_MARK_COND 10
46
Lorenzo Colitti7035f222017-02-13 18:29:00 +090047namespace android {
Lorenzo Colitti7035f222017-02-13 18:29:00 +090048
Mike Yue7e332f2019-03-13 17:15:48 +080049using netdutils::Stopwatch;
50
51namespace net {
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +090052namespace {
53
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +090054int checkError(int fd) {
55 struct {
56 nlmsghdr h;
57 nlmsgerr err;
58 } __attribute__((__packed__)) ack;
59 ssize_t bytesread = recv(fd, &ack, sizeof(ack), MSG_DONTWAIT | MSG_PEEK);
60 if (bytesread == -1) {
61 // Read failed (error), or nothing to read (good).
62 return (errno == EAGAIN) ? 0 : -errno;
63 } else if (bytesread == (ssize_t) sizeof(ack) && ack.h.nlmsg_type == NLMSG_ERROR) {
64 // We got an error. Consume it.
65 recv(fd, &ack, sizeof(ack), 0);
66 return ack.err.error;
67 } else {
68 // The kernel replied with something. Leave it to the caller.
69 return 0;
70 }
71}
72
73} // namespace
74
75bool SockDiag::open() {
76 if (hasSocks()) {
77 return false;
78 }
79
Nick Kralevichaf02b552016-12-20 08:40:35 -080080 mSock = socket(PF_NETLINK, SOCK_DGRAM | SOCK_CLOEXEC, NETLINK_INET_DIAG);
81 mWriteSock = socket(PF_NETLINK, SOCK_DGRAM | SOCK_CLOEXEC, NETLINK_INET_DIAG);
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +090082 if (!hasSocks()) {
83 closeSocks();
84 return false;
85 }
86
87 sockaddr_nl nl = { .nl_family = AF_NETLINK };
88 if ((connect(mSock, reinterpret_cast<sockaddr *>(&nl), sizeof(nl)) == -1) ||
89 (connect(mWriteSock, reinterpret_cast<sockaddr *>(&nl), sizeof(nl)) == -1)) {
90 closeSocks();
91 return false;
92 }
93
94 return true;
95}
96
Hugo Benichidee94812018-01-12 14:47:00 +090097int SockDiag::sendDumpRequest(uint8_t proto, uint8_t family, uint8_t extensions, uint32_t states,
Lorenzo Colitti94a7b432016-03-24 16:47:12 +090098 iovec *iov, int iovcnt) {
99 struct {
100 nlmsghdr nlh;
101 inet_diag_req_v2 req;
102 } __attribute__((__packed__)) request = {
103 .nlh = {
104 .nlmsg_type = SOCK_DIAG_BY_FAMILY,
105 .nlmsg_flags = NLM_F_REQUEST | NLM_F_DUMP,
106 },
107 .req = {
108 .sdiag_family = family,
109 .sdiag_protocol = proto,
Hugo Benichidee94812018-01-12 14:47:00 +0900110 .idiag_ext = extensions,
Lorenzo Colitti94a7b432016-03-24 16:47:12 +0900111 .idiag_states = states,
112 },
113 };
114
115 size_t len = 0;
116 iov[0].iov_base = &request;
117 iov[0].iov_len = sizeof(request);
118 for (int i = 0; i < iovcnt; i++) {
119 len += iov[i].iov_len;
120 }
121 request.nlh.nlmsg_len = len;
122
123 if (writev(mSock, iov, iovcnt) != (ssize_t) len) {
124 return -errno;
125 }
126
127 return checkError(mSock);
128}
129
130int SockDiag::sendDumpRequest(uint8_t proto, uint8_t family, uint32_t states) {
131 iovec iov[] = {
132 { nullptr, 0 },
133 };
Hugo Benichidee94812018-01-12 14:47:00 +0900134 return sendDumpRequest(proto, family, 0, states, iov, ARRAY_SIZE(iov));
Lorenzo Colitti94a7b432016-03-24 16:47:12 +0900135}
136
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +0900137int SockDiag::sendDumpRequest(uint8_t proto, uint8_t family, const char *addrstr) {
138 addrinfo hints = { .ai_flags = AI_NUMERICHOST };
139 addrinfo *res;
140 in6_addr mapped = { .s6_addr32 = { 0, 0, htonl(0xffff), 0 } };
141 int ret;
142
143 // TODO: refactor the netlink parsing code out of system/core, bring it into netd, and stop
144 // doing string conversions when they're not necessary.
145 if ((ret = getaddrinfo(addrstr, nullptr, &hints, &res)) != 0) {
146 return -EINVAL;
147 }
148
149 // So we don't have to call freeaddrinfo on every failure path.
150 ScopedAddrinfo resP(res);
151
152 void *addr;
153 uint8_t addrlen;
154 if (res->ai_family == AF_INET && family == AF_INET) {
155 in_addr& ina = reinterpret_cast<sockaddr_in*>(res->ai_addr)->sin_addr;
156 addr = &ina;
157 addrlen = sizeof(ina);
158 } else if (res->ai_family == AF_INET && family == AF_INET6) {
159 in_addr& ina = reinterpret_cast<sockaddr_in*>(res->ai_addr)->sin_addr;
160 mapped.s6_addr32[3] = ina.s_addr;
161 addr = &mapped;
162 addrlen = sizeof(mapped);
163 } else if (res->ai_family == AF_INET6 && family == AF_INET6) {
164 in6_addr& in6a = reinterpret_cast<sockaddr_in6*>(res->ai_addr)->sin6_addr;
165 addr = &in6a;
166 addrlen = sizeof(in6a);
167 } else {
168 return -EAFNOSUPPORT;
169 }
170
171 uint8_t prefixlen = addrlen * 8;
172 uint8_t yesjump = sizeof(inet_diag_bc_op) + sizeof(inet_diag_hostcond) + addrlen;
173 uint8_t nojump = yesjump + 4;
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +0900174
175 struct {
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +0900176 nlattr nla;
177 inet_diag_bc_op op;
178 inet_diag_hostcond cond;
Lorenzo Colitti94a7b432016-03-24 16:47:12 +0900179 } __attribute__((__packed__)) attrs = {
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +0900180 .nla = {
181 .nla_type = INET_DIAG_REQ_BYTECODE,
182 },
183 .op = {
184 INET_DIAG_BC_S_COND,
185 yesjump,
186 nojump,
187 },
188 .cond = {
189 family,
190 prefixlen,
191 -1,
192 {}
193 },
194 };
195
Lorenzo Colitti94a7b432016-03-24 16:47:12 +0900196 attrs.nla.nla_len = sizeof(attrs) + addrlen;
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +0900197
Lorenzo Colitti94a7b432016-03-24 16:47:12 +0900198 iovec iov[] = {
Lorenzo Colittifbe76b92016-09-14 02:25:05 +0900199 { nullptr, 0 },
200 { &attrs, sizeof(attrs) },
201 { addr, addrlen },
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +0900202 };
203
Lorenzo Colitti94a7b432016-03-24 16:47:12 +0900204 uint32_t states = ~(1 << TCP_TIME_WAIT);
Hugo Benichidee94812018-01-12 14:47:00 +0900205 return sendDumpRequest(proto, family, 0, states, iov, ARRAY_SIZE(iov));
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +0900206}
207
Lorenzo Colitti0b733e42017-02-13 16:29:00 +0900208int SockDiag::readDiagMsg(uint8_t proto, const SockDiag::DestroyFilter& shouldDestroy) {
209 NetlinkDumpCallback callback = [this, proto, shouldDestroy] (nlmsghdr *nlh) {
Lorenzo Colitti0b733e42017-02-13 16:29:00 +0900210 const inet_diag_msg *msg = reinterpret_cast<inet_diag_msg *>(NLMSG_DATA(nlh));
211 if (shouldDestroy(proto, msg)) {
212 sockDestroy(proto, msg);
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +0900213 }
Lorenzo Colitti0b733e42017-02-13 16:29:00 +0900214 };
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +0900215
Lorenzo Colitti0b733e42017-02-13 16:29:00 +0900216 return processNetlinkDump(mSock, callback);
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +0900217}
218
Hugo Benichidee94812018-01-12 14:47:00 +0900219int SockDiag::readDiagMsgWithTcpInfo(const TcpInfoReader& tcpInfoReader) {
220 NetlinkDumpCallback callback = [tcpInfoReader] (nlmsghdr *nlh) {
Hugo Benichi321b22c2018-01-30 11:37:27 +0900221 if (nlh->nlmsg_type != SOCK_DIAG_BY_FAMILY) {
222 ALOGE("expected nlmsg_type=SOCK_DIAG_BY_FAMILY, got nlmsg_type=%d", nlh->nlmsg_type);
223 return;
224 }
Hugo Benichicbaa36b2018-01-17 12:11:43 +0900225 Fwmark mark;
Hugo Benichidee94812018-01-12 14:47:00 +0900226 struct tcp_info *tcpinfo = nullptr;
Hugo Benichi54bfc7c2018-01-23 14:16:52 +0900227 uint32_t tcpinfoLength = 0;
Hugo Benichidee94812018-01-12 14:47:00 +0900228 inet_diag_msg *msg = reinterpret_cast<inet_diag_msg *>(NLMSG_DATA(nlh));
229 uint32_t attr_len = nlh->nlmsg_len - NLMSG_LENGTH(sizeof(*msg));
230 struct rtattr *attr = reinterpret_cast<struct rtattr*>(msg+1);
231 while (RTA_OK(attr, attr_len)) {
232 if (attr->rta_type == INET_DIAG_INFO) {
233 tcpinfo = reinterpret_cast<struct tcp_info*>(RTA_DATA(attr));
Hugo Benichi54bfc7c2018-01-23 14:16:52 +0900234 tcpinfoLength = RTA_PAYLOAD(attr);
Hugo Benichicbaa36b2018-01-17 12:11:43 +0900235 }
236 if (attr->rta_type == INET_DIAG_MARK) {
237 mark.intValue = *reinterpret_cast<uint32_t*>(RTA_DATA(attr));
Hugo Benichidee94812018-01-12 14:47:00 +0900238 }
239 attr = RTA_NEXT(attr, attr_len);
240 }
241
Hugo Benichi54bfc7c2018-01-23 14:16:52 +0900242 tcpInfoReader(mark, msg, tcpinfo, tcpinfoLength);
Hugo Benichidee94812018-01-12 14:47:00 +0900243 };
244
245 return processNetlinkDump(mSock, callback);
246}
247
Lorenzo Colittie5c3c992016-07-26 17:53:50 +0900248// Determines whether a socket is a loopback socket. Does not check socket state.
249bool SockDiag::isLoopbackSocket(const inet_diag_msg *msg) {
250 switch (msg->idiag_family) {
251 case AF_INET:
252 // Old kernels only copy the IPv4 address and leave the other 12 bytes uninitialized.
253 return IN_LOOPBACK(htonl(msg->id.idiag_src[0])) ||
254 IN_LOOPBACK(htonl(msg->id.idiag_dst[0])) ||
255 msg->id.idiag_src[0] == msg->id.idiag_dst[0];
256
257 case AF_INET6: {
258 const struct in6_addr *src = (const struct in6_addr *) &msg->id.idiag_src;
259 const struct in6_addr *dst = (const struct in6_addr *) &msg->id.idiag_dst;
260 return (IN6_IS_ADDR_V4MAPPED(src) && IN_LOOPBACK(src->s6_addr32[3])) ||
261 (IN6_IS_ADDR_V4MAPPED(dst) && IN_LOOPBACK(dst->s6_addr32[3])) ||
262 IN6_IS_ADDR_LOOPBACK(src) || IN6_IS_ADDR_LOOPBACK(dst) ||
263 !memcmp(src, dst, sizeof(*src));
264 }
265 default:
266 return false;
267 }
268}
269
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +0900270int SockDiag::sockDestroy(uint8_t proto, const inet_diag_msg *msg) {
Lorenzo Colittif32fc592016-02-15 01:09:14 +0900271 if (msg == nullptr) {
272 return 0;
273 }
274
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +0900275 DestroyRequest request = {
276 .nlh = {
277 .nlmsg_type = SOCK_DESTROY,
278 .nlmsg_flags = NLM_F_REQUEST,
279 },
280 .req = {
281 .sdiag_family = msg->idiag_family,
282 .sdiag_protocol = proto,
283 .idiag_states = (uint32_t) (1 << msg->idiag_state),
284 .id = msg->id,
285 },
286 };
287 request.nlh.nlmsg_len = sizeof(request);
288
289 if (write(mWriteSock, &request, sizeof(request)) < (ssize_t) sizeof(request)) {
290 return -errno;
291 }
292
Lorenzo Colittif32fc592016-02-15 01:09:14 +0900293 int ret = checkError(mWriteSock);
294 if (!ret) mSocketsDestroyed++;
295 return ret;
296}
297
298int SockDiag::destroySockets(uint8_t proto, int family, const char *addrstr) {
299 if (!hasSocks()) {
300 return -EBADFD;
301 }
302
303 if (int ret = sendDumpRequest(proto, family, addrstr)) {
304 return ret;
305 }
306
Lorenzo Colittifff4bd32016-04-14 00:56:01 +0900307 auto destroyAll = [] (uint8_t, const inet_diag_msg*) { return true; };
Lorenzo Colittif32fc592016-02-15 01:09:14 +0900308
Lorenzo Colittifff4bd32016-04-14 00:56:01 +0900309 return readDiagMsg(proto, destroyAll);
Lorenzo Colittif32fc592016-02-15 01:09:14 +0900310}
311
312int SockDiag::destroySockets(const char *addrstr) {
Lorenzo Colitti94a7b432016-03-24 16:47:12 +0900313 Stopwatch s;
Lorenzo Colittif32fc592016-02-15 01:09:14 +0900314 mSocketsDestroyed = 0;
Lorenzo Colitti94a7b432016-03-24 16:47:12 +0900315
Lorenzo Colittif32fc592016-02-15 01:09:14 +0900316 if (!strchr(addrstr, ':')) {
317 if (int ret = destroySockets(IPPROTO_TCP, AF_INET, addrstr)) {
318 ALOGE("Failed to destroy IPv4 sockets on %s: %s", addrstr, strerror(-ret));
319 return ret;
320 }
321 }
322 if (int ret = destroySockets(IPPROTO_TCP, AF_INET6, addrstr)) {
323 ALOGE("Failed to destroy IPv6 sockets on %s: %s", addrstr, strerror(-ret));
324 return ret;
325 }
Lorenzo Colittif32fc592016-02-15 01:09:14 +0900326
327 if (mSocketsDestroyed > 0) {
Bernie Innocenti196f1b82019-05-20 16:34:16 +0900328 ALOGI("Destroyed %d sockets on %s in %" PRId64 "us", mSocketsDestroyed, addrstr,
329 s.timeTakenUs());
Lorenzo Colittif32fc592016-02-15 01:09:14 +0900330 }
331
332 return mSocketsDestroyed;
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +0900333}
Lorenzo Colitti94a7b432016-03-24 16:47:12 +0900334
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900335int SockDiag::destroyLiveSockets(const DestroyFilter& destroyFilter, const char *what,
Lorenzo Colittifbe76b92016-09-14 02:25:05 +0900336 iovec *iov, int iovcnt) {
Hugo Benichidee94812018-01-12 14:47:00 +0900337 const int proto = IPPROTO_TCP;
338 const uint32_t states = (1 << TCP_ESTABLISHED) | (1 << TCP_SYN_SENT) | (1 << TCP_SYN_RECV);
Lorenzo Colittifff4bd32016-04-14 00:56:01 +0900339
340 for (const int family : {AF_INET, AF_INET6}) {
341 const char *familyName = (family == AF_INET) ? "IPv4" : "IPv6";
Hugo Benichidee94812018-01-12 14:47:00 +0900342 if (int ret = sendDumpRequest(proto, family, 0, states, iov, iovcnt)) {
Lorenzo Colittifbe76b92016-09-14 02:25:05 +0900343 ALOGE("Failed to dump %s sockets for %s: %s", familyName, what, strerror(-ret));
Lorenzo Colittifff4bd32016-04-14 00:56:01 +0900344 return ret;
345 }
346 if (int ret = readDiagMsg(proto, destroyFilter)) {
Lorenzo Colittifbe76b92016-09-14 02:25:05 +0900347 ALOGE("Failed to destroy %s sockets for %s: %s", familyName, what, strerror(-ret));
Lorenzo Colittifff4bd32016-04-14 00:56:01 +0900348 return ret;
349 }
350 }
351
352 return 0;
353}
354
Hugo Benichidee94812018-01-12 14:47:00 +0900355int SockDiag::getLiveTcpInfos(const TcpInfoReader& tcpInfoReader) {
356 const int proto = IPPROTO_TCP;
357 const uint32_t states = (1 << TCP_ESTABLISHED) | (1 << TCP_SYN_SENT) | (1 << TCP_SYN_RECV);
358 const uint8_t extensions = (1 << INET_DIAG_MEMINFO); // flag for dumping struct tcp_info.
359
360 iovec iov[] = {
361 { nullptr, 0 },
362 };
363
364 for (const int family : {AF_INET, AF_INET6}) {
365 const char *familyName = (family == AF_INET) ? "IPv4" : "IPv6";
366 if (int ret = sendDumpRequest(proto, family, extensions, states, iov, ARRAY_SIZE(iov))) {
367 ALOGE("Failed to dump %s sockets struct tcp_info: %s", familyName, strerror(-ret));
368 return ret;
369 }
370 if (int ret = readDiagMsgWithTcpInfo(tcpInfoReader)) {
371 ALOGE("Failed to read %s sockets struct tcp_info: %s", familyName, strerror(-ret));
372 return ret;
373 }
374 }
375
376 return 0;
377}
378
Lorenzo Colittie5c3c992016-07-26 17:53:50 +0900379int SockDiag::destroySockets(uint8_t proto, const uid_t uid, bool excludeLoopback) {
Lorenzo Colitti94a7b432016-03-24 16:47:12 +0900380 mSocketsDestroyed = 0;
381 Stopwatch s;
382
Lorenzo Colittie5c3c992016-07-26 17:53:50 +0900383 auto shouldDestroy = [uid, excludeLoopback] (uint8_t, const inet_diag_msg *msg) {
384 return msg != nullptr &&
385 msg->idiag_uid == uid &&
386 !(excludeLoopback && isLoopbackSocket(msg));
Lorenzo Colitti94a7b432016-03-24 16:47:12 +0900387 };
388
389 for (const int family : {AF_INET, AF_INET6}) {
390 const char *familyName = family == AF_INET ? "IPv4" : "IPv6";
391 uint32_t states = (1 << TCP_ESTABLISHED) | (1 << TCP_SYN_SENT) | (1 << TCP_SYN_RECV);
392 if (int ret = sendDumpRequest(proto, family, states)) {
393 ALOGE("Failed to dump %s sockets for UID: %s", familyName, strerror(-ret));
394 return ret;
395 }
Lorenzo Colittifff4bd32016-04-14 00:56:01 +0900396 if (int ret = readDiagMsg(proto, shouldDestroy)) {
Lorenzo Colitti94a7b432016-03-24 16:47:12 +0900397 ALOGE("Failed to destroy %s sockets for UID: %s", familyName, strerror(-ret));
398 return ret;
399 }
400 }
401
402 if (mSocketsDestroyed > 0) {
Bernie Innocenti196f1b82019-05-20 16:34:16 +0900403 ALOGI("Destroyed %d sockets for UID in %" PRId64 "us", mSocketsDestroyed, s.timeTakenUs());
Lorenzo Colitti94a7b432016-03-24 16:47:12 +0900404 }
405
406 return 0;
407}
Lorenzo Colittifff4bd32016-04-14 00:56:01 +0900408
Lorenzo Colittie5c3c992016-07-26 17:53:50 +0900409int SockDiag::destroySockets(const UidRanges& uidRanges, const std::set<uid_t>& skipUids,
410 bool excludeLoopback) {
Lorenzo Colittifff4bd32016-04-14 00:56:01 +0900411 mSocketsDestroyed = 0;
412 Stopwatch s;
413
414 auto shouldDestroy = [&] (uint8_t, const inet_diag_msg *msg) {
415 return msg != nullptr &&
416 uidRanges.hasUid(msg->idiag_uid) &&
Lorenzo Colittie5c3c992016-07-26 17:53:50 +0900417 skipUids.find(msg->idiag_uid) == skipUids.end() &&
418 !(excludeLoopback && isLoopbackSocket(msg));
Lorenzo Colittifff4bd32016-04-14 00:56:01 +0900419 };
420
Lorenzo Colittifbe76b92016-09-14 02:25:05 +0900421 iovec iov[] = {
422 { nullptr, 0 },
423 };
424
425 if (int ret = destroyLiveSockets(shouldDestroy, "UID", iov, ARRAY_SIZE(iov))) {
Lorenzo Colittifff4bd32016-04-14 00:56:01 +0900426 return ret;
427 }
428
Lorenzo Colittifff4bd32016-04-14 00:56:01 +0900429 if (mSocketsDestroyed > 0) {
Bernie Innocenti196f1b82019-05-20 16:34:16 +0900430 ALOGI("Destroyed %d sockets for %s skip={%s} in %" PRId64 "us", mSocketsDestroyed,
431 uidRanges.toString().c_str(), android::base::Join(skipUids, " ").c_str(),
432 s.timeTakenUs());
Lorenzo Colittifff4bd32016-04-14 00:56:01 +0900433 }
434
435 return 0;
436}
Lorenzo Colittifbe76b92016-09-14 02:25:05 +0900437
438// Destroys all "live" (CONNECTED, SYN_SENT, SYN_RECV) TCP sockets on the specified netId where:
439// 1. The opening app no longer has permission to use this network, or:
440// 2. The opening app does have permission, but did not explicitly select this network.
441//
442// We destroy sockets without the explicit bit because we want to avoid the situation where a
443// privileged app uses its privileges without knowing it is doing so. For example, a privileged app
444// might have opened a socket on this network just because it was the default network at the
445// time. If we don't kill these sockets, those apps could continue to use them without realizing
446// that they are now sending and receiving traffic on a network that is now restricted.
447int SockDiag::destroySocketsLackingPermission(unsigned netId, Permission permission,
448 bool excludeLoopback) {
449 struct markmatch {
450 inet_diag_bc_op op;
451 // TODO: switch to inet_diag_markcond
452 __u32 mark;
453 __u32 mask;
454 } __attribute__((packed));
455 constexpr uint8_t matchlen = sizeof(markmatch);
456
457 Fwmark netIdMark, netIdMask;
458 netIdMark.netId = netId;
459 netIdMask.netId = 0xffff;
460
461 Fwmark controlMark;
462 controlMark.explicitlySelected = true;
463 controlMark.permission = permission;
464
465 // A SOCK_DIAG bytecode program that accepts the sockets we intend to destroy.
466 struct bytecode {
467 markmatch netIdMatch;
468 markmatch controlMatch;
469 inet_diag_bc_op controlJump;
470 } __attribute__((packed)) bytecode;
471
472 // The length of the INET_DIAG_BC_JMP instruction.
473 constexpr uint8_t jmplen = sizeof(inet_diag_bc_op);
474 // Jump exactly this far past the end of the program to reject.
475 constexpr uint8_t rejectoffset = sizeof(inet_diag_bc_op);
476 // Total length of the program.
477 constexpr uint8_t bytecodelen = sizeof(bytecode);
478
479 bytecode = (struct bytecode) {
480 // If netId matches, continue, otherwise, reject (i.e., leave socket alone).
481 { { INET_DIAG_BC_MARK_COND, matchlen, bytecodelen + rejectoffset },
482 netIdMark.intValue, netIdMask.intValue },
483
484 // If explicit and permission bits match, go to the JMP below which rejects the socket
485 // (i.e., we leave it alone). Otherwise, jump to the end of the program, which accepts the
486 // socket (so we destroy it).
487 { { INET_DIAG_BC_MARK_COND, matchlen, matchlen + jmplen },
488 controlMark.intValue, controlMark.intValue },
489
490 // This JMP unconditionally rejects the packet by jumping to the reject target. It is
491 // necessary to keep the kernel bytecode verifier happy. If we don't have a JMP the bytecode
492 // is invalid because the target of every no jump must always be reachable by yes jumps.
493 // Without this JMP, the accept target is not reachable by yes jumps and the program will
494 // be rejected by the validator.
495 { INET_DIAG_BC_JMP, jmplen, jmplen + rejectoffset },
496
497 // We have reached the end of the program. Accept the socket, and destroy it below.
498 };
499
500 struct nlattr nla = {
501 .nla_type = INET_DIAG_REQ_BYTECODE,
502 .nla_len = sizeof(struct nlattr) + bytecodelen,
503 };
504
505 iovec iov[] = {
506 { nullptr, 0 },
507 { &nla, sizeof(nla) },
508 { &bytecode, bytecodelen },
509 };
510
511 mSocketsDestroyed = 0;
512 Stopwatch s;
513
514 auto shouldDestroy = [&] (uint8_t, const inet_diag_msg *msg) {
515 return msg != nullptr && !(excludeLoopback && isLoopbackSocket(msg));
516 };
517
518 if (int ret = destroyLiveSockets(shouldDestroy, "permission change", iov, ARRAY_SIZE(iov))) {
519 return ret;
520 }
521
522 if (mSocketsDestroyed > 0) {
Bernie Innocenti196f1b82019-05-20 16:34:16 +0900523 ALOGI("Destroyed %d sockets for netId %d permission=%d in %" PRId64 "us", mSocketsDestroyed,
524 netId, permission, s.timeTakenUs());
Lorenzo Colittifbe76b92016-09-14 02:25:05 +0900525 }
526
527 return 0;
528}
Lorenzo Colitti7035f222017-02-13 18:29:00 +0900529
530} // namespace net
531} // namespace android