blob: 0b4550e2274b4b053d30eedf7a1aafaea5e54dfd [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
Motomu Utsumi8b42e6d2022-05-19 06:23:40 +0000218 void expectUidOwnerMapValues(const std::vector<uint32_t>& appUids, uint32_t expectedRule,
Wayne Ma4d692332022-01-19 16:04:04 +0800219 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 Utsumid9801492022-06-01 13:57:27 +0000392 checkUidOwnerRuleForChain(OEM_DENY_1, OEM_DENY_1_MATCH);
393 checkUidOwnerRuleForChain(OEM_DENY_2, OEM_DENY_2_MATCH);
Motomu Utsumi1d9054b2022-06-06 07:44:05 +0000394 checkUidOwnerRuleForChain(OEM_DENY_3, OEM_DENY_3_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);
Motomu Utsumi1d9054b2022-06-06 07:44:05 +0000408 checkUidMapReplace("fw_oem_deny_3", uids, OEM_DENY_3_MATCH);
Wayne Ma4d692332022-01-19 16:04:04 +0800409 ASSERT_EQ(-EINVAL, mTc.replaceUidOwnerMap("unknow", true, uids));
410}
411
412TEST_F(TrafficControllerTest, TestReplaceSameChain) {
413 std::vector<int32_t> uids = {TEST_UID, TEST_UID2, TEST_UID3};
414 checkUidMapReplace("fw_dozable", uids, DOZABLE_MATCH);
415 std::vector<int32_t> newUids = {TEST_UID2, TEST_UID3};
416 checkUidMapReplace("fw_dozable", newUids, DOZABLE_MATCH);
417}
418
419TEST_F(TrafficControllerTest, TestDenylistUidMatch) {
420 std::vector<uint32_t> appUids = {1000, 1001, 10012};
Wayne Ma7be6bce2022-01-12 16:29:49 +0800421 ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, PENALTY_BOX_MATCH,
422 TrafficController::IptOpInsert)));
Wayne Ma4d692332022-01-19 16:04:04 +0800423 expectUidOwnerMapValues(appUids, PENALTY_BOX_MATCH, 0);
Wayne Ma7be6bce2022-01-12 16:29:49 +0800424 ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, PENALTY_BOX_MATCH,
425 TrafficController::IptOpDelete)));
Wayne Ma4d692332022-01-19 16:04:04 +0800426 expectMapEmpty(mFakeUidOwnerMap);
427}
428
429TEST_F(TrafficControllerTest, TestAllowlistUidMatch) {
430 std::vector<uint32_t> appUids = {1000, 1001, 10012};
Wayne Ma7be6bce2022-01-12 16:29:49 +0800431 ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, HAPPY_BOX_MATCH, TrafficController::IptOpInsert)));
Wayne Ma4d692332022-01-19 16:04:04 +0800432 expectUidOwnerMapValues(appUids, HAPPY_BOX_MATCH, 0);
Wayne Ma7be6bce2022-01-12 16:29:49 +0800433 ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, HAPPY_BOX_MATCH, TrafficController::IptOpDelete)));
Wayne Ma4d692332022-01-19 16:04:04 +0800434 expectMapEmpty(mFakeUidOwnerMap);
435}
436
437TEST_F(TrafficControllerTest, TestReplaceMatchUid) {
438 std::vector<uint32_t> appUids = {1000, 1001, 10012};
439 // Add appUids to the denylist and expect that their values are all PENALTY_BOX_MATCH.
Wayne Ma7be6bce2022-01-12 16:29:49 +0800440 ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, PENALTY_BOX_MATCH,
441 TrafficController::IptOpInsert)));
Wayne Ma4d692332022-01-19 16:04:04 +0800442 expectUidOwnerMapValues(appUids, PENALTY_BOX_MATCH, 0);
443
444 // Add the same UIDs to the allowlist and expect that we get PENALTY_BOX_MATCH |
445 // HAPPY_BOX_MATCH.
Wayne Ma7be6bce2022-01-12 16:29:49 +0800446 ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, HAPPY_BOX_MATCH, TrafficController::IptOpInsert)));
Wayne Ma4d692332022-01-19 16:04:04 +0800447 expectUidOwnerMapValues(appUids, HAPPY_BOX_MATCH | PENALTY_BOX_MATCH, 0);
448
449 // Remove the same UIDs from the allowlist and check the PENALTY_BOX_MATCH is still there.
Wayne Ma7be6bce2022-01-12 16:29:49 +0800450 ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, HAPPY_BOX_MATCH, TrafficController::IptOpDelete)));
Wayne Ma4d692332022-01-19 16:04:04 +0800451 expectUidOwnerMapValues(appUids, PENALTY_BOX_MATCH, 0);
452
453 // Remove the same UIDs from the denylist and check the map is empty.
Wayne Ma7be6bce2022-01-12 16:29:49 +0800454 ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, PENALTY_BOX_MATCH,
455 TrafficController::IptOpDelete)));
Wayne Ma4d692332022-01-19 16:04:04 +0800456 ASSERT_FALSE(mFakeUidOwnerMap.getFirstKey().ok());
457}
458
459TEST_F(TrafficControllerTest, TestDeleteWrongMatchSilentlyFails) {
460 std::vector<uint32_t> appUids = {1000, 1001, 10012};
461 // 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 +0800462 ASSERT_FALSE(isOk(updateUidOwnerMaps(appUids, HAPPY_BOX_MATCH,
463 TrafficController::IptOpDelete)));
Wayne Ma4d692332022-01-19 16:04:04 +0800464 expectMapEmpty(mFakeUidOwnerMap);
465
466 // Add denylist rules for appUids.
Wayne Ma7be6bce2022-01-12 16:29:49 +0800467 ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, HAPPY_BOX_MATCH,
468 TrafficController::IptOpInsert)));
Wayne Ma4d692332022-01-19 16:04:04 +0800469 expectUidOwnerMapValues(appUids, HAPPY_BOX_MATCH, 0);
470
471 // Delete (non-existent) denylist rules for appUids, and check that this silently does
472 // nothing if the uid is in the map but does not have denylist match. This is required because
473 // NetworkManagementService will try to remove a uid from denylist after adding it to the
474 // allowlist and if the remove fails it will not update the uid status.
Wayne Ma7be6bce2022-01-12 16:29:49 +0800475 ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, PENALTY_BOX_MATCH,
476 TrafficController::IptOpDelete)));
Wayne Ma4d692332022-01-19 16:04:04 +0800477 expectUidOwnerMapValues(appUids, HAPPY_BOX_MATCH, 0);
478}
479
480TEST_F(TrafficControllerTest, TestAddUidInterfaceFilteringRules) {
481 int iif0 = 15;
482 ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif0, {1000, 1001})));
483 expectUidOwnerMapValues({1000, 1001}, IIF_MATCH, iif0);
484
485 // Add some non-overlapping new uids. They should coexist with existing rules
486 int iif1 = 16;
487 ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif1, {2000, 2001})));
488 expectUidOwnerMapValues({1000, 1001}, IIF_MATCH, iif0);
489 expectUidOwnerMapValues({2000, 2001}, IIF_MATCH, iif1);
490
491 // Overwrite some existing uids
492 int iif2 = 17;
493 ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif2, {1000, 2000})));
494 expectUidOwnerMapValues({1001}, IIF_MATCH, iif0);
495 expectUidOwnerMapValues({2001}, IIF_MATCH, iif1);
496 expectUidOwnerMapValues({1000, 2000}, IIF_MATCH, iif2);
497}
498
499TEST_F(TrafficControllerTest, TestRemoveUidInterfaceFilteringRules) {
500 int iif0 = 15;
501 int iif1 = 16;
502 ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif0, {1000, 1001})));
503 ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif1, {2000, 2001})));
504 expectUidOwnerMapValues({1000, 1001}, IIF_MATCH, iif0);
505 expectUidOwnerMapValues({2000, 2001}, IIF_MATCH, iif1);
506
507 // Rmove some uids
508 ASSERT_TRUE(isOk(mTc.removeUidInterfaceRules({1001, 2001})));
509 expectUidOwnerMapValues({1000}, IIF_MATCH, iif0);
510 expectUidOwnerMapValues({2000}, IIF_MATCH, iif1);
511 checkEachUidValue({1000, 2000}, IIF_MATCH); // Make sure there are only two uids remaining
512
513 // Remove non-existent uids shouldn't fail
514 ASSERT_TRUE(isOk(mTc.removeUidInterfaceRules({2000, 3000})));
515 expectUidOwnerMapValues({1000}, IIF_MATCH, iif0);
516 checkEachUidValue({1000}, IIF_MATCH); // Make sure there are only one uid remaining
517
518 // Remove everything
519 ASSERT_TRUE(isOk(mTc.removeUidInterfaceRules({1000})));
520 expectMapEmpty(mFakeUidOwnerMap);
521}
522
Motomu Utsumi8b42e6d2022-05-19 06:23:40 +0000523TEST_F(TrafficControllerTest, TestUpdateUidLockdownRule) {
524 // Add Lockdown rules
525 ASSERT_TRUE(isOk(mTc.updateUidLockdownRule(1000, true /* add */)));
526 ASSERT_TRUE(isOk(mTc.updateUidLockdownRule(1001, true /* add */)));
527 expectUidOwnerMapValues({1000, 1001}, LOCKDOWN_VPN_MATCH, 0);
528
529 // Remove one of Lockdown rules
530 ASSERT_TRUE(isOk(mTc.updateUidLockdownRule(1000, false /* add */)));
531 expectUidOwnerMapValues({1001}, LOCKDOWN_VPN_MATCH, 0);
532
533 // Remove remaining Lockdown rule
534 ASSERT_TRUE(isOk(mTc.updateUidLockdownRule(1001, false /* add */)));
535 expectMapEmpty(mFakeUidOwnerMap);
536}
537
Wayne Ma4d692332022-01-19 16:04:04 +0800538TEST_F(TrafficControllerTest, TestUidInterfaceFilteringRulesCoexistWithExistingMatches) {
539 // Set up existing PENALTY_BOX_MATCH rules
Wayne Ma7be6bce2022-01-12 16:29:49 +0800540 ASSERT_TRUE(isOk(updateUidOwnerMaps({1000, 1001, 10012}, PENALTY_BOX_MATCH,
541 TrafficController::IptOpInsert)));
Wayne Ma4d692332022-01-19 16:04:04 +0800542 expectUidOwnerMapValues({1000, 1001, 10012}, PENALTY_BOX_MATCH, 0);
543
544 // Add some partially-overlapping uid owner rules and check result
545 int iif1 = 32;
546 ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif1, {10012, 10013, 10014})));
547 expectUidOwnerMapValues({1000, 1001}, PENALTY_BOX_MATCH, 0);
548 expectUidOwnerMapValues({10012}, PENALTY_BOX_MATCH | IIF_MATCH, iif1);
549 expectUidOwnerMapValues({10013, 10014}, IIF_MATCH, iif1);
550
551 // Removing some PENALTY_BOX_MATCH rules should not change uid interface rule
Wayne Ma7be6bce2022-01-12 16:29:49 +0800552 ASSERT_TRUE(isOk(updateUidOwnerMaps({1001, 10012}, PENALTY_BOX_MATCH,
553 TrafficController::IptOpDelete)));
Wayne Ma4d692332022-01-19 16:04:04 +0800554 expectUidOwnerMapValues({1000}, PENALTY_BOX_MATCH, 0);
555 expectUidOwnerMapValues({10012, 10013, 10014}, IIF_MATCH, iif1);
556
557 // Remove all uid interface rules
558 ASSERT_TRUE(isOk(mTc.removeUidInterfaceRules({10012, 10013, 10014})));
559 expectUidOwnerMapValues({1000}, PENALTY_BOX_MATCH, 0);
560 // Make sure these are the only uids left
561 checkEachUidValue({1000}, PENALTY_BOX_MATCH);
562}
563
564TEST_F(TrafficControllerTest, TestUidInterfaceFilteringRulesCoexistWithNewMatches) {
565 int iif1 = 56;
566 // Set up existing uid interface rules
567 ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif1, {10001, 10002})));
568 expectUidOwnerMapValues({10001, 10002}, IIF_MATCH, iif1);
569
570 // Add some partially-overlapping doze rules
571 EXPECT_EQ(0, mTc.replaceUidOwnerMap("fw_dozable", true, {10002, 10003}));
572 expectUidOwnerMapValues({10001}, IIF_MATCH, iif1);
573 expectUidOwnerMapValues({10002}, DOZABLE_MATCH | IIF_MATCH, iif1);
574 expectUidOwnerMapValues({10003}, DOZABLE_MATCH, 0);
575
576 // Introduce a third rule type (powersave) on various existing UIDs
577 EXPECT_EQ(0, mTc.replaceUidOwnerMap("fw_powersave", true, {10000, 10001, 10002, 10003}));
578 expectUidOwnerMapValues({10000}, POWERSAVE_MATCH, 0);
579 expectUidOwnerMapValues({10001}, POWERSAVE_MATCH | IIF_MATCH, iif1);
580 expectUidOwnerMapValues({10002}, POWERSAVE_MATCH | DOZABLE_MATCH | IIF_MATCH, iif1);
581 expectUidOwnerMapValues({10003}, POWERSAVE_MATCH | DOZABLE_MATCH, 0);
582
583 // Remove all doze rules
584 EXPECT_EQ(0, mTc.replaceUidOwnerMap("fw_dozable", true, {}));
585 expectUidOwnerMapValues({10000}, POWERSAVE_MATCH, 0);
586 expectUidOwnerMapValues({10001}, POWERSAVE_MATCH | IIF_MATCH, iif1);
587 expectUidOwnerMapValues({10002}, POWERSAVE_MATCH | IIF_MATCH, iif1);
588 expectUidOwnerMapValues({10003}, POWERSAVE_MATCH, 0);
589
590 // Remove all powersave rules, expect ownerMap to only have uid interface rules left
591 EXPECT_EQ(0, mTc.replaceUidOwnerMap("fw_powersave", true, {}));
592 expectUidOwnerMapValues({10001, 10002}, IIF_MATCH, iif1);
593 // Make sure these are the only uids left
594 checkEachUidValue({10001, 10002}, IIF_MATCH);
595}
596
Motomu Utsumib08654c2022-05-11 05:56:26 +0000597TEST_F(TrafficControllerTest, TestAddUidInterfaceFilteringRulesWithWildcard) {
598 // iif=0 is a wildcard
599 int iif = 0;
600 // Add interface rule with wildcard to uids
601 ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif, {1000, 1001})));
602 expectUidOwnerMapValues({1000, 1001}, IIF_MATCH, iif);
603}
604
605TEST_F(TrafficControllerTest, TestRemoveUidInterfaceFilteringRulesWithWildcard) {
606 // iif=0 is a wildcard
607 int iif = 0;
608 // Add interface rule with wildcard to two uids
609 ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif, {1000, 1001})));
610 expectUidOwnerMapValues({1000, 1001}, IIF_MATCH, iif);
611
612 // Remove interface rule from one of the uids
613 ASSERT_TRUE(isOk(mTc.removeUidInterfaceRules({1000})));
614 expectUidOwnerMapValues({1001}, IIF_MATCH, iif);
615 checkEachUidValue({1001}, IIF_MATCH);
616
617 // Remove interface rule from the remaining uid
618 ASSERT_TRUE(isOk(mTc.removeUidInterfaceRules({1001})));
619 expectMapEmpty(mFakeUidOwnerMap);
620}
621
622TEST_F(TrafficControllerTest, TestUidInterfaceFilteringRulesWithWildcardAndExistingMatches) {
623 // Set up existing DOZABLE_MATCH and POWERSAVE_MATCH rule
624 ASSERT_TRUE(isOk(updateUidOwnerMaps({1000}, DOZABLE_MATCH,
625 TrafficController::IptOpInsert)));
626 ASSERT_TRUE(isOk(updateUidOwnerMaps({1000}, POWERSAVE_MATCH,
627 TrafficController::IptOpInsert)));
628
629 // iif=0 is a wildcard
630 int iif = 0;
631 // Add interface rule with wildcard to the existing uid
632 ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif, {1000})));
633 expectUidOwnerMapValues({1000}, POWERSAVE_MATCH | DOZABLE_MATCH | IIF_MATCH, iif);
634
635 // Remove interface rule with wildcard from the existing uid
636 ASSERT_TRUE(isOk(mTc.removeUidInterfaceRules({1000})));
637 expectUidOwnerMapValues({1000}, POWERSAVE_MATCH | DOZABLE_MATCH, 0);
638}
639
640TEST_F(TrafficControllerTest, TestUidInterfaceFilteringRulesWithWildcardAndNewMatches) {
641 // iif=0 is a wildcard
642 int iif = 0;
643 // Set up existing interface rule with wildcard
644 ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif, {1000})));
645
646 // Add DOZABLE_MATCH and POWERSAVE_MATCH rule to the existing uid
647 ASSERT_TRUE(isOk(updateUidOwnerMaps({1000}, DOZABLE_MATCH,
648 TrafficController::IptOpInsert)));
649 ASSERT_TRUE(isOk(updateUidOwnerMaps({1000}, POWERSAVE_MATCH,
650 TrafficController::IptOpInsert)));
651 expectUidOwnerMapValues({1000}, POWERSAVE_MATCH | DOZABLE_MATCH | IIF_MATCH, iif);
652
653 // Remove DOZABLE_MATCH and POWERSAVE_MATCH rule from the existing uid
654 ASSERT_TRUE(isOk(updateUidOwnerMaps({1000}, DOZABLE_MATCH,
655 TrafficController::IptOpDelete)));
656 ASSERT_TRUE(isOk(updateUidOwnerMaps({1000}, POWERSAVE_MATCH,
657 TrafficController::IptOpDelete)));
658 expectUidOwnerMapValues({1000}, IIF_MATCH, iif);
659}
660
Wayne Ma4d692332022-01-19 16:04:04 +0800661TEST_F(TrafficControllerTest, TestGrantInternetPermission) {
662 std::vector<uid_t> appUids = {TEST_UID, TEST_UID2, TEST_UID3};
663
664 mTc.setPermissionForUids(INetd::PERMISSION_INTERNET, appUids);
665 expectMapEmpty(mFakeUidPermissionMap);
666 expectPrivilegedUserSetEmpty();
667}
668
669TEST_F(TrafficControllerTest, TestRevokeInternetPermission) {
670 std::vector<uid_t> appUids = {TEST_UID, TEST_UID2, TEST_UID3};
671
672 mTc.setPermissionForUids(INetd::PERMISSION_NONE, appUids);
673 expectUidPermissionMapValues(appUids, INetd::PERMISSION_NONE);
674}
675
676TEST_F(TrafficControllerTest, TestPermissionUninstalled) {
677 std::vector<uid_t> appUids = {TEST_UID, TEST_UID2, TEST_UID3};
678
679 mTc.setPermissionForUids(INetd::PERMISSION_UPDATE_DEVICE_STATS, appUids);
680 expectUidPermissionMapValues(appUids, INetd::PERMISSION_UPDATE_DEVICE_STATS);
681 expectPrivilegedUserSet(appUids);
682
683 std::vector<uid_t> uidToRemove = {TEST_UID};
684 mTc.setPermissionForUids(INetd::PERMISSION_UNINSTALLED, uidToRemove);
685
686 std::vector<uid_t> uidRemain = {TEST_UID3, TEST_UID2};
687 expectUidPermissionMapValues(uidRemain, INetd::PERMISSION_UPDATE_DEVICE_STATS);
688 expectPrivilegedUserSet(uidRemain);
689
690 mTc.setPermissionForUids(INetd::PERMISSION_UNINSTALLED, uidRemain);
691 expectMapEmpty(mFakeUidPermissionMap);
692 expectPrivilegedUserSetEmpty();
693}
694
695TEST_F(TrafficControllerTest, TestGrantUpdateStatsPermission) {
696 std::vector<uid_t> appUids = {TEST_UID, TEST_UID2, TEST_UID3};
697
698 mTc.setPermissionForUids(INetd::PERMISSION_UPDATE_DEVICE_STATS, appUids);
699 expectUidPermissionMapValues(appUids, INetd::PERMISSION_UPDATE_DEVICE_STATS);
700 expectPrivilegedUserSet(appUids);
701
702 mTc.setPermissionForUids(INetd::PERMISSION_NONE, appUids);
703 expectPrivilegedUserSetEmpty();
704 expectUidPermissionMapValues(appUids, INetd::PERMISSION_NONE);
705}
706
707TEST_F(TrafficControllerTest, TestRevokeUpdateStatsPermission) {
708 std::vector<uid_t> appUids = {TEST_UID, TEST_UID2, TEST_UID3};
709
710 mTc.setPermissionForUids(INetd::PERMISSION_UPDATE_DEVICE_STATS, appUids);
711 expectPrivilegedUserSet(appUids);
712
713 std::vector<uid_t> uidToRemove = {TEST_UID};
714 mTc.setPermissionForUids(INetd::PERMISSION_NONE, uidToRemove);
715
716 std::vector<uid_t> uidRemain = {TEST_UID3, TEST_UID2};
717 expectPrivilegedUserSet(uidRemain);
718
719 mTc.setPermissionForUids(INetd::PERMISSION_NONE, uidRemain);
720 expectPrivilegedUserSetEmpty();
721}
722
723TEST_F(TrafficControllerTest, TestGrantWrongPermission) {
724 std::vector<uid_t> appUids = {TEST_UID, TEST_UID2, TEST_UID3};
725
726 mTc.setPermissionForUids(INetd::PERMISSION_NONE, appUids);
727 expectPrivilegedUserSetEmpty();
728 expectUidPermissionMapValues(appUids, INetd::PERMISSION_NONE);
729}
730
731TEST_F(TrafficControllerTest, TestGrantDuplicatePermissionSlientlyFail) {
732 std::vector<uid_t> appUids = {TEST_UID, TEST_UID2, TEST_UID3};
733
734 mTc.setPermissionForUids(INetd::PERMISSION_INTERNET, appUids);
735 expectMapEmpty(mFakeUidPermissionMap);
736
737 std::vector<uid_t> uidToAdd = {TEST_UID};
738 mTc.setPermissionForUids(INetd::PERMISSION_INTERNET, uidToAdd);
739
740 expectPrivilegedUserSetEmpty();
741
742 mTc.setPermissionForUids(INetd::PERMISSION_NONE, appUids);
743 expectUidPermissionMapValues(appUids, INetd::PERMISSION_NONE);
744
745 mTc.setPermissionForUids(INetd::PERMISSION_UPDATE_DEVICE_STATS, appUids);
746 expectPrivilegedUserSet(appUids);
747
748 mTc.setPermissionForUids(INetd::PERMISSION_UPDATE_DEVICE_STATS, uidToAdd);
749 expectPrivilegedUserSet(appUids);
750
751 mTc.setPermissionForUids(INetd::PERMISSION_NONE, appUids);
752 expectPrivilegedUserSetEmpty();
753}
754
Ken Chen2fb86362022-06-05 11:39:38 +0800755TEST_F(TrafficControllerTest, TestDumpsys) {
Ken Chen0dd74952022-06-06 18:25:18 +0800756 StatsKey tagStatsMapKey;
757 populateFakeStats(TEST_COOKIE, TEST_UID, TEST_TAG, &tagStatsMapKey);
758 populateFakeCounterSet(TEST_UID3, TEST_COUNTERSET);
Ken Chen2fb86362022-06-05 11:39:38 +0800759
Ken Chen0dd74952022-06-06 18:25:18 +0800760 // Expect: (part of this depends on hard-code values in populateFakeStats())
761 //
762 // mCookieTagMap:
763 // cookie=1 tag=0x2a uid=10086
764 //
765 // mUidCounterSetMap:
766 // 98765 1
767 //
768 // mAppUidStatsMap::
769 // uid rxBytes rxPackets txBytes txPackets
770 // 10086 100 1 0 0
771 //
772 // mStatsMapA:
773 // ifaceIndex ifaceName tag_hex uid_int cnt_set rxBytes rxPackets txBytes txPackets
774 // 999 test0 0x2a 10086 1 100 1 0 0
Ken Chen2fb86362022-06-05 11:39:38 +0800775 std::vector<std::string> expectedLines = {
Ken Chen0dd74952022-06-06 18:25:18 +0800776 "mCookieTagMap:",
777 fmt::format("cookie={} tag={:#x} uid={}", TEST_COOKIE, TEST_TAG, TEST_UID),
778 "mUidCounterSetMap:",
779 fmt::format("{} {}", TEST_UID3, TEST_COUNTERSET),
780 "mAppUidStatsMap::", // TODO@: fix double colon
781 "uid rxBytes rxPackets txBytes txPackets",
782 fmt::format("{} {} {} {} {}", TEST_UID, RXBYTES, RXPACKETS, TXBYTES, TXPACKETS),
783 "mStatsMapA",
784 "ifaceIndex ifaceName tag_hex uid_int cnt_set rxBytes rxPackets txBytes txPackets",
785 fmt::format("{} {} {:#x} {} {} {} {} {} {}",
786 TEST_IFINDEX, TEST_IFNAME, TEST_TAG, TEST_UID, TEST_COUNTERSET, RXBYTES,
787 RXPACKETS, TXBYTES, TXPACKETS)};
Ken Chen2fb86362022-06-05 11:39:38 +0800788
Ken Chen0dd74952022-06-06 18:25:18 +0800789 populateFakeIfaceIndexName(TEST_IFNAME, TEST_IFINDEX);
790 expectedLines.emplace_back("mIfaceIndexNameMap:");
791 expectedLines.emplace_back(fmt::format("ifaceIndex={} ifaceName={}",
792 TEST_IFINDEX, TEST_IFNAME));
793
794 ASSERT_TRUE(isOk(updateUidOwnerMaps({TEST_UID}, HAPPY_BOX_MATCH,
795 TrafficController::IptOpInsert)));
796 expectedLines.emplace_back("mUidOwnerMap:");
797 expectedLines.emplace_back(fmt::format("{} HAPPY_BOX_MATCH", TEST_UID));
798
799 mTc.setPermissionForUids(INetd::PERMISSION_UPDATE_DEVICE_STATS, {TEST_UID2});
800 expectedLines.emplace_back("mUidPermissionMap:");
801 expectedLines.emplace_back(fmt::format("{} BPF_PERMISSION_UPDATE_DEVICE_STATS", TEST_UID2));
802 expectedLines.emplace_back("mPrivilegedUser:");
803 expectedLines.emplace_back(fmt::format("{} ALLOW_UPDATE_DEVICE_STATS", TEST_UID2));
Ken Chen2fb86362022-06-05 11:39:38 +0800804 EXPECT_TRUE(expectDumpsysContains(expectedLines));
805}
806
Ken Chen77a6b712022-06-06 12:46:36 +0800807TEST_F(TrafficControllerTest, getFirewallType) {
808 static const struct TestConfig {
809 ChildChain childChain;
810 FirewallType firewallType;
811 } testConfigs[] = {
812 // clang-format off
813 {NONE, DENYLIST},
814 {DOZABLE, ALLOWLIST},
815 {STANDBY, DENYLIST},
816 {POWERSAVE, ALLOWLIST},
817 {RESTRICTED, ALLOWLIST},
818 {LOW_POWER_STANDBY, ALLOWLIST},
Ken Chen77a6b712022-06-06 12:46:36 +0800819 {OEM_DENY_1, DENYLIST},
820 {OEM_DENY_2, DENYLIST},
821 {INVALID_CHAIN, DENYLIST},
822 // clang-format on
823 };
824
825 for (const auto& config : testConfigs) {
826 SCOPED_TRACE(fmt::format("testConfig: [{}, {}]", config.childChain, config.firewallType));
827 EXPECT_EQ(config.firewallType, mTc.getFirewallType(config.childChain));
828 }
829}
830
Patrick Rohr61e94672022-02-01 21:06:40 +0100831constexpr uint32_t SOCK_CLOSE_WAIT_US = 30 * 1000;
832constexpr uint32_t ENOBUFS_POLL_WAIT_US = 10 * 1000;
833
834using android::base::Error;
835using android::base::Result;
836using android::bpf::BpfMap;
837
838// This test set up a SkDestroyListener that is running parallel with the production
839// SkDestroyListener. The test will create thousands of sockets and tag them on the
840// production cookieUidTagMap and close them in a short time. When the number of
841// sockets get closed exceeds the buffer size, it will start to return ENOBUFF
842// error. The error will be ignored by the production SkDestroyListener and the
843// test will clean up the tags in tearDown if there is any remains.
844
845// TODO: Instead of test the ENOBUFF error, we can test the production
846// SkDestroyListener to see if it failed to delete a tagged socket when ENOBUFF
847// triggered.
848class NetlinkListenerTest : public testing::Test {
849 protected:
850 NetlinkListenerTest() {}
851 BpfMap<uint64_t, UidTagValue> mCookieTagMap;
852
853 void SetUp() {
Maciej Żenczykowskiced35312022-05-31 05:11:12 -0700854 mCookieTagMap.init(COOKIE_TAG_MAP_PATH);
Patrick Rohr61e94672022-02-01 21:06:40 +0100855 ASSERT_TRUE(mCookieTagMap.isValid());
856 }
857
858 void TearDown() {
859 const auto deleteTestCookieEntries = [](const uint64_t& key, const UidTagValue& value,
860 BpfMap<uint64_t, UidTagValue>& map) {
861 if ((value.uid == TEST_UID) && (value.tag == TEST_TAG)) {
862 Result<void> res = map.deleteValue(key);
863 if (res.ok() || (res.error().code() == ENOENT)) {
864 return Result<void>();
865 }
Maciej Żenczykowskie0f58462022-05-17 13:59:22 -0700866 ALOGE("Failed to delete data(cookie = %" PRIu64 "): %s", key,
Patrick Rohr61e94672022-02-01 21:06:40 +0100867 strerror(res.error().code()));
868 }
869 // Move forward to next cookie in the map.
870 return Result<void>();
871 };
872 EXPECT_RESULT_OK(mCookieTagMap.iterateWithValue(deleteTestCookieEntries));
873 }
874
875 Result<void> checkNoGarbageTagsExist() {
876 const auto checkGarbageTags = [](const uint64_t&, const UidTagValue& value,
877 const BpfMap<uint64_t, UidTagValue>&) -> Result<void> {
878 if ((TEST_UID == value.uid) && (TEST_TAG == value.tag)) {
879 return Error(EUCLEAN) << "Closed socket is not untagged";
880 }
881 return {};
882 };
883 return mCookieTagMap.iterateWithValue(checkGarbageTags);
884 }
885
886 bool checkMassiveSocketDestroy(int totalNumber, bool expectError) {
887 std::unique_ptr<android::netdutils::NetlinkListenerInterface> skDestroyListener;
888 auto result = android::net::TrafficController::makeSkDestroyListener();
889 if (!isOk(result)) {
890 ALOGE("Unable to create SkDestroyListener: %s", toString(result).c_str());
891 } else {
892 skDestroyListener = std::move(result.value());
893 }
894 int rxErrorCount = 0;
895 // Rx handler extracts nfgenmsg looks up and invokes registered dispatch function.
896 const auto rxErrorHandler = [&rxErrorCount](const int, const int) { rxErrorCount++; };
897 skDestroyListener->registerSkErrorHandler(rxErrorHandler);
898 int fds[totalNumber];
899 for (int i = 0; i < totalNumber; i++) {
900 fds[i] = socket(AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0);
901 // The likely reason for a failure is running out of available file descriptors.
902 EXPECT_LE(0, fds[i]) << i << " of " << totalNumber;
903 if (fds[i] < 0) {
904 // EXPECT_LE already failed above, so test case is a failure, but we don't
905 // want potentially tens of thousands of extra failures creating and then
906 // closing all these fds cluttering up the logs.
907 totalNumber = i;
908 break;
909 };
910 libnetd_updatable_tagSocket(fds[i], TEST_TAG, TEST_UID, 1000);
911 }
912
913 // TODO: Use a separate thread that has its own fd table so we can
914 // close sockets even faster simply by terminating that thread.
915 for (int i = 0; i < totalNumber; i++) {
916 EXPECT_EQ(0, close(fds[i]));
917 }
918 // wait a bit for netlink listener to handle all the messages.
919 usleep(SOCK_CLOSE_WAIT_US);
920 if (expectError) {
921 // If ENOBUFS triggered, check it only called into the handler once, ie.
922 // that the netlink handler is not spinning.
923 int currentErrorCount = rxErrorCount;
924 // 0 error count is acceptable because the system has chances to close all sockets
925 // normally.
926 EXPECT_LE(0, rxErrorCount);
927 if (!rxErrorCount) return true;
928
929 usleep(ENOBUFS_POLL_WAIT_US);
930 EXPECT_EQ(currentErrorCount, rxErrorCount);
931 } else {
932 EXPECT_RESULT_OK(checkNoGarbageTagsExist());
933 EXPECT_EQ(0, rxErrorCount);
934 }
935 return false;
936 }
937};
938
939TEST_F(NetlinkListenerTest, TestAllSocketUntagged) {
940 checkMassiveSocketDestroy(10, false);
941 checkMassiveSocketDestroy(100, false);
942}
943
944// Disabled because flaky on blueline-userdebug; this test relies on the main thread
945// winning a race against the NetlinkListener::run() thread. There's no way to ensure
946// things will be scheduled the same way across all architectures and test environments.
947TEST_F(NetlinkListenerTest, DISABLED_TestSkDestroyError) {
948 bool needRetry = false;
949 int retryCount = 0;
950 do {
951 needRetry = checkMassiveSocketDestroy(32500, true);
952 if (needRetry) retryCount++;
953 } while (needRetry && retryCount < 3);
954 // Should review test if it can always close all sockets correctly.
955 EXPECT_GT(3, retryCount);
956}
957
958
Wayne Ma4d692332022-01-19 16:04:04 +0800959} // namespace net
960} // namespace android