blob: 68fc9c87cd1b7e336ee7d296c3b2e4b1a929b947 [file] [log] [blame]
Wayne Ma4d692332022-01-19 16:04:04 +08001/*
Wayne Maa9716ff2022-01-12 10:37:04 +08002 * Copyright (C) 2022 The Android Open Source Project
Wayne Ma4d692332022-01-19 16:04:04 +08003 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "TrafficController"
18#include <inttypes.h>
Wayne Ma4d692332022-01-19 16:04:04 +080019#include <linux/if_ether.h>
20#include <linux/in.h>
21#include <linux/inet_diag.h>
22#include <linux/netlink.h>
23#include <linux/sock_diag.h>
24#include <linux/unistd.h>
25#include <net/if.h>
26#include <stdlib.h>
27#include <string.h>
28#include <sys/socket.h>
29#include <sys/stat.h>
30#include <sys/types.h>
31#include <sys/utsname.h>
32#include <sys/wait.h>
Wayne Maa9716ff2022-01-12 10:37:04 +080033#include <map>
Wayne Ma4d692332022-01-19 16:04:04 +080034#include <mutex>
35#include <unordered_set>
36#include <vector>
37
38#include <android-base/stringprintf.h>
39#include <android-base/strings.h>
40#include <android-base/unique_fd.h>
41#include <netdutils/StatusOr.h>
Wayne Ma4d692332022-01-19 16:04:04 +080042#include <netdutils/Syscalls.h>
Ken Chenf426b2b2022-01-23 15:39:13 +080043#include <netdutils/UidConstants.h>
Wayne Ma4d692332022-01-19 16:04:04 +080044#include <netdutils/Utils.h>
Wayne Maa9716ff2022-01-12 10:37:04 +080045#include <private/android_filesystem_config.h>
46
Wayne Ma4d692332022-01-19 16:04:04 +080047#include "TrafficController.h"
48#include "bpf/BpfMap.h"
Wayne Ma4d692332022-01-19 16:04:04 +080049#include "netdutils/DumpWriter.h"
50
51namespace android {
52namespace net {
53
54using base::StringPrintf;
55using base::unique_fd;
56using bpf::BpfMap;
Wayne Ma4d692332022-01-19 16:04:04 +080057using bpf::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;
Wayne Ma4d692332022-01-19 16:04:04 +080068
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";
Robert Horvathd945bf02022-01-27 19:55:16 +010076const char* TrafficController::LOCAL_LOW_POWER_STANDBY = "fw_low_power_standby";
Motomu Utsumid9801492022-06-01 13:57:27 +000077const char* TrafficController::LOCAL_OEM_DENY_1 = "fw_oem_deny_1";
78const char* TrafficController::LOCAL_OEM_DENY_2 = "fw_oem_deny_2";
Wayne Ma4d692332022-01-19 16:04:04 +080079
80static_assert(BPF_PERMISSION_INTERNET == INetd::PERMISSION_INTERNET,
81 "Mismatch between BPF and AIDL permissions: PERMISSION_INTERNET");
82static_assert(BPF_PERMISSION_UPDATE_DEVICE_STATS == INetd::PERMISSION_UPDATE_DEVICE_STATS,
83 "Mismatch between BPF and AIDL permissions: PERMISSION_UPDATE_DEVICE_STATS");
Wayne Ma4d692332022-01-19 16:04:04 +080084
85#define FLAG_MSG_TRANS(result, flag, value) \
86 do { \
87 if ((value) & (flag)) { \
88 (result).append(" " #flag); \
89 (value) &= ~(flag); \
90 } \
91 } while (0)
92
Motomu Utsumi42edc602022-05-12 13:57:42 +000093const std::string uidMatchTypeToString(uint32_t match) {
Wayne Ma4d692332022-01-19 16:04:04 +080094 std::string matchType;
95 FLAG_MSG_TRANS(matchType, HAPPY_BOX_MATCH, match);
96 FLAG_MSG_TRANS(matchType, PENALTY_BOX_MATCH, match);
97 FLAG_MSG_TRANS(matchType, DOZABLE_MATCH, match);
98 FLAG_MSG_TRANS(matchType, STANDBY_MATCH, match);
99 FLAG_MSG_TRANS(matchType, POWERSAVE_MATCH, match);
100 FLAG_MSG_TRANS(matchType, RESTRICTED_MATCH, match);
Robert Horvathd945bf02022-01-27 19:55:16 +0100101 FLAG_MSG_TRANS(matchType, LOW_POWER_STANDBY_MATCH, match);
Wayne Ma4d692332022-01-19 16:04:04 +0800102 FLAG_MSG_TRANS(matchType, IIF_MATCH, match);
Motomu Utsumib08654c2022-05-11 05:56:26 +0000103 FLAG_MSG_TRANS(matchType, LOCKDOWN_VPN_MATCH, match);
Motomu Utsumid9801492022-06-01 13:57:27 +0000104 FLAG_MSG_TRANS(matchType, OEM_DENY_1_MATCH, match);
105 FLAG_MSG_TRANS(matchType, OEM_DENY_2_MATCH, match);
Wayne Ma4d692332022-01-19 16:04:04 +0800106 if (match) {
107 return StringPrintf("Unknown match: %u", match);
108 }
109 return matchType;
110}
111
112bool TrafficController::hasUpdateDeviceStatsPermission(uid_t uid) {
113 // This implementation is the same logic as method ActivityManager#checkComponentPermission.
114 // It implies that the calling uid can never be the same as PER_USER_RANGE.
115 uint32_t appId = uid % PER_USER_RANGE;
116 return ((appId == AID_ROOT) || (appId == AID_SYSTEM) ||
117 mPrivilegedUser.find(appId) != mPrivilegedUser.end());
118}
119
120const std::string UidPermissionTypeToString(int permission) {
121 if (permission == INetd::PERMISSION_NONE) {
122 return "PERMISSION_NONE";
123 }
124 if (permission == INetd::PERMISSION_UNINSTALLED) {
125 // This should never appear in the map, complain loudly if it does.
126 return "PERMISSION_UNINSTALLED error!";
127 }
128 std::string permissionType;
129 FLAG_MSG_TRANS(permissionType, BPF_PERMISSION_INTERNET, permission);
130 FLAG_MSG_TRANS(permissionType, BPF_PERMISSION_UPDATE_DEVICE_STATS, permission);
131 if (permission) {
132 return StringPrintf("Unknown permission: %u", permission);
133 }
134 return permissionType;
135}
136
137StatusOr<std::unique_ptr<NetlinkListenerInterface>> TrafficController::makeSkDestroyListener() {
138 const auto& sys = sSyscalls.get();
139 ASSIGN_OR_RETURN(auto event, sys.eventfd(0, EFD_CLOEXEC));
140 const int domain = AF_NETLINK;
141 const int type = SOCK_DGRAM | SOCK_CLOEXEC | SOCK_NONBLOCK;
142 const int protocol = NETLINK_INET_DIAG;
143 ASSIGN_OR_RETURN(auto sock, sys.socket(domain, type, protocol));
144
145 // TODO: if too many sockets are closed too quickly, we can overflow the socket buffer, and
146 // some entries in mCookieTagMap will not be freed. In order to fix this we would need to
147 // periodically dump all sockets and remove the tag entries for sockets that have been closed.
148 // For now, set a large-enough buffer that we can close hundreds of sockets without getting
149 // ENOBUFS and leaking mCookieTagMap entries.
150 int rcvbuf = 512 * 1024;
151 auto ret = sys.setsockopt(sock, SOL_SOCKET, SO_RCVBUF, &rcvbuf, sizeof(rcvbuf));
152 if (!ret.ok()) {
153 ALOGW("Failed to set SkDestroyListener buffer size to %d: %s", rcvbuf, ret.msg().c_str());
154 }
155
156 sockaddr_nl addr = {
157 .nl_family = AF_NETLINK,
158 .nl_groups = 1 << (SKNLGRP_INET_TCP_DESTROY - 1) | 1 << (SKNLGRP_INET_UDP_DESTROY - 1) |
159 1 << (SKNLGRP_INET6_TCP_DESTROY - 1) | 1 << (SKNLGRP_INET6_UDP_DESTROY - 1)};
160 RETURN_IF_NOT_OK(sys.bind(sock, addr));
161
162 const sockaddr_nl kernel = {.nl_family = AF_NETLINK};
163 RETURN_IF_NOT_OK(sys.connect(sock, kernel));
164
165 std::unique_ptr<NetlinkListenerInterface> listener =
166 std::make_unique<NetlinkListener>(std::move(event), std::move(sock), "SkDestroyListen");
167
168 return listener;
169}
170
Wayne Ma4d692332022-01-19 16:04:04 +0800171Status TrafficController::initMaps() {
172 std::lock_guard guard(mMutex);
173
174 RETURN_IF_NOT_OK(mCookieTagMap.init(COOKIE_TAG_MAP_PATH));
175 RETURN_IF_NOT_OK(mUidCounterSetMap.init(UID_COUNTERSET_MAP_PATH));
176 RETURN_IF_NOT_OK(mAppUidStatsMap.init(APP_UID_STATS_MAP_PATH));
177 RETURN_IF_NOT_OK(mStatsMapA.init(STATS_MAP_A_PATH));
178 RETURN_IF_NOT_OK(mStatsMapB.init(STATS_MAP_B_PATH));
179 RETURN_IF_NOT_OK(mIfaceIndexNameMap.init(IFACE_INDEX_NAME_MAP_PATH));
180 RETURN_IF_NOT_OK(mIfaceStatsMap.init(IFACE_STATS_MAP_PATH));
181
182 RETURN_IF_NOT_OK(mConfigurationMap.init(CONFIGURATION_MAP_PATH));
183 RETURN_IF_NOT_OK(
184 mConfigurationMap.writeValue(UID_RULES_CONFIGURATION_KEY, DEFAULT_CONFIG, BPF_ANY));
185 RETURN_IF_NOT_OK(mConfigurationMap.writeValue(CURRENT_STATS_MAP_CONFIGURATION_KEY, SELECT_MAP_A,
186 BPF_ANY));
187
188 RETURN_IF_NOT_OK(mUidOwnerMap.init(UID_OWNER_MAP_PATH));
189 RETURN_IF_NOT_OK(mUidOwnerMap.clear());
190 RETURN_IF_NOT_OK(mUidPermissionMap.init(UID_PERMISSION_MAP_PATH));
Ken Chen322ffcb2022-05-23 22:27:40 +0800191 ALOGI("%s successfully", __func__);
Wayne Ma4d692332022-01-19 16:04:04 +0800192
193 return netdutils::status::ok;
194}
195
Wayne Ma4d692332022-01-19 16:04:04 +0800196Status TrafficController::start() {
Wayne Ma4d692332022-01-19 16:04:04 +0800197 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.
Wayne Maa9716ff2022-01-12 10:37:04 +0800201 // TODO: Clean-up addInterface() after interface monitoring is in
202 // NetworkStatsService.
Wayne Ma4d692332022-01-19 16:04:04 +0800203 std::map<std::string, uint32_t> ifacePairs;
204 ASSIGN_OR_RETURN(ifacePairs, getIfaceList());
205 for (const auto& ifacePair:ifacePairs) {
206 addInterface(ifacePair.first.c_str(), ifacePair.second);
207 }
208
209 auto result = makeSkDestroyListener();
210 if (!isOk(result)) {
211 ALOGE("Unable to create SkDestroyListener: %s", toString(result).c_str());
212 } else {
213 mSkDestroyListener = std::move(result.value());
214 }
215 // Rx handler extracts nfgenmsg looks up and invokes registered dispatch function.
216 const auto rxHandler = [this](const nlmsghdr&, const Slice msg) {
217 std::lock_guard guard(mMutex);
218 inet_diag_msg diagmsg = {};
219 if (extract(msg, diagmsg) < sizeof(inet_diag_msg)) {
220 ALOGE("Unrecognized netlink message: %s", toString(msg).c_str());
221 return;
222 }
223 uint64_t sock_cookie = static_cast<uint64_t>(diagmsg.id.idiag_cookie[0]) |
224 (static_cast<uint64_t>(diagmsg.id.idiag_cookie[1]) << 32);
225
226 Status s = mCookieTagMap.deleteValue(sock_cookie);
227 if (!isOk(s) && s.code() != ENOENT) {
228 ALOGE("Failed to delete cookie %" PRIx64 ": %s", sock_cookie, toString(s).c_str());
229 return;
230 }
231 };
232 expectOk(mSkDestroyListener->subscribe(kSockDiagMsgType, rxHandler));
233
234 // In case multiple netlink message comes in as a stream, we need to handle the rxDone message
235 // properly.
236 const auto rxDoneHandler = [](const nlmsghdr&, const Slice msg) {
237 // Ignore NLMSG_DONE messages
238 inet_diag_msg diagmsg = {};
239 extract(msg, diagmsg);
240 };
241 expectOk(mSkDestroyListener->subscribe(kSockDiagDoneMsgType, rxDoneHandler));
242
243 return netdutils::status::ok;
244}
245
Wayne Ma4d692332022-01-19 16:04:04 +0800246int TrafficController::addInterface(const char* name, uint32_t ifaceIndex) {
247 IfaceValue iface;
248 if (ifaceIndex == 0) {
249 ALOGE("Unknown interface %s(%d)", name, ifaceIndex);
250 return -1;
251 }
252
253 strlcpy(iface.name, name, sizeof(IfaceValue));
254 Status res = mIfaceIndexNameMap.writeValue(ifaceIndex, iface, BPF_ANY);
255 if (!isOk(res)) {
256 ALOGE("Failed to add iface %s(%d): %s", name, ifaceIndex, strerror(res.code()));
257 return -res.code();
258 }
259 return 0;
260}
261
262Status TrafficController::updateOwnerMapEntry(UidOwnerMatchType match, uid_t uid, FirewallRule rule,
263 FirewallType type) {
264 std::lock_guard guard(mMutex);
265 if ((rule == ALLOW && type == ALLOWLIST) || (rule == DENY && type == DENYLIST)) {
266 RETURN_IF_NOT_OK(addRule(uid, match));
267 } else if ((rule == ALLOW && type == DENYLIST) || (rule == DENY && type == ALLOWLIST)) {
268 RETURN_IF_NOT_OK(removeRule(uid, match));
269 } else {
270 //Cannot happen.
271 return statusFromErrno(EINVAL, "");
272 }
273 return netdutils::status::ok;
274}
275
276Status TrafficController::removeRule(uint32_t uid, UidOwnerMatchType match) {
277 auto oldMatch = mUidOwnerMap.readValue(uid);
278 if (oldMatch.ok()) {
279 UidOwnerValue newMatch = {
280 .iif = (match == IIF_MATCH) ? 0 : oldMatch.value().iif,
Motomu Utsumi42edc602022-05-12 13:57:42 +0000281 .rule = oldMatch.value().rule & ~match,
Wayne Ma4d692332022-01-19 16:04:04 +0800282 };
283 if (newMatch.rule == 0) {
284 RETURN_IF_NOT_OK(mUidOwnerMap.deleteValue(uid));
285 } else {
286 RETURN_IF_NOT_OK(mUidOwnerMap.writeValue(uid, newMatch, BPF_ANY));
287 }
288 } else {
289 return statusFromErrno(ENOENT, StringPrintf("uid: %u does not exist in map", uid));
290 }
291 return netdutils::status::ok;
292}
293
294Status TrafficController::addRule(uint32_t uid, UidOwnerMatchType match, uint32_t iif) {
Motomu Utsumib08654c2022-05-11 05:56:26 +0000295 if (match != IIF_MATCH && iif != 0) {
Wayne Ma4d692332022-01-19 16:04:04 +0800296 return statusFromErrno(EINVAL, "Non-interface match must have zero interface index");
297 }
298 auto oldMatch = mUidOwnerMap.readValue(uid);
299 if (oldMatch.ok()) {
300 UidOwnerValue newMatch = {
Motomu Utsumib08654c2022-05-11 05:56:26 +0000301 .iif = (match == IIF_MATCH) ? iif : oldMatch.value().iif,
Motomu Utsumi42edc602022-05-12 13:57:42 +0000302 .rule = oldMatch.value().rule | match,
Wayne Ma4d692332022-01-19 16:04:04 +0800303 };
304 RETURN_IF_NOT_OK(mUidOwnerMap.writeValue(uid, newMatch, BPF_ANY));
305 } else {
306 UidOwnerValue newMatch = {
307 .iif = iif,
Motomu Utsumi42edc602022-05-12 13:57:42 +0000308 .rule = match,
Wayne Ma4d692332022-01-19 16:04:04 +0800309 };
310 RETURN_IF_NOT_OK(mUidOwnerMap.writeValue(uid, newMatch, BPF_ANY));
311 }
312 return netdutils::status::ok;
313}
314
Wayne Maa9716ff2022-01-12 10:37:04 +0800315Status TrafficController::updateUidOwnerMap(const uint32_t uid,
Wayne Ma4d692332022-01-19 16:04:04 +0800316 UidOwnerMatchType matchType, IptOp op) {
317 std::lock_guard guard(mMutex);
Wayne Maa9716ff2022-01-12 10:37:04 +0800318 if (op == IptOpDelete) {
319 RETURN_IF_NOT_OK(removeRule(uid, matchType));
320 } else if (op == IptOpInsert) {
321 RETURN_IF_NOT_OK(addRule(uid, matchType));
322 } else {
323 // Cannot happen.
324 return statusFromErrno(EINVAL, StringPrintf("invalid IptOp: %d, %d", op, matchType));
Wayne Ma4d692332022-01-19 16:04:04 +0800325 }
326 return netdutils::status::ok;
327}
328
329FirewallType TrafficController::getFirewallType(ChildChain chain) {
330 switch (chain) {
331 case DOZABLE:
332 return ALLOWLIST;
333 case STANDBY:
334 return DENYLIST;
335 case POWERSAVE:
336 return ALLOWLIST;
337 case RESTRICTED:
338 return ALLOWLIST;
Robert Horvathd945bf02022-01-27 19:55:16 +0100339 case LOW_POWER_STANDBY:
340 return ALLOWLIST;
Motomu Utsumib08654c2022-05-11 05:56:26 +0000341 case LOCKDOWN:
342 return DENYLIST;
Motomu Utsumid9801492022-06-01 13:57:27 +0000343 case OEM_DENY_1:
344 return DENYLIST;
345 case OEM_DENY_2:
346 return DENYLIST;
Wayne Ma4d692332022-01-19 16:04:04 +0800347 case NONE:
348 default:
349 return DENYLIST;
350 }
351}
352
353int TrafficController::changeUidOwnerRule(ChildChain chain, uid_t uid, FirewallRule rule,
354 FirewallType type) {
355 Status res;
356 switch (chain) {
357 case DOZABLE:
358 res = updateOwnerMapEntry(DOZABLE_MATCH, uid, rule, type);
359 break;
360 case STANDBY:
361 res = updateOwnerMapEntry(STANDBY_MATCH, uid, rule, type);
362 break;
363 case POWERSAVE:
364 res = updateOwnerMapEntry(POWERSAVE_MATCH, uid, rule, type);
365 break;
366 case RESTRICTED:
367 res = updateOwnerMapEntry(RESTRICTED_MATCH, uid, rule, type);
368 break;
Robert Horvathd945bf02022-01-27 19:55:16 +0100369 case LOW_POWER_STANDBY:
370 res = updateOwnerMapEntry(LOW_POWER_STANDBY_MATCH, uid, rule, type);
371 break;
Motomu Utsumib08654c2022-05-11 05:56:26 +0000372 case LOCKDOWN:
373 res = updateOwnerMapEntry(LOCKDOWN_VPN_MATCH, uid, rule, type);
374 break;
Motomu Utsumid9801492022-06-01 13:57:27 +0000375 case OEM_DENY_1:
376 res = updateOwnerMapEntry(OEM_DENY_1_MATCH, uid, rule, type);
377 break;
378 case OEM_DENY_2:
379 res = updateOwnerMapEntry(OEM_DENY_2_MATCH, uid, rule, type);
380 break;
Wayne Ma4d692332022-01-19 16:04:04 +0800381 case NONE:
382 default:
383 ALOGW("Unknown child chain: %d", chain);
384 return -EINVAL;
385 }
386 if (!isOk(res)) {
387 ALOGE("change uid(%u) rule of %d failed: %s, rule: %d, type: %d", uid, chain,
388 res.msg().c_str(), rule, type);
389 return -res.code();
390 }
391 return 0;
392}
393
394Status TrafficController::replaceRulesInMap(const UidOwnerMatchType match,
395 const std::vector<int32_t>& uids) {
396 std::lock_guard guard(mMutex);
397 std::set<int32_t> uidSet(uids.begin(), uids.end());
398 std::vector<uint32_t> uidsToDelete;
399 auto getUidsToDelete = [&uidsToDelete, &uidSet](const uint32_t& key,
400 const BpfMap<uint32_t, UidOwnerValue>&) {
401 if (uidSet.find((int32_t) key) == uidSet.end()) {
402 uidsToDelete.push_back(key);
403 }
404 return base::Result<void>();
405 };
406 RETURN_IF_NOT_OK(mUidOwnerMap.iterate(getUidsToDelete));
407
408 for(auto uid : uidsToDelete) {
409 RETURN_IF_NOT_OK(removeRule(uid, match));
410 }
411
412 for (auto uid : uids) {
413 RETURN_IF_NOT_OK(addRule(uid, match));
414 }
415 return netdutils::status::ok;
416}
417
418Status TrafficController::addUidInterfaceRules(const int iif,
419 const std::vector<int32_t>& uidsToAdd) {
Wayne Ma4d692332022-01-19 16:04:04 +0800420 std::lock_guard guard(mMutex);
421
422 for (auto uid : uidsToAdd) {
423 netdutils::Status result = addRule(uid, IIF_MATCH, iif);
424 if (!isOk(result)) {
425 ALOGW("addRule failed(%d): uid=%d iif=%d", result.code(), uid, iif);
426 }
427 }
428 return netdutils::status::ok;
429}
430
431Status TrafficController::removeUidInterfaceRules(const std::vector<int32_t>& uidsToDelete) {
432 std::lock_guard guard(mMutex);
433
434 for (auto uid : uidsToDelete) {
435 netdutils::Status result = removeRule(uid, IIF_MATCH);
436 if (!isOk(result)) {
437 ALOGW("removeRule failed(%d): uid=%d", result.code(), uid);
438 }
439 }
440 return netdutils::status::ok;
441}
442
443int TrafficController::replaceUidOwnerMap(const std::string& name, bool isAllowlist __unused,
444 const std::vector<int32_t>& uids) {
445 // FirewallRule rule = isAllowlist ? ALLOW : DENY;
446 // FirewallType type = isAllowlist ? ALLOWLIST : DENYLIST;
447 Status res;
448 if (!name.compare(LOCAL_DOZABLE)) {
449 res = replaceRulesInMap(DOZABLE_MATCH, uids);
450 } else if (!name.compare(LOCAL_STANDBY)) {
451 res = replaceRulesInMap(STANDBY_MATCH, uids);
452 } else if (!name.compare(LOCAL_POWERSAVE)) {
453 res = replaceRulesInMap(POWERSAVE_MATCH, uids);
454 } else if (!name.compare(LOCAL_RESTRICTED)) {
455 res = replaceRulesInMap(RESTRICTED_MATCH, uids);
Robert Horvathd945bf02022-01-27 19:55:16 +0100456 } else if (!name.compare(LOCAL_LOW_POWER_STANDBY)) {
457 res = replaceRulesInMap(LOW_POWER_STANDBY_MATCH, uids);
Motomu Utsumid9801492022-06-01 13:57:27 +0000458 } else if (!name.compare(LOCAL_OEM_DENY_1)) {
459 res = replaceRulesInMap(OEM_DENY_1_MATCH, uids);
460 } else if (!name.compare(LOCAL_OEM_DENY_2)) {
461 res = replaceRulesInMap(OEM_DENY_2_MATCH, uids);
Wayne Ma4d692332022-01-19 16:04:04 +0800462 } else {
463 ALOGE("unknown chain name: %s", name.c_str());
464 return -EINVAL;
465 }
466 if (!isOk(res)) {
467 ALOGE("Failed to clean up chain: %s: %s", name.c_str(), res.msg().c_str());
468 return -res.code();
469 }
470 return 0;
471}
472
473int TrafficController::toggleUidOwnerMap(ChildChain chain, bool enable) {
474 std::lock_guard guard(mMutex);
475 uint32_t key = UID_RULES_CONFIGURATION_KEY;
Lorenzo Colitti60cbed32022-03-03 17:49:01 +0900476 auto oldConfigure = mConfigurationMap.readValue(key);
477 if (!oldConfigure.ok()) {
Wayne Ma4d692332022-01-19 16:04:04 +0800478 ALOGE("Cannot read the old configuration from map: %s",
Lorenzo Colitti60cbed32022-03-03 17:49:01 +0900479 oldConfigure.error().message().c_str());
480 return -oldConfigure.error().code();
Wayne Ma4d692332022-01-19 16:04:04 +0800481 }
482 Status res;
483 BpfConfig newConfiguration;
Lorenzo Colitti60cbed32022-03-03 17:49:01 +0900484 uint32_t match;
Wayne Ma4d692332022-01-19 16:04:04 +0800485 switch (chain) {
486 case DOZABLE:
487 match = DOZABLE_MATCH;
488 break;
489 case STANDBY:
490 match = STANDBY_MATCH;
491 break;
492 case POWERSAVE:
493 match = POWERSAVE_MATCH;
494 break;
495 case RESTRICTED:
496 match = RESTRICTED_MATCH;
497 break;
Robert Horvathd945bf02022-01-27 19:55:16 +0100498 case LOW_POWER_STANDBY:
499 match = LOW_POWER_STANDBY_MATCH;
500 break;
Motomu Utsumid9801492022-06-01 13:57:27 +0000501 case OEM_DENY_1:
502 match = OEM_DENY_1_MATCH;
503 break;
504 case OEM_DENY_2:
505 match = OEM_DENY_2_MATCH;
506 break;
Wayne Ma4d692332022-01-19 16:04:04 +0800507 default:
508 return -EINVAL;
509 }
510 newConfiguration =
Lorenzo Colitti60cbed32022-03-03 17:49:01 +0900511 enable ? (oldConfigure.value() | match) : (oldConfigure.value() & (~match));
Wayne Ma4d692332022-01-19 16:04:04 +0800512 res = mConfigurationMap.writeValue(key, newConfiguration, BPF_EXIST);
513 if (!isOk(res)) {
514 ALOGE("Failed to toggleUidOwnerMap(%d): %s", chain, res.msg().c_str());
515 }
516 return -res.code();
517}
518
519Status TrafficController::swapActiveStatsMap() {
520 std::lock_guard guard(mMutex);
521
522 uint32_t key = CURRENT_STATS_MAP_CONFIGURATION_KEY;
Lorenzo Colitti60cbed32022-03-03 17:49:01 +0900523 auto oldConfigure = mConfigurationMap.readValue(key);
524 if (!oldConfigure.ok()) {
Wayne Ma4d692332022-01-19 16:04:04 +0800525 ALOGE("Cannot read the old configuration from map: %s",
Lorenzo Colitti60cbed32022-03-03 17:49:01 +0900526 oldConfigure.error().message().c_str());
527 return Status(oldConfigure.error().code(), oldConfigure.error().message());
Wayne Ma4d692332022-01-19 16:04:04 +0800528 }
529
530 // Write to the configuration map to inform the kernel eBPF program to switch
531 // from using one map to the other. Use flag BPF_EXIST here since the map should
532 // be already populated in initMaps.
Lorenzo Colitti60cbed32022-03-03 17:49:01 +0900533 uint32_t newConfigure = (oldConfigure.value() == SELECT_MAP_A) ? SELECT_MAP_B : SELECT_MAP_A;
Wayne Ma4d692332022-01-19 16:04:04 +0800534 auto res = mConfigurationMap.writeValue(CURRENT_STATS_MAP_CONFIGURATION_KEY, newConfigure,
535 BPF_EXIST);
536 if (!res.ok()) {
537 ALOGE("Failed to toggle the stats map: %s", strerror(res.error().code()));
538 return res;
539 }
540 // After changing the config, we need to make sure all the current running
541 // eBPF programs are finished and all the CPUs are aware of this config change
542 // before we modify the old map. So we do a special hack here to wait for
543 // the kernel to do a synchronize_rcu(). Once the kernel called
544 // synchronize_rcu(), the config we just updated will be available to all cores
545 // and the next eBPF programs triggered inside the kernel will use the new
546 // map configuration. So once this function returns we can safely modify the
547 // old stats map without concerning about race between the kernel and
548 // userspace.
549 int ret = synchronizeKernelRCU();
550 if (ret) {
551 ALOGE("map swap synchronize_rcu() ended with failure: %s", strerror(-ret));
552 return statusFromErrno(-ret, "map swap synchronize_rcu() failed");
553 }
554 return netdutils::status::ok;
555}
556
557void TrafficController::setPermissionForUids(int permission, const std::vector<uid_t>& uids) {
558 std::lock_guard guard(mMutex);
559 if (permission == INetd::PERMISSION_UNINSTALLED) {
560 for (uid_t uid : uids) {
561 // Clean up all permission information for the related uid if all the
562 // packages related to it are uninstalled.
563 mPrivilegedUser.erase(uid);
564 Status ret = mUidPermissionMap.deleteValue(uid);
565 if (!isOk(ret) && ret.code() != ENOENT) {
566 ALOGE("Failed to clean up the permission for %u: %s", uid, strerror(ret.code()));
567 }
568 }
569 return;
570 }
571
572 bool privileged = (permission & INetd::PERMISSION_UPDATE_DEVICE_STATS);
573
574 for (uid_t uid : uids) {
575 if (privileged) {
576 mPrivilegedUser.insert(uid);
577 } else {
578 mPrivilegedUser.erase(uid);
579 }
580
581 // The map stores all the permissions that the UID has, except if the only permission
582 // the UID has is the INTERNET permission, then the UID should not appear in the map.
583 if (permission != INetd::PERMISSION_INTERNET) {
584 Status ret = mUidPermissionMap.writeValue(uid, permission, BPF_ANY);
585 if (!isOk(ret)) {
586 ALOGE("Failed to set permission: %s of uid(%u) to permission map: %s",
587 UidPermissionTypeToString(permission).c_str(), uid, strerror(ret.code()));
588 }
589 } else {
590 Status ret = mUidPermissionMap.deleteValue(uid);
591 if (!isOk(ret) && ret.code() != ENOENT) {
592 ALOGE("Failed to remove uid %u from permission map: %s", uid, strerror(ret.code()));
593 }
594 }
595 }
596}
597
598std::string getProgramStatus(const char *path) {
599 int ret = access(path, R_OK);
600 if (ret == 0) {
601 return StringPrintf("OK");
602 }
603 if (ret != 0 && errno == ENOENT) {
604 return StringPrintf("program is missing at: %s", path);
605 }
606 return StringPrintf("check Program %s error: %s", path, strerror(errno));
607}
608
609std::string getMapStatus(const base::unique_fd& map_fd, const char* path) {
610 if (map_fd.get() < 0) {
611 return StringPrintf("map fd lost");
612 }
613 if (access(path, F_OK) != 0) {
614 return StringPrintf("map not pinned to location: %s", path);
615 }
616 return StringPrintf("OK");
617}
618
619// NOLINTNEXTLINE(google-runtime-references): grandfathered pass by non-const reference
620void dumpBpfMap(const std::string& mapName, DumpWriter& dw, const std::string& header) {
621 dw.blankline();
622 dw.println("%s:", mapName.c_str());
623 if (!header.empty()) {
624 dw.println(header);
625 }
626}
627
Ken Chene6d511f2022-01-25 11:10:42 +0800628void TrafficController::dump(int fd, bool verbose) {
Wayne Ma4d692332022-01-19 16:04:04 +0800629 std::lock_guard guard(mMutex);
Ken Chene6d511f2022-01-25 11:10:42 +0800630 DumpWriter dw(fd);
631
Wayne Ma4d692332022-01-19 16:04:04 +0800632 ScopedIndent indentTop(dw);
633 dw.println("TrafficController");
634
635 ScopedIndent indentPreBpfModule(dw);
636
637 dw.blankline();
638 dw.println("mCookieTagMap status: %s",
639 getMapStatus(mCookieTagMap.getMap(), COOKIE_TAG_MAP_PATH).c_str());
640 dw.println("mUidCounterSetMap status: %s",
641 getMapStatus(mUidCounterSetMap.getMap(), UID_COUNTERSET_MAP_PATH).c_str());
642 dw.println("mAppUidStatsMap status: %s",
643 getMapStatus(mAppUidStatsMap.getMap(), APP_UID_STATS_MAP_PATH).c_str());
644 dw.println("mStatsMapA status: %s",
645 getMapStatus(mStatsMapA.getMap(), STATS_MAP_A_PATH).c_str());
646 dw.println("mStatsMapB status: %s",
647 getMapStatus(mStatsMapB.getMap(), STATS_MAP_B_PATH).c_str());
648 dw.println("mIfaceIndexNameMap status: %s",
649 getMapStatus(mIfaceIndexNameMap.getMap(), IFACE_INDEX_NAME_MAP_PATH).c_str());
650 dw.println("mIfaceStatsMap status: %s",
651 getMapStatus(mIfaceStatsMap.getMap(), IFACE_STATS_MAP_PATH).c_str());
652 dw.println("mConfigurationMap status: %s",
653 getMapStatus(mConfigurationMap.getMap(), CONFIGURATION_MAP_PATH).c_str());
654 dw.println("mUidOwnerMap status: %s",
655 getMapStatus(mUidOwnerMap.getMap(), UID_OWNER_MAP_PATH).c_str());
656
657 dw.blankline();
658 dw.println("Cgroup ingress program status: %s",
659 getProgramStatus(BPF_INGRESS_PROG_PATH).c_str());
660 dw.println("Cgroup egress program status: %s", getProgramStatus(BPF_EGRESS_PROG_PATH).c_str());
661 dw.println("xt_bpf ingress program status: %s",
662 getProgramStatus(XT_BPF_INGRESS_PROG_PATH).c_str());
663 dw.println("xt_bpf egress program status: %s",
664 getProgramStatus(XT_BPF_EGRESS_PROG_PATH).c_str());
665 dw.println("xt_bpf bandwidth allowlist program status: %s",
666 getProgramStatus(XT_BPF_ALLOWLIST_PROG_PATH).c_str());
667 dw.println("xt_bpf bandwidth denylist program status: %s",
668 getProgramStatus(XT_BPF_DENYLIST_PROG_PATH).c_str());
669
670 if (!verbose) {
671 return;
672 }
673
674 dw.blankline();
675 dw.println("BPF map content:");
676
677 ScopedIndent indentForMapContent(dw);
678
679 // Print CookieTagMap content.
680 dumpBpfMap("mCookieTagMap", dw, "");
681 const auto printCookieTagInfo = [&dw](const uint64_t& key, const UidTagValue& value,
682 const BpfMap<uint64_t, UidTagValue>&) {
683 dw.println("cookie=%" PRIu64 " tag=0x%x uid=%u", key, value.tag, value.uid);
684 return base::Result<void>();
685 };
686 base::Result<void> res = mCookieTagMap.iterateWithValue(printCookieTagInfo);
687 if (!res.ok()) {
688 dw.println("mCookieTagMap print end with error: %s", res.error().message().c_str());
689 }
690
Wayne Maa9716ff2022-01-12 10:37:04 +0800691 // Print UidCounterSetMap content.
Wayne Ma4d692332022-01-19 16:04:04 +0800692 dumpBpfMap("mUidCounterSetMap", dw, "");
693 const auto printUidInfo = [&dw](const uint32_t& key, const uint8_t& value,
694 const BpfMap<uint32_t, uint8_t>&) {
695 dw.println("%u %u", key, value);
696 return base::Result<void>();
697 };
698 res = mUidCounterSetMap.iterateWithValue(printUidInfo);
699 if (!res.ok()) {
700 dw.println("mUidCounterSetMap print end with error: %s", res.error().message().c_str());
701 }
702
Wayne Maa9716ff2022-01-12 10:37:04 +0800703 // Print AppUidStatsMap content.
Wayne Ma4d692332022-01-19 16:04:04 +0800704 std::string appUidStatsHeader = StringPrintf("uid rxBytes rxPackets txBytes txPackets");
705 dumpBpfMap("mAppUidStatsMap:", dw, appUidStatsHeader);
706 auto printAppUidStatsInfo = [&dw](const uint32_t& key, const StatsValue& value,
707 const BpfMap<uint32_t, StatsValue>&) {
708 dw.println("%u %" PRIu64 " %" PRIu64 " %" PRIu64 " %" PRIu64, key, value.rxBytes,
709 value.rxPackets, value.txBytes, value.txPackets);
710 return base::Result<void>();
711 };
712 res = mAppUidStatsMap.iterateWithValue(printAppUidStatsInfo);
713 if (!res.ok()) {
714 dw.println("mAppUidStatsMap print end with error: %s", res.error().message().c_str());
715 }
716
Wayne Maa9716ff2022-01-12 10:37:04 +0800717 // Print uidStatsMap content.
Wayne Ma4d692332022-01-19 16:04:04 +0800718 std::string statsHeader = StringPrintf("ifaceIndex ifaceName tag_hex uid_int cnt_set rxBytes"
719 " rxPackets txBytes txPackets");
720 dumpBpfMap("mStatsMapA", dw, statsHeader);
721 const auto printStatsInfo = [&dw, this](const StatsKey& key, const StatsValue& value,
722 const BpfMap<StatsKey, StatsValue>&) {
723 uint32_t ifIndex = key.ifaceIndex;
724 auto ifname = mIfaceIndexNameMap.readValue(ifIndex);
725 if (!ifname.ok()) {
726 ifname = IfaceValue{"unknown"};
727 }
728 dw.println("%u %s 0x%x %u %u %" PRIu64 " %" PRIu64 " %" PRIu64 " %" PRIu64, ifIndex,
729 ifname.value().name, key.tag, key.uid, key.counterSet, value.rxBytes,
730 value.rxPackets, value.txBytes, value.txPackets);
731 return base::Result<void>();
732 };
733 res = mStatsMapA.iterateWithValue(printStatsInfo);
734 if (!res.ok()) {
735 dw.println("mStatsMapA print end with error: %s", res.error().message().c_str());
736 }
737
738 // Print TagStatsMap content.
739 dumpBpfMap("mStatsMapB", dw, statsHeader);
740 res = mStatsMapB.iterateWithValue(printStatsInfo);
741 if (!res.ok()) {
742 dw.println("mStatsMapB print end with error: %s", res.error().message().c_str());
743 }
744
745 // Print ifaceIndexToNameMap content.
746 dumpBpfMap("mIfaceIndexNameMap", dw, "");
747 const auto printIfaceNameInfo = [&dw](const uint32_t& key, const IfaceValue& value,
748 const BpfMap<uint32_t, IfaceValue>&) {
749 const char* ifname = value.name;
750 dw.println("ifaceIndex=%u ifaceName=%s", key, ifname);
751 return base::Result<void>();
752 };
753 res = mIfaceIndexNameMap.iterateWithValue(printIfaceNameInfo);
754 if (!res.ok()) {
755 dw.println("mIfaceIndexNameMap print end with error: %s", res.error().message().c_str());
756 }
757
758 // Print ifaceStatsMap content
759 std::string ifaceStatsHeader = StringPrintf("ifaceIndex ifaceName rxBytes rxPackets txBytes"
760 " txPackets");
761 dumpBpfMap("mIfaceStatsMap:", dw, ifaceStatsHeader);
762 const auto printIfaceStatsInfo = [&dw, this](const uint32_t& key, const StatsValue& value,
763 const BpfMap<uint32_t, StatsValue>&) {
764 auto ifname = mIfaceIndexNameMap.readValue(key);
765 if (!ifname.ok()) {
766 ifname = IfaceValue{"unknown"};
767 }
768 dw.println("%u %s %" PRIu64 " %" PRIu64 " %" PRIu64 " %" PRIu64, key, ifname.value().name,
769 value.rxBytes, value.rxPackets, value.txBytes, value.txPackets);
770 return base::Result<void>();
771 };
772 res = mIfaceStatsMap.iterateWithValue(printIfaceStatsInfo);
773 if (!res.ok()) {
774 dw.println("mIfaceStatsMap print end with error: %s", res.error().message().c_str());
775 }
776
777 dw.blankline();
778
779 uint32_t key = UID_RULES_CONFIGURATION_KEY;
780 auto configuration = mConfigurationMap.readValue(key);
781 if (configuration.ok()) {
782 dw.println("current ownerMatch configuration: %d%s", configuration.value(),
783 uidMatchTypeToString(configuration.value()).c_str());
784 } else {
785 dw.println("mConfigurationMap read ownerMatch configure failed with error: %s",
786 configuration.error().message().c_str());
787 }
788
789 key = CURRENT_STATS_MAP_CONFIGURATION_KEY;
790 configuration = mConfigurationMap.readValue(key);
791 if (configuration.ok()) {
792 const char* statsMapDescription = "???";
793 switch (configuration.value()) {
794 case SELECT_MAP_A:
795 statsMapDescription = "SELECT_MAP_A";
796 break;
797 case SELECT_MAP_B:
798 statsMapDescription = "SELECT_MAP_B";
799 break;
800 // No default clause, so if we ever add a third map, this code will fail to build.
801 }
802 dw.println("current statsMap configuration: %d %s", configuration.value(),
803 statsMapDescription);
804 } else {
805 dw.println("mConfigurationMap read stats map configure failed with error: %s",
806 configuration.error().message().c_str());
807 }
808 dumpBpfMap("mUidOwnerMap", dw, "");
809 const auto printUidMatchInfo = [&dw, this](const uint32_t& key, const UidOwnerValue& value,
810 const BpfMap<uint32_t, UidOwnerValue>&) {
811 if (value.rule & IIF_MATCH) {
812 auto ifname = mIfaceIndexNameMap.readValue(value.iif);
813 if (ifname.ok()) {
814 dw.println("%u %s %s", key, uidMatchTypeToString(value.rule).c_str(),
815 ifname.value().name);
816 } else {
817 dw.println("%u %s %u", key, uidMatchTypeToString(value.rule).c_str(), value.iif);
818 }
819 } else {
820 dw.println("%u %s", key, uidMatchTypeToString(value.rule).c_str());
821 }
822 return base::Result<void>();
823 };
824 res = mUidOwnerMap.iterateWithValue(printUidMatchInfo);
825 if (!res.ok()) {
826 dw.println("mUidOwnerMap print end with error: %s", res.error().message().c_str());
827 }
828 dumpBpfMap("mUidPermissionMap", dw, "");
829 const auto printUidPermissionInfo = [&dw](const uint32_t& key, const int& value,
830 const BpfMap<uint32_t, uint8_t>&) {
831 dw.println("%u %s", key, UidPermissionTypeToString(value).c_str());
832 return base::Result<void>();
833 };
834 res = mUidPermissionMap.iterateWithValue(printUidPermissionInfo);
835 if (!res.ok()) {
836 dw.println("mUidPermissionMap print end with error: %s", res.error().message().c_str());
837 }
838
839 dumpBpfMap("mPrivilegedUser", dw, "");
840 for (uid_t uid : mPrivilegedUser) {
841 dw.println("%u ALLOW_UPDATE_DEVICE_STATS", (uint32_t)uid);
842 }
843}
844
845} // namespace net
846} // namespace android