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