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