从Python访问802.11无线管理帧

use*_*941 7 python linux scapy wifi tshark

从Linux上的Python我想嗅探802.11管理'探测请求'帧.这可以从Scapy那样:

# -*- coding: utf-8 -*-
from scapy.all import *

def proc(p):
        if ( p.haslayer(Dot11ProbeReq) ):
                mac=re.sub(':','',p.addr2)
                ssid=p[Dot11Elt].info
                ssid=ssid.decode('utf-8','ignore')
                if ssid == "":
                        ssid="<BROADCAST>"
                print "%s:%s" %(mac,ssid)

sniff(iface="mon0",prn=proc)
Run Code Online (Sandbox Code Playgroud)

或者像这样的tshark:

tshark -n -i mon0 subtype probereq -R 'wlan.fc.type_subtype eq 4' -T fields -e wlan.sa -e wlan_mgt.ssid
Run Code Online (Sandbox Code Playgroud)

我们可以重定向来自tshark的输出,并用一些Python啜饮它(不是很漂亮,但它可以工作).

但是,这两个选项都有GPL许可,这使得潜在的商业项目变得棘手.因此,我正试图在Python中找出针对此特定问题的"较低级别"解决方案.来自Google我已经设法找出了两个可能的方向:

  1. Pcap库:似乎有三个可用于Python的pcap库: pylibpcap,pypcappcapy.我不太确定如何将上述功能纳入这些功能.任何示例代码或解决方案都会很棒.

  2. 原始套接字:PF_PACKET:"数据包套接字用于在设备驱动程序(OSI第2层)级别接收或发送原始数据包.它们允许用户在物理层顶部的用户空间中实现协议模块."

听起来这可能是另一种选择,完全绕过pcap.我听说过这可能是一个更好的方法,消除了pcap库的开销.不过,我不知道从哪里开始解决这个问题.

任何帮助解决这个问题将不胜感激.

use*_*941 7

我设法解决了这个问题.这是我经历的过程:

  1. 捕获一些802.11管理"探测请求"帧:

    tshark -n -i mon0 subtype probereq -c 5 -w probe.pcap
    
    Run Code Online (Sandbox Code Playgroud)
  2. 了解RadioTap

    阅读RadioTap文档,我意识到RadioTap帧由以下字段组成:

    it_version (2 bytes) - major version of the radiotap header is in use. Currently, this is always 0
    it_pad (2 bytes) - currently unused 
    it_len (4 bytes) - entire length of the radiotap data, including the radiotap header
    it_present (8 byte) - bitmask of the radiotap data fields that follows the radiotap header
    
    Run Code Online (Sandbox Code Playgroud)

    因此,it_len允许我们找到跟随radiotap数据的802.11帧的开头.

  3. Python编码解决方案

    我选择使用pylibpcap从我在以前的帖子发现了三个PCAP库选项,并发现了dpkt模块解析802.11帧.文档很薄,所以通过在Python解释器中播放,我设法计算出以下代码,从我们的捕获文件中提取MAC,探测SSID和信号强度:

    f = open('probe.pcap')
    pc = dpkt.pcap.Reader(f)
    dl=pc.datalink()
    if pc.datalink() == 127: #Check if RadioTap
            for timestamp, rawdata in pc:
                    tap = dpkt.radiotap.Radiotap(rawdata)
                    signal_ssi=-(256-tap.ant_sig.db)        #Calculate signal strength
                    t_len=binascii.hexlify(rawdata[2:3])    #t_len field indicates the entire length of the radiotap data, including the radiotap header.
                    t_len=int(t_len,16)                     #Convert to decimal
                    wlan = dpkt.ieee80211.IEEE80211(rawdata[t_len:])
                    if wlan.type == 0 and wlan.subtype == 4: # Indicates a probe request
                        ssid = wlan.ies[0].info
                        mac=binascii.hexlify(wlan.mgmt.src)
                        print "%s, %s (%d dBm)"%(mac,ssid,signal_ssi)
    
    Run Code Online (Sandbox Code Playgroud)