blob: 2eabc26e03672fe2b1960c56c67235fc49f23fde [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())
Hungming Chen410bb122022-06-09 01:32:00 +080071#define ASSERT_INVALID(x) ASSERT_FALSE((x).isValid())
Wayne Ma4d692332022-01-19 16:04:04 +080072
73class TrafficControllerTest : public ::testing::Test {
74 protected:
Wayne Ma92d80792022-01-20 13:20:34 +080075 TrafficControllerTest() {}
Wayne Ma4d692332022-01-19 16:04:04 +080076 TrafficController mTc;
77 BpfMap<uint64_t, UidTagValue> mFakeCookieTagMap;
Wayne Ma4d692332022-01-19 16:04:04 +080078 BpfMap<uint32_t, StatsValue> mFakeAppUidStatsMap;
79 BpfMap<StatsKey, StatsValue> mFakeStatsMapA;
Hungming Chen410bb122022-06-09 01:32:00 +080080 BpfMap<StatsKey, StatsValue> mFakeStatsMapB; // makeTrafficControllerMapsInvalid only
81 BpfMap<uint32_t, StatsValue> mFakeIfaceStatsMap; ; // makeTrafficControllerMapsInvalid only
Lorenzo Colitti60cbed32022-03-03 17:49:01 +090082 BpfMap<uint32_t, uint32_t> mFakeConfigurationMap;
Wayne Ma4d692332022-01-19 16:04:04 +080083 BpfMap<uint32_t, UidOwnerValue> mFakeUidOwnerMap;
84 BpfMap<uint32_t, uint8_t> mFakeUidPermissionMap;
Ken Chen0dd74952022-06-06 18:25:18 +080085 BpfMap<uint32_t, uint8_t> mFakeUidCounterSetMap;
86 BpfMap<uint32_t, IfaceValue> mFakeIfaceIndexNameMap;
Wayne Ma4d692332022-01-19 16:04:04 +080087
88 void SetUp() {
89 std::lock_guard guard(mTc.mMutex);
90 ASSERT_EQ(0, setrlimitForTest());
91
Maciej Żenczykowski439bac22022-05-31 03:22:32 -070092 mFakeCookieTagMap.resetMap(BPF_MAP_TYPE_HASH, TEST_MAP_SIZE);
Wayne Ma4d692332022-01-19 16:04:04 +080093 ASSERT_VALID(mFakeCookieTagMap);
94
Maciej Żenczykowski439bac22022-05-31 03:22:32 -070095 mFakeAppUidStatsMap.resetMap(BPF_MAP_TYPE_HASH, TEST_MAP_SIZE);
Wayne Ma4d692332022-01-19 16:04:04 +080096 ASSERT_VALID(mFakeAppUidStatsMap);
97
Maciej Żenczykowski439bac22022-05-31 03:22:32 -070098 mFakeStatsMapA.resetMap(BPF_MAP_TYPE_HASH, TEST_MAP_SIZE);
Wayne Ma4d692332022-01-19 16:04:04 +080099 ASSERT_VALID(mFakeStatsMapA);
100
Maciej Żenczykowski439bac22022-05-31 03:22:32 -0700101 mFakeConfigurationMap.resetMap(BPF_MAP_TYPE_HASH, 1);
Wayne Ma4d692332022-01-19 16:04:04 +0800102 ASSERT_VALID(mFakeConfigurationMap);
103
Maciej Żenczykowski439bac22022-05-31 03:22:32 -0700104 mFakeUidOwnerMap.resetMap(BPF_MAP_TYPE_HASH, TEST_MAP_SIZE);
Wayne Ma4d692332022-01-19 16:04:04 +0800105 ASSERT_VALID(mFakeUidOwnerMap);
Maciej Żenczykowski439bac22022-05-31 03:22:32 -0700106 mFakeUidPermissionMap.resetMap(BPF_MAP_TYPE_HASH, TEST_MAP_SIZE);
Wayne Ma4d692332022-01-19 16:04:04 +0800107 ASSERT_VALID(mFakeUidPermissionMap);
108
Ken Chen0dd74952022-06-06 18:25:18 +0800109 mFakeUidCounterSetMap.resetMap(BPF_MAP_TYPE_HASH, TEST_MAP_SIZE);
110 ASSERT_VALID(mFakeUidCounterSetMap);
111
112 mFakeIfaceIndexNameMap.resetMap(BPF_MAP_TYPE_HASH, TEST_MAP_SIZE);
113 ASSERT_VALID(mFakeIfaceIndexNameMap);
114
Maciej Żenczykowski55ab87a2022-05-31 03:15:12 -0700115 mTc.mCookieTagMap = mFakeCookieTagMap;
Wayne Ma4d692332022-01-19 16:04:04 +0800116 ASSERT_VALID(mTc.mCookieTagMap);
Maciej Żenczykowski55ab87a2022-05-31 03:15:12 -0700117 mTc.mAppUidStatsMap = mFakeAppUidStatsMap;
Wayne Ma4d692332022-01-19 16:04:04 +0800118 ASSERT_VALID(mTc.mAppUidStatsMap);
Maciej Żenczykowski55ab87a2022-05-31 03:15:12 -0700119 mTc.mStatsMapA = mFakeStatsMapA;
Wayne Ma4d692332022-01-19 16:04:04 +0800120 ASSERT_VALID(mTc.mStatsMapA);
Maciej Żenczykowski55ab87a2022-05-31 03:15:12 -0700121 mTc.mConfigurationMap = mFakeConfigurationMap;
Wayne Ma4d692332022-01-19 16:04:04 +0800122 ASSERT_VALID(mTc.mConfigurationMap);
123
124 // Always write to stats map A by default.
125 ASSERT_RESULT_OK(mTc.mConfigurationMap.writeValue(CURRENT_STATS_MAP_CONFIGURATION_KEY,
126 SELECT_MAP_A, BPF_ANY));
Maciej Żenczykowski55ab87a2022-05-31 03:15:12 -0700127 mTc.mUidOwnerMap = mFakeUidOwnerMap;
Wayne Ma4d692332022-01-19 16:04:04 +0800128 ASSERT_VALID(mTc.mUidOwnerMap);
Maciej Żenczykowski55ab87a2022-05-31 03:15:12 -0700129 mTc.mUidPermissionMap = mFakeUidPermissionMap;
Wayne Ma4d692332022-01-19 16:04:04 +0800130 ASSERT_VALID(mTc.mUidPermissionMap);
131 mTc.mPrivilegedUser.clear();
Ken Chen0dd74952022-06-06 18:25:18 +0800132
133 mTc.mUidCounterSetMap = mFakeUidCounterSetMap;
134 ASSERT_VALID(mTc.mUidCounterSetMap);
135
136 mTc.mIfaceIndexNameMap = mFakeIfaceIndexNameMap;
137 ASSERT_VALID(mTc.mIfaceIndexNameMap);
Wayne Ma4d692332022-01-19 16:04:04 +0800138 }
139
Wayne Ma4d692332022-01-19 16:04:04 +0800140 void populateFakeStats(uint64_t cookie, uint32_t uid, uint32_t tag, StatsKey* key) {
141 UidTagValue cookieMapkey = {.uid = (uint32_t)uid, .tag = tag};
142 EXPECT_RESULT_OK(mFakeCookieTagMap.writeValue(cookie, cookieMapkey, BPF_ANY));
Ken Chen0dd74952022-06-06 18:25:18 +0800143 *key = {.uid = uid, .tag = tag, .counterSet = TEST_COUNTERSET, .ifaceIndex = TEST_IFINDEX};
144 StatsValue statsMapValue = {.rxPackets = RXPACKETS, .rxBytes = RXBYTES,
145 .txPackets = TXPACKETS, .txBytes = TXBYTES};
Wayne Ma4d692332022-01-19 16:04:04 +0800146 EXPECT_RESULT_OK(mFakeStatsMapA.writeValue(*key, statsMapValue, BPF_ANY));
147 EXPECT_RESULT_OK(mFakeAppUidStatsMap.writeValue(uid, statsMapValue, BPF_ANY));
148 // put tag information back to statsKey
149 key->tag = tag;
150 }
151
Ken Chen0dd74952022-06-06 18:25:18 +0800152 void populateFakeCounterSet(uint32_t uid, uint32_t counterSet) {
153 EXPECT_RESULT_OK(mFakeUidCounterSetMap.writeValue(uid, counterSet, BPF_ANY));
154 }
155
156 void populateFakeIfaceIndexName(const char* name, uint32_t ifaceIndex) {
157 if (name == nullptr || ifaceIndex <= 0) return;
158
159 IfaceValue iface;
160 strlcpy(iface.name, name, sizeof(IfaceValue));
161 EXPECT_RESULT_OK(mFakeIfaceIndexNameMap.writeValue(ifaceIndex, iface, BPF_ANY));
162 }
163
Wayne Ma4d692332022-01-19 16:04:04 +0800164 void checkUidOwnerRuleForChain(ChildChain chain, UidOwnerMatchType match) {
165 uint32_t uid = TEST_UID;
166 EXPECT_EQ(0, mTc.changeUidOwnerRule(chain, uid, DENY, DENYLIST));
167 Result<UidOwnerValue> value = mFakeUidOwnerMap.readValue(uid);
168 EXPECT_RESULT_OK(value);
169 EXPECT_TRUE(value.value().rule & match);
170
171 uid = TEST_UID2;
172 EXPECT_EQ(0, mTc.changeUidOwnerRule(chain, uid, ALLOW, ALLOWLIST));
173 value = mFakeUidOwnerMap.readValue(uid);
174 EXPECT_RESULT_OK(value);
175 EXPECT_TRUE(value.value().rule & match);
176
177 EXPECT_EQ(0, mTc.changeUidOwnerRule(chain, uid, DENY, ALLOWLIST));
178 value = mFakeUidOwnerMap.readValue(uid);
179 EXPECT_FALSE(value.ok());
180 EXPECT_EQ(ENOENT, value.error().code());
181
182 uid = TEST_UID;
183 EXPECT_EQ(0, mTc.changeUidOwnerRule(chain, uid, ALLOW, DENYLIST));
184 value = mFakeUidOwnerMap.readValue(uid);
185 EXPECT_FALSE(value.ok());
186 EXPECT_EQ(ENOENT, value.error().code());
187
188 uid = TEST_UID3;
189 EXPECT_EQ(-ENOENT, mTc.changeUidOwnerRule(chain, uid, ALLOW, DENYLIST));
190 value = mFakeUidOwnerMap.readValue(uid);
191 EXPECT_FALSE(value.ok());
192 EXPECT_EQ(ENOENT, value.error().code());
193 }
194
195 void checkEachUidValue(const std::vector<int32_t>& uids, UidOwnerMatchType match) {
196 for (uint32_t uid : uids) {
197 Result<UidOwnerValue> value = mFakeUidOwnerMap.readValue(uid);
198 EXPECT_RESULT_OK(value);
199 EXPECT_TRUE(value.value().rule & match);
200 }
201 std::set<uint32_t> uidSet(uids.begin(), uids.end());
202 const auto checkNoOtherUid = [&uidSet](const int32_t& key,
203 const BpfMap<uint32_t, UidOwnerValue>&) {
204 EXPECT_NE(uidSet.end(), uidSet.find(key));
205 return Result<void>();
206 };
207 EXPECT_RESULT_OK(mFakeUidOwnerMap.iterate(checkNoOtherUid));
208 }
209
210 void checkUidMapReplace(const std::string& name, const std::vector<int32_t>& uids,
211 UidOwnerMatchType match) {
212 bool isAllowlist = true;
213 EXPECT_EQ(0, mTc.replaceUidOwnerMap(name, isAllowlist, uids));
214 checkEachUidValue(uids, match);
215
216 isAllowlist = false;
217 EXPECT_EQ(0, mTc.replaceUidOwnerMap(name, isAllowlist, uids));
218 checkEachUidValue(uids, match);
219 }
220
221 void expectUidOwnerMapValues(const std::vector<uint32_t>& appUids, uint8_t expectedRule,
222 uint32_t expectedIif) {
223 for (uint32_t uid : appUids) {
224 Result<UidOwnerValue> value = mFakeUidOwnerMap.readValue(uid);
225 EXPECT_RESULT_OK(value);
226 EXPECT_EQ(expectedRule, value.value().rule)
227 << "Expected rule for UID " << uid << " to be " << expectedRule << ", but was "
228 << value.value().rule;
229 EXPECT_EQ(expectedIif, value.value().iif)
230 << "Expected iif for UID " << uid << " to be " << expectedIif << ", but was "
231 << value.value().iif;
232 }
233 }
234
235 template <class Key, class Value>
236 void expectMapEmpty(BpfMap<Key, Value>& map) {
237 auto isEmpty = map.isEmpty();
238 EXPECT_RESULT_OK(isEmpty);
239 EXPECT_TRUE(isEmpty.value());
240 }
241
242 void expectUidPermissionMapValues(const std::vector<uid_t>& appUids, uint8_t expectedValue) {
243 for (uid_t uid : appUids) {
244 Result<uint8_t> value = mFakeUidPermissionMap.readValue(uid);
245 EXPECT_RESULT_OK(value);
246 EXPECT_EQ(expectedValue, value.value())
247 << "Expected value for UID " << uid << " to be " << expectedValue
248 << ", but was " << value.value();
249 }
250 }
251
252 void expectPrivilegedUserSet(const std::vector<uid_t>& appUids) {
253 std::lock_guard guard(mTc.mMutex);
254 EXPECT_EQ(appUids.size(), mTc.mPrivilegedUser.size());
255 for (uid_t uid : appUids) {
256 EXPECT_NE(mTc.mPrivilegedUser.end(), mTc.mPrivilegedUser.find(uid));
257 }
258 }
259
260 void expectPrivilegedUserSetEmpty() {
261 std::lock_guard guard(mTc.mMutex);
262 EXPECT_TRUE(mTc.mPrivilegedUser.empty());
263 }
264
265 void addPrivilegedUid(uid_t uid) {
266 std::vector privilegedUid = {uid};
267 mTc.setPermissionForUids(INetd::PERMISSION_UPDATE_DEVICE_STATS, privilegedUid);
268 }
269
270 void removePrivilegedUid(uid_t uid) {
271 std::vector privilegedUid = {uid};
272 mTc.setPermissionForUids(INetd::PERMISSION_NONE, privilegedUid);
273 }
274
275 void expectFakeStatsUnchanged(uint64_t cookie, uint32_t tag, uint32_t uid,
276 StatsKey tagStatsMapKey) {
277 Result<UidTagValue> cookieMapResult = mFakeCookieTagMap.readValue(cookie);
278 EXPECT_RESULT_OK(cookieMapResult);
279 EXPECT_EQ(uid, cookieMapResult.value().uid);
280 EXPECT_EQ(tag, cookieMapResult.value().tag);
Wayne Ma4d692332022-01-19 16:04:04 +0800281 Result<StatsValue> statsMapResult = mFakeStatsMapA.readValue(tagStatsMapKey);
282 EXPECT_RESULT_OK(statsMapResult);
Ken Chen0dd74952022-06-06 18:25:18 +0800283 EXPECT_EQ((uint64_t)RXPACKETS, statsMapResult.value().rxPackets);
284 EXPECT_EQ((uint64_t)RXBYTES, statsMapResult.value().rxBytes);
Wayne Ma4d692332022-01-19 16:04:04 +0800285 tagStatsMapKey.tag = 0;
286 statsMapResult = mFakeStatsMapA.readValue(tagStatsMapKey);
287 EXPECT_RESULT_OK(statsMapResult);
Ken Chen0dd74952022-06-06 18:25:18 +0800288 EXPECT_EQ((uint64_t)RXPACKETS, statsMapResult.value().rxPackets);
289 EXPECT_EQ((uint64_t)RXBYTES, statsMapResult.value().rxBytes);
Wayne Ma4d692332022-01-19 16:04:04 +0800290 auto appStatsResult = mFakeAppUidStatsMap.readValue(uid);
291 EXPECT_RESULT_OK(appStatsResult);
Ken Chen0dd74952022-06-06 18:25:18 +0800292 EXPECT_EQ((uint64_t)RXPACKETS, appStatsResult.value().rxPackets);
293 EXPECT_EQ((uint64_t)RXBYTES, appStatsResult.value().rxBytes);
Wayne Ma4d692332022-01-19 16:04:04 +0800294 }
Wayne Ma7be6bce2022-01-12 16:29:49 +0800295
296 Status updateUidOwnerMaps(const std::vector<uint32_t>& appUids,
297 UidOwnerMatchType matchType, TrafficController::IptOp op) {
298 Status ret(0);
299 for (auto uid : appUids) {
300 ret = mTc.updateUidOwnerMap(uid, matchType, op);
301 if(!isOk(ret)) break;
302 }
303 return ret;
304 }
305
Ken Chen2fb86362022-06-05 11:39:38 +0800306 Status dump(bool verbose, std::vector<std::string>& outputLines) {
307 if (!outputLines.empty()) return statusFromErrno(EUCLEAN, "Output buffer is not empty");
308
309 android::base::unique_fd localFd, remoteFd;
310 if (!Pipe(&localFd, &remoteFd)) return statusFromErrno(errno, "Failed on pipe");
311
312 // dump() blocks until another thread has consumed all its output.
313 std::thread dumpThread =
314 std::thread([this, remoteFd{std::move(remoteFd)}, verbose]() {
315 mTc.dump(remoteFd, verbose);
316 });
317
318 std::string dumpContent;
319 if (!android::base::ReadFdToString(localFd.get(), &dumpContent)) {
320 return statusFromErrno(errno, "Failed to read dump results from fd");
321 }
322 dumpThread.join();
323
324 std::stringstream dumpStream(std::move(dumpContent));
325 std::string line;
326 while (std::getline(dumpStream, line)) {
327 outputLines.push_back(line);
328 }
329
330 return netdutils::status::ok;
331 }
332
333 // Strings in the |expect| must exist in dump results in order. But no need to be consecutive.
334 bool expectDumpsysContains(std::vector<std::string>& expect) {
335 if (expect.empty()) return false;
336
337 std::vector<std::string> output;
338 Status result = dump(true, output);
339 if (!isOk(result)) {
340 GTEST_LOG_(ERROR) << "TrafficController dump failed: " << netdutils::toString(result);
341 return false;
342 }
343
344 int matched = 0;
345 auto it = expect.begin();
346 for (const auto& line : output) {
347 if (it == expect.end()) break;
348 if (std::string::npos != line.find(*it)) {
349 matched++;
350 ++it;
351 }
352 }
Ken Chen0dd74952022-06-06 18:25:18 +0800353
354 if (matched != expect.size()) {
355 // dump results for debugging
356 for (const auto& o : output) LOG(INFO) << "output: " << o;
357 for (const auto& e : expect) LOG(INFO) << "expect: " << e;
358 return false;
359 }
360 return true;
Ken Chen2fb86362022-06-05 11:39:38 +0800361 }
Hungming Chen410bb122022-06-09 01:32:00 +0800362
363 // Once called, the maps of TrafficController can't recover to valid maps which initialized
364 // in SetUp().
365 void makeTrafficControllerMapsInvalid() {
366 constexpr char INVALID_PATH[] = "invalid";
367
368 mFakeCookieTagMap.init(INVALID_PATH);
369 mTc.mCookieTagMap = mFakeCookieTagMap;
370 ASSERT_INVALID(mTc.mCookieTagMap);
371
372 mFakeAppUidStatsMap.init(INVALID_PATH);
373 mTc.mAppUidStatsMap = mFakeAppUidStatsMap;
374 ASSERT_INVALID(mTc.mAppUidStatsMap);
375
376 mFakeStatsMapA.init(INVALID_PATH);
377 mTc.mStatsMapA = mFakeStatsMapA;
378 ASSERT_INVALID(mTc.mStatsMapA);
379
380 mFakeStatsMapB.init(INVALID_PATH);
381 mTc.mStatsMapB = mFakeStatsMapB;
382 ASSERT_INVALID(mTc.mStatsMapB);
383
384 mFakeIfaceStatsMap.init(INVALID_PATH);
385 mTc.mIfaceStatsMap = mFakeIfaceStatsMap;
386 ASSERT_INVALID(mTc.mIfaceStatsMap);
387
388 mFakeConfigurationMap.init(INVALID_PATH);
389 mTc.mConfigurationMap = mFakeConfigurationMap;
390 ASSERT_INVALID(mTc.mConfigurationMap);
391
392 mFakeUidOwnerMap.init(INVALID_PATH);
393 mTc.mUidOwnerMap = mFakeUidOwnerMap;
394 ASSERT_INVALID(mTc.mUidOwnerMap);
395
396 mFakeUidPermissionMap.init(INVALID_PATH);
397 mTc.mUidPermissionMap = mFakeUidPermissionMap;
398 ASSERT_INVALID(mTc.mUidPermissionMap);
399
400 mFakeUidCounterSetMap.init(INVALID_PATH);
401 mTc.mUidCounterSetMap = mFakeUidCounterSetMap;
402 ASSERT_INVALID(mTc.mUidCounterSetMap);
403
404 mFakeIfaceIndexNameMap.init(INVALID_PATH);
405 mTc.mIfaceIndexNameMap = mFakeIfaceIndexNameMap;
406 ASSERT_INVALID(mTc.mIfaceIndexNameMap);
407 }
Wayne Ma4d692332022-01-19 16:04:04 +0800408};
409
Wayne Ma4d692332022-01-19 16:04:04 +0800410TEST_F(TrafficControllerTest, TestUpdateOwnerMapEntry) {
411 uint32_t uid = TEST_UID;
412 ASSERT_TRUE(isOk(mTc.updateOwnerMapEntry(STANDBY_MATCH, uid, DENY, DENYLIST)));
413 Result<UidOwnerValue> value = mFakeUidOwnerMap.readValue(uid);
414 ASSERT_RESULT_OK(value);
415 ASSERT_TRUE(value.value().rule & STANDBY_MATCH);
416
417 ASSERT_TRUE(isOk(mTc.updateOwnerMapEntry(DOZABLE_MATCH, uid, ALLOW, ALLOWLIST)));
418 value = mFakeUidOwnerMap.readValue(uid);
419 ASSERT_RESULT_OK(value);
420 ASSERT_TRUE(value.value().rule & DOZABLE_MATCH);
421
422 ASSERT_TRUE(isOk(mTc.updateOwnerMapEntry(DOZABLE_MATCH, uid, DENY, ALLOWLIST)));
423 value = mFakeUidOwnerMap.readValue(uid);
424 ASSERT_RESULT_OK(value);
425 ASSERT_FALSE(value.value().rule & DOZABLE_MATCH);
426
427 ASSERT_TRUE(isOk(mTc.updateOwnerMapEntry(STANDBY_MATCH, uid, ALLOW, DENYLIST)));
428 ASSERT_FALSE(mFakeUidOwnerMap.readValue(uid).ok());
429
430 uid = TEST_UID2;
431 ASSERT_FALSE(isOk(mTc.updateOwnerMapEntry(STANDBY_MATCH, uid, ALLOW, DENYLIST)));
432 ASSERT_FALSE(mFakeUidOwnerMap.readValue(uid).ok());
433}
434
435TEST_F(TrafficControllerTest, TestChangeUidOwnerRule) {
436 checkUidOwnerRuleForChain(DOZABLE, DOZABLE_MATCH);
437 checkUidOwnerRuleForChain(STANDBY, STANDBY_MATCH);
438 checkUidOwnerRuleForChain(POWERSAVE, POWERSAVE_MATCH);
439 checkUidOwnerRuleForChain(RESTRICTED, RESTRICTED_MATCH);
Robert Horvathd945bf02022-01-27 19:55:16 +0100440 checkUidOwnerRuleForChain(LOW_POWER_STANDBY, LOW_POWER_STANDBY_MATCH);
Motomu Utsumib08654c2022-05-11 05:56:26 +0000441 checkUidOwnerRuleForChain(LOCKDOWN, LOCKDOWN_VPN_MATCH);
Motomu Utsumid9801492022-06-01 13:57:27 +0000442 checkUidOwnerRuleForChain(OEM_DENY_1, OEM_DENY_1_MATCH);
443 checkUidOwnerRuleForChain(OEM_DENY_2, OEM_DENY_2_MATCH);
Motomu Utsumi1d9054b2022-06-06 07:44:05 +0000444 checkUidOwnerRuleForChain(OEM_DENY_3, OEM_DENY_3_MATCH);
Wayne Ma4d692332022-01-19 16:04:04 +0800445 ASSERT_EQ(-EINVAL, mTc.changeUidOwnerRule(NONE, TEST_UID, ALLOW, ALLOWLIST));
446 ASSERT_EQ(-EINVAL, mTc.changeUidOwnerRule(INVALID_CHAIN, TEST_UID, ALLOW, ALLOWLIST));
447}
448
449TEST_F(TrafficControllerTest, TestReplaceUidOwnerMap) {
450 std::vector<int32_t> uids = {TEST_UID, TEST_UID2, TEST_UID3};
451 checkUidMapReplace("fw_dozable", uids, DOZABLE_MATCH);
452 checkUidMapReplace("fw_standby", uids, STANDBY_MATCH);
453 checkUidMapReplace("fw_powersave", uids, POWERSAVE_MATCH);
454 checkUidMapReplace("fw_restricted", uids, RESTRICTED_MATCH);
Robert Horvathd945bf02022-01-27 19:55:16 +0100455 checkUidMapReplace("fw_low_power_standby", uids, LOW_POWER_STANDBY_MATCH);
Motomu Utsumid9801492022-06-01 13:57:27 +0000456 checkUidMapReplace("fw_oem_deny_1", uids, OEM_DENY_1_MATCH);
457 checkUidMapReplace("fw_oem_deny_2", uids, OEM_DENY_2_MATCH);
Motomu Utsumi1d9054b2022-06-06 07:44:05 +0000458 checkUidMapReplace("fw_oem_deny_3", uids, OEM_DENY_3_MATCH);
Wayne Ma4d692332022-01-19 16:04:04 +0800459 ASSERT_EQ(-EINVAL, mTc.replaceUidOwnerMap("unknow", true, uids));
460}
461
462TEST_F(TrafficControllerTest, TestReplaceSameChain) {
463 std::vector<int32_t> uids = {TEST_UID, TEST_UID2, TEST_UID3};
464 checkUidMapReplace("fw_dozable", uids, DOZABLE_MATCH);
465 std::vector<int32_t> newUids = {TEST_UID2, TEST_UID3};
466 checkUidMapReplace("fw_dozable", newUids, DOZABLE_MATCH);
467}
468
469TEST_F(TrafficControllerTest, TestDenylistUidMatch) {
470 std::vector<uint32_t> appUids = {1000, 1001, 10012};
Wayne Ma7be6bce2022-01-12 16:29:49 +0800471 ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, PENALTY_BOX_MATCH,
472 TrafficController::IptOpInsert)));
Wayne Ma4d692332022-01-19 16:04:04 +0800473 expectUidOwnerMapValues(appUids, PENALTY_BOX_MATCH, 0);
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 expectMapEmpty(mFakeUidOwnerMap);
477}
478
479TEST_F(TrafficControllerTest, TestAllowlistUidMatch) {
480 std::vector<uint32_t> appUids = {1000, 1001, 10012};
Wayne Ma7be6bce2022-01-12 16:29:49 +0800481 ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, HAPPY_BOX_MATCH, TrafficController::IptOpInsert)));
Wayne Ma4d692332022-01-19 16:04:04 +0800482 expectUidOwnerMapValues(appUids, HAPPY_BOX_MATCH, 0);
Wayne Ma7be6bce2022-01-12 16:29:49 +0800483 ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, HAPPY_BOX_MATCH, TrafficController::IptOpDelete)));
Wayne Ma4d692332022-01-19 16:04:04 +0800484 expectMapEmpty(mFakeUidOwnerMap);
485}
486
487TEST_F(TrafficControllerTest, TestReplaceMatchUid) {
488 std::vector<uint32_t> appUids = {1000, 1001, 10012};
489 // Add appUids to the denylist and expect that their values are all PENALTY_BOX_MATCH.
Wayne Ma7be6bce2022-01-12 16:29:49 +0800490 ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, PENALTY_BOX_MATCH,
491 TrafficController::IptOpInsert)));
Wayne Ma4d692332022-01-19 16:04:04 +0800492 expectUidOwnerMapValues(appUids, PENALTY_BOX_MATCH, 0);
493
494 // Add the same UIDs to the allowlist and expect that we get PENALTY_BOX_MATCH |
495 // HAPPY_BOX_MATCH.
Wayne Ma7be6bce2022-01-12 16:29:49 +0800496 ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, HAPPY_BOX_MATCH, TrafficController::IptOpInsert)));
Wayne Ma4d692332022-01-19 16:04:04 +0800497 expectUidOwnerMapValues(appUids, HAPPY_BOX_MATCH | PENALTY_BOX_MATCH, 0);
498
499 // Remove the same UIDs from the allowlist and check the PENALTY_BOX_MATCH is still there.
Wayne Ma7be6bce2022-01-12 16:29:49 +0800500 ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, HAPPY_BOX_MATCH, TrafficController::IptOpDelete)));
Wayne Ma4d692332022-01-19 16:04:04 +0800501 expectUidOwnerMapValues(appUids, PENALTY_BOX_MATCH, 0);
502
503 // Remove the same UIDs from the denylist and check the map is empty.
Wayne Ma7be6bce2022-01-12 16:29:49 +0800504 ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, PENALTY_BOX_MATCH,
505 TrafficController::IptOpDelete)));
Wayne Ma4d692332022-01-19 16:04:04 +0800506 ASSERT_FALSE(mFakeUidOwnerMap.getFirstKey().ok());
507}
508
509TEST_F(TrafficControllerTest, TestDeleteWrongMatchSilentlyFails) {
510 std::vector<uint32_t> appUids = {1000, 1001, 10012};
511 // 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 +0800512 ASSERT_FALSE(isOk(updateUidOwnerMaps(appUids, HAPPY_BOX_MATCH,
513 TrafficController::IptOpDelete)));
Wayne Ma4d692332022-01-19 16:04:04 +0800514 expectMapEmpty(mFakeUidOwnerMap);
515
516 // Add denylist rules for appUids.
Wayne Ma7be6bce2022-01-12 16:29:49 +0800517 ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, HAPPY_BOX_MATCH,
518 TrafficController::IptOpInsert)));
Wayne Ma4d692332022-01-19 16:04:04 +0800519 expectUidOwnerMapValues(appUids, HAPPY_BOX_MATCH, 0);
520
521 // Delete (non-existent) denylist rules for appUids, and check that this silently does
522 // nothing if the uid is in the map but does not have denylist match. This is required because
523 // NetworkManagementService will try to remove a uid from denylist after adding it to the
524 // allowlist and if the remove fails it will not update the uid status.
Wayne Ma7be6bce2022-01-12 16:29:49 +0800525 ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, PENALTY_BOX_MATCH,
526 TrafficController::IptOpDelete)));
Wayne Ma4d692332022-01-19 16:04:04 +0800527 expectUidOwnerMapValues(appUids, HAPPY_BOX_MATCH, 0);
528}
529
530TEST_F(TrafficControllerTest, TestAddUidInterfaceFilteringRules) {
531 int iif0 = 15;
532 ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif0, {1000, 1001})));
533 expectUidOwnerMapValues({1000, 1001}, IIF_MATCH, iif0);
534
535 // Add some non-overlapping new uids. They should coexist with existing rules
536 int iif1 = 16;
537 ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif1, {2000, 2001})));
538 expectUidOwnerMapValues({1000, 1001}, IIF_MATCH, iif0);
539 expectUidOwnerMapValues({2000, 2001}, IIF_MATCH, iif1);
540
541 // Overwrite some existing uids
542 int iif2 = 17;
543 ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif2, {1000, 2000})));
544 expectUidOwnerMapValues({1001}, IIF_MATCH, iif0);
545 expectUidOwnerMapValues({2001}, IIF_MATCH, iif1);
546 expectUidOwnerMapValues({1000, 2000}, IIF_MATCH, iif2);
547}
548
549TEST_F(TrafficControllerTest, TestRemoveUidInterfaceFilteringRules) {
550 int iif0 = 15;
551 int iif1 = 16;
552 ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif0, {1000, 1001})));
553 ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif1, {2000, 2001})));
554 expectUidOwnerMapValues({1000, 1001}, IIF_MATCH, iif0);
555 expectUidOwnerMapValues({2000, 2001}, IIF_MATCH, iif1);
556
557 // Rmove some uids
558 ASSERT_TRUE(isOk(mTc.removeUidInterfaceRules({1001, 2001})));
559 expectUidOwnerMapValues({1000}, IIF_MATCH, iif0);
560 expectUidOwnerMapValues({2000}, IIF_MATCH, iif1);
561 checkEachUidValue({1000, 2000}, IIF_MATCH); // Make sure there are only two uids remaining
562
563 // Remove non-existent uids shouldn't fail
564 ASSERT_TRUE(isOk(mTc.removeUidInterfaceRules({2000, 3000})));
565 expectUidOwnerMapValues({1000}, IIF_MATCH, iif0);
566 checkEachUidValue({1000}, IIF_MATCH); // Make sure there are only one uid remaining
567
568 // Remove everything
569 ASSERT_TRUE(isOk(mTc.removeUidInterfaceRules({1000})));
570 expectMapEmpty(mFakeUidOwnerMap);
571}
572
573TEST_F(TrafficControllerTest, TestUidInterfaceFilteringRulesCoexistWithExistingMatches) {
574 // Set up existing PENALTY_BOX_MATCH rules
Wayne Ma7be6bce2022-01-12 16:29:49 +0800575 ASSERT_TRUE(isOk(updateUidOwnerMaps({1000, 1001, 10012}, PENALTY_BOX_MATCH,
576 TrafficController::IptOpInsert)));
Wayne Ma4d692332022-01-19 16:04:04 +0800577 expectUidOwnerMapValues({1000, 1001, 10012}, PENALTY_BOX_MATCH, 0);
578
579 // Add some partially-overlapping uid owner rules and check result
580 int iif1 = 32;
581 ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif1, {10012, 10013, 10014})));
582 expectUidOwnerMapValues({1000, 1001}, PENALTY_BOX_MATCH, 0);
583 expectUidOwnerMapValues({10012}, PENALTY_BOX_MATCH | IIF_MATCH, iif1);
584 expectUidOwnerMapValues({10013, 10014}, IIF_MATCH, iif1);
585
586 // Removing some PENALTY_BOX_MATCH rules should not change uid interface rule
Wayne Ma7be6bce2022-01-12 16:29:49 +0800587 ASSERT_TRUE(isOk(updateUidOwnerMaps({1001, 10012}, PENALTY_BOX_MATCH,
588 TrafficController::IptOpDelete)));
Wayne Ma4d692332022-01-19 16:04:04 +0800589 expectUidOwnerMapValues({1000}, PENALTY_BOX_MATCH, 0);
590 expectUidOwnerMapValues({10012, 10013, 10014}, IIF_MATCH, iif1);
591
592 // Remove all uid interface rules
593 ASSERT_TRUE(isOk(mTc.removeUidInterfaceRules({10012, 10013, 10014})));
594 expectUidOwnerMapValues({1000}, PENALTY_BOX_MATCH, 0);
595 // Make sure these are the only uids left
596 checkEachUidValue({1000}, PENALTY_BOX_MATCH);
597}
598
599TEST_F(TrafficControllerTest, TestUidInterfaceFilteringRulesCoexistWithNewMatches) {
600 int iif1 = 56;
601 // Set up existing uid interface rules
602 ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif1, {10001, 10002})));
603 expectUidOwnerMapValues({10001, 10002}, IIF_MATCH, iif1);
604
605 // Add some partially-overlapping doze rules
606 EXPECT_EQ(0, mTc.replaceUidOwnerMap("fw_dozable", true, {10002, 10003}));
607 expectUidOwnerMapValues({10001}, IIF_MATCH, iif1);
608 expectUidOwnerMapValues({10002}, DOZABLE_MATCH | IIF_MATCH, iif1);
609 expectUidOwnerMapValues({10003}, DOZABLE_MATCH, 0);
610
611 // Introduce a third rule type (powersave) on various existing UIDs
612 EXPECT_EQ(0, mTc.replaceUidOwnerMap("fw_powersave", true, {10000, 10001, 10002, 10003}));
613 expectUidOwnerMapValues({10000}, POWERSAVE_MATCH, 0);
614 expectUidOwnerMapValues({10001}, POWERSAVE_MATCH | IIF_MATCH, iif1);
615 expectUidOwnerMapValues({10002}, POWERSAVE_MATCH | DOZABLE_MATCH | IIF_MATCH, iif1);
616 expectUidOwnerMapValues({10003}, POWERSAVE_MATCH | DOZABLE_MATCH, 0);
617
618 // Remove all doze rules
619 EXPECT_EQ(0, mTc.replaceUidOwnerMap("fw_dozable", true, {}));
620 expectUidOwnerMapValues({10000}, POWERSAVE_MATCH, 0);
621 expectUidOwnerMapValues({10001}, POWERSAVE_MATCH | IIF_MATCH, iif1);
622 expectUidOwnerMapValues({10002}, POWERSAVE_MATCH | IIF_MATCH, iif1);
623 expectUidOwnerMapValues({10003}, POWERSAVE_MATCH, 0);
624
625 // Remove all powersave rules, expect ownerMap to only have uid interface rules left
626 EXPECT_EQ(0, mTc.replaceUidOwnerMap("fw_powersave", true, {}));
627 expectUidOwnerMapValues({10001, 10002}, IIF_MATCH, iif1);
628 // Make sure these are the only uids left
629 checkEachUidValue({10001, 10002}, IIF_MATCH);
630}
631
Motomu Utsumib08654c2022-05-11 05:56:26 +0000632TEST_F(TrafficControllerTest, TestAddUidInterfaceFilteringRulesWithWildcard) {
633 // iif=0 is a wildcard
634 int iif = 0;
635 // Add interface rule with wildcard to uids
636 ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif, {1000, 1001})));
637 expectUidOwnerMapValues({1000, 1001}, IIF_MATCH, iif);
638}
639
640TEST_F(TrafficControllerTest, TestRemoveUidInterfaceFilteringRulesWithWildcard) {
641 // iif=0 is a wildcard
642 int iif = 0;
643 // Add interface rule with wildcard to two uids
644 ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif, {1000, 1001})));
645 expectUidOwnerMapValues({1000, 1001}, IIF_MATCH, iif);
646
647 // Remove interface rule from one of the uids
648 ASSERT_TRUE(isOk(mTc.removeUidInterfaceRules({1000})));
649 expectUidOwnerMapValues({1001}, IIF_MATCH, iif);
650 checkEachUidValue({1001}, IIF_MATCH);
651
652 // Remove interface rule from the remaining uid
653 ASSERT_TRUE(isOk(mTc.removeUidInterfaceRules({1001})));
654 expectMapEmpty(mFakeUidOwnerMap);
655}
656
657TEST_F(TrafficControllerTest, TestUidInterfaceFilteringRulesWithWildcardAndExistingMatches) {
658 // Set up existing DOZABLE_MATCH and POWERSAVE_MATCH rule
659 ASSERT_TRUE(isOk(updateUidOwnerMaps({1000}, DOZABLE_MATCH,
660 TrafficController::IptOpInsert)));
661 ASSERT_TRUE(isOk(updateUidOwnerMaps({1000}, POWERSAVE_MATCH,
662 TrafficController::IptOpInsert)));
663
664 // iif=0 is a wildcard
665 int iif = 0;
666 // Add interface rule with wildcard to the existing uid
667 ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif, {1000})));
668 expectUidOwnerMapValues({1000}, POWERSAVE_MATCH | DOZABLE_MATCH | IIF_MATCH, iif);
669
670 // Remove interface rule with wildcard from the existing uid
671 ASSERT_TRUE(isOk(mTc.removeUidInterfaceRules({1000})));
672 expectUidOwnerMapValues({1000}, POWERSAVE_MATCH | DOZABLE_MATCH, 0);
673}
674
675TEST_F(TrafficControllerTest, TestUidInterfaceFilteringRulesWithWildcardAndNewMatches) {
676 // iif=0 is a wildcard
677 int iif = 0;
678 // Set up existing interface rule with wildcard
679 ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif, {1000})));
680
681 // Add DOZABLE_MATCH and POWERSAVE_MATCH rule to the existing uid
682 ASSERT_TRUE(isOk(updateUidOwnerMaps({1000}, DOZABLE_MATCH,
683 TrafficController::IptOpInsert)));
684 ASSERT_TRUE(isOk(updateUidOwnerMaps({1000}, POWERSAVE_MATCH,
685 TrafficController::IptOpInsert)));
686 expectUidOwnerMapValues({1000}, POWERSAVE_MATCH | DOZABLE_MATCH | IIF_MATCH, iif);
687
688 // Remove DOZABLE_MATCH and POWERSAVE_MATCH rule from the existing uid
689 ASSERT_TRUE(isOk(updateUidOwnerMaps({1000}, DOZABLE_MATCH,
690 TrafficController::IptOpDelete)));
691 ASSERT_TRUE(isOk(updateUidOwnerMaps({1000}, POWERSAVE_MATCH,
692 TrafficController::IptOpDelete)));
693 expectUidOwnerMapValues({1000}, IIF_MATCH, iif);
694}
695
Wayne Ma4d692332022-01-19 16:04:04 +0800696TEST_F(TrafficControllerTest, TestGrantInternetPermission) {
697 std::vector<uid_t> appUids = {TEST_UID, TEST_UID2, TEST_UID3};
698
699 mTc.setPermissionForUids(INetd::PERMISSION_INTERNET, appUids);
700 expectMapEmpty(mFakeUidPermissionMap);
701 expectPrivilegedUserSetEmpty();
702}
703
704TEST_F(TrafficControllerTest, TestRevokeInternetPermission) {
705 std::vector<uid_t> appUids = {TEST_UID, TEST_UID2, TEST_UID3};
706
707 mTc.setPermissionForUids(INetd::PERMISSION_NONE, appUids);
708 expectUidPermissionMapValues(appUids, INetd::PERMISSION_NONE);
709}
710
711TEST_F(TrafficControllerTest, TestPermissionUninstalled) {
712 std::vector<uid_t> appUids = {TEST_UID, TEST_UID2, TEST_UID3};
713
714 mTc.setPermissionForUids(INetd::PERMISSION_UPDATE_DEVICE_STATS, appUids);
715 expectUidPermissionMapValues(appUids, INetd::PERMISSION_UPDATE_DEVICE_STATS);
716 expectPrivilegedUserSet(appUids);
717
718 std::vector<uid_t> uidToRemove = {TEST_UID};
719 mTc.setPermissionForUids(INetd::PERMISSION_UNINSTALLED, uidToRemove);
720
721 std::vector<uid_t> uidRemain = {TEST_UID3, TEST_UID2};
722 expectUidPermissionMapValues(uidRemain, INetd::PERMISSION_UPDATE_DEVICE_STATS);
723 expectPrivilegedUserSet(uidRemain);
724
725 mTc.setPermissionForUids(INetd::PERMISSION_UNINSTALLED, uidRemain);
726 expectMapEmpty(mFakeUidPermissionMap);
727 expectPrivilegedUserSetEmpty();
728}
729
730TEST_F(TrafficControllerTest, TestGrantUpdateStatsPermission) {
731 std::vector<uid_t> appUids = {TEST_UID, TEST_UID2, TEST_UID3};
732
733 mTc.setPermissionForUids(INetd::PERMISSION_UPDATE_DEVICE_STATS, appUids);
734 expectUidPermissionMapValues(appUids, INetd::PERMISSION_UPDATE_DEVICE_STATS);
735 expectPrivilegedUserSet(appUids);
736
737 mTc.setPermissionForUids(INetd::PERMISSION_NONE, appUids);
738 expectPrivilegedUserSetEmpty();
739 expectUidPermissionMapValues(appUids, INetd::PERMISSION_NONE);
740}
741
742TEST_F(TrafficControllerTest, TestRevokeUpdateStatsPermission) {
743 std::vector<uid_t> appUids = {TEST_UID, TEST_UID2, TEST_UID3};
744
745 mTc.setPermissionForUids(INetd::PERMISSION_UPDATE_DEVICE_STATS, appUids);
746 expectPrivilegedUserSet(appUids);
747
748 std::vector<uid_t> uidToRemove = {TEST_UID};
749 mTc.setPermissionForUids(INetd::PERMISSION_NONE, uidToRemove);
750
751 std::vector<uid_t> uidRemain = {TEST_UID3, TEST_UID2};
752 expectPrivilegedUserSet(uidRemain);
753
754 mTc.setPermissionForUids(INetd::PERMISSION_NONE, uidRemain);
755 expectPrivilegedUserSetEmpty();
756}
757
758TEST_F(TrafficControllerTest, TestGrantWrongPermission) {
759 std::vector<uid_t> appUids = {TEST_UID, TEST_UID2, TEST_UID3};
760
761 mTc.setPermissionForUids(INetd::PERMISSION_NONE, appUids);
762 expectPrivilegedUserSetEmpty();
763 expectUidPermissionMapValues(appUids, INetd::PERMISSION_NONE);
764}
765
766TEST_F(TrafficControllerTest, TestGrantDuplicatePermissionSlientlyFail) {
767 std::vector<uid_t> appUids = {TEST_UID, TEST_UID2, TEST_UID3};
768
769 mTc.setPermissionForUids(INetd::PERMISSION_INTERNET, appUids);
770 expectMapEmpty(mFakeUidPermissionMap);
771
772 std::vector<uid_t> uidToAdd = {TEST_UID};
773 mTc.setPermissionForUids(INetd::PERMISSION_INTERNET, uidToAdd);
774
775 expectPrivilegedUserSetEmpty();
776
777 mTc.setPermissionForUids(INetd::PERMISSION_NONE, appUids);
778 expectUidPermissionMapValues(appUids, INetd::PERMISSION_NONE);
779
780 mTc.setPermissionForUids(INetd::PERMISSION_UPDATE_DEVICE_STATS, appUids);
781 expectPrivilegedUserSet(appUids);
782
783 mTc.setPermissionForUids(INetd::PERMISSION_UPDATE_DEVICE_STATS, uidToAdd);
784 expectPrivilegedUserSet(appUids);
785
786 mTc.setPermissionForUids(INetd::PERMISSION_NONE, appUids);
787 expectPrivilegedUserSetEmpty();
788}
789
Ken Chen2fb86362022-06-05 11:39:38 +0800790TEST_F(TrafficControllerTest, TestDumpsys) {
Ken Chen0dd74952022-06-06 18:25:18 +0800791 StatsKey tagStatsMapKey;
792 populateFakeStats(TEST_COOKIE, TEST_UID, TEST_TAG, &tagStatsMapKey);
793 populateFakeCounterSet(TEST_UID3, TEST_COUNTERSET);
Ken Chen2fb86362022-06-05 11:39:38 +0800794
Ken Chen0dd74952022-06-06 18:25:18 +0800795 // Expect: (part of this depends on hard-code values in populateFakeStats())
796 //
797 // mCookieTagMap:
798 // cookie=1 tag=0x2a uid=10086
799 //
800 // mUidCounterSetMap:
801 // 98765 1
802 //
803 // mAppUidStatsMap::
804 // uid rxBytes rxPackets txBytes txPackets
805 // 10086 100 1 0 0
806 //
807 // mStatsMapA:
808 // ifaceIndex ifaceName tag_hex uid_int cnt_set rxBytes rxPackets txBytes txPackets
809 // 999 test0 0x2a 10086 1 100 1 0 0
Ken Chen2fb86362022-06-05 11:39:38 +0800810 std::vector<std::string> expectedLines = {
Ken Chen0dd74952022-06-06 18:25:18 +0800811 "mCookieTagMap:",
812 fmt::format("cookie={} tag={:#x} uid={}", TEST_COOKIE, TEST_TAG, TEST_UID),
813 "mUidCounterSetMap:",
814 fmt::format("{} {}", TEST_UID3, TEST_COUNTERSET),
815 "mAppUidStatsMap::", // TODO@: fix double colon
816 "uid rxBytes rxPackets txBytes txPackets",
817 fmt::format("{} {} {} {} {}", TEST_UID, RXBYTES, RXPACKETS, TXBYTES, TXPACKETS),
818 "mStatsMapA",
819 "ifaceIndex ifaceName tag_hex uid_int cnt_set rxBytes rxPackets txBytes txPackets",
820 fmt::format("{} {} {:#x} {} {} {} {} {} {}",
821 TEST_IFINDEX, TEST_IFNAME, TEST_TAG, TEST_UID, TEST_COUNTERSET, RXBYTES,
822 RXPACKETS, TXBYTES, TXPACKETS)};
Ken Chen2fb86362022-06-05 11:39:38 +0800823
Ken Chen0dd74952022-06-06 18:25:18 +0800824 populateFakeIfaceIndexName(TEST_IFNAME, TEST_IFINDEX);
825 expectedLines.emplace_back("mIfaceIndexNameMap:");
826 expectedLines.emplace_back(fmt::format("ifaceIndex={} ifaceName={}",
827 TEST_IFINDEX, TEST_IFNAME));
828
829 ASSERT_TRUE(isOk(updateUidOwnerMaps({TEST_UID}, HAPPY_BOX_MATCH,
830 TrafficController::IptOpInsert)));
831 expectedLines.emplace_back("mUidOwnerMap:");
832 expectedLines.emplace_back(fmt::format("{} HAPPY_BOX_MATCH", TEST_UID));
833
834 mTc.setPermissionForUids(INetd::PERMISSION_UPDATE_DEVICE_STATS, {TEST_UID2});
835 expectedLines.emplace_back("mUidPermissionMap:");
836 expectedLines.emplace_back(fmt::format("{} BPF_PERMISSION_UPDATE_DEVICE_STATS", TEST_UID2));
837 expectedLines.emplace_back("mPrivilegedUser:");
838 expectedLines.emplace_back(fmt::format("{} ALLOW_UPDATE_DEVICE_STATS", TEST_UID2));
Ken Chen2fb86362022-06-05 11:39:38 +0800839 EXPECT_TRUE(expectDumpsysContains(expectedLines));
840}
841
Hungming Chen410bb122022-06-09 01:32:00 +0800842TEST_F(TrafficControllerTest, dumpsysInvalidMaps) {
843 makeTrafficControllerMapsInvalid();
844
Hungming Chen56b90132022-06-09 11:33:43 +0800845 const std::string kErrIterate = "print end with error: Get firstKey map -1 failed: "
846 "Bad file descriptor";
847 const std::string kErrReadRulesConfig = "read ownerMatch configure failed with error: "
848 "Read value of map -1 failed: Bad file descriptor";
849 const std::string kErrReadStatsMapConfig = "read stats map configure failed with error: "
850 "Read value of map -1 failed: Bad file descriptor";
851
Hungming Chen410bb122022-06-09 01:32:00 +0800852 std::vector<std::string> expectedLines = {
Hungming Chen56b90132022-06-09 11:33:43 +0800853 fmt::format("mCookieTagMap {}", kErrIterate),
854 fmt::format("mUidCounterSetMap {}", kErrIterate),
855 fmt::format("mAppUidStatsMap {}", kErrIterate),
856 fmt::format("mStatsMapA {}", kErrIterate),
857 fmt::format("mStatsMapB {}", kErrIterate),
858 fmt::format("mIfaceIndexNameMap {}", kErrIterate),
859 fmt::format("mIfaceStatsMap {}", kErrIterate),
860 fmt::format("mConfigurationMap {}", kErrReadRulesConfig),
861 fmt::format("mConfigurationMap {}", kErrReadStatsMapConfig),
862 fmt::format("mUidOwnerMap {}", kErrIterate),
863 fmt::format("mUidPermissionMap {}", kErrIterate)};
Hungming Chen410bb122022-06-09 01:32:00 +0800864 EXPECT_TRUE(expectDumpsysContains(expectedLines));
865}
866
Hungming Chen1d4d3d22022-06-08 11:50:15 +0800867TEST_F(TrafficControllerTest, uidMatchTypeToString) {
868 // NO_MATCH(0) can't be verified because match type flag is added by OR operator.
869 // See TrafficController::addRule()
870 static const struct TestConfig {
871 UidOwnerMatchType uidOwnerMatchType;
872 std::string expected;
873 } testConfigs[] = {
874 // clang-format off
875 {HAPPY_BOX_MATCH, "HAPPY_BOX_MATCH"},
876 {DOZABLE_MATCH, "DOZABLE_MATCH"},
877 {STANDBY_MATCH, "STANDBY_MATCH"},
878 {POWERSAVE_MATCH, "POWERSAVE_MATCH"},
879 {HAPPY_BOX_MATCH, "HAPPY_BOX_MATCH"},
880 {RESTRICTED_MATCH, "RESTRICTED_MATCH"},
881 {LOW_POWER_STANDBY_MATCH, "LOW_POWER_STANDBY_MATCH"},
882 {IIF_MATCH, "IIF_MATCH"},
883 {LOCKDOWN_VPN_MATCH, "LOCKDOWN_VPN_MATCH"},
884 {OEM_DENY_1_MATCH, "OEM_DENY_1_MATCH"},
885 {OEM_DENY_2_MATCH, "OEM_DENY_2_MATCH"},
886 {OEM_DENY_3_MATCH, "OEM_DENY_3_MATCH"},
887 // clang-format on
888 };
889
890 for (const auto& config : testConfigs) {
891 SCOPED_TRACE(fmt::format("testConfig: [{}, {}]", config.uidOwnerMatchType,
892 config.expected));
893
894 // Test private function uidMatchTypeToString() via dumpsys.
895 ASSERT_TRUE(isOk(updateUidOwnerMaps({TEST_UID}, config.uidOwnerMatchType,
896 TrafficController::IptOpInsert)));
897 std::vector<std::string> expectedLines;
898 expectedLines.emplace_back(fmt::format("{} {}", TEST_UID, config.expected));
899 EXPECT_TRUE(expectDumpsysContains(expectedLines));
900
901 // Clean up the stubs.
902 ASSERT_TRUE(isOk(updateUidOwnerMaps({TEST_UID}, config.uidOwnerMatchType,
903 TrafficController::IptOpDelete)));
904 }
905}
906
Ken Chen77a6b712022-06-06 12:46:36 +0800907TEST_F(TrafficControllerTest, getFirewallType) {
908 static const struct TestConfig {
909 ChildChain childChain;
910 FirewallType firewallType;
911 } testConfigs[] = {
912 // clang-format off
913 {NONE, DENYLIST},
914 {DOZABLE, ALLOWLIST},
915 {STANDBY, DENYLIST},
916 {POWERSAVE, ALLOWLIST},
917 {RESTRICTED, ALLOWLIST},
918 {LOW_POWER_STANDBY, ALLOWLIST},
919 {LOCKDOWN, DENYLIST},
920 {OEM_DENY_1, DENYLIST},
921 {OEM_DENY_2, DENYLIST},
Ken Chend3a3af52022-06-08 02:54:09 +0000922 {OEM_DENY_3, DENYLIST},
Ken Chen77a6b712022-06-06 12:46:36 +0800923 {INVALID_CHAIN, DENYLIST},
924 // clang-format on
925 };
926
927 for (const auto& config : testConfigs) {
928 SCOPED_TRACE(fmt::format("testConfig: [{}, {}]", config.childChain, config.firewallType));
929 EXPECT_EQ(config.firewallType, mTc.getFirewallType(config.childChain));
930 }
931}
932
Patrick Rohr61e94672022-02-01 21:06:40 +0100933constexpr uint32_t SOCK_CLOSE_WAIT_US = 30 * 1000;
934constexpr uint32_t ENOBUFS_POLL_WAIT_US = 10 * 1000;
935
936using android::base::Error;
937using android::base::Result;
938using android::bpf::BpfMap;
939
940// This test set up a SkDestroyListener that is running parallel with the production
941// SkDestroyListener. The test will create thousands of sockets and tag them on the
942// production cookieUidTagMap and close them in a short time. When the number of
943// sockets get closed exceeds the buffer size, it will start to return ENOBUFF
944// error. The error will be ignored by the production SkDestroyListener and the
945// test will clean up the tags in tearDown if there is any remains.
946
947// TODO: Instead of test the ENOBUFF error, we can test the production
948// SkDestroyListener to see if it failed to delete a tagged socket when ENOBUFF
949// triggered.
950class NetlinkListenerTest : public testing::Test {
951 protected:
952 NetlinkListenerTest() {}
953 BpfMap<uint64_t, UidTagValue> mCookieTagMap;
954
955 void SetUp() {
Maciej Żenczykowskiced35312022-05-31 05:11:12 -0700956 mCookieTagMap.init(COOKIE_TAG_MAP_PATH);
Patrick Rohr61e94672022-02-01 21:06:40 +0100957 ASSERT_TRUE(mCookieTagMap.isValid());
958 }
959
960 void TearDown() {
961 const auto deleteTestCookieEntries = [](const uint64_t& key, const UidTagValue& value,
962 BpfMap<uint64_t, UidTagValue>& map) {
963 if ((value.uid == TEST_UID) && (value.tag == TEST_TAG)) {
964 Result<void> res = map.deleteValue(key);
965 if (res.ok() || (res.error().code() == ENOENT)) {
966 return Result<void>();
967 }
Maciej Żenczykowskie0f58462022-05-17 13:59:22 -0700968 ALOGE("Failed to delete data(cookie = %" PRIu64 "): %s", key,
Patrick Rohr61e94672022-02-01 21:06:40 +0100969 strerror(res.error().code()));
970 }
971 // Move forward to next cookie in the map.
972 return Result<void>();
973 };
974 EXPECT_RESULT_OK(mCookieTagMap.iterateWithValue(deleteTestCookieEntries));
975 }
976
977 Result<void> checkNoGarbageTagsExist() {
978 const auto checkGarbageTags = [](const uint64_t&, const UidTagValue& value,
979 const BpfMap<uint64_t, UidTagValue>&) -> Result<void> {
980 if ((TEST_UID == value.uid) && (TEST_TAG == value.tag)) {
981 return Error(EUCLEAN) << "Closed socket is not untagged";
982 }
983 return {};
984 };
985 return mCookieTagMap.iterateWithValue(checkGarbageTags);
986 }
987
988 bool checkMassiveSocketDestroy(int totalNumber, bool expectError) {
989 std::unique_ptr<android::netdutils::NetlinkListenerInterface> skDestroyListener;
990 auto result = android::net::TrafficController::makeSkDestroyListener();
991 if (!isOk(result)) {
992 ALOGE("Unable to create SkDestroyListener: %s", toString(result).c_str());
993 } else {
994 skDestroyListener = std::move(result.value());
995 }
996 int rxErrorCount = 0;
997 // Rx handler extracts nfgenmsg looks up and invokes registered dispatch function.
998 const auto rxErrorHandler = [&rxErrorCount](const int, const int) { rxErrorCount++; };
999 skDestroyListener->registerSkErrorHandler(rxErrorHandler);
1000 int fds[totalNumber];
1001 for (int i = 0; i < totalNumber; i++) {
1002 fds[i] = socket(AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0);
1003 // The likely reason for a failure is running out of available file descriptors.
1004 EXPECT_LE(0, fds[i]) << i << " of " << totalNumber;
1005 if (fds[i] < 0) {
1006 // EXPECT_LE already failed above, so test case is a failure, but we don't
1007 // want potentially tens of thousands of extra failures creating and then
1008 // closing all these fds cluttering up the logs.
1009 totalNumber = i;
1010 break;
1011 };
1012 libnetd_updatable_tagSocket(fds[i], TEST_TAG, TEST_UID, 1000);
1013 }
1014
1015 // TODO: Use a separate thread that has its own fd table so we can
1016 // close sockets even faster simply by terminating that thread.
1017 for (int i = 0; i < totalNumber; i++) {
1018 EXPECT_EQ(0, close(fds[i]));
1019 }
1020 // wait a bit for netlink listener to handle all the messages.
1021 usleep(SOCK_CLOSE_WAIT_US);
1022 if (expectError) {
1023 // If ENOBUFS triggered, check it only called into the handler once, ie.
1024 // that the netlink handler is not spinning.
1025 int currentErrorCount = rxErrorCount;
1026 // 0 error count is acceptable because the system has chances to close all sockets
1027 // normally.
1028 EXPECT_LE(0, rxErrorCount);
1029 if (!rxErrorCount) return true;
1030
1031 usleep(ENOBUFS_POLL_WAIT_US);
1032 EXPECT_EQ(currentErrorCount, rxErrorCount);
1033 } else {
1034 EXPECT_RESULT_OK(checkNoGarbageTagsExist());
1035 EXPECT_EQ(0, rxErrorCount);
1036 }
1037 return false;
1038 }
1039};
1040
1041TEST_F(NetlinkListenerTest, TestAllSocketUntagged) {
1042 checkMassiveSocketDestroy(10, false);
1043 checkMassiveSocketDestroy(100, false);
1044}
1045
1046// Disabled because flaky on blueline-userdebug; this test relies on the main thread
1047// winning a race against the NetlinkListener::run() thread. There's no way to ensure
1048// things will be scheduled the same way across all architectures and test environments.
1049TEST_F(NetlinkListenerTest, DISABLED_TestSkDestroyError) {
1050 bool needRetry = false;
1051 int retryCount = 0;
1052 do {
1053 needRetry = checkMassiveSocketDestroy(32500, true);
1054 if (needRetry) retryCount++;
1055 } while (needRetry && retryCount < 3);
1056 // Should review test if it can always close all sockets correctly.
1057 EXPECT_GT(3, retryCount);
1058}
1059
1060
Wayne Ma4d692332022-01-19 16:04:04 +08001061} // namespace net
1062} // namespace android