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