blob: 4d4cae332678f45b56f8e9c02265638e71f6d83f [file] [log] [blame]
Chenbo Feng75b410b2018-10-10 15:01:19 -07001/*
2 * Copyright (C) 2017 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 "BpfUtils"
18
Bernie Innocenti26ffded2018-10-19 15:41:53 +090019#include "bpf/BpfUtils.h"
20
Chenbo Feng75b410b2018-10-10 15:01:19 -070021#include <elf.h>
22#include <inttypes.h>
23#include <linux/bpf.h>
24#include <linux/if_ether.h>
25#include <linux/in.h>
26#include <stdlib.h>
27#include <string.h>
28#include <sys/mman.h>
29#include <sys/socket.h>
30#include <sys/stat.h>
31#include <sys/utsname.h>
32#include <sstream>
33#include <string>
34
35#include <android-base/properties.h>
Chenbo Feng75b410b2018-10-10 15:01:19 -070036#include <android-base/unique_fd.h>
Bernie Innocenti26ffded2018-10-19 15:41:53 +090037#include <log/log.h>
Chenbo Feng75b410b2018-10-10 15:01:19 -070038#include <netdutils/MemBlock.h>
39#include <netdutils/Slice.h>
Chenbo Feng75b410b2018-10-10 15:01:19 -070040
41using android::base::GetUintProperty;
Chenbo Feng75b410b2018-10-10 15:01:19 -070042using android::base::unique_fd;
43using android::netdutils::MemBlock;
44using android::netdutils::Slice;
45using android::netdutils::statusFromErrno;
Chenbo Feng75b410b2018-10-10 15:01:19 -070046
47constexpr size_t LOG_BUF_SIZE = 65536;
48
49namespace android {
50namespace bpf {
51
52/* The bpf_attr is a union which might have a much larger size then the struct we are using, while
53 * The inline initializer only reset the field we are using and leave the reset of the memory as
54 * is. The bpf kernel code will performs a much stricter check to ensure all unused field is 0. So
55 * this syscall will normally fail with E2BIG if we don't do a memset to bpf_attr.
56 */
57bool operator==(const StatsKey& lhs, const StatsKey& rhs) {
58 return ((lhs.uid == rhs.uid) && (lhs.tag == rhs.tag) && (lhs.counterSet == rhs.counterSet) &&
59 (lhs.ifaceIndex == rhs.ifaceIndex));
60}
61
62bool operator==(const UidTag& lhs, const UidTag& rhs) {
63 return ((lhs.uid == rhs.uid) && (lhs.tag == rhs.tag));
64}
65
66bool operator==(const StatsValue& lhs, const StatsValue& rhs) {
67 return ((lhs.rxBytes == rhs.rxBytes) && (lhs.txBytes == rhs.txBytes) &&
68 (lhs.rxPackets == rhs.rxPackets) && (lhs.txPackets == rhs.txPackets));
69}
70
71int bpf(int cmd, Slice bpfAttr) {
72 return syscall(__NR_bpf, cmd, bpfAttr.base(), bpfAttr.size());
73}
74
75int createMap(bpf_map_type map_type, uint32_t key_size, uint32_t value_size, uint32_t max_entries,
76 uint32_t map_flags) {
77 bpf_attr attr;
78 memset(&attr, 0, sizeof(attr));
79 attr.map_type = map_type;
80 attr.key_size = key_size;
81 attr.value_size = value_size;
82 attr.max_entries = max_entries;
83 attr.map_flags = map_flags;
84
85 return bpf(BPF_MAP_CREATE, Slice(&attr, sizeof(attr)));
86}
87
88int writeToMapEntry(const base::unique_fd& map_fd, void* key, void* value, uint64_t flags) {
89 bpf_attr attr;
90 memset(&attr, 0, sizeof(attr));
91 attr.map_fd = map_fd.get();
92 attr.key = ptr_to_u64(key);
93 attr.value = ptr_to_u64(value);
94 attr.flags = flags;
95
96 return bpf(BPF_MAP_UPDATE_ELEM, Slice(&attr, sizeof(attr)));
97}
98
99int findMapEntry(const base::unique_fd& map_fd, void* key, void* value) {
100 bpf_attr attr;
101 memset(&attr, 0, sizeof(attr));
102 attr.map_fd = map_fd.get();
103 attr.key = ptr_to_u64(key);
104 attr.value = ptr_to_u64(value);
105
106 return bpf(BPF_MAP_LOOKUP_ELEM, Slice(&attr, sizeof(attr)));
107}
108
109int deleteMapEntry(const base::unique_fd& map_fd, void* key) {
110 bpf_attr attr;
111 memset(&attr, 0, sizeof(attr));
112 attr.map_fd = map_fd.get();
113 attr.key = ptr_to_u64(key);
114
115 return bpf(BPF_MAP_DELETE_ELEM, Slice(&attr, sizeof(attr)));
116}
117
118int getNextMapKey(const base::unique_fd& map_fd, void* key, void* next_key) {
119 bpf_attr attr;
120 memset(&attr, 0, sizeof(attr));
121 attr.map_fd = map_fd.get();
122 attr.key = ptr_to_u64(key);
123 attr.next_key = ptr_to_u64(next_key);
124
125 return bpf(BPF_MAP_GET_NEXT_KEY, Slice(&attr, sizeof(attr)));
126}
127
128int getFirstMapKey(const base::unique_fd& map_fd, void* firstKey) {
129 bpf_attr attr;
130 memset(&attr, 0, sizeof(attr));
131 attr.map_fd = map_fd.get();
132 attr.key = 0;
133 attr.next_key = ptr_to_u64(firstKey);
134
135 return bpf(BPF_MAP_GET_NEXT_KEY, Slice(&attr, sizeof(attr)));
136}
137
138int bpfProgLoad(bpf_prog_type prog_type, Slice bpf_insns, const char* license,
139 uint32_t kern_version, Slice bpf_log) {
140 bpf_attr attr;
141 memset(&attr, 0, sizeof(attr));
142 attr.prog_type = prog_type;
143 attr.insns = ptr_to_u64(bpf_insns.base());
144 attr.insn_cnt = bpf_insns.size() / sizeof(struct bpf_insn);
145 attr.license = ptr_to_u64((void*)license);
146 attr.log_buf = ptr_to_u64(bpf_log.base());
147 attr.log_size = bpf_log.size();
148 attr.log_level = DEFAULT_LOG_LEVEL;
149 attr.kern_version = kern_version;
150 int ret = bpf(BPF_PROG_LOAD, Slice(&attr, sizeof(attr)));
151
152 if (ret < 0) {
153 std::string prog_log = netdutils::toString(bpf_log);
154 std::istringstream iss(prog_log);
155 for (std::string line; std::getline(iss, line);) {
156 ALOGE("%s", line.c_str());
157 }
158 }
159 return ret;
160}
161
162int bpfFdPin(const base::unique_fd& map_fd, const char* pathname) {
163 bpf_attr attr;
164 memset(&attr, 0, sizeof(attr));
165 attr.pathname = ptr_to_u64((void*)pathname);
166 attr.bpf_fd = map_fd.get();
167
168 return bpf(BPF_OBJ_PIN, Slice(&attr, sizeof(attr)));
169}
170
171int mapRetrieve(const char* pathname, uint32_t flag) {
172 bpf_attr attr;
173 memset(&attr, 0, sizeof(attr));
174 attr.pathname = ptr_to_u64((void*)pathname);
175 attr.file_flags = flag;
176 return bpf(BPF_OBJ_GET, Slice(&attr, sizeof(attr)));
177}
178
179int attachProgram(bpf_attach_type type, uint32_t prog_fd, uint32_t cg_fd) {
180 bpf_attr attr;
181 memset(&attr, 0, sizeof(attr));
182 attr.target_fd = cg_fd;
183 attr.attach_bpf_fd = prog_fd;
184 attr.attach_type = type;
185
186 return bpf(BPF_PROG_ATTACH, Slice(&attr, sizeof(attr)));
187}
188
189int detachProgram(bpf_attach_type type, uint32_t cg_fd) {
190 bpf_attr attr;
191 memset(&attr, 0, sizeof(attr));
192 attr.target_fd = cg_fd;
193 attr.attach_type = type;
194
195 return bpf(BPF_PROG_DETACH, Slice(&attr, sizeof(attr)));
196}
197
198uint64_t getSocketCookie(int sockFd) {
199 uint64_t sock_cookie;
200 socklen_t cookie_len = sizeof(sock_cookie);
201 int res = getsockopt(sockFd, SOL_SOCKET, SO_COOKIE, &sock_cookie, &cookie_len);
202 if (res < 0) {
203 res = -errno;
204 ALOGE("Failed to get socket cookie: %s\n", strerror(errno));
205 errno = -res;
206 // 0 is an invalid cookie. See sock_gen_cookie.
207 return NONEXISTENT_COOKIE;
208 }
209 return sock_cookie;
210}
211
212bool hasBpfSupport() {
213 struct utsname buf;
214 int kernel_version_major;
215 int kernel_version_minor;
216
217 uint64_t api_level = GetUintProperty<uint64_t>("ro.product.first_api_level", 0);
218 if (api_level == 0) {
219 ALOGE("Cannot determine initial API level of the device");
220 api_level = GetUintProperty<uint64_t>("ro.build.version.sdk", 0);
221 }
222
223 int ret = uname(&buf);
224 if (ret) {
225 return false;
226 }
227 char dummy;
228 ret = sscanf(buf.release, "%d.%d%c", &kernel_version_major, &kernel_version_minor, &dummy);
229 if (ret >= 2 && ((kernel_version_major > 4) ||
230 (kernel_version_major == 4 && kernel_version_minor >= 9))) {
231 // Check if the device is shipped originally with android P.
232 return api_level >= MINIMUM_API_REQUIRED;
233 }
234 return false;
235}
236
237int loadAndPinProgram(BpfProgInfo* prog, Slice progBlock) {
238 // Program doesn't exist. Try to load it.
239 char bpf_log_buf[LOG_BUF_SIZE];
240 Slice bpfLog = Slice(bpf_log_buf, sizeof(bpf_log_buf));
241 prog->fd.reset(bpfProgLoad(prog->loadType, progBlock, "Apache 2.0", 0, bpfLog));
242 if (prog->fd < 0) {
243 int ret = -errno;
244 ALOGE("load %s failed: %s", prog->name, strerror(errno));
245 return ret;
246 }
247 if (prog->attachType == BPF_CGROUP_INET_EGRESS || prog->attachType == BPF_CGROUP_INET_INGRESS) {
248 unique_fd cg_fd(open(CGROUP_ROOT_PATH, O_DIRECTORY | O_RDONLY | O_CLOEXEC));
249 if (cg_fd < 0) {
250 int ret = -errno;
251 ALOGE("Failed to open the cgroup directory");
252 return ret;
253 }
254 int ret = android::bpf::attachProgram(prog->attachType, prog->fd, cg_fd);
255 if (ret) {
256 ret = -errno;
257 ALOGE("%s attach failed: %s", prog->name, strerror(errno));
258 return ret;
259 }
260 }
261 if (prog->path) {
262 int ret = android::bpf::bpfFdPin(prog->fd, prog->path);
263 if (ret) {
264 ret = -errno;
265 ALOGE("Pin %s as file %s failed: %s", prog->name, prog->path, strerror(errno));
266 return ret;
267 }
268 }
269 return 0;
270}
271
272int extractAndLoadProg(BpfProgInfo* prog, Elf64_Shdr* sectionPtr, Slice fileContents,
273 const std::vector<BpfMapInfo>& mapPatterns) {
274 uint64_t progSize = (uint64_t) sectionPtr->sh_size;
275 Slice progSection = take(drop(fileContents, sectionPtr->sh_offset), progSize);
276 if (progSection.size() < progSize) {
277 ALOGE("programSection out of bound");
278 return -EINVAL;
279 }
280 MemBlock progCopy(progSection);
281 if (progCopy.get().size() != progSize) {
282 ALOGE("program cannot be extracted");
283 return -EINVAL;
284 }
285 Slice remaining = progCopy.get();
286 while (remaining.size() >= MAP_CMD_SIZE) {
287 // Scan the program, examining all possible places that might be the start of a
288 // map load operation (i.e., all bytes of value MAP_LD_CMD_HEAD).
289 // In each of these places, check whether it is the start of one of the patterns
290 // we want to replace, and if so, replace it.
291 Slice mapHead = findFirstMatching(remaining, MAP_LD_CMD_HEAD);
292 if (mapHead.size() < MAP_CMD_SIZE) break;
293 bool replaced = false;
294 for (const auto& pattern : mapPatterns) {
295 if (!memcmp(mapHead.base(), pattern.search.data(), MAP_CMD_SIZE)) {
296 memcpy(mapHead.base(), pattern.replace.data(), MAP_CMD_SIZE);
297 replaced = true;
298 break;
299 }
300 }
301 remaining = drop(mapHead, replaced ? MAP_CMD_SIZE : sizeof(uint8_t));
302 }
303 if (!(prog->path) || access(prog->path, R_OK) == -1) {
304 return loadAndPinProgram(prog, progCopy.get());
305 }
306 return 0;
307}
308
309int parsePrograms(Slice fileContents, BpfProgInfo* programs, size_t size,
310 const std::vector<BpfMapInfo>& mapPatterns) {
311 Slice elfHeader = take(fileContents, sizeof(Elf64_Ehdr));
312 if (elfHeader.size() < sizeof(Elf64_Ehdr)) {
313 ALOGE("bpf fileContents does not have complete elf header");
314 return -EINVAL;
315 }
316
317 Elf64_Ehdr* elf = (Elf64_Ehdr*) elfHeader.base();
318 // Find section names string table. This is the section whose index is e_shstrndx.
319 if (elf->e_shstrndx == SHN_UNDEF) {
320 ALOGE("cannot locate namesSection\n");
321 return -EINVAL;
322 }
323 size_t totalSectionSize = (elf->e_shnum) * sizeof(Elf64_Shdr);
324 Slice sections = take(drop(fileContents, elf->e_shoff), totalSectionSize);
325 if (sections.size() < totalSectionSize) {
326 ALOGE("sections corrupted");
327 return -EMSGSIZE;
328 }
329
330 Slice namesSection =
331 take(drop(sections, elf->e_shstrndx * sizeof(Elf64_Shdr)), sizeof(Elf64_Shdr));
332 if (namesSection.size() != sizeof(Elf64_Shdr)) {
333 ALOGE("namesSection corrupted");
334 return -EMSGSIZE;
335 }
336 size_t strTabOffset = ((Elf64_Shdr*) namesSection.base())->sh_offset;
337 size_t strTabSize = ((Elf64_Shdr*) namesSection.base())->sh_size;
338
339 Slice strTab = take(drop(fileContents, strTabOffset), strTabSize);
340 if (strTab.size() < strTabSize) {
341 ALOGE("string table out of bound\n");
342 return -EMSGSIZE;
343 }
344
345 for (int i = 0; i < elf->e_shnum; i++) {
346 Slice section = take(drop(sections, i * sizeof(Elf64_Shdr)), sizeof(Elf64_Shdr));
347 if (section.size() < sizeof(Elf64_Shdr)) {
348 ALOGE("section %d is out of bound, section size: %zu, header size: %zu, total size: "
349 "%zu",
350 i, section.size(), sizeof(Elf64_Shdr), sections.size());
351 return -EBADF;
352 }
353 Elf64_Shdr* sectionPtr = (Elf64_Shdr*) section.base();
354 Slice nameSlice = drop(strTab, sectionPtr->sh_name);
355 if (nameSlice.size() == 0) {
356 ALOGE("nameSlice out of bound, i: %d, strTabSize: %zu, sh_name: %u", i, strTabSize,
357 sectionPtr->sh_name);
358 return -EBADF;
359 }
360 for (size_t i = 0; i < size; i++) {
361 BpfProgInfo* prog = programs + i;
362 if (!strcmp((char*) nameSlice.base(), prog->name)) {
363 int ret = extractAndLoadProg(prog, sectionPtr, fileContents, mapPatterns);
364 if (ret) return ret;
365 }
366 }
367 }
368
369 // Check all the program struct passed in to make sure they all have a valid fd.
370 for (size_t i = 0; i < size; i++) {
371 BpfProgInfo* prog = programs + i;
372 if (access(prog->path, R_OK) == -1) {
373 ALOGE("Load program %s failed", prog->name);
374 return -EINVAL;
375 }
376 }
377 return 0;
378}
379
380int parseProgramsFromFile(const char* path, BpfProgInfo* programs, size_t size,
381 const std::vector<BpfMapInfo>& mapPatterns) {
Chenbo Feng4c9e9ec2018-10-16 20:31:52 -0700382 unique_fd fd(open(path, O_RDONLY | O_CLOEXEC));
Chenbo Feng75b410b2018-10-10 15:01:19 -0700383 int ret;
384 if (fd < 0) {
385 ret = -errno;
386 ALOGE("Failed to open %s program: %s", path, strerror(errno));
387 return ret;
388 }
389
390 struct stat stat;
391 if (fstat(fd.get(), &stat)) {
392 ret = -errno;
393 ALOGE("Failed to get file (%s) size: %s", path, strerror(errno));
394 return ret;
395 }
396
397 off_t fileLen = stat.st_size;
398 char* baseAddr =
399 (char*) mmap(NULL, fileLen, PROT_READ, MAP_PRIVATE | MAP_POPULATE, fd.get(), 0);
400 if (baseAddr == MAP_FAILED) {
401 ALOGE("Failed to map the program (%s) into memory: %s", path, strerror(errno));
402 ret = -errno;
403 return ret;
404 }
405
406 ret = parsePrograms(Slice(baseAddr, fileLen), programs, size, mapPatterns);
407
408 munmap(baseAddr, fileLen);
409 return ret;
410}
411
412} // namespace bpf
413} // namespace android