Reputation: 4364
The following code is from BPF filters (Berkley Packet Filters). in the first line, ldh [12]
, it loads [12] something
of a packet but documentation of BPF filter
says ldh
is used to load a half word of a packet and in third line it loads [23] something
of a packet but documentation says ldb
is used to a load byte . I like to know what is 12
and 23
along with ldh
and ldb
respectively.
ldh [12]
jne #0x800, drop
ldb [23]
jneq #6, drop
ret #-1
drop: ret #0
the above code only allow tcp packets to enter into the tcp-ip stack(socket).
Explanation of BPF filters https://www.kernel.org/doc/Documentation/networking/filter.txt
Upvotes: 0
Views: 484
Reputation: 9114
In addition to pchaigno's answer, here is an explanation on the concrete values that your program loads.
In your case the program processes the packet starting from the Layer 2 (Ethernet) (other socket families/types can start at layer 3 or 4 headers). It goes like this:
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”)
Upvotes: 1
Reputation: 13063
12 and 23 are offsets into the packet. So ldh [12]
loads a half word at offset 12 in the packet.
This is referred to as the "Addressing mode" in the documentation and, in this case, the bytecode is using the "Addressing mode 1".
Upvotes: 0