Scapy: How to insert a new layer (802.1q) into existing packet?

∥☆過路亽.° 提交于 2019-12-12 10:55:36

问题


I have a packet dump and want to inject a vlan tag (802.1q header) to the packets.
How to do that?


回答1:


To find the answer, I had a look at Scapy: Inserting a new layer and logging issues, which is really helpful, but contains some cruft.

My solution for adding a layer, based on the referenced question (add-dot1q_pcap.py):

import sys
from scapy.all import rdpcap, wrpcap, NoPayload, Ether, Dot1Q

# read all packets into buffer
# WARNING works only for small files
packets = []

for packet in rdpcap(sys.argv[1]):
    # gets the first layer of the current packet
    layer = packet.firstlayer()
    # loop over the layers
    while not isinstance(layer, NoPayload):
        if 'chksum' in layer.default_fields:
            del layer.chksum

        if (type(layer) is Ether):
            # adjust ether type
            layer.type = 33024
            # add 802.1q layer between Ether and IP
            dot1q = Dot1Q(vlan=42)
            dot1q.add_payload(layer.payload)
            layer.remove_payload()
            layer.add_payload(dot1q)
            layer = dot1q

        # advance to the next layer
        layer = layer.payload
    packets.append(packet)

wrpcap(sys.argv[2], packets)

The script adds a vlan tag with vlan id 42.

Usage: ./add-dot1q_pcap.py <source_file> <output_file>



来源:https://stackoverflow.com/questions/29133482/scapy-how-to-insert-a-new-layer-802-1q-into-existing-packet

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!