如何使用 scapy 创建新层或新协议?

Ome*_*mer 2 python network-protocols layer scapy python-3.x

我想使用 scapy 创建一个新层。我创建了一个新图层,但是当我将其发送到另一台计算机时,它丢失了,Wireshark 也无法识别它。我怎么解决这个问题?

class OMER(Packet):
    name = "OMER"
    fields_desc = [StrLenField("Omer", "", None)]
Run Code Online (Sandbox Code Playgroud)

cod*_*der 5

当您使用创建新协议或新层时scapy,其他网络工具wireshark(以及其他工具)由于不知道您的协议的具体细节将无法自动正确解析它。

如果您想尝试新协议,则必须创建自己的本地解码器。以下示例即使是最小的,也演示了上述所有内容:


#!/usr/bin/env python 

from scapy.all import *

# create a simple protocol 
# (example similar with the one in the scapy docs...)
class Exmpl(Packet):
    name = "myprotocol"
    fields_desc=[ ShortField("fld1",5),
                  XByteField("fld2",3) ]

from scapy.utils import PcapWriter

# write data in a pcap file to examine later with
# 1 -> scapy
# 2 -> wireshark
print '\n[+] Writing net.pcap file...'
cap = PcapWriter("net.pcap", append=True, sync=True)
for i in range(10):
    packet = Exmpl(fld1=i)
    cap.write(packet)

# read the data and examine them with scapy
# scapy is aware of the "Exmpl" protocol (e.g. its fields etc...) 
# and how to decode it, while wireshark is not
print '[+] Examining net.pcap file...\n'
packets = rdpcap('net.pcap')
for p in packets: 
    Exmpl(str(p)).show()
Run Code Online (Sandbox Code Playgroud)

上述脚本的输出将类似于:

[+] Writing net.pcap file...
[+] Examining net.pcap file...

###[ myprotocol ]###
  fld1      = 0
  fld2      = 0x3
###[ myprotocol ]###
  fld1      = 1
  fld2      = 0x3
###[ myprotocol ]###
  fld1      = 2
  fld2      = 0x3
...skip...
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,知道该协议,因此可以正确解析数据。现在,如果您尝试检查“net.pcap”文件,wireshark您将看到以下内容:

在此输入图像描述

不知道您的协议,因此无法正确解析它。

注意:正如您所理解的,即使您在另一个设备中发送这些数据包(要真正做到这一点,您还必须实现一些其他东西),那么该设备也必须知道您的协议,否则它将无法才能正确解析它。这就是为什么当您尝试将数据包从一台计算机发送到另一台计算机时,接收方无法成功解码它们。