Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a Scapy packet from raw bytes

Tags:

python

scapy

Using the python packet parsing/sniffing tool Scapy, I would like to create a packet from a raw byte-string. While the details of my specific use-case are more realistic, the following example illustrates my problem and my present attempt:

# Get an example packet (we won't really have an offline file in production.)
pkt = sniff(offline="./example_packets/example_packets2.pcap")

# Convert it to raw bytes -- oddly __str__ does this.
raw_packet = str(pkt)

# Current, broken, attempt to construct a new packet from the same bytes as the old.
# In truth, there are easier ways to copy packets from existing Scapy packets, but
# we are really just using that offline packet as a convenient example.
new_packet = Packet(_pkt=raw_packet)

# Sadly, while this packet has the bytes internally, it no longer has the
# interpretations of the layers like the original packet did (such as saying that
# the packet is ARP and has these field values, etc.
print repr(new_packet)

How can I produce a new_packet from raw bytes that will look the same as if it were sniffed from a pcap file?

like image 326
icfy Avatar asked Dec 03 '14 01:12

icfy


People also ask

How do you make scapy packets?

Creating a packet In scapy, packets are constructed by defining packet headers for each protocol at different layers of TCP/IP and then stacking these layers in order. To create a DNS query, you need to build Ether(sometimes optional), IP,UDP headers and stack them using / operator.

What is raw scapy?

Scapy is a Python-based packet manipulation tool which has a number of useful features for those looking to perform raw TCP/IP requests and analysis.

What is a scapy packet?

Scapy is a packet manipulation tool for computer networks, originally written in Python by Philippe Biondi. It can forge or decode packets, send them on the wire, capture them, and match requests and replies. It can also handle tasks like scanning, tracerouting, probing, unit tests, attacks, and network discovery.

Does scapy use libpcap?

Scapy runs natively on Linux, Windows, OSX and on most Unixes with libpcap (see scapy's installation page). The same code base now runs natively on both Python 2 and Python 3.


1 Answers

There is no way for Scapy to guess the first layer of your packet, so you need to specify it.

You can do so by using the appropriate Packet subclass. For example, say your packet's first layer is Ethernet, use Ether(raw_packet) instead of Packet(raw_packet).

like image 116
Pierre Avatar answered Sep 29 '22 09:09

Pierre