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