blob: 57f32afe6bce10200542af4f1632bcb4881fcfb3 [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 Żenczykowski01319d92022-06-13 18:25:34 -070041#define BPF_MAP_MAKE_VISIBLE_FOR_TESTING
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_IFINDEX = 999;
63constexpr int RXPACKETS = 1;
64constexpr int RXBYTES = 100;
65constexpr int TXPACKETS = 0;
66constexpr int TXBYTES = 0;
Wayne Ma4d692332022-01-19 16:04:04 +080067
68#define ASSERT_VALID(x) ASSERT_TRUE((x).isValid())
Hungming Chen410bb122022-06-09 01:32:00 +080069#define ASSERT_INVALID(x) ASSERT_FALSE((x).isValid())
Wayne Ma4d692332022-01-19 16:04:04 +080070
71class TrafficControllerTest : public ::testing::Test {
72 protected:
Wayne Ma92d80792022-01-20 13:20:34 +080073 TrafficControllerTest() {}
Wayne Ma4d692332022-01-19 16:04:04 +080074 TrafficController mTc;
75 BpfMap<uint64_t, UidTagValue> mFakeCookieTagMap;
Wayne Ma4d692332022-01-19 16:04:04 +080076 BpfMap<uint32_t, StatsValue> mFakeAppUidStatsMap;
77 BpfMap<StatsKey, StatsValue> mFakeStatsMapA;
Hungming Chen410bb122022-06-09 01:32:00 +080078 BpfMap<StatsKey, StatsValue> mFakeStatsMapB; // makeTrafficControllerMapsInvalid only
79 BpfMap<uint32_t, StatsValue> mFakeIfaceStatsMap; ; // makeTrafficControllerMapsInvalid only
Lorenzo Colitti60cbed32022-03-03 17:49:01 +090080 BpfMap<uint32_t, uint32_t> mFakeConfigurationMap;
Wayne Ma4d692332022-01-19 16:04:04 +080081 BpfMap<uint32_t, UidOwnerValue> mFakeUidOwnerMap;
82 BpfMap<uint32_t, uint8_t> mFakeUidPermissionMap;
Ken Chen0dd74952022-06-06 18:25:18 +080083 BpfMap<uint32_t, uint8_t> mFakeUidCounterSetMap;
84 BpfMap<uint32_t, IfaceValue> mFakeIfaceIndexNameMap;
Wayne Ma4d692332022-01-19 16:04:04 +080085
86 void SetUp() {
87 std::lock_guard guard(mTc.mMutex);
88 ASSERT_EQ(0, setrlimitForTest());
89
Maciej Żenczykowski439bac22022-05-31 03:22:32 -070090 mFakeCookieTagMap.resetMap(BPF_MAP_TYPE_HASH, TEST_MAP_SIZE);
Wayne Ma4d692332022-01-19 16:04:04 +080091 ASSERT_VALID(mFakeCookieTagMap);
92
Maciej Żenczykowski439bac22022-05-31 03:22:32 -070093 mFakeAppUidStatsMap.resetMap(BPF_MAP_TYPE_HASH, TEST_MAP_SIZE);
Wayne Ma4d692332022-01-19 16:04:04 +080094 ASSERT_VALID(mFakeAppUidStatsMap);
95
Maciej Żenczykowski439bac22022-05-31 03:22:32 -070096 mFakeStatsMapA.resetMap(BPF_MAP_TYPE_HASH, TEST_MAP_SIZE);
Wayne Ma4d692332022-01-19 16:04:04 +080097 ASSERT_VALID(mFakeStatsMapA);
98
Maciej Żenczykowskib10e0552022-06-16 14:49:27 -070099 mFakeConfigurationMap.resetMap(BPF_MAP_TYPE_ARRAY, CONFIGURATION_MAP_SIZE);
Wayne Ma4d692332022-01-19 16:04:04 +0800100 ASSERT_VALID(mFakeConfigurationMap);
101
Maciej Żenczykowski439bac22022-05-31 03:22:32 -0700102 mFakeUidOwnerMap.resetMap(BPF_MAP_TYPE_HASH, TEST_MAP_SIZE);
Wayne Ma4d692332022-01-19 16:04:04 +0800103 ASSERT_VALID(mFakeUidOwnerMap);
Maciej Żenczykowski439bac22022-05-31 03:22:32 -0700104 mFakeUidPermissionMap.resetMap(BPF_MAP_TYPE_HASH, TEST_MAP_SIZE);
Wayne Ma4d692332022-01-19 16:04:04 +0800105 ASSERT_VALID(mFakeUidPermissionMap);
106
Ken Chen0dd74952022-06-06 18:25:18 +0800107 mFakeUidCounterSetMap.resetMap(BPF_MAP_TYPE_HASH, TEST_MAP_SIZE);
108 ASSERT_VALID(mFakeUidCounterSetMap);
109
110 mFakeIfaceIndexNameMap.resetMap(BPF_MAP_TYPE_HASH, TEST_MAP_SIZE);
111 ASSERT_VALID(mFakeIfaceIndexNameMap);
112
Maciej Żenczykowski55ab87a2022-05-31 03:15:12 -0700113 mTc.mCookieTagMap = mFakeCookieTagMap;
Wayne Ma4d692332022-01-19 16:04:04 +0800114 ASSERT_VALID(mTc.mCookieTagMap);
Maciej Żenczykowski55ab87a2022-05-31 03:15:12 -0700115 mTc.mAppUidStatsMap = mFakeAppUidStatsMap;
Wayne Ma4d692332022-01-19 16:04:04 +0800116 ASSERT_VALID(mTc.mAppUidStatsMap);
Maciej Żenczykowski55ab87a2022-05-31 03:15:12 -0700117 mTc.mStatsMapA = mFakeStatsMapA;
Wayne Ma4d692332022-01-19 16:04:04 +0800118 ASSERT_VALID(mTc.mStatsMapA);
Maciej Żenczykowski55ab87a2022-05-31 03:15:12 -0700119 mTc.mConfigurationMap = mFakeConfigurationMap;
Wayne Ma4d692332022-01-19 16:04:04 +0800120 ASSERT_VALID(mTc.mConfigurationMap);
121
122 // Always write to stats map A by default.
Maciej Żenczykowskib10e0552022-06-16 14:49:27 -0700123 static_assert(SELECT_MAP_A == 0);
124
Maciej Żenczykowski55ab87a2022-05-31 03:15:12 -0700125 mTc.mUidOwnerMap = mFakeUidOwnerMap;
Wayne Ma4d692332022-01-19 16:04:04 +0800126 ASSERT_VALID(mTc.mUidOwnerMap);
Maciej Żenczykowski55ab87a2022-05-31 03:15:12 -0700127 mTc.mUidPermissionMap = mFakeUidPermissionMap;
Wayne Ma4d692332022-01-19 16:04:04 +0800128 ASSERT_VALID(mTc.mUidPermissionMap);
129 mTc.mPrivilegedUser.clear();
Ken Chen0dd74952022-06-06 18:25:18 +0800130
131 mTc.mUidCounterSetMap = mFakeUidCounterSetMap;
132 ASSERT_VALID(mTc.mUidCounterSetMap);
133
134 mTc.mIfaceIndexNameMap = mFakeIfaceIndexNameMap;
135 ASSERT_VALID(mTc.mIfaceIndexNameMap);
Wayne Ma4d692332022-01-19 16:04:04 +0800136 }
137
Wayne Ma4d692332022-01-19 16:04:04 +0800138 void populateFakeStats(uint64_t cookie, uint32_t uid, uint32_t tag, StatsKey* key) {
139 UidTagValue cookieMapkey = {.uid = (uint32_t)uid, .tag = tag};
140 EXPECT_RESULT_OK(mFakeCookieTagMap.writeValue(cookie, cookieMapkey, BPF_ANY));
Ken Chen0dd74952022-06-06 18:25:18 +0800141 *key = {.uid = uid, .tag = tag, .counterSet = TEST_COUNTERSET, .ifaceIndex = TEST_IFINDEX};
142 StatsValue statsMapValue = {.rxPackets = RXPACKETS, .rxBytes = RXBYTES,
143 .txPackets = TXPACKETS, .txBytes = TXBYTES};
Wayne Ma4d692332022-01-19 16:04:04 +0800144 EXPECT_RESULT_OK(mFakeStatsMapA.writeValue(*key, statsMapValue, BPF_ANY));
145 EXPECT_RESULT_OK(mFakeAppUidStatsMap.writeValue(uid, statsMapValue, BPF_ANY));
146 // put tag information back to statsKey
147 key->tag = tag;
148 }
149
Ken Chen0dd74952022-06-06 18:25:18 +0800150 void populateFakeCounterSet(uint32_t uid, uint32_t counterSet) {
151 EXPECT_RESULT_OK(mFakeUidCounterSetMap.writeValue(uid, counterSet, BPF_ANY));
152 }
153
154 void populateFakeIfaceIndexName(const char* name, uint32_t ifaceIndex) {
155 if (name == nullptr || ifaceIndex <= 0) return;
156
157 IfaceValue iface;
158 strlcpy(iface.name, name, sizeof(IfaceValue));
159 EXPECT_RESULT_OK(mFakeIfaceIndexNameMap.writeValue(ifaceIndex, iface, BPF_ANY));
160 }
161
Wayne Ma4d692332022-01-19 16:04:04 +0800162 void checkUidOwnerRuleForChain(ChildChain chain, UidOwnerMatchType match) {
163 uint32_t uid = TEST_UID;
164 EXPECT_EQ(0, mTc.changeUidOwnerRule(chain, uid, DENY, DENYLIST));
165 Result<UidOwnerValue> value = mFakeUidOwnerMap.readValue(uid);
166 EXPECT_RESULT_OK(value);
167 EXPECT_TRUE(value.value().rule & match);
168
169 uid = TEST_UID2;
170 EXPECT_EQ(0, mTc.changeUidOwnerRule(chain, uid, ALLOW, ALLOWLIST));
171 value = mFakeUidOwnerMap.readValue(uid);
172 EXPECT_RESULT_OK(value);
173 EXPECT_TRUE(value.value().rule & match);
174
175 EXPECT_EQ(0, mTc.changeUidOwnerRule(chain, uid, DENY, ALLOWLIST));
176 value = mFakeUidOwnerMap.readValue(uid);
177 EXPECT_FALSE(value.ok());
178 EXPECT_EQ(ENOENT, value.error().code());
179
180 uid = TEST_UID;
181 EXPECT_EQ(0, mTc.changeUidOwnerRule(chain, uid, ALLOW, DENYLIST));
182 value = mFakeUidOwnerMap.readValue(uid);
183 EXPECT_FALSE(value.ok());
184 EXPECT_EQ(ENOENT, value.error().code());
185
186 uid = TEST_UID3;
187 EXPECT_EQ(-ENOENT, mTc.changeUidOwnerRule(chain, uid, ALLOW, DENYLIST));
188 value = mFakeUidOwnerMap.readValue(uid);
189 EXPECT_FALSE(value.ok());
190 EXPECT_EQ(ENOENT, value.error().code());
191 }
192
193 void checkEachUidValue(const std::vector<int32_t>& uids, UidOwnerMatchType match) {
194 for (uint32_t uid : uids) {
195 Result<UidOwnerValue> value = mFakeUidOwnerMap.readValue(uid);
196 EXPECT_RESULT_OK(value);
197 EXPECT_TRUE(value.value().rule & match);
198 }
199 std::set<uint32_t> uidSet(uids.begin(), uids.end());
200 const auto checkNoOtherUid = [&uidSet](const int32_t& key,
201 const BpfMap<uint32_t, UidOwnerValue>&) {
202 EXPECT_NE(uidSet.end(), uidSet.find(key));
203 return Result<void>();
204 };
205 EXPECT_RESULT_OK(mFakeUidOwnerMap.iterate(checkNoOtherUid));
206 }
207
208 void checkUidMapReplace(const std::string& name, const std::vector<int32_t>& uids,
209 UidOwnerMatchType match) {
210 bool isAllowlist = true;
211 EXPECT_EQ(0, mTc.replaceUidOwnerMap(name, isAllowlist, uids));
212 checkEachUidValue(uids, match);
213
214 isAllowlist = false;
215 EXPECT_EQ(0, mTc.replaceUidOwnerMap(name, isAllowlist, uids));
216 checkEachUidValue(uids, match);
217 }
218
Motomu Utsumi8b42e6d2022-05-19 06:23:40 +0000219 void expectUidOwnerMapValues(const std::vector<uint32_t>& appUids, uint32_t expectedRule,
Wayne Ma4d692332022-01-19 16:04:04 +0800220 uint32_t expectedIif) {
221 for (uint32_t uid : appUids) {
222 Result<UidOwnerValue> value = mFakeUidOwnerMap.readValue(uid);
223 EXPECT_RESULT_OK(value);
224 EXPECT_EQ(expectedRule, value.value().rule)
225 << "Expected rule for UID " << uid << " to be " << expectedRule << ", but was "
226 << value.value().rule;
227 EXPECT_EQ(expectedIif, value.value().iif)
228 << "Expected iif for UID " << uid << " to be " << expectedIif << ", but was "
229 << value.value().iif;
230 }
231 }
232
233 template <class Key, class Value>
234 void expectMapEmpty(BpfMap<Key, Value>& map) {
235 auto isEmpty = map.isEmpty();
236 EXPECT_RESULT_OK(isEmpty);
237 EXPECT_TRUE(isEmpty.value());
238 }
239
240 void expectUidPermissionMapValues(const std::vector<uid_t>& appUids, uint8_t expectedValue) {
241 for (uid_t uid : appUids) {
242 Result<uint8_t> value = mFakeUidPermissionMap.readValue(uid);
243 EXPECT_RESULT_OK(value);
244 EXPECT_EQ(expectedValue, value.value())
245 << "Expected value for UID " << uid << " to be " << expectedValue
246 << ", but was " << value.value();
247 }
248 }
249
250 void expectPrivilegedUserSet(const std::vector<uid_t>& appUids) {
251 std::lock_guard guard(mTc.mMutex);
252 EXPECT_EQ(appUids.size(), mTc.mPrivilegedUser.size());
253 for (uid_t uid : appUids) {
254 EXPECT_NE(mTc.mPrivilegedUser.end(), mTc.mPrivilegedUser.find(uid));
255 }
256 }
257
258 void expectPrivilegedUserSetEmpty() {
259 std::lock_guard guard(mTc.mMutex);
260 EXPECT_TRUE(mTc.mPrivilegedUser.empty());
261 }
262
Wayne Ma7be6bce2022-01-12 16:29:49 +0800263 Status updateUidOwnerMaps(const std::vector<uint32_t>& appUids,
264 UidOwnerMatchType matchType, TrafficController::IptOp op) {
265 Status ret(0);
266 for (auto uid : appUids) {
267 ret = mTc.updateUidOwnerMap(uid, matchType, op);
268 if(!isOk(ret)) break;
269 }
270 return ret;
271 }
272
Ken Chen2fb86362022-06-05 11:39:38 +0800273 Status dump(bool verbose, std::vector<std::string>& outputLines) {
274 if (!outputLines.empty()) return statusFromErrno(EUCLEAN, "Output buffer is not empty");
275
276 android::base::unique_fd localFd, remoteFd;
277 if (!Pipe(&localFd, &remoteFd)) return statusFromErrno(errno, "Failed on pipe");
278
279 // dump() blocks until another thread has consumed all its output.
280 std::thread dumpThread =
281 std::thread([this, remoteFd{std::move(remoteFd)}, verbose]() {
282 mTc.dump(remoteFd, verbose);
283 });
284
285 std::string dumpContent;
286 if (!android::base::ReadFdToString(localFd.get(), &dumpContent)) {
287 return statusFromErrno(errno, "Failed to read dump results from fd");
288 }
289 dumpThread.join();
290
291 std::stringstream dumpStream(std::move(dumpContent));
292 std::string line;
293 while (std::getline(dumpStream, line)) {
294 outputLines.push_back(line);
295 }
296
297 return netdutils::status::ok;
298 }
299
300 // Strings in the |expect| must exist in dump results in order. But no need to be consecutive.
301 bool expectDumpsysContains(std::vector<std::string>& expect) {
302 if (expect.empty()) return false;
303
304 std::vector<std::string> output;
305 Status result = dump(true, output);
306 if (!isOk(result)) {
307 GTEST_LOG_(ERROR) << "TrafficController dump failed: " << netdutils::toString(result);
308 return false;
309 }
310
311 int matched = 0;
312 auto it = expect.begin();
313 for (const auto& line : output) {
314 if (it == expect.end()) break;
315 if (std::string::npos != line.find(*it)) {
316 matched++;
317 ++it;
318 }
319 }
Ken Chen0dd74952022-06-06 18:25:18 +0800320
321 if (matched != expect.size()) {
322 // dump results for debugging
323 for (const auto& o : output) LOG(INFO) << "output: " << o;
324 for (const auto& e : expect) LOG(INFO) << "expect: " << e;
325 return false;
326 }
327 return true;
Ken Chen2fb86362022-06-05 11:39:38 +0800328 }
Hungming Chen410bb122022-06-09 01:32:00 +0800329
330 // Once called, the maps of TrafficController can't recover to valid maps which initialized
331 // in SetUp().
332 void makeTrafficControllerMapsInvalid() {
333 constexpr char INVALID_PATH[] = "invalid";
334
335 mFakeCookieTagMap.init(INVALID_PATH);
336 mTc.mCookieTagMap = mFakeCookieTagMap;
337 ASSERT_INVALID(mTc.mCookieTagMap);
338
339 mFakeAppUidStatsMap.init(INVALID_PATH);
340 mTc.mAppUidStatsMap = mFakeAppUidStatsMap;
341 ASSERT_INVALID(mTc.mAppUidStatsMap);
342
343 mFakeStatsMapA.init(INVALID_PATH);
344 mTc.mStatsMapA = mFakeStatsMapA;
345 ASSERT_INVALID(mTc.mStatsMapA);
346
347 mFakeStatsMapB.init(INVALID_PATH);
348 mTc.mStatsMapB = mFakeStatsMapB;
349 ASSERT_INVALID(mTc.mStatsMapB);
350
351 mFakeIfaceStatsMap.init(INVALID_PATH);
352 mTc.mIfaceStatsMap = mFakeIfaceStatsMap;
353 ASSERT_INVALID(mTc.mIfaceStatsMap);
354
355 mFakeConfigurationMap.init(INVALID_PATH);
356 mTc.mConfigurationMap = mFakeConfigurationMap;
357 ASSERT_INVALID(mTc.mConfigurationMap);
358
359 mFakeUidOwnerMap.init(INVALID_PATH);
360 mTc.mUidOwnerMap = mFakeUidOwnerMap;
361 ASSERT_INVALID(mTc.mUidOwnerMap);
362
363 mFakeUidPermissionMap.init(INVALID_PATH);
364 mTc.mUidPermissionMap = mFakeUidPermissionMap;
365 ASSERT_INVALID(mTc.mUidPermissionMap);
366
367 mFakeUidCounterSetMap.init(INVALID_PATH);
368 mTc.mUidCounterSetMap = mFakeUidCounterSetMap;
369 ASSERT_INVALID(mTc.mUidCounterSetMap);
370
371 mFakeIfaceIndexNameMap.init(INVALID_PATH);
372 mTc.mIfaceIndexNameMap = mFakeIfaceIndexNameMap;
373 ASSERT_INVALID(mTc.mIfaceIndexNameMap);
374 }
Wayne Ma4d692332022-01-19 16:04:04 +0800375};
376
Wayne Ma4d692332022-01-19 16:04:04 +0800377TEST_F(TrafficControllerTest, TestUpdateOwnerMapEntry) {
378 uint32_t uid = TEST_UID;
379 ASSERT_TRUE(isOk(mTc.updateOwnerMapEntry(STANDBY_MATCH, uid, DENY, DENYLIST)));
380 Result<UidOwnerValue> value = mFakeUidOwnerMap.readValue(uid);
381 ASSERT_RESULT_OK(value);
382 ASSERT_TRUE(value.value().rule & STANDBY_MATCH);
383
384 ASSERT_TRUE(isOk(mTc.updateOwnerMapEntry(DOZABLE_MATCH, uid, ALLOW, ALLOWLIST)));
385 value = mFakeUidOwnerMap.readValue(uid);
386 ASSERT_RESULT_OK(value);
387 ASSERT_TRUE(value.value().rule & DOZABLE_MATCH);
388
389 ASSERT_TRUE(isOk(mTc.updateOwnerMapEntry(DOZABLE_MATCH, uid, DENY, ALLOWLIST)));
390 value = mFakeUidOwnerMap.readValue(uid);
391 ASSERT_RESULT_OK(value);
392 ASSERT_FALSE(value.value().rule & DOZABLE_MATCH);
393
394 ASSERT_TRUE(isOk(mTc.updateOwnerMapEntry(STANDBY_MATCH, uid, ALLOW, DENYLIST)));
395 ASSERT_FALSE(mFakeUidOwnerMap.readValue(uid).ok());
396
397 uid = TEST_UID2;
398 ASSERT_FALSE(isOk(mTc.updateOwnerMapEntry(STANDBY_MATCH, uid, ALLOW, DENYLIST)));
399 ASSERT_FALSE(mFakeUidOwnerMap.readValue(uid).ok());
400}
401
402TEST_F(TrafficControllerTest, TestChangeUidOwnerRule) {
403 checkUidOwnerRuleForChain(DOZABLE, DOZABLE_MATCH);
404 checkUidOwnerRuleForChain(STANDBY, STANDBY_MATCH);
405 checkUidOwnerRuleForChain(POWERSAVE, POWERSAVE_MATCH);
406 checkUidOwnerRuleForChain(RESTRICTED, RESTRICTED_MATCH);
Robert Horvathd945bf02022-01-27 19:55:16 +0100407 checkUidOwnerRuleForChain(LOW_POWER_STANDBY, LOW_POWER_STANDBY_MATCH);
Motomu Utsumid9801492022-06-01 13:57:27 +0000408 checkUidOwnerRuleForChain(OEM_DENY_1, OEM_DENY_1_MATCH);
409 checkUidOwnerRuleForChain(OEM_DENY_2, OEM_DENY_2_MATCH);
Motomu Utsumi1d9054b2022-06-06 07:44:05 +0000410 checkUidOwnerRuleForChain(OEM_DENY_3, OEM_DENY_3_MATCH);
Wayne Ma4d692332022-01-19 16:04:04 +0800411 ASSERT_EQ(-EINVAL, mTc.changeUidOwnerRule(NONE, TEST_UID, ALLOW, ALLOWLIST));
412 ASSERT_EQ(-EINVAL, mTc.changeUidOwnerRule(INVALID_CHAIN, TEST_UID, ALLOW, ALLOWLIST));
413}
414
415TEST_F(TrafficControllerTest, TestReplaceUidOwnerMap) {
416 std::vector<int32_t> uids = {TEST_UID, TEST_UID2, TEST_UID3};
417 checkUidMapReplace("fw_dozable", uids, DOZABLE_MATCH);
418 checkUidMapReplace("fw_standby", uids, STANDBY_MATCH);
419 checkUidMapReplace("fw_powersave", uids, POWERSAVE_MATCH);
420 checkUidMapReplace("fw_restricted", uids, RESTRICTED_MATCH);
Robert Horvathd945bf02022-01-27 19:55:16 +0100421 checkUidMapReplace("fw_low_power_standby", uids, LOW_POWER_STANDBY_MATCH);
Motomu Utsumid9801492022-06-01 13:57:27 +0000422 checkUidMapReplace("fw_oem_deny_1", uids, OEM_DENY_1_MATCH);
423 checkUidMapReplace("fw_oem_deny_2", uids, OEM_DENY_2_MATCH);
Motomu Utsumi1d9054b2022-06-06 07:44:05 +0000424 checkUidMapReplace("fw_oem_deny_3", uids, OEM_DENY_3_MATCH);
Wayne Ma4d692332022-01-19 16:04:04 +0800425 ASSERT_EQ(-EINVAL, mTc.replaceUidOwnerMap("unknow", true, uids));
426}
427
428TEST_F(TrafficControllerTest, TestReplaceSameChain) {
429 std::vector<int32_t> uids = {TEST_UID, TEST_UID2, TEST_UID3};
430 checkUidMapReplace("fw_dozable", uids, DOZABLE_MATCH);
431 std::vector<int32_t> newUids = {TEST_UID2, TEST_UID3};
432 checkUidMapReplace("fw_dozable", newUids, DOZABLE_MATCH);
433}
434
435TEST_F(TrafficControllerTest, TestDenylistUidMatch) {
436 std::vector<uint32_t> appUids = {1000, 1001, 10012};
Wayne Ma7be6bce2022-01-12 16:29:49 +0800437 ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, PENALTY_BOX_MATCH,
438 TrafficController::IptOpInsert)));
Wayne Ma4d692332022-01-19 16:04:04 +0800439 expectUidOwnerMapValues(appUids, PENALTY_BOX_MATCH, 0);
Wayne Ma7be6bce2022-01-12 16:29:49 +0800440 ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, PENALTY_BOX_MATCH,
441 TrafficController::IptOpDelete)));
Wayne Ma4d692332022-01-19 16:04:04 +0800442 expectMapEmpty(mFakeUidOwnerMap);
443}
444
445TEST_F(TrafficControllerTest, TestAllowlistUidMatch) {
446 std::vector<uint32_t> appUids = {1000, 1001, 10012};
Wayne Ma7be6bce2022-01-12 16:29:49 +0800447 ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, HAPPY_BOX_MATCH, TrafficController::IptOpInsert)));
Wayne Ma4d692332022-01-19 16:04:04 +0800448 expectUidOwnerMapValues(appUids, HAPPY_BOX_MATCH, 0);
Wayne Ma7be6bce2022-01-12 16:29:49 +0800449 ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, HAPPY_BOX_MATCH, TrafficController::IptOpDelete)));
Wayne Ma4d692332022-01-19 16:04:04 +0800450 expectMapEmpty(mFakeUidOwnerMap);
451}
452
453TEST_F(TrafficControllerTest, TestReplaceMatchUid) {
454 std::vector<uint32_t> appUids = {1000, 1001, 10012};
455 // Add appUids to the denylist and expect that their values are all PENALTY_BOX_MATCH.
Wayne Ma7be6bce2022-01-12 16:29:49 +0800456 ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, PENALTY_BOX_MATCH,
457 TrafficController::IptOpInsert)));
Wayne Ma4d692332022-01-19 16:04:04 +0800458 expectUidOwnerMapValues(appUids, PENALTY_BOX_MATCH, 0);
459
460 // Add the same UIDs to the allowlist and expect that we get PENALTY_BOX_MATCH |
461 // HAPPY_BOX_MATCH.
Wayne Ma7be6bce2022-01-12 16:29:49 +0800462 ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, HAPPY_BOX_MATCH, TrafficController::IptOpInsert)));
Wayne Ma4d692332022-01-19 16:04:04 +0800463 expectUidOwnerMapValues(appUids, HAPPY_BOX_MATCH | PENALTY_BOX_MATCH, 0);
464
465 // Remove the same UIDs from the allowlist and check the PENALTY_BOX_MATCH is still there.
Wayne Ma7be6bce2022-01-12 16:29:49 +0800466 ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, HAPPY_BOX_MATCH, TrafficController::IptOpDelete)));
Wayne Ma4d692332022-01-19 16:04:04 +0800467 expectUidOwnerMapValues(appUids, PENALTY_BOX_MATCH, 0);
468
469 // Remove the same UIDs from the denylist and check the map is empty.
Wayne Ma7be6bce2022-01-12 16:29:49 +0800470 ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, PENALTY_BOX_MATCH,
471 TrafficController::IptOpDelete)));
Wayne Ma4d692332022-01-19 16:04:04 +0800472 ASSERT_FALSE(mFakeUidOwnerMap.getFirstKey().ok());
473}
474
475TEST_F(TrafficControllerTest, TestDeleteWrongMatchSilentlyFails) {
476 std::vector<uint32_t> appUids = {1000, 1001, 10012};
477 // 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 +0800478 ASSERT_FALSE(isOk(updateUidOwnerMaps(appUids, HAPPY_BOX_MATCH,
479 TrafficController::IptOpDelete)));
Wayne Ma4d692332022-01-19 16:04:04 +0800480 expectMapEmpty(mFakeUidOwnerMap);
481
482 // Add denylist rules for appUids.
Wayne Ma7be6bce2022-01-12 16:29:49 +0800483 ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, HAPPY_BOX_MATCH,
484 TrafficController::IptOpInsert)));
Wayne Ma4d692332022-01-19 16:04:04 +0800485 expectUidOwnerMapValues(appUids, HAPPY_BOX_MATCH, 0);
486
487 // Delete (non-existent) denylist rules for appUids, and check that this silently does
488 // nothing if the uid is in the map but does not have denylist match. This is required because
489 // NetworkManagementService will try to remove a uid from denylist after adding it to the
490 // allowlist and if the remove fails it will not update the uid status.
Wayne Ma7be6bce2022-01-12 16:29:49 +0800491 ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, PENALTY_BOX_MATCH,
492 TrafficController::IptOpDelete)));
Wayne Ma4d692332022-01-19 16:04:04 +0800493 expectUidOwnerMapValues(appUids, HAPPY_BOX_MATCH, 0);
494}
495
496TEST_F(TrafficControllerTest, TestAddUidInterfaceFilteringRules) {
497 int iif0 = 15;
498 ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif0, {1000, 1001})));
499 expectUidOwnerMapValues({1000, 1001}, IIF_MATCH, iif0);
500
501 // Add some non-overlapping new uids. They should coexist with existing rules
502 int iif1 = 16;
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 // Overwrite some existing uids
508 int iif2 = 17;
509 ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif2, {1000, 2000})));
510 expectUidOwnerMapValues({1001}, IIF_MATCH, iif0);
511 expectUidOwnerMapValues({2001}, IIF_MATCH, iif1);
512 expectUidOwnerMapValues({1000, 2000}, IIF_MATCH, iif2);
513}
514
515TEST_F(TrafficControllerTest, TestRemoveUidInterfaceFilteringRules) {
516 int iif0 = 15;
517 int iif1 = 16;
518 ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif0, {1000, 1001})));
519 ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif1, {2000, 2001})));
520 expectUidOwnerMapValues({1000, 1001}, IIF_MATCH, iif0);
521 expectUidOwnerMapValues({2000, 2001}, IIF_MATCH, iif1);
522
523 // Rmove some uids
524 ASSERT_TRUE(isOk(mTc.removeUidInterfaceRules({1001, 2001})));
525 expectUidOwnerMapValues({1000}, IIF_MATCH, iif0);
526 expectUidOwnerMapValues({2000}, IIF_MATCH, iif1);
527 checkEachUidValue({1000, 2000}, IIF_MATCH); // Make sure there are only two uids remaining
528
529 // Remove non-existent uids shouldn't fail
530 ASSERT_TRUE(isOk(mTc.removeUidInterfaceRules({2000, 3000})));
531 expectUidOwnerMapValues({1000}, IIF_MATCH, iif0);
532 checkEachUidValue({1000}, IIF_MATCH); // Make sure there are only one uid remaining
533
534 // Remove everything
535 ASSERT_TRUE(isOk(mTc.removeUidInterfaceRules({1000})));
536 expectMapEmpty(mFakeUidOwnerMap);
537}
538
Motomu Utsumi8b42e6d2022-05-19 06:23:40 +0000539TEST_F(TrafficControllerTest, TestUpdateUidLockdownRule) {
540 // Add Lockdown rules
541 ASSERT_TRUE(isOk(mTc.updateUidLockdownRule(1000, true /* add */)));
542 ASSERT_TRUE(isOk(mTc.updateUidLockdownRule(1001, true /* add */)));
543 expectUidOwnerMapValues({1000, 1001}, LOCKDOWN_VPN_MATCH, 0);
544
545 // Remove one of Lockdown rules
546 ASSERT_TRUE(isOk(mTc.updateUidLockdownRule(1000, false /* add */)));
547 expectUidOwnerMapValues({1001}, LOCKDOWN_VPN_MATCH, 0);
548
549 // Remove remaining Lockdown rule
550 ASSERT_TRUE(isOk(mTc.updateUidLockdownRule(1001, false /* add */)));
551 expectMapEmpty(mFakeUidOwnerMap);
552}
553
Wayne Ma4d692332022-01-19 16:04:04 +0800554TEST_F(TrafficControllerTest, TestUidInterfaceFilteringRulesCoexistWithExistingMatches) {
555 // Set up existing PENALTY_BOX_MATCH rules
Wayne Ma7be6bce2022-01-12 16:29:49 +0800556 ASSERT_TRUE(isOk(updateUidOwnerMaps({1000, 1001, 10012}, PENALTY_BOX_MATCH,
557 TrafficController::IptOpInsert)));
Wayne Ma4d692332022-01-19 16:04:04 +0800558 expectUidOwnerMapValues({1000, 1001, 10012}, PENALTY_BOX_MATCH, 0);
559
560 // Add some partially-overlapping uid owner rules and check result
561 int iif1 = 32;
562 ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif1, {10012, 10013, 10014})));
563 expectUidOwnerMapValues({1000, 1001}, PENALTY_BOX_MATCH, 0);
564 expectUidOwnerMapValues({10012}, PENALTY_BOX_MATCH | IIF_MATCH, iif1);
565 expectUidOwnerMapValues({10013, 10014}, IIF_MATCH, iif1);
566
567 // Removing some PENALTY_BOX_MATCH rules should not change uid interface rule
Wayne Ma7be6bce2022-01-12 16:29:49 +0800568 ASSERT_TRUE(isOk(updateUidOwnerMaps({1001, 10012}, PENALTY_BOX_MATCH,
569 TrafficController::IptOpDelete)));
Wayne Ma4d692332022-01-19 16:04:04 +0800570 expectUidOwnerMapValues({1000}, PENALTY_BOX_MATCH, 0);
571 expectUidOwnerMapValues({10012, 10013, 10014}, IIF_MATCH, iif1);
572
573 // Remove all uid interface rules
574 ASSERT_TRUE(isOk(mTc.removeUidInterfaceRules({10012, 10013, 10014})));
575 expectUidOwnerMapValues({1000}, PENALTY_BOX_MATCH, 0);
576 // Make sure these are the only uids left
577 checkEachUidValue({1000}, PENALTY_BOX_MATCH);
578}
579
580TEST_F(TrafficControllerTest, TestUidInterfaceFilteringRulesCoexistWithNewMatches) {
581 int iif1 = 56;
582 // Set up existing uid interface rules
583 ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif1, {10001, 10002})));
584 expectUidOwnerMapValues({10001, 10002}, IIF_MATCH, iif1);
585
586 // Add some partially-overlapping doze rules
587 EXPECT_EQ(0, mTc.replaceUidOwnerMap("fw_dozable", true, {10002, 10003}));
588 expectUidOwnerMapValues({10001}, IIF_MATCH, iif1);
589 expectUidOwnerMapValues({10002}, DOZABLE_MATCH | IIF_MATCH, iif1);
590 expectUidOwnerMapValues({10003}, DOZABLE_MATCH, 0);
591
592 // Introduce a third rule type (powersave) on various existing UIDs
593 EXPECT_EQ(0, mTc.replaceUidOwnerMap("fw_powersave", true, {10000, 10001, 10002, 10003}));
594 expectUidOwnerMapValues({10000}, POWERSAVE_MATCH, 0);
595 expectUidOwnerMapValues({10001}, POWERSAVE_MATCH | IIF_MATCH, iif1);
596 expectUidOwnerMapValues({10002}, POWERSAVE_MATCH | DOZABLE_MATCH | IIF_MATCH, iif1);
597 expectUidOwnerMapValues({10003}, POWERSAVE_MATCH | DOZABLE_MATCH, 0);
598
599 // Remove all doze rules
600 EXPECT_EQ(0, mTc.replaceUidOwnerMap("fw_dozable", true, {}));
601 expectUidOwnerMapValues({10000}, POWERSAVE_MATCH, 0);
602 expectUidOwnerMapValues({10001}, POWERSAVE_MATCH | IIF_MATCH, iif1);
603 expectUidOwnerMapValues({10002}, POWERSAVE_MATCH | IIF_MATCH, iif1);
604 expectUidOwnerMapValues({10003}, POWERSAVE_MATCH, 0);
605
606 // Remove all powersave rules, expect ownerMap to only have uid interface rules left
607 EXPECT_EQ(0, mTc.replaceUidOwnerMap("fw_powersave", true, {}));
608 expectUidOwnerMapValues({10001, 10002}, IIF_MATCH, iif1);
609 // Make sure these are the only uids left
610 checkEachUidValue({10001, 10002}, IIF_MATCH);
611}
612
Motomu Utsumib08654c2022-05-11 05:56:26 +0000613TEST_F(TrafficControllerTest, TestAddUidInterfaceFilteringRulesWithWildcard) {
614 // iif=0 is a wildcard
615 int iif = 0;
616 // Add interface rule with wildcard to uids
617 ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif, {1000, 1001})));
618 expectUidOwnerMapValues({1000, 1001}, IIF_MATCH, iif);
619}
620
621TEST_F(TrafficControllerTest, TestRemoveUidInterfaceFilteringRulesWithWildcard) {
622 // iif=0 is a wildcard
623 int iif = 0;
624 // Add interface rule with wildcard to two uids
625 ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif, {1000, 1001})));
626 expectUidOwnerMapValues({1000, 1001}, IIF_MATCH, iif);
627
628 // Remove interface rule from one of the uids
629 ASSERT_TRUE(isOk(mTc.removeUidInterfaceRules({1000})));
630 expectUidOwnerMapValues({1001}, IIF_MATCH, iif);
631 checkEachUidValue({1001}, IIF_MATCH);
632
633 // Remove interface rule from the remaining uid
634 ASSERT_TRUE(isOk(mTc.removeUidInterfaceRules({1001})));
635 expectMapEmpty(mFakeUidOwnerMap);
636}
637
638TEST_F(TrafficControllerTest, TestUidInterfaceFilteringRulesWithWildcardAndExistingMatches) {
639 // Set up existing DOZABLE_MATCH and POWERSAVE_MATCH rule
640 ASSERT_TRUE(isOk(updateUidOwnerMaps({1000}, DOZABLE_MATCH,
641 TrafficController::IptOpInsert)));
642 ASSERT_TRUE(isOk(updateUidOwnerMaps({1000}, POWERSAVE_MATCH,
643 TrafficController::IptOpInsert)));
644
645 // iif=0 is a wildcard
646 int iif = 0;
647 // Add interface rule with wildcard to the existing uid
648 ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif, {1000})));
649 expectUidOwnerMapValues({1000}, POWERSAVE_MATCH | DOZABLE_MATCH | IIF_MATCH, iif);
650
651 // Remove interface rule with wildcard from the existing uid
652 ASSERT_TRUE(isOk(mTc.removeUidInterfaceRules({1000})));
653 expectUidOwnerMapValues({1000}, POWERSAVE_MATCH | DOZABLE_MATCH, 0);
654}
655
656TEST_F(TrafficControllerTest, TestUidInterfaceFilteringRulesWithWildcardAndNewMatches) {
657 // iif=0 is a wildcard
658 int iif = 0;
659 // Set up existing interface rule with wildcard
660 ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif, {1000})));
661
662 // Add DOZABLE_MATCH and POWERSAVE_MATCH rule to the existing uid
663 ASSERT_TRUE(isOk(updateUidOwnerMaps({1000}, DOZABLE_MATCH,
664 TrafficController::IptOpInsert)));
665 ASSERT_TRUE(isOk(updateUidOwnerMaps({1000}, POWERSAVE_MATCH,
666 TrafficController::IptOpInsert)));
667 expectUidOwnerMapValues({1000}, POWERSAVE_MATCH | DOZABLE_MATCH | IIF_MATCH, iif);
668
669 // Remove DOZABLE_MATCH and POWERSAVE_MATCH rule from the existing uid
670 ASSERT_TRUE(isOk(updateUidOwnerMaps({1000}, DOZABLE_MATCH,
671 TrafficController::IptOpDelete)));
672 ASSERT_TRUE(isOk(updateUidOwnerMaps({1000}, POWERSAVE_MATCH,
673 TrafficController::IptOpDelete)));
674 expectUidOwnerMapValues({1000}, IIF_MATCH, iif);
675}
676
Wayne Ma4d692332022-01-19 16:04:04 +0800677TEST_F(TrafficControllerTest, TestGrantInternetPermission) {
678 std::vector<uid_t> appUids = {TEST_UID, TEST_UID2, TEST_UID3};
679
680 mTc.setPermissionForUids(INetd::PERMISSION_INTERNET, appUids);
681 expectMapEmpty(mFakeUidPermissionMap);
682 expectPrivilegedUserSetEmpty();
683}
684
685TEST_F(TrafficControllerTest, TestRevokeInternetPermission) {
686 std::vector<uid_t> appUids = {TEST_UID, TEST_UID2, TEST_UID3};
687
688 mTc.setPermissionForUids(INetd::PERMISSION_NONE, appUids);
689 expectUidPermissionMapValues(appUids, INetd::PERMISSION_NONE);
690}
691
692TEST_F(TrafficControllerTest, TestPermissionUninstalled) {
693 std::vector<uid_t> appUids = {TEST_UID, TEST_UID2, TEST_UID3};
694
695 mTc.setPermissionForUids(INetd::PERMISSION_UPDATE_DEVICE_STATS, appUids);
696 expectUidPermissionMapValues(appUids, INetd::PERMISSION_UPDATE_DEVICE_STATS);
697 expectPrivilegedUserSet(appUids);
698
699 std::vector<uid_t> uidToRemove = {TEST_UID};
700 mTc.setPermissionForUids(INetd::PERMISSION_UNINSTALLED, uidToRemove);
701
702 std::vector<uid_t> uidRemain = {TEST_UID3, TEST_UID2};
703 expectUidPermissionMapValues(uidRemain, INetd::PERMISSION_UPDATE_DEVICE_STATS);
704 expectPrivilegedUserSet(uidRemain);
705
706 mTc.setPermissionForUids(INetd::PERMISSION_UNINSTALLED, uidRemain);
707 expectMapEmpty(mFakeUidPermissionMap);
708 expectPrivilegedUserSetEmpty();
709}
710
711TEST_F(TrafficControllerTest, TestGrantUpdateStatsPermission) {
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 mTc.setPermissionForUids(INetd::PERMISSION_NONE, appUids);
719 expectPrivilegedUserSetEmpty();
720 expectUidPermissionMapValues(appUids, INetd::PERMISSION_NONE);
721}
722
723TEST_F(TrafficControllerTest, TestRevokeUpdateStatsPermission) {
724 std::vector<uid_t> appUids = {TEST_UID, TEST_UID2, TEST_UID3};
725
726 mTc.setPermissionForUids(INetd::PERMISSION_UPDATE_DEVICE_STATS, appUids);
727 expectPrivilegedUserSet(appUids);
728
729 std::vector<uid_t> uidToRemove = {TEST_UID};
730 mTc.setPermissionForUids(INetd::PERMISSION_NONE, uidToRemove);
731
732 std::vector<uid_t> uidRemain = {TEST_UID3, TEST_UID2};
733 expectPrivilegedUserSet(uidRemain);
734
735 mTc.setPermissionForUids(INetd::PERMISSION_NONE, uidRemain);
736 expectPrivilegedUserSetEmpty();
737}
738
739TEST_F(TrafficControllerTest, TestGrantWrongPermission) {
740 std::vector<uid_t> appUids = {TEST_UID, TEST_UID2, TEST_UID3};
741
742 mTc.setPermissionForUids(INetd::PERMISSION_NONE, appUids);
743 expectPrivilegedUserSetEmpty();
744 expectUidPermissionMapValues(appUids, INetd::PERMISSION_NONE);
745}
746
747TEST_F(TrafficControllerTest, TestGrantDuplicatePermissionSlientlyFail) {
748 std::vector<uid_t> appUids = {TEST_UID, TEST_UID2, TEST_UID3};
749
750 mTc.setPermissionForUids(INetd::PERMISSION_INTERNET, appUids);
751 expectMapEmpty(mFakeUidPermissionMap);
752
753 std::vector<uid_t> uidToAdd = {TEST_UID};
754 mTc.setPermissionForUids(INetd::PERMISSION_INTERNET, uidToAdd);
755
756 expectPrivilegedUserSetEmpty();
757
758 mTc.setPermissionForUids(INetd::PERMISSION_NONE, appUids);
759 expectUidPermissionMapValues(appUids, INetd::PERMISSION_NONE);
760
761 mTc.setPermissionForUids(INetd::PERMISSION_UPDATE_DEVICE_STATS, appUids);
762 expectPrivilegedUserSet(appUids);
763
764 mTc.setPermissionForUids(INetd::PERMISSION_UPDATE_DEVICE_STATS, uidToAdd);
765 expectPrivilegedUserSet(appUids);
766
767 mTc.setPermissionForUids(INetd::PERMISSION_NONE, appUids);
768 expectPrivilegedUserSetEmpty();
769}
770
Ken Chen77a6b712022-06-06 12:46:36 +0800771TEST_F(TrafficControllerTest, getFirewallType) {
772 static const struct TestConfig {
773 ChildChain childChain;
774 FirewallType firewallType;
775 } testConfigs[] = {
776 // clang-format off
777 {NONE, DENYLIST},
778 {DOZABLE, ALLOWLIST},
779 {STANDBY, DENYLIST},
780 {POWERSAVE, ALLOWLIST},
781 {RESTRICTED, ALLOWLIST},
782 {LOW_POWER_STANDBY, ALLOWLIST},
Ken Chen77a6b712022-06-06 12:46:36 +0800783 {OEM_DENY_1, DENYLIST},
784 {OEM_DENY_2, DENYLIST},
Ken Chend3a3af52022-06-08 02:54:09 +0000785 {OEM_DENY_3, DENYLIST},
Ken Chen77a6b712022-06-06 12:46:36 +0800786 {INVALID_CHAIN, DENYLIST},
787 // clang-format on
788 };
789
790 for (const auto& config : testConfigs) {
791 SCOPED_TRACE(fmt::format("testConfig: [{}, {}]", config.childChain, config.firewallType));
792 EXPECT_EQ(config.firewallType, mTc.getFirewallType(config.childChain));
793 }
794}
795
Patrick Rohr61e94672022-02-01 21:06:40 +0100796constexpr uint32_t SOCK_CLOSE_WAIT_US = 30 * 1000;
797constexpr uint32_t ENOBUFS_POLL_WAIT_US = 10 * 1000;
798
799using android::base::Error;
800using android::base::Result;
801using android::bpf::BpfMap;
802
803// This test set up a SkDestroyListener that is running parallel with the production
804// SkDestroyListener. The test will create thousands of sockets and tag them on the
805// production cookieUidTagMap and close them in a short time. When the number of
806// sockets get closed exceeds the buffer size, it will start to return ENOBUFF
807// error. The error will be ignored by the production SkDestroyListener and the
808// test will clean up the tags in tearDown if there is any remains.
809
810// TODO: Instead of test the ENOBUFF error, we can test the production
811// SkDestroyListener to see if it failed to delete a tagged socket when ENOBUFF
812// triggered.
813class NetlinkListenerTest : public testing::Test {
814 protected:
815 NetlinkListenerTest() {}
816 BpfMap<uint64_t, UidTagValue> mCookieTagMap;
817
818 void SetUp() {
Maciej Żenczykowskiced35312022-05-31 05:11:12 -0700819 mCookieTagMap.init(COOKIE_TAG_MAP_PATH);
Patrick Rohr61e94672022-02-01 21:06:40 +0100820 ASSERT_TRUE(mCookieTagMap.isValid());
821 }
822
823 void TearDown() {
824 const auto deleteTestCookieEntries = [](const uint64_t& key, const UidTagValue& value,
825 BpfMap<uint64_t, UidTagValue>& map) {
826 if ((value.uid == TEST_UID) && (value.tag == TEST_TAG)) {
827 Result<void> res = map.deleteValue(key);
828 if (res.ok() || (res.error().code() == ENOENT)) {
829 return Result<void>();
830 }
Maciej Żenczykowskie0f58462022-05-17 13:59:22 -0700831 ALOGE("Failed to delete data(cookie = %" PRIu64 "): %s", key,
Patrick Rohr61e94672022-02-01 21:06:40 +0100832 strerror(res.error().code()));
833 }
834 // Move forward to next cookie in the map.
835 return Result<void>();
836 };
837 EXPECT_RESULT_OK(mCookieTagMap.iterateWithValue(deleteTestCookieEntries));
838 }
839
840 Result<void> checkNoGarbageTagsExist() {
841 const auto checkGarbageTags = [](const uint64_t&, const UidTagValue& value,
842 const BpfMap<uint64_t, UidTagValue>&) -> Result<void> {
843 if ((TEST_UID == value.uid) && (TEST_TAG == value.tag)) {
844 return Error(EUCLEAN) << "Closed socket is not untagged";
845 }
846 return {};
847 };
848 return mCookieTagMap.iterateWithValue(checkGarbageTags);
849 }
850
851 bool checkMassiveSocketDestroy(int totalNumber, bool expectError) {
852 std::unique_ptr<android::netdutils::NetlinkListenerInterface> skDestroyListener;
853 auto result = android::net::TrafficController::makeSkDestroyListener();
854 if (!isOk(result)) {
855 ALOGE("Unable to create SkDestroyListener: %s", toString(result).c_str());
856 } else {
857 skDestroyListener = std::move(result.value());
858 }
859 int rxErrorCount = 0;
860 // Rx handler extracts nfgenmsg looks up and invokes registered dispatch function.
861 const auto rxErrorHandler = [&rxErrorCount](const int, const int) { rxErrorCount++; };
862 skDestroyListener->registerSkErrorHandler(rxErrorHandler);
863 int fds[totalNumber];
864 for (int i = 0; i < totalNumber; i++) {
865 fds[i] = socket(AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0);
866 // The likely reason for a failure is running out of available file descriptors.
867 EXPECT_LE(0, fds[i]) << i << " of " << totalNumber;
868 if (fds[i] < 0) {
869 // EXPECT_LE already failed above, so test case is a failure, but we don't
870 // want potentially tens of thousands of extra failures creating and then
871 // closing all these fds cluttering up the logs.
872 totalNumber = i;
873 break;
874 };
875 libnetd_updatable_tagSocket(fds[i], TEST_TAG, TEST_UID, 1000);
876 }
877
878 // TODO: Use a separate thread that has its own fd table so we can
879 // close sockets even faster simply by terminating that thread.
880 for (int i = 0; i < totalNumber; i++) {
881 EXPECT_EQ(0, close(fds[i]));
882 }
883 // wait a bit for netlink listener to handle all the messages.
884 usleep(SOCK_CLOSE_WAIT_US);
885 if (expectError) {
886 // If ENOBUFS triggered, check it only called into the handler once, ie.
887 // that the netlink handler is not spinning.
888 int currentErrorCount = rxErrorCount;
889 // 0 error count is acceptable because the system has chances to close all sockets
890 // normally.
891 EXPECT_LE(0, rxErrorCount);
892 if (!rxErrorCount) return true;
893
894 usleep(ENOBUFS_POLL_WAIT_US);
895 EXPECT_EQ(currentErrorCount, rxErrorCount);
896 } else {
897 EXPECT_RESULT_OK(checkNoGarbageTagsExist());
898 EXPECT_EQ(0, rxErrorCount);
899 }
900 return false;
901 }
902};
903
904TEST_F(NetlinkListenerTest, TestAllSocketUntagged) {
905 checkMassiveSocketDestroy(10, false);
906 checkMassiveSocketDestroy(100, false);
907}
908
909// Disabled because flaky on blueline-userdebug; this test relies on the main thread
910// winning a race against the NetlinkListener::run() thread. There's no way to ensure
911// things will be scheduled the same way across all architectures and test environments.
912TEST_F(NetlinkListenerTest, DISABLED_TestSkDestroyError) {
913 bool needRetry = false;
914 int retryCount = 0;
915 do {
916 needRetry = checkMassiveSocketDestroy(32500, true);
917 if (needRetry) retryCount++;
918 } while (needRetry && retryCount < 3);
919 // Should review test if it can always close all sockets correctly.
920 EXPECT_GT(3, retryCount);
921}
922
923
Wayne Ma4d692332022-01-19 16:04:04 +0800924} // namespace net
925} // namespace android