Adding ethernet padding to packet using scapy
سؤال
I need to write a tool that can take in a pcap file and rewrite all packets shorter than 60 bytes and apply the ethernet padding to them. This is to avoid having the NIC alter the number of bytes sent when I run tcpreplay.
When I try this segment of code I can see that scapy can detect a padding field in some packets in my file.
pkts = rdpcap(infile)
for pkt in pkts:
if len(pkt) = 60:
print pkt.show()
This returns the following output for a packet with padding.
###[ Ethernet ]###
dst = fe:ff:20:00:01:00
src = 00:00:01:00:00:00
type = 0x800
###[ IP ]###
version = 4L
ihl = 5L
tos = 0x0
len = 40
id = 3929
flags = DF
frag = 0L
ttl = 128
proto = tcp
chksum = 0xa438
src = 145.254.160.237
dst = 216.239.59.99
\options \
###[ TCP ]###
sport = 3371
dport = www
seq = 918692089
ack = 778787258
dataofs = 5L
reserved = 0L
flags = A
window = 8760
chksum = 0x5902
urgptr = 0
options = {}
###[ Padding ]###
load = '\x00\x00\x00\x00\x00\x00'
Then I tried altering my code to write to the padding field for shorter packets.
pkts = rdpcap(infile)
for pkt in pkts:
if len(pkt) < 60:
print pkt.show()
pad_len = 60 - len(pkt)
pkt[Padding].load = '\x00' * pad_len
if len(pkt) == 60:
print pkt.show()
However this returns an error
Traceback (most recent call last):
File "rewrite_pcap.py", line 18, in <module>
pkt[Padding].load = '\x00' * pad_len
File "/usr/lib/pymodules/python2.7/scapy/packet.py", line 758, in __getitem__
raise IndexError("Layer [%s] not found" % lname)
IndexError: Layer [Padding] not found
How can I use scapy to append some padding data to the end of a packet?
المحلول
So this turned out to be simpler than I expected. I just needed to initialize a Padding object first then add it to my packet.
pkts = rdpcap(infile)
for pkt in pkts:
print len(pkt)
if len(pkt) < 60:
pad_len = 60 - len(pkt)
pad = Padding()
pad.load = '\x00' * pad_len
pkt = pkt/pad
if len(pkt) == 60:
print pkt.show()
لا تنتمي إلى StackOverflow