blob: 4f33c1603a0aa3805552903ef3138dd5509c230b [file] [log] [blame]
Wayne Ma4d692332022-01-19 16:04:04 +08001/*
Wayne Ma7be6bce2022-01-12 16:29:49 +08002 * Copyright 2022 The Android Open Source Project
Wayne Ma4d692332022-01-19 16:04:04 +08003 *
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 * TrafficControllerTest.cpp - unit tests for TrafficController.cpp
17 */
18
19#include <cstdint>
20#include <string>
21#include <vector>
22
23#include <fcntl.h>
24#include <inttypes.h>
25#include <linux/inet_diag.h>
26#include <linux/sock_diag.h>
27#include <sys/socket.h>
28#include <sys/types.h>
29#include <unistd.h>
30
31#include <gtest/gtest.h>
32
Ken Chen2fb86362022-06-05 11:39:38 +080033#include <android-base/file.h>
Wayne Ma4d692332022-01-19 16:04:04 +080034#include <android-base/stringprintf.h>
35#include <android-base/strings.h>
Wayne Ma7be6bce2022-01-12 16:29:49 +080036#include <binder/Status.h>
Wayne Ma4d692332022-01-19 16:04:04 +080037
38#include <netdutils/MockSyscalls.h>
39
Maciej Żenczykowski439bac22022-05-31 03:22:32 -070040#define TEST_BPF_MAP
Wayne Ma4d692332022-01-19 16:04:04 +080041#include "TrafficController.h"
42#include "bpf/BpfUtils.h"
Patrick Rohr61e94672022-02-01 21:06:40 +010043#include "NetdUpdatablePublic.h"
Wayne Ma4d692332022-01-19 16:04:04 +080044
45using namespace android::bpf; // NOLINT(google-build-using-namespace): grandfathered
46
47namespace android {
48namespace net {
49
Wayne Ma7be6bce2022-01-12 16:29:49 +080050using android::netdutils::Status;
Wayne Ma4d692332022-01-19 16:04:04 +080051using base::Result;
52using netdutils::isOk;
Ken Chen2fb86362022-06-05 11:39:38 +080053using netdutils::statusFromErrno;
Wayne Ma4d692332022-01-19 16:04:04 +080054
55constexpr int TEST_MAP_SIZE = 10;
Wayne Ma4d692332022-01-19 16:04:04 +080056constexpr uid_t TEST_UID = 10086;
57constexpr uid_t TEST_UID2 = 54321;
58constexpr uid_t TEST_UID3 = 98765;
59constexpr uint32_t TEST_TAG = 42;
60constexpr uint32_t TEST_COUNTERSET = 1;
Wayne Ma4d692332022-01-19 16:04:04 +080061
62#define ASSERT_VALID(x) ASSERT_TRUE((x).isValid())
63
64class TrafficControllerTest : public ::testing::Test {
65 protected:
Wayne Ma92d80792022-01-20 13:20:34 +080066 TrafficControllerTest() {}
Wayne Ma4d692332022-01-19 16:04:04 +080067 TrafficController mTc;
68 BpfMap<uint64_t, UidTagValue> mFakeCookieTagMap;
Wayne Ma4d692332022-01-19 16:04:04 +080069 BpfMap<uint32_t, StatsValue> mFakeAppUidStatsMap;
70 BpfMap<StatsKey, StatsValue> mFakeStatsMapA;
Lorenzo Colitti60cbed32022-03-03 17:49:01 +090071 BpfMap<uint32_t, uint32_t> mFakeConfigurationMap;
Wayne Ma4d692332022-01-19 16:04:04 +080072 BpfMap<uint32_t, UidOwnerValue> mFakeUidOwnerMap;
73 BpfMap<uint32_t, uint8_t> mFakeUidPermissionMap;
74
75 void SetUp() {
76 std::lock_guard guard(mTc.mMutex);
77 ASSERT_EQ(0, setrlimitForTest());
78
Maciej Żenczykowski439bac22022-05-31 03:22:32 -070079 mFakeCookieTagMap.resetMap(BPF_MAP_TYPE_HASH, TEST_MAP_SIZE);
Wayne Ma4d692332022-01-19 16:04:04 +080080 ASSERT_VALID(mFakeCookieTagMap);
81
Maciej Żenczykowski439bac22022-05-31 03:22:32 -070082 mFakeAppUidStatsMap.resetMap(BPF_MAP_TYPE_HASH, TEST_MAP_SIZE);
Wayne Ma4d692332022-01-19 16:04:04 +080083 ASSERT_VALID(mFakeAppUidStatsMap);
84
Maciej Żenczykowski439bac22022-05-31 03:22:32 -070085 mFakeStatsMapA.resetMap(BPF_MAP_TYPE_HASH, TEST_MAP_SIZE);
Wayne Ma4d692332022-01-19 16:04:04 +080086 ASSERT_VALID(mFakeStatsMapA);
87
Maciej Żenczykowski439bac22022-05-31 03:22:32 -070088 mFakeConfigurationMap.resetMap(BPF_MAP_TYPE_HASH, 1);
Wayne Ma4d692332022-01-19 16:04:04 +080089 ASSERT_VALID(mFakeConfigurationMap);
90
Maciej Żenczykowski439bac22022-05-31 03:22:32 -070091 mFakeUidOwnerMap.resetMap(BPF_MAP_TYPE_HASH, TEST_MAP_SIZE);
Wayne Ma4d692332022-01-19 16:04:04 +080092 ASSERT_VALID(mFakeUidOwnerMap);
Maciej Żenczykowski439bac22022-05-31 03:22:32 -070093 mFakeUidPermissionMap.resetMap(BPF_MAP_TYPE_HASH, TEST_MAP_SIZE);
Wayne Ma4d692332022-01-19 16:04:04 +080094 ASSERT_VALID(mFakeUidPermissionMap);
95
Maciej Żenczykowski55ab87a2022-05-31 03:15:12 -070096 mTc.mCookieTagMap = mFakeCookieTagMap;
Wayne Ma4d692332022-01-19 16:04:04 +080097 ASSERT_VALID(mTc.mCookieTagMap);
Maciej Żenczykowski55ab87a2022-05-31 03:15:12 -070098 mTc.mAppUidStatsMap = mFakeAppUidStatsMap;
Wayne Ma4d692332022-01-19 16:04:04 +080099 ASSERT_VALID(mTc.mAppUidStatsMap);
Maciej Żenczykowski55ab87a2022-05-31 03:15:12 -0700100 mTc.mStatsMapA = mFakeStatsMapA;
Wayne Ma4d692332022-01-19 16:04:04 +0800101 ASSERT_VALID(mTc.mStatsMapA);
Maciej Żenczykowski55ab87a2022-05-31 03:15:12 -0700102 mTc.mConfigurationMap = mFakeConfigurationMap;
Wayne Ma4d692332022-01-19 16:04:04 +0800103 ASSERT_VALID(mTc.mConfigurationMap);
104
105 // Always write to stats map A by default.
106 ASSERT_RESULT_OK(mTc.mConfigurationMap.writeValue(CURRENT_STATS_MAP_CONFIGURATION_KEY,
107 SELECT_MAP_A, BPF_ANY));
Maciej Żenczykowski55ab87a2022-05-31 03:15:12 -0700108 mTc.mUidOwnerMap = mFakeUidOwnerMap;
Wayne Ma4d692332022-01-19 16:04:04 +0800109 ASSERT_VALID(mTc.mUidOwnerMap);
Maciej Żenczykowski55ab87a2022-05-31 03:15:12 -0700110 mTc.mUidPermissionMap = mFakeUidPermissionMap;
Wayne Ma4d692332022-01-19 16:04:04 +0800111 ASSERT_VALID(mTc.mUidPermissionMap);
112 mTc.mPrivilegedUser.clear();
113 }
114
Wayne Ma4d692332022-01-19 16:04:04 +0800115 void populateFakeStats(uint64_t cookie, uint32_t uid, uint32_t tag, StatsKey* key) {
116 UidTagValue cookieMapkey = {.uid = (uint32_t)uid, .tag = tag};
117 EXPECT_RESULT_OK(mFakeCookieTagMap.writeValue(cookie, cookieMapkey, BPF_ANY));
118 *key = {.uid = uid, .tag = tag, .counterSet = TEST_COUNTERSET, .ifaceIndex = 1};
119 StatsValue statsMapValue = {.rxPackets = 1, .rxBytes = 100};
Wayne Ma4d692332022-01-19 16:04:04 +0800120 EXPECT_RESULT_OK(mFakeStatsMapA.writeValue(*key, statsMapValue, BPF_ANY));
121 key->tag = 0;
122 EXPECT_RESULT_OK(mFakeStatsMapA.writeValue(*key, statsMapValue, BPF_ANY));
123 EXPECT_RESULT_OK(mFakeAppUidStatsMap.writeValue(uid, statsMapValue, BPF_ANY));
124 // put tag information back to statsKey
125 key->tag = tag;
126 }
127
128 void checkUidOwnerRuleForChain(ChildChain chain, UidOwnerMatchType match) {
129 uint32_t uid = TEST_UID;
130 EXPECT_EQ(0, mTc.changeUidOwnerRule(chain, uid, DENY, DENYLIST));
131 Result<UidOwnerValue> value = mFakeUidOwnerMap.readValue(uid);
132 EXPECT_RESULT_OK(value);
133 EXPECT_TRUE(value.value().rule & match);
134
135 uid = TEST_UID2;
136 EXPECT_EQ(0, mTc.changeUidOwnerRule(chain, uid, ALLOW, ALLOWLIST));
137 value = mFakeUidOwnerMap.readValue(uid);
138 EXPECT_RESULT_OK(value);
139 EXPECT_TRUE(value.value().rule & match);
140
141 EXPECT_EQ(0, mTc.changeUidOwnerRule(chain, uid, DENY, ALLOWLIST));
142 value = mFakeUidOwnerMap.readValue(uid);
143 EXPECT_FALSE(value.ok());
144 EXPECT_EQ(ENOENT, value.error().code());
145
146 uid = TEST_UID;
147 EXPECT_EQ(0, mTc.changeUidOwnerRule(chain, uid, ALLOW, DENYLIST));
148 value = mFakeUidOwnerMap.readValue(uid);
149 EXPECT_FALSE(value.ok());
150 EXPECT_EQ(ENOENT, value.error().code());
151
152 uid = TEST_UID3;
153 EXPECT_EQ(-ENOENT, mTc.changeUidOwnerRule(chain, uid, ALLOW, DENYLIST));
154 value = mFakeUidOwnerMap.readValue(uid);
155 EXPECT_FALSE(value.ok());
156 EXPECT_EQ(ENOENT, value.error().code());
157 }
158
159 void checkEachUidValue(const std::vector<int32_t>& uids, UidOwnerMatchType match) {
160 for (uint32_t uid : uids) {
161 Result<UidOwnerValue> value = mFakeUidOwnerMap.readValue(uid);
162 EXPECT_RESULT_OK(value);
163 EXPECT_TRUE(value.value().rule & match);
164 }
165 std::set<uint32_t> uidSet(uids.begin(), uids.end());
166 const auto checkNoOtherUid = [&uidSet](const int32_t& key,
167 const BpfMap<uint32_t, UidOwnerValue>&) {
168 EXPECT_NE(uidSet.end(), uidSet.find(key));
169 return Result<void>();
170 };
171 EXPECT_RESULT_OK(mFakeUidOwnerMap.iterate(checkNoOtherUid));
172 }
173
174 void checkUidMapReplace(const std::string& name, const std::vector<int32_t>& uids,
175 UidOwnerMatchType match) {
176 bool isAllowlist = true;
177 EXPECT_EQ(0, mTc.replaceUidOwnerMap(name, isAllowlist, uids));
178 checkEachUidValue(uids, match);
179
180 isAllowlist = false;
181 EXPECT_EQ(0, mTc.replaceUidOwnerMap(name, isAllowlist, uids));
182 checkEachUidValue(uids, match);
183 }
184
185 void expectUidOwnerMapValues(const std::vector<uint32_t>& appUids, uint8_t expectedRule,
186 uint32_t expectedIif) {
187 for (uint32_t uid : appUids) {
188 Result<UidOwnerValue> value = mFakeUidOwnerMap.readValue(uid);
189 EXPECT_RESULT_OK(value);
190 EXPECT_EQ(expectedRule, value.value().rule)
191 << "Expected rule for UID " << uid << " to be " << expectedRule << ", but was "
192 << value.value().rule;
193 EXPECT_EQ(expectedIif, value.value().iif)
194 << "Expected iif for UID " << uid << " to be " << expectedIif << ", but was "
195 << value.value().iif;
196 }
197 }
198
199 template <class Key, class Value>
200 void expectMapEmpty(BpfMap<Key, Value>& map) {
201 auto isEmpty = map.isEmpty();
202 EXPECT_RESULT_OK(isEmpty);
203 EXPECT_TRUE(isEmpty.value());
204 }
205
206 void expectUidPermissionMapValues(const std::vector<uid_t>& appUids, uint8_t expectedValue) {
207 for (uid_t uid : appUids) {
208 Result<uint8_t> value = mFakeUidPermissionMap.readValue(uid);
209 EXPECT_RESULT_OK(value);
210 EXPECT_EQ(expectedValue, value.value())
211 << "Expected value for UID " << uid << " to be " << expectedValue
212 << ", but was " << value.value();
213 }
214 }
215
216 void expectPrivilegedUserSet(const std::vector<uid_t>& appUids) {
217 std::lock_guard guard(mTc.mMutex);
218 EXPECT_EQ(appUids.size(), mTc.mPrivilegedUser.size());
219 for (uid_t uid : appUids) {
220 EXPECT_NE(mTc.mPrivilegedUser.end(), mTc.mPrivilegedUser.find(uid));
221 }
222 }
223
224 void expectPrivilegedUserSetEmpty() {
225 std::lock_guard guard(mTc.mMutex);
226 EXPECT_TRUE(mTc.mPrivilegedUser.empty());
227 }
228
229 void addPrivilegedUid(uid_t uid) {
230 std::vector privilegedUid = {uid};
231 mTc.setPermissionForUids(INetd::PERMISSION_UPDATE_DEVICE_STATS, privilegedUid);
232 }
233
234 void removePrivilegedUid(uid_t uid) {
235 std::vector privilegedUid = {uid};
236 mTc.setPermissionForUids(INetd::PERMISSION_NONE, privilegedUid);
237 }
238
239 void expectFakeStatsUnchanged(uint64_t cookie, uint32_t tag, uint32_t uid,
240 StatsKey tagStatsMapKey) {
241 Result<UidTagValue> cookieMapResult = mFakeCookieTagMap.readValue(cookie);
242 EXPECT_RESULT_OK(cookieMapResult);
243 EXPECT_EQ(uid, cookieMapResult.value().uid);
244 EXPECT_EQ(tag, cookieMapResult.value().tag);
Wayne Ma4d692332022-01-19 16:04:04 +0800245 Result<StatsValue> statsMapResult = mFakeStatsMapA.readValue(tagStatsMapKey);
246 EXPECT_RESULT_OK(statsMapResult);
247 EXPECT_EQ((uint64_t)1, statsMapResult.value().rxPackets);
248 EXPECT_EQ((uint64_t)100, statsMapResult.value().rxBytes);
249 tagStatsMapKey.tag = 0;
250 statsMapResult = mFakeStatsMapA.readValue(tagStatsMapKey);
251 EXPECT_RESULT_OK(statsMapResult);
252 EXPECT_EQ((uint64_t)1, statsMapResult.value().rxPackets);
253 EXPECT_EQ((uint64_t)100, statsMapResult.value().rxBytes);
254 auto appStatsResult = mFakeAppUidStatsMap.readValue(uid);
255 EXPECT_RESULT_OK(appStatsResult);
256 EXPECT_EQ((uint64_t)1, appStatsResult.value().rxPackets);
257 EXPECT_EQ((uint64_t)100, appStatsResult.value().rxBytes);
258 }
Wayne Ma7be6bce2022-01-12 16:29:49 +0800259
260 Status updateUidOwnerMaps(const std::vector<uint32_t>& appUids,
261 UidOwnerMatchType matchType, TrafficController::IptOp op) {
262 Status ret(0);
263 for (auto uid : appUids) {
264 ret = mTc.updateUidOwnerMap(uid, matchType, op);
265 if(!isOk(ret)) break;
266 }
267 return ret;
268 }
269
Ken Chen2fb86362022-06-05 11:39:38 +0800270 Status dump(bool verbose, std::vector<std::string>& outputLines) {
271 if (!outputLines.empty()) return statusFromErrno(EUCLEAN, "Output buffer is not empty");
272
273 android::base::unique_fd localFd, remoteFd;
274 if (!Pipe(&localFd, &remoteFd)) return statusFromErrno(errno, "Failed on pipe");
275
276 // dump() blocks until another thread has consumed all its output.
277 std::thread dumpThread =
278 std::thread([this, remoteFd{std::move(remoteFd)}, verbose]() {
279 mTc.dump(remoteFd, verbose);
280 });
281
282 std::string dumpContent;
283 if (!android::base::ReadFdToString(localFd.get(), &dumpContent)) {
284 return statusFromErrno(errno, "Failed to read dump results from fd");
285 }
286 dumpThread.join();
287
288 std::stringstream dumpStream(std::move(dumpContent));
289 std::string line;
290 while (std::getline(dumpStream, line)) {
291 outputLines.push_back(line);
292 }
293
294 return netdutils::status::ok;
295 }
296
297 // Strings in the |expect| must exist in dump results in order. But no need to be consecutive.
298 bool expectDumpsysContains(std::vector<std::string>& expect) {
299 if (expect.empty()) return false;
300
301 std::vector<std::string> output;
302 Status result = dump(true, output);
303 if (!isOk(result)) {
304 GTEST_LOG_(ERROR) << "TrafficController dump failed: " << netdutils::toString(result);
305 return false;
306 }
307
308 int matched = 0;
309 auto it = expect.begin();
310 for (const auto& line : output) {
311 if (it == expect.end()) break;
312 if (std::string::npos != line.find(*it)) {
313 matched++;
314 ++it;
315 }
316 }
317 return matched == expect.size();
318 }
Wayne Ma4d692332022-01-19 16:04:04 +0800319};
320
Wayne Ma4d692332022-01-19 16:04:04 +0800321TEST_F(TrafficControllerTest, TestUpdateOwnerMapEntry) {
322 uint32_t uid = TEST_UID;
323 ASSERT_TRUE(isOk(mTc.updateOwnerMapEntry(STANDBY_MATCH, uid, DENY, DENYLIST)));
324 Result<UidOwnerValue> value = mFakeUidOwnerMap.readValue(uid);
325 ASSERT_RESULT_OK(value);
326 ASSERT_TRUE(value.value().rule & STANDBY_MATCH);
327
328 ASSERT_TRUE(isOk(mTc.updateOwnerMapEntry(DOZABLE_MATCH, uid, ALLOW, ALLOWLIST)));
329 value = mFakeUidOwnerMap.readValue(uid);
330 ASSERT_RESULT_OK(value);
331 ASSERT_TRUE(value.value().rule & DOZABLE_MATCH);
332
333 ASSERT_TRUE(isOk(mTc.updateOwnerMapEntry(DOZABLE_MATCH, uid, DENY, ALLOWLIST)));
334 value = mFakeUidOwnerMap.readValue(uid);
335 ASSERT_RESULT_OK(value);
336 ASSERT_FALSE(value.value().rule & DOZABLE_MATCH);
337
338 ASSERT_TRUE(isOk(mTc.updateOwnerMapEntry(STANDBY_MATCH, uid, ALLOW, DENYLIST)));
339 ASSERT_FALSE(mFakeUidOwnerMap.readValue(uid).ok());
340
341 uid = TEST_UID2;
342 ASSERT_FALSE(isOk(mTc.updateOwnerMapEntry(STANDBY_MATCH, uid, ALLOW, DENYLIST)));
343 ASSERT_FALSE(mFakeUidOwnerMap.readValue(uid).ok());
344}
345
346TEST_F(TrafficControllerTest, TestChangeUidOwnerRule) {
347 checkUidOwnerRuleForChain(DOZABLE, DOZABLE_MATCH);
348 checkUidOwnerRuleForChain(STANDBY, STANDBY_MATCH);
349 checkUidOwnerRuleForChain(POWERSAVE, POWERSAVE_MATCH);
350 checkUidOwnerRuleForChain(RESTRICTED, RESTRICTED_MATCH);
Robert Horvathd945bf02022-01-27 19:55:16 +0100351 checkUidOwnerRuleForChain(LOW_POWER_STANDBY, LOW_POWER_STANDBY_MATCH);
Motomu Utsumib08654c2022-05-11 05:56:26 +0000352 checkUidOwnerRuleForChain(LOCKDOWN, LOCKDOWN_VPN_MATCH);
Motomu Utsumid9801492022-06-01 13:57:27 +0000353 checkUidOwnerRuleForChain(OEM_DENY_1, OEM_DENY_1_MATCH);
354 checkUidOwnerRuleForChain(OEM_DENY_2, OEM_DENY_2_MATCH);
Wayne Ma4d692332022-01-19 16:04:04 +0800355 ASSERT_EQ(-EINVAL, mTc.changeUidOwnerRule(NONE, TEST_UID, ALLOW, ALLOWLIST));
356 ASSERT_EQ(-EINVAL, mTc.changeUidOwnerRule(INVALID_CHAIN, TEST_UID, ALLOW, ALLOWLIST));
357}
358
359TEST_F(TrafficControllerTest, TestReplaceUidOwnerMap) {
360 std::vector<int32_t> uids = {TEST_UID, TEST_UID2, TEST_UID3};
361 checkUidMapReplace("fw_dozable", uids, DOZABLE_MATCH);
362 checkUidMapReplace("fw_standby", uids, STANDBY_MATCH);
363 checkUidMapReplace("fw_powersave", uids, POWERSAVE_MATCH);
364 checkUidMapReplace("fw_restricted", uids, RESTRICTED_MATCH);
Robert Horvathd945bf02022-01-27 19:55:16 +0100365 checkUidMapReplace("fw_low_power_standby", uids, LOW_POWER_STANDBY_MATCH);
Motomu Utsumid9801492022-06-01 13:57:27 +0000366 checkUidMapReplace("fw_oem_deny_1", uids, OEM_DENY_1_MATCH);
367 checkUidMapReplace("fw_oem_deny_2", uids, OEM_DENY_2_MATCH);
Wayne Ma4d692332022-01-19 16:04:04 +0800368 ASSERT_EQ(-EINVAL, mTc.replaceUidOwnerMap("unknow", true, uids));
369}
370
371TEST_F(TrafficControllerTest, TestReplaceSameChain) {
372 std::vector<int32_t> uids = {TEST_UID, TEST_UID2, TEST_UID3};
373 checkUidMapReplace("fw_dozable", uids, DOZABLE_MATCH);
374 std::vector<int32_t> newUids = {TEST_UID2, TEST_UID3};
375 checkUidMapReplace("fw_dozable", newUids, DOZABLE_MATCH);
376}
377
378TEST_F(TrafficControllerTest, TestDenylistUidMatch) {
379 std::vector<uint32_t> appUids = {1000, 1001, 10012};
Wayne Ma7be6bce2022-01-12 16:29:49 +0800380 ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, PENALTY_BOX_MATCH,
381 TrafficController::IptOpInsert)));
Wayne Ma4d692332022-01-19 16:04:04 +0800382 expectUidOwnerMapValues(appUids, PENALTY_BOX_MATCH, 0);
Wayne Ma7be6bce2022-01-12 16:29:49 +0800383 ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, PENALTY_BOX_MATCH,
384 TrafficController::IptOpDelete)));
Wayne Ma4d692332022-01-19 16:04:04 +0800385 expectMapEmpty(mFakeUidOwnerMap);
386}
387
388TEST_F(TrafficControllerTest, TestAllowlistUidMatch) {
389 std::vector<uint32_t> appUids = {1000, 1001, 10012};
Wayne Ma7be6bce2022-01-12 16:29:49 +0800390 ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, HAPPY_BOX_MATCH, TrafficController::IptOpInsert)));
Wayne Ma4d692332022-01-19 16:04:04 +0800391 expectUidOwnerMapValues(appUids, HAPPY_BOX_MATCH, 0);
Wayne Ma7be6bce2022-01-12 16:29:49 +0800392 ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, HAPPY_BOX_MATCH, TrafficController::IptOpDelete)));
Wayne Ma4d692332022-01-19 16:04:04 +0800393 expectMapEmpty(mFakeUidOwnerMap);
394}
395
396TEST_F(TrafficControllerTest, TestReplaceMatchUid) {
397 std::vector<uint32_t> appUids = {1000, 1001, 10012};
398 // Add appUids to the denylist and expect that their values are all PENALTY_BOX_MATCH.
Wayne Ma7be6bce2022-01-12 16:29:49 +0800399 ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, PENALTY_BOX_MATCH,
400 TrafficController::IptOpInsert)));
Wayne Ma4d692332022-01-19 16:04:04 +0800401 expectUidOwnerMapValues(appUids, PENALTY_BOX_MATCH, 0);
402
403 // Add the same UIDs to the allowlist and expect that we get PENALTY_BOX_MATCH |
404 // HAPPY_BOX_MATCH.
Wayne Ma7be6bce2022-01-12 16:29:49 +0800405 ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, HAPPY_BOX_MATCH, TrafficController::IptOpInsert)));
Wayne Ma4d692332022-01-19 16:04:04 +0800406 expectUidOwnerMapValues(appUids, HAPPY_BOX_MATCH | PENALTY_BOX_MATCH, 0);
407
408 // Remove the same UIDs from the allowlist and check the PENALTY_BOX_MATCH is still there.
Wayne Ma7be6bce2022-01-12 16:29:49 +0800409 ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, HAPPY_BOX_MATCH, TrafficController::IptOpDelete)));
Wayne Ma4d692332022-01-19 16:04:04 +0800410 expectUidOwnerMapValues(appUids, PENALTY_BOX_MATCH, 0);
411
412 // Remove the same UIDs from the denylist and check the map is empty.
Wayne Ma7be6bce2022-01-12 16:29:49 +0800413 ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, PENALTY_BOX_MATCH,
414 TrafficController::IptOpDelete)));
Wayne Ma4d692332022-01-19 16:04:04 +0800415 ASSERT_FALSE(mFakeUidOwnerMap.getFirstKey().ok());
416}
417
418TEST_F(TrafficControllerTest, TestDeleteWrongMatchSilentlyFails) {
419 std::vector<uint32_t> appUids = {1000, 1001, 10012};
420 // If the uid does not exist in the map, trying to delete a rule about it will fail.
Wayne Ma7be6bce2022-01-12 16:29:49 +0800421 ASSERT_FALSE(isOk(updateUidOwnerMaps(appUids, HAPPY_BOX_MATCH,
422 TrafficController::IptOpDelete)));
Wayne Ma4d692332022-01-19 16:04:04 +0800423 expectMapEmpty(mFakeUidOwnerMap);
424
425 // Add denylist rules for appUids.
Wayne Ma7be6bce2022-01-12 16:29:49 +0800426 ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, HAPPY_BOX_MATCH,
427 TrafficController::IptOpInsert)));
Wayne Ma4d692332022-01-19 16:04:04 +0800428 expectUidOwnerMapValues(appUids, HAPPY_BOX_MATCH, 0);
429
430 // Delete (non-existent) denylist rules for appUids, and check that this silently does
431 // nothing if the uid is in the map but does not have denylist match. This is required because
432 // NetworkManagementService will try to remove a uid from denylist after adding it to the
433 // allowlist and if the remove fails it will not update the uid status.
Wayne Ma7be6bce2022-01-12 16:29:49 +0800434 ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, PENALTY_BOX_MATCH,
435 TrafficController::IptOpDelete)));
Wayne Ma4d692332022-01-19 16:04:04 +0800436 expectUidOwnerMapValues(appUids, HAPPY_BOX_MATCH, 0);
437}
438
439TEST_F(TrafficControllerTest, TestAddUidInterfaceFilteringRules) {
440 int iif0 = 15;
441 ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif0, {1000, 1001})));
442 expectUidOwnerMapValues({1000, 1001}, IIF_MATCH, iif0);
443
444 // Add some non-overlapping new uids. They should coexist with existing rules
445 int iif1 = 16;
446 ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif1, {2000, 2001})));
447 expectUidOwnerMapValues({1000, 1001}, IIF_MATCH, iif0);
448 expectUidOwnerMapValues({2000, 2001}, IIF_MATCH, iif1);
449
450 // Overwrite some existing uids
451 int iif2 = 17;
452 ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif2, {1000, 2000})));
453 expectUidOwnerMapValues({1001}, IIF_MATCH, iif0);
454 expectUidOwnerMapValues({2001}, IIF_MATCH, iif1);
455 expectUidOwnerMapValues({1000, 2000}, IIF_MATCH, iif2);
456}
457
458TEST_F(TrafficControllerTest, TestRemoveUidInterfaceFilteringRules) {
459 int iif0 = 15;
460 int iif1 = 16;
461 ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif0, {1000, 1001})));
462 ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif1, {2000, 2001})));
463 expectUidOwnerMapValues({1000, 1001}, IIF_MATCH, iif0);
464 expectUidOwnerMapValues({2000, 2001}, IIF_MATCH, iif1);
465
466 // Rmove some uids
467 ASSERT_TRUE(isOk(mTc.removeUidInterfaceRules({1001, 2001})));
468 expectUidOwnerMapValues({1000}, IIF_MATCH, iif0);
469 expectUidOwnerMapValues({2000}, IIF_MATCH, iif1);
470 checkEachUidValue({1000, 2000}, IIF_MATCH); // Make sure there are only two uids remaining
471
472 // Remove non-existent uids shouldn't fail
473 ASSERT_TRUE(isOk(mTc.removeUidInterfaceRules({2000, 3000})));
474 expectUidOwnerMapValues({1000}, IIF_MATCH, iif0);
475 checkEachUidValue({1000}, IIF_MATCH); // Make sure there are only one uid remaining
476
477 // Remove everything
478 ASSERT_TRUE(isOk(mTc.removeUidInterfaceRules({1000})));
479 expectMapEmpty(mFakeUidOwnerMap);
480}
481
482TEST_F(TrafficControllerTest, TestUidInterfaceFilteringRulesCoexistWithExistingMatches) {
483 // Set up existing PENALTY_BOX_MATCH rules
Wayne Ma7be6bce2022-01-12 16:29:49 +0800484 ASSERT_TRUE(isOk(updateUidOwnerMaps({1000, 1001, 10012}, PENALTY_BOX_MATCH,
485 TrafficController::IptOpInsert)));
Wayne Ma4d692332022-01-19 16:04:04 +0800486 expectUidOwnerMapValues({1000, 1001, 10012}, PENALTY_BOX_MATCH, 0);
487
488 // Add some partially-overlapping uid owner rules and check result
489 int iif1 = 32;
490 ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif1, {10012, 10013, 10014})));
491 expectUidOwnerMapValues({1000, 1001}, PENALTY_BOX_MATCH, 0);
492 expectUidOwnerMapValues({10012}, PENALTY_BOX_MATCH | IIF_MATCH, iif1);
493 expectUidOwnerMapValues({10013, 10014}, IIF_MATCH, iif1);
494
495 // Removing some PENALTY_BOX_MATCH rules should not change uid interface rule
Wayne Ma7be6bce2022-01-12 16:29:49 +0800496 ASSERT_TRUE(isOk(updateUidOwnerMaps({1001, 10012}, PENALTY_BOX_MATCH,
497 TrafficController::IptOpDelete)));
Wayne Ma4d692332022-01-19 16:04:04 +0800498 expectUidOwnerMapValues({1000}, PENALTY_BOX_MATCH, 0);
499 expectUidOwnerMapValues({10012, 10013, 10014}, IIF_MATCH, iif1);
500
501 // Remove all uid interface rules
502 ASSERT_TRUE(isOk(mTc.removeUidInterfaceRules({10012, 10013, 10014})));
503 expectUidOwnerMapValues({1000}, PENALTY_BOX_MATCH, 0);
504 // Make sure these are the only uids left
505 checkEachUidValue({1000}, PENALTY_BOX_MATCH);
506}
507
508TEST_F(TrafficControllerTest, TestUidInterfaceFilteringRulesCoexistWithNewMatches) {
509 int iif1 = 56;
510 // Set up existing uid interface rules
511 ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif1, {10001, 10002})));
512 expectUidOwnerMapValues({10001, 10002}, IIF_MATCH, iif1);
513
514 // Add some partially-overlapping doze rules
515 EXPECT_EQ(0, mTc.replaceUidOwnerMap("fw_dozable", true, {10002, 10003}));
516 expectUidOwnerMapValues({10001}, IIF_MATCH, iif1);
517 expectUidOwnerMapValues({10002}, DOZABLE_MATCH | IIF_MATCH, iif1);
518 expectUidOwnerMapValues({10003}, DOZABLE_MATCH, 0);
519
520 // Introduce a third rule type (powersave) on various existing UIDs
521 EXPECT_EQ(0, mTc.replaceUidOwnerMap("fw_powersave", true, {10000, 10001, 10002, 10003}));
522 expectUidOwnerMapValues({10000}, POWERSAVE_MATCH, 0);
523 expectUidOwnerMapValues({10001}, POWERSAVE_MATCH | IIF_MATCH, iif1);
524 expectUidOwnerMapValues({10002}, POWERSAVE_MATCH | DOZABLE_MATCH | IIF_MATCH, iif1);
525 expectUidOwnerMapValues({10003}, POWERSAVE_MATCH | DOZABLE_MATCH, 0);
526
527 // Remove all doze rules
528 EXPECT_EQ(0, mTc.replaceUidOwnerMap("fw_dozable", true, {}));
529 expectUidOwnerMapValues({10000}, POWERSAVE_MATCH, 0);
530 expectUidOwnerMapValues({10001}, POWERSAVE_MATCH | IIF_MATCH, iif1);
531 expectUidOwnerMapValues({10002}, POWERSAVE_MATCH | IIF_MATCH, iif1);
532 expectUidOwnerMapValues({10003}, POWERSAVE_MATCH, 0);
533
534 // Remove all powersave rules, expect ownerMap to only have uid interface rules left
535 EXPECT_EQ(0, mTc.replaceUidOwnerMap("fw_powersave", true, {}));
536 expectUidOwnerMapValues({10001, 10002}, IIF_MATCH, iif1);
537 // Make sure these are the only uids left
538 checkEachUidValue({10001, 10002}, IIF_MATCH);
539}
540
Motomu Utsumib08654c2022-05-11 05:56:26 +0000541TEST_F(TrafficControllerTest, TestAddUidInterfaceFilteringRulesWithWildcard) {
542 // iif=0 is a wildcard
543 int iif = 0;
544 // Add interface rule with wildcard to uids
545 ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif, {1000, 1001})));
546 expectUidOwnerMapValues({1000, 1001}, IIF_MATCH, iif);
547}
548
549TEST_F(TrafficControllerTest, TestRemoveUidInterfaceFilteringRulesWithWildcard) {
550 // iif=0 is a wildcard
551 int iif = 0;
552 // Add interface rule with wildcard to two uids
553 ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif, {1000, 1001})));
554 expectUidOwnerMapValues({1000, 1001}, IIF_MATCH, iif);
555
556 // Remove interface rule from one of the uids
557 ASSERT_TRUE(isOk(mTc.removeUidInterfaceRules({1000})));
558 expectUidOwnerMapValues({1001}, IIF_MATCH, iif);
559 checkEachUidValue({1001}, IIF_MATCH);
560
561 // Remove interface rule from the remaining uid
562 ASSERT_TRUE(isOk(mTc.removeUidInterfaceRules({1001})));
563 expectMapEmpty(mFakeUidOwnerMap);
564}
565
566TEST_F(TrafficControllerTest, TestUidInterfaceFilteringRulesWithWildcardAndExistingMatches) {
567 // Set up existing DOZABLE_MATCH and POWERSAVE_MATCH rule
568 ASSERT_TRUE(isOk(updateUidOwnerMaps({1000}, DOZABLE_MATCH,
569 TrafficController::IptOpInsert)));
570 ASSERT_TRUE(isOk(updateUidOwnerMaps({1000}, POWERSAVE_MATCH,
571 TrafficController::IptOpInsert)));
572
573 // iif=0 is a wildcard
574 int iif = 0;
575 // Add interface rule with wildcard to the existing uid
576 ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif, {1000})));
577 expectUidOwnerMapValues({1000}, POWERSAVE_MATCH | DOZABLE_MATCH | IIF_MATCH, iif);
578
579 // Remove interface rule with wildcard from the existing uid
580 ASSERT_TRUE(isOk(mTc.removeUidInterfaceRules({1000})));
581 expectUidOwnerMapValues({1000}, POWERSAVE_MATCH | DOZABLE_MATCH, 0);
582}
583
584TEST_F(TrafficControllerTest, TestUidInterfaceFilteringRulesWithWildcardAndNewMatches) {
585 // iif=0 is a wildcard
586 int iif = 0;
587 // Set up existing interface rule with wildcard
588 ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif, {1000})));
589
590 // Add DOZABLE_MATCH and POWERSAVE_MATCH rule to the existing uid
591 ASSERT_TRUE(isOk(updateUidOwnerMaps({1000}, DOZABLE_MATCH,
592 TrafficController::IptOpInsert)));
593 ASSERT_TRUE(isOk(updateUidOwnerMaps({1000}, POWERSAVE_MATCH,
594 TrafficController::IptOpInsert)));
595 expectUidOwnerMapValues({1000}, POWERSAVE_MATCH | DOZABLE_MATCH | IIF_MATCH, iif);
596
597 // Remove DOZABLE_MATCH and POWERSAVE_MATCH rule from the existing uid
598 ASSERT_TRUE(isOk(updateUidOwnerMaps({1000}, DOZABLE_MATCH,
599 TrafficController::IptOpDelete)));
600 ASSERT_TRUE(isOk(updateUidOwnerMaps({1000}, POWERSAVE_MATCH,
601 TrafficController::IptOpDelete)));
602 expectUidOwnerMapValues({1000}, IIF_MATCH, iif);
603}
604
Wayne Ma4d692332022-01-19 16:04:04 +0800605TEST_F(TrafficControllerTest, TestGrantInternetPermission) {
606 std::vector<uid_t> appUids = {TEST_UID, TEST_UID2, TEST_UID3};
607
608 mTc.setPermissionForUids(INetd::PERMISSION_INTERNET, appUids);
609 expectMapEmpty(mFakeUidPermissionMap);
610 expectPrivilegedUserSetEmpty();
611}
612
613TEST_F(TrafficControllerTest, TestRevokeInternetPermission) {
614 std::vector<uid_t> appUids = {TEST_UID, TEST_UID2, TEST_UID3};
615
616 mTc.setPermissionForUids(INetd::PERMISSION_NONE, appUids);
617 expectUidPermissionMapValues(appUids, INetd::PERMISSION_NONE);
618}
619
620TEST_F(TrafficControllerTest, TestPermissionUninstalled) {
621 std::vector<uid_t> appUids = {TEST_UID, TEST_UID2, TEST_UID3};
622
623 mTc.setPermissionForUids(INetd::PERMISSION_UPDATE_DEVICE_STATS, appUids);
624 expectUidPermissionMapValues(appUids, INetd::PERMISSION_UPDATE_DEVICE_STATS);
625 expectPrivilegedUserSet(appUids);
626
627 std::vector<uid_t> uidToRemove = {TEST_UID};
628 mTc.setPermissionForUids(INetd::PERMISSION_UNINSTALLED, uidToRemove);
629
630 std::vector<uid_t> uidRemain = {TEST_UID3, TEST_UID2};
631 expectUidPermissionMapValues(uidRemain, INetd::PERMISSION_UPDATE_DEVICE_STATS);
632 expectPrivilegedUserSet(uidRemain);
633
634 mTc.setPermissionForUids(INetd::PERMISSION_UNINSTALLED, uidRemain);
635 expectMapEmpty(mFakeUidPermissionMap);
636 expectPrivilegedUserSetEmpty();
637}
638
639TEST_F(TrafficControllerTest, TestGrantUpdateStatsPermission) {
640 std::vector<uid_t> appUids = {TEST_UID, TEST_UID2, TEST_UID3};
641
642 mTc.setPermissionForUids(INetd::PERMISSION_UPDATE_DEVICE_STATS, appUids);
643 expectUidPermissionMapValues(appUids, INetd::PERMISSION_UPDATE_DEVICE_STATS);
644 expectPrivilegedUserSet(appUids);
645
646 mTc.setPermissionForUids(INetd::PERMISSION_NONE, appUids);
647 expectPrivilegedUserSetEmpty();
648 expectUidPermissionMapValues(appUids, INetd::PERMISSION_NONE);
649}
650
651TEST_F(TrafficControllerTest, TestRevokeUpdateStatsPermission) {
652 std::vector<uid_t> appUids = {TEST_UID, TEST_UID2, TEST_UID3};
653
654 mTc.setPermissionForUids(INetd::PERMISSION_UPDATE_DEVICE_STATS, appUids);
655 expectPrivilegedUserSet(appUids);
656
657 std::vector<uid_t> uidToRemove = {TEST_UID};
658 mTc.setPermissionForUids(INetd::PERMISSION_NONE, uidToRemove);
659
660 std::vector<uid_t> uidRemain = {TEST_UID3, TEST_UID2};
661 expectPrivilegedUserSet(uidRemain);
662
663 mTc.setPermissionForUids(INetd::PERMISSION_NONE, uidRemain);
664 expectPrivilegedUserSetEmpty();
665}
666
667TEST_F(TrafficControllerTest, TestGrantWrongPermission) {
668 std::vector<uid_t> appUids = {TEST_UID, TEST_UID2, TEST_UID3};
669
670 mTc.setPermissionForUids(INetd::PERMISSION_NONE, appUids);
671 expectPrivilegedUserSetEmpty();
672 expectUidPermissionMapValues(appUids, INetd::PERMISSION_NONE);
673}
674
675TEST_F(TrafficControllerTest, TestGrantDuplicatePermissionSlientlyFail) {
676 std::vector<uid_t> appUids = {TEST_UID, TEST_UID2, TEST_UID3};
677
678 mTc.setPermissionForUids(INetd::PERMISSION_INTERNET, appUids);
679 expectMapEmpty(mFakeUidPermissionMap);
680
681 std::vector<uid_t> uidToAdd = {TEST_UID};
682 mTc.setPermissionForUids(INetd::PERMISSION_INTERNET, uidToAdd);
683
684 expectPrivilegedUserSetEmpty();
685
686 mTc.setPermissionForUids(INetd::PERMISSION_NONE, appUids);
687 expectUidPermissionMapValues(appUids, INetd::PERMISSION_NONE);
688
689 mTc.setPermissionForUids(INetd::PERMISSION_UPDATE_DEVICE_STATS, appUids);
690 expectPrivilegedUserSet(appUids);
691
692 mTc.setPermissionForUids(INetd::PERMISSION_UPDATE_DEVICE_STATS, uidToAdd);
693 expectPrivilegedUserSet(appUids);
694
695 mTc.setPermissionForUids(INetd::PERMISSION_NONE, appUids);
696 expectPrivilegedUserSetEmpty();
697}
698
Ken Chen2fb86362022-06-05 11:39:38 +0800699TEST_F(TrafficControllerTest, TestDumpsys) {
700 std::vector<uid_t> appUid = {TEST_UID};
701 mTc.setPermissionForUids(INetd::PERMISSION_NONE, appUid);
702 std::vector<uid_t> appUid2 = {TEST_UID2};
703 mTc.setPermissionForUids(INetd::PERMISSION_UPDATE_DEVICE_STATS, appUid2);
704
705 std::vector<std::string> expectedLines = {
706 "mUidPermissionMap:",
707 fmt::format("{} BPF_PERMISSION_UPDATE_DEVICE_STATS", TEST_UID2),
708 fmt::format("{} PERMISSION_NONE", TEST_UID),
709 "mPrivilegedUser:",
710 fmt::format("{} ALLOW_UPDATE_DEVICE_STATS", TEST_UID2)};
711 EXPECT_TRUE(expectDumpsysContains(expectedLines));
712
713 mTc.setPermissionForUids(INetd::PERMISSION_INTERNET, {TEST_UID, TEST_UID2});
714 expectedLines = {
715 "mUidPermissionMap:",
716 "mPrivilegedUser:",
717 };
718 EXPECT_TRUE(expectDumpsysContains(expectedLines));
719}
720
Ken Chen77a6b712022-06-06 12:46:36 +0800721TEST_F(TrafficControllerTest, getFirewallType) {
722 static const struct TestConfig {
723 ChildChain childChain;
724 FirewallType firewallType;
725 } testConfigs[] = {
726 // clang-format off
727 {NONE, DENYLIST},
728 {DOZABLE, ALLOWLIST},
729 {STANDBY, DENYLIST},
730 {POWERSAVE, ALLOWLIST},
731 {RESTRICTED, ALLOWLIST},
732 {LOW_POWER_STANDBY, ALLOWLIST},
733 {LOCKDOWN, DENYLIST},
734 {OEM_DENY_1, DENYLIST},
735 {OEM_DENY_2, DENYLIST},
736 {INVALID_CHAIN, DENYLIST},
737 // clang-format on
738 };
739
740 for (const auto& config : testConfigs) {
741 SCOPED_TRACE(fmt::format("testConfig: [{}, {}]", config.childChain, config.firewallType));
742 EXPECT_EQ(config.firewallType, mTc.getFirewallType(config.childChain));
743 }
744}
745
Patrick Rohr61e94672022-02-01 21:06:40 +0100746constexpr uint32_t SOCK_CLOSE_WAIT_US = 30 * 1000;
747constexpr uint32_t ENOBUFS_POLL_WAIT_US = 10 * 1000;
748
749using android::base::Error;
750using android::base::Result;
751using android::bpf::BpfMap;
752
753// This test set up a SkDestroyListener that is running parallel with the production
754// SkDestroyListener. The test will create thousands of sockets and tag them on the
755// production cookieUidTagMap and close them in a short time. When the number of
756// sockets get closed exceeds the buffer size, it will start to return ENOBUFF
757// error. The error will be ignored by the production SkDestroyListener and the
758// test will clean up the tags in tearDown if there is any remains.
759
760// TODO: Instead of test the ENOBUFF error, we can test the production
761// SkDestroyListener to see if it failed to delete a tagged socket when ENOBUFF
762// triggered.
763class NetlinkListenerTest : public testing::Test {
764 protected:
765 NetlinkListenerTest() {}
766 BpfMap<uint64_t, UidTagValue> mCookieTagMap;
767
768 void SetUp() {
Maciej Żenczykowskiced35312022-05-31 05:11:12 -0700769 mCookieTagMap.init(COOKIE_TAG_MAP_PATH);
Patrick Rohr61e94672022-02-01 21:06:40 +0100770 ASSERT_TRUE(mCookieTagMap.isValid());
771 }
772
773 void TearDown() {
774 const auto deleteTestCookieEntries = [](const uint64_t& key, const UidTagValue& value,
775 BpfMap<uint64_t, UidTagValue>& map) {
776 if ((value.uid == TEST_UID) && (value.tag == TEST_TAG)) {
777 Result<void> res = map.deleteValue(key);
778 if (res.ok() || (res.error().code() == ENOENT)) {
779 return Result<void>();
780 }
Maciej Żenczykowskie0f58462022-05-17 13:59:22 -0700781 ALOGE("Failed to delete data(cookie = %" PRIu64 "): %s", key,
Patrick Rohr61e94672022-02-01 21:06:40 +0100782 strerror(res.error().code()));
783 }
784 // Move forward to next cookie in the map.
785 return Result<void>();
786 };
787 EXPECT_RESULT_OK(mCookieTagMap.iterateWithValue(deleteTestCookieEntries));
788 }
789
790 Result<void> checkNoGarbageTagsExist() {
791 const auto checkGarbageTags = [](const uint64_t&, const UidTagValue& value,
792 const BpfMap<uint64_t, UidTagValue>&) -> Result<void> {
793 if ((TEST_UID == value.uid) && (TEST_TAG == value.tag)) {
794 return Error(EUCLEAN) << "Closed socket is not untagged";
795 }
796 return {};
797 };
798 return mCookieTagMap.iterateWithValue(checkGarbageTags);
799 }
800
801 bool checkMassiveSocketDestroy(int totalNumber, bool expectError) {
802 std::unique_ptr<android::netdutils::NetlinkListenerInterface> skDestroyListener;
803 auto result = android::net::TrafficController::makeSkDestroyListener();
804 if (!isOk(result)) {
805 ALOGE("Unable to create SkDestroyListener: %s", toString(result).c_str());
806 } else {
807 skDestroyListener = std::move(result.value());
808 }
809 int rxErrorCount = 0;
810 // Rx handler extracts nfgenmsg looks up and invokes registered dispatch function.
811 const auto rxErrorHandler = [&rxErrorCount](const int, const int) { rxErrorCount++; };
812 skDestroyListener->registerSkErrorHandler(rxErrorHandler);
813 int fds[totalNumber];
814 for (int i = 0; i < totalNumber; i++) {
815 fds[i] = socket(AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0);
816 // The likely reason for a failure is running out of available file descriptors.
817 EXPECT_LE(0, fds[i]) << i << " of " << totalNumber;
818 if (fds[i] < 0) {
819 // EXPECT_LE already failed above, so test case is a failure, but we don't
820 // want potentially tens of thousands of extra failures creating and then
821 // closing all these fds cluttering up the logs.
822 totalNumber = i;
823 break;
824 };
825 libnetd_updatable_tagSocket(fds[i], TEST_TAG, TEST_UID, 1000);
826 }
827
828 // TODO: Use a separate thread that has its own fd table so we can
829 // close sockets even faster simply by terminating that thread.
830 for (int i = 0; i < totalNumber; i++) {
831 EXPECT_EQ(0, close(fds[i]));
832 }
833 // wait a bit for netlink listener to handle all the messages.
834 usleep(SOCK_CLOSE_WAIT_US);
835 if (expectError) {
836 // If ENOBUFS triggered, check it only called into the handler once, ie.
837 // that the netlink handler is not spinning.
838 int currentErrorCount = rxErrorCount;
839 // 0 error count is acceptable because the system has chances to close all sockets
840 // normally.
841 EXPECT_LE(0, rxErrorCount);
842 if (!rxErrorCount) return true;
843
844 usleep(ENOBUFS_POLL_WAIT_US);
845 EXPECT_EQ(currentErrorCount, rxErrorCount);
846 } else {
847 EXPECT_RESULT_OK(checkNoGarbageTagsExist());
848 EXPECT_EQ(0, rxErrorCount);
849 }
850 return false;
851 }
852};
853
854TEST_F(NetlinkListenerTest, TestAllSocketUntagged) {
855 checkMassiveSocketDestroy(10, false);
856 checkMassiveSocketDestroy(100, false);
857}
858
859// Disabled because flaky on blueline-userdebug; this test relies on the main thread
860// winning a race against the NetlinkListener::run() thread. There's no way to ensure
861// things will be scheduled the same way across all architectures and test environments.
862TEST_F(NetlinkListenerTest, DISABLED_TestSkDestroyError) {
863 bool needRetry = false;
864 int retryCount = 0;
865 do {
866 needRetry = checkMassiveSocketDestroy(32500, true);
867 if (needRetry) retryCount++;
868 } while (needRetry && retryCount < 3);
869 // Should review test if it can always close all sockets correctly.
870 EXPECT_GT(3, retryCount);
871}
872
873
Wayne Ma4d692332022-01-19 16:04:04 +0800874} // namespace net
875} // namespace android