BPF 过滤器加载数据包的半个字和一个字节。需要语法解释
BPF filters load half word and byte of a packet. Syntax explanation required
以下代码来自 BPF 过滤器(Berkley Packet Filters)。在第一行,ldh [12]
,它加载了一个数据包的 [12] something
但是 BPF filter
的文档说 ldh
用于加载一个数据包的半个字并且在第三行它加载了一个数据包的 [23] something
但文档说 ldb
用于加载字节。我想分别知道 12
和 23
以及 ldh
和 ldb
是什么。
ldh [12]
jne #0x800, drop
ldb [23]
jneq #6, drop
ret #-1
drop: ret #0
以上代码只允许tcp数据包进入tcp-ip栈(套接字)。
BPF过滤器的解释https://www.kernel.org/doc/Documentation/networking/filter.txt
12 和 23 是数据包 中的 偏移量。因此 ldh [12]
在数据包的偏移量 12 处加载一个半字。
这在 the documentation 中称为“寻址模式”,在这种情况下,字节码使用“寻址模式 1”。
除了 pchaigno 的回答之外,这里还有对您的程序加载的具体值的解释。
在您的情况下,程序从第 2 层(以太网)开始处理数据包(其他套接字 families/types 可以从第 3 层或第 4 层 headers 开始)。它是这样的:
ldh [12] # Load two bytes at offset 12
# Offset 12 is the 2-byte long Ethertype field of the
# Ethernet header
jne #0x800, drop # If those two bytes are not 0x800
# (i.e. packet is not IPv4), go to “drop”
ldb [23] # Load one byte at offset 23
# Offset 23 is offset 9 in the IPv4 header
# (23 minus 14 bytes for the Ethernet header)
# This is the 1-byte long Protocol field
jneq #6, drop # Load Protocol number, if different from 6
# (IANA number for TCP), go to “drop”
ret #-1 # Keep packet
drop: ret #0 # Drop packet (“truncate to 0 length”)
以下代码来自 BPF 过滤器(Berkley Packet Filters)。在第一行,ldh [12]
,它加载了一个数据包的 [12] something
但是 BPF filter
的文档说 ldh
用于加载一个数据包的半个字并且在第三行它加载了一个数据包的 [23] something
但文档说 ldb
用于加载字节。我想分别知道 12
和 23
以及 ldh
和 ldb
是什么。
ldh [12]
jne #0x800, drop
ldb [23]
jneq #6, drop
ret #-1
drop: ret #0
以上代码只允许tcp数据包进入tcp-ip栈(套接字)。
BPF过滤器的解释https://www.kernel.org/doc/Documentation/networking/filter.txt
12 和 23 是数据包 中的 偏移量。因此 ldh [12]
在数据包的偏移量 12 处加载一个半字。
这在 the documentation 中称为“寻址模式”,在这种情况下,字节码使用“寻址模式 1”。
除了 pchaigno 的回答之外,这里还有对您的程序加载的具体值的解释。
在您的情况下,程序从第 2 层(以太网)开始处理数据包(其他套接字 families/types 可以从第 3 层或第 4 层 headers 开始)。它是这样的:
ldh [12] # Load two bytes at offset 12
# Offset 12 is the 2-byte long Ethertype field of the
# Ethernet header
jne #0x800, drop # If those two bytes are not 0x800
# (i.e. packet is not IPv4), go to “drop”
ldb [23] # Load one byte at offset 23
# Offset 23 is offset 9 in the IPv4 header
# (23 minus 14 bytes for the Ethernet header)
# This is the 1-byte long Protocol field
jneq #6, drop # Load Protocol number, if different from 6
# (IANA number for TCP), go to “drop”
ret #-1 # Keep packet
drop: ret #0 # Drop packet (“truncate to 0 length”)