blob: 9e2ff4480df38778a4fefc31c6e6eda190ca767a [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
170int mapRetrieve(const char* pathname, uint32_t flag) {
171 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
178int attachProgram(bpf_attach_type type, uint32_t prog_fd, uint32_t cg_fd) {
179 bpf_attr attr;
180 memset(&attr, 0, sizeof(attr));
181 attr.target_fd = cg_fd;
182 attr.attach_bpf_fd = prog_fd;
183 attr.attach_type = type;
184
185 return bpf(BPF_PROG_ATTACH, Slice(&attr, sizeof(attr)));
186}
187
188int detachProgram(bpf_attach_type type, uint32_t cg_fd) {
189 bpf_attr attr;
190 memset(&attr, 0, sizeof(attr));
191 attr.target_fd = cg_fd;
192 attr.attach_type = type;
193
194 return bpf(BPF_PROG_DETACH, Slice(&attr, sizeof(attr)));
195}
196
197uint64_t getSocketCookie(int sockFd) {
198 uint64_t sock_cookie;
199 socklen_t cookie_len = sizeof(sock_cookie);
200 int res = getsockopt(sockFd, SOL_SOCKET, SO_COOKIE, &sock_cookie, &cookie_len);
201 if (res < 0) {
202 res = -errno;
203 ALOGE("Failed to get socket cookie: %s\n", strerror(errno));
204 errno = -res;
205 // 0 is an invalid cookie. See sock_gen_cookie.
206 return NONEXISTENT_COOKIE;
207 }
208 return sock_cookie;
209}
210
211bool hasBpfSupport() {
212 struct utsname buf;
213 int kernel_version_major;
214 int kernel_version_minor;
215
216 uint64_t api_level = GetUintProperty<uint64_t>("ro.product.first_api_level", 0);
217 if (api_level == 0) {
218 ALOGE("Cannot determine initial API level of the device");
219 api_level = GetUintProperty<uint64_t>("ro.build.version.sdk", 0);
220 }
221
222 int ret = uname(&buf);
223 if (ret) {
224 return false;
225 }
226 char dummy;
227 ret = sscanf(buf.release, "%d.%d%c", &kernel_version_major, &kernel_version_minor, &dummy);
Chenbo Feng1f20ad32018-11-26 15:18:46 -0800228 if (ret >= 2 &&
229 ((kernel_version_major > 4) || (kernel_version_major == 4 && kernel_version_minor >= 9))) {
Chenbo Feng75b410b2018-10-10 15:01:19 -0700230 // Check if the device is shipped originally with android P.
231 return api_level >= MINIMUM_API_REQUIRED;
232 }
233 return false;
234}
235
236int loadAndPinProgram(BpfProgInfo* prog, Slice progBlock) {
237 // Program doesn't exist. Try to load it.
238 char bpf_log_buf[LOG_BUF_SIZE];
239 Slice bpfLog = Slice(bpf_log_buf, sizeof(bpf_log_buf));
240 prog->fd.reset(bpfProgLoad(prog->loadType, progBlock, "Apache 2.0", 0, bpfLog));
241 if (prog->fd < 0) {
242 int ret = -errno;
243 ALOGE("load %s failed: %s", prog->name, strerror(errno));
244 return ret;
245 }
246 if (prog->attachType == BPF_CGROUP_INET_EGRESS || prog->attachType == BPF_CGROUP_INET_INGRESS) {
247 unique_fd cg_fd(open(CGROUP_ROOT_PATH, O_DIRECTORY | O_RDONLY | O_CLOEXEC));
248 if (cg_fd < 0) {
249 int ret = -errno;
250 ALOGE("Failed to open the cgroup directory");
251 return ret;
252 }
253 int ret = android::bpf::attachProgram(prog->attachType, prog->fd, cg_fd);
254 if (ret) {
255 ret = -errno;
256 ALOGE("%s attach failed: %s", prog->name, strerror(errno));
257 return ret;
258 }
259 }
260 if (prog->path) {
261 int ret = android::bpf::bpfFdPin(prog->fd, prog->path);
262 if (ret) {
263 ret = -errno;
264 ALOGE("Pin %s as file %s failed: %s", prog->name, prog->path, strerror(errno));
265 return ret;
266 }
267 }
268 return 0;
269}
270
271int extractAndLoadProg(BpfProgInfo* prog, Elf64_Shdr* sectionPtr, Slice fileContents,
272 const std::vector<BpfMapInfo>& mapPatterns) {
Chenbo Feng1f20ad32018-11-26 15:18:46 -0800273 uint64_t progSize = (uint64_t)sectionPtr->sh_size;
Chenbo Feng75b410b2018-10-10 15:01:19 -0700274 Slice progSection = take(drop(fileContents, sectionPtr->sh_offset), progSize);
275 if (progSection.size() < progSize) {
276 ALOGE("programSection out of bound");
277 return -EINVAL;
278 }
279 MemBlock progCopy(progSection);
280 if (progCopy.get().size() != progSize) {
281 ALOGE("program cannot be extracted");
282 return -EINVAL;
283 }
284 Slice remaining = progCopy.get();
285 while (remaining.size() >= MAP_CMD_SIZE) {
286 // Scan the program, examining all possible places that might be the start of a
287 // map load operation (i.e., all bytes of value MAP_LD_CMD_HEAD).
288 // In each of these places, check whether it is the start of one of the patterns
289 // we want to replace, and if so, replace it.
290 Slice mapHead = findFirstMatching(remaining, MAP_LD_CMD_HEAD);
291 if (mapHead.size() < MAP_CMD_SIZE) break;
292 bool replaced = false;
293 for (const auto& pattern : mapPatterns) {
294 if (!memcmp(mapHead.base(), pattern.search.data(), MAP_CMD_SIZE)) {
295 memcpy(mapHead.base(), pattern.replace.data(), MAP_CMD_SIZE);
296 replaced = true;
297 break;
298 }
299 }
300 remaining = drop(mapHead, replaced ? MAP_CMD_SIZE : sizeof(uint8_t));
301 }
302 if (!(prog->path) || access(prog->path, R_OK) == -1) {
303 return loadAndPinProgram(prog, progCopy.get());
304 }
305 return 0;
306}
307
308int parsePrograms(Slice fileContents, BpfProgInfo* programs, size_t size,
309 const std::vector<BpfMapInfo>& mapPatterns) {
310 Slice elfHeader = take(fileContents, sizeof(Elf64_Ehdr));
311 if (elfHeader.size() < sizeof(Elf64_Ehdr)) {
312 ALOGE("bpf fileContents does not have complete elf header");
313 return -EINVAL;
314 }
315
Chenbo Feng1f20ad32018-11-26 15:18:46 -0800316 Elf64_Ehdr* elf = (Elf64_Ehdr*)elfHeader.base();
Chenbo Feng75b410b2018-10-10 15:01:19 -0700317 // Find section names string table. This is the section whose index is e_shstrndx.
318 if (elf->e_shstrndx == SHN_UNDEF) {
319 ALOGE("cannot locate namesSection\n");
320 return -EINVAL;
321 }
322 size_t totalSectionSize = (elf->e_shnum) * sizeof(Elf64_Shdr);
323 Slice sections = take(drop(fileContents, elf->e_shoff), totalSectionSize);
324 if (sections.size() < totalSectionSize) {
325 ALOGE("sections corrupted");
326 return -EMSGSIZE;
327 }
328
329 Slice namesSection =
Chenbo Feng1f20ad32018-11-26 15:18:46 -0800330 take(drop(sections, elf->e_shstrndx * sizeof(Elf64_Shdr)), sizeof(Elf64_Shdr));
Chenbo Feng75b410b2018-10-10 15:01:19 -0700331 if (namesSection.size() != sizeof(Elf64_Shdr)) {
332 ALOGE("namesSection corrupted");
333 return -EMSGSIZE;
334 }
Chenbo Feng1f20ad32018-11-26 15:18:46 -0800335 size_t strTabOffset = ((Elf64_Shdr*)namesSection.base())->sh_offset;
336 size_t strTabSize = ((Elf64_Shdr*)namesSection.base())->sh_size;
Chenbo Feng75b410b2018-10-10 15:01:19 -0700337
338 Slice strTab = take(drop(fileContents, strTabOffset), strTabSize);
339 if (strTab.size() < strTabSize) {
340 ALOGE("string table out of bound\n");
341 return -EMSGSIZE;
342 }
343
344 for (int i = 0; i < elf->e_shnum; i++) {
345 Slice section = take(drop(sections, i * sizeof(Elf64_Shdr)), sizeof(Elf64_Shdr));
346 if (section.size() < sizeof(Elf64_Shdr)) {
347 ALOGE("section %d is out of bound, section size: %zu, header size: %zu, total size: "
348 "%zu",
349 i, section.size(), sizeof(Elf64_Shdr), sections.size());
350 return -EBADF;
351 }
Chenbo Feng1f20ad32018-11-26 15:18:46 -0800352 Elf64_Shdr* sectionPtr = (Elf64_Shdr*)section.base();
Chenbo Feng75b410b2018-10-10 15:01:19 -0700353 Slice nameSlice = drop(strTab, sectionPtr->sh_name);
354 if (nameSlice.size() == 0) {
355 ALOGE("nameSlice out of bound, i: %d, strTabSize: %zu, sh_name: %u", i, strTabSize,
356 sectionPtr->sh_name);
357 return -EBADF;
358 }
359 for (size_t i = 0; i < size; i++) {
360 BpfProgInfo* prog = programs + i;
Chenbo Feng1f20ad32018-11-26 15:18:46 -0800361 if (!strcmp((char*)nameSlice.base(), prog->name)) {
Chenbo Feng75b410b2018-10-10 15:01:19 -0700362 int ret = extractAndLoadProg(prog, sectionPtr, fileContents, mapPatterns);
363 if (ret) return ret;
364 }
365 }
366 }
367
368 // Check all the program struct passed in to make sure they all have a valid fd.
369 for (size_t i = 0; i < size; i++) {
370 BpfProgInfo* prog = programs + i;
371 if (access(prog->path, R_OK) == -1) {
372 ALOGE("Load program %s failed", prog->name);
373 return -EINVAL;
374 }
375 }
376 return 0;
377}
378
379int parseProgramsFromFile(const char* path, BpfProgInfo* programs, size_t size,
380 const std::vector<BpfMapInfo>& mapPatterns) {
Chenbo Feng4c9e9ec2018-10-16 20:31:52 -0700381 unique_fd fd(open(path, O_RDONLY | O_CLOEXEC));
Chenbo Feng75b410b2018-10-10 15:01:19 -0700382 int ret;
383 if (fd < 0) {
384 ret = -errno;
385 ALOGE("Failed to open %s program: %s", path, strerror(errno));
386 return ret;
387 }
388
389 struct stat stat;
390 if (fstat(fd.get(), &stat)) {
391 ret = -errno;
392 ALOGE("Failed to get file (%s) size: %s", path, strerror(errno));
393 return ret;
394 }
395
396 off_t fileLen = stat.st_size;
Chenbo Feng1f20ad32018-11-26 15:18:46 -0800397 char* baseAddr = (char*)mmap(NULL, fileLen, PROT_READ, MAP_PRIVATE | MAP_POPULATE, fd.get(), 0);
Chenbo Feng75b410b2018-10-10 15:01:19 -0700398 if (baseAddr == MAP_FAILED) {
399 ALOGE("Failed to map the program (%s) into memory: %s", path, strerror(errno));
400 ret = -errno;
401 return ret;
402 }
403
404 ret = parsePrograms(Slice(baseAddr, fileLen), programs, size, mapPatterns);
405
406 munmap(baseAddr, fileLen);
407 return ret;
408}
409
410} // namespace bpf
411} // namespace android