blob: b3d9150aef843be394040d0b9a9d2f2a36b2708b [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
steven_fannf3cfb3a2021-01-20 14:43:00 +080034#include <android-base/properties.h>
Treehugger Robot9e41e9f2021-06-17 10:42:58 +000035#include <android-base/stringprintf.h>
Lorenzo Colittifff4bd32016-04-14 00:56:01 +090036#include <android-base/strings.h>
Logan Chien3f461482018-04-23 14:31:32 +080037#include <log/log.h>
Luke Huang25599322019-06-14 00:34:05 +080038#include <netdutils/InternetAddresses.h>
Mike Yue7e332f2019-03-13 17:15:48 +080039#include <netdutils/Stopwatch.h>
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +090040
Lorenzo Colittifbe76b92016-09-14 02:25:05 +090041#include "Permission.h"
Lorenzo Colittif32fc592016-02-15 01:09:14 +090042
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +090043#ifndef SOCK_DESTROY
44#define SOCK_DESTROY 21
45#endif
46
Lorenzo Colittifbe76b92016-09-14 02:25:05 +090047#define INET_DIAG_BC_MARK_COND 10
48
Lorenzo Colitti7035f222017-02-13 18:29:00 +090049namespace android {
Lorenzo Colitti7035f222017-02-13 18:29:00 +090050
Treehugger Robot9e41e9f2021-06-17 10:42:58 +000051using android::base::StringPrintf;
Luke Huang25599322019-06-14 00:34:05 +080052using netdutils::ScopedAddrinfo;
Mike Yue7e332f2019-03-13 17:15:48 +080053using netdutils::Stopwatch;
54
55namespace net {
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +090056namespace {
57
steven_fannf3cfb3a2021-01-20 14:43:00 +080058int getAdbPort() {
59 return android::base::GetIntProperty("service.adb.tcp.port", 0);
60}
61
62bool isAdbSocket(const inet_diag_msg *msg, int adbPort) {
63 return adbPort > 0 && msg->id.idiag_sport == htons(adbPort) &&
64 (msg->idiag_uid == AID_ROOT || msg->idiag_uid == AID_SHELL);
65}
66
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +090067int checkError(int fd) {
68 struct {
69 nlmsghdr h;
70 nlmsgerr err;
71 } __attribute__((__packed__)) ack;
72 ssize_t bytesread = recv(fd, &ack, sizeof(ack), MSG_DONTWAIT | MSG_PEEK);
73 if (bytesread == -1) {
74 // Read failed (error), or nothing to read (good).
75 return (errno == EAGAIN) ? 0 : -errno;
76 } else if (bytesread == (ssize_t) sizeof(ack) && ack.h.nlmsg_type == NLMSG_ERROR) {
77 // We got an error. Consume it.
78 recv(fd, &ack, sizeof(ack), 0);
79 return ack.err.error;
80 } else {
81 // The kernel replied with something. Leave it to the caller.
82 return 0;
83 }
84}
85
86} // namespace
87
88bool SockDiag::open() {
89 if (hasSocks()) {
90 return false;
91 }
92
Nick Kralevichaf02b552016-12-20 08:40:35 -080093 mSock = socket(PF_NETLINK, SOCK_DGRAM | SOCK_CLOEXEC, NETLINK_INET_DIAG);
94 mWriteSock = socket(PF_NETLINK, SOCK_DGRAM | SOCK_CLOEXEC, NETLINK_INET_DIAG);
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +090095 if (!hasSocks()) {
96 closeSocks();
97 return false;
98 }
99
100 sockaddr_nl nl = { .nl_family = AF_NETLINK };
101 if ((connect(mSock, reinterpret_cast<sockaddr *>(&nl), sizeof(nl)) == -1) ||
102 (connect(mWriteSock, reinterpret_cast<sockaddr *>(&nl), sizeof(nl)) == -1)) {
103 closeSocks();
104 return false;
105 }
106
107 return true;
108}
109
Hugo Benichidee94812018-01-12 14:47:00 +0900110int SockDiag::sendDumpRequest(uint8_t proto, uint8_t family, uint8_t extensions, uint32_t states,
Lorenzo Colitti94a7b432016-03-24 16:47:12 +0900111 iovec *iov, int iovcnt) {
112 struct {
113 nlmsghdr nlh;
114 inet_diag_req_v2 req;
115 } __attribute__((__packed__)) request = {
116 .nlh = {
117 .nlmsg_type = SOCK_DIAG_BY_FAMILY,
118 .nlmsg_flags = NLM_F_REQUEST | NLM_F_DUMP,
119 },
120 .req = {
121 .sdiag_family = family,
122 .sdiag_protocol = proto,
Hugo Benichidee94812018-01-12 14:47:00 +0900123 .idiag_ext = extensions,
Lorenzo Colitti94a7b432016-03-24 16:47:12 +0900124 .idiag_states = states,
125 },
126 };
127
128 size_t len = 0;
129 iov[0].iov_base = &request;
130 iov[0].iov_len = sizeof(request);
131 for (int i = 0; i < iovcnt; i++) {
132 len += iov[i].iov_len;
133 }
134 request.nlh.nlmsg_len = len;
135
136 if (writev(mSock, iov, iovcnt) != (ssize_t) len) {
137 return -errno;
138 }
139
140 return checkError(mSock);
141}
142
143int SockDiag::sendDumpRequest(uint8_t proto, uint8_t family, uint32_t states) {
144 iovec iov[] = {
145 { nullptr, 0 },
146 };
Hugo Benichidee94812018-01-12 14:47:00 +0900147 return sendDumpRequest(proto, family, 0, states, iov, ARRAY_SIZE(iov));
Lorenzo Colitti94a7b432016-03-24 16:47:12 +0900148}
149
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +0900150int SockDiag::sendDumpRequest(uint8_t proto, uint8_t family, const char *addrstr) {
151 addrinfo hints = { .ai_flags = AI_NUMERICHOST };
152 addrinfo *res;
153 in6_addr mapped = { .s6_addr32 = { 0, 0, htonl(0xffff), 0 } };
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +0900154
155 // TODO: refactor the netlink parsing code out of system/core, bring it into netd, and stop
156 // doing string conversions when they're not necessary.
Maciej Żenczykowski84b59d92020-04-30 16:30:55 -0700157 int ret = getaddrinfo(addrstr, nullptr, &hints, &res);
158 if (ret != 0) return -EINVAL;
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +0900159
160 // So we don't have to call freeaddrinfo on every failure path.
161 ScopedAddrinfo resP(res);
162
163 void *addr;
164 uint8_t addrlen;
165 if (res->ai_family == AF_INET && family == AF_INET) {
166 in_addr& ina = reinterpret_cast<sockaddr_in*>(res->ai_addr)->sin_addr;
167 addr = &ina;
168 addrlen = sizeof(ina);
169 } else if (res->ai_family == AF_INET && family == AF_INET6) {
170 in_addr& ina = reinterpret_cast<sockaddr_in*>(res->ai_addr)->sin_addr;
171 mapped.s6_addr32[3] = ina.s_addr;
172 addr = &mapped;
173 addrlen = sizeof(mapped);
174 } else if (res->ai_family == AF_INET6 && family == AF_INET6) {
175 in6_addr& in6a = reinterpret_cast<sockaddr_in6*>(res->ai_addr)->sin6_addr;
176 addr = &in6a;
177 addrlen = sizeof(in6a);
178 } else {
179 return -EAFNOSUPPORT;
180 }
181
182 uint8_t prefixlen = addrlen * 8;
183 uint8_t yesjump = sizeof(inet_diag_bc_op) + sizeof(inet_diag_hostcond) + addrlen;
184 uint8_t nojump = yesjump + 4;
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +0900185
186 struct {
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +0900187 nlattr nla;
188 inet_diag_bc_op op;
189 inet_diag_hostcond cond;
Lorenzo Colitti94a7b432016-03-24 16:47:12 +0900190 } __attribute__((__packed__)) attrs = {
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +0900191 .nla = {
192 .nla_type = INET_DIAG_REQ_BYTECODE,
193 },
194 .op = {
195 INET_DIAG_BC_S_COND,
196 yesjump,
197 nojump,
198 },
199 .cond = {
200 family,
201 prefixlen,
202 -1,
203 {}
204 },
205 };
206
Lorenzo Colitti94a7b432016-03-24 16:47:12 +0900207 attrs.nla.nla_len = sizeof(attrs) + addrlen;
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +0900208
Lorenzo Colitti94a7b432016-03-24 16:47:12 +0900209 iovec iov[] = {
Lorenzo Colittifbe76b92016-09-14 02:25:05 +0900210 { nullptr, 0 },
211 { &attrs, sizeof(attrs) },
212 { addr, addrlen },
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +0900213 };
214
Lorenzo Colitti94a7b432016-03-24 16:47:12 +0900215 uint32_t states = ~(1 << TCP_TIME_WAIT);
Hugo Benichidee94812018-01-12 14:47:00 +0900216 return sendDumpRequest(proto, family, 0, states, iov, ARRAY_SIZE(iov));
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +0900217}
218
Lorenzo Colitti0b733e42017-02-13 16:29:00 +0900219int SockDiag::readDiagMsg(uint8_t proto, const SockDiag::DestroyFilter& shouldDestroy) {
220 NetlinkDumpCallback callback = [this, proto, shouldDestroy] (nlmsghdr *nlh) {
Lorenzo Colitti0b733e42017-02-13 16:29:00 +0900221 const inet_diag_msg *msg = reinterpret_cast<inet_diag_msg *>(NLMSG_DATA(nlh));
222 if (shouldDestroy(proto, msg)) {
223 sockDestroy(proto, msg);
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +0900224 }
Lorenzo Colitti0b733e42017-02-13 16:29:00 +0900225 };
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +0900226
Lorenzo Colitti0b733e42017-02-13 16:29:00 +0900227 return processNetlinkDump(mSock, callback);
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +0900228}
229
Hugo Benichidee94812018-01-12 14:47:00 +0900230int SockDiag::readDiagMsgWithTcpInfo(const TcpInfoReader& tcpInfoReader) {
231 NetlinkDumpCallback callback = [tcpInfoReader] (nlmsghdr *nlh) {
Hugo Benichi321b22c2018-01-30 11:37:27 +0900232 if (nlh->nlmsg_type != SOCK_DIAG_BY_FAMILY) {
233 ALOGE("expected nlmsg_type=SOCK_DIAG_BY_FAMILY, got nlmsg_type=%d", nlh->nlmsg_type);
234 return;
235 }
Hugo Benichicbaa36b2018-01-17 12:11:43 +0900236 Fwmark mark;
Hugo Benichidee94812018-01-12 14:47:00 +0900237 struct tcp_info *tcpinfo = nullptr;
Hugo Benichi54bfc7c2018-01-23 14:16:52 +0900238 uint32_t tcpinfoLength = 0;
Hugo Benichidee94812018-01-12 14:47:00 +0900239 inet_diag_msg *msg = reinterpret_cast<inet_diag_msg *>(NLMSG_DATA(nlh));
240 uint32_t attr_len = nlh->nlmsg_len - NLMSG_LENGTH(sizeof(*msg));
241 struct rtattr *attr = reinterpret_cast<struct rtattr*>(msg+1);
242 while (RTA_OK(attr, attr_len)) {
243 if (attr->rta_type == INET_DIAG_INFO) {
244 tcpinfo = reinterpret_cast<struct tcp_info*>(RTA_DATA(attr));
Hugo Benichi54bfc7c2018-01-23 14:16:52 +0900245 tcpinfoLength = RTA_PAYLOAD(attr);
Hugo Benichicbaa36b2018-01-17 12:11:43 +0900246 }
247 if (attr->rta_type == INET_DIAG_MARK) {
248 mark.intValue = *reinterpret_cast<uint32_t*>(RTA_DATA(attr));
Hugo Benichidee94812018-01-12 14:47:00 +0900249 }
250 attr = RTA_NEXT(attr, attr_len);
251 }
252
Hugo Benichi54bfc7c2018-01-23 14:16:52 +0900253 tcpInfoReader(mark, msg, tcpinfo, tcpinfoLength);
Hugo Benichidee94812018-01-12 14:47:00 +0900254 };
255
256 return processNetlinkDump(mSock, callback);
257}
258
Lorenzo Colittie5c3c992016-07-26 17:53:50 +0900259// Determines whether a socket is a loopback socket. Does not check socket state.
260bool SockDiag::isLoopbackSocket(const inet_diag_msg *msg) {
261 switch (msg->idiag_family) {
262 case AF_INET:
263 // Old kernels only copy the IPv4 address and leave the other 12 bytes uninitialized.
264 return IN_LOOPBACK(htonl(msg->id.idiag_src[0])) ||
265 IN_LOOPBACK(htonl(msg->id.idiag_dst[0])) ||
266 msg->id.idiag_src[0] == msg->id.idiag_dst[0];
267
268 case AF_INET6: {
269 const struct in6_addr *src = (const struct in6_addr *) &msg->id.idiag_src;
270 const struct in6_addr *dst = (const struct in6_addr *) &msg->id.idiag_dst;
271 return (IN6_IS_ADDR_V4MAPPED(src) && IN_LOOPBACK(src->s6_addr32[3])) ||
272 (IN6_IS_ADDR_V4MAPPED(dst) && IN_LOOPBACK(dst->s6_addr32[3])) ||
273 IN6_IS_ADDR_LOOPBACK(src) || IN6_IS_ADDR_LOOPBACK(dst) ||
274 !memcmp(src, dst, sizeof(*src));
275 }
276 default:
277 return false;
278 }
279}
280
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +0900281int SockDiag::sockDestroy(uint8_t proto, const inet_diag_msg *msg) {
Lorenzo Colittif32fc592016-02-15 01:09:14 +0900282 if (msg == nullptr) {
283 return 0;
284 }
285
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +0900286 DestroyRequest request = {
287 .nlh = {
288 .nlmsg_type = SOCK_DESTROY,
289 .nlmsg_flags = NLM_F_REQUEST,
290 },
291 .req = {
292 .sdiag_family = msg->idiag_family,
293 .sdiag_protocol = proto,
294 .idiag_states = (uint32_t) (1 << msg->idiag_state),
295 .id = msg->id,
296 },
297 };
298 request.nlh.nlmsg_len = sizeof(request);
299
300 if (write(mWriteSock, &request, sizeof(request)) < (ssize_t) sizeof(request)) {
301 return -errno;
302 }
303
Lorenzo Colittif32fc592016-02-15 01:09:14 +0900304 int ret = checkError(mWriteSock);
305 if (!ret) mSocketsDestroyed++;
306 return ret;
307}
308
Treehugger Robot9e41e9f2021-06-17 10:42:58 +0000309int SockDiag::destroySockets(uint8_t proto, int family, const char* addrstr, int ifindex) {
Lorenzo Colittif32fc592016-02-15 01:09:14 +0900310 if (!hasSocks()) {
311 return -EBADFD;
312 }
313
314 if (int ret = sendDumpRequest(proto, family, addrstr)) {
315 return ret;
316 }
317
Treehugger Robot9e41e9f2021-06-17 10:42:58 +0000318 auto destroyAll = [ifindex](uint8_t, const inet_diag_msg* msg) {
319 return ifindex == 0 || ifindex == (int)msg->id.idiag_if;
320 };
Lorenzo Colittif32fc592016-02-15 01:09:14 +0900321
Lorenzo Colittifff4bd32016-04-14 00:56:01 +0900322 return readDiagMsg(proto, destroyAll);
Lorenzo Colittif32fc592016-02-15 01:09:14 +0900323}
324
Treehugger Robot9e41e9f2021-06-17 10:42:58 +0000325int SockDiag::destroySockets(const char* addrstr, int ifindex) {
Lorenzo Colitti94a7b432016-03-24 16:47:12 +0900326 Stopwatch s;
Lorenzo Colittif32fc592016-02-15 01:09:14 +0900327 mSocketsDestroyed = 0;
Lorenzo Colitti94a7b432016-03-24 16:47:12 +0900328
Treehugger Robot9e41e9f2021-06-17 10:42:58 +0000329 std::string where = addrstr;
330 if (ifindex) where += StringPrintf(" ifindex %d", ifindex);
331
332 if (!strchr(addrstr, ':')) { // inet_ntop never returns something like ::ffff:192.0.2.1
333 if (int ret = destroySockets(IPPROTO_TCP, AF_INET, addrstr, ifindex)) {
334 ALOGE("Failed to destroy IPv4 sockets on %s: %s", where.c_str(), strerror(-ret));
Lorenzo Colittif32fc592016-02-15 01:09:14 +0900335 return ret;
336 }
337 }
Treehugger Robot9e41e9f2021-06-17 10:42:58 +0000338 if (int ret = destroySockets(IPPROTO_TCP, AF_INET6, addrstr, ifindex)) {
339 ALOGE("Failed to destroy IPv6 sockets on %s: %s", where.c_str(), strerror(-ret));
Lorenzo Colittif32fc592016-02-15 01:09:14 +0900340 return ret;
341 }
Lorenzo Colittif32fc592016-02-15 01:09:14 +0900342
343 if (mSocketsDestroyed > 0) {
Treehugger Robot9e41e9f2021-06-17 10:42:58 +0000344 ALOGI("Destroyed %d sockets on %s in %" PRId64 "us", mSocketsDestroyed, where.c_str(),
Bernie Innocenti196f1b82019-05-20 16:34:16 +0900345 s.timeTakenUs());
Lorenzo Colittif32fc592016-02-15 01:09:14 +0900346 }
347
348 return mSocketsDestroyed;
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +0900349}
Lorenzo Colitti94a7b432016-03-24 16:47:12 +0900350
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900351int SockDiag::destroyLiveSockets(const DestroyFilter& destroyFilter, const char *what,
Lorenzo Colittifbe76b92016-09-14 02:25:05 +0900352 iovec *iov, int iovcnt) {
Hugo Benichidee94812018-01-12 14:47:00 +0900353 const int proto = IPPROTO_TCP;
354 const uint32_t states = (1 << TCP_ESTABLISHED) | (1 << TCP_SYN_SENT) | (1 << TCP_SYN_RECV);
Lorenzo Colittifff4bd32016-04-14 00:56:01 +0900355
356 for (const int family : {AF_INET, AF_INET6}) {
357 const char *familyName = (family == AF_INET) ? "IPv4" : "IPv6";
Hugo Benichidee94812018-01-12 14:47:00 +0900358 if (int ret = sendDumpRequest(proto, family, 0, states, iov, iovcnt)) {
Lorenzo Colittifbe76b92016-09-14 02:25:05 +0900359 ALOGE("Failed to dump %s sockets for %s: %s", familyName, what, strerror(-ret));
Lorenzo Colittifff4bd32016-04-14 00:56:01 +0900360 return ret;
361 }
362 if (int ret = readDiagMsg(proto, destroyFilter)) {
Lorenzo Colittifbe76b92016-09-14 02:25:05 +0900363 ALOGE("Failed to destroy %s sockets for %s: %s", familyName, what, strerror(-ret));
Lorenzo Colittifff4bd32016-04-14 00:56:01 +0900364 return ret;
365 }
366 }
367
368 return 0;
369}
370
Hugo Benichidee94812018-01-12 14:47:00 +0900371int SockDiag::getLiveTcpInfos(const TcpInfoReader& tcpInfoReader) {
372 const int proto = IPPROTO_TCP;
373 const uint32_t states = (1 << TCP_ESTABLISHED) | (1 << TCP_SYN_SENT) | (1 << TCP_SYN_RECV);
374 const uint8_t extensions = (1 << INET_DIAG_MEMINFO); // flag for dumping struct tcp_info.
375
376 iovec iov[] = {
377 { nullptr, 0 },
378 };
379
380 for (const int family : {AF_INET, AF_INET6}) {
381 const char *familyName = (family == AF_INET) ? "IPv4" : "IPv6";
382 if (int ret = sendDumpRequest(proto, family, extensions, states, iov, ARRAY_SIZE(iov))) {
383 ALOGE("Failed to dump %s sockets struct tcp_info: %s", familyName, strerror(-ret));
384 return ret;
385 }
386 if (int ret = readDiagMsgWithTcpInfo(tcpInfoReader)) {
387 ALOGE("Failed to read %s sockets struct tcp_info: %s", familyName, strerror(-ret));
388 return ret;
389 }
390 }
391
392 return 0;
393}
394
Lorenzo Colittie5c3c992016-07-26 17:53:50 +0900395int SockDiag::destroySockets(uint8_t proto, const uid_t uid, bool excludeLoopback) {
Lorenzo Colitti94a7b432016-03-24 16:47:12 +0900396 mSocketsDestroyed = 0;
397 Stopwatch s;
398
Lorenzo Colittie5c3c992016-07-26 17:53:50 +0900399 auto shouldDestroy = [uid, excludeLoopback] (uint8_t, const inet_diag_msg *msg) {
400 return msg != nullptr &&
401 msg->idiag_uid == uid &&
402 !(excludeLoopback && isLoopbackSocket(msg));
Lorenzo Colitti94a7b432016-03-24 16:47:12 +0900403 };
404
405 for (const int family : {AF_INET, AF_INET6}) {
406 const char *familyName = family == AF_INET ? "IPv4" : "IPv6";
407 uint32_t states = (1 << TCP_ESTABLISHED) | (1 << TCP_SYN_SENT) | (1 << TCP_SYN_RECV);
408 if (int ret = sendDumpRequest(proto, family, states)) {
409 ALOGE("Failed to dump %s sockets for UID: %s", familyName, strerror(-ret));
410 return ret;
411 }
Lorenzo Colittifff4bd32016-04-14 00:56:01 +0900412 if (int ret = readDiagMsg(proto, shouldDestroy)) {
Lorenzo Colitti94a7b432016-03-24 16:47:12 +0900413 ALOGE("Failed to destroy %s sockets for UID: %s", familyName, strerror(-ret));
414 return ret;
415 }
416 }
417
418 if (mSocketsDestroyed > 0) {
Bernie Innocenti196f1b82019-05-20 16:34:16 +0900419 ALOGI("Destroyed %d sockets for UID in %" PRId64 "us", mSocketsDestroyed, s.timeTakenUs());
Lorenzo Colitti94a7b432016-03-24 16:47:12 +0900420 }
421
422 return 0;
423}
Lorenzo Colittifff4bd32016-04-14 00:56:01 +0900424
Lorenzo Colittie5c3c992016-07-26 17:53:50 +0900425int SockDiag::destroySockets(const UidRanges& uidRanges, const std::set<uid_t>& skipUids,
426 bool excludeLoopback) {
Lorenzo Colittifff4bd32016-04-14 00:56:01 +0900427 mSocketsDestroyed = 0;
428 Stopwatch s;
429
430 auto shouldDestroy = [&] (uint8_t, const inet_diag_msg *msg) {
431 return msg != nullptr &&
432 uidRanges.hasUid(msg->idiag_uid) &&
Lorenzo Colittie5c3c992016-07-26 17:53:50 +0900433 skipUids.find(msg->idiag_uid) == skipUids.end() &&
steven_fannf3cfb3a2021-01-20 14:43:00 +0800434 !(excludeLoopback && isLoopbackSocket(msg)) &&
435 !isAdbSocket(msg, getAdbPort());
Lorenzo Colittifff4bd32016-04-14 00:56:01 +0900436 };
437
Lorenzo Colittifbe76b92016-09-14 02:25:05 +0900438 iovec iov[] = {
439 { nullptr, 0 },
440 };
441
442 if (int ret = destroyLiveSockets(shouldDestroy, "UID", iov, ARRAY_SIZE(iov))) {
Lorenzo Colittifff4bd32016-04-14 00:56:01 +0900443 return ret;
444 }
445
Lorenzo Colittifff4bd32016-04-14 00:56:01 +0900446 if (mSocketsDestroyed > 0) {
Bernie Innocenti196f1b82019-05-20 16:34:16 +0900447 ALOGI("Destroyed %d sockets for %s skip={%s} in %" PRId64 "us", mSocketsDestroyed,
448 uidRanges.toString().c_str(), android::base::Join(skipUids, " ").c_str(),
449 s.timeTakenUs());
Lorenzo Colittifff4bd32016-04-14 00:56:01 +0900450 }
451
452 return 0;
453}
Lorenzo Colittifbe76b92016-09-14 02:25:05 +0900454
455// Destroys all "live" (CONNECTED, SYN_SENT, SYN_RECV) TCP sockets on the specified netId where:
456// 1. The opening app no longer has permission to use this network, or:
457// 2. The opening app does have permission, but did not explicitly select this network.
458//
459// We destroy sockets without the explicit bit because we want to avoid the situation where a
460// privileged app uses its privileges without knowing it is doing so. For example, a privileged app
461// might have opened a socket on this network just because it was the default network at the
462// time. If we don't kill these sockets, those apps could continue to use them without realizing
463// that they are now sending and receiving traffic on a network that is now restricted.
464int SockDiag::destroySocketsLackingPermission(unsigned netId, Permission permission,
465 bool excludeLoopback) {
466 struct markmatch {
467 inet_diag_bc_op op;
468 // TODO: switch to inet_diag_markcond
469 __u32 mark;
470 __u32 mask;
471 } __attribute__((packed));
472 constexpr uint8_t matchlen = sizeof(markmatch);
473
474 Fwmark netIdMark, netIdMask;
475 netIdMark.netId = netId;
476 netIdMask.netId = 0xffff;
477
478 Fwmark controlMark;
479 controlMark.explicitlySelected = true;
480 controlMark.permission = permission;
481
482 // A SOCK_DIAG bytecode program that accepts the sockets we intend to destroy.
483 struct bytecode {
484 markmatch netIdMatch;
485 markmatch controlMatch;
486 inet_diag_bc_op controlJump;
487 } __attribute__((packed)) bytecode;
488
489 // The length of the INET_DIAG_BC_JMP instruction.
490 constexpr uint8_t jmplen = sizeof(inet_diag_bc_op);
491 // Jump exactly this far past the end of the program to reject.
492 constexpr uint8_t rejectoffset = sizeof(inet_diag_bc_op);
493 // Total length of the program.
494 constexpr uint8_t bytecodelen = sizeof(bytecode);
495
496 bytecode = (struct bytecode) {
497 // If netId matches, continue, otherwise, reject (i.e., leave socket alone).
498 { { INET_DIAG_BC_MARK_COND, matchlen, bytecodelen + rejectoffset },
499 netIdMark.intValue, netIdMask.intValue },
500
501 // If explicit and permission bits match, go to the JMP below which rejects the socket
502 // (i.e., we leave it alone). Otherwise, jump to the end of the program, which accepts the
503 // socket (so we destroy it).
504 { { INET_DIAG_BC_MARK_COND, matchlen, matchlen + jmplen },
505 controlMark.intValue, controlMark.intValue },
506
507 // This JMP unconditionally rejects the packet by jumping to the reject target. It is
508 // necessary to keep the kernel bytecode verifier happy. If we don't have a JMP the bytecode
509 // is invalid because the target of every no jump must always be reachable by yes jumps.
510 // Without this JMP, the accept target is not reachable by yes jumps and the program will
511 // be rejected by the validator.
512 { INET_DIAG_BC_JMP, jmplen, jmplen + rejectoffset },
513
514 // We have reached the end of the program. Accept the socket, and destroy it below.
515 };
516
517 struct nlattr nla = {
Nick Desaulniers6b357502019-10-11 09:26:44 -0700518 .nla_len = sizeof(struct nlattr) + bytecodelen,
519 .nla_type = INET_DIAG_REQ_BYTECODE,
Lorenzo Colittifbe76b92016-09-14 02:25:05 +0900520 };
521
522 iovec iov[] = {
523 { nullptr, 0 },
524 { &nla, sizeof(nla) },
525 { &bytecode, bytecodelen },
526 };
527
528 mSocketsDestroyed = 0;
529 Stopwatch s;
530
531 auto shouldDestroy = [&] (uint8_t, const inet_diag_msg *msg) {
532 return msg != nullptr && !(excludeLoopback && isLoopbackSocket(msg));
533 };
534
535 if (int ret = destroyLiveSockets(shouldDestroy, "permission change", iov, ARRAY_SIZE(iov))) {
536 return ret;
537 }
538
539 if (mSocketsDestroyed > 0) {
Bernie Innocenti196f1b82019-05-20 16:34:16 +0900540 ALOGI("Destroyed %d sockets for netId %d permission=%d in %" PRId64 "us", mSocketsDestroyed,
541 netId, permission, s.timeTakenUs());
Lorenzo Colittifbe76b92016-09-14 02:25:05 +0900542 }
543
544 return 0;
545}
Lorenzo Colitti7035f222017-02-13 18:29:00 +0900546
547} // namespace net
548} // namespace android