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