blob: 853b8edebfdd2844993112b50d790cf26613b941 [file] [log] [blame]
Narayan Kamatha5ace892017-01-06 15:10:02 +00001/*
2 * Copyright 2017 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
Lorenzo Colitti173da322017-02-05 01:56:40 +090017#include <fcntl.h>
Bernie Innocenti196f1b82019-05-20 16:34:16 +090018#include <gmock/gmock.h>
19#include <gtest/gtest.h>
Lorenzo Colitti2bd804a2017-03-10 12:19:08 +090020#include <sys/file.h>
Lorenzo Colittia701afb2017-02-28 01:47:11 +090021#include <sys/socket.h>
22#include <sys/un.h>
Narayan Kamatha5ace892017-01-06 15:10:02 +000023
Bernie Innocenti196f1b82019-05-20 16:34:16 +090024#include <cinttypes>
25#include <iostream>
26#include <string>
Narayan Kamatha5ace892017-01-06 15:10:02 +000027
Lorenzo Colitti173da322017-02-05 01:56:40 +090028#define LOG_TAG "IptablesRestoreControllerTest"
Lorenzo Colitti173da322017-02-05 01:56:40 +090029#include <android-base/stringprintf.h>
Lorenzo Colitticd283772017-01-31 19:00:49 +090030#include <android-base/strings.h>
Mike Yue7e332f2019-03-13 17:15:48 +080031#include <log/log.h>
Lorenzo Colitti2103b6b2017-08-14 11:38:18 +090032#include <netdutils/MockSyscalls.h>
Mike Yue7e332f2019-03-13 17:15:48 +080033#include <netdutils/Stopwatch.h>
Lorenzo Colitti173da322017-02-05 01:56:40 +090034
Narayan Kamatha5ace892017-01-06 15:10:02 +000035#include "IptablesRestoreController.h"
36#include "NetdConstants.h"
Chenbo Feng89c12f12018-03-21 10:29:18 -070037#include "bpf/BpfUtils.h"
Narayan Kamatha5ace892017-01-06 15:10:02 +000038
Lorenzo Colitti2bd804a2017-03-10 12:19:08 +090039#define XT_LOCK_NAME "/system/etc/xtables.lock"
40#define XT_LOCK_ATTEMPTS 10
41#define XT_LOCK_POLL_INTERVAL_MS 100
Lorenzo Colittia701afb2017-02-28 01:47:11 +090042
Lorenzo Colitti0766f2f2020-09-18 02:46:53 +000043#define PROC_STAT_MIN_ELEMENTS 52U
44#define PROC_STAT_RSS_INDEX 23U
45
46#define IPTABLES_COMM "(iptables-restor)"
47#define IP6TABLES_COMM "(ip6tables-resto)"
48
Lorenzo Colitticd283772017-01-31 19:00:49 +090049using android::base::Join;
Lorenzo Colitti0766f2f2020-09-18 02:46:53 +000050using android::base::StringAppendF;
Lorenzo Colitti173da322017-02-05 01:56:40 +090051using android::base::StringPrintf;
Lorenzo Colitti2103b6b2017-08-14 11:38:18 +090052using android::netdutils::ScopedMockSyscalls;
Mike Yue7e332f2019-03-13 17:15:48 +080053using android::netdutils::Stopwatch;
Lorenzo Colitti2103b6b2017-08-14 11:38:18 +090054using testing::Return;
55using testing::StrictMock;
Narayan Kamatha5ace892017-01-06 15:10:02 +000056
Lorenzo Colitti173da322017-02-05 01:56:40 +090057class IptablesRestoreControllerTest : public ::testing::Test {
58public:
59 IptablesRestoreController con;
Lorenzo Colittia701afb2017-02-28 01:47:11 +090060 int mDefaultMaxRetries = con.MAX_RETRIES;
61 int mDefaultPollTimeoutMs = con.POLL_TIMEOUT_MS;
62 int mIptablesLock = -1;
63 std::string mChainName;
64
Nick Desaulniers485a4772019-10-11 09:25:59 -070065 static void SetUpTestSuite() { blockSigpipe(); }
Lorenzo Colitti839d7d62017-04-03 15:37:19 +090066
Lorenzo Colittia701afb2017-02-28 01:47:11 +090067 void SetUp() {
68 ASSERT_EQ(0, createTestChain());
69 }
70
71 void TearDown() {
72 con.MAX_RETRIES = mDefaultMaxRetries;
73 con.POLL_TIMEOUT_MS = mDefaultPollTimeoutMs;
74 deleteTestChain();
75 }
Lorenzo Colitti173da322017-02-05 01:56:40 +090076
Lorenzo Colitti2103b6b2017-08-14 11:38:18 +090077 void Init() {
78 con.Init();
79 }
80
Lorenzo Colitti173da322017-02-05 01:56:40 +090081 pid_t getIpRestorePid(const IptablesRestoreController::IptablesProcessType type) {
82 return con.getIpRestorePid(type);
83 };
84
Lorenzo Colitti0766f2f2020-09-18 02:46:53 +000085 const std::string getProcStatPath(pid_t pid) { return StringPrintf("/proc/%d/stat", pid); }
86
87 std::vector<std::string> parseProcStat(int fd, const std::string& path) {
88 std::vector<std::string> procStat;
89
90 char statBuf[1024];
91 EXPECT_NE(-1, read(fd, statBuf, sizeof(statBuf)))
92 << "Could not read from " << path << ": " << strerror(errno);
93
94 std::stringstream stream(statBuf);
95 std::string item;
96 while (std::getline(stream, item, ' ')) {
97 procStat.push_back(item);
98 }
99
100 EXPECT_LE(PROC_STAT_MIN_ELEMENTS, procStat.size()) << "Too few elements in " << path;
101 return procStat;
102 }
103
Lorenzo Colitti173da322017-02-05 01:56:40 +0900104 void expectNoIptablesRestoreProcess(pid_t pid) {
105 // We can't readlink /proc/PID/exe, because zombie processes don't have it.
106 // Parse /proc/PID/stat instead.
Lorenzo Colitti0766f2f2020-09-18 02:46:53 +0000107 std::string statPath = getProcStatPath(pid);
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900108 int fd = open(statPath.c_str(), O_RDONLY | O_CLOEXEC);
Lorenzo Colitti173da322017-02-05 01:56:40 +0900109 if (fd == -1) {
110 // ENOENT means the process is gone (expected).
111 ASSERT_EQ(errno, ENOENT)
112 << "Unexpected error opening " << statPath << ": " << strerror(errno);
113 return;
114 }
115
116 // If the PID exists, it's possible (though very unlikely) that the PID was reused. Check the
117 // binary name as well, to ensure the test isn't flaky.
Lorenzo Colitti0766f2f2020-09-18 02:46:53 +0000118 std::vector<std::string> procStat = parseProcStat(fd, statPath);
119 EXPECT_FALSE(procStat[1] == IPTABLES_COMM || procStat[1] == IP6TABLES_COMM)
120 << "Previous iptables-restore or ip6tables-restore pid " << pid
121 << " still alive: " << Join(procStat, " ");
Lorenzo Colitti173da322017-02-05 01:56:40 +0900122
Lorenzo Colitti0766f2f2020-09-18 02:46:53 +0000123 close(fd);
124 }
125
126 unsigned getRssPages(pid_t pid) {
127 std::string statPath = getProcStatPath(pid);
128 int fd = open(statPath.c_str(), O_RDONLY | O_CLOEXEC);
129 EXPECT_NE(-1, fd) << "Unexpected error opening " << statPath << ": " << strerror(errno);
130 if (fd == -1) return 0;
131
132 const auto& procStat = parseProcStat(fd, statPath);
133 close(fd);
134
135 if (procStat.size() < PROC_STAT_MIN_ELEMENTS) return 0;
136 EXPECT_TRUE(procStat[1] == IPTABLES_COMM || procStat[1] == IP6TABLES_COMM)
137 << statPath << " is for unexpected process: " << procStat[1];
138
139 return std::atoi(procStat[PROC_STAT_RSS_INDEX].c_str());
Lorenzo Colitti173da322017-02-05 01:56:40 +0900140 }
Lorenzo Colittia701afb2017-02-28 01:47:11 +0900141
142 int createTestChain() {
143 mChainName = StringPrintf("netd_unit_test_%u", arc4random_uniform(10000)).c_str();
144
145 // Create a chain to list.
146 std::vector<std::string> createCommands = {
147 "*filter",
148 StringPrintf(":%s -", mChainName.c_str()),
149 StringPrintf("-A %s -j RETURN", mChainName.c_str()),
150 "COMMIT",
151 ""
152 };
153
154 int ret = con.execute(V4V6, Join(createCommands, "\n"), nullptr);
155 if (ret) mChainName = "";
156 return ret;
157 }
158
159 void deleteTestChain() {
160 std::vector<std::string> deleteCommands = {
161 "*filter",
162 StringPrintf(":%s -", mChainName.c_str()), // Flush chain (otherwise we can't delete it).
163 StringPrintf("-X %s", mChainName.c_str()), // Delete it.
164 "COMMIT",
165 ""
166 };
167 con.execute(V4V6, Join(deleteCommands, "\n"), nullptr);
168 mChainName = "";
169 }
170
171 int acquireIptablesLock() {
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900172 mIptablesLock = open(XT_LOCK_NAME, O_CREAT | O_CLOEXEC, 0600);
Lorenzo Colitti2bd804a2017-03-10 12:19:08 +0900173 if (mIptablesLock == -1) return mIptablesLock;
174 int attempts;
175 for (attempts = 0; attempts < XT_LOCK_ATTEMPTS; attempts++) {
176 if (flock(mIptablesLock, LOCK_EX | LOCK_NB) == 0) {
177 return 0;
178 }
179 usleep(XT_LOCK_POLL_INTERVAL_MS * 1000);
Lorenzo Colittia701afb2017-02-28 01:47:11 +0900180 }
Lorenzo Colitti2bd804a2017-03-10 12:19:08 +0900181 EXPECT_LT(attempts, XT_LOCK_ATTEMPTS) <<
182 "Could not acquire iptables lock after " << XT_LOCK_ATTEMPTS << " attempts " <<
183 XT_LOCK_POLL_INTERVAL_MS << "ms apart";
184 return -1;
Lorenzo Colittia701afb2017-02-28 01:47:11 +0900185 }
186
187 void releaseIptablesLock() {
188 if (mIptablesLock != -1) {
189 close(mIptablesLock);
190 }
191 }
192
193 void setRetryParameters(int maxRetries, int pollTimeoutMs) {
194 con.MAX_RETRIES = maxRetries;
195 con.POLL_TIMEOUT_MS = pollTimeoutMs;
196 }
Narayan Kamatha5ace892017-01-06 15:10:02 +0000197};
198
Lorenzo Colitti173da322017-02-05 01:56:40 +0900199TEST_F(IptablesRestoreControllerTest, TestBasicCommand) {
Lorenzo Colitticd283772017-01-31 19:00:49 +0900200 std::string output;
201
202 EXPECT_EQ(0, con.execute(IptablesTarget::V4V6, "#Test\n", nullptr));
Lorenzo Colitti173da322017-02-05 01:56:40 +0900203
204 pid_t pid4 = getIpRestorePid(IptablesRestoreController::IPTABLES_PROCESS);
205 pid_t pid6 = getIpRestorePid(IptablesRestoreController::IP6TABLES_PROCESS);
206
Lorenzo Colitticd283772017-01-31 19:00:49 +0900207 EXPECT_EQ(0, con.execute(IptablesTarget::V6, "#Test\n", nullptr));
208 EXPECT_EQ(0, con.execute(IptablesTarget::V4, "#Test\n", nullptr));
209
210 EXPECT_EQ(0, con.execute(IptablesTarget::V4V6, "#Test\n", &output));
211 EXPECT_EQ("#Test\n#Test\n", output); // One for IPv4 and one for IPv6.
Lorenzo Colitti173da322017-02-05 01:56:40 +0900212
213 // Check the PIDs are the same as they were before. If they're not, the child processes were
214 // restarted, which causes a 30-60ms delay.
215 EXPECT_EQ(pid4, getIpRestorePid(IptablesRestoreController::IPTABLES_PROCESS));
216 EXPECT_EQ(pid6, getIpRestorePid(IptablesRestoreController::IP6TABLES_PROCESS));
Narayan Kamatha5ace892017-01-06 15:10:02 +0000217}
218
Lorenzo Colitti173da322017-02-05 01:56:40 +0900219TEST_F(IptablesRestoreControllerTest, TestRestartOnMalformedCommand) {
Lorenzo Colitticd283772017-01-31 19:00:49 +0900220 std::string buffer;
Lorenzo Colitti173da322017-02-05 01:56:40 +0900221 for (int i = 0; i < 50; i++) {
222 IptablesTarget target = (IptablesTarget) (i % 3);
Lorenzo Colitticd283772017-01-31 19:00:49 +0900223 std::string *output = (i % 2) ? &buffer : nullptr;
224 ASSERT_EQ(-1, con.execute(target, "malformed command\n", output)) <<
Lorenzo Colitti173da322017-02-05 01:56:40 +0900225 "Malformed command did not fail at iteration " << i;
Lorenzo Colitticd283772017-01-31 19:00:49 +0900226 ASSERT_EQ(0, con.execute(target, "#Test\n", output)) <<
Lorenzo Colitti173da322017-02-05 01:56:40 +0900227 "No-op command did not succeed at iteration " << i;
228 }
229}
230
231TEST_F(IptablesRestoreControllerTest, TestRestartOnProcessDeath) {
Lorenzo Colitticd283772017-01-31 19:00:49 +0900232 std::string output;
233
Lorenzo Colitti173da322017-02-05 01:56:40 +0900234 // Run a command to ensure that the processes are running.
Lorenzo Colitticd283772017-01-31 19:00:49 +0900235 EXPECT_EQ(0, con.execute(IptablesTarget::V4V6, "#Test\n", &output));
Lorenzo Colitti173da322017-02-05 01:56:40 +0900236
237 pid_t pid4 = getIpRestorePid(IptablesRestoreController::IPTABLES_PROCESS);
238 pid_t pid6 = getIpRestorePid(IptablesRestoreController::IP6TABLES_PROCESS);
239
240 ASSERT_EQ(0, kill(pid4, 0)) << "iptables-restore pid " << pid4 << " does not exist";
241 ASSERT_EQ(0, kill(pid6, 0)) << "ip6tables-restore pid " << pid6 << " does not exist";
242 ASSERT_EQ(0, kill(pid4, SIGTERM)) << "Failed to send SIGTERM to iptables-restore pid " << pid4;
243 ASSERT_EQ(0, kill(pid6, SIGTERM)) << "Failed to send SIGTERM to ip6tables-restore pid " << pid6;
244
245 // Wait 100ms for processes to terminate.
246 TEMP_FAILURE_RETRY(usleep(100 * 1000));
247
248 // Ensure that running a new command properly restarts the processes.
Lorenzo Colitticd283772017-01-31 19:00:49 +0900249 EXPECT_EQ(0, con.execute(IptablesTarget::V4V6, "#Test\n", nullptr));
Lorenzo Colitti173da322017-02-05 01:56:40 +0900250 EXPECT_NE(pid4, getIpRestorePid(IptablesRestoreController::IPTABLES_PROCESS));
251 EXPECT_NE(pid6, getIpRestorePid(IptablesRestoreController::IP6TABLES_PROCESS));
252
253 // Check there are no zombies.
254 expectNoIptablesRestoreProcess(pid4);
255 expectNoIptablesRestoreProcess(pid6);
Narayan Kamatha5ace892017-01-06 15:10:02 +0000256}
Lorenzo Colitticd283772017-01-31 19:00:49 +0900257
Lorenzo Colittia701afb2017-02-28 01:47:11 +0900258TEST_F(IptablesRestoreControllerTest, TestCommandTimeout) {
259 // Don't wait 10 seconds for this test to fail.
260 setRetryParameters(3, 50);
Lorenzo Colitticd283772017-01-31 19:00:49 +0900261
262 // Expected contents of the chain.
263 std::vector<std::string> expectedLines = {
Lorenzo Colittia701afb2017-02-28 01:47:11 +0900264 StringPrintf("Chain %s (0 references)", mChainName.c_str()),
Lorenzo Colitticd283772017-01-31 19:00:49 +0900265 "target prot opt source destination ",
266 "RETURN all -- 0.0.0.0/0 0.0.0.0/0 ",
Lorenzo Colittia701afb2017-02-28 01:47:11 +0900267 StringPrintf("Chain %s (0 references)", mChainName.c_str()),
Lorenzo Colitticd283772017-01-31 19:00:49 +0900268 "target prot opt source destination ",
269 "RETURN all ::/0 ::/0 ",
270 ""
271 };
272 std::string expected = Join(expectedLines, "\n");
273
Lorenzo Colitticd283772017-01-31 19:00:49 +0900274 std::vector<std::string> listCommands = {
275 "*filter",
Lorenzo Colittia701afb2017-02-28 01:47:11 +0900276 StringPrintf("-n -L %s", mChainName.c_str()), // List chain.
Lorenzo Colitticd283772017-01-31 19:00:49 +0900277 "COMMIT",
278 ""
279 };
Lorenzo Colittia701afb2017-02-28 01:47:11 +0900280 std::string commandString = Join(listCommands, "\n");
Lorenzo Colitticd283772017-01-31 19:00:49 +0900281 std::string output;
Lorenzo Colittia701afb2017-02-28 01:47:11 +0900282
283 EXPECT_EQ(0, con.execute(IptablesTarget::V4V6, commandString, &output));
284 EXPECT_EQ(expected, output);
285
286 ASSERT_EQ(0, acquireIptablesLock());
287 EXPECT_EQ(-1, con.execute(IptablesTarget::V4V6, commandString, &output));
288 EXPECT_EQ(-1, con.execute(IptablesTarget::V4V6, commandString, &output));
289 releaseIptablesLock();
290
291 EXPECT_EQ(0, con.execute(IptablesTarget::V4V6, commandString, &output));
Lorenzo Colitticd283772017-01-31 19:00:49 +0900292 EXPECT_EQ(expected, output);
293}
Lorenzo Colittia7357652017-04-25 00:16:36 +0900294
Chenbo Feng89c12f12018-03-21 10:29:18 -0700295
Lorenzo Colittia7357652017-04-25 00:16:36 +0900296TEST_F(IptablesRestoreControllerTest, TestUidRuleBenchmark) {
297 const std::vector<int> ITERATIONS = { 1, 5, 10 };
298
299 const std::string IPTABLES_RESTORE_ADD =
Chenbo Feng89c12f12018-03-21 10:29:18 -0700300 StringPrintf("*filter\n-I %s -m owner --uid-owner 2000000000 -j RETURN\nCOMMIT\n",
301 mChainName.c_str());
Lorenzo Colittia7357652017-04-25 00:16:36 +0900302 const std::string IPTABLES_RESTORE_DEL =
Chenbo Feng89c12f12018-03-21 10:29:18 -0700303 StringPrintf("*filter\n-D %s -m owner --uid-owner 2000000000 -j RETURN\nCOMMIT\n",
304 mChainName.c_str());
Lorenzo Colittia7357652017-04-25 00:16:36 +0900305
306 for (const int iterations : ITERATIONS) {
307 Stopwatch s;
308 for (int i = 0; i < iterations; i++) {
309 EXPECT_EQ(0, con.execute(V4V6, IPTABLES_RESTORE_ADD, nullptr));
310 EXPECT_EQ(0, con.execute(V4V6, IPTABLES_RESTORE_DEL, nullptr));
311 }
Bernie Innocenti196f1b82019-05-20 16:34:16 +0900312 int64_t timeTaken = s.getTimeAndResetUs();
313 std::cerr << " Add/del " << iterations << " UID rules via restore: " << timeTaken
314 << "us (" << (timeTaken / 2 / iterations) << "us per operation)" << std::endl;
Lorenzo Colittia7357652017-04-25 00:16:36 +0900315 }
316}
Lorenzo Colitti2103b6b2017-08-14 11:38:18 +0900317
318TEST_F(IptablesRestoreControllerTest, TestStartup) {
319 // Tests that IptablesRestoreController::Init never sets its processes to null pointers if
320 // fork() succeeds.
321 {
322 // Mock fork(), and check that initializing 100 times never results in a null pointer.
323 constexpr int NUM_ITERATIONS = 100; // Takes 100-150ms on angler.
324 constexpr pid_t FAKE_PID = 2000000001;
325 StrictMock<ScopedMockSyscalls> sys;
326
327 EXPECT_CALL(sys, fork()).Times(NUM_ITERATIONS * 2).WillRepeatedly(Return(FAKE_PID));
328 for (int i = 0; i < NUM_ITERATIONS; i++) {
329 Init();
330 EXPECT_NE(0, getIpRestorePid(IptablesRestoreController::IPTABLES_PROCESS));
331 EXPECT_NE(0, getIpRestorePid(IptablesRestoreController::IP6TABLES_PROCESS));
332 }
333 }
334
335 // The controller is now in an invalid state: the pipes are connected to working iptables
336 // processes, but the PIDs are set to FAKE_PID. Send a malformed command to ensure that the
337 // processes terminate and close the pipes, then send a valid command to have the controller
338 // re-initialize properly now that fork() is no longer mocked.
339 EXPECT_EQ(-1, con.execute(V4V6, "malformed command\n", nullptr));
340 EXPECT_EQ(0, con.execute(V4V6, "#Test\n", nullptr));
341}
Lorenzo Colitti0766f2f2020-09-18 02:46:53 +0000342
343TEST_F(IptablesRestoreControllerTest, TestMemoryLeak) {
344 std::string cmd = "*filter\n";
345
346 // Keep command within PIPE_BUF (4096) just to make sure. Each line is 60 bytes including \n:
347 // -I netd_unit_test_9999 -p udp -m udp --sport 12345 -j DROP
348 for (int i = 0; i < 33; i++) {
349 StringAppendF(&cmd, "-I %s -p udp -m udp --sport 12345 -j DROP\n", mChainName.c_str());
350 StringAppendF(&cmd, "-D %s -p udp -m udp --sport 12345 -j DROP\n", mChainName.c_str());
351 }
352 StringAppendF(&cmd, "COMMIT\n");
353 ASSERT_GE(4096U, cmd.size());
354
355 // Run the command once in case it causes the first allocations for these iptables-restore
356 // processes, and check they don't crash.
357 pid_t pid4 = getIpRestorePid(IptablesRestoreController::IPTABLES_PROCESS);
358 pid_t pid6 = getIpRestorePid(IptablesRestoreController::IP6TABLES_PROCESS);
359 std::string output;
360 EXPECT_EQ(0, con.execute(IptablesTarget::V4V6, cmd, nullptr));
361 EXPECT_EQ(pid4, getIpRestorePid(IptablesRestoreController::IPTABLES_PROCESS));
362 EXPECT_EQ(pid6, getIpRestorePid(IptablesRestoreController::IP6TABLES_PROCESS));
363
364 // Check how much RAM the processes are using.
365 unsigned pages4 = getRssPages(pid4);
366 ASSERT_NE(0U, pages4);
367 unsigned pages6 = getRssPages(pid6);
368 ASSERT_NE(0U, pages6);
369
370 // Run the command a few times and check that it doesn't crash.
371 for (int i = 0; i < 10; i++) {
372 EXPECT_EQ(0, con.execute(IptablesTarget::V4V6, cmd, nullptr));
373 }
374 EXPECT_EQ(pid4, getIpRestorePid(IptablesRestoreController::IPTABLES_PROCESS));
375 EXPECT_EQ(pid6, getIpRestorePid(IptablesRestoreController::IP6TABLES_PROCESS));
376
377 // Don't allow a leak of more than 5 pages (20kB).
378 // This is more than enough for accuracy: the leak in b/162925719 fails with:
379 // Expected: (5U) >= (getRssPages(pid4) - pages4), actual: 5 vs 66
380 EXPECT_GE(5U, getRssPages(pid4) - pages4) << "iptables-restore leaked too many pages";
381 EXPECT_GE(5U, getRssPages(pid6) - pages6) << "ip6tables-restore leaked too many pages";
382}