blob: 548ecbeb4d72a2e67fd19e30f0dc8fb3840a81fa [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 Utsumi9cd47262022-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 Utsumi7f9c79b2022-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 Utsumi966ff7f2022-05-11 05:56:26 +0000103 FLAG_MSG_TRANS(matchType, LOCKDOWN_VPN_MATCH, match);
Motomu Utsumi9cd47262022-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));
191
192 return netdutils::status::ok;
193}
194
Wayne Ma4d692332022-01-19 16:04:04 +0800195Status TrafficController::start() {
Wayne Ma4d692332022-01-19 16:04:04 +0800196 RETURN_IF_NOT_OK(initMaps());
197
Wayne Ma4d692332022-01-19 16:04:04 +0800198 // Fetch the list of currently-existing interfaces. At this point NetlinkHandler is
199 // already running, so it will call addInterface() when any new interface appears.
Wayne Maa9716ff2022-01-12 10:37:04 +0800200 // TODO: Clean-up addInterface() after interface monitoring is in
201 // NetworkStatsService.
Wayne Ma4d692332022-01-19 16:04:04 +0800202 std::map<std::string, uint32_t> ifacePairs;
203 ASSIGN_OR_RETURN(ifacePairs, getIfaceList());
204 for (const auto& ifacePair:ifacePairs) {
205 addInterface(ifacePair.first.c_str(), ifacePair.second);
206 }
207
208 auto result = makeSkDestroyListener();
209 if (!isOk(result)) {
210 ALOGE("Unable to create SkDestroyListener: %s", toString(result).c_str());
211 } else {
212 mSkDestroyListener = std::move(result.value());
213 }
214 // Rx handler extracts nfgenmsg looks up and invokes registered dispatch function.
215 const auto rxHandler = [this](const nlmsghdr&, const Slice msg) {
216 std::lock_guard guard(mMutex);
217 inet_diag_msg diagmsg = {};
218 if (extract(msg, diagmsg) < sizeof(inet_diag_msg)) {
219 ALOGE("Unrecognized netlink message: %s", toString(msg).c_str());
220 return;
221 }
222 uint64_t sock_cookie = static_cast<uint64_t>(diagmsg.id.idiag_cookie[0]) |
223 (static_cast<uint64_t>(diagmsg.id.idiag_cookie[1]) << 32);
224
225 Status s = mCookieTagMap.deleteValue(sock_cookie);
226 if (!isOk(s) && s.code() != ENOENT) {
227 ALOGE("Failed to delete cookie %" PRIx64 ": %s", sock_cookie, toString(s).c_str());
228 return;
229 }
230 };
231 expectOk(mSkDestroyListener->subscribe(kSockDiagMsgType, rxHandler));
232
233 // In case multiple netlink message comes in as a stream, we need to handle the rxDone message
234 // properly.
235 const auto rxDoneHandler = [](const nlmsghdr&, const Slice msg) {
236 // Ignore NLMSG_DONE messages
237 inet_diag_msg diagmsg = {};
238 extract(msg, diagmsg);
239 };
240 expectOk(mSkDestroyListener->subscribe(kSockDiagDoneMsgType, rxDoneHandler));
241
242 return netdutils::status::ok;
243}
244
Wayne Ma4d692332022-01-19 16:04:04 +0800245int TrafficController::addInterface(const char* name, uint32_t ifaceIndex) {
246 IfaceValue iface;
247 if (ifaceIndex == 0) {
248 ALOGE("Unknown interface %s(%d)", name, ifaceIndex);
249 return -1;
250 }
251
252 strlcpy(iface.name, name, sizeof(IfaceValue));
253 Status res = mIfaceIndexNameMap.writeValue(ifaceIndex, iface, BPF_ANY);
254 if (!isOk(res)) {
255 ALOGE("Failed to add iface %s(%d): %s", name, ifaceIndex, strerror(res.code()));
256 return -res.code();
257 }
258 return 0;
259}
260
261Status TrafficController::updateOwnerMapEntry(UidOwnerMatchType match, uid_t uid, FirewallRule rule,
262 FirewallType type) {
263 std::lock_guard guard(mMutex);
264 if ((rule == ALLOW && type == ALLOWLIST) || (rule == DENY && type == DENYLIST)) {
265 RETURN_IF_NOT_OK(addRule(uid, match));
266 } else if ((rule == ALLOW && type == DENYLIST) || (rule == DENY && type == ALLOWLIST)) {
267 RETURN_IF_NOT_OK(removeRule(uid, match));
268 } else {
269 //Cannot happen.
270 return statusFromErrno(EINVAL, "");
271 }
272 return netdutils::status::ok;
273}
274
275Status TrafficController::removeRule(uint32_t uid, UidOwnerMatchType match) {
276 auto oldMatch = mUidOwnerMap.readValue(uid);
277 if (oldMatch.ok()) {
278 UidOwnerValue newMatch = {
279 .iif = (match == IIF_MATCH) ? 0 : oldMatch.value().iif,
Motomu Utsumi7f9c79b2022-05-12 13:57:42 +0000280 .rule = oldMatch.value().rule & ~match,
Wayne Ma4d692332022-01-19 16:04:04 +0800281 };
282 if (newMatch.rule == 0) {
283 RETURN_IF_NOT_OK(mUidOwnerMap.deleteValue(uid));
284 } else {
285 RETURN_IF_NOT_OK(mUidOwnerMap.writeValue(uid, newMatch, BPF_ANY));
286 }
287 } else {
288 return statusFromErrno(ENOENT, StringPrintf("uid: %u does not exist in map", uid));
289 }
290 return netdutils::status::ok;
291}
292
293Status TrafficController::addRule(uint32_t uid, UidOwnerMatchType match, uint32_t iif) {
Motomu Utsumi966ff7f2022-05-11 05:56:26 +0000294 if (match != IIF_MATCH && iif != 0) {
Wayne Ma4d692332022-01-19 16:04:04 +0800295 return statusFromErrno(EINVAL, "Non-interface match must have zero interface index");
296 }
297 auto oldMatch = mUidOwnerMap.readValue(uid);
298 if (oldMatch.ok()) {
299 UidOwnerValue newMatch = {
Motomu Utsumi966ff7f2022-05-11 05:56:26 +0000300 .iif = (match == IIF_MATCH) ? iif : oldMatch.value().iif,
Motomu Utsumi7f9c79b2022-05-12 13:57:42 +0000301 .rule = oldMatch.value().rule | match,
Wayne Ma4d692332022-01-19 16:04:04 +0800302 };
303 RETURN_IF_NOT_OK(mUidOwnerMap.writeValue(uid, newMatch, BPF_ANY));
304 } else {
305 UidOwnerValue newMatch = {
306 .iif = iif,
Motomu Utsumi7f9c79b2022-05-12 13:57:42 +0000307 .rule = match,
Wayne Ma4d692332022-01-19 16:04:04 +0800308 };
309 RETURN_IF_NOT_OK(mUidOwnerMap.writeValue(uid, newMatch, BPF_ANY));
310 }
311 return netdutils::status::ok;
312}
313
Wayne Maa9716ff2022-01-12 10:37:04 +0800314Status TrafficController::updateUidOwnerMap(const uint32_t uid,
Wayne Ma4d692332022-01-19 16:04:04 +0800315 UidOwnerMatchType matchType, IptOp op) {
316 std::lock_guard guard(mMutex);
Wayne Maa9716ff2022-01-12 10:37:04 +0800317 if (op == IptOpDelete) {
318 RETURN_IF_NOT_OK(removeRule(uid, matchType));
319 } else if (op == IptOpInsert) {
320 RETURN_IF_NOT_OK(addRule(uid, matchType));
321 } else {
322 // Cannot happen.
323 return statusFromErrno(EINVAL, StringPrintf("invalid IptOp: %d, %d", op, matchType));
Wayne Ma4d692332022-01-19 16:04:04 +0800324 }
325 return netdutils::status::ok;
326}
327
328FirewallType TrafficController::getFirewallType(ChildChain chain) {
329 switch (chain) {
330 case DOZABLE:
331 return ALLOWLIST;
332 case STANDBY:
333 return DENYLIST;
334 case POWERSAVE:
335 return ALLOWLIST;
336 case RESTRICTED:
337 return ALLOWLIST;
Robert Horvathd945bf02022-01-27 19:55:16 +0100338 case LOW_POWER_STANDBY:
339 return ALLOWLIST;
Motomu Utsumi966ff7f2022-05-11 05:56:26 +0000340 case LOCKDOWN:
341 return DENYLIST;
Motomu Utsumi9cd47262022-06-01 13:57:27 +0000342 case OEM_DENY_1:
343 return DENYLIST;
344 case OEM_DENY_2:
345 return DENYLIST;
Wayne Ma4d692332022-01-19 16:04:04 +0800346 case NONE:
347 default:
348 return DENYLIST;
349 }
350}
351
352int TrafficController::changeUidOwnerRule(ChildChain chain, uid_t uid, FirewallRule rule,
353 FirewallType type) {
354 Status res;
355 switch (chain) {
356 case DOZABLE:
357 res = updateOwnerMapEntry(DOZABLE_MATCH, uid, rule, type);
358 break;
359 case STANDBY:
360 res = updateOwnerMapEntry(STANDBY_MATCH, uid, rule, type);
361 break;
362 case POWERSAVE:
363 res = updateOwnerMapEntry(POWERSAVE_MATCH, uid, rule, type);
364 break;
365 case RESTRICTED:
366 res = updateOwnerMapEntry(RESTRICTED_MATCH, uid, rule, type);
367 break;
Robert Horvathd945bf02022-01-27 19:55:16 +0100368 case LOW_POWER_STANDBY:
369 res = updateOwnerMapEntry(LOW_POWER_STANDBY_MATCH, uid, rule, type);
370 break;
Motomu Utsumi966ff7f2022-05-11 05:56:26 +0000371 case LOCKDOWN:
372 res = updateOwnerMapEntry(LOCKDOWN_VPN_MATCH, uid, rule, type);
373 break;
Motomu Utsumi9cd47262022-06-01 13:57:27 +0000374 case OEM_DENY_1:
375 res = updateOwnerMapEntry(OEM_DENY_1_MATCH, uid, rule, type);
376 break;
377 case OEM_DENY_2:
378 res = updateOwnerMapEntry(OEM_DENY_2_MATCH, uid, rule, type);
379 break;
Wayne Ma4d692332022-01-19 16:04:04 +0800380 case NONE:
381 default:
382 ALOGW("Unknown child chain: %d", chain);
383 return -EINVAL;
384 }
385 if (!isOk(res)) {
386 ALOGE("change uid(%u) rule of %d failed: %s, rule: %d, type: %d", uid, chain,
387 res.msg().c_str(), rule, type);
388 return -res.code();
389 }
390 return 0;
391}
392
393Status TrafficController::replaceRulesInMap(const UidOwnerMatchType match,
394 const std::vector<int32_t>& uids) {
395 std::lock_guard guard(mMutex);
396 std::set<int32_t> uidSet(uids.begin(), uids.end());
397 std::vector<uint32_t> uidsToDelete;
398 auto getUidsToDelete = [&uidsToDelete, &uidSet](const uint32_t& key,
399 const BpfMap<uint32_t, UidOwnerValue>&) {
400 if (uidSet.find((int32_t) key) == uidSet.end()) {
401 uidsToDelete.push_back(key);
402 }
403 return base::Result<void>();
404 };
405 RETURN_IF_NOT_OK(mUidOwnerMap.iterate(getUidsToDelete));
406
407 for(auto uid : uidsToDelete) {
408 RETURN_IF_NOT_OK(removeRule(uid, match));
409 }
410
411 for (auto uid : uids) {
412 RETURN_IF_NOT_OK(addRule(uid, match));
413 }
414 return netdutils::status::ok;
415}
416
417Status TrafficController::addUidInterfaceRules(const int iif,
418 const std::vector<int32_t>& uidsToAdd) {
Wayne Ma4d692332022-01-19 16:04:04 +0800419 std::lock_guard guard(mMutex);
420
421 for (auto uid : uidsToAdd) {
422 netdutils::Status result = addRule(uid, IIF_MATCH, iif);
423 if (!isOk(result)) {
424 ALOGW("addRule failed(%d): uid=%d iif=%d", result.code(), uid, iif);
425 }
426 }
427 return netdutils::status::ok;
428}
429
430Status TrafficController::removeUidInterfaceRules(const std::vector<int32_t>& uidsToDelete) {
431 std::lock_guard guard(mMutex);
432
433 for (auto uid : uidsToDelete) {
434 netdutils::Status result = removeRule(uid, IIF_MATCH);
435 if (!isOk(result)) {
436 ALOGW("removeRule failed(%d): uid=%d", result.code(), uid);
437 }
438 }
439 return netdutils::status::ok;
440}
441
442int TrafficController::replaceUidOwnerMap(const std::string& name, bool isAllowlist __unused,
443 const std::vector<int32_t>& uids) {
444 // FirewallRule rule = isAllowlist ? ALLOW : DENY;
445 // FirewallType type = isAllowlist ? ALLOWLIST : DENYLIST;
446 Status res;
447 if (!name.compare(LOCAL_DOZABLE)) {
448 res = replaceRulesInMap(DOZABLE_MATCH, uids);
449 } else if (!name.compare(LOCAL_STANDBY)) {
450 res = replaceRulesInMap(STANDBY_MATCH, uids);
451 } else if (!name.compare(LOCAL_POWERSAVE)) {
452 res = replaceRulesInMap(POWERSAVE_MATCH, uids);
453 } else if (!name.compare(LOCAL_RESTRICTED)) {
454 res = replaceRulesInMap(RESTRICTED_MATCH, uids);
Robert Horvathd945bf02022-01-27 19:55:16 +0100455 } else if (!name.compare(LOCAL_LOW_POWER_STANDBY)) {
456 res = replaceRulesInMap(LOW_POWER_STANDBY_MATCH, uids);
Motomu Utsumi9cd47262022-06-01 13:57:27 +0000457 } else if (!name.compare(LOCAL_OEM_DENY_1)) {
458 res = replaceRulesInMap(OEM_DENY_1_MATCH, uids);
459 } else if (!name.compare(LOCAL_OEM_DENY_2)) {
460 res = replaceRulesInMap(OEM_DENY_2_MATCH, uids);
Wayne Ma4d692332022-01-19 16:04:04 +0800461 } else {
462 ALOGE("unknown chain name: %s", name.c_str());
463 return -EINVAL;
464 }
465 if (!isOk(res)) {
466 ALOGE("Failed to clean up chain: %s: %s", name.c_str(), res.msg().c_str());
467 return -res.code();
468 }
469 return 0;
470}
471
472int TrafficController::toggleUidOwnerMap(ChildChain chain, bool enable) {
473 std::lock_guard guard(mMutex);
474 uint32_t key = UID_RULES_CONFIGURATION_KEY;
Lorenzo Colitti90c0c3f2022-03-03 17:49:01 +0900475 auto oldConfigure = mConfigurationMap.readValue(key);
476 if (!oldConfigure.ok()) {
Wayne Ma4d692332022-01-19 16:04:04 +0800477 ALOGE("Cannot read the old configuration from map: %s",
Lorenzo Colitti90c0c3f2022-03-03 17:49:01 +0900478 oldConfigure.error().message().c_str());
479 return -oldConfigure.error().code();
Wayne Ma4d692332022-01-19 16:04:04 +0800480 }
481 Status res;
482 BpfConfig newConfiguration;
Lorenzo Colitti90c0c3f2022-03-03 17:49:01 +0900483 uint32_t match;
Wayne Ma4d692332022-01-19 16:04:04 +0800484 switch (chain) {
485 case DOZABLE:
486 match = DOZABLE_MATCH;
487 break;
488 case STANDBY:
489 match = STANDBY_MATCH;
490 break;
491 case POWERSAVE:
492 match = POWERSAVE_MATCH;
493 break;
494 case RESTRICTED:
495 match = RESTRICTED_MATCH;
496 break;
Robert Horvathd945bf02022-01-27 19:55:16 +0100497 case LOW_POWER_STANDBY:
498 match = LOW_POWER_STANDBY_MATCH;
499 break;
Motomu Utsumi9cd47262022-06-01 13:57:27 +0000500 case OEM_DENY_1:
501 match = OEM_DENY_1_MATCH;
502 break;
503 case OEM_DENY_2:
504 match = OEM_DENY_2_MATCH;
505 break;
Wayne Ma4d692332022-01-19 16:04:04 +0800506 default:
507 return -EINVAL;
508 }
509 newConfiguration =
Lorenzo Colitti90c0c3f2022-03-03 17:49:01 +0900510 enable ? (oldConfigure.value() | match) : (oldConfigure.value() & (~match));
Wayne Ma4d692332022-01-19 16:04:04 +0800511 res = mConfigurationMap.writeValue(key, newConfiguration, BPF_EXIST);
512 if (!isOk(res)) {
513 ALOGE("Failed to toggleUidOwnerMap(%d): %s", chain, res.msg().c_str());
514 }
515 return -res.code();
516}
517
518Status TrafficController::swapActiveStatsMap() {
519 std::lock_guard guard(mMutex);
520
521 uint32_t key = CURRENT_STATS_MAP_CONFIGURATION_KEY;
Lorenzo Colitti90c0c3f2022-03-03 17:49:01 +0900522 auto oldConfigure = mConfigurationMap.readValue(key);
523 if (!oldConfigure.ok()) {
Wayne Ma4d692332022-01-19 16:04:04 +0800524 ALOGE("Cannot read the old configuration from map: %s",
Lorenzo Colitti90c0c3f2022-03-03 17:49:01 +0900525 oldConfigure.error().message().c_str());
526 return Status(oldConfigure.error().code(), oldConfigure.error().message());
Wayne Ma4d692332022-01-19 16:04:04 +0800527 }
528
529 // Write to the configuration map to inform the kernel eBPF program to switch
530 // from using one map to the other. Use flag BPF_EXIST here since the map should
531 // be already populated in initMaps.
Lorenzo Colitti90c0c3f2022-03-03 17:49:01 +0900532 uint32_t newConfigure = (oldConfigure.value() == SELECT_MAP_A) ? SELECT_MAP_B : SELECT_MAP_A;
Wayne Ma4d692332022-01-19 16:04:04 +0800533 auto res = mConfigurationMap.writeValue(CURRENT_STATS_MAP_CONFIGURATION_KEY, newConfigure,
534 BPF_EXIST);
535 if (!res.ok()) {
536 ALOGE("Failed to toggle the stats map: %s", strerror(res.error().code()));
537 return res;
538 }
539 // After changing the config, we need to make sure all the current running
540 // eBPF programs are finished and all the CPUs are aware of this config change
541 // before we modify the old map. So we do a special hack here to wait for
542 // the kernel to do a synchronize_rcu(). Once the kernel called
543 // synchronize_rcu(), the config we just updated will be available to all cores
544 // and the next eBPF programs triggered inside the kernel will use the new
545 // map configuration. So once this function returns we can safely modify the
546 // old stats map without concerning about race between the kernel and
547 // userspace.
548 int ret = synchronizeKernelRCU();
549 if (ret) {
550 ALOGE("map swap synchronize_rcu() ended with failure: %s", strerror(-ret));
551 return statusFromErrno(-ret, "map swap synchronize_rcu() failed");
552 }
553 return netdutils::status::ok;
554}
555
556void TrafficController::setPermissionForUids(int permission, const std::vector<uid_t>& uids) {
557 std::lock_guard guard(mMutex);
558 if (permission == INetd::PERMISSION_UNINSTALLED) {
559 for (uid_t uid : uids) {
560 // Clean up all permission information for the related uid if all the
561 // packages related to it are uninstalled.
562 mPrivilegedUser.erase(uid);
563 Status ret = mUidPermissionMap.deleteValue(uid);
564 if (!isOk(ret) && ret.code() != ENOENT) {
565 ALOGE("Failed to clean up the permission for %u: %s", uid, strerror(ret.code()));
566 }
567 }
568 return;
569 }
570
571 bool privileged = (permission & INetd::PERMISSION_UPDATE_DEVICE_STATS);
572
573 for (uid_t uid : uids) {
574 if (privileged) {
575 mPrivilegedUser.insert(uid);
576 } else {
577 mPrivilegedUser.erase(uid);
578 }
579
580 // The map stores all the permissions that the UID has, except if the only permission
581 // the UID has is the INTERNET permission, then the UID should not appear in the map.
582 if (permission != INetd::PERMISSION_INTERNET) {
583 Status ret = mUidPermissionMap.writeValue(uid, permission, BPF_ANY);
584 if (!isOk(ret)) {
585 ALOGE("Failed to set permission: %s of uid(%u) to permission map: %s",
586 UidPermissionTypeToString(permission).c_str(), uid, strerror(ret.code()));
587 }
588 } else {
589 Status ret = mUidPermissionMap.deleteValue(uid);
590 if (!isOk(ret) && ret.code() != ENOENT) {
591 ALOGE("Failed to remove uid %u from permission map: %s", uid, strerror(ret.code()));
592 }
593 }
594 }
595}
596
597std::string getProgramStatus(const char *path) {
598 int ret = access(path, R_OK);
599 if (ret == 0) {
600 return StringPrintf("OK");
601 }
602 if (ret != 0 && errno == ENOENT) {
603 return StringPrintf("program is missing at: %s", path);
604 }
605 return StringPrintf("check Program %s error: %s", path, strerror(errno));
606}
607
608std::string getMapStatus(const base::unique_fd& map_fd, const char* path) {
609 if (map_fd.get() < 0) {
610 return StringPrintf("map fd lost");
611 }
612 if (access(path, F_OK) != 0) {
613 return StringPrintf("map not pinned to location: %s", path);
614 }
615 return StringPrintf("OK");
616}
617
618// NOLINTNEXTLINE(google-runtime-references): grandfathered pass by non-const reference
619void dumpBpfMap(const std::string& mapName, DumpWriter& dw, const std::string& header) {
620 dw.blankline();
621 dw.println("%s:", mapName.c_str());
622 if (!header.empty()) {
623 dw.println(header);
624 }
625}
626
Ken Chene6d511f2022-01-25 11:10:42 +0800627void TrafficController::dump(int fd, bool verbose) {
Wayne Ma4d692332022-01-19 16:04:04 +0800628 std::lock_guard guard(mMutex);
Ken Chene6d511f2022-01-25 11:10:42 +0800629 DumpWriter dw(fd);
630
Wayne Ma4d692332022-01-19 16:04:04 +0800631 ScopedIndent indentTop(dw);
632 dw.println("TrafficController");
633
634 ScopedIndent indentPreBpfModule(dw);
635
636 dw.blankline();
637 dw.println("mCookieTagMap status: %s",
638 getMapStatus(mCookieTagMap.getMap(), COOKIE_TAG_MAP_PATH).c_str());
639 dw.println("mUidCounterSetMap status: %s",
640 getMapStatus(mUidCounterSetMap.getMap(), UID_COUNTERSET_MAP_PATH).c_str());
641 dw.println("mAppUidStatsMap status: %s",
642 getMapStatus(mAppUidStatsMap.getMap(), APP_UID_STATS_MAP_PATH).c_str());
643 dw.println("mStatsMapA status: %s",
644 getMapStatus(mStatsMapA.getMap(), STATS_MAP_A_PATH).c_str());
645 dw.println("mStatsMapB status: %s",
646 getMapStatus(mStatsMapB.getMap(), STATS_MAP_B_PATH).c_str());
647 dw.println("mIfaceIndexNameMap status: %s",
648 getMapStatus(mIfaceIndexNameMap.getMap(), IFACE_INDEX_NAME_MAP_PATH).c_str());
649 dw.println("mIfaceStatsMap status: %s",
650 getMapStatus(mIfaceStatsMap.getMap(), IFACE_STATS_MAP_PATH).c_str());
651 dw.println("mConfigurationMap status: %s",
652 getMapStatus(mConfigurationMap.getMap(), CONFIGURATION_MAP_PATH).c_str());
653 dw.println("mUidOwnerMap status: %s",
654 getMapStatus(mUidOwnerMap.getMap(), UID_OWNER_MAP_PATH).c_str());
655
656 dw.blankline();
657 dw.println("Cgroup ingress program status: %s",
658 getProgramStatus(BPF_INGRESS_PROG_PATH).c_str());
659 dw.println("Cgroup egress program status: %s", getProgramStatus(BPF_EGRESS_PROG_PATH).c_str());
660 dw.println("xt_bpf ingress program status: %s",
661 getProgramStatus(XT_BPF_INGRESS_PROG_PATH).c_str());
662 dw.println("xt_bpf egress program status: %s",
663 getProgramStatus(XT_BPF_EGRESS_PROG_PATH).c_str());
664 dw.println("xt_bpf bandwidth allowlist program status: %s",
665 getProgramStatus(XT_BPF_ALLOWLIST_PROG_PATH).c_str());
666 dw.println("xt_bpf bandwidth denylist program status: %s",
667 getProgramStatus(XT_BPF_DENYLIST_PROG_PATH).c_str());
668
669 if (!verbose) {
670 return;
671 }
672
673 dw.blankline();
674 dw.println("BPF map content:");
675
676 ScopedIndent indentForMapContent(dw);
677
678 // Print CookieTagMap content.
679 dumpBpfMap("mCookieTagMap", dw, "");
680 const auto printCookieTagInfo = [&dw](const uint64_t& key, const UidTagValue& value,
681 const BpfMap<uint64_t, UidTagValue>&) {
682 dw.println("cookie=%" PRIu64 " tag=0x%x uid=%u", key, value.tag, value.uid);
683 return base::Result<void>();
684 };
685 base::Result<void> res = mCookieTagMap.iterateWithValue(printCookieTagInfo);
686 if (!res.ok()) {
687 dw.println("mCookieTagMap print end with error: %s", res.error().message().c_str());
688 }
689
Wayne Maa9716ff2022-01-12 10:37:04 +0800690 // Print UidCounterSetMap content.
Wayne Ma4d692332022-01-19 16:04:04 +0800691 dumpBpfMap("mUidCounterSetMap", dw, "");
692 const auto printUidInfo = [&dw](const uint32_t& key, const uint8_t& value,
693 const BpfMap<uint32_t, uint8_t>&) {
694 dw.println("%u %u", key, value);
695 return base::Result<void>();
696 };
697 res = mUidCounterSetMap.iterateWithValue(printUidInfo);
698 if (!res.ok()) {
699 dw.println("mUidCounterSetMap print end with error: %s", res.error().message().c_str());
700 }
701
Wayne Maa9716ff2022-01-12 10:37:04 +0800702 // Print AppUidStatsMap content.
Wayne Ma4d692332022-01-19 16:04:04 +0800703 std::string appUidStatsHeader = StringPrintf("uid rxBytes rxPackets txBytes txPackets");
704 dumpBpfMap("mAppUidStatsMap:", dw, appUidStatsHeader);
705 auto printAppUidStatsInfo = [&dw](const uint32_t& key, const StatsValue& value,
706 const BpfMap<uint32_t, StatsValue>&) {
707 dw.println("%u %" PRIu64 " %" PRIu64 " %" PRIu64 " %" PRIu64, key, value.rxBytes,
708 value.rxPackets, value.txBytes, value.txPackets);
709 return base::Result<void>();
710 };
711 res = mAppUidStatsMap.iterateWithValue(printAppUidStatsInfo);
712 if (!res.ok()) {
713 dw.println("mAppUidStatsMap print end with error: %s", res.error().message().c_str());
714 }
715
Wayne Maa9716ff2022-01-12 10:37:04 +0800716 // Print uidStatsMap content.
Wayne Ma4d692332022-01-19 16:04:04 +0800717 std::string statsHeader = StringPrintf("ifaceIndex ifaceName tag_hex uid_int cnt_set rxBytes"
718 " rxPackets txBytes txPackets");
719 dumpBpfMap("mStatsMapA", dw, statsHeader);
720 const auto printStatsInfo = [&dw, this](const StatsKey& key, const StatsValue& value,
721 const BpfMap<StatsKey, StatsValue>&) {
722 uint32_t ifIndex = key.ifaceIndex;
723 auto ifname = mIfaceIndexNameMap.readValue(ifIndex);
724 if (!ifname.ok()) {
725 ifname = IfaceValue{"unknown"};
726 }
727 dw.println("%u %s 0x%x %u %u %" PRIu64 " %" PRIu64 " %" PRIu64 " %" PRIu64, ifIndex,
728 ifname.value().name, key.tag, key.uid, key.counterSet, value.rxBytes,
729 value.rxPackets, value.txBytes, value.txPackets);
730 return base::Result<void>();
731 };
732 res = mStatsMapA.iterateWithValue(printStatsInfo);
733 if (!res.ok()) {
734 dw.println("mStatsMapA print end with error: %s", res.error().message().c_str());
735 }
736
737 // Print TagStatsMap content.
738 dumpBpfMap("mStatsMapB", dw, statsHeader);
739 res = mStatsMapB.iterateWithValue(printStatsInfo);
740 if (!res.ok()) {
741 dw.println("mStatsMapB print end with error: %s", res.error().message().c_str());
742 }
743
744 // Print ifaceIndexToNameMap content.
745 dumpBpfMap("mIfaceIndexNameMap", dw, "");
746 const auto printIfaceNameInfo = [&dw](const uint32_t& key, const IfaceValue& value,
747 const BpfMap<uint32_t, IfaceValue>&) {
748 const char* ifname = value.name;
749 dw.println("ifaceIndex=%u ifaceName=%s", key, ifname);
750 return base::Result<void>();
751 };
752 res = mIfaceIndexNameMap.iterateWithValue(printIfaceNameInfo);
753 if (!res.ok()) {
754 dw.println("mIfaceIndexNameMap print end with error: %s", res.error().message().c_str());
755 }
756
757 // Print ifaceStatsMap content
758 std::string ifaceStatsHeader = StringPrintf("ifaceIndex ifaceName rxBytes rxPackets txBytes"
759 " txPackets");
760 dumpBpfMap("mIfaceStatsMap:", dw, ifaceStatsHeader);
761 const auto printIfaceStatsInfo = [&dw, this](const uint32_t& key, const StatsValue& value,
762 const BpfMap<uint32_t, StatsValue>&) {
763 auto ifname = mIfaceIndexNameMap.readValue(key);
764 if (!ifname.ok()) {
765 ifname = IfaceValue{"unknown"};
766 }
767 dw.println("%u %s %" PRIu64 " %" PRIu64 " %" PRIu64 " %" PRIu64, key, ifname.value().name,
768 value.rxBytes, value.rxPackets, value.txBytes, value.txPackets);
769 return base::Result<void>();
770 };
771 res = mIfaceStatsMap.iterateWithValue(printIfaceStatsInfo);
772 if (!res.ok()) {
773 dw.println("mIfaceStatsMap print end with error: %s", res.error().message().c_str());
774 }
775
776 dw.blankline();
777
778 uint32_t key = UID_RULES_CONFIGURATION_KEY;
779 auto configuration = mConfigurationMap.readValue(key);
780 if (configuration.ok()) {
781 dw.println("current ownerMatch configuration: %d%s", configuration.value(),
782 uidMatchTypeToString(configuration.value()).c_str());
783 } else {
784 dw.println("mConfigurationMap read ownerMatch configure failed with error: %s",
785 configuration.error().message().c_str());
786 }
787
788 key = CURRENT_STATS_MAP_CONFIGURATION_KEY;
789 configuration = mConfigurationMap.readValue(key);
790 if (configuration.ok()) {
791 const char* statsMapDescription = "???";
792 switch (configuration.value()) {
793 case SELECT_MAP_A:
794 statsMapDescription = "SELECT_MAP_A";
795 break;
796 case SELECT_MAP_B:
797 statsMapDescription = "SELECT_MAP_B";
798 break;
799 // No default clause, so if we ever add a third map, this code will fail to build.
800 }
801 dw.println("current statsMap configuration: %d %s", configuration.value(),
802 statsMapDescription);
803 } else {
804 dw.println("mConfigurationMap read stats map configure failed with error: %s",
805 configuration.error().message().c_str());
806 }
807 dumpBpfMap("mUidOwnerMap", dw, "");
808 const auto printUidMatchInfo = [&dw, this](const uint32_t& key, const UidOwnerValue& value,
809 const BpfMap<uint32_t, UidOwnerValue>&) {
810 if (value.rule & IIF_MATCH) {
811 auto ifname = mIfaceIndexNameMap.readValue(value.iif);
812 if (ifname.ok()) {
813 dw.println("%u %s %s", key, uidMatchTypeToString(value.rule).c_str(),
814 ifname.value().name);
815 } else {
816 dw.println("%u %s %u", key, uidMatchTypeToString(value.rule).c_str(), value.iif);
817 }
818 } else {
819 dw.println("%u %s", key, uidMatchTypeToString(value.rule).c_str());
820 }
821 return base::Result<void>();
822 };
823 res = mUidOwnerMap.iterateWithValue(printUidMatchInfo);
824 if (!res.ok()) {
825 dw.println("mUidOwnerMap print end with error: %s", res.error().message().c_str());
826 }
827 dumpBpfMap("mUidPermissionMap", dw, "");
828 const auto printUidPermissionInfo = [&dw](const uint32_t& key, const int& value,
829 const BpfMap<uint32_t, uint8_t>&) {
830 dw.println("%u %s", key, UidPermissionTypeToString(value).c_str());
831 return base::Result<void>();
832 };
833 res = mUidPermissionMap.iterateWithValue(printUidPermissionInfo);
834 if (!res.ok()) {
835 dw.println("mUidPermissionMap print end with error: %s", res.error().message().c_str());
836 }
837
838 dumpBpfMap("mPrivilegedUser", dw, "");
839 for (uid_t uid : mPrivilegedUser) {
840 dw.println("%u ALLOW_UPDATE_DEVICE_STATS", (uint32_t)uid);
841 }
842}
843
844} // namespace net
845} // namespace android