blob: fc680d9712298215669dbed584b79673a715897b [file] [log] [blame]
Ken Chen1647f602021-10-05 21:55:22 +08001/**
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>
Nick Wille5076a022023-06-01 18:39:25 +000022#include <inttypes.h>
Ken Chen1647f602021-10-05 21:55:22 +080023
24#include <android-base/unique_fd.h>
Maciej Żenczykowski65075bb2023-06-01 23:09:14 +000025#include <android-modules-utils/sdk_level.h>
Ken Chen1647f602021-10-05 21:55:22 +080026#include <bpf/WaitForProgsLoaded.h>
27#include <log/log.h>
28#include <netdutils/UidConstants.h>
29#include <private/android_filesystem_config.h>
30
31#include "BpfSyscallWrappers.h"
32
33namespace android {
34namespace net {
35
36using base::unique_fd;
Ken Chen1647f602021-10-05 21:55:22 +080037using bpf::getSocketCookie;
38using bpf::retrieveProgram;
39using netdutils::Status;
40using netdutils::statusFromErrno;
41
42constexpr int PER_UID_STATS_ENTRIES_LIMIT = 500;
43// At most 90% of the stats map may be used by tagged traffic entries. This ensures
44// that 10% of the map is always available to count untagged traffic, one entry per UID.
45// Otherwise, apps would be able to avoid data usage accounting entirely by filling up the
46// map with tagged traffic entries.
47constexpr int TOTAL_UID_STATS_ENTRIES_LIMIT = STATS_MAP_SIZE * 0.9;
48
49static_assert(STATS_MAP_SIZE - TOTAL_UID_STATS_ENTRIES_LIMIT > 100,
50 "The limit for stats map is to high, stats data may be lost due to overflow");
51
52static Status attachProgramToCgroup(const char* programPath, const unique_fd& cgroupFd,
53 bpf_attach_type type) {
54 unique_fd cgroupProg(retrieveProgram(programPath));
Maciej Żenczykowski25824452023-06-14 10:08:31 +000055 if (!cgroupProg.ok()) {
56 const int err = errno;
57 ALOGE("Failed to get program from %s: %s", programPath, strerror(err));
58 return statusFromErrno(err, "cgroup program get failed");
Ken Chen1647f602021-10-05 21:55:22 +080059 }
60 if (android::bpf::attachProgram(type, cgroupProg, cgroupFd)) {
Maciej Żenczykowski25824452023-06-14 10:08:31 +000061 const int err = errno;
62 ALOGE("Program from %s attach failed: %s", programPath, strerror(err));
63 return statusFromErrno(err, "program attach failed");
Ken Chen1647f602021-10-05 21:55:22 +080064 }
65 return netdutils::status::ok;
66}
67
Maciej Żenczykowskic576c0d2022-08-07 22:18:15 +000068static Status checkProgramAccessible(const char* programPath) {
69 unique_fd prog(retrieveProgram(programPath));
Maciej Żenczykowski25824452023-06-14 10:08:31 +000070 if (!prog.ok()) {
71 const int err = errno;
72 ALOGE("Failed to get program from %s: %s", programPath, strerror(err));
73 return statusFromErrno(err, "program retrieve failed");
Maciej Żenczykowskic576c0d2022-08-07 22:18:15 +000074 }
75 return netdutils::status::ok;
76}
77
Ken Chen1647f602021-10-05 21:55:22 +080078static Status initPrograms(const char* cg2_path) {
Maciej Żenczykowskic2dd01c2023-09-01 21:02:36 +000079 // This code was mainlined in T, so this should be trivially satisfied.
80 if (!modules::sdklevel::IsAtLeastT()) abort();
81
82 // S requires eBPF support which was only added in 4.9, so this should be satisfied.
83 if (!bpf::isAtLeastKernelVersion(4, 9, 0)) abort();
84
85 // U bumps the kernel requirement up to 4.14
86 if (modules::sdklevel::IsAtLeastU() && !bpf::isAtLeastKernelVersion(4, 14, 0)) abort();
87
88 // V bumps the kernel requirement up to 4.19
89 if (modules::sdklevel::IsAtLeastV() && !bpf::isAtLeastKernelVersion(4, 19, 0)) abort();
90
91 // U mandates this mount point (though it should also be the case on T)
Maciej Żenczykowski65075bb2023-06-01 23:09:14 +000092 if (modules::sdklevel::IsAtLeastU() && !!strcmp(cg2_path, "/sys/fs/cgroup")) abort();
93
Ken Chen1647f602021-10-05 21:55:22 +080094 unique_fd cg_fd(open(cg2_path, O_DIRECTORY | O_RDONLY | O_CLOEXEC));
Maciej Żenczykowski25824452023-06-14 10:08:31 +000095 if (!cg_fd.ok()) {
96 const int err = errno;
97 ALOGE("Failed to open the cgroup directory: %s", strerror(err));
98 return statusFromErrno(err, "Open the cgroup directory failed");
Ken Chen1647f602021-10-05 21:55:22 +080099 }
Maciej Żenczykowskic576c0d2022-08-07 22:18:15 +0000100 RETURN_IF_NOT_OK(checkProgramAccessible(XT_BPF_ALLOWLIST_PROG_PATH));
101 RETURN_IF_NOT_OK(checkProgramAccessible(XT_BPF_DENYLIST_PROG_PATH));
102 RETURN_IF_NOT_OK(checkProgramAccessible(XT_BPF_EGRESS_PROG_PATH));
103 RETURN_IF_NOT_OK(checkProgramAccessible(XT_BPF_INGRESS_PROG_PATH));
Ken Chen1647f602021-10-05 21:55:22 +0800104 RETURN_IF_NOT_OK(attachProgramToCgroup(BPF_EGRESS_PROG_PATH, cg_fd, BPF_CGROUP_INET_EGRESS));
105 RETURN_IF_NOT_OK(attachProgramToCgroup(BPF_INGRESS_PROG_PATH, cg_fd, BPF_CGROUP_INET_INGRESS));
Lorenzo Colitti3505b582022-10-27 19:36:27 +0900106
107 // For the devices that support cgroup socket filter, the socket filter
108 // should be loaded successfully by bpfloader. So we attach the filter to
109 // cgroup if the program is pinned properly.
110 // TODO: delete the if statement once all devices should support cgroup
111 // socket filter (ie. the minimum kernel version required is 4.14).
Maciej Żenczykowski03093622023-02-22 22:09:25 +0000112 if (bpf::isAtLeastKernelVersion(4, 14, 0)) {
Lorenzo Colitti3505b582022-10-27 19:36:27 +0900113 RETURN_IF_NOT_OK(
114 attachProgramToCgroup(CGROUP_SOCKET_PROG_PATH, cg_fd, BPF_CGROUP_INET_SOCK_CREATE));
115 }
Ken Chen1647f602021-10-05 21:55:22 +0800116 return netdutils::status::ok;
117}
118
119BpfHandler::BpfHandler()
120 : mPerUidStatsEntriesLimit(PER_UID_STATS_ENTRIES_LIMIT),
121 mTotalUidStatsEntriesLimit(TOTAL_UID_STATS_ENTRIES_LIMIT) {}
122
123BpfHandler::BpfHandler(uint32_t perUidLimit, uint32_t totalLimit)
124 : mPerUidStatsEntriesLimit(perUidLimit), mTotalUidStatsEntriesLimit(totalLimit) {}
125
126Status BpfHandler::init(const char* cg2_path) {
127 // Make sure BPF programs are loaded before doing anything
128 android::bpf::waitForProgsLoaded();
129 ALOGI("BPF programs are loaded");
130
131 RETURN_IF_NOT_OK(initPrograms(cg2_path));
132 RETURN_IF_NOT_OK(initMaps());
133
134 return netdutils::status::ok;
135}
136
137Status BpfHandler::initMaps() {
Ken Chen1647f602021-10-05 21:55:22 +0800138 RETURN_IF_NOT_OK(mStatsMapA.init(STATS_MAP_A_PATH));
139 RETURN_IF_NOT_OK(mStatsMapB.init(STATS_MAP_B_PATH));
140 RETURN_IF_NOT_OK(mConfigurationMap.init(CONFIGURATION_MAP_PATH));
Ken Chen1647f602021-10-05 21:55:22 +0800141 RETURN_IF_NOT_OK(mUidPermissionMap.init(UID_PERMISSION_MAP_PATH));
Maciej Żenczykowskib5868a02022-08-31 04:21:01 +0000142 // initialized last so mCookieTagMap.isValid() implies everything else is valid too
143 RETURN_IF_NOT_OK(mCookieTagMap.init(COOKIE_TAG_MAP_PATH));
Ken Chen322ffcb2022-05-23 22:27:40 +0800144 ALOGI("%s successfully", __func__);
Ken Chen1647f602021-10-05 21:55:22 +0800145
146 return netdutils::status::ok;
147}
148
149bool BpfHandler::hasUpdateDeviceStatsPermission(uid_t uid) {
150 // This implementation is the same logic as method ActivityManager#checkComponentPermission.
151 // It implies that the real uid can never be the same as PER_USER_RANGE.
152 uint32_t appId = uid % PER_USER_RANGE;
153 auto permission = mUidPermissionMap.readValue(appId);
154 if (permission.ok() && (permission.value() & BPF_PERMISSION_UPDATE_DEVICE_STATS)) {
155 return true;
156 }
157 return ((appId == AID_ROOT) || (appId == AID_SYSTEM) || (appId == AID_DNS));
158}
159
160int BpfHandler::tagSocket(int sockFd, uint32_t tag, uid_t chargeUid, uid_t realUid) {
Maciej Żenczykowski4938d402022-08-14 14:36:20 +0000161 if (!mCookieTagMap.isValid()) return -EPERM;
162
163 if (chargeUid != realUid && !hasUpdateDeviceStatsPermission(realUid)) return -EPERM;
Ken Chen1647f602021-10-05 21:55:22 +0800164
Hungming Chen436547e2022-02-18 17:52:11 +0800165 // Note that tagging the socket to AID_CLAT is only implemented in JNI ClatCoordinator.
166 // The process is not allowed to tag socket to AID_CLAT via tagSocket() which would cause
167 // process data usage accounting to be bypassed. Tagging AID_CLAT is used for avoiding counting
168 // CLAT traffic data usage twice. See packages/modules/Connectivity/service/jni/
169 // com_android_server_connectivity_ClatCoordinator.cpp
Maciej Żenczykowski4938d402022-08-14 14:36:20 +0000170 if (chargeUid == AID_CLAT) return -EPERM;
Hungming Chen436547e2022-02-18 17:52:11 +0800171
Hungming Chen478c0eb2022-03-04 21:16:59 +0800172 // The socket destroy listener only monitors on the group {INET_TCP, INET_UDP, INET6_TCP,
173 // INET6_UDP}. Tagging listener unsupported socket causes that the tag can't be removed from
174 // tag map automatically. Eventually, the tag map may run out of space because of dead tag
Hungming Chenbcc0f5b2022-03-07 14:13:49 +0800175 // entries. Note that although tagSocket() of net client has already denied the family which
176 // is neither AF_INET nor AF_INET6, the family validation is still added here just in case.
177 // See tagSocket in system/netd/client/NetdClient.cpp and
178 // TrafficController::makeSkDestroyListener in
Hungming Chen478c0eb2022-03-04 21:16:59 +0800179 // packages/modules/Connectivity/service/native/TrafficController.cpp
180 // TODO: remove this once the socket destroy listener can detect more types of socket destroy.
Hungming Chenbcc0f5b2022-03-07 14:13:49 +0800181 int socketFamily;
182 socklen_t familyLen = sizeof(socketFamily);
183 if (getsockopt(sockFd, SOL_SOCKET, SO_DOMAIN, &socketFamily, &familyLen)) {
184 ALOGE("Failed to getsockopt SO_DOMAIN: %s, fd: %d", strerror(errno), sockFd);
Hungming Chen478c0eb2022-03-04 21:16:59 +0800185 return -errno;
Hungming Chenbcc0f5b2022-03-07 14:13:49 +0800186 }
187 if (socketFamily != AF_INET && socketFamily != AF_INET6) {
188 ALOGE("Unsupported family: %d", socketFamily);
189 return -EAFNOSUPPORT;
190 }
191
192 int socketProto;
193 socklen_t protoLen = sizeof(socketProto);
194 if (getsockopt(sockFd, SOL_SOCKET, SO_PROTOCOL, &socketProto, &protoLen)) {
195 ALOGE("Failed to getsockopt SO_PROTOCOL: %s, fd: %d", strerror(errno), sockFd);
196 return -errno;
197 }
198 if (socketProto != IPPROTO_UDP && socketProto != IPPROTO_TCP) {
199 ALOGE("Unsupported protocol: %d", socketProto);
200 return -EPROTONOSUPPORT;
Hungming Chen478c0eb2022-03-04 21:16:59 +0800201 }
202
Ken Chen1647f602021-10-05 21:55:22 +0800203 uint64_t sock_cookie = getSocketCookie(sockFd);
Maciej Żenczykowskid3fe1542023-02-23 03:56:45 +0000204 if (!sock_cookie) return -errno;
Maciej Żenczykowski4938d402022-08-14 14:36:20 +0000205
Ken Chen1647f602021-10-05 21:55:22 +0800206 UidTagValue newKey = {.uid = (uint32_t)chargeUid, .tag = tag};
207
208 uint32_t totalEntryCount = 0;
209 uint32_t perUidEntryCount = 0;
210 // Now we go through the stats map and count how many entries are associated
211 // with chargeUid. If the uid entry hit the limit for each chargeUid, we block
Maciej Żenczykowskib5868a02022-08-31 04:21:01 +0000212 // the request to prevent the map from overflow. Note though that it isn't really
213 // safe here to iterate over the map since it might be modified by the system server,
214 // which might toggle the live stats map and clean it.
Ken Chen1647f602021-10-05 21:55:22 +0800215 const auto countUidStatsEntries = [chargeUid, &totalEntryCount, &perUidEntryCount](
216 const StatsKey& key,
217 const BpfMap<StatsKey, StatsValue>&) {
218 if (key.uid == chargeUid) {
219 perUidEntryCount++;
220 }
221 totalEntryCount++;
222 return base::Result<void>();
223 };
224 auto configuration = mConfigurationMap.readValue(CURRENT_STATS_MAP_CONFIGURATION_KEY);
225 if (!configuration.ok()) {
Maciej Żenczykowski85d4a5e2023-08-20 16:41:50 +0000226 ALOGE("Failed to get current configuration: %s",
227 strerror(configuration.error().code()));
Ken Chen1647f602021-10-05 21:55:22 +0800228 return -configuration.error().code();
229 }
230 if (configuration.value() != SELECT_MAP_A && configuration.value() != SELECT_MAP_B) {
231 ALOGE("unknown configuration value: %d", configuration.value());
232 return -EINVAL;
233 }
234
235 BpfMap<StatsKey, StatsValue>& currentMap =
236 (configuration.value() == SELECT_MAP_A) ? mStatsMapA : mStatsMapB;
Maciej Żenczykowski21ce7212022-06-13 17:28:41 -0700237 // HACK: mStatsMapB becomes RW BpfMap here, but countUidStatsEntries doesn't modify so it works
Ken Chen1647f602021-10-05 21:55:22 +0800238 base::Result<void> res = currentMap.iterate(countUidStatsEntries);
239 if (!res.ok()) {
Maciej Żenczykowski85d4a5e2023-08-20 16:41:50 +0000240 ALOGE("Failed to count the stats entry in map: %s",
Ken Chen1647f602021-10-05 21:55:22 +0800241 strerror(res.error().code()));
242 return -res.error().code();
243 }
244
245 if (totalEntryCount > mTotalUidStatsEntriesLimit ||
246 perUidEntryCount > mPerUidStatsEntriesLimit) {
247 ALOGE("Too many stats entries in the map, total count: %u, chargeUid(%u) count: %u,"
248 " blocking tag request to prevent map overflow",
249 totalEntryCount, chargeUid, perUidEntryCount);
250 return -EMFILE;
251 }
252 // Update the tag information of a socket to the cookieUidMap. Use BPF_ANY
253 // flag so it will insert a new entry to the map if that value doesn't exist
Maciej Żenczykowskib5868a02022-08-31 04:21:01 +0000254 // yet and update the tag if there is already a tag stored. Since the eBPF
Ken Chen1647f602021-10-05 21:55:22 +0800255 // program in kernel only read this map, and is protected by rcu read lock. It
Maciej Żenczykowskib5868a02022-08-31 04:21:01 +0000256 // should be fine to concurrently update the map while eBPF program is running.
Ken Chen1647f602021-10-05 21:55:22 +0800257 res = mCookieTagMap.writeValue(sock_cookie, newKey, BPF_ANY);
258 if (!res.ok()) {
Maciej Żenczykowski85d4a5e2023-08-20 16:41:50 +0000259 ALOGE("Failed to tag the socket: %s", strerror(res.error().code()));
Ken Chen1647f602021-10-05 21:55:22 +0800260 return -res.error().code();
261 }
Nick Wille5076a022023-06-01 18:39:25 +0000262 ALOGD("Socket with cookie %" PRIu64 " tagged successfully with tag %" PRIu32 " uid %u "
263 "and real uid %u", sock_cookie, tag, chargeUid, realUid);
Ken Chen1647f602021-10-05 21:55:22 +0800264 return 0;
265}
266
267int BpfHandler::untagSocket(int sockFd) {
Maciej Żenczykowski4938d402022-08-14 14:36:20 +0000268 uint64_t sock_cookie = getSocketCookie(sockFd);
Maciej Żenczykowskid3fe1542023-02-23 03:56:45 +0000269 if (!sock_cookie) return -errno;
Maciej Żenczykowski4938d402022-08-14 14:36:20 +0000270
271 if (!mCookieTagMap.isValid()) return -EPERM;
Ken Chen1647f602021-10-05 21:55:22 +0800272 base::Result<void> res = mCookieTagMap.deleteValue(sock_cookie);
273 if (!res.ok()) {
Maciej Żenczykowskie0f58462022-05-17 13:59:22 -0700274 ALOGE("Failed to untag socket: %s", strerror(res.error().code()));
Ken Chen1647f602021-10-05 21:55:22 +0800275 return -res.error().code();
276 }
Nick Wille5076a022023-06-01 18:39:25 +0000277 ALOGD("Socket with cookie %" PRIu64 " untagged successfully.", sock_cookie);
Ken Chen1647f602021-10-05 21:55:22 +0800278 return 0;
279}
280
281} // namespace net
282} // namespace android