我正在尝试使用scapy
指定新的数据包格式。在数据包中有一个项目列表,项目由“分组字段”组成。 “分组字段”是指不同类型的字段的子序列。在scapy中创建我所知道的“分组字段”的唯一方法是使用Packet
类并使用FieldLenField
/ PacketListField
来引用序列的长度和列表成员的类型。这是要走的路吗?看起来像这样:
from scapy.packet import Packet
from scapy.fields import *
class RepeatingGroupedSequence(Packet):
name = "Simple group of two fields"
fields_desc = [IntField('field1', 1),
IntField('field2', 2)]
class TopLayer(Packet):
name = "Storage for Repeating Sequence"
fields_desc = [FieldLenField("length", None, count_of='rep_seq'),
PacketListField('rep_seq', None, RepeatingGroupedSequence,
count_from = lambda pkt: pkt.length),
]
#Now here is the problem that I have with assembling PacketListField:
#craft TopLayer packet
p = TopLayer()
#add two "repeated sequences"
p.rep_seq = [ RepeatingGroupedSequence(), RepeatingGroupedSequence() ]
#both sequences can observed
p.show()
#but the underlying structure of the repeated sequence is #Raw# at this stage
p.show2()
#length is 2
print p.rep_seq, 'length:', len(p.rep_seq)
#but the cloned packet has only one "repeated sequence", the rest is raw
clone = TopLayer(str(p))
clone.show()
#length is 1
print clone.rep_seq, 'length:', len(clone.rep_seq)
这种方法的问题在于,当重新组装数据包时,不会保留分组的结构。在汇编时,RepeatedSequence
的第二个实例被视为原始实体,即使count字段为2.如何添加RepeatingSequences
这样的结构以便在重组时保留结构?有没有办法对字段进行分组而不依赖Packet
作为列表的存储类型?
答案 0 :(得分:7)
类RepeatingGroupedSequence
需要覆盖extract_padding
方法:
def extract_padding(self, s):
return '', s
默认情况下,每个子数据包都将所有内容视为属于自己的图层,即:
def extract_padding(self, s):
return s, None
这不是用于分组目的的。有人可以详细说明填充和层分离之间的区别吗?