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