blob: fad6bbb6abcfd9f398f483ea7507bdcdbbbc1c60 [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>
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
31namespace android {
32namespace net {
33
34using base::unique_fd;
35using bpf::NONEXISTENT_COOKIE;
36using 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
67static Status initPrograms(const char* cg2_path) {
68 unique_fd cg_fd(open(cg2_path, O_DIRECTORY | O_RDONLY | O_CLOEXEC));
69 if (cg_fd == -1) {
70 int ret = errno;
71 ALOGE("Failed to open the cgroup directory: %s", strerror(ret));
72 return statusFromErrno(ret, "Open the cgroup directory failed");
73 }
74 RETURN_IF_NOT_OK(attachProgramToCgroup(BPF_EGRESS_PROG_PATH, cg_fd, BPF_CGROUP_INET_EGRESS));
75 RETURN_IF_NOT_OK(attachProgramToCgroup(BPF_INGRESS_PROG_PATH, cg_fd, BPF_CGROUP_INET_INGRESS));
Maciej Żenczykowski6ed2ab92022-05-16 11:00:11 -070076 RETURN_IF_NOT_OK(attachProgramToCgroup(CGROUP_SOCKET_PROG_PATH, cg_fd, BPF_CGROUP_INET_SOCK_CREATE));
Ken Chen1647f602021-10-05 21:55:22 +080077 return netdutils::status::ok;
78}
79
80BpfHandler::BpfHandler()
81 : mPerUidStatsEntriesLimit(PER_UID_STATS_ENTRIES_LIMIT),
82 mTotalUidStatsEntriesLimit(TOTAL_UID_STATS_ENTRIES_LIMIT) {}
83
84BpfHandler::BpfHandler(uint32_t perUidLimit, uint32_t totalLimit)
85 : mPerUidStatsEntriesLimit(perUidLimit), mTotalUidStatsEntriesLimit(totalLimit) {}
86
87Status BpfHandler::init(const char* cg2_path) {
88 // Make sure BPF programs are loaded before doing anything
89 android::bpf::waitForProgsLoaded();
90 ALOGI("BPF programs are loaded");
91
92 RETURN_IF_NOT_OK(initPrograms(cg2_path));
93 RETURN_IF_NOT_OK(initMaps());
94
95 return netdutils::status::ok;
96}
97
98Status BpfHandler::initMaps() {
99 std::lock_guard guard(mMutex);
100 RETURN_IF_NOT_OK(mCookieTagMap.init(COOKIE_TAG_MAP_PATH));
101 RETURN_IF_NOT_OK(mStatsMapA.init(STATS_MAP_A_PATH));
102 RETURN_IF_NOT_OK(mStatsMapB.init(STATS_MAP_B_PATH));
103 RETURN_IF_NOT_OK(mConfigurationMap.init(CONFIGURATION_MAP_PATH));
Ken Chen1647f602021-10-05 21:55:22 +0800104 RETURN_IF_NOT_OK(mUidPermissionMap.init(UID_PERMISSION_MAP_PATH));
Ken Chen322ffcb2022-05-23 22:27:40 +0800105 ALOGI("%s successfully", __func__);
Ken Chen1647f602021-10-05 21:55:22 +0800106
107 return netdutils::status::ok;
108}
109
110bool BpfHandler::hasUpdateDeviceStatsPermission(uid_t uid) {
111 // This implementation is the same logic as method ActivityManager#checkComponentPermission.
112 // It implies that the real uid can never be the same as PER_USER_RANGE.
113 uint32_t appId = uid % PER_USER_RANGE;
114 auto permission = mUidPermissionMap.readValue(appId);
115 if (permission.ok() && (permission.value() & BPF_PERMISSION_UPDATE_DEVICE_STATS)) {
116 return true;
117 }
118 return ((appId == AID_ROOT) || (appId == AID_SYSTEM) || (appId == AID_DNS));
119}
120
121int BpfHandler::tagSocket(int sockFd, uint32_t tag, uid_t chargeUid, uid_t realUid) {
122 std::lock_guard guard(mMutex);
123 if (chargeUid != realUid && !hasUpdateDeviceStatsPermission(realUid)) {
124 return -EPERM;
125 }
126
Hungming Chen436547e2022-02-18 17:52:11 +0800127 // Note that tagging the socket to AID_CLAT is only implemented in JNI ClatCoordinator.
128 // The process is not allowed to tag socket to AID_CLAT via tagSocket() which would cause
129 // process data usage accounting to be bypassed. Tagging AID_CLAT is used for avoiding counting
130 // CLAT traffic data usage twice. See packages/modules/Connectivity/service/jni/
131 // com_android_server_connectivity_ClatCoordinator.cpp
132 if (chargeUid == AID_CLAT) {
133 return -EPERM;
134 }
135
Hungming Chen478c0eb2022-03-04 21:16:59 +0800136 // The socket destroy listener only monitors on the group {INET_TCP, INET_UDP, INET6_TCP,
137 // INET6_UDP}. Tagging listener unsupported socket causes that the tag can't be removed from
138 // tag map automatically. Eventually, the tag map may run out of space because of dead tag
Hungming Chenbcc0f5b2022-03-07 14:13:49 +0800139 // entries. Note that although tagSocket() of net client has already denied the family which
140 // is neither AF_INET nor AF_INET6, the family validation is still added here just in case.
141 // See tagSocket in system/netd/client/NetdClient.cpp and
142 // TrafficController::makeSkDestroyListener in
Hungming Chen478c0eb2022-03-04 21:16:59 +0800143 // packages/modules/Connectivity/service/native/TrafficController.cpp
144 // TODO: remove this once the socket destroy listener can detect more types of socket destroy.
Hungming Chenbcc0f5b2022-03-07 14:13:49 +0800145 int socketFamily;
146 socklen_t familyLen = sizeof(socketFamily);
147 if (getsockopt(sockFd, SOL_SOCKET, SO_DOMAIN, &socketFamily, &familyLen)) {
148 ALOGE("Failed to getsockopt SO_DOMAIN: %s, fd: %d", strerror(errno), sockFd);
Hungming Chen478c0eb2022-03-04 21:16:59 +0800149 return -errno;
Hungming Chenbcc0f5b2022-03-07 14:13:49 +0800150 }
151 if (socketFamily != AF_INET && socketFamily != AF_INET6) {
152 ALOGE("Unsupported family: %d", socketFamily);
153 return -EAFNOSUPPORT;
154 }
155
156 int socketProto;
157 socklen_t protoLen = sizeof(socketProto);
158 if (getsockopt(sockFd, SOL_SOCKET, SO_PROTOCOL, &socketProto, &protoLen)) {
159 ALOGE("Failed to getsockopt SO_PROTOCOL: %s, fd: %d", strerror(errno), sockFd);
160 return -errno;
161 }
162 if (socketProto != IPPROTO_UDP && socketProto != IPPROTO_TCP) {
163 ALOGE("Unsupported protocol: %d", socketProto);
164 return -EPROTONOSUPPORT;
Hungming Chen478c0eb2022-03-04 21:16:59 +0800165 }
166
Ken Chen1647f602021-10-05 21:55:22 +0800167 uint64_t sock_cookie = getSocketCookie(sockFd);
168 if (sock_cookie == NONEXISTENT_COOKIE) return -errno;
169 UidTagValue newKey = {.uid = (uint32_t)chargeUid, .tag = tag};
170
171 uint32_t totalEntryCount = 0;
172 uint32_t perUidEntryCount = 0;
173 // Now we go through the stats map and count how many entries are associated
174 // with chargeUid. If the uid entry hit the limit for each chargeUid, we block
175 // the request to prevent the map from overflow. It is safe here to iterate
176 // over the map since when mMutex is hold, system server cannot toggle
177 // the live stats map and clean it. So nobody can delete entries from the map.
178 const auto countUidStatsEntries = [chargeUid, &totalEntryCount, &perUidEntryCount](
179 const StatsKey& key,
180 const BpfMap<StatsKey, StatsValue>&) {
181 if (key.uid == chargeUid) {
182 perUidEntryCount++;
183 }
184 totalEntryCount++;
185 return base::Result<void>();
186 };
187 auto configuration = mConfigurationMap.readValue(CURRENT_STATS_MAP_CONFIGURATION_KEY);
188 if (!configuration.ok()) {
189 ALOGE("Failed to get current configuration: %s, fd: %d",
190 strerror(configuration.error().code()), mConfigurationMap.getMap().get());
191 return -configuration.error().code();
192 }
193 if (configuration.value() != SELECT_MAP_A && configuration.value() != SELECT_MAP_B) {
194 ALOGE("unknown configuration value: %d", configuration.value());
195 return -EINVAL;
196 }
197
198 BpfMap<StatsKey, StatsValue>& currentMap =
199 (configuration.value() == SELECT_MAP_A) ? mStatsMapA : mStatsMapB;
Maciej Żenczykowski21ce7212022-06-13 17:28:41 -0700200 // HACK: mStatsMapB becomes RW BpfMap here, but countUidStatsEntries doesn't modify so it works
Ken Chen1647f602021-10-05 21:55:22 +0800201 base::Result<void> res = currentMap.iterate(countUidStatsEntries);
202 if (!res.ok()) {
203 ALOGE("Failed to count the stats entry in map %d: %s", currentMap.getMap().get(),
204 strerror(res.error().code()));
205 return -res.error().code();
206 }
207
208 if (totalEntryCount > mTotalUidStatsEntriesLimit ||
209 perUidEntryCount > mPerUidStatsEntriesLimit) {
210 ALOGE("Too many stats entries in the map, total count: %u, chargeUid(%u) count: %u,"
211 " blocking tag request to prevent map overflow",
212 totalEntryCount, chargeUid, perUidEntryCount);
213 return -EMFILE;
214 }
215 // Update the tag information of a socket to the cookieUidMap. Use BPF_ANY
216 // flag so it will insert a new entry to the map if that value doesn't exist
217 // yet. And update the tag if there is already a tag stored. Since the eBPF
218 // program in kernel only read this map, and is protected by rcu read lock. It
219 // should be fine to cocurrently update the map while eBPF program is running.
220 res = mCookieTagMap.writeValue(sock_cookie, newKey, BPF_ANY);
221 if (!res.ok()) {
222 ALOGE("Failed to tag the socket: %s, fd: %d", strerror(res.error().code()),
223 mCookieTagMap.getMap().get());
224 return -res.error().code();
225 }
226 return 0;
227}
228
229int BpfHandler::untagSocket(int sockFd) {
230 std::lock_guard guard(mMutex);
231 uint64_t sock_cookie = getSocketCookie(sockFd);
232
233 if (sock_cookie == NONEXISTENT_COOKIE) return -errno;
234 base::Result<void> res = mCookieTagMap.deleteValue(sock_cookie);
235 if (!res.ok()) {
Maciej Żenczykowskie0f58462022-05-17 13:59:22 -0700236 ALOGE("Failed to untag socket: %s", strerror(res.error().code()));
Ken Chen1647f602021-10-05 21:55:22 +0800237 return -res.error().code();
238 }
239 return 0;
240}
241
242} // namespace net
243} // namespace android