我正在尝试使用 scapy 发送先前记录的流量(以 pcap 格式捕获)。目前我被困在剥离原始以太层。流量是在另一台主机上捕获的,我基本上需要更改 IP 和以太层 src 和 dst。我设法更换 IP 层并重新计算校验和,但以太层给我带来了麻烦。
任何人都有从捕获文件重新发送数据包的经验,并对 IP 和以太网层(src 和 dst)进行了更改?此外,捕获量相当大,只有几 Gb,在如此大的流量下,scapy 性能如何?
检查这个例子
from scapy.all import *
from scapy.utils import rdpcap
pkts=rdpcap("FileName.pcap") # could be used like this rdpcap("filename",500) fetches first 500 pkts
for pkt in pkts:
pkt[Ether].src= new_src_mac # i.e new_src_mac="00:11:22:33:44:55"
pkt[Ether].dst= new_dst_mac
pkt[IP].src= new_src_ip # i.e new_src_ip="255.255.255.255"
pkt[IP].dst= new_dst_ip
sendp(pkt) #sending packet at layer 2
注释:
sniff(offline="filename")
用来读取数据包,sniff(offline="filename",prn=My_Function)
在这种情况下您可以使用这样的 prn 参数 My_Functions 将应用于每个 pkt 嗅探ip="1.1.1.1"
等等,如上图所示。如果我是你,我会让 Scapy 处理Ether
图层,并使用send()
函数。例如:
ip_map = {"1.2.3.4": "10.0.0.1", "1.2.3.5": "10.0.0.2"}
for p in PcapReader("filename.cap"):
if IP not in p:
continue
p = p[IP]
# if you want to use a constant map, only let the following line
p.src = "10.0.0.1"
p.dst = "10.0.0.2"
# if you want to use the original src/dst if you don't find it in ip_map
p.src = ip_map.get(p.src, p.src)
p.dst = ip_map.get(p.dst, p.dst)
# if you want to drop the packet if you don't find both src and dst in ip_map
if p.src not in ip_map or p.dst not in ip_map:
continue
p.src = ip_map[p.src]
p.dst = ip_map[p.dst]
# as suggested by @AliA, we need to let Scapy compute the correct checksum
del(p.chksum)
# then send the packet
send(p)
Well, with scapy I came up with the following (sorry for my Python). Hopefully it will help someone. There was a possible simpler scenario where all packets from pcap file are read into memory, but this could lead to problems with large capture files.
from scapy.all import *
global src_ip, dst_ip
src_ip = 1.1.1.1
dst_ip = 2.2.2.2
infile = "dump.pcap"
try:
my_reader = PcapReader(infile)
my_send(my_reader)
except IOError:
print "Failed reading file %s contents" % infile
sys.exit(1)
def my_send(rd, count=100):
pkt_cnt = 0
p_out = []
for p in rd:
pkt_cnt += 1
np = p.payload
np[IP].dst = dst_ip
np[IP].src = src_ip
del np[IP].chksum
p_out.append(np)
if pkt_cnt % count == 0:
send(PacketList(p_out))
p_out = []
# Send remaining in final batch
send(PacketList(p_out))
print "Total packets sent %d" % pkt_cn
对于正确的校验和,我还需要添加del p[UDP].chksum