姜鹏辉的个人博客 GreyNius

【Python】使用scapy库来分析pcap数据包

2020-03-27

import scapy
from scapy.all import *
from scapy.utils import PcapReader

比较详细的一篇教程https://www.cntofu.com/book/33/6.md

读取pcap

packets=rdpcap("test.pcap")
for data in packets:
    if 'TCP' in data:
        s = repr(data)
        print(s)

可以通过data.time获取一个时间戳

IP数据读取

  • BitField(“version”, 4, 4),
  • BitField(“ihl”, None, 4),
  • XByteField(“tos”, 0),
  • ShortField(“len”, None),
  • ShortField(“id”, 1),
  • FlagsField(“flags”, 0, 3, [“MF”, “DF”, “evil”]),
  • BitField(“frag”, 0, 13),
  • ByteField(“ttl”, 64),
  • ByteEnumField(“proto”, 0, IP_PROTOS),
  • XShortField(“chksum”, None),
  • Emph(SourceIPField(“src”, “dst”)),
  • Emph(DestIPField(“dst”, “127.0.0.1”)),
  • PacketListField(“options”, [], IPOption, length_from=lambda p:p.ihl * 4 - 20)

其中proto的值是根据/etc/protocols文件确定的 常见的tcp是6,udp是17

TCP数据读取

源码地址:https://github.com/secdev/scapy/blob/master/scapy/layers/inet.py

TCP类有以下字段:

  • ShortEnumField(“sport”, 20, TCP_SERVICES),
  • ShortEnumField(“dport”, 80, TCP_SERVICES),
  • IntField(“seq”, 0),
  • IntField(“ack”, 0),
  • BitField(“dataofs”, None, 4),
  • BitField(“reserved”, 0, 3),
  • FlagsField(“flags”, 0x2, 9, “FSRPAUECN”),
  • ShortField(“window”, 8192),
  • XShortField(“chksum”, None),
  • ShortField(“urgptr”, 0),
  • TCPOptionsField(“options”, “”)

其中flags包括多个布尔值

  • flags
    • A ACK
    • S SYN
    • F FIN
    • R RST

方法:

  • mysummary() 打印一个数据包的流向,如TCP 192.168.2.241:51829 > 52.109.120.23:https A
  • answer(other) 判断是否是另一个包的回应

使用

print("{}:{} -> {}:{} seq={},ack={}".format(data['IP'].src,data['TCP'].sport,
            data['IP'].dst,data['TCP'].dport,data['TCP'].seq,data['TCP'].ack))

输出结果

52.109.120.23:443 -> 192.168.2.241:51829 seq=1658205636,ack=345150758

找到SYN等标志位

for data in packets:
    if 'TCP' in data:
        s = repr(data)
        if data['TCP'].flags == "S":
            print("S:")
        if data['TCP'].flags == "SA":
            print("A:")
        if data['TCP'].flags == "A":
            print("A:")
        print("{}:{} -> {}:{} seq={},ack={}".format(data['IP'].src,data['TCP'].sport,
                data['IP'].dst,data['TCP'].dport,data['TCP'].seq,data['TCP'].ack))

UDP数据获取

  • ShortEnumField(“sport”, 53, UDP_SERVICES)
  • ShortEnumField(“dport”, 53, UDP_SERVICES),
  • ShortField(“len”, None),
  • XShortField(“chksum”, None),

Comments

Content