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