| Ken Chen | 1647f60 | 2021-10-05 21:55:22 +0800 | [diff] [blame] | 1 | /** | 
|  | 2 | * Copyright (c) 2022, The Android Open Source Project | 
|  | 3 | * | 
|  | 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 "BpfHandler" | 
|  | 18 |  | 
|  | 19 | #include "BpfHandler.h" | 
|  | 20 |  | 
|  | 21 | #include <linux/bpf.h> | 
|  | 22 |  | 
|  | 23 | #include <android-base/unique_fd.h> | 
|  | 24 | #include <bpf/WaitForProgsLoaded.h> | 
|  | 25 | #include <log/log.h> | 
|  | 26 | #include <netdutils/UidConstants.h> | 
|  | 27 | #include <private/android_filesystem_config.h> | 
|  | 28 |  | 
|  | 29 | #include "BpfSyscallWrappers.h" | 
|  | 30 |  | 
|  | 31 | namespace android { | 
|  | 32 | namespace net { | 
|  | 33 |  | 
|  | 34 | using base::unique_fd; | 
| Ken Chen | 1647f60 | 2021-10-05 21:55:22 +0800 | [diff] [blame] | 35 | using bpf::getSocketCookie; | 
|  | 36 | using bpf::retrieveProgram; | 
|  | 37 | using netdutils::Status; | 
|  | 38 | using netdutils::statusFromErrno; | 
|  | 39 |  | 
|  | 40 | constexpr int PER_UID_STATS_ENTRIES_LIMIT = 500; | 
|  | 41 | // At most 90% of the stats map may be used by tagged traffic entries. This ensures | 
|  | 42 | // that 10% of the map is always available to count untagged traffic, one entry per UID. | 
|  | 43 | // Otherwise, apps would be able to avoid data usage accounting entirely by filling up the | 
|  | 44 | // map with tagged traffic entries. | 
|  | 45 | constexpr int TOTAL_UID_STATS_ENTRIES_LIMIT = STATS_MAP_SIZE * 0.9; | 
|  | 46 |  | 
|  | 47 | static_assert(STATS_MAP_SIZE - TOTAL_UID_STATS_ENTRIES_LIMIT > 100, | 
|  | 48 | "The limit for stats map is to high, stats data may be lost due to overflow"); | 
|  | 49 |  | 
|  | 50 | static Status attachProgramToCgroup(const char* programPath, const unique_fd& cgroupFd, | 
|  | 51 | bpf_attach_type type) { | 
|  | 52 | unique_fd cgroupProg(retrieveProgram(programPath)); | 
|  | 53 | if (cgroupProg == -1) { | 
|  | 54 | int ret = errno; | 
|  | 55 | ALOGE("Failed to get program from %s: %s", programPath, strerror(ret)); | 
|  | 56 | return statusFromErrno(ret, "cgroup program get failed"); | 
|  | 57 | } | 
|  | 58 | if (android::bpf::attachProgram(type, cgroupProg, cgroupFd)) { | 
|  | 59 | int ret = errno; | 
|  | 60 | ALOGE("Program from %s attach failed: %s", programPath, strerror(ret)); | 
|  | 61 | return statusFromErrno(ret, "program attach failed"); | 
|  | 62 | } | 
|  | 63 | return netdutils::status::ok; | 
|  | 64 | } | 
|  | 65 |  | 
| Maciej Żenczykowski | c576c0d | 2022-08-07 22:18:15 +0000 | [diff] [blame] | 66 | static Status checkProgramAccessible(const char* programPath) { | 
|  | 67 | unique_fd prog(retrieveProgram(programPath)); | 
|  | 68 | if (prog == -1) { | 
|  | 69 | int ret = errno; | 
|  | 70 | ALOGE("Failed to get program from %s: %s", programPath, strerror(ret)); | 
|  | 71 | return statusFromErrno(ret, "program retrieve failed"); | 
|  | 72 | } | 
|  | 73 | return netdutils::status::ok; | 
|  | 74 | } | 
|  | 75 |  | 
| Ken Chen | 1647f60 | 2021-10-05 21:55:22 +0800 | [diff] [blame] | 76 | static Status initPrograms(const char* cg2_path) { | 
|  | 77 | unique_fd cg_fd(open(cg2_path, O_DIRECTORY | O_RDONLY | O_CLOEXEC)); | 
|  | 78 | if (cg_fd == -1) { | 
|  | 79 | int ret = errno; | 
|  | 80 | ALOGE("Failed to open the cgroup directory: %s", strerror(ret)); | 
|  | 81 | return statusFromErrno(ret, "Open the cgroup directory failed"); | 
|  | 82 | } | 
| Maciej Żenczykowski | c576c0d | 2022-08-07 22:18:15 +0000 | [diff] [blame] | 83 | RETURN_IF_NOT_OK(checkProgramAccessible(XT_BPF_ALLOWLIST_PROG_PATH)); | 
|  | 84 | RETURN_IF_NOT_OK(checkProgramAccessible(XT_BPF_DENYLIST_PROG_PATH)); | 
|  | 85 | RETURN_IF_NOT_OK(checkProgramAccessible(XT_BPF_EGRESS_PROG_PATH)); | 
|  | 86 | RETURN_IF_NOT_OK(checkProgramAccessible(XT_BPF_INGRESS_PROG_PATH)); | 
| Ken Chen | 1647f60 | 2021-10-05 21:55:22 +0800 | [diff] [blame] | 87 | RETURN_IF_NOT_OK(attachProgramToCgroup(BPF_EGRESS_PROG_PATH, cg_fd, BPF_CGROUP_INET_EGRESS)); | 
|  | 88 | RETURN_IF_NOT_OK(attachProgramToCgroup(BPF_INGRESS_PROG_PATH, cg_fd, BPF_CGROUP_INET_INGRESS)); | 
| Lorenzo Colitti | 3505b58 | 2022-10-27 19:36:27 +0900 | [diff] [blame] | 89 |  | 
|  | 90 | // For the devices that support cgroup socket filter, the socket filter | 
|  | 91 | // should be loaded successfully by bpfloader. So we attach the filter to | 
|  | 92 | // cgroup if the program is pinned properly. | 
|  | 93 | // TODO: delete the if statement once all devices should support cgroup | 
|  | 94 | // socket filter (ie. the minimum kernel version required is 4.14). | 
| Maciej Żenczykowski | 0309362 | 2023-02-22 22:09:25 +0000 | [diff] [blame] | 95 | if (bpf::isAtLeastKernelVersion(4, 14, 0)) { | 
| Lorenzo Colitti | 3505b58 | 2022-10-27 19:36:27 +0900 | [diff] [blame] | 96 | RETURN_IF_NOT_OK( | 
|  | 97 | attachProgramToCgroup(CGROUP_SOCKET_PROG_PATH, cg_fd, BPF_CGROUP_INET_SOCK_CREATE)); | 
|  | 98 | } | 
| Ken Chen | 1647f60 | 2021-10-05 21:55:22 +0800 | [diff] [blame] | 99 | return netdutils::status::ok; | 
|  | 100 | } | 
|  | 101 |  | 
|  | 102 | BpfHandler::BpfHandler() | 
|  | 103 | : mPerUidStatsEntriesLimit(PER_UID_STATS_ENTRIES_LIMIT), | 
|  | 104 | mTotalUidStatsEntriesLimit(TOTAL_UID_STATS_ENTRIES_LIMIT) {} | 
|  | 105 |  | 
|  | 106 | BpfHandler::BpfHandler(uint32_t perUidLimit, uint32_t totalLimit) | 
|  | 107 | : mPerUidStatsEntriesLimit(perUidLimit), mTotalUidStatsEntriesLimit(totalLimit) {} | 
|  | 108 |  | 
|  | 109 | Status BpfHandler::init(const char* cg2_path) { | 
|  | 110 | // Make sure BPF programs are loaded before doing anything | 
|  | 111 | android::bpf::waitForProgsLoaded(); | 
|  | 112 | ALOGI("BPF programs are loaded"); | 
|  | 113 |  | 
|  | 114 | RETURN_IF_NOT_OK(initPrograms(cg2_path)); | 
|  | 115 | RETURN_IF_NOT_OK(initMaps()); | 
|  | 116 |  | 
|  | 117 | return netdutils::status::ok; | 
|  | 118 | } | 
|  | 119 |  | 
|  | 120 | Status BpfHandler::initMaps() { | 
| Ken Chen | 1647f60 | 2021-10-05 21:55:22 +0800 | [diff] [blame] | 121 | RETURN_IF_NOT_OK(mStatsMapA.init(STATS_MAP_A_PATH)); | 
|  | 122 | RETURN_IF_NOT_OK(mStatsMapB.init(STATS_MAP_B_PATH)); | 
|  | 123 | RETURN_IF_NOT_OK(mConfigurationMap.init(CONFIGURATION_MAP_PATH)); | 
| Ken Chen | 1647f60 | 2021-10-05 21:55:22 +0800 | [diff] [blame] | 124 | RETURN_IF_NOT_OK(mUidPermissionMap.init(UID_PERMISSION_MAP_PATH)); | 
| Maciej Żenczykowski | b5868a0 | 2022-08-31 04:21:01 +0000 | [diff] [blame] | 125 | // initialized last so mCookieTagMap.isValid() implies everything else is valid too | 
|  | 126 | RETURN_IF_NOT_OK(mCookieTagMap.init(COOKIE_TAG_MAP_PATH)); | 
| Ken Chen | 322ffcb | 2022-05-23 22:27:40 +0800 | [diff] [blame] | 127 | ALOGI("%s successfully", __func__); | 
| Ken Chen | 1647f60 | 2021-10-05 21:55:22 +0800 | [diff] [blame] | 128 |  | 
|  | 129 | return netdutils::status::ok; | 
|  | 130 | } | 
|  | 131 |  | 
|  | 132 | bool BpfHandler::hasUpdateDeviceStatsPermission(uid_t uid) { | 
|  | 133 | // This implementation is the same logic as method ActivityManager#checkComponentPermission. | 
|  | 134 | // It implies that the real uid can never be the same as PER_USER_RANGE. | 
|  | 135 | uint32_t appId = uid % PER_USER_RANGE; | 
|  | 136 | auto permission = mUidPermissionMap.readValue(appId); | 
|  | 137 | if (permission.ok() && (permission.value() & BPF_PERMISSION_UPDATE_DEVICE_STATS)) { | 
|  | 138 | return true; | 
|  | 139 | } | 
|  | 140 | return ((appId == AID_ROOT) || (appId == AID_SYSTEM) || (appId == AID_DNS)); | 
|  | 141 | } | 
|  | 142 |  | 
|  | 143 | int BpfHandler::tagSocket(int sockFd, uint32_t tag, uid_t chargeUid, uid_t realUid) { | 
| Maciej Żenczykowski | 4938d40 | 2022-08-14 14:36:20 +0000 | [diff] [blame] | 144 | if (!mCookieTagMap.isValid()) return -EPERM; | 
|  | 145 |  | 
|  | 146 | if (chargeUid != realUid && !hasUpdateDeviceStatsPermission(realUid)) return -EPERM; | 
| Ken Chen | 1647f60 | 2021-10-05 21:55:22 +0800 | [diff] [blame] | 147 |  | 
| Hungming Chen | 436547e | 2022-02-18 17:52:11 +0800 | [diff] [blame] | 148 | // Note that tagging the socket to AID_CLAT is only implemented in JNI ClatCoordinator. | 
|  | 149 | // The process is not allowed to tag socket to AID_CLAT via tagSocket() which would cause | 
|  | 150 | // process data usage accounting to be bypassed. Tagging AID_CLAT is used for avoiding counting | 
|  | 151 | // CLAT traffic data usage twice. See packages/modules/Connectivity/service/jni/ | 
|  | 152 | // com_android_server_connectivity_ClatCoordinator.cpp | 
| Maciej Żenczykowski | 4938d40 | 2022-08-14 14:36:20 +0000 | [diff] [blame] | 153 | if (chargeUid == AID_CLAT) return -EPERM; | 
| Hungming Chen | 436547e | 2022-02-18 17:52:11 +0800 | [diff] [blame] | 154 |  | 
| Hungming Chen | 478c0eb | 2022-03-04 21:16:59 +0800 | [diff] [blame] | 155 | // The socket destroy listener only monitors on the group {INET_TCP, INET_UDP, INET6_TCP, | 
|  | 156 | // INET6_UDP}. Tagging listener unsupported socket causes that the tag can't be removed from | 
|  | 157 | // tag map automatically. Eventually, the tag map may run out of space because of dead tag | 
| Hungming Chen | bcc0f5b | 2022-03-07 14:13:49 +0800 | [diff] [blame] | 158 | // entries. Note that although tagSocket() of net client has already denied the family which | 
|  | 159 | // is neither AF_INET nor AF_INET6, the family validation is still added here just in case. | 
|  | 160 | // See tagSocket in system/netd/client/NetdClient.cpp and | 
|  | 161 | // TrafficController::makeSkDestroyListener in | 
| Hungming Chen | 478c0eb | 2022-03-04 21:16:59 +0800 | [diff] [blame] | 162 | // packages/modules/Connectivity/service/native/TrafficController.cpp | 
|  | 163 | // TODO: remove this once the socket destroy listener can detect more types of socket destroy. | 
| Hungming Chen | bcc0f5b | 2022-03-07 14:13:49 +0800 | [diff] [blame] | 164 | int socketFamily; | 
|  | 165 | socklen_t familyLen = sizeof(socketFamily); | 
|  | 166 | if (getsockopt(sockFd, SOL_SOCKET, SO_DOMAIN, &socketFamily, &familyLen)) { | 
|  | 167 | ALOGE("Failed to getsockopt SO_DOMAIN: %s, fd: %d", strerror(errno), sockFd); | 
| Hungming Chen | 478c0eb | 2022-03-04 21:16:59 +0800 | [diff] [blame] | 168 | return -errno; | 
| Hungming Chen | bcc0f5b | 2022-03-07 14:13:49 +0800 | [diff] [blame] | 169 | } | 
|  | 170 | if (socketFamily != AF_INET && socketFamily != AF_INET6) { | 
|  | 171 | ALOGE("Unsupported family: %d", socketFamily); | 
|  | 172 | return -EAFNOSUPPORT; | 
|  | 173 | } | 
|  | 174 |  | 
|  | 175 | int socketProto; | 
|  | 176 | socklen_t protoLen = sizeof(socketProto); | 
|  | 177 | if (getsockopt(sockFd, SOL_SOCKET, SO_PROTOCOL, &socketProto, &protoLen)) { | 
|  | 178 | ALOGE("Failed to getsockopt SO_PROTOCOL: %s, fd: %d", strerror(errno), sockFd); | 
|  | 179 | return -errno; | 
|  | 180 | } | 
|  | 181 | if (socketProto != IPPROTO_UDP && socketProto != IPPROTO_TCP) { | 
|  | 182 | ALOGE("Unsupported protocol: %d", socketProto); | 
|  | 183 | return -EPROTONOSUPPORT; | 
| Hungming Chen | 478c0eb | 2022-03-04 21:16:59 +0800 | [diff] [blame] | 184 | } | 
|  | 185 |  | 
| Ken Chen | 1647f60 | 2021-10-05 21:55:22 +0800 | [diff] [blame] | 186 | uint64_t sock_cookie = getSocketCookie(sockFd); | 
| Maciej Żenczykowski | d3fe154 | 2023-02-23 03:56:45 +0000 | [diff] [blame] | 187 | if (!sock_cookie) return -errno; | 
| Maciej Żenczykowski | 4938d40 | 2022-08-14 14:36:20 +0000 | [diff] [blame] | 188 |  | 
| Ken Chen | 1647f60 | 2021-10-05 21:55:22 +0800 | [diff] [blame] | 189 | UidTagValue newKey = {.uid = (uint32_t)chargeUid, .tag = tag}; | 
|  | 190 |  | 
|  | 191 | uint32_t totalEntryCount = 0; | 
|  | 192 | uint32_t perUidEntryCount = 0; | 
|  | 193 | // Now we go through the stats map and count how many entries are associated | 
|  | 194 | // with chargeUid. If the uid entry hit the limit for each chargeUid, we block | 
| Maciej Żenczykowski | b5868a0 | 2022-08-31 04:21:01 +0000 | [diff] [blame] | 195 | // the request to prevent the map from overflow. Note though that it isn't really | 
|  | 196 | // safe here to iterate over the map since it might be modified by the system server, | 
|  | 197 | // which might toggle the live stats map and clean it. | 
| Ken Chen | 1647f60 | 2021-10-05 21:55:22 +0800 | [diff] [blame] | 198 | const auto countUidStatsEntries = [chargeUid, &totalEntryCount, &perUidEntryCount]( | 
|  | 199 | const StatsKey& key, | 
|  | 200 | const BpfMap<StatsKey, StatsValue>&) { | 
|  | 201 | if (key.uid == chargeUid) { | 
|  | 202 | perUidEntryCount++; | 
|  | 203 | } | 
|  | 204 | totalEntryCount++; | 
|  | 205 | return base::Result<void>(); | 
|  | 206 | }; | 
|  | 207 | auto configuration = mConfigurationMap.readValue(CURRENT_STATS_MAP_CONFIGURATION_KEY); | 
|  | 208 | if (!configuration.ok()) { | 
|  | 209 | ALOGE("Failed to get current configuration: %s, fd: %d", | 
|  | 210 | strerror(configuration.error().code()), mConfigurationMap.getMap().get()); | 
|  | 211 | return -configuration.error().code(); | 
|  | 212 | } | 
|  | 213 | if (configuration.value() != SELECT_MAP_A && configuration.value() != SELECT_MAP_B) { | 
|  | 214 | ALOGE("unknown configuration value: %d", configuration.value()); | 
|  | 215 | return -EINVAL; | 
|  | 216 | } | 
|  | 217 |  | 
|  | 218 | BpfMap<StatsKey, StatsValue>& currentMap = | 
|  | 219 | (configuration.value() == SELECT_MAP_A) ? mStatsMapA : mStatsMapB; | 
| Maciej Żenczykowski | 21ce721 | 2022-06-13 17:28:41 -0700 | [diff] [blame] | 220 | // HACK: mStatsMapB becomes RW BpfMap here, but countUidStatsEntries doesn't modify so it works | 
| Ken Chen | 1647f60 | 2021-10-05 21:55:22 +0800 | [diff] [blame] | 221 | base::Result<void> res = currentMap.iterate(countUidStatsEntries); | 
|  | 222 | if (!res.ok()) { | 
|  | 223 | ALOGE("Failed to count the stats entry in map %d: %s", currentMap.getMap().get(), | 
|  | 224 | strerror(res.error().code())); | 
|  | 225 | return -res.error().code(); | 
|  | 226 | } | 
|  | 227 |  | 
|  | 228 | if (totalEntryCount > mTotalUidStatsEntriesLimit || | 
|  | 229 | perUidEntryCount > mPerUidStatsEntriesLimit) { | 
|  | 230 | ALOGE("Too many stats entries in the map, total count: %u, chargeUid(%u) count: %u," | 
|  | 231 | " blocking tag request to prevent map overflow", | 
|  | 232 | totalEntryCount, chargeUid, perUidEntryCount); | 
|  | 233 | return -EMFILE; | 
|  | 234 | } | 
|  | 235 | // Update the tag information of a socket to the cookieUidMap. Use BPF_ANY | 
|  | 236 | // flag so it will insert a new entry to the map if that value doesn't exist | 
| Maciej Żenczykowski | b5868a0 | 2022-08-31 04:21:01 +0000 | [diff] [blame] | 237 | // yet and update the tag if there is already a tag stored. Since the eBPF | 
| Ken Chen | 1647f60 | 2021-10-05 21:55:22 +0800 | [diff] [blame] | 238 | // program in kernel only read this map, and is protected by rcu read lock. It | 
| Maciej Żenczykowski | b5868a0 | 2022-08-31 04:21:01 +0000 | [diff] [blame] | 239 | // should be fine to concurrently update the map while eBPF program is running. | 
| Ken Chen | 1647f60 | 2021-10-05 21:55:22 +0800 | [diff] [blame] | 240 | res = mCookieTagMap.writeValue(sock_cookie, newKey, BPF_ANY); | 
|  | 241 | if (!res.ok()) { | 
|  | 242 | ALOGE("Failed to tag the socket: %s, fd: %d", strerror(res.error().code()), | 
|  | 243 | mCookieTagMap.getMap().get()); | 
|  | 244 | return -res.error().code(); | 
|  | 245 | } | 
|  | 246 | return 0; | 
|  | 247 | } | 
|  | 248 |  | 
|  | 249 | int BpfHandler::untagSocket(int sockFd) { | 
| Maciej Żenczykowski | 4938d40 | 2022-08-14 14:36:20 +0000 | [diff] [blame] | 250 | uint64_t sock_cookie = getSocketCookie(sockFd); | 
| Maciej Żenczykowski | d3fe154 | 2023-02-23 03:56:45 +0000 | [diff] [blame] | 251 | if (!sock_cookie) return -errno; | 
| Maciej Żenczykowski | 4938d40 | 2022-08-14 14:36:20 +0000 | [diff] [blame] | 252 |  | 
|  | 253 | if (!mCookieTagMap.isValid()) return -EPERM; | 
| Ken Chen | 1647f60 | 2021-10-05 21:55:22 +0800 | [diff] [blame] | 254 | base::Result<void> res = mCookieTagMap.deleteValue(sock_cookie); | 
|  | 255 | if (!res.ok()) { | 
| Maciej Żenczykowski | e0f5846 | 2022-05-17 13:59:22 -0700 | [diff] [blame] | 256 | ALOGE("Failed to untag socket: %s", strerror(res.error().code())); | 
| Ken Chen | 1647f60 | 2021-10-05 21:55:22 +0800 | [diff] [blame] | 257 | return -res.error().code(); | 
|  | 258 | } | 
|  | 259 | return 0; | 
|  | 260 | } | 
|  | 261 |  | 
|  | 262 | }  // namespace net | 
|  | 263 | }  // namespace android |