Scapy raw data manipulation

user2762655 picture user2762655 · Sep 9, 2013 · Viewed 8.3k times · Source

I am having troubles manipulating raw data. I am trying to change around a resp_cookie in my ISAKMP header and when I do a sniff on the packet it is all in raw data format under Raw Load='\x00\x43\x01........... ' with about 3 lines like that. When I do a Wireshark capture I see the information I want to change but I cant seem to find a way to convert and change that raw data to find and replace the information I am looking for. Also, I can see the information I need when I do a hexdump(), but I can't store that in a variable. when I type i = hexdump(pkt) it spits out the hexdump but doesn't store the hexdump in i.

Answer

CanBeNull picture CanBeNull · Jun 9, 2017

So this post is a little old, but I've come across it a dozen or so times trying to find the answer to a similar problem I'm having. I doubt OP has need for an answer anymore, but if anyone else is looking to do something similar...here you go!

I found the following code snippet somewhere in the deep, dark depths of google and it worked for my situation.

Hexdump(), show() and other methods of Scapy just output the packet to the terminal/console; they don't actually return a string or any other sort of object. So you need a way to intercept that data that it intends to write and put it in a variable to be manipulated.

NOTE: THIS IS PYTHON 3.X and SCAPY 3K

import io
import scapy

#generic scapy sniff
sniff(iface=interface,prn=parsePacket, filter=filter)

With the above sniff method, you're going to want to do the following.

def parsePacket(packet):

    outputPacket = '' 

    #setup
    qsave = sys.stdout
    q = io.StringIO() 

    #CAPTURES OUTPUT
    sys.stdout = q  

    #Text you're capturing
    packet.show()

    #restore original stdout
    sys.stdout = qsave

    #release output
    sout = q.getvalue()

    #Add to string (format if need be)
    outputPacket += sout + '\n'

    #Close IOStream
    q.close() 

    #return your packet
    return outputPacket

The string you return (outputPacket) can now be manipulated how you want.

Swap out .show() with whatever function you see fit.

P.S. Forgive me if this is a little rough from a Pythonic point of view...not a python dev by any stretch.