2 * Copyright (C) 2016 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
20 #include <netinet/in.h>
21 #include <netinet/tcp.h>
22 #include <sys/socket.h>
25 #include <linux/netlink.h>
26 #include <linux/sock_diag.h>
27 #include <linux/inet_diag.h>
29 #define LOG_TAG "Netd"
31 #include <android-base/strings.h>
32 #include <cutils/log.h>
34 #include "NetdConstants.h"
40 #define SOCK_DESTROY 21
45 int checkError(int fd) {
49 } __attribute__((__packed__)) ack;
50 ssize_t bytesread = recv(fd, &ack, sizeof(ack), MSG_DONTWAIT | MSG_PEEK);
51 if (bytesread == -1) {
52 // Read failed (error), or nothing to read (good).
53 return (errno == EAGAIN) ? 0 : -errno;
54 } else if (bytesread == (ssize_t) sizeof(ack) && ack.h.nlmsg_type == NLMSG_ERROR) {
55 // We got an error. Consume it.
56 recv(fd, &ack, sizeof(ack), 0);
59 // The kernel replied with something. Leave it to the caller.
66 bool SockDiag::open() {
71 mSock = socket(PF_NETLINK, SOCK_DGRAM, NETLINK_INET_DIAG);
72 mWriteSock = socket(PF_NETLINK, SOCK_DGRAM, NETLINK_INET_DIAG);
78 sockaddr_nl nl = { .nl_family = AF_NETLINK };
79 if ((connect(mSock, reinterpret_cast<sockaddr *>(&nl), sizeof(nl)) == -1) ||
80 (connect(mWriteSock, reinterpret_cast<sockaddr *>(&nl), sizeof(nl)) == -1)) {
88 int SockDiag::sendDumpRequest(uint8_t proto, uint8_t family, uint32_t states,
89 iovec *iov, int iovcnt) {
93 } __attribute__((__packed__)) request = {
95 .nlmsg_type = SOCK_DIAG_BY_FAMILY,
96 .nlmsg_flags = NLM_F_REQUEST | NLM_F_DUMP,
99 .sdiag_family = family,
100 .sdiag_protocol = proto,
101 .idiag_states = states,
106 iov[0].iov_base = &request;
107 iov[0].iov_len = sizeof(request);
108 for (int i = 0; i < iovcnt; i++) {
109 len += iov[i].iov_len;
111 request.nlh.nlmsg_len = len;
113 if (writev(mSock, iov, iovcnt) != (ssize_t) len) {
117 return checkError(mSock);
120 int SockDiag::sendDumpRequest(uint8_t proto, uint8_t family, uint32_t states) {
124 return sendDumpRequest(proto, family, states, iov, ARRAY_SIZE(iov));
127 int SockDiag::sendDumpRequest(uint8_t proto, uint8_t family, const char *addrstr) {
128 addrinfo hints = { .ai_flags = AI_NUMERICHOST };
130 in6_addr mapped = { .s6_addr32 = { 0, 0, htonl(0xffff), 0 } };
133 // TODO: refactor the netlink parsing code out of system/core, bring it into netd, and stop
134 // doing string conversions when they're not necessary.
135 if ((ret = getaddrinfo(addrstr, nullptr, &hints, &res)) != 0) {
139 // So we don't have to call freeaddrinfo on every failure path.
140 ScopedAddrinfo resP(res);
144 if (res->ai_family == AF_INET && family == AF_INET) {
145 in_addr& ina = reinterpret_cast<sockaddr_in*>(res->ai_addr)->sin_addr;
147 addrlen = sizeof(ina);
148 } else if (res->ai_family == AF_INET && family == AF_INET6) {
149 in_addr& ina = reinterpret_cast<sockaddr_in*>(res->ai_addr)->sin_addr;
150 mapped.s6_addr32[3] = ina.s_addr;
152 addrlen = sizeof(mapped);
153 } else if (res->ai_family == AF_INET6 && family == AF_INET6) {
154 in6_addr& in6a = reinterpret_cast<sockaddr_in6*>(res->ai_addr)->sin6_addr;
156 addrlen = sizeof(in6a);
158 return -EAFNOSUPPORT;
161 uint8_t prefixlen = addrlen * 8;
162 uint8_t yesjump = sizeof(inet_diag_bc_op) + sizeof(inet_diag_hostcond) + addrlen;
163 uint8_t nojump = yesjump + 4;
168 inet_diag_hostcond cond;
169 } __attribute__((__packed__)) attrs = {
171 .nla_type = INET_DIAG_REQ_BYTECODE,
186 attrs.nla.nla_len = sizeof(attrs) + addrlen;
190 { &attrs, sizeof(attrs) },
194 uint32_t states = ~(1 << TCP_TIME_WAIT);
195 return sendDumpRequest(proto, family, states, iov, ARRAY_SIZE(iov));
198 int SockDiag::readDiagMsg(uint8_t proto, SockDiag::DumpCallback callback) {
199 char buf[kBufferSize];
203 bytesread = read(mSock, buf, sizeof(buf));
209 uint32_t len = bytesread;
210 for (nlmsghdr *nlh = reinterpret_cast<nlmsghdr *>(buf);
212 nlh = NLMSG_NEXT(nlh, len)) {
213 switch (nlh->nlmsg_type) {
215 callback(proto, NULL);
218 nlmsgerr *err = reinterpret_cast<nlmsgerr *>(NLMSG_DATA(nlh));
222 inet_diag_msg *msg = reinterpret_cast<inet_diag_msg *>(NLMSG_DATA(nlh));
223 if (callback(proto, msg)) {
224 sockDestroy(proto, msg);
228 } while (bytesread > 0);
233 // Determines whether a socket is a loopback socket. Does not check socket state.
234 bool SockDiag::isLoopbackSocket(const inet_diag_msg *msg) {
235 switch (msg->idiag_family) {
237 // Old kernels only copy the IPv4 address and leave the other 12 bytes uninitialized.
238 return IN_LOOPBACK(htonl(msg->id.idiag_src[0])) ||
239 IN_LOOPBACK(htonl(msg->id.idiag_dst[0])) ||
240 msg->id.idiag_src[0] == msg->id.idiag_dst[0];
243 const struct in6_addr *src = (const struct in6_addr *) &msg->id.idiag_src;
244 const struct in6_addr *dst = (const struct in6_addr *) &msg->id.idiag_dst;
245 return (IN6_IS_ADDR_V4MAPPED(src) && IN_LOOPBACK(src->s6_addr32[3])) ||
246 (IN6_IS_ADDR_V4MAPPED(dst) && IN_LOOPBACK(dst->s6_addr32[3])) ||
247 IN6_IS_ADDR_LOOPBACK(src) || IN6_IS_ADDR_LOOPBACK(dst) ||
248 !memcmp(src, dst, sizeof(*src));
255 int SockDiag::sockDestroy(uint8_t proto, const inet_diag_msg *msg) {
256 if (msg == nullptr) {
260 DestroyRequest request = {
262 .nlmsg_type = SOCK_DESTROY,
263 .nlmsg_flags = NLM_F_REQUEST,
266 .sdiag_family = msg->idiag_family,
267 .sdiag_protocol = proto,
268 .idiag_states = (uint32_t) (1 << msg->idiag_state),
272 request.nlh.nlmsg_len = sizeof(request);
274 if (write(mWriteSock, &request, sizeof(request)) < (ssize_t) sizeof(request)) {
278 int ret = checkError(mWriteSock);
279 if (!ret) mSocketsDestroyed++;
283 int SockDiag::destroySockets(uint8_t proto, int family, const char *addrstr) {
288 if (int ret = sendDumpRequest(proto, family, addrstr)) {
292 auto destroyAll = [] (uint8_t, const inet_diag_msg*) { return true; };
294 return readDiagMsg(proto, destroyAll);
297 int SockDiag::destroySockets(const char *addrstr) {
299 mSocketsDestroyed = 0;
301 if (!strchr(addrstr, ':')) {
302 if (int ret = destroySockets(IPPROTO_TCP, AF_INET, addrstr)) {
303 ALOGE("Failed to destroy IPv4 sockets on %s: %s", addrstr, strerror(-ret));
307 if (int ret = destroySockets(IPPROTO_TCP, AF_INET6, addrstr)) {
308 ALOGE("Failed to destroy IPv6 sockets on %s: %s", addrstr, strerror(-ret));
312 if (mSocketsDestroyed > 0) {
313 ALOGI("Destroyed %d sockets on %s in %.1f ms", mSocketsDestroyed, addrstr, s.timeTaken());
316 return mSocketsDestroyed;
319 int SockDiag::destroyLiveSockets(DumpCallback destroyFilter) {
320 int proto = IPPROTO_TCP;
322 for (const int family : {AF_INET, AF_INET6}) {
323 const char *familyName = (family == AF_INET) ? "IPv4" : "IPv6";
324 uint32_t states = (1 << TCP_ESTABLISHED) | (1 << TCP_SYN_SENT) | (1 << TCP_SYN_RECV);
325 if (int ret = sendDumpRequest(proto, family, states)) {
326 ALOGE("Failed to dump %s sockets for UID: %s", familyName, strerror(-ret));
329 if (int ret = readDiagMsg(proto, destroyFilter)) {
330 ALOGE("Failed to destroy %s sockets for UID: %s", familyName, strerror(-ret));
338 int SockDiag::destroySockets(uint8_t proto, const uid_t uid, bool excludeLoopback) {
339 mSocketsDestroyed = 0;
342 auto shouldDestroy = [uid, excludeLoopback] (uint8_t, const inet_diag_msg *msg) {
343 return msg != nullptr &&
344 msg->idiag_uid == uid &&
345 !(excludeLoopback && isLoopbackSocket(msg));
348 for (const int family : {AF_INET, AF_INET6}) {
349 const char *familyName = family == AF_INET ? "IPv4" : "IPv6";
350 uint32_t states = (1 << TCP_ESTABLISHED) | (1 << TCP_SYN_SENT) | (1 << TCP_SYN_RECV);
351 if (int ret = sendDumpRequest(proto, family, states)) {
352 ALOGE("Failed to dump %s sockets for UID: %s", familyName, strerror(-ret));
355 if (int ret = readDiagMsg(proto, shouldDestroy)) {
356 ALOGE("Failed to destroy %s sockets for UID: %s", familyName, strerror(-ret));
361 if (mSocketsDestroyed > 0) {
362 ALOGI("Destroyed %d sockets for UID in %.1f ms", mSocketsDestroyed, s.timeTaken());
368 int SockDiag::destroySockets(const UidRanges& uidRanges, const std::set<uid_t>& skipUids,
369 bool excludeLoopback) {
370 mSocketsDestroyed = 0;
373 auto shouldDestroy = [&] (uint8_t, const inet_diag_msg *msg) {
374 return msg != nullptr &&
375 uidRanges.hasUid(msg->idiag_uid) &&
376 skipUids.find(msg->idiag_uid) == skipUids.end() &&
377 !(excludeLoopback && isLoopbackSocket(msg));
380 if (int ret = destroyLiveSockets(shouldDestroy)) {
384 std::vector<uid_t> skipUidStrings;
385 for (uid_t uid : skipUids) {
386 skipUidStrings.push_back(uid);
388 std::sort(skipUidStrings.begin(), skipUidStrings.end());
390 if (mSocketsDestroyed > 0) {
391 ALOGI("Destroyed %d sockets for %s skip={%s} in %.1f ms",
392 mSocketsDestroyed, uidRanges.toString().c_str(),
393 android::base::Join(skipUidStrings, " ").c_str(), s.timeTaken());