Linux eBPF-编写避坑指南

Posted:   December 25, 2021

Edited:   December 25, 2021

Status:   Completed

Tags :   eBPF

Categories :   eBPF

Were equations, pictures or diagrams not properly rendered, please refresh the page. If the problem persists, you can contact me.

0x1:基本概念

  1. 当使用tracepoint的时候,函数参数如何确认?

cat /sys/kernel/debug/tracing/events/syscalls/xxx/format. xxx为要跟踪的函数,在这里有函数参数定义。

0x2:注意事项

  1. 写结构体的时候一定要注意内存对齐,防止被编译器优化填充。

  2. 使用 LLVM 内置的函数做内存操作

#ifndef memset
# define memset(dest, chr, n)   __builtin_memset((dest), (chr), (n))
#endif

#ifndef memcpy
# define memcpy(dest, src, n)   __builtin_memcpy((dest), (src), (n))
#endif

#ifndef memmove
# define memmove(dest, src, n)  __builtin_memmove((dest), (src), (n))
#endif
  1. 指针被操作过后,就得再次声明,不然会被禁止访问
struct iphdr *ip4 = (struct iphdr *) skb->data + ETH_HLEN; //第一次赋值

skb_store_bytes(skb, l3_off + offsetof(struct iphdr, saddr), &new_saddr, 4, 0); //skb被操作了 因此ip4的值不可信,此时如果操作ip4会被拒绝

ip4 = (struct iphdr *) skb->data + ETH_HLEN; //再获取一次

if (ip4->protocol == IPPROTO_TCP) { //才能正常使用
    // do something
}

0x3:常见报错

  1. R2 min value is negative, either use unsigned or ‘var &= const’

第二个变量需要保证非负。 逻辑运算0xFFFFFFFF。

  1. R2 unbounded memory access, use ‘var &= const’ or ‘if (var < const)’
bpf验证器有限制 

#define BPF_MAX_VAR_SIZ (1 << 29)
if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
	verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
		regno);
	return -EACCES;
}
  1. invalid stack type R1 off=-72 access_size=536870911
类似的问题,需要进行逻辑运算保证变量的范围。

off = reg->off + reg->var_off.value;
if (off >= 0 || off < -MAX_BPF_STACK || off + access_size > 0 ||
    access_size < 0 || (access_size == 0 && !zero_size_allowed)) {
	verbose(env, "invalid stack type R%d off=%d access_size=%d\n",
		regno, off, access_size);
	return -EACCES;
}
  1. 从map中lookup出来的指针,不能直接update回去,在eBPF代码中更新值之后不再需要重新update,因为拿到了引用.

  2. 字符串拷贝可以使用编译器内置的 __builtin_memcpy

  3. 一个bpf程序不能申请太多的栈空间,目前限制512Byte,多了就会报错:Looks like the BPF stack limit of 512 bytes is exceeded.。例如在程序中申请了两个数组char arr1[256];char arr2[256];程序就会报错了

  4. 程序包含无法执行到的指令

unreachable insn 1
  1. 程序读取未初始化的寄存器
0: (bf) r0 = r2
R2 !read_ok
  1. 程序退出前未设置 R0 寄存器
0: (bf) r2 = r1
1: (95) exit
R0 !read_ok
  1. 程序访问超出栈空间
0: (7a) *(u64 *)(r10 +8) = 0
invalid stack off=8 size=8
  1. 未初始化栈内元素,就传递该栈地址
0: (bf) r2 = r10
1: (07) r2 += -8
2: (b7) r1 = 0x0
3: (85) call 1
invalid indirect read from stack off -8+0 size 8
  1. 程序未检查 map_lookup_elem() 的返回值是否为空就开始使用
0: (7a) *(u64 *)(r10 -8) = 0
1: (bf) r2 = r10
2: (07) r2 += -8
3: (b7) r1 = 0x0
4: (85) call 1
5: (7a) *(u64 *)(r0 +0) = 0
R0 invalid mem access 'map_value_or_null'

Comments


Be the first one to comment on this page!
You can use extended GitHub flavored markdown in your comment. Commenting FAQs & Guidelines