blob: 20432f5d2cd6513dd8e3bf9a0a366ed4455dbd14 [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);
Maciej Żenczykowski731acfe2024-04-30 10:09:57 +000062 if (!v) return true;
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -070063 if (errno == ENOENT) return false;
64 ALOGE("FATAL: access(%s, F_OK) -> %d [%d:%s]", path, v, errno, strerror(errno));
65 abort(); // can only hit this if permissions (likely selinux) are screwed up
66}
67
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -070068
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -070069const Location locations[] = {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -070070 // S+ Tethering mainline module (network_stack): tether offload
71 {
72 .dir = "/apex/com.android.tethering/etc/bpf/",
73 .prefix = "tethering/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -070074 },
75 // T+ Tethering mainline module (shared with netd & system server)
76 // netutils_wrapper (for iptables xt_bpf) has access to programs
77 {
78 .dir = "/apex/com.android.tethering/etc/bpf/netd_shared/",
79 .prefix = "netd_shared/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -070080 },
81 // T+ Tethering mainline module (shared with netd & system server)
82 // netutils_wrapper has no access, netd has read only access
83 {
84 .dir = "/apex/com.android.tethering/etc/bpf/netd_readonly/",
85 .prefix = "netd_readonly/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -070086 },
87 // T+ Tethering mainline module (shared with system server)
88 {
89 .dir = "/apex/com.android.tethering/etc/bpf/net_shared/",
90 .prefix = "net_shared/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -070091 },
92 // T+ Tethering mainline module (not shared, just network_stack)
93 {
94 .dir = "/apex/com.android.tethering/etc/bpf/net_private/",
95 .prefix = "net_private/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -070096 },
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -070097};
98
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -070099static int loadAllElfObjects(const unsigned int bpfloader_ver, const Location& location) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -0700100 int retVal = 0;
101 DIR* dir;
102 struct dirent* ent;
103
104 if ((dir = opendir(location.dir)) != NULL) {
105 while ((ent = readdir(dir)) != NULL) {
106 string s = ent->d_name;
107 if (!EndsWith(s, ".o")) continue;
108
109 string progPath(location.dir);
110 progPath += s;
111
112 bool critical;
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -0700113 int ret = loadProg(progPath.c_str(), &critical, bpfloader_ver, location);
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -0700114 if (ret) {
115 if (critical) retVal = ret;
116 ALOGE("Failed to load object: %s, ret: %s", progPath.c_str(), std::strerror(-ret));
117 } else {
Maciej Żenczykowski5c057ed2024-04-30 11:59:13 +0000118 ALOGD("Loaded object: %s", progPath.c_str());
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -0700119 }
120 }
121 closedir(dir);
122 }
123 return retVal;
124}
125
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -0700126static int createSysFsBpfSubDir(const char* const prefix) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -0700127 if (*prefix) {
128 mode_t prevUmask = umask(0);
129
130 string s = "/sys/fs/bpf/";
131 s += prefix;
132
133 errno = 0;
134 int ret = mkdir(s.c_str(), S_ISVTX | S_IRWXU | S_IRWXG | S_IRWXO);
135 if (ret && errno != EEXIST) {
136 const int err = errno;
137 ALOGE("Failed to create directory: %s, ret: %s", s.c_str(), std::strerror(err));
138 return -err;
139 }
140
141 umask(prevUmask);
142 }
143 return 0;
144}
145
146// Technically 'value' doesn't need to be newline terminated, but it's best
147// to include a newline to match 'echo "value" > /proc/sys/...foo' behaviour,
148// which is usually how kernel devs test the actual sysctl interfaces.
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -0700149static int writeProcSysFile(const char *filename, const char *value) {
150 base::unique_fd fd(open(filename, O_WRONLY | O_CLOEXEC));
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -0700151 if (fd < 0) {
152 const int err = errno;
153 ALOGE("open('%s', O_WRONLY | O_CLOEXEC) -> %s", filename, strerror(err));
154 return -err;
155 }
156 int len = strlen(value);
157 int v = write(fd, value, len);
158 if (v < 0) {
159 const int err = errno;
160 ALOGE("write('%s', '%s', %d) -> %s", filename, value, len, strerror(err));
161 return -err;
162 }
163 if (v != len) {
164 // In practice, due to us only using this for /proc/sys/... files, this can't happen.
165 ALOGE("write('%s', '%s', %d) -> short write [%d]", filename, value, len, v);
166 return -EINVAL;
167 }
168 return 0;
169}
170
Maciej Żenczykowskib60599b2024-02-09 12:30:52 -0800171#define APEX_MOUNT_POINT "/apex/com.android.tethering"
Maciej Żenczykowski2fe2db52024-02-07 01:23:58 +0000172const char * const platformBpfLoader = "/system/bin/bpfloader";
Maciej Żenczykowskib60599b2024-02-09 12:30:52 -0800173
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -0700174static int logTetheringApexVersion(void) {
Maciej Żenczykowskib60599b2024-02-09 12:30:52 -0800175 char * found_blockdev = NULL;
176 FILE * f = NULL;
177 char buf[4096];
178
179 f = fopen("/proc/mounts", "re");
180 if (!f) return 1;
181
182 // /proc/mounts format: block_device [space] mount_point [space] other stuff... newline
183 while (fgets(buf, sizeof(buf), f)) {
184 char * blockdev = buf;
185 char * space = strchr(blockdev, ' ');
186 if (!space) continue;
187 *space = '\0';
188 char * mntpath = space + 1;
189 space = strchr(mntpath, ' ');
190 if (!space) continue;
191 *space = '\0';
192 if (strcmp(mntpath, APEX_MOUNT_POINT)) continue;
193 found_blockdev = strdup(blockdev);
194 break;
195 }
196 fclose(f);
197 f = NULL;
198
199 if (!found_blockdev) return 2;
Maciej Żenczykowski5c057ed2024-04-30 11:59:13 +0000200 ALOGV("Found Tethering Apex mounted from blockdev %s", found_blockdev);
Maciej Żenczykowskib60599b2024-02-09 12:30:52 -0800201
202 f = fopen("/proc/mounts", "re");
203 if (!f) { free(found_blockdev); return 3; }
204
205 while (fgets(buf, sizeof(buf), f)) {
206 char * blockdev = buf;
207 char * space = strchr(blockdev, ' ');
208 if (!space) continue;
209 *space = '\0';
210 char * mntpath = space + 1;
211 space = strchr(mntpath, ' ');
212 if (!space) continue;
213 *space = '\0';
214 if (strcmp(blockdev, found_blockdev)) continue;
215 if (strncmp(mntpath, APEX_MOUNT_POINT "@", strlen(APEX_MOUNT_POINT "@"))) continue;
216 char * at = strchr(mntpath, '@');
217 if (!at) continue;
218 char * ver = at + 1;
219 ALOGI("Tethering APEX version %s", ver);
220 }
221 fclose(f);
222 free(found_blockdev);
223 return 0;
224}
Maciej Żenczykowski2fe2db52024-02-07 01:23:58 +0000225
Maciej Żenczykowskic982a4b2024-04-25 23:04:09 -0700226static bool isGSI() {
227 // From //system/gsid/libgsi.cpp IsGsiRunning()
228 return !access("/metadata/gsi/dsu/booted", F_OK);
229}
230
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -0700231static int main(char** argv, char * const envp[]) {
232 base::InitLogging(argv, &base::KernelLogger);
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -0700233
Maciej Żenczykowski041be522023-10-23 23:34:52 -0700234 const int device_api_level = android_get_device_api_level();
235 const bool isAtLeastT = (device_api_level >= __ANDROID_API_T__);
236 const bool isAtLeastU = (device_api_level >= __ANDROID_API_U__);
237 const bool isAtLeastV = (device_api_level >= __ANDROID_API_V__);
238
Maciej Żenczykowski03ef12c2024-02-10 21:34:22 +0000239 // last in U QPR2 beta1
240 const bool has_platform_bpfloader_rc = exists("/system/etc/init/bpfloader.rc");
241 // first in U QPR2 beta~2
242 const bool has_platform_netbpfload_rc = exists("/system/etc/init/netbpfload.rc");
243
Maciej Żenczykowski4e5fb4a2024-04-26 14:56:15 -0700244 ALOGI("NetBpfLoad (%s) api:%d/%d kver:%07x (%s) rc:%d%d",
245 argv[0], android_get_application_target_sdk_version(), device_api_level,
Maciej Żenczykowski8b74cbb2024-04-26 12:15:00 -0700246 kernelVersion(), describeArch(),
Maciej Żenczykowski03ef12c2024-02-10 21:34:22 +0000247 has_platform_bpfloader_rc, has_platform_netbpfload_rc);
Maciej Żenczykowski041be522023-10-23 23:34:52 -0700248
Maciej Żenczykowski03ef12c2024-02-10 21:34:22 +0000249 if (!has_platform_bpfloader_rc && !has_platform_netbpfload_rc) {
250 ALOGE("Unable to find platform's bpfloader & netbpfload init scripts.");
251 return 1;
252 }
253
254 if (has_platform_bpfloader_rc && has_platform_netbpfload_rc) {
255 ALOGE("Platform has *both* bpfloader & netbpfload init scripts.");
256 return 1;
257 }
258
Maciej Żenczykowskib60599b2024-02-09 12:30:52 -0800259 logTetheringApexVersion();
260
Maciej Żenczykowski11141da2024-03-15 18:21:33 -0700261 if (!isAtLeastT) {
262 ALOGE("Impossible - not reachable on Android <T.");
Maciej Żenczykowski03ef12c2024-02-10 21:34:22 +0000263 return 1;
264 }
265
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -0700266 if (isAtLeastT && !isAtLeastKernelVersion(4, 9, 0)) {
Maciej Żenczykowski041be522023-10-23 23:34:52 -0700267 ALOGE("Android T requires kernel 4.9.");
268 return 1;
269 }
270
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -0700271 if (isAtLeastU && !isAtLeastKernelVersion(4, 14, 0)) {
Maciej Żenczykowski041be522023-10-23 23:34:52 -0700272 ALOGE("Android U requires kernel 4.14.");
273 return 1;
274 }
275
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -0700276 if (isAtLeastV && !isAtLeastKernelVersion(4, 19, 0)) {
Maciej Żenczykowski041be522023-10-23 23:34:52 -0700277 ALOGE("Android V requires kernel 4.19.");
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -0700278 return 1;
279 }
280
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -0700281 if (isAtLeastV && isX86() && !isKernel64Bit()) {
Maciej Żenczykowski7f6a4262024-02-17 00:42:42 +0000282 ALOGE("Android V requires X86 kernel to be 64-bit.");
283 return 1;
284 }
285
Maciej Żenczykowskic982a4b2024-04-25 23:04:09 -0700286 if (isAtLeastV) {
287 bool bad = false;
288
289 if (!isLtsKernel()) {
290 ALOGW("Android V only supports LTS kernels.");
291 bad = true;
292 }
293
294#define REQUIRE(maj, min, sub) \
295 if (isKernelVersion(maj, min) && !isAtLeastKernelVersion(maj, min, sub)) { \
296 ALOGW("Android V requires %d.%d kernel to be %d.%d.%d+.", maj, min, maj, min, sub); \
297 bad = true; \
298 }
299
300 REQUIRE(4, 19, 236)
301 REQUIRE(5, 4, 186)
302 REQUIRE(5, 10, 199)
303 REQUIRE(5, 15, 136)
304 REQUIRE(6, 1, 57)
305 REQUIRE(6, 6, 0)
306
307#undef REQUIRE
308
309 if (bad && !isGSI()) {
310 ALOGE("Unsupported kernel version (%07x).", kernelVersion());
311 }
312 }
313
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -0700314 if (isUserspace32bit() && isAtLeastKernelVersion(6, 2, 0)) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -0700315 /* Android 14/U should only launch on 64-bit kernels
316 * T launches on 5.10/5.15
317 * U launches on 5.15/6.1
318 * So >=5.16 implies isKernel64Bit()
319 *
320 * We thus added a test to V VTS which requires 5.16+ devices to use 64-bit kernels.
321 *
322 * Starting with Android V, which is the first to support a post 6.1 Linux Kernel,
323 * we also require 64-bit userspace.
324 *
325 * There are various known issues with 32-bit userspace talking to various
326 * kernel interfaces (especially CAP_NET_ADMIN ones) on a 64-bit kernel.
327 * Some of these have userspace or kernel workarounds/hacks.
328 * Some of them don't...
329 * We're going to be removing the hacks.
330 *
331 * Additionally the 32-bit kernel jit support is poor,
332 * and 32-bit userspace on 64-bit kernel bpf ringbuffer compatibility is broken.
333 */
334 ALOGE("64-bit userspace required on 6.2+ kernels.");
335 return 1;
336 }
337
338 // Ensure we can determine the Android build type.
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -0700339 if (!isEng() && !isUser() && !isUserdebug()) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -0700340 ALOGE("Failed to determine the build type: got %s, want 'eng', 'user', or 'userdebug'",
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -0700341 getBuildType().c_str());
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -0700342 return 1;
343 }
344
Maciej Żenczykowski3218a812024-04-15 00:39:59 -0700345 if (isAtLeastV) {
Maciej Żenczykowskif33f1282023-10-24 04:41:54 -0700346 // Linux 5.16-rc1 changed the default to 2 (disabled but changeable),
347 // but we need 0 (enabled)
348 // (this writeFile is known to fail on at least 4.19, but always defaults to 0 on
349 // pre-5.13, on 5.13+ it depends on CONFIG_BPF_UNPRIV_DEFAULT_OFF)
350 if (writeProcSysFile("/proc/sys/kernel/unprivileged_bpf_disabled", "0\n") &&
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -0700351 isAtLeastKernelVersion(5, 13, 0)) return 1;
Maciej Żenczykowski732a1412024-03-14 00:17:18 -0700352 }
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -0700353
Maciej Żenczykowski732a1412024-03-14 00:17:18 -0700354 if (isAtLeastU) {
Maciej Żenczykowskif33f1282023-10-24 04:41:54 -0700355 // Enable the eBPF JIT -- but do note that on 64-bit kernels it is likely
356 // already force enabled by the kernel config option BPF_JIT_ALWAYS_ON.
357 // (Note: this (open) will fail with ENOENT 'No such file or directory' if
358 // kernel does not have CONFIG_BPF_JIT=y)
359 // BPF_JIT is required by R VINTF (which means 4.14/4.19/5.4 kernels),
360 // but 4.14/4.19 were released with P & Q, and only 5.4 is new in R+.
361 if (writeProcSysFile("/proc/sys/net/core/bpf_jit_enable", "1\n")) return 1;
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -0700362
Maciej Żenczykowskif33f1282023-10-24 04:41:54 -0700363 // Enable JIT kallsyms export for privileged users only
364 // (Note: this (open) will fail with ENOENT 'No such file or directory' if
365 // kernel does not have CONFIG_HAVE_EBPF_JIT=y)
366 if (writeProcSysFile("/proc/sys/net/core/bpf_jit_kallsyms", "1\n")) return 1;
367 }
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -0700368
369 // Create all the pin subdirectories
370 // (this must be done first to allow selinux_context and pin_subdir functionality,
371 // which could otherwise fail with ENOENT during object pinning or renaming,
372 // due to ordering issues)
373 for (const auto& location : locations) {
374 if (createSysFsBpfSubDir(location.prefix)) return 1;
375 }
376
Maciej Żenczykowskia9209da2024-02-29 02:01:20 +0000377 // Note: there's no actual src dir for fs_bpf_loader .o's,
378 // so it is not listed in 'locations[].prefix'.
379 // This is because this is primarily meant for triggering genfscon rules,
380 // and as such this will likely always be the case.
381 // Thus we need to manually create the /sys/fs/bpf/loader subdirectory.
382 if (createSysFsBpfSubDir("loader")) return 1;
383
Maciej Żenczykowski65f70222024-03-18 14:43:09 -0700384 // Version of Network BpfLoader depends on the Android OS version
385 unsigned int bpfloader_ver = 42u; // [42] BPFLOADER_MAINLINE_VERSION
386 if (isAtLeastT) ++bpfloader_ver; // [43] BPFLOADER_MAINLINE_T_VERSION
387 if (isAtLeastU) ++bpfloader_ver; // [44] BPFLOADER_MAINLINE_U_VERSION
388 if (isAtLeastV) ++bpfloader_ver; // [45] BPFLOADER_MAINLINE_V_VERSION
Maciej Żenczykowski221b2482024-03-18 14:33:10 -0700389
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -0700390 // Load all ELF objects, create programs and maps, and pin them
391 for (const auto& location : locations) {
Maciej Żenczykowski221b2482024-03-18 14:33:10 -0700392 if (loadAllElfObjects(bpfloader_ver, location) != 0) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -0700393 ALOGE("=== CRITICAL FAILURE LOADING BPF PROGRAMS FROM %s ===", location.dir);
394 ALOGE("If this triggers reliably, you're probably missing kernel options or patches.");
395 ALOGE("If this triggers randomly, you might be hitting some memory allocation "
396 "problems or startup script race.");
397 ALOGE("--- DO NOT EXPECT SYSTEM TO BOOT SUCCESSFULLY ---");
398 sleep(20);
399 return 2;
400 }
401 }
402
403 int key = 1;
404 int value = 123;
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -0700405 base::unique_fd map(
406 createMap(BPF_MAP_TYPE_ARRAY, sizeof(key), sizeof(value), 2, 0));
407 if (writeToMapEntry(map, &key, &value, BPF_ANY)) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -0700408 ALOGE("Critical kernel bug - failure to write into index 1 of 2 element bpf map array.");
409 return 1;
410 }
411
Maciej Żenczykowski3218a812024-04-15 00:39:59 -0700412 if (isAtLeastV) {
Maciej Żenczykowski732a1412024-03-14 00:17:18 -0700413 ALOGI("done, transferring control to platform bpfloader.");
Maciej Żenczykowski58c18222023-10-20 14:40:16 -0700414
Maciej Żenczykowski732a1412024-03-14 00:17:18 -0700415 const char * args[] = { platformBpfLoader, NULL, };
416 execve(args[0], (char**)args, envp);
417 ALOGE("FATAL: execve('%s'): %d[%s]", platformBpfLoader, errno, strerror(errno));
418 return 1;
419 }
420
421 ALOGI("mainline done!");
422 return 0;
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -0700423}
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -0700424
425} // namespace bpf
426} // namespace android
427
428int main(int __unused argc, char** argv, char * const envp[]) {
429 return android::bpf::main(argv, envp);
430}