Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse packet bytes using Scapy

Tags:

python

scapy

I would like to parse the first two bytes of a packets payload using Scapy. What would be the best way to accomplish this? Are offset calculations required?

First the payload needs to be parsed though the following will parse the whole PCAP file, is there a more efficient way to obtain the first two bytes of every payload? link:

>>> fp = open("payloads.dat","wb")
>>> def handler(packet):
...     fp.write(str(packet.payload.payload.payload))
...
>>> sniff(offline="capture1.dump",prn=handler,filter="tcp or udp")
like image 828
Astron Avatar asked Mar 06 '26 00:03

Astron


1 Answers

I see. That looks pretty efficient from here.

You might try fp.write(str(packet.payload.payload.payload)[:2]) to get just the first 2 bytes.

You could also do fp.write(str(packet[TCP].payload)[:2]) to skip past all those payloads.

Alternately, you could define an SSL Packet object, bind it to the appropriate port, then print the SSL layer.

class SSL(Packet):
  name = "SSL" fields_desc = [ ShortField("firstBytes", None) ]

bind_layers( TCP, SSL, sport=443 )
bind_layers( TCP, SSL, dport=443 )

def handler(packet):
... fp.write(str(packet[SSL]))

...but this seems like overkill.

like image 71
tbroberg Avatar answered Mar 07 '26 14:03

tbroberg