1 /*
2 * Copyright (C) 2017-2023 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
17 #ifndef LOG_TAG
18 #define LOG_TAG "NetBpfLoad"
19 #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
41 #include <android/api-level.h>
42 #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>
48 #include <log/log.h>
49
50 #include "BpfSyscallWrappers.h"
51 #include "bpf/BpfUtils.h"
52 #include "loader.h"
53
54 namespace android {
55 namespace bpf {
56
57 using base::StartsWith;
58 using base::EndsWith;
59 using std::string;
60
exists(const char * const path)61 static bool exists(const char* const path) {
62 int v = access(path, F_OK);
63 if (!v) return true;
64 if (errno == ENOENT) return false;
65 ALOGE("FATAL: access(%s, F_OK) -> %d [%d:%s]", path, v, errno, strerror(errno));
66 abort(); // can only hit this if permissions (likely selinux) are screwed up
67 }
68
69
70 const Location locations[] = {
71 // S+ Tethering mainline module (network_stack): tether offload
72 {
73 .dir = "/apex/com.android.tethering/etc/bpf/",
74 .prefix = "tethering/",
75 },
76 // T+ Tethering mainline module (shared with netd & system server)
77 // netutils_wrapper (for iptables xt_bpf) has access to programs
78 {
79 .dir = "/apex/com.android.tethering/etc/bpf/netd_shared/",
80 .prefix = "netd_shared/",
81 },
82 // T+ Tethering mainline module (shared with netd & system server)
83 // netutils_wrapper has no access, netd has read only access
84 {
85 .dir = "/apex/com.android.tethering/etc/bpf/netd_readonly/",
86 .prefix = "netd_readonly/",
87 },
88 // T+ Tethering mainline module (shared with system server)
89 {
90 .dir = "/apex/com.android.tethering/etc/bpf/net_shared/",
91 .prefix = "net_shared/",
92 },
93 // T+ Tethering mainline module (not shared, just network_stack)
94 {
95 .dir = "/apex/com.android.tethering/etc/bpf/net_private/",
96 .prefix = "net_private/",
97 },
98 };
99
loadAllElfObjects(const unsigned int bpfloader_ver,const Location & location)100 static int loadAllElfObjects(const unsigned int bpfloader_ver, const Location& location) {
101 int retVal = 0;
102 DIR* dir;
103 struct dirent* ent;
104
105 if ((dir = opendir(location.dir)) != NULL) {
106 while ((ent = readdir(dir)) != NULL) {
107 string s = ent->d_name;
108 if (!EndsWith(s, ".o")) continue;
109
110 string progPath(location.dir);
111 progPath += s;
112
113 bool critical;
114 int ret = loadProg(progPath.c_str(), &critical, bpfloader_ver, location);
115 if (ret) {
116 if (critical) retVal = ret;
117 ALOGE("Failed to load object: %s, ret: %s", progPath.c_str(), std::strerror(-ret));
118 } else {
119 ALOGD("Loaded object: %s", progPath.c_str());
120 }
121 }
122 closedir(dir);
123 }
124 return retVal;
125 }
126
createSysFsBpfSubDir(const char * const prefix)127 static int createSysFsBpfSubDir(const char* const prefix) {
128 if (*prefix) {
129 mode_t prevUmask = umask(0);
130
131 string s = "/sys/fs/bpf/";
132 s += prefix;
133
134 errno = 0;
135 int ret = mkdir(s.c_str(), S_ISVTX | S_IRWXU | S_IRWXG | S_IRWXO);
136 if (ret && errno != EEXIST) {
137 const int err = errno;
138 ALOGE("Failed to create directory: %s, ret: %s", s.c_str(), std::strerror(err));
139 return -err;
140 }
141
142 umask(prevUmask);
143 }
144 return 0;
145 }
146
147 // Technically 'value' doesn't need to be newline terminated, but it's best
148 // to include a newline to match 'echo "value" > /proc/sys/...foo' behaviour,
149 // which is usually how kernel devs test the actual sysctl interfaces.
writeProcSysFile(const char * filename,const char * value)150 static int writeProcSysFile(const char *filename, const char *value) {
151 base::unique_fd fd(open(filename, O_WRONLY | O_CLOEXEC));
152 if (fd < 0) {
153 const int err = errno;
154 ALOGE("open('%s', O_WRONLY | O_CLOEXEC) -> %s", filename, strerror(err));
155 return -err;
156 }
157 int len = strlen(value);
158 int v = write(fd, value, len);
159 if (v < 0) {
160 const int err = errno;
161 ALOGE("write('%s', '%s', %d) -> %s", filename, value, len, strerror(err));
162 return -err;
163 }
164 if (v != len) {
165 // In practice, due to us only using this for /proc/sys/... files, this can't happen.
166 ALOGE("write('%s', '%s', %d) -> short write [%d]", filename, value, len, v);
167 return -EINVAL;
168 }
169 return 0;
170 }
171
172 #define APEX_MOUNT_POINT "/apex/com.android.tethering"
173 const char * const platformBpfLoader = "/system/bin/bpfloader";
174
logTetheringApexVersion(void)175 static int logTetheringApexVersion(void) {
176 char * found_blockdev = NULL;
177 FILE * f = NULL;
178 char buf[4096];
179
180 f = fopen("/proc/mounts", "re");
181 if (!f) return 1;
182
183 // /proc/mounts format: block_device [space] mount_point [space] other stuff... newline
184 while (fgets(buf, sizeof(buf), f)) {
185 char * blockdev = buf;
186 char * space = strchr(blockdev, ' ');
187 if (!space) continue;
188 *space = '\0';
189 char * mntpath = space + 1;
190 space = strchr(mntpath, ' ');
191 if (!space) continue;
192 *space = '\0';
193 if (strcmp(mntpath, APEX_MOUNT_POINT)) continue;
194 found_blockdev = strdup(blockdev);
195 break;
196 }
197 fclose(f);
198 f = NULL;
199
200 if (!found_blockdev) return 2;
201 ALOGV("Found Tethering Apex mounted from blockdev %s", found_blockdev);
202
203 f = fopen("/proc/mounts", "re");
204 if (!f) { free(found_blockdev); return 3; }
205
206 while (fgets(buf, sizeof(buf), f)) {
207 char * blockdev = buf;
208 char * space = strchr(blockdev, ' ');
209 if (!space) continue;
210 *space = '\0';
211 char * mntpath = space + 1;
212 space = strchr(mntpath, ' ');
213 if (!space) continue;
214 *space = '\0';
215 if (strcmp(blockdev, found_blockdev)) continue;
216 if (strncmp(mntpath, APEX_MOUNT_POINT "@", strlen(APEX_MOUNT_POINT "@"))) continue;
217 char * at = strchr(mntpath, '@');
218 if (!at) continue;
219 char * ver = at + 1;
220 ALOGI("Tethering APEX version %s", ver);
221 }
222 fclose(f);
223 free(found_blockdev);
224 return 0;
225 }
226
hasGSM()227 static bool hasGSM() {
228 static string ph = base::GetProperty("gsm.current.phone-type", "");
229 static bool gsm = (ph != "");
230 static bool logged = false;
231 if (!logged) {
232 logged = true;
233 ALOGI("hasGSM(gsm.current.phone-type='%s'): %s", ph.c_str(), gsm ? "true" : "false");
234 }
235 return gsm;
236 }
237
isTV()238 static bool isTV() {
239 if (hasGSM()) return false; // TVs don't do GSM
240
241 static string key = base::GetProperty("ro.oem.key1", "");
242 static bool tv = StartsWith(key, "ATV00");
243 static bool logged = false;
244 if (!logged) {
245 logged = true;
246 ALOGI("isTV(ro.oem.key1='%s'): %s.", key.c_str(), tv ? "true" : "false");
247 }
248 return tv;
249 }
250
doLoad(char ** argv,char * const envp[])251 static int doLoad(char** argv, char * const envp[]) {
252 const bool runningAsRoot = !getuid(); // true iff U QPR3 or V+
253
254 // Any released device will have codename REL instead of a 'real' codename.
255 // For safety: default to 'REL' so we default to unreleased=false on failure.
256 const bool unreleased = (base::GetProperty("ro.build.version.codename", "REL") != "REL");
257
258 // goog/main device_api_level is bumped *way* before aosp/main api level
259 // (the latter only gets bumped during the push of goog/main to aosp/main)
260 //
261 // Since we develop in AOSP, we want it to behave as if it was bumped too.
262 //
263 // Note that AOSP doesn't really have a good api level (for example during
264 // early V dev cycle, it would have *all* of T, some but not all of U, and some V).
265 // One could argue that for our purposes AOSP api level should be infinite or 10000.
266 //
267 // This could also cause api to be increased in goog/main or other branches,
268 // but I can't imagine a case where this would be a problem: the problem
269 // is rather a too low api level, rather than some ill defined high value.
270 // For example as I write this aosp is 34/U, and goog is 35/V,
271 // we want to treat both goog & aosp as 35/V, but it's harmless if we
272 // treat goog as 36 because that value isn't yet defined to mean anything,
273 // and we thus never compare against it.
274 //
275 // Also note that 'android_get_device_api_level()' is what the
276 // //system/core/init/apex_init_util.cpp
277 // apex init .XXrc parsing code uses for XX filtering.
278 //
279 // That code has a hack to bump <35 to 35 (to force aosp/main to parse .35rc),
280 // but could (should?) perhaps be adjusted to match this.
281 const int effective_api_level = android_get_device_api_level() + (int)unreleased;
282 const bool isAtLeastT = (effective_api_level >= __ANDROID_API_T__);
283 const bool isAtLeastU = (effective_api_level >= __ANDROID_API_U__);
284 const bool isAtLeastV = (effective_api_level >= __ANDROID_API_V__);
285
286 // last in U QPR2 beta1
287 const bool has_platform_bpfloader_rc = exists("/system/etc/init/bpfloader.rc");
288 // first in U QPR2 beta~2
289 const bool has_platform_netbpfload_rc = exists("/system/etc/init/netbpfload.rc");
290
291 // Version of Network BpfLoader depends on the Android OS version
292 unsigned int bpfloader_ver = 42u; // [42] BPFLOADER_MAINLINE_VERSION
293 if (isAtLeastT) ++bpfloader_ver; // [43] BPFLOADER_MAINLINE_T_VERSION
294 if (isAtLeastU) ++bpfloader_ver; // [44] BPFLOADER_MAINLINE_U_VERSION
295 if (runningAsRoot) ++bpfloader_ver; // [45] BPFLOADER_MAINLINE_U_QPR3_VERSION
296 if (isAtLeastV) ++bpfloader_ver; // [46] BPFLOADER_MAINLINE_V_VERSION
297
298 ALOGI("NetBpfLoad v0.%u (%s) api:%d/%d kver:%07x (%s) uid:%d rc:%d%d",
299 bpfloader_ver, argv[0], android_get_device_api_level(), effective_api_level,
300 kernelVersion(), describeArch(), getuid(),
301 has_platform_bpfloader_rc, has_platform_netbpfload_rc);
302
303 if (!has_platform_bpfloader_rc && !has_platform_netbpfload_rc) {
304 ALOGE("Unable to find platform's bpfloader & netbpfload init scripts.");
305 return 1;
306 }
307
308 if (has_platform_bpfloader_rc && has_platform_netbpfload_rc) {
309 ALOGE("Platform has *both* bpfloader & netbpfload init scripts.");
310 return 1;
311 }
312
313 logTetheringApexVersion();
314
315 if (!isAtLeastT) {
316 ALOGE("Impossible - not reachable on Android <T.");
317 return 1;
318 }
319
320 // both S and T require kernel 4.9 (and eBpf support)
321 if (isAtLeastT && !isAtLeastKernelVersion(4, 9, 0)) {
322 ALOGE("Android T requires kernel 4.9.");
323 return 1;
324 }
325
326 // U bumps the kernel requirement up to 4.14
327 if (isAtLeastU && !isAtLeastKernelVersion(4, 14, 0)) {
328 ALOGE("Android U requires kernel 4.14.");
329 return 1;
330 }
331
332 // V bumps the kernel requirement up to 4.19
333 // see also: //system/netd/tests/kernel_test.cpp TestKernel419
334 if (isAtLeastV && !isAtLeastKernelVersion(4, 19, 0)) {
335 ALOGE("Android V requires kernel 4.19.");
336 return 1;
337 }
338
339 // Technically already required by U, but only enforce on V+
340 // see also: //system/netd/tests/kernel_test.cpp TestKernel64Bit
341 if (isAtLeastV && isKernel32Bit() && isAtLeastKernelVersion(5, 16, 0)) {
342 ALOGE("Android V+ platform with 32 bit kernel version >= 5.16.0 is unsupported");
343 if (!isTV()) return 1;
344 }
345
346 // Various known ABI layout issues, particularly wrt. bpf and ipsec/xfrm.
347 if (isAtLeastV && isKernel32Bit() && isX86()) {
348 ALOGE("Android V requires X86 kernel to be 64-bit.");
349 if (!isTV()) return 1;
350 }
351
352 if (isAtLeastV) {
353 bool bad = false;
354
355 if (!isLtsKernel()) {
356 ALOGW("Android V only supports LTS kernels.");
357 bad = true;
358 }
359
360 #define REQUIRE(maj, min, sub) \
361 if (isKernelVersion(maj, min) && !isAtLeastKernelVersion(maj, min, sub)) { \
362 ALOGW("Android V requires %d.%d kernel to be %d.%d.%d+.", maj, min, maj, min, sub); \
363 bad = true; \
364 }
365
366 REQUIRE(4, 19, 236)
367 REQUIRE(5, 4, 186)
368 REQUIRE(5, 10, 199)
369 REQUIRE(5, 15, 136)
370 REQUIRE(6, 1, 57)
371 REQUIRE(6, 6, 0)
372
373 #undef REQUIRE
374
375 if (bad) {
376 ALOGE("Unsupported kernel version (%07x).", kernelVersion());
377 }
378 }
379
380 if (isUserspace32bit() && isAtLeastKernelVersion(6, 2, 0)) {
381 /* Android 14/U should only launch on 64-bit kernels
382 * T launches on 5.10/5.15
383 * U launches on 5.15/6.1
384 * So >=5.16 implies isKernel64Bit()
385 *
386 * We thus added a test to V VTS which requires 5.16+ devices to use 64-bit kernels.
387 *
388 * Starting with Android V, which is the first to support a post 6.1 Linux Kernel,
389 * we also require 64-bit userspace.
390 *
391 * There are various known issues with 32-bit userspace talking to various
392 * kernel interfaces (especially CAP_NET_ADMIN ones) on a 64-bit kernel.
393 * Some of these have userspace or kernel workarounds/hacks.
394 * Some of them don't...
395 * We're going to be removing the hacks.
396 * (for example "ANDROID: xfrm: remove in_compat_syscall() checks").
397 * Note: this check/enforcement only applies to *system* userspace code,
398 * it does not affect unprivileged apps, the 32-on-64 compatibility
399 * problems are AFAIK limited to various CAP_NET_ADMIN protected interfaces.
400 *
401 * Additionally the 32-bit kernel jit support is poor,
402 * and 32-bit userspace on 64-bit kernel bpf ringbuffer compatibility is broken.
403 */
404 ALOGE("64-bit userspace required on 6.2+ kernels.");
405 if (!isTV()) return 1;
406 }
407
408 // Ensure we can determine the Android build type.
409 if (!isEng() && !isUser() && !isUserdebug()) {
410 ALOGE("Failed to determine the build type: got %s, want 'eng', 'user', or 'userdebug'",
411 getBuildType().c_str());
412 return 1;
413 }
414
415 if (runningAsRoot) {
416 // Note: writing this proc file requires being root (always the case on V+)
417
418 // Linux 5.16-rc1 changed the default to 2 (disabled but changeable),
419 // but we need 0 (enabled)
420 // (this writeFile is known to fail on at least 4.19, but always defaults to 0 on
421 // pre-5.13, on 5.13+ it depends on CONFIG_BPF_UNPRIV_DEFAULT_OFF)
422 if (writeProcSysFile("/proc/sys/kernel/unprivileged_bpf_disabled", "0\n") &&
423 isAtLeastKernelVersion(5, 13, 0)) return 1;
424 }
425
426 if (isAtLeastU) {
427 // Note: writing these proc files requires CAP_NET_ADMIN
428 // and sepolicy which is only present on U+,
429 // on Android T and earlier versions they're written from the 'load_bpf_programs'
430 // trigger (ie. by init itself) instead.
431
432 // Enable the eBPF JIT -- but do note that on 64-bit kernels it is likely
433 // already force enabled by the kernel config option BPF_JIT_ALWAYS_ON.
434 // (Note: this (open) will fail with ENOENT 'No such file or directory' if
435 // kernel does not have CONFIG_BPF_JIT=y)
436 // BPF_JIT is required by R VINTF (which means 4.14/4.19/5.4 kernels),
437 // but 4.14/4.19 were released with P & Q, and only 5.4 is new in R+.
438 if (writeProcSysFile("/proc/sys/net/core/bpf_jit_enable", "1\n")) return 1;
439
440 // Enable JIT kallsyms export for privileged users only
441 // (Note: this (open) will fail with ENOENT 'No such file or directory' if
442 // kernel does not have CONFIG_HAVE_EBPF_JIT=y)
443 if (writeProcSysFile("/proc/sys/net/core/bpf_jit_kallsyms", "1\n")) return 1;
444 }
445
446 // Create all the pin subdirectories
447 // (this must be done first to allow selinux_context and pin_subdir functionality,
448 // which could otherwise fail with ENOENT during object pinning or renaming,
449 // due to ordering issues)
450 for (const auto& location : locations) {
451 if (createSysFsBpfSubDir(location.prefix)) return 1;
452 }
453
454 // Note: there's no actual src dir for fs_bpf_loader .o's,
455 // so it is not listed in 'locations[].prefix'.
456 // This is because this is primarily meant for triggering genfscon rules,
457 // and as such this will likely always be the case.
458 // Thus we need to manually create the /sys/fs/bpf/loader subdirectory.
459 if (createSysFsBpfSubDir("loader")) return 1;
460
461 // Load all ELF objects, create programs and maps, and pin them
462 for (const auto& location : locations) {
463 if (loadAllElfObjects(bpfloader_ver, location) != 0) {
464 ALOGE("=== CRITICAL FAILURE LOADING BPF PROGRAMS FROM %s ===", location.dir);
465 ALOGE("If this triggers reliably, you're probably missing kernel options or patches.");
466 ALOGE("If this triggers randomly, you might be hitting some memory allocation "
467 "problems or startup script race.");
468 ALOGE("--- DO NOT EXPECT SYSTEM TO BOOT SUCCESSFULLY ---");
469 sleep(20);
470 return 2;
471 }
472 }
473
474 int key = 1;
475 int value = 123;
476 base::unique_fd map(
477 createMap(BPF_MAP_TYPE_ARRAY, sizeof(key), sizeof(value), 2, 0));
478 if (writeToMapEntry(map, &key, &value, BPF_ANY)) {
479 ALOGE("Critical kernel bug - failure to write into index 1 of 2 element bpf map array.");
480 return 1;
481 }
482
483 // leave a flag that we're done
484 if (createSysFsBpfSubDir("netd_shared/mainline_done")) return 1;
485
486 // platform bpfloader will only succeed when run as root
487 if (!runningAsRoot) {
488 // unreachable on U QPR3+ which always runs netbpfload as root
489
490 ALOGI("mainline done, no need to transfer control to platform bpf loader.");
491 return 0;
492 }
493
494 // unreachable before U QPR3
495 ALOGI("done, transferring control to platform bpfloader.");
496
497 // platform BpfLoader *needs* to run as root
498 const char * args[] = { platformBpfLoader, NULL, };
499 execve(args[0], (char**)args, envp);
500 ALOGE("FATAL: execve('%s'): %d[%s]", platformBpfLoader, errno, strerror(errno));
501 return 1;
502 }
503
504 } // namespace bpf
505 } // namespace android
506
main(int argc,char ** argv,char * const envp[])507 int main(int argc, char** argv, char * const envp[]) {
508 android::base::InitLogging(argv, &android::base::KernelLogger);
509
510 if (argc == 2 && !strcmp(argv[1], "done")) {
511 // we're being re-exec'ed from platform bpfloader to 'finalize' things
512 if (!android::base::SetProperty("bpf.progs_loaded", "1")) {
513 ALOGE("Failed to set bpf.progs_loaded property to 1.");
514 return 125;
515 }
516 ALOGI("success.");
517 return 0;
518 }
519
520 return android::bpf::doLoad(argv, envp);
521 }
522