为什么 scapy 无法识别我的自定义图层?

问题描述 投票:0回答:1

在 scapy 中,我添加了一个带有“bind_layers”的图层。但似乎我做错了什么,无法正确识别数据包。

我尝试向 scipy 添加一层,但不明白我错在哪里。

from scapy.data import ETHER_TYPES
from scapy.fields import XBitField, BitFieldLenField, ShortField, XShortEnumField
from scapy.layers.l2 import Ether, Dot1Q, LLC
from scapy.packet import Packet, bind_layers


def remove_layer(pkt, pos):
    print('remove_layer N = ' + str(pos))
    payload = pkt[pos].payload
    pkt[pos - 1].remove_payload()
    return pkt / payload


def remove_hsr(pkt):
    print('remove_hsr')
    print('layers:')
    for layer in pkt:
        print(layer.name)
    if HSR in pkt:
        print('HSR is here')
    j = 0
    for layer in pkt:
        if layer is HSR:
            print('HSR layer index: ' + str(j))
            return remove_layer(pkt, j)
        j += 1
    print('remove_hsr : HSR not found')
    return pkt


class HSR(Packet):
    name = "HSR"
    fields_desc = [
        XBitField("path_id", 0, 4),
        BitFieldLenField("lsdu_size", 0, 12),
        ShortField("sequence_number", 0),
        XShortEnumField("type", 0x9000, ETHER_TYPES),
    ]


bind_layers(Ether, HSR, type=0x892f)
bind_layers(Dot1Q, HSR, type=0x892f)


pkt_nohsr = '0060089fb1f300400540ef24000e810000200800450000a43b3b40004006b7548397208183972015048a17704e14e0754d3d609980187c70b13900000101080a0004f0c90199a3f3420007001d00c0000800c00000005e00d9025e00d9020000d9025e00420007001d00c0000900c00001005d00d8025d00d8020100d8025d00420007001d00c0000700c00001000100d80201000100010001005d00420007001d00c0000a00c00000000000d90200000000000000005e00568034cb'
pkt_nohsr = bytearray.fromhex(pkt_nohsr)
pkt_nohsr = Ether(pkt_nohsr)
print(pkt_nohsr)
pkt = '0060089fb1f300400540ef24892f10b60000000e810000200800450000a43b3b40004006b7548397208183972015048a17704e14e0754d3d609980187c70b13900000101080a0004f0c90199a3f3420007001d00c0000800c00000005e00d9025e00d9020000d9025e00420007001d00c0000900c00001005d00d8025d00d8020100d8025d00420007001d00c0000700c00001000100d80201000100010001005d00420007001d00c0000a00c00000000000d90200000000000000005e00568034cb'
pkt = bytearray.fromhex(pkt)
pkt = Ether(pkt)
print(pkt)
print(remove_hsr(pkt))

我的标题是“892f10b60000”,其中“892f”是我的类型的指示符。 我将我的层与 Ether 和 Dot1Q 连接起来,因为这些可能是较低层。 此代码产生输出:

802.3 00:40:05:40:ef:24 > 00:60:08:9f:b1:f3 / LLC / Raw / Padding
00:40:05:40:ef:24 > 00:60:08:9f:b1:f3 (0x892f) / HSR / Raw
remove_hsr
layers:
Ethernet
HSR is here
remove_hsr : HSR not found
00:40:05:40:ef:24 > 00:60:08:9f:b1:f3 (0x892f) / HSR / Raw

print(pkt)
无法识别添加了 HSR 的内层。
HSR in pkt
是正确的,但是
for layer in pkt
只有 1 次迭代,且层 == Ether。 我做错了什么?

python network-programming scapy
1个回答
0
投票

像您正在做的那样迭代有效负载并不会执行您认为的操作。 (

for layer in pkt:
)

您可以简单地使用以下代码:

def remove_hsr(pkt):
    while HSR in pkt:
        # Take set the payload of the layer above HSR to the payload under HSR
        pkt[HSR].underlayer.payload = pkt[HSR].payload
    return pkt
© www.soinside.com 2019 - 2024. All rights reserved.