blob: c6a0a920317087f8bfbe2443c11f87b21690265e [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
Lorenzo Colittifbe76b92016-09-14 02:25:05 +090034#include "Fwmark.h"
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +090035#include "NetdConstants.h"
Lorenzo Colittifbe76b92016-09-14 02:25:05 +090036#include "Permission.h"
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +090037#include "SockDiag.h"
Robin Lee7e05cc92016-09-21 16:31:33 +090038#include "Stopwatch.h"
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +090039
Lorenzo Colittif32fc592016-02-15 01:09:14 +090040#include <chrono>
41
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +090042#ifndef SOCK_DESTROY
43#define SOCK_DESTROY 21
44#endif
45
Lorenzo Colittifbe76b92016-09-14 02:25:05 +090046#define INET_DIAG_BC_MARK_COND 10
47
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +090048namespace {
49
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +090050int checkError(int fd) {
51 struct {
52 nlmsghdr h;
53 nlmsgerr err;
54 } __attribute__((__packed__)) ack;
55 ssize_t bytesread = recv(fd, &ack, sizeof(ack), MSG_DONTWAIT | MSG_PEEK);
56 if (bytesread == -1) {
57 // Read failed (error), or nothing to read (good).
58 return (errno == EAGAIN) ? 0 : -errno;
59 } else if (bytesread == (ssize_t) sizeof(ack) && ack.h.nlmsg_type == NLMSG_ERROR) {
60 // We got an error. Consume it.
61 recv(fd, &ack, sizeof(ack), 0);
62 return ack.err.error;
63 } else {
64 // The kernel replied with something. Leave it to the caller.
65 return 0;
66 }
67}
68
69} // namespace
70
71bool SockDiag::open() {
72 if (hasSocks()) {
73 return false;
74 }
75
Nick Kralevichaf02b552016-12-20 08:40:35 -080076 mSock = socket(PF_NETLINK, SOCK_DGRAM | SOCK_CLOEXEC, NETLINK_INET_DIAG);
77 mWriteSock = socket(PF_NETLINK, SOCK_DGRAM | SOCK_CLOEXEC, NETLINK_INET_DIAG);
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +090078 if (!hasSocks()) {
79 closeSocks();
80 return false;
81 }
82
83 sockaddr_nl nl = { .nl_family = AF_NETLINK };
84 if ((connect(mSock, reinterpret_cast<sockaddr *>(&nl), sizeof(nl)) == -1) ||
85 (connect(mWriteSock, reinterpret_cast<sockaddr *>(&nl), sizeof(nl)) == -1)) {
86 closeSocks();
87 return false;
88 }
89
90 return true;
91}
92
Lorenzo Colitti94a7b432016-03-24 16:47:12 +090093int SockDiag::sendDumpRequest(uint8_t proto, uint8_t family, uint32_t states,
94 iovec *iov, int iovcnt) {
95 struct {
96 nlmsghdr nlh;
97 inet_diag_req_v2 req;
98 } __attribute__((__packed__)) request = {
99 .nlh = {
100 .nlmsg_type = SOCK_DIAG_BY_FAMILY,
101 .nlmsg_flags = NLM_F_REQUEST | NLM_F_DUMP,
102 },
103 .req = {
104 .sdiag_family = family,
105 .sdiag_protocol = proto,
106 .idiag_states = states,
107 },
108 };
109
110 size_t len = 0;
111 iov[0].iov_base = &request;
112 iov[0].iov_len = sizeof(request);
113 for (int i = 0; i < iovcnt; i++) {
114 len += iov[i].iov_len;
115 }
116 request.nlh.nlmsg_len = len;
117
118 if (writev(mSock, iov, iovcnt) != (ssize_t) len) {
119 return -errno;
120 }
121
122 return checkError(mSock);
123}
124
125int SockDiag::sendDumpRequest(uint8_t proto, uint8_t family, uint32_t states) {
126 iovec iov[] = {
127 { nullptr, 0 },
128 };
129 return sendDumpRequest(proto, family, states, iov, ARRAY_SIZE(iov));
130}
131
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +0900132int SockDiag::sendDumpRequest(uint8_t proto, uint8_t family, const char *addrstr) {
133 addrinfo hints = { .ai_flags = AI_NUMERICHOST };
134 addrinfo *res;
135 in6_addr mapped = { .s6_addr32 = { 0, 0, htonl(0xffff), 0 } };
136 int ret;
137
138 // TODO: refactor the netlink parsing code out of system/core, bring it into netd, and stop
139 // doing string conversions when they're not necessary.
140 if ((ret = getaddrinfo(addrstr, nullptr, &hints, &res)) != 0) {
141 return -EINVAL;
142 }
143
144 // So we don't have to call freeaddrinfo on every failure path.
145 ScopedAddrinfo resP(res);
146
147 void *addr;
148 uint8_t addrlen;
149 if (res->ai_family == AF_INET && family == AF_INET) {
150 in_addr& ina = reinterpret_cast<sockaddr_in*>(res->ai_addr)->sin_addr;
151 addr = &ina;
152 addrlen = sizeof(ina);
153 } else if (res->ai_family == AF_INET && family == AF_INET6) {
154 in_addr& ina = reinterpret_cast<sockaddr_in*>(res->ai_addr)->sin_addr;
155 mapped.s6_addr32[3] = ina.s_addr;
156 addr = &mapped;
157 addrlen = sizeof(mapped);
158 } else if (res->ai_family == AF_INET6 && family == AF_INET6) {
159 in6_addr& in6a = reinterpret_cast<sockaddr_in6*>(res->ai_addr)->sin6_addr;
160 addr = &in6a;
161 addrlen = sizeof(in6a);
162 } else {
163 return -EAFNOSUPPORT;
164 }
165
166 uint8_t prefixlen = addrlen * 8;
167 uint8_t yesjump = sizeof(inet_diag_bc_op) + sizeof(inet_diag_hostcond) + addrlen;
168 uint8_t nojump = yesjump + 4;
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +0900169
170 struct {
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +0900171 nlattr nla;
172 inet_diag_bc_op op;
173 inet_diag_hostcond cond;
Lorenzo Colitti94a7b432016-03-24 16:47:12 +0900174 } __attribute__((__packed__)) attrs = {
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +0900175 .nla = {
176 .nla_type = INET_DIAG_REQ_BYTECODE,
177 },
178 .op = {
179 INET_DIAG_BC_S_COND,
180 yesjump,
181 nojump,
182 },
183 .cond = {
184 family,
185 prefixlen,
186 -1,
187 {}
188 },
189 };
190
Lorenzo Colitti94a7b432016-03-24 16:47:12 +0900191 attrs.nla.nla_len = sizeof(attrs) + addrlen;
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +0900192
Lorenzo Colitti94a7b432016-03-24 16:47:12 +0900193 iovec iov[] = {
Lorenzo Colittifbe76b92016-09-14 02:25:05 +0900194 { nullptr, 0 },
195 { &attrs, sizeof(attrs) },
196 { addr, addrlen },
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +0900197 };
198
Lorenzo Colitti94a7b432016-03-24 16:47:12 +0900199 uint32_t states = ~(1 << TCP_TIME_WAIT);
200 return sendDumpRequest(proto, family, states, iov, ARRAY_SIZE(iov));
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +0900201}
202
Chih-Hung Hsiehb22e4d22016-07-28 14:13:11 -0700203int SockDiag::readDiagMsg(uint8_t proto, const SockDiag::DumpCallback& callback) {
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +0900204 char buf[kBufferSize];
205
206 ssize_t bytesread;
207 do {
208 bytesread = read(mSock, buf, sizeof(buf));
209
210 if (bytesread < 0) {
211 return -errno;
212 }
213
214 uint32_t len = bytesread;
215 for (nlmsghdr *nlh = reinterpret_cast<nlmsghdr *>(buf);
216 NLMSG_OK(nlh, len);
217 nlh = NLMSG_NEXT(nlh, len)) {
218 switch (nlh->nlmsg_type) {
219 case NLMSG_DONE:
220 callback(proto, NULL);
221 return 0;
222 case NLMSG_ERROR: {
223 nlmsgerr *err = reinterpret_cast<nlmsgerr *>(NLMSG_DATA(nlh));
224 return err->error;
225 }
226 default:
227 inet_diag_msg *msg = reinterpret_cast<inet_diag_msg *>(NLMSG_DATA(nlh));
Lorenzo Colittifff4bd32016-04-14 00:56:01 +0900228 if (callback(proto, msg)) {
229 sockDestroy(proto, msg);
230 }
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +0900231 }
232 }
233 } while (bytesread > 0);
234
235 return 0;
236}
237
Lorenzo Colittie5c3c992016-07-26 17:53:50 +0900238// Determines whether a socket is a loopback socket. Does not check socket state.
239bool SockDiag::isLoopbackSocket(const inet_diag_msg *msg) {
240 switch (msg->idiag_family) {
241 case AF_INET:
242 // Old kernels only copy the IPv4 address and leave the other 12 bytes uninitialized.
243 return IN_LOOPBACK(htonl(msg->id.idiag_src[0])) ||
244 IN_LOOPBACK(htonl(msg->id.idiag_dst[0])) ||
245 msg->id.idiag_src[0] == msg->id.idiag_dst[0];
246
247 case AF_INET6: {
248 const struct in6_addr *src = (const struct in6_addr *) &msg->id.idiag_src;
249 const struct in6_addr *dst = (const struct in6_addr *) &msg->id.idiag_dst;
250 return (IN6_IS_ADDR_V4MAPPED(src) && IN_LOOPBACK(src->s6_addr32[3])) ||
251 (IN6_IS_ADDR_V4MAPPED(dst) && IN_LOOPBACK(dst->s6_addr32[3])) ||
252 IN6_IS_ADDR_LOOPBACK(src) || IN6_IS_ADDR_LOOPBACK(dst) ||
253 !memcmp(src, dst, sizeof(*src));
254 }
255 default:
256 return false;
257 }
258}
259
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +0900260int SockDiag::sockDestroy(uint8_t proto, const inet_diag_msg *msg) {
Lorenzo Colittif32fc592016-02-15 01:09:14 +0900261 if (msg == nullptr) {
262 return 0;
263 }
264
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +0900265 DestroyRequest request = {
266 .nlh = {
267 .nlmsg_type = SOCK_DESTROY,
268 .nlmsg_flags = NLM_F_REQUEST,
269 },
270 .req = {
271 .sdiag_family = msg->idiag_family,
272 .sdiag_protocol = proto,
273 .idiag_states = (uint32_t) (1 << msg->idiag_state),
274 .id = msg->id,
275 },
276 };
277 request.nlh.nlmsg_len = sizeof(request);
278
279 if (write(mWriteSock, &request, sizeof(request)) < (ssize_t) sizeof(request)) {
280 return -errno;
281 }
282
Lorenzo Colittif32fc592016-02-15 01:09:14 +0900283 int ret = checkError(mWriteSock);
284 if (!ret) mSocketsDestroyed++;
285 return ret;
286}
287
288int SockDiag::destroySockets(uint8_t proto, int family, const char *addrstr) {
289 if (!hasSocks()) {
290 return -EBADFD;
291 }
292
293 if (int ret = sendDumpRequest(proto, family, addrstr)) {
294 return ret;
295 }
296
Lorenzo Colittifff4bd32016-04-14 00:56:01 +0900297 auto destroyAll = [] (uint8_t, const inet_diag_msg*) { return true; };
Lorenzo Colittif32fc592016-02-15 01:09:14 +0900298
Lorenzo Colittifff4bd32016-04-14 00:56:01 +0900299 return readDiagMsg(proto, destroyAll);
Lorenzo Colittif32fc592016-02-15 01:09:14 +0900300}
301
302int SockDiag::destroySockets(const char *addrstr) {
Lorenzo Colitti94a7b432016-03-24 16:47:12 +0900303 Stopwatch s;
Lorenzo Colittif32fc592016-02-15 01:09:14 +0900304 mSocketsDestroyed = 0;
Lorenzo Colitti94a7b432016-03-24 16:47:12 +0900305
Lorenzo Colittif32fc592016-02-15 01:09:14 +0900306 if (!strchr(addrstr, ':')) {
307 if (int ret = destroySockets(IPPROTO_TCP, AF_INET, addrstr)) {
308 ALOGE("Failed to destroy IPv4 sockets on %s: %s", addrstr, strerror(-ret));
309 return ret;
310 }
311 }
312 if (int ret = destroySockets(IPPROTO_TCP, AF_INET6, addrstr)) {
313 ALOGE("Failed to destroy IPv6 sockets on %s: %s", addrstr, strerror(-ret));
314 return ret;
315 }
Lorenzo Colittif32fc592016-02-15 01:09:14 +0900316
317 if (mSocketsDestroyed > 0) {
Lorenzo Colitti94a7b432016-03-24 16:47:12 +0900318 ALOGI("Destroyed %d sockets on %s in %.1f ms", mSocketsDestroyed, addrstr, s.timeTaken());
Lorenzo Colittif32fc592016-02-15 01:09:14 +0900319 }
320
321 return mSocketsDestroyed;
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +0900322}
Lorenzo Colitti94a7b432016-03-24 16:47:12 +0900323
Lorenzo Colittifbe76b92016-09-14 02:25:05 +0900324int SockDiag::destroyLiveSockets(DumpCallback destroyFilter, const char *what,
325 iovec *iov, int iovcnt) {
Lorenzo Colittifff4bd32016-04-14 00:56:01 +0900326 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);
Lorenzo Colittifbe76b92016-09-14 02:25:05 +0900331 if (int ret = sendDumpRequest(proto, family, states, iov, iovcnt)) {
332 ALOGE("Failed to dump %s sockets for %s: %s", familyName, what, strerror(-ret));
Lorenzo Colittifff4bd32016-04-14 00:56:01 +0900333 return ret;
334 }
335 if (int ret = readDiagMsg(proto, destroyFilter)) {
Lorenzo Colittifbe76b92016-09-14 02:25:05 +0900336 ALOGE("Failed to destroy %s sockets for %s: %s", familyName, what, strerror(-ret));
Lorenzo Colittifff4bd32016-04-14 00:56:01 +0900337 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
Lorenzo Colittifbe76b92016-09-14 02:25:05 +0900386 iovec iov[] = {
387 { nullptr, 0 },
388 };
389
390 if (int ret = destroyLiveSockets(shouldDestroy, "UID", iov, ARRAY_SIZE(iov))) {
Lorenzo Colittifff4bd32016-04-14 00:56:01 +0900391 return ret;
392 }
393
394 std::vector<uid_t> skipUidStrings;
395 for (uid_t uid : skipUids) {
396 skipUidStrings.push_back(uid);
397 }
398 std::sort(skipUidStrings.begin(), skipUidStrings.end());
399
400 if (mSocketsDestroyed > 0) {
401 ALOGI("Destroyed %d sockets for %s skip={%s} in %.1f ms",
402 mSocketsDestroyed, uidRanges.toString().c_str(),
403 android::base::Join(skipUidStrings, " ").c_str(), s.timeTaken());
404 }
405
406 return 0;
407}
Lorenzo Colittifbe76b92016-09-14 02:25:05 +0900408
409// Destroys all "live" (CONNECTED, SYN_SENT, SYN_RECV) TCP sockets on the specified netId where:
410// 1. The opening app no longer has permission to use this network, or:
411// 2. The opening app does have permission, but did not explicitly select this network.
412//
413// We destroy sockets without the explicit bit because we want to avoid the situation where a
414// privileged app uses its privileges without knowing it is doing so. For example, a privileged app
415// might have opened a socket on this network just because it was the default network at the
416// time. If we don't kill these sockets, those apps could continue to use them without realizing
417// that they are now sending and receiving traffic on a network that is now restricted.
418int SockDiag::destroySocketsLackingPermission(unsigned netId, Permission permission,
419 bool excludeLoopback) {
420 struct markmatch {
421 inet_diag_bc_op op;
422 // TODO: switch to inet_diag_markcond
423 __u32 mark;
424 __u32 mask;
425 } __attribute__((packed));
426 constexpr uint8_t matchlen = sizeof(markmatch);
427
428 Fwmark netIdMark, netIdMask;
429 netIdMark.netId = netId;
430 netIdMask.netId = 0xffff;
431
432 Fwmark controlMark;
433 controlMark.explicitlySelected = true;
434 controlMark.permission = permission;
435
436 // A SOCK_DIAG bytecode program that accepts the sockets we intend to destroy.
437 struct bytecode {
438 markmatch netIdMatch;
439 markmatch controlMatch;
440 inet_diag_bc_op controlJump;
441 } __attribute__((packed)) bytecode;
442
443 // The length of the INET_DIAG_BC_JMP instruction.
444 constexpr uint8_t jmplen = sizeof(inet_diag_bc_op);
445 // Jump exactly this far past the end of the program to reject.
446 constexpr uint8_t rejectoffset = sizeof(inet_diag_bc_op);
447 // Total length of the program.
448 constexpr uint8_t bytecodelen = sizeof(bytecode);
449
450 bytecode = (struct bytecode) {
451 // If netId matches, continue, otherwise, reject (i.e., leave socket alone).
452 { { INET_DIAG_BC_MARK_COND, matchlen, bytecodelen + rejectoffset },
453 netIdMark.intValue, netIdMask.intValue },
454
455 // If explicit and permission bits match, go to the JMP below which rejects the socket
456 // (i.e., we leave it alone). Otherwise, jump to the end of the program, which accepts the
457 // socket (so we destroy it).
458 { { INET_DIAG_BC_MARK_COND, matchlen, matchlen + jmplen },
459 controlMark.intValue, controlMark.intValue },
460
461 // This JMP unconditionally rejects the packet by jumping to the reject target. It is
462 // necessary to keep the kernel bytecode verifier happy. If we don't have a JMP the bytecode
463 // is invalid because the target of every no jump must always be reachable by yes jumps.
464 // Without this JMP, the accept target is not reachable by yes jumps and the program will
465 // be rejected by the validator.
466 { INET_DIAG_BC_JMP, jmplen, jmplen + rejectoffset },
467
468 // We have reached the end of the program. Accept the socket, and destroy it below.
469 };
470
471 struct nlattr nla = {
472 .nla_type = INET_DIAG_REQ_BYTECODE,
473 .nla_len = sizeof(struct nlattr) + bytecodelen,
474 };
475
476 iovec iov[] = {
477 { nullptr, 0 },
478 { &nla, sizeof(nla) },
479 { &bytecode, bytecodelen },
480 };
481
482 mSocketsDestroyed = 0;
483 Stopwatch s;
484
485 auto shouldDestroy = [&] (uint8_t, const inet_diag_msg *msg) {
486 return msg != nullptr && !(excludeLoopback && isLoopbackSocket(msg));
487 };
488
489 if (int ret = destroyLiveSockets(shouldDestroy, "permission change", iov, ARRAY_SIZE(iov))) {
490 return ret;
491 }
492
493 if (mSocketsDestroyed > 0) {
494 ALOGI("Destroyed %d sockets for netId %d permission=%d in %.1f ms",
495 mSocketsDestroyed, netId, permission, s.timeTaken());
496 }
497
498 return 0;
499}