blob: afb55689bd450cc9be7f51be72c6d4a6fedae008 [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;
68 BpfMap<uint32_t, uint8_t> mFakeConfigurationMap;
69 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 Żenczykowski55ab87a2022-05-31 03:15:12 -070099 mTc.mCookieTagMap = mFakeCookieTagMap;
Wayne Ma4d692332022-01-19 16:04:04 +0800100 ASSERT_VALID(mTc.mCookieTagMap);
Maciej Żenczykowski55ab87a2022-05-31 03:15:12 -0700101 mTc.mAppUidStatsMap = mFakeAppUidStatsMap;
Wayne Ma4d692332022-01-19 16:04:04 +0800102 ASSERT_VALID(mTc.mAppUidStatsMap);
Maciej Żenczykowski55ab87a2022-05-31 03:15:12 -0700103 mTc.mStatsMapA = mFakeStatsMapA;
Wayne Ma4d692332022-01-19 16:04:04 +0800104 ASSERT_VALID(mTc.mStatsMapA);
Maciej Żenczykowski55ab87a2022-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 Żenczykowski55ab87a2022-05-31 03:15:12 -0700111 mTc.mUidOwnerMap = mFakeUidOwnerMap;
Wayne Ma4d692332022-01-19 16:04:04 +0800112 ASSERT_VALID(mTc.mUidOwnerMap);
Maciej Żenczykowski55ab87a2022-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 Utsumib08654c2022-05-11 05:56:26 +0000306 checkUidOwnerRuleForChain(LOCKDOWN, LOCKDOWN_VPN_MATCH);
Wayne Ma4d692332022-01-19 16:04:04 +0800307 ASSERT_EQ(-EINVAL, mTc.changeUidOwnerRule(NONE, TEST_UID, ALLOW, ALLOWLIST));
308 ASSERT_EQ(-EINVAL, mTc.changeUidOwnerRule(INVALID_CHAIN, TEST_UID, ALLOW, ALLOWLIST));
309}
310
311TEST_F(TrafficControllerTest, TestReplaceUidOwnerMap) {
312 std::vector<int32_t> uids = {TEST_UID, TEST_UID2, TEST_UID3};
313 checkUidMapReplace("fw_dozable", uids, DOZABLE_MATCH);
314 checkUidMapReplace("fw_standby", uids, STANDBY_MATCH);
315 checkUidMapReplace("fw_powersave", uids, POWERSAVE_MATCH);
316 checkUidMapReplace("fw_restricted", uids, RESTRICTED_MATCH);
Robert Horvathd945bf02022-01-27 19:55:16 +0100317 checkUidMapReplace("fw_low_power_standby", uids, LOW_POWER_STANDBY_MATCH);
Wayne Ma4d692332022-01-19 16:04:04 +0800318 ASSERT_EQ(-EINVAL, mTc.replaceUidOwnerMap("unknow", true, uids));
319}
320
321TEST_F(TrafficControllerTest, TestReplaceSameChain) {
322 std::vector<int32_t> uids = {TEST_UID, TEST_UID2, TEST_UID3};
323 checkUidMapReplace("fw_dozable", uids, DOZABLE_MATCH);
324 std::vector<int32_t> newUids = {TEST_UID2, TEST_UID3};
325 checkUidMapReplace("fw_dozable", newUids, DOZABLE_MATCH);
326}
327
328TEST_F(TrafficControllerTest, TestDenylistUidMatch) {
329 std::vector<uint32_t> appUids = {1000, 1001, 10012};
Wayne Ma7be6bce2022-01-12 16:29:49 +0800330 ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, PENALTY_BOX_MATCH,
331 TrafficController::IptOpInsert)));
Wayne Ma4d692332022-01-19 16:04:04 +0800332 expectUidOwnerMapValues(appUids, PENALTY_BOX_MATCH, 0);
Wayne Ma7be6bce2022-01-12 16:29:49 +0800333 ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, PENALTY_BOX_MATCH,
334 TrafficController::IptOpDelete)));
Wayne Ma4d692332022-01-19 16:04:04 +0800335 expectMapEmpty(mFakeUidOwnerMap);
336}
337
338TEST_F(TrafficControllerTest, TestAllowlistUidMatch) {
339 std::vector<uint32_t> appUids = {1000, 1001, 10012};
Wayne Ma7be6bce2022-01-12 16:29:49 +0800340 ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, HAPPY_BOX_MATCH, TrafficController::IptOpInsert)));
Wayne Ma4d692332022-01-19 16:04:04 +0800341 expectUidOwnerMapValues(appUids, HAPPY_BOX_MATCH, 0);
Wayne Ma7be6bce2022-01-12 16:29:49 +0800342 ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, HAPPY_BOX_MATCH, TrafficController::IptOpDelete)));
Wayne Ma4d692332022-01-19 16:04:04 +0800343 expectMapEmpty(mFakeUidOwnerMap);
344}
345
346TEST_F(TrafficControllerTest, TestReplaceMatchUid) {
347 std::vector<uint32_t> appUids = {1000, 1001, 10012};
348 // Add appUids to the denylist and expect that their values are all PENALTY_BOX_MATCH.
Wayne Ma7be6bce2022-01-12 16:29:49 +0800349 ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, PENALTY_BOX_MATCH,
350 TrafficController::IptOpInsert)));
Wayne Ma4d692332022-01-19 16:04:04 +0800351 expectUidOwnerMapValues(appUids, PENALTY_BOX_MATCH, 0);
352
353 // Add the same UIDs to the allowlist and expect that we get PENALTY_BOX_MATCH |
354 // HAPPY_BOX_MATCH.
Wayne Ma7be6bce2022-01-12 16:29:49 +0800355 ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, HAPPY_BOX_MATCH, TrafficController::IptOpInsert)));
Wayne Ma4d692332022-01-19 16:04:04 +0800356 expectUidOwnerMapValues(appUids, HAPPY_BOX_MATCH | PENALTY_BOX_MATCH, 0);
357
358 // Remove the same UIDs from the allowlist and check the PENALTY_BOX_MATCH is still there.
Wayne Ma7be6bce2022-01-12 16:29:49 +0800359 ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, HAPPY_BOX_MATCH, TrafficController::IptOpDelete)));
Wayne Ma4d692332022-01-19 16:04:04 +0800360 expectUidOwnerMapValues(appUids, PENALTY_BOX_MATCH, 0);
361
362 // Remove the same UIDs from the denylist and check the map is empty.
Wayne Ma7be6bce2022-01-12 16:29:49 +0800363 ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, PENALTY_BOX_MATCH,
364 TrafficController::IptOpDelete)));
Wayne Ma4d692332022-01-19 16:04:04 +0800365 ASSERT_FALSE(mFakeUidOwnerMap.getFirstKey().ok());
366}
367
368TEST_F(TrafficControllerTest, TestDeleteWrongMatchSilentlyFails) {
369 std::vector<uint32_t> appUids = {1000, 1001, 10012};
370 // 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 +0800371 ASSERT_FALSE(isOk(updateUidOwnerMaps(appUids, HAPPY_BOX_MATCH,
372 TrafficController::IptOpDelete)));
Wayne Ma4d692332022-01-19 16:04:04 +0800373 expectMapEmpty(mFakeUidOwnerMap);
374
375 // Add denylist rules for appUids.
Wayne Ma7be6bce2022-01-12 16:29:49 +0800376 ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, HAPPY_BOX_MATCH,
377 TrafficController::IptOpInsert)));
Wayne Ma4d692332022-01-19 16:04:04 +0800378 expectUidOwnerMapValues(appUids, HAPPY_BOX_MATCH, 0);
379
380 // Delete (non-existent) denylist rules for appUids, and check that this silently does
381 // nothing if the uid is in the map but does not have denylist match. This is required because
382 // NetworkManagementService will try to remove a uid from denylist after adding it to the
383 // allowlist and if the remove fails it will not update the uid status.
Wayne Ma7be6bce2022-01-12 16:29:49 +0800384 ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, PENALTY_BOX_MATCH,
385 TrafficController::IptOpDelete)));
Wayne Ma4d692332022-01-19 16:04:04 +0800386 expectUidOwnerMapValues(appUids, HAPPY_BOX_MATCH, 0);
387}
388
389TEST_F(TrafficControllerTest, TestAddUidInterfaceFilteringRules) {
390 int iif0 = 15;
391 ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif0, {1000, 1001})));
392 expectUidOwnerMapValues({1000, 1001}, IIF_MATCH, iif0);
393
394 // Add some non-overlapping new uids. They should coexist with existing rules
395 int iif1 = 16;
396 ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif1, {2000, 2001})));
397 expectUidOwnerMapValues({1000, 1001}, IIF_MATCH, iif0);
398 expectUidOwnerMapValues({2000, 2001}, IIF_MATCH, iif1);
399
400 // Overwrite some existing uids
401 int iif2 = 17;
402 ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif2, {1000, 2000})));
403 expectUidOwnerMapValues({1001}, IIF_MATCH, iif0);
404 expectUidOwnerMapValues({2001}, IIF_MATCH, iif1);
405 expectUidOwnerMapValues({1000, 2000}, IIF_MATCH, iif2);
406}
407
408TEST_F(TrafficControllerTest, TestRemoveUidInterfaceFilteringRules) {
409 int iif0 = 15;
410 int iif1 = 16;
411 ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif0, {1000, 1001})));
412 ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif1, {2000, 2001})));
413 expectUidOwnerMapValues({1000, 1001}, IIF_MATCH, iif0);
414 expectUidOwnerMapValues({2000, 2001}, IIF_MATCH, iif1);
415
416 // Rmove some uids
417 ASSERT_TRUE(isOk(mTc.removeUidInterfaceRules({1001, 2001})));
418 expectUidOwnerMapValues({1000}, IIF_MATCH, iif0);
419 expectUidOwnerMapValues({2000}, IIF_MATCH, iif1);
420 checkEachUidValue({1000, 2000}, IIF_MATCH); // Make sure there are only two uids remaining
421
422 // Remove non-existent uids shouldn't fail
423 ASSERT_TRUE(isOk(mTc.removeUidInterfaceRules({2000, 3000})));
424 expectUidOwnerMapValues({1000}, IIF_MATCH, iif0);
425 checkEachUidValue({1000}, IIF_MATCH); // Make sure there are only one uid remaining
426
427 // Remove everything
428 ASSERT_TRUE(isOk(mTc.removeUidInterfaceRules({1000})));
429 expectMapEmpty(mFakeUidOwnerMap);
430}
431
432TEST_F(TrafficControllerTest, TestUidInterfaceFilteringRulesCoexistWithExistingMatches) {
433 // Set up existing PENALTY_BOX_MATCH rules
Wayne Ma7be6bce2022-01-12 16:29:49 +0800434 ASSERT_TRUE(isOk(updateUidOwnerMaps({1000, 1001, 10012}, PENALTY_BOX_MATCH,
435 TrafficController::IptOpInsert)));
Wayne Ma4d692332022-01-19 16:04:04 +0800436 expectUidOwnerMapValues({1000, 1001, 10012}, PENALTY_BOX_MATCH, 0);
437
438 // Add some partially-overlapping uid owner rules and check result
439 int iif1 = 32;
440 ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif1, {10012, 10013, 10014})));
441 expectUidOwnerMapValues({1000, 1001}, PENALTY_BOX_MATCH, 0);
442 expectUidOwnerMapValues({10012}, PENALTY_BOX_MATCH | IIF_MATCH, iif1);
443 expectUidOwnerMapValues({10013, 10014}, IIF_MATCH, iif1);
444
445 // Removing some PENALTY_BOX_MATCH rules should not change uid interface rule
Wayne Ma7be6bce2022-01-12 16:29:49 +0800446 ASSERT_TRUE(isOk(updateUidOwnerMaps({1001, 10012}, PENALTY_BOX_MATCH,
447 TrafficController::IptOpDelete)));
Wayne Ma4d692332022-01-19 16:04:04 +0800448 expectUidOwnerMapValues({1000}, PENALTY_BOX_MATCH, 0);
449 expectUidOwnerMapValues({10012, 10013, 10014}, IIF_MATCH, iif1);
450
451 // Remove all uid interface rules
452 ASSERT_TRUE(isOk(mTc.removeUidInterfaceRules({10012, 10013, 10014})));
453 expectUidOwnerMapValues({1000}, PENALTY_BOX_MATCH, 0);
454 // Make sure these are the only uids left
455 checkEachUidValue({1000}, PENALTY_BOX_MATCH);
456}
457
458TEST_F(TrafficControllerTest, TestUidInterfaceFilteringRulesCoexistWithNewMatches) {
459 int iif1 = 56;
460 // Set up existing uid interface rules
461 ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif1, {10001, 10002})));
462 expectUidOwnerMapValues({10001, 10002}, IIF_MATCH, iif1);
463
464 // Add some partially-overlapping doze rules
465 EXPECT_EQ(0, mTc.replaceUidOwnerMap("fw_dozable", true, {10002, 10003}));
466 expectUidOwnerMapValues({10001}, IIF_MATCH, iif1);
467 expectUidOwnerMapValues({10002}, DOZABLE_MATCH | IIF_MATCH, iif1);
468 expectUidOwnerMapValues({10003}, DOZABLE_MATCH, 0);
469
470 // Introduce a third rule type (powersave) on various existing UIDs
471 EXPECT_EQ(0, mTc.replaceUidOwnerMap("fw_powersave", true, {10000, 10001, 10002, 10003}));
472 expectUidOwnerMapValues({10000}, POWERSAVE_MATCH, 0);
473 expectUidOwnerMapValues({10001}, POWERSAVE_MATCH | IIF_MATCH, iif1);
474 expectUidOwnerMapValues({10002}, POWERSAVE_MATCH | DOZABLE_MATCH | IIF_MATCH, iif1);
475 expectUidOwnerMapValues({10003}, POWERSAVE_MATCH | DOZABLE_MATCH, 0);
476
477 // Remove all doze rules
478 EXPECT_EQ(0, mTc.replaceUidOwnerMap("fw_dozable", true, {}));
479 expectUidOwnerMapValues({10000}, POWERSAVE_MATCH, 0);
480 expectUidOwnerMapValues({10001}, POWERSAVE_MATCH | IIF_MATCH, iif1);
481 expectUidOwnerMapValues({10002}, POWERSAVE_MATCH | IIF_MATCH, iif1);
482 expectUidOwnerMapValues({10003}, POWERSAVE_MATCH, 0);
483
484 // Remove all powersave rules, expect ownerMap to only have uid interface rules left
485 EXPECT_EQ(0, mTc.replaceUidOwnerMap("fw_powersave", true, {}));
486 expectUidOwnerMapValues({10001, 10002}, IIF_MATCH, iif1);
487 // Make sure these are the only uids left
488 checkEachUidValue({10001, 10002}, IIF_MATCH);
489}
490
Motomu Utsumib08654c2022-05-11 05:56:26 +0000491TEST_F(TrafficControllerTest, TestAddUidInterfaceFilteringRulesWithWildcard) {
492 // iif=0 is a wildcard
493 int iif = 0;
494 // Add interface rule with wildcard to uids
495 ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif, {1000, 1001})));
496 expectUidOwnerMapValues({1000, 1001}, IIF_MATCH, iif);
497}
498
499TEST_F(TrafficControllerTest, TestRemoveUidInterfaceFilteringRulesWithWildcard) {
500 // iif=0 is a wildcard
501 int iif = 0;
502 // Add interface rule with wildcard to two uids
503 ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif, {1000, 1001})));
504 expectUidOwnerMapValues({1000, 1001}, IIF_MATCH, iif);
505
506 // Remove interface rule from one of the uids
507 ASSERT_TRUE(isOk(mTc.removeUidInterfaceRules({1000})));
508 expectUidOwnerMapValues({1001}, IIF_MATCH, iif);
509 checkEachUidValue({1001}, IIF_MATCH);
510
511 // Remove interface rule from the remaining uid
512 ASSERT_TRUE(isOk(mTc.removeUidInterfaceRules({1001})));
513 expectMapEmpty(mFakeUidOwnerMap);
514}
515
516TEST_F(TrafficControllerTest, TestUidInterfaceFilteringRulesWithWildcardAndExistingMatches) {
517 // Set up existing DOZABLE_MATCH and POWERSAVE_MATCH rule
518 ASSERT_TRUE(isOk(updateUidOwnerMaps({1000}, DOZABLE_MATCH,
519 TrafficController::IptOpInsert)));
520 ASSERT_TRUE(isOk(updateUidOwnerMaps({1000}, POWERSAVE_MATCH,
521 TrafficController::IptOpInsert)));
522
523 // iif=0 is a wildcard
524 int iif = 0;
525 // Add interface rule with wildcard to the existing uid
526 ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif, {1000})));
527 expectUidOwnerMapValues({1000}, POWERSAVE_MATCH | DOZABLE_MATCH | IIF_MATCH, iif);
528
529 // Remove interface rule with wildcard from the existing uid
530 ASSERT_TRUE(isOk(mTc.removeUidInterfaceRules({1000})));
531 expectUidOwnerMapValues({1000}, POWERSAVE_MATCH | DOZABLE_MATCH, 0);
532}
533
534TEST_F(TrafficControllerTest, TestUidInterfaceFilteringRulesWithWildcardAndNewMatches) {
535 // iif=0 is a wildcard
536 int iif = 0;
537 // Set up existing interface rule with wildcard
538 ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif, {1000})));
539
540 // Add DOZABLE_MATCH and POWERSAVE_MATCH rule to the existing uid
541 ASSERT_TRUE(isOk(updateUidOwnerMaps({1000}, DOZABLE_MATCH,
542 TrafficController::IptOpInsert)));
543 ASSERT_TRUE(isOk(updateUidOwnerMaps({1000}, POWERSAVE_MATCH,
544 TrafficController::IptOpInsert)));
545 expectUidOwnerMapValues({1000}, POWERSAVE_MATCH | DOZABLE_MATCH | IIF_MATCH, iif);
546
547 // Remove DOZABLE_MATCH and POWERSAVE_MATCH rule from the existing uid
548 ASSERT_TRUE(isOk(updateUidOwnerMaps({1000}, DOZABLE_MATCH,
549 TrafficController::IptOpDelete)));
550 ASSERT_TRUE(isOk(updateUidOwnerMaps({1000}, POWERSAVE_MATCH,
551 TrafficController::IptOpDelete)));
552 expectUidOwnerMapValues({1000}, IIF_MATCH, iif);
553}
554
Wayne Ma4d692332022-01-19 16:04:04 +0800555TEST_F(TrafficControllerTest, TestGrantInternetPermission) {
556 std::vector<uid_t> appUids = {TEST_UID, TEST_UID2, TEST_UID3};
557
558 mTc.setPermissionForUids(INetd::PERMISSION_INTERNET, appUids);
559 expectMapEmpty(mFakeUidPermissionMap);
560 expectPrivilegedUserSetEmpty();
561}
562
563TEST_F(TrafficControllerTest, TestRevokeInternetPermission) {
564 std::vector<uid_t> appUids = {TEST_UID, TEST_UID2, TEST_UID3};
565
566 mTc.setPermissionForUids(INetd::PERMISSION_NONE, appUids);
567 expectUidPermissionMapValues(appUids, INetd::PERMISSION_NONE);
568}
569
570TEST_F(TrafficControllerTest, TestPermissionUninstalled) {
571 std::vector<uid_t> appUids = {TEST_UID, TEST_UID2, TEST_UID3};
572
573 mTc.setPermissionForUids(INetd::PERMISSION_UPDATE_DEVICE_STATS, appUids);
574 expectUidPermissionMapValues(appUids, INetd::PERMISSION_UPDATE_DEVICE_STATS);
575 expectPrivilegedUserSet(appUids);
576
577 std::vector<uid_t> uidToRemove = {TEST_UID};
578 mTc.setPermissionForUids(INetd::PERMISSION_UNINSTALLED, uidToRemove);
579
580 std::vector<uid_t> uidRemain = {TEST_UID3, TEST_UID2};
581 expectUidPermissionMapValues(uidRemain, INetd::PERMISSION_UPDATE_DEVICE_STATS);
582 expectPrivilegedUserSet(uidRemain);
583
584 mTc.setPermissionForUids(INetd::PERMISSION_UNINSTALLED, uidRemain);
585 expectMapEmpty(mFakeUidPermissionMap);
586 expectPrivilegedUserSetEmpty();
587}
588
589TEST_F(TrafficControllerTest, TestGrantUpdateStatsPermission) {
590 std::vector<uid_t> appUids = {TEST_UID, TEST_UID2, TEST_UID3};
591
592 mTc.setPermissionForUids(INetd::PERMISSION_UPDATE_DEVICE_STATS, appUids);
593 expectUidPermissionMapValues(appUids, INetd::PERMISSION_UPDATE_DEVICE_STATS);
594 expectPrivilegedUserSet(appUids);
595
596 mTc.setPermissionForUids(INetd::PERMISSION_NONE, appUids);
597 expectPrivilegedUserSetEmpty();
598 expectUidPermissionMapValues(appUids, INetd::PERMISSION_NONE);
599}
600
601TEST_F(TrafficControllerTest, TestRevokeUpdateStatsPermission) {
602 std::vector<uid_t> appUids = {TEST_UID, TEST_UID2, TEST_UID3};
603
604 mTc.setPermissionForUids(INetd::PERMISSION_UPDATE_DEVICE_STATS, appUids);
605 expectPrivilegedUserSet(appUids);
606
607 std::vector<uid_t> uidToRemove = {TEST_UID};
608 mTc.setPermissionForUids(INetd::PERMISSION_NONE, uidToRemove);
609
610 std::vector<uid_t> uidRemain = {TEST_UID3, TEST_UID2};
611 expectPrivilegedUserSet(uidRemain);
612
613 mTc.setPermissionForUids(INetd::PERMISSION_NONE, uidRemain);
614 expectPrivilegedUserSetEmpty();
615}
616
617TEST_F(TrafficControllerTest, TestGrantWrongPermission) {
618 std::vector<uid_t> appUids = {TEST_UID, TEST_UID2, TEST_UID3};
619
620 mTc.setPermissionForUids(INetd::PERMISSION_NONE, appUids);
621 expectPrivilegedUserSetEmpty();
622 expectUidPermissionMapValues(appUids, INetd::PERMISSION_NONE);
623}
624
625TEST_F(TrafficControllerTest, TestGrantDuplicatePermissionSlientlyFail) {
626 std::vector<uid_t> appUids = {TEST_UID, TEST_UID2, TEST_UID3};
627
628 mTc.setPermissionForUids(INetd::PERMISSION_INTERNET, appUids);
629 expectMapEmpty(mFakeUidPermissionMap);
630
631 std::vector<uid_t> uidToAdd = {TEST_UID};
632 mTc.setPermissionForUids(INetd::PERMISSION_INTERNET, uidToAdd);
633
634 expectPrivilegedUserSetEmpty();
635
636 mTc.setPermissionForUids(INetd::PERMISSION_NONE, appUids);
637 expectUidPermissionMapValues(appUids, INetd::PERMISSION_NONE);
638
639 mTc.setPermissionForUids(INetd::PERMISSION_UPDATE_DEVICE_STATS, appUids);
640 expectPrivilegedUserSet(appUids);
641
642 mTc.setPermissionForUids(INetd::PERMISSION_UPDATE_DEVICE_STATS, uidToAdd);
643 expectPrivilegedUserSet(appUids);
644
645 mTc.setPermissionForUids(INetd::PERMISSION_NONE, appUids);
646 expectPrivilegedUserSetEmpty();
647}
648
Patrick Rohr61e94672022-02-01 21:06:40 +0100649constexpr uint32_t SOCK_CLOSE_WAIT_US = 30 * 1000;
650constexpr uint32_t ENOBUFS_POLL_WAIT_US = 10 * 1000;
651
652using android::base::Error;
653using android::base::Result;
654using android::bpf::BpfMap;
655
656// This test set up a SkDestroyListener that is running parallel with the production
657// SkDestroyListener. The test will create thousands of sockets and tag them on the
658// production cookieUidTagMap and close them in a short time. When the number of
659// sockets get closed exceeds the buffer size, it will start to return ENOBUFF
660// error. The error will be ignored by the production SkDestroyListener and the
661// test will clean up the tags in tearDown if there is any remains.
662
663// TODO: Instead of test the ENOBUFF error, we can test the production
664// SkDestroyListener to see if it failed to delete a tagged socket when ENOBUFF
665// triggered.
666class NetlinkListenerTest : public testing::Test {
667 protected:
668 NetlinkListenerTest() {}
669 BpfMap<uint64_t, UidTagValue> mCookieTagMap;
670
671 void SetUp() {
Maciej Żenczykowskiced35312022-05-31 05:11:12 -0700672 mCookieTagMap.init(COOKIE_TAG_MAP_PATH);
Patrick Rohr61e94672022-02-01 21:06:40 +0100673 ASSERT_TRUE(mCookieTagMap.isValid());
674 }
675
676 void TearDown() {
677 const auto deleteTestCookieEntries = [](const uint64_t& key, const UidTagValue& value,
678 BpfMap<uint64_t, UidTagValue>& map) {
679 if ((value.uid == TEST_UID) && (value.tag == TEST_TAG)) {
680 Result<void> res = map.deleteValue(key);
681 if (res.ok() || (res.error().code() == ENOENT)) {
682 return Result<void>();
683 }
Maciej Żenczykowskie0f58462022-05-17 13:59:22 -0700684 ALOGE("Failed to delete data(cookie = %" PRIu64 "): %s", key,
Patrick Rohr61e94672022-02-01 21:06:40 +0100685 strerror(res.error().code()));
686 }
687 // Move forward to next cookie in the map.
688 return Result<void>();
689 };
690 EXPECT_RESULT_OK(mCookieTagMap.iterateWithValue(deleteTestCookieEntries));
691 }
692
693 Result<void> checkNoGarbageTagsExist() {
694 const auto checkGarbageTags = [](const uint64_t&, const UidTagValue& value,
695 const BpfMap<uint64_t, UidTagValue>&) -> Result<void> {
696 if ((TEST_UID == value.uid) && (TEST_TAG == value.tag)) {
697 return Error(EUCLEAN) << "Closed socket is not untagged";
698 }
699 return {};
700 };
701 return mCookieTagMap.iterateWithValue(checkGarbageTags);
702 }
703
704 bool checkMassiveSocketDestroy(int totalNumber, bool expectError) {
705 std::unique_ptr<android::netdutils::NetlinkListenerInterface> skDestroyListener;
706 auto result = android::net::TrafficController::makeSkDestroyListener();
707 if (!isOk(result)) {
708 ALOGE("Unable to create SkDestroyListener: %s", toString(result).c_str());
709 } else {
710 skDestroyListener = std::move(result.value());
711 }
712 int rxErrorCount = 0;
713 // Rx handler extracts nfgenmsg looks up and invokes registered dispatch function.
714 const auto rxErrorHandler = [&rxErrorCount](const int, const int) { rxErrorCount++; };
715 skDestroyListener->registerSkErrorHandler(rxErrorHandler);
716 int fds[totalNumber];
717 for (int i = 0; i < totalNumber; i++) {
718 fds[i] = socket(AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0);
719 // The likely reason for a failure is running out of available file descriptors.
720 EXPECT_LE(0, fds[i]) << i << " of " << totalNumber;
721 if (fds[i] < 0) {
722 // EXPECT_LE already failed above, so test case is a failure, but we don't
723 // want potentially tens of thousands of extra failures creating and then
724 // closing all these fds cluttering up the logs.
725 totalNumber = i;
726 break;
727 };
728 libnetd_updatable_tagSocket(fds[i], TEST_TAG, TEST_UID, 1000);
729 }
730
731 // TODO: Use a separate thread that has its own fd table so we can
732 // close sockets even faster simply by terminating that thread.
733 for (int i = 0; i < totalNumber; i++) {
734 EXPECT_EQ(0, close(fds[i]));
735 }
736 // wait a bit for netlink listener to handle all the messages.
737 usleep(SOCK_CLOSE_WAIT_US);
738 if (expectError) {
739 // If ENOBUFS triggered, check it only called into the handler once, ie.
740 // that the netlink handler is not spinning.
741 int currentErrorCount = rxErrorCount;
742 // 0 error count is acceptable because the system has chances to close all sockets
743 // normally.
744 EXPECT_LE(0, rxErrorCount);
745 if (!rxErrorCount) return true;
746
747 usleep(ENOBUFS_POLL_WAIT_US);
748 EXPECT_EQ(currentErrorCount, rxErrorCount);
749 } else {
750 EXPECT_RESULT_OK(checkNoGarbageTagsExist());
751 EXPECT_EQ(0, rxErrorCount);
752 }
753 return false;
754 }
755};
756
757TEST_F(NetlinkListenerTest, TestAllSocketUntagged) {
758 checkMassiveSocketDestroy(10, false);
759 checkMassiveSocketDestroy(100, false);
760}
761
762// Disabled because flaky on blueline-userdebug; this test relies on the main thread
763// winning a race against the NetlinkListener::run() thread. There's no way to ensure
764// things will be scheduled the same way across all architectures and test environments.
765TEST_F(NetlinkListenerTest, DISABLED_TestSkDestroyError) {
766 bool needRetry = false;
767 int retryCount = 0;
768 do {
769 needRetry = checkMassiveSocketDestroy(32500, true);
770 if (needRetry) retryCount++;
771 } while (needRetry && retryCount < 3);
772 // Should review test if it can always close all sockets correctly.
773 EXPECT_GT(3, retryCount);
774}
775
776
Wayne Ma4d692332022-01-19 16:04:04 +0800777} // namespace net
778} // namespace android