blob: 9331548e3f8ae7aa8e938672f75f212c8c251d14 [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::NetlinkListener;
60using netdutils::NetlinkListenerInterface;
61using netdutils::ScopedIndent;
62using netdutils::Slice;
63using netdutils::sSyscalls;
64using netdutils::Status;
65using netdutils::statusFromErrno;
66using netdutils::StatusOr;
Wayne Ma4d692332022-01-19 16:04:04 +080067
68constexpr int kSockDiagMsgType = SOCK_DIAG_BY_FAMILY;
69constexpr int kSockDiagDoneMsgType = NLMSG_DONE;
Wayne Ma4d692332022-01-19 16:04:04 +080070
71const char* TrafficController::LOCAL_DOZABLE = "fw_dozable";
72const char* TrafficController::LOCAL_STANDBY = "fw_standby";
73const char* TrafficController::LOCAL_POWERSAVE = "fw_powersave";
74const char* TrafficController::LOCAL_RESTRICTED = "fw_restricted";
Robert Horvathd945bf02022-01-27 19:55:16 +010075const char* TrafficController::LOCAL_LOW_POWER_STANDBY = "fw_low_power_standby";
Motomu Utsumid9801492022-06-01 13:57:27 +000076const char* TrafficController::LOCAL_OEM_DENY_1 = "fw_oem_deny_1";
77const char* TrafficController::LOCAL_OEM_DENY_2 = "fw_oem_deny_2";
Motomu Utsumi1d9054b2022-06-06 07:44:05 +000078const char* TrafficController::LOCAL_OEM_DENY_3 = "fw_oem_deny_3";
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);
Motomu Utsumi1d9054b2022-06-06 07:44:05 +0000106 FLAG_MSG_TRANS(matchType, OEM_DENY_3_MATCH, match);
Wayne Ma4d692332022-01-19 16:04:04 +0800107 if (match) {
108 return StringPrintf("Unknown match: %u", match);
109 }
110 return matchType;
111}
112
Wayne Ma4d692332022-01-19 16:04:04 +0800113const std::string UidPermissionTypeToString(int permission) {
114 if (permission == INetd::PERMISSION_NONE) {
115 return "PERMISSION_NONE";
116 }
117 if (permission == INetd::PERMISSION_UNINSTALLED) {
118 // This should never appear in the map, complain loudly if it does.
119 return "PERMISSION_UNINSTALLED error!";
120 }
121 std::string permissionType;
122 FLAG_MSG_TRANS(permissionType, BPF_PERMISSION_INTERNET, permission);
123 FLAG_MSG_TRANS(permissionType, BPF_PERMISSION_UPDATE_DEVICE_STATS, permission);
124 if (permission) {
125 return StringPrintf("Unknown permission: %u", permission);
126 }
127 return permissionType;
128}
129
130StatusOr<std::unique_ptr<NetlinkListenerInterface>> TrafficController::makeSkDestroyListener() {
131 const auto& sys = sSyscalls.get();
132 ASSIGN_OR_RETURN(auto event, sys.eventfd(0, EFD_CLOEXEC));
133 const int domain = AF_NETLINK;
134 const int type = SOCK_DGRAM | SOCK_CLOEXEC | SOCK_NONBLOCK;
135 const int protocol = NETLINK_INET_DIAG;
136 ASSIGN_OR_RETURN(auto sock, sys.socket(domain, type, protocol));
137
138 // TODO: if too many sockets are closed too quickly, we can overflow the socket buffer, and
139 // some entries in mCookieTagMap will not be freed. In order to fix this we would need to
140 // periodically dump all sockets and remove the tag entries for sockets that have been closed.
141 // For now, set a large-enough buffer that we can close hundreds of sockets without getting
142 // ENOBUFS and leaking mCookieTagMap entries.
143 int rcvbuf = 512 * 1024;
144 auto ret = sys.setsockopt(sock, SOL_SOCKET, SO_RCVBUF, &rcvbuf, sizeof(rcvbuf));
145 if (!ret.ok()) {
146 ALOGW("Failed to set SkDestroyListener buffer size to %d: %s", rcvbuf, ret.msg().c_str());
147 }
148
149 sockaddr_nl addr = {
150 .nl_family = AF_NETLINK,
151 .nl_groups = 1 << (SKNLGRP_INET_TCP_DESTROY - 1) | 1 << (SKNLGRP_INET_UDP_DESTROY - 1) |
152 1 << (SKNLGRP_INET6_TCP_DESTROY - 1) | 1 << (SKNLGRP_INET6_UDP_DESTROY - 1)};
153 RETURN_IF_NOT_OK(sys.bind(sock, addr));
154
155 const sockaddr_nl kernel = {.nl_family = AF_NETLINK};
156 RETURN_IF_NOT_OK(sys.connect(sock, kernel));
157
158 std::unique_ptr<NetlinkListenerInterface> listener =
159 std::make_unique<NetlinkListener>(std::move(event), std::move(sock), "SkDestroyListen");
160
161 return listener;
162}
163
Wayne Ma4d692332022-01-19 16:04:04 +0800164Status TrafficController::initMaps() {
165 std::lock_guard guard(mMutex);
166
167 RETURN_IF_NOT_OK(mCookieTagMap.init(COOKIE_TAG_MAP_PATH));
168 RETURN_IF_NOT_OK(mUidCounterSetMap.init(UID_COUNTERSET_MAP_PATH));
169 RETURN_IF_NOT_OK(mAppUidStatsMap.init(APP_UID_STATS_MAP_PATH));
170 RETURN_IF_NOT_OK(mStatsMapA.init(STATS_MAP_A_PATH));
171 RETURN_IF_NOT_OK(mStatsMapB.init(STATS_MAP_B_PATH));
172 RETURN_IF_NOT_OK(mIfaceIndexNameMap.init(IFACE_INDEX_NAME_MAP_PATH));
173 RETURN_IF_NOT_OK(mIfaceStatsMap.init(IFACE_STATS_MAP_PATH));
174
175 RETURN_IF_NOT_OK(mConfigurationMap.init(CONFIGURATION_MAP_PATH));
176 RETURN_IF_NOT_OK(
177 mConfigurationMap.writeValue(UID_RULES_CONFIGURATION_KEY, DEFAULT_CONFIG, BPF_ANY));
178 RETURN_IF_NOT_OK(mConfigurationMap.writeValue(CURRENT_STATS_MAP_CONFIGURATION_KEY, SELECT_MAP_A,
179 BPF_ANY));
180
181 RETURN_IF_NOT_OK(mUidOwnerMap.init(UID_OWNER_MAP_PATH));
182 RETURN_IF_NOT_OK(mUidOwnerMap.clear());
183 RETURN_IF_NOT_OK(mUidPermissionMap.init(UID_PERMISSION_MAP_PATH));
Ken Chen322ffcb2022-05-23 22:27:40 +0800184 ALOGI("%s successfully", __func__);
Wayne Ma4d692332022-01-19 16:04:04 +0800185
186 return netdutils::status::ok;
187}
188
Wayne Ma4d692332022-01-19 16:04:04 +0800189Status TrafficController::start() {
Wayne Ma4d692332022-01-19 16:04:04 +0800190 RETURN_IF_NOT_OK(initMaps());
191
Wayne Ma4d692332022-01-19 16:04:04 +0800192 auto result = makeSkDestroyListener();
193 if (!isOk(result)) {
194 ALOGE("Unable to create SkDestroyListener: %s", toString(result).c_str());
195 } else {
196 mSkDestroyListener = std::move(result.value());
197 }
198 // Rx handler extracts nfgenmsg looks up and invokes registered dispatch function.
199 const auto rxHandler = [this](const nlmsghdr&, const Slice msg) {
200 std::lock_guard guard(mMutex);
201 inet_diag_msg diagmsg = {};
202 if (extract(msg, diagmsg) < sizeof(inet_diag_msg)) {
203 ALOGE("Unrecognized netlink message: %s", toString(msg).c_str());
204 return;
205 }
206 uint64_t sock_cookie = static_cast<uint64_t>(diagmsg.id.idiag_cookie[0]) |
207 (static_cast<uint64_t>(diagmsg.id.idiag_cookie[1]) << 32);
208
209 Status s = mCookieTagMap.deleteValue(sock_cookie);
210 if (!isOk(s) && s.code() != ENOENT) {
211 ALOGE("Failed to delete cookie %" PRIx64 ": %s", sock_cookie, toString(s).c_str());
212 return;
213 }
214 };
215 expectOk(mSkDestroyListener->subscribe(kSockDiagMsgType, rxHandler));
216
217 // In case multiple netlink message comes in as a stream, we need to handle the rxDone message
218 // properly.
219 const auto rxDoneHandler = [](const nlmsghdr&, const Slice msg) {
220 // Ignore NLMSG_DONE messages
221 inet_diag_msg diagmsg = {};
222 extract(msg, diagmsg);
223 };
224 expectOk(mSkDestroyListener->subscribe(kSockDiagDoneMsgType, rxDoneHandler));
225
226 return netdutils::status::ok;
227}
228
Wayne Ma4d692332022-01-19 16:04:04 +0800229Status TrafficController::updateOwnerMapEntry(UidOwnerMatchType match, uid_t uid, FirewallRule rule,
230 FirewallType type) {
231 std::lock_guard guard(mMutex);
232 if ((rule == ALLOW && type == ALLOWLIST) || (rule == DENY && type == DENYLIST)) {
233 RETURN_IF_NOT_OK(addRule(uid, match));
234 } else if ((rule == ALLOW && type == DENYLIST) || (rule == DENY && type == ALLOWLIST)) {
235 RETURN_IF_NOT_OK(removeRule(uid, match));
236 } else {
237 //Cannot happen.
238 return statusFromErrno(EINVAL, "");
239 }
240 return netdutils::status::ok;
241}
242
243Status TrafficController::removeRule(uint32_t uid, UidOwnerMatchType match) {
244 auto oldMatch = mUidOwnerMap.readValue(uid);
245 if (oldMatch.ok()) {
246 UidOwnerValue newMatch = {
247 .iif = (match == IIF_MATCH) ? 0 : oldMatch.value().iif,
Motomu Utsumi42edc602022-05-12 13:57:42 +0000248 .rule = oldMatch.value().rule & ~match,
Wayne Ma4d692332022-01-19 16:04:04 +0800249 };
250 if (newMatch.rule == 0) {
251 RETURN_IF_NOT_OK(mUidOwnerMap.deleteValue(uid));
252 } else {
253 RETURN_IF_NOT_OK(mUidOwnerMap.writeValue(uid, newMatch, BPF_ANY));
254 }
255 } else {
256 return statusFromErrno(ENOENT, StringPrintf("uid: %u does not exist in map", uid));
257 }
258 return netdutils::status::ok;
259}
260
261Status TrafficController::addRule(uint32_t uid, UidOwnerMatchType match, uint32_t iif) {
Motomu Utsumib08654c2022-05-11 05:56:26 +0000262 if (match != IIF_MATCH && iif != 0) {
Wayne Ma4d692332022-01-19 16:04:04 +0800263 return statusFromErrno(EINVAL, "Non-interface match must have zero interface index");
264 }
265 auto oldMatch = mUidOwnerMap.readValue(uid);
266 if (oldMatch.ok()) {
267 UidOwnerValue newMatch = {
Motomu Utsumib08654c2022-05-11 05:56:26 +0000268 .iif = (match == IIF_MATCH) ? iif : oldMatch.value().iif,
Motomu Utsumi42edc602022-05-12 13:57:42 +0000269 .rule = oldMatch.value().rule | match,
Wayne Ma4d692332022-01-19 16:04:04 +0800270 };
271 RETURN_IF_NOT_OK(mUidOwnerMap.writeValue(uid, newMatch, BPF_ANY));
272 } else {
273 UidOwnerValue newMatch = {
274 .iif = iif,
Motomu Utsumi42edc602022-05-12 13:57:42 +0000275 .rule = match,
Wayne Ma4d692332022-01-19 16:04:04 +0800276 };
277 RETURN_IF_NOT_OK(mUidOwnerMap.writeValue(uid, newMatch, BPF_ANY));
278 }
279 return netdutils::status::ok;
280}
281
Wayne Maa9716ff2022-01-12 10:37:04 +0800282Status TrafficController::updateUidOwnerMap(const uint32_t uid,
Wayne Ma4d692332022-01-19 16:04:04 +0800283 UidOwnerMatchType matchType, IptOp op) {
284 std::lock_guard guard(mMutex);
Wayne Maa9716ff2022-01-12 10:37:04 +0800285 if (op == IptOpDelete) {
286 RETURN_IF_NOT_OK(removeRule(uid, matchType));
287 } else if (op == IptOpInsert) {
288 RETURN_IF_NOT_OK(addRule(uid, matchType));
289 } else {
290 // Cannot happen.
291 return statusFromErrno(EINVAL, StringPrintf("invalid IptOp: %d, %d", op, matchType));
Wayne Ma4d692332022-01-19 16:04:04 +0800292 }
293 return netdutils::status::ok;
294}
295
296FirewallType TrafficController::getFirewallType(ChildChain chain) {
297 switch (chain) {
298 case DOZABLE:
299 return ALLOWLIST;
300 case STANDBY:
301 return DENYLIST;
302 case POWERSAVE:
303 return ALLOWLIST;
304 case RESTRICTED:
305 return ALLOWLIST;
Robert Horvathd945bf02022-01-27 19:55:16 +0100306 case LOW_POWER_STANDBY:
307 return ALLOWLIST;
Motomu Utsumid9801492022-06-01 13:57:27 +0000308 case OEM_DENY_1:
309 return DENYLIST;
310 case OEM_DENY_2:
311 return DENYLIST;
Motomu Utsumi1d9054b2022-06-06 07:44:05 +0000312 case OEM_DENY_3:
313 return DENYLIST;
Wayne Ma4d692332022-01-19 16:04:04 +0800314 case NONE:
315 default:
316 return DENYLIST;
317 }
318}
319
320int TrafficController::changeUidOwnerRule(ChildChain chain, uid_t uid, FirewallRule rule,
321 FirewallType type) {
322 Status res;
323 switch (chain) {
324 case DOZABLE:
325 res = updateOwnerMapEntry(DOZABLE_MATCH, uid, rule, type);
326 break;
327 case STANDBY:
328 res = updateOwnerMapEntry(STANDBY_MATCH, uid, rule, type);
329 break;
330 case POWERSAVE:
331 res = updateOwnerMapEntry(POWERSAVE_MATCH, uid, rule, type);
332 break;
333 case RESTRICTED:
334 res = updateOwnerMapEntry(RESTRICTED_MATCH, uid, rule, type);
335 break;
Robert Horvathd945bf02022-01-27 19:55:16 +0100336 case LOW_POWER_STANDBY:
337 res = updateOwnerMapEntry(LOW_POWER_STANDBY_MATCH, uid, rule, type);
338 break;
Motomu Utsumid9801492022-06-01 13:57:27 +0000339 case OEM_DENY_1:
340 res = updateOwnerMapEntry(OEM_DENY_1_MATCH, uid, rule, type);
341 break;
342 case OEM_DENY_2:
343 res = updateOwnerMapEntry(OEM_DENY_2_MATCH, uid, rule, type);
344 break;
Motomu Utsumi1d9054b2022-06-06 07:44:05 +0000345 case OEM_DENY_3:
346 res = updateOwnerMapEntry(OEM_DENY_3_MATCH, uid, rule, type);
347 break;
Wayne Ma4d692332022-01-19 16:04:04 +0800348 case NONE:
349 default:
350 ALOGW("Unknown child chain: %d", chain);
351 return -EINVAL;
352 }
353 if (!isOk(res)) {
354 ALOGE("change uid(%u) rule of %d failed: %s, rule: %d, type: %d", uid, chain,
355 res.msg().c_str(), rule, type);
356 return -res.code();
357 }
358 return 0;
359}
360
361Status TrafficController::replaceRulesInMap(const UidOwnerMatchType match,
362 const std::vector<int32_t>& uids) {
363 std::lock_guard guard(mMutex);
364 std::set<int32_t> uidSet(uids.begin(), uids.end());
365 std::vector<uint32_t> uidsToDelete;
366 auto getUidsToDelete = [&uidsToDelete, &uidSet](const uint32_t& key,
367 const BpfMap<uint32_t, UidOwnerValue>&) {
368 if (uidSet.find((int32_t) key) == uidSet.end()) {
369 uidsToDelete.push_back(key);
370 }
371 return base::Result<void>();
372 };
373 RETURN_IF_NOT_OK(mUidOwnerMap.iterate(getUidsToDelete));
374
375 for(auto uid : uidsToDelete) {
376 RETURN_IF_NOT_OK(removeRule(uid, match));
377 }
378
379 for (auto uid : uids) {
380 RETURN_IF_NOT_OK(addRule(uid, match));
381 }
382 return netdutils::status::ok;
383}
384
385Status TrafficController::addUidInterfaceRules(const int iif,
386 const std::vector<int32_t>& uidsToAdd) {
Wayne Ma4d692332022-01-19 16:04:04 +0800387 std::lock_guard guard(mMutex);
388
389 for (auto uid : uidsToAdd) {
390 netdutils::Status result = addRule(uid, IIF_MATCH, iif);
391 if (!isOk(result)) {
392 ALOGW("addRule failed(%d): uid=%d iif=%d", result.code(), uid, iif);
393 }
394 }
395 return netdutils::status::ok;
396}
397
398Status TrafficController::removeUidInterfaceRules(const std::vector<int32_t>& uidsToDelete) {
399 std::lock_guard guard(mMutex);
400
401 for (auto uid : uidsToDelete) {
402 netdutils::Status result = removeRule(uid, IIF_MATCH);
403 if (!isOk(result)) {
404 ALOGW("removeRule failed(%d): uid=%d", result.code(), uid);
405 }
406 }
407 return netdutils::status::ok;
408}
409
Motomu Utsumi8b42e6d2022-05-19 06:23:40 +0000410Status TrafficController::updateUidLockdownRule(const uid_t uid, const bool add) {
411 std::lock_guard guard(mMutex);
412
413 netdutils::Status result = add ? addRule(uid, LOCKDOWN_VPN_MATCH)
414 : removeRule(uid, LOCKDOWN_VPN_MATCH);
415 if (!isOk(result)) {
416 ALOGW("%s Lockdown rule failed(%d): uid=%d",
417 (add ? "add": "remove"), result.code(), uid);
418 }
419 return result;
420}
421
Wayne Ma4d692332022-01-19 16:04:04 +0800422int TrafficController::replaceUidOwnerMap(const std::string& name, bool isAllowlist __unused,
423 const std::vector<int32_t>& uids) {
424 // FirewallRule rule = isAllowlist ? ALLOW : DENY;
425 // FirewallType type = isAllowlist ? ALLOWLIST : DENYLIST;
426 Status res;
427 if (!name.compare(LOCAL_DOZABLE)) {
428 res = replaceRulesInMap(DOZABLE_MATCH, uids);
429 } else if (!name.compare(LOCAL_STANDBY)) {
430 res = replaceRulesInMap(STANDBY_MATCH, uids);
431 } else if (!name.compare(LOCAL_POWERSAVE)) {
432 res = replaceRulesInMap(POWERSAVE_MATCH, uids);
433 } else if (!name.compare(LOCAL_RESTRICTED)) {
434 res = replaceRulesInMap(RESTRICTED_MATCH, uids);
Robert Horvathd945bf02022-01-27 19:55:16 +0100435 } else if (!name.compare(LOCAL_LOW_POWER_STANDBY)) {
436 res = replaceRulesInMap(LOW_POWER_STANDBY_MATCH, uids);
Motomu Utsumid9801492022-06-01 13:57:27 +0000437 } else if (!name.compare(LOCAL_OEM_DENY_1)) {
438 res = replaceRulesInMap(OEM_DENY_1_MATCH, uids);
439 } else if (!name.compare(LOCAL_OEM_DENY_2)) {
440 res = replaceRulesInMap(OEM_DENY_2_MATCH, uids);
Motomu Utsumi1d9054b2022-06-06 07:44:05 +0000441 } else if (!name.compare(LOCAL_OEM_DENY_3)) {
442 res = replaceRulesInMap(OEM_DENY_3_MATCH, uids);
Wayne Ma4d692332022-01-19 16:04:04 +0800443 } else {
444 ALOGE("unknown chain name: %s", name.c_str());
445 return -EINVAL;
446 }
447 if (!isOk(res)) {
448 ALOGE("Failed to clean up chain: %s: %s", name.c_str(), res.msg().c_str());
449 return -res.code();
450 }
451 return 0;
452}
453
Wayne Ma4d692332022-01-19 16:04:04 +0800454Status TrafficController::swapActiveStatsMap() {
455 std::lock_guard guard(mMutex);
456
457 uint32_t key = CURRENT_STATS_MAP_CONFIGURATION_KEY;
Lorenzo Colitti60cbed32022-03-03 17:49:01 +0900458 auto oldConfigure = mConfigurationMap.readValue(key);
459 if (!oldConfigure.ok()) {
Wayne Ma4d692332022-01-19 16:04:04 +0800460 ALOGE("Cannot read the old configuration from map: %s",
Lorenzo Colitti60cbed32022-03-03 17:49:01 +0900461 oldConfigure.error().message().c_str());
462 return Status(oldConfigure.error().code(), oldConfigure.error().message());
Wayne Ma4d692332022-01-19 16:04:04 +0800463 }
464
465 // Write to the configuration map to inform the kernel eBPF program to switch
466 // from using one map to the other. Use flag BPF_EXIST here since the map should
467 // be already populated in initMaps.
Lorenzo Colitti60cbed32022-03-03 17:49:01 +0900468 uint32_t newConfigure = (oldConfigure.value() == SELECT_MAP_A) ? SELECT_MAP_B : SELECT_MAP_A;
Wayne Ma4d692332022-01-19 16:04:04 +0800469 auto res = mConfigurationMap.writeValue(CURRENT_STATS_MAP_CONFIGURATION_KEY, newConfigure,
470 BPF_EXIST);
471 if (!res.ok()) {
472 ALOGE("Failed to toggle the stats map: %s", strerror(res.error().code()));
473 return res;
474 }
475 // After changing the config, we need to make sure all the current running
476 // eBPF programs are finished and all the CPUs are aware of this config change
477 // before we modify the old map. So we do a special hack here to wait for
478 // the kernel to do a synchronize_rcu(). Once the kernel called
479 // synchronize_rcu(), the config we just updated will be available to all cores
480 // and the next eBPF programs triggered inside the kernel will use the new
481 // map configuration. So once this function returns we can safely modify the
482 // old stats map without concerning about race between the kernel and
483 // userspace.
484 int ret = synchronizeKernelRCU();
485 if (ret) {
486 ALOGE("map swap synchronize_rcu() ended with failure: %s", strerror(-ret));
487 return statusFromErrno(-ret, "map swap synchronize_rcu() failed");
488 }
489 return netdutils::status::ok;
490}
491
492void TrafficController::setPermissionForUids(int permission, const std::vector<uid_t>& uids) {
493 std::lock_guard guard(mMutex);
494 if (permission == INetd::PERMISSION_UNINSTALLED) {
495 for (uid_t uid : uids) {
496 // Clean up all permission information for the related uid if all the
497 // packages related to it are uninstalled.
498 mPrivilegedUser.erase(uid);
499 Status ret = mUidPermissionMap.deleteValue(uid);
500 if (!isOk(ret) && ret.code() != ENOENT) {
501 ALOGE("Failed to clean up the permission for %u: %s", uid, strerror(ret.code()));
502 }
503 }
504 return;
505 }
506
507 bool privileged = (permission & INetd::PERMISSION_UPDATE_DEVICE_STATS);
508
509 for (uid_t uid : uids) {
510 if (privileged) {
511 mPrivilegedUser.insert(uid);
512 } else {
513 mPrivilegedUser.erase(uid);
514 }
515
516 // The map stores all the permissions that the UID has, except if the only permission
517 // the UID has is the INTERNET permission, then the UID should not appear in the map.
518 if (permission != INetd::PERMISSION_INTERNET) {
519 Status ret = mUidPermissionMap.writeValue(uid, permission, BPF_ANY);
520 if (!isOk(ret)) {
521 ALOGE("Failed to set permission: %s of uid(%u) to permission map: %s",
522 UidPermissionTypeToString(permission).c_str(), uid, strerror(ret.code()));
523 }
524 } else {
525 Status ret = mUidPermissionMap.deleteValue(uid);
526 if (!isOk(ret) && ret.code() != ENOENT) {
527 ALOGE("Failed to remove uid %u from permission map: %s", uid, strerror(ret.code()));
528 }
529 }
530 }
531}
532
533std::string getProgramStatus(const char *path) {
534 int ret = access(path, R_OK);
535 if (ret == 0) {
536 return StringPrintf("OK");
537 }
538 if (ret != 0 && errno == ENOENT) {
539 return StringPrintf("program is missing at: %s", path);
540 }
541 return StringPrintf("check Program %s error: %s", path, strerror(errno));
542}
543
544std::string getMapStatus(const base::unique_fd& map_fd, const char* path) {
545 if (map_fd.get() < 0) {
546 return StringPrintf("map fd lost");
547 }
548 if (access(path, F_OK) != 0) {
549 return StringPrintf("map not pinned to location: %s", path);
550 }
551 return StringPrintf("OK");
552}
553
554// NOLINTNEXTLINE(google-runtime-references): grandfathered pass by non-const reference
555void dumpBpfMap(const std::string& mapName, DumpWriter& dw, const std::string& header) {
556 dw.blankline();
557 dw.println("%s:", mapName.c_str());
558 if (!header.empty()) {
559 dw.println(header);
560 }
561}
562
Ken Chene6d511f2022-01-25 11:10:42 +0800563void TrafficController::dump(int fd, bool verbose) {
Wayne Ma4d692332022-01-19 16:04:04 +0800564 std::lock_guard guard(mMutex);
Ken Chene6d511f2022-01-25 11:10:42 +0800565 DumpWriter dw(fd);
566
Wayne Ma4d692332022-01-19 16:04:04 +0800567 ScopedIndent indentTop(dw);
568 dw.println("TrafficController");
569
570 ScopedIndent indentPreBpfModule(dw);
571
572 dw.blankline();
573 dw.println("mCookieTagMap status: %s",
574 getMapStatus(mCookieTagMap.getMap(), COOKIE_TAG_MAP_PATH).c_str());
575 dw.println("mUidCounterSetMap status: %s",
576 getMapStatus(mUidCounterSetMap.getMap(), UID_COUNTERSET_MAP_PATH).c_str());
577 dw.println("mAppUidStatsMap status: %s",
578 getMapStatus(mAppUidStatsMap.getMap(), APP_UID_STATS_MAP_PATH).c_str());
579 dw.println("mStatsMapA status: %s",
580 getMapStatus(mStatsMapA.getMap(), STATS_MAP_A_PATH).c_str());
581 dw.println("mStatsMapB status: %s",
582 getMapStatus(mStatsMapB.getMap(), STATS_MAP_B_PATH).c_str());
583 dw.println("mIfaceIndexNameMap status: %s",
584 getMapStatus(mIfaceIndexNameMap.getMap(), IFACE_INDEX_NAME_MAP_PATH).c_str());
585 dw.println("mIfaceStatsMap status: %s",
586 getMapStatus(mIfaceStatsMap.getMap(), IFACE_STATS_MAP_PATH).c_str());
587 dw.println("mConfigurationMap status: %s",
588 getMapStatus(mConfigurationMap.getMap(), CONFIGURATION_MAP_PATH).c_str());
589 dw.println("mUidOwnerMap status: %s",
590 getMapStatus(mUidOwnerMap.getMap(), UID_OWNER_MAP_PATH).c_str());
591
592 dw.blankline();
593 dw.println("Cgroup ingress program status: %s",
594 getProgramStatus(BPF_INGRESS_PROG_PATH).c_str());
595 dw.println("Cgroup egress program status: %s", getProgramStatus(BPF_EGRESS_PROG_PATH).c_str());
596 dw.println("xt_bpf ingress program status: %s",
597 getProgramStatus(XT_BPF_INGRESS_PROG_PATH).c_str());
598 dw.println("xt_bpf egress program status: %s",
599 getProgramStatus(XT_BPF_EGRESS_PROG_PATH).c_str());
600 dw.println("xt_bpf bandwidth allowlist program status: %s",
601 getProgramStatus(XT_BPF_ALLOWLIST_PROG_PATH).c_str());
602 dw.println("xt_bpf bandwidth denylist program status: %s",
603 getProgramStatus(XT_BPF_DENYLIST_PROG_PATH).c_str());
604
605 if (!verbose) {
606 return;
607 }
608
609 dw.blankline();
610 dw.println("BPF map content:");
611
612 ScopedIndent indentForMapContent(dw);
613
614 // Print CookieTagMap content.
615 dumpBpfMap("mCookieTagMap", dw, "");
616 const auto printCookieTagInfo = [&dw](const uint64_t& key, const UidTagValue& value,
617 const BpfMap<uint64_t, UidTagValue>&) {
618 dw.println("cookie=%" PRIu64 " tag=0x%x uid=%u", key, value.tag, value.uid);
619 return base::Result<void>();
620 };
621 base::Result<void> res = mCookieTagMap.iterateWithValue(printCookieTagInfo);
622 if (!res.ok()) {
623 dw.println("mCookieTagMap print end with error: %s", res.error().message().c_str());
624 }
625
Wayne Maa9716ff2022-01-12 10:37:04 +0800626 // Print UidCounterSetMap content.
Wayne Ma4d692332022-01-19 16:04:04 +0800627 dumpBpfMap("mUidCounterSetMap", dw, "");
628 const auto printUidInfo = [&dw](const uint32_t& key, const uint8_t& value,
629 const BpfMap<uint32_t, uint8_t>&) {
630 dw.println("%u %u", key, value);
631 return base::Result<void>();
632 };
633 res = mUidCounterSetMap.iterateWithValue(printUidInfo);
634 if (!res.ok()) {
635 dw.println("mUidCounterSetMap print end with error: %s", res.error().message().c_str());
636 }
637
Wayne Maa9716ff2022-01-12 10:37:04 +0800638 // Print AppUidStatsMap content.
Wayne Ma4d692332022-01-19 16:04:04 +0800639 std::string appUidStatsHeader = StringPrintf("uid rxBytes rxPackets txBytes txPackets");
640 dumpBpfMap("mAppUidStatsMap:", dw, appUidStatsHeader);
641 auto printAppUidStatsInfo = [&dw](const uint32_t& key, const StatsValue& value,
642 const BpfMap<uint32_t, StatsValue>&) {
643 dw.println("%u %" PRIu64 " %" PRIu64 " %" PRIu64 " %" PRIu64, key, value.rxBytes,
644 value.rxPackets, value.txBytes, value.txPackets);
645 return base::Result<void>();
646 };
647 res = mAppUidStatsMap.iterateWithValue(printAppUidStatsInfo);
648 if (!res.ok()) {
649 dw.println("mAppUidStatsMap print end with error: %s", res.error().message().c_str());
650 }
651
Wayne Maa9716ff2022-01-12 10:37:04 +0800652 // Print uidStatsMap content.
Wayne Ma4d692332022-01-19 16:04:04 +0800653 std::string statsHeader = StringPrintf("ifaceIndex ifaceName tag_hex uid_int cnt_set rxBytes"
654 " rxPackets txBytes txPackets");
655 dumpBpfMap("mStatsMapA", dw, statsHeader);
656 const auto printStatsInfo = [&dw, this](const StatsKey& key, const StatsValue& value,
657 const BpfMap<StatsKey, StatsValue>&) {
658 uint32_t ifIndex = key.ifaceIndex;
659 auto ifname = mIfaceIndexNameMap.readValue(ifIndex);
660 if (!ifname.ok()) {
661 ifname = IfaceValue{"unknown"};
662 }
663 dw.println("%u %s 0x%x %u %u %" PRIu64 " %" PRIu64 " %" PRIu64 " %" PRIu64, ifIndex,
664 ifname.value().name, key.tag, key.uid, key.counterSet, value.rxBytes,
665 value.rxPackets, value.txBytes, value.txPackets);
666 return base::Result<void>();
667 };
668 res = mStatsMapA.iterateWithValue(printStatsInfo);
669 if (!res.ok()) {
670 dw.println("mStatsMapA print end with error: %s", res.error().message().c_str());
671 }
672
673 // Print TagStatsMap content.
674 dumpBpfMap("mStatsMapB", dw, statsHeader);
675 res = mStatsMapB.iterateWithValue(printStatsInfo);
676 if (!res.ok()) {
677 dw.println("mStatsMapB print end with error: %s", res.error().message().c_str());
678 }
679
680 // Print ifaceIndexToNameMap content.
681 dumpBpfMap("mIfaceIndexNameMap", dw, "");
682 const auto printIfaceNameInfo = [&dw](const uint32_t& key, const IfaceValue& value,
683 const BpfMap<uint32_t, IfaceValue>&) {
684 const char* ifname = value.name;
685 dw.println("ifaceIndex=%u ifaceName=%s", key, ifname);
686 return base::Result<void>();
687 };
688 res = mIfaceIndexNameMap.iterateWithValue(printIfaceNameInfo);
689 if (!res.ok()) {
690 dw.println("mIfaceIndexNameMap print end with error: %s", res.error().message().c_str());
691 }
692
693 // Print ifaceStatsMap content
694 std::string ifaceStatsHeader = StringPrintf("ifaceIndex ifaceName rxBytes rxPackets txBytes"
695 " txPackets");
696 dumpBpfMap("mIfaceStatsMap:", dw, ifaceStatsHeader);
697 const auto printIfaceStatsInfo = [&dw, this](const uint32_t& key, const StatsValue& value,
698 const BpfMap<uint32_t, StatsValue>&) {
699 auto ifname = mIfaceIndexNameMap.readValue(key);
700 if (!ifname.ok()) {
701 ifname = IfaceValue{"unknown"};
702 }
703 dw.println("%u %s %" PRIu64 " %" PRIu64 " %" PRIu64 " %" PRIu64, key, ifname.value().name,
704 value.rxBytes, value.rxPackets, value.txBytes, value.txPackets);
705 return base::Result<void>();
706 };
707 res = mIfaceStatsMap.iterateWithValue(printIfaceStatsInfo);
708 if (!res.ok()) {
709 dw.println("mIfaceStatsMap print end with error: %s", res.error().message().c_str());
710 }
711
712 dw.blankline();
713
714 uint32_t key = UID_RULES_CONFIGURATION_KEY;
715 auto configuration = mConfigurationMap.readValue(key);
716 if (configuration.ok()) {
717 dw.println("current ownerMatch configuration: %d%s", configuration.value(),
718 uidMatchTypeToString(configuration.value()).c_str());
719 } else {
720 dw.println("mConfigurationMap read ownerMatch configure failed with error: %s",
721 configuration.error().message().c_str());
722 }
723
724 key = CURRENT_STATS_MAP_CONFIGURATION_KEY;
725 configuration = mConfigurationMap.readValue(key);
726 if (configuration.ok()) {
727 const char* statsMapDescription = "???";
728 switch (configuration.value()) {
729 case SELECT_MAP_A:
730 statsMapDescription = "SELECT_MAP_A";
731 break;
732 case SELECT_MAP_B:
733 statsMapDescription = "SELECT_MAP_B";
734 break;
735 // No default clause, so if we ever add a third map, this code will fail to build.
736 }
737 dw.println("current statsMap configuration: %d %s", configuration.value(),
738 statsMapDescription);
739 } else {
740 dw.println("mConfigurationMap read stats map configure failed with error: %s",
741 configuration.error().message().c_str());
742 }
743 dumpBpfMap("mUidOwnerMap", dw, "");
744 const auto printUidMatchInfo = [&dw, this](const uint32_t& key, const UidOwnerValue& value,
745 const BpfMap<uint32_t, UidOwnerValue>&) {
746 if (value.rule & IIF_MATCH) {
747 auto ifname = mIfaceIndexNameMap.readValue(value.iif);
748 if (ifname.ok()) {
749 dw.println("%u %s %s", key, uidMatchTypeToString(value.rule).c_str(),
750 ifname.value().name);
751 } else {
752 dw.println("%u %s %u", key, uidMatchTypeToString(value.rule).c_str(), value.iif);
753 }
754 } else {
755 dw.println("%u %s", key, uidMatchTypeToString(value.rule).c_str());
756 }
757 return base::Result<void>();
758 };
759 res = mUidOwnerMap.iterateWithValue(printUidMatchInfo);
760 if (!res.ok()) {
761 dw.println("mUidOwnerMap print end with error: %s", res.error().message().c_str());
762 }
763 dumpBpfMap("mUidPermissionMap", dw, "");
764 const auto printUidPermissionInfo = [&dw](const uint32_t& key, const int& value,
765 const BpfMap<uint32_t, uint8_t>&) {
766 dw.println("%u %s", key, UidPermissionTypeToString(value).c_str());
767 return base::Result<void>();
768 };
769 res = mUidPermissionMap.iterateWithValue(printUidPermissionInfo);
770 if (!res.ok()) {
771 dw.println("mUidPermissionMap print end with error: %s", res.error().message().c_str());
772 }
773
774 dumpBpfMap("mPrivilegedUser", dw, "");
775 for (uid_t uid : mPrivilegedUser) {
776 dw.println("%u ALLOW_UPDATE_DEVICE_STATS", (uint32_t)uid);
777 }
778}
779
780} // namespace net
781} // namespace android