xref: /aosp_15_r20/system/bpf/loader/Loader.cpp (revision 55039e042b8390f50b0bdd70c11a2419f6d8fd50)
1 /*
2  * Copyright (C) 2018 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 #define LOG_TAG "BpfLoader"
18 
19 #include <errno.h>
20 #include <fcntl.h>
21 #include <linux/bpf.h>
22 #include <linux/elf.h>
23 #include <log/log.h>
24 #include <stdint.h>
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <string.h>
28 #include <sysexits.h>
29 #include <sys/stat.h>
30 #include <sys/utsname.h>
31 #include <sys/wait.h>
32 #include <unistd.h>
33 
34 #include "BpfSyscallWrappers.h"
35 #include "bpf/BpfUtils.h"
36 #include "bpf_map_def.h"
37 #include "include/libbpf_android.h"
38 
39 #include <cstdlib>
40 #include <fstream>
41 #include <iostream>
42 #include <optional>
43 #include <string>
44 #include <unordered_map>
45 #include <vector>
46 
47 #include <android-base/cmsg.h>
48 #include <android-base/file.h>
49 #include <android-base/logging.h>
50 #include <android-base/strings.h>
51 #include <android-base/unique_fd.h>
52 
53 #define BPF_FS_PATH "/sys/fs/bpf/"
54 
55 // Size of the BPF log buffer for verifier logging
56 #define BPF_LOAD_LOG_SZ 0xfffff
57 
58 using android::base::EndsWith;
59 using android::base::StartsWith;
60 using android::base::unique_fd;
61 using std::ifstream;
62 using std::ios;
63 using std::optional;
64 using std::strerror;
65 using std::string;
66 using std::vector;
67 
68 namespace android {
69 namespace bpf {
70 
71 static unsigned int page_size = static_cast<unsigned int>(getpagesize());
72 
pathToObjName(const string & path)73 static string pathToObjName(const string& path) {
74     // extract everything after the final slash, ie. this is the filename '[email protected]' or 'bar.o'
75     string filename = android::base::Split(path, "/").back();
76     // strip off everything from the final period onwards (strip '.o' suffix), ie. 'foo@1' or 'bar'
77     string name = filename.substr(0, filename.find_last_of('.'));
78     // strip any potential @1 suffix, this will leave us with just 'foo' or 'bar'
79     // this can be used to provide duplicate programs (mux based on the bpfloader version)
80     return name.substr(0, name.find_last_of('@'));
81 }
82 
83 typedef struct {
84     const char* name;
85     enum bpf_prog_type type;
86 } sectionType;
87 
88 /*
89  * Map section name prefixes to program types, the section name will be:
90  *   SECTION(<prefix>/<name-of-program>)
91  * For example:
92  *   SECTION("tracepoint/sched_switch_func") where sched_switch_funcs
93  * is the name of the program, and tracepoint is the type.
94  *
95  * However, be aware that you should not be directly using the SECTION() macro.
96  * Instead use the DEFINE_(BPF|XDP)_(PROG|MAP)... & LICENSE/CRITICAL macros.
97  */
98 sectionType sectionNameTypes[] = {
99         {"kprobe/",        BPF_PROG_TYPE_KPROBE},
100         {"kretprobe/",     BPF_PROG_TYPE_KPROBE},
101         {"perf_event/",    BPF_PROG_TYPE_PERF_EVENT},
102         {"skfilter/",      BPF_PROG_TYPE_SOCKET_FILTER},
103         {"tracepoint/",    BPF_PROG_TYPE_TRACEPOINT},
104         {"uprobe/",        BPF_PROG_TYPE_KPROBE},
105         {"uretprobe/",     BPF_PROG_TYPE_KPROBE},
106 };
107 
108 typedef struct {
109     enum bpf_prog_type type;
110     string name;
111     vector<char> data;
112     vector<char> rel_data;
113     optional<struct bpf_prog_def> prog_def;
114 
115     unique_fd prog_fd; /* fd after loading */
116 } codeSection;
117 
readElfHeader(ifstream & elfFile,Elf64_Ehdr * eh)118 static int readElfHeader(ifstream& elfFile, Elf64_Ehdr* eh) {
119     elfFile.seekg(0);
120     if (elfFile.fail()) return -1;
121 
122     if (!elfFile.read((char*)eh, sizeof(*eh))) return -1;
123 
124     return 0;
125 }
126 
127 /* Reads all section header tables into an Shdr array */
readSectionHeadersAll(ifstream & elfFile,vector<Elf64_Shdr> & shTable)128 static int readSectionHeadersAll(ifstream& elfFile, vector<Elf64_Shdr>& shTable) {
129     Elf64_Ehdr eh;
130     int ret = 0;
131 
132     ret = readElfHeader(elfFile, &eh);
133     if (ret) return ret;
134 
135     elfFile.seekg(eh.e_shoff);
136     if (elfFile.fail()) return -1;
137 
138     /* Read shdr table entries */
139     shTable.resize(eh.e_shnum);
140 
141     if (!elfFile.read((char*)shTable.data(), (eh.e_shnum * eh.e_shentsize))) return -ENOMEM;
142 
143     return 0;
144 }
145 
146 /* Read a section by its index - for ex to get sec hdr strtab blob */
readSectionByIdx(ifstream & elfFile,int id,vector<char> & sec)147 static int readSectionByIdx(ifstream& elfFile, int id, vector<char>& sec) {
148     vector<Elf64_Shdr> shTable;
149     int ret = readSectionHeadersAll(elfFile, shTable);
150     if (ret) return ret;
151 
152     elfFile.seekg(shTable[id].sh_offset);
153     if (elfFile.fail()) return -1;
154 
155     sec.resize(shTable[id].sh_size);
156     if (!elfFile.read(sec.data(), shTable[id].sh_size)) return -1;
157 
158     return 0;
159 }
160 
161 /* Read whole section header string table */
readSectionHeaderStrtab(ifstream & elfFile,vector<char> & strtab)162 static int readSectionHeaderStrtab(ifstream& elfFile, vector<char>& strtab) {
163     Elf64_Ehdr eh;
164     int ret = readElfHeader(elfFile, &eh);
165     if (ret) return ret;
166 
167     ret = readSectionByIdx(elfFile, eh.e_shstrndx, strtab);
168     if (ret) return ret;
169 
170     return 0;
171 }
172 
173 /* Get name from offset in strtab */
getSymName(ifstream & elfFile,int nameOff,string & name)174 static int getSymName(ifstream& elfFile, int nameOff, string& name) {
175     int ret;
176     vector<char> secStrTab;
177 
178     ret = readSectionHeaderStrtab(elfFile, secStrTab);
179     if (ret) return ret;
180 
181     if (nameOff >= (int)secStrTab.size()) return -1;
182 
183     name = string((char*)secStrTab.data() + nameOff);
184     return 0;
185 }
186 
187 /* Reads a full section by name - example to get the GPL license */
readSectionByName(const char * name,ifstream & elfFile,vector<char> & data)188 static int readSectionByName(const char* name, ifstream& elfFile, vector<char>& data) {
189     vector<char> secStrTab;
190     vector<Elf64_Shdr> shTable;
191     int ret;
192 
193     ret = readSectionHeadersAll(elfFile, shTable);
194     if (ret) return ret;
195 
196     ret = readSectionHeaderStrtab(elfFile, secStrTab);
197     if (ret) return ret;
198 
199     for (int i = 0; i < (int)shTable.size(); i++) {
200         char* secname = secStrTab.data() + shTable[i].sh_name;
201         if (!secname) continue;
202 
203         if (!strcmp(secname, name)) {
204             vector<char> dataTmp;
205             dataTmp.resize(shTable[i].sh_size);
206 
207             elfFile.seekg(shTable[i].sh_offset);
208             if (elfFile.fail()) return -1;
209 
210             if (!elfFile.read((char*)dataTmp.data(), shTable[i].sh_size)) return -1;
211 
212             data = dataTmp;
213             return 0;
214         }
215     }
216     return -2;
217 }
218 
readSectionUint(const char * name,ifstream & elfFile,unsigned int defVal)219 unsigned int readSectionUint(const char* name, ifstream& elfFile, unsigned int defVal) {
220     vector<char> theBytes;
221     int ret = readSectionByName(name, elfFile, theBytes);
222     if (ret) {
223         ALOGV("Couldn't find section %s (defaulting to %u [0x%x]).", name, defVal, defVal);
224         return defVal;
225     } else if (theBytes.size() < sizeof(unsigned int)) {
226         ALOGE("Section %s too short (defaulting to %u [0x%x]).", name, defVal, defVal);
227         return defVal;
228     } else {
229         // decode first 4 bytes as LE32 uint, there will likely be more bytes due to alignment.
230         unsigned int value = static_cast<unsigned char>(theBytes[3]);
231         value <<= 8;
232         value += static_cast<unsigned char>(theBytes[2]);
233         value <<= 8;
234         value += static_cast<unsigned char>(theBytes[1]);
235         value <<= 8;
236         value += static_cast<unsigned char>(theBytes[0]);
237         ALOGV("Section %s value is %u [0x%x]", name, value, value);
238         return value;
239     }
240 }
241 
readSectionByType(ifstream & elfFile,int type,vector<char> & data)242 static int readSectionByType(ifstream& elfFile, int type, vector<char>& data) {
243     int ret;
244     vector<Elf64_Shdr> shTable;
245 
246     ret = readSectionHeadersAll(elfFile, shTable);
247     if (ret) return ret;
248 
249     for (int i = 0; i < (int)shTable.size(); i++) {
250         if ((int)shTable[i].sh_type != type) continue;
251 
252         vector<char> dataTmp;
253         dataTmp.resize(shTable[i].sh_size);
254 
255         elfFile.seekg(shTable[i].sh_offset);
256         if (elfFile.fail()) return -1;
257 
258         if (!elfFile.read((char*)dataTmp.data(), shTable[i].sh_size)) return -1;
259 
260         data = dataTmp;
261         return 0;
262     }
263     return -2;
264 }
265 
symCompare(Elf64_Sym a,Elf64_Sym b)266 static bool symCompare(Elf64_Sym a, Elf64_Sym b) {
267     return (a.st_value < b.st_value);
268 }
269 
readSymTab(ifstream & elfFile,int sort,vector<Elf64_Sym> & data)270 static int readSymTab(ifstream& elfFile, int sort, vector<Elf64_Sym>& data) {
271     int ret, numElems;
272     Elf64_Sym* buf;
273     vector<char> secData;
274 
275     ret = readSectionByType(elfFile, SHT_SYMTAB, secData);
276     if (ret) return ret;
277 
278     buf = (Elf64_Sym*)secData.data();
279     numElems = (secData.size() / sizeof(Elf64_Sym));
280     data.assign(buf, buf + numElems);
281 
282     if (sort) std::sort(data.begin(), data.end(), symCompare);
283     return 0;
284 }
285 
getFuseProgType()286 static enum bpf_prog_type getFuseProgType() {
287     int result = BPF_PROG_TYPE_UNSPEC;
288     ifstream("/sys/fs/fuse/bpf_prog_type_fuse") >> result;
289     return static_cast<bpf_prog_type>(result);
290 }
291 
getSectionType(string & name)292 static enum bpf_prog_type getSectionType(string& name) {
293     for (auto& snt : sectionNameTypes)
294         if (StartsWith(name, snt.name)) return snt.type;
295 
296     // TODO Remove this code when fuse-bpf is upstream and this BPF_PROG_TYPE_FUSE is fixed
297     if (StartsWith(name, "fuse/")) return getFuseProgType();
298 
299     return BPF_PROG_TYPE_UNSPEC;
300 }
301 
getSectionName(enum bpf_prog_type type)302 static string getSectionName(enum bpf_prog_type type)
303 {
304     for (auto& snt : sectionNameTypes)
305         if (snt.type == type)
306             return string(snt.name);
307 
308     return "UNKNOWN SECTION NAME " + std::to_string(type);
309 }
310 
readProgDefs(ifstream & elfFile,vector<struct bpf_prog_def> & pd)311 static int readProgDefs(ifstream& elfFile, vector<struct bpf_prog_def>& pd) {
312     vector<char> pdData;
313     int ret = readSectionByName("progs", elfFile, pdData);
314     if (ret) return ret;
315 
316     if (pdData.size() % sizeof(struct bpf_prog_def)) {
317         ALOGE("readProgDefs failed due to improper sized progs section, %zu %% %zu != 0",
318               pdData.size(), sizeof(struct bpf_prog_def));
319         return -1;
320     };
321 
322     pd.resize(pdData.size() / sizeof(struct bpf_prog_def));
323     memcpy(pd.data(), pdData.data(), pdData.size());
324     return 0;
325 }
326 
getSectionSymNames(ifstream & elfFile,const string & sectionName,vector<string> & names,optional<unsigned> symbolType=std::nullopt)327 static int getSectionSymNames(ifstream& elfFile, const string& sectionName, vector<string>& names,
328                               optional<unsigned> symbolType = std::nullopt) {
329     int ret;
330     string name;
331     vector<Elf64_Sym> symtab;
332     vector<Elf64_Shdr> shTable;
333 
334     ret = readSymTab(elfFile, 1 /* sort */, symtab);
335     if (ret) return ret;
336 
337     /* Get index of section */
338     ret = readSectionHeadersAll(elfFile, shTable);
339     if (ret) return ret;
340 
341     int sec_idx = -1;
342     for (int i = 0; i < (int)shTable.size(); i++) {
343         ret = getSymName(elfFile, shTable[i].sh_name, name);
344         if (ret) return ret;
345 
346         if (!name.compare(sectionName)) {
347             sec_idx = i;
348             break;
349         }
350     }
351 
352     /* No section found with matching name*/
353     if (sec_idx == -1) {
354         ALOGW("No %s section could be found in elf object", sectionName.c_str());
355         return -1;
356     }
357 
358     for (int i = 0; i < (int)symtab.size(); i++) {
359         if (symbolType.has_value() && ELF_ST_TYPE(symtab[i].st_info) != symbolType) continue;
360 
361         if (symtab[i].st_shndx == sec_idx) {
362             string s;
363             ret = getSymName(elfFile, symtab[i].st_name, s);
364             if (ret) return ret;
365             names.push_back(s);
366         }
367     }
368 
369     return 0;
370 }
371 
IsAllowed(bpf_prog_type type,const bpf_prog_type * allowed,size_t numAllowed)372 static bool IsAllowed(bpf_prog_type type, const bpf_prog_type* allowed, size_t numAllowed) {
373     if (allowed == nullptr) return true;
374 
375     for (size_t i = 0; i < numAllowed; i++) {
376         if (allowed[i] == BPF_PROG_TYPE_UNSPEC) {
377             if (type == getFuseProgType()) return true;
378         } else if (type == allowed[i])
379             return true;
380     }
381 
382     return false;
383 }
384 
385 /* Read a section by its index - for ex to get sec hdr strtab blob */
readCodeSections(ifstream & elfFile,vector<codeSection> & cs,const bpf_prog_type * allowed,size_t numAllowed)386 static int readCodeSections(ifstream& elfFile, vector<codeSection>& cs,
387                             const bpf_prog_type* allowed, size_t numAllowed) {
388     vector<Elf64_Shdr> shTable;
389     int entries, ret = 0;
390 
391     ret = readSectionHeadersAll(elfFile, shTable);
392     if (ret) return ret;
393     entries = shTable.size();
394 
395     vector<struct bpf_prog_def> pd;
396     ret = readProgDefs(elfFile, pd);
397     if (ret) return ret;
398     vector<string> progDefNames;
399     ret = getSectionSymNames(elfFile, "progs", progDefNames);
400     if (!pd.empty() && ret) return ret;
401 
402     for (int i = 0; i < entries; i++) {
403         string name;
404         codeSection cs_temp;
405         cs_temp.type = BPF_PROG_TYPE_UNSPEC;
406 
407         ret = getSymName(elfFile, shTable[i].sh_name, name);
408         if (ret) return ret;
409 
410         enum bpf_prog_type ptype = getSectionType(name);
411 
412         if (ptype == BPF_PROG_TYPE_UNSPEC) continue;
413 
414         if (!IsAllowed(ptype, allowed, numAllowed)) {
415             ALOGE("Program type %s not permitted here", getSectionName(ptype).c_str());
416             return -1;
417         }
418 
419         string oldName = name;
420 
421         // convert all slashes to underscores
422         std::replace(name.begin(), name.end(), '/', '_');
423 
424         cs_temp.type = ptype;
425         cs_temp.name = name;
426 
427         ret = readSectionByIdx(elfFile, i, cs_temp.data);
428         if (ret) return ret;
429         ALOGV("Loaded code section %d (%s)", i, name.c_str());
430 
431         vector<string> csSymNames;
432         ret = getSectionSymNames(elfFile, oldName, csSymNames, STT_FUNC);
433         if (ret || !csSymNames.size()) return ret;
434         for (size_t i = 0; i < progDefNames.size(); ++i) {
435             if (!progDefNames[i].compare(csSymNames[0] + "_def")) {
436                 cs_temp.prog_def = pd[i];
437                 break;
438             }
439         }
440 
441         /* Check for rel section */
442         if (cs_temp.data.size() > 0 && i < entries) {
443             ret = getSymName(elfFile, shTable[i + 1].sh_name, name);
444             if (ret) return ret;
445 
446             if (name == (".rel" + oldName)) {
447                 ret = readSectionByIdx(elfFile, i + 1, cs_temp.rel_data);
448                 if (ret) return ret;
449                 ALOGV("Loaded relo section %d (%s)", i, name.c_str());
450             }
451         }
452 
453         if (cs_temp.data.size() > 0) {
454             cs.push_back(std::move(cs_temp));
455             ALOGV("Adding section %d to cs list", i);
456         }
457     }
458     return 0;
459 }
460 
getSymNameByIdx(ifstream & elfFile,int index,string & name)461 static int getSymNameByIdx(ifstream& elfFile, int index, string& name) {
462     vector<Elf64_Sym> symtab;
463     int ret = 0;
464 
465     ret = readSymTab(elfFile, 0 /* !sort */, symtab);
466     if (ret) return ret;
467 
468     if (index >= (int)symtab.size()) return -1;
469 
470     return getSymName(elfFile, symtab[index].st_name, name);
471 }
472 
mapMatchesExpectations(const unique_fd & fd,const string & mapName,const struct bpf_map_def & mapDef,const enum bpf_map_type type)473 static bool mapMatchesExpectations(const unique_fd& fd, const string& mapName,
474                                    const struct bpf_map_def& mapDef, const enum bpf_map_type type) {
475     // Assuming fd is a valid Bpf Map file descriptor then
476     // all the following should always succeed on a 4.14+ kernel.
477     // If they somehow do fail, they'll return -1 (and set errno),
478     // which should then cause (among others) a key_size mismatch.
479     int fd_type = bpfGetFdMapType(fd);
480     int fd_key_size = bpfGetFdKeySize(fd);
481     int fd_value_size = bpfGetFdValueSize(fd);
482     int fd_max_entries = bpfGetFdMaxEntries(fd);
483     int fd_map_flags = bpfGetFdMapFlags(fd);
484 
485     // DEVMAPs are readonly from the bpf program side's point of view, as such
486     // the kernel in kernel/bpf/devmap.c dev_map_init_map() will set the flag
487     int desired_map_flags = (int)mapDef.map_flags;
488     if (type == BPF_MAP_TYPE_DEVMAP || type == BPF_MAP_TYPE_DEVMAP_HASH)
489         desired_map_flags |= BPF_F_RDONLY_PROG;
490 
491     // The .h file enforces that this is a power of two, and page size will
492     // also always be a power of two, so this logic is actually enough to
493     // force it to be a multiple of the page size, as required by the kernel.
494     unsigned int desired_max_entries = mapDef.max_entries;
495     if (type == BPF_MAP_TYPE_RINGBUF) {
496         if (desired_max_entries < page_size) desired_max_entries = page_size;
497     }
498 
499     // The following checks should *never* trigger, if one of them somehow does,
500     // it probably means a bpf .o file has been changed/replaced at runtime
501     // and bpfloader was manually rerun (normally it should only run *once*
502     // early during the boot process).
503     // Another possibility is that something is misconfigured in the code:
504     // most likely a shared map is declared twice differently.
505     // But such a change should never be checked into the source tree...
506     if ((fd_type == type) &&
507         (fd_key_size == (int)mapDef.key_size) &&
508         (fd_value_size == (int)mapDef.value_size) &&
509         (fd_max_entries == (int)desired_max_entries) &&
510         (fd_map_flags == desired_map_flags)) {
511         return true;
512     }
513 
514     ALOGE("bpf map name %s mismatch: desired/found: "
515           "type:%d/%d key:%u/%d value:%u/%d entries:%u/%d flags:%u/%d",
516           mapName.c_str(), type, fd_type, mapDef.key_size, fd_key_size, mapDef.value_size,
517           fd_value_size, mapDef.max_entries, fd_max_entries, desired_map_flags, fd_map_flags);
518     return false;
519 }
520 
createMaps(const char * elfPath,ifstream & elfFile,vector<unique_fd> & mapFds,const char * prefix)521 static int createMaps(const char* elfPath, ifstream& elfFile, vector<unique_fd>& mapFds,
522                       const char* prefix) {
523     int ret;
524     vector<char> mdData;
525     vector<struct bpf_map_def> md;
526     vector<string> mapNames;
527     string objName = pathToObjName(string(elfPath));
528 
529     ret = readSectionByName("maps", elfFile, mdData);
530     if (ret == -2) return 0;  // no maps to read
531     if (ret) return ret;
532 
533     if (mdData.size() % sizeof(struct bpf_map_def)) {
534         ALOGE("createMaps failed due to improper sized maps section, %zu %% %zu != 0",
535               mdData.size(), sizeof(struct bpf_map_def));
536         return -1;
537     }
538     md.resize(mdData.size() / sizeof(struct bpf_map_def));
539     memcpy(md.data(), mdData.data(), mdData.size());
540 
541     ret = getSectionSymNames(elfFile, "maps", mapNames);
542     if (ret) return ret;
543 
544     unsigned kvers = kernelVersion();
545 
546     for (int i = 0; i < (int)mapNames.size(); i++) {
547         if (md[i].zero != 0) abort();
548 
549         if (kvers < md[i].min_kver) {
550             ALOGD("skipping map %s which requires kernel version 0x%x >= 0x%x",
551                   mapNames[i].c_str(), kvers, md[i].min_kver);
552             mapFds.push_back(unique_fd());
553             continue;
554         }
555 
556         if (kvers >= md[i].max_kver) {
557             ALOGD("skipping map %s which requires kernel version 0x%x < 0x%x",
558                   mapNames[i].c_str(), kvers, md[i].max_kver);
559             mapFds.push_back(unique_fd());
560             continue;
561         }
562 
563         enum bpf_map_type type = md[i].type;
564         if (type == BPF_MAP_TYPE_DEVMAP_HASH && !isAtLeastKernelVersion(5, 4, 0)) {
565             // On Linux Kernels older than 5.4 this map type doesn't exist, but it can kind
566             // of be approximated: HASH has the same userspace visible api.
567             // However it cannot be used by ebpf programs in the same way.
568             // Since bpf_redirect_map() only requires 4.14, a program using a DEVMAP_HASH map
569             // would fail to load (due to trying to redirect to a HASH instead of DEVMAP_HASH).
570             // One must thus tag any BPF_MAP_TYPE_DEVMAP_HASH + bpf_redirect_map() using
571             // programs as being 5.4+...
572             type = BPF_MAP_TYPE_HASH;
573         }
574 
575         // The .h file enforces that this is a power of two, and page size will
576         // also always be a power of two, so this logic is actually enough to
577         // force it to be a multiple of the page size, as required by the kernel.
578         unsigned int max_entries = md[i].max_entries;
579         if (type == BPF_MAP_TYPE_RINGBUF) {
580             if (max_entries < page_size) max_entries = page_size;
581         }
582 
583         // Format of pin location is /sys/fs/bpf/<prefix>map_<objName>_<mapName>
584         // except that maps shared across .o's have empty <objName>
585         // Note: <objName> refers to the extension-less basename of the .o file (without @ suffix).
586         string mapPinLoc = string(BPF_FS_PATH) + prefix + "map_" +
587                            (md[i].shared ? "" : objName) + "_" + mapNames[i];
588         bool reuse = false;
589         unique_fd fd;
590         int saved_errno;
591 
592         if (access(mapPinLoc.c_str(), F_OK) == 0) {
593             fd.reset(mapRetrieveRO(mapPinLoc.c_str()));
594             saved_errno = errno;
595             ALOGV("bpf_create_map reusing map %s, ret: %d", mapNames[i].c_str(), fd.get());
596             reuse = true;
597         } else {
598             union bpf_attr req = {
599               .map_type = type,
600               .key_size = md[i].key_size,
601               .value_size = md[i].value_size,
602               .max_entries = max_entries,
603               .map_flags = md[i].map_flags,
604             };
605             strlcpy(req.map_name, mapNames[i].c_str(), sizeof(req.map_name));
606             fd.reset(bpf(BPF_MAP_CREATE, req));
607             saved_errno = errno;
608             ALOGV("bpf_create_map name %s, ret: %d", mapNames[i].c_str(), fd.get());
609         }
610 
611         if (!fd.ok()) return -saved_errno;
612 
613         // When reusing a pinned map, we need to check the map type/sizes/etc match, but for
614         // safety (since reuse code path is rare) run these checks even if we just created it.
615         // We assume failure is due to pinned map mismatch, hence the 'NOT UNIQUE' return code.
616         if (!mapMatchesExpectations(fd, mapNames[i], md[i], type)) return -ENOTUNIQ;
617 
618         if (!reuse) {
619             ret = bpfFdPin(fd, mapPinLoc.c_str());
620             if (ret) {
621                 int err = errno;
622                 ALOGE("pin %s -> %d [%d:%s]", mapPinLoc.c_str(), ret, err, strerror(err));
623                 return -err;
624             }
625             ret = chmod(mapPinLoc.c_str(), md[i].mode);
626             if (ret) {
627                 int err = errno;
628                 ALOGE("chmod(%s, 0%o) = %d [%d:%s]", mapPinLoc.c_str(), md[i].mode, ret, err,
629                       strerror(err));
630                 return -err;
631             }
632             ret = chown(mapPinLoc.c_str(), (uid_t)md[i].uid, (gid_t)md[i].gid);
633             if (ret) {
634                 int err = errno;
635                 ALOGE("chown(%s, %u, %u) = %d [%d:%s]", mapPinLoc.c_str(), md[i].uid, md[i].gid,
636                       ret, err, strerror(err));
637                 return -err;
638             }
639         }
640 
641         int mapId = bpfGetFdMapId(fd);
642         if (mapId == -1) {
643             ALOGE("bpfGetFdMapId failed, ret: %d [%d]", mapId, errno);
644         } else {
645             ALOGD("map %s id %d", mapPinLoc.c_str(), mapId);
646         }
647 
648         mapFds.push_back(std::move(fd));
649     }
650 
651     return ret;
652 }
653 
applyRelo(void * insnsPtr,Elf64_Addr offset,int fd)654 static void applyRelo(void* insnsPtr, Elf64_Addr offset, int fd) {
655     int insnIndex;
656     struct bpf_insn *insn, *insns;
657 
658     insns = (struct bpf_insn*)(insnsPtr);
659 
660     insnIndex = offset / sizeof(struct bpf_insn);
661     insn = &insns[insnIndex];
662 
663     // Occasionally might be useful for relocation debugging, but pretty spammy
664     if (0) {
665         ALOGV("applying relo to instruction at byte offset: %llu, "
666               "insn offset %d, insn %llx",
667               (unsigned long long)offset, insnIndex, *(unsigned long long*)insn);
668     }
669 
670     if (insn->code != (BPF_LD | BPF_IMM | BPF_DW)) {
671         ALOGE("invalid relo for insn %d: code 0x%x", insnIndex, insn->code);
672         return;
673     }
674 
675     insn->imm = fd;
676     insn->src_reg = BPF_PSEUDO_MAP_FD;
677 }
678 
applyMapRelo(ifstream & elfFile,vector<unique_fd> & mapFds,vector<codeSection> & cs)679 static void applyMapRelo(ifstream& elfFile, vector<unique_fd> &mapFds, vector<codeSection>& cs) {
680     vector<string> mapNames;
681 
682     int ret = getSectionSymNames(elfFile, "maps", mapNames);
683     if (ret) return;
684 
685     for (int k = 0; k != (int)cs.size(); k++) {
686         Elf64_Rel* rel = (Elf64_Rel*)(cs[k].rel_data.data());
687         int n_rel = cs[k].rel_data.size() / sizeof(*rel);
688 
689         for (int i = 0; i < n_rel; i++) {
690             int symIndex = ELF64_R_SYM(rel[i].r_info);
691             string symName;
692 
693             ret = getSymNameByIdx(elfFile, symIndex, symName);
694             if (ret) return;
695 
696             /* Find the map fd and apply relo */
697             for (int j = 0; j < (int)mapNames.size(); j++) {
698                 if (!mapNames[j].compare(symName)) {
699                     applyRelo(cs[k].data.data(), rel[i].r_offset, mapFds[j]);
700                     break;
701                 }
702             }
703         }
704     }
705 }
706 
loadCodeSections(const char * elfPath,vector<codeSection> & cs,const string & license,const char * prefix)707 static int loadCodeSections(const char* elfPath, vector<codeSection>& cs, const string& license,
708                             const char* prefix) {
709     unsigned kvers = kernelVersion();
710 
711     if (!kvers) {
712         ALOGE("unable to get kernel version");
713         return -EINVAL;
714     }
715 
716     string objName = pathToObjName(string(elfPath));
717 
718     for (int i = 0; i < (int)cs.size(); i++) {
719         unique_fd& fd = cs[i].prog_fd;
720         int ret;
721         string name = cs[i].name;
722 
723         if (!cs[i].prog_def.has_value()) {
724             ALOGE("[%d] '%s' missing program definition! bad bpf.o build?", i, name.c_str());
725             return -EINVAL;
726         }
727 
728         unsigned min_kver = cs[i].prog_def->min_kver;
729         unsigned max_kver = cs[i].prog_def->max_kver;
730         if (kvers < min_kver || kvers >= max_kver) {
731             ALOGD("skipping program cs[%d].name:%s min_kver:%x max_kver:%x (kvers:%x)",
732                   i, name.c_str(), min_kver, max_kver, kvers);
733             continue;
734         }
735 
736         // strip any potential $foo suffix
737         // this can be used to provide duplicate programs
738         // conditionally loaded based on running kernel version
739         name = name.substr(0, name.find_last_of('$'));
740 
741         bool reuse = false;
742         // Format of pin location is
743         // /sys/fs/bpf/<prefix>prog_<objName>_<progName>
744         string progPinLoc = string(BPF_FS_PATH) + prefix + "prog_" +
745                             objName + '_' + string(name);
746         if (access(progPinLoc.c_str(), F_OK) == 0) {
747             fd.reset(retrieveProgram(progPinLoc.c_str()));
748             ALOGV("New bpf prog load reusing prog %s, ret: %d (%s)", progPinLoc.c_str(), fd.get(),
749                   (!fd.ok() ? std::strerror(errno) : "no error"));
750             reuse = true;
751         } else {
752             vector<char> log_buf(BPF_LOAD_LOG_SZ, 0);
753 
754             union bpf_attr req = {
755               .prog_type = cs[i].type,
756               .kern_version = kvers,
757               .license = ptr_to_u64(license.c_str()),
758               .insns = ptr_to_u64(cs[i].data.data()),
759               .insn_cnt = static_cast<__u32>(cs[i].data.size() / sizeof(struct bpf_insn)),
760               .log_level = 1,
761               .log_buf = ptr_to_u64(log_buf.data()),
762               .log_size = static_cast<__u32>(log_buf.size()),
763             };
764             strlcpy(req.prog_name, cs[i].name.c_str(), sizeof(req.prog_name));
765             fd.reset(bpf(BPF_PROG_LOAD, req));
766 
767             if (!fd.ok()) {
768                 ALOGW("BPF_PROG_LOAD call for %s (%s) returned fd: %d (%s)", elfPath,
769                       cs[i].name.c_str(), fd.get(), std::strerror(errno));
770 
771                 vector<string> lines = android::base::Split(log_buf.data(), "\n");
772 
773                 ALOGW("BPF_PROG_LOAD - BEGIN log_buf contents:");
774                 for (const auto& line : lines) ALOGW("%s", line.c_str());
775                 ALOGW("BPF_PROG_LOAD - END log_buf contents.");
776 
777                 if (cs[i].prog_def->optional) {
778                     ALOGW("failed program is marked optional - continuing...");
779                     continue;
780                 }
781                 ALOGE("non-optional program failed to load.");
782             }
783         }
784 
785         if (!fd.ok()) return fd.get();
786 
787         if (!reuse) {
788             ret = bpfFdPin(fd, progPinLoc.c_str());
789             if (ret) {
790                 int err = errno;
791                 ALOGE("create %s -> %d [%d:%s]", progPinLoc.c_str(), ret, err, strerror(err));
792                 return -err;
793             }
794             if (chmod(progPinLoc.c_str(), 0440)) {
795                 int err = errno;
796                 ALOGE("chmod %s 0440 -> [%d:%s]", progPinLoc.c_str(), err, strerror(err));
797                 return -err;
798             }
799             if (chown(progPinLoc.c_str(), (uid_t)cs[i].prog_def->uid,
800                       (gid_t)cs[i].prog_def->gid)) {
801                 int err = errno;
802                 ALOGE("chown %s %d %d -> [%d:%s]", progPinLoc.c_str(), cs[i].prog_def->uid,
803                       cs[i].prog_def->gid, err, strerror(err));
804                 return -err;
805             }
806         }
807 
808         int progId = bpfGetFdProgId(fd);
809         if (progId == -1) {
810             ALOGE("bpfGetFdProgId failed, ret: %d [%d]", progId, errno);
811         } else {
812             ALOGD("prog %s id %d", progPinLoc.c_str(), progId);
813         }
814     }
815 
816     return 0;
817 }
818 
loadProg(const char * elfPath,bool * isCritical,const Location & location)819 int loadProg(const char* elfPath, bool* isCritical, const Location& location) {
820     vector<char> license;
821     vector<char> critical;
822     vector<codeSection> cs;
823     vector<unique_fd> mapFds;
824     int ret;
825 
826     if (!isCritical) return -1;
827     *isCritical = false;
828 
829     ifstream elfFile(elfPath, ios::in | ios::binary);
830     if (!elfFile.is_open()) return -1;
831 
832     ret = readSectionByName("critical", elfFile, critical);
833     *isCritical = !ret;
834 
835     ret = readSectionByName("license", elfFile, license);
836     if (ret) {
837         ALOGE("Couldn't find license in %s", elfPath);
838         return ret;
839     }
840 
841     ALOGI("Platform BpfLoader loading %s%s ELF object %s with license %s",
842           *isCritical ? "critical for " : "optional", *isCritical ? (char*)critical.data() : "",
843           elfPath, (char*)license.data());
844 
845     ret = readCodeSections(elfFile, cs, location.allowedProgTypes, location.allowedProgTypesLength);
846     if (ret) {
847         ALOGE("Couldn't read all code sections in %s", elfPath);
848         return ret;
849     }
850 
851     ret = createMaps(elfPath, elfFile, mapFds, location.prefix);
852     if (ret) {
853         ALOGE("Failed to create maps: (ret=%d) in %s", ret, elfPath);
854         return ret;
855     }
856 
857     for (int i = 0; i < (int)mapFds.size(); i++)
858         ALOGV("map_fd found at %d is %d in %s", i, mapFds[i].get(), elfPath);
859 
860     applyMapRelo(elfFile, mapFds, cs);
861 
862     ret = loadCodeSections(elfPath, cs, string(license.data()), location.prefix);
863     if (ret) ALOGE("Failed to load programs, loadCodeSections ret=%d", ret);
864 
865     return ret;
866 }
867 
868 // Networking-related program types are limited to the Tethering Apex
869 // to prevent things from breaking due to conflicts on mainline updates
870 // (exception made for socket filters, ie. xt_bpf for potential use in iptables,
871 // or for attaching to sockets directly)
872 constexpr bpf_prog_type kPlatformAllowedProgTypes[] = {
873         BPF_PROG_TYPE_KPROBE,
874         BPF_PROG_TYPE_PERF_EVENT,
875         BPF_PROG_TYPE_SOCKET_FILTER,
876         BPF_PROG_TYPE_TRACEPOINT,
877         BPF_PROG_TYPE_UNSPEC,  // Will be replaced with fuse bpf program type
878 };
879 
880 constexpr bpf_prog_type kMemEventsAllowedProgTypes[] = {
881         BPF_PROG_TYPE_TRACEPOINT,
882         BPF_PROG_TYPE_SOCKET_FILTER,
883 };
884 
885 constexpr bpf_prog_type kUprobestatsAllowedProgTypes[] = {
886         BPF_PROG_TYPE_KPROBE,
887 };
888 
889 // see b/162057235. For arbitrary program types, the concern is that due to the lack of
890 // SELinux access controls over BPF program attachpoints, we have no way to control the
891 // attachment of programs to shared resources (or to detect when a shared resource
892 // has one BPF program replace another that is attached there)
893 constexpr bpf_prog_type kVendorAllowedProgTypes[] = {
894         BPF_PROG_TYPE_SOCKET_FILTER,
895 };
896 
897 const Location locations[] = {
898         // Core operating system
899         {
900                 .dir = "/system/etc/bpf/",
901                 .prefix = "",
902                 .allowedProgTypes = kPlatformAllowedProgTypes,
903                 .allowedProgTypesLength = arraysize(kPlatformAllowedProgTypes),
904         },
905         // memevents
906         {
907                 .dir = "/system/etc/bpf/memevents/",
908                 .prefix = "memevents/",
909                 .allowedProgTypes = kMemEventsAllowedProgTypes,
910                 .allowedProgTypesLength = arraysize(kMemEventsAllowedProgTypes),
911         },
912         // uprobestats
913         {
914                 .dir = "/system/etc/bpf/uprobestats/",
915                 .prefix = "uprobestats/",
916                 .allowedProgTypes = kUprobestatsAllowedProgTypes,
917                 .allowedProgTypesLength = arraysize(kUprobestatsAllowedProgTypes),
918         },
919         // Vendor operating system
920         {
921                 .dir = "/vendor/etc/bpf/",
922                 .prefix = "vendor/",
923                 .allowedProgTypes = kVendorAllowedProgTypes,
924                 .allowedProgTypesLength = arraysize(kVendorAllowedProgTypes),
925         },
926 };
927 
loadAllElfObjects(const Location & location)928 int loadAllElfObjects(const Location& location) {
929     int retVal = 0;
930     DIR* dir;
931     struct dirent* ent;
932 
933     if ((dir = opendir(location.dir)) != NULL) {
934         while ((ent = readdir(dir)) != NULL) {
935             string s = ent->d_name;
936             if (!EndsWith(s, ".o")) continue;
937 
938             string progPath(location.dir);
939             progPath += s;
940 
941             bool critical;
942             int ret = loadProg(progPath.c_str(), &critical, location);
943             if (ret) {
944                 if (critical) retVal = ret;
945                 ALOGE("Failed to load object: %s, ret: %s", progPath.c_str(), strerror(-ret));
946             } else {
947                 ALOGV("Loaded object: %s", progPath.c_str());
948             }
949         }
950         closedir(dir);
951     }
952     return retVal;
953 }
954 
createSysFsBpfSubDir(const char * const prefix)955 int createSysFsBpfSubDir(const char* const prefix) {
956     if (*prefix) {
957         mode_t prevUmask = umask(0);
958 
959         string s = "/sys/fs/bpf/";
960         s += prefix;
961 
962         errno = 0;
963         int ret = mkdir(s.c_str(), S_ISVTX | S_IRWXU | S_IRWXG | S_IRWXO);
964         if (ret && errno != EEXIST) {
965             const int err = errno;
966             ALOGE("Failed to create directory: %s, ret: %s", s.c_str(), strerror(err));
967             return -err;
968         }
969 
970         umask(prevUmask);
971     }
972     return 0;
973 }
974 
975 }  // namespace bpf
976 }  // namespace android
977 
978 // ----- extern C stuff for rust below here -----
979 
initLogging()980 void initLogging() {
981     // since we only ever get called from mainline NetBpfLoad
982     // (see packages/modules/Connectivity/netbpfload/NetBpfLoad.cpp around line 516)
983     // and there no arguments, so we can just pretend/assume this is the case.
984     const char* argv[] = {"/system/bin/bpfloader", NULL};
985     android::base::InitLogging(const_cast<char**>(argv), &android::base::KernelLogger);
986 }
987 
createBpfFsSubDirectories()988 void createBpfFsSubDirectories() {
989     for (const auto& location : android::bpf::locations) {
990         if (android::bpf::createSysFsBpfSubDir(location.prefix)) {
991             exit(120);
992         }
993     }
994 }
995 
legacyBpfLoader()996 void legacyBpfLoader() {
997     // Load all ELF objects, create programs and maps, and pin them
998     for (const auto& location : android::bpf::locations) {
999         if (android::bpf::loadAllElfObjects(location)) {
1000             ALOGE("=== CRITICAL FAILURE LOADING BPF PROGRAMS FROM %s ===", location.dir);
1001             ALOGE("If this triggers reliably, you're probably missing kernel options or patches.");
1002             ALOGE("If this triggers randomly, you might be hitting some memory allocation "
1003                   "problems or startup script race.");
1004             ALOGE("--- DO NOT EXPECT SYSTEM TO BOOT SUCCESSFULLY ---");
1005             sleep(20);
1006             exit(121);
1007         }
1008     }
1009 }
1010 
execNetBpfLoadDone()1011 void execNetBpfLoadDone() {
1012     const char* args[] = {"/apex/com.android.tethering/bin/netbpfload", "done", NULL};
1013     execve(args[0], (char**)args, environ);
1014     ALOGE("FATAL: execve(): %d[%s]", errno, strerror(errno));
1015     exit(122);
1016 }
1017