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

标签 python scapy

我正在尝试在 Scapy 中为具有名为“扩展字段”的自定义字段类型的协议(protocol)创建一个层。

原理很简单,但我很难实现。

原理是:

  • 字段的第一个字节位于已知位置,后跟可变数量的字节。
  • 帧中的任何位置均未定义字节数。
  • 如果一个字节的 LSB 为“1”,则后续字节是该字段的一部分
  • 如果字节的 LSB 为“0”,则表示该字段结束。
  • 结果是一个位字段,每个字节连接 7 个 MSB 位

我做了一张图片以使其更简单:

Extended Field Description

我已经阅读了很多有关 Scapy 中可变长度字段的内容,但据我了解,这并不涵盖这种情况。

你认为它可以在 Scapy Layer 中实现吗?任何帮助将不胜感激。

最佳答案

好吧,我在深入研究 Scapy 后回答了自己。

这是一个有效的解决方案(可能不是最佳的,但对我来说足够了):

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)

关于python - 创建 Scapy 层时的扩展字段(链接字节),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55119682/

相关文章:

php - 检查页面内容是否已更改的最佳方法?

python - 协方差不是正定的

python - 使用嵌套的可写序列化程序上传 django rest 框架文件

python - if, elif 和 else.. 优先级和链

python - 如何使用 python scapy 创建示例 IPSec 数据包

python - 3次握手并在python中使用scapy获取请求

python - python 生成器的不一致行为

python - 使用 Scapy 更改数据包 - 在编辑数据包的有效负载后自动更新属性(长度、校验和等)

python-3.x - 如何使用scapy像wireshark一样抓取流量?

python - 如何在Python中使用scapy和nfqueue从数据包中获取ip?