blob: d05e6fa21b2f3d529c62ce76bd5e849305714a58 [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";
Motomu Utsumi1d9054b2022-06-06 07:44:05 +000079const char* TrafficController::LOCAL_OEM_DENY_3 = "fw_oem_deny_3";
Wayne Ma4d692332022-01-19 16:04:04 +080080
81static_assert(BPF_PERMISSION_INTERNET == INetd::PERMISSION_INTERNET,
82 "Mismatch between BPF and AIDL permissions: PERMISSION_INTERNET");
83static_assert(BPF_PERMISSION_UPDATE_DEVICE_STATS == INetd::PERMISSION_UPDATE_DEVICE_STATS,
84 "Mismatch between BPF and AIDL permissions: PERMISSION_UPDATE_DEVICE_STATS");
Wayne Ma4d692332022-01-19 16:04:04 +080085
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
Motomu Utsumi42edc602022-05-12 13:57:42 +000094const std::string uidMatchTypeToString(uint32_t match) {
Wayne Ma4d692332022-01-19 16:04:04 +080095 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);
Robert Horvathd945bf02022-01-27 19:55:16 +0100102 FLAG_MSG_TRANS(matchType, LOW_POWER_STANDBY_MATCH, match);
Wayne Ma4d692332022-01-19 16:04:04 +0800103 FLAG_MSG_TRANS(matchType, IIF_MATCH, match);
Motomu Utsumib08654c2022-05-11 05:56:26 +0000104 FLAG_MSG_TRANS(matchType, LOCKDOWN_VPN_MATCH, match);
Motomu Utsumid9801492022-06-01 13:57:27 +0000105 FLAG_MSG_TRANS(matchType, OEM_DENY_1_MATCH, match);
106 FLAG_MSG_TRANS(matchType, OEM_DENY_2_MATCH, match);
Motomu Utsumi1d9054b2022-06-06 07:44:05 +0000107 FLAG_MSG_TRANS(matchType, OEM_DENY_3_MATCH, match);
Wayne Ma4d692332022-01-19 16:04:04 +0800108 if (match) {
109 return StringPrintf("Unknown match: %u", match);
110 }
111 return matchType;
112}
113
114bool 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
122const 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
139StatusOr<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
Wayne Ma4d692332022-01-19 16:04:04 +0800173Status 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));
Ken Chen322ffcb2022-05-23 22:27:40 +0800193 ALOGI("%s successfully", __func__);
Wayne Ma4d692332022-01-19 16:04:04 +0800194
195 return netdutils::status::ok;
196}
197
Wayne Ma4d692332022-01-19 16:04:04 +0800198Status TrafficController::start() {
Wayne Ma4d692332022-01-19 16:04:04 +0800199 RETURN_IF_NOT_OK(initMaps());
200
Wayne Ma4d692332022-01-19 16:04:04 +0800201 // Fetch the list of currently-existing interfaces. At this point NetlinkHandler is
202 // already running, so it will call addInterface() when any new interface appears.
Wayne Maa9716ff2022-01-12 10:37:04 +0800203 // TODO: Clean-up addInterface() after interface monitoring is in
204 // NetworkStatsService.
Wayne Ma4d692332022-01-19 16:04:04 +0800205 std::map<std::string, uint32_t> ifacePairs;
206 ASSIGN_OR_RETURN(ifacePairs, getIfaceList());
207 for (const auto& ifacePair:ifacePairs) {
208 addInterface(ifacePair.first.c_str(), ifacePair.second);
209 }
210
211 auto result = makeSkDestroyListener();
212 if (!isOk(result)) {
213 ALOGE("Unable to create SkDestroyListener: %s", toString(result).c_str());
214 } else {
215 mSkDestroyListener = std::move(result.value());
216 }
217 // Rx handler extracts nfgenmsg looks up and invokes registered dispatch function.
218 const auto rxHandler = [this](const nlmsghdr&, const Slice msg) {
219 std::lock_guard guard(mMutex);
220 inet_diag_msg diagmsg = {};
221 if (extract(msg, diagmsg) < sizeof(inet_diag_msg)) {
222 ALOGE("Unrecognized netlink message: %s", toString(msg).c_str());
223 return;
224 }
225 uint64_t sock_cookie = static_cast<uint64_t>(diagmsg.id.idiag_cookie[0]) |
226 (static_cast<uint64_t>(diagmsg.id.idiag_cookie[1]) << 32);
227
228 Status s = mCookieTagMap.deleteValue(sock_cookie);
229 if (!isOk(s) && s.code() != ENOENT) {
230 ALOGE("Failed to delete cookie %" PRIx64 ": %s", sock_cookie, toString(s).c_str());
231 return;
232 }
233 };
234 expectOk(mSkDestroyListener->subscribe(kSockDiagMsgType, rxHandler));
235
236 // In case multiple netlink message comes in as a stream, we need to handle the rxDone message
237 // properly.
238 const auto rxDoneHandler = [](const nlmsghdr&, const Slice msg) {
239 // Ignore NLMSG_DONE messages
240 inet_diag_msg diagmsg = {};
241 extract(msg, diagmsg);
242 };
243 expectOk(mSkDestroyListener->subscribe(kSockDiagDoneMsgType, rxDoneHandler));
244
245 return netdutils::status::ok;
246}
247
Wayne Ma4d692332022-01-19 16:04:04 +0800248int TrafficController::addInterface(const char* name, uint32_t ifaceIndex) {
249 IfaceValue iface;
250 if (ifaceIndex == 0) {
251 ALOGE("Unknown interface %s(%d)", name, ifaceIndex);
252 return -1;
253 }
254
255 strlcpy(iface.name, name, sizeof(IfaceValue));
256 Status res = mIfaceIndexNameMap.writeValue(ifaceIndex, iface, BPF_ANY);
257 if (!isOk(res)) {
258 ALOGE("Failed to add iface %s(%d): %s", name, ifaceIndex, strerror(res.code()));
259 return -res.code();
260 }
261 return 0;
262}
263
264Status TrafficController::updateOwnerMapEntry(UidOwnerMatchType match, uid_t uid, FirewallRule rule,
265 FirewallType type) {
266 std::lock_guard guard(mMutex);
267 if ((rule == ALLOW && type == ALLOWLIST) || (rule == DENY && type == DENYLIST)) {
268 RETURN_IF_NOT_OK(addRule(uid, match));
269 } else if ((rule == ALLOW && type == DENYLIST) || (rule == DENY && type == ALLOWLIST)) {
270 RETURN_IF_NOT_OK(removeRule(uid, match));
271 } else {
272 //Cannot happen.
273 return statusFromErrno(EINVAL, "");
274 }
275 return netdutils::status::ok;
276}
277
278Status TrafficController::removeRule(uint32_t uid, UidOwnerMatchType match) {
279 auto oldMatch = mUidOwnerMap.readValue(uid);
280 if (oldMatch.ok()) {
281 UidOwnerValue newMatch = {
282 .iif = (match == IIF_MATCH) ? 0 : oldMatch.value().iif,
Motomu Utsumi42edc602022-05-12 13:57:42 +0000283 .rule = oldMatch.value().rule & ~match,
Wayne Ma4d692332022-01-19 16:04:04 +0800284 };
285 if (newMatch.rule == 0) {
286 RETURN_IF_NOT_OK(mUidOwnerMap.deleteValue(uid));
287 } else {
288 RETURN_IF_NOT_OK(mUidOwnerMap.writeValue(uid, newMatch, BPF_ANY));
289 }
290 } else {
291 return statusFromErrno(ENOENT, StringPrintf("uid: %u does not exist in map", uid));
292 }
293 return netdutils::status::ok;
294}
295
296Status TrafficController::addRule(uint32_t uid, UidOwnerMatchType match, uint32_t iif) {
Motomu Utsumib08654c2022-05-11 05:56:26 +0000297 if (match != IIF_MATCH && iif != 0) {
Wayne Ma4d692332022-01-19 16:04:04 +0800298 return statusFromErrno(EINVAL, "Non-interface match must have zero interface index");
299 }
300 auto oldMatch = mUidOwnerMap.readValue(uid);
301 if (oldMatch.ok()) {
302 UidOwnerValue newMatch = {
Motomu Utsumib08654c2022-05-11 05:56:26 +0000303 .iif = (match == IIF_MATCH) ? iif : oldMatch.value().iif,
Motomu Utsumi42edc602022-05-12 13:57:42 +0000304 .rule = oldMatch.value().rule | match,
Wayne Ma4d692332022-01-19 16:04:04 +0800305 };
306 RETURN_IF_NOT_OK(mUidOwnerMap.writeValue(uid, newMatch, BPF_ANY));
307 } else {
308 UidOwnerValue newMatch = {
309 .iif = iif,
Motomu Utsumi42edc602022-05-12 13:57:42 +0000310 .rule = match,
Wayne Ma4d692332022-01-19 16:04:04 +0800311 };
312 RETURN_IF_NOT_OK(mUidOwnerMap.writeValue(uid, newMatch, BPF_ANY));
313 }
314 return netdutils::status::ok;
315}
316
Wayne Maa9716ff2022-01-12 10:37:04 +0800317Status TrafficController::updateUidOwnerMap(const uint32_t uid,
Wayne Ma4d692332022-01-19 16:04:04 +0800318 UidOwnerMatchType matchType, IptOp op) {
319 std::lock_guard guard(mMutex);
Wayne Maa9716ff2022-01-12 10:37:04 +0800320 if (op == IptOpDelete) {
321 RETURN_IF_NOT_OK(removeRule(uid, matchType));
322 } else if (op == IptOpInsert) {
323 RETURN_IF_NOT_OK(addRule(uid, matchType));
324 } else {
325 // Cannot happen.
326 return statusFromErrno(EINVAL, StringPrintf("invalid IptOp: %d, %d", op, matchType));
Wayne Ma4d692332022-01-19 16:04:04 +0800327 }
328 return netdutils::status::ok;
329}
330
331FirewallType TrafficController::getFirewallType(ChildChain chain) {
332 switch (chain) {
333 case DOZABLE:
334 return ALLOWLIST;
335 case STANDBY:
336 return DENYLIST;
337 case POWERSAVE:
338 return ALLOWLIST;
339 case RESTRICTED:
340 return ALLOWLIST;
Robert Horvathd945bf02022-01-27 19:55:16 +0100341 case LOW_POWER_STANDBY:
342 return ALLOWLIST;
Motomu Utsumib08654c2022-05-11 05:56:26 +0000343 case LOCKDOWN:
344 return DENYLIST;
Motomu Utsumid9801492022-06-01 13:57:27 +0000345 case OEM_DENY_1:
346 return DENYLIST;
347 case OEM_DENY_2:
348 return DENYLIST;
Motomu Utsumi1d9054b2022-06-06 07:44:05 +0000349 case OEM_DENY_3:
350 return DENYLIST;
Wayne Ma4d692332022-01-19 16:04:04 +0800351 case NONE:
352 default:
353 return DENYLIST;
354 }
355}
356
357int TrafficController::changeUidOwnerRule(ChildChain chain, uid_t uid, FirewallRule rule,
358 FirewallType type) {
359 Status res;
360 switch (chain) {
361 case DOZABLE:
362 res = updateOwnerMapEntry(DOZABLE_MATCH, uid, rule, type);
363 break;
364 case STANDBY:
365 res = updateOwnerMapEntry(STANDBY_MATCH, uid, rule, type);
366 break;
367 case POWERSAVE:
368 res = updateOwnerMapEntry(POWERSAVE_MATCH, uid, rule, type);
369 break;
370 case RESTRICTED:
371 res = updateOwnerMapEntry(RESTRICTED_MATCH, uid, rule, type);
372 break;
Robert Horvathd945bf02022-01-27 19:55:16 +0100373 case LOW_POWER_STANDBY:
374 res = updateOwnerMapEntry(LOW_POWER_STANDBY_MATCH, uid, rule, type);
375 break;
Motomu Utsumib08654c2022-05-11 05:56:26 +0000376 case LOCKDOWN:
377 res = updateOwnerMapEntry(LOCKDOWN_VPN_MATCH, uid, rule, type);
378 break;
Motomu Utsumid9801492022-06-01 13:57:27 +0000379 case OEM_DENY_1:
380 res = updateOwnerMapEntry(OEM_DENY_1_MATCH, uid, rule, type);
381 break;
382 case OEM_DENY_2:
383 res = updateOwnerMapEntry(OEM_DENY_2_MATCH, uid, rule, type);
384 break;
Motomu Utsumi1d9054b2022-06-06 07:44:05 +0000385 case OEM_DENY_3:
386 res = updateOwnerMapEntry(OEM_DENY_3_MATCH, uid, rule, type);
387 break;
Wayne Ma4d692332022-01-19 16:04:04 +0800388 case NONE:
389 default:
390 ALOGW("Unknown child chain: %d", chain);
391 return -EINVAL;
392 }
393 if (!isOk(res)) {
394 ALOGE("change uid(%u) rule of %d failed: %s, rule: %d, type: %d", uid, chain,
395 res.msg().c_str(), rule, type);
396 return -res.code();
397 }
398 return 0;
399}
400
401Status TrafficController::replaceRulesInMap(const UidOwnerMatchType match,
402 const std::vector<int32_t>& uids) {
403 std::lock_guard guard(mMutex);
404 std::set<int32_t> uidSet(uids.begin(), uids.end());
405 std::vector<uint32_t> uidsToDelete;
406 auto getUidsToDelete = [&uidsToDelete, &uidSet](const uint32_t& key,
407 const BpfMap<uint32_t, UidOwnerValue>&) {
408 if (uidSet.find((int32_t) key) == uidSet.end()) {
409 uidsToDelete.push_back(key);
410 }
411 return base::Result<void>();
412 };
413 RETURN_IF_NOT_OK(mUidOwnerMap.iterate(getUidsToDelete));
414
415 for(auto uid : uidsToDelete) {
416 RETURN_IF_NOT_OK(removeRule(uid, match));
417 }
418
419 for (auto uid : uids) {
420 RETURN_IF_NOT_OK(addRule(uid, match));
421 }
422 return netdutils::status::ok;
423}
424
425Status TrafficController::addUidInterfaceRules(const int iif,
426 const std::vector<int32_t>& uidsToAdd) {
Wayne Ma4d692332022-01-19 16:04:04 +0800427 std::lock_guard guard(mMutex);
428
429 for (auto uid : uidsToAdd) {
430 netdutils::Status result = addRule(uid, IIF_MATCH, iif);
431 if (!isOk(result)) {
432 ALOGW("addRule failed(%d): uid=%d iif=%d", result.code(), uid, iif);
433 }
434 }
435 return netdutils::status::ok;
436}
437
438Status TrafficController::removeUidInterfaceRules(const std::vector<int32_t>& uidsToDelete) {
439 std::lock_guard guard(mMutex);
440
441 for (auto uid : uidsToDelete) {
442 netdutils::Status result = removeRule(uid, IIF_MATCH);
443 if (!isOk(result)) {
444 ALOGW("removeRule failed(%d): uid=%d", result.code(), uid);
445 }
446 }
447 return netdutils::status::ok;
448}
449
450int TrafficController::replaceUidOwnerMap(const std::string& name, bool isAllowlist __unused,
451 const std::vector<int32_t>& uids) {
452 // FirewallRule rule = isAllowlist ? ALLOW : DENY;
453 // FirewallType type = isAllowlist ? ALLOWLIST : DENYLIST;
454 Status res;
455 if (!name.compare(LOCAL_DOZABLE)) {
456 res = replaceRulesInMap(DOZABLE_MATCH, uids);
457 } else if (!name.compare(LOCAL_STANDBY)) {
458 res = replaceRulesInMap(STANDBY_MATCH, uids);
459 } else if (!name.compare(LOCAL_POWERSAVE)) {
460 res = replaceRulesInMap(POWERSAVE_MATCH, uids);
461 } else if (!name.compare(LOCAL_RESTRICTED)) {
462 res = replaceRulesInMap(RESTRICTED_MATCH, uids);
Robert Horvathd945bf02022-01-27 19:55:16 +0100463 } else if (!name.compare(LOCAL_LOW_POWER_STANDBY)) {
464 res = replaceRulesInMap(LOW_POWER_STANDBY_MATCH, uids);
Motomu Utsumid9801492022-06-01 13:57:27 +0000465 } else if (!name.compare(LOCAL_OEM_DENY_1)) {
466 res = replaceRulesInMap(OEM_DENY_1_MATCH, uids);
467 } else if (!name.compare(LOCAL_OEM_DENY_2)) {
468 res = replaceRulesInMap(OEM_DENY_2_MATCH, uids);
Motomu Utsumi1d9054b2022-06-06 07:44:05 +0000469 } else if (!name.compare(LOCAL_OEM_DENY_3)) {
470 res = replaceRulesInMap(OEM_DENY_3_MATCH, uids);
Wayne Ma4d692332022-01-19 16:04:04 +0800471 } else {
472 ALOGE("unknown chain name: %s", name.c_str());
473 return -EINVAL;
474 }
475 if (!isOk(res)) {
476 ALOGE("Failed to clean up chain: %s: %s", name.c_str(), res.msg().c_str());
477 return -res.code();
478 }
479 return 0;
480}
481
482int TrafficController::toggleUidOwnerMap(ChildChain chain, bool enable) {
483 std::lock_guard guard(mMutex);
484 uint32_t key = UID_RULES_CONFIGURATION_KEY;
Lorenzo Colitti60cbed32022-03-03 17:49:01 +0900485 auto oldConfigure = mConfigurationMap.readValue(key);
486 if (!oldConfigure.ok()) {
Wayne Ma4d692332022-01-19 16:04:04 +0800487 ALOGE("Cannot read the old configuration from map: %s",
Lorenzo Colitti60cbed32022-03-03 17:49:01 +0900488 oldConfigure.error().message().c_str());
489 return -oldConfigure.error().code();
Wayne Ma4d692332022-01-19 16:04:04 +0800490 }
491 Status res;
492 BpfConfig newConfiguration;
Lorenzo Colitti60cbed32022-03-03 17:49:01 +0900493 uint32_t match;
Wayne Ma4d692332022-01-19 16:04:04 +0800494 switch (chain) {
495 case DOZABLE:
496 match = DOZABLE_MATCH;
497 break;
498 case STANDBY:
499 match = STANDBY_MATCH;
500 break;
501 case POWERSAVE:
502 match = POWERSAVE_MATCH;
503 break;
504 case RESTRICTED:
505 match = RESTRICTED_MATCH;
506 break;
Robert Horvathd945bf02022-01-27 19:55:16 +0100507 case LOW_POWER_STANDBY:
508 match = LOW_POWER_STANDBY_MATCH;
509 break;
Motomu Utsumid9801492022-06-01 13:57:27 +0000510 case OEM_DENY_1:
511 match = OEM_DENY_1_MATCH;
512 break;
513 case OEM_DENY_2:
514 match = OEM_DENY_2_MATCH;
515 break;
Motomu Utsumi1d9054b2022-06-06 07:44:05 +0000516 case OEM_DENY_3:
517 match = OEM_DENY_3_MATCH;
518 break;
Wayne Ma4d692332022-01-19 16:04:04 +0800519 default:
520 return -EINVAL;
521 }
522 newConfiguration =
Lorenzo Colitti60cbed32022-03-03 17:49:01 +0900523 enable ? (oldConfigure.value() | match) : (oldConfigure.value() & (~match));
Wayne Ma4d692332022-01-19 16:04:04 +0800524 res = mConfigurationMap.writeValue(key, newConfiguration, BPF_EXIST);
525 if (!isOk(res)) {
526 ALOGE("Failed to toggleUidOwnerMap(%d): %s", chain, res.msg().c_str());
527 }
528 return -res.code();
529}
530
531Status TrafficController::swapActiveStatsMap() {
532 std::lock_guard guard(mMutex);
533
534 uint32_t key = CURRENT_STATS_MAP_CONFIGURATION_KEY;
Lorenzo Colitti60cbed32022-03-03 17:49:01 +0900535 auto oldConfigure = mConfigurationMap.readValue(key);
536 if (!oldConfigure.ok()) {
Wayne Ma4d692332022-01-19 16:04:04 +0800537 ALOGE("Cannot read the old configuration from map: %s",
Lorenzo Colitti60cbed32022-03-03 17:49:01 +0900538 oldConfigure.error().message().c_str());
539 return Status(oldConfigure.error().code(), oldConfigure.error().message());
Wayne Ma4d692332022-01-19 16:04:04 +0800540 }
541
542 // Write to the configuration map to inform the kernel eBPF program to switch
543 // from using one map to the other. Use flag BPF_EXIST here since the map should
544 // be already populated in initMaps.
Lorenzo Colitti60cbed32022-03-03 17:49:01 +0900545 uint32_t newConfigure = (oldConfigure.value() == SELECT_MAP_A) ? SELECT_MAP_B : SELECT_MAP_A;
Wayne Ma4d692332022-01-19 16:04:04 +0800546 auto res = mConfigurationMap.writeValue(CURRENT_STATS_MAP_CONFIGURATION_KEY, newConfigure,
547 BPF_EXIST);
548 if (!res.ok()) {
549 ALOGE("Failed to toggle the stats map: %s", strerror(res.error().code()));
550 return res;
551 }
552 // After changing the config, we need to make sure all the current running
553 // eBPF programs are finished and all the CPUs are aware of this config change
554 // before we modify the old map. So we do a special hack here to wait for
555 // the kernel to do a synchronize_rcu(). Once the kernel called
556 // synchronize_rcu(), the config we just updated will be available to all cores
557 // and the next eBPF programs triggered inside the kernel will use the new
558 // map configuration. So once this function returns we can safely modify the
559 // old stats map without concerning about race between the kernel and
560 // userspace.
561 int ret = synchronizeKernelRCU();
562 if (ret) {
563 ALOGE("map swap synchronize_rcu() ended with failure: %s", strerror(-ret));
564 return statusFromErrno(-ret, "map swap synchronize_rcu() failed");
565 }
566 return netdutils::status::ok;
567}
568
569void TrafficController::setPermissionForUids(int permission, const std::vector<uid_t>& uids) {
570 std::lock_guard guard(mMutex);
571 if (permission == INetd::PERMISSION_UNINSTALLED) {
572 for (uid_t uid : uids) {
573 // Clean up all permission information for the related uid if all the
574 // packages related to it are uninstalled.
575 mPrivilegedUser.erase(uid);
576 Status ret = mUidPermissionMap.deleteValue(uid);
577 if (!isOk(ret) && ret.code() != ENOENT) {
578 ALOGE("Failed to clean up the permission for %u: %s", uid, strerror(ret.code()));
579 }
580 }
581 return;
582 }
583
584 bool privileged = (permission & INetd::PERMISSION_UPDATE_DEVICE_STATS);
585
586 for (uid_t uid : uids) {
587 if (privileged) {
588 mPrivilegedUser.insert(uid);
589 } else {
590 mPrivilegedUser.erase(uid);
591 }
592
593 // The map stores all the permissions that the UID has, except if the only permission
594 // the UID has is the INTERNET permission, then the UID should not appear in the map.
595 if (permission != INetd::PERMISSION_INTERNET) {
596 Status ret = mUidPermissionMap.writeValue(uid, permission, BPF_ANY);
597 if (!isOk(ret)) {
598 ALOGE("Failed to set permission: %s of uid(%u) to permission map: %s",
599 UidPermissionTypeToString(permission).c_str(), uid, strerror(ret.code()));
600 }
601 } else {
602 Status ret = mUidPermissionMap.deleteValue(uid);
603 if (!isOk(ret) && ret.code() != ENOENT) {
604 ALOGE("Failed to remove uid %u from permission map: %s", uid, strerror(ret.code()));
605 }
606 }
607 }
608}
609
610std::string getProgramStatus(const char *path) {
611 int ret = access(path, R_OK);
612 if (ret == 0) {
613 return StringPrintf("OK");
614 }
615 if (ret != 0 && errno == ENOENT) {
616 return StringPrintf("program is missing at: %s", path);
617 }
618 return StringPrintf("check Program %s error: %s", path, strerror(errno));
619}
620
621std::string getMapStatus(const base::unique_fd& map_fd, const char* path) {
622 if (map_fd.get() < 0) {
623 return StringPrintf("map fd lost");
624 }
625 if (access(path, F_OK) != 0) {
626 return StringPrintf("map not pinned to location: %s", path);
627 }
628 return StringPrintf("OK");
629}
630
631// NOLINTNEXTLINE(google-runtime-references): grandfathered pass by non-const reference
632void dumpBpfMap(const std::string& mapName, DumpWriter& dw, const std::string& header) {
633 dw.blankline();
634 dw.println("%s:", mapName.c_str());
635 if (!header.empty()) {
636 dw.println(header);
637 }
638}
639
Ken Chene6d511f2022-01-25 11:10:42 +0800640void TrafficController::dump(int fd, bool verbose) {
Wayne Ma4d692332022-01-19 16:04:04 +0800641 std::lock_guard guard(mMutex);
Ken Chene6d511f2022-01-25 11:10:42 +0800642 DumpWriter dw(fd);
643
Wayne Ma4d692332022-01-19 16:04:04 +0800644 ScopedIndent indentTop(dw);
645 dw.println("TrafficController");
646
647 ScopedIndent indentPreBpfModule(dw);
648
649 dw.blankline();
650 dw.println("mCookieTagMap status: %s",
651 getMapStatus(mCookieTagMap.getMap(), COOKIE_TAG_MAP_PATH).c_str());
652 dw.println("mUidCounterSetMap status: %s",
653 getMapStatus(mUidCounterSetMap.getMap(), UID_COUNTERSET_MAP_PATH).c_str());
654 dw.println("mAppUidStatsMap status: %s",
655 getMapStatus(mAppUidStatsMap.getMap(), APP_UID_STATS_MAP_PATH).c_str());
656 dw.println("mStatsMapA status: %s",
657 getMapStatus(mStatsMapA.getMap(), STATS_MAP_A_PATH).c_str());
658 dw.println("mStatsMapB status: %s",
659 getMapStatus(mStatsMapB.getMap(), STATS_MAP_B_PATH).c_str());
660 dw.println("mIfaceIndexNameMap status: %s",
661 getMapStatus(mIfaceIndexNameMap.getMap(), IFACE_INDEX_NAME_MAP_PATH).c_str());
662 dw.println("mIfaceStatsMap status: %s",
663 getMapStatus(mIfaceStatsMap.getMap(), IFACE_STATS_MAP_PATH).c_str());
664 dw.println("mConfigurationMap status: %s",
665 getMapStatus(mConfigurationMap.getMap(), CONFIGURATION_MAP_PATH).c_str());
666 dw.println("mUidOwnerMap status: %s",
667 getMapStatus(mUidOwnerMap.getMap(), UID_OWNER_MAP_PATH).c_str());
668
669 dw.blankline();
670 dw.println("Cgroup ingress program status: %s",
671 getProgramStatus(BPF_INGRESS_PROG_PATH).c_str());
672 dw.println("Cgroup egress program status: %s", getProgramStatus(BPF_EGRESS_PROG_PATH).c_str());
673 dw.println("xt_bpf ingress program status: %s",
674 getProgramStatus(XT_BPF_INGRESS_PROG_PATH).c_str());
675 dw.println("xt_bpf egress program status: %s",
676 getProgramStatus(XT_BPF_EGRESS_PROG_PATH).c_str());
677 dw.println("xt_bpf bandwidth allowlist program status: %s",
678 getProgramStatus(XT_BPF_ALLOWLIST_PROG_PATH).c_str());
679 dw.println("xt_bpf bandwidth denylist program status: %s",
680 getProgramStatus(XT_BPF_DENYLIST_PROG_PATH).c_str());
681
682 if (!verbose) {
683 return;
684 }
685
686 dw.blankline();
687 dw.println("BPF map content:");
688
689 ScopedIndent indentForMapContent(dw);
690
691 // Print CookieTagMap content.
692 dumpBpfMap("mCookieTagMap", dw, "");
693 const auto printCookieTagInfo = [&dw](const uint64_t& key, const UidTagValue& value,
694 const BpfMap<uint64_t, UidTagValue>&) {
695 dw.println("cookie=%" PRIu64 " tag=0x%x uid=%u", key, value.tag, value.uid);
696 return base::Result<void>();
697 };
698 base::Result<void> res = mCookieTagMap.iterateWithValue(printCookieTagInfo);
699 if (!res.ok()) {
700 dw.println("mCookieTagMap print end with error: %s", res.error().message().c_str());
701 }
702
Wayne Maa9716ff2022-01-12 10:37:04 +0800703 // Print UidCounterSetMap content.
Wayne Ma4d692332022-01-19 16:04:04 +0800704 dumpBpfMap("mUidCounterSetMap", dw, "");
705 const auto printUidInfo = [&dw](const uint32_t& key, const uint8_t& value,
706 const BpfMap<uint32_t, uint8_t>&) {
707 dw.println("%u %u", key, value);
708 return base::Result<void>();
709 };
710 res = mUidCounterSetMap.iterateWithValue(printUidInfo);
711 if (!res.ok()) {
712 dw.println("mUidCounterSetMap print end with error: %s", res.error().message().c_str());
713 }
714
Wayne Maa9716ff2022-01-12 10:37:04 +0800715 // Print AppUidStatsMap content.
Wayne Ma4d692332022-01-19 16:04:04 +0800716 std::string appUidStatsHeader = StringPrintf("uid rxBytes rxPackets txBytes txPackets");
717 dumpBpfMap("mAppUidStatsMap:", dw, appUidStatsHeader);
718 auto printAppUidStatsInfo = [&dw](const uint32_t& key, const StatsValue& value,
719 const BpfMap<uint32_t, StatsValue>&) {
720 dw.println("%u %" PRIu64 " %" PRIu64 " %" PRIu64 " %" PRIu64, key, value.rxBytes,
721 value.rxPackets, value.txBytes, value.txPackets);
722 return base::Result<void>();
723 };
724 res = mAppUidStatsMap.iterateWithValue(printAppUidStatsInfo);
725 if (!res.ok()) {
726 dw.println("mAppUidStatsMap print end with error: %s", res.error().message().c_str());
727 }
728
Wayne Maa9716ff2022-01-12 10:37:04 +0800729 // Print uidStatsMap content.
Wayne Ma4d692332022-01-19 16:04:04 +0800730 std::string statsHeader = StringPrintf("ifaceIndex ifaceName tag_hex uid_int cnt_set rxBytes"
731 " rxPackets txBytes txPackets");
732 dumpBpfMap("mStatsMapA", dw, statsHeader);
733 const auto printStatsInfo = [&dw, this](const StatsKey& key, const StatsValue& value,
734 const BpfMap<StatsKey, StatsValue>&) {
735 uint32_t ifIndex = key.ifaceIndex;
736 auto ifname = mIfaceIndexNameMap.readValue(ifIndex);
737 if (!ifname.ok()) {
738 ifname = IfaceValue{"unknown"};
739 }
740 dw.println("%u %s 0x%x %u %u %" PRIu64 " %" PRIu64 " %" PRIu64 " %" PRIu64, ifIndex,
741 ifname.value().name, key.tag, key.uid, key.counterSet, value.rxBytes,
742 value.rxPackets, value.txBytes, value.txPackets);
743 return base::Result<void>();
744 };
745 res = mStatsMapA.iterateWithValue(printStatsInfo);
746 if (!res.ok()) {
747 dw.println("mStatsMapA print end with error: %s", res.error().message().c_str());
748 }
749
750 // Print TagStatsMap content.
751 dumpBpfMap("mStatsMapB", dw, statsHeader);
752 res = mStatsMapB.iterateWithValue(printStatsInfo);
753 if (!res.ok()) {
754 dw.println("mStatsMapB print end with error: %s", res.error().message().c_str());
755 }
756
757 // Print ifaceIndexToNameMap content.
758 dumpBpfMap("mIfaceIndexNameMap", dw, "");
759 const auto printIfaceNameInfo = [&dw](const uint32_t& key, const IfaceValue& value,
760 const BpfMap<uint32_t, IfaceValue>&) {
761 const char* ifname = value.name;
762 dw.println("ifaceIndex=%u ifaceName=%s", key, ifname);
763 return base::Result<void>();
764 };
765 res = mIfaceIndexNameMap.iterateWithValue(printIfaceNameInfo);
766 if (!res.ok()) {
767 dw.println("mIfaceIndexNameMap print end with error: %s", res.error().message().c_str());
768 }
769
770 // Print ifaceStatsMap content
771 std::string ifaceStatsHeader = StringPrintf("ifaceIndex ifaceName rxBytes rxPackets txBytes"
772 " txPackets");
773 dumpBpfMap("mIfaceStatsMap:", dw, ifaceStatsHeader);
774 const auto printIfaceStatsInfo = [&dw, this](const uint32_t& key, const StatsValue& value,
775 const BpfMap<uint32_t, StatsValue>&) {
776 auto ifname = mIfaceIndexNameMap.readValue(key);
777 if (!ifname.ok()) {
778 ifname = IfaceValue{"unknown"};
779 }
780 dw.println("%u %s %" PRIu64 " %" PRIu64 " %" PRIu64 " %" PRIu64, key, ifname.value().name,
781 value.rxBytes, value.rxPackets, value.txBytes, value.txPackets);
782 return base::Result<void>();
783 };
784 res = mIfaceStatsMap.iterateWithValue(printIfaceStatsInfo);
785 if (!res.ok()) {
786 dw.println("mIfaceStatsMap print end with error: %s", res.error().message().c_str());
787 }
788
789 dw.blankline();
790
791 uint32_t key = UID_RULES_CONFIGURATION_KEY;
792 auto configuration = mConfigurationMap.readValue(key);
793 if (configuration.ok()) {
794 dw.println("current ownerMatch configuration: %d%s", configuration.value(),
795 uidMatchTypeToString(configuration.value()).c_str());
796 } else {
797 dw.println("mConfigurationMap read ownerMatch configure failed with error: %s",
798 configuration.error().message().c_str());
799 }
800
801 key = CURRENT_STATS_MAP_CONFIGURATION_KEY;
802 configuration = mConfigurationMap.readValue(key);
803 if (configuration.ok()) {
804 const char* statsMapDescription = "???";
805 switch (configuration.value()) {
806 case SELECT_MAP_A:
807 statsMapDescription = "SELECT_MAP_A";
808 break;
809 case SELECT_MAP_B:
810 statsMapDescription = "SELECT_MAP_B";
811 break;
812 // No default clause, so if we ever add a third map, this code will fail to build.
813 }
814 dw.println("current statsMap configuration: %d %s", configuration.value(),
815 statsMapDescription);
816 } else {
817 dw.println("mConfigurationMap read stats map configure failed with error: %s",
818 configuration.error().message().c_str());
819 }
820 dumpBpfMap("mUidOwnerMap", dw, "");
821 const auto printUidMatchInfo = [&dw, this](const uint32_t& key, const UidOwnerValue& value,
822 const BpfMap<uint32_t, UidOwnerValue>&) {
823 if (value.rule & IIF_MATCH) {
824 auto ifname = mIfaceIndexNameMap.readValue(value.iif);
825 if (ifname.ok()) {
826 dw.println("%u %s %s", key, uidMatchTypeToString(value.rule).c_str(),
827 ifname.value().name);
828 } else {
829 dw.println("%u %s %u", key, uidMatchTypeToString(value.rule).c_str(), value.iif);
830 }
831 } else {
832 dw.println("%u %s", key, uidMatchTypeToString(value.rule).c_str());
833 }
834 return base::Result<void>();
835 };
836 res = mUidOwnerMap.iterateWithValue(printUidMatchInfo);
837 if (!res.ok()) {
838 dw.println("mUidOwnerMap print end with error: %s", res.error().message().c_str());
839 }
840 dumpBpfMap("mUidPermissionMap", dw, "");
841 const auto printUidPermissionInfo = [&dw](const uint32_t& key, const int& value,
842 const BpfMap<uint32_t, uint8_t>&) {
843 dw.println("%u %s", key, UidPermissionTypeToString(value).c_str());
844 return base::Result<void>();
845 };
846 res = mUidPermissionMap.iterateWithValue(printUidPermissionInfo);
847 if (!res.ok()) {
848 dw.println("mUidPermissionMap print end with error: %s", res.error().message().c_str());
849 }
850
851 dumpBpfMap("mPrivilegedUser", dw, "");
852 for (uid_t uid : mPrivilegedUser) {
853 dw.println("%u ALLOW_UPDATE_DEVICE_STATS", (uint32_t)uid);
854 }
855}
856
857} // namespace net
858} // namespace android