blob: e3e508b52df4e956d3df7d5f37671fd4cc2c24c9 [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
Maciej Żenczykowskia81daca2024-05-20 14:33:17 +000017#define LOG_TAG "NetdUpdatable"
Ken Chen1647f602021-10-05 21:55:22 +080018
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;
Maciej Żenczykowski15f97312024-06-13 14:11:28 -070036using base::WaitForProperty;
Ken Chen1647f602021-10-05 21:55:22 +080037using bpf::getSocketCookie;
Maciej Żenczykowski7a7dcf82025-02-04 13:52:37 -080038using bpf::isAtLeastKernelVersion;
Maciej Żenczykowski73238632025-02-24 14:50:09 -080039using bpf::isAtLeastT;
40using bpf::isAtLeastU;
41using bpf::isAtLeastV;
42using bpf::isAtLeast25Q2;
Maciej Żenczykowski7a7dcf82025-02-04 13:52:37 -080043using bpf::queryProgram;
Ken Chen1647f602021-10-05 21:55:22 +080044using bpf::retrieveProgram;
45using netdutils::Status;
46using netdutils::statusFromErrno;
47
48constexpr int PER_UID_STATS_ENTRIES_LIMIT = 500;
49// At most 90% of the stats map may be used by tagged traffic entries. This ensures
50// that 10% of the map is always available to count untagged traffic, one entry per UID.
51// Otherwise, apps would be able to avoid data usage accounting entirely by filling up the
52// map with tagged traffic entries.
53constexpr int TOTAL_UID_STATS_ENTRIES_LIMIT = STATS_MAP_SIZE * 0.9;
54
55static_assert(STATS_MAP_SIZE - TOTAL_UID_STATS_ENTRIES_LIMIT > 100,
56 "The limit for stats map is to high, stats data may be lost due to overflow");
57
58static Status attachProgramToCgroup(const char* programPath, const unique_fd& cgroupFd,
59 bpf_attach_type type) {
60 unique_fd cgroupProg(retrieveProgram(programPath));
Maciej Żenczykowski25824452023-06-14 10:08:31 +000061 if (!cgroupProg.ok()) {
Ken Chend6ea75a2023-11-28 23:29:47 +080062 return statusFromErrno(errno, fmt::format("Failed to get program from {}", programPath));
Ken Chen1647f602021-10-05 21:55:22 +080063 }
Maciej Żenczykowski7a7dcf82025-02-04 13:52:37 -080064 if (bpf::attachProgram(type, cgroupProg, cgroupFd)) {
Ken Chend6ea75a2023-11-28 23:29:47 +080065 return statusFromErrno(errno, fmt::format("Program {} attach failed", programPath));
Ken Chen1647f602021-10-05 21:55:22 +080066 }
67 return netdutils::status::ok;
68}
69
Maciej Żenczykowskic576c0d2022-08-07 22:18:15 +000070static Status checkProgramAccessible(const char* programPath) {
71 unique_fd prog(retrieveProgram(programPath));
Maciej Żenczykowski25824452023-06-14 10:08:31 +000072 if (!prog.ok()) {
Ken Chend6ea75a2023-11-28 23:29:47 +080073 return statusFromErrno(errno, fmt::format("Failed to get program from {}", programPath));
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) {
Ken Chend6ea75a2023-11-28 23:29:47 +080079 if (!cg2_path) return Status("cg2_path is NULL");
Ken Chen5d146492023-11-27 17:05:43 +080080
Maciej Żenczykowskic2dd01c2023-09-01 21:02:36 +000081 // This code was mainlined in T, so this should be trivially satisfied.
Maciej Żenczykowski73238632025-02-24 14:50:09 -080082 if (!isAtLeastT) return Status("S- platform is unsupported");
Maciej Żenczykowskic2dd01c2023-09-01 21:02:36 +000083
84 // S requires eBPF support which was only added in 4.9, so this should be satisfied.
Maciej Żenczykowski7a7dcf82025-02-04 13:52:37 -080085 if (!isAtLeastKernelVersion(4, 9, 0)) {
Ken Chend6ea75a2023-11-28 23:29:47 +080086 return Status("kernel version < 4.9.0 is unsupported");
Ken Chen5d146492023-11-27 17:05:43 +080087 }
Maciej Żenczykowskic2dd01c2023-09-01 21:02:36 +000088
89 // U bumps the kernel requirement up to 4.14
Maciej Żenczykowski73238632025-02-24 14:50:09 -080090 if (isAtLeastU && !isAtLeastKernelVersion(4, 14, 0)) {
Ken Chend6ea75a2023-11-28 23:29:47 +080091 return Status("U+ platform with kernel version < 4.14.0 is unsupported");
Ken Chen5d146492023-11-27 17:05:43 +080092 }
Maciej Żenczykowskic2dd01c2023-09-01 21:02:36 +000093
Maciej Żenczykowskic2dd01c2023-09-01 21:02:36 +000094 // U mandates this mount point (though it should also be the case on T)
Maciej Żenczykowski73238632025-02-24 14:50:09 -080095 if (isAtLeastU && !!strcmp(cg2_path, "/sys/fs/cgroup")) {
Ken Chend6ea75a2023-11-28 23:29:47 +080096 return Status("U+ platform with cg2_path != /sys/fs/cgroup is unsupported");
Ken Chen5d146492023-11-27 17:05:43 +080097 }
Maciej Żenczykowski65075bb2023-06-01 23:09:14 +000098
Maciej Żenczykowski1758f412025-01-13 12:18:47 -080099 // V bumps the kernel requirement up to 4.19
Maciej Żenczykowski73238632025-02-24 14:50:09 -0800100 if (isAtLeastV && !isAtLeastKernelVersion(4, 19, 0)) {
Maciej Żenczykowski1758f412025-01-13 12:18:47 -0800101 return Status("V+ platform with kernel version < 4.19.0 is unsupported");
102 }
103
104 // 25Q2 bumps the kernel requirement up to 5.4
Maciej Żenczykowski73238632025-02-24 14:50:09 -0800105 if (isAtLeast25Q2 && !isAtLeastKernelVersion(5, 4, 0)) {
Maciej Żenczykowski1758f412025-01-13 12:18:47 -0800106 return Status("25Q2+ platform with kernel version < 5.4.0 is unsupported");
107 }
108
Ken Chen1647f602021-10-05 21:55:22 +0800109 unique_fd cg_fd(open(cg2_path, O_DIRECTORY | O_RDONLY | O_CLOEXEC));
Maciej Żenczykowski0bcb13f2025-01-31 12:51:53 -0800110 if (!cg_fd.ok()) return statusFromErrno(errno, "Opening cgroup dir failed");
Maciej Żenczykowskieb85ea52024-11-20 19:32:07 +0000111
Maciej Żenczykowskic576c0d2022-08-07 22:18:15 +0000112 RETURN_IF_NOT_OK(checkProgramAccessible(XT_BPF_ALLOWLIST_PROG_PATH));
113 RETURN_IF_NOT_OK(checkProgramAccessible(XT_BPF_DENYLIST_PROG_PATH));
114 RETURN_IF_NOT_OK(checkProgramAccessible(XT_BPF_EGRESS_PROG_PATH));
115 RETURN_IF_NOT_OK(checkProgramAccessible(XT_BPF_INGRESS_PROG_PATH));
Ken Chen1647f602021-10-05 21:55:22 +0800116 RETURN_IF_NOT_OK(attachProgramToCgroup(BPF_EGRESS_PROG_PATH, cg_fd, BPF_CGROUP_INET_EGRESS));
117 RETURN_IF_NOT_OK(attachProgramToCgroup(BPF_INGRESS_PROG_PATH, cg_fd, BPF_CGROUP_INET_INGRESS));
Lorenzo Colitti3505b582022-10-27 19:36:27 +0900118
119 // For the devices that support cgroup socket filter, the socket filter
120 // should be loaded successfully by bpfloader. So we attach the filter to
121 // cgroup if the program is pinned properly.
122 // TODO: delete the if statement once all devices should support cgroup
123 // socket filter (ie. the minimum kernel version required is 4.14).
Maciej Żenczykowski7a7dcf82025-02-04 13:52:37 -0800124 if (isAtLeastKernelVersion(4, 14, 0)) {
Maciej Żenczykowski22db5902024-05-10 06:44:08 -0700125 RETURN_IF_NOT_OK(attachProgramToCgroup(CGROUP_INET_CREATE_PROG_PATH,
126 cg_fd, BPF_CGROUP_INET_SOCK_CREATE));
127 }
128
Maciej Żenczykowski7a7dcf82025-02-04 13:52:37 -0800129 if (isAtLeastKernelVersion(5, 10, 0)) {
Maciej Żenczykowski6e945832024-09-23 20:20:36 +0000130 RETURN_IF_NOT_OK(attachProgramToCgroup(CGROUP_INET_RELEASE_PROG_PATH,
131 cg_fd, BPF_CGROUP_INET_SOCK_RELEASE));
132 }
133
Maciej Żenczykowski73238632025-02-24 14:50:09 -0800134 if (isAtLeastV) {
LuK13372918f062024-11-04 18:41:05 +0100135 // V requires 4.19+, so technically this 2nd 'if' is not required, but it
136 // doesn't hurt us to try to support AOSP forks that try to support older kernels.
Maciej Żenczykowski7a7dcf82025-02-04 13:52:37 -0800137 if (isAtLeastKernelVersion(4, 19, 0)) {
LuK13372918f062024-11-04 18:41:05 +0100138 RETURN_IF_NOT_OK(attachProgramToCgroup(CGROUP_CONNECT4_PROG_PATH,
139 cg_fd, BPF_CGROUP_INET4_CONNECT));
140 RETURN_IF_NOT_OK(attachProgramToCgroup(CGROUP_CONNECT6_PROG_PATH,
141 cg_fd, BPF_CGROUP_INET6_CONNECT));
142 RETURN_IF_NOT_OK(attachProgramToCgroup(CGROUP_UDP4_RECVMSG_PROG_PATH,
143 cg_fd, BPF_CGROUP_UDP4_RECVMSG));
144 RETURN_IF_NOT_OK(attachProgramToCgroup(CGROUP_UDP6_RECVMSG_PROG_PATH,
145 cg_fd, BPF_CGROUP_UDP6_RECVMSG));
146 RETURN_IF_NOT_OK(attachProgramToCgroup(CGROUP_UDP4_SENDMSG_PROG_PATH,
147 cg_fd, BPF_CGROUP_UDP4_SENDMSG));
148 RETURN_IF_NOT_OK(attachProgramToCgroup(CGROUP_UDP6_SENDMSG_PROG_PATH,
149 cg_fd, BPF_CGROUP_UDP6_SENDMSG));
150 }
Maciej Żenczykowski05ebcf02024-06-18 17:49:19 -0700151
Maciej Żenczykowski7a7dcf82025-02-04 13:52:37 -0800152 if (isAtLeastKernelVersion(5, 4, 0)) {
Maciej Żenczykowski22db5902024-05-10 06:44:08 -0700153 RETURN_IF_NOT_OK(attachProgramToCgroup(CGROUP_GETSOCKOPT_PROG_PATH,
154 cg_fd, BPF_CGROUP_GETSOCKOPT));
155 RETURN_IF_NOT_OK(attachProgramToCgroup(CGROUP_SETSOCKOPT_PROG_PATH,
156 cg_fd, BPF_CGROUP_SETSOCKOPT));
Maciej Żenczykowski05ebcf02024-06-18 17:49:19 -0700157 }
Lorenzo Colitti3505b582022-10-27 19:36:27 +0900158 }
Maciej Żenczykowski5b2611d2023-10-04 00:44:56 +0000159
Maciej Żenczykowski7a7dcf82025-02-04 13:52:37 -0800160 if (isAtLeastKernelVersion(4, 19, 0)) {
Maciej Żenczykowski3ad37942024-09-19 00:13:04 +0000161 RETURN_IF_NOT_OK(attachProgramToCgroup(CGROUP_BIND4_PROG_PATH,
Maciej Żenczykowski3cb494f2023-10-04 21:35:41 +0000162 cg_fd, BPF_CGROUP_INET4_BIND));
Maciej Żenczykowski3ad37942024-09-19 00:13:04 +0000163 RETURN_IF_NOT_OK(attachProgramToCgroup(CGROUP_BIND6_PROG_PATH,
Maciej Żenczykowski3cb494f2023-10-04 21:35:41 +0000164 cg_fd, BPF_CGROUP_INET6_BIND));
165
166 // This should trivially pass, since we just attached up above,
167 // but BPF_PROG_QUERY is only implemented on 4.19+ kernels.
Maciej Żenczykowski7a7dcf82025-02-04 13:52:37 -0800168 if (queryProgram(cg_fd, BPF_CGROUP_INET_EGRESS) <= 0) abort();
169 if (queryProgram(cg_fd, BPF_CGROUP_INET_INGRESS) <= 0) abort();
170 if (queryProgram(cg_fd, BPF_CGROUP_INET_SOCK_CREATE) <= 0) abort();
171 if (queryProgram(cg_fd, BPF_CGROUP_INET4_BIND) <= 0) abort();
172 if (queryProgram(cg_fd, BPF_CGROUP_INET6_BIND) <= 0) abort();
Maciej Żenczykowski5b2611d2023-10-04 00:44:56 +0000173 }
174
Maciej Żenczykowski7a7dcf82025-02-04 13:52:37 -0800175 if (isAtLeastKernelVersion(5, 10, 0)) {
176 if (queryProgram(cg_fd, BPF_CGROUP_INET_SOCK_RELEASE) <= 0) abort();
Maciej Żenczykowski6e945832024-09-23 20:20:36 +0000177 }
178
Maciej Żenczykowski73238632025-02-24 14:50:09 -0800179 if (isAtLeastV) {
LuK13372918f062024-11-04 18:41:05 +0100180 // V requires 4.19+, so technically this 2nd 'if' is not required, but it
181 // doesn't hurt us to try to support AOSP forks that try to support older kernels.
Maciej Żenczykowski7a7dcf82025-02-04 13:52:37 -0800182 if (isAtLeastKernelVersion(4, 19, 0)) {
183 if (queryProgram(cg_fd, BPF_CGROUP_INET4_CONNECT) <= 0) abort();
184 if (queryProgram(cg_fd, BPF_CGROUP_INET6_CONNECT) <= 0) abort();
185 if (queryProgram(cg_fd, BPF_CGROUP_UDP4_RECVMSG) <= 0) abort();
186 if (queryProgram(cg_fd, BPF_CGROUP_UDP6_RECVMSG) <= 0) abort();
187 if (queryProgram(cg_fd, BPF_CGROUP_UDP4_SENDMSG) <= 0) abort();
188 if (queryProgram(cg_fd, BPF_CGROUP_UDP6_SENDMSG) <= 0) abort();
LuK13372918f062024-11-04 18:41:05 +0100189 }
Maciej Żenczykowski05ebcf02024-06-18 17:49:19 -0700190
Maciej Żenczykowski7a7dcf82025-02-04 13:52:37 -0800191 if (isAtLeastKernelVersion(5, 4, 0)) {
192 if (queryProgram(cg_fd, BPF_CGROUP_GETSOCKOPT) <= 0) abort();
193 if (queryProgram(cg_fd, BPF_CGROUP_SETSOCKOPT) <= 0) abort();
Maciej Żenczykowski05ebcf02024-06-18 17:49:19 -0700194 }
Maciej Żenczykowski22db5902024-05-10 06:44:08 -0700195 }
196
Ken Chen1647f602021-10-05 21:55:22 +0800197 return netdutils::status::ok;
198}
199
200BpfHandler::BpfHandler()
201 : mPerUidStatsEntriesLimit(PER_UID_STATS_ENTRIES_LIMIT),
202 mTotalUidStatsEntriesLimit(TOTAL_UID_STATS_ENTRIES_LIMIT) {}
203
204BpfHandler::BpfHandler(uint32_t perUidLimit, uint32_t totalLimit)
205 : mPerUidStatsEntriesLimit(perUidLimit), mTotalUidStatsEntriesLimit(totalLimit) {}
206
Maciej Żenczykowski15f97312024-06-13 14:11:28 -0700207static bool mainlineNetBpfLoadDone() {
208 return !access("/sys/fs/bpf/netd_shared/mainline_done", F_OK);
209}
210
Maciej Żenczykowski732a1412024-03-14 00:17:18 -0700211// copied with minor changes from waitForProgsLoaded()
212// p/m/C's staticlibs/native/bpf_headers/include/bpf/WaitForProgsLoaded.h
213static inline void waitForNetProgsLoaded() {
214 // infinite loop until success with 5/10/20/40/60/60/60... delay
215 for (int delay = 5;; delay *= 2) {
216 if (delay > 60) delay = 60;
Maciej Żenczykowski15f97312024-06-13 14:11:28 -0700217 if (WaitForProperty("init.svc.mdnsd_netbpfload", "stopped", std::chrono::seconds(delay))
218 && mainlineNetBpfLoadDone())
Maciej Żenczykowski732a1412024-03-14 00:17:18 -0700219 return;
Maciej Żenczykowski15f97312024-06-13 14:11:28 -0700220 ALOGW("Waited %ds for init.svc.mdnsd_netbpfload=stopped, still waiting...", delay);
Maciej Żenczykowski732a1412024-03-14 00:17:18 -0700221 }
222}
223
Maciej Żenczykowski23c02b02024-10-02 22:48:19 +0000224static inline void waitForBpf() {
Maciej Żenczykowski15f97312024-06-13 14:11:28 -0700225 // Note: netd *can* be restarted, so this might get called a second time after boot is complete
226 // at which point we don't need to (and shouldn't) wait for (more importantly start) loading bpf
227
Maciej Żenczykowski23d2c1e2024-03-28 22:54:01 -0700228 if (base::GetProperty("bpf.progs_loaded", "") != "1") {
Maciej Żenczykowski15f97312024-06-13 14:11:28 -0700229 // AOSP platform netd & mainline don't need this (at least prior to U QPR3),
230 // but there could be platform provided (xt_)bpf programs that oem/vendor
231 // modified netd (which calls us during init) depends on...
232 ALOGI("Waiting for platform BPF programs");
Maciej Żenczykowski7a7dcf82025-02-04 13:52:37 -0800233 bpf::waitForProgsLoaded();
Maciej Żenczykowski732a1412024-03-14 00:17:18 -0700234 }
Maciej Żenczykowski15f97312024-06-13 14:11:28 -0700235
Maciej Żenczykowski4e4f8722024-06-15 06:38:08 -0700236 if (!mainlineNetBpfLoadDone()) {
Maciej Żenczykowski72628992024-06-14 13:46:11 -0700237 // We're on < U QPR3 & it's the first time netd is starting up (unless crashlooping)
238 //
239 // On U QPR3+ netbpfload is guaranteed to run before the platform bpfloader,
240 // so waitForProgsLoaded() implies mainlineNetBpfLoadDone().
Maciej Żenczykowski15f97312024-06-13 14:11:28 -0700241 if (!base::SetProperty("ctl.start", "mdnsd_netbpfload")) {
242 ALOGE("Failed to set property ctl.start=mdnsd_netbpfload, see dmesg for reason.");
Maciej Żenczykowski2afffc22024-06-15 06:37:03 -0700243 abort();
Maciej Żenczykowski15f97312024-06-13 14:11:28 -0700244 }
245
Maciej Żenczykowski2afffc22024-06-15 06:37:03 -0700246 ALOGI("Waiting for Networking BPF programs");
247 waitForNetProgsLoaded();
248 ALOGI("Networking BPF programs are loaded");
Maciej Żenczykowski15f97312024-06-13 14:11:28 -0700249 }
250
Ken Chen1647f602021-10-05 21:55:22 +0800251 ALOGI("BPF programs are loaded");
Maciej Żenczykowski23c02b02024-10-02 22:48:19 +0000252}
253
254Status BpfHandler::init(const char* cg2_path) {
255 // This wait is effectively a no-op on U QPR3+ devices (as netd starts
Maciej Żenczykowskie6113242024-10-03 18:42:18 +0000256 // *after* the synchronous 'exec_start bpfloader' which calls NetBpfLoad)
Maciej Żenczykowski23c02b02024-10-02 22:48:19 +0000257 // but checking for U QPR3 is hard.
258 //
259 // Waiting should not be required on U QPR3+ devices,
260 // ...
261 //
262 // ...unless someone changed 'exec_start bpfloader' to 'start bpfloader'
263 // in the rc file.
264 //
Maciej Żenczykowski73238632025-02-24 14:50:09 -0800265 if (!isAtLeast25Q2) waitForBpf();
Ken Chen1647f602021-10-05 21:55:22 +0800266
267 RETURN_IF_NOT_OK(initPrograms(cg2_path));
268 RETURN_IF_NOT_OK(initMaps());
269
Maciej Żenczykowski73238632025-02-24 14:50:09 -0800270 if (isAtLeast25Q2) {
271 // Make sure netd can create & write maps. sepolicy is V+, but enough to enforce on 25Q2+
Maciej Żenczykowski48f244e2025-01-30 13:18:28 -0800272 int key = 1;
273 int value = 123;
274 unique_fd map(bpf::createMap(BPF_MAP_TYPE_ARRAY, sizeof(key), sizeof(value), 2, 0));
275 if (!map.ok()) return statusFromErrno(errno, fmt::format("map create failed"));
276 int rv = bpf::writeToMapEntry(map, &key, &value, BPF_ANY);
277 if (rv) return statusFromErrno(errno, fmt::format("map write failed (rv={})", rv));
278 }
279
Ken Chen1647f602021-10-05 21:55:22 +0800280 return netdutils::status::ok;
281}
282
Maciej Żenczykowski52018c82024-06-04 16:05:16 +0000283static void mapLockTest(void) {
284 // The maps must be R/W, and as yet unopened (or more specifically not yet lock'ed).
285 const char * const m1 = BPF_NETD_PATH "map_netd_lock_array_test_map";
286 const char * const m2 = BPF_NETD_PATH "map_netd_lock_hash_test_map";
287
Maciej Żenczykowski7eb7d672024-06-14 13:55:09 -0700288 unique_fd fd0(bpf::mapRetrieveExclusiveRW(m1)); if (!fd0.ok()) abort(); // grabs exclusive lock
Maciej Żenczykowski52018c82024-06-04 16:05:16 +0000289
290 unique_fd fd1(bpf::mapRetrieveExclusiveRW(m2)); if (!fd1.ok()) abort(); // no conflict with fd0
291 unique_fd fd2(bpf::mapRetrieveExclusiveRW(m2)); if ( fd2.ok()) abort(); // busy due to fd1
292 unique_fd fd3(bpf::mapRetrieveRO(m2)); if (!fd3.ok()) abort(); // no lock taken
293 unique_fd fd4(bpf::mapRetrieveRW(m2)); if ( fd4.ok()) abort(); // busy due to fd1
294 fd1.reset(); // releases exclusive lock
295 unique_fd fd5(bpf::mapRetrieveRO(m2)); if (!fd5.ok()) abort(); // no lock taken
296 unique_fd fd6(bpf::mapRetrieveRW(m2)); if (!fd6.ok()) abort(); // now ok
297 unique_fd fd7(bpf::mapRetrieveRO(m2)); if (!fd7.ok()) abort(); // no lock taken
298 unique_fd fd8(bpf::mapRetrieveExclusiveRW(m2)); if ( fd8.ok()) abort(); // busy due to fd6
Maciej Żenczykowski7eb7d672024-06-14 13:55:09 -0700299
300 fd0.reset(); // releases exclusive lock
301 unique_fd fd9(bpf::mapRetrieveWO(m1)); if (!fd9.ok()) abort(); // grabs exclusive lock
Maciej Żenczykowski52018c82024-06-04 16:05:16 +0000302}
303
Ken Chen1647f602021-10-05 21:55:22 +0800304Status BpfHandler::initMaps() {
Patrick Rohr78ad0032024-06-28 00:25:50 +0000305 // bpfLock() requires bpfGetFdMapId which is only available on 4.14+ kernels.
Maciej Żenczykowski7a7dcf82025-02-04 13:52:37 -0800306 if (isAtLeastKernelVersion(4, 14, 0)) {
Patrick Rohr78ad0032024-06-28 00:25:50 +0000307 mapLockTest();
308 }
Maciej Żenczykowski52018c82024-06-04 16:05:16 +0000309
Ken Chen1647f602021-10-05 21:55:22 +0800310 RETURN_IF_NOT_OK(mStatsMapA.init(STATS_MAP_A_PATH));
311 RETURN_IF_NOT_OK(mStatsMapB.init(STATS_MAP_B_PATH));
312 RETURN_IF_NOT_OK(mConfigurationMap.init(CONFIGURATION_MAP_PATH));
Ken Chen1647f602021-10-05 21:55:22 +0800313 RETURN_IF_NOT_OK(mUidPermissionMap.init(UID_PERMISSION_MAP_PATH));
Maciej Żenczykowskib5868a02022-08-31 04:21:01 +0000314 // initialized last so mCookieTagMap.isValid() implies everything else is valid too
315 RETURN_IF_NOT_OK(mCookieTagMap.init(COOKIE_TAG_MAP_PATH));
Ken Chen1647f602021-10-05 21:55:22 +0800316
317 return netdutils::status::ok;
318}
319
320bool BpfHandler::hasUpdateDeviceStatsPermission(uid_t uid) {
321 // This implementation is the same logic as method ActivityManager#checkComponentPermission.
322 // It implies that the real uid can never be the same as PER_USER_RANGE.
323 uint32_t appId = uid % PER_USER_RANGE;
324 auto permission = mUidPermissionMap.readValue(appId);
325 if (permission.ok() && (permission.value() & BPF_PERMISSION_UPDATE_DEVICE_STATS)) {
326 return true;
327 }
328 return ((appId == AID_ROOT) || (appId == AID_SYSTEM) || (appId == AID_DNS));
329}
330
331int BpfHandler::tagSocket(int sockFd, uint32_t tag, uid_t chargeUid, uid_t realUid) {
Maciej Żenczykowski4938d402022-08-14 14:36:20 +0000332 if (!mCookieTagMap.isValid()) return -EPERM;
333
334 if (chargeUid != realUid && !hasUpdateDeviceStatsPermission(realUid)) return -EPERM;
Ken Chen1647f602021-10-05 21:55:22 +0800335
Hungming Chen436547e2022-02-18 17:52:11 +0800336 // Note that tagging the socket to AID_CLAT is only implemented in JNI ClatCoordinator.
337 // The process is not allowed to tag socket to AID_CLAT via tagSocket() which would cause
338 // process data usage accounting to be bypassed. Tagging AID_CLAT is used for avoiding counting
339 // CLAT traffic data usage twice. See packages/modules/Connectivity/service/jni/
340 // com_android_server_connectivity_ClatCoordinator.cpp
Maciej Żenczykowski4938d402022-08-14 14:36:20 +0000341 if (chargeUid == AID_CLAT) return -EPERM;
Hungming Chen436547e2022-02-18 17:52:11 +0800342
Hungming Chen478c0eb2022-03-04 21:16:59 +0800343 // The socket destroy listener only monitors on the group {INET_TCP, INET_UDP, INET6_TCP,
344 // INET6_UDP}. Tagging listener unsupported socket causes that the tag can't be removed from
345 // tag map automatically. Eventually, the tag map may run out of space because of dead tag
Hungming Chenbcc0f5b2022-03-07 14:13:49 +0800346 // entries. Note that although tagSocket() of net client has already denied the family which
347 // is neither AF_INET nor AF_INET6, the family validation is still added here just in case.
348 // See tagSocket in system/netd/client/NetdClient.cpp and
349 // TrafficController::makeSkDestroyListener in
Hungming Chen478c0eb2022-03-04 21:16:59 +0800350 // packages/modules/Connectivity/service/native/TrafficController.cpp
351 // TODO: remove this once the socket destroy listener can detect more types of socket destroy.
Hungming Chenbcc0f5b2022-03-07 14:13:49 +0800352 int socketFamily;
353 socklen_t familyLen = sizeof(socketFamily);
354 if (getsockopt(sockFd, SOL_SOCKET, SO_DOMAIN, &socketFamily, &familyLen)) {
355 ALOGE("Failed to getsockopt SO_DOMAIN: %s, fd: %d", strerror(errno), sockFd);
Hungming Chen478c0eb2022-03-04 21:16:59 +0800356 return -errno;
Hungming Chenbcc0f5b2022-03-07 14:13:49 +0800357 }
358 if (socketFamily != AF_INET && socketFamily != AF_INET6) {
Maciej Żenczykowski0bcb13f2025-01-31 12:51:53 -0800359 ALOGV("Unsupported family: %d", socketFamily);
Hungming Chenbcc0f5b2022-03-07 14:13:49 +0800360 return -EAFNOSUPPORT;
361 }
362
363 int socketProto;
364 socklen_t protoLen = sizeof(socketProto);
365 if (getsockopt(sockFd, SOL_SOCKET, SO_PROTOCOL, &socketProto, &protoLen)) {
366 ALOGE("Failed to getsockopt SO_PROTOCOL: %s, fd: %d", strerror(errno), sockFd);
367 return -errno;
368 }
369 if (socketProto != IPPROTO_UDP && socketProto != IPPROTO_TCP) {
Maciej Żenczykowski0bcb13f2025-01-31 12:51:53 -0800370 ALOGV("Unsupported protocol: %d", socketProto);
Hungming Chenbcc0f5b2022-03-07 14:13:49 +0800371 return -EPROTONOSUPPORT;
Hungming Chen478c0eb2022-03-04 21:16:59 +0800372 }
373
Ken Chen1647f602021-10-05 21:55:22 +0800374 uint64_t sock_cookie = getSocketCookie(sockFd);
Maciej Żenczykowskid3fe1542023-02-23 03:56:45 +0000375 if (!sock_cookie) return -errno;
Maciej Żenczykowski4938d402022-08-14 14:36:20 +0000376
Ken Chen1647f602021-10-05 21:55:22 +0800377 UidTagValue newKey = {.uid = (uint32_t)chargeUid, .tag = tag};
378
379 uint32_t totalEntryCount = 0;
380 uint32_t perUidEntryCount = 0;
381 // Now we go through the stats map and count how many entries are associated
382 // with chargeUid. If the uid entry hit the limit for each chargeUid, we block
Maciej Żenczykowskib5868a02022-08-31 04:21:01 +0000383 // the request to prevent the map from overflow. Note though that it isn't really
384 // safe here to iterate over the map since it might be modified by the system server,
385 // which might toggle the live stats map and clean it.
Ken Chen1647f602021-10-05 21:55:22 +0800386 const auto countUidStatsEntries = [chargeUid, &totalEntryCount, &perUidEntryCount](
387 const StatsKey& key,
Maciej Żenczykowski7e2f53e2023-09-28 01:08:28 +0000388 const BpfMapRO<StatsKey, StatsValue>&) {
Ken Chen1647f602021-10-05 21:55:22 +0800389 if (key.uid == chargeUid) {
390 perUidEntryCount++;
391 }
392 totalEntryCount++;
393 return base::Result<void>();
394 };
395 auto configuration = mConfigurationMap.readValue(CURRENT_STATS_MAP_CONFIGURATION_KEY);
396 if (!configuration.ok()) {
Maciej Żenczykowski85d4a5e2023-08-20 16:41:50 +0000397 ALOGE("Failed to get current configuration: %s",
398 strerror(configuration.error().code()));
Ken Chen1647f602021-10-05 21:55:22 +0800399 return -configuration.error().code();
400 }
401 if (configuration.value() != SELECT_MAP_A && configuration.value() != SELECT_MAP_B) {
402 ALOGE("unknown configuration value: %d", configuration.value());
403 return -EINVAL;
404 }
405
Maciej Żenczykowski7e2f53e2023-09-28 01:08:28 +0000406 BpfMapRO<StatsKey, StatsValue>& currentMap =
Ken Chen1647f602021-10-05 21:55:22 +0800407 (configuration.value() == SELECT_MAP_A) ? mStatsMapA : mStatsMapB;
408 base::Result<void> res = currentMap.iterate(countUidStatsEntries);
409 if (!res.ok()) {
Maciej Żenczykowski85d4a5e2023-08-20 16:41:50 +0000410 ALOGE("Failed to count the stats entry in map: %s",
Ken Chen1647f602021-10-05 21:55:22 +0800411 strerror(res.error().code()));
412 return -res.error().code();
413 }
414
415 if (totalEntryCount > mTotalUidStatsEntriesLimit ||
416 perUidEntryCount > mPerUidStatsEntriesLimit) {
417 ALOGE("Too many stats entries in the map, total count: %u, chargeUid(%u) count: %u,"
418 " blocking tag request to prevent map overflow",
419 totalEntryCount, chargeUid, perUidEntryCount);
420 return -EMFILE;
421 }
422 // Update the tag information of a socket to the cookieUidMap. Use BPF_ANY
423 // flag so it will insert a new entry to the map if that value doesn't exist
Maciej Żenczykowskib5868a02022-08-31 04:21:01 +0000424 // yet and update the tag if there is already a tag stored. Since the eBPF
Ken Chen1647f602021-10-05 21:55:22 +0800425 // program in kernel only read this map, and is protected by rcu read lock. It
Maciej Żenczykowskib5868a02022-08-31 04:21:01 +0000426 // should be fine to concurrently update the map while eBPF program is running.
Ken Chen1647f602021-10-05 21:55:22 +0800427 res = mCookieTagMap.writeValue(sock_cookie, newKey, BPF_ANY);
428 if (!res.ok()) {
Maciej Żenczykowski85d4a5e2023-08-20 16:41:50 +0000429 ALOGE("Failed to tag the socket: %s", strerror(res.error().code()));
Ken Chen1647f602021-10-05 21:55:22 +0800430 return -res.error().code();
431 }
Maciej Żenczykowski0bcb13f2025-01-31 12:51:53 -0800432 ALOGV("Socket with cookie %" PRIu64 " tagged successfully with tag %" PRIu32 " uid %u "
433 "and real uid %u", sock_cookie, tag, chargeUid, realUid);
Ken Chen1647f602021-10-05 21:55:22 +0800434 return 0;
435}
436
437int BpfHandler::untagSocket(int sockFd) {
Maciej Żenczykowski4938d402022-08-14 14:36:20 +0000438 uint64_t sock_cookie = getSocketCookie(sockFd);
Maciej Żenczykowskid3fe1542023-02-23 03:56:45 +0000439 if (!sock_cookie) return -errno;
Maciej Żenczykowski4938d402022-08-14 14:36:20 +0000440
441 if (!mCookieTagMap.isValid()) return -EPERM;
Ken Chen1647f602021-10-05 21:55:22 +0800442 base::Result<void> res = mCookieTagMap.deleteValue(sock_cookie);
443 if (!res.ok()) {
Maciej Żenczykowski0bcb13f2025-01-31 12:51:53 -0800444 const int err = res.error().code();
445 if (err != ENOENT) ALOGE("Failed to untag socket: %s", strerror(err));
446 return -err;
Ken Chen1647f602021-10-05 21:55:22 +0800447 }
Maciej Żenczykowski0bcb13f2025-01-31 12:51:53 -0800448 ALOGV("Socket with cookie %" PRIu64 " untagged successfully.", sock_cookie);
Ken Chen1647f602021-10-05 21:55:22 +0800449 return 0;
450}
451
452} // namespace net
453} // namespace android