BPF aka Boolean Packet Filter language

Yes. BPF is Berkeley Packet Filter but could be renamed Boolean Packet Filter as the filter function output a true or false regarding a packet traveling from the kernel to the application.

This result can be obtained glad to a directed acyclic control flow graph composed of comparison predicates and boolean operations.

Here is how to decrypt the language helped by the next two examples. The people accustomed with the randomly chosen assembly languages should enjoy the syntax :-)

On a side snote, wireshark 1.6.0 feature a BPF compiler in the capture wizard to impress your girlfriend.

pello@Networker:~$ sudo tcpdump -i eth0 -d “ip”

(000) ldh      [12] (Load a half-word (16 bits) at the position 12 in decimal)

(001) jeq      #0x800           jt 2 jf 3 (jt = jump to (002) if true / jf = jump to (003) if false)

(002) ret      #65535 (65535 = TRUE) <= DELIVERED TO THE APP (WIRESHARK by example)

(003) ret      #0 (0 = FALSE) <= DELIVERED TO IGNORE LAND

Another example .. a little bit more complicated:

pello@Networker:~$ sudo tcpdump -i eth0 -d “tcp port 22

(000) ldh      [12]

(001) jeq      #0x86dd          jt 2 jf 8 (Check if IPv6)

(002) ldb      [20] (Move to position 20 - Next header field - IPv6 branch)

(003) jeq      #0x6             jt 4 jf 19 (Check if IPv6 next header is TCP)

(004) ldh      [54]

(005) jeq      #0x16            jt 18 jf 6 (Check if TCP source port equals 22 - IPv6 Branch)

(006) ldh      [56]

(007) jeq      #0x16            jt 18 jf 19 (Check if TCP destination port equals 22 - IPv6 Branch)

(008) jeq      #0x800           jt 9 jf 19 (Check if IPv4 from instruction 000)

(009) ldb      [23] (Move to the 23th byte position of the packet starting from the link layer header (Ethernet in this case) and read 1 byte considering 1 byte equals to 8 bits)

(010) jeq      #0x6             jt 11 jf 19 (Check if TCP - Ipv4 branch)

(011) ldh      [20] 

(012) jset     #0x1fff          jt 19 jf 13 (Bitwise and with the IP fragmentation bit mask check. If non-zero then this is a fragmented packet so we cannot find the TCP header in this packet  |=> ignored)

(013) ldxb     4*([14]&0xf) (Seek the IP header length bitwise and with 0xf then multiplicate it by 4. The result is stored as a Byte in the index register: x)

(014) ldh      [x + 14] (TCP source port position derived from x - IPv4 branch - 16 bits)

(015) jeq      #0x16            jt 18 jf 16 (True if 22)

(016) ldh      [x + 16] (TCP destination port position derived from x - IPv4 branch - 16 bits)

(017) jeq      #0x16            jt 18 jf 19 (True if 22)

(018) ret      #65535

(019) ret      #0

As a next step of playing with BPF filters the reader could reverse the order of the ‘and’ filters and observe the difference. As an example: “tcp port 22 and host 127.0.0.1” versus “host 127.0.0.1 and tcp port 22”

Happy BPF! :>

70 Notes/ Hide

  1. fropert posted this

Recent comments

Blog comments powered by Disqus