blob: d0eca34e24aed95ea2506a8e6d343b184235262d [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
33#include <android-base/stringprintf.h>
34#include <android-base/strings.h>
Wayne Ma7be6bce2022-01-12 16:29:49 +080035#include <binder/Status.h>
Wayne Ma4d692332022-01-19 16:04:04 +080036
37#include <netdutils/MockSyscalls.h>
38
39#include "TrafficController.h"
40#include "bpf/BpfUtils.h"
Patrick Rohr61e94672022-02-01 21:06:40 +010041#include "NetdUpdatablePublic.h"
Wayne Ma4d692332022-01-19 16:04:04 +080042
43using namespace android::bpf; // NOLINT(google-build-using-namespace): grandfathered
44
45namespace android {
46namespace net {
47
Wayne Ma7be6bce2022-01-12 16:29:49 +080048using android::netdutils::Status;
Wayne Ma4d692332022-01-19 16:04:04 +080049using base::Result;
50using netdutils::isOk;
51
52constexpr int TEST_MAP_SIZE = 10;
Wayne Ma4d692332022-01-19 16:04:04 +080053constexpr uid_t TEST_UID = 10086;
54constexpr uid_t TEST_UID2 = 54321;
55constexpr uid_t TEST_UID3 = 98765;
56constexpr uint32_t TEST_TAG = 42;
57constexpr uint32_t TEST_COUNTERSET = 1;
58constexpr uint32_t DEFAULT_COUNTERSET = 0;
Wayne Ma4d692332022-01-19 16:04:04 +080059
60#define ASSERT_VALID(x) ASSERT_TRUE((x).isValid())
61
62class TrafficControllerTest : public ::testing::Test {
63 protected:
Wayne Ma92d80792022-01-20 13:20:34 +080064 TrafficControllerTest() {}
Wayne Ma4d692332022-01-19 16:04:04 +080065 TrafficController mTc;
66 BpfMap<uint64_t, UidTagValue> mFakeCookieTagMap;
67 BpfMap<uint32_t, uint8_t> mFakeUidCounterSetMap;
68 BpfMap<uint32_t, StatsValue> mFakeAppUidStatsMap;
69 BpfMap<StatsKey, StatsValue> mFakeStatsMapA;
70 BpfMap<uint32_t, uint8_t> mFakeConfigurationMap;
71 BpfMap<uint32_t, UidOwnerValue> mFakeUidOwnerMap;
72 BpfMap<uint32_t, uint8_t> mFakeUidPermissionMap;
73
74 void SetUp() {
75 std::lock_guard guard(mTc.mMutex);
76 ASSERT_EQ(0, setrlimitForTest());
77
78 mFakeCookieTagMap.reset(createMap(BPF_MAP_TYPE_HASH, sizeof(uint64_t), sizeof(UidTagValue),
79 TEST_MAP_SIZE, 0));
80 ASSERT_VALID(mFakeCookieTagMap);
81
82 mFakeUidCounterSetMap.reset(
83 createMap(BPF_MAP_TYPE_HASH, sizeof(uint32_t), sizeof(uint8_t), TEST_MAP_SIZE, 0));
84 ASSERT_VALID(mFakeUidCounterSetMap);
85
86 mFakeAppUidStatsMap.reset(createMap(BPF_MAP_TYPE_HASH, sizeof(uint32_t), sizeof(StatsValue),
87 TEST_MAP_SIZE, 0));
88 ASSERT_VALID(mFakeAppUidStatsMap);
89
90 mFakeStatsMapA.reset(createMap(BPF_MAP_TYPE_HASH, sizeof(StatsKey), sizeof(StatsValue),
91 TEST_MAP_SIZE, 0));
92 ASSERT_VALID(mFakeStatsMapA);
93
94 mFakeConfigurationMap.reset(
95 createMap(BPF_MAP_TYPE_HASH, sizeof(uint32_t), sizeof(uint8_t), 1, 0));
96 ASSERT_VALID(mFakeConfigurationMap);
97
98 mFakeUidOwnerMap.reset(createMap(BPF_MAP_TYPE_HASH, sizeof(uint32_t), sizeof(UidOwnerValue),
99 TEST_MAP_SIZE, 0));
100 ASSERT_VALID(mFakeUidOwnerMap);
101 mFakeUidPermissionMap.reset(
102 createMap(BPF_MAP_TYPE_HASH, sizeof(uint32_t), sizeof(uint8_t), TEST_MAP_SIZE, 0));
103 ASSERT_VALID(mFakeUidPermissionMap);
104
105 mTc.mCookieTagMap.reset(dupFd(mFakeCookieTagMap.getMap()));
106 ASSERT_VALID(mTc.mCookieTagMap);
107 mTc.mUidCounterSetMap.reset(dupFd(mFakeUidCounterSetMap.getMap()));
108 ASSERT_VALID(mTc.mUidCounterSetMap);
109 mTc.mAppUidStatsMap.reset(dupFd(mFakeAppUidStatsMap.getMap()));
110 ASSERT_VALID(mTc.mAppUidStatsMap);
111 mTc.mStatsMapA.reset(dupFd(mFakeStatsMapA.getMap()));
112 ASSERT_VALID(mTc.mStatsMapA);
113 mTc.mConfigurationMap.reset(dupFd(mFakeConfigurationMap.getMap()));
114 ASSERT_VALID(mTc.mConfigurationMap);
115
116 // Always write to stats map A by default.
117 ASSERT_RESULT_OK(mTc.mConfigurationMap.writeValue(CURRENT_STATS_MAP_CONFIGURATION_KEY,
118 SELECT_MAP_A, BPF_ANY));
119 mTc.mUidOwnerMap.reset(dupFd(mFakeUidOwnerMap.getMap()));
120 ASSERT_VALID(mTc.mUidOwnerMap);
121 mTc.mUidPermissionMap.reset(dupFd(mFakeUidPermissionMap.getMap()));
122 ASSERT_VALID(mTc.mUidPermissionMap);
123 mTc.mPrivilegedUser.clear();
124 }
125
126 int dupFd(const android::base::unique_fd& mapFd) {
127 return fcntl(mapFd.get(), F_DUPFD_CLOEXEC, 0);
128 }
129
Wayne Ma4d692332022-01-19 16:04:04 +0800130 void populateFakeStats(uint64_t cookie, uint32_t uid, uint32_t tag, StatsKey* key) {
131 UidTagValue cookieMapkey = {.uid = (uint32_t)uid, .tag = tag};
132 EXPECT_RESULT_OK(mFakeCookieTagMap.writeValue(cookie, cookieMapkey, BPF_ANY));
133 *key = {.uid = uid, .tag = tag, .counterSet = TEST_COUNTERSET, .ifaceIndex = 1};
134 StatsValue statsMapValue = {.rxPackets = 1, .rxBytes = 100};
135 uint8_t counterSet = TEST_COUNTERSET;
136 EXPECT_RESULT_OK(mFakeUidCounterSetMap.writeValue(uid, counterSet, BPF_ANY));
137 EXPECT_RESULT_OK(mFakeStatsMapA.writeValue(*key, statsMapValue, BPF_ANY));
138 key->tag = 0;
139 EXPECT_RESULT_OK(mFakeStatsMapA.writeValue(*key, statsMapValue, BPF_ANY));
140 EXPECT_RESULT_OK(mFakeAppUidStatsMap.writeValue(uid, statsMapValue, BPF_ANY));
141 // put tag information back to statsKey
142 key->tag = tag;
143 }
144
145 void checkUidOwnerRuleForChain(ChildChain chain, UidOwnerMatchType match) {
146 uint32_t uid = TEST_UID;
147 EXPECT_EQ(0, mTc.changeUidOwnerRule(chain, uid, DENY, DENYLIST));
148 Result<UidOwnerValue> value = mFakeUidOwnerMap.readValue(uid);
149 EXPECT_RESULT_OK(value);
150 EXPECT_TRUE(value.value().rule & match);
151
152 uid = TEST_UID2;
153 EXPECT_EQ(0, mTc.changeUidOwnerRule(chain, uid, ALLOW, ALLOWLIST));
154 value = mFakeUidOwnerMap.readValue(uid);
155 EXPECT_RESULT_OK(value);
156 EXPECT_TRUE(value.value().rule & match);
157
158 EXPECT_EQ(0, mTc.changeUidOwnerRule(chain, uid, DENY, ALLOWLIST));
159 value = mFakeUidOwnerMap.readValue(uid);
160 EXPECT_FALSE(value.ok());
161 EXPECT_EQ(ENOENT, value.error().code());
162
163 uid = TEST_UID;
164 EXPECT_EQ(0, mTc.changeUidOwnerRule(chain, uid, ALLOW, DENYLIST));
165 value = mFakeUidOwnerMap.readValue(uid);
166 EXPECT_FALSE(value.ok());
167 EXPECT_EQ(ENOENT, value.error().code());
168
169 uid = TEST_UID3;
170 EXPECT_EQ(-ENOENT, mTc.changeUidOwnerRule(chain, uid, ALLOW, DENYLIST));
171 value = mFakeUidOwnerMap.readValue(uid);
172 EXPECT_FALSE(value.ok());
173 EXPECT_EQ(ENOENT, value.error().code());
174 }
175
176 void checkEachUidValue(const std::vector<int32_t>& uids, UidOwnerMatchType match) {
177 for (uint32_t uid : uids) {
178 Result<UidOwnerValue> value = mFakeUidOwnerMap.readValue(uid);
179 EXPECT_RESULT_OK(value);
180 EXPECT_TRUE(value.value().rule & match);
181 }
182 std::set<uint32_t> uidSet(uids.begin(), uids.end());
183 const auto checkNoOtherUid = [&uidSet](const int32_t& key,
184 const BpfMap<uint32_t, UidOwnerValue>&) {
185 EXPECT_NE(uidSet.end(), uidSet.find(key));
186 return Result<void>();
187 };
188 EXPECT_RESULT_OK(mFakeUidOwnerMap.iterate(checkNoOtherUid));
189 }
190
191 void checkUidMapReplace(const std::string& name, const std::vector<int32_t>& uids,
192 UidOwnerMatchType match) {
193 bool isAllowlist = true;
194 EXPECT_EQ(0, mTc.replaceUidOwnerMap(name, isAllowlist, uids));
195 checkEachUidValue(uids, match);
196
197 isAllowlist = false;
198 EXPECT_EQ(0, mTc.replaceUidOwnerMap(name, isAllowlist, uids));
199 checkEachUidValue(uids, match);
200 }
201
202 void expectUidOwnerMapValues(const std::vector<uint32_t>& appUids, uint8_t expectedRule,
203 uint32_t expectedIif) {
204 for (uint32_t uid : appUids) {
205 Result<UidOwnerValue> value = mFakeUidOwnerMap.readValue(uid);
206 EXPECT_RESULT_OK(value);
207 EXPECT_EQ(expectedRule, value.value().rule)
208 << "Expected rule for UID " << uid << " to be " << expectedRule << ", but was "
209 << value.value().rule;
210 EXPECT_EQ(expectedIif, value.value().iif)
211 << "Expected iif for UID " << uid << " to be " << expectedIif << ", but was "
212 << value.value().iif;
213 }
214 }
215
216 template <class Key, class Value>
217 void expectMapEmpty(BpfMap<Key, Value>& map) {
218 auto isEmpty = map.isEmpty();
219 EXPECT_RESULT_OK(isEmpty);
220 EXPECT_TRUE(isEmpty.value());
221 }
222
223 void expectUidPermissionMapValues(const std::vector<uid_t>& appUids, uint8_t expectedValue) {
224 for (uid_t uid : appUids) {
225 Result<uint8_t> value = mFakeUidPermissionMap.readValue(uid);
226 EXPECT_RESULT_OK(value);
227 EXPECT_EQ(expectedValue, value.value())
228 << "Expected value for UID " << uid << " to be " << expectedValue
229 << ", but was " << value.value();
230 }
231 }
232
233 void expectPrivilegedUserSet(const std::vector<uid_t>& appUids) {
234 std::lock_guard guard(mTc.mMutex);
235 EXPECT_EQ(appUids.size(), mTc.mPrivilegedUser.size());
236 for (uid_t uid : appUids) {
237 EXPECT_NE(mTc.mPrivilegedUser.end(), mTc.mPrivilegedUser.find(uid));
238 }
239 }
240
241 void expectPrivilegedUserSetEmpty() {
242 std::lock_guard guard(mTc.mMutex);
243 EXPECT_TRUE(mTc.mPrivilegedUser.empty());
244 }
245
246 void addPrivilegedUid(uid_t uid) {
247 std::vector privilegedUid = {uid};
248 mTc.setPermissionForUids(INetd::PERMISSION_UPDATE_DEVICE_STATS, privilegedUid);
249 }
250
251 void removePrivilegedUid(uid_t uid) {
252 std::vector privilegedUid = {uid};
253 mTc.setPermissionForUids(INetd::PERMISSION_NONE, privilegedUid);
254 }
255
256 void expectFakeStatsUnchanged(uint64_t cookie, uint32_t tag, uint32_t uid,
257 StatsKey tagStatsMapKey) {
258 Result<UidTagValue> cookieMapResult = mFakeCookieTagMap.readValue(cookie);
259 EXPECT_RESULT_OK(cookieMapResult);
260 EXPECT_EQ(uid, cookieMapResult.value().uid);
261 EXPECT_EQ(tag, cookieMapResult.value().tag);
262 Result<uint8_t> counterSetResult = mFakeUidCounterSetMap.readValue(uid);
263 EXPECT_RESULT_OK(counterSetResult);
264 EXPECT_EQ(TEST_COUNTERSET, counterSetResult.value());
265 Result<StatsValue> statsMapResult = mFakeStatsMapA.readValue(tagStatsMapKey);
266 EXPECT_RESULT_OK(statsMapResult);
267 EXPECT_EQ((uint64_t)1, statsMapResult.value().rxPackets);
268 EXPECT_EQ((uint64_t)100, statsMapResult.value().rxBytes);
269 tagStatsMapKey.tag = 0;
270 statsMapResult = mFakeStatsMapA.readValue(tagStatsMapKey);
271 EXPECT_RESULT_OK(statsMapResult);
272 EXPECT_EQ((uint64_t)1, statsMapResult.value().rxPackets);
273 EXPECT_EQ((uint64_t)100, statsMapResult.value().rxBytes);
274 auto appStatsResult = mFakeAppUidStatsMap.readValue(uid);
275 EXPECT_RESULT_OK(appStatsResult);
276 EXPECT_EQ((uint64_t)1, appStatsResult.value().rxPackets);
277 EXPECT_EQ((uint64_t)100, appStatsResult.value().rxBytes);
278 }
Wayne Ma7be6bce2022-01-12 16:29:49 +0800279
280 Status updateUidOwnerMaps(const std::vector<uint32_t>& appUids,
281 UidOwnerMatchType matchType, TrafficController::IptOp op) {
282 Status ret(0);
283 for (auto uid : appUids) {
284 ret = mTc.updateUidOwnerMap(uid, matchType, op);
285 if(!isOk(ret)) break;
286 }
287 return ret;
288 }
289
Wayne Ma4d692332022-01-19 16:04:04 +0800290};
291
Wayne Ma4d692332022-01-19 16:04:04 +0800292TEST_F(TrafficControllerTest, TestSetCounterSet) {
293 uid_t callingUid = TEST_UID2;
294 addPrivilegedUid(callingUid);
295 ASSERT_EQ(0, mTc.setCounterSet(TEST_COUNTERSET, TEST_UID, callingUid));
296 uid_t uid = TEST_UID;
297 Result<uint8_t> counterSetResult = mFakeUidCounterSetMap.readValue(uid);
298 ASSERT_RESULT_OK(counterSetResult);
299 ASSERT_EQ(TEST_COUNTERSET, counterSetResult.value());
300 ASSERT_EQ(0, mTc.setCounterSet(DEFAULT_COUNTERSET, TEST_UID, callingUid));
301 ASSERT_FALSE(mFakeUidCounterSetMap.readValue(uid).ok());
302 expectMapEmpty(mFakeUidCounterSetMap);
303}
304
305TEST_F(TrafficControllerTest, TestSetCounterSetWithoutPermission) {
306 ASSERT_EQ(-EPERM, mTc.setCounterSet(TEST_COUNTERSET, TEST_UID, TEST_UID2));
307 uid_t uid = TEST_UID;
308 ASSERT_FALSE(mFakeUidCounterSetMap.readValue(uid).ok());
309 expectMapEmpty(mFakeUidCounterSetMap);
310}
311
312TEST_F(TrafficControllerTest, TestSetInvalidCounterSet) {
313 uid_t callingUid = TEST_UID2;
314 addPrivilegedUid(callingUid);
315 ASSERT_GT(0, mTc.setCounterSet(OVERFLOW_COUNTERSET, TEST_UID, callingUid));
316 uid_t uid = TEST_UID;
317 ASSERT_FALSE(mFakeUidCounterSetMap.readValue(uid).ok());
318 expectMapEmpty(mFakeUidCounterSetMap);
319}
320
321TEST_F(TrafficControllerTest, TestDeleteTagDataWithoutPermission) {
322 uint64_t cookie = 1;
323 uid_t uid = TEST_UID;
324 uint32_t tag = TEST_TAG;
325 StatsKey tagStatsMapKey;
326 populateFakeStats(cookie, uid, tag, &tagStatsMapKey);
327 ASSERT_EQ(-EPERM, mTc.deleteTagData(0, TEST_UID, TEST_UID2));
328
329 expectFakeStatsUnchanged(cookie, tag, uid, tagStatsMapKey);
330}
331
332TEST_F(TrafficControllerTest, TestDeleteTagData) {
333 uid_t callingUid = TEST_UID2;
334 addPrivilegedUid(callingUid);
335 uint64_t cookie = 1;
336 uid_t uid = TEST_UID;
337 uint32_t tag = TEST_TAG;
338 StatsKey tagStatsMapKey;
339 populateFakeStats(cookie, uid, tag, &tagStatsMapKey);
340 ASSERT_EQ(0, mTc.deleteTagData(TEST_TAG, TEST_UID, callingUid));
341 ASSERT_FALSE(mFakeCookieTagMap.readValue(cookie).ok());
342 Result<uint8_t> counterSetResult = mFakeUidCounterSetMap.readValue(uid);
343 ASSERT_RESULT_OK(counterSetResult);
344 ASSERT_EQ(TEST_COUNTERSET, counterSetResult.value());
345 ASSERT_FALSE(mFakeStatsMapA.readValue(tagStatsMapKey).ok());
346 tagStatsMapKey.tag = 0;
347 Result<StatsValue> statsMapResult = mFakeStatsMapA.readValue(tagStatsMapKey);
348 ASSERT_RESULT_OK(statsMapResult);
349 ASSERT_EQ((uint64_t)1, statsMapResult.value().rxPackets);
350 ASSERT_EQ((uint64_t)100, statsMapResult.value().rxBytes);
351 auto appStatsResult = mFakeAppUidStatsMap.readValue(TEST_UID);
352 ASSERT_RESULT_OK(appStatsResult);
353 ASSERT_EQ((uint64_t)1, appStatsResult.value().rxPackets);
354 ASSERT_EQ((uint64_t)100, appStatsResult.value().rxBytes);
355}
356
357TEST_F(TrafficControllerTest, TestDeleteAllUidData) {
358 uid_t callingUid = TEST_UID2;
359 addPrivilegedUid(callingUid);
360 uint64_t cookie = 1;
361 uid_t uid = TEST_UID;
362 uint32_t tag = TEST_TAG;
363 StatsKey tagStatsMapKey;
364 populateFakeStats(cookie, uid, tag, &tagStatsMapKey);
365 ASSERT_EQ(0, mTc.deleteTagData(0, TEST_UID, callingUid));
366 ASSERT_FALSE(mFakeCookieTagMap.readValue(cookie).ok());
367 ASSERT_FALSE(mFakeUidCounterSetMap.readValue(uid).ok());
368 ASSERT_FALSE(mFakeStatsMapA.readValue(tagStatsMapKey).ok());
369 tagStatsMapKey.tag = 0;
370 ASSERT_FALSE(mFakeStatsMapA.readValue(tagStatsMapKey).ok());
371 ASSERT_FALSE(mFakeAppUidStatsMap.readValue(TEST_UID).ok());
372}
373
374TEST_F(TrafficControllerTest, TestDeleteDataWithTwoTags) {
375 uid_t callingUid = TEST_UID2;
376 addPrivilegedUid(callingUid);
377 uint64_t cookie1 = 1;
378 uint64_t cookie2 = 2;
379 uid_t uid = TEST_UID;
380 uint32_t tag1 = TEST_TAG;
381 uint32_t tag2 = TEST_TAG + 1;
382 StatsKey tagStatsMapKey1;
383 StatsKey tagStatsMapKey2;
384 populateFakeStats(cookie1, uid, tag1, &tagStatsMapKey1);
385 populateFakeStats(cookie2, uid, tag2, &tagStatsMapKey2);
386 ASSERT_EQ(0, mTc.deleteTagData(TEST_TAG, TEST_UID, callingUid));
387 ASSERT_FALSE(mFakeCookieTagMap.readValue(cookie1).ok());
388 Result<UidTagValue> cookieMapResult = mFakeCookieTagMap.readValue(cookie2);
389 ASSERT_RESULT_OK(cookieMapResult);
390 ASSERT_EQ(TEST_UID, cookieMapResult.value().uid);
391 ASSERT_EQ(TEST_TAG + 1, cookieMapResult.value().tag);
392 Result<uint8_t> counterSetResult = mFakeUidCounterSetMap.readValue(uid);
393 ASSERT_RESULT_OK(counterSetResult);
394 ASSERT_EQ(TEST_COUNTERSET, counterSetResult.value());
395 ASSERT_FALSE(mFakeStatsMapA.readValue(tagStatsMapKey1).ok());
396 Result<StatsValue> statsMapResult = mFakeStatsMapA.readValue(tagStatsMapKey2);
397 ASSERT_RESULT_OK(statsMapResult);
398 ASSERT_EQ((uint64_t)1, statsMapResult.value().rxPackets);
399 ASSERT_EQ((uint64_t)100, statsMapResult.value().rxBytes);
400}
401
402TEST_F(TrafficControllerTest, TestDeleteDataWithTwoUids) {
403 uid_t callingUid = TEST_UID2;
404 addPrivilegedUid(callingUid);
405 uint64_t cookie1 = 1;
406 uint64_t cookie2 = 2;
407 uid_t uid1 = TEST_UID;
408 uid_t uid2 = TEST_UID + 1;
409 uint32_t tag = TEST_TAG;
410 StatsKey tagStatsMapKey1;
411 StatsKey tagStatsMapKey2;
412 populateFakeStats(cookie1, uid1, tag, &tagStatsMapKey1);
413 populateFakeStats(cookie2, uid2, tag, &tagStatsMapKey2);
414
415 // Delete the stats of one of the uid. Check if it is properly collected by
416 // removedStats.
417 ASSERT_EQ(0, mTc.deleteTagData(0, uid2, callingUid));
418 ASSERT_FALSE(mFakeCookieTagMap.readValue(cookie2).ok());
419 Result<uint8_t> counterSetResult = mFakeUidCounterSetMap.readValue(uid1);
420 ASSERT_RESULT_OK(counterSetResult);
421 ASSERT_EQ(TEST_COUNTERSET, counterSetResult.value());
422 ASSERT_FALSE(mFakeUidCounterSetMap.readValue(uid2).ok());
423 ASSERT_FALSE(mFakeStatsMapA.readValue(tagStatsMapKey2).ok());
424 tagStatsMapKey2.tag = 0;
425 ASSERT_FALSE(mFakeStatsMapA.readValue(tagStatsMapKey2).ok());
426 ASSERT_FALSE(mFakeAppUidStatsMap.readValue(uid2).ok());
427 tagStatsMapKey1.tag = 0;
428 Result<StatsValue> statsMapResult = mFakeStatsMapA.readValue(tagStatsMapKey1);
429 ASSERT_RESULT_OK(statsMapResult);
430 ASSERT_EQ((uint64_t)1, statsMapResult.value().rxPackets);
431 ASSERT_EQ((uint64_t)100, statsMapResult.value().rxBytes);
432 auto appStatsResult = mFakeAppUidStatsMap.readValue(uid1);
433 ASSERT_RESULT_OK(appStatsResult);
434 ASSERT_EQ((uint64_t)1, appStatsResult.value().rxPackets);
435 ASSERT_EQ((uint64_t)100, appStatsResult.value().rxBytes);
436
437 // Delete the stats of the other uid.
438 ASSERT_EQ(0, mTc.deleteTagData(0, uid1, callingUid));
439 ASSERT_FALSE(mFakeStatsMapA.readValue(tagStatsMapKey1).ok());
440 ASSERT_FALSE(mFakeAppUidStatsMap.readValue(uid1).ok());
441}
442
443TEST_F(TrafficControllerTest, TestUpdateOwnerMapEntry) {
444 uint32_t uid = TEST_UID;
445 ASSERT_TRUE(isOk(mTc.updateOwnerMapEntry(STANDBY_MATCH, uid, DENY, DENYLIST)));
446 Result<UidOwnerValue> value = mFakeUidOwnerMap.readValue(uid);
447 ASSERT_RESULT_OK(value);
448 ASSERT_TRUE(value.value().rule & STANDBY_MATCH);
449
450 ASSERT_TRUE(isOk(mTc.updateOwnerMapEntry(DOZABLE_MATCH, uid, ALLOW, ALLOWLIST)));
451 value = mFakeUidOwnerMap.readValue(uid);
452 ASSERT_RESULT_OK(value);
453 ASSERT_TRUE(value.value().rule & DOZABLE_MATCH);
454
455 ASSERT_TRUE(isOk(mTc.updateOwnerMapEntry(DOZABLE_MATCH, uid, DENY, ALLOWLIST)));
456 value = mFakeUidOwnerMap.readValue(uid);
457 ASSERT_RESULT_OK(value);
458 ASSERT_FALSE(value.value().rule & DOZABLE_MATCH);
459
460 ASSERT_TRUE(isOk(mTc.updateOwnerMapEntry(STANDBY_MATCH, uid, ALLOW, DENYLIST)));
461 ASSERT_FALSE(mFakeUidOwnerMap.readValue(uid).ok());
462
463 uid = TEST_UID2;
464 ASSERT_FALSE(isOk(mTc.updateOwnerMapEntry(STANDBY_MATCH, uid, ALLOW, DENYLIST)));
465 ASSERT_FALSE(mFakeUidOwnerMap.readValue(uid).ok());
466}
467
468TEST_F(TrafficControllerTest, TestChangeUidOwnerRule) {
469 checkUidOwnerRuleForChain(DOZABLE, DOZABLE_MATCH);
470 checkUidOwnerRuleForChain(STANDBY, STANDBY_MATCH);
471 checkUidOwnerRuleForChain(POWERSAVE, POWERSAVE_MATCH);
472 checkUidOwnerRuleForChain(RESTRICTED, RESTRICTED_MATCH);
Robert Horvathd945bf02022-01-27 19:55:16 +0100473 checkUidOwnerRuleForChain(LOW_POWER_STANDBY, LOW_POWER_STANDBY_MATCH);
Wayne Ma4d692332022-01-19 16:04:04 +0800474 ASSERT_EQ(-EINVAL, mTc.changeUidOwnerRule(NONE, TEST_UID, ALLOW, ALLOWLIST));
475 ASSERT_EQ(-EINVAL, mTc.changeUidOwnerRule(INVALID_CHAIN, TEST_UID, ALLOW, ALLOWLIST));
476}
477
478TEST_F(TrafficControllerTest, TestReplaceUidOwnerMap) {
479 std::vector<int32_t> uids = {TEST_UID, TEST_UID2, TEST_UID3};
480 checkUidMapReplace("fw_dozable", uids, DOZABLE_MATCH);
481 checkUidMapReplace("fw_standby", uids, STANDBY_MATCH);
482 checkUidMapReplace("fw_powersave", uids, POWERSAVE_MATCH);
483 checkUidMapReplace("fw_restricted", uids, RESTRICTED_MATCH);
Robert Horvathd945bf02022-01-27 19:55:16 +0100484 checkUidMapReplace("fw_low_power_standby", uids, LOW_POWER_STANDBY_MATCH);
Wayne Ma4d692332022-01-19 16:04:04 +0800485 ASSERT_EQ(-EINVAL, mTc.replaceUidOwnerMap("unknow", true, uids));
486}
487
488TEST_F(TrafficControllerTest, TestReplaceSameChain) {
489 std::vector<int32_t> uids = {TEST_UID, TEST_UID2, TEST_UID3};
490 checkUidMapReplace("fw_dozable", uids, DOZABLE_MATCH);
491 std::vector<int32_t> newUids = {TEST_UID2, TEST_UID3};
492 checkUidMapReplace("fw_dozable", newUids, DOZABLE_MATCH);
493}
494
495TEST_F(TrafficControllerTest, TestDenylistUidMatch) {
496 std::vector<uint32_t> appUids = {1000, 1001, 10012};
Wayne Ma7be6bce2022-01-12 16:29:49 +0800497 ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, PENALTY_BOX_MATCH,
498 TrafficController::IptOpInsert)));
Wayne Ma4d692332022-01-19 16:04:04 +0800499 expectUidOwnerMapValues(appUids, PENALTY_BOX_MATCH, 0);
Wayne Ma7be6bce2022-01-12 16:29:49 +0800500 ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, PENALTY_BOX_MATCH,
501 TrafficController::IptOpDelete)));
Wayne Ma4d692332022-01-19 16:04:04 +0800502 expectMapEmpty(mFakeUidOwnerMap);
503}
504
505TEST_F(TrafficControllerTest, TestAllowlistUidMatch) {
506 std::vector<uint32_t> appUids = {1000, 1001, 10012};
Wayne Ma7be6bce2022-01-12 16:29:49 +0800507 ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, HAPPY_BOX_MATCH, TrafficController::IptOpInsert)));
Wayne Ma4d692332022-01-19 16:04:04 +0800508 expectUidOwnerMapValues(appUids, HAPPY_BOX_MATCH, 0);
Wayne Ma7be6bce2022-01-12 16:29:49 +0800509 ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, HAPPY_BOX_MATCH, TrafficController::IptOpDelete)));
Wayne Ma4d692332022-01-19 16:04:04 +0800510 expectMapEmpty(mFakeUidOwnerMap);
511}
512
513TEST_F(TrafficControllerTest, TestReplaceMatchUid) {
514 std::vector<uint32_t> appUids = {1000, 1001, 10012};
515 // Add appUids to the denylist and expect that their values are all PENALTY_BOX_MATCH.
Wayne Ma7be6bce2022-01-12 16:29:49 +0800516 ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, PENALTY_BOX_MATCH,
517 TrafficController::IptOpInsert)));
Wayne Ma4d692332022-01-19 16:04:04 +0800518 expectUidOwnerMapValues(appUids, PENALTY_BOX_MATCH, 0);
519
520 // Add the same UIDs to the allowlist and expect that we get PENALTY_BOX_MATCH |
521 // HAPPY_BOX_MATCH.
Wayne Ma7be6bce2022-01-12 16:29:49 +0800522 ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, HAPPY_BOX_MATCH, TrafficController::IptOpInsert)));
Wayne Ma4d692332022-01-19 16:04:04 +0800523 expectUidOwnerMapValues(appUids, HAPPY_BOX_MATCH | PENALTY_BOX_MATCH, 0);
524
525 // Remove the same UIDs from the allowlist and check the PENALTY_BOX_MATCH is still there.
Wayne Ma7be6bce2022-01-12 16:29:49 +0800526 ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, HAPPY_BOX_MATCH, TrafficController::IptOpDelete)));
Wayne Ma4d692332022-01-19 16:04:04 +0800527 expectUidOwnerMapValues(appUids, PENALTY_BOX_MATCH, 0);
528
529 // Remove the same UIDs from the denylist and check the map is empty.
Wayne Ma7be6bce2022-01-12 16:29:49 +0800530 ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, PENALTY_BOX_MATCH,
531 TrafficController::IptOpDelete)));
Wayne Ma4d692332022-01-19 16:04:04 +0800532 ASSERT_FALSE(mFakeUidOwnerMap.getFirstKey().ok());
533}
534
535TEST_F(TrafficControllerTest, TestDeleteWrongMatchSilentlyFails) {
536 std::vector<uint32_t> appUids = {1000, 1001, 10012};
537 // 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 +0800538 ASSERT_FALSE(isOk(updateUidOwnerMaps(appUids, HAPPY_BOX_MATCH,
539 TrafficController::IptOpDelete)));
Wayne Ma4d692332022-01-19 16:04:04 +0800540 expectMapEmpty(mFakeUidOwnerMap);
541
542 // Add denylist rules for appUids.
Wayne Ma7be6bce2022-01-12 16:29:49 +0800543 ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, HAPPY_BOX_MATCH,
544 TrafficController::IptOpInsert)));
Wayne Ma4d692332022-01-19 16:04:04 +0800545 expectUidOwnerMapValues(appUids, HAPPY_BOX_MATCH, 0);
546
547 // Delete (non-existent) denylist rules for appUids, and check that this silently does
548 // nothing if the uid is in the map but does not have denylist match. This is required because
549 // NetworkManagementService will try to remove a uid from denylist after adding it to the
550 // allowlist and if the remove fails it will not update the uid status.
Wayne Ma7be6bce2022-01-12 16:29:49 +0800551 ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, PENALTY_BOX_MATCH,
552 TrafficController::IptOpDelete)));
Wayne Ma4d692332022-01-19 16:04:04 +0800553 expectUidOwnerMapValues(appUids, HAPPY_BOX_MATCH, 0);
554}
555
556TEST_F(TrafficControllerTest, TestAddUidInterfaceFilteringRules) {
557 int iif0 = 15;
558 ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif0, {1000, 1001})));
559 expectUidOwnerMapValues({1000, 1001}, IIF_MATCH, iif0);
560
561 // Add some non-overlapping new uids. They should coexist with existing rules
562 int iif1 = 16;
563 ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif1, {2000, 2001})));
564 expectUidOwnerMapValues({1000, 1001}, IIF_MATCH, iif0);
565 expectUidOwnerMapValues({2000, 2001}, IIF_MATCH, iif1);
566
567 // Overwrite some existing uids
568 int iif2 = 17;
569 ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif2, {1000, 2000})));
570 expectUidOwnerMapValues({1001}, IIF_MATCH, iif0);
571 expectUidOwnerMapValues({2001}, IIF_MATCH, iif1);
572 expectUidOwnerMapValues({1000, 2000}, IIF_MATCH, iif2);
573}
574
575TEST_F(TrafficControllerTest, TestRemoveUidInterfaceFilteringRules) {
576 int iif0 = 15;
577 int iif1 = 16;
578 ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif0, {1000, 1001})));
579 ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif1, {2000, 2001})));
580 expectUidOwnerMapValues({1000, 1001}, IIF_MATCH, iif0);
581 expectUidOwnerMapValues({2000, 2001}, IIF_MATCH, iif1);
582
583 // Rmove some uids
584 ASSERT_TRUE(isOk(mTc.removeUidInterfaceRules({1001, 2001})));
585 expectUidOwnerMapValues({1000}, IIF_MATCH, iif0);
586 expectUidOwnerMapValues({2000}, IIF_MATCH, iif1);
587 checkEachUidValue({1000, 2000}, IIF_MATCH); // Make sure there are only two uids remaining
588
589 // Remove non-existent uids shouldn't fail
590 ASSERT_TRUE(isOk(mTc.removeUidInterfaceRules({2000, 3000})));
591 expectUidOwnerMapValues({1000}, IIF_MATCH, iif0);
592 checkEachUidValue({1000}, IIF_MATCH); // Make sure there are only one uid remaining
593
594 // Remove everything
595 ASSERT_TRUE(isOk(mTc.removeUidInterfaceRules({1000})));
596 expectMapEmpty(mFakeUidOwnerMap);
597}
598
599TEST_F(TrafficControllerTest, TestUidInterfaceFilteringRulesCoexistWithExistingMatches) {
600 // Set up existing PENALTY_BOX_MATCH rules
Wayne Ma7be6bce2022-01-12 16:29:49 +0800601 ASSERT_TRUE(isOk(updateUidOwnerMaps({1000, 1001, 10012}, PENALTY_BOX_MATCH,
602 TrafficController::IptOpInsert)));
Wayne Ma4d692332022-01-19 16:04:04 +0800603 expectUidOwnerMapValues({1000, 1001, 10012}, PENALTY_BOX_MATCH, 0);
604
605 // Add some partially-overlapping uid owner rules and check result
606 int iif1 = 32;
607 ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif1, {10012, 10013, 10014})));
608 expectUidOwnerMapValues({1000, 1001}, PENALTY_BOX_MATCH, 0);
609 expectUidOwnerMapValues({10012}, PENALTY_BOX_MATCH | IIF_MATCH, iif1);
610 expectUidOwnerMapValues({10013, 10014}, IIF_MATCH, iif1);
611
612 // Removing some PENALTY_BOX_MATCH rules should not change uid interface rule
Wayne Ma7be6bce2022-01-12 16:29:49 +0800613 ASSERT_TRUE(isOk(updateUidOwnerMaps({1001, 10012}, PENALTY_BOX_MATCH,
614 TrafficController::IptOpDelete)));
Wayne Ma4d692332022-01-19 16:04:04 +0800615 expectUidOwnerMapValues({1000}, PENALTY_BOX_MATCH, 0);
616 expectUidOwnerMapValues({10012, 10013, 10014}, IIF_MATCH, iif1);
617
618 // Remove all uid interface rules
619 ASSERT_TRUE(isOk(mTc.removeUidInterfaceRules({10012, 10013, 10014})));
620 expectUidOwnerMapValues({1000}, PENALTY_BOX_MATCH, 0);
621 // Make sure these are the only uids left
622 checkEachUidValue({1000}, PENALTY_BOX_MATCH);
623}
624
625TEST_F(TrafficControllerTest, TestUidInterfaceFilteringRulesCoexistWithNewMatches) {
626 int iif1 = 56;
627 // Set up existing uid interface rules
628 ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif1, {10001, 10002})));
629 expectUidOwnerMapValues({10001, 10002}, IIF_MATCH, iif1);
630
631 // Add some partially-overlapping doze rules
632 EXPECT_EQ(0, mTc.replaceUidOwnerMap("fw_dozable", true, {10002, 10003}));
633 expectUidOwnerMapValues({10001}, IIF_MATCH, iif1);
634 expectUidOwnerMapValues({10002}, DOZABLE_MATCH | IIF_MATCH, iif1);
635 expectUidOwnerMapValues({10003}, DOZABLE_MATCH, 0);
636
637 // Introduce a third rule type (powersave) on various existing UIDs
638 EXPECT_EQ(0, mTc.replaceUidOwnerMap("fw_powersave", true, {10000, 10001, 10002, 10003}));
639 expectUidOwnerMapValues({10000}, POWERSAVE_MATCH, 0);
640 expectUidOwnerMapValues({10001}, POWERSAVE_MATCH | IIF_MATCH, iif1);
641 expectUidOwnerMapValues({10002}, POWERSAVE_MATCH | DOZABLE_MATCH | IIF_MATCH, iif1);
642 expectUidOwnerMapValues({10003}, POWERSAVE_MATCH | DOZABLE_MATCH, 0);
643
644 // Remove all doze rules
645 EXPECT_EQ(0, mTc.replaceUidOwnerMap("fw_dozable", true, {}));
646 expectUidOwnerMapValues({10000}, POWERSAVE_MATCH, 0);
647 expectUidOwnerMapValues({10001}, POWERSAVE_MATCH | IIF_MATCH, iif1);
648 expectUidOwnerMapValues({10002}, POWERSAVE_MATCH | IIF_MATCH, iif1);
649 expectUidOwnerMapValues({10003}, POWERSAVE_MATCH, 0);
650
651 // Remove all powersave rules, expect ownerMap to only have uid interface rules left
652 EXPECT_EQ(0, mTc.replaceUidOwnerMap("fw_powersave", true, {}));
653 expectUidOwnerMapValues({10001, 10002}, IIF_MATCH, iif1);
654 // Make sure these are the only uids left
655 checkEachUidValue({10001, 10002}, IIF_MATCH);
656}
657
658TEST_F(TrafficControllerTest, TestGrantInternetPermission) {
659 std::vector<uid_t> appUids = {TEST_UID, TEST_UID2, TEST_UID3};
660
661 mTc.setPermissionForUids(INetd::PERMISSION_INTERNET, appUids);
662 expectMapEmpty(mFakeUidPermissionMap);
663 expectPrivilegedUserSetEmpty();
664}
665
666TEST_F(TrafficControllerTest, TestRevokeInternetPermission) {
667 std::vector<uid_t> appUids = {TEST_UID, TEST_UID2, TEST_UID3};
668
669 mTc.setPermissionForUids(INetd::PERMISSION_NONE, appUids);
670 expectUidPermissionMapValues(appUids, INetd::PERMISSION_NONE);
671}
672
673TEST_F(TrafficControllerTest, TestPermissionUninstalled) {
674 std::vector<uid_t> appUids = {TEST_UID, TEST_UID2, TEST_UID3};
675
676 mTc.setPermissionForUids(INetd::PERMISSION_UPDATE_DEVICE_STATS, appUids);
677 expectUidPermissionMapValues(appUids, INetd::PERMISSION_UPDATE_DEVICE_STATS);
678 expectPrivilegedUserSet(appUids);
679
680 std::vector<uid_t> uidToRemove = {TEST_UID};
681 mTc.setPermissionForUids(INetd::PERMISSION_UNINSTALLED, uidToRemove);
682
683 std::vector<uid_t> uidRemain = {TEST_UID3, TEST_UID2};
684 expectUidPermissionMapValues(uidRemain, INetd::PERMISSION_UPDATE_DEVICE_STATS);
685 expectPrivilegedUserSet(uidRemain);
686
687 mTc.setPermissionForUids(INetd::PERMISSION_UNINSTALLED, uidRemain);
688 expectMapEmpty(mFakeUidPermissionMap);
689 expectPrivilegedUserSetEmpty();
690}
691
692TEST_F(TrafficControllerTest, TestGrantUpdateStatsPermission) {
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 mTc.setPermissionForUids(INetd::PERMISSION_NONE, appUids);
700 expectPrivilegedUserSetEmpty();
701 expectUidPermissionMapValues(appUids, INetd::PERMISSION_NONE);
702}
703
704TEST_F(TrafficControllerTest, TestRevokeUpdateStatsPermission) {
705 std::vector<uid_t> appUids = {TEST_UID, TEST_UID2, TEST_UID3};
706
707 mTc.setPermissionForUids(INetd::PERMISSION_UPDATE_DEVICE_STATS, appUids);
708 expectPrivilegedUserSet(appUids);
709
710 std::vector<uid_t> uidToRemove = {TEST_UID};
711 mTc.setPermissionForUids(INetd::PERMISSION_NONE, uidToRemove);
712
713 std::vector<uid_t> uidRemain = {TEST_UID3, TEST_UID2};
714 expectPrivilegedUserSet(uidRemain);
715
716 mTc.setPermissionForUids(INetd::PERMISSION_NONE, uidRemain);
717 expectPrivilegedUserSetEmpty();
718}
719
720TEST_F(TrafficControllerTest, TestGrantWrongPermission) {
721 std::vector<uid_t> appUids = {TEST_UID, TEST_UID2, TEST_UID3};
722
723 mTc.setPermissionForUids(INetd::PERMISSION_NONE, appUids);
724 expectPrivilegedUserSetEmpty();
725 expectUidPermissionMapValues(appUids, INetd::PERMISSION_NONE);
726}
727
728TEST_F(TrafficControllerTest, TestGrantDuplicatePermissionSlientlyFail) {
729 std::vector<uid_t> appUids = {TEST_UID, TEST_UID2, TEST_UID3};
730
731 mTc.setPermissionForUids(INetd::PERMISSION_INTERNET, appUids);
732 expectMapEmpty(mFakeUidPermissionMap);
733
734 std::vector<uid_t> uidToAdd = {TEST_UID};
735 mTc.setPermissionForUids(INetd::PERMISSION_INTERNET, uidToAdd);
736
737 expectPrivilegedUserSetEmpty();
738
739 mTc.setPermissionForUids(INetd::PERMISSION_NONE, appUids);
740 expectUidPermissionMapValues(appUids, INetd::PERMISSION_NONE);
741
742 mTc.setPermissionForUids(INetd::PERMISSION_UPDATE_DEVICE_STATS, appUids);
743 expectPrivilegedUserSet(appUids);
744
745 mTc.setPermissionForUids(INetd::PERMISSION_UPDATE_DEVICE_STATS, uidToAdd);
746 expectPrivilegedUserSet(appUids);
747
748 mTc.setPermissionForUids(INetd::PERMISSION_NONE, appUids);
749 expectPrivilegedUserSetEmpty();
750}
751
Patrick Rohr61e94672022-02-01 21:06:40 +0100752constexpr uint32_t SOCK_CLOSE_WAIT_US = 30 * 1000;
753constexpr uint32_t ENOBUFS_POLL_WAIT_US = 10 * 1000;
754
755using android::base::Error;
756using android::base::Result;
757using android::bpf::BpfMap;
758
759// This test set up a SkDestroyListener that is running parallel with the production
760// SkDestroyListener. The test will create thousands of sockets and tag them on the
761// production cookieUidTagMap and close them in a short time. When the number of
762// sockets get closed exceeds the buffer size, it will start to return ENOBUFF
763// error. The error will be ignored by the production SkDestroyListener and the
764// test will clean up the tags in tearDown if there is any remains.
765
766// TODO: Instead of test the ENOBUFF error, we can test the production
767// SkDestroyListener to see if it failed to delete a tagged socket when ENOBUFF
768// triggered.
769class NetlinkListenerTest : public testing::Test {
770 protected:
771 NetlinkListenerTest() {}
772 BpfMap<uint64_t, UidTagValue> mCookieTagMap;
773
774 void SetUp() {
775 mCookieTagMap.reset(android::bpf::mapRetrieveRW(COOKIE_TAG_MAP_PATH));
776 ASSERT_TRUE(mCookieTagMap.isValid());
777 }
778
779 void TearDown() {
780 const auto deleteTestCookieEntries = [](const uint64_t& key, const UidTagValue& value,
781 BpfMap<uint64_t, UidTagValue>& map) {
782 if ((value.uid == TEST_UID) && (value.tag == TEST_TAG)) {
783 Result<void> res = map.deleteValue(key);
784 if (res.ok() || (res.error().code() == ENOENT)) {
785 return Result<void>();
786 }
787 ALOGE("Failed to delete data(cookie = %" PRIu64 "): %s\n", key,
788 strerror(res.error().code()));
789 }
790 // Move forward to next cookie in the map.
791 return Result<void>();
792 };
793 EXPECT_RESULT_OK(mCookieTagMap.iterateWithValue(deleteTestCookieEntries));
794 }
795
796 Result<void> checkNoGarbageTagsExist() {
797 const auto checkGarbageTags = [](const uint64_t&, const UidTagValue& value,
798 const BpfMap<uint64_t, UidTagValue>&) -> Result<void> {
799 if ((TEST_UID == value.uid) && (TEST_TAG == value.tag)) {
800 return Error(EUCLEAN) << "Closed socket is not untagged";
801 }
802 return {};
803 };
804 return mCookieTagMap.iterateWithValue(checkGarbageTags);
805 }
806
807 bool checkMassiveSocketDestroy(int totalNumber, bool expectError) {
808 std::unique_ptr<android::netdutils::NetlinkListenerInterface> skDestroyListener;
809 auto result = android::net::TrafficController::makeSkDestroyListener();
810 if (!isOk(result)) {
811 ALOGE("Unable to create SkDestroyListener: %s", toString(result).c_str());
812 } else {
813 skDestroyListener = std::move(result.value());
814 }
815 int rxErrorCount = 0;
816 // Rx handler extracts nfgenmsg looks up and invokes registered dispatch function.
817 const auto rxErrorHandler = [&rxErrorCount](const int, const int) { rxErrorCount++; };
818 skDestroyListener->registerSkErrorHandler(rxErrorHandler);
819 int fds[totalNumber];
820 for (int i = 0; i < totalNumber; i++) {
821 fds[i] = socket(AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0);
822 // The likely reason for a failure is running out of available file descriptors.
823 EXPECT_LE(0, fds[i]) << i << " of " << totalNumber;
824 if (fds[i] < 0) {
825 // EXPECT_LE already failed above, so test case is a failure, but we don't
826 // want potentially tens of thousands of extra failures creating and then
827 // closing all these fds cluttering up the logs.
828 totalNumber = i;
829 break;
830 };
831 libnetd_updatable_tagSocket(fds[i], TEST_TAG, TEST_UID, 1000);
832 }
833
834 // TODO: Use a separate thread that has its own fd table so we can
835 // close sockets even faster simply by terminating that thread.
836 for (int i = 0; i < totalNumber; i++) {
837 EXPECT_EQ(0, close(fds[i]));
838 }
839 // wait a bit for netlink listener to handle all the messages.
840 usleep(SOCK_CLOSE_WAIT_US);
841 if (expectError) {
842 // If ENOBUFS triggered, check it only called into the handler once, ie.
843 // that the netlink handler is not spinning.
844 int currentErrorCount = rxErrorCount;
845 // 0 error count is acceptable because the system has chances to close all sockets
846 // normally.
847 EXPECT_LE(0, rxErrorCount);
848 if (!rxErrorCount) return true;
849
850 usleep(ENOBUFS_POLL_WAIT_US);
851 EXPECT_EQ(currentErrorCount, rxErrorCount);
852 } else {
853 EXPECT_RESULT_OK(checkNoGarbageTagsExist());
854 EXPECT_EQ(0, rxErrorCount);
855 }
856 return false;
857 }
858};
859
860TEST_F(NetlinkListenerTest, TestAllSocketUntagged) {
861 checkMassiveSocketDestroy(10, false);
862 checkMassiveSocketDestroy(100, false);
863}
864
865// Disabled because flaky on blueline-userdebug; this test relies on the main thread
866// winning a race against the NetlinkListener::run() thread. There's no way to ensure
867// things will be scheduled the same way across all architectures and test environments.
868TEST_F(NetlinkListenerTest, DISABLED_TestSkDestroyError) {
869 bool needRetry = false;
870 int retryCount = 0;
871 do {
872 needRetry = checkMassiveSocketDestroy(32500, true);
873 if (needRetry) retryCount++;
874 } while (needRetry && retryCount < 3);
875 // Should review test if it can always close all sockets correctly.
876 EXPECT_GT(3, retryCount);
877}
878
879
Wayne Ma4d692332022-01-19 16:04:04 +0800880} // namespace net
881} // namespace android