OSDN Git Service

Don't close loopback sockets when a VPN connects or entering doze.
[android-x86/system-netd.git] / server / SockDiagTest.cpp
1 /*
2  * Copyright 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  * sock_diag_test.cpp - unit tests for SockDiag.cpp
17  */
18
19 #include <sys/socket.h>
20 #include <netdb.h>
21 #include <arpa/inet.h>
22 #include <netinet/in.h>
23 #include <netinet/tcp.h>
24 #include <linux/inet_diag.h>
25
26 #include <gtest/gtest.h>
27
28 #include "NetdConstants.h"
29 #include "SockDiag.h"
30 #include "UidRanges.h"
31
32 class SockDiagTest : public ::testing::Test {
33 protected:
34     static bool isLoopbackSocket(const inet_diag_msg *msg) {
35         return SockDiag::isLoopbackSocket(msg);
36     };
37 };
38
39 uint16_t bindAndListen(int s) {
40     for (int i = 0; i < 10; i++) {
41         uint16_t port = 1024 + arc4random_uniform(0xffff - 1024);
42         sockaddr_in6 sin6 = { .sin6_family = AF_INET6, .sin6_port = htons(port) };
43         if (bind(s, (sockaddr *) &sin6, sizeof(sin6)) == 0) {
44             listen(s, 1);
45             return port;
46         }
47     }
48     close(s);
49     return 0;
50 }
51
52 const char *tcpStateName(uint8_t state) {
53     static const char *states[] = {
54         "???",
55         "TCP_ESTABLISHED",
56         "TCP_SYN_SENT",
57         "TCP_SYN_RECV",
58         "TCP_FIN_WAIT1",
59         "TCP_FIN_WAIT2",
60         "TCP_TIME_WAIT",
61         "TCP_CLOSE",
62         "TCP_CLOSE_WAIT",
63         "TCP_LAST_ACK",
64         "TCP_LISTEN",
65         "TCP_CLOSING",
66         "TCP_NEW_SYN_RECV",
67     };
68     return states[(state < ARRAY_SIZE(states)) ? state : 0];
69 }
70
71 TEST_F(SockDiagTest, TestDump) {
72     int v4socket = socket(AF_INET, SOCK_STREAM, 0);
73     ASSERT_NE(-1, v4socket) << "Failed to open IPv4 socket: " << strerror(errno);
74     int v6socket = socket(AF_INET6, SOCK_STREAM, 0);
75     ASSERT_NE(-1, v6socket) << "Failed to open IPv6 socket: " << strerror(errno);
76     int listensocket = socket(AF_INET6, SOCK_STREAM, 0);
77     ASSERT_NE(-1, listensocket) << "Failed to open listen socket: " << strerror(errno);
78
79     uint16_t port = bindAndListen(listensocket);
80     ASSERT_NE(0, port) << "Can't bind to server port";
81
82     // Connect to loopback.
83     sockaddr_in server4 = { .sin_family = AF_INET, .sin_port = htons(port) };
84     sockaddr_in6 server6 = { .sin6_family = AF_INET6, .sin6_port = htons(port) };
85     ASSERT_EQ(0, connect(v4socket, (sockaddr *) &server4, sizeof(server4)))
86         << "IPv4 connect failed: " << strerror(errno);
87     ASSERT_EQ(0, connect(v6socket, (sockaddr *) &server6, sizeof(server6)))
88         << "IPv6 connect failed: " << strerror(errno);
89
90     sockaddr_in6 client46, client6;
91     socklen_t clientlen = std::max(sizeof(client46), sizeof(client6));
92     int accepted4 = accept(listensocket, (sockaddr *) &client46, &clientlen);
93     int accepted6 = accept(listensocket, (sockaddr *) &client6, &clientlen);
94     ASSERT_NE(-1, accepted4);
95     ASSERT_NE(-1, accepted6);
96
97     int v4SocketsSeen = 0;
98     bool seenclient46 = false;
99     bool seenNull = false;
100     char src[INET6_ADDRSTRLEN], dst[INET6_ADDRSTRLEN];
101
102     fprintf(stderr, "Ports:\n  server=%d. client46=%d, client6=%d\n",
103             port, ntohs(client46.sin6_port), ntohs(client6.sin6_port));
104
105     auto checkIPv4Dump = [&] (uint8_t /* proto */, const inet_diag_msg *msg) {
106         if (msg == nullptr) {
107             EXPECT_FALSE(seenNull);
108             seenNull = true;
109             return false;
110         }
111         EXPECT_EQ(htonl(INADDR_LOOPBACK), msg->id.idiag_src[0]);
112         v4SocketsSeen++;
113         seenclient46 |= (msg->id.idiag_sport == client46.sin6_port);
114         inet_ntop(AF_INET, msg->id.idiag_src, src, sizeof(src));
115         inet_ntop(AF_INET, msg->id.idiag_src, dst, sizeof(dst));
116         fprintf(stderr, "  v4 %s:%d -> %s:%d %s\n",
117                 src, htons(msg->id.idiag_sport),
118                 dst, htons(msg->id.idiag_dport),
119                 tcpStateName(msg->idiag_state));
120         if (msg->idiag_state == TCP_ESTABLISHED) {
121             EXPECT_TRUE(isLoopbackSocket(msg));
122         }
123         return false;
124     };
125
126     int v6SocketsSeen = 0;
127     bool seenClient6 = false, seenServer46 = false, seenServer6 = false;
128
129     auto checkIPv6Dump = [&] (uint8_t /* proto */, const inet_diag_msg *msg) {
130         if (msg == nullptr) {
131             EXPECT_FALSE(seenNull);
132             seenNull = true;
133             return false;
134         }
135         struct in6_addr *saddr = (struct in6_addr *) msg->id.idiag_src;
136         EXPECT_TRUE(
137             IN6_IS_ADDR_LOOPBACK(saddr) ||
138             (IN6_IS_ADDR_V4MAPPED(saddr) && saddr->s6_addr32[3] == htonl(INADDR_LOOPBACK)));
139         v6SocketsSeen++;
140         seenClient6 |= (msg->id.idiag_sport == client6.sin6_port);
141         seenServer46 |= (msg->id.idiag_sport == htons(port));
142         seenServer6 |= (msg->id.idiag_sport == htons(port));
143         inet_ntop(AF_INET6, msg->id.idiag_src, src, sizeof(src));
144         inet_ntop(AF_INET6, msg->id.idiag_src, dst, sizeof(dst));
145         fprintf(stderr, "  v6 [%s]:%d -> [%s]:%d %s\n",
146                 src, htons(msg->id.idiag_sport),
147                 dst, htons(msg->id.idiag_dport),
148                 tcpStateName(msg->idiag_state));
149         if (msg->idiag_state == TCP_ESTABLISHED) {
150             EXPECT_TRUE(isLoopbackSocket(msg));
151         }
152         return false;
153     };
154
155     SockDiag sd;
156     ASSERT_TRUE(sd.open()) << "Failed to open SOCK_DIAG socket";
157
158     seenNull = false;
159     int ret = sd.sendDumpRequest(IPPROTO_TCP, AF_INET, "127.0.0.1");
160     ASSERT_EQ(0, ret) << "Failed to send IPv4 dump request: " << strerror(-ret);
161     fprintf(stderr, "Sent IPv4 dump\n");
162     sd.readDiagMsg(IPPROTO_TCP, checkIPv4Dump);
163     EXPECT_GE(v4SocketsSeen, 1);
164     EXPECT_TRUE(seenclient46);
165     EXPECT_FALSE(seenServer46);
166
167     seenNull = false;
168     ret = sd.sendDumpRequest(IPPROTO_TCP, AF_INET6, "127.0.0.1");
169     ASSERT_EQ(0, ret) << "Failed to send mapped dump request: " << strerror(-ret);
170     fprintf(stderr, "Sent mapped dump\n");
171     sd.readDiagMsg(IPPROTO_TCP, checkIPv6Dump);
172     EXPECT_TRUE(seenServer46);
173
174     seenNull = false;
175     ret = sd.sendDumpRequest(IPPROTO_TCP, AF_INET6, "::1");
176     ASSERT_EQ(0, ret) << "Failed to send IPv6 dump request: " << strerror(-ret);
177     fprintf(stderr, "Sent IPv6 dump\n");
178
179     sd.readDiagMsg(IPPROTO_TCP, checkIPv6Dump);
180     EXPECT_GE(v6SocketsSeen, 1);
181     EXPECT_TRUE(seenClient6);
182     EXPECT_TRUE(seenServer6);
183
184     close(v4socket);
185     close(v6socket);
186     close(listensocket);
187     close(accepted4);
188     close(accepted6);
189 }
190
191 bool fillDiagAddr(__be32 addr[4], const sockaddr *sa) {
192     switch (sa->sa_family) {
193         case AF_INET: {
194             sockaddr_in *sin = (sockaddr_in *) sa;
195             memcpy(addr, &sin->sin_addr, sizeof(sin->sin_addr));
196             return true;
197         }
198         case AF_INET6: {
199             sockaddr_in6 *sin6 = (sockaddr_in6 *) sa;
200             memcpy(addr, &sin6->sin6_addr, sizeof(sin6->sin6_addr));
201             return true;
202         }
203         default:
204             return false;
205     }
206 }
207
208 inet_diag_msg makeDiagMessage(__u8 family,  const sockaddr *src, const sockaddr *dst) {
209     inet_diag_msg msg = {
210         .idiag_family = family,
211         .idiag_state = TCP_ESTABLISHED,
212         .idiag_uid = AID_APP + 123,
213         .idiag_inode = 123456789,
214         .id = {
215             .idiag_sport = 1234,
216             .idiag_dport = 4321,
217         }
218     };
219     EXPECT_TRUE(fillDiagAddr(msg.id.idiag_src, src));
220     EXPECT_TRUE(fillDiagAddr(msg.id.idiag_dst, dst));
221     return msg;
222 }
223
224 inet_diag_msg makeDiagMessage(const char* srcstr, const char* dststr) {
225     addrinfo hints = { .ai_flags = AI_NUMERICHOST }, *src, *dst;
226     EXPECT_EQ(0, getaddrinfo(srcstr, NULL, &hints, &src));
227     EXPECT_EQ(0, getaddrinfo(dststr, NULL, &hints, &dst));
228     EXPECT_EQ(src->ai_addr->sa_family, dst->ai_addr->sa_family);
229     inet_diag_msg msg = makeDiagMessage(src->ai_addr->sa_family, src->ai_addr, dst->ai_addr);
230     freeaddrinfo(src);
231     freeaddrinfo(dst);
232     return msg;
233 }
234
235 TEST_F(SockDiagTest, TestIsLoopbackSocket) {
236     inet_diag_msg msg;
237
238     msg = makeDiagMessage("127.0.0.1", "127.0.0.1");
239     EXPECT_TRUE(isLoopbackSocket(&msg));
240
241     msg = makeDiagMessage("::1", "::1");
242     EXPECT_TRUE(isLoopbackSocket(&msg));
243
244     msg = makeDiagMessage("::1", "::ffff:127.0.0.1");
245     EXPECT_TRUE(isLoopbackSocket(&msg));
246
247     msg = makeDiagMessage("192.0.2.1", "192.0.2.1");
248     EXPECT_TRUE(isLoopbackSocket(&msg));
249
250     msg = makeDiagMessage("192.0.2.1", "8.8.8.8");
251     EXPECT_FALSE(isLoopbackSocket(&msg));
252
253     msg = makeDiagMessage("192.0.2.1", "127.0.0.1");
254     EXPECT_TRUE(isLoopbackSocket(&msg));
255
256     msg = makeDiagMessage("2001:db8::1", "2001:db8::1");
257     EXPECT_TRUE(isLoopbackSocket(&msg));
258
259     msg = makeDiagMessage("2001:db8::1", "2001:4860:4860::6464");
260     EXPECT_FALSE(isLoopbackSocket(&msg));
261
262     // While isLoopbackSocket returns true on these sockets, we usually don't want to close them
263     // because they aren't specific to any particular network and thus don't become unusable when
264     // an app's routing changes or its network access is removed.
265     //
266     // This isn't a problem, as anything that calls destroyLiveSockets will skip them because
267     // destroyLiveSockets only enumerates ESTABLISHED, SYN_SENT, and SYN_RECV sockets.
268     msg = makeDiagMessage("127.0.0.1", "0.0.0.0");
269     EXPECT_TRUE(isLoopbackSocket(&msg));
270
271     msg = makeDiagMessage("::1", "::");
272     EXPECT_TRUE(isLoopbackSocket(&msg));
273 }
274
275 enum MicroBenchmarkTestType {
276     ADDRESS,
277     UID,
278     UID_EXCLUDE_LOOPBACK,
279     UIDRANGE,
280     UIDRANGE_EXCLUDE_LOOPBACK,
281 };
282
283 const char *testTypeName(MicroBenchmarkTestType mode) {
284 #define TO_STRING_TYPE(x) case ((x)): return #x;
285     switch((mode)) {
286         TO_STRING_TYPE(ADDRESS);
287         TO_STRING_TYPE(UID);
288         TO_STRING_TYPE(UID_EXCLUDE_LOOPBACK);
289         TO_STRING_TYPE(UIDRANGE);
290         TO_STRING_TYPE(UIDRANGE_EXCLUDE_LOOPBACK);
291     }
292 #undef TO_STRING_TYPE
293 }
294
295 class SockDiagMicroBenchmarkTest : public ::testing::TestWithParam<MicroBenchmarkTestType> {
296
297 public:
298     void SetUp() {
299         ASSERT_TRUE(mSd.open()) << "Failed to open SOCK_DIAG socket";
300     }
301
302 protected:
303     SockDiag mSd;
304
305     constexpr static int MAX_SOCKETS = 500;
306     constexpr static int ADDRESS_SOCKETS = 500;
307     constexpr static int UID_SOCKETS = 50;
308     constexpr static uid_t START_UID = 8000;  // START_UID + number of sockets must be <= 9999.
309     constexpr static int CLOSE_UID = START_UID + UID_SOCKETS - 42;  // Close to the end
310     static_assert(START_UID + MAX_SOCKETS < 9999, "Too many sockets");
311
312     int howManySockets() {
313         MicroBenchmarkTestType mode = GetParam();
314         switch (mode) {
315         case ADDRESS:
316             return ADDRESS_SOCKETS;
317         case UID:
318         case UID_EXCLUDE_LOOPBACK:
319         case UIDRANGE:
320         case UIDRANGE_EXCLUDE_LOOPBACK:
321             return UID_SOCKETS;
322         }
323     }
324
325     int destroySockets() {
326         MicroBenchmarkTestType mode = GetParam();
327         int ret;
328         switch (mode) {
329             case ADDRESS:
330                 ret = mSd.destroySockets("::1");
331                 EXPECT_LE(0, ret) << ": Failed to destroy sockets on ::1: " << strerror(-ret);
332                 break;
333             case UID:
334             case UID_EXCLUDE_LOOPBACK: {
335                 bool excludeLoopback = (mode == UID_EXCLUDE_LOOPBACK);
336                 ret = mSd.destroySockets(IPPROTO_TCP, CLOSE_UID, excludeLoopback);
337                 EXPECT_LE(0, ret) << ": Failed to destroy sockets for UID " << CLOSE_UID << ": " <<
338                         strerror(-ret);
339                 break;
340             }
341             case UIDRANGE:
342             case UIDRANGE_EXCLUDE_LOOPBACK: {
343                 bool excludeLoopback = (mode == UIDRANGE_EXCLUDE_LOOPBACK);
344                 const char *uidRangeStrings[] = { "8005-8012", "8042", "8043", "8090-8099" };
345                 std::set<uid_t> skipUids { 8007, 8043, 8098, 8099 };
346                 UidRanges uidRanges;
347                 uidRanges.parseFrom(ARRAY_SIZE(uidRangeStrings), (char **) uidRangeStrings);
348                 ret = mSd.destroySockets(uidRanges, skipUids, excludeLoopback);
349             }
350         }
351         return ret;
352     }
353
354     bool shouldHaveClosedSocket(int i) {
355         MicroBenchmarkTestType mode = GetParam();
356         switch (mode) {
357             case ADDRESS:
358                 return true;
359             case UID:
360                 return i == CLOSE_UID - START_UID;
361             case UIDRANGE: {
362                 uid_t uid = i + START_UID;
363                 // Skip UIDs in skipUids.
364                 if (uid == 8007 || uid == 8043 || uid == 8098 || uid == 8099) {
365                     return false;
366                 }
367                 // Include UIDs in uidRanges.
368                 if ((8005 <= uid && uid <= 8012) || uid == 8042 || (8090 <= uid && uid <= 8099)) {
369                     return true;
370                 }
371                 return false;
372             }
373             case UID_EXCLUDE_LOOPBACK:
374             case UIDRANGE_EXCLUDE_LOOPBACK:
375                 return false;
376         }
377     }
378
379     bool checkSocketState(int i, int sock, const char *msg) {
380         const char data[] = "foo";
381         const int ret = send(sock, data, sizeof(data), 0);
382         const int err = errno;
383         if (!shouldHaveClosedSocket(i)) {
384             EXPECT_EQ((ssize_t) sizeof(data), ret) <<
385                     "Write on open socket failed: " << strerror(err);
386             return false;
387         }
388
389         EXPECT_EQ(-1, ret) << msg << " " << i << " not closed";
390         if (ret != -1) {
391             return false;
392         }
393
394         // Since we're connected to ourselves, the error might be ECONNABORTED (if we destroyed the
395         // socket) or ECONNRESET (if the other end was destroyed and sent a RST).
396         EXPECT_TRUE(err == ECONNABORTED || err == ECONNRESET)
397             << msg << ": unexpected error: " << strerror(err);
398         return (err == ECONNABORTED);  // Return true iff. SOCK_DESTROY closed this socket.
399     }
400 };
401
402 TEST_P(SockDiagMicroBenchmarkTest, TestMicroBenchmark) {
403     MicroBenchmarkTestType mode = GetParam();
404
405     int numSockets = howManySockets();
406
407     fprintf(stderr, "Benchmarking closing %d sockets based on %s\n",
408             numSockets, testTypeName(mode));
409
410     int listensocket = socket(AF_INET6, SOCK_STREAM, 0);
411     ASSERT_NE(-1, listensocket) << "Failed to open listen socket";
412
413     uint16_t port = bindAndListen(listensocket);
414     ASSERT_NE(0, port) << "Can't bind to server port";
415     sockaddr_in6 server = { .sin6_family = AF_INET6, .sin6_port = htons(port) };
416
417     using ms = std::chrono::duration<float, std::ratio<1, 1000>>;
418
419     int clientsockets[MAX_SOCKETS], serversockets[MAX_SOCKETS];
420     uint16_t clientports[MAX_SOCKETS];
421     sockaddr_in6 client;
422     socklen_t clientlen;
423
424     auto start = std::chrono::steady_clock::now();
425     for (int i = 0; i < numSockets; i++) {
426         int s = socket(AF_INET6, SOCK_STREAM, 0);
427         uid_t uid = START_UID + i;
428         ASSERT_EQ(0, fchown(s, uid, -1));
429         clientlen = sizeof(client);
430         ASSERT_EQ(0, connect(s, (sockaddr *) &server, sizeof(server)))
431             << "Connecting socket " << i << " failed " << strerror(errno);
432         serversockets[i] = accept(listensocket, (sockaddr *) &client, &clientlen);
433         ASSERT_NE(-1, serversockets[i])
434             << "Accepting socket " << i << " failed " << strerror(errno);
435         clientports[i] = client.sin6_port;
436         clientsockets[i] = s;
437     }
438     fprintf(stderr, "  Connecting: %6.1f ms\n",
439             std::chrono::duration_cast<ms>(std::chrono::steady_clock::now() - start).count());
440
441     start = std::chrono::steady_clock::now();
442     destroySockets();
443     fprintf(stderr, "  Destroying: %6.1f ms\n",
444             std::chrono::duration_cast<ms>(std::chrono::steady_clock::now() - start).count());
445
446     start = std::chrono::steady_clock::now();
447     int socketsClosed = 0;
448     for (int i = 0; i < numSockets; i++) {
449         socketsClosed += checkSocketState(i, clientsockets[i], "Client socket");
450         socketsClosed += checkSocketState(i, serversockets[i], "Server socket");
451     }
452     fprintf(stderr, "   Verifying: %6.1f ms (%d sockets destroyed)\n",
453             std::chrono::duration_cast<ms>(std::chrono::steady_clock::now() - start).count(),
454             socketsClosed);
455     if (strstr(testTypeName(mode), "_EXCLUDE_LOOPBACK") == nullptr) {
456         EXPECT_GT(socketsClosed, 0);  // Just in case there's a bug in the test.
457     }
458
459     start = std::chrono::steady_clock::now();
460     for (int i = 0; i < numSockets; i++) {
461         close(clientsockets[i]);
462         close(serversockets[i]);
463     }
464     fprintf(stderr, "     Closing: %6.1f ms\n",
465             std::chrono::duration_cast<ms>(std::chrono::steady_clock::now() - start).count());
466
467     close(listensocket);
468 }
469
470 // "SockDiagTest.cpp:232: error: undefined reference to 'SockDiagMicroBenchmarkTest::CLOSE_UID'".
471 constexpr int SockDiagMicroBenchmarkTest::CLOSE_UID;
472
473 INSTANTIATE_TEST_CASE_P(Address, SockDiagMicroBenchmarkTest,
474                         testing::Values(ADDRESS, UID, UIDRANGE,
475                                         UID_EXCLUDE_LOOPBACK, UIDRANGE_EXCLUDE_LOOPBACK));