blob: 11b2c9004b9443517bfabb44bb06355ebdda5982 [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
41#include <android-base/logging.h>
42#include <android-base/macros.h>
43#include <android-base/properties.h>
44#include <android-base/stringprintf.h>
45#include <android-base/strings.h>
46#include <android-base/unique_fd.h>
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -070047#include <log/log.h>
Maciej Żenczykowski40dfe532023-10-08 20:21:11 -070048
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -070049#include "BpfSyscallWrappers.h"
50#include "bpf/BpfUtils.h"
Maciej Żenczykowski40dfe532023-10-08 20:21:11 -070051#include "loader.h"
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -070052
53using android::base::EndsWith;
54using android::bpf::domain;
55using std::string;
56
57bool exists(const char* const path) {
58 int v = access(path, F_OK);
59 if (!v) {
60 ALOGI("%s exists.", path);
61 return true;
62 }
63 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
68constexpr unsigned long long kTetheringApexDomainBitmask =
69 domainToBitmask(domain::tethering) |
70 domainToBitmask(domain::net_private) |
71 domainToBitmask(domain::net_shared) |
72 domainToBitmask(domain::netd_readonly) |
73 domainToBitmask(domain::netd_shared);
74
75// Programs shipped inside the tethering apex should be limited to networking stuff,
76// as KPROBE, PERF_EVENT, TRACEPOINT are dangerous to use from mainline updatable code,
77// since they are less stable abi/api and may conflict with platform uses of bpf.
78constexpr bpf_prog_type kTetheringApexAllowedProgTypes[] = {
79 BPF_PROG_TYPE_CGROUP_SKB,
80 BPF_PROG_TYPE_CGROUP_SOCK,
81 BPF_PROG_TYPE_CGROUP_SOCKOPT,
82 BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
83 BPF_PROG_TYPE_CGROUP_SYSCTL,
84 BPF_PROG_TYPE_LWT_IN,
85 BPF_PROG_TYPE_LWT_OUT,
86 BPF_PROG_TYPE_LWT_SEG6LOCAL,
87 BPF_PROG_TYPE_LWT_XMIT,
88 BPF_PROG_TYPE_SCHED_ACT,
89 BPF_PROG_TYPE_SCHED_CLS,
90 BPF_PROG_TYPE_SOCKET_FILTER,
91 BPF_PROG_TYPE_SOCK_OPS,
92 BPF_PROG_TYPE_XDP,
93};
94
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -070095
96const android::bpf::Location locations[] = {
97 // S+ Tethering mainline module (network_stack): tether offload
98 {
99 .dir = "/apex/com.android.tethering/etc/bpf/",
100 .prefix = "tethering/",
101 .allowedDomainBitmask = kTetheringApexDomainBitmask,
102 .allowedProgTypes = kTetheringApexAllowedProgTypes,
103 .allowedProgTypesLength = arraysize(kTetheringApexAllowedProgTypes),
104 },
105 // T+ Tethering mainline module (shared with netd & system server)
106 // netutils_wrapper (for iptables xt_bpf) has access to programs
107 {
108 .dir = "/apex/com.android.tethering/etc/bpf/netd_shared/",
109 .prefix = "netd_shared/",
110 .allowedDomainBitmask = kTetheringApexDomainBitmask,
111 .allowedProgTypes = kTetheringApexAllowedProgTypes,
112 .allowedProgTypesLength = arraysize(kTetheringApexAllowedProgTypes),
113 },
114 // T+ Tethering mainline module (shared with netd & system server)
115 // netutils_wrapper has no access, netd has read only access
116 {
117 .dir = "/apex/com.android.tethering/etc/bpf/netd_readonly/",
118 .prefix = "netd_readonly/",
119 .allowedDomainBitmask = kTetheringApexDomainBitmask,
120 .allowedProgTypes = kTetheringApexAllowedProgTypes,
121 .allowedProgTypesLength = arraysize(kTetheringApexAllowedProgTypes),
122 },
123 // T+ Tethering mainline module (shared with system server)
124 {
125 .dir = "/apex/com.android.tethering/etc/bpf/net_shared/",
126 .prefix = "net_shared/",
127 .allowedDomainBitmask = kTetheringApexDomainBitmask,
128 .allowedProgTypes = kTetheringApexAllowedProgTypes,
129 .allowedProgTypesLength = arraysize(kTetheringApexAllowedProgTypes),
130 },
131 // T+ Tethering mainline module (not shared, just network_stack)
132 {
133 .dir = "/apex/com.android.tethering/etc/bpf/net_private/",
134 .prefix = "net_private/",
135 .allowedDomainBitmask = kTetheringApexDomainBitmask,
136 .allowedProgTypes = kTetheringApexAllowedProgTypes,
137 .allowedProgTypesLength = arraysize(kTetheringApexAllowedProgTypes),
138 },
Maciej Żenczykowski60c159f2023-10-02 14:54:48 -0700139};
140
141int loadAllElfObjects(const android::bpf::Location& location) {
142 int retVal = 0;
143 DIR* dir;
144 struct dirent* ent;
145
146 if ((dir = opendir(location.dir)) != NULL) {
147 while ((ent = readdir(dir)) != NULL) {
148 string s = ent->d_name;
149 if (!EndsWith(s, ".o")) continue;
150
151 string progPath(location.dir);
152 progPath += s;
153
154 bool critical;
155 int ret = android::bpf::loadProg(progPath.c_str(), &critical, location);
156 if (ret) {
157 if (critical) retVal = ret;
158 ALOGE("Failed to load object: %s, ret: %s", progPath.c_str(), std::strerror(-ret));
159 } else {
160 ALOGI("Loaded object: %s", progPath.c_str());
161 }
162 }
163 closedir(dir);
164 }
165 return retVal;
166}
167
168int createSysFsBpfSubDir(const char* const prefix) {
169 if (*prefix) {
170 mode_t prevUmask = umask(0);
171
172 string s = "/sys/fs/bpf/";
173 s += prefix;
174
175 errno = 0;
176 int ret = mkdir(s.c_str(), S_ISVTX | S_IRWXU | S_IRWXG | S_IRWXO);
177 if (ret && errno != EEXIST) {
178 const int err = errno;
179 ALOGE("Failed to create directory: %s, ret: %s", s.c_str(), std::strerror(err));
180 return -err;
181 }
182
183 umask(prevUmask);
184 }
185 return 0;
186}
187
188// Technically 'value' doesn't need to be newline terminated, but it's best
189// to include a newline to match 'echo "value" > /proc/sys/...foo' behaviour,
190// which is usually how kernel devs test the actual sysctl interfaces.
191int writeProcSysFile(const char *filename, const char *value) {
192 android::base::unique_fd fd(open(filename, O_WRONLY | O_CLOEXEC));
193 if (fd < 0) {
194 const int err = errno;
195 ALOGE("open('%s', O_WRONLY | O_CLOEXEC) -> %s", filename, strerror(err));
196 return -err;
197 }
198 int len = strlen(value);
199 int v = write(fd, value, len);
200 if (v < 0) {
201 const int err = errno;
202 ALOGE("write('%s', '%s', %d) -> %s", filename, value, len, strerror(err));
203 return -err;
204 }
205 if (v != len) {
206 // In practice, due to us only using this for /proc/sys/... files, this can't happen.
207 ALOGE("write('%s', '%s', %d) -> short write [%d]", filename, value, len, v);
208 return -EINVAL;
209 }
210 return 0;
211}
212
213int main(int argc, char** argv) {
214 (void)argc;
215 android::base::InitLogging(argv, &android::base::KernelLogger);
216
217 if (!android::bpf::isAtLeastKernelVersion(4, 19, 0)) {
218 ALOGE("Android U QPR2 requires kernel 4.19.");
219 return 1;
220 }
221
222 if (android::bpf::isUserspace32bit() && android::bpf::isAtLeastKernelVersion(6, 2, 0)) {
223 /* Android 14/U should only launch on 64-bit kernels
224 * T launches on 5.10/5.15
225 * U launches on 5.15/6.1
226 * So >=5.16 implies isKernel64Bit()
227 *
228 * We thus added a test to V VTS which requires 5.16+ devices to use 64-bit kernels.
229 *
230 * Starting with Android V, which is the first to support a post 6.1 Linux Kernel,
231 * we also require 64-bit userspace.
232 *
233 * There are various known issues with 32-bit userspace talking to various
234 * kernel interfaces (especially CAP_NET_ADMIN ones) on a 64-bit kernel.
235 * Some of these have userspace or kernel workarounds/hacks.
236 * Some of them don't...
237 * We're going to be removing the hacks.
238 *
239 * Additionally the 32-bit kernel jit support is poor,
240 * and 32-bit userspace on 64-bit kernel bpf ringbuffer compatibility is broken.
241 */
242 ALOGE("64-bit userspace required on 6.2+ kernels.");
243 return 1;
244 }
245
246 // Ensure we can determine the Android build type.
247 if (!android::bpf::isEng() && !android::bpf::isUser() && !android::bpf::isUserdebug()) {
248 ALOGE("Failed to determine the build type: got %s, want 'eng', 'user', or 'userdebug'",
249 android::bpf::getBuildType().c_str());
250 return 1;
251 }
252
253 // Linux 5.16-rc1 changed the default to 2 (disabled but changeable), but we need 0 (enabled)
254 // (this writeFile is known to fail on at least 4.19, but always defaults to 0 on pre-5.13,
255 // on 5.13+ it depends on CONFIG_BPF_UNPRIV_DEFAULT_OFF)
256 if (writeProcSysFile("/proc/sys/kernel/unprivileged_bpf_disabled", "0\n") &&
257 android::bpf::isAtLeastKernelVersion(5, 13, 0)) return 1;
258
259 // Enable the eBPF JIT -- but do note that on 64-bit kernels it is likely
260 // already force enabled by the kernel config option BPF_JIT_ALWAYS_ON.
261 // (Note: this (open) will fail with ENOENT 'No such file or directory' if
262 // kernel does not have CONFIG_BPF_JIT=y)
263 // BPF_JIT is required by R VINTF (which means 4.14/4.19/5.4 kernels),
264 // but 4.14/4.19 were released with P & Q, and only 5.4 is new in R+.
265 if (writeProcSysFile("/proc/sys/net/core/bpf_jit_enable", "1\n")) return 1;
266
267 // Enable JIT kallsyms export for privileged users only
268 // (Note: this (open) will fail with ENOENT 'No such file or directory' if
269 // kernel does not have CONFIG_HAVE_EBPF_JIT=y)
270 if (writeProcSysFile("/proc/sys/net/core/bpf_jit_kallsyms", "1\n")) return 1;
271
272 // Create all the pin subdirectories
273 // (this must be done first to allow selinux_context and pin_subdir functionality,
274 // which could otherwise fail with ENOENT during object pinning or renaming,
275 // due to ordering issues)
276 for (const auto& location : locations) {
277 if (createSysFsBpfSubDir(location.prefix)) return 1;
278 }
279
280 // Note: there's no actual src dir for fs_bpf_loader .o's,
281 // so it is not listed in 'locations[].prefix'.
282 // This is because this is primarily meant for triggering genfscon rules,
283 // and as such this will likely always be the case.
284 // Thus we need to manually create the /sys/fs/bpf/loader subdirectory.
285 if (createSysFsBpfSubDir("loader")) return 1;
286
287 // Load all ELF objects, create programs and maps, and pin them
288 for (const auto& location : locations) {
289 if (loadAllElfObjects(location) != 0) {
290 ALOGE("=== CRITICAL FAILURE LOADING BPF PROGRAMS FROM %s ===", location.dir);
291 ALOGE("If this triggers reliably, you're probably missing kernel options or patches.");
292 ALOGE("If this triggers randomly, you might be hitting some memory allocation "
293 "problems or startup script race.");
294 ALOGE("--- DO NOT EXPECT SYSTEM TO BOOT SUCCESSFULLY ---");
295 sleep(20);
296 return 2;
297 }
298 }
299
300 int key = 1;
301 int value = 123;
302 android::base::unique_fd map(
303 android::bpf::createMap(BPF_MAP_TYPE_ARRAY, sizeof(key), sizeof(value), 2, 0));
304 if (android::bpf::writeToMapEntry(map, &key, &value, BPF_ANY)) {
305 ALOGE("Critical kernel bug - failure to write into index 1 of 2 element bpf map array.");
306 return 1;
307 }
308
309 if (android::base::SetProperty("bpf.progs_loaded", "1") == false) {
310 ALOGE("Failed to set bpf.progs_loaded property");
311 return 1;
312 }
313
314 return 0;
315}