假设我有一个包含所有十六进制值的字段的数据包。如何定义一个返回数据包的函数,其中数据包中字段的所有十六进制值都被反转?以下是我到目前为止的情况:
def complementPacket(pkt):
'''
Function: complementPacket
Purpose: Takes a packet as an input and inverts all bits in the packet.
Return: Inverted packet of same structure as the input packet
'''
retPkt = pkt
while(pkt): # iterate through the packets
for field in pkt.fields_desc:
print(fmtToLen(field.fmt)) # converts scapy field.fmt to the number of bits for that field type
# invert bits, assign to retPkt
pkt = pkt.payload
return retPkt
我能想到的唯一解决方案是迭代数据包并通过获取所有字段的补码来构造新数据包。有更好的方法吗?
给定一个带有十六进制(二进制)值的数据包P,我想返回〜P.
示例:
def customPacket(Packet):
name = "myPacket"
fields_desc = [XByteField("data", 1)]
pkt = customPacket()
pkt.show()
将输出' data'的值是0x1
complementedPkt = complementPacket(pkt)
complementedPkt.show()
将输出' data'的值是0xE
(0x1 = 0001,~0001 = 1110,1110 = 0xE)
答案 0 :(得分:0)
据我了解你的问题,你只需要反转数据包,对吧?在那种情况下:
class Packet(object):
""" Class represents a Packet object """
# _fields - is a list containing all hexa values, e.g. 0xff, 0x14
def __init__(self,vals):
self._fields = list(vals)
'''
def __iter__(self):
for field in self._fields:
yield field '''
'''
Function mimics bit (~) inversion. For instance,
1. 0xA4 -> ~1010 0100 -> 0101 1011 -> 0x5B
Param:
mask -> number of bytes'''
def invert(self, mask=2):
for (i, f) in zip(range(len(self._fields)), self._fields):
#check is needed for Ox0000 value(s)
if f.lower().lstrip('0x') == '':
xor = int('0', 16) ^ int('f'*mask, 16)
self._fields[i] = hex(xor)
else:
xor = int(f.lower().lstrip('0x'), 16) ^ int('f'*mask, 16)
self._fields[i] = hex(xor)
def __str__(self):
return ", ".join(x for x in self._fields)
def __repr__(self):
return ", ".join(x for x in self._fields)
要对此进行测试,您必须创建一个Packet对象并使用数据填充。你可以试试这个:
p1 = Packet([hex(x) for x in range(32)])
p2 = Packet([hex(x) for x in range(32,64)])
p3 = Packet([hex(x) for x in range(64,128)])
print("Original packet(p1): \n", p1)
p1.invert()
print("Packet after inversion(p1):\n",p1)
#----------------------------------------------
print("Original packet(p2): \n", p2)
p2.invert()
print("Packet after inversion(p2):\n",p2)
#----------------------------------------------
print("Original packet(p3): \n", p3)
p3.invert(3)
print("Packet after inversion(p3):\n",p3)