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