blob: 0d4a5c4f7b472e3dbfbb018bdcb48a03c69a5058 [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
Maciej Żenczykowski68eab892024-05-24 03:17:59 -070057using base::StartsWith;
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -070058using base::EndsWith;
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -070059using std::string;
Maciej Żenczykowski6e6b2092024-06-24 23:57:41 +000060using std::vector;
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -070061
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -070062static bool exists(const char* const path) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -070063 int v = access(path, F_OK);
Maciej Żenczykowski731acfe2024-04-30 10:09:57 +000064 if (!v) return true;
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -070065 if (errno == ENOENT) return false;
66 ALOGE("FATAL: access(%s, F_OK) -> %d [%d:%s]", path, v, errno, strerror(errno));
67 abort(); // can only hit this if permissions (likely selinux) are screwed up
68}
69
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -070070
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -070071const Location locations[] = {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -070072 // S+ Tethering mainline module (network_stack): tether offload
73 {
74 .dir = "/apex/com.android.tethering/etc/bpf/",
75 .prefix = "tethering/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -070076 },
77 // T+ Tethering mainline module (shared with netd & system server)
78 // netutils_wrapper (for iptables xt_bpf) has access to programs
79 {
80 .dir = "/apex/com.android.tethering/etc/bpf/netd_shared/",
81 .prefix = "netd_shared/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -070082 },
83 // T+ Tethering mainline module (shared with netd & system server)
84 // netutils_wrapper has no access, netd has read only access
85 {
86 .dir = "/apex/com.android.tethering/etc/bpf/netd_readonly/",
87 .prefix = "netd_readonly/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -070088 },
89 // T+ Tethering mainline module (shared with system server)
90 {
91 .dir = "/apex/com.android.tethering/etc/bpf/net_shared/",
92 .prefix = "net_shared/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -070093 },
94 // T+ Tethering mainline module (not shared, just network_stack)
95 {
96 .dir = "/apex/com.android.tethering/etc/bpf/net_private/",
97 .prefix = "net_private/",
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -070098 },
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -070099};
100
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -0700101static int loadAllElfObjects(const unsigned int bpfloader_ver, const Location& location) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -0700102 int retVal = 0;
103 DIR* dir;
104 struct dirent* ent;
105
106 if ((dir = opendir(location.dir)) != NULL) {
107 while ((ent = readdir(dir)) != NULL) {
108 string s = ent->d_name;
109 if (!EndsWith(s, ".o")) continue;
110
111 string progPath(location.dir);
112 progPath += s;
113
114 bool critical;
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -0700115 int ret = loadProg(progPath.c_str(), &critical, bpfloader_ver, location);
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -0700116 if (ret) {
117 if (critical) retVal = ret;
118 ALOGE("Failed to load object: %s, ret: %s", progPath.c_str(), std::strerror(-ret));
119 } else {
Maciej Żenczykowski5c057ed2024-04-30 11:59:13 +0000120 ALOGD("Loaded object: %s", progPath.c_str());
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -0700121 }
122 }
123 closedir(dir);
124 }
125 return retVal;
126}
127
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -0700128static int createSysFsBpfSubDir(const char* const prefix) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -0700129 if (*prefix) {
130 mode_t prevUmask = umask(0);
131
132 string s = "/sys/fs/bpf/";
133 s += prefix;
134
135 errno = 0;
136 int ret = mkdir(s.c_str(), S_ISVTX | S_IRWXU | S_IRWXG | S_IRWXO);
137 if (ret && errno != EEXIST) {
138 const int err = errno;
139 ALOGE("Failed to create directory: %s, ret: %s", s.c_str(), std::strerror(err));
140 return -err;
141 }
142
143 umask(prevUmask);
144 }
145 return 0;
146}
147
148// Technically 'value' doesn't need to be newline terminated, but it's best
149// to include a newline to match 'echo "value" > /proc/sys/...foo' behaviour,
150// which is usually how kernel devs test the actual sysctl interfaces.
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -0700151static int writeProcSysFile(const char *filename, const char *value) {
152 base::unique_fd fd(open(filename, O_WRONLY | O_CLOEXEC));
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -0700153 if (fd < 0) {
154 const int err = errno;
155 ALOGE("open('%s', O_WRONLY | O_CLOEXEC) -> %s", filename, strerror(err));
156 return -err;
157 }
158 int len = strlen(value);
159 int v = write(fd, value, len);
160 if (v < 0) {
161 const int err = errno;
162 ALOGE("write('%s', '%s', %d) -> %s", filename, value, len, strerror(err));
163 return -err;
164 }
165 if (v != len) {
166 // In practice, due to us only using this for /proc/sys/... files, this can't happen.
167 ALOGE("write('%s', '%s', %d) -> short write [%d]", filename, value, len, v);
168 return -EINVAL;
169 }
170 return 0;
171}
172
Maciej Żenczykowskib60599b2024-02-09 12:30:52 -0800173#define APEX_MOUNT_POINT "/apex/com.android.tethering"
Maciej Żenczykowski2fe2db52024-02-07 01:23:58 +0000174const char * const platformBpfLoader = "/system/bin/bpfloader";
Maciej Żenczykowskib60599b2024-02-09 12:30:52 -0800175
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -0700176static int logTetheringApexVersion(void) {
Maciej Żenczykowskib60599b2024-02-09 12:30:52 -0800177 char * found_blockdev = NULL;
178 FILE * f = NULL;
179 char buf[4096];
180
181 f = fopen("/proc/mounts", "re");
182 if (!f) return 1;
183
184 // /proc/mounts format: block_device [space] mount_point [space] other stuff... newline
185 while (fgets(buf, sizeof(buf), f)) {
186 char * blockdev = buf;
187 char * space = strchr(blockdev, ' ');
188 if (!space) continue;
189 *space = '\0';
190 char * mntpath = space + 1;
191 space = strchr(mntpath, ' ');
192 if (!space) continue;
193 *space = '\0';
194 if (strcmp(mntpath, APEX_MOUNT_POINT)) continue;
195 found_blockdev = strdup(blockdev);
196 break;
197 }
198 fclose(f);
199 f = NULL;
200
201 if (!found_blockdev) return 2;
Maciej Żenczykowski5c057ed2024-04-30 11:59:13 +0000202 ALOGV("Found Tethering Apex mounted from blockdev %s", found_blockdev);
Maciej Żenczykowskib60599b2024-02-09 12:30:52 -0800203
204 f = fopen("/proc/mounts", "re");
205 if (!f) { free(found_blockdev); return 3; }
206
207 while (fgets(buf, sizeof(buf), f)) {
208 char * blockdev = buf;
209 char * space = strchr(blockdev, ' ');
210 if (!space) continue;
211 *space = '\0';
212 char * mntpath = space + 1;
213 space = strchr(mntpath, ' ');
214 if (!space) continue;
215 *space = '\0';
216 if (strcmp(blockdev, found_blockdev)) continue;
217 if (strncmp(mntpath, APEX_MOUNT_POINT "@", strlen(APEX_MOUNT_POINT "@"))) continue;
218 char * at = strchr(mntpath, '@');
219 if (!at) continue;
220 char * ver = at + 1;
221 ALOGI("Tethering APEX version %s", ver);
222 }
223 fclose(f);
224 free(found_blockdev);
225 return 0;
226}
Maciej Żenczykowski2fe2db52024-02-07 01:23:58 +0000227
Maciej Żenczykowski68eab892024-05-24 03:17:59 -0700228static bool hasGSM() {
229 static string ph = base::GetProperty("gsm.current.phone-type", "");
230 static bool gsm = (ph != "");
231 static bool logged = false;
232 if (!logged) {
233 logged = true;
234 ALOGI("hasGSM(gsm.current.phone-type='%s'): %s", ph.c_str(), gsm ? "true" : "false");
235 }
236 return gsm;
237}
238
239static bool isTV() {
240 if (hasGSM()) return false; // TVs don't do GSM
241
242 static string key = base::GetProperty("ro.oem.key1", "");
243 static bool tv = StartsWith(key, "ATV00");
244 static bool logged = false;
245 if (!logged) {
246 logged = true;
247 ALOGI("isTV(ro.oem.key1='%s'): %s.", key.c_str(), tv ? "true" : "false");
248 }
249 return tv;
250}
251
Maciej Żenczykowski6e6b2092024-06-24 23:57:41 +0000252static bool isWear() {
253 static string wearSdkStr = base::GetProperty("ro.cw_build.wear_sdk.version", "");
254 static int wearSdkInt = base::GetIntProperty("ro.cw_build.wear_sdk.version", 0);
255 static string buildChars = base::GetProperty("ro.build.characteristics", "");
256 static vector<string> v = base::Tokenize(buildChars, ",");
257 static bool watch = (std::find(v.begin(), v.end(), "watch") != v.end());
258 static bool wear = (wearSdkInt > 0) || watch;
259 static bool logged = false;
260 if (!logged) {
261 logged = true;
262 ALOGI("isWear(ro.cw_build.wear_sdk.version=%d[%s] ro.build.characteristics='%s'): %s",
263 wearSdkInt, wearSdkStr.c_str(), buildChars.c_str(), wear ? "true" : "false");
264 }
265 return wear;
266}
267
Maciej Żenczykowski6d151ef2024-04-30 23:55:57 -0700268static int doLoad(char** argv, char * const envp[]) {
Maciej Żenczykowski15f97312024-06-13 14:11:28 -0700269 const bool runningAsRoot = !getuid(); // true iff U QPR3 or V+
Maciej Żenczykowski7b95d992024-06-13 18:18:11 -0700270
Maciej Żenczykowski686f6ac2024-06-14 14:42:06 -0700271 // Any released device will have codename REL instead of a 'real' codename.
272 // For safety: default to 'REL' so we default to unreleased=false on failure.
273 const bool unreleased = (base::GetProperty("ro.build.version.codename", "REL") != "REL");
274
275 // goog/main device_api_level is bumped *way* before aosp/main api level
276 // (the latter only gets bumped during the push of goog/main to aosp/main)
277 //
278 // Since we develop in AOSP, we want it to behave as if it was bumped too.
279 //
280 // Note that AOSP doesn't really have a good api level (for example during
281 // early V dev cycle, it would have *all* of T, some but not all of U, and some V).
282 // One could argue that for our purposes AOSP api level should be infinite or 10000.
283 //
284 // This could also cause api to be increased in goog/main or other branches,
285 // but I can't imagine a case where this would be a problem: the problem
286 // is rather a too low api level, rather than some ill defined high value.
287 // For example as I write this aosp is 34/U, and goog is 35/V,
288 // we want to treat both goog & aosp as 35/V, but it's harmless if we
289 // treat goog as 36 because that value isn't yet defined to mean anything,
290 // and we thus never compare against it.
291 //
292 // Also note that 'android_get_device_api_level()' is what the
293 // //system/core/init/apex_init_util.cpp
294 // apex init .XXrc parsing code uses for XX filtering.
295 //
296 // That code has a hack to bump <35 to 35 (to force aosp/main to parse .35rc),
297 // but could (should?) perhaps be adjusted to match this.
298 const int effective_api_level = android_get_device_api_level() + (int)unreleased;
299 const bool isAtLeastT = (effective_api_level >= __ANDROID_API_T__);
300 const bool isAtLeastU = (effective_api_level >= __ANDROID_API_U__);
301 const bool isAtLeastV = (effective_api_level >= __ANDROID_API_V__);
Maciej Żenczykowski041be522023-10-23 23:34:52 -0700302
Maciej Żenczykowski03ef12c2024-02-10 21:34:22 +0000303 // last in U QPR2 beta1
304 const bool has_platform_bpfloader_rc = exists("/system/etc/init/bpfloader.rc");
305 // first in U QPR2 beta~2
306 const bool has_platform_netbpfload_rc = exists("/system/etc/init/netbpfload.rc");
307
Maciej Żenczykowski62956142024-06-13 15:32:57 -0700308 // Version of Network BpfLoader depends on the Android OS version
Maciej Żenczykowski1a3b54f2024-06-13 15:35:46 -0700309 unsigned int bpfloader_ver = 42u; // [42] BPFLOADER_MAINLINE_VERSION
310 if (isAtLeastT) ++bpfloader_ver; // [43] BPFLOADER_MAINLINE_T_VERSION
311 if (isAtLeastU) ++bpfloader_ver; // [44] BPFLOADER_MAINLINE_U_VERSION
312 if (runningAsRoot) ++bpfloader_ver; // [45] BPFLOADER_MAINLINE_U_QPR3_VERSION
313 if (isAtLeastV) ++bpfloader_ver; // [46] BPFLOADER_MAINLINE_V_VERSION
Maciej Żenczykowski62956142024-06-13 15:32:57 -0700314
Maciej Żenczykowski7b95d992024-06-13 18:18:11 -0700315 ALOGI("NetBpfLoad v0.%u (%s) api:%d/%d kver:%07x (%s) uid:%d rc:%d%d",
Maciej Żenczykowski686f6ac2024-06-14 14:42:06 -0700316 bpfloader_ver, argv[0], android_get_device_api_level(), effective_api_level,
Maciej Żenczykowski7b95d992024-06-13 18:18:11 -0700317 kernelVersion(), describeArch(), getuid(),
Maciej Żenczykowski03ef12c2024-02-10 21:34:22 +0000318 has_platform_bpfloader_rc, has_platform_netbpfload_rc);
Maciej Żenczykowski041be522023-10-23 23:34:52 -0700319
Maciej Żenczykowski03ef12c2024-02-10 21:34:22 +0000320 if (!has_platform_bpfloader_rc && !has_platform_netbpfload_rc) {
321 ALOGE("Unable to find platform's bpfloader & netbpfload init scripts.");
322 return 1;
323 }
324
325 if (has_platform_bpfloader_rc && has_platform_netbpfload_rc) {
326 ALOGE("Platform has *both* bpfloader & netbpfload init scripts.");
327 return 1;
328 }
329
Maciej Żenczykowskib60599b2024-02-09 12:30:52 -0800330 logTetheringApexVersion();
331
Maciej Żenczykowski11141da2024-03-15 18:21:33 -0700332 if (!isAtLeastT) {
333 ALOGE("Impossible - not reachable on Android <T.");
Maciej Żenczykowski03ef12c2024-02-10 21:34:22 +0000334 return 1;
335 }
336
Maciej Żenczykowskic834fdb2024-06-02 22:24:01 +0000337 // both S and T require kernel 4.9 (and eBpf support)
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -0700338 if (isAtLeastT && !isAtLeastKernelVersion(4, 9, 0)) {
Maciej Żenczykowski041be522023-10-23 23:34:52 -0700339 ALOGE("Android T requires kernel 4.9.");
340 return 1;
341 }
342
Maciej Żenczykowskic834fdb2024-06-02 22:24:01 +0000343 // U bumps the kernel requirement up to 4.14
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -0700344 if (isAtLeastU && !isAtLeastKernelVersion(4, 14, 0)) {
Maciej Żenczykowski041be522023-10-23 23:34:52 -0700345 ALOGE("Android U requires kernel 4.14.");
346 return 1;
347 }
348
Maciej Żenczykowskic834fdb2024-06-02 22:24:01 +0000349 // V bumps the kernel requirement up to 4.19
350 // see also: //system/netd/tests/kernel_test.cpp TestKernel419
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -0700351 if (isAtLeastV && !isAtLeastKernelVersion(4, 19, 0)) {
Maciej Żenczykowski041be522023-10-23 23:34:52 -0700352 ALOGE("Android V requires kernel 4.19.");
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -0700353 return 1;
354 }
355
Maciej Żenczykowskic834fdb2024-06-02 22:24:01 +0000356 // Technically already required by U, but only enforce on V+
357 // see also: //system/netd/tests/kernel_test.cpp TestKernel64Bit
358 if (isAtLeastV && isKernel32Bit() && isAtLeastKernelVersion(5, 16, 0)) {
359 ALOGE("Android V+ platform with 32 bit kernel version >= 5.16.0 is unsupported");
360 if (!isTV()) return 1;
361 }
362
363 // Various known ABI layout issues, particularly wrt. bpf and ipsec/xfrm.
364 if (isAtLeastV && isKernel32Bit() && isX86()) {
Maciej Żenczykowski7f6a4262024-02-17 00:42:42 +0000365 ALOGE("Android V requires X86 kernel to be 64-bit.");
Maciej Żenczykowski68eab892024-05-24 03:17:59 -0700366 if (!isTV()) return 1;
Maciej Żenczykowski7f6a4262024-02-17 00:42:42 +0000367 }
368
Maciej Żenczykowskic982a4b2024-04-25 23:04:09 -0700369 if (isAtLeastV) {
370 bool bad = false;
371
372 if (!isLtsKernel()) {
373 ALOGW("Android V only supports LTS kernels.");
374 bad = true;
375 }
376
377#define REQUIRE(maj, min, sub) \
378 if (isKernelVersion(maj, min) && !isAtLeastKernelVersion(maj, min, sub)) { \
379 ALOGW("Android V requires %d.%d kernel to be %d.%d.%d+.", maj, min, maj, min, sub); \
380 bad = true; \
381 }
382
383 REQUIRE(4, 19, 236)
384 REQUIRE(5, 4, 186)
385 REQUIRE(5, 10, 199)
386 REQUIRE(5, 15, 136)
387 REQUIRE(6, 1, 57)
388 REQUIRE(6, 6, 0)
389
390#undef REQUIRE
391
Maciej Żenczykowski4a0838c2024-06-14 20:22:20 +0000392 if (bad) {
Maciej Żenczykowskic982a4b2024-04-25 23:04:09 -0700393 ALOGE("Unsupported kernel version (%07x).", kernelVersion());
394 }
395 }
396
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -0700397 if (isUserspace32bit() && isAtLeastKernelVersion(6, 2, 0)) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -0700398 /* Android 14/U should only launch on 64-bit kernels
399 * T launches on 5.10/5.15
400 * U launches on 5.15/6.1
401 * So >=5.16 implies isKernel64Bit()
402 *
403 * We thus added a test to V VTS which requires 5.16+ devices to use 64-bit kernels.
404 *
405 * Starting with Android V, which is the first to support a post 6.1 Linux Kernel,
406 * we also require 64-bit userspace.
407 *
408 * There are various known issues with 32-bit userspace talking to various
409 * kernel interfaces (especially CAP_NET_ADMIN ones) on a 64-bit kernel.
410 * Some of these have userspace or kernel workarounds/hacks.
411 * Some of them don't...
412 * We're going to be removing the hacks.
Maciej Żenczykowskic834fdb2024-06-02 22:24:01 +0000413 * (for example "ANDROID: xfrm: remove in_compat_syscall() checks").
414 * Note: this check/enforcement only applies to *system* userspace code,
415 * it does not affect unprivileged apps, the 32-on-64 compatibility
416 * problems are AFAIK limited to various CAP_NET_ADMIN protected interfaces.
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -0700417 *
418 * Additionally the 32-bit kernel jit support is poor,
419 * and 32-bit userspace on 64-bit kernel bpf ringbuffer compatibility is broken.
420 */
421 ALOGE("64-bit userspace required on 6.2+ kernels.");
Maciej Żenczykowski6e6b2092024-06-24 23:57:41 +0000422 // Stuff won't work reliably, but exempt TVs & Arm Wear devices
423 if (!isTV() && !(isWear() && isArm())) return 1;
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -0700424 }
425
426 // Ensure we can determine the Android build type.
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -0700427 if (!isEng() && !isUser() && !isUserdebug()) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -0700428 ALOGE("Failed to determine the build type: got %s, want 'eng', 'user', or 'userdebug'",
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -0700429 getBuildType().c_str());
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -0700430 return 1;
431 }
432
Maciej Żenczykowski48e476b2024-06-13 14:06:49 -0700433 if (runningAsRoot) {
434 // Note: writing this proc file requires being root (always the case on V+)
435
Maciej Żenczykowskif33f1282023-10-24 04:41:54 -0700436 // Linux 5.16-rc1 changed the default to 2 (disabled but changeable),
437 // but we need 0 (enabled)
438 // (this writeFile is known to fail on at least 4.19, but always defaults to 0 on
439 // pre-5.13, on 5.13+ it depends on CONFIG_BPF_UNPRIV_DEFAULT_OFF)
440 if (writeProcSysFile("/proc/sys/kernel/unprivileged_bpf_disabled", "0\n") &&
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -0700441 isAtLeastKernelVersion(5, 13, 0)) return 1;
Maciej Żenczykowski732a1412024-03-14 00:17:18 -0700442 }
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -0700443
Maciej Żenczykowski732a1412024-03-14 00:17:18 -0700444 if (isAtLeastU) {
Maciej Żenczykowski48e476b2024-06-13 14:06:49 -0700445 // Note: writing these proc files requires CAP_NET_ADMIN
446 // and sepolicy which is only present on U+,
447 // on Android T and earlier versions they're written from the 'load_bpf_programs'
448 // trigger (ie. by init itself) instead.
449
Maciej Żenczykowskif33f1282023-10-24 04:41:54 -0700450 // Enable the eBPF JIT -- but do note that on 64-bit kernels it is likely
451 // already force enabled by the kernel config option BPF_JIT_ALWAYS_ON.
452 // (Note: this (open) will fail with ENOENT 'No such file or directory' if
453 // kernel does not have CONFIG_BPF_JIT=y)
454 // BPF_JIT is required by R VINTF (which means 4.14/4.19/5.4 kernels),
455 // but 4.14/4.19 were released with P & Q, and only 5.4 is new in R+.
456 if (writeProcSysFile("/proc/sys/net/core/bpf_jit_enable", "1\n")) return 1;
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -0700457
Maciej Żenczykowskif33f1282023-10-24 04:41:54 -0700458 // Enable JIT kallsyms export for privileged users only
459 // (Note: this (open) will fail with ENOENT 'No such file or directory' if
460 // kernel does not have CONFIG_HAVE_EBPF_JIT=y)
461 if (writeProcSysFile("/proc/sys/net/core/bpf_jit_kallsyms", "1\n")) return 1;
462 }
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -0700463
464 // Create all the pin subdirectories
465 // (this must be done first to allow selinux_context and pin_subdir functionality,
466 // which could otherwise fail with ENOENT during object pinning or renaming,
467 // due to ordering issues)
468 for (const auto& location : locations) {
469 if (createSysFsBpfSubDir(location.prefix)) return 1;
470 }
471
Maciej Żenczykowskia9209da2024-02-29 02:01:20 +0000472 // Note: there's no actual src dir for fs_bpf_loader .o's,
473 // so it is not listed in 'locations[].prefix'.
474 // This is because this is primarily meant for triggering genfscon rules,
475 // and as such this will likely always be the case.
476 // Thus we need to manually create the /sys/fs/bpf/loader subdirectory.
477 if (createSysFsBpfSubDir("loader")) return 1;
478
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -0700479 // Load all ELF objects, create programs and maps, and pin them
480 for (const auto& location : locations) {
Maciej Żenczykowski221b2482024-03-18 14:33:10 -0700481 if (loadAllElfObjects(bpfloader_ver, location) != 0) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -0700482 ALOGE("=== CRITICAL FAILURE LOADING BPF PROGRAMS FROM %s ===", location.dir);
483 ALOGE("If this triggers reliably, you're probably missing kernel options or patches.");
484 ALOGE("If this triggers randomly, you might be hitting some memory allocation "
485 "problems or startup script race.");
486 ALOGE("--- DO NOT EXPECT SYSTEM TO BOOT SUCCESSFULLY ---");
487 sleep(20);
488 return 2;
489 }
490 }
491
492 int key = 1;
493 int value = 123;
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -0700494 base::unique_fd map(
495 createMap(BPF_MAP_TYPE_ARRAY, sizeof(key), sizeof(value), 2, 0));
496 if (writeToMapEntry(map, &key, &value, BPF_ANY)) {
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -0700497 ALOGE("Critical kernel bug - failure to write into index 1 of 2 element bpf map array.");
498 return 1;
499 }
500
Maciej Żenczykowski15f97312024-06-13 14:11:28 -0700501 // leave a flag that we're done
502 if (createSysFsBpfSubDir("netd_shared/mainline_done")) return 1;
Maciej Żenczykowski58c18222023-10-20 14:40:16 -0700503
Maciej Żenczykowski15f97312024-06-13 14:11:28 -0700504 // platform bpfloader will only succeed when run as root
505 if (!runningAsRoot) {
506 // unreachable on U QPR3+ which always runs netbpfload as root
507
508 ALOGI("mainline done, no need to transfer control to platform bpf loader.");
509 return 0;
Maciej Żenczykowski732a1412024-03-14 00:17:18 -0700510 }
511
Maciej Żenczykowski15f97312024-06-13 14:11:28 -0700512 // unreachable before U QPR3
513 ALOGI("done, transferring control to platform bpfloader.");
514
515 // platform BpfLoader *needs* to run as root
516 const char * args[] = { platformBpfLoader, NULL, };
517 execve(args[0], (char**)args, envp);
518 ALOGE("FATAL: execve('%s'): %d[%s]", platformBpfLoader, errno, strerror(errno));
519 return 1;
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -0700520}
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -0700521
522} // namespace bpf
523} // namespace android
524
Maciej Żenczykowski6d151ef2024-04-30 23:55:57 -0700525int main(int argc, char** argv, char * const envp[]) {
526 android::base::InitLogging(argv, &android::base::KernelLogger);
527
528 if (argc == 2 && !strcmp(argv[1], "done")) {
529 // we're being re-exec'ed from platform bpfloader to 'finalize' things
530 if (!android::base::SetProperty("bpf.progs_loaded", "1")) {
531 ALOGE("Failed to set bpf.progs_loaded property to 1.");
532 return 125;
533 }
Maciej Żenczykowski66f16292024-05-06 23:52:33 -0700534 ALOGI("success.");
Maciej Żenczykowski6d151ef2024-04-30 23:55:57 -0700535 return 0;
536 }
537
538 return android::bpf::doLoad(argv, envp);
Maciej Żenczykowski75c2def2024-04-25 14:19:14 -0700539}