blob: 6b93a9755a2eaf7dbca3a45878e2c464eed8d3cd [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"
35#include "SockDiag.h"
36
Lorenzo Colittif32fc592016-02-15 01:09:14 +090037#include <chrono>
38
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +090039#ifndef SOCK_DESTROY
40#define SOCK_DESTROY 21
41#endif
42
43namespace {
44
45struct AddrinfoDeleter {
46 void operator()(addrinfo *a) { if (a) freeaddrinfo(a); }
47};
48
49typedef std::unique_ptr<addrinfo, AddrinfoDeleter> ScopedAddrinfo;
50
51int checkError(int fd) {
52 struct {
53 nlmsghdr h;
54 nlmsgerr err;
55 } __attribute__((__packed__)) ack;
56 ssize_t bytesread = recv(fd, &ack, sizeof(ack), MSG_DONTWAIT | MSG_PEEK);
57 if (bytesread == -1) {
58 // Read failed (error), or nothing to read (good).
59 return (errno == EAGAIN) ? 0 : -errno;
60 } else if (bytesread == (ssize_t) sizeof(ack) && ack.h.nlmsg_type == NLMSG_ERROR) {
61 // We got an error. Consume it.
62 recv(fd, &ack, sizeof(ack), 0);
63 return ack.err.error;
64 } else {
65 // The kernel replied with something. Leave it to the caller.
66 return 0;
67 }
68}
69
70} // namespace
71
72bool SockDiag::open() {
73 if (hasSocks()) {
74 return false;
75 }
76
77 mSock = socket(PF_NETLINK, SOCK_DGRAM, NETLINK_INET_DIAG);
78 mWriteSock = socket(PF_NETLINK, SOCK_DGRAM, NETLINK_INET_DIAG);
79 if (!hasSocks()) {
80 closeSocks();
81 return false;
82 }
83
84 sockaddr_nl nl = { .nl_family = AF_NETLINK };
85 if ((connect(mSock, reinterpret_cast<sockaddr *>(&nl), sizeof(nl)) == -1) ||
86 (connect(mWriteSock, reinterpret_cast<sockaddr *>(&nl), sizeof(nl)) == -1)) {
87 closeSocks();
88 return false;
89 }
90
91 return true;
92}
93
Lorenzo Colitti94a7b432016-03-24 16:47:12 +090094int SockDiag::sendDumpRequest(uint8_t proto, uint8_t family, uint32_t states,
95 iovec *iov, int iovcnt) {
96 struct {
97 nlmsghdr nlh;
98 inet_diag_req_v2 req;
99 } __attribute__((__packed__)) request = {
100 .nlh = {
101 .nlmsg_type = SOCK_DIAG_BY_FAMILY,
102 .nlmsg_flags = NLM_F_REQUEST | NLM_F_DUMP,
103 },
104 .req = {
105 .sdiag_family = family,
106 .sdiag_protocol = proto,
107 .idiag_states = states,
108 },
109 };
110
111 size_t len = 0;
112 iov[0].iov_base = &request;
113 iov[0].iov_len = sizeof(request);
114 for (int i = 0; i < iovcnt; i++) {
115 len += iov[i].iov_len;
116 }
117 request.nlh.nlmsg_len = len;
118
119 if (writev(mSock, iov, iovcnt) != (ssize_t) len) {
120 return -errno;
121 }
122
123 return checkError(mSock);
124}
125
126int SockDiag::sendDumpRequest(uint8_t proto, uint8_t family, uint32_t states) {
127 iovec iov[] = {
128 { nullptr, 0 },
129 };
130 return sendDumpRequest(proto, family, states, iov, ARRAY_SIZE(iov));
131}
132
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +0900133int SockDiag::sendDumpRequest(uint8_t proto, uint8_t family, const char *addrstr) {
134 addrinfo hints = { .ai_flags = AI_NUMERICHOST };
135 addrinfo *res;
136 in6_addr mapped = { .s6_addr32 = { 0, 0, htonl(0xffff), 0 } };
137 int ret;
138
139 // TODO: refactor the netlink parsing code out of system/core, bring it into netd, and stop
140 // doing string conversions when they're not necessary.
141 if ((ret = getaddrinfo(addrstr, nullptr, &hints, &res)) != 0) {
142 return -EINVAL;
143 }
144
145 // So we don't have to call freeaddrinfo on every failure path.
146 ScopedAddrinfo resP(res);
147
148 void *addr;
149 uint8_t addrlen;
150 if (res->ai_family == AF_INET && family == AF_INET) {
151 in_addr& ina = reinterpret_cast<sockaddr_in*>(res->ai_addr)->sin_addr;
152 addr = &ina;
153 addrlen = sizeof(ina);
154 } else if (res->ai_family == AF_INET && family == AF_INET6) {
155 in_addr& ina = reinterpret_cast<sockaddr_in*>(res->ai_addr)->sin_addr;
156 mapped.s6_addr32[3] = ina.s_addr;
157 addr = &mapped;
158 addrlen = sizeof(mapped);
159 } else if (res->ai_family == AF_INET6 && family == AF_INET6) {
160 in6_addr& in6a = reinterpret_cast<sockaddr_in6*>(res->ai_addr)->sin6_addr;
161 addr = &in6a;
162 addrlen = sizeof(in6a);
163 } else {
164 return -EAFNOSUPPORT;
165 }
166
167 uint8_t prefixlen = addrlen * 8;
168 uint8_t yesjump = sizeof(inet_diag_bc_op) + sizeof(inet_diag_hostcond) + addrlen;
169 uint8_t nojump = yesjump + 4;
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +0900170
171 struct {
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +0900172 nlattr nla;
173 inet_diag_bc_op op;
174 inet_diag_hostcond cond;
Lorenzo Colitti94a7b432016-03-24 16:47:12 +0900175 } __attribute__((__packed__)) attrs = {
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +0900176 .nla = {
177 .nla_type = INET_DIAG_REQ_BYTECODE,
178 },
179 .op = {
180 INET_DIAG_BC_S_COND,
181 yesjump,
182 nojump,
183 },
184 .cond = {
185 family,
186 prefixlen,
187 -1,
188 {}
189 },
190 };
191
Lorenzo Colitti94a7b432016-03-24 16:47:12 +0900192 attrs.nla.nla_len = sizeof(attrs) + addrlen;
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +0900193
Lorenzo Colitti94a7b432016-03-24 16:47:12 +0900194 iovec iov[] = {
195 { nullptr, 0 },
196 { &attrs, sizeof(attrs) },
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +0900197 { addr, addrlen },
198 };
199
Lorenzo Colitti94a7b432016-03-24 16:47:12 +0900200 uint32_t states = ~(1 << TCP_TIME_WAIT);
201 return sendDumpRequest(proto, family, states, iov, ARRAY_SIZE(iov));
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +0900202}
203
Chih-Hung Hsiehb22e4d22016-07-28 14:13:11 -0700204int SockDiag::readDiagMsg(uint8_t proto, const SockDiag::DumpCallback& callback) {
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +0900205 char buf[kBufferSize];
206
207 ssize_t bytesread;
208 do {
209 bytesread = read(mSock, buf, sizeof(buf));
210
211 if (bytesread < 0) {
212 return -errno;
213 }
214
215 uint32_t len = bytesread;
216 for (nlmsghdr *nlh = reinterpret_cast<nlmsghdr *>(buf);
217 NLMSG_OK(nlh, len);
218 nlh = NLMSG_NEXT(nlh, len)) {
219 switch (nlh->nlmsg_type) {
220 case NLMSG_DONE:
221 callback(proto, NULL);
222 return 0;
223 case NLMSG_ERROR: {
224 nlmsgerr *err = reinterpret_cast<nlmsgerr *>(NLMSG_DATA(nlh));
225 return err->error;
226 }
227 default:
228 inet_diag_msg *msg = reinterpret_cast<inet_diag_msg *>(NLMSG_DATA(nlh));
Lorenzo Colittifff4bd32016-04-14 00:56:01 +0900229 if (callback(proto, msg)) {
230 sockDestroy(proto, msg);
231 }
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +0900232 }
233 }
234 } while (bytesread > 0);
235
236 return 0;
237}
238
Lorenzo Colittie5c3c992016-07-26 17:53:50 +0900239// Determines whether a socket is a loopback socket. Does not check socket state.
240bool SockDiag::isLoopbackSocket(const inet_diag_msg *msg) {
241 switch (msg->idiag_family) {
242 case AF_INET:
243 // Old kernels only copy the IPv4 address and leave the other 12 bytes uninitialized.
244 return IN_LOOPBACK(htonl(msg->id.idiag_src[0])) ||
245 IN_LOOPBACK(htonl(msg->id.idiag_dst[0])) ||
246 msg->id.idiag_src[0] == msg->id.idiag_dst[0];
247
248 case AF_INET6: {
249 const struct in6_addr *src = (const struct in6_addr *) &msg->id.idiag_src;
250 const struct in6_addr *dst = (const struct in6_addr *) &msg->id.idiag_dst;
251 return (IN6_IS_ADDR_V4MAPPED(src) && IN_LOOPBACK(src->s6_addr32[3])) ||
252 (IN6_IS_ADDR_V4MAPPED(dst) && IN_LOOPBACK(dst->s6_addr32[3])) ||
253 IN6_IS_ADDR_LOOPBACK(src) || IN6_IS_ADDR_LOOPBACK(dst) ||
254 !memcmp(src, dst, sizeof(*src));
255 }
256 default:
257 return false;
258 }
259}
260
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +0900261int SockDiag::sockDestroy(uint8_t proto, const inet_diag_msg *msg) {
Lorenzo Colittif32fc592016-02-15 01:09:14 +0900262 if (msg == nullptr) {
263 return 0;
264 }
265
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +0900266 DestroyRequest request = {
267 .nlh = {
268 .nlmsg_type = SOCK_DESTROY,
269 .nlmsg_flags = NLM_F_REQUEST,
270 },
271 .req = {
272 .sdiag_family = msg->idiag_family,
273 .sdiag_protocol = proto,
274 .idiag_states = (uint32_t) (1 << msg->idiag_state),
275 .id = msg->id,
276 },
277 };
278 request.nlh.nlmsg_len = sizeof(request);
279
280 if (write(mWriteSock, &request, sizeof(request)) < (ssize_t) sizeof(request)) {
281 return -errno;
282 }
283
Lorenzo Colittif32fc592016-02-15 01:09:14 +0900284 int ret = checkError(mWriteSock);
285 if (!ret) mSocketsDestroyed++;
286 return ret;
287}
288
289int SockDiag::destroySockets(uint8_t proto, int family, const char *addrstr) {
290 if (!hasSocks()) {
291 return -EBADFD;
292 }
293
294 if (int ret = sendDumpRequest(proto, family, addrstr)) {
295 return ret;
296 }
297
Lorenzo Colittifff4bd32016-04-14 00:56:01 +0900298 auto destroyAll = [] (uint8_t, const inet_diag_msg*) { return true; };
Lorenzo Colittif32fc592016-02-15 01:09:14 +0900299
Lorenzo Colittifff4bd32016-04-14 00:56:01 +0900300 return readDiagMsg(proto, destroyAll);
Lorenzo Colittif32fc592016-02-15 01:09:14 +0900301}
302
303int SockDiag::destroySockets(const char *addrstr) {
Lorenzo Colitti94a7b432016-03-24 16:47:12 +0900304 Stopwatch s;
Lorenzo Colittif32fc592016-02-15 01:09:14 +0900305 mSocketsDestroyed = 0;
Lorenzo Colitti94a7b432016-03-24 16:47:12 +0900306
Lorenzo Colittif32fc592016-02-15 01:09:14 +0900307 if (!strchr(addrstr, ':')) {
308 if (int ret = destroySockets(IPPROTO_TCP, AF_INET, addrstr)) {
309 ALOGE("Failed to destroy IPv4 sockets on %s: %s", addrstr, strerror(-ret));
310 return ret;
311 }
312 }
313 if (int ret = destroySockets(IPPROTO_TCP, AF_INET6, addrstr)) {
314 ALOGE("Failed to destroy IPv6 sockets on %s: %s", addrstr, strerror(-ret));
315 return ret;
316 }
Lorenzo Colittif32fc592016-02-15 01:09:14 +0900317
318 if (mSocketsDestroyed > 0) {
Lorenzo Colitti94a7b432016-03-24 16:47:12 +0900319 ALOGI("Destroyed %d sockets on %s in %.1f ms", mSocketsDestroyed, addrstr, s.timeTaken());
Lorenzo Colittif32fc592016-02-15 01:09:14 +0900320 }
321
322 return mSocketsDestroyed;
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +0900323}
Lorenzo Colitti94a7b432016-03-24 16:47:12 +0900324
Lorenzo Colittifff4bd32016-04-14 00:56:01 +0900325int SockDiag::destroyLiveSockets(DumpCallback destroyFilter) {
326 int proto = IPPROTO_TCP;
327
328 for (const int family : {AF_INET, AF_INET6}) {
329 const char *familyName = (family == AF_INET) ? "IPv4" : "IPv6";
330 uint32_t states = (1 << TCP_ESTABLISHED) | (1 << TCP_SYN_SENT) | (1 << TCP_SYN_RECV);
331 if (int ret = sendDumpRequest(proto, family, states)) {
332 ALOGE("Failed to dump %s sockets for UID: %s", familyName, strerror(-ret));
333 return ret;
334 }
335 if (int ret = readDiagMsg(proto, destroyFilter)) {
336 ALOGE("Failed to destroy %s sockets for UID: %s", familyName, strerror(-ret));
337 return ret;
338 }
339 }
340
341 return 0;
342}
343
Lorenzo Colittie5c3c992016-07-26 17:53:50 +0900344int SockDiag::destroySockets(uint8_t proto, const uid_t uid, bool excludeLoopback) {
Lorenzo Colitti94a7b432016-03-24 16:47:12 +0900345 mSocketsDestroyed = 0;
346 Stopwatch s;
347
Lorenzo Colittie5c3c992016-07-26 17:53:50 +0900348 auto shouldDestroy = [uid, excludeLoopback] (uint8_t, const inet_diag_msg *msg) {
349 return msg != nullptr &&
350 msg->idiag_uid == uid &&
351 !(excludeLoopback && isLoopbackSocket(msg));
Lorenzo Colitti94a7b432016-03-24 16:47:12 +0900352 };
353
354 for (const int family : {AF_INET, AF_INET6}) {
355 const char *familyName = family == AF_INET ? "IPv4" : "IPv6";
356 uint32_t states = (1 << TCP_ESTABLISHED) | (1 << TCP_SYN_SENT) | (1 << TCP_SYN_RECV);
357 if (int ret = sendDumpRequest(proto, family, states)) {
358 ALOGE("Failed to dump %s sockets for UID: %s", familyName, strerror(-ret));
359 return ret;
360 }
Lorenzo Colittifff4bd32016-04-14 00:56:01 +0900361 if (int ret = readDiagMsg(proto, shouldDestroy)) {
Lorenzo Colitti94a7b432016-03-24 16:47:12 +0900362 ALOGE("Failed to destroy %s sockets for UID: %s", familyName, strerror(-ret));
363 return ret;
364 }
365 }
366
367 if (mSocketsDestroyed > 0) {
368 ALOGI("Destroyed %d sockets for UID in %.1f ms", mSocketsDestroyed, s.timeTaken());
369 }
370
371 return 0;
372}
Lorenzo Colittifff4bd32016-04-14 00:56:01 +0900373
Lorenzo Colittie5c3c992016-07-26 17:53:50 +0900374int SockDiag::destroySockets(const UidRanges& uidRanges, const std::set<uid_t>& skipUids,
375 bool excludeLoopback) {
Lorenzo Colittifff4bd32016-04-14 00:56:01 +0900376 mSocketsDestroyed = 0;
377 Stopwatch s;
378
379 auto shouldDestroy = [&] (uint8_t, const inet_diag_msg *msg) {
380 return msg != nullptr &&
381 uidRanges.hasUid(msg->idiag_uid) &&
Lorenzo Colittie5c3c992016-07-26 17:53:50 +0900382 skipUids.find(msg->idiag_uid) == skipUids.end() &&
383 !(excludeLoopback && isLoopbackSocket(msg));
Lorenzo Colittifff4bd32016-04-14 00:56:01 +0900384 };
385
386 if (int ret = destroyLiveSockets(shouldDestroy)) {
387 return ret;
388 }
389
390 std::vector<uid_t> skipUidStrings;
391 for (uid_t uid : skipUids) {
392 skipUidStrings.push_back(uid);
393 }
394 std::sort(skipUidStrings.begin(), skipUidStrings.end());
395
396 if (mSocketsDestroyed > 0) {
397 ALOGI("Destroyed %d sockets for %s skip={%s} in %.1f ms",
398 mSocketsDestroyed, uidRanges.toString().c_str(),
399 android::base::Join(skipUidStrings, " ").c_str(), s.timeTaken());
400 }
401
402 return 0;
403}