blob: f84a910e2712168b1156383d9ad74e16b1e1a63d [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_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
Wayne Ma7be6bce2022-01-12 16:29:49 +0800265 Status updateUidOwnerMaps(const std::vector<uint32_t>& appUids,
266 UidOwnerMatchType matchType, TrafficController::IptOp op) {
267 Status ret(0);
268 for (auto uid : appUids) {
269 ret = mTc.updateUidOwnerMap(uid, matchType, op);
270 if(!isOk(ret)) break;
271 }
272 return ret;
273 }
274
Ken Chen2fb86362022-06-05 11:39:38 +0800275 Status dump(bool verbose, std::vector<std::string>& outputLines) {
276 if (!outputLines.empty()) return statusFromErrno(EUCLEAN, "Output buffer is not empty");
277
278 android::base::unique_fd localFd, remoteFd;
279 if (!Pipe(&localFd, &remoteFd)) return statusFromErrno(errno, "Failed on pipe");
280
281 // dump() blocks until another thread has consumed all its output.
282 std::thread dumpThread =
283 std::thread([this, remoteFd{std::move(remoteFd)}, verbose]() {
284 mTc.dump(remoteFd, verbose);
285 });
286
287 std::string dumpContent;
288 if (!android::base::ReadFdToString(localFd.get(), &dumpContent)) {
289 return statusFromErrno(errno, "Failed to read dump results from fd");
290 }
291 dumpThread.join();
292
293 std::stringstream dumpStream(std::move(dumpContent));
294 std::string line;
295 while (std::getline(dumpStream, line)) {
296 outputLines.push_back(line);
297 }
298
299 return netdutils::status::ok;
300 }
301
302 // Strings in the |expect| must exist in dump results in order. But no need to be consecutive.
303 bool expectDumpsysContains(std::vector<std::string>& expect) {
304 if (expect.empty()) return false;
305
306 std::vector<std::string> output;
307 Status result = dump(true, output);
308 if (!isOk(result)) {
309 GTEST_LOG_(ERROR) << "TrafficController dump failed: " << netdutils::toString(result);
310 return false;
311 }
312
313 int matched = 0;
314 auto it = expect.begin();
315 for (const auto& line : output) {
316 if (it == expect.end()) break;
317 if (std::string::npos != line.find(*it)) {
318 matched++;
319 ++it;
320 }
321 }
Ken Chen0dd74952022-06-06 18:25:18 +0800322
323 if (matched != expect.size()) {
324 // dump results for debugging
325 for (const auto& o : output) LOG(INFO) << "output: " << o;
326 for (const auto& e : expect) LOG(INFO) << "expect: " << e;
327 return false;
328 }
329 return true;
Ken Chen2fb86362022-06-05 11:39:38 +0800330 }
Hungming Chen410bb122022-06-09 01:32:00 +0800331
332 // Once called, the maps of TrafficController can't recover to valid maps which initialized
333 // in SetUp().
334 void makeTrafficControllerMapsInvalid() {
335 constexpr char INVALID_PATH[] = "invalid";
336
337 mFakeCookieTagMap.init(INVALID_PATH);
338 mTc.mCookieTagMap = mFakeCookieTagMap;
339 ASSERT_INVALID(mTc.mCookieTagMap);
340
341 mFakeAppUidStatsMap.init(INVALID_PATH);
342 mTc.mAppUidStatsMap = mFakeAppUidStatsMap;
343 ASSERT_INVALID(mTc.mAppUidStatsMap);
344
345 mFakeStatsMapA.init(INVALID_PATH);
346 mTc.mStatsMapA = mFakeStatsMapA;
347 ASSERT_INVALID(mTc.mStatsMapA);
348
349 mFakeStatsMapB.init(INVALID_PATH);
350 mTc.mStatsMapB = mFakeStatsMapB;
351 ASSERT_INVALID(mTc.mStatsMapB);
352
353 mFakeIfaceStatsMap.init(INVALID_PATH);
354 mTc.mIfaceStatsMap = mFakeIfaceStatsMap;
355 ASSERT_INVALID(mTc.mIfaceStatsMap);
356
357 mFakeConfigurationMap.init(INVALID_PATH);
358 mTc.mConfigurationMap = mFakeConfigurationMap;
359 ASSERT_INVALID(mTc.mConfigurationMap);
360
361 mFakeUidOwnerMap.init(INVALID_PATH);
362 mTc.mUidOwnerMap = mFakeUidOwnerMap;
363 ASSERT_INVALID(mTc.mUidOwnerMap);
364
365 mFakeUidPermissionMap.init(INVALID_PATH);
366 mTc.mUidPermissionMap = mFakeUidPermissionMap;
367 ASSERT_INVALID(mTc.mUidPermissionMap);
368
369 mFakeUidCounterSetMap.init(INVALID_PATH);
370 mTc.mUidCounterSetMap = mFakeUidCounterSetMap;
371 ASSERT_INVALID(mTc.mUidCounterSetMap);
372
373 mFakeIfaceIndexNameMap.init(INVALID_PATH);
374 mTc.mIfaceIndexNameMap = mFakeIfaceIndexNameMap;
375 ASSERT_INVALID(mTc.mIfaceIndexNameMap);
376 }
Wayne Ma4d692332022-01-19 16:04:04 +0800377};
378
Wayne Ma4d692332022-01-19 16:04:04 +0800379TEST_F(TrafficControllerTest, TestUpdateOwnerMapEntry) {
380 uint32_t uid = TEST_UID;
381 ASSERT_TRUE(isOk(mTc.updateOwnerMapEntry(STANDBY_MATCH, uid, DENY, DENYLIST)));
382 Result<UidOwnerValue> value = mFakeUidOwnerMap.readValue(uid);
383 ASSERT_RESULT_OK(value);
384 ASSERT_TRUE(value.value().rule & STANDBY_MATCH);
385
386 ASSERT_TRUE(isOk(mTc.updateOwnerMapEntry(DOZABLE_MATCH, uid, ALLOW, ALLOWLIST)));
387 value = mFakeUidOwnerMap.readValue(uid);
388 ASSERT_RESULT_OK(value);
389 ASSERT_TRUE(value.value().rule & DOZABLE_MATCH);
390
391 ASSERT_TRUE(isOk(mTc.updateOwnerMapEntry(DOZABLE_MATCH, uid, DENY, ALLOWLIST)));
392 value = mFakeUidOwnerMap.readValue(uid);
393 ASSERT_RESULT_OK(value);
394 ASSERT_FALSE(value.value().rule & DOZABLE_MATCH);
395
396 ASSERT_TRUE(isOk(mTc.updateOwnerMapEntry(STANDBY_MATCH, uid, ALLOW, DENYLIST)));
397 ASSERT_FALSE(mFakeUidOwnerMap.readValue(uid).ok());
398
399 uid = TEST_UID2;
400 ASSERT_FALSE(isOk(mTc.updateOwnerMapEntry(STANDBY_MATCH, uid, ALLOW, DENYLIST)));
401 ASSERT_FALSE(mFakeUidOwnerMap.readValue(uid).ok());
402}
403
404TEST_F(TrafficControllerTest, TestChangeUidOwnerRule) {
405 checkUidOwnerRuleForChain(DOZABLE, DOZABLE_MATCH);
406 checkUidOwnerRuleForChain(STANDBY, STANDBY_MATCH);
407 checkUidOwnerRuleForChain(POWERSAVE, POWERSAVE_MATCH);
408 checkUidOwnerRuleForChain(RESTRICTED, RESTRICTED_MATCH);
Robert Horvathd945bf02022-01-27 19:55:16 +0100409 checkUidOwnerRuleForChain(LOW_POWER_STANDBY, LOW_POWER_STANDBY_MATCH);
Motomu Utsumib08654c2022-05-11 05:56:26 +0000410 checkUidOwnerRuleForChain(LOCKDOWN, LOCKDOWN_VPN_MATCH);
Motomu Utsumid9801492022-06-01 13:57:27 +0000411 checkUidOwnerRuleForChain(OEM_DENY_1, OEM_DENY_1_MATCH);
412 checkUidOwnerRuleForChain(OEM_DENY_2, OEM_DENY_2_MATCH);
Motomu Utsumi1d9054b2022-06-06 07:44:05 +0000413 checkUidOwnerRuleForChain(OEM_DENY_3, OEM_DENY_3_MATCH);
Wayne Ma4d692332022-01-19 16:04:04 +0800414 ASSERT_EQ(-EINVAL, mTc.changeUidOwnerRule(NONE, TEST_UID, ALLOW, ALLOWLIST));
415 ASSERT_EQ(-EINVAL, mTc.changeUidOwnerRule(INVALID_CHAIN, TEST_UID, ALLOW, ALLOWLIST));
416}
417
418TEST_F(TrafficControllerTest, TestReplaceUidOwnerMap) {
419 std::vector<int32_t> uids = {TEST_UID, TEST_UID2, TEST_UID3};
420 checkUidMapReplace("fw_dozable", uids, DOZABLE_MATCH);
421 checkUidMapReplace("fw_standby", uids, STANDBY_MATCH);
422 checkUidMapReplace("fw_powersave", uids, POWERSAVE_MATCH);
423 checkUidMapReplace("fw_restricted", uids, RESTRICTED_MATCH);
Robert Horvathd945bf02022-01-27 19:55:16 +0100424 checkUidMapReplace("fw_low_power_standby", uids, LOW_POWER_STANDBY_MATCH);
Motomu Utsumid9801492022-06-01 13:57:27 +0000425 checkUidMapReplace("fw_oem_deny_1", uids, OEM_DENY_1_MATCH);
426 checkUidMapReplace("fw_oem_deny_2", uids, OEM_DENY_2_MATCH);
Motomu Utsumi1d9054b2022-06-06 07:44:05 +0000427 checkUidMapReplace("fw_oem_deny_3", uids, OEM_DENY_3_MATCH);
Wayne Ma4d692332022-01-19 16:04:04 +0800428 ASSERT_EQ(-EINVAL, mTc.replaceUidOwnerMap("unknow", true, uids));
429}
430
431TEST_F(TrafficControllerTest, TestReplaceSameChain) {
432 std::vector<int32_t> uids = {TEST_UID, TEST_UID2, TEST_UID3};
433 checkUidMapReplace("fw_dozable", uids, DOZABLE_MATCH);
434 std::vector<int32_t> newUids = {TEST_UID2, TEST_UID3};
435 checkUidMapReplace("fw_dozable", newUids, DOZABLE_MATCH);
436}
437
438TEST_F(TrafficControllerTest, TestDenylistUidMatch) {
439 std::vector<uint32_t> appUids = {1000, 1001, 10012};
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);
Wayne Ma7be6bce2022-01-12 16:29:49 +0800443 ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, PENALTY_BOX_MATCH,
444 TrafficController::IptOpDelete)));
Wayne Ma4d692332022-01-19 16:04:04 +0800445 expectMapEmpty(mFakeUidOwnerMap);
446}
447
448TEST_F(TrafficControllerTest, TestAllowlistUidMatch) {
449 std::vector<uint32_t> appUids = {1000, 1001, 10012};
Wayne Ma7be6bce2022-01-12 16:29:49 +0800450 ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, HAPPY_BOX_MATCH, TrafficController::IptOpInsert)));
Wayne Ma4d692332022-01-19 16:04:04 +0800451 expectUidOwnerMapValues(appUids, HAPPY_BOX_MATCH, 0);
Wayne Ma7be6bce2022-01-12 16:29:49 +0800452 ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, HAPPY_BOX_MATCH, TrafficController::IptOpDelete)));
Wayne Ma4d692332022-01-19 16:04:04 +0800453 expectMapEmpty(mFakeUidOwnerMap);
454}
455
456TEST_F(TrafficControllerTest, TestReplaceMatchUid) {
457 std::vector<uint32_t> appUids = {1000, 1001, 10012};
458 // Add appUids to the denylist and expect that their values are all PENALTY_BOX_MATCH.
Wayne Ma7be6bce2022-01-12 16:29:49 +0800459 ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, PENALTY_BOX_MATCH,
460 TrafficController::IptOpInsert)));
Wayne Ma4d692332022-01-19 16:04:04 +0800461 expectUidOwnerMapValues(appUids, PENALTY_BOX_MATCH, 0);
462
463 // Add the same UIDs to the allowlist and expect that we get PENALTY_BOX_MATCH |
464 // HAPPY_BOX_MATCH.
Wayne Ma7be6bce2022-01-12 16:29:49 +0800465 ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, HAPPY_BOX_MATCH, TrafficController::IptOpInsert)));
Wayne Ma4d692332022-01-19 16:04:04 +0800466 expectUidOwnerMapValues(appUids, HAPPY_BOX_MATCH | PENALTY_BOX_MATCH, 0);
467
468 // Remove the same UIDs from the allowlist and check the PENALTY_BOX_MATCH is still there.
Wayne Ma7be6bce2022-01-12 16:29:49 +0800469 ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, HAPPY_BOX_MATCH, TrafficController::IptOpDelete)));
Wayne Ma4d692332022-01-19 16:04:04 +0800470 expectUidOwnerMapValues(appUids, PENALTY_BOX_MATCH, 0);
471
472 // Remove the same UIDs from the denylist and check the map is empty.
Wayne Ma7be6bce2022-01-12 16:29:49 +0800473 ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, PENALTY_BOX_MATCH,
474 TrafficController::IptOpDelete)));
Wayne Ma4d692332022-01-19 16:04:04 +0800475 ASSERT_FALSE(mFakeUidOwnerMap.getFirstKey().ok());
476}
477
478TEST_F(TrafficControllerTest, TestDeleteWrongMatchSilentlyFails) {
479 std::vector<uint32_t> appUids = {1000, 1001, 10012};
480 // 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 +0800481 ASSERT_FALSE(isOk(updateUidOwnerMaps(appUids, HAPPY_BOX_MATCH,
482 TrafficController::IptOpDelete)));
Wayne Ma4d692332022-01-19 16:04:04 +0800483 expectMapEmpty(mFakeUidOwnerMap);
484
485 // Add denylist rules for appUids.
Wayne Ma7be6bce2022-01-12 16:29:49 +0800486 ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, HAPPY_BOX_MATCH,
487 TrafficController::IptOpInsert)));
Wayne Ma4d692332022-01-19 16:04:04 +0800488 expectUidOwnerMapValues(appUids, HAPPY_BOX_MATCH, 0);
489
490 // Delete (non-existent) denylist rules for appUids, and check that this silently does
491 // nothing if the uid is in the map but does not have denylist match. This is required because
492 // NetworkManagementService will try to remove a uid from denylist after adding it to the
493 // allowlist and if the remove fails it will not update the uid status.
Wayne Ma7be6bce2022-01-12 16:29:49 +0800494 ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, PENALTY_BOX_MATCH,
495 TrafficController::IptOpDelete)));
Wayne Ma4d692332022-01-19 16:04:04 +0800496 expectUidOwnerMapValues(appUids, HAPPY_BOX_MATCH, 0);
497}
498
499TEST_F(TrafficControllerTest, TestAddUidInterfaceFilteringRules) {
500 int iif0 = 15;
501 ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif0, {1000, 1001})));
502 expectUidOwnerMapValues({1000, 1001}, IIF_MATCH, iif0);
503
504 // Add some non-overlapping new uids. They should coexist with existing rules
505 int iif1 = 16;
506 ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif1, {2000, 2001})));
507 expectUidOwnerMapValues({1000, 1001}, IIF_MATCH, iif0);
508 expectUidOwnerMapValues({2000, 2001}, IIF_MATCH, iif1);
509
510 // Overwrite some existing uids
511 int iif2 = 17;
512 ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif2, {1000, 2000})));
513 expectUidOwnerMapValues({1001}, IIF_MATCH, iif0);
514 expectUidOwnerMapValues({2001}, IIF_MATCH, iif1);
515 expectUidOwnerMapValues({1000, 2000}, IIF_MATCH, iif2);
516}
517
518TEST_F(TrafficControllerTest, TestRemoveUidInterfaceFilteringRules) {
519 int iif0 = 15;
520 int iif1 = 16;
521 ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif0, {1000, 1001})));
522 ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif1, {2000, 2001})));
523 expectUidOwnerMapValues({1000, 1001}, IIF_MATCH, iif0);
524 expectUidOwnerMapValues({2000, 2001}, IIF_MATCH, iif1);
525
526 // Rmove some uids
527 ASSERT_TRUE(isOk(mTc.removeUidInterfaceRules({1001, 2001})));
528 expectUidOwnerMapValues({1000}, IIF_MATCH, iif0);
529 expectUidOwnerMapValues({2000}, IIF_MATCH, iif1);
530 checkEachUidValue({1000, 2000}, IIF_MATCH); // Make sure there are only two uids remaining
531
532 // Remove non-existent uids shouldn't fail
533 ASSERT_TRUE(isOk(mTc.removeUidInterfaceRules({2000, 3000})));
534 expectUidOwnerMapValues({1000}, IIF_MATCH, iif0);
535 checkEachUidValue({1000}, IIF_MATCH); // Make sure there are only one uid remaining
536
537 // Remove everything
538 ASSERT_TRUE(isOk(mTc.removeUidInterfaceRules({1000})));
539 expectMapEmpty(mFakeUidOwnerMap);
540}
541
542TEST_F(TrafficControllerTest, TestUidInterfaceFilteringRulesCoexistWithExistingMatches) {
543 // Set up existing PENALTY_BOX_MATCH rules
Wayne Ma7be6bce2022-01-12 16:29:49 +0800544 ASSERT_TRUE(isOk(updateUidOwnerMaps({1000, 1001, 10012}, PENALTY_BOX_MATCH,
545 TrafficController::IptOpInsert)));
Wayne Ma4d692332022-01-19 16:04:04 +0800546 expectUidOwnerMapValues({1000, 1001, 10012}, PENALTY_BOX_MATCH, 0);
547
548 // Add some partially-overlapping uid owner rules and check result
549 int iif1 = 32;
550 ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif1, {10012, 10013, 10014})));
551 expectUidOwnerMapValues({1000, 1001}, PENALTY_BOX_MATCH, 0);
552 expectUidOwnerMapValues({10012}, PENALTY_BOX_MATCH | IIF_MATCH, iif1);
553 expectUidOwnerMapValues({10013, 10014}, IIF_MATCH, iif1);
554
555 // Removing some PENALTY_BOX_MATCH rules should not change uid interface rule
Wayne Ma7be6bce2022-01-12 16:29:49 +0800556 ASSERT_TRUE(isOk(updateUidOwnerMaps({1001, 10012}, PENALTY_BOX_MATCH,
557 TrafficController::IptOpDelete)));
Wayne Ma4d692332022-01-19 16:04:04 +0800558 expectUidOwnerMapValues({1000}, PENALTY_BOX_MATCH, 0);
559 expectUidOwnerMapValues({10012, 10013, 10014}, IIF_MATCH, iif1);
560
561 // Remove all uid interface rules
562 ASSERT_TRUE(isOk(mTc.removeUidInterfaceRules({10012, 10013, 10014})));
563 expectUidOwnerMapValues({1000}, PENALTY_BOX_MATCH, 0);
564 // Make sure these are the only uids left
565 checkEachUidValue({1000}, PENALTY_BOX_MATCH);
566}
567
568TEST_F(TrafficControllerTest, TestUidInterfaceFilteringRulesCoexistWithNewMatches) {
569 int iif1 = 56;
570 // Set up existing uid interface rules
571 ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif1, {10001, 10002})));
572 expectUidOwnerMapValues({10001, 10002}, IIF_MATCH, iif1);
573
574 // Add some partially-overlapping doze rules
575 EXPECT_EQ(0, mTc.replaceUidOwnerMap("fw_dozable", true, {10002, 10003}));
576 expectUidOwnerMapValues({10001}, IIF_MATCH, iif1);
577 expectUidOwnerMapValues({10002}, DOZABLE_MATCH | IIF_MATCH, iif1);
578 expectUidOwnerMapValues({10003}, DOZABLE_MATCH, 0);
579
580 // Introduce a third rule type (powersave) on various existing UIDs
581 EXPECT_EQ(0, mTc.replaceUidOwnerMap("fw_powersave", true, {10000, 10001, 10002, 10003}));
582 expectUidOwnerMapValues({10000}, POWERSAVE_MATCH, 0);
583 expectUidOwnerMapValues({10001}, POWERSAVE_MATCH | IIF_MATCH, iif1);
584 expectUidOwnerMapValues({10002}, POWERSAVE_MATCH | DOZABLE_MATCH | IIF_MATCH, iif1);
585 expectUidOwnerMapValues({10003}, POWERSAVE_MATCH | DOZABLE_MATCH, 0);
586
587 // Remove all doze rules
588 EXPECT_EQ(0, mTc.replaceUidOwnerMap("fw_dozable", true, {}));
589 expectUidOwnerMapValues({10000}, POWERSAVE_MATCH, 0);
590 expectUidOwnerMapValues({10001}, POWERSAVE_MATCH | IIF_MATCH, iif1);
591 expectUidOwnerMapValues({10002}, POWERSAVE_MATCH | IIF_MATCH, iif1);
592 expectUidOwnerMapValues({10003}, POWERSAVE_MATCH, 0);
593
594 // Remove all powersave rules, expect ownerMap to only have uid interface rules left
595 EXPECT_EQ(0, mTc.replaceUidOwnerMap("fw_powersave", true, {}));
596 expectUidOwnerMapValues({10001, 10002}, IIF_MATCH, iif1);
597 // Make sure these are the only uids left
598 checkEachUidValue({10001, 10002}, IIF_MATCH);
599}
600
Motomu Utsumib08654c2022-05-11 05:56:26 +0000601TEST_F(TrafficControllerTest, TestAddUidInterfaceFilteringRulesWithWildcard) {
602 // iif=0 is a wildcard
603 int iif = 0;
604 // Add interface rule with wildcard to uids
605 ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif, {1000, 1001})));
606 expectUidOwnerMapValues({1000, 1001}, IIF_MATCH, iif);
607}
608
609TEST_F(TrafficControllerTest, TestRemoveUidInterfaceFilteringRulesWithWildcard) {
610 // iif=0 is a wildcard
611 int iif = 0;
612 // Add interface rule with wildcard to two uids
613 ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif, {1000, 1001})));
614 expectUidOwnerMapValues({1000, 1001}, IIF_MATCH, iif);
615
616 // Remove interface rule from one of the uids
617 ASSERT_TRUE(isOk(mTc.removeUidInterfaceRules({1000})));
618 expectUidOwnerMapValues({1001}, IIF_MATCH, iif);
619 checkEachUidValue({1001}, IIF_MATCH);
620
621 // Remove interface rule from the remaining uid
622 ASSERT_TRUE(isOk(mTc.removeUidInterfaceRules({1001})));
623 expectMapEmpty(mFakeUidOwnerMap);
624}
625
626TEST_F(TrafficControllerTest, TestUidInterfaceFilteringRulesWithWildcardAndExistingMatches) {
627 // Set up existing DOZABLE_MATCH and POWERSAVE_MATCH rule
628 ASSERT_TRUE(isOk(updateUidOwnerMaps({1000}, DOZABLE_MATCH,
629 TrafficController::IptOpInsert)));
630 ASSERT_TRUE(isOk(updateUidOwnerMaps({1000}, POWERSAVE_MATCH,
631 TrafficController::IptOpInsert)));
632
633 // iif=0 is a wildcard
634 int iif = 0;
635 // Add interface rule with wildcard to the existing uid
636 ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif, {1000})));
637 expectUidOwnerMapValues({1000}, POWERSAVE_MATCH | DOZABLE_MATCH | IIF_MATCH, iif);
638
639 // Remove interface rule with wildcard from the existing uid
640 ASSERT_TRUE(isOk(mTc.removeUidInterfaceRules({1000})));
641 expectUidOwnerMapValues({1000}, POWERSAVE_MATCH | DOZABLE_MATCH, 0);
642}
643
644TEST_F(TrafficControllerTest, TestUidInterfaceFilteringRulesWithWildcardAndNewMatches) {
645 // iif=0 is a wildcard
646 int iif = 0;
647 // Set up existing interface rule with wildcard
648 ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif, {1000})));
649
650 // Add DOZABLE_MATCH and POWERSAVE_MATCH rule to the existing uid
651 ASSERT_TRUE(isOk(updateUidOwnerMaps({1000}, DOZABLE_MATCH,
652 TrafficController::IptOpInsert)));
653 ASSERT_TRUE(isOk(updateUidOwnerMaps({1000}, POWERSAVE_MATCH,
654 TrafficController::IptOpInsert)));
655 expectUidOwnerMapValues({1000}, POWERSAVE_MATCH | DOZABLE_MATCH | IIF_MATCH, iif);
656
657 // Remove DOZABLE_MATCH and POWERSAVE_MATCH rule from the existing uid
658 ASSERT_TRUE(isOk(updateUidOwnerMaps({1000}, DOZABLE_MATCH,
659 TrafficController::IptOpDelete)));
660 ASSERT_TRUE(isOk(updateUidOwnerMaps({1000}, POWERSAVE_MATCH,
661 TrafficController::IptOpDelete)));
662 expectUidOwnerMapValues({1000}, IIF_MATCH, iif);
663}
664
Wayne Ma4d692332022-01-19 16:04:04 +0800665TEST_F(TrafficControllerTest, TestGrantInternetPermission) {
666 std::vector<uid_t> appUids = {TEST_UID, TEST_UID2, TEST_UID3};
667
668 mTc.setPermissionForUids(INetd::PERMISSION_INTERNET, appUids);
669 expectMapEmpty(mFakeUidPermissionMap);
670 expectPrivilegedUserSetEmpty();
671}
672
673TEST_F(TrafficControllerTest, TestRevokeInternetPermission) {
674 std::vector<uid_t> appUids = {TEST_UID, TEST_UID2, TEST_UID3};
675
676 mTc.setPermissionForUids(INetd::PERMISSION_NONE, appUids);
677 expectUidPermissionMapValues(appUids, INetd::PERMISSION_NONE);
678}
679
680TEST_F(TrafficControllerTest, TestPermissionUninstalled) {
681 std::vector<uid_t> appUids = {TEST_UID, TEST_UID2, TEST_UID3};
682
683 mTc.setPermissionForUids(INetd::PERMISSION_UPDATE_DEVICE_STATS, appUids);
684 expectUidPermissionMapValues(appUids, INetd::PERMISSION_UPDATE_DEVICE_STATS);
685 expectPrivilegedUserSet(appUids);
686
687 std::vector<uid_t> uidToRemove = {TEST_UID};
688 mTc.setPermissionForUids(INetd::PERMISSION_UNINSTALLED, uidToRemove);
689
690 std::vector<uid_t> uidRemain = {TEST_UID3, TEST_UID2};
691 expectUidPermissionMapValues(uidRemain, INetd::PERMISSION_UPDATE_DEVICE_STATS);
692 expectPrivilegedUserSet(uidRemain);
693
694 mTc.setPermissionForUids(INetd::PERMISSION_UNINSTALLED, uidRemain);
695 expectMapEmpty(mFakeUidPermissionMap);
696 expectPrivilegedUserSetEmpty();
697}
698
699TEST_F(TrafficControllerTest, TestGrantUpdateStatsPermission) {
700 std::vector<uid_t> appUids = {TEST_UID, TEST_UID2, TEST_UID3};
701
702 mTc.setPermissionForUids(INetd::PERMISSION_UPDATE_DEVICE_STATS, appUids);
703 expectUidPermissionMapValues(appUids, INetd::PERMISSION_UPDATE_DEVICE_STATS);
704 expectPrivilegedUserSet(appUids);
705
706 mTc.setPermissionForUids(INetd::PERMISSION_NONE, appUids);
707 expectPrivilegedUserSetEmpty();
708 expectUidPermissionMapValues(appUids, INetd::PERMISSION_NONE);
709}
710
711TEST_F(TrafficControllerTest, TestRevokeUpdateStatsPermission) {
712 std::vector<uid_t> appUids = {TEST_UID, TEST_UID2, TEST_UID3};
713
714 mTc.setPermissionForUids(INetd::PERMISSION_UPDATE_DEVICE_STATS, appUids);
715 expectPrivilegedUserSet(appUids);
716
717 std::vector<uid_t> uidToRemove = {TEST_UID};
718 mTc.setPermissionForUids(INetd::PERMISSION_NONE, uidToRemove);
719
720 std::vector<uid_t> uidRemain = {TEST_UID3, TEST_UID2};
721 expectPrivilegedUserSet(uidRemain);
722
723 mTc.setPermissionForUids(INetd::PERMISSION_NONE, uidRemain);
724 expectPrivilegedUserSetEmpty();
725}
726
727TEST_F(TrafficControllerTest, TestGrantWrongPermission) {
728 std::vector<uid_t> appUids = {TEST_UID, TEST_UID2, TEST_UID3};
729
730 mTc.setPermissionForUids(INetd::PERMISSION_NONE, appUids);
731 expectPrivilegedUserSetEmpty();
732 expectUidPermissionMapValues(appUids, INetd::PERMISSION_NONE);
733}
734
735TEST_F(TrafficControllerTest, TestGrantDuplicatePermissionSlientlyFail) {
736 std::vector<uid_t> appUids = {TEST_UID, TEST_UID2, TEST_UID3};
737
738 mTc.setPermissionForUids(INetd::PERMISSION_INTERNET, appUids);
739 expectMapEmpty(mFakeUidPermissionMap);
740
741 std::vector<uid_t> uidToAdd = {TEST_UID};
742 mTc.setPermissionForUids(INetd::PERMISSION_INTERNET, uidToAdd);
743
744 expectPrivilegedUserSetEmpty();
745
746 mTc.setPermissionForUids(INetd::PERMISSION_NONE, appUids);
747 expectUidPermissionMapValues(appUids, INetd::PERMISSION_NONE);
748
749 mTc.setPermissionForUids(INetd::PERMISSION_UPDATE_DEVICE_STATS, appUids);
750 expectPrivilegedUserSet(appUids);
751
752 mTc.setPermissionForUids(INetd::PERMISSION_UPDATE_DEVICE_STATS, uidToAdd);
753 expectPrivilegedUserSet(appUids);
754
755 mTc.setPermissionForUids(INetd::PERMISSION_NONE, appUids);
756 expectPrivilegedUserSetEmpty();
757}
758
Ken Chen2fb86362022-06-05 11:39:38 +0800759TEST_F(TrafficControllerTest, TestDumpsys) {
Ken Chen0dd74952022-06-06 18:25:18 +0800760 StatsKey tagStatsMapKey;
761 populateFakeStats(TEST_COOKIE, TEST_UID, TEST_TAG, &tagStatsMapKey);
762 populateFakeCounterSet(TEST_UID3, TEST_COUNTERSET);
Ken Chen2fb86362022-06-05 11:39:38 +0800763
Ken Chen0dd74952022-06-06 18:25:18 +0800764 // Expect: (part of this depends on hard-code values in populateFakeStats())
765 //
766 // mCookieTagMap:
767 // cookie=1 tag=0x2a uid=10086
768 //
769 // mUidCounterSetMap:
770 // 98765 1
771 //
772 // mAppUidStatsMap::
773 // uid rxBytes rxPackets txBytes txPackets
774 // 10086 100 1 0 0
775 //
776 // mStatsMapA:
777 // ifaceIndex ifaceName tag_hex uid_int cnt_set rxBytes rxPackets txBytes txPackets
778 // 999 test0 0x2a 10086 1 100 1 0 0
Ken Chen2fb86362022-06-05 11:39:38 +0800779 std::vector<std::string> expectedLines = {
Ken Chen0dd74952022-06-06 18:25:18 +0800780 "mCookieTagMap:",
781 fmt::format("cookie={} tag={:#x} uid={}", TEST_COOKIE, TEST_TAG, TEST_UID),
782 "mUidCounterSetMap:",
783 fmt::format("{} {}", TEST_UID3, TEST_COUNTERSET),
784 "mAppUidStatsMap::", // TODO@: fix double colon
785 "uid rxBytes rxPackets txBytes txPackets",
786 fmt::format("{} {} {} {} {}", TEST_UID, RXBYTES, RXPACKETS, TXBYTES, TXPACKETS),
787 "mStatsMapA",
788 "ifaceIndex ifaceName tag_hex uid_int cnt_set rxBytes rxPackets txBytes txPackets",
789 fmt::format("{} {} {:#x} {} {} {} {} {} {}",
790 TEST_IFINDEX, TEST_IFNAME, TEST_TAG, TEST_UID, TEST_COUNTERSET, RXBYTES,
791 RXPACKETS, TXBYTES, TXPACKETS)};
Ken Chen2fb86362022-06-05 11:39:38 +0800792
Ken Chen0dd74952022-06-06 18:25:18 +0800793 populateFakeIfaceIndexName(TEST_IFNAME, TEST_IFINDEX);
794 expectedLines.emplace_back("mIfaceIndexNameMap:");
795 expectedLines.emplace_back(fmt::format("ifaceIndex={} ifaceName={}",
796 TEST_IFINDEX, TEST_IFNAME));
797
798 ASSERT_TRUE(isOk(updateUidOwnerMaps({TEST_UID}, HAPPY_BOX_MATCH,
799 TrafficController::IptOpInsert)));
800 expectedLines.emplace_back("mUidOwnerMap:");
801 expectedLines.emplace_back(fmt::format("{} HAPPY_BOX_MATCH", TEST_UID));
802
803 mTc.setPermissionForUids(INetd::PERMISSION_UPDATE_DEVICE_STATS, {TEST_UID2});
804 expectedLines.emplace_back("mUidPermissionMap:");
805 expectedLines.emplace_back(fmt::format("{} BPF_PERMISSION_UPDATE_DEVICE_STATS", TEST_UID2));
806 expectedLines.emplace_back("mPrivilegedUser:");
807 expectedLines.emplace_back(fmt::format("{} ALLOW_UPDATE_DEVICE_STATS", TEST_UID2));
Ken Chen2fb86362022-06-05 11:39:38 +0800808 EXPECT_TRUE(expectDumpsysContains(expectedLines));
809}
810
Hungming Chen410bb122022-06-09 01:32:00 +0800811TEST_F(TrafficControllerTest, dumpsysInvalidMaps) {
812 makeTrafficControllerMapsInvalid();
813
Hungming Chen56b90132022-06-09 11:33:43 +0800814 const std::string kErrIterate = "print end with error: Get firstKey map -1 failed: "
815 "Bad file descriptor";
816 const std::string kErrReadRulesConfig = "read ownerMatch configure failed with error: "
817 "Read value of map -1 failed: Bad file descriptor";
818 const std::string kErrReadStatsMapConfig = "read stats map configure failed with error: "
819 "Read value of map -1 failed: Bad file descriptor";
820
Hungming Chen410bb122022-06-09 01:32:00 +0800821 std::vector<std::string> expectedLines = {
Hungming Chen56b90132022-06-09 11:33:43 +0800822 fmt::format("mCookieTagMap {}", kErrIterate),
823 fmt::format("mUidCounterSetMap {}", kErrIterate),
824 fmt::format("mAppUidStatsMap {}", kErrIterate),
825 fmt::format("mStatsMapA {}", kErrIterate),
826 fmt::format("mStatsMapB {}", kErrIterate),
827 fmt::format("mIfaceIndexNameMap {}", kErrIterate),
828 fmt::format("mIfaceStatsMap {}", kErrIterate),
829 fmt::format("mConfigurationMap {}", kErrReadRulesConfig),
830 fmt::format("mConfigurationMap {}", kErrReadStatsMapConfig),
831 fmt::format("mUidOwnerMap {}", kErrIterate),
832 fmt::format("mUidPermissionMap {}", kErrIterate)};
Hungming Chen410bb122022-06-09 01:32:00 +0800833 EXPECT_TRUE(expectDumpsysContains(expectedLines));
834}
835
Hungming Chen1d4d3d22022-06-08 11:50:15 +0800836TEST_F(TrafficControllerTest, uidMatchTypeToString) {
837 // NO_MATCH(0) can't be verified because match type flag is added by OR operator.
838 // See TrafficController::addRule()
839 static const struct TestConfig {
840 UidOwnerMatchType uidOwnerMatchType;
841 std::string expected;
842 } testConfigs[] = {
843 // clang-format off
844 {HAPPY_BOX_MATCH, "HAPPY_BOX_MATCH"},
845 {DOZABLE_MATCH, "DOZABLE_MATCH"},
846 {STANDBY_MATCH, "STANDBY_MATCH"},
847 {POWERSAVE_MATCH, "POWERSAVE_MATCH"},
848 {HAPPY_BOX_MATCH, "HAPPY_BOX_MATCH"},
849 {RESTRICTED_MATCH, "RESTRICTED_MATCH"},
850 {LOW_POWER_STANDBY_MATCH, "LOW_POWER_STANDBY_MATCH"},
851 {IIF_MATCH, "IIF_MATCH"},
852 {LOCKDOWN_VPN_MATCH, "LOCKDOWN_VPN_MATCH"},
853 {OEM_DENY_1_MATCH, "OEM_DENY_1_MATCH"},
854 {OEM_DENY_2_MATCH, "OEM_DENY_2_MATCH"},
855 {OEM_DENY_3_MATCH, "OEM_DENY_3_MATCH"},
856 // clang-format on
857 };
858
859 for (const auto& config : testConfigs) {
860 SCOPED_TRACE(fmt::format("testConfig: [{}, {}]", config.uidOwnerMatchType,
861 config.expected));
862
863 // Test private function uidMatchTypeToString() via dumpsys.
864 ASSERT_TRUE(isOk(updateUidOwnerMaps({TEST_UID}, config.uidOwnerMatchType,
865 TrafficController::IptOpInsert)));
866 std::vector<std::string> expectedLines;
867 expectedLines.emplace_back(fmt::format("{} {}", TEST_UID, config.expected));
868 EXPECT_TRUE(expectDumpsysContains(expectedLines));
869
870 // Clean up the stubs.
871 ASSERT_TRUE(isOk(updateUidOwnerMaps({TEST_UID}, config.uidOwnerMatchType,
872 TrafficController::IptOpDelete)));
873 }
874}
875
Ken Chen77a6b712022-06-06 12:46:36 +0800876TEST_F(TrafficControllerTest, getFirewallType) {
877 static const struct TestConfig {
878 ChildChain childChain;
879 FirewallType firewallType;
880 } testConfigs[] = {
881 // clang-format off
882 {NONE, DENYLIST},
883 {DOZABLE, ALLOWLIST},
884 {STANDBY, DENYLIST},
885 {POWERSAVE, ALLOWLIST},
886 {RESTRICTED, ALLOWLIST},
887 {LOW_POWER_STANDBY, ALLOWLIST},
888 {LOCKDOWN, DENYLIST},
889 {OEM_DENY_1, DENYLIST},
890 {OEM_DENY_2, DENYLIST},
Ken Chend3a3af52022-06-08 02:54:09 +0000891 {OEM_DENY_3, DENYLIST},
Ken Chen77a6b712022-06-06 12:46:36 +0800892 {INVALID_CHAIN, DENYLIST},
893 // clang-format on
894 };
895
896 for (const auto& config : testConfigs) {
897 SCOPED_TRACE(fmt::format("testConfig: [{}, {}]", config.childChain, config.firewallType));
898 EXPECT_EQ(config.firewallType, mTc.getFirewallType(config.childChain));
899 }
900}
901
Patrick Rohr61e94672022-02-01 21:06:40 +0100902constexpr uint32_t SOCK_CLOSE_WAIT_US = 30 * 1000;
903constexpr uint32_t ENOBUFS_POLL_WAIT_US = 10 * 1000;
904
905using android::base::Error;
906using android::base::Result;
907using android::bpf::BpfMap;
908
909// This test set up a SkDestroyListener that is running parallel with the production
910// SkDestroyListener. The test will create thousands of sockets and tag them on the
911// production cookieUidTagMap and close them in a short time. When the number of
912// sockets get closed exceeds the buffer size, it will start to return ENOBUFF
913// error. The error will be ignored by the production SkDestroyListener and the
914// test will clean up the tags in tearDown if there is any remains.
915
916// TODO: Instead of test the ENOBUFF error, we can test the production
917// SkDestroyListener to see if it failed to delete a tagged socket when ENOBUFF
918// triggered.
919class NetlinkListenerTest : public testing::Test {
920 protected:
921 NetlinkListenerTest() {}
922 BpfMap<uint64_t, UidTagValue> mCookieTagMap;
923
924 void SetUp() {
Maciej Żenczykowskiced35312022-05-31 05:11:12 -0700925 mCookieTagMap.init(COOKIE_TAG_MAP_PATH);
Patrick Rohr61e94672022-02-01 21:06:40 +0100926 ASSERT_TRUE(mCookieTagMap.isValid());
927 }
928
929 void TearDown() {
930 const auto deleteTestCookieEntries = [](const uint64_t& key, const UidTagValue& value,
931 BpfMap<uint64_t, UidTagValue>& map) {
932 if ((value.uid == TEST_UID) && (value.tag == TEST_TAG)) {
933 Result<void> res = map.deleteValue(key);
934 if (res.ok() || (res.error().code() == ENOENT)) {
935 return Result<void>();
936 }
Maciej Żenczykowskie0f58462022-05-17 13:59:22 -0700937 ALOGE("Failed to delete data(cookie = %" PRIu64 "): %s", key,
Patrick Rohr61e94672022-02-01 21:06:40 +0100938 strerror(res.error().code()));
939 }
940 // Move forward to next cookie in the map.
941 return Result<void>();
942 };
943 EXPECT_RESULT_OK(mCookieTagMap.iterateWithValue(deleteTestCookieEntries));
944 }
945
946 Result<void> checkNoGarbageTagsExist() {
947 const auto checkGarbageTags = [](const uint64_t&, const UidTagValue& value,
948 const BpfMap<uint64_t, UidTagValue>&) -> Result<void> {
949 if ((TEST_UID == value.uid) && (TEST_TAG == value.tag)) {
950 return Error(EUCLEAN) << "Closed socket is not untagged";
951 }
952 return {};
953 };
954 return mCookieTagMap.iterateWithValue(checkGarbageTags);
955 }
956
957 bool checkMassiveSocketDestroy(int totalNumber, bool expectError) {
958 std::unique_ptr<android::netdutils::NetlinkListenerInterface> skDestroyListener;
959 auto result = android::net::TrafficController::makeSkDestroyListener();
960 if (!isOk(result)) {
961 ALOGE("Unable to create SkDestroyListener: %s", toString(result).c_str());
962 } else {
963 skDestroyListener = std::move(result.value());
964 }
965 int rxErrorCount = 0;
966 // Rx handler extracts nfgenmsg looks up and invokes registered dispatch function.
967 const auto rxErrorHandler = [&rxErrorCount](const int, const int) { rxErrorCount++; };
968 skDestroyListener->registerSkErrorHandler(rxErrorHandler);
969 int fds[totalNumber];
970 for (int i = 0; i < totalNumber; i++) {
971 fds[i] = socket(AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0);
972 // The likely reason for a failure is running out of available file descriptors.
973 EXPECT_LE(0, fds[i]) << i << " of " << totalNumber;
974 if (fds[i] < 0) {
975 // EXPECT_LE already failed above, so test case is a failure, but we don't
976 // want potentially tens of thousands of extra failures creating and then
977 // closing all these fds cluttering up the logs.
978 totalNumber = i;
979 break;
980 };
981 libnetd_updatable_tagSocket(fds[i], TEST_TAG, TEST_UID, 1000);
982 }
983
984 // TODO: Use a separate thread that has its own fd table so we can
985 // close sockets even faster simply by terminating that thread.
986 for (int i = 0; i < totalNumber; i++) {
987 EXPECT_EQ(0, close(fds[i]));
988 }
989 // wait a bit for netlink listener to handle all the messages.
990 usleep(SOCK_CLOSE_WAIT_US);
991 if (expectError) {
992 // If ENOBUFS triggered, check it only called into the handler once, ie.
993 // that the netlink handler is not spinning.
994 int currentErrorCount = rxErrorCount;
995 // 0 error count is acceptable because the system has chances to close all sockets
996 // normally.
997 EXPECT_LE(0, rxErrorCount);
998 if (!rxErrorCount) return true;
999
1000 usleep(ENOBUFS_POLL_WAIT_US);
1001 EXPECT_EQ(currentErrorCount, rxErrorCount);
1002 } else {
1003 EXPECT_RESULT_OK(checkNoGarbageTagsExist());
1004 EXPECT_EQ(0, rxErrorCount);
1005 }
1006 return false;
1007 }
1008};
1009
1010TEST_F(NetlinkListenerTest, TestAllSocketUntagged) {
1011 checkMassiveSocketDestroy(10, false);
1012 checkMassiveSocketDestroy(100, false);
1013}
1014
1015// Disabled because flaky on blueline-userdebug; this test relies on the main thread
1016// winning a race against the NetlinkListener::run() thread. There's no way to ensure
1017// things will be scheduled the same way across all architectures and test environments.
1018TEST_F(NetlinkListenerTest, DISABLED_TestSkDestroyError) {
1019 bool needRetry = false;
1020 int retryCount = 0;
1021 do {
1022 needRetry = checkMassiveSocketDestroy(32500, true);
1023 if (needRetry) retryCount++;
1024 } while (needRetry && retryCount < 3);
1025 // Should review test if it can always close all sockets correctly.
1026 EXPECT_GT(3, retryCount);
1027}
1028
1029
Wayne Ma4d692332022-01-19 16:04:04 +08001030} // namespace net
1031} // namespace android