blob: 96394c19f63213248c33dd7907344217d5df5c9e [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
17#include <string>
Lorenzo Colitti173da322017-02-05 01:56:40 +090018#include <fcntl.h>
Lorenzo Colitti2bd804a2017-03-10 12:19:08 +090019#include <sys/file.h>
Lorenzo Colittia701afb2017-02-28 01:47:11 +090020#include <sys/socket.h>
21#include <sys/un.h>
Narayan Kamatha5ace892017-01-06 15:10:02 +000022
23#include <gtest/gtest.h>
24
Lorenzo Colitti173da322017-02-05 01:56:40 +090025#define LOG_TAG "IptablesRestoreControllerTest"
26#include <cutils/log.h>
27#include <android-base/stringprintf.h>
Lorenzo Colitticd283772017-01-31 19:00:49 +090028#include <android-base/strings.h>
Lorenzo Colitti173da322017-02-05 01:56:40 +090029
Narayan Kamatha5ace892017-01-06 15:10:02 +000030#include "IptablesRestoreController.h"
31#include "NetdConstants.h"
32
Lorenzo Colitti2bd804a2017-03-10 12:19:08 +090033#define XT_LOCK_NAME "/system/etc/xtables.lock"
34#define XT_LOCK_ATTEMPTS 10
35#define XT_LOCK_POLL_INTERVAL_MS 100
Lorenzo Colittia701afb2017-02-28 01:47:11 +090036
Lorenzo Colitticd283772017-01-31 19:00:49 +090037using android::base::Join;
Lorenzo Colitti173da322017-02-05 01:56:40 +090038using android::base::StringPrintf;
Narayan Kamatha5ace892017-01-06 15:10:02 +000039
Lorenzo Colitti173da322017-02-05 01:56:40 +090040class IptablesRestoreControllerTest : public ::testing::Test {
41public:
42 IptablesRestoreController con;
Lorenzo Colittia701afb2017-02-28 01:47:11 +090043 int mDefaultMaxRetries = con.MAX_RETRIES;
44 int mDefaultPollTimeoutMs = con.POLL_TIMEOUT_MS;
45 int mIptablesLock = -1;
46 std::string mChainName;
47
48 void SetUp() {
49 ASSERT_EQ(0, createTestChain());
50 }
51
52 void TearDown() {
53 con.MAX_RETRIES = mDefaultMaxRetries;
54 con.POLL_TIMEOUT_MS = mDefaultPollTimeoutMs;
55 deleteTestChain();
56 }
Lorenzo Colitti173da322017-02-05 01:56:40 +090057
58 pid_t getIpRestorePid(const IptablesRestoreController::IptablesProcessType type) {
59 return con.getIpRestorePid(type);
60 };
61
62 void expectNoIptablesRestoreProcess(pid_t pid) {
63 // We can't readlink /proc/PID/exe, because zombie processes don't have it.
64 // Parse /proc/PID/stat instead.
65 std::string statPath = StringPrintf("/proc/%d/stat", pid);
66 int fd = open(statPath.c_str(), O_RDONLY);
67 if (fd == -1) {
68 // ENOENT means the process is gone (expected).
69 ASSERT_EQ(errno, ENOENT)
70 << "Unexpected error opening " << statPath << ": " << strerror(errno);
71 return;
72 }
73
74 // If the PID exists, it's possible (though very unlikely) that the PID was reused. Check the
75 // binary name as well, to ensure the test isn't flaky.
76 char statBuf[1024];
77 ASSERT_NE(-1, read(fd, statBuf, sizeof(statBuf)))
78 << "Could not read from " << statPath << ": " << strerror(errno);
79 close(fd);
80
81 std::string statString(statBuf);
82 EXPECT_FALSE(statString.find("iptables-restor") || statString.find("ip6tables-resto"))
83 << "Previous iptables-restore pid " << pid << " still alive: " << statString;
84 }
Lorenzo Colittia701afb2017-02-28 01:47:11 +090085
86 int createTestChain() {
87 mChainName = StringPrintf("netd_unit_test_%u", arc4random_uniform(10000)).c_str();
88
89 // Create a chain to list.
90 std::vector<std::string> createCommands = {
91 "*filter",
92 StringPrintf(":%s -", mChainName.c_str()),
93 StringPrintf("-A %s -j RETURN", mChainName.c_str()),
94 "COMMIT",
95 ""
96 };
97
98 int ret = con.execute(V4V6, Join(createCommands, "\n"), nullptr);
99 if (ret) mChainName = "";
100 return ret;
101 }
102
103 void deleteTestChain() {
104 std::vector<std::string> deleteCommands = {
105 "*filter",
106 StringPrintf(":%s -", mChainName.c_str()), // Flush chain (otherwise we can't delete it).
107 StringPrintf("-X %s", mChainName.c_str()), // Delete it.
108 "COMMIT",
109 ""
110 };
111 con.execute(V4V6, Join(deleteCommands, "\n"), nullptr);
112 mChainName = "";
113 }
114
115 int acquireIptablesLock() {
Lorenzo Colitti2bd804a2017-03-10 12:19:08 +0900116 mIptablesLock = open(XT_LOCK_NAME, O_CREAT, 0600);
117 if (mIptablesLock == -1) return mIptablesLock;
118 int attempts;
119 for (attempts = 0; attempts < XT_LOCK_ATTEMPTS; attempts++) {
120 if (flock(mIptablesLock, LOCK_EX | LOCK_NB) == 0) {
121 return 0;
122 }
123 usleep(XT_LOCK_POLL_INTERVAL_MS * 1000);
Lorenzo Colittia701afb2017-02-28 01:47:11 +0900124 }
Lorenzo Colitti2bd804a2017-03-10 12:19:08 +0900125 EXPECT_LT(attempts, XT_LOCK_ATTEMPTS) <<
126 "Could not acquire iptables lock after " << XT_LOCK_ATTEMPTS << " attempts " <<
127 XT_LOCK_POLL_INTERVAL_MS << "ms apart";
128 return -1;
Lorenzo Colittia701afb2017-02-28 01:47:11 +0900129 }
130
131 void releaseIptablesLock() {
132 if (mIptablesLock != -1) {
133 close(mIptablesLock);
134 }
135 }
136
137 void setRetryParameters(int maxRetries, int pollTimeoutMs) {
138 con.MAX_RETRIES = maxRetries;
139 con.POLL_TIMEOUT_MS = pollTimeoutMs;
140 }
Narayan Kamatha5ace892017-01-06 15:10:02 +0000141};
142
Lorenzo Colitti173da322017-02-05 01:56:40 +0900143TEST_F(IptablesRestoreControllerTest, TestBasicCommand) {
Lorenzo Colitticd283772017-01-31 19:00:49 +0900144 std::string output;
145
146 EXPECT_EQ(0, con.execute(IptablesTarget::V4V6, "#Test\n", nullptr));
Lorenzo Colitti173da322017-02-05 01:56:40 +0900147
148 pid_t pid4 = getIpRestorePid(IptablesRestoreController::IPTABLES_PROCESS);
149 pid_t pid6 = getIpRestorePid(IptablesRestoreController::IP6TABLES_PROCESS);
150
Lorenzo Colitticd283772017-01-31 19:00:49 +0900151 EXPECT_EQ(0, con.execute(IptablesTarget::V6, "#Test\n", nullptr));
152 EXPECT_EQ(0, con.execute(IptablesTarget::V4, "#Test\n", nullptr));
153
154 EXPECT_EQ(0, con.execute(IptablesTarget::V4V6, "#Test\n", &output));
155 EXPECT_EQ("#Test\n#Test\n", output); // One for IPv4 and one for IPv6.
Lorenzo Colitti173da322017-02-05 01:56:40 +0900156
157 // Check the PIDs are the same as they were before. If they're not, the child processes were
158 // restarted, which causes a 30-60ms delay.
159 EXPECT_EQ(pid4, getIpRestorePid(IptablesRestoreController::IPTABLES_PROCESS));
160 EXPECT_EQ(pid6, getIpRestorePid(IptablesRestoreController::IP6TABLES_PROCESS));
Narayan Kamatha5ace892017-01-06 15:10:02 +0000161}
162
Lorenzo Colitti173da322017-02-05 01:56:40 +0900163TEST_F(IptablesRestoreControllerTest, TestRestartOnMalformedCommand) {
Lorenzo Colitticd283772017-01-31 19:00:49 +0900164 std::string buffer;
Lorenzo Colitti173da322017-02-05 01:56:40 +0900165 for (int i = 0; i < 50; i++) {
166 IptablesTarget target = (IptablesTarget) (i % 3);
Lorenzo Colitticd283772017-01-31 19:00:49 +0900167 std::string *output = (i % 2) ? &buffer : nullptr;
168 ASSERT_EQ(-1, con.execute(target, "malformed command\n", output)) <<
Lorenzo Colitti173da322017-02-05 01:56:40 +0900169 "Malformed command did not fail at iteration " << i;
Lorenzo Colitticd283772017-01-31 19:00:49 +0900170 ASSERT_EQ(0, con.execute(target, "#Test\n", output)) <<
Lorenzo Colitti173da322017-02-05 01:56:40 +0900171 "No-op command did not succeed at iteration " << i;
172 }
173}
174
175TEST_F(IptablesRestoreControllerTest, TestRestartOnProcessDeath) {
Lorenzo Colitticd283772017-01-31 19:00:49 +0900176 std::string output;
177
Lorenzo Colitti173da322017-02-05 01:56:40 +0900178 // Run a command to ensure that the processes are running.
Lorenzo Colitticd283772017-01-31 19:00:49 +0900179 EXPECT_EQ(0, con.execute(IptablesTarget::V4V6, "#Test\n", &output));
Lorenzo Colitti173da322017-02-05 01:56:40 +0900180
181 pid_t pid4 = getIpRestorePid(IptablesRestoreController::IPTABLES_PROCESS);
182 pid_t pid6 = getIpRestorePid(IptablesRestoreController::IP6TABLES_PROCESS);
183
184 ASSERT_EQ(0, kill(pid4, 0)) << "iptables-restore pid " << pid4 << " does not exist";
185 ASSERT_EQ(0, kill(pid6, 0)) << "ip6tables-restore pid " << pid6 << " does not exist";
186 ASSERT_EQ(0, kill(pid4, SIGTERM)) << "Failed to send SIGTERM to iptables-restore pid " << pid4;
187 ASSERT_EQ(0, kill(pid6, SIGTERM)) << "Failed to send SIGTERM to ip6tables-restore pid " << pid6;
188
189 // Wait 100ms for processes to terminate.
190 TEMP_FAILURE_RETRY(usleep(100 * 1000));
191
192 // Ensure that running a new command properly restarts the processes.
Lorenzo Colitticd283772017-01-31 19:00:49 +0900193 EXPECT_EQ(0, con.execute(IptablesTarget::V4V6, "#Test\n", nullptr));
Lorenzo Colitti173da322017-02-05 01:56:40 +0900194 EXPECT_NE(pid4, getIpRestorePid(IptablesRestoreController::IPTABLES_PROCESS));
195 EXPECT_NE(pid6, getIpRestorePid(IptablesRestoreController::IP6TABLES_PROCESS));
196
197 // Check there are no zombies.
198 expectNoIptablesRestoreProcess(pid4);
199 expectNoIptablesRestoreProcess(pid6);
Narayan Kamatha5ace892017-01-06 15:10:02 +0000200}
Lorenzo Colitticd283772017-01-31 19:00:49 +0900201
Lorenzo Colittia701afb2017-02-28 01:47:11 +0900202TEST_F(IptablesRestoreControllerTest, TestCommandTimeout) {
203 // Don't wait 10 seconds for this test to fail.
204 setRetryParameters(3, 50);
Lorenzo Colitticd283772017-01-31 19:00:49 +0900205
206 // Expected contents of the chain.
207 std::vector<std::string> expectedLines = {
Lorenzo Colittia701afb2017-02-28 01:47:11 +0900208 StringPrintf("Chain %s (0 references)", mChainName.c_str()),
Lorenzo Colitticd283772017-01-31 19:00:49 +0900209 "target prot opt source destination ",
210 "RETURN all -- 0.0.0.0/0 0.0.0.0/0 ",
Lorenzo Colittia701afb2017-02-28 01:47:11 +0900211 StringPrintf("Chain %s (0 references)", mChainName.c_str()),
Lorenzo Colitticd283772017-01-31 19:00:49 +0900212 "target prot opt source destination ",
213 "RETURN all ::/0 ::/0 ",
214 ""
215 };
216 std::string expected = Join(expectedLines, "\n");
217
Lorenzo Colitticd283772017-01-31 19:00:49 +0900218 std::vector<std::string> listCommands = {
219 "*filter",
Lorenzo Colittia701afb2017-02-28 01:47:11 +0900220 StringPrintf("-n -L %s", mChainName.c_str()), // List chain.
Lorenzo Colitticd283772017-01-31 19:00:49 +0900221 "COMMIT",
222 ""
223 };
Lorenzo Colittia701afb2017-02-28 01:47:11 +0900224 std::string commandString = Join(listCommands, "\n");
Lorenzo Colitticd283772017-01-31 19:00:49 +0900225 std::string output;
Lorenzo Colittia701afb2017-02-28 01:47:11 +0900226
227 EXPECT_EQ(0, con.execute(IptablesTarget::V4V6, commandString, &output));
228 EXPECT_EQ(expected, output);
229
230 ASSERT_EQ(0, acquireIptablesLock());
231 EXPECT_EQ(-1, con.execute(IptablesTarget::V4V6, commandString, &output));
232 EXPECT_EQ(-1, con.execute(IptablesTarget::V4V6, commandString, &output));
233 releaseIptablesLock();
234
235 EXPECT_EQ(0, con.execute(IptablesTarget::V4V6, commandString, &output));
Lorenzo Colitticd283772017-01-31 19:00:49 +0900236 EXPECT_EQ(expected, output);
237}