Search code examples
pythonscapypcap

Python Scapy - create a new protocol definition within UDP Data


Is it possible to use Scapy's PcapReader to analyze UDP packet data with custom fields? For example, within the UDP packet Data (see attached Wireshark capture), there are the following fields of my_proto:

VER - 2 bytes
FLAGS - 2 bytes
TIMESTAMP - 8 bytes
VAL1 - 4 bytes
VAL2 - 4 bytes, etc

I would like to parse these fields, such that for each packet received I can retrieve [my_proto].VER, [my_proto].FLAGS, etc.

I think what I want is similar to the Disney example in the documentation, however, I am unsure of how to bind (not sure if that is the right word) it to the Data portion of UDP. (https://scapy.readthedocs.io/en/latest/build_dissect.html)

enter image description here


Solution

  • as you said your protocol could like similar to that:

    from scapy.all import Packet,LEShortField, LELongField, LEIntField
    
    class GreatProtocol(Packet):
        name = "GreatProtocol "
        fields_desc=[ LEShortField("VER", 0),
                      LEShortField("FLAGS",0),
                      LELongField("TIMESTAMP", 0),
                      LEIntField("VAL1", 0),
                     ]
    

    now, to bind you need to use the function bind. you could use it 3 different ways:

    • All UDP payload are GreatProtocol (not recomended)
    • All UDP with dest port = X are GreatProtocol (most logical)
    • All UDP with src port = X are GreatProtocol
    from scapy.all import bind_layers
    from scapy.layers.inet import UDP
    
    
    # All UDP payload are GreatProtocol (not recomended)
    bind_layers(UDP, GreatProtocol)
    
    # All UDP with dest port = X are GreatProtocol (most logical)
    bind_layers(UDP, GreatProtocol, dport=55)
    
    
    # All UDP with src port = X are GreatProtocol
    bind_layers(UDP, GreatProtocol, sport=99)
    
    

    note that I show using the src and dst port, but you can use any field of the layer UDP

    there is also the option of doing a one off.

    
    
    my_packet[UDP].decode_payload_as(GreatProtocol)
    
    

    docs:

    creating layer: https://scapy.readthedocs.io/en/latest/build_dissect.html

    binding layer: https://scapy.readthedocs.io/en/latest/build_dissect.html#binding-layers

    decode_payload_as: https://scapy.readthedocs.io/en/latest/api/scapy.packet.html#scapy.packet.Packet.decode_payload_as