blob: 5981906fc3f2b1f06859f9fecb3f67bb50d37965 [file] [log] [blame]
Wayne Ma4d692332022-01-19 16:04:04 +08001/*
Wayne Maa9716ff2022-01-12 10:37:04 +08002 * Copyright (C) 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
17#define LOG_TAG "TrafficController"
18#include <inttypes.h>
Wayne Ma4d692332022-01-19 16:04:04 +080019#include <linux/if_ether.h>
20#include <linux/in.h>
21#include <linux/inet_diag.h>
22#include <linux/netlink.h>
23#include <linux/sock_diag.h>
24#include <linux/unistd.h>
25#include <net/if.h>
26#include <stdlib.h>
27#include <string.h>
28#include <sys/socket.h>
29#include <sys/stat.h>
30#include <sys/types.h>
31#include <sys/utsname.h>
32#include <sys/wait.h>
Wayne Maa9716ff2022-01-12 10:37:04 +080033#include <map>
Wayne Ma4d692332022-01-19 16:04:04 +080034#include <mutex>
35#include <unordered_set>
36#include <vector>
37
38#include <android-base/stringprintf.h>
39#include <android-base/strings.h>
40#include <android-base/unique_fd.h>
41#include <netdutils/StatusOr.h>
Wayne Ma4d692332022-01-19 16:04:04 +080042#include <netdutils/Syscalls.h>
Ken Chenf426b2b2022-01-23 15:39:13 +080043#include <netdutils/UidConstants.h>
Wayne Ma4d692332022-01-19 16:04:04 +080044#include <netdutils/Utils.h>
Wayne Maa9716ff2022-01-12 10:37:04 +080045#include <private/android_filesystem_config.h>
46
Wayne Ma4d692332022-01-19 16:04:04 +080047#include "TrafficController.h"
48#include "bpf/BpfMap.h"
Wayne Ma4d692332022-01-19 16:04:04 +080049#include "netdutils/DumpWriter.h"
50
51namespace android {
52namespace net {
53
54using base::StringPrintf;
55using base::unique_fd;
56using bpf::BpfMap;
Wayne Ma4d692332022-01-19 16:04:04 +080057using bpf::OVERFLOW_COUNTERSET;
Wayne Ma4d692332022-01-19 16:04:04 +080058using bpf::synchronizeKernelRCU;
59using netdutils::DumpWriter;
Wayne Ma4d692332022-01-19 16:04:04 +080060using netdutils::getIfaceList;
61using netdutils::NetlinkListener;
62using netdutils::NetlinkListenerInterface;
63using netdutils::ScopedIndent;
64using netdutils::Slice;
65using netdutils::sSyscalls;
66using netdutils::Status;
67using netdutils::statusFromErrno;
68using netdutils::StatusOr;
69using netdutils::status::ok;
70
71constexpr int kSockDiagMsgType = SOCK_DIAG_BY_FAMILY;
72constexpr int kSockDiagDoneMsgType = NLMSG_DONE;
Wayne Ma4d692332022-01-19 16:04:04 +080073
74const char* TrafficController::LOCAL_DOZABLE = "fw_dozable";
75const char* TrafficController::LOCAL_STANDBY = "fw_standby";
76const char* TrafficController::LOCAL_POWERSAVE = "fw_powersave";
77const char* TrafficController::LOCAL_RESTRICTED = "fw_restricted";
Robert Horvathd945bf02022-01-27 19:55:16 +010078const char* TrafficController::LOCAL_LOW_POWER_STANDBY = "fw_low_power_standby";
Wayne Ma4d692332022-01-19 16:04:04 +080079
80static_assert(BPF_PERMISSION_INTERNET == INetd::PERMISSION_INTERNET,
81 "Mismatch between BPF and AIDL permissions: PERMISSION_INTERNET");
82static_assert(BPF_PERMISSION_UPDATE_DEVICE_STATS == INetd::PERMISSION_UPDATE_DEVICE_STATS,
83 "Mismatch between BPF and AIDL permissions: PERMISSION_UPDATE_DEVICE_STATS");
Wayne Ma4d692332022-01-19 16:04:04 +080084
85#define FLAG_MSG_TRANS(result, flag, value) \
86 do { \
87 if ((value) & (flag)) { \
88 (result).append(" " #flag); \
89 (value) &= ~(flag); \
90 } \
91 } while (0)
92
93const std::string uidMatchTypeToString(uint8_t match) {
94 std::string matchType;
95 FLAG_MSG_TRANS(matchType, HAPPY_BOX_MATCH, match);
96 FLAG_MSG_TRANS(matchType, PENALTY_BOX_MATCH, match);
97 FLAG_MSG_TRANS(matchType, DOZABLE_MATCH, match);
98 FLAG_MSG_TRANS(matchType, STANDBY_MATCH, match);
99 FLAG_MSG_TRANS(matchType, POWERSAVE_MATCH, match);
100 FLAG_MSG_TRANS(matchType, RESTRICTED_MATCH, match);
Robert Horvathd945bf02022-01-27 19:55:16 +0100101 FLAG_MSG_TRANS(matchType, LOW_POWER_STANDBY_MATCH, match);
Wayne Ma4d692332022-01-19 16:04:04 +0800102 FLAG_MSG_TRANS(matchType, IIF_MATCH, match);
103 if (match) {
104 return StringPrintf("Unknown match: %u", match);
105 }
106 return matchType;
107}
108
109bool TrafficController::hasUpdateDeviceStatsPermission(uid_t uid) {
110 // This implementation is the same logic as method ActivityManager#checkComponentPermission.
111 // It implies that the calling uid can never be the same as PER_USER_RANGE.
112 uint32_t appId = uid % PER_USER_RANGE;
113 return ((appId == AID_ROOT) || (appId == AID_SYSTEM) ||
114 mPrivilegedUser.find(appId) != mPrivilegedUser.end());
115}
116
117const std::string UidPermissionTypeToString(int permission) {
118 if (permission == INetd::PERMISSION_NONE) {
119 return "PERMISSION_NONE";
120 }
121 if (permission == INetd::PERMISSION_UNINSTALLED) {
122 // This should never appear in the map, complain loudly if it does.
123 return "PERMISSION_UNINSTALLED error!";
124 }
125 std::string permissionType;
126 FLAG_MSG_TRANS(permissionType, BPF_PERMISSION_INTERNET, permission);
127 FLAG_MSG_TRANS(permissionType, BPF_PERMISSION_UPDATE_DEVICE_STATS, permission);
128 if (permission) {
129 return StringPrintf("Unknown permission: %u", permission);
130 }
131 return permissionType;
132}
133
134StatusOr<std::unique_ptr<NetlinkListenerInterface>> TrafficController::makeSkDestroyListener() {
135 const auto& sys = sSyscalls.get();
136 ASSIGN_OR_RETURN(auto event, sys.eventfd(0, EFD_CLOEXEC));
137 const int domain = AF_NETLINK;
138 const int type = SOCK_DGRAM | SOCK_CLOEXEC | SOCK_NONBLOCK;
139 const int protocol = NETLINK_INET_DIAG;
140 ASSIGN_OR_RETURN(auto sock, sys.socket(domain, type, protocol));
141
142 // TODO: if too many sockets are closed too quickly, we can overflow the socket buffer, and
143 // some entries in mCookieTagMap will not be freed. In order to fix this we would need to
144 // periodically dump all sockets and remove the tag entries for sockets that have been closed.
145 // For now, set a large-enough buffer that we can close hundreds of sockets without getting
146 // ENOBUFS and leaking mCookieTagMap entries.
147 int rcvbuf = 512 * 1024;
148 auto ret = sys.setsockopt(sock, SOL_SOCKET, SO_RCVBUF, &rcvbuf, sizeof(rcvbuf));
149 if (!ret.ok()) {
150 ALOGW("Failed to set SkDestroyListener buffer size to %d: %s", rcvbuf, ret.msg().c_str());
151 }
152
153 sockaddr_nl addr = {
154 .nl_family = AF_NETLINK,
155 .nl_groups = 1 << (SKNLGRP_INET_TCP_DESTROY - 1) | 1 << (SKNLGRP_INET_UDP_DESTROY - 1) |
156 1 << (SKNLGRP_INET6_TCP_DESTROY - 1) | 1 << (SKNLGRP_INET6_UDP_DESTROY - 1)};
157 RETURN_IF_NOT_OK(sys.bind(sock, addr));
158
159 const sockaddr_nl kernel = {.nl_family = AF_NETLINK};
160 RETURN_IF_NOT_OK(sys.connect(sock, kernel));
161
162 std::unique_ptr<NetlinkListenerInterface> listener =
163 std::make_unique<NetlinkListener>(std::move(event), std::move(sock), "SkDestroyListen");
164
165 return listener;
166}
167
Wayne Ma4d692332022-01-19 16:04:04 +0800168Status TrafficController::initMaps() {
169 std::lock_guard guard(mMutex);
170
171 RETURN_IF_NOT_OK(mCookieTagMap.init(COOKIE_TAG_MAP_PATH));
172 RETURN_IF_NOT_OK(mUidCounterSetMap.init(UID_COUNTERSET_MAP_PATH));
173 RETURN_IF_NOT_OK(mAppUidStatsMap.init(APP_UID_STATS_MAP_PATH));
174 RETURN_IF_NOT_OK(mStatsMapA.init(STATS_MAP_A_PATH));
175 RETURN_IF_NOT_OK(mStatsMapB.init(STATS_MAP_B_PATH));
176 RETURN_IF_NOT_OK(mIfaceIndexNameMap.init(IFACE_INDEX_NAME_MAP_PATH));
177 RETURN_IF_NOT_OK(mIfaceStatsMap.init(IFACE_STATS_MAP_PATH));
178
179 RETURN_IF_NOT_OK(mConfigurationMap.init(CONFIGURATION_MAP_PATH));
180 RETURN_IF_NOT_OK(
181 mConfigurationMap.writeValue(UID_RULES_CONFIGURATION_KEY, DEFAULT_CONFIG, BPF_ANY));
182 RETURN_IF_NOT_OK(mConfigurationMap.writeValue(CURRENT_STATS_MAP_CONFIGURATION_KEY, SELECT_MAP_A,
183 BPF_ANY));
184
185 RETURN_IF_NOT_OK(mUidOwnerMap.init(UID_OWNER_MAP_PATH));
186 RETURN_IF_NOT_OK(mUidOwnerMap.clear());
187 RETURN_IF_NOT_OK(mUidPermissionMap.init(UID_PERMISSION_MAP_PATH));
188
189 return netdutils::status::ok;
190}
191
Wayne Ma4d692332022-01-19 16:04:04 +0800192Status TrafficController::start() {
Wayne Ma4d692332022-01-19 16:04:04 +0800193 RETURN_IF_NOT_OK(initMaps());
194
Wayne Ma4d692332022-01-19 16:04:04 +0800195 // Fetch the list of currently-existing interfaces. At this point NetlinkHandler is
196 // already running, so it will call addInterface() when any new interface appears.
Wayne Maa9716ff2022-01-12 10:37:04 +0800197 // TODO: Clean-up addInterface() after interface monitoring is in
198 // NetworkStatsService.
Wayne Ma4d692332022-01-19 16:04:04 +0800199 std::map<std::string, uint32_t> ifacePairs;
200 ASSIGN_OR_RETURN(ifacePairs, getIfaceList());
201 for (const auto& ifacePair:ifacePairs) {
202 addInterface(ifacePair.first.c_str(), ifacePair.second);
203 }
204
205 auto result = makeSkDestroyListener();
206 if (!isOk(result)) {
207 ALOGE("Unable to create SkDestroyListener: %s", toString(result).c_str());
208 } else {
209 mSkDestroyListener = std::move(result.value());
210 }
211 // Rx handler extracts nfgenmsg looks up and invokes registered dispatch function.
212 const auto rxHandler = [this](const nlmsghdr&, const Slice msg) {
213 std::lock_guard guard(mMutex);
214 inet_diag_msg diagmsg = {};
215 if (extract(msg, diagmsg) < sizeof(inet_diag_msg)) {
216 ALOGE("Unrecognized netlink message: %s", toString(msg).c_str());
217 return;
218 }
219 uint64_t sock_cookie = static_cast<uint64_t>(diagmsg.id.idiag_cookie[0]) |
220 (static_cast<uint64_t>(diagmsg.id.idiag_cookie[1]) << 32);
221
222 Status s = mCookieTagMap.deleteValue(sock_cookie);
223 if (!isOk(s) && s.code() != ENOENT) {
224 ALOGE("Failed to delete cookie %" PRIx64 ": %s", sock_cookie, toString(s).c_str());
225 return;
226 }
227 };
228 expectOk(mSkDestroyListener->subscribe(kSockDiagMsgType, rxHandler));
229
230 // In case multiple netlink message comes in as a stream, we need to handle the rxDone message
231 // properly.
232 const auto rxDoneHandler = [](const nlmsghdr&, const Slice msg) {
233 // Ignore NLMSG_DONE messages
234 inet_diag_msg diagmsg = {};
235 extract(msg, diagmsg);
236 };
237 expectOk(mSkDestroyListener->subscribe(kSockDiagDoneMsgType, rxDoneHandler));
238
239 return netdutils::status::ok;
240}
241
Wayne Ma4d692332022-01-19 16:04:04 +0800242int TrafficController::setCounterSet(int counterSetNum, uid_t uid, uid_t callingUid) {
243 if (counterSetNum < 0 || counterSetNum >= OVERFLOW_COUNTERSET) return -EINVAL;
244
245 std::lock_guard guard(mMutex);
246 if (!hasUpdateDeviceStatsPermission(callingUid)) return -EPERM;
247
248 // The default counter set for all uid is 0, so deleting the current counterset for that uid
249 // will automatically set it to 0.
250 if (counterSetNum == 0) {
251 Status res = mUidCounterSetMap.deleteValue(uid);
252 if (isOk(res) || (!isOk(res) && res.code() == ENOENT)) {
253 return 0;
254 } else {
255 ALOGE("Failed to delete the counterSet: %s\n", strerror(res.code()));
256 return -res.code();
257 }
258 }
259 uint8_t tmpCounterSetNum = (uint8_t)counterSetNum;
260 Status res = mUidCounterSetMap.writeValue(uid, tmpCounterSetNum, BPF_ANY);
261 if (!isOk(res)) {
262 ALOGE("Failed to set the counterSet: %s, fd: %d", strerror(res.code()),
263 mUidCounterSetMap.getMap().get());
264 return -res.code();
265 }
266 return 0;
267}
268
269// This method only get called by system_server when an app get uinstalled, it
270// is called inside removeUidsLocked() while holding mStatsLock. So it is safe
271// to iterate and modify the stats maps.
272int TrafficController::deleteTagData(uint32_t tag, uid_t uid, uid_t callingUid) {
273 std::lock_guard guard(mMutex);
274 if (!hasUpdateDeviceStatsPermission(callingUid)) return -EPERM;
275
276 // First we go through the cookieTagMap to delete the target uid tag combination. Or delete all
277 // the tags related to the uid if the tag is 0.
278 const auto deleteMatchedCookieEntries = [uid, tag](const uint64_t& key,
279 const UidTagValue& value,
280 BpfMap<uint64_t, UidTagValue>& map) {
281 if (value.uid == uid && (value.tag == tag || tag == 0)) {
282 auto res = map.deleteValue(key);
283 if (res.ok() || (res.error().code() == ENOENT)) {
284 return base::Result<void>();
285 }
286 ALOGE("Failed to delete data(cookie = %" PRIu64 "): %s\n", key,
287 strerror(res.error().code()));
288 }
289 // Move forward to next cookie in the map.
290 return base::Result<void>();
291 };
292 mCookieTagMap.iterateWithValue(deleteMatchedCookieEntries);
293 // Now we go through the Tag stats map and delete the data entry with correct uid and tag
294 // combination. Or all tag stats under that uid if the target tag is 0.
295 const auto deleteMatchedUidTagEntries = [uid, tag](const StatsKey& key,
296 BpfMap<StatsKey, StatsValue>& map) {
297 if (key.uid == uid && (key.tag == tag || tag == 0)) {
298 auto res = map.deleteValue(key);
299 if (res.ok() || (res.error().code() == ENOENT)) {
300 //Entry is deleted, use the current key to get a new nextKey;
301 return base::Result<void>();
302 }
303 ALOGE("Failed to delete data(uid=%u, tag=%u): %s\n", key.uid, key.tag,
304 strerror(res.error().code()));
305 }
306 return base::Result<void>();
307 };
308 mStatsMapB.iterate(deleteMatchedUidTagEntries);
309 mStatsMapA.iterate(deleteMatchedUidTagEntries);
310 // If the tag is not zero, we already deleted all the data entry required. If tag is 0, we also
311 // need to delete the stats stored in uidStatsMap and counterSet map.
312 if (tag != 0) return 0;
313
314 auto res = mUidCounterSetMap.deleteValue(uid);
315 if (!res.ok() && res.error().code() != ENOENT) {
316 ALOGE("Failed to delete counterSet data(uid=%u, tag=%u): %s\n", uid, tag,
317 strerror(res.error().code()));
318 }
319
320 auto deleteAppUidStatsEntry = [uid](const uint32_t& key,
321 BpfMap<uint32_t, StatsValue>& map) -> base::Result<void> {
322 if (key == uid) {
323 auto res = map.deleteValue(key);
324 if (res.ok() || (res.error().code() == ENOENT)) {
325 return {};
326 }
327 ALOGE("Failed to delete data(uid=%u): %s", key, strerror(res.error().code()));
328 }
329 return {};
330 };
331 mAppUidStatsMap.iterate(deleteAppUidStatsEntry);
332 return 0;
333}
334
335int TrafficController::addInterface(const char* name, uint32_t ifaceIndex) {
336 IfaceValue iface;
337 if (ifaceIndex == 0) {
338 ALOGE("Unknown interface %s(%d)", name, ifaceIndex);
339 return -1;
340 }
341
342 strlcpy(iface.name, name, sizeof(IfaceValue));
343 Status res = mIfaceIndexNameMap.writeValue(ifaceIndex, iface, BPF_ANY);
344 if (!isOk(res)) {
345 ALOGE("Failed to add iface %s(%d): %s", name, ifaceIndex, strerror(res.code()));
346 return -res.code();
347 }
348 return 0;
349}
350
351Status TrafficController::updateOwnerMapEntry(UidOwnerMatchType match, uid_t uid, FirewallRule rule,
352 FirewallType type) {
353 std::lock_guard guard(mMutex);
354 if ((rule == ALLOW && type == ALLOWLIST) || (rule == DENY && type == DENYLIST)) {
355 RETURN_IF_NOT_OK(addRule(uid, match));
356 } else if ((rule == ALLOW && type == DENYLIST) || (rule == DENY && type == ALLOWLIST)) {
357 RETURN_IF_NOT_OK(removeRule(uid, match));
358 } else {
359 //Cannot happen.
360 return statusFromErrno(EINVAL, "");
361 }
362 return netdutils::status::ok;
363}
364
365Status TrafficController::removeRule(uint32_t uid, UidOwnerMatchType match) {
366 auto oldMatch = mUidOwnerMap.readValue(uid);
367 if (oldMatch.ok()) {
368 UidOwnerValue newMatch = {
369 .iif = (match == IIF_MATCH) ? 0 : oldMatch.value().iif,
370 .rule = static_cast<uint8_t>(oldMatch.value().rule & ~match),
371 };
372 if (newMatch.rule == 0) {
373 RETURN_IF_NOT_OK(mUidOwnerMap.deleteValue(uid));
374 } else {
375 RETURN_IF_NOT_OK(mUidOwnerMap.writeValue(uid, newMatch, BPF_ANY));
376 }
377 } else {
378 return statusFromErrno(ENOENT, StringPrintf("uid: %u does not exist in map", uid));
379 }
380 return netdutils::status::ok;
381}
382
383Status TrafficController::addRule(uint32_t uid, UidOwnerMatchType match, uint32_t iif) {
384 // iif should be non-zero if and only if match == MATCH_IIF
385 if (match == IIF_MATCH && iif == 0) {
386 return statusFromErrno(EINVAL, "Interface match must have nonzero interface index");
387 } else if (match != IIF_MATCH && iif != 0) {
388 return statusFromErrno(EINVAL, "Non-interface match must have zero interface index");
389 }
390 auto oldMatch = mUidOwnerMap.readValue(uid);
391 if (oldMatch.ok()) {
392 UidOwnerValue newMatch = {
393 .iif = iif ? iif : oldMatch.value().iif,
394 .rule = static_cast<uint8_t>(oldMatch.value().rule | match),
395 };
396 RETURN_IF_NOT_OK(mUidOwnerMap.writeValue(uid, newMatch, BPF_ANY));
397 } else {
398 UidOwnerValue newMatch = {
399 .iif = iif,
400 .rule = static_cast<uint8_t>(match),
401 };
402 RETURN_IF_NOT_OK(mUidOwnerMap.writeValue(uid, newMatch, BPF_ANY));
403 }
404 return netdutils::status::ok;
405}
406
Wayne Maa9716ff2022-01-12 10:37:04 +0800407Status TrafficController::updateUidOwnerMap(const uint32_t uid,
Wayne Ma4d692332022-01-19 16:04:04 +0800408 UidOwnerMatchType matchType, IptOp op) {
409 std::lock_guard guard(mMutex);
Wayne Maa9716ff2022-01-12 10:37:04 +0800410 if (op == IptOpDelete) {
411 RETURN_IF_NOT_OK(removeRule(uid, matchType));
412 } else if (op == IptOpInsert) {
413 RETURN_IF_NOT_OK(addRule(uid, matchType));
414 } else {
415 // Cannot happen.
416 return statusFromErrno(EINVAL, StringPrintf("invalid IptOp: %d, %d", op, matchType));
Wayne Ma4d692332022-01-19 16:04:04 +0800417 }
418 return netdutils::status::ok;
419}
420
421FirewallType TrafficController::getFirewallType(ChildChain chain) {
422 switch (chain) {
423 case DOZABLE:
424 return ALLOWLIST;
425 case STANDBY:
426 return DENYLIST;
427 case POWERSAVE:
428 return ALLOWLIST;
429 case RESTRICTED:
430 return ALLOWLIST;
Robert Horvathd945bf02022-01-27 19:55:16 +0100431 case LOW_POWER_STANDBY:
432 return ALLOWLIST;
Wayne Ma4d692332022-01-19 16:04:04 +0800433 case NONE:
434 default:
435 return DENYLIST;
436 }
437}
438
439int TrafficController::changeUidOwnerRule(ChildChain chain, uid_t uid, FirewallRule rule,
440 FirewallType type) {
441 Status res;
442 switch (chain) {
443 case DOZABLE:
444 res = updateOwnerMapEntry(DOZABLE_MATCH, uid, rule, type);
445 break;
446 case STANDBY:
447 res = updateOwnerMapEntry(STANDBY_MATCH, uid, rule, type);
448 break;
449 case POWERSAVE:
450 res = updateOwnerMapEntry(POWERSAVE_MATCH, uid, rule, type);
451 break;
452 case RESTRICTED:
453 res = updateOwnerMapEntry(RESTRICTED_MATCH, uid, rule, type);
454 break;
Robert Horvathd945bf02022-01-27 19:55:16 +0100455 case LOW_POWER_STANDBY:
456 res = updateOwnerMapEntry(LOW_POWER_STANDBY_MATCH, uid, rule, type);
457 break;
Wayne Ma4d692332022-01-19 16:04:04 +0800458 case NONE:
459 default:
460 ALOGW("Unknown child chain: %d", chain);
461 return -EINVAL;
462 }
463 if (!isOk(res)) {
464 ALOGE("change uid(%u) rule of %d failed: %s, rule: %d, type: %d", uid, chain,
465 res.msg().c_str(), rule, type);
466 return -res.code();
467 }
468 return 0;
469}
470
471Status TrafficController::replaceRulesInMap(const UidOwnerMatchType match,
472 const std::vector<int32_t>& uids) {
473 std::lock_guard guard(mMutex);
474 std::set<int32_t> uidSet(uids.begin(), uids.end());
475 std::vector<uint32_t> uidsToDelete;
476 auto getUidsToDelete = [&uidsToDelete, &uidSet](const uint32_t& key,
477 const BpfMap<uint32_t, UidOwnerValue>&) {
478 if (uidSet.find((int32_t) key) == uidSet.end()) {
479 uidsToDelete.push_back(key);
480 }
481 return base::Result<void>();
482 };
483 RETURN_IF_NOT_OK(mUidOwnerMap.iterate(getUidsToDelete));
484
485 for(auto uid : uidsToDelete) {
486 RETURN_IF_NOT_OK(removeRule(uid, match));
487 }
488
489 for (auto uid : uids) {
490 RETURN_IF_NOT_OK(addRule(uid, match));
491 }
492 return netdutils::status::ok;
493}
494
495Status TrafficController::addUidInterfaceRules(const int iif,
496 const std::vector<int32_t>& uidsToAdd) {
497 if (!iif) {
498 return statusFromErrno(EINVAL, "Interface rule must specify interface");
499 }
500 std::lock_guard guard(mMutex);
501
502 for (auto uid : uidsToAdd) {
503 netdutils::Status result = addRule(uid, IIF_MATCH, iif);
504 if (!isOk(result)) {
505 ALOGW("addRule failed(%d): uid=%d iif=%d", result.code(), uid, iif);
506 }
507 }
508 return netdutils::status::ok;
509}
510
511Status TrafficController::removeUidInterfaceRules(const std::vector<int32_t>& uidsToDelete) {
512 std::lock_guard guard(mMutex);
513
514 for (auto uid : uidsToDelete) {
515 netdutils::Status result = removeRule(uid, IIF_MATCH);
516 if (!isOk(result)) {
517 ALOGW("removeRule failed(%d): uid=%d", result.code(), uid);
518 }
519 }
520 return netdutils::status::ok;
521}
522
523int TrafficController::replaceUidOwnerMap(const std::string& name, bool isAllowlist __unused,
524 const std::vector<int32_t>& uids) {
525 // FirewallRule rule = isAllowlist ? ALLOW : DENY;
526 // FirewallType type = isAllowlist ? ALLOWLIST : DENYLIST;
527 Status res;
528 if (!name.compare(LOCAL_DOZABLE)) {
529 res = replaceRulesInMap(DOZABLE_MATCH, uids);
530 } else if (!name.compare(LOCAL_STANDBY)) {
531 res = replaceRulesInMap(STANDBY_MATCH, uids);
532 } else if (!name.compare(LOCAL_POWERSAVE)) {
533 res = replaceRulesInMap(POWERSAVE_MATCH, uids);
534 } else if (!name.compare(LOCAL_RESTRICTED)) {
535 res = replaceRulesInMap(RESTRICTED_MATCH, uids);
Robert Horvathd945bf02022-01-27 19:55:16 +0100536 } else if (!name.compare(LOCAL_LOW_POWER_STANDBY)) {
537 res = replaceRulesInMap(LOW_POWER_STANDBY_MATCH, uids);
Wayne Ma4d692332022-01-19 16:04:04 +0800538 } else {
539 ALOGE("unknown chain name: %s", name.c_str());
540 return -EINVAL;
541 }
542 if (!isOk(res)) {
543 ALOGE("Failed to clean up chain: %s: %s", name.c_str(), res.msg().c_str());
544 return -res.code();
545 }
546 return 0;
547}
548
549int TrafficController::toggleUidOwnerMap(ChildChain chain, bool enable) {
550 std::lock_guard guard(mMutex);
551 uint32_t key = UID_RULES_CONFIGURATION_KEY;
552 auto oldConfiguration = mConfigurationMap.readValue(key);
553 if (!oldConfiguration.ok()) {
554 ALOGE("Cannot read the old configuration from map: %s",
555 oldConfiguration.error().message().c_str());
556 return -oldConfiguration.error().code();
557 }
558 Status res;
559 BpfConfig newConfiguration;
560 uint8_t match;
561 switch (chain) {
562 case DOZABLE:
563 match = DOZABLE_MATCH;
564 break;
565 case STANDBY:
566 match = STANDBY_MATCH;
567 break;
568 case POWERSAVE:
569 match = POWERSAVE_MATCH;
570 break;
571 case RESTRICTED:
572 match = RESTRICTED_MATCH;
573 break;
Robert Horvathd945bf02022-01-27 19:55:16 +0100574 case LOW_POWER_STANDBY:
575 match = LOW_POWER_STANDBY_MATCH;
576 break;
Wayne Ma4d692332022-01-19 16:04:04 +0800577 default:
578 return -EINVAL;
579 }
580 newConfiguration =
581 enable ? (oldConfiguration.value() | match) : (oldConfiguration.value() & (~match));
582 res = mConfigurationMap.writeValue(key, newConfiguration, BPF_EXIST);
583 if (!isOk(res)) {
584 ALOGE("Failed to toggleUidOwnerMap(%d): %s", chain, res.msg().c_str());
585 }
586 return -res.code();
587}
588
589Status TrafficController::swapActiveStatsMap() {
590 std::lock_guard guard(mMutex);
591
592 uint32_t key = CURRENT_STATS_MAP_CONFIGURATION_KEY;
593 auto oldConfiguration = mConfigurationMap.readValue(key);
594 if (!oldConfiguration.ok()) {
595 ALOGE("Cannot read the old configuration from map: %s",
596 oldConfiguration.error().message().c_str());
597 return Status(oldConfiguration.error().code(), oldConfiguration.error().message());
598 }
599
600 // Write to the configuration map to inform the kernel eBPF program to switch
601 // from using one map to the other. Use flag BPF_EXIST here since the map should
602 // be already populated in initMaps.
603 uint8_t newConfigure = (oldConfiguration.value() == SELECT_MAP_A) ? SELECT_MAP_B : SELECT_MAP_A;
604 auto res = mConfigurationMap.writeValue(CURRENT_STATS_MAP_CONFIGURATION_KEY, newConfigure,
605 BPF_EXIST);
606 if (!res.ok()) {
607 ALOGE("Failed to toggle the stats map: %s", strerror(res.error().code()));
608 return res;
609 }
610 // After changing the config, we need to make sure all the current running
611 // eBPF programs are finished and all the CPUs are aware of this config change
612 // before we modify the old map. So we do a special hack here to wait for
613 // the kernel to do a synchronize_rcu(). Once the kernel called
614 // synchronize_rcu(), the config we just updated will be available to all cores
615 // and the next eBPF programs triggered inside the kernel will use the new
616 // map configuration. So once this function returns we can safely modify the
617 // old stats map without concerning about race between the kernel and
618 // userspace.
619 int ret = synchronizeKernelRCU();
620 if (ret) {
621 ALOGE("map swap synchronize_rcu() ended with failure: %s", strerror(-ret));
622 return statusFromErrno(-ret, "map swap synchronize_rcu() failed");
623 }
624 return netdutils::status::ok;
625}
626
627void TrafficController::setPermissionForUids(int permission, const std::vector<uid_t>& uids) {
628 std::lock_guard guard(mMutex);
629 if (permission == INetd::PERMISSION_UNINSTALLED) {
630 for (uid_t uid : uids) {
631 // Clean up all permission information for the related uid if all the
632 // packages related to it are uninstalled.
633 mPrivilegedUser.erase(uid);
634 Status ret = mUidPermissionMap.deleteValue(uid);
635 if (!isOk(ret) && ret.code() != ENOENT) {
636 ALOGE("Failed to clean up the permission for %u: %s", uid, strerror(ret.code()));
637 }
638 }
639 return;
640 }
641
642 bool privileged = (permission & INetd::PERMISSION_UPDATE_DEVICE_STATS);
643
644 for (uid_t uid : uids) {
645 if (privileged) {
646 mPrivilegedUser.insert(uid);
647 } else {
648 mPrivilegedUser.erase(uid);
649 }
650
651 // The map stores all the permissions that the UID has, except if the only permission
652 // the UID has is the INTERNET permission, then the UID should not appear in the map.
653 if (permission != INetd::PERMISSION_INTERNET) {
654 Status ret = mUidPermissionMap.writeValue(uid, permission, BPF_ANY);
655 if (!isOk(ret)) {
656 ALOGE("Failed to set permission: %s of uid(%u) to permission map: %s",
657 UidPermissionTypeToString(permission).c_str(), uid, strerror(ret.code()));
658 }
659 } else {
660 Status ret = mUidPermissionMap.deleteValue(uid);
661 if (!isOk(ret) && ret.code() != ENOENT) {
662 ALOGE("Failed to remove uid %u from permission map: %s", uid, strerror(ret.code()));
663 }
664 }
665 }
666}
667
668std::string getProgramStatus(const char *path) {
669 int ret = access(path, R_OK);
670 if (ret == 0) {
671 return StringPrintf("OK");
672 }
673 if (ret != 0 && errno == ENOENT) {
674 return StringPrintf("program is missing at: %s", path);
675 }
676 return StringPrintf("check Program %s error: %s", path, strerror(errno));
677}
678
679std::string getMapStatus(const base::unique_fd& map_fd, const char* path) {
680 if (map_fd.get() < 0) {
681 return StringPrintf("map fd lost");
682 }
683 if (access(path, F_OK) != 0) {
684 return StringPrintf("map not pinned to location: %s", path);
685 }
686 return StringPrintf("OK");
687}
688
689// NOLINTNEXTLINE(google-runtime-references): grandfathered pass by non-const reference
690void dumpBpfMap(const std::string& mapName, DumpWriter& dw, const std::string& header) {
691 dw.blankline();
692 dw.println("%s:", mapName.c_str());
693 if (!header.empty()) {
694 dw.println(header);
695 }
696}
697
Wayne Ma4d692332022-01-19 16:04:04 +0800698void TrafficController::dump(DumpWriter& dw, bool verbose) {
699 std::lock_guard guard(mMutex);
700 ScopedIndent indentTop(dw);
701 dw.println("TrafficController");
702
703 ScopedIndent indentPreBpfModule(dw);
704
705 dw.blankline();
706 dw.println("mCookieTagMap status: %s",
707 getMapStatus(mCookieTagMap.getMap(), COOKIE_TAG_MAP_PATH).c_str());
708 dw.println("mUidCounterSetMap status: %s",
709 getMapStatus(mUidCounterSetMap.getMap(), UID_COUNTERSET_MAP_PATH).c_str());
710 dw.println("mAppUidStatsMap status: %s",
711 getMapStatus(mAppUidStatsMap.getMap(), APP_UID_STATS_MAP_PATH).c_str());
712 dw.println("mStatsMapA status: %s",
713 getMapStatus(mStatsMapA.getMap(), STATS_MAP_A_PATH).c_str());
714 dw.println("mStatsMapB status: %s",
715 getMapStatus(mStatsMapB.getMap(), STATS_MAP_B_PATH).c_str());
716 dw.println("mIfaceIndexNameMap status: %s",
717 getMapStatus(mIfaceIndexNameMap.getMap(), IFACE_INDEX_NAME_MAP_PATH).c_str());
718 dw.println("mIfaceStatsMap status: %s",
719 getMapStatus(mIfaceStatsMap.getMap(), IFACE_STATS_MAP_PATH).c_str());
720 dw.println("mConfigurationMap status: %s",
721 getMapStatus(mConfigurationMap.getMap(), CONFIGURATION_MAP_PATH).c_str());
722 dw.println("mUidOwnerMap status: %s",
723 getMapStatus(mUidOwnerMap.getMap(), UID_OWNER_MAP_PATH).c_str());
724
725 dw.blankline();
726 dw.println("Cgroup ingress program status: %s",
727 getProgramStatus(BPF_INGRESS_PROG_PATH).c_str());
728 dw.println("Cgroup egress program status: %s", getProgramStatus(BPF_EGRESS_PROG_PATH).c_str());
729 dw.println("xt_bpf ingress program status: %s",
730 getProgramStatus(XT_BPF_INGRESS_PROG_PATH).c_str());
731 dw.println("xt_bpf egress program status: %s",
732 getProgramStatus(XT_BPF_EGRESS_PROG_PATH).c_str());
733 dw.println("xt_bpf bandwidth allowlist program status: %s",
734 getProgramStatus(XT_BPF_ALLOWLIST_PROG_PATH).c_str());
735 dw.println("xt_bpf bandwidth denylist program status: %s",
736 getProgramStatus(XT_BPF_DENYLIST_PROG_PATH).c_str());
737
738 if (!verbose) {
739 return;
740 }
741
742 dw.blankline();
743 dw.println("BPF map content:");
744
745 ScopedIndent indentForMapContent(dw);
746
747 // Print CookieTagMap content.
748 dumpBpfMap("mCookieTagMap", dw, "");
749 const auto printCookieTagInfo = [&dw](const uint64_t& key, const UidTagValue& value,
750 const BpfMap<uint64_t, UidTagValue>&) {
751 dw.println("cookie=%" PRIu64 " tag=0x%x uid=%u", key, value.tag, value.uid);
752 return base::Result<void>();
753 };
754 base::Result<void> res = mCookieTagMap.iterateWithValue(printCookieTagInfo);
755 if (!res.ok()) {
756 dw.println("mCookieTagMap print end with error: %s", res.error().message().c_str());
757 }
758
Wayne Maa9716ff2022-01-12 10:37:04 +0800759 // Print UidCounterSetMap content.
Wayne Ma4d692332022-01-19 16:04:04 +0800760 dumpBpfMap("mUidCounterSetMap", dw, "");
761 const auto printUidInfo = [&dw](const uint32_t& key, const uint8_t& value,
762 const BpfMap<uint32_t, uint8_t>&) {
763 dw.println("%u %u", key, value);
764 return base::Result<void>();
765 };
766 res = mUidCounterSetMap.iterateWithValue(printUidInfo);
767 if (!res.ok()) {
768 dw.println("mUidCounterSetMap print end with error: %s", res.error().message().c_str());
769 }
770
Wayne Maa9716ff2022-01-12 10:37:04 +0800771 // Print AppUidStatsMap content.
Wayne Ma4d692332022-01-19 16:04:04 +0800772 std::string appUidStatsHeader = StringPrintf("uid rxBytes rxPackets txBytes txPackets");
773 dumpBpfMap("mAppUidStatsMap:", dw, appUidStatsHeader);
774 auto printAppUidStatsInfo = [&dw](const uint32_t& key, const StatsValue& value,
775 const BpfMap<uint32_t, StatsValue>&) {
776 dw.println("%u %" PRIu64 " %" PRIu64 " %" PRIu64 " %" PRIu64, key, value.rxBytes,
777 value.rxPackets, value.txBytes, value.txPackets);
778 return base::Result<void>();
779 };
780 res = mAppUidStatsMap.iterateWithValue(printAppUidStatsInfo);
781 if (!res.ok()) {
782 dw.println("mAppUidStatsMap print end with error: %s", res.error().message().c_str());
783 }
784
Wayne Maa9716ff2022-01-12 10:37:04 +0800785 // Print uidStatsMap content.
Wayne Ma4d692332022-01-19 16:04:04 +0800786 std::string statsHeader = StringPrintf("ifaceIndex ifaceName tag_hex uid_int cnt_set rxBytes"
787 " rxPackets txBytes txPackets");
788 dumpBpfMap("mStatsMapA", dw, statsHeader);
789 const auto printStatsInfo = [&dw, this](const StatsKey& key, const StatsValue& value,
790 const BpfMap<StatsKey, StatsValue>&) {
791 uint32_t ifIndex = key.ifaceIndex;
792 auto ifname = mIfaceIndexNameMap.readValue(ifIndex);
793 if (!ifname.ok()) {
794 ifname = IfaceValue{"unknown"};
795 }
796 dw.println("%u %s 0x%x %u %u %" PRIu64 " %" PRIu64 " %" PRIu64 " %" PRIu64, ifIndex,
797 ifname.value().name, key.tag, key.uid, key.counterSet, value.rxBytes,
798 value.rxPackets, value.txBytes, value.txPackets);
799 return base::Result<void>();
800 };
801 res = mStatsMapA.iterateWithValue(printStatsInfo);
802 if (!res.ok()) {
803 dw.println("mStatsMapA print end with error: %s", res.error().message().c_str());
804 }
805
806 // Print TagStatsMap content.
807 dumpBpfMap("mStatsMapB", dw, statsHeader);
808 res = mStatsMapB.iterateWithValue(printStatsInfo);
809 if (!res.ok()) {
810 dw.println("mStatsMapB print end with error: %s", res.error().message().c_str());
811 }
812
813 // Print ifaceIndexToNameMap content.
814 dumpBpfMap("mIfaceIndexNameMap", dw, "");
815 const auto printIfaceNameInfo = [&dw](const uint32_t& key, const IfaceValue& value,
816 const BpfMap<uint32_t, IfaceValue>&) {
817 const char* ifname = value.name;
818 dw.println("ifaceIndex=%u ifaceName=%s", key, ifname);
819 return base::Result<void>();
820 };
821 res = mIfaceIndexNameMap.iterateWithValue(printIfaceNameInfo);
822 if (!res.ok()) {
823 dw.println("mIfaceIndexNameMap print end with error: %s", res.error().message().c_str());
824 }
825
826 // Print ifaceStatsMap content
827 std::string ifaceStatsHeader = StringPrintf("ifaceIndex ifaceName rxBytes rxPackets txBytes"
828 " txPackets");
829 dumpBpfMap("mIfaceStatsMap:", dw, ifaceStatsHeader);
830 const auto printIfaceStatsInfo = [&dw, this](const uint32_t& key, const StatsValue& value,
831 const BpfMap<uint32_t, StatsValue>&) {
832 auto ifname = mIfaceIndexNameMap.readValue(key);
833 if (!ifname.ok()) {
834 ifname = IfaceValue{"unknown"};
835 }
836 dw.println("%u %s %" PRIu64 " %" PRIu64 " %" PRIu64 " %" PRIu64, key, ifname.value().name,
837 value.rxBytes, value.rxPackets, value.txBytes, value.txPackets);
838 return base::Result<void>();
839 };
840 res = mIfaceStatsMap.iterateWithValue(printIfaceStatsInfo);
841 if (!res.ok()) {
842 dw.println("mIfaceStatsMap print end with error: %s", res.error().message().c_str());
843 }
844
845 dw.blankline();
846
847 uint32_t key = UID_RULES_CONFIGURATION_KEY;
848 auto configuration = mConfigurationMap.readValue(key);
849 if (configuration.ok()) {
850 dw.println("current ownerMatch configuration: %d%s", configuration.value(),
851 uidMatchTypeToString(configuration.value()).c_str());
852 } else {
853 dw.println("mConfigurationMap read ownerMatch configure failed with error: %s",
854 configuration.error().message().c_str());
855 }
856
857 key = CURRENT_STATS_MAP_CONFIGURATION_KEY;
858 configuration = mConfigurationMap.readValue(key);
859 if (configuration.ok()) {
860 const char* statsMapDescription = "???";
861 switch (configuration.value()) {
862 case SELECT_MAP_A:
863 statsMapDescription = "SELECT_MAP_A";
864 break;
865 case SELECT_MAP_B:
866 statsMapDescription = "SELECT_MAP_B";
867 break;
868 // No default clause, so if we ever add a third map, this code will fail to build.
869 }
870 dw.println("current statsMap configuration: %d %s", configuration.value(),
871 statsMapDescription);
872 } else {
873 dw.println("mConfigurationMap read stats map configure failed with error: %s",
874 configuration.error().message().c_str());
875 }
876 dumpBpfMap("mUidOwnerMap", dw, "");
877 const auto printUidMatchInfo = [&dw, this](const uint32_t& key, const UidOwnerValue& value,
878 const BpfMap<uint32_t, UidOwnerValue>&) {
879 if (value.rule & IIF_MATCH) {
880 auto ifname = mIfaceIndexNameMap.readValue(value.iif);
881 if (ifname.ok()) {
882 dw.println("%u %s %s", key, uidMatchTypeToString(value.rule).c_str(),
883 ifname.value().name);
884 } else {
885 dw.println("%u %s %u", key, uidMatchTypeToString(value.rule).c_str(), value.iif);
886 }
887 } else {
888 dw.println("%u %s", key, uidMatchTypeToString(value.rule).c_str());
889 }
890 return base::Result<void>();
891 };
892 res = mUidOwnerMap.iterateWithValue(printUidMatchInfo);
893 if (!res.ok()) {
894 dw.println("mUidOwnerMap print end with error: %s", res.error().message().c_str());
895 }
896 dumpBpfMap("mUidPermissionMap", dw, "");
897 const auto printUidPermissionInfo = [&dw](const uint32_t& key, const int& value,
898 const BpfMap<uint32_t, uint8_t>&) {
899 dw.println("%u %s", key, UidPermissionTypeToString(value).c_str());
900 return base::Result<void>();
901 };
902 res = mUidPermissionMap.iterateWithValue(printUidPermissionInfo);
903 if (!res.ok()) {
904 dw.println("mUidPermissionMap print end with error: %s", res.error().message().c_str());
905 }
906
907 dumpBpfMap("mPrivilegedUser", dw, "");
908 for (uid_t uid : mPrivilegedUser) {
909 dw.println("%u ALLOW_UPDATE_DEVICE_STATS", (uint32_t)uid);
910 }
911}
912
913} // namespace net
914} // namespace android