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