在 Scapy/Kamene python 中,如何找到 pcap 文件的全局 headers?

In Scapy/Kamene python, how do I find the global headers for a pcap file?

所以在 C 中,在读取 Pcap 文件时,您可以使用 C libpcap 库来获取与全局相关的所有信息 headers:

typedef struct pcap_hdr_s {
        guint32 magic_number;   /* magic number */
        guint16 version_major;  /* major version number */
        guint16 version_minor;  /* minor version number */
        gint32  thiszone;       /* GMT to local correction */
        guint32 sigfigs;        /* accuracy of timestamps */
        guint32 snaplen;        /* max length of captured packets, in octets */
        guint32 network;        /* data link type */
} pcap_hdr_t;

所以我搜索了很长时间都没有找到如何在 python 库 Scapy/Kamene 中找到这些变量 Scapy/Kamene。

有人可以向我展示 Scapy/Kamene 中的示例代码,这将帮助我找到所有这些变量或至少找到所有这些变量的方法吗?

截至撰写本文时,这在 Scapy 中是不可能的。您仍然可以使用 python 来执行此操作,但将其作为字节结构读取:

import struct

LITTLE_ENDIAN = "<"
BIG_ENDIAN = ">"

with open("temp.pcap", "rb") as f:
    filebytes = f.read()
if filebytes[:2] == b"\xa1\xb2":
    endianness = BIG_ENDIAN
elif filebytes[:2] == b"\xd4\xc3":
    endianness = LITTLE_ENDIAN
# pcapng is a completely different filetype and has different headers
# It's magic number is also the same between big/little endian
elif filebytes[:2] == b"\n\r":
    raise ValueError("This capture is a pcapng file (expected pcap).")
else:
    raise ValueError("This capture is the wrong filetype (expected pcap.")

# Endianness is < or > and is handled by checking magic number.
pcap_headers = struct.unpack(endianness + "IHHIIII", filebytes[:24])
print(pcap_headers)
---
(2712847316, 2, 4, 0, 0, 524288, 1)

在这里,我们在我的 macos 系统上使用 < 解压小端(> 用于大端)。 H 读取 4 个字节,而 I 读取 2 个字节。您可以在 Python3 struct documentation 中阅读有关格式字符的更多信息。 我们可以很容易地检查幻数:

>>> int(str("A1B2C3D4"), 16)
2712847316

看起来这确实是一个具有正确幻数的 pcap。对于幻数字节顺序恶作剧,看看这个 SO answer(可以有多个正确的 pcap "magic numbers")。

感谢@Cukic0d:scapy 源代码是查看解析的好地方 pcap magic numbers