Friday, December 25, 2009

Improved version of pcap2rawc

This version split each packet into layers, and each layer is pointed from an array of name like rawpktLayer_name[]


-- pcap2RawCLayers.py --
#!/usr/bin/python
try:
from scapy.all import *
except:
print "old way..."
from scapy import *

import sys
from binascii import *

if len(sys.argv) ==2:
print "Parsing "+str(sys.argv[1])
else:
print "Usage: python "+sys.argv[0]+" file.pcap"
exit(10)

pcap=rdpcap(sys.argv[1])
out=file(sys.argv[1]+".rawc","w")

out.write("// Generated from pcap2RawCLayers.py\n")

i=0
buff=""
arrays=[]

for p in pcap:
print "// packet "+str(i)+": ***"

while p.payload and len(p.payload) > 0:
q=p.copy()
q.payload = ''
bytes=len(q)
strbyte=""

for j in range(0,bytes):
if j %8 ==0:
strbyte = strbyte +"\n "
strbyte = strbyte + "0x" + str(hexlify(str(q)[j]))
if j < bytes-1:
if j+1 %8:
strbyte= strbyte + ","
else:
strbyte= strbyte + ", "

rawpkt=" rawpkt" + str(q.name) + "["+str(i)+"] = {" + strbyte + " }; /* end rawpkt" + str(p.name) +"["+ str(i) +"] */\n"
p=p.payload
arrays.append("rawpkt" + str(q.name))
buff = buff + rawpkt

if not p.payload and p.load:
q=p.copy()
bytes=len(q.load)
strbyte=""

for j in range(0,bytes):
if j %8 ==0:
strbyte = strbyte +"\n "
strbyte = strbyte + "0x" + str(hexlify(str(q.load)[j]))
if j < bytes-1:
if j+1 %8:
strbyte= strbyte + ","
else:
strbyte= strbyte + ", "

rawpkt=" rawpktPayload["+str(i)+"] = {" + strbyte + " }; /* end rawpktPayload["+ str(i) +"] */\n"
p=p.payload
arrays.append("rawpktPayload")

i=i+1
buff = buff + rawpkt

declares=""
for l in arrays:
declares = declares + " uint8_t *"+ l +"["+str(i)+"];\n"

filebuff = declares+ "\n"+ buff + "\n"
out.write(filebuff)
out.close()

print filebuff
print "//"+ str(i) +" packets written in "+sys.argv[1]+".rawc"

No comments:

Post a Comment