blob: 9529caee487102764052b309c49d7c6848ff7b6e [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
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);
Wayne Ma4d692332022-01-19 16:04:04 +0800310 ASSERT_EQ(-EINVAL, mTc.changeUidOwnerRule(NONE, TEST_UID, ALLOW, ALLOWLIST));
311 ASSERT_EQ(-EINVAL, mTc.changeUidOwnerRule(INVALID_CHAIN, TEST_UID, ALLOW, ALLOWLIST));
312}
313
314TEST_F(TrafficControllerTest, TestReplaceUidOwnerMap) {
315 std::vector<int32_t> uids = {TEST_UID, TEST_UID2, TEST_UID3};
316 checkUidMapReplace("fw_dozable", uids, DOZABLE_MATCH);
317 checkUidMapReplace("fw_standby", uids, STANDBY_MATCH);
318 checkUidMapReplace("fw_powersave", uids, POWERSAVE_MATCH);
319 checkUidMapReplace("fw_restricted", uids, RESTRICTED_MATCH);
Robert Horvathd945bf02022-01-27 19:55:16 +0100320 checkUidMapReplace("fw_low_power_standby", uids, LOW_POWER_STANDBY_MATCH);
Wayne Ma4d692332022-01-19 16:04:04 +0800321 ASSERT_EQ(-EINVAL, mTc.replaceUidOwnerMap("unknow", true, uids));
322}
323
324TEST_F(TrafficControllerTest, TestReplaceSameChain) {
325 std::vector<int32_t> uids = {TEST_UID, TEST_UID2, TEST_UID3};
326 checkUidMapReplace("fw_dozable", uids, DOZABLE_MATCH);
327 std::vector<int32_t> newUids = {TEST_UID2, TEST_UID3};
328 checkUidMapReplace("fw_dozable", newUids, DOZABLE_MATCH);
329}
330
331TEST_F(TrafficControllerTest, TestDenylistUidMatch) {
332 std::vector<uint32_t> appUids = {1000, 1001, 10012};
Wayne Ma7be6bce2022-01-12 16:29:49 +0800333 ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, PENALTY_BOX_MATCH,
334 TrafficController::IptOpInsert)));
Wayne Ma4d692332022-01-19 16:04:04 +0800335 expectUidOwnerMapValues(appUids, PENALTY_BOX_MATCH, 0);
Wayne Ma7be6bce2022-01-12 16:29:49 +0800336 ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, PENALTY_BOX_MATCH,
337 TrafficController::IptOpDelete)));
Wayne Ma4d692332022-01-19 16:04:04 +0800338 expectMapEmpty(mFakeUidOwnerMap);
339}
340
341TEST_F(TrafficControllerTest, TestAllowlistUidMatch) {
342 std::vector<uint32_t> appUids = {1000, 1001, 10012};
Wayne Ma7be6bce2022-01-12 16:29:49 +0800343 ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, HAPPY_BOX_MATCH, TrafficController::IptOpInsert)));
Wayne Ma4d692332022-01-19 16:04:04 +0800344 expectUidOwnerMapValues(appUids, HAPPY_BOX_MATCH, 0);
Wayne Ma7be6bce2022-01-12 16:29:49 +0800345 ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, HAPPY_BOX_MATCH, TrafficController::IptOpDelete)));
Wayne Ma4d692332022-01-19 16:04:04 +0800346 expectMapEmpty(mFakeUidOwnerMap);
347}
348
349TEST_F(TrafficControllerTest, TestReplaceMatchUid) {
350 std::vector<uint32_t> appUids = {1000, 1001, 10012};
351 // Add appUids to the denylist and expect that their values are all PENALTY_BOX_MATCH.
Wayne Ma7be6bce2022-01-12 16:29:49 +0800352 ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, PENALTY_BOX_MATCH,
353 TrafficController::IptOpInsert)));
Wayne Ma4d692332022-01-19 16:04:04 +0800354 expectUidOwnerMapValues(appUids, PENALTY_BOX_MATCH, 0);
355
356 // Add the same UIDs to the allowlist and expect that we get PENALTY_BOX_MATCH |
357 // HAPPY_BOX_MATCH.
Wayne Ma7be6bce2022-01-12 16:29:49 +0800358 ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, HAPPY_BOX_MATCH, TrafficController::IptOpInsert)));
Wayne Ma4d692332022-01-19 16:04:04 +0800359 expectUidOwnerMapValues(appUids, HAPPY_BOX_MATCH | PENALTY_BOX_MATCH, 0);
360
361 // Remove the same UIDs from the allowlist and check the PENALTY_BOX_MATCH is still there.
Wayne Ma7be6bce2022-01-12 16:29:49 +0800362 ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, HAPPY_BOX_MATCH, TrafficController::IptOpDelete)));
Wayne Ma4d692332022-01-19 16:04:04 +0800363 expectUidOwnerMapValues(appUids, PENALTY_BOX_MATCH, 0);
364
365 // Remove the same UIDs from the denylist and check the map is empty.
Wayne Ma7be6bce2022-01-12 16:29:49 +0800366 ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, PENALTY_BOX_MATCH,
367 TrafficController::IptOpDelete)));
Wayne Ma4d692332022-01-19 16:04:04 +0800368 ASSERT_FALSE(mFakeUidOwnerMap.getFirstKey().ok());
369}
370
371TEST_F(TrafficControllerTest, TestDeleteWrongMatchSilentlyFails) {
372 std::vector<uint32_t> appUids = {1000, 1001, 10012};
373 // 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 +0800374 ASSERT_FALSE(isOk(updateUidOwnerMaps(appUids, HAPPY_BOX_MATCH,
375 TrafficController::IptOpDelete)));
Wayne Ma4d692332022-01-19 16:04:04 +0800376 expectMapEmpty(mFakeUidOwnerMap);
377
378 // Add denylist rules for appUids.
Wayne Ma7be6bce2022-01-12 16:29:49 +0800379 ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, HAPPY_BOX_MATCH,
380 TrafficController::IptOpInsert)));
Wayne Ma4d692332022-01-19 16:04:04 +0800381 expectUidOwnerMapValues(appUids, HAPPY_BOX_MATCH, 0);
382
383 // Delete (non-existent) denylist rules for appUids, and check that this silently does
384 // nothing if the uid is in the map but does not have denylist match. This is required because
385 // NetworkManagementService will try to remove a uid from denylist after adding it to the
386 // allowlist and if the remove fails it will not update the uid status.
Wayne Ma7be6bce2022-01-12 16:29:49 +0800387 ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, PENALTY_BOX_MATCH,
388 TrafficController::IptOpDelete)));
Wayne Ma4d692332022-01-19 16:04:04 +0800389 expectUidOwnerMapValues(appUids, HAPPY_BOX_MATCH, 0);
390}
391
392TEST_F(TrafficControllerTest, TestAddUidInterfaceFilteringRules) {
393 int iif0 = 15;
394 ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif0, {1000, 1001})));
395 expectUidOwnerMapValues({1000, 1001}, IIF_MATCH, iif0);
396
397 // Add some non-overlapping new uids. They should coexist with existing rules
398 int iif1 = 16;
399 ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif1, {2000, 2001})));
400 expectUidOwnerMapValues({1000, 1001}, IIF_MATCH, iif0);
401 expectUidOwnerMapValues({2000, 2001}, IIF_MATCH, iif1);
402
403 // Overwrite some existing uids
404 int iif2 = 17;
405 ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif2, {1000, 2000})));
406 expectUidOwnerMapValues({1001}, IIF_MATCH, iif0);
407 expectUidOwnerMapValues({2001}, IIF_MATCH, iif1);
408 expectUidOwnerMapValues({1000, 2000}, IIF_MATCH, iif2);
409}
410
411TEST_F(TrafficControllerTest, TestRemoveUidInterfaceFilteringRules) {
412 int iif0 = 15;
413 int iif1 = 16;
414 ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif0, {1000, 1001})));
415 ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif1, {2000, 2001})));
416 expectUidOwnerMapValues({1000, 1001}, IIF_MATCH, iif0);
417 expectUidOwnerMapValues({2000, 2001}, IIF_MATCH, iif1);
418
419 // Rmove some uids
420 ASSERT_TRUE(isOk(mTc.removeUidInterfaceRules({1001, 2001})));
421 expectUidOwnerMapValues({1000}, IIF_MATCH, iif0);
422 expectUidOwnerMapValues({2000}, IIF_MATCH, iif1);
423 checkEachUidValue({1000, 2000}, IIF_MATCH); // Make sure there are only two uids remaining
424
425 // Remove non-existent uids shouldn't fail
426 ASSERT_TRUE(isOk(mTc.removeUidInterfaceRules({2000, 3000})));
427 expectUidOwnerMapValues({1000}, IIF_MATCH, iif0);
428 checkEachUidValue({1000}, IIF_MATCH); // Make sure there are only one uid remaining
429
430 // Remove everything
431 ASSERT_TRUE(isOk(mTc.removeUidInterfaceRules({1000})));
432 expectMapEmpty(mFakeUidOwnerMap);
433}
434
435TEST_F(TrafficControllerTest, TestUidInterfaceFilteringRulesCoexistWithExistingMatches) {
436 // Set up existing PENALTY_BOX_MATCH rules
Wayne Ma7be6bce2022-01-12 16:29:49 +0800437 ASSERT_TRUE(isOk(updateUidOwnerMaps({1000, 1001, 10012}, PENALTY_BOX_MATCH,
438 TrafficController::IptOpInsert)));
Wayne Ma4d692332022-01-19 16:04:04 +0800439 expectUidOwnerMapValues({1000, 1001, 10012}, PENALTY_BOX_MATCH, 0);
440
441 // Add some partially-overlapping uid owner rules and check result
442 int iif1 = 32;
443 ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif1, {10012, 10013, 10014})));
444 expectUidOwnerMapValues({1000, 1001}, PENALTY_BOX_MATCH, 0);
445 expectUidOwnerMapValues({10012}, PENALTY_BOX_MATCH | IIF_MATCH, iif1);
446 expectUidOwnerMapValues({10013, 10014}, IIF_MATCH, iif1);
447
448 // Removing some PENALTY_BOX_MATCH rules should not change uid interface rule
Wayne Ma7be6bce2022-01-12 16:29:49 +0800449 ASSERT_TRUE(isOk(updateUidOwnerMaps({1001, 10012}, PENALTY_BOX_MATCH,
450 TrafficController::IptOpDelete)));
Wayne Ma4d692332022-01-19 16:04:04 +0800451 expectUidOwnerMapValues({1000}, PENALTY_BOX_MATCH, 0);
452 expectUidOwnerMapValues({10012, 10013, 10014}, IIF_MATCH, iif1);
453
454 // Remove all uid interface rules
455 ASSERT_TRUE(isOk(mTc.removeUidInterfaceRules({10012, 10013, 10014})));
456 expectUidOwnerMapValues({1000}, PENALTY_BOX_MATCH, 0);
457 // Make sure these are the only uids left
458 checkEachUidValue({1000}, PENALTY_BOX_MATCH);
459}
460
461TEST_F(TrafficControllerTest, TestUidInterfaceFilteringRulesCoexistWithNewMatches) {
462 int iif1 = 56;
463 // Set up existing uid interface rules
464 ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif1, {10001, 10002})));
465 expectUidOwnerMapValues({10001, 10002}, IIF_MATCH, iif1);
466
467 // Add some partially-overlapping doze rules
468 EXPECT_EQ(0, mTc.replaceUidOwnerMap("fw_dozable", true, {10002, 10003}));
469 expectUidOwnerMapValues({10001}, IIF_MATCH, iif1);
470 expectUidOwnerMapValues({10002}, DOZABLE_MATCH | IIF_MATCH, iif1);
471 expectUidOwnerMapValues({10003}, DOZABLE_MATCH, 0);
472
473 // Introduce a third rule type (powersave) on various existing UIDs
474 EXPECT_EQ(0, mTc.replaceUidOwnerMap("fw_powersave", true, {10000, 10001, 10002, 10003}));
475 expectUidOwnerMapValues({10000}, POWERSAVE_MATCH, 0);
476 expectUidOwnerMapValues({10001}, POWERSAVE_MATCH | IIF_MATCH, iif1);
477 expectUidOwnerMapValues({10002}, POWERSAVE_MATCH | DOZABLE_MATCH | IIF_MATCH, iif1);
478 expectUidOwnerMapValues({10003}, POWERSAVE_MATCH | DOZABLE_MATCH, 0);
479
480 // Remove all doze rules
481 EXPECT_EQ(0, mTc.replaceUidOwnerMap("fw_dozable", true, {}));
482 expectUidOwnerMapValues({10000}, POWERSAVE_MATCH, 0);
483 expectUidOwnerMapValues({10001}, POWERSAVE_MATCH | IIF_MATCH, iif1);
484 expectUidOwnerMapValues({10002}, POWERSAVE_MATCH | IIF_MATCH, iif1);
485 expectUidOwnerMapValues({10003}, POWERSAVE_MATCH, 0);
486
487 // Remove all powersave rules, expect ownerMap to only have uid interface rules left
488 EXPECT_EQ(0, mTc.replaceUidOwnerMap("fw_powersave", true, {}));
489 expectUidOwnerMapValues({10001, 10002}, IIF_MATCH, iif1);
490 // Make sure these are the only uids left
491 checkEachUidValue({10001, 10002}, IIF_MATCH);
492}
493
494TEST_F(TrafficControllerTest, TestGrantInternetPermission) {
495 std::vector<uid_t> appUids = {TEST_UID, TEST_UID2, TEST_UID3};
496
497 mTc.setPermissionForUids(INetd::PERMISSION_INTERNET, appUids);
498 expectMapEmpty(mFakeUidPermissionMap);
499 expectPrivilegedUserSetEmpty();
500}
501
502TEST_F(TrafficControllerTest, TestRevokeInternetPermission) {
503 std::vector<uid_t> appUids = {TEST_UID, TEST_UID2, TEST_UID3};
504
505 mTc.setPermissionForUids(INetd::PERMISSION_NONE, appUids);
506 expectUidPermissionMapValues(appUids, INetd::PERMISSION_NONE);
507}
508
509TEST_F(TrafficControllerTest, TestPermissionUninstalled) {
510 std::vector<uid_t> appUids = {TEST_UID, TEST_UID2, TEST_UID3};
511
512 mTc.setPermissionForUids(INetd::PERMISSION_UPDATE_DEVICE_STATS, appUids);
513 expectUidPermissionMapValues(appUids, INetd::PERMISSION_UPDATE_DEVICE_STATS);
514 expectPrivilegedUserSet(appUids);
515
516 std::vector<uid_t> uidToRemove = {TEST_UID};
517 mTc.setPermissionForUids(INetd::PERMISSION_UNINSTALLED, uidToRemove);
518
519 std::vector<uid_t> uidRemain = {TEST_UID3, TEST_UID2};
520 expectUidPermissionMapValues(uidRemain, INetd::PERMISSION_UPDATE_DEVICE_STATS);
521 expectPrivilegedUserSet(uidRemain);
522
523 mTc.setPermissionForUids(INetd::PERMISSION_UNINSTALLED, uidRemain);
524 expectMapEmpty(mFakeUidPermissionMap);
525 expectPrivilegedUserSetEmpty();
526}
527
528TEST_F(TrafficControllerTest, TestGrantUpdateStatsPermission) {
529 std::vector<uid_t> appUids = {TEST_UID, TEST_UID2, TEST_UID3};
530
531 mTc.setPermissionForUids(INetd::PERMISSION_UPDATE_DEVICE_STATS, appUids);
532 expectUidPermissionMapValues(appUids, INetd::PERMISSION_UPDATE_DEVICE_STATS);
533 expectPrivilegedUserSet(appUids);
534
535 mTc.setPermissionForUids(INetd::PERMISSION_NONE, appUids);
536 expectPrivilegedUserSetEmpty();
537 expectUidPermissionMapValues(appUids, INetd::PERMISSION_NONE);
538}
539
540TEST_F(TrafficControllerTest, TestRevokeUpdateStatsPermission) {
541 std::vector<uid_t> appUids = {TEST_UID, TEST_UID2, TEST_UID3};
542
543 mTc.setPermissionForUids(INetd::PERMISSION_UPDATE_DEVICE_STATS, appUids);
544 expectPrivilegedUserSet(appUids);
545
546 std::vector<uid_t> uidToRemove = {TEST_UID};
547 mTc.setPermissionForUids(INetd::PERMISSION_NONE, uidToRemove);
548
549 std::vector<uid_t> uidRemain = {TEST_UID3, TEST_UID2};
550 expectPrivilegedUserSet(uidRemain);
551
552 mTc.setPermissionForUids(INetd::PERMISSION_NONE, uidRemain);
553 expectPrivilegedUserSetEmpty();
554}
555
556TEST_F(TrafficControllerTest, TestGrantWrongPermission) {
557 std::vector<uid_t> appUids = {TEST_UID, TEST_UID2, TEST_UID3};
558
559 mTc.setPermissionForUids(INetd::PERMISSION_NONE, appUids);
560 expectPrivilegedUserSetEmpty();
561 expectUidPermissionMapValues(appUids, INetd::PERMISSION_NONE);
562}
563
564TEST_F(TrafficControllerTest, TestGrantDuplicatePermissionSlientlyFail) {
565 std::vector<uid_t> appUids = {TEST_UID, TEST_UID2, TEST_UID3};
566
567 mTc.setPermissionForUids(INetd::PERMISSION_INTERNET, appUids);
568 expectMapEmpty(mFakeUidPermissionMap);
569
570 std::vector<uid_t> uidToAdd = {TEST_UID};
571 mTc.setPermissionForUids(INetd::PERMISSION_INTERNET, uidToAdd);
572
573 expectPrivilegedUserSetEmpty();
574
575 mTc.setPermissionForUids(INetd::PERMISSION_NONE, appUids);
576 expectUidPermissionMapValues(appUids, INetd::PERMISSION_NONE);
577
578 mTc.setPermissionForUids(INetd::PERMISSION_UPDATE_DEVICE_STATS, appUids);
579 expectPrivilegedUserSet(appUids);
580
581 mTc.setPermissionForUids(INetd::PERMISSION_UPDATE_DEVICE_STATS, uidToAdd);
582 expectPrivilegedUserSet(appUids);
583
584 mTc.setPermissionForUids(INetd::PERMISSION_NONE, appUids);
585 expectPrivilegedUserSetEmpty();
586}
587
Patrick Rohr61e94672022-02-01 21:06:40 +0100588constexpr uint32_t SOCK_CLOSE_WAIT_US = 30 * 1000;
589constexpr uint32_t ENOBUFS_POLL_WAIT_US = 10 * 1000;
590
591using android::base::Error;
592using android::base::Result;
593using android::bpf::BpfMap;
594
595// This test set up a SkDestroyListener that is running parallel with the production
596// SkDestroyListener. The test will create thousands of sockets and tag them on the
597// production cookieUidTagMap and close them in a short time. When the number of
598// sockets get closed exceeds the buffer size, it will start to return ENOBUFF
599// error. The error will be ignored by the production SkDestroyListener and the
600// test will clean up the tags in tearDown if there is any remains.
601
602// TODO: Instead of test the ENOBUFF error, we can test the production
603// SkDestroyListener to see if it failed to delete a tagged socket when ENOBUFF
604// triggered.
605class NetlinkListenerTest : public testing::Test {
606 protected:
607 NetlinkListenerTest() {}
608 BpfMap<uint64_t, UidTagValue> mCookieTagMap;
609
610 void SetUp() {
611 mCookieTagMap.reset(android::bpf::mapRetrieveRW(COOKIE_TAG_MAP_PATH));
612 ASSERT_TRUE(mCookieTagMap.isValid());
613 }
614
615 void TearDown() {
616 const auto deleteTestCookieEntries = [](const uint64_t& key, const UidTagValue& value,
617 BpfMap<uint64_t, UidTagValue>& map) {
618 if ((value.uid == TEST_UID) && (value.tag == TEST_TAG)) {
619 Result<void> res = map.deleteValue(key);
620 if (res.ok() || (res.error().code() == ENOENT)) {
621 return Result<void>();
622 }
623 ALOGE("Failed to delete data(cookie = %" PRIu64 "): %s\n", key,
624 strerror(res.error().code()));
625 }
626 // Move forward to next cookie in the map.
627 return Result<void>();
628 };
629 EXPECT_RESULT_OK(mCookieTagMap.iterateWithValue(deleteTestCookieEntries));
630 }
631
632 Result<void> checkNoGarbageTagsExist() {
633 const auto checkGarbageTags = [](const uint64_t&, const UidTagValue& value,
634 const BpfMap<uint64_t, UidTagValue>&) -> Result<void> {
635 if ((TEST_UID == value.uid) && (TEST_TAG == value.tag)) {
636 return Error(EUCLEAN) << "Closed socket is not untagged";
637 }
638 return {};
639 };
640 return mCookieTagMap.iterateWithValue(checkGarbageTags);
641 }
642
643 bool checkMassiveSocketDestroy(int totalNumber, bool expectError) {
644 std::unique_ptr<android::netdutils::NetlinkListenerInterface> skDestroyListener;
645 auto result = android::net::TrafficController::makeSkDestroyListener();
646 if (!isOk(result)) {
647 ALOGE("Unable to create SkDestroyListener: %s", toString(result).c_str());
648 } else {
649 skDestroyListener = std::move(result.value());
650 }
651 int rxErrorCount = 0;
652 // Rx handler extracts nfgenmsg looks up and invokes registered dispatch function.
653 const auto rxErrorHandler = [&rxErrorCount](const int, const int) { rxErrorCount++; };
654 skDestroyListener->registerSkErrorHandler(rxErrorHandler);
655 int fds[totalNumber];
656 for (int i = 0; i < totalNumber; i++) {
657 fds[i] = socket(AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0);
658 // The likely reason for a failure is running out of available file descriptors.
659 EXPECT_LE(0, fds[i]) << i << " of " << totalNumber;
660 if (fds[i] < 0) {
661 // EXPECT_LE already failed above, so test case is a failure, but we don't
662 // want potentially tens of thousands of extra failures creating and then
663 // closing all these fds cluttering up the logs.
664 totalNumber = i;
665 break;
666 };
667 libnetd_updatable_tagSocket(fds[i], TEST_TAG, TEST_UID, 1000);
668 }
669
670 // TODO: Use a separate thread that has its own fd table so we can
671 // close sockets even faster simply by terminating that thread.
672 for (int i = 0; i < totalNumber; i++) {
673 EXPECT_EQ(0, close(fds[i]));
674 }
675 // wait a bit for netlink listener to handle all the messages.
676 usleep(SOCK_CLOSE_WAIT_US);
677 if (expectError) {
678 // If ENOBUFS triggered, check it only called into the handler once, ie.
679 // that the netlink handler is not spinning.
680 int currentErrorCount = rxErrorCount;
681 // 0 error count is acceptable because the system has chances to close all sockets
682 // normally.
683 EXPECT_LE(0, rxErrorCount);
684 if (!rxErrorCount) return true;
685
686 usleep(ENOBUFS_POLL_WAIT_US);
687 EXPECT_EQ(currentErrorCount, rxErrorCount);
688 } else {
689 EXPECT_RESULT_OK(checkNoGarbageTagsExist());
690 EXPECT_EQ(0, rxErrorCount);
691 }
692 return false;
693 }
694};
695
696TEST_F(NetlinkListenerTest, TestAllSocketUntagged) {
697 checkMassiveSocketDestroy(10, false);
698 checkMassiveSocketDestroy(100, false);
699}
700
701// Disabled because flaky on blueline-userdebug; this test relies on the main thread
702// winning a race against the NetlinkListener::run() thread. There's no way to ensure
703// things will be scheduled the same way across all architectures and test environments.
704TEST_F(NetlinkListenerTest, DISABLED_TestSkDestroyError) {
705 bool needRetry = false;
706 int retryCount = 0;
707 do {
708 needRetry = checkMassiveSocketDestroy(32500, true);
709 if (needRetry) retryCount++;
710 } while (needRetry && retryCount < 3);
711 // Should review test if it can always close all sockets correctly.
712 EXPECT_GT(3, retryCount);
713}
714
715
Wayne Ma4d692332022-01-19 16:04:04 +0800716} // namespace net
717} // namespace android