Linux BPF筛选器失败
有人能解释一下为什么这个(经典的)BPF程序有时允许非DHCP响应数据包通过:Linux BPF筛选器失败,linux,linux-kernel,bpf,Linux,Linux Kernel,Bpf,有人能解释一下为什么这个(经典的)BPF程序有时允许非DHCP响应数据包通过: # Load the Ethertype field BPF_LD | BPF_H | BPF_ABS 12 # And reject the packet if it's not 0x0800 (IPv4) BPF_JMP | BPF_JEQ | BPF_K 0x0800 0 8 # Load the IP protocol field BPF_LD | BPF_B | BPF_ABS
# Load the Ethertype field
BPF_LD | BPF_H | BPF_ABS 12
# And reject the packet if it's not 0x0800 (IPv4)
BPF_JMP | BPF_JEQ | BPF_K 0x0800 0 8
# Load the IP protocol field
BPF_LD | BPF_B | BPF_ABS 23
# And reject the packet if it's not 17 (UDP)
BPF_JMP | BPF_JEQ | BPF_K 17 0 6
# Check that the packet has not been fragmented
BPF_LD | BPF_H | BPF_ABS 20
BPF_JMP | BPF_JSET | BPF_K 0x1fff 4 0
# Load the IP header length field
BPF_LDX | BPF_B | BPF_MSH 14
# And load that offset + 16 to get the UDP destination port
BPF_LD | BPF_IND | BPF_H 16
# And reject the packet if the destination port is not 68
BPF_JMP | BPF_JEQ | BPF_K 68 0 1
# Accept the frame
BPF_RET | BPF_K 1500
# Reject the frame
BPF_RET | BPF_K 0
它不能让每一帧都通过,但是在网络负载很重的情况下,它经常失败。我正在用这个Python 3程序测试它:
import ctypes
import struct
import socket
ETH_P_ALL = 0x0003
SO_ATTACH_FILTER = 26
SO_ATTACH_BPF = 50
filters = [
0x28, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x00, 0x00, 0x15, 0x00, 0x00, 0x08, 0x00, 0x08, 0x00, 0x00,
0x30, 0x00, 0x00, 0x00, 0x17, 0x00, 0x00, 0x00, 0x15, 0x00, 0x00, 0x06, 0x11, 0x00, 0x00, 0x00,
0x28, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x45, 0x00, 0x04, 0x00, 0xff, 0x1f, 0x00, 0x00,
0xb1, 0x00, 0x00, 0x00, 0x0e, 0x00, 0x00, 0x00, 0x48, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00,
0x15, 0x00, 0x00, 0x01, 0x44, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0xdc, 0x05, 0x00, 0x00,
0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
]
filters = bytes(filters)
b = ctypes.create_string_buffer(filters)
mem_addr_of_filters = ctypes.addressof(b)
pf = struct.pack("HL", 11, mem_addr_of_filters)
pf = bytes(pf)
def main():
sock = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(ETH_P_ALL))
sock.bind(("eth0", ETH_P_ALL))
sock.setsockopt(socket.SOL_SOCKET, SO_ATTACH_FILTER, pf)
# sock.send(req)
sock.settimeout(1)
try:
data = sock.recv(1500)
if data[35] == 0x43:
return
print('Packet got through: 0x{:02x} 0x{:02x}, 0x{:02x}, 0x{:02x}'.format(data[12], data[13], data
except:
print('Timeout')
return
sock.close()
for ii in range(1000):
main()
如果我在将一个大的核心文件SCPing到运行该脚本的主机时执行此操作,那么在大多数(但不是所有)情况下,它都不会达到1秒超时。在负载较轻的情况下,故障更为罕见——例如,在套接字接收数据时,在ssh链路上旋转;有时,它能顺利完成1000次迭代
所讨论的主机是Linux 4.9.0。内核具有CONFIG\u BPF=y
编辑
对于同一问题的更简单版本,为什么这个BPF程序允许任何数据包通过:
BPF_RET | BPF_K 0
编辑2
上述测试是在ARM64机器上进行的。我已在amd64/Linux 5.9.0上重新测试。我仍然看到失败,虽然没有那么多。我得到了解释
问题是,当帧到达接口时应用过滤器,而不是当它通过recv()
传递到用户空间时应用过滤器。因此,在重载情况下,在使用socket.socket创建套接字(socket.AF\u PACKET,socket.SOCK\u RAW,socket.htons(ETH\u P\u ALL))
和使用SOCK.setsockopt(socket.SOL\u socket,So\u ATTACH\u filter,pf)应用过滤器之间,帧到达。这些框架排在队列中;一旦应用了过滤器,随后到达的数据包就会应用过滤器
因此,一旦应用了筛选器,就必须先从套接字中“排出”所有排队的帧,然后才能依赖筛选器。能否链接到上游讨论?