blob: 9ec50af6ef7dcc6ce31579420fa216a36b50664d [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;
Wayne Ma4d692332022-01-19 16:04:04 +080058
59#define ASSERT_VALID(x) ASSERT_TRUE((x).isValid())
60
61class TrafficControllerTest : public ::testing::Test {
62 protected:
Wayne Ma92d80792022-01-20 13:20:34 +080063 TrafficControllerTest() {}
Wayne Ma4d692332022-01-19 16:04:04 +080064 TrafficController mTc;
65 BpfMap<uint64_t, UidTagValue> mFakeCookieTagMap;
Wayne Ma4d692332022-01-19 16:04:04 +080066 BpfMap<uint32_t, StatsValue> mFakeAppUidStatsMap;
67 BpfMap<StatsKey, StatsValue> mFakeStatsMapA;
Lorenzo Colitti90c0c3f2022-03-03 17:49:01 +090068 BpfMap<uint32_t, uint32_t> mFakeConfigurationMap;
Wayne Ma4d692332022-01-19 16:04:04 +080069 BpfMap<uint32_t, UidOwnerValue> mFakeUidOwnerMap;
70 BpfMap<uint32_t, uint8_t> mFakeUidPermissionMap;
71
72 void SetUp() {
73 std::lock_guard guard(mTc.mMutex);
74 ASSERT_EQ(0, setrlimitForTest());
75
76 mFakeCookieTagMap.reset(createMap(BPF_MAP_TYPE_HASH, sizeof(uint64_t), sizeof(UidTagValue),
77 TEST_MAP_SIZE, 0));
78 ASSERT_VALID(mFakeCookieTagMap);
79
Wayne Ma4d692332022-01-19 16:04:04 +080080 mFakeAppUidStatsMap.reset(createMap(BPF_MAP_TYPE_HASH, sizeof(uint32_t), sizeof(StatsValue),
81 TEST_MAP_SIZE, 0));
82 ASSERT_VALID(mFakeAppUidStatsMap);
83
84 mFakeStatsMapA.reset(createMap(BPF_MAP_TYPE_HASH, sizeof(StatsKey), sizeof(StatsValue),
85 TEST_MAP_SIZE, 0));
86 ASSERT_VALID(mFakeStatsMapA);
87
88 mFakeConfigurationMap.reset(
89 createMap(BPF_MAP_TYPE_HASH, sizeof(uint32_t), sizeof(uint8_t), 1, 0));
90 ASSERT_VALID(mFakeConfigurationMap);
91
92 mFakeUidOwnerMap.reset(createMap(BPF_MAP_TYPE_HASH, sizeof(uint32_t), sizeof(UidOwnerValue),
93 TEST_MAP_SIZE, 0));
94 ASSERT_VALID(mFakeUidOwnerMap);
95 mFakeUidPermissionMap.reset(
96 createMap(BPF_MAP_TYPE_HASH, sizeof(uint32_t), sizeof(uint8_t), TEST_MAP_SIZE, 0));
97 ASSERT_VALID(mFakeUidPermissionMap);
98
99 mTc.mCookieTagMap.reset(dupFd(mFakeCookieTagMap.getMap()));
100 ASSERT_VALID(mTc.mCookieTagMap);
Wayne Ma4d692332022-01-19 16:04:04 +0800101 mTc.mAppUidStatsMap.reset(dupFd(mFakeAppUidStatsMap.getMap()));
102 ASSERT_VALID(mTc.mAppUidStatsMap);
103 mTc.mStatsMapA.reset(dupFd(mFakeStatsMapA.getMap()));
104 ASSERT_VALID(mTc.mStatsMapA);
105 mTc.mConfigurationMap.reset(dupFd(mFakeConfigurationMap.getMap()));
106 ASSERT_VALID(mTc.mConfigurationMap);
107
108 // Always write to stats map A by default.
109 ASSERT_RESULT_OK(mTc.mConfigurationMap.writeValue(CURRENT_STATS_MAP_CONFIGURATION_KEY,
110 SELECT_MAP_A, BPF_ANY));
111 mTc.mUidOwnerMap.reset(dupFd(mFakeUidOwnerMap.getMap()));
112 ASSERT_VALID(mTc.mUidOwnerMap);
113 mTc.mUidPermissionMap.reset(dupFd(mFakeUidPermissionMap.getMap()));
114 ASSERT_VALID(mTc.mUidPermissionMap);
115 mTc.mPrivilegedUser.clear();
116 }
117
118 int dupFd(const android::base::unique_fd& mapFd) {
119 return fcntl(mapFd.get(), F_DUPFD_CLOEXEC, 0);
120 }
121
Wayne Ma4d692332022-01-19 16:04:04 +0800122 void populateFakeStats(uint64_t cookie, uint32_t uid, uint32_t tag, StatsKey* key) {
123 UidTagValue cookieMapkey = {.uid = (uint32_t)uid, .tag = tag};
124 EXPECT_RESULT_OK(mFakeCookieTagMap.writeValue(cookie, cookieMapkey, BPF_ANY));
125 *key = {.uid = uid, .tag = tag, .counterSet = TEST_COUNTERSET, .ifaceIndex = 1};
126 StatsValue statsMapValue = {.rxPackets = 1, .rxBytes = 100};
Wayne Ma4d692332022-01-19 16:04:04 +0800127 EXPECT_RESULT_OK(mFakeStatsMapA.writeValue(*key, statsMapValue, BPF_ANY));
128 key->tag = 0;
129 EXPECT_RESULT_OK(mFakeStatsMapA.writeValue(*key, statsMapValue, BPF_ANY));
130 EXPECT_RESULT_OK(mFakeAppUidStatsMap.writeValue(uid, statsMapValue, BPF_ANY));
131 // put tag information back to statsKey
132 key->tag = tag;
133 }
134
135 void checkUidOwnerRuleForChain(ChildChain chain, UidOwnerMatchType match) {
136 uint32_t uid = TEST_UID;
137 EXPECT_EQ(0, mTc.changeUidOwnerRule(chain, uid, DENY, DENYLIST));
138 Result<UidOwnerValue> value = mFakeUidOwnerMap.readValue(uid);
139 EXPECT_RESULT_OK(value);
140 EXPECT_TRUE(value.value().rule & match);
141
142 uid = TEST_UID2;
143 EXPECT_EQ(0, mTc.changeUidOwnerRule(chain, uid, ALLOW, ALLOWLIST));
144 value = mFakeUidOwnerMap.readValue(uid);
145 EXPECT_RESULT_OK(value);
146 EXPECT_TRUE(value.value().rule & match);
147
148 EXPECT_EQ(0, mTc.changeUidOwnerRule(chain, uid, DENY, ALLOWLIST));
149 value = mFakeUidOwnerMap.readValue(uid);
150 EXPECT_FALSE(value.ok());
151 EXPECT_EQ(ENOENT, value.error().code());
152
153 uid = TEST_UID;
154 EXPECT_EQ(0, mTc.changeUidOwnerRule(chain, uid, ALLOW, DENYLIST));
155 value = mFakeUidOwnerMap.readValue(uid);
156 EXPECT_FALSE(value.ok());
157 EXPECT_EQ(ENOENT, value.error().code());
158
159 uid = TEST_UID3;
160 EXPECT_EQ(-ENOENT, mTc.changeUidOwnerRule(chain, uid, ALLOW, DENYLIST));
161 value = mFakeUidOwnerMap.readValue(uid);
162 EXPECT_FALSE(value.ok());
163 EXPECT_EQ(ENOENT, value.error().code());
164 }
165
166 void checkEachUidValue(const std::vector<int32_t>& uids, UidOwnerMatchType match) {
167 for (uint32_t uid : uids) {
168 Result<UidOwnerValue> value = mFakeUidOwnerMap.readValue(uid);
169 EXPECT_RESULT_OK(value);
170 EXPECT_TRUE(value.value().rule & match);
171 }
172 std::set<uint32_t> uidSet(uids.begin(), uids.end());
173 const auto checkNoOtherUid = [&uidSet](const int32_t& key,
174 const BpfMap<uint32_t, UidOwnerValue>&) {
175 EXPECT_NE(uidSet.end(), uidSet.find(key));
176 return Result<void>();
177 };
178 EXPECT_RESULT_OK(mFakeUidOwnerMap.iterate(checkNoOtherUid));
179 }
180
181 void checkUidMapReplace(const std::string& name, const std::vector<int32_t>& uids,
182 UidOwnerMatchType match) {
183 bool isAllowlist = true;
184 EXPECT_EQ(0, mTc.replaceUidOwnerMap(name, isAllowlist, uids));
185 checkEachUidValue(uids, match);
186
187 isAllowlist = false;
188 EXPECT_EQ(0, mTc.replaceUidOwnerMap(name, isAllowlist, uids));
189 checkEachUidValue(uids, match);
190 }
191
192 void expectUidOwnerMapValues(const std::vector<uint32_t>& appUids, uint8_t expectedRule,
193 uint32_t expectedIif) {
194 for (uint32_t uid : appUids) {
195 Result<UidOwnerValue> value = mFakeUidOwnerMap.readValue(uid);
196 EXPECT_RESULT_OK(value);
197 EXPECT_EQ(expectedRule, value.value().rule)
198 << "Expected rule for UID " << uid << " to be " << expectedRule << ", but was "
199 << value.value().rule;
200 EXPECT_EQ(expectedIif, value.value().iif)
201 << "Expected iif for UID " << uid << " to be " << expectedIif << ", but was "
202 << value.value().iif;
203 }
204 }
205
206 template <class Key, class Value>
207 void expectMapEmpty(BpfMap<Key, Value>& map) {
208 auto isEmpty = map.isEmpty();
209 EXPECT_RESULT_OK(isEmpty);
210 EXPECT_TRUE(isEmpty.value());
211 }
212
213 void expectUidPermissionMapValues(const std::vector<uid_t>& appUids, uint8_t expectedValue) {
214 for (uid_t uid : appUids) {
215 Result<uint8_t> value = mFakeUidPermissionMap.readValue(uid);
216 EXPECT_RESULT_OK(value);
217 EXPECT_EQ(expectedValue, value.value())
218 << "Expected value for UID " << uid << " to be " << expectedValue
219 << ", but was " << value.value();
220 }
221 }
222
223 void expectPrivilegedUserSet(const std::vector<uid_t>& appUids) {
224 std::lock_guard guard(mTc.mMutex);
225 EXPECT_EQ(appUids.size(), mTc.mPrivilegedUser.size());
226 for (uid_t uid : appUids) {
227 EXPECT_NE(mTc.mPrivilegedUser.end(), mTc.mPrivilegedUser.find(uid));
228 }
229 }
230
231 void expectPrivilegedUserSetEmpty() {
232 std::lock_guard guard(mTc.mMutex);
233 EXPECT_TRUE(mTc.mPrivilegedUser.empty());
234 }
235
236 void addPrivilegedUid(uid_t uid) {
237 std::vector privilegedUid = {uid};
238 mTc.setPermissionForUids(INetd::PERMISSION_UPDATE_DEVICE_STATS, privilegedUid);
239 }
240
241 void removePrivilegedUid(uid_t uid) {
242 std::vector privilegedUid = {uid};
243 mTc.setPermissionForUids(INetd::PERMISSION_NONE, privilegedUid);
244 }
245
246 void expectFakeStatsUnchanged(uint64_t cookie, uint32_t tag, uint32_t uid,
247 StatsKey tagStatsMapKey) {
248 Result<UidTagValue> cookieMapResult = mFakeCookieTagMap.readValue(cookie);
249 EXPECT_RESULT_OK(cookieMapResult);
250 EXPECT_EQ(uid, cookieMapResult.value().uid);
251 EXPECT_EQ(tag, cookieMapResult.value().tag);
Wayne Ma4d692332022-01-19 16:04:04 +0800252 Result<StatsValue> statsMapResult = mFakeStatsMapA.readValue(tagStatsMapKey);
253 EXPECT_RESULT_OK(statsMapResult);
254 EXPECT_EQ((uint64_t)1, statsMapResult.value().rxPackets);
255 EXPECT_EQ((uint64_t)100, statsMapResult.value().rxBytes);
256 tagStatsMapKey.tag = 0;
257 statsMapResult = mFakeStatsMapA.readValue(tagStatsMapKey);
258 EXPECT_RESULT_OK(statsMapResult);
259 EXPECT_EQ((uint64_t)1, statsMapResult.value().rxPackets);
260 EXPECT_EQ((uint64_t)100, statsMapResult.value().rxBytes);
261 auto appStatsResult = mFakeAppUidStatsMap.readValue(uid);
262 EXPECT_RESULT_OK(appStatsResult);
263 EXPECT_EQ((uint64_t)1, appStatsResult.value().rxPackets);
264 EXPECT_EQ((uint64_t)100, appStatsResult.value().rxBytes);
265 }
Wayne Ma7be6bce2022-01-12 16:29:49 +0800266
267 Status updateUidOwnerMaps(const std::vector<uint32_t>& appUids,
268 UidOwnerMatchType matchType, TrafficController::IptOp op) {
269 Status ret(0);
270 for (auto uid : appUids) {
271 ret = mTc.updateUidOwnerMap(uid, matchType, op);
272 if(!isOk(ret)) break;
273 }
274 return ret;
275 }
276
Wayne Ma4d692332022-01-19 16:04:04 +0800277};
278
Wayne Ma4d692332022-01-19 16:04:04 +0800279TEST_F(TrafficControllerTest, TestUpdateOwnerMapEntry) {
280 uint32_t uid = TEST_UID;
281 ASSERT_TRUE(isOk(mTc.updateOwnerMapEntry(STANDBY_MATCH, uid, DENY, DENYLIST)));
282 Result<UidOwnerValue> value = mFakeUidOwnerMap.readValue(uid);
283 ASSERT_RESULT_OK(value);
284 ASSERT_TRUE(value.value().rule & STANDBY_MATCH);
285
286 ASSERT_TRUE(isOk(mTc.updateOwnerMapEntry(DOZABLE_MATCH, uid, ALLOW, ALLOWLIST)));
287 value = mFakeUidOwnerMap.readValue(uid);
288 ASSERT_RESULT_OK(value);
289 ASSERT_TRUE(value.value().rule & DOZABLE_MATCH);
290
291 ASSERT_TRUE(isOk(mTc.updateOwnerMapEntry(DOZABLE_MATCH, uid, DENY, ALLOWLIST)));
292 value = mFakeUidOwnerMap.readValue(uid);
293 ASSERT_RESULT_OK(value);
294 ASSERT_FALSE(value.value().rule & DOZABLE_MATCH);
295
296 ASSERT_TRUE(isOk(mTc.updateOwnerMapEntry(STANDBY_MATCH, uid, ALLOW, DENYLIST)));
297 ASSERT_FALSE(mFakeUidOwnerMap.readValue(uid).ok());
298
299 uid = TEST_UID2;
300 ASSERT_FALSE(isOk(mTc.updateOwnerMapEntry(STANDBY_MATCH, uid, ALLOW, DENYLIST)));
301 ASSERT_FALSE(mFakeUidOwnerMap.readValue(uid).ok());
302}
303
304TEST_F(TrafficControllerTest, TestChangeUidOwnerRule) {
305 checkUidOwnerRuleForChain(DOZABLE, DOZABLE_MATCH);
306 checkUidOwnerRuleForChain(STANDBY, STANDBY_MATCH);
307 checkUidOwnerRuleForChain(POWERSAVE, POWERSAVE_MATCH);
308 checkUidOwnerRuleForChain(RESTRICTED, RESTRICTED_MATCH);
Robert Horvathd945bf02022-01-27 19:55:16 +0100309 checkUidOwnerRuleForChain(LOW_POWER_STANDBY, LOW_POWER_STANDBY_MATCH);
Motomu Utsumi966ff7f2022-05-11 05:56:26 +0000310 checkUidOwnerRuleForChain(LOCKDOWN, LOCKDOWN_VPN_MATCH);
Motomu Utsumi9cd47262022-06-01 13:57:27 +0000311 checkUidOwnerRuleForChain(OEM_DENY_1, OEM_DENY_1_MATCH);
312 checkUidOwnerRuleForChain(OEM_DENY_2, OEM_DENY_2_MATCH);
Wayne Ma4d692332022-01-19 16:04:04 +0800313 ASSERT_EQ(-EINVAL, mTc.changeUidOwnerRule(NONE, TEST_UID, ALLOW, ALLOWLIST));
314 ASSERT_EQ(-EINVAL, mTc.changeUidOwnerRule(INVALID_CHAIN, TEST_UID, ALLOW, ALLOWLIST));
315}
316
317TEST_F(TrafficControllerTest, TestReplaceUidOwnerMap) {
318 std::vector<int32_t> uids = {TEST_UID, TEST_UID2, TEST_UID3};
319 checkUidMapReplace("fw_dozable", uids, DOZABLE_MATCH);
320 checkUidMapReplace("fw_standby", uids, STANDBY_MATCH);
321 checkUidMapReplace("fw_powersave", uids, POWERSAVE_MATCH);
322 checkUidMapReplace("fw_restricted", uids, RESTRICTED_MATCH);
Robert Horvathd945bf02022-01-27 19:55:16 +0100323 checkUidMapReplace("fw_low_power_standby", uids, LOW_POWER_STANDBY_MATCH);
Motomu Utsumi9cd47262022-06-01 13:57:27 +0000324 checkUidMapReplace("fw_oem_deny_1", uids, OEM_DENY_1_MATCH);
325 checkUidMapReplace("fw_oem_deny_2", uids, OEM_DENY_2_MATCH);
Wayne Ma4d692332022-01-19 16:04:04 +0800326 ASSERT_EQ(-EINVAL, mTc.replaceUidOwnerMap("unknow", true, uids));
327}
328
329TEST_F(TrafficControllerTest, TestReplaceSameChain) {
330 std::vector<int32_t> uids = {TEST_UID, TEST_UID2, TEST_UID3};
331 checkUidMapReplace("fw_dozable", uids, DOZABLE_MATCH);
332 std::vector<int32_t> newUids = {TEST_UID2, TEST_UID3};
333 checkUidMapReplace("fw_dozable", newUids, DOZABLE_MATCH);
334}
335
336TEST_F(TrafficControllerTest, TestDenylistUidMatch) {
337 std::vector<uint32_t> appUids = {1000, 1001, 10012};
Wayne Ma7be6bce2022-01-12 16:29:49 +0800338 ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, PENALTY_BOX_MATCH,
339 TrafficController::IptOpInsert)));
Wayne Ma4d692332022-01-19 16:04:04 +0800340 expectUidOwnerMapValues(appUids, PENALTY_BOX_MATCH, 0);
Wayne Ma7be6bce2022-01-12 16:29:49 +0800341 ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, PENALTY_BOX_MATCH,
342 TrafficController::IptOpDelete)));
Wayne Ma4d692332022-01-19 16:04:04 +0800343 expectMapEmpty(mFakeUidOwnerMap);
344}
345
346TEST_F(TrafficControllerTest, TestAllowlistUidMatch) {
347 std::vector<uint32_t> appUids = {1000, 1001, 10012};
Wayne Ma7be6bce2022-01-12 16:29:49 +0800348 ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, HAPPY_BOX_MATCH, TrafficController::IptOpInsert)));
Wayne Ma4d692332022-01-19 16:04:04 +0800349 expectUidOwnerMapValues(appUids, HAPPY_BOX_MATCH, 0);
Wayne Ma7be6bce2022-01-12 16:29:49 +0800350 ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, HAPPY_BOX_MATCH, TrafficController::IptOpDelete)));
Wayne Ma4d692332022-01-19 16:04:04 +0800351 expectMapEmpty(mFakeUidOwnerMap);
352}
353
354TEST_F(TrafficControllerTest, TestReplaceMatchUid) {
355 std::vector<uint32_t> appUids = {1000, 1001, 10012};
356 // Add appUids to the denylist and expect that their values are all PENALTY_BOX_MATCH.
Wayne Ma7be6bce2022-01-12 16:29:49 +0800357 ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, PENALTY_BOX_MATCH,
358 TrafficController::IptOpInsert)));
Wayne Ma4d692332022-01-19 16:04:04 +0800359 expectUidOwnerMapValues(appUids, PENALTY_BOX_MATCH, 0);
360
361 // Add the same UIDs to the allowlist and expect that we get PENALTY_BOX_MATCH |
362 // HAPPY_BOX_MATCH.
Wayne Ma7be6bce2022-01-12 16:29:49 +0800363 ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, HAPPY_BOX_MATCH, TrafficController::IptOpInsert)));
Wayne Ma4d692332022-01-19 16:04:04 +0800364 expectUidOwnerMapValues(appUids, HAPPY_BOX_MATCH | PENALTY_BOX_MATCH, 0);
365
366 // Remove the same UIDs from the allowlist and check the PENALTY_BOX_MATCH is still there.
Wayne Ma7be6bce2022-01-12 16:29:49 +0800367 ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, HAPPY_BOX_MATCH, TrafficController::IptOpDelete)));
Wayne Ma4d692332022-01-19 16:04:04 +0800368 expectUidOwnerMapValues(appUids, PENALTY_BOX_MATCH, 0);
369
370 // Remove the same UIDs from the denylist and check the map is empty.
Wayne Ma7be6bce2022-01-12 16:29:49 +0800371 ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, PENALTY_BOX_MATCH,
372 TrafficController::IptOpDelete)));
Wayne Ma4d692332022-01-19 16:04:04 +0800373 ASSERT_FALSE(mFakeUidOwnerMap.getFirstKey().ok());
374}
375
376TEST_F(TrafficControllerTest, TestDeleteWrongMatchSilentlyFails) {
377 std::vector<uint32_t> appUids = {1000, 1001, 10012};
378 // 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 +0800379 ASSERT_FALSE(isOk(updateUidOwnerMaps(appUids, HAPPY_BOX_MATCH,
380 TrafficController::IptOpDelete)));
Wayne Ma4d692332022-01-19 16:04:04 +0800381 expectMapEmpty(mFakeUidOwnerMap);
382
383 // Add denylist rules for appUids.
Wayne Ma7be6bce2022-01-12 16:29:49 +0800384 ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, HAPPY_BOX_MATCH,
385 TrafficController::IptOpInsert)));
Wayne Ma4d692332022-01-19 16:04:04 +0800386 expectUidOwnerMapValues(appUids, HAPPY_BOX_MATCH, 0);
387
388 // Delete (non-existent) denylist rules for appUids, and check that this silently does
389 // nothing if the uid is in the map but does not have denylist match. This is required because
390 // NetworkManagementService will try to remove a uid from denylist after adding it to the
391 // allowlist and if the remove fails it will not update the uid status.
Wayne Ma7be6bce2022-01-12 16:29:49 +0800392 ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, PENALTY_BOX_MATCH,
393 TrafficController::IptOpDelete)));
Wayne Ma4d692332022-01-19 16:04:04 +0800394 expectUidOwnerMapValues(appUids, HAPPY_BOX_MATCH, 0);
395}
396
397TEST_F(TrafficControllerTest, TestAddUidInterfaceFilteringRules) {
398 int iif0 = 15;
399 ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif0, {1000, 1001})));
400 expectUidOwnerMapValues({1000, 1001}, IIF_MATCH, iif0);
401
402 // Add some non-overlapping new uids. They should coexist with existing rules
403 int iif1 = 16;
404 ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif1, {2000, 2001})));
405 expectUidOwnerMapValues({1000, 1001}, IIF_MATCH, iif0);
406 expectUidOwnerMapValues({2000, 2001}, IIF_MATCH, iif1);
407
408 // Overwrite some existing uids
409 int iif2 = 17;
410 ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif2, {1000, 2000})));
411 expectUidOwnerMapValues({1001}, IIF_MATCH, iif0);
412 expectUidOwnerMapValues({2001}, IIF_MATCH, iif1);
413 expectUidOwnerMapValues({1000, 2000}, IIF_MATCH, iif2);
414}
415
416TEST_F(TrafficControllerTest, TestRemoveUidInterfaceFilteringRules) {
417 int iif0 = 15;
418 int iif1 = 16;
419 ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif0, {1000, 1001})));
420 ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif1, {2000, 2001})));
421 expectUidOwnerMapValues({1000, 1001}, IIF_MATCH, iif0);
422 expectUidOwnerMapValues({2000, 2001}, IIF_MATCH, iif1);
423
424 // Rmove some uids
425 ASSERT_TRUE(isOk(mTc.removeUidInterfaceRules({1001, 2001})));
426 expectUidOwnerMapValues({1000}, IIF_MATCH, iif0);
427 expectUidOwnerMapValues({2000}, IIF_MATCH, iif1);
428 checkEachUidValue({1000, 2000}, IIF_MATCH); // Make sure there are only two uids remaining
429
430 // Remove non-existent uids shouldn't fail
431 ASSERT_TRUE(isOk(mTc.removeUidInterfaceRules({2000, 3000})));
432 expectUidOwnerMapValues({1000}, IIF_MATCH, iif0);
433 checkEachUidValue({1000}, IIF_MATCH); // Make sure there are only one uid remaining
434
435 // Remove everything
436 ASSERT_TRUE(isOk(mTc.removeUidInterfaceRules({1000})));
437 expectMapEmpty(mFakeUidOwnerMap);
438}
439
440TEST_F(TrafficControllerTest, TestUidInterfaceFilteringRulesCoexistWithExistingMatches) {
441 // Set up existing PENALTY_BOX_MATCH rules
Wayne Ma7be6bce2022-01-12 16:29:49 +0800442 ASSERT_TRUE(isOk(updateUidOwnerMaps({1000, 1001, 10012}, PENALTY_BOX_MATCH,
443 TrafficController::IptOpInsert)));
Wayne Ma4d692332022-01-19 16:04:04 +0800444 expectUidOwnerMapValues({1000, 1001, 10012}, PENALTY_BOX_MATCH, 0);
445
446 // Add some partially-overlapping uid owner rules and check result
447 int iif1 = 32;
448 ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif1, {10012, 10013, 10014})));
449 expectUidOwnerMapValues({1000, 1001}, PENALTY_BOX_MATCH, 0);
450 expectUidOwnerMapValues({10012}, PENALTY_BOX_MATCH | IIF_MATCH, iif1);
451 expectUidOwnerMapValues({10013, 10014}, IIF_MATCH, iif1);
452
453 // Removing some PENALTY_BOX_MATCH rules should not change uid interface rule
Wayne Ma7be6bce2022-01-12 16:29:49 +0800454 ASSERT_TRUE(isOk(updateUidOwnerMaps({1001, 10012}, PENALTY_BOX_MATCH,
455 TrafficController::IptOpDelete)));
Wayne Ma4d692332022-01-19 16:04:04 +0800456 expectUidOwnerMapValues({1000}, PENALTY_BOX_MATCH, 0);
457 expectUidOwnerMapValues({10012, 10013, 10014}, IIF_MATCH, iif1);
458
459 // Remove all uid interface rules
460 ASSERT_TRUE(isOk(mTc.removeUidInterfaceRules({10012, 10013, 10014})));
461 expectUidOwnerMapValues({1000}, PENALTY_BOX_MATCH, 0);
462 // Make sure these are the only uids left
463 checkEachUidValue({1000}, PENALTY_BOX_MATCH);
464}
465
466TEST_F(TrafficControllerTest, TestUidInterfaceFilteringRulesCoexistWithNewMatches) {
467 int iif1 = 56;
468 // Set up existing uid interface rules
469 ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif1, {10001, 10002})));
470 expectUidOwnerMapValues({10001, 10002}, IIF_MATCH, iif1);
471
472 // Add some partially-overlapping doze rules
473 EXPECT_EQ(0, mTc.replaceUidOwnerMap("fw_dozable", true, {10002, 10003}));
474 expectUidOwnerMapValues({10001}, IIF_MATCH, iif1);
475 expectUidOwnerMapValues({10002}, DOZABLE_MATCH | IIF_MATCH, iif1);
476 expectUidOwnerMapValues({10003}, DOZABLE_MATCH, 0);
477
478 // Introduce a third rule type (powersave) on various existing UIDs
479 EXPECT_EQ(0, mTc.replaceUidOwnerMap("fw_powersave", true, {10000, 10001, 10002, 10003}));
480 expectUidOwnerMapValues({10000}, POWERSAVE_MATCH, 0);
481 expectUidOwnerMapValues({10001}, POWERSAVE_MATCH | IIF_MATCH, iif1);
482 expectUidOwnerMapValues({10002}, POWERSAVE_MATCH | DOZABLE_MATCH | IIF_MATCH, iif1);
483 expectUidOwnerMapValues({10003}, POWERSAVE_MATCH | DOZABLE_MATCH, 0);
484
485 // Remove all doze rules
486 EXPECT_EQ(0, mTc.replaceUidOwnerMap("fw_dozable", true, {}));
487 expectUidOwnerMapValues({10000}, POWERSAVE_MATCH, 0);
488 expectUidOwnerMapValues({10001}, POWERSAVE_MATCH | IIF_MATCH, iif1);
489 expectUidOwnerMapValues({10002}, POWERSAVE_MATCH | IIF_MATCH, iif1);
490 expectUidOwnerMapValues({10003}, POWERSAVE_MATCH, 0);
491
492 // Remove all powersave rules, expect ownerMap to only have uid interface rules left
493 EXPECT_EQ(0, mTc.replaceUidOwnerMap("fw_powersave", true, {}));
494 expectUidOwnerMapValues({10001, 10002}, IIF_MATCH, iif1);
495 // Make sure these are the only uids left
496 checkEachUidValue({10001, 10002}, IIF_MATCH);
497}
498
Motomu Utsumi966ff7f2022-05-11 05:56:26 +0000499TEST_F(TrafficControllerTest, TestAddUidInterfaceFilteringRulesWithWildcard) {
500 // iif=0 is a wildcard
501 int iif = 0;
502 // Add interface rule with wildcard to uids
503 ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif, {1000, 1001})));
504 expectUidOwnerMapValues({1000, 1001}, IIF_MATCH, iif);
505}
506
507TEST_F(TrafficControllerTest, TestRemoveUidInterfaceFilteringRulesWithWildcard) {
508 // iif=0 is a wildcard
509 int iif = 0;
510 // Add interface rule with wildcard to two uids
511 ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif, {1000, 1001})));
512 expectUidOwnerMapValues({1000, 1001}, IIF_MATCH, iif);
513
514 // Remove interface rule from one of the uids
515 ASSERT_TRUE(isOk(mTc.removeUidInterfaceRules({1000})));
516 expectUidOwnerMapValues({1001}, IIF_MATCH, iif);
517 checkEachUidValue({1001}, IIF_MATCH);
518
519 // Remove interface rule from the remaining uid
520 ASSERT_TRUE(isOk(mTc.removeUidInterfaceRules({1001})));
521 expectMapEmpty(mFakeUidOwnerMap);
522}
523
524TEST_F(TrafficControllerTest, TestUidInterfaceFilteringRulesWithWildcardAndExistingMatches) {
525 // Set up existing DOZABLE_MATCH and POWERSAVE_MATCH rule
526 ASSERT_TRUE(isOk(updateUidOwnerMaps({1000}, DOZABLE_MATCH,
527 TrafficController::IptOpInsert)));
528 ASSERT_TRUE(isOk(updateUidOwnerMaps({1000}, POWERSAVE_MATCH,
529 TrafficController::IptOpInsert)));
530
531 // iif=0 is a wildcard
532 int iif = 0;
533 // Add interface rule with wildcard to the existing uid
534 ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif, {1000})));
535 expectUidOwnerMapValues({1000}, POWERSAVE_MATCH | DOZABLE_MATCH | IIF_MATCH, iif);
536
537 // Remove interface rule with wildcard from the existing uid
538 ASSERT_TRUE(isOk(mTc.removeUidInterfaceRules({1000})));
539 expectUidOwnerMapValues({1000}, POWERSAVE_MATCH | DOZABLE_MATCH, 0);
540}
541
542TEST_F(TrafficControllerTest, TestUidInterfaceFilteringRulesWithWildcardAndNewMatches) {
543 // iif=0 is a wildcard
544 int iif = 0;
545 // Set up existing interface rule with wildcard
546 ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif, {1000})));
547
548 // Add DOZABLE_MATCH and POWERSAVE_MATCH rule to the existing uid
549 ASSERT_TRUE(isOk(updateUidOwnerMaps({1000}, DOZABLE_MATCH,
550 TrafficController::IptOpInsert)));
551 ASSERT_TRUE(isOk(updateUidOwnerMaps({1000}, POWERSAVE_MATCH,
552 TrafficController::IptOpInsert)));
553 expectUidOwnerMapValues({1000}, POWERSAVE_MATCH | DOZABLE_MATCH | IIF_MATCH, iif);
554
555 // Remove DOZABLE_MATCH and POWERSAVE_MATCH rule from the existing uid
556 ASSERT_TRUE(isOk(updateUidOwnerMaps({1000}, DOZABLE_MATCH,
557 TrafficController::IptOpDelete)));
558 ASSERT_TRUE(isOk(updateUidOwnerMaps({1000}, POWERSAVE_MATCH,
559 TrafficController::IptOpDelete)));
560 expectUidOwnerMapValues({1000}, IIF_MATCH, iif);
561}
562
Wayne Ma4d692332022-01-19 16:04:04 +0800563TEST_F(TrafficControllerTest, TestGrantInternetPermission) {
564 std::vector<uid_t> appUids = {TEST_UID, TEST_UID2, TEST_UID3};
565
566 mTc.setPermissionForUids(INetd::PERMISSION_INTERNET, appUids);
567 expectMapEmpty(mFakeUidPermissionMap);
568 expectPrivilegedUserSetEmpty();
569}
570
571TEST_F(TrafficControllerTest, TestRevokeInternetPermission) {
572 std::vector<uid_t> appUids = {TEST_UID, TEST_UID2, TEST_UID3};
573
574 mTc.setPermissionForUids(INetd::PERMISSION_NONE, appUids);
575 expectUidPermissionMapValues(appUids, INetd::PERMISSION_NONE);
576}
577
578TEST_F(TrafficControllerTest, TestPermissionUninstalled) {
579 std::vector<uid_t> appUids = {TEST_UID, TEST_UID2, TEST_UID3};
580
581 mTc.setPermissionForUids(INetd::PERMISSION_UPDATE_DEVICE_STATS, appUids);
582 expectUidPermissionMapValues(appUids, INetd::PERMISSION_UPDATE_DEVICE_STATS);
583 expectPrivilegedUserSet(appUids);
584
585 std::vector<uid_t> uidToRemove = {TEST_UID};
586 mTc.setPermissionForUids(INetd::PERMISSION_UNINSTALLED, uidToRemove);
587
588 std::vector<uid_t> uidRemain = {TEST_UID3, TEST_UID2};
589 expectUidPermissionMapValues(uidRemain, INetd::PERMISSION_UPDATE_DEVICE_STATS);
590 expectPrivilegedUserSet(uidRemain);
591
592 mTc.setPermissionForUids(INetd::PERMISSION_UNINSTALLED, uidRemain);
593 expectMapEmpty(mFakeUidPermissionMap);
594 expectPrivilegedUserSetEmpty();
595}
596
597TEST_F(TrafficControllerTest, TestGrantUpdateStatsPermission) {
598 std::vector<uid_t> appUids = {TEST_UID, TEST_UID2, TEST_UID3};
599
600 mTc.setPermissionForUids(INetd::PERMISSION_UPDATE_DEVICE_STATS, appUids);
601 expectUidPermissionMapValues(appUids, INetd::PERMISSION_UPDATE_DEVICE_STATS);
602 expectPrivilegedUserSet(appUids);
603
604 mTc.setPermissionForUids(INetd::PERMISSION_NONE, appUids);
605 expectPrivilegedUserSetEmpty();
606 expectUidPermissionMapValues(appUids, INetd::PERMISSION_NONE);
607}
608
609TEST_F(TrafficControllerTest, TestRevokeUpdateStatsPermission) {
610 std::vector<uid_t> appUids = {TEST_UID, TEST_UID2, TEST_UID3};
611
612 mTc.setPermissionForUids(INetd::PERMISSION_UPDATE_DEVICE_STATS, appUids);
613 expectPrivilegedUserSet(appUids);
614
615 std::vector<uid_t> uidToRemove = {TEST_UID};
616 mTc.setPermissionForUids(INetd::PERMISSION_NONE, uidToRemove);
617
618 std::vector<uid_t> uidRemain = {TEST_UID3, TEST_UID2};
619 expectPrivilegedUserSet(uidRemain);
620
621 mTc.setPermissionForUids(INetd::PERMISSION_NONE, uidRemain);
622 expectPrivilegedUserSetEmpty();
623}
624
625TEST_F(TrafficControllerTest, TestGrantWrongPermission) {
626 std::vector<uid_t> appUids = {TEST_UID, TEST_UID2, TEST_UID3};
627
628 mTc.setPermissionForUids(INetd::PERMISSION_NONE, appUids);
629 expectPrivilegedUserSetEmpty();
630 expectUidPermissionMapValues(appUids, INetd::PERMISSION_NONE);
631}
632
633TEST_F(TrafficControllerTest, TestGrantDuplicatePermissionSlientlyFail) {
634 std::vector<uid_t> appUids = {TEST_UID, TEST_UID2, TEST_UID3};
635
636 mTc.setPermissionForUids(INetd::PERMISSION_INTERNET, appUids);
637 expectMapEmpty(mFakeUidPermissionMap);
638
639 std::vector<uid_t> uidToAdd = {TEST_UID};
640 mTc.setPermissionForUids(INetd::PERMISSION_INTERNET, uidToAdd);
641
642 expectPrivilegedUserSetEmpty();
643
644 mTc.setPermissionForUids(INetd::PERMISSION_NONE, appUids);
645 expectUidPermissionMapValues(appUids, INetd::PERMISSION_NONE);
646
647 mTc.setPermissionForUids(INetd::PERMISSION_UPDATE_DEVICE_STATS, appUids);
648 expectPrivilegedUserSet(appUids);
649
650 mTc.setPermissionForUids(INetd::PERMISSION_UPDATE_DEVICE_STATS, uidToAdd);
651 expectPrivilegedUserSet(appUids);
652
653 mTc.setPermissionForUids(INetd::PERMISSION_NONE, appUids);
654 expectPrivilegedUserSetEmpty();
655}
656
Patrick Rohr61e94672022-02-01 21:06:40 +0100657constexpr uint32_t SOCK_CLOSE_WAIT_US = 30 * 1000;
658constexpr uint32_t ENOBUFS_POLL_WAIT_US = 10 * 1000;
659
660using android::base::Error;
661using android::base::Result;
662using android::bpf::BpfMap;
663
664// This test set up a SkDestroyListener that is running parallel with the production
665// SkDestroyListener. The test will create thousands of sockets and tag them on the
666// production cookieUidTagMap and close them in a short time. When the number of
667// sockets get closed exceeds the buffer size, it will start to return ENOBUFF
668// error. The error will be ignored by the production SkDestroyListener and the
669// test will clean up the tags in tearDown if there is any remains.
670
671// TODO: Instead of test the ENOBUFF error, we can test the production
672// SkDestroyListener to see if it failed to delete a tagged socket when ENOBUFF
673// triggered.
674class NetlinkListenerTest : public testing::Test {
675 protected:
676 NetlinkListenerTest() {}
677 BpfMap<uint64_t, UidTagValue> mCookieTagMap;
678
679 void SetUp() {
680 mCookieTagMap.reset(android::bpf::mapRetrieveRW(COOKIE_TAG_MAP_PATH));
681 ASSERT_TRUE(mCookieTagMap.isValid());
682 }
683
684 void TearDown() {
685 const auto deleteTestCookieEntries = [](const uint64_t& key, const UidTagValue& value,
686 BpfMap<uint64_t, UidTagValue>& map) {
687 if ((value.uid == TEST_UID) && (value.tag == TEST_TAG)) {
688 Result<void> res = map.deleteValue(key);
689 if (res.ok() || (res.error().code() == ENOENT)) {
690 return Result<void>();
691 }
692 ALOGE("Failed to delete data(cookie = %" PRIu64 "): %s\n", key,
693 strerror(res.error().code()));
694 }
695 // Move forward to next cookie in the map.
696 return Result<void>();
697 };
698 EXPECT_RESULT_OK(mCookieTagMap.iterateWithValue(deleteTestCookieEntries));
699 }
700
701 Result<void> checkNoGarbageTagsExist() {
702 const auto checkGarbageTags = [](const uint64_t&, const UidTagValue& value,
703 const BpfMap<uint64_t, UidTagValue>&) -> Result<void> {
704 if ((TEST_UID == value.uid) && (TEST_TAG == value.tag)) {
705 return Error(EUCLEAN) << "Closed socket is not untagged";
706 }
707 return {};
708 };
709 return mCookieTagMap.iterateWithValue(checkGarbageTags);
710 }
711
712 bool checkMassiveSocketDestroy(int totalNumber, bool expectError) {
713 std::unique_ptr<android::netdutils::NetlinkListenerInterface> skDestroyListener;
714 auto result = android::net::TrafficController::makeSkDestroyListener();
715 if (!isOk(result)) {
716 ALOGE("Unable to create SkDestroyListener: %s", toString(result).c_str());
717 } else {
718 skDestroyListener = std::move(result.value());
719 }
720 int rxErrorCount = 0;
721 // Rx handler extracts nfgenmsg looks up and invokes registered dispatch function.
722 const auto rxErrorHandler = [&rxErrorCount](const int, const int) { rxErrorCount++; };
723 skDestroyListener->registerSkErrorHandler(rxErrorHandler);
724 int fds[totalNumber];
725 for (int i = 0; i < totalNumber; i++) {
726 fds[i] = socket(AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0);
727 // The likely reason for a failure is running out of available file descriptors.
728 EXPECT_LE(0, fds[i]) << i << " of " << totalNumber;
729 if (fds[i] < 0) {
730 // EXPECT_LE already failed above, so test case is a failure, but we don't
731 // want potentially tens of thousands of extra failures creating and then
732 // closing all these fds cluttering up the logs.
733 totalNumber = i;
734 break;
735 };
736 libnetd_updatable_tagSocket(fds[i], TEST_TAG, TEST_UID, 1000);
737 }
738
739 // TODO: Use a separate thread that has its own fd table so we can
740 // close sockets even faster simply by terminating that thread.
741 for (int i = 0; i < totalNumber; i++) {
742 EXPECT_EQ(0, close(fds[i]));
743 }
744 // wait a bit for netlink listener to handle all the messages.
745 usleep(SOCK_CLOSE_WAIT_US);
746 if (expectError) {
747 // If ENOBUFS triggered, check it only called into the handler once, ie.
748 // that the netlink handler is not spinning.
749 int currentErrorCount = rxErrorCount;
750 // 0 error count is acceptable because the system has chances to close all sockets
751 // normally.
752 EXPECT_LE(0, rxErrorCount);
753 if (!rxErrorCount) return true;
754
755 usleep(ENOBUFS_POLL_WAIT_US);
756 EXPECT_EQ(currentErrorCount, rxErrorCount);
757 } else {
758 EXPECT_RESULT_OK(checkNoGarbageTagsExist());
759 EXPECT_EQ(0, rxErrorCount);
760 }
761 return false;
762 }
763};
764
765TEST_F(NetlinkListenerTest, TestAllSocketUntagged) {
766 checkMassiveSocketDestroy(10, false);
767 checkMassiveSocketDestroy(100, false);
768}
769
770// Disabled because flaky on blueline-userdebug; this test relies on the main thread
771// winning a race against the NetlinkListener::run() thread. There's no way to ensure
772// things will be scheduled the same way across all architectures and test environments.
773TEST_F(NetlinkListenerTest, DISABLED_TestSkDestroyError) {
774 bool needRetry = false;
775 int retryCount = 0;
776 do {
777 needRetry = checkMassiveSocketDestroy(32500, true);
778 if (needRetry) retryCount++;
779 } while (needRetry && retryCount < 3);
780 // Should review test if it can always close all sockets correctly.
781 EXPECT_GT(3, retryCount);
782}
783
784
Wayne Ma4d692332022-01-19 16:04:04 +0800785} // namespace net
786} // namespace android