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