Astron
Astron

Reputation: 1221

Parse packet bytes using 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")

Upvotes: 3

Views: 8938

Answers (1)

tbroberg
tbroberg

Reputation: 635

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.

Upvotes: 3

Related Questions