blob: bcd0cbac46ad82e506183356d8411a0cbe41be83 [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>
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;
Maciej Żenczykowski15f97312024-06-13 14:11:28 -070037using base::WaitForProperty;
Ken Chen1647f602021-10-05 21:55:22 +080038using bpf::getSocketCookie;
39using bpf::retrieveProgram;
40using netdutils::Status;
41using netdutils::statusFromErrno;
42
43constexpr int PER_UID_STATS_ENTRIES_LIMIT = 500;
44// At most 90% of the stats map may be used by tagged traffic entries. This ensures
45// that 10% of the map is always available to count untagged traffic, one entry per UID.
46// Otherwise, apps would be able to avoid data usage accounting entirely by filling up the
47// map with tagged traffic entries.
48constexpr int TOTAL_UID_STATS_ENTRIES_LIMIT = STATS_MAP_SIZE * 0.9;
49
50static_assert(STATS_MAP_SIZE - TOTAL_UID_STATS_ENTRIES_LIMIT > 100,
51 "The limit for stats map is to high, stats data may be lost due to overflow");
52
53static Status attachProgramToCgroup(const char* programPath, const unique_fd& cgroupFd,
54 bpf_attach_type type) {
55 unique_fd cgroupProg(retrieveProgram(programPath));
Maciej Żenczykowski25824452023-06-14 10:08:31 +000056 if (!cgroupProg.ok()) {
Ken Chend6ea75a2023-11-28 23:29:47 +080057 return statusFromErrno(errno, fmt::format("Failed to get program from {}", programPath));
Ken Chen1647f602021-10-05 21:55:22 +080058 }
59 if (android::bpf::attachProgram(type, cgroupProg, cgroupFd)) {
Ken Chend6ea75a2023-11-28 23:29:47 +080060 return statusFromErrno(errno, fmt::format("Program {} attach failed", programPath));
Ken Chen1647f602021-10-05 21:55:22 +080061 }
62 return netdutils::status::ok;
63}
64
Maciej Żenczykowskic576c0d2022-08-07 22:18:15 +000065static Status checkProgramAccessible(const char* programPath) {
66 unique_fd prog(retrieveProgram(programPath));
Maciej Żenczykowski25824452023-06-14 10:08:31 +000067 if (!prog.ok()) {
Ken Chend6ea75a2023-11-28 23:29:47 +080068 return statusFromErrno(errno, fmt::format("Failed to get program from {}", programPath));
Maciej Żenczykowskic576c0d2022-08-07 22:18:15 +000069 }
70 return netdutils::status::ok;
71}
72
Maciej Żenczykowski1758f412025-01-13 12:18:47 -080073// Checks if the device is running on release version of Android 25Q2 or newer.
74static bool isAtLeast25Q2() {
75 return android_get_device_api_level() >= 36 ||
76 (android_get_device_api_level() == 35 &&
77 modules::sdklevel::detail::IsAtLeastPreReleaseCodename("Baklava"));
78}
79
Ken Chen1647f602021-10-05 21:55:22 +080080static Status initPrograms(const char* cg2_path) {
Ken Chend6ea75a2023-11-28 23:29:47 +080081 if (!cg2_path) return Status("cg2_path is NULL");
Ken Chen5d146492023-11-27 17:05:43 +080082
Maciej Żenczykowskic2dd01c2023-09-01 21:02:36 +000083 // This code was mainlined in T, so this should be trivially satisfied.
Ken Chend6ea75a2023-11-28 23:29:47 +080084 if (!modules::sdklevel::IsAtLeastT()) return Status("S- platform is unsupported");
Maciej Żenczykowskic2dd01c2023-09-01 21:02:36 +000085
86 // S requires eBPF support which was only added in 4.9, so this should be satisfied.
Ken Chen5d146492023-11-27 17:05:43 +080087 if (!bpf::isAtLeastKernelVersion(4, 9, 0)) {
Ken Chend6ea75a2023-11-28 23:29:47 +080088 return Status("kernel version < 4.9.0 is unsupported");
Ken Chen5d146492023-11-27 17:05:43 +080089 }
Maciej Żenczykowskic2dd01c2023-09-01 21:02:36 +000090
91 // U bumps the kernel requirement up to 4.14
Ken Chen5d146492023-11-27 17:05:43 +080092 if (modules::sdklevel::IsAtLeastU() && !bpf::isAtLeastKernelVersion(4, 14, 0)) {
Ken Chend6ea75a2023-11-28 23:29:47 +080093 return Status("U+ platform with kernel version < 4.14.0 is unsupported");
Ken Chen5d146492023-11-27 17:05:43 +080094 }
Maciej Żenczykowskic2dd01c2023-09-01 21:02:36 +000095
Maciej Żenczykowskic2dd01c2023-09-01 21:02:36 +000096 // U mandates this mount point (though it should also be the case on T)
Ken Chen5d146492023-11-27 17:05:43 +080097 if (modules::sdklevel::IsAtLeastU() && !!strcmp(cg2_path, "/sys/fs/cgroup")) {
Ken Chend6ea75a2023-11-28 23:29:47 +080098 return Status("U+ platform with cg2_path != /sys/fs/cgroup is unsupported");
Ken Chen5d146492023-11-27 17:05:43 +080099 }
Maciej Żenczykowski65075bb2023-06-01 23:09:14 +0000100
Maciej Żenczykowski1758f412025-01-13 12:18:47 -0800101 // V bumps the kernel requirement up to 4.19
102 if (modules::sdklevel::IsAtLeastV() && !bpf::isAtLeastKernelVersion(4, 19, 0)) {
103 return Status("V+ platform with kernel version < 4.19.0 is unsupported");
104 }
105
106 // 25Q2 bumps the kernel requirement up to 5.4
107 if (isAtLeast25Q2() && !bpf::isAtLeastKernelVersion(5, 4, 0)) {
108 return Status("25Q2+ platform with kernel version < 5.4.0 is unsupported");
109 }
110
Ken Chen1647f602021-10-05 21:55:22 +0800111 unique_fd cg_fd(open(cg2_path, O_DIRECTORY | O_RDONLY | O_CLOEXEC));
Maciej Żenczykowski25824452023-06-14 10:08:31 +0000112 if (!cg_fd.ok()) {
113 const int err = errno;
114 ALOGE("Failed to open the cgroup directory: %s", strerror(err));
115 return statusFromErrno(err, "Open the cgroup directory failed");
Ken Chen1647f602021-10-05 21:55:22 +0800116 }
Maciej Żenczykowskieb85ea52024-11-20 19:32:07 +0000117
Maciej Żenczykowskic576c0d2022-08-07 22:18:15 +0000118 RETURN_IF_NOT_OK(checkProgramAccessible(XT_BPF_ALLOWLIST_PROG_PATH));
119 RETURN_IF_NOT_OK(checkProgramAccessible(XT_BPF_DENYLIST_PROG_PATH));
120 RETURN_IF_NOT_OK(checkProgramAccessible(XT_BPF_EGRESS_PROG_PATH));
121 RETURN_IF_NOT_OK(checkProgramAccessible(XT_BPF_INGRESS_PROG_PATH));
Ken Chen1647f602021-10-05 21:55:22 +0800122 RETURN_IF_NOT_OK(attachProgramToCgroup(BPF_EGRESS_PROG_PATH, cg_fd, BPF_CGROUP_INET_EGRESS));
123 RETURN_IF_NOT_OK(attachProgramToCgroup(BPF_INGRESS_PROG_PATH, cg_fd, BPF_CGROUP_INET_INGRESS));
Lorenzo Colitti3505b582022-10-27 19:36:27 +0900124
125 // For the devices that support cgroup socket filter, the socket filter
126 // should be loaded successfully by bpfloader. So we attach the filter to
127 // cgroup if the program is pinned properly.
128 // TODO: delete the if statement once all devices should support cgroup
129 // socket filter (ie. the minimum kernel version required is 4.14).
Maciej Żenczykowski03093622023-02-22 22:09:25 +0000130 if (bpf::isAtLeastKernelVersion(4, 14, 0)) {
Maciej Żenczykowski22db5902024-05-10 06:44:08 -0700131 RETURN_IF_NOT_OK(attachProgramToCgroup(CGROUP_INET_CREATE_PROG_PATH,
132 cg_fd, BPF_CGROUP_INET_SOCK_CREATE));
133 }
134
Maciej Żenczykowski6e945832024-09-23 20:20:36 +0000135 if (bpf::isAtLeastKernelVersion(5, 10, 0)) {
136 RETURN_IF_NOT_OK(attachProgramToCgroup(CGROUP_INET_RELEASE_PROG_PATH,
137 cg_fd, BPF_CGROUP_INET_SOCK_RELEASE));
138 }
139
Maciej Żenczykowski22db5902024-05-10 06:44:08 -0700140 if (modules::sdklevel::IsAtLeastV()) {
LuK13372918f062024-11-04 18:41:05 +0100141 // V requires 4.19+, so technically this 2nd 'if' is not required, but it
142 // doesn't hurt us to try to support AOSP forks that try to support older kernels.
143 if (bpf::isAtLeastKernelVersion(4, 19, 0)) {
144 RETURN_IF_NOT_OK(attachProgramToCgroup(CGROUP_CONNECT4_PROG_PATH,
145 cg_fd, BPF_CGROUP_INET4_CONNECT));
146 RETURN_IF_NOT_OK(attachProgramToCgroup(CGROUP_CONNECT6_PROG_PATH,
147 cg_fd, BPF_CGROUP_INET6_CONNECT));
148 RETURN_IF_NOT_OK(attachProgramToCgroup(CGROUP_UDP4_RECVMSG_PROG_PATH,
149 cg_fd, BPF_CGROUP_UDP4_RECVMSG));
150 RETURN_IF_NOT_OK(attachProgramToCgroup(CGROUP_UDP6_RECVMSG_PROG_PATH,
151 cg_fd, BPF_CGROUP_UDP6_RECVMSG));
152 RETURN_IF_NOT_OK(attachProgramToCgroup(CGROUP_UDP4_SENDMSG_PROG_PATH,
153 cg_fd, BPF_CGROUP_UDP4_SENDMSG));
154 RETURN_IF_NOT_OK(attachProgramToCgroup(CGROUP_UDP6_SENDMSG_PROG_PATH,
155 cg_fd, BPF_CGROUP_UDP6_SENDMSG));
156 }
Maciej Żenczykowski05ebcf02024-06-18 17:49:19 -0700157
158 if (bpf::isAtLeastKernelVersion(5, 4, 0)) {
Maciej Żenczykowski22db5902024-05-10 06:44:08 -0700159 RETURN_IF_NOT_OK(attachProgramToCgroup(CGROUP_GETSOCKOPT_PROG_PATH,
160 cg_fd, BPF_CGROUP_GETSOCKOPT));
161 RETURN_IF_NOT_OK(attachProgramToCgroup(CGROUP_SETSOCKOPT_PROG_PATH,
162 cg_fd, BPF_CGROUP_SETSOCKOPT));
Maciej Żenczykowski05ebcf02024-06-18 17:49:19 -0700163 }
Lorenzo Colitti3505b582022-10-27 19:36:27 +0900164 }
Maciej Żenczykowski5b2611d2023-10-04 00:44:56 +0000165
Maciej Żenczykowski5b2611d2023-10-04 00:44:56 +0000166 if (bpf::isAtLeastKernelVersion(4, 19, 0)) {
Maciej Żenczykowski3ad37942024-09-19 00:13:04 +0000167 RETURN_IF_NOT_OK(attachProgramToCgroup(CGROUP_BIND4_PROG_PATH,
Maciej Żenczykowski3cb494f2023-10-04 21:35:41 +0000168 cg_fd, BPF_CGROUP_INET4_BIND));
Maciej Żenczykowski3ad37942024-09-19 00:13:04 +0000169 RETURN_IF_NOT_OK(attachProgramToCgroup(CGROUP_BIND6_PROG_PATH,
Maciej Żenczykowski3cb494f2023-10-04 21:35:41 +0000170 cg_fd, BPF_CGROUP_INET6_BIND));
171
172 // This should trivially pass, since we just attached up above,
173 // but BPF_PROG_QUERY is only implemented on 4.19+ kernels.
Maciej Żenczykowski5b2611d2023-10-04 00:44:56 +0000174 if (bpf::queryProgram(cg_fd, BPF_CGROUP_INET_EGRESS) <= 0) abort();
175 if (bpf::queryProgram(cg_fd, BPF_CGROUP_INET_INGRESS) <= 0) abort();
176 if (bpf::queryProgram(cg_fd, BPF_CGROUP_INET_SOCK_CREATE) <= 0) abort();
Maciej Żenczykowski3cb494f2023-10-04 21:35:41 +0000177 if (bpf::queryProgram(cg_fd, BPF_CGROUP_INET4_BIND) <= 0) abort();
178 if (bpf::queryProgram(cg_fd, BPF_CGROUP_INET6_BIND) <= 0) abort();
Maciej Żenczykowski5b2611d2023-10-04 00:44:56 +0000179 }
180
Maciej Żenczykowski6e945832024-09-23 20:20:36 +0000181 if (bpf::isAtLeastKernelVersion(5, 10, 0)) {
182 if (bpf::queryProgram(cg_fd, BPF_CGROUP_INET_SOCK_RELEASE) <= 0) abort();
183 }
184
Maciej Żenczykowski22db5902024-05-10 06:44:08 -0700185 if (modules::sdklevel::IsAtLeastV()) {
LuK13372918f062024-11-04 18:41:05 +0100186 // V requires 4.19+, so technically this 2nd 'if' is not required, but it
187 // doesn't hurt us to try to support AOSP forks that try to support older kernels.
188 if (bpf::isAtLeastKernelVersion(4, 19, 0)) {
189 if (bpf::queryProgram(cg_fd, BPF_CGROUP_INET4_CONNECT) <= 0) abort();
190 if (bpf::queryProgram(cg_fd, BPF_CGROUP_INET6_CONNECT) <= 0) abort();
191 if (bpf::queryProgram(cg_fd, BPF_CGROUP_UDP4_RECVMSG) <= 0) abort();
192 if (bpf::queryProgram(cg_fd, BPF_CGROUP_UDP6_RECVMSG) <= 0) abort();
193 if (bpf::queryProgram(cg_fd, BPF_CGROUP_UDP4_SENDMSG) <= 0) abort();
194 if (bpf::queryProgram(cg_fd, BPF_CGROUP_UDP6_SENDMSG) <= 0) abort();
195 }
Maciej Żenczykowski05ebcf02024-06-18 17:49:19 -0700196
197 if (bpf::isAtLeastKernelVersion(5, 4, 0)) {
Maciej Żenczykowski22db5902024-05-10 06:44:08 -0700198 if (bpf::queryProgram(cg_fd, BPF_CGROUP_GETSOCKOPT) <= 0) abort();
199 if (bpf::queryProgram(cg_fd, BPF_CGROUP_SETSOCKOPT) <= 0) abort();
Maciej Żenczykowski05ebcf02024-06-18 17:49:19 -0700200 }
Maciej Żenczykowski22db5902024-05-10 06:44:08 -0700201 }
202
Ken Chen1647f602021-10-05 21:55:22 +0800203 return netdutils::status::ok;
204}
205
206BpfHandler::BpfHandler()
207 : mPerUidStatsEntriesLimit(PER_UID_STATS_ENTRIES_LIMIT),
208 mTotalUidStatsEntriesLimit(TOTAL_UID_STATS_ENTRIES_LIMIT) {}
209
210BpfHandler::BpfHandler(uint32_t perUidLimit, uint32_t totalLimit)
211 : mPerUidStatsEntriesLimit(perUidLimit), mTotalUidStatsEntriesLimit(totalLimit) {}
212
Maciej Żenczykowski15f97312024-06-13 14:11:28 -0700213static bool mainlineNetBpfLoadDone() {
214 return !access("/sys/fs/bpf/netd_shared/mainline_done", F_OK);
215}
216
Maciej Żenczykowski732a1412024-03-14 00:17:18 -0700217// copied with minor changes from waitForProgsLoaded()
218// p/m/C's staticlibs/native/bpf_headers/include/bpf/WaitForProgsLoaded.h
219static inline void waitForNetProgsLoaded() {
220 // infinite loop until success with 5/10/20/40/60/60/60... delay
221 for (int delay = 5;; delay *= 2) {
222 if (delay > 60) delay = 60;
Maciej Żenczykowski15f97312024-06-13 14:11:28 -0700223 if (WaitForProperty("init.svc.mdnsd_netbpfload", "stopped", std::chrono::seconds(delay))
224 && mainlineNetBpfLoadDone())
Maciej Żenczykowski732a1412024-03-14 00:17:18 -0700225 return;
Maciej Żenczykowski15f97312024-06-13 14:11:28 -0700226 ALOGW("Waited %ds for init.svc.mdnsd_netbpfload=stopped, still waiting...", delay);
Maciej Żenczykowski732a1412024-03-14 00:17:18 -0700227 }
228}
229
Maciej Żenczykowski23c02b02024-10-02 22:48:19 +0000230static inline void waitForBpf() {
Maciej Żenczykowski15f97312024-06-13 14:11:28 -0700231 // Note: netd *can* be restarted, so this might get called a second time after boot is complete
232 // at which point we don't need to (and shouldn't) wait for (more importantly start) loading bpf
233
Maciej Żenczykowski23d2c1e2024-03-28 22:54:01 -0700234 if (base::GetProperty("bpf.progs_loaded", "") != "1") {
Maciej Żenczykowski15f97312024-06-13 14:11:28 -0700235 // AOSP platform netd & mainline don't need this (at least prior to U QPR3),
236 // but there could be platform provided (xt_)bpf programs that oem/vendor
237 // modified netd (which calls us during init) depends on...
238 ALOGI("Waiting for platform BPF programs");
Maciej Żenczykowski23d2c1e2024-03-28 22:54:01 -0700239 android::bpf::waitForProgsLoaded();
Maciej Żenczykowski732a1412024-03-14 00:17:18 -0700240 }
Maciej Żenczykowski15f97312024-06-13 14:11:28 -0700241
Maciej Żenczykowski4e4f8722024-06-15 06:38:08 -0700242 if (!mainlineNetBpfLoadDone()) {
Maciej Żenczykowski72628992024-06-14 13:46:11 -0700243 // We're on < U QPR3 & it's the first time netd is starting up (unless crashlooping)
244 //
245 // On U QPR3+ netbpfload is guaranteed to run before the platform bpfloader,
246 // so waitForProgsLoaded() implies mainlineNetBpfLoadDone().
Maciej Żenczykowski15f97312024-06-13 14:11:28 -0700247 if (!base::SetProperty("ctl.start", "mdnsd_netbpfload")) {
248 ALOGE("Failed to set property ctl.start=mdnsd_netbpfload, see dmesg for reason.");
Maciej Żenczykowski2afffc22024-06-15 06:37:03 -0700249 abort();
Maciej Żenczykowski15f97312024-06-13 14:11:28 -0700250 }
251
Maciej Żenczykowski2afffc22024-06-15 06:37:03 -0700252 ALOGI("Waiting for Networking BPF programs");
253 waitForNetProgsLoaded();
254 ALOGI("Networking BPF programs are loaded");
Maciej Żenczykowski15f97312024-06-13 14:11:28 -0700255 }
256
Ken Chen1647f602021-10-05 21:55:22 +0800257 ALOGI("BPF programs are loaded");
Maciej Żenczykowski23c02b02024-10-02 22:48:19 +0000258}
259
260Status BpfHandler::init(const char* cg2_path) {
261 // This wait is effectively a no-op on U QPR3+ devices (as netd starts
Maciej Żenczykowskie6113242024-10-03 18:42:18 +0000262 // *after* the synchronous 'exec_start bpfloader' which calls NetBpfLoad)
Maciej Żenczykowski23c02b02024-10-02 22:48:19 +0000263 // but checking for U QPR3 is hard.
264 //
265 // Waiting should not be required on U QPR3+ devices,
266 // ...
267 //
268 // ...unless someone changed 'exec_start bpfloader' to 'start bpfloader'
269 // in the rc file.
270 //
271 // TODO: should be: if (!modules::sdklevel::IsAtLeastW())
272 if (android_get_device_api_level() <= __ANDROID_API_V__) waitForBpf();
Ken Chen1647f602021-10-05 21:55:22 +0800273
274 RETURN_IF_NOT_OK(initPrograms(cg2_path));
275 RETURN_IF_NOT_OK(initMaps());
276
277 return netdutils::status::ok;
278}
279
Maciej Żenczykowski52018c82024-06-04 16:05:16 +0000280static void mapLockTest(void) {
281 // The maps must be R/W, and as yet unopened (or more specifically not yet lock'ed).
282 const char * const m1 = BPF_NETD_PATH "map_netd_lock_array_test_map";
283 const char * const m2 = BPF_NETD_PATH "map_netd_lock_hash_test_map";
284
Maciej Żenczykowski7eb7d672024-06-14 13:55:09 -0700285 unique_fd fd0(bpf::mapRetrieveExclusiveRW(m1)); if (!fd0.ok()) abort(); // grabs exclusive lock
Maciej Żenczykowski52018c82024-06-04 16:05:16 +0000286
287 unique_fd fd1(bpf::mapRetrieveExclusiveRW(m2)); if (!fd1.ok()) abort(); // no conflict with fd0
288 unique_fd fd2(bpf::mapRetrieveExclusiveRW(m2)); if ( fd2.ok()) abort(); // busy due to fd1
289 unique_fd fd3(bpf::mapRetrieveRO(m2)); if (!fd3.ok()) abort(); // no lock taken
290 unique_fd fd4(bpf::mapRetrieveRW(m2)); if ( fd4.ok()) abort(); // busy due to fd1
291 fd1.reset(); // releases exclusive lock
292 unique_fd fd5(bpf::mapRetrieveRO(m2)); if (!fd5.ok()) abort(); // no lock taken
293 unique_fd fd6(bpf::mapRetrieveRW(m2)); if (!fd6.ok()) abort(); // now ok
294 unique_fd fd7(bpf::mapRetrieveRO(m2)); if (!fd7.ok()) abort(); // no lock taken
295 unique_fd fd8(bpf::mapRetrieveExclusiveRW(m2)); if ( fd8.ok()) abort(); // busy due to fd6
Maciej Żenczykowski7eb7d672024-06-14 13:55:09 -0700296
297 fd0.reset(); // releases exclusive lock
298 unique_fd fd9(bpf::mapRetrieveWO(m1)); if (!fd9.ok()) abort(); // grabs exclusive lock
Maciej Żenczykowski52018c82024-06-04 16:05:16 +0000299}
300
Ken Chen1647f602021-10-05 21:55:22 +0800301Status BpfHandler::initMaps() {
Patrick Rohr78ad0032024-06-28 00:25:50 +0000302 // bpfLock() requires bpfGetFdMapId which is only available on 4.14+ kernels.
303 if (bpf::isAtLeastKernelVersion(4, 14, 0)) {
304 mapLockTest();
305 }
Maciej Żenczykowski52018c82024-06-04 16:05:16 +0000306
Ken Chen1647f602021-10-05 21:55:22 +0800307 RETURN_IF_NOT_OK(mStatsMapA.init(STATS_MAP_A_PATH));
308 RETURN_IF_NOT_OK(mStatsMapB.init(STATS_MAP_B_PATH));
309 RETURN_IF_NOT_OK(mConfigurationMap.init(CONFIGURATION_MAP_PATH));
Ken Chen1647f602021-10-05 21:55:22 +0800310 RETURN_IF_NOT_OK(mUidPermissionMap.init(UID_PERMISSION_MAP_PATH));
Maciej Żenczykowskib5868a02022-08-31 04:21:01 +0000311 // initialized last so mCookieTagMap.isValid() implies everything else is valid too
312 RETURN_IF_NOT_OK(mCookieTagMap.init(COOKIE_TAG_MAP_PATH));
Ken Chen322ffcb2022-05-23 22:27:40 +0800313 ALOGI("%s successfully", __func__);
Ken Chen1647f602021-10-05 21:55:22 +0800314
315 return netdutils::status::ok;
316}
317
318bool BpfHandler::hasUpdateDeviceStatsPermission(uid_t uid) {
319 // This implementation is the same logic as method ActivityManager#checkComponentPermission.
320 // It implies that the real uid can never be the same as PER_USER_RANGE.
321 uint32_t appId = uid % PER_USER_RANGE;
322 auto permission = mUidPermissionMap.readValue(appId);
323 if (permission.ok() && (permission.value() & BPF_PERMISSION_UPDATE_DEVICE_STATS)) {
324 return true;
325 }
326 return ((appId == AID_ROOT) || (appId == AID_SYSTEM) || (appId == AID_DNS));
327}
328
329int BpfHandler::tagSocket(int sockFd, uint32_t tag, uid_t chargeUid, uid_t realUid) {
Maciej Żenczykowski4938d402022-08-14 14:36:20 +0000330 if (!mCookieTagMap.isValid()) return -EPERM;
331
332 if (chargeUid != realUid && !hasUpdateDeviceStatsPermission(realUid)) return -EPERM;
Ken Chen1647f602021-10-05 21:55:22 +0800333
Hungming Chen436547e2022-02-18 17:52:11 +0800334 // Note that tagging the socket to AID_CLAT is only implemented in JNI ClatCoordinator.
335 // The process is not allowed to tag socket to AID_CLAT via tagSocket() which would cause
336 // process data usage accounting to be bypassed. Tagging AID_CLAT is used for avoiding counting
337 // CLAT traffic data usage twice. See packages/modules/Connectivity/service/jni/
338 // com_android_server_connectivity_ClatCoordinator.cpp
Maciej Żenczykowski4938d402022-08-14 14:36:20 +0000339 if (chargeUid == AID_CLAT) return -EPERM;
Hungming Chen436547e2022-02-18 17:52:11 +0800340
Hungming Chen478c0eb2022-03-04 21:16:59 +0800341 // The socket destroy listener only monitors on the group {INET_TCP, INET_UDP, INET6_TCP,
342 // INET6_UDP}. Tagging listener unsupported socket causes that the tag can't be removed from
343 // tag map automatically. Eventually, the tag map may run out of space because of dead tag
Hungming Chenbcc0f5b2022-03-07 14:13:49 +0800344 // entries. Note that although tagSocket() of net client has already denied the family which
345 // is neither AF_INET nor AF_INET6, the family validation is still added here just in case.
346 // See tagSocket in system/netd/client/NetdClient.cpp and
347 // TrafficController::makeSkDestroyListener in
Hungming Chen478c0eb2022-03-04 21:16:59 +0800348 // packages/modules/Connectivity/service/native/TrafficController.cpp
349 // TODO: remove this once the socket destroy listener can detect more types of socket destroy.
Hungming Chenbcc0f5b2022-03-07 14:13:49 +0800350 int socketFamily;
351 socklen_t familyLen = sizeof(socketFamily);
352 if (getsockopt(sockFd, SOL_SOCKET, SO_DOMAIN, &socketFamily, &familyLen)) {
353 ALOGE("Failed to getsockopt SO_DOMAIN: %s, fd: %d", strerror(errno), sockFd);
Hungming Chen478c0eb2022-03-04 21:16:59 +0800354 return -errno;
Hungming Chenbcc0f5b2022-03-07 14:13:49 +0800355 }
356 if (socketFamily != AF_INET && socketFamily != AF_INET6) {
357 ALOGE("Unsupported family: %d", socketFamily);
358 return -EAFNOSUPPORT;
359 }
360
361 int socketProto;
362 socklen_t protoLen = sizeof(socketProto);
363 if (getsockopt(sockFd, SOL_SOCKET, SO_PROTOCOL, &socketProto, &protoLen)) {
364 ALOGE("Failed to getsockopt SO_PROTOCOL: %s, fd: %d", strerror(errno), sockFd);
365 return -errno;
366 }
367 if (socketProto != IPPROTO_UDP && socketProto != IPPROTO_TCP) {
368 ALOGE("Unsupported protocol: %d", socketProto);
369 return -EPROTONOSUPPORT;
Hungming Chen478c0eb2022-03-04 21:16:59 +0800370 }
371
Ken Chen1647f602021-10-05 21:55:22 +0800372 uint64_t sock_cookie = getSocketCookie(sockFd);
Maciej Żenczykowskid3fe1542023-02-23 03:56:45 +0000373 if (!sock_cookie) return -errno;
Maciej Żenczykowski4938d402022-08-14 14:36:20 +0000374
Ken Chen1647f602021-10-05 21:55:22 +0800375 UidTagValue newKey = {.uid = (uint32_t)chargeUid, .tag = tag};
376
377 uint32_t totalEntryCount = 0;
378 uint32_t perUidEntryCount = 0;
379 // Now we go through the stats map and count how many entries are associated
380 // with chargeUid. If the uid entry hit the limit for each chargeUid, we block
Maciej Żenczykowskib5868a02022-08-31 04:21:01 +0000381 // the request to prevent the map from overflow. Note though that it isn't really
382 // safe here to iterate over the map since it might be modified by the system server,
383 // which might toggle the live stats map and clean it.
Ken Chen1647f602021-10-05 21:55:22 +0800384 const auto countUidStatsEntries = [chargeUid, &totalEntryCount, &perUidEntryCount](
385 const StatsKey& key,
Maciej Żenczykowski7e2f53e2023-09-28 01:08:28 +0000386 const BpfMapRO<StatsKey, StatsValue>&) {
Ken Chen1647f602021-10-05 21:55:22 +0800387 if (key.uid == chargeUid) {
388 perUidEntryCount++;
389 }
390 totalEntryCount++;
391 return base::Result<void>();
392 };
393 auto configuration = mConfigurationMap.readValue(CURRENT_STATS_MAP_CONFIGURATION_KEY);
394 if (!configuration.ok()) {
Maciej Żenczykowski85d4a5e2023-08-20 16:41:50 +0000395 ALOGE("Failed to get current configuration: %s",
396 strerror(configuration.error().code()));
Ken Chen1647f602021-10-05 21:55:22 +0800397 return -configuration.error().code();
398 }
399 if (configuration.value() != SELECT_MAP_A && configuration.value() != SELECT_MAP_B) {
400 ALOGE("unknown configuration value: %d", configuration.value());
401 return -EINVAL;
402 }
403
Maciej Żenczykowski7e2f53e2023-09-28 01:08:28 +0000404 BpfMapRO<StatsKey, StatsValue>& currentMap =
Ken Chen1647f602021-10-05 21:55:22 +0800405 (configuration.value() == SELECT_MAP_A) ? mStatsMapA : mStatsMapB;
406 base::Result<void> res = currentMap.iterate(countUidStatsEntries);
407 if (!res.ok()) {
Maciej Żenczykowski85d4a5e2023-08-20 16:41:50 +0000408 ALOGE("Failed to count the stats entry in map: %s",
Ken Chen1647f602021-10-05 21:55:22 +0800409 strerror(res.error().code()));
410 return -res.error().code();
411 }
412
413 if (totalEntryCount > mTotalUidStatsEntriesLimit ||
414 perUidEntryCount > mPerUidStatsEntriesLimit) {
415 ALOGE("Too many stats entries in the map, total count: %u, chargeUid(%u) count: %u,"
416 " blocking tag request to prevent map overflow",
417 totalEntryCount, chargeUid, perUidEntryCount);
418 return -EMFILE;
419 }
420 // Update the tag information of a socket to the cookieUidMap. Use BPF_ANY
421 // flag so it will insert a new entry to the map if that value doesn't exist
Maciej Żenczykowskib5868a02022-08-31 04:21:01 +0000422 // yet and update the tag if there is already a tag stored. Since the eBPF
Ken Chen1647f602021-10-05 21:55:22 +0800423 // program in kernel only read this map, and is protected by rcu read lock. It
Maciej Żenczykowskib5868a02022-08-31 04:21:01 +0000424 // should be fine to concurrently update the map while eBPF program is running.
Ken Chen1647f602021-10-05 21:55:22 +0800425 res = mCookieTagMap.writeValue(sock_cookie, newKey, BPF_ANY);
426 if (!res.ok()) {
Maciej Żenczykowski85d4a5e2023-08-20 16:41:50 +0000427 ALOGE("Failed to tag the socket: %s", strerror(res.error().code()));
Ken Chen1647f602021-10-05 21:55:22 +0800428 return -res.error().code();
429 }
Nick Wille5076a022023-06-01 18:39:25 +0000430 ALOGD("Socket with cookie %" PRIu64 " tagged successfully with tag %" PRIu32 " uid %u "
431 "and real uid %u", sock_cookie, tag, chargeUid, realUid);
Ken Chen1647f602021-10-05 21:55:22 +0800432 return 0;
433}
434
435int BpfHandler::untagSocket(int sockFd) {
Maciej Żenczykowski4938d402022-08-14 14:36:20 +0000436 uint64_t sock_cookie = getSocketCookie(sockFd);
Maciej Żenczykowskid3fe1542023-02-23 03:56:45 +0000437 if (!sock_cookie) return -errno;
Maciej Żenczykowski4938d402022-08-14 14:36:20 +0000438
439 if (!mCookieTagMap.isValid()) return -EPERM;
Ken Chen1647f602021-10-05 21:55:22 +0800440 base::Result<void> res = mCookieTagMap.deleteValue(sock_cookie);
441 if (!res.ok()) {
Maciej Żenczykowskie0f58462022-05-17 13:59:22 -0700442 ALOGE("Failed to untag socket: %s", strerror(res.error().code()));
Ken Chen1647f602021-10-05 21:55:22 +0800443 return -res.error().code();
444 }
Nick Wille5076a022023-06-01 18:39:25 +0000445 ALOGD("Socket with cookie %" PRIu64 " untagged successfully.", sock_cookie);
Ken Chen1647f602021-10-05 21:55:22 +0800446 return 0;
447}
448
449} // namespace net
450} // namespace android