blob: f353ec1b4decc0ec6770f709c7077d588cafae32 [file] [log] [blame]
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07001/*
Maciej Żenczykowski283c25a2023-10-02 19:43:30 -07002 * Copyright (C) 2017-2023 The Android Open Source Project
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -07003 *
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#ifndef LOG_TAG
Maciej Żenczykowski283c25a2023-10-02 19:43:30 -070018#define LOG_TAG "NetBpfLoad"
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -070019#endif
20
21#include <arpa/inet.h>
22#include <dirent.h>
23#include <elf.h>
24#include <error.h>
25#include <fcntl.h>
26#include <inttypes.h>
27#include <linux/bpf.h>
28#include <linux/unistd.h>
29#include <net/if.h>
30#include <stdint.h>
31#include <stdio.h>
32#include <stdlib.h>
33#include <string.h>
34#include <unistd.h>
35
36#include <sys/mman.h>
37#include <sys/socket.h>
38#include <sys/stat.h>
39#include <sys/types.h>
40
Maciej Żenczykowskif33f1282023-10-24 04:41:54 -070041#include <android/api-level.h>
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -070042#include <android-base/logging.h>
43#include <android-base/macros.h>
44#include <android-base/properties.h>
45#include <android-base/stringprintf.h>
46#include <android-base/strings.h>
47#include <android-base/unique_fd.h>
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -070048#include <log/log.h>
Maciej Żenczykowski40dfe532023-10-08 20:21:11 -070049
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -070050#include "BpfSyscallWrappers.h"
51#include "bpf/BpfUtils.h"
Maciej Żenczykowski40dfe532023-10-08 20:21:11 -070052#include "loader.h"
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -070053
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -070054namespace android {
55namespace bpf {
56
57using base::EndsWith;
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -070058using std::string;
59
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -070060static bool exists(const char* const path) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -070061 int v = access(path, F_OK);
62 if (!v) {
63 ALOGI("%s exists.", path);
64 return true;
65 }
66 if (errno == ENOENT) return false;
67 ALOGE("FATAL: access(%s, F_OK) -> %d [%d:%s]", path, v, errno, strerror(errno));
68 abort(); // can only hit this if permissions (likely selinux) are screwed up
69}
70
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -070071
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -070072const Location locations[] = {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -070073 // S+ Tethering mainline module (network_stack): tether offload
74 {
75 .dir = "/apex/com.android.tethering/etc/bpf/",
76 .prefix = "tethering/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -070077 },
78 // T+ Tethering mainline module (shared with netd & system server)
79 // netutils_wrapper (for iptables xt_bpf) has access to programs
80 {
81 .dir = "/apex/com.android.tethering/etc/bpf/netd_shared/",
82 .prefix = "netd_shared/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -070083 },
84 // T+ Tethering mainline module (shared with netd & system server)
85 // netutils_wrapper has no access, netd has read only access
86 {
87 .dir = "/apex/com.android.tethering/etc/bpf/netd_readonly/",
88 .prefix = "netd_readonly/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -070089 },
90 // T+ Tethering mainline module (shared with system server)
91 {
92 .dir = "/apex/com.android.tethering/etc/bpf/net_shared/",
93 .prefix = "net_shared/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -070094 },
95 // T+ Tethering mainline module (not shared, just network_stack)
96 {
97 .dir = "/apex/com.android.tethering/etc/bpf/net_private/",
98 .prefix = "net_private/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -070099 },
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -0700100};
101
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -0700102static int loadAllElfObjects(const unsigned int bpfloader_ver, const Location& location) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -0700103 int retVal = 0;
104 DIR* dir;
105 struct dirent* ent;
106
107 if ((dir = opendir(location.dir)) != NULL) {
108 while ((ent = readdir(dir)) != NULL) {
109 string s = ent->d_name;
110 if (!EndsWith(s, ".o")) continue;
111
112 string progPath(location.dir);
113 progPath += s;
114
115 bool critical;
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -0700116 int ret = loadProg(progPath.c_str(), &critical, bpfloader_ver, location);
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -0700117 if (ret) {
118 if (critical) retVal = ret;
119 ALOGE("Failed to load object: %s, ret: %s", progPath.c_str(), std::strerror(-ret));
120 } else {
121 ALOGI("Loaded object: %s", progPath.c_str());
122 }
123 }
124 closedir(dir);
125 }
126 return retVal;
127}
128
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -0700129static int createSysFsBpfSubDir(const char* const prefix) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -0700130 if (*prefix) {
131 mode_t prevUmask = umask(0);
132
133 string s = "/sys/fs/bpf/";
134 s += prefix;
135
136 errno = 0;
137 int ret = mkdir(s.c_str(), S_ISVTX | S_IRWXU | S_IRWXG | S_IRWXO);
138 if (ret && errno != EEXIST) {
139 const int err = errno;
140 ALOGE("Failed to create directory: %s, ret: %s", s.c_str(), std::strerror(err));
141 return -err;
142 }
143
144 umask(prevUmask);
145 }
146 return 0;
147}
148
149// Technically 'value' doesn't need to be newline terminated, but it's best
150// to include a newline to match 'echo "value" > /proc/sys/...foo' behaviour,
151// which is usually how kernel devs test the actual sysctl interfaces.
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -0700152static int writeProcSysFile(const char *filename, const char *value) {
153 base::unique_fd fd(open(filename, O_WRONLY | O_CLOEXEC));
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -0700154 if (fd < 0) {
155 const int err = errno;
156 ALOGE("open('%s', O_WRONLY | O_CLOEXEC) -> %s", filename, strerror(err));
157 return -err;
158 }
159 int len = strlen(value);
160 int v = write(fd, value, len);
161 if (v < 0) {
162 const int err = errno;
163 ALOGE("write('%s', '%s', %d) -> %s", filename, value, len, strerror(err));
164 return -err;
165 }
166 if (v != len) {
167 // In practice, due to us only using this for /proc/sys/... files, this can't happen.
168 ALOGE("write('%s', '%s', %d) -> short write [%d]", filename, value, len, v);
169 return -EINVAL;
170 }
171 return 0;
172}
173
Maciej Żenczykowskib60599b2024-02-09 12:30:52 -0800174#define APEX_MOUNT_POINT "/apex/com.android.tethering"
Maciej Żenczykowski2fe2db52024-02-07 01:23:58 +0000175const char * const platformBpfLoader = "/system/bin/bpfloader";
Maciej Żenczykowskib60599b2024-02-09 12:30:52 -0800176
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -0700177static int logTetheringApexVersion(void) {
Maciej Żenczykowskib60599b2024-02-09 12:30:52 -0800178 char * found_blockdev = NULL;
179 FILE * f = NULL;
180 char buf[4096];
181
182 f = fopen("/proc/mounts", "re");
183 if (!f) return 1;
184
185 // /proc/mounts format: block_device [space] mount_point [space] other stuff... newline
186 while (fgets(buf, sizeof(buf), f)) {
187 char * blockdev = buf;
188 char * space = strchr(blockdev, ' ');
189 if (!space) continue;
190 *space = '\0';
191 char * mntpath = space + 1;
192 space = strchr(mntpath, ' ');
193 if (!space) continue;
194 *space = '\0';
195 if (strcmp(mntpath, APEX_MOUNT_POINT)) continue;
196 found_blockdev = strdup(blockdev);
197 break;
198 }
199 fclose(f);
200 f = NULL;
201
202 if (!found_blockdev) return 2;
203 ALOGD("Found Tethering Apex mounted from blockdev %s", found_blockdev);
204
205 f = fopen("/proc/mounts", "re");
206 if (!f) { free(found_blockdev); return 3; }
207
208 while (fgets(buf, sizeof(buf), f)) {
209 char * blockdev = buf;
210 char * space = strchr(blockdev, ' ');
211 if (!space) continue;
212 *space = '\0';
213 char * mntpath = space + 1;
214 space = strchr(mntpath, ' ');
215 if (!space) continue;
216 *space = '\0';
217 if (strcmp(blockdev, found_blockdev)) continue;
218 if (strncmp(mntpath, APEX_MOUNT_POINT "@", strlen(APEX_MOUNT_POINT "@"))) continue;
219 char * at = strchr(mntpath, '@');
220 if (!at) continue;
221 char * ver = at + 1;
222 ALOGI("Tethering APEX version %s", ver);
223 }
224 fclose(f);
225 free(found_blockdev);
226 return 0;
227}
Maciej Żenczykowski2fe2db52024-02-07 01:23:58 +0000228
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -0700229static int main(char** argv, char * const envp[]) {
230 base::InitLogging(argv, &base::KernelLogger);
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -0700231
Maciej Żenczykowski041be522023-10-23 23:34:52 -0700232 const int device_api_level = android_get_device_api_level();
233 const bool isAtLeastT = (device_api_level >= __ANDROID_API_T__);
234 const bool isAtLeastU = (device_api_level >= __ANDROID_API_U__);
235 const bool isAtLeastV = (device_api_level >= __ANDROID_API_V__);
236
Maciej Żenczykowski03ef12c2024-02-10 21:34:22 +0000237 // last in U QPR2 beta1
238 const bool has_platform_bpfloader_rc = exists("/system/etc/init/bpfloader.rc");
239 // first in U QPR2 beta~2
240 const bool has_platform_netbpfload_rc = exists("/system/etc/init/netbpfload.rc");
241
Maciej Żenczykowski4e5fb4a2024-04-26 14:56:15 -0700242 ALOGI("NetBpfLoad (%s) api:%d/%d kver:%07x (%s) rc:%d%d",
243 argv[0], android_get_application_target_sdk_version(), device_api_level,
Maciej Żenczykowski8b74cbb2024-04-26 12:15:00 -0700244 kernelVersion(), describeArch(),
Maciej Żenczykowski03ef12c2024-02-10 21:34:22 +0000245 has_platform_bpfloader_rc, has_platform_netbpfload_rc);
Maciej Żenczykowski041be522023-10-23 23:34:52 -0700246
Maciej Żenczykowski03ef12c2024-02-10 21:34:22 +0000247 if (!has_platform_bpfloader_rc && !has_platform_netbpfload_rc) {
248 ALOGE("Unable to find platform's bpfloader & netbpfload init scripts.");
249 return 1;
250 }
251
252 if (has_platform_bpfloader_rc && has_platform_netbpfload_rc) {
253 ALOGE("Platform has *both* bpfloader & netbpfload init scripts.");
254 return 1;
255 }
256
Maciej Żenczykowskib60599b2024-02-09 12:30:52 -0800257 logTetheringApexVersion();
258
Maciej Żenczykowski11141da2024-03-15 18:21:33 -0700259 if (!isAtLeastT) {
260 ALOGE("Impossible - not reachable on Android <T.");
Maciej Żenczykowski03ef12c2024-02-10 21:34:22 +0000261 return 1;
262 }
263
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -0700264 if (isAtLeastT && !isAtLeastKernelVersion(4, 9, 0)) {
Maciej Żenczykowski041be522023-10-23 23:34:52 -0700265 ALOGE("Android T requires kernel 4.9.");
266 return 1;
267 }
268
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -0700269 if (isAtLeastU && !isAtLeastKernelVersion(4, 14, 0)) {
Maciej Żenczykowski041be522023-10-23 23:34:52 -0700270 ALOGE("Android U requires kernel 4.14.");
271 return 1;
272 }
273
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -0700274 if (isAtLeastV && !isAtLeastKernelVersion(4, 19, 0)) {
Maciej Żenczykowski041be522023-10-23 23:34:52 -0700275 ALOGE("Android V requires kernel 4.19.");
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -0700276 return 1;
277 }
278
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -0700279 if (isAtLeastV && isX86() && !isKernel64Bit()) {
Maciej Żenczykowski7f6a4262024-02-17 00:42:42 +0000280 ALOGE("Android V requires X86 kernel to be 64-bit.");
281 return 1;
282 }
283
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -0700284 if (isUserspace32bit() && isAtLeastKernelVersion(6, 2, 0)) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -0700285 /* Android 14/U should only launch on 64-bit kernels
286 * T launches on 5.10/5.15
287 * U launches on 5.15/6.1
288 * So >=5.16 implies isKernel64Bit()
289 *
290 * We thus added a test to V VTS which requires 5.16+ devices to use 64-bit kernels.
291 *
292 * Starting with Android V, which is the first to support a post 6.1 Linux Kernel,
293 * we also require 64-bit userspace.
294 *
295 * There are various known issues with 32-bit userspace talking to various
296 * kernel interfaces (especially CAP_NET_ADMIN ones) on a 64-bit kernel.
297 * Some of these have userspace or kernel workarounds/hacks.
298 * Some of them don't...
299 * We're going to be removing the hacks.
300 *
301 * Additionally the 32-bit kernel jit support is poor,
302 * and 32-bit userspace on 64-bit kernel bpf ringbuffer compatibility is broken.
303 */
304 ALOGE("64-bit userspace required on 6.2+ kernels.");
305 return 1;
306 }
307
308 // Ensure we can determine the Android build type.
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -0700309 if (!isEng() && !isUser() && !isUserdebug()) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -0700310 ALOGE("Failed to determine the build type: got %s, want 'eng', 'user', or 'userdebug'",
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -0700311 getBuildType().c_str());
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -0700312 return 1;
313 }
314
Maciej Żenczykowski3218a812024-04-15 00:39:59 -0700315 if (isAtLeastV) {
Maciej Żenczykowskif33f1282023-10-24 04:41:54 -0700316 // Linux 5.16-rc1 changed the default to 2 (disabled but changeable),
317 // but we need 0 (enabled)
318 // (this writeFile is known to fail on at least 4.19, but always defaults to 0 on
319 // pre-5.13, on 5.13+ it depends on CONFIG_BPF_UNPRIV_DEFAULT_OFF)
320 if (writeProcSysFile("/proc/sys/kernel/unprivileged_bpf_disabled", "0\n") &&
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -0700321 isAtLeastKernelVersion(5, 13, 0)) return 1;
Maciej Żenczykowski732a1412024-03-14 00:17:18 -0700322 }
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -0700323
Maciej Żenczykowski732a1412024-03-14 00:17:18 -0700324 if (isAtLeastU) {
Maciej Żenczykowskif33f1282023-10-24 04:41:54 -0700325 // Enable the eBPF JIT -- but do note that on 64-bit kernels it is likely
326 // already force enabled by the kernel config option BPF_JIT_ALWAYS_ON.
327 // (Note: this (open) will fail with ENOENT 'No such file or directory' if
328 // kernel does not have CONFIG_BPF_JIT=y)
329 // BPF_JIT is required by R VINTF (which means 4.14/4.19/5.4 kernels),
330 // but 4.14/4.19 were released with P & Q, and only 5.4 is new in R+.
331 if (writeProcSysFile("/proc/sys/net/core/bpf_jit_enable", "1\n")) return 1;
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -0700332
Maciej Żenczykowskif33f1282023-10-24 04:41:54 -0700333 // Enable JIT kallsyms export for privileged users only
334 // (Note: this (open) will fail with ENOENT 'No such file or directory' if
335 // kernel does not have CONFIG_HAVE_EBPF_JIT=y)
336 if (writeProcSysFile("/proc/sys/net/core/bpf_jit_kallsyms", "1\n")) return 1;
337 }
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -0700338
339 // Create all the pin subdirectories
340 // (this must be done first to allow selinux_context and pin_subdir functionality,
341 // which could otherwise fail with ENOENT during object pinning or renaming,
342 // due to ordering issues)
343 for (const auto& location : locations) {
344 if (createSysFsBpfSubDir(location.prefix)) return 1;
345 }
346
Maciej Żenczykowskia9209da2024-02-29 02:01:20 +0000347 // Note: there's no actual src dir for fs_bpf_loader .o's,
348 // so it is not listed in 'locations[].prefix'.
349 // This is because this is primarily meant for triggering genfscon rules,
350 // and as such this will likely always be the case.
351 // Thus we need to manually create the /sys/fs/bpf/loader subdirectory.
352 if (createSysFsBpfSubDir("loader")) return 1;
353
Maciej Żenczykowski65f70222024-03-18 14:43:09 -0700354 // Version of Network BpfLoader depends on the Android OS version
355 unsigned int bpfloader_ver = 42u; // [42] BPFLOADER_MAINLINE_VERSION
356 if (isAtLeastT) ++bpfloader_ver; // [43] BPFLOADER_MAINLINE_T_VERSION
357 if (isAtLeastU) ++bpfloader_ver; // [44] BPFLOADER_MAINLINE_U_VERSION
358 if (isAtLeastV) ++bpfloader_ver; // [45] BPFLOADER_MAINLINE_V_VERSION
Maciej Żenczykowski221b2482024-03-18 14:33:10 -0700359
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -0700360 // Load all ELF objects, create programs and maps, and pin them
361 for (const auto& location : locations) {
Maciej Żenczykowski221b2482024-03-18 14:33:10 -0700362 if (loadAllElfObjects(bpfloader_ver, location) != 0) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -0700363 ALOGE("=== CRITICAL FAILURE LOADING BPF PROGRAMS FROM %s ===", location.dir);
364 ALOGE("If this triggers reliably, you're probably missing kernel options or patches.");
365 ALOGE("If this triggers randomly, you might be hitting some memory allocation "
366 "problems or startup script race.");
367 ALOGE("--- DO NOT EXPECT SYSTEM TO BOOT SUCCESSFULLY ---");
368 sleep(20);
369 return 2;
370 }
371 }
372
373 int key = 1;
374 int value = 123;
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -0700375 base::unique_fd map(
376 createMap(BPF_MAP_TYPE_ARRAY, sizeof(key), sizeof(value), 2, 0));
377 if (writeToMapEntry(map, &key, &value, BPF_ANY)) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -0700378 ALOGE("Critical kernel bug - failure to write into index 1 of 2 element bpf map array.");
379 return 1;
380 }
381
Maciej Żenczykowski3218a812024-04-15 00:39:59 -0700382 if (isAtLeastV) {
Maciej Żenczykowski732a1412024-03-14 00:17:18 -0700383 ALOGI("done, transferring control to platform bpfloader.");
Maciej Żenczykowski58c18222023-10-20 14:40:16 -0700384
Maciej Żenczykowski732a1412024-03-14 00:17:18 -0700385 const char * args[] = { platformBpfLoader, NULL, };
386 execve(args[0], (char**)args, envp);
387 ALOGE("FATAL: execve('%s'): %d[%s]", platformBpfLoader, errno, strerror(errno));
388 return 1;
389 }
390
391 ALOGI("mainline done!");
392 return 0;
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -0700393}
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -0700394
395} // namespace bpf
396} // namespace android
397
398int main(int __unused argc, char** argv, char * const envp[]) {
399 return android::bpf::main(argv, envp);
400}