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