1 /*
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
17 #include <string>
18 #include <fcntl.h>
19 #include <sys/file.h>
20 #include <sys/socket.h>
21 #include <sys/un.h>
22
23 #include <gmock/gmock.h>
24 #include <gtest/gtest.h>
25
26 #define LOG_TAG "IptablesRestoreControllerTest"
27 #include <cutils/log.h>
28 #include <android-base/stringprintf.h>
29 #include <android-base/strings.h>
30 #include <netdutils/MockSyscalls.h>
31
32 #include "IptablesRestoreController.h"
33 #include "NetdConstants.h"
34 #include "Stopwatch.h"
35
36 #define XT_LOCK_NAME "/system/etc/xtables.lock"
37 #define XT_LOCK_ATTEMPTS 10
38 #define XT_LOCK_POLL_INTERVAL_MS 100
39
40 using android::base::Join;
41 using android::base::StringPrintf;
42 using android::netdutils::ScopedMockSyscalls;
43 using testing::Return;
44 using testing::StrictMock;
45
46 class IptablesRestoreControllerTest : public ::testing::Test {
47 public:
48 IptablesRestoreController con;
49 int mDefaultMaxRetries = con.MAX_RETRIES;
50 int mDefaultPollTimeoutMs = con.POLL_TIMEOUT_MS;
51 int mIptablesLock = -1;
52 std::string mChainName;
53
SetUpTestCase()54 static void SetUpTestCase() {
55 blockSigpipe();
56 }
57
SetUp()58 void SetUp() {
59 ASSERT_EQ(0, createTestChain());
60 }
61
TearDown()62 void TearDown() {
63 con.MAX_RETRIES = mDefaultMaxRetries;
64 con.POLL_TIMEOUT_MS = mDefaultPollTimeoutMs;
65 deleteTestChain();
66 }
67
Init()68 void Init() {
69 con.Init();
70 }
71
getIpRestorePid(const IptablesRestoreController::IptablesProcessType type)72 pid_t getIpRestorePid(const IptablesRestoreController::IptablesProcessType type) {
73 return con.getIpRestorePid(type);
74 };
75
expectNoIptablesRestoreProcess(pid_t pid)76 void expectNoIptablesRestoreProcess(pid_t pid) {
77 // We can't readlink /proc/PID/exe, because zombie processes don't have it.
78 // Parse /proc/PID/stat instead.
79 std::string statPath = StringPrintf("/proc/%d/stat", pid);
80 int fd = open(statPath.c_str(), O_RDONLY);
81 if (fd == -1) {
82 // ENOENT means the process is gone (expected).
83 ASSERT_EQ(errno, ENOENT)
84 << "Unexpected error opening " << statPath << ": " << strerror(errno);
85 return;
86 }
87
88 // If the PID exists, it's possible (though very unlikely) that the PID was reused. Check the
89 // binary name as well, to ensure the test isn't flaky.
90 char statBuf[1024];
91 ASSERT_NE(-1, read(fd, statBuf, sizeof(statBuf)))
92 << "Could not read from " << statPath << ": " << strerror(errno);
93 close(fd);
94
95 std::string statString(statBuf);
96 EXPECT_FALSE(statString.find("iptables-restor") || statString.find("ip6tables-resto"))
97 << "Previous iptables-restore pid " << pid << " still alive: " << statString;
98 }
99
createTestChain()100 int createTestChain() {
101 mChainName = StringPrintf("netd_unit_test_%u", arc4random_uniform(10000)).c_str();
102
103 // Create a chain to list.
104 std::vector<std::string> createCommands = {
105 "*filter",
106 StringPrintf(":%s -", mChainName.c_str()),
107 StringPrintf("-A %s -j RETURN", mChainName.c_str()),
108 "COMMIT",
109 ""
110 };
111
112 int ret = con.execute(V4V6, Join(createCommands, "\n"), nullptr);
113 if (ret) mChainName = "";
114 return ret;
115 }
116
deleteTestChain()117 void deleteTestChain() {
118 std::vector<std::string> deleteCommands = {
119 "*filter",
120 StringPrintf(":%s -", mChainName.c_str()), // Flush chain (otherwise we can't delete it).
121 StringPrintf("-X %s", mChainName.c_str()), // Delete it.
122 "COMMIT",
123 ""
124 };
125 con.execute(V4V6, Join(deleteCommands, "\n"), nullptr);
126 mChainName = "";
127 }
128
acquireIptablesLock()129 int acquireIptablesLock() {
130 mIptablesLock = open(XT_LOCK_NAME, O_CREAT, 0600);
131 if (mIptablesLock == -1) return mIptablesLock;
132 int attempts;
133 for (attempts = 0; attempts < XT_LOCK_ATTEMPTS; attempts++) {
134 if (flock(mIptablesLock, LOCK_EX | LOCK_NB) == 0) {
135 return 0;
136 }
137 usleep(XT_LOCK_POLL_INTERVAL_MS * 1000);
138 }
139 EXPECT_LT(attempts, XT_LOCK_ATTEMPTS) <<
140 "Could not acquire iptables lock after " << XT_LOCK_ATTEMPTS << " attempts " <<
141 XT_LOCK_POLL_INTERVAL_MS << "ms apart";
142 return -1;
143 }
144
releaseIptablesLock()145 void releaseIptablesLock() {
146 if (mIptablesLock != -1) {
147 close(mIptablesLock);
148 }
149 }
150
setRetryParameters(int maxRetries,int pollTimeoutMs)151 void setRetryParameters(int maxRetries, int pollTimeoutMs) {
152 con.MAX_RETRIES = maxRetries;
153 con.POLL_TIMEOUT_MS = pollTimeoutMs;
154 }
155 };
156
TEST_F(IptablesRestoreControllerTest,TestBasicCommand)157 TEST_F(IptablesRestoreControllerTest, TestBasicCommand) {
158 std::string output;
159
160 EXPECT_EQ(0, con.execute(IptablesTarget::V4V6, "#Test\n", nullptr));
161
162 pid_t pid4 = getIpRestorePid(IptablesRestoreController::IPTABLES_PROCESS);
163 pid_t pid6 = getIpRestorePid(IptablesRestoreController::IP6TABLES_PROCESS);
164
165 EXPECT_EQ(0, con.execute(IptablesTarget::V6, "#Test\n", nullptr));
166 EXPECT_EQ(0, con.execute(IptablesTarget::V4, "#Test\n", nullptr));
167
168 EXPECT_EQ(0, con.execute(IptablesTarget::V4V6, "#Test\n", &output));
169 EXPECT_EQ("#Test\n#Test\n", output); // One for IPv4 and one for IPv6.
170
171 // Check the PIDs are the same as they were before. If they're not, the child processes were
172 // restarted, which causes a 30-60ms delay.
173 EXPECT_EQ(pid4, getIpRestorePid(IptablesRestoreController::IPTABLES_PROCESS));
174 EXPECT_EQ(pid6, getIpRestorePid(IptablesRestoreController::IP6TABLES_PROCESS));
175 }
176
TEST_F(IptablesRestoreControllerTest,TestRestartOnMalformedCommand)177 TEST_F(IptablesRestoreControllerTest, TestRestartOnMalformedCommand) {
178 std::string buffer;
179 for (int i = 0; i < 50; i++) {
180 IptablesTarget target = (IptablesTarget) (i % 3);
181 std::string *output = (i % 2) ? &buffer : nullptr;
182 ASSERT_EQ(-1, con.execute(target, "malformed command\n", output)) <<
183 "Malformed command did not fail at iteration " << i;
184 ASSERT_EQ(0, con.execute(target, "#Test\n", output)) <<
185 "No-op command did not succeed at iteration " << i;
186 }
187 }
188
TEST_F(IptablesRestoreControllerTest,TestRestartOnProcessDeath)189 TEST_F(IptablesRestoreControllerTest, TestRestartOnProcessDeath) {
190 std::string output;
191
192 // Run a command to ensure that the processes are running.
193 EXPECT_EQ(0, con.execute(IptablesTarget::V4V6, "#Test\n", &output));
194
195 pid_t pid4 = getIpRestorePid(IptablesRestoreController::IPTABLES_PROCESS);
196 pid_t pid6 = getIpRestorePid(IptablesRestoreController::IP6TABLES_PROCESS);
197
198 ASSERT_EQ(0, kill(pid4, 0)) << "iptables-restore pid " << pid4 << " does not exist";
199 ASSERT_EQ(0, kill(pid6, 0)) << "ip6tables-restore pid " << pid6 << " does not exist";
200 ASSERT_EQ(0, kill(pid4, SIGTERM)) << "Failed to send SIGTERM to iptables-restore pid " << pid4;
201 ASSERT_EQ(0, kill(pid6, SIGTERM)) << "Failed to send SIGTERM to ip6tables-restore pid " << pid6;
202
203 // Wait 100ms for processes to terminate.
204 TEMP_FAILURE_RETRY(usleep(100 * 1000));
205
206 // Ensure that running a new command properly restarts the processes.
207 EXPECT_EQ(0, con.execute(IptablesTarget::V4V6, "#Test\n", nullptr));
208 EXPECT_NE(pid4, getIpRestorePid(IptablesRestoreController::IPTABLES_PROCESS));
209 EXPECT_NE(pid6, getIpRestorePid(IptablesRestoreController::IP6TABLES_PROCESS));
210
211 // Check there are no zombies.
212 expectNoIptablesRestoreProcess(pid4);
213 expectNoIptablesRestoreProcess(pid6);
214 }
215
TEST_F(IptablesRestoreControllerTest,TestCommandTimeout)216 TEST_F(IptablesRestoreControllerTest, TestCommandTimeout) {
217 // Don't wait 10 seconds for this test to fail.
218 setRetryParameters(3, 50);
219
220 // Expected contents of the chain.
221 std::vector<std::string> expectedLines = {
222 StringPrintf("Chain %s (0 references)", mChainName.c_str()),
223 "target prot opt source destination ",
224 "RETURN all -- 0.0.0.0/0 0.0.0.0/0 ",
225 StringPrintf("Chain %s (0 references)", mChainName.c_str()),
226 "target prot opt source destination ",
227 "RETURN all ::/0 ::/0 ",
228 ""
229 };
230 std::string expected = Join(expectedLines, "\n");
231
232 std::vector<std::string> listCommands = {
233 "*filter",
234 StringPrintf("-n -L %s", mChainName.c_str()), // List chain.
235 "COMMIT",
236 ""
237 };
238 std::string commandString = Join(listCommands, "\n");
239 std::string output;
240
241 EXPECT_EQ(0, con.execute(IptablesTarget::V4V6, commandString, &output));
242 EXPECT_EQ(expected, output);
243
244 ASSERT_EQ(0, acquireIptablesLock());
245 EXPECT_EQ(-1, con.execute(IptablesTarget::V4V6, commandString, &output));
246 EXPECT_EQ(-1, con.execute(IptablesTarget::V4V6, commandString, &output));
247 releaseIptablesLock();
248
249 EXPECT_EQ(0, con.execute(IptablesTarget::V4V6, commandString, &output));
250 EXPECT_EQ(expected, output);
251 }
252
TEST_F(IptablesRestoreControllerTest,TestUidRuleBenchmark)253 TEST_F(IptablesRestoreControllerTest, TestUidRuleBenchmark) {
254 const std::vector<int> ITERATIONS = { 1, 5, 10 };
255
256 const std::string IPTABLES_RESTORE_ADD =
257 "*filter\n-I fw_powersave -m owner --uid-owner 2000000000 -j RETURN\nCOMMIT\n";
258 const std::string IPTABLES_RESTORE_DEL =
259 "*filter\n-D fw_powersave -m owner --uid-owner 2000000000 -j RETURN\nCOMMIT\n";
260
261 for (const int iterations : ITERATIONS) {
262 Stopwatch s;
263 for (int i = 0; i < iterations; i++) {
264 EXPECT_EQ(0, con.execute(V4V6, IPTABLES_RESTORE_ADD, nullptr));
265 EXPECT_EQ(0, con.execute(V4V6, IPTABLES_RESTORE_DEL, nullptr));
266 }
267 float timeTaken = s.getTimeAndReset();
268 fprintf(stderr, " Add/del %d UID rules via restore: %.1fms (%.2fms per operation)\n",
269 iterations, timeTaken, timeTaken / 2 / iterations);
270 }
271 }
272
TEST_F(IptablesRestoreControllerTest,TestStartup)273 TEST_F(IptablesRestoreControllerTest, TestStartup) {
274 // Tests that IptablesRestoreController::Init never sets its processes to null pointers if
275 // fork() succeeds.
276 {
277 // Mock fork(), and check that initializing 100 times never results in a null pointer.
278 constexpr int NUM_ITERATIONS = 100; // Takes 100-150ms on angler.
279 constexpr pid_t FAKE_PID = 2000000001;
280 StrictMock<ScopedMockSyscalls> sys;
281
282 EXPECT_CALL(sys, fork()).Times(NUM_ITERATIONS * 2).WillRepeatedly(Return(FAKE_PID));
283 for (int i = 0; i < NUM_ITERATIONS; i++) {
284 Init();
285 EXPECT_NE(0, getIpRestorePid(IptablesRestoreController::IPTABLES_PROCESS));
286 EXPECT_NE(0, getIpRestorePid(IptablesRestoreController::IP6TABLES_PROCESS));
287 }
288 }
289
290 // The controller is now in an invalid state: the pipes are connected to working iptables
291 // processes, but the PIDs are set to FAKE_PID. Send a malformed command to ensure that the
292 // processes terminate and close the pipes, then send a valid command to have the controller
293 // re-initialize properly now that fork() is no longer mocked.
294 EXPECT_EQ(-1, con.execute(V4V6, "malformed command\n", nullptr));
295 EXPECT_EQ(0, con.execute(V4V6, "#Test\n", nullptr));
296 }
297