blob: 423ad3bb79f30338a094a48dcd9747e1782e7045 [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 Colitti7035f222017-02-13 18:29:00 +090048namespace android {
49namespace net {
50
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +090051namespace {
52
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +090053int checkError(int fd) {
54 struct {
55 nlmsghdr h;
56 nlmsgerr err;
57 } __attribute__((__packed__)) ack;
58 ssize_t bytesread = recv(fd, &ack, sizeof(ack), MSG_DONTWAIT | MSG_PEEK);
59 if (bytesread == -1) {
60 // Read failed (error), or nothing to read (good).
61 return (errno == EAGAIN) ? 0 : -errno;
62 } else if (bytesread == (ssize_t) sizeof(ack) && ack.h.nlmsg_type == NLMSG_ERROR) {
63 // We got an error. Consume it.
64 recv(fd, &ack, sizeof(ack), 0);
65 return ack.err.error;
66 } else {
67 // The kernel replied with something. Leave it to the caller.
68 return 0;
69 }
70}
71
72} // namespace
73
74bool SockDiag::open() {
75 if (hasSocks()) {
76 return false;
77 }
78
Nick Kralevichaf02b552016-12-20 08:40:35 -080079 mSock = socket(PF_NETLINK, SOCK_DGRAM | SOCK_CLOEXEC, NETLINK_INET_DIAG);
80 mWriteSock = socket(PF_NETLINK, SOCK_DGRAM | SOCK_CLOEXEC, NETLINK_INET_DIAG);
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +090081 if (!hasSocks()) {
82 closeSocks();
83 return false;
84 }
85
86 sockaddr_nl nl = { .nl_family = AF_NETLINK };
87 if ((connect(mSock, reinterpret_cast<sockaddr *>(&nl), sizeof(nl)) == -1) ||
88 (connect(mWriteSock, reinterpret_cast<sockaddr *>(&nl), sizeof(nl)) == -1)) {
89 closeSocks();
90 return false;
91 }
92
93 return true;
94}
95
Lorenzo Colitti94a7b432016-03-24 16:47:12 +090096int SockDiag::sendDumpRequest(uint8_t proto, uint8_t family, uint32_t states,
97 iovec *iov, int iovcnt) {
98 struct {
99 nlmsghdr nlh;
100 inet_diag_req_v2 req;
101 } __attribute__((__packed__)) request = {
102 .nlh = {
103 .nlmsg_type = SOCK_DIAG_BY_FAMILY,
104 .nlmsg_flags = NLM_F_REQUEST | NLM_F_DUMP,
105 },
106 .req = {
107 .sdiag_family = family,
108 .sdiag_protocol = proto,
109 .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 };
132 return sendDumpRequest(proto, family, states, iov, ARRAY_SIZE(iov));
133}
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);
203 return sendDumpRequest(proto, family, states, iov, ARRAY_SIZE(iov));
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +0900204}
205
Chih-Hung Hsiehb22e4d22016-07-28 14:13:11 -0700206int SockDiag::readDiagMsg(uint8_t proto, const SockDiag::DumpCallback& callback) {
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +0900207 char buf[kBufferSize];
208
209 ssize_t bytesread;
210 do {
211 bytesread = read(mSock, buf, sizeof(buf));
212
213 if (bytesread < 0) {
214 return -errno;
215 }
216
217 uint32_t len = bytesread;
218 for (nlmsghdr *nlh = reinterpret_cast<nlmsghdr *>(buf);
219 NLMSG_OK(nlh, len);
220 nlh = NLMSG_NEXT(nlh, len)) {
221 switch (nlh->nlmsg_type) {
222 case NLMSG_DONE:
223 callback(proto, NULL);
224 return 0;
225 case NLMSG_ERROR: {
226 nlmsgerr *err = reinterpret_cast<nlmsgerr *>(NLMSG_DATA(nlh));
227 return err->error;
228 }
229 default:
230 inet_diag_msg *msg = reinterpret_cast<inet_diag_msg *>(NLMSG_DATA(nlh));
Lorenzo Colittifff4bd32016-04-14 00:56:01 +0900231 if (callback(proto, msg)) {
232 sockDestroy(proto, msg);
233 }
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +0900234 }
235 }
236 } while (bytesread > 0);
237
238 return 0;
239}
240
Lorenzo Colittie5c3c992016-07-26 17:53:50 +0900241// Determines whether a socket is a loopback socket. Does not check socket state.
242bool SockDiag::isLoopbackSocket(const inet_diag_msg *msg) {
243 switch (msg->idiag_family) {
244 case AF_INET:
245 // Old kernels only copy the IPv4 address and leave the other 12 bytes uninitialized.
246 return IN_LOOPBACK(htonl(msg->id.idiag_src[0])) ||
247 IN_LOOPBACK(htonl(msg->id.idiag_dst[0])) ||
248 msg->id.idiag_src[0] == msg->id.idiag_dst[0];
249
250 case AF_INET6: {
251 const struct in6_addr *src = (const struct in6_addr *) &msg->id.idiag_src;
252 const struct in6_addr *dst = (const struct in6_addr *) &msg->id.idiag_dst;
253 return (IN6_IS_ADDR_V4MAPPED(src) && IN_LOOPBACK(src->s6_addr32[3])) ||
254 (IN6_IS_ADDR_V4MAPPED(dst) && IN_LOOPBACK(dst->s6_addr32[3])) ||
255 IN6_IS_ADDR_LOOPBACK(src) || IN6_IS_ADDR_LOOPBACK(dst) ||
256 !memcmp(src, dst, sizeof(*src));
257 }
258 default:
259 return false;
260 }
261}
262
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +0900263int SockDiag::sockDestroy(uint8_t proto, const inet_diag_msg *msg) {
Lorenzo Colittif32fc592016-02-15 01:09:14 +0900264 if (msg == nullptr) {
265 return 0;
266 }
267
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +0900268 DestroyRequest request = {
269 .nlh = {
270 .nlmsg_type = SOCK_DESTROY,
271 .nlmsg_flags = NLM_F_REQUEST,
272 },
273 .req = {
274 .sdiag_family = msg->idiag_family,
275 .sdiag_protocol = proto,
276 .idiag_states = (uint32_t) (1 << msg->idiag_state),
277 .id = msg->id,
278 },
279 };
280 request.nlh.nlmsg_len = sizeof(request);
281
282 if (write(mWriteSock, &request, sizeof(request)) < (ssize_t) sizeof(request)) {
283 return -errno;
284 }
285
Lorenzo Colittif32fc592016-02-15 01:09:14 +0900286 int ret = checkError(mWriteSock);
287 if (!ret) mSocketsDestroyed++;
288 return ret;
289}
290
291int SockDiag::destroySockets(uint8_t proto, int family, const char *addrstr) {
292 if (!hasSocks()) {
293 return -EBADFD;
294 }
295
296 if (int ret = sendDumpRequest(proto, family, addrstr)) {
297 return ret;
298 }
299
Lorenzo Colittifff4bd32016-04-14 00:56:01 +0900300 auto destroyAll = [] (uint8_t, const inet_diag_msg*) { return true; };
Lorenzo Colittif32fc592016-02-15 01:09:14 +0900301
Lorenzo Colittifff4bd32016-04-14 00:56:01 +0900302 return readDiagMsg(proto, destroyAll);
Lorenzo Colittif32fc592016-02-15 01:09:14 +0900303}
304
305int SockDiag::destroySockets(const char *addrstr) {
Lorenzo Colitti94a7b432016-03-24 16:47:12 +0900306 Stopwatch s;
Lorenzo Colittif32fc592016-02-15 01:09:14 +0900307 mSocketsDestroyed = 0;
Lorenzo Colitti94a7b432016-03-24 16:47:12 +0900308
Lorenzo Colittif32fc592016-02-15 01:09:14 +0900309 if (!strchr(addrstr, ':')) {
310 if (int ret = destroySockets(IPPROTO_TCP, AF_INET, addrstr)) {
311 ALOGE("Failed to destroy IPv4 sockets on %s: %s", addrstr, strerror(-ret));
312 return ret;
313 }
314 }
315 if (int ret = destroySockets(IPPROTO_TCP, AF_INET6, addrstr)) {
316 ALOGE("Failed to destroy IPv6 sockets on %s: %s", addrstr, strerror(-ret));
317 return ret;
318 }
Lorenzo Colittif32fc592016-02-15 01:09:14 +0900319
320 if (mSocketsDestroyed > 0) {
Lorenzo Colitti94a7b432016-03-24 16:47:12 +0900321 ALOGI("Destroyed %d sockets on %s in %.1f ms", mSocketsDestroyed, addrstr, s.timeTaken());
Lorenzo Colittif32fc592016-02-15 01:09:14 +0900322 }
323
324 return mSocketsDestroyed;
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +0900325}
Lorenzo Colitti94a7b432016-03-24 16:47:12 +0900326
Lorenzo Colittifbe76b92016-09-14 02:25:05 +0900327int SockDiag::destroyLiveSockets(DumpCallback destroyFilter, const char *what,
328 iovec *iov, int iovcnt) {
Lorenzo Colittifff4bd32016-04-14 00:56:01 +0900329 int proto = IPPROTO_TCP;
330
331 for (const int family : {AF_INET, AF_INET6}) {
332 const char *familyName = (family == AF_INET) ? "IPv4" : "IPv6";
333 uint32_t states = (1 << TCP_ESTABLISHED) | (1 << TCP_SYN_SENT) | (1 << TCP_SYN_RECV);
Lorenzo Colittifbe76b92016-09-14 02:25:05 +0900334 if (int ret = sendDumpRequest(proto, family, states, iov, iovcnt)) {
335 ALOGE("Failed to dump %s sockets for %s: %s", familyName, what, strerror(-ret));
Lorenzo Colittifff4bd32016-04-14 00:56:01 +0900336 return ret;
337 }
338 if (int ret = readDiagMsg(proto, destroyFilter)) {
Lorenzo Colittifbe76b92016-09-14 02:25:05 +0900339 ALOGE("Failed to destroy %s sockets for %s: %s", familyName, what, strerror(-ret));
Lorenzo Colittifff4bd32016-04-14 00:56:01 +0900340 return ret;
341 }
342 }
343
344 return 0;
345}
346
Lorenzo Colittie5c3c992016-07-26 17:53:50 +0900347int SockDiag::destroySockets(uint8_t proto, const uid_t uid, bool excludeLoopback) {
Lorenzo Colitti94a7b432016-03-24 16:47:12 +0900348 mSocketsDestroyed = 0;
349 Stopwatch s;
350
Lorenzo Colittie5c3c992016-07-26 17:53:50 +0900351 auto shouldDestroy = [uid, excludeLoopback] (uint8_t, const inet_diag_msg *msg) {
352 return msg != nullptr &&
353 msg->idiag_uid == uid &&
354 !(excludeLoopback && isLoopbackSocket(msg));
Lorenzo Colitti94a7b432016-03-24 16:47:12 +0900355 };
356
357 for (const int family : {AF_INET, AF_INET6}) {
358 const char *familyName = family == AF_INET ? "IPv4" : "IPv6";
359 uint32_t states = (1 << TCP_ESTABLISHED) | (1 << TCP_SYN_SENT) | (1 << TCP_SYN_RECV);
360 if (int ret = sendDumpRequest(proto, family, states)) {
361 ALOGE("Failed to dump %s sockets for UID: %s", familyName, strerror(-ret));
362 return ret;
363 }
Lorenzo Colittifff4bd32016-04-14 00:56:01 +0900364 if (int ret = readDiagMsg(proto, shouldDestroy)) {
Lorenzo Colitti94a7b432016-03-24 16:47:12 +0900365 ALOGE("Failed to destroy %s sockets for UID: %s", familyName, strerror(-ret));
366 return ret;
367 }
368 }
369
370 if (mSocketsDestroyed > 0) {
371 ALOGI("Destroyed %d sockets for UID in %.1f ms", mSocketsDestroyed, s.timeTaken());
372 }
373
374 return 0;
375}
Lorenzo Colittifff4bd32016-04-14 00:56:01 +0900376
Lorenzo Colittie5c3c992016-07-26 17:53:50 +0900377int SockDiag::destroySockets(const UidRanges& uidRanges, const std::set<uid_t>& skipUids,
378 bool excludeLoopback) {
Lorenzo Colittifff4bd32016-04-14 00:56:01 +0900379 mSocketsDestroyed = 0;
380 Stopwatch s;
381
382 auto shouldDestroy = [&] (uint8_t, const inet_diag_msg *msg) {
383 return msg != nullptr &&
384 uidRanges.hasUid(msg->idiag_uid) &&
Lorenzo Colittie5c3c992016-07-26 17:53:50 +0900385 skipUids.find(msg->idiag_uid) == skipUids.end() &&
386 !(excludeLoopback && isLoopbackSocket(msg));
Lorenzo Colittifff4bd32016-04-14 00:56:01 +0900387 };
388
Lorenzo Colittifbe76b92016-09-14 02:25:05 +0900389 iovec iov[] = {
390 { nullptr, 0 },
391 };
392
393 if (int ret = destroyLiveSockets(shouldDestroy, "UID", iov, ARRAY_SIZE(iov))) {
Lorenzo Colittifff4bd32016-04-14 00:56:01 +0900394 return ret;
395 }
396
397 std::vector<uid_t> skipUidStrings;
398 for (uid_t uid : skipUids) {
399 skipUidStrings.push_back(uid);
400 }
401 std::sort(skipUidStrings.begin(), skipUidStrings.end());
402
403 if (mSocketsDestroyed > 0) {
404 ALOGI("Destroyed %d sockets for %s skip={%s} in %.1f ms",
405 mSocketsDestroyed, uidRanges.toString().c_str(),
406 android::base::Join(skipUidStrings, " ").c_str(), s.timeTaken());
407 }
408
409 return 0;
410}
Lorenzo Colittifbe76b92016-09-14 02:25:05 +0900411
412// Destroys all "live" (CONNECTED, SYN_SENT, SYN_RECV) TCP sockets on the specified netId where:
413// 1. The opening app no longer has permission to use this network, or:
414// 2. The opening app does have permission, but did not explicitly select this network.
415//
416// We destroy sockets without the explicit bit because we want to avoid the situation where a
417// privileged app uses its privileges without knowing it is doing so. For example, a privileged app
418// might have opened a socket on this network just because it was the default network at the
419// time. If we don't kill these sockets, those apps could continue to use them without realizing
420// that they are now sending and receiving traffic on a network that is now restricted.
421int SockDiag::destroySocketsLackingPermission(unsigned netId, Permission permission,
422 bool excludeLoopback) {
423 struct markmatch {
424 inet_diag_bc_op op;
425 // TODO: switch to inet_diag_markcond
426 __u32 mark;
427 __u32 mask;
428 } __attribute__((packed));
429 constexpr uint8_t matchlen = sizeof(markmatch);
430
431 Fwmark netIdMark, netIdMask;
432 netIdMark.netId = netId;
433 netIdMask.netId = 0xffff;
434
435 Fwmark controlMark;
436 controlMark.explicitlySelected = true;
437 controlMark.permission = permission;
438
439 // A SOCK_DIAG bytecode program that accepts the sockets we intend to destroy.
440 struct bytecode {
441 markmatch netIdMatch;
442 markmatch controlMatch;
443 inet_diag_bc_op controlJump;
444 } __attribute__((packed)) bytecode;
445
446 // The length of the INET_DIAG_BC_JMP instruction.
447 constexpr uint8_t jmplen = sizeof(inet_diag_bc_op);
448 // Jump exactly this far past the end of the program to reject.
449 constexpr uint8_t rejectoffset = sizeof(inet_diag_bc_op);
450 // Total length of the program.
451 constexpr uint8_t bytecodelen = sizeof(bytecode);
452
453 bytecode = (struct bytecode) {
454 // If netId matches, continue, otherwise, reject (i.e., leave socket alone).
455 { { INET_DIAG_BC_MARK_COND, matchlen, bytecodelen + rejectoffset },
456 netIdMark.intValue, netIdMask.intValue },
457
458 // If explicit and permission bits match, go to the JMP below which rejects the socket
459 // (i.e., we leave it alone). Otherwise, jump to the end of the program, which accepts the
460 // socket (so we destroy it).
461 { { INET_DIAG_BC_MARK_COND, matchlen, matchlen + jmplen },
462 controlMark.intValue, controlMark.intValue },
463
464 // This JMP unconditionally rejects the packet by jumping to the reject target. It is
465 // necessary to keep the kernel bytecode verifier happy. If we don't have a JMP the bytecode
466 // is invalid because the target of every no jump must always be reachable by yes jumps.
467 // Without this JMP, the accept target is not reachable by yes jumps and the program will
468 // be rejected by the validator.
469 { INET_DIAG_BC_JMP, jmplen, jmplen + rejectoffset },
470
471 // We have reached the end of the program. Accept the socket, and destroy it below.
472 };
473
474 struct nlattr nla = {
475 .nla_type = INET_DIAG_REQ_BYTECODE,
476 .nla_len = sizeof(struct nlattr) + bytecodelen,
477 };
478
479 iovec iov[] = {
480 { nullptr, 0 },
481 { &nla, sizeof(nla) },
482 { &bytecode, bytecodelen },
483 };
484
485 mSocketsDestroyed = 0;
486 Stopwatch s;
487
488 auto shouldDestroy = [&] (uint8_t, const inet_diag_msg *msg) {
489 return msg != nullptr && !(excludeLoopback && isLoopbackSocket(msg));
490 };
491
492 if (int ret = destroyLiveSockets(shouldDestroy, "permission change", iov, ARRAY_SIZE(iov))) {
493 return ret;
494 }
495
496 if (mSocketsDestroyed > 0) {
497 ALOGI("Destroyed %d sockets for netId %d permission=%d in %.1f ms",
498 mSocketsDestroyed, netId, permission, s.timeTaken());
499 }
500
501 return 0;
502}
Lorenzo Colitti7035f222017-02-13 18:29:00 +0900503
504} // namespace net
505} // namespace android