简体   繁体   English

通过ctypes使用pcap的python分段错误

[英]python segmentation fault using pcap via ctypes

I am porting my sniffer from C to Python using libpcap via ctypes. 我通过ctypes使用libpcap将嗅探器从C移植到Python。 Here is the python code: 这是python代码:

import ctypes, sys
from ctypes.util import find_library

if sys.platform == "darwin":
    _pcap = ctypes.cdll.LoadLibrary(find_library("libpcap"))
elif sys.platform == "linux2":
    _pcap = ctypes.cdll.LoadLibrary("libpcap.so")

errbuf = ctypes.create_string_buffer(256)

pcap_lookupdev = _pcap.pcap_lookupdev
pcap_lookupdev.restype = ctypes.c_char_p
dev = pcap_lookupdev(errbuf)
print dev

# create handler
pcap_create = _pcap.pcap_create
handle = pcap_create(dev, errbuf)
print handle
if not handle:
    print "failed creating handler:",errbuf
    exit()

# monitor mode
pcap_can_set_rfmon = _pcap.pcap_can_set_rfmon
print "can rfmon:",pcap_can_set_rfmon(handle)

On Linux it works perfectly fine, but on Mac OS X it runs into a segmentation fault when I use handle. 在Linux上,它工作得很好,但是在Mac OS X上,当我使用handle时,它会遇到分段错误。 The value of handle even is sometimes negative, sometimes positive. handle的值有时为负,有时为正。 I already tried to change the return type of pcap_create to unsigned int, but that didn't help, but I think it returns a wrong type under OS X... 我已经尝试将pcap_create的返回类型更改为unsigned int,但这没有帮助,但是我认为它在OS X下返回了错误的类型...

I did a printf("size of pcap_t: %zu\\n", sizeof(pcap_t *)); 我做了一个printf("size of pcap_t: %zu\\n", sizeof(pcap_t *)); on both systems in C to get the size of pcap_t handler type. 在C中的两个系统上都可以获取pcap_t处理程序类型的大小。 On Linux it says 4 and on OS X 8. But II don't know how to go on from this point... 在Linux上,它表示4,在OS X 8上,但是II不知道如何继续。

Or am I on the wrong path? 还是我走错了路? Does anyone have an idea? 有人有主意吗?

Data types matter. 数据类型很重要。

You need to tell ctypes that the return value of pcap_create() is a pointer, and you need to tell it that the argument to pcap_can_set_rfmon() is a pointer. 您需要告诉ctypes pcap_create()的返回值是一个指针,并且需要告诉它pcap_can_set_rfmon()的参数是一个指针。

You do this by doing 你这样做

# create handler
pcap_create = _pcap.pcap_create
pcap_create.restype = ctypes.c_void_p
handle = pcap_create(dev, errbuf)
print handle
if not handle:
    print "failed creating handler:",errbuf
    exit()

# monitor mode
pcap_can_set_rfmon = _pcap.pcap_can_set_rfmon
pcap_can_set_rfmon.argtypes = [ctypes.c_void_p]
print "can rfmon:",pcap_can_set_rfmon(handle)

The

pcap_create.restype = ctypes.c_void_p

and

pcap_can_set_rfmon.argtypes = [ctypes.c_void_p]

lines are required here. 这里需要行。 This code will work with both 32-bit and 64-bit pointers, so you can use it on 32-bit and 64-bit Linux and on 32-bit and 64-bit OS X (and 32-bit and 64-bit Solaris and 32-bit and 64-bit FreeBSD and..., with whatever changes are needed to the code to load the library - on most Un*xes shared libraries have names ending with ".so", so if you don't want to use find_library on other Un*xes, the Linux code may suffice). 该代码可同时用于32位和64位指针,因此您可以在32位和64位Linux以及32位和64位OS X(以及32位和64位Solaris)上使用它以及32位和64位FreeBSD以及...,对加载库的代码进行了任何更改-在大多数Un * xes共享库中,名称都以“ .so”结尾,因此如果您不想要在其他Un * find_library上使用find_library ,Linux代码可能就足够了)。

I really wanted to come here and post since I was having this issue on OS X as well. 我真的很想来到这里发布,因为我在OS X上也遇到了这个问题。 The issue I found with your code is: 我在您的代码中发现的问题是:

handle = pcap_create(dev, errbuf)

You need to set the restype, here is my example as this may help a few of you down the road: https://github.com/killswitch-GUI/NIX-Sniffer-Examples 您需要设置restype,这是我的示例,因为这可能会帮助一些人: https : //github.com/killswitch-GUI/NIX-Sniffer-Examples

    import ctypes
    import threading
    import sys
    import os
    import errno


    OSX_PCAP_DYLIB = '/usr/lib/libpcap.A.dylib'
    OSX_LIBC_DYLIB = '/usr/lib/libSystem.B.dylib'
    PCAP_ERRBUF_SIZE = 256
    packet_count_limit = ctypes.c_int(1)
    timeout_limit = ctypes.c_int(1000) # In milliseconds 
    err_buf = ctypes.create_string_buffer(PCAP_ERRBUF_SIZE)

    class bpf_program(ctypes.Structure):
        _fields_ = [("bf_len", ctypes.c_int),("bf_insns", ctypes.c_void_p)]

    class pcap_pkthdr(ctypes.Structure):
        _fields_ = [("tv_sec", ctypes.c_long), ("tv_usec", ctypes.c_long), ("caplen", ctypes.c_uint), ("len", ctypes.c_uint)]

    class pcap_stat(ctypes.Structure):
        _fields_ = [("ps_recv",ctypes.c_uint), ("ps_drop",ctypes.c_uint), ("ps_ifdrop", ctypes.c_int)]

    def pkthandler(pkthdr,packet):
        print("In callback:")
        print("pkthdr[0:7]:",pkthdr.contents.len)
        print(pkthdr.contents.tv_sec,pkthdr.contents.caplen,pkthdr.contents.len)
        print(packet.contents[:10])
        print()

    print "-------------------------------------------"
    libc = ctypes.CDLL(OSX_LIBC_DYLIB, use_errno=True)
    if not libc:
        print "Error loading C libary: %s" % errno.errorcode[ctypes.get_errno()]
    print "* C runtime libary loaded: %s" % OSX_LIBC_DYLIB
    pcap = ctypes.CDLL(OSX_PCAP_DYLIB, use_errno=True)
    if not pcap:
        print "Error loading C libary: %s" % errno.errorcode[ctypes.get_errno()]
    print "* C runtime libary loaded: %s" % OSX_PCAP_DYLIB
    print "* C runtime handle at: %s" % pcap

    print "-------------------------------------------"
    pcap_lookupdev = pcap.pcap_lookupdev
    pcap_lookupdev.restype = ctypes.c_char_p
    dev = pcap.pcap_lookupdev()
    print "* Device handle at: %s" % dev

    net = ctypes.c_uint()
    mask = ctypes.c_uint()
    pcap.pcap_lookupnet(dev,ctypes.byref(net),ctypes.byref(mask),err_buf)
    print "* Device IP to bind: %s" % net
    print "* Device net mask: %s" % mask

    #pcap_t *pcap_open_live(const char *device, int snaplen,int promisc, int to_ms, char *errbuf)
    pcap_open_live = pcap.pcap_open_live
    pcap_open_live.restype = ctypes.POINTER(ctypes.c_void_p)
    pcap_create = pcap.pcap_create
    pcap_create.restype = ctypes.c_void_p
    #pcap_handle = pcap.pcap_create(dev, err_buf)
    pcap_handle = pcap.pcap_open_live(dev, 1024, packet_count_limit, timeout_limit, err_buf)
    print "* Live capture device handle at: %s" % pcap_handle 

    pcap_can_set_rfmon = pcap.pcap_can_set_rfmon
    pcap_can_set_rfmon.argtypes = [ctypes.c_void_p]
    if (pcap_can_set_rfmon(pcap_handle) == 1):
        print "* Can set interface in monitor mode"

    pcap_pkthdr_p = ctypes.POINTER(pcap_pkthdr)()
    packetdata = ctypes.POINTER(ctypes.c_ubyte*65536)()
    #print pcap.pcap_next(pcap_handle,ctypes.byref(pcap_pkthdr_p))

    if (pcap.pcap_next_ex(pcap_handle, ctypes.byref(pcap_pkthdr_p), ctypes.byref(packetdata)) == 1):
        print "* Packet captured!"
        pkthandler(pcap_pkthdr_p,packetdata)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM