blob: ff2ebad9f136c990a824a72a87f82b8ca0e9256f [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>
Ken Chen0dd74952022-06-06 18:25:18 +080034#include <android-base/logging.h>
Wayne Ma4d692332022-01-19 16:04:04 +080035#include <android-base/stringprintf.h>
36#include <android-base/strings.h>
Wayne Ma7be6bce2022-01-12 16:29:49 +080037#include <binder/Status.h>
Wayne Ma4d692332022-01-19 16:04:04 +080038
39#include <netdutils/MockSyscalls.h>
40
Maciej Żenczykowski439bac22022-05-31 03:22:32 -070041#define TEST_BPF_MAP
Wayne Ma4d692332022-01-19 16:04:04 +080042#include "TrafficController.h"
43#include "bpf/BpfUtils.h"
Patrick Rohr61e94672022-02-01 21:06:40 +010044#include "NetdUpdatablePublic.h"
Wayne Ma4d692332022-01-19 16:04:04 +080045
46using namespace android::bpf; // NOLINT(google-build-using-namespace): grandfathered
47
48namespace android {
49namespace net {
50
Wayne Ma7be6bce2022-01-12 16:29:49 +080051using android::netdutils::Status;
Wayne Ma4d692332022-01-19 16:04:04 +080052using base::Result;
53using netdutils::isOk;
Ken Chen2fb86362022-06-05 11:39:38 +080054using netdutils::statusFromErrno;
Wayne Ma4d692332022-01-19 16:04:04 +080055
56constexpr int TEST_MAP_SIZE = 10;
Wayne Ma4d692332022-01-19 16:04:04 +080057constexpr uid_t TEST_UID = 10086;
58constexpr uid_t TEST_UID2 = 54321;
59constexpr uid_t TEST_UID3 = 98765;
60constexpr uint32_t TEST_TAG = 42;
61constexpr uint32_t TEST_COUNTERSET = 1;
Ken Chen0dd74952022-06-06 18:25:18 +080062constexpr int TEST_COOKIE = 1;
63constexpr char TEST_IFNAME[] = "test0";
64constexpr int TEST_IFINDEX = 999;
65constexpr int RXPACKETS = 1;
66constexpr int RXBYTES = 100;
67constexpr int TXPACKETS = 0;
68constexpr int TXBYTES = 0;
Wayne Ma4d692332022-01-19 16:04:04 +080069
70#define ASSERT_VALID(x) ASSERT_TRUE((x).isValid())
71
72class TrafficControllerTest : public ::testing::Test {
73 protected:
Wayne Ma92d80792022-01-20 13:20:34 +080074 TrafficControllerTest() {}
Wayne Ma4d692332022-01-19 16:04:04 +080075 TrafficController mTc;
76 BpfMap<uint64_t, UidTagValue> mFakeCookieTagMap;
Wayne Ma4d692332022-01-19 16:04:04 +080077 BpfMap<uint32_t, StatsValue> mFakeAppUidStatsMap;
78 BpfMap<StatsKey, StatsValue> mFakeStatsMapA;
Lorenzo Colitti60cbed32022-03-03 17:49:01 +090079 BpfMap<uint32_t, uint32_t> mFakeConfigurationMap;
Wayne Ma4d692332022-01-19 16:04:04 +080080 BpfMap<uint32_t, UidOwnerValue> mFakeUidOwnerMap;
81 BpfMap<uint32_t, uint8_t> mFakeUidPermissionMap;
Ken Chen0dd74952022-06-06 18:25:18 +080082 BpfMap<uint32_t, uint8_t> mFakeUidCounterSetMap;
83 BpfMap<uint32_t, IfaceValue> mFakeIfaceIndexNameMap;
Wayne Ma4d692332022-01-19 16:04:04 +080084
85 void SetUp() {
86 std::lock_guard guard(mTc.mMutex);
87 ASSERT_EQ(0, setrlimitForTest());
88
Maciej Żenczykowski439bac22022-05-31 03:22:32 -070089 mFakeCookieTagMap.resetMap(BPF_MAP_TYPE_HASH, TEST_MAP_SIZE);
Wayne Ma4d692332022-01-19 16:04:04 +080090 ASSERT_VALID(mFakeCookieTagMap);
91
Maciej Żenczykowski439bac22022-05-31 03:22:32 -070092 mFakeAppUidStatsMap.resetMap(BPF_MAP_TYPE_HASH, TEST_MAP_SIZE);
Wayne Ma4d692332022-01-19 16:04:04 +080093 ASSERT_VALID(mFakeAppUidStatsMap);
94
Maciej Żenczykowski439bac22022-05-31 03:22:32 -070095 mFakeStatsMapA.resetMap(BPF_MAP_TYPE_HASH, TEST_MAP_SIZE);
Wayne Ma4d692332022-01-19 16:04:04 +080096 ASSERT_VALID(mFakeStatsMapA);
97
Maciej Żenczykowski439bac22022-05-31 03:22:32 -070098 mFakeConfigurationMap.resetMap(BPF_MAP_TYPE_HASH, 1);
Wayne Ma4d692332022-01-19 16:04:04 +080099 ASSERT_VALID(mFakeConfigurationMap);
100
Maciej Żenczykowski439bac22022-05-31 03:22:32 -0700101 mFakeUidOwnerMap.resetMap(BPF_MAP_TYPE_HASH, TEST_MAP_SIZE);
Wayne Ma4d692332022-01-19 16:04:04 +0800102 ASSERT_VALID(mFakeUidOwnerMap);
Maciej Żenczykowski439bac22022-05-31 03:22:32 -0700103 mFakeUidPermissionMap.resetMap(BPF_MAP_TYPE_HASH, TEST_MAP_SIZE);
Wayne Ma4d692332022-01-19 16:04:04 +0800104 ASSERT_VALID(mFakeUidPermissionMap);
105
Ken Chen0dd74952022-06-06 18:25:18 +0800106 mFakeUidCounterSetMap.resetMap(BPF_MAP_TYPE_HASH, TEST_MAP_SIZE);
107 ASSERT_VALID(mFakeUidCounterSetMap);
108
109 mFakeIfaceIndexNameMap.resetMap(BPF_MAP_TYPE_HASH, TEST_MAP_SIZE);
110 ASSERT_VALID(mFakeIfaceIndexNameMap);
111
Maciej Żenczykowski55ab87a2022-05-31 03:15:12 -0700112 mTc.mCookieTagMap = mFakeCookieTagMap;
Wayne Ma4d692332022-01-19 16:04:04 +0800113 ASSERT_VALID(mTc.mCookieTagMap);
Maciej Żenczykowski55ab87a2022-05-31 03:15:12 -0700114 mTc.mAppUidStatsMap = mFakeAppUidStatsMap;
Wayne Ma4d692332022-01-19 16:04:04 +0800115 ASSERT_VALID(mTc.mAppUidStatsMap);
Maciej Żenczykowski55ab87a2022-05-31 03:15:12 -0700116 mTc.mStatsMapA = mFakeStatsMapA;
Wayne Ma4d692332022-01-19 16:04:04 +0800117 ASSERT_VALID(mTc.mStatsMapA);
Maciej Żenczykowski55ab87a2022-05-31 03:15:12 -0700118 mTc.mConfigurationMap = mFakeConfigurationMap;
Wayne Ma4d692332022-01-19 16:04:04 +0800119 ASSERT_VALID(mTc.mConfigurationMap);
120
121 // Always write to stats map A by default.
122 ASSERT_RESULT_OK(mTc.mConfigurationMap.writeValue(CURRENT_STATS_MAP_CONFIGURATION_KEY,
123 SELECT_MAP_A, BPF_ANY));
Maciej Żenczykowski55ab87a2022-05-31 03:15:12 -0700124 mTc.mUidOwnerMap = mFakeUidOwnerMap;
Wayne Ma4d692332022-01-19 16:04:04 +0800125 ASSERT_VALID(mTc.mUidOwnerMap);
Maciej Żenczykowski55ab87a2022-05-31 03:15:12 -0700126 mTc.mUidPermissionMap = mFakeUidPermissionMap;
Wayne Ma4d692332022-01-19 16:04:04 +0800127 ASSERT_VALID(mTc.mUidPermissionMap);
128 mTc.mPrivilegedUser.clear();
Ken Chen0dd74952022-06-06 18:25:18 +0800129
130 mTc.mUidCounterSetMap = mFakeUidCounterSetMap;
131 ASSERT_VALID(mTc.mUidCounterSetMap);
132
133 mTc.mIfaceIndexNameMap = mFakeIfaceIndexNameMap;
134 ASSERT_VALID(mTc.mIfaceIndexNameMap);
Wayne Ma4d692332022-01-19 16:04:04 +0800135 }
136
Wayne Ma4d692332022-01-19 16:04:04 +0800137 void populateFakeStats(uint64_t cookie, uint32_t uid, uint32_t tag, StatsKey* key) {
138 UidTagValue cookieMapkey = {.uid = (uint32_t)uid, .tag = tag};
139 EXPECT_RESULT_OK(mFakeCookieTagMap.writeValue(cookie, cookieMapkey, BPF_ANY));
Ken Chen0dd74952022-06-06 18:25:18 +0800140 *key = {.uid = uid, .tag = tag, .counterSet = TEST_COUNTERSET, .ifaceIndex = TEST_IFINDEX};
141 StatsValue statsMapValue = {.rxPackets = RXPACKETS, .rxBytes = RXBYTES,
142 .txPackets = TXPACKETS, .txBytes = TXBYTES};
Wayne Ma4d692332022-01-19 16:04:04 +0800143 EXPECT_RESULT_OK(mFakeStatsMapA.writeValue(*key, statsMapValue, BPF_ANY));
144 EXPECT_RESULT_OK(mFakeAppUidStatsMap.writeValue(uid, statsMapValue, BPF_ANY));
145 // put tag information back to statsKey
146 key->tag = tag;
147 }
148
Ken Chen0dd74952022-06-06 18:25:18 +0800149 void populateFakeCounterSet(uint32_t uid, uint32_t counterSet) {
150 EXPECT_RESULT_OK(mFakeUidCounterSetMap.writeValue(uid, counterSet, BPF_ANY));
151 }
152
153 void populateFakeIfaceIndexName(const char* name, uint32_t ifaceIndex) {
154 if (name == nullptr || ifaceIndex <= 0) return;
155
156 IfaceValue iface;
157 strlcpy(iface.name, name, sizeof(IfaceValue));
158 EXPECT_RESULT_OK(mFakeIfaceIndexNameMap.writeValue(ifaceIndex, iface, BPF_ANY));
159 }
160
Wayne Ma4d692332022-01-19 16:04:04 +0800161 void checkUidOwnerRuleForChain(ChildChain chain, UidOwnerMatchType match) {
162 uint32_t uid = TEST_UID;
163 EXPECT_EQ(0, mTc.changeUidOwnerRule(chain, uid, DENY, DENYLIST));
164 Result<UidOwnerValue> value = mFakeUidOwnerMap.readValue(uid);
165 EXPECT_RESULT_OK(value);
166 EXPECT_TRUE(value.value().rule & match);
167
168 uid = TEST_UID2;
169 EXPECT_EQ(0, mTc.changeUidOwnerRule(chain, uid, ALLOW, ALLOWLIST));
170 value = mFakeUidOwnerMap.readValue(uid);
171 EXPECT_RESULT_OK(value);
172 EXPECT_TRUE(value.value().rule & match);
173
174 EXPECT_EQ(0, mTc.changeUidOwnerRule(chain, uid, DENY, ALLOWLIST));
175 value = mFakeUidOwnerMap.readValue(uid);
176 EXPECT_FALSE(value.ok());
177 EXPECT_EQ(ENOENT, value.error().code());
178
179 uid = TEST_UID;
180 EXPECT_EQ(0, mTc.changeUidOwnerRule(chain, uid, ALLOW, DENYLIST));
181 value = mFakeUidOwnerMap.readValue(uid);
182 EXPECT_FALSE(value.ok());
183 EXPECT_EQ(ENOENT, value.error().code());
184
185 uid = TEST_UID3;
186 EXPECT_EQ(-ENOENT, mTc.changeUidOwnerRule(chain, uid, ALLOW, DENYLIST));
187 value = mFakeUidOwnerMap.readValue(uid);
188 EXPECT_FALSE(value.ok());
189 EXPECT_EQ(ENOENT, value.error().code());
190 }
191
192 void checkEachUidValue(const std::vector<int32_t>& uids, UidOwnerMatchType match) {
193 for (uint32_t uid : uids) {
194 Result<UidOwnerValue> value = mFakeUidOwnerMap.readValue(uid);
195 EXPECT_RESULT_OK(value);
196 EXPECT_TRUE(value.value().rule & match);
197 }
198 std::set<uint32_t> uidSet(uids.begin(), uids.end());
199 const auto checkNoOtherUid = [&uidSet](const int32_t& key,
200 const BpfMap<uint32_t, UidOwnerValue>&) {
201 EXPECT_NE(uidSet.end(), uidSet.find(key));
202 return Result<void>();
203 };
204 EXPECT_RESULT_OK(mFakeUidOwnerMap.iterate(checkNoOtherUid));
205 }
206
207 void checkUidMapReplace(const std::string& name, const std::vector<int32_t>& uids,
208 UidOwnerMatchType match) {
209 bool isAllowlist = true;
210 EXPECT_EQ(0, mTc.replaceUidOwnerMap(name, isAllowlist, uids));
211 checkEachUidValue(uids, match);
212
213 isAllowlist = false;
214 EXPECT_EQ(0, mTc.replaceUidOwnerMap(name, isAllowlist, uids));
215 checkEachUidValue(uids, match);
216 }
217
218 void expectUidOwnerMapValues(const std::vector<uint32_t>& appUids, uint8_t expectedRule,
219 uint32_t expectedIif) {
220 for (uint32_t uid : appUids) {
221 Result<UidOwnerValue> value = mFakeUidOwnerMap.readValue(uid);
222 EXPECT_RESULT_OK(value);
223 EXPECT_EQ(expectedRule, value.value().rule)
224 << "Expected rule for UID " << uid << " to be " << expectedRule << ", but was "
225 << value.value().rule;
226 EXPECT_EQ(expectedIif, value.value().iif)
227 << "Expected iif for UID " << uid << " to be " << expectedIif << ", but was "
228 << value.value().iif;
229 }
230 }
231
232 template <class Key, class Value>
233 void expectMapEmpty(BpfMap<Key, Value>& map) {
234 auto isEmpty = map.isEmpty();
235 EXPECT_RESULT_OK(isEmpty);
236 EXPECT_TRUE(isEmpty.value());
237 }
238
239 void expectUidPermissionMapValues(const std::vector<uid_t>& appUids, uint8_t expectedValue) {
240 for (uid_t uid : appUids) {
241 Result<uint8_t> value = mFakeUidPermissionMap.readValue(uid);
242 EXPECT_RESULT_OK(value);
243 EXPECT_EQ(expectedValue, value.value())
244 << "Expected value for UID " << uid << " to be " << expectedValue
245 << ", but was " << value.value();
246 }
247 }
248
249 void expectPrivilegedUserSet(const std::vector<uid_t>& appUids) {
250 std::lock_guard guard(mTc.mMutex);
251 EXPECT_EQ(appUids.size(), mTc.mPrivilegedUser.size());
252 for (uid_t uid : appUids) {
253 EXPECT_NE(mTc.mPrivilegedUser.end(), mTc.mPrivilegedUser.find(uid));
254 }
255 }
256
257 void expectPrivilegedUserSetEmpty() {
258 std::lock_guard guard(mTc.mMutex);
259 EXPECT_TRUE(mTc.mPrivilegedUser.empty());
260 }
261
262 void addPrivilegedUid(uid_t uid) {
263 std::vector privilegedUid = {uid};
264 mTc.setPermissionForUids(INetd::PERMISSION_UPDATE_DEVICE_STATS, privilegedUid);
265 }
266
267 void removePrivilegedUid(uid_t uid) {
268 std::vector privilegedUid = {uid};
269 mTc.setPermissionForUids(INetd::PERMISSION_NONE, privilegedUid);
270 }
271
272 void expectFakeStatsUnchanged(uint64_t cookie, uint32_t tag, uint32_t uid,
273 StatsKey tagStatsMapKey) {
274 Result<UidTagValue> cookieMapResult = mFakeCookieTagMap.readValue(cookie);
275 EXPECT_RESULT_OK(cookieMapResult);
276 EXPECT_EQ(uid, cookieMapResult.value().uid);
277 EXPECT_EQ(tag, cookieMapResult.value().tag);
Wayne Ma4d692332022-01-19 16:04:04 +0800278 Result<StatsValue> statsMapResult = mFakeStatsMapA.readValue(tagStatsMapKey);
279 EXPECT_RESULT_OK(statsMapResult);
Ken Chen0dd74952022-06-06 18:25:18 +0800280 EXPECT_EQ((uint64_t)RXPACKETS, statsMapResult.value().rxPackets);
281 EXPECT_EQ((uint64_t)RXBYTES, statsMapResult.value().rxBytes);
Wayne Ma4d692332022-01-19 16:04:04 +0800282 tagStatsMapKey.tag = 0;
283 statsMapResult = mFakeStatsMapA.readValue(tagStatsMapKey);
284 EXPECT_RESULT_OK(statsMapResult);
Ken Chen0dd74952022-06-06 18:25:18 +0800285 EXPECT_EQ((uint64_t)RXPACKETS, statsMapResult.value().rxPackets);
286 EXPECT_EQ((uint64_t)RXBYTES, statsMapResult.value().rxBytes);
Wayne Ma4d692332022-01-19 16:04:04 +0800287 auto appStatsResult = mFakeAppUidStatsMap.readValue(uid);
288 EXPECT_RESULT_OK(appStatsResult);
Ken Chen0dd74952022-06-06 18:25:18 +0800289 EXPECT_EQ((uint64_t)RXPACKETS, appStatsResult.value().rxPackets);
290 EXPECT_EQ((uint64_t)RXBYTES, appStatsResult.value().rxBytes);
Wayne Ma4d692332022-01-19 16:04:04 +0800291 }
Wayne Ma7be6bce2022-01-12 16:29:49 +0800292
293 Status updateUidOwnerMaps(const std::vector<uint32_t>& appUids,
294 UidOwnerMatchType matchType, TrafficController::IptOp op) {
295 Status ret(0);
296 for (auto uid : appUids) {
297 ret = mTc.updateUidOwnerMap(uid, matchType, op);
298 if(!isOk(ret)) break;
299 }
300 return ret;
301 }
302
Ken Chen2fb86362022-06-05 11:39:38 +0800303 Status dump(bool verbose, std::vector<std::string>& outputLines) {
304 if (!outputLines.empty()) return statusFromErrno(EUCLEAN, "Output buffer is not empty");
305
306 android::base::unique_fd localFd, remoteFd;
307 if (!Pipe(&localFd, &remoteFd)) return statusFromErrno(errno, "Failed on pipe");
308
309 // dump() blocks until another thread has consumed all its output.
310 std::thread dumpThread =
311 std::thread([this, remoteFd{std::move(remoteFd)}, verbose]() {
312 mTc.dump(remoteFd, verbose);
313 });
314
315 std::string dumpContent;
316 if (!android::base::ReadFdToString(localFd.get(), &dumpContent)) {
317 return statusFromErrno(errno, "Failed to read dump results from fd");
318 }
319 dumpThread.join();
320
321 std::stringstream dumpStream(std::move(dumpContent));
322 std::string line;
323 while (std::getline(dumpStream, line)) {
324 outputLines.push_back(line);
325 }
326
327 return netdutils::status::ok;
328 }
329
330 // Strings in the |expect| must exist in dump results in order. But no need to be consecutive.
331 bool expectDumpsysContains(std::vector<std::string>& expect) {
332 if (expect.empty()) return false;
333
334 std::vector<std::string> output;
335 Status result = dump(true, output);
336 if (!isOk(result)) {
337 GTEST_LOG_(ERROR) << "TrafficController dump failed: " << netdutils::toString(result);
338 return false;
339 }
340
341 int matched = 0;
342 auto it = expect.begin();
343 for (const auto& line : output) {
344 if (it == expect.end()) break;
345 if (std::string::npos != line.find(*it)) {
346 matched++;
347 ++it;
348 }
349 }
Ken Chen0dd74952022-06-06 18:25:18 +0800350
351 if (matched != expect.size()) {
352 // dump results for debugging
353 for (const auto& o : output) LOG(INFO) << "output: " << o;
354 for (const auto& e : expect) LOG(INFO) << "expect: " << e;
355 return false;
356 }
357 return true;
Ken Chen2fb86362022-06-05 11:39:38 +0800358 }
Wayne Ma4d692332022-01-19 16:04:04 +0800359};
360
Wayne Ma4d692332022-01-19 16:04:04 +0800361TEST_F(TrafficControllerTest, TestUpdateOwnerMapEntry) {
362 uint32_t uid = TEST_UID;
363 ASSERT_TRUE(isOk(mTc.updateOwnerMapEntry(STANDBY_MATCH, uid, DENY, DENYLIST)));
364 Result<UidOwnerValue> value = mFakeUidOwnerMap.readValue(uid);
365 ASSERT_RESULT_OK(value);
366 ASSERT_TRUE(value.value().rule & STANDBY_MATCH);
367
368 ASSERT_TRUE(isOk(mTc.updateOwnerMapEntry(DOZABLE_MATCH, uid, ALLOW, ALLOWLIST)));
369 value = mFakeUidOwnerMap.readValue(uid);
370 ASSERT_RESULT_OK(value);
371 ASSERT_TRUE(value.value().rule & DOZABLE_MATCH);
372
373 ASSERT_TRUE(isOk(mTc.updateOwnerMapEntry(DOZABLE_MATCH, uid, DENY, ALLOWLIST)));
374 value = mFakeUidOwnerMap.readValue(uid);
375 ASSERT_RESULT_OK(value);
376 ASSERT_FALSE(value.value().rule & DOZABLE_MATCH);
377
378 ASSERT_TRUE(isOk(mTc.updateOwnerMapEntry(STANDBY_MATCH, uid, ALLOW, DENYLIST)));
379 ASSERT_FALSE(mFakeUidOwnerMap.readValue(uid).ok());
380
381 uid = TEST_UID2;
382 ASSERT_FALSE(isOk(mTc.updateOwnerMapEntry(STANDBY_MATCH, uid, ALLOW, DENYLIST)));
383 ASSERT_FALSE(mFakeUidOwnerMap.readValue(uid).ok());
384}
385
386TEST_F(TrafficControllerTest, TestChangeUidOwnerRule) {
387 checkUidOwnerRuleForChain(DOZABLE, DOZABLE_MATCH);
388 checkUidOwnerRuleForChain(STANDBY, STANDBY_MATCH);
389 checkUidOwnerRuleForChain(POWERSAVE, POWERSAVE_MATCH);
390 checkUidOwnerRuleForChain(RESTRICTED, RESTRICTED_MATCH);
Robert Horvathd945bf02022-01-27 19:55:16 +0100391 checkUidOwnerRuleForChain(LOW_POWER_STANDBY, LOW_POWER_STANDBY_MATCH);
Motomu Utsumib08654c2022-05-11 05:56:26 +0000392 checkUidOwnerRuleForChain(LOCKDOWN, LOCKDOWN_VPN_MATCH);
Motomu Utsumid9801492022-06-01 13:57:27 +0000393 checkUidOwnerRuleForChain(OEM_DENY_1, OEM_DENY_1_MATCH);
394 checkUidOwnerRuleForChain(OEM_DENY_2, OEM_DENY_2_MATCH);
Wayne Ma4d692332022-01-19 16:04:04 +0800395 ASSERT_EQ(-EINVAL, mTc.changeUidOwnerRule(NONE, TEST_UID, ALLOW, ALLOWLIST));
396 ASSERT_EQ(-EINVAL, mTc.changeUidOwnerRule(INVALID_CHAIN, TEST_UID, ALLOW, ALLOWLIST));
397}
398
399TEST_F(TrafficControllerTest, TestReplaceUidOwnerMap) {
400 std::vector<int32_t> uids = {TEST_UID, TEST_UID2, TEST_UID3};
401 checkUidMapReplace("fw_dozable", uids, DOZABLE_MATCH);
402 checkUidMapReplace("fw_standby", uids, STANDBY_MATCH);
403 checkUidMapReplace("fw_powersave", uids, POWERSAVE_MATCH);
404 checkUidMapReplace("fw_restricted", uids, RESTRICTED_MATCH);
Robert Horvathd945bf02022-01-27 19:55:16 +0100405 checkUidMapReplace("fw_low_power_standby", uids, LOW_POWER_STANDBY_MATCH);
Motomu Utsumid9801492022-06-01 13:57:27 +0000406 checkUidMapReplace("fw_oem_deny_1", uids, OEM_DENY_1_MATCH);
407 checkUidMapReplace("fw_oem_deny_2", uids, OEM_DENY_2_MATCH);
Wayne Ma4d692332022-01-19 16:04:04 +0800408 ASSERT_EQ(-EINVAL, mTc.replaceUidOwnerMap("unknow", true, uids));
409}
410
411TEST_F(TrafficControllerTest, TestReplaceSameChain) {
412 std::vector<int32_t> uids = {TEST_UID, TEST_UID2, TEST_UID3};
413 checkUidMapReplace("fw_dozable", uids, DOZABLE_MATCH);
414 std::vector<int32_t> newUids = {TEST_UID2, TEST_UID3};
415 checkUidMapReplace("fw_dozable", newUids, DOZABLE_MATCH);
416}
417
418TEST_F(TrafficControllerTest, TestDenylistUidMatch) {
419 std::vector<uint32_t> appUids = {1000, 1001, 10012};
Wayne Ma7be6bce2022-01-12 16:29:49 +0800420 ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, PENALTY_BOX_MATCH,
421 TrafficController::IptOpInsert)));
Wayne Ma4d692332022-01-19 16:04:04 +0800422 expectUidOwnerMapValues(appUids, PENALTY_BOX_MATCH, 0);
Wayne Ma7be6bce2022-01-12 16:29:49 +0800423 ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, PENALTY_BOX_MATCH,
424 TrafficController::IptOpDelete)));
Wayne Ma4d692332022-01-19 16:04:04 +0800425 expectMapEmpty(mFakeUidOwnerMap);
426}
427
428TEST_F(TrafficControllerTest, TestAllowlistUidMatch) {
429 std::vector<uint32_t> appUids = {1000, 1001, 10012};
Wayne Ma7be6bce2022-01-12 16:29:49 +0800430 ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, HAPPY_BOX_MATCH, TrafficController::IptOpInsert)));
Wayne Ma4d692332022-01-19 16:04:04 +0800431 expectUidOwnerMapValues(appUids, HAPPY_BOX_MATCH, 0);
Wayne Ma7be6bce2022-01-12 16:29:49 +0800432 ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, HAPPY_BOX_MATCH, TrafficController::IptOpDelete)));
Wayne Ma4d692332022-01-19 16:04:04 +0800433 expectMapEmpty(mFakeUidOwnerMap);
434}
435
436TEST_F(TrafficControllerTest, TestReplaceMatchUid) {
437 std::vector<uint32_t> appUids = {1000, 1001, 10012};
438 // Add appUids to the denylist and expect that their values are all PENALTY_BOX_MATCH.
Wayne Ma7be6bce2022-01-12 16:29:49 +0800439 ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, PENALTY_BOX_MATCH,
440 TrafficController::IptOpInsert)));
Wayne Ma4d692332022-01-19 16:04:04 +0800441 expectUidOwnerMapValues(appUids, PENALTY_BOX_MATCH, 0);
442
443 // Add the same UIDs to the allowlist and expect that we get PENALTY_BOX_MATCH |
444 // HAPPY_BOX_MATCH.
Wayne Ma7be6bce2022-01-12 16:29:49 +0800445 ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, HAPPY_BOX_MATCH, TrafficController::IptOpInsert)));
Wayne Ma4d692332022-01-19 16:04:04 +0800446 expectUidOwnerMapValues(appUids, HAPPY_BOX_MATCH | PENALTY_BOX_MATCH, 0);
447
448 // Remove the same UIDs from the allowlist and check the PENALTY_BOX_MATCH is still there.
Wayne Ma7be6bce2022-01-12 16:29:49 +0800449 ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, HAPPY_BOX_MATCH, TrafficController::IptOpDelete)));
Wayne Ma4d692332022-01-19 16:04:04 +0800450 expectUidOwnerMapValues(appUids, PENALTY_BOX_MATCH, 0);
451
452 // Remove the same UIDs from the denylist and check the map is empty.
Wayne Ma7be6bce2022-01-12 16:29:49 +0800453 ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, PENALTY_BOX_MATCH,
454 TrafficController::IptOpDelete)));
Wayne Ma4d692332022-01-19 16:04:04 +0800455 ASSERT_FALSE(mFakeUidOwnerMap.getFirstKey().ok());
456}
457
458TEST_F(TrafficControllerTest, TestDeleteWrongMatchSilentlyFails) {
459 std::vector<uint32_t> appUids = {1000, 1001, 10012};
460 // 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 +0800461 ASSERT_FALSE(isOk(updateUidOwnerMaps(appUids, HAPPY_BOX_MATCH,
462 TrafficController::IptOpDelete)));
Wayne Ma4d692332022-01-19 16:04:04 +0800463 expectMapEmpty(mFakeUidOwnerMap);
464
465 // Add denylist rules for appUids.
Wayne Ma7be6bce2022-01-12 16:29:49 +0800466 ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, HAPPY_BOX_MATCH,
467 TrafficController::IptOpInsert)));
Wayne Ma4d692332022-01-19 16:04:04 +0800468 expectUidOwnerMapValues(appUids, HAPPY_BOX_MATCH, 0);
469
470 // Delete (non-existent) denylist rules for appUids, and check that this silently does
471 // nothing if the uid is in the map but does not have denylist match. This is required because
472 // NetworkManagementService will try to remove a uid from denylist after adding it to the
473 // allowlist and if the remove fails it will not update the uid status.
Wayne Ma7be6bce2022-01-12 16:29:49 +0800474 ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, PENALTY_BOX_MATCH,
475 TrafficController::IptOpDelete)));
Wayne Ma4d692332022-01-19 16:04:04 +0800476 expectUidOwnerMapValues(appUids, HAPPY_BOX_MATCH, 0);
477}
478
479TEST_F(TrafficControllerTest, TestAddUidInterfaceFilteringRules) {
480 int iif0 = 15;
481 ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif0, {1000, 1001})));
482 expectUidOwnerMapValues({1000, 1001}, IIF_MATCH, iif0);
483
484 // Add some non-overlapping new uids. They should coexist with existing rules
485 int iif1 = 16;
486 ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif1, {2000, 2001})));
487 expectUidOwnerMapValues({1000, 1001}, IIF_MATCH, iif0);
488 expectUidOwnerMapValues({2000, 2001}, IIF_MATCH, iif1);
489
490 // Overwrite some existing uids
491 int iif2 = 17;
492 ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif2, {1000, 2000})));
493 expectUidOwnerMapValues({1001}, IIF_MATCH, iif0);
494 expectUidOwnerMapValues({2001}, IIF_MATCH, iif1);
495 expectUidOwnerMapValues({1000, 2000}, IIF_MATCH, iif2);
496}
497
498TEST_F(TrafficControllerTest, TestRemoveUidInterfaceFilteringRules) {
499 int iif0 = 15;
500 int iif1 = 16;
501 ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif0, {1000, 1001})));
502 ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif1, {2000, 2001})));
503 expectUidOwnerMapValues({1000, 1001}, IIF_MATCH, iif0);
504 expectUidOwnerMapValues({2000, 2001}, IIF_MATCH, iif1);
505
506 // Rmove some uids
507 ASSERT_TRUE(isOk(mTc.removeUidInterfaceRules({1001, 2001})));
508 expectUidOwnerMapValues({1000}, IIF_MATCH, iif0);
509 expectUidOwnerMapValues({2000}, IIF_MATCH, iif1);
510 checkEachUidValue({1000, 2000}, IIF_MATCH); // Make sure there are only two uids remaining
511
512 // Remove non-existent uids shouldn't fail
513 ASSERT_TRUE(isOk(mTc.removeUidInterfaceRules({2000, 3000})));
514 expectUidOwnerMapValues({1000}, IIF_MATCH, iif0);
515 checkEachUidValue({1000}, IIF_MATCH); // Make sure there are only one uid remaining
516
517 // Remove everything
518 ASSERT_TRUE(isOk(mTc.removeUidInterfaceRules({1000})));
519 expectMapEmpty(mFakeUidOwnerMap);
520}
521
522TEST_F(TrafficControllerTest, TestUidInterfaceFilteringRulesCoexistWithExistingMatches) {
523 // Set up existing PENALTY_BOX_MATCH rules
Wayne Ma7be6bce2022-01-12 16:29:49 +0800524 ASSERT_TRUE(isOk(updateUidOwnerMaps({1000, 1001, 10012}, PENALTY_BOX_MATCH,
525 TrafficController::IptOpInsert)));
Wayne Ma4d692332022-01-19 16:04:04 +0800526 expectUidOwnerMapValues({1000, 1001, 10012}, PENALTY_BOX_MATCH, 0);
527
528 // Add some partially-overlapping uid owner rules and check result
529 int iif1 = 32;
530 ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif1, {10012, 10013, 10014})));
531 expectUidOwnerMapValues({1000, 1001}, PENALTY_BOX_MATCH, 0);
532 expectUidOwnerMapValues({10012}, PENALTY_BOX_MATCH | IIF_MATCH, iif1);
533 expectUidOwnerMapValues({10013, 10014}, IIF_MATCH, iif1);
534
535 // Removing some PENALTY_BOX_MATCH rules should not change uid interface rule
Wayne Ma7be6bce2022-01-12 16:29:49 +0800536 ASSERT_TRUE(isOk(updateUidOwnerMaps({1001, 10012}, PENALTY_BOX_MATCH,
537 TrafficController::IptOpDelete)));
Wayne Ma4d692332022-01-19 16:04:04 +0800538 expectUidOwnerMapValues({1000}, PENALTY_BOX_MATCH, 0);
539 expectUidOwnerMapValues({10012, 10013, 10014}, IIF_MATCH, iif1);
540
541 // Remove all uid interface rules
542 ASSERT_TRUE(isOk(mTc.removeUidInterfaceRules({10012, 10013, 10014})));
543 expectUidOwnerMapValues({1000}, PENALTY_BOX_MATCH, 0);
544 // Make sure these are the only uids left
545 checkEachUidValue({1000}, PENALTY_BOX_MATCH);
546}
547
548TEST_F(TrafficControllerTest, TestUidInterfaceFilteringRulesCoexistWithNewMatches) {
549 int iif1 = 56;
550 // Set up existing uid interface rules
551 ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif1, {10001, 10002})));
552 expectUidOwnerMapValues({10001, 10002}, IIF_MATCH, iif1);
553
554 // Add some partially-overlapping doze rules
555 EXPECT_EQ(0, mTc.replaceUidOwnerMap("fw_dozable", true, {10002, 10003}));
556 expectUidOwnerMapValues({10001}, IIF_MATCH, iif1);
557 expectUidOwnerMapValues({10002}, DOZABLE_MATCH | IIF_MATCH, iif1);
558 expectUidOwnerMapValues({10003}, DOZABLE_MATCH, 0);
559
560 // Introduce a third rule type (powersave) on various existing UIDs
561 EXPECT_EQ(0, mTc.replaceUidOwnerMap("fw_powersave", true, {10000, 10001, 10002, 10003}));
562 expectUidOwnerMapValues({10000}, POWERSAVE_MATCH, 0);
563 expectUidOwnerMapValues({10001}, POWERSAVE_MATCH | IIF_MATCH, iif1);
564 expectUidOwnerMapValues({10002}, POWERSAVE_MATCH | DOZABLE_MATCH | IIF_MATCH, iif1);
565 expectUidOwnerMapValues({10003}, POWERSAVE_MATCH | DOZABLE_MATCH, 0);
566
567 // Remove all doze rules
568 EXPECT_EQ(0, mTc.replaceUidOwnerMap("fw_dozable", true, {}));
569 expectUidOwnerMapValues({10000}, POWERSAVE_MATCH, 0);
570 expectUidOwnerMapValues({10001}, POWERSAVE_MATCH | IIF_MATCH, iif1);
571 expectUidOwnerMapValues({10002}, POWERSAVE_MATCH | IIF_MATCH, iif1);
572 expectUidOwnerMapValues({10003}, POWERSAVE_MATCH, 0);
573
574 // Remove all powersave rules, expect ownerMap to only have uid interface rules left
575 EXPECT_EQ(0, mTc.replaceUidOwnerMap("fw_powersave", true, {}));
576 expectUidOwnerMapValues({10001, 10002}, IIF_MATCH, iif1);
577 // Make sure these are the only uids left
578 checkEachUidValue({10001, 10002}, IIF_MATCH);
579}
580
Motomu Utsumib08654c2022-05-11 05:56:26 +0000581TEST_F(TrafficControllerTest, TestAddUidInterfaceFilteringRulesWithWildcard) {
582 // iif=0 is a wildcard
583 int iif = 0;
584 // Add interface rule with wildcard to uids
585 ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif, {1000, 1001})));
586 expectUidOwnerMapValues({1000, 1001}, IIF_MATCH, iif);
587}
588
589TEST_F(TrafficControllerTest, TestRemoveUidInterfaceFilteringRulesWithWildcard) {
590 // iif=0 is a wildcard
591 int iif = 0;
592 // Add interface rule with wildcard to two uids
593 ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif, {1000, 1001})));
594 expectUidOwnerMapValues({1000, 1001}, IIF_MATCH, iif);
595
596 // Remove interface rule from one of the uids
597 ASSERT_TRUE(isOk(mTc.removeUidInterfaceRules({1000})));
598 expectUidOwnerMapValues({1001}, IIF_MATCH, iif);
599 checkEachUidValue({1001}, IIF_MATCH);
600
601 // Remove interface rule from the remaining uid
602 ASSERT_TRUE(isOk(mTc.removeUidInterfaceRules({1001})));
603 expectMapEmpty(mFakeUidOwnerMap);
604}
605
606TEST_F(TrafficControllerTest, TestUidInterfaceFilteringRulesWithWildcardAndExistingMatches) {
607 // Set up existing DOZABLE_MATCH and POWERSAVE_MATCH rule
608 ASSERT_TRUE(isOk(updateUidOwnerMaps({1000}, DOZABLE_MATCH,
609 TrafficController::IptOpInsert)));
610 ASSERT_TRUE(isOk(updateUidOwnerMaps({1000}, POWERSAVE_MATCH,
611 TrafficController::IptOpInsert)));
612
613 // iif=0 is a wildcard
614 int iif = 0;
615 // Add interface rule with wildcard to the existing uid
616 ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif, {1000})));
617 expectUidOwnerMapValues({1000}, POWERSAVE_MATCH | DOZABLE_MATCH | IIF_MATCH, iif);
618
619 // Remove interface rule with wildcard from the existing uid
620 ASSERT_TRUE(isOk(mTc.removeUidInterfaceRules({1000})));
621 expectUidOwnerMapValues({1000}, POWERSAVE_MATCH | DOZABLE_MATCH, 0);
622}
623
624TEST_F(TrafficControllerTest, TestUidInterfaceFilteringRulesWithWildcardAndNewMatches) {
625 // iif=0 is a wildcard
626 int iif = 0;
627 // Set up existing interface rule with wildcard
628 ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif, {1000})));
629
630 // Add DOZABLE_MATCH and POWERSAVE_MATCH rule to the existing uid
631 ASSERT_TRUE(isOk(updateUidOwnerMaps({1000}, DOZABLE_MATCH,
632 TrafficController::IptOpInsert)));
633 ASSERT_TRUE(isOk(updateUidOwnerMaps({1000}, POWERSAVE_MATCH,
634 TrafficController::IptOpInsert)));
635 expectUidOwnerMapValues({1000}, POWERSAVE_MATCH | DOZABLE_MATCH | IIF_MATCH, iif);
636
637 // Remove DOZABLE_MATCH and POWERSAVE_MATCH rule from the existing uid
638 ASSERT_TRUE(isOk(updateUidOwnerMaps({1000}, DOZABLE_MATCH,
639 TrafficController::IptOpDelete)));
640 ASSERT_TRUE(isOk(updateUidOwnerMaps({1000}, POWERSAVE_MATCH,
641 TrafficController::IptOpDelete)));
642 expectUidOwnerMapValues({1000}, IIF_MATCH, iif);
643}
644
Wayne Ma4d692332022-01-19 16:04:04 +0800645TEST_F(TrafficControllerTest, TestGrantInternetPermission) {
646 std::vector<uid_t> appUids = {TEST_UID, TEST_UID2, TEST_UID3};
647
648 mTc.setPermissionForUids(INetd::PERMISSION_INTERNET, appUids);
649 expectMapEmpty(mFakeUidPermissionMap);
650 expectPrivilegedUserSetEmpty();
651}
652
653TEST_F(TrafficControllerTest, TestRevokeInternetPermission) {
654 std::vector<uid_t> appUids = {TEST_UID, TEST_UID2, TEST_UID3};
655
656 mTc.setPermissionForUids(INetd::PERMISSION_NONE, appUids);
657 expectUidPermissionMapValues(appUids, INetd::PERMISSION_NONE);
658}
659
660TEST_F(TrafficControllerTest, TestPermissionUninstalled) {
661 std::vector<uid_t> appUids = {TEST_UID, TEST_UID2, TEST_UID3};
662
663 mTc.setPermissionForUids(INetd::PERMISSION_UPDATE_DEVICE_STATS, appUids);
664 expectUidPermissionMapValues(appUids, INetd::PERMISSION_UPDATE_DEVICE_STATS);
665 expectPrivilegedUserSet(appUids);
666
667 std::vector<uid_t> uidToRemove = {TEST_UID};
668 mTc.setPermissionForUids(INetd::PERMISSION_UNINSTALLED, uidToRemove);
669
670 std::vector<uid_t> uidRemain = {TEST_UID3, TEST_UID2};
671 expectUidPermissionMapValues(uidRemain, INetd::PERMISSION_UPDATE_DEVICE_STATS);
672 expectPrivilegedUserSet(uidRemain);
673
674 mTc.setPermissionForUids(INetd::PERMISSION_UNINSTALLED, uidRemain);
675 expectMapEmpty(mFakeUidPermissionMap);
676 expectPrivilegedUserSetEmpty();
677}
678
679TEST_F(TrafficControllerTest, TestGrantUpdateStatsPermission) {
680 std::vector<uid_t> appUids = {TEST_UID, TEST_UID2, TEST_UID3};
681
682 mTc.setPermissionForUids(INetd::PERMISSION_UPDATE_DEVICE_STATS, appUids);
683 expectUidPermissionMapValues(appUids, INetd::PERMISSION_UPDATE_DEVICE_STATS);
684 expectPrivilegedUserSet(appUids);
685
686 mTc.setPermissionForUids(INetd::PERMISSION_NONE, appUids);
687 expectPrivilegedUserSetEmpty();
688 expectUidPermissionMapValues(appUids, INetd::PERMISSION_NONE);
689}
690
691TEST_F(TrafficControllerTest, TestRevokeUpdateStatsPermission) {
692 std::vector<uid_t> appUids = {TEST_UID, TEST_UID2, TEST_UID3};
693
694 mTc.setPermissionForUids(INetd::PERMISSION_UPDATE_DEVICE_STATS, appUids);
695 expectPrivilegedUserSet(appUids);
696
697 std::vector<uid_t> uidToRemove = {TEST_UID};
698 mTc.setPermissionForUids(INetd::PERMISSION_NONE, uidToRemove);
699
700 std::vector<uid_t> uidRemain = {TEST_UID3, TEST_UID2};
701 expectPrivilegedUserSet(uidRemain);
702
703 mTc.setPermissionForUids(INetd::PERMISSION_NONE, uidRemain);
704 expectPrivilegedUserSetEmpty();
705}
706
707TEST_F(TrafficControllerTest, TestGrantWrongPermission) {
708 std::vector<uid_t> appUids = {TEST_UID, TEST_UID2, TEST_UID3};
709
710 mTc.setPermissionForUids(INetd::PERMISSION_NONE, appUids);
711 expectPrivilegedUserSetEmpty();
712 expectUidPermissionMapValues(appUids, INetd::PERMISSION_NONE);
713}
714
715TEST_F(TrafficControllerTest, TestGrantDuplicatePermissionSlientlyFail) {
716 std::vector<uid_t> appUids = {TEST_UID, TEST_UID2, TEST_UID3};
717
718 mTc.setPermissionForUids(INetd::PERMISSION_INTERNET, appUids);
719 expectMapEmpty(mFakeUidPermissionMap);
720
721 std::vector<uid_t> uidToAdd = {TEST_UID};
722 mTc.setPermissionForUids(INetd::PERMISSION_INTERNET, uidToAdd);
723
724 expectPrivilegedUserSetEmpty();
725
726 mTc.setPermissionForUids(INetd::PERMISSION_NONE, appUids);
727 expectUidPermissionMapValues(appUids, INetd::PERMISSION_NONE);
728
729 mTc.setPermissionForUids(INetd::PERMISSION_UPDATE_DEVICE_STATS, appUids);
730 expectPrivilegedUserSet(appUids);
731
732 mTc.setPermissionForUids(INetd::PERMISSION_UPDATE_DEVICE_STATS, uidToAdd);
733 expectPrivilegedUserSet(appUids);
734
735 mTc.setPermissionForUids(INetd::PERMISSION_NONE, appUids);
736 expectPrivilegedUserSetEmpty();
737}
738
Ken Chen2fb86362022-06-05 11:39:38 +0800739TEST_F(TrafficControllerTest, TestDumpsys) {
Ken Chen0dd74952022-06-06 18:25:18 +0800740 StatsKey tagStatsMapKey;
741 populateFakeStats(TEST_COOKIE, TEST_UID, TEST_TAG, &tagStatsMapKey);
742 populateFakeCounterSet(TEST_UID3, TEST_COUNTERSET);
Ken Chen2fb86362022-06-05 11:39:38 +0800743
Ken Chen0dd74952022-06-06 18:25:18 +0800744 // Expect: (part of this depends on hard-code values in populateFakeStats())
745 //
746 // mCookieTagMap:
747 // cookie=1 tag=0x2a uid=10086
748 //
749 // mUidCounterSetMap:
750 // 98765 1
751 //
752 // mAppUidStatsMap::
753 // uid rxBytes rxPackets txBytes txPackets
754 // 10086 100 1 0 0
755 //
756 // mStatsMapA:
757 // ifaceIndex ifaceName tag_hex uid_int cnt_set rxBytes rxPackets txBytes txPackets
758 // 999 test0 0x2a 10086 1 100 1 0 0
Ken Chen2fb86362022-06-05 11:39:38 +0800759 std::vector<std::string> expectedLines = {
Ken Chen0dd74952022-06-06 18:25:18 +0800760 "mCookieTagMap:",
761 fmt::format("cookie={} tag={:#x} uid={}", TEST_COOKIE, TEST_TAG, TEST_UID),
762 "mUidCounterSetMap:",
763 fmt::format("{} {}", TEST_UID3, TEST_COUNTERSET),
764 "mAppUidStatsMap::", // TODO@: fix double colon
765 "uid rxBytes rxPackets txBytes txPackets",
766 fmt::format("{} {} {} {} {}", TEST_UID, RXBYTES, RXPACKETS, TXBYTES, TXPACKETS),
767 "mStatsMapA",
768 "ifaceIndex ifaceName tag_hex uid_int cnt_set rxBytes rxPackets txBytes txPackets",
769 fmt::format("{} {} {:#x} {} {} {} {} {} {}",
770 TEST_IFINDEX, TEST_IFNAME, TEST_TAG, TEST_UID, TEST_COUNTERSET, RXBYTES,
771 RXPACKETS, TXBYTES, TXPACKETS)};
Ken Chen2fb86362022-06-05 11:39:38 +0800772
Ken Chen0dd74952022-06-06 18:25:18 +0800773 populateFakeIfaceIndexName(TEST_IFNAME, TEST_IFINDEX);
774 expectedLines.emplace_back("mIfaceIndexNameMap:");
775 expectedLines.emplace_back(fmt::format("ifaceIndex={} ifaceName={}",
776 TEST_IFINDEX, TEST_IFNAME));
777
778 ASSERT_TRUE(isOk(updateUidOwnerMaps({TEST_UID}, HAPPY_BOX_MATCH,
779 TrafficController::IptOpInsert)));
780 expectedLines.emplace_back("mUidOwnerMap:");
781 expectedLines.emplace_back(fmt::format("{} HAPPY_BOX_MATCH", TEST_UID));
782
783 mTc.setPermissionForUids(INetd::PERMISSION_UPDATE_DEVICE_STATS, {TEST_UID2});
784 expectedLines.emplace_back("mUidPermissionMap:");
785 expectedLines.emplace_back(fmt::format("{} BPF_PERMISSION_UPDATE_DEVICE_STATS", TEST_UID2));
786 expectedLines.emplace_back("mPrivilegedUser:");
787 expectedLines.emplace_back(fmt::format("{} ALLOW_UPDATE_DEVICE_STATS", TEST_UID2));
Ken Chen2fb86362022-06-05 11:39:38 +0800788 EXPECT_TRUE(expectDumpsysContains(expectedLines));
789}
790
Ken Chen77a6b712022-06-06 12:46:36 +0800791TEST_F(TrafficControllerTest, getFirewallType) {
792 static const struct TestConfig {
793 ChildChain childChain;
794 FirewallType firewallType;
795 } testConfigs[] = {
796 // clang-format off
797 {NONE, DENYLIST},
798 {DOZABLE, ALLOWLIST},
799 {STANDBY, DENYLIST},
800 {POWERSAVE, ALLOWLIST},
801 {RESTRICTED, ALLOWLIST},
802 {LOW_POWER_STANDBY, ALLOWLIST},
803 {LOCKDOWN, DENYLIST},
804 {OEM_DENY_1, DENYLIST},
805 {OEM_DENY_2, DENYLIST},
806 {INVALID_CHAIN, DENYLIST},
807 // clang-format on
808 };
809
810 for (const auto& config : testConfigs) {
811 SCOPED_TRACE(fmt::format("testConfig: [{}, {}]", config.childChain, config.firewallType));
812 EXPECT_EQ(config.firewallType, mTc.getFirewallType(config.childChain));
813 }
814}
815
Patrick Rohr61e94672022-02-01 21:06:40 +0100816constexpr uint32_t SOCK_CLOSE_WAIT_US = 30 * 1000;
817constexpr uint32_t ENOBUFS_POLL_WAIT_US = 10 * 1000;
818
819using android::base::Error;
820using android::base::Result;
821using android::bpf::BpfMap;
822
823// This test set up a SkDestroyListener that is running parallel with the production
824// SkDestroyListener. The test will create thousands of sockets and tag them on the
825// production cookieUidTagMap and close them in a short time. When the number of
826// sockets get closed exceeds the buffer size, it will start to return ENOBUFF
827// error. The error will be ignored by the production SkDestroyListener and the
828// test will clean up the tags in tearDown if there is any remains.
829
830// TODO: Instead of test the ENOBUFF error, we can test the production
831// SkDestroyListener to see if it failed to delete a tagged socket when ENOBUFF
832// triggered.
833class NetlinkListenerTest : public testing::Test {
834 protected:
835 NetlinkListenerTest() {}
836 BpfMap<uint64_t, UidTagValue> mCookieTagMap;
837
838 void SetUp() {
Maciej Żenczykowskiced35312022-05-31 05:11:12 -0700839 mCookieTagMap.init(COOKIE_TAG_MAP_PATH);
Patrick Rohr61e94672022-02-01 21:06:40 +0100840 ASSERT_TRUE(mCookieTagMap.isValid());
841 }
842
843 void TearDown() {
844 const auto deleteTestCookieEntries = [](const uint64_t& key, const UidTagValue& value,
845 BpfMap<uint64_t, UidTagValue>& map) {
846 if ((value.uid == TEST_UID) && (value.tag == TEST_TAG)) {
847 Result<void> res = map.deleteValue(key);
848 if (res.ok() || (res.error().code() == ENOENT)) {
849 return Result<void>();
850 }
Maciej Żenczykowskie0f58462022-05-17 13:59:22 -0700851 ALOGE("Failed to delete data(cookie = %" PRIu64 "): %s", key,
Patrick Rohr61e94672022-02-01 21:06:40 +0100852 strerror(res.error().code()));
853 }
854 // Move forward to next cookie in the map.
855 return Result<void>();
856 };
857 EXPECT_RESULT_OK(mCookieTagMap.iterateWithValue(deleteTestCookieEntries));
858 }
859
860 Result<void> checkNoGarbageTagsExist() {
861 const auto checkGarbageTags = [](const uint64_t&, const UidTagValue& value,
862 const BpfMap<uint64_t, UidTagValue>&) -> Result<void> {
863 if ((TEST_UID == value.uid) && (TEST_TAG == value.tag)) {
864 return Error(EUCLEAN) << "Closed socket is not untagged";
865 }
866 return {};
867 };
868 return mCookieTagMap.iterateWithValue(checkGarbageTags);
869 }
870
871 bool checkMassiveSocketDestroy(int totalNumber, bool expectError) {
872 std::unique_ptr<android::netdutils::NetlinkListenerInterface> skDestroyListener;
873 auto result = android::net::TrafficController::makeSkDestroyListener();
874 if (!isOk(result)) {
875 ALOGE("Unable to create SkDestroyListener: %s", toString(result).c_str());
876 } else {
877 skDestroyListener = std::move(result.value());
878 }
879 int rxErrorCount = 0;
880 // Rx handler extracts nfgenmsg looks up and invokes registered dispatch function.
881 const auto rxErrorHandler = [&rxErrorCount](const int, const int) { rxErrorCount++; };
882 skDestroyListener->registerSkErrorHandler(rxErrorHandler);
883 int fds[totalNumber];
884 for (int i = 0; i < totalNumber; i++) {
885 fds[i] = socket(AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0);
886 // The likely reason for a failure is running out of available file descriptors.
887 EXPECT_LE(0, fds[i]) << i << " of " << totalNumber;
888 if (fds[i] < 0) {
889 // EXPECT_LE already failed above, so test case is a failure, but we don't
890 // want potentially tens of thousands of extra failures creating and then
891 // closing all these fds cluttering up the logs.
892 totalNumber = i;
893 break;
894 };
895 libnetd_updatable_tagSocket(fds[i], TEST_TAG, TEST_UID, 1000);
896 }
897
898 // TODO: Use a separate thread that has its own fd table so we can
899 // close sockets even faster simply by terminating that thread.
900 for (int i = 0; i < totalNumber; i++) {
901 EXPECT_EQ(0, close(fds[i]));
902 }
903 // wait a bit for netlink listener to handle all the messages.
904 usleep(SOCK_CLOSE_WAIT_US);
905 if (expectError) {
906 // If ENOBUFS triggered, check it only called into the handler once, ie.
907 // that the netlink handler is not spinning.
908 int currentErrorCount = rxErrorCount;
909 // 0 error count is acceptable because the system has chances to close all sockets
910 // normally.
911 EXPECT_LE(0, rxErrorCount);
912 if (!rxErrorCount) return true;
913
914 usleep(ENOBUFS_POLL_WAIT_US);
915 EXPECT_EQ(currentErrorCount, rxErrorCount);
916 } else {
917 EXPECT_RESULT_OK(checkNoGarbageTagsExist());
918 EXPECT_EQ(0, rxErrorCount);
919 }
920 return false;
921 }
922};
923
924TEST_F(NetlinkListenerTest, TestAllSocketUntagged) {
925 checkMassiveSocketDestroy(10, false);
926 checkMassiveSocketDestroy(100, false);
927}
928
929// Disabled because flaky on blueline-userdebug; this test relies on the main thread
930// winning a race against the NetlinkListener::run() thread. There's no way to ensure
931// things will be scheduled the same way across all architectures and test environments.
932TEST_F(NetlinkListenerTest, DISABLED_TestSkDestroyError) {
933 bool needRetry = false;
934 int retryCount = 0;
935 do {
936 needRetry = checkMassiveSocketDestroy(32500, true);
937 if (needRetry) retryCount++;
938 } while (needRetry && retryCount < 3);
939 // Should review test if it can always close all sockets correctly.
940 EXPECT_GT(3, retryCount);
941}
942
943
Wayne Ma4d692332022-01-19 16:04:04 +0800944} // namespace net
945} // namespace android