blob: 6a3999770e9cd7846412641b4f0404f3b39034d7 [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
Lorenzo Colitti94a7b432016-03-24 16:47:12 +090051class Stopwatch {
52public:
53 Stopwatch(): mStart(std::chrono::steady_clock::now()) {}
54 float timeTaken() {
55 using ms = std::chrono::duration<float, std::ratio<1, 1000>>;
56 return (std::chrono::duration_cast<ms>(
57 std::chrono::steady_clock::now() - mStart)).count();
58 }
59
60private:
61 std::chrono::time_point<std::chrono::steady_clock> mStart;
62 std::string mName;
63};
64
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +090065int checkError(int fd) {
66 struct {
67 nlmsghdr h;
68 nlmsgerr err;
69 } __attribute__((__packed__)) ack;
70 ssize_t bytesread = recv(fd, &ack, sizeof(ack), MSG_DONTWAIT | MSG_PEEK);
71 if (bytesread == -1) {
72 // Read failed (error), or nothing to read (good).
73 return (errno == EAGAIN) ? 0 : -errno;
74 } else if (bytesread == (ssize_t) sizeof(ack) && ack.h.nlmsg_type == NLMSG_ERROR) {
75 // We got an error. Consume it.
76 recv(fd, &ack, sizeof(ack), 0);
77 return ack.err.error;
78 } else {
79 // The kernel replied with something. Leave it to the caller.
80 return 0;
81 }
82}
83
84} // namespace
85
86bool SockDiag::open() {
87 if (hasSocks()) {
88 return false;
89 }
90
91 mSock = socket(PF_NETLINK, SOCK_DGRAM, NETLINK_INET_DIAG);
92 mWriteSock = socket(PF_NETLINK, SOCK_DGRAM, NETLINK_INET_DIAG);
93 if (!hasSocks()) {
94 closeSocks();
95 return false;
96 }
97
98 sockaddr_nl nl = { .nl_family = AF_NETLINK };
99 if ((connect(mSock, reinterpret_cast<sockaddr *>(&nl), sizeof(nl)) == -1) ||
100 (connect(mWriteSock, reinterpret_cast<sockaddr *>(&nl), sizeof(nl)) == -1)) {
101 closeSocks();
102 return false;
103 }
104
105 return true;
106}
107
Lorenzo Colitti94a7b432016-03-24 16:47:12 +0900108int SockDiag::sendDumpRequest(uint8_t proto, uint8_t family, uint32_t states,
109 iovec *iov, int iovcnt) {
110 struct {
111 nlmsghdr nlh;
112 inet_diag_req_v2 req;
113 } __attribute__((__packed__)) request = {
114 .nlh = {
115 .nlmsg_type = SOCK_DIAG_BY_FAMILY,
116 .nlmsg_flags = NLM_F_REQUEST | NLM_F_DUMP,
117 },
118 .req = {
119 .sdiag_family = family,
120 .sdiag_protocol = proto,
121 .idiag_states = states,
122 },
123 };
124
125 size_t len = 0;
126 iov[0].iov_base = &request;
127 iov[0].iov_len = sizeof(request);
128 for (int i = 0; i < iovcnt; i++) {
129 len += iov[i].iov_len;
130 }
131 request.nlh.nlmsg_len = len;
132
133 if (writev(mSock, iov, iovcnt) != (ssize_t) len) {
134 return -errno;
135 }
136
137 return checkError(mSock);
138}
139
140int SockDiag::sendDumpRequest(uint8_t proto, uint8_t family, uint32_t states) {
141 iovec iov[] = {
142 { nullptr, 0 },
143 };
144 return sendDumpRequest(proto, family, states, iov, ARRAY_SIZE(iov));
145}
146
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +0900147int SockDiag::sendDumpRequest(uint8_t proto, uint8_t family, const char *addrstr) {
148 addrinfo hints = { .ai_flags = AI_NUMERICHOST };
149 addrinfo *res;
150 in6_addr mapped = { .s6_addr32 = { 0, 0, htonl(0xffff), 0 } };
151 int ret;
152
153 // TODO: refactor the netlink parsing code out of system/core, bring it into netd, and stop
154 // doing string conversions when they're not necessary.
155 if ((ret = getaddrinfo(addrstr, nullptr, &hints, &res)) != 0) {
156 return -EINVAL;
157 }
158
159 // So we don't have to call freeaddrinfo on every failure path.
160 ScopedAddrinfo resP(res);
161
162 void *addr;
163 uint8_t addrlen;
164 if (res->ai_family == AF_INET && family == AF_INET) {
165 in_addr& ina = reinterpret_cast<sockaddr_in*>(res->ai_addr)->sin_addr;
166 addr = &ina;
167 addrlen = sizeof(ina);
168 } else if (res->ai_family == AF_INET && family == AF_INET6) {
169 in_addr& ina = reinterpret_cast<sockaddr_in*>(res->ai_addr)->sin_addr;
170 mapped.s6_addr32[3] = ina.s_addr;
171 addr = &mapped;
172 addrlen = sizeof(mapped);
173 } else if (res->ai_family == AF_INET6 && family == AF_INET6) {
174 in6_addr& in6a = reinterpret_cast<sockaddr_in6*>(res->ai_addr)->sin6_addr;
175 addr = &in6a;
176 addrlen = sizeof(in6a);
177 } else {
178 return -EAFNOSUPPORT;
179 }
180
181 uint8_t prefixlen = addrlen * 8;
182 uint8_t yesjump = sizeof(inet_diag_bc_op) + sizeof(inet_diag_hostcond) + addrlen;
183 uint8_t nojump = yesjump + 4;
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +0900184
185 struct {
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +0900186 nlattr nla;
187 inet_diag_bc_op op;
188 inet_diag_hostcond cond;
Lorenzo Colitti94a7b432016-03-24 16:47:12 +0900189 } __attribute__((__packed__)) attrs = {
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +0900190 .nla = {
191 .nla_type = INET_DIAG_REQ_BYTECODE,
192 },
193 .op = {
194 INET_DIAG_BC_S_COND,
195 yesjump,
196 nojump,
197 },
198 .cond = {
199 family,
200 prefixlen,
201 -1,
202 {}
203 },
204 };
205
Lorenzo Colitti94a7b432016-03-24 16:47:12 +0900206 attrs.nla.nla_len = sizeof(attrs) + addrlen;
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +0900207
Lorenzo Colitti94a7b432016-03-24 16:47:12 +0900208 iovec iov[] = {
209 { nullptr, 0 },
210 { &attrs, sizeof(attrs) },
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +0900211 { addr, addrlen },
212 };
213
Lorenzo Colitti94a7b432016-03-24 16:47:12 +0900214 uint32_t states = ~(1 << TCP_TIME_WAIT);
215 return sendDumpRequest(proto, family, states, iov, ARRAY_SIZE(iov));
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +0900216}
217
218int SockDiag::readDiagMsg(uint8_t proto, SockDiag::DumpCallback callback) {
219 char buf[kBufferSize];
220
221 ssize_t bytesread;
222 do {
223 bytesread = read(mSock, buf, sizeof(buf));
224
225 if (bytesread < 0) {
226 return -errno;
227 }
228
229 uint32_t len = bytesread;
230 for (nlmsghdr *nlh = reinterpret_cast<nlmsghdr *>(buf);
231 NLMSG_OK(nlh, len);
232 nlh = NLMSG_NEXT(nlh, len)) {
233 switch (nlh->nlmsg_type) {
234 case NLMSG_DONE:
235 callback(proto, NULL);
236 return 0;
237 case NLMSG_ERROR: {
238 nlmsgerr *err = reinterpret_cast<nlmsgerr *>(NLMSG_DATA(nlh));
239 return err->error;
240 }
241 default:
242 inet_diag_msg *msg = reinterpret_cast<inet_diag_msg *>(NLMSG_DATA(nlh));
Lorenzo Colittifff4bd32016-04-14 00:56:01 +0900243 if (callback(proto, msg)) {
244 sockDestroy(proto, msg);
245 }
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +0900246 }
247 }
248 } while (bytesread > 0);
249
250 return 0;
251}
252
253int SockDiag::sockDestroy(uint8_t proto, const inet_diag_msg *msg) {
Lorenzo Colittif32fc592016-02-15 01:09:14 +0900254 if (msg == nullptr) {
255 return 0;
256 }
257
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +0900258 DestroyRequest request = {
259 .nlh = {
260 .nlmsg_type = SOCK_DESTROY,
261 .nlmsg_flags = NLM_F_REQUEST,
262 },
263 .req = {
264 .sdiag_family = msg->idiag_family,
265 .sdiag_protocol = proto,
266 .idiag_states = (uint32_t) (1 << msg->idiag_state),
267 .id = msg->id,
268 },
269 };
270 request.nlh.nlmsg_len = sizeof(request);
271
272 if (write(mWriteSock, &request, sizeof(request)) < (ssize_t) sizeof(request)) {
273 return -errno;
274 }
275
Lorenzo Colittif32fc592016-02-15 01:09:14 +0900276 int ret = checkError(mWriteSock);
277 if (!ret) mSocketsDestroyed++;
278 return ret;
279}
280
281int SockDiag::destroySockets(uint8_t proto, int family, const char *addrstr) {
282 if (!hasSocks()) {
283 return -EBADFD;
284 }
285
286 if (int ret = sendDumpRequest(proto, family, addrstr)) {
287 return ret;
288 }
289
Lorenzo Colittifff4bd32016-04-14 00:56:01 +0900290 auto destroyAll = [] (uint8_t, const inet_diag_msg*) { return true; };
Lorenzo Colittif32fc592016-02-15 01:09:14 +0900291
Lorenzo Colittifff4bd32016-04-14 00:56:01 +0900292 return readDiagMsg(proto, destroyAll);
Lorenzo Colittif32fc592016-02-15 01:09:14 +0900293}
294
295int SockDiag::destroySockets(const char *addrstr) {
Lorenzo Colitti94a7b432016-03-24 16:47:12 +0900296 Stopwatch s;
Lorenzo Colittif32fc592016-02-15 01:09:14 +0900297 mSocketsDestroyed = 0;
Lorenzo Colitti94a7b432016-03-24 16:47:12 +0900298
Lorenzo Colittif32fc592016-02-15 01:09:14 +0900299 if (!strchr(addrstr, ':')) {
300 if (int ret = destroySockets(IPPROTO_TCP, AF_INET, addrstr)) {
301 ALOGE("Failed to destroy IPv4 sockets on %s: %s", addrstr, strerror(-ret));
302 return ret;
303 }
304 }
305 if (int ret = destroySockets(IPPROTO_TCP, AF_INET6, addrstr)) {
306 ALOGE("Failed to destroy IPv6 sockets on %s: %s", addrstr, strerror(-ret));
307 return ret;
308 }
Lorenzo Colittif32fc592016-02-15 01:09:14 +0900309
310 if (mSocketsDestroyed > 0) {
Lorenzo Colitti94a7b432016-03-24 16:47:12 +0900311 ALOGI("Destroyed %d sockets on %s in %.1f ms", mSocketsDestroyed, addrstr, s.timeTaken());
Lorenzo Colittif32fc592016-02-15 01:09:14 +0900312 }
313
314 return mSocketsDestroyed;
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +0900315}
Lorenzo Colitti94a7b432016-03-24 16:47:12 +0900316
Lorenzo Colittifff4bd32016-04-14 00:56:01 +0900317int SockDiag::destroyLiveSockets(DumpCallback destroyFilter) {
318 int proto = IPPROTO_TCP;
319
320 for (const int family : {AF_INET, AF_INET6}) {
321 const char *familyName = (family == AF_INET) ? "IPv4" : "IPv6";
322 uint32_t states = (1 << TCP_ESTABLISHED) | (1 << TCP_SYN_SENT) | (1 << TCP_SYN_RECV);
323 if (int ret = sendDumpRequest(proto, family, states)) {
324 ALOGE("Failed to dump %s sockets for UID: %s", familyName, strerror(-ret));
325 return ret;
326 }
327 if (int ret = readDiagMsg(proto, destroyFilter)) {
328 ALOGE("Failed to destroy %s sockets for UID: %s", familyName, strerror(-ret));
329 return ret;
330 }
331 }
332
333 return 0;
334}
335
Lorenzo Colitti94a7b432016-03-24 16:47:12 +0900336int SockDiag::destroySockets(uint8_t proto, const uid_t uid) {
337 mSocketsDestroyed = 0;
338 Stopwatch s;
339
Lorenzo Colittifff4bd32016-04-14 00:56:01 +0900340 auto shouldDestroy = [uid] (uint8_t, const inet_diag_msg *msg) {
341 return (msg != nullptr && msg->idiag_uid == uid);
Lorenzo Colitti94a7b432016-03-24 16:47:12 +0900342 };
343
344 for (const int family : {AF_INET, AF_INET6}) {
345 const char *familyName = family == AF_INET ? "IPv4" : "IPv6";
346 uint32_t states = (1 << TCP_ESTABLISHED) | (1 << TCP_SYN_SENT) | (1 << TCP_SYN_RECV);
347 if (int ret = sendDumpRequest(proto, family, states)) {
348 ALOGE("Failed to dump %s sockets for UID: %s", familyName, strerror(-ret));
349 return ret;
350 }
Lorenzo Colittifff4bd32016-04-14 00:56:01 +0900351 if (int ret = readDiagMsg(proto, shouldDestroy)) {
Lorenzo Colitti94a7b432016-03-24 16:47:12 +0900352 ALOGE("Failed to destroy %s sockets for UID: %s", familyName, strerror(-ret));
353 return ret;
354 }
355 }
356
357 if (mSocketsDestroyed > 0) {
358 ALOGI("Destroyed %d sockets for UID in %.1f ms", mSocketsDestroyed, s.timeTaken());
359 }
360
361 return 0;
362}
Lorenzo Colittifff4bd32016-04-14 00:56:01 +0900363
364int SockDiag::destroySockets(const UidRanges& uidRanges, const std::set<uid_t>& skipUids) {
365 mSocketsDestroyed = 0;
366 Stopwatch s;
367
368 auto shouldDestroy = [&] (uint8_t, const inet_diag_msg *msg) {
369 return msg != nullptr &&
370 uidRanges.hasUid(msg->idiag_uid) &&
371 skipUids.find(msg->idiag_uid) == skipUids.end();
372 };
373
374 if (int ret = destroyLiveSockets(shouldDestroy)) {
375 return ret;
376 }
377
378 std::vector<uid_t> skipUidStrings;
379 for (uid_t uid : skipUids) {
380 skipUidStrings.push_back(uid);
381 }
382 std::sort(skipUidStrings.begin(), skipUidStrings.end());
383
384 if (mSocketsDestroyed > 0) {
385 ALOGI("Destroyed %d sockets for %s skip={%s} in %.1f ms",
386 mSocketsDestroyed, uidRanges.toString().c_str(),
387 android::base::Join(skipUidStrings, " ").c_str(), s.timeTaken());
388 }
389
390 return 0;
391}