创建Scapy层时的扩展字段(链接字节)

2024-04-26 13:02:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在Scapy中为一个协议创建一个层,该协议有一个名为“扩展字段”的自定义字段类型。你知道吗

原则很简单,但我很难实现。你知道吗

原则是:

  • 字段的第一个字节位于已知位置,后跟可变的字节数。你知道吗
  • 帧中的任何位置都没有定义字节数。你知道吗
  • 如果一个字节的LSB是“1”,那么下面的字节就是字段的一部分
  • 如果一个字节的LSB是“0”,那么它就是字段的结尾。你知道吗
  • 结果是一个位字段,每个字节包含7个MSB位

我画了一张图让它更简单:

Extended Field Description

我在Scapy读了很多关于可变长度字段的资料,但据我所知,这并不包括这个案例。你知道吗

你认为它可以在Scapy层实现吗?任何帮助都将不胜感激。你知道吗


Tags: extended协议类型field字节定义结尾description
1条回答
网友
1楼 · 发布于 2024-04-26 13:02:40

好吧,我在深入研究了一下斯卡皮之后回答了我自己。你知道吗

下面是一个可行的解决方案(可能不是最优的,但对我来说已经足够了):

from scapy.all import *

class LSBExtendedField(Field):
    """
    LSB Extended Field
             

    This type of field has a variable number of bytes. Each byte is defined as follows:
    - The 7 MSB bits are data
    - The LSB is an extenesion bit
        * 0 means it is last byte of the field ("stopping bit")
        * 1 means there is another byte after this one ("forwarding bit")

    To get the actual data, it is necessary to navigate the binary data byte per byte and to check if LSB until 0
    """

    """
    Converts bytes to field
    """
    def str2extended(self, l=""):
        s = []
        # First bit is the stopping bit at zero
        bits = 0b0
        # Then we retrieve 7 bits. If "forwarding bit" is 1, then we continue on another byte
        i = 0
        for c in l:
            s.append(hex(c & 0xfe))
            bits = bits << 7 | (int(c) >> 1)
            if not int(c)&0b1:
                end = l[i+1:]
                break
            i=i+1
        return end, bits

    """
    Converts field to bytes
    """
    def extended2str(self, l):
        l=int(l)
        s = []
        # First bit is the stopping bit at zero
        bits = 0b0
        # Then we group bits 7 by 7 adding the "forwarding bit" if necessary
        i=1
        while (l>0):
            if i%8 == 0:
                s.append(bits)
                bits = 0b1
                i=0
            else:
                bits = bits | (l & 0b1) << i
                l = l >> 1
            i = i+1
        s.append(bits)
        s.reverse()

        result = "".encode()
        for x in s:
            result = result + struct.pack(">B", x)
        return result

    def i2m(self, pkt, x):
        return self.extended2str(x)

    def m2i(self, pkt, x):
        return self.str2extended(x)[1]

    def addfield(self, pkt, s, val):
        return s+self.i2m(pkt, val)

    def getfield(self, pkt, s):
        return self.str2extended(s)

相关问题 更多 >