blob: adc1925fc9ad3a33ec0d19fec1b639ca30f03bf7 [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 Utsumid9801492022-06-01 13:57:27 +0000343 case OEM_DENY_1:
344 return DENYLIST;
345 case OEM_DENY_2:
346 return DENYLIST;
Motomu Utsumi1d9054b2022-06-06 07:44:05 +0000347 case OEM_DENY_3:
348 return DENYLIST;
Wayne Ma4d692332022-01-19 16:04:04 +0800349 case NONE:
350 default:
351 return DENYLIST;
352 }
353}
354
355int TrafficController::changeUidOwnerRule(ChildChain chain, uid_t uid, FirewallRule rule,
356 FirewallType type) {
357 Status res;
358 switch (chain) {
359 case DOZABLE:
360 res = updateOwnerMapEntry(DOZABLE_MATCH, uid, rule, type);
361 break;
362 case STANDBY:
363 res = updateOwnerMapEntry(STANDBY_MATCH, uid, rule, type);
364 break;
365 case POWERSAVE:
366 res = updateOwnerMapEntry(POWERSAVE_MATCH, uid, rule, type);
367 break;
368 case RESTRICTED:
369 res = updateOwnerMapEntry(RESTRICTED_MATCH, uid, rule, type);
370 break;
Robert Horvathd945bf02022-01-27 19:55:16 +0100371 case LOW_POWER_STANDBY:
372 res = updateOwnerMapEntry(LOW_POWER_STANDBY_MATCH, uid, rule, type);
373 break;
Motomu Utsumid9801492022-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;
Motomu Utsumi1d9054b2022-06-06 07:44:05 +0000380 case OEM_DENY_3:
381 res = updateOwnerMapEntry(OEM_DENY_3_MATCH, uid, rule, type);
382 break;
Wayne Ma4d692332022-01-19 16:04:04 +0800383 case NONE:
384 default:
385 ALOGW("Unknown child chain: %d", chain);
386 return -EINVAL;
387 }
388 if (!isOk(res)) {
389 ALOGE("change uid(%u) rule of %d failed: %s, rule: %d, type: %d", uid, chain,
390 res.msg().c_str(), rule, type);
391 return -res.code();
392 }
393 return 0;
394}
395
396Status TrafficController::replaceRulesInMap(const UidOwnerMatchType match,
397 const std::vector<int32_t>& uids) {
398 std::lock_guard guard(mMutex);
399 std::set<int32_t> uidSet(uids.begin(), uids.end());
400 std::vector<uint32_t> uidsToDelete;
401 auto getUidsToDelete = [&uidsToDelete, &uidSet](const uint32_t& key,
402 const BpfMap<uint32_t, UidOwnerValue>&) {
403 if (uidSet.find((int32_t) key) == uidSet.end()) {
404 uidsToDelete.push_back(key);
405 }
406 return base::Result<void>();
407 };
408 RETURN_IF_NOT_OK(mUidOwnerMap.iterate(getUidsToDelete));
409
410 for(auto uid : uidsToDelete) {
411 RETURN_IF_NOT_OK(removeRule(uid, match));
412 }
413
414 for (auto uid : uids) {
415 RETURN_IF_NOT_OK(addRule(uid, match));
416 }
417 return netdutils::status::ok;
418}
419
420Status TrafficController::addUidInterfaceRules(const int iif,
421 const std::vector<int32_t>& uidsToAdd) {
Wayne Ma4d692332022-01-19 16:04:04 +0800422 std::lock_guard guard(mMutex);
423
424 for (auto uid : uidsToAdd) {
425 netdutils::Status result = addRule(uid, IIF_MATCH, iif);
426 if (!isOk(result)) {
427 ALOGW("addRule failed(%d): uid=%d iif=%d", result.code(), uid, iif);
428 }
429 }
430 return netdutils::status::ok;
431}
432
433Status TrafficController::removeUidInterfaceRules(const std::vector<int32_t>& uidsToDelete) {
434 std::lock_guard guard(mMutex);
435
436 for (auto uid : uidsToDelete) {
437 netdutils::Status result = removeRule(uid, IIF_MATCH);
438 if (!isOk(result)) {
439 ALOGW("removeRule failed(%d): uid=%d", result.code(), uid);
440 }
441 }
442 return netdutils::status::ok;
443}
444
Motomu Utsumi8b42e6d2022-05-19 06:23:40 +0000445Status TrafficController::updateUidLockdownRule(const uid_t uid, const bool add) {
446 std::lock_guard guard(mMutex);
447
448 netdutils::Status result = add ? addRule(uid, LOCKDOWN_VPN_MATCH)
449 : removeRule(uid, LOCKDOWN_VPN_MATCH);
450 if (!isOk(result)) {
451 ALOGW("%s Lockdown rule failed(%d): uid=%d",
452 (add ? "add": "remove"), result.code(), uid);
453 }
454 return result;
455}
456
Wayne Ma4d692332022-01-19 16:04:04 +0800457int TrafficController::replaceUidOwnerMap(const std::string& name, bool isAllowlist __unused,
458 const std::vector<int32_t>& uids) {
459 // FirewallRule rule = isAllowlist ? ALLOW : DENY;
460 // FirewallType type = isAllowlist ? ALLOWLIST : DENYLIST;
461 Status res;
462 if (!name.compare(LOCAL_DOZABLE)) {
463 res = replaceRulesInMap(DOZABLE_MATCH, uids);
464 } else if (!name.compare(LOCAL_STANDBY)) {
465 res = replaceRulesInMap(STANDBY_MATCH, uids);
466 } else if (!name.compare(LOCAL_POWERSAVE)) {
467 res = replaceRulesInMap(POWERSAVE_MATCH, uids);
468 } else if (!name.compare(LOCAL_RESTRICTED)) {
469 res = replaceRulesInMap(RESTRICTED_MATCH, uids);
Robert Horvathd945bf02022-01-27 19:55:16 +0100470 } else if (!name.compare(LOCAL_LOW_POWER_STANDBY)) {
471 res = replaceRulesInMap(LOW_POWER_STANDBY_MATCH, uids);
Motomu Utsumid9801492022-06-01 13:57:27 +0000472 } else if (!name.compare(LOCAL_OEM_DENY_1)) {
473 res = replaceRulesInMap(OEM_DENY_1_MATCH, uids);
474 } else if (!name.compare(LOCAL_OEM_DENY_2)) {
475 res = replaceRulesInMap(OEM_DENY_2_MATCH, uids);
Motomu Utsumi1d9054b2022-06-06 07:44:05 +0000476 } else if (!name.compare(LOCAL_OEM_DENY_3)) {
477 res = replaceRulesInMap(OEM_DENY_3_MATCH, uids);
Wayne Ma4d692332022-01-19 16:04:04 +0800478 } else {
479 ALOGE("unknown chain name: %s", name.c_str());
480 return -EINVAL;
481 }
482 if (!isOk(res)) {
483 ALOGE("Failed to clean up chain: %s: %s", name.c_str(), res.msg().c_str());
484 return -res.code();
485 }
486 return 0;
487}
488
489int TrafficController::toggleUidOwnerMap(ChildChain chain, bool enable) {
490 std::lock_guard guard(mMutex);
491 uint32_t key = UID_RULES_CONFIGURATION_KEY;
Lorenzo Colitti60cbed32022-03-03 17:49:01 +0900492 auto oldConfigure = mConfigurationMap.readValue(key);
493 if (!oldConfigure.ok()) {
Wayne Ma4d692332022-01-19 16:04:04 +0800494 ALOGE("Cannot read the old configuration from map: %s",
Lorenzo Colitti60cbed32022-03-03 17:49:01 +0900495 oldConfigure.error().message().c_str());
496 return -oldConfigure.error().code();
Wayne Ma4d692332022-01-19 16:04:04 +0800497 }
Lorenzo Colitti60cbed32022-03-03 17:49:01 +0900498 uint32_t match;
Wayne Ma4d692332022-01-19 16:04:04 +0800499 switch (chain) {
500 case DOZABLE:
501 match = DOZABLE_MATCH;
502 break;
503 case STANDBY:
504 match = STANDBY_MATCH;
505 break;
506 case POWERSAVE:
507 match = POWERSAVE_MATCH;
508 break;
509 case RESTRICTED:
510 match = RESTRICTED_MATCH;
511 break;
Robert Horvathd945bf02022-01-27 19:55:16 +0100512 case LOW_POWER_STANDBY:
513 match = LOW_POWER_STANDBY_MATCH;
514 break;
Motomu Utsumid9801492022-06-01 13:57:27 +0000515 case OEM_DENY_1:
516 match = OEM_DENY_1_MATCH;
517 break;
518 case OEM_DENY_2:
519 match = OEM_DENY_2_MATCH;
520 break;
Motomu Utsumi1d9054b2022-06-06 07:44:05 +0000521 case OEM_DENY_3:
522 match = OEM_DENY_3_MATCH;
523 break;
Wayne Ma4d692332022-01-19 16:04:04 +0800524 default:
525 return -EINVAL;
526 }
Maciej Żenczykowski93406ac2022-05-31 15:30:07 -0700527 BpfConfig newConfiguration =
528 enable ? (oldConfigure.value() | match) : (oldConfigure.value() & ~match);
529 Status res = mConfigurationMap.writeValue(key, newConfiguration, BPF_EXIST);
Wayne Ma4d692332022-01-19 16:04:04 +0800530 if (!isOk(res)) {
531 ALOGE("Failed to toggleUidOwnerMap(%d): %s", chain, res.msg().c_str());
532 }
533 return -res.code();
534}
535
536Status TrafficController::swapActiveStatsMap() {
537 std::lock_guard guard(mMutex);
538
539 uint32_t key = CURRENT_STATS_MAP_CONFIGURATION_KEY;
Lorenzo Colitti60cbed32022-03-03 17:49:01 +0900540 auto oldConfigure = mConfigurationMap.readValue(key);
541 if (!oldConfigure.ok()) {
Wayne Ma4d692332022-01-19 16:04:04 +0800542 ALOGE("Cannot read the old configuration from map: %s",
Lorenzo Colitti60cbed32022-03-03 17:49:01 +0900543 oldConfigure.error().message().c_str());
544 return Status(oldConfigure.error().code(), oldConfigure.error().message());
Wayne Ma4d692332022-01-19 16:04:04 +0800545 }
546
547 // Write to the configuration map to inform the kernel eBPF program to switch
548 // from using one map to the other. Use flag BPF_EXIST here since the map should
549 // be already populated in initMaps.
Lorenzo Colitti60cbed32022-03-03 17:49:01 +0900550 uint32_t newConfigure = (oldConfigure.value() == SELECT_MAP_A) ? SELECT_MAP_B : SELECT_MAP_A;
Wayne Ma4d692332022-01-19 16:04:04 +0800551 auto res = mConfigurationMap.writeValue(CURRENT_STATS_MAP_CONFIGURATION_KEY, newConfigure,
552 BPF_EXIST);
553 if (!res.ok()) {
554 ALOGE("Failed to toggle the stats map: %s", strerror(res.error().code()));
555 return res;
556 }
557 // After changing the config, we need to make sure all the current running
558 // eBPF programs are finished and all the CPUs are aware of this config change
559 // before we modify the old map. So we do a special hack here to wait for
560 // the kernel to do a synchronize_rcu(). Once the kernel called
561 // synchronize_rcu(), the config we just updated will be available to all cores
562 // and the next eBPF programs triggered inside the kernel will use the new
563 // map configuration. So once this function returns we can safely modify the
564 // old stats map without concerning about race between the kernel and
565 // userspace.
566 int ret = synchronizeKernelRCU();
567 if (ret) {
568 ALOGE("map swap synchronize_rcu() ended with failure: %s", strerror(-ret));
569 return statusFromErrno(-ret, "map swap synchronize_rcu() failed");
570 }
571 return netdutils::status::ok;
572}
573
574void TrafficController::setPermissionForUids(int permission, const std::vector<uid_t>& uids) {
575 std::lock_guard guard(mMutex);
576 if (permission == INetd::PERMISSION_UNINSTALLED) {
577 for (uid_t uid : uids) {
578 // Clean up all permission information for the related uid if all the
579 // packages related to it are uninstalled.
580 mPrivilegedUser.erase(uid);
581 Status ret = mUidPermissionMap.deleteValue(uid);
582 if (!isOk(ret) && ret.code() != ENOENT) {
583 ALOGE("Failed to clean up the permission for %u: %s", uid, strerror(ret.code()));
584 }
585 }
586 return;
587 }
588
589 bool privileged = (permission & INetd::PERMISSION_UPDATE_DEVICE_STATS);
590
591 for (uid_t uid : uids) {
592 if (privileged) {
593 mPrivilegedUser.insert(uid);
594 } else {
595 mPrivilegedUser.erase(uid);
596 }
597
598 // The map stores all the permissions that the UID has, except if the only permission
599 // the UID has is the INTERNET permission, then the UID should not appear in the map.
600 if (permission != INetd::PERMISSION_INTERNET) {
601 Status ret = mUidPermissionMap.writeValue(uid, permission, BPF_ANY);
602 if (!isOk(ret)) {
603 ALOGE("Failed to set permission: %s of uid(%u) to permission map: %s",
604 UidPermissionTypeToString(permission).c_str(), uid, strerror(ret.code()));
605 }
606 } else {
607 Status ret = mUidPermissionMap.deleteValue(uid);
608 if (!isOk(ret) && ret.code() != ENOENT) {
609 ALOGE("Failed to remove uid %u from permission map: %s", uid, strerror(ret.code()));
610 }
611 }
612 }
613}
614
615std::string getProgramStatus(const char *path) {
616 int ret = access(path, R_OK);
617 if (ret == 0) {
618 return StringPrintf("OK");
619 }
620 if (ret != 0 && errno == ENOENT) {
621 return StringPrintf("program is missing at: %s", path);
622 }
623 return StringPrintf("check Program %s error: %s", path, strerror(errno));
624}
625
626std::string getMapStatus(const base::unique_fd& map_fd, const char* path) {
627 if (map_fd.get() < 0) {
628 return StringPrintf("map fd lost");
629 }
630 if (access(path, F_OK) != 0) {
631 return StringPrintf("map not pinned to location: %s", path);
632 }
633 return StringPrintf("OK");
634}
635
636// NOLINTNEXTLINE(google-runtime-references): grandfathered pass by non-const reference
637void dumpBpfMap(const std::string& mapName, DumpWriter& dw, const std::string& header) {
638 dw.blankline();
639 dw.println("%s:", mapName.c_str());
640 if (!header.empty()) {
641 dw.println(header);
642 }
643}
644
Ken Chene6d511f2022-01-25 11:10:42 +0800645void TrafficController::dump(int fd, bool verbose) {
Wayne Ma4d692332022-01-19 16:04:04 +0800646 std::lock_guard guard(mMutex);
Ken Chene6d511f2022-01-25 11:10:42 +0800647 DumpWriter dw(fd);
648
Wayne Ma4d692332022-01-19 16:04:04 +0800649 ScopedIndent indentTop(dw);
650 dw.println("TrafficController");
651
652 ScopedIndent indentPreBpfModule(dw);
653
654 dw.blankline();
655 dw.println("mCookieTagMap status: %s",
656 getMapStatus(mCookieTagMap.getMap(), COOKIE_TAG_MAP_PATH).c_str());
657 dw.println("mUidCounterSetMap status: %s",
658 getMapStatus(mUidCounterSetMap.getMap(), UID_COUNTERSET_MAP_PATH).c_str());
659 dw.println("mAppUidStatsMap status: %s",
660 getMapStatus(mAppUidStatsMap.getMap(), APP_UID_STATS_MAP_PATH).c_str());
661 dw.println("mStatsMapA status: %s",
662 getMapStatus(mStatsMapA.getMap(), STATS_MAP_A_PATH).c_str());
663 dw.println("mStatsMapB status: %s",
664 getMapStatus(mStatsMapB.getMap(), STATS_MAP_B_PATH).c_str());
665 dw.println("mIfaceIndexNameMap status: %s",
666 getMapStatus(mIfaceIndexNameMap.getMap(), IFACE_INDEX_NAME_MAP_PATH).c_str());
667 dw.println("mIfaceStatsMap status: %s",
668 getMapStatus(mIfaceStatsMap.getMap(), IFACE_STATS_MAP_PATH).c_str());
669 dw.println("mConfigurationMap status: %s",
670 getMapStatus(mConfigurationMap.getMap(), CONFIGURATION_MAP_PATH).c_str());
671 dw.println("mUidOwnerMap status: %s",
672 getMapStatus(mUidOwnerMap.getMap(), UID_OWNER_MAP_PATH).c_str());
673
674 dw.blankline();
675 dw.println("Cgroup ingress program status: %s",
676 getProgramStatus(BPF_INGRESS_PROG_PATH).c_str());
677 dw.println("Cgroup egress program status: %s", getProgramStatus(BPF_EGRESS_PROG_PATH).c_str());
678 dw.println("xt_bpf ingress program status: %s",
679 getProgramStatus(XT_BPF_INGRESS_PROG_PATH).c_str());
680 dw.println("xt_bpf egress program status: %s",
681 getProgramStatus(XT_BPF_EGRESS_PROG_PATH).c_str());
682 dw.println("xt_bpf bandwidth allowlist program status: %s",
683 getProgramStatus(XT_BPF_ALLOWLIST_PROG_PATH).c_str());
684 dw.println("xt_bpf bandwidth denylist program status: %s",
685 getProgramStatus(XT_BPF_DENYLIST_PROG_PATH).c_str());
686
687 if (!verbose) {
688 return;
689 }
690
691 dw.blankline();
692 dw.println("BPF map content:");
693
694 ScopedIndent indentForMapContent(dw);
695
696 // Print CookieTagMap content.
697 dumpBpfMap("mCookieTagMap", dw, "");
698 const auto printCookieTagInfo = [&dw](const uint64_t& key, const UidTagValue& value,
699 const BpfMap<uint64_t, UidTagValue>&) {
700 dw.println("cookie=%" PRIu64 " tag=0x%x uid=%u", key, value.tag, value.uid);
701 return base::Result<void>();
702 };
703 base::Result<void> res = mCookieTagMap.iterateWithValue(printCookieTagInfo);
704 if (!res.ok()) {
705 dw.println("mCookieTagMap print end with error: %s", res.error().message().c_str());
706 }
707
Wayne Maa9716ff2022-01-12 10:37:04 +0800708 // Print UidCounterSetMap content.
Wayne Ma4d692332022-01-19 16:04:04 +0800709 dumpBpfMap("mUidCounterSetMap", dw, "");
710 const auto printUidInfo = [&dw](const uint32_t& key, const uint8_t& value,
711 const BpfMap<uint32_t, uint8_t>&) {
712 dw.println("%u %u", key, value);
713 return base::Result<void>();
714 };
715 res = mUidCounterSetMap.iterateWithValue(printUidInfo);
716 if (!res.ok()) {
717 dw.println("mUidCounterSetMap print end with error: %s", res.error().message().c_str());
718 }
719
Wayne Maa9716ff2022-01-12 10:37:04 +0800720 // Print AppUidStatsMap content.
Wayne Ma4d692332022-01-19 16:04:04 +0800721 std::string appUidStatsHeader = StringPrintf("uid rxBytes rxPackets txBytes txPackets");
722 dumpBpfMap("mAppUidStatsMap:", dw, appUidStatsHeader);
723 auto printAppUidStatsInfo = [&dw](const uint32_t& key, const StatsValue& value,
724 const BpfMap<uint32_t, StatsValue>&) {
725 dw.println("%u %" PRIu64 " %" PRIu64 " %" PRIu64 " %" PRIu64, key, value.rxBytes,
726 value.rxPackets, value.txBytes, value.txPackets);
727 return base::Result<void>();
728 };
729 res = mAppUidStatsMap.iterateWithValue(printAppUidStatsInfo);
730 if (!res.ok()) {
731 dw.println("mAppUidStatsMap print end with error: %s", res.error().message().c_str());
732 }
733
Wayne Maa9716ff2022-01-12 10:37:04 +0800734 // Print uidStatsMap content.
Wayne Ma4d692332022-01-19 16:04:04 +0800735 std::string statsHeader = StringPrintf("ifaceIndex ifaceName tag_hex uid_int cnt_set rxBytes"
736 " rxPackets txBytes txPackets");
737 dumpBpfMap("mStatsMapA", dw, statsHeader);
738 const auto printStatsInfo = [&dw, this](const StatsKey& key, const StatsValue& value,
739 const BpfMap<StatsKey, StatsValue>&) {
740 uint32_t ifIndex = key.ifaceIndex;
741 auto ifname = mIfaceIndexNameMap.readValue(ifIndex);
742 if (!ifname.ok()) {
743 ifname = IfaceValue{"unknown"};
744 }
745 dw.println("%u %s 0x%x %u %u %" PRIu64 " %" PRIu64 " %" PRIu64 " %" PRIu64, ifIndex,
746 ifname.value().name, key.tag, key.uid, key.counterSet, value.rxBytes,
747 value.rxPackets, value.txBytes, value.txPackets);
748 return base::Result<void>();
749 };
750 res = mStatsMapA.iterateWithValue(printStatsInfo);
751 if (!res.ok()) {
752 dw.println("mStatsMapA print end with error: %s", res.error().message().c_str());
753 }
754
755 // Print TagStatsMap content.
756 dumpBpfMap("mStatsMapB", dw, statsHeader);
757 res = mStatsMapB.iterateWithValue(printStatsInfo);
758 if (!res.ok()) {
759 dw.println("mStatsMapB print end with error: %s", res.error().message().c_str());
760 }
761
762 // Print ifaceIndexToNameMap content.
763 dumpBpfMap("mIfaceIndexNameMap", dw, "");
764 const auto printIfaceNameInfo = [&dw](const uint32_t& key, const IfaceValue& value,
765 const BpfMap<uint32_t, IfaceValue>&) {
766 const char* ifname = value.name;
767 dw.println("ifaceIndex=%u ifaceName=%s", key, ifname);
768 return base::Result<void>();
769 };
770 res = mIfaceIndexNameMap.iterateWithValue(printIfaceNameInfo);
771 if (!res.ok()) {
772 dw.println("mIfaceIndexNameMap print end with error: %s", res.error().message().c_str());
773 }
774
775 // Print ifaceStatsMap content
776 std::string ifaceStatsHeader = StringPrintf("ifaceIndex ifaceName rxBytes rxPackets txBytes"
777 " txPackets");
778 dumpBpfMap("mIfaceStatsMap:", dw, ifaceStatsHeader);
779 const auto printIfaceStatsInfo = [&dw, this](const uint32_t& key, const StatsValue& value,
780 const BpfMap<uint32_t, StatsValue>&) {
781 auto ifname = mIfaceIndexNameMap.readValue(key);
782 if (!ifname.ok()) {
783 ifname = IfaceValue{"unknown"};
784 }
785 dw.println("%u %s %" PRIu64 " %" PRIu64 " %" PRIu64 " %" PRIu64, key, ifname.value().name,
786 value.rxBytes, value.rxPackets, value.txBytes, value.txPackets);
787 return base::Result<void>();
788 };
789 res = mIfaceStatsMap.iterateWithValue(printIfaceStatsInfo);
790 if (!res.ok()) {
791 dw.println("mIfaceStatsMap print end with error: %s", res.error().message().c_str());
792 }
793
794 dw.blankline();
795
796 uint32_t key = UID_RULES_CONFIGURATION_KEY;
797 auto configuration = mConfigurationMap.readValue(key);
798 if (configuration.ok()) {
799 dw.println("current ownerMatch configuration: %d%s", configuration.value(),
800 uidMatchTypeToString(configuration.value()).c_str());
801 } else {
802 dw.println("mConfigurationMap read ownerMatch configure failed with error: %s",
803 configuration.error().message().c_str());
804 }
805
806 key = CURRENT_STATS_MAP_CONFIGURATION_KEY;
807 configuration = mConfigurationMap.readValue(key);
808 if (configuration.ok()) {
809 const char* statsMapDescription = "???";
810 switch (configuration.value()) {
811 case SELECT_MAP_A:
812 statsMapDescription = "SELECT_MAP_A";
813 break;
814 case SELECT_MAP_B:
815 statsMapDescription = "SELECT_MAP_B";
816 break;
817 // No default clause, so if we ever add a third map, this code will fail to build.
818 }
819 dw.println("current statsMap configuration: %d %s", configuration.value(),
820 statsMapDescription);
821 } else {
822 dw.println("mConfigurationMap read stats map configure failed with error: %s",
823 configuration.error().message().c_str());
824 }
825 dumpBpfMap("mUidOwnerMap", dw, "");
826 const auto printUidMatchInfo = [&dw, this](const uint32_t& key, const UidOwnerValue& value,
827 const BpfMap<uint32_t, UidOwnerValue>&) {
828 if (value.rule & IIF_MATCH) {
829 auto ifname = mIfaceIndexNameMap.readValue(value.iif);
830 if (ifname.ok()) {
831 dw.println("%u %s %s", key, uidMatchTypeToString(value.rule).c_str(),
832 ifname.value().name);
833 } else {
834 dw.println("%u %s %u", key, uidMatchTypeToString(value.rule).c_str(), value.iif);
835 }
836 } else {
837 dw.println("%u %s", key, uidMatchTypeToString(value.rule).c_str());
838 }
839 return base::Result<void>();
840 };
841 res = mUidOwnerMap.iterateWithValue(printUidMatchInfo);
842 if (!res.ok()) {
843 dw.println("mUidOwnerMap print end with error: %s", res.error().message().c_str());
844 }
845 dumpBpfMap("mUidPermissionMap", dw, "");
846 const auto printUidPermissionInfo = [&dw](const uint32_t& key, const int& value,
847 const BpfMap<uint32_t, uint8_t>&) {
848 dw.println("%u %s", key, UidPermissionTypeToString(value).c_str());
849 return base::Result<void>();
850 };
851 res = mUidPermissionMap.iterateWithValue(printUidPermissionInfo);
852 if (!res.ok()) {
853 dw.println("mUidPermissionMap print end with error: %s", res.error().message().c_str());
854 }
855
856 dumpBpfMap("mPrivilegedUser", dw, "");
857 for (uid_t uid : mPrivilegedUser) {
858 dw.println("%u ALLOW_UPDATE_DEVICE_STATS", (uint32_t)uid);
859 }
860}
861
862} // namespace net
863} // namespace android