blob: 32fec6e96f6730a54833803539ef4ba926ddaf2b [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
34#include "NetdConstants.h"
Lorenzo Colittifbe76b92016-09-14 02:25:05 +090035#include "Permission.h"
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +090036#include "SockDiag.h"
Robin Lee7e05cc92016-09-21 16:31:33 +090037#include "Stopwatch.h"
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +090038
Lorenzo Colittif32fc592016-02-15 01:09:14 +090039#include <chrono>
40
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 {
48namespace net {
49
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +090050namespace {
51
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +090052int checkError(int fd) {
53 struct {
54 nlmsghdr h;
55 nlmsgerr err;
56 } __attribute__((__packed__)) ack;
57 ssize_t bytesread = recv(fd, &ack, sizeof(ack), MSG_DONTWAIT | MSG_PEEK);
58 if (bytesread == -1) {
59 // Read failed (error), or nothing to read (good).
60 return (errno == EAGAIN) ? 0 : -errno;
61 } else if (bytesread == (ssize_t) sizeof(ack) && ack.h.nlmsg_type == NLMSG_ERROR) {
62 // We got an error. Consume it.
63 recv(fd, &ack, sizeof(ack), 0);
64 return ack.err.error;
65 } else {
66 // The kernel replied with something. Leave it to the caller.
67 return 0;
68 }
69}
70
71} // namespace
72
73bool SockDiag::open() {
74 if (hasSocks()) {
75 return false;
76 }
77
Nick Kralevichaf02b552016-12-20 08:40:35 -080078 mSock = socket(PF_NETLINK, SOCK_DGRAM | SOCK_CLOEXEC, NETLINK_INET_DIAG);
79 mWriteSock = socket(PF_NETLINK, SOCK_DGRAM | SOCK_CLOEXEC, NETLINK_INET_DIAG);
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +090080 if (!hasSocks()) {
81 closeSocks();
82 return false;
83 }
84
85 sockaddr_nl nl = { .nl_family = AF_NETLINK };
86 if ((connect(mSock, reinterpret_cast<sockaddr *>(&nl), sizeof(nl)) == -1) ||
87 (connect(mWriteSock, reinterpret_cast<sockaddr *>(&nl), sizeof(nl)) == -1)) {
88 closeSocks();
89 return false;
90 }
91
92 return true;
93}
94
Hugo Benichidee94812018-01-12 14:47:00 +090095int SockDiag::sendDumpRequest(uint8_t proto, uint8_t family, uint8_t extensions, uint32_t states,
Lorenzo Colitti94a7b432016-03-24 16:47:12 +090096 iovec *iov, int iovcnt) {
97 struct {
98 nlmsghdr nlh;
99 inet_diag_req_v2 req;
100 } __attribute__((__packed__)) request = {
101 .nlh = {
102 .nlmsg_type = SOCK_DIAG_BY_FAMILY,
103 .nlmsg_flags = NLM_F_REQUEST | NLM_F_DUMP,
104 },
105 .req = {
106 .sdiag_family = family,
107 .sdiag_protocol = proto,
Hugo Benichidee94812018-01-12 14:47:00 +0900108 .idiag_ext = extensions,
Lorenzo Colitti94a7b432016-03-24 16:47:12 +0900109 .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 };
Hugo Benichidee94812018-01-12 14:47:00 +0900132 return sendDumpRequest(proto, family, 0, states, iov, ARRAY_SIZE(iov));
Lorenzo Colitti94a7b432016-03-24 16:47:12 +0900133}
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);
Hugo Benichidee94812018-01-12 14:47:00 +0900203 return sendDumpRequest(proto, family, 0, 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) {
Lorenzo Colitti0b733e42017-02-13 16:29:00 +0900208 const inet_diag_msg *msg = reinterpret_cast<inet_diag_msg *>(NLMSG_DATA(nlh));
209 if (shouldDestroy(proto, msg)) {
210 sockDestroy(proto, msg);
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +0900211 }
Lorenzo Colitti0b733e42017-02-13 16:29:00 +0900212 };
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +0900213
Lorenzo Colitti0b733e42017-02-13 16:29:00 +0900214 return processNetlinkDump(mSock, callback);
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +0900215}
216
Hugo Benichidee94812018-01-12 14:47:00 +0900217int SockDiag::readDiagMsgWithTcpInfo(const TcpInfoReader& tcpInfoReader) {
218 NetlinkDumpCallback callback = [tcpInfoReader] (nlmsghdr *nlh) {
Hugo Benichicbaa36b2018-01-17 12:11:43 +0900219 Fwmark mark;
Hugo Benichidee94812018-01-12 14:47:00 +0900220 struct tcp_info *tcpinfo = nullptr;
Hugo Benichi54bfc7c2018-01-23 14:16:52 +0900221 uint32_t tcpinfoLength = 0;
Hugo Benichidee94812018-01-12 14:47:00 +0900222 inet_diag_msg *msg = reinterpret_cast<inet_diag_msg *>(NLMSG_DATA(nlh));
223 uint32_t attr_len = nlh->nlmsg_len - NLMSG_LENGTH(sizeof(*msg));
224 struct rtattr *attr = reinterpret_cast<struct rtattr*>(msg+1);
225 while (RTA_OK(attr, attr_len)) {
226 if (attr->rta_type == INET_DIAG_INFO) {
227 tcpinfo = reinterpret_cast<struct tcp_info*>(RTA_DATA(attr));
Hugo Benichi54bfc7c2018-01-23 14:16:52 +0900228 tcpinfoLength = RTA_PAYLOAD(attr);
Hugo Benichicbaa36b2018-01-17 12:11:43 +0900229 }
230 if (attr->rta_type == INET_DIAG_MARK) {
231 mark.intValue = *reinterpret_cast<uint32_t*>(RTA_DATA(attr));
Hugo Benichidee94812018-01-12 14:47:00 +0900232 }
233 attr = RTA_NEXT(attr, attr_len);
234 }
235
Hugo Benichi54bfc7c2018-01-23 14:16:52 +0900236 tcpInfoReader(mark, msg, tcpinfo, tcpinfoLength);
Hugo Benichidee94812018-01-12 14:47:00 +0900237 };
238
239 return processNetlinkDump(mSock, callback);
240}
241
Lorenzo Colittie5c3c992016-07-26 17:53:50 +0900242// Determines whether a socket is a loopback socket. Does not check socket state.
243bool SockDiag::isLoopbackSocket(const inet_diag_msg *msg) {
244 switch (msg->idiag_family) {
245 case AF_INET:
246 // Old kernels only copy the IPv4 address and leave the other 12 bytes uninitialized.
247 return IN_LOOPBACK(htonl(msg->id.idiag_src[0])) ||
248 IN_LOOPBACK(htonl(msg->id.idiag_dst[0])) ||
249 msg->id.idiag_src[0] == msg->id.idiag_dst[0];
250
251 case AF_INET6: {
252 const struct in6_addr *src = (const struct in6_addr *) &msg->id.idiag_src;
253 const struct in6_addr *dst = (const struct in6_addr *) &msg->id.idiag_dst;
254 return (IN6_IS_ADDR_V4MAPPED(src) && IN_LOOPBACK(src->s6_addr32[3])) ||
255 (IN6_IS_ADDR_V4MAPPED(dst) && IN_LOOPBACK(dst->s6_addr32[3])) ||
256 IN6_IS_ADDR_LOOPBACK(src) || IN6_IS_ADDR_LOOPBACK(dst) ||
257 !memcmp(src, dst, sizeof(*src));
258 }
259 default:
260 return false;
261 }
262}
263
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +0900264int SockDiag::sockDestroy(uint8_t proto, const inet_diag_msg *msg) {
Lorenzo Colittif32fc592016-02-15 01:09:14 +0900265 if (msg == nullptr) {
266 return 0;
267 }
268
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +0900269 DestroyRequest request = {
270 .nlh = {
271 .nlmsg_type = SOCK_DESTROY,
272 .nlmsg_flags = NLM_F_REQUEST,
273 },
274 .req = {
275 .sdiag_family = msg->idiag_family,
276 .sdiag_protocol = proto,
277 .idiag_states = (uint32_t) (1 << msg->idiag_state),
278 .id = msg->id,
279 },
280 };
281 request.nlh.nlmsg_len = sizeof(request);
282
283 if (write(mWriteSock, &request, sizeof(request)) < (ssize_t) sizeof(request)) {
284 return -errno;
285 }
286
Lorenzo Colittif32fc592016-02-15 01:09:14 +0900287 int ret = checkError(mWriteSock);
288 if (!ret) mSocketsDestroyed++;
289 return ret;
290}
291
292int SockDiag::destroySockets(uint8_t proto, int family, const char *addrstr) {
293 if (!hasSocks()) {
294 return -EBADFD;
295 }
296
297 if (int ret = sendDumpRequest(proto, family, addrstr)) {
298 return ret;
299 }
300
Lorenzo Colittifff4bd32016-04-14 00:56:01 +0900301 auto destroyAll = [] (uint8_t, const inet_diag_msg*) { return true; };
Lorenzo Colittif32fc592016-02-15 01:09:14 +0900302
Lorenzo Colittifff4bd32016-04-14 00:56:01 +0900303 return readDiagMsg(proto, destroyAll);
Lorenzo Colittif32fc592016-02-15 01:09:14 +0900304}
305
306int SockDiag::destroySockets(const char *addrstr) {
Lorenzo Colitti94a7b432016-03-24 16:47:12 +0900307 Stopwatch s;
Lorenzo Colittif32fc592016-02-15 01:09:14 +0900308 mSocketsDestroyed = 0;
Lorenzo Colitti94a7b432016-03-24 16:47:12 +0900309
Lorenzo Colittif32fc592016-02-15 01:09:14 +0900310 if (!strchr(addrstr, ':')) {
311 if (int ret = destroySockets(IPPROTO_TCP, AF_INET, addrstr)) {
312 ALOGE("Failed to destroy IPv4 sockets on %s: %s", addrstr, strerror(-ret));
313 return ret;
314 }
315 }
316 if (int ret = destroySockets(IPPROTO_TCP, AF_INET6, addrstr)) {
317 ALOGE("Failed to destroy IPv6 sockets on %s: %s", addrstr, strerror(-ret));
318 return ret;
319 }
Lorenzo Colittif32fc592016-02-15 01:09:14 +0900320
321 if (mSocketsDestroyed > 0) {
Lorenzo Colitti94a7b432016-03-24 16:47:12 +0900322 ALOGI("Destroyed %d sockets on %s in %.1f ms", mSocketsDestroyed, addrstr, s.timeTaken());
Lorenzo Colittif32fc592016-02-15 01:09:14 +0900323 }
324
325 return mSocketsDestroyed;
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +0900326}
Lorenzo Colitti94a7b432016-03-24 16:47:12 +0900327
Lorenzo Colitti0b733e42017-02-13 16:29:00 +0900328int SockDiag::destroyLiveSockets(DestroyFilter destroyFilter, const char *what,
Lorenzo Colittifbe76b92016-09-14 02:25:05 +0900329 iovec *iov, int iovcnt) {
Hugo Benichidee94812018-01-12 14:47:00 +0900330 const int proto = IPPROTO_TCP;
331 const uint32_t states = (1 << TCP_ESTABLISHED) | (1 << TCP_SYN_SENT) | (1 << TCP_SYN_RECV);
Lorenzo Colittifff4bd32016-04-14 00:56:01 +0900332
333 for (const int family : {AF_INET, AF_INET6}) {
334 const char *familyName = (family == AF_INET) ? "IPv4" : "IPv6";
Hugo Benichidee94812018-01-12 14:47:00 +0900335 if (int ret = sendDumpRequest(proto, family, 0, states, iov, iovcnt)) {
Lorenzo Colittifbe76b92016-09-14 02:25:05 +0900336 ALOGE("Failed to dump %s sockets for %s: %s", familyName, what, strerror(-ret));
Lorenzo Colittifff4bd32016-04-14 00:56:01 +0900337 return ret;
338 }
339 if (int ret = readDiagMsg(proto, destroyFilter)) {
Lorenzo Colittifbe76b92016-09-14 02:25:05 +0900340 ALOGE("Failed to destroy %s sockets for %s: %s", familyName, what, strerror(-ret));
Lorenzo Colittifff4bd32016-04-14 00:56:01 +0900341 return ret;
342 }
343 }
344
345 return 0;
346}
347
Hugo Benichidee94812018-01-12 14:47:00 +0900348int SockDiag::getLiveTcpInfos(const TcpInfoReader& tcpInfoReader) {
349 const int proto = IPPROTO_TCP;
350 const uint32_t states = (1 << TCP_ESTABLISHED) | (1 << TCP_SYN_SENT) | (1 << TCP_SYN_RECV);
351 const uint8_t extensions = (1 << INET_DIAG_MEMINFO); // flag for dumping struct tcp_info.
352
353 iovec iov[] = {
354 { nullptr, 0 },
355 };
356
357 for (const int family : {AF_INET, AF_INET6}) {
358 const char *familyName = (family == AF_INET) ? "IPv4" : "IPv6";
359 if (int ret = sendDumpRequest(proto, family, extensions, states, iov, ARRAY_SIZE(iov))) {
360 ALOGE("Failed to dump %s sockets struct tcp_info: %s", familyName, strerror(-ret));
361 return ret;
362 }
363 if (int ret = readDiagMsgWithTcpInfo(tcpInfoReader)) {
364 ALOGE("Failed to read %s sockets struct tcp_info: %s", familyName, strerror(-ret));
365 return ret;
366 }
367 }
368
369 return 0;
370}
371
Lorenzo Colittie5c3c992016-07-26 17:53:50 +0900372int SockDiag::destroySockets(uint8_t proto, const uid_t uid, bool excludeLoopback) {
Lorenzo Colitti94a7b432016-03-24 16:47:12 +0900373 mSocketsDestroyed = 0;
374 Stopwatch s;
375
Lorenzo Colittie5c3c992016-07-26 17:53:50 +0900376 auto shouldDestroy = [uid, excludeLoopback] (uint8_t, const inet_diag_msg *msg) {
377 return msg != nullptr &&
378 msg->idiag_uid == uid &&
379 !(excludeLoopback && isLoopbackSocket(msg));
Lorenzo Colitti94a7b432016-03-24 16:47:12 +0900380 };
381
382 for (const int family : {AF_INET, AF_INET6}) {
383 const char *familyName = family == AF_INET ? "IPv4" : "IPv6";
384 uint32_t states = (1 << TCP_ESTABLISHED) | (1 << TCP_SYN_SENT) | (1 << TCP_SYN_RECV);
385 if (int ret = sendDumpRequest(proto, family, states)) {
386 ALOGE("Failed to dump %s sockets for UID: %s", familyName, strerror(-ret));
387 return ret;
388 }
Lorenzo Colittifff4bd32016-04-14 00:56:01 +0900389 if (int ret = readDiagMsg(proto, shouldDestroy)) {
Lorenzo Colitti94a7b432016-03-24 16:47:12 +0900390 ALOGE("Failed to destroy %s sockets for UID: %s", familyName, strerror(-ret));
391 return ret;
392 }
393 }
394
395 if (mSocketsDestroyed > 0) {
396 ALOGI("Destroyed %d sockets for UID in %.1f ms", mSocketsDestroyed, s.timeTaken());
397 }
398
399 return 0;
400}
Lorenzo Colittifff4bd32016-04-14 00:56:01 +0900401
Lorenzo Colittie5c3c992016-07-26 17:53:50 +0900402int SockDiag::destroySockets(const UidRanges& uidRanges, const std::set<uid_t>& skipUids,
403 bool excludeLoopback) {
Lorenzo Colittifff4bd32016-04-14 00:56:01 +0900404 mSocketsDestroyed = 0;
405 Stopwatch s;
406
407 auto shouldDestroy = [&] (uint8_t, const inet_diag_msg *msg) {
408 return msg != nullptr &&
409 uidRanges.hasUid(msg->idiag_uid) &&
Lorenzo Colittie5c3c992016-07-26 17:53:50 +0900410 skipUids.find(msg->idiag_uid) == skipUids.end() &&
411 !(excludeLoopback && isLoopbackSocket(msg));
Lorenzo Colittifff4bd32016-04-14 00:56:01 +0900412 };
413
Lorenzo Colittifbe76b92016-09-14 02:25:05 +0900414 iovec iov[] = {
415 { nullptr, 0 },
416 };
417
418 if (int ret = destroyLiveSockets(shouldDestroy, "UID", iov, ARRAY_SIZE(iov))) {
Lorenzo Colittifff4bd32016-04-14 00:56:01 +0900419 return ret;
420 }
421
422 std::vector<uid_t> skipUidStrings;
423 for (uid_t uid : skipUids) {
424 skipUidStrings.push_back(uid);
425 }
426 std::sort(skipUidStrings.begin(), skipUidStrings.end());
427
428 if (mSocketsDestroyed > 0) {
429 ALOGI("Destroyed %d sockets for %s skip={%s} in %.1f ms",
430 mSocketsDestroyed, uidRanges.toString().c_str(),
431 android::base::Join(skipUidStrings, " ").c_str(), s.timeTaken());
432 }
433
434 return 0;
435}
Lorenzo Colittifbe76b92016-09-14 02:25:05 +0900436
437// Destroys all "live" (CONNECTED, SYN_SENT, SYN_RECV) TCP sockets on the specified netId where:
438// 1. The opening app no longer has permission to use this network, or:
439// 2. The opening app does have permission, but did not explicitly select this network.
440//
441// We destroy sockets without the explicit bit because we want to avoid the situation where a
442// privileged app uses its privileges without knowing it is doing so. For example, a privileged app
443// might have opened a socket on this network just because it was the default network at the
444// time. If we don't kill these sockets, those apps could continue to use them without realizing
445// that they are now sending and receiving traffic on a network that is now restricted.
446int SockDiag::destroySocketsLackingPermission(unsigned netId, Permission permission,
447 bool excludeLoopback) {
448 struct markmatch {
449 inet_diag_bc_op op;
450 // TODO: switch to inet_diag_markcond
451 __u32 mark;
452 __u32 mask;
453 } __attribute__((packed));
454 constexpr uint8_t matchlen = sizeof(markmatch);
455
456 Fwmark netIdMark, netIdMask;
457 netIdMark.netId = netId;
458 netIdMask.netId = 0xffff;
459
460 Fwmark controlMark;
461 controlMark.explicitlySelected = true;
462 controlMark.permission = permission;
463
464 // A SOCK_DIAG bytecode program that accepts the sockets we intend to destroy.
465 struct bytecode {
466 markmatch netIdMatch;
467 markmatch controlMatch;
468 inet_diag_bc_op controlJump;
469 } __attribute__((packed)) bytecode;
470
471 // The length of the INET_DIAG_BC_JMP instruction.
472 constexpr uint8_t jmplen = sizeof(inet_diag_bc_op);
473 // Jump exactly this far past the end of the program to reject.
474 constexpr uint8_t rejectoffset = sizeof(inet_diag_bc_op);
475 // Total length of the program.
476 constexpr uint8_t bytecodelen = sizeof(bytecode);
477
478 bytecode = (struct bytecode) {
479 // If netId matches, continue, otherwise, reject (i.e., leave socket alone).
480 { { INET_DIAG_BC_MARK_COND, matchlen, bytecodelen + rejectoffset },
481 netIdMark.intValue, netIdMask.intValue },
482
483 // If explicit and permission bits match, go to the JMP below which rejects the socket
484 // (i.e., we leave it alone). Otherwise, jump to the end of the program, which accepts the
485 // socket (so we destroy it).
486 { { INET_DIAG_BC_MARK_COND, matchlen, matchlen + jmplen },
487 controlMark.intValue, controlMark.intValue },
488
489 // This JMP unconditionally rejects the packet by jumping to the reject target. It is
490 // necessary to keep the kernel bytecode verifier happy. If we don't have a JMP the bytecode
491 // is invalid because the target of every no jump must always be reachable by yes jumps.
492 // Without this JMP, the accept target is not reachable by yes jumps and the program will
493 // be rejected by the validator.
494 { INET_DIAG_BC_JMP, jmplen, jmplen + rejectoffset },
495
496 // We have reached the end of the program. Accept the socket, and destroy it below.
497 };
498
499 struct nlattr nla = {
500 .nla_type = INET_DIAG_REQ_BYTECODE,
501 .nla_len = sizeof(struct nlattr) + bytecodelen,
502 };
503
504 iovec iov[] = {
505 { nullptr, 0 },
506 { &nla, sizeof(nla) },
507 { &bytecode, bytecodelen },
508 };
509
510 mSocketsDestroyed = 0;
511 Stopwatch s;
512
513 auto shouldDestroy = [&] (uint8_t, const inet_diag_msg *msg) {
514 return msg != nullptr && !(excludeLoopback && isLoopbackSocket(msg));
515 };
516
517 if (int ret = destroyLiveSockets(shouldDestroy, "permission change", iov, ARRAY_SIZE(iov))) {
518 return ret;
519 }
520
521 if (mSocketsDestroyed > 0) {
522 ALOGI("Destroyed %d sockets for netId %d permission=%d in %.1f ms",
523 mSocketsDestroyed, netId, permission, s.timeTaken());
524 }
525
526 return 0;
527}
Lorenzo Colitti7035f222017-02-13 18:29:00 +0900528
529} // namespace net
530} // namespace android