summaryrefslogtreecommitdiffstats
path: root/scripts/external_libs/scapy-python3-0.18/scapy/arch
diff options
context:
space:
mode:
authorimarom <imarom@cisco.com>2016-03-21 16:03:47 +0200
committerimarom <imarom@cisco.com>2016-03-21 16:03:47 +0200
commitb89efa188810bf95a9d245e69e2961b5721c3b0f (patch)
tree454273ac6c4ae972ebb8a2c86b893296970b4fa9 /scripts/external_libs/scapy-python3-0.18/scapy/arch
parentf72c6df9d2e9998ae1f3529d729ab7930b35785a (diff)
scapy python 2/3
Diffstat (limited to 'scripts/external_libs/scapy-python3-0.18/scapy/arch')
-rw-r--r--scripts/external_libs/scapy-python3-0.18/scapy/arch/__init__.py108
-rw-r--r--scripts/external_libs/scapy-python3-0.18/scapy/arch/bsd.py12
-rw-r--r--scripts/external_libs/scapy-python3-0.18/scapy/arch/cdnet.py229
-rw-r--r--scripts/external_libs/scapy-python3-0.18/scapy/arch/linux.py530
-rw-r--r--scripts/external_libs/scapy-python3-0.18/scapy/arch/pcapdnet.py565
-rw-r--r--scripts/external_libs/scapy-python3-0.18/scapy/arch/solaris.py16
-rw-r--r--scripts/external_libs/scapy-python3-0.18/scapy/arch/unix.py168
-rw-r--r--scripts/external_libs/scapy-python3-0.18/scapy/arch/windows/__init__.py501
-rw-r--r--scripts/external_libs/scapy-python3-0.18/scapy/arch/winpcapy.py739
9 files changed, 0 insertions, 2868 deletions
diff --git a/scripts/external_libs/scapy-python3-0.18/scapy/arch/__init__.py b/scripts/external_libs/scapy-python3-0.18/scapy/arch/__init__.py
deleted file mode 100644
index 0066e049..00000000
--- a/scripts/external_libs/scapy-python3-0.18/scapy/arch/__init__.py
+++ /dev/null
@@ -1,108 +0,0 @@
-## This file is part of Scapy
-## See http://www.secdev.org/projects/scapy for more informations
-## Copyright (C) Philippe Biondi <phil@secdev.org>
-## This program is published under a GPLv2 license
-
-"""
-Operating system specific functionality.
-"""
-
-
-import sys,os,socket
-from scapy.error import *
-import scapy.config
-
-try:
- import matplotlib.pyplot as plt
- MATPLOTLIB = True
- if scapy.config.conf.interactive:
- plt.ion()
-except ImportError:
- log_loading.info("Can't import matplotlib. Not critical, but won't be able to plot.")
- MATPLOTLIB = False
-
-try:
- import networkx as nx
- NETWORKX = True
-except ImportError:
- log_loading.info("Can't import networkx. Not criticial, but won't be able to draw network graphs.")
- NETWORKX = False
-
-try:
- import pyx
- PYX=1
-except ImportError:
- log_loading.info("Can't import PyX. Won't be able to use psdump() or pdfdump().")
- PYX=0
-
-
-def str2mac(s):
- #return ("%02x:"*6)[:-1] % tuple(map(ord, s))
- return ("%02x:"*6)[:-1] % tuple(s)
-
-
-
-def get_if_addr(iff):
- return socket.inet_ntoa(get_if_raw_addr(iff))
-
-def get_if_hwaddr(iff):
- mac = get_if_raw_hwaddr(iff)
- return str2mac(mac)
-
-
-LINUX=sys.platform.startswith("linux")
-OPENBSD=sys.platform.startswith("openbsd")
-FREEBSD=sys.platform.startswith("freebsd")
-NETBSD = sys.platform.startswith("netbsd")
-DARWIN=sys.platform.startswith("darwin")
-SOLARIS=sys.platform.startswith("sunos")
-WINDOWS=sys.platform.startswith("win32")
-
-X86_64 = not WINDOWS and (os.uname()[4] == 'x86_64')
-
-#if WINDOWS:
-# log_loading.warning("Windows support for scapy3k is currently in testing. Sniffing/sending/receiving packets should be working with WinPcap driver and Powershell. Create issues at https://github.com/phaethon/scapy")
-
-# Next step is to import following architecture specific functions:
-# def get_if_raw_hwaddr(iff)
-# def get_if_raw_addr(iff):
-# def get_if_list():
-# def get_working_if():
-# def attach_filter(s, filter):
-# def set_promisc(s,iff,val=1):
-# def read_routes():
-# def get_if(iff,cmd):
-# def get_if_index(iff):
-
-
-
-if LINUX:
- from .linux import *
- if scapy.config.conf.use_winpcapy or scapy.config.conf.use_netifaces:
- from pcapdnet import *
-elif OPENBSD or FREEBSD or NETBSD or DARWIN:
- from .bsd import *
-elif SOLARIS:
- from .solaris import *
-elif WINDOWS:
- pass;
- #from .windows import *
-
-LOOPBACK_NAME="a"
-
-if scapy.config.conf.iface is None:
- scapy.config.conf.iface = LOOPBACK_NAME
-
-def get_if_raw_addr6(iff):
- """
- Returns the main global unicast address associated with provided
- interface, in network format. If no global address is found, None
- is returned.
- """
- #r = filter(lambda x: x[2] == iff and x[1] == IPV6_ADDR_GLOBAL, in6_getifaddr())
- r = [ x for x in in6_getifaddr() if x[2] == iff and x[1] == IPV6_ADDR_GLOBAL]
- if len(r) == 0:
- return None
- else:
- r = r[0][0]
- return inet_pton(socket.AF_INET6, r)
diff --git a/scripts/external_libs/scapy-python3-0.18/scapy/arch/bsd.py b/scripts/external_libs/scapy-python3-0.18/scapy/arch/bsd.py
deleted file mode 100644
index c4220308..00000000
--- a/scripts/external_libs/scapy-python3-0.18/scapy/arch/bsd.py
+++ /dev/null
@@ -1,12 +0,0 @@
-## This file is part of Scapy
-## See http://www.secdev.org/projects/scapy for more informations
-## Copyright (C) Philippe Biondi <phil@secdev.org>
-## This program is published under a GPLv2 license
-
-"""
-Support for BSD-like operating systems such as FreeBSD, OpenBSD and Mac OS X.
-"""
-
-LOOPBACK_NAME="lo0"
-
-from .unix import *
diff --git a/scripts/external_libs/scapy-python3-0.18/scapy/arch/cdnet.py b/scripts/external_libs/scapy-python3-0.18/scapy/arch/cdnet.py
deleted file mode 100644
index 98ebf084..00000000
--- a/scripts/external_libs/scapy-python3-0.18/scapy/arch/cdnet.py
+++ /dev/null
@@ -1,229 +0,0 @@
-from ctypes import *
-from ctypes.util import find_library
-import sys
-
-WIN=False
-
-if sys.platform.startswith('win'):
- WIN=True
-
-if WIN:
- SOCKET = c_uint
- _lib=CDLL('dnet')
-else:
- SOCKET = c_int
- _lib_name = find_library('dnet')
- if not _lib_name:
- raise OSError("Cannot find libdnet.so")
- _lib=CDLL(_lib_name)
-
-ETH_ADDR_LEN = 6
-INTF_NAME_LEN = 16
-INTF_NAME_COUNT = 20
-INTF_ALIAS_COUNT = 20
-IP6_ADDR_LEN = 16
-
-ADDR_TYPE_NONE = 0
-ADDR_TYPE_ETH = 1
-ADDR_TYPE_IP = 2
-ADDR_TYPE_IP6 = 3
-
-INTF_TYPE_OTHER = 1
-INTF_TYPE_ETH = 6
-INTF_TYPE_TOKENRING = 9
-INTF_TYPE_FDDI = 15
-INTF_TYPE_PPP = 23
-INTF_TYPE_LOOPBACK = 24
-INTF_TYPE_SLIP = 28
-INTF_TYPE_TUN = 53
-
-
-uint8_t = c_ubyte
-uint16_t = c_ushort
-uint32_t = c_uint
-ssize_t = c_long
-dnet_ip_addr_t = uint32_t
-
-dnet_intf_name = c_char * INTF_NAME_LEN
-
-class dnet_intf_list(Structure):
- pass
-
-dnet_intf_list._fields_ = [ ('length', c_int),
- ('interfaces', dnet_intf_name * 20) ]
-
-class dnet_eth_addr(Structure):
- pass
-
-dnet_eth_addr._fields_ = [ ('data', uint8_t * ETH_ADDR_LEN) ]
-dnet_eth_addr_t = dnet_eth_addr
-
-class dnet_ip6_addr(Structure):
- pass
-
-dnet_ip6_addr._fields_ = [ ('data', uint8_t * IP6_ADDR_LEN) ]
-dnet_ip6_addr_t = dnet_ip6_addr
-
-class dnet_addr_u(Union):
- pass
-
-dnet_addr_u._fields_ = [ ('eth', dnet_eth_addr_t),
- ('ip', dnet_ip_addr_t),
- ('ip6', dnet_ip6_addr_t),
- ('data8', uint8_t * 16),
- ('data16', uint16_t * 8),
- ('data32', uint32_t * 4) ]
-
-class dnet_addr(Structure):
- pass
-dnet_addr._anonymous_ = ('__addr_u', )
-dnet_addr._fields_ = [ ('addr_type', uint16_t),
- ('addr_bits', uint16_t),
- ('__addr_u', dnet_addr_u) ]
-
-class dnet_intf_entry(Structure):
- pass
-
-dnet_intf_entry._fields_ = [ ('intf_len', c_uint),
- ('intf_name', c_char * INTF_NAME_LEN),
- ('intf_type', c_ushort),
- ('intf_flags', c_ushort),
- ('intf_mtu', c_uint),
- ('intf_addr', dnet_addr),
- ('intf_dst_addr', dnet_addr),
- ('intf_link_addr', dnet_addr),
- ('intf_alias_num', c_uint),
- ('intf_alias_addrs', dnet_addr * INTF_ALIAS_COUNT) ]
-
-
-eth_t = c_void_p
-intf_t = c_void_p
-ip_t = c_void_p
-dnet_intf_handler = CFUNCTYPE(c_int, POINTER(dnet_intf_entry), POINTER(c_void_p))
-
-dnet_eth_open = _lib.eth_open
-dnet_eth_open.restype = POINTER(eth_t)
-dnet_eth_open.argtypes = [ POINTER(c_char) ]
-
-dnet_eth_get = _lib.eth_get
-dnet_eth_get.restype = c_int
-dnet_eth_get.argtypes = [ POINTER(eth_t), POINTER(dnet_eth_addr_t) ]
-
-dnet_eth_set = _lib.eth_set
-dnet_eth_set.restype = c_int
-dnet_eth_set.argtypes = [ POINTER(eth_t), POINTER(dnet_eth_addr_t) ]
-
-dnet_eth_send = _lib.eth_send
-dnet_eth_send.restype = ssize_t
-dnet_eth_send.argtypes = [ POINTER(eth_t), c_void_p, c_size_t ]
-
-dnet_eth_close = _lib.eth_close
-dnet_eth_close.restype = POINTER(eth_t)
-dnet_eth_close.argtypes = [ POINTER(eth_t) ]
-
-dnet_intf_open = _lib.intf_open
-dnet_intf_open.restype = POINTER(intf_t)
-dnet_intf_open.argtypes = [ ]
-
-dnet_intf_get = _lib.intf_get
-dnet_intf_get.restype = c_int
-dnet_intf_get.argtypes = [ POINTER(intf_t), POINTER(dnet_intf_entry) ]
-
-dnet_intf_get_src = _lib.intf_get_src
-dnet_intf_get_src.restype = c_int
-dnet_intf_get_src.argtypes = [ POINTER(intf_t), POINTER(dnet_intf_entry), POINTER(dnet_addr) ]
-
-dnet_intf_get_dst = _lib.intf_get_dst
-dnet_intf_get_dst.restype = c_int
-dnet_intf_get_dst.argtypes = [ POINTER(intf_t), POINTER(dnet_intf_entry), POINTER(dnet_addr) ]
-
-dnet_intf_set = _lib.intf_set
-dnet_intf_set.restype = c_int
-dnet_intf_set.argtypes = [ POINTER(intf_t), POINTER(dnet_intf_entry) ]
-
-dnet_intf_loop = _lib.intf_loop
-dnet_intf_loop.restype = POINTER(intf_t)
-dnet_intf_loop.argtypes = [ POINTER(intf_t), dnet_intf_handler, c_void_p ]
-
-dnet_intf_close = _lib.intf_close
-dnet_intf_close.restype = POINTER(intf_t)
-dnet_intf_close.argtypes = [ POINTER(intf_t) ]
-
-dnet_ip_open = _lib.ip_open
-dnet_ip_open.restype = POINTER(ip_t)
-dnet_ip_open.argtypes = [ ]
-
-dnet_ip_add_option = _lib.ip_add_option
-dnet_ip_add_option.restype = ssize_t
-dnet_ip_add_option.argtypes = [ POINTER(c_void_p), c_size_t, c_int, POINTER(c_void_p), c_size_t ]
-
-dnet_ip_checksum = _lib.ip_checksum
-dnet_ip_checksum.restype = None
-dnet_ip_checksum.argtypes = [ POINTER(c_void_p), c_size_t ]
-
-dnet_ip_send = _lib.ip_send
-dnet_ip_send.restype = ssize_t
-dnet_ip_send.argtypes = [ POINTER(ip_t), c_void_p, c_size_t ]
-
-dnet_ip_close = _lib.ip_close
-dnet_ip_close.restype = POINTER(ip_t)
-dnet_ip_close.argtypes = [ POINTER(ip_t) ]
-
-class dnet_eth:
- def __init__(self, iface):
- self.iface_b = create_string_buffer(iface.encode('ascii'))
- self.eth = dnet_eth_open(self.iface_b)
- def send(self, sx):
- dnet_eth_send(self.eth, sx, len(sx))
- def close(self):
- return dnet_eth_close(self.eth)
-
-class dnet_ip:
- def __init__(self):
- self.ip = dnet_ip_open()
- def send(self, sx):
- dnet_ip_send(self.ip, sx, len(sx))
- def close(self):
- return dnet_ip_close(self.ip)
-
-def dnet_intf_name_loop(entry, intf_list):
- l = cast(intf_list, POINTER(dnet_intf_list))
- if l.contents.length >= INTF_NAME_COUNT:
- return -1
- for i in enumerate(entry.contents.intf_name):
- l.contents.interfaces[l.contents.length][i[0]] = i[1]
- l.contents.length += 1
- return 0
-
-class dnet_intf:
- def __init__(self):
- self.intf = dnet_intf_open()
- intf_list = dnet_intf_list()
- intf_list.length = 0
- dnet_intf_loop(self.intf, dnet_intf_handler(dnet_intf_name_loop), pointer(intf_list))
- self.names = []
- for i in range(INTF_NAME_COUNT):
- if i >= intf_list.length:
- break
- self.names.append(intf_list.interfaces[i].value.decode('ascii').strip('\0'))
-
- def close(self):
- return dnet_intf_close(self.intf)
-
- def get(self, iface):
- ret = {}
- entry = dnet_intf_entry()
- entry.intf_name = iface.encode('ascii')
- entry.intf_len = sizeof(entry)
- r = dnet_intf_get(self.intf, byref(entry))
- if r < 0:
- return {}
- ret['addr6'] = []
- for i in range(entry.intf_alias_num):
- if entry.intf_alias_addrs[i].addr_type == ADDR_TYPE_IP6:
- ret['addr6'].append(bytes(entry.intf_alias_addrs[i].data8[:16]))
- ret['type'] = entry.intf_type
- ret['addr'] = bytes(entry.intf_addr.data8[:4])
- ret['link_addr'] = bytes(entry.intf_link_addr.data8[:6])
- return ret
-
diff --git a/scripts/external_libs/scapy-python3-0.18/scapy/arch/linux.py b/scripts/external_libs/scapy-python3-0.18/scapy/arch/linux.py
deleted file mode 100644
index 3eab16c6..00000000
--- a/scripts/external_libs/scapy-python3-0.18/scapy/arch/linux.py
+++ /dev/null
@@ -1,530 +0,0 @@
-## This file is part of Scapy
-## See http://www.secdev.org/projects/scapy for more informations
-## Copyright (C) Philippe Biondi <phil@secdev.org>
-## This program is published under a GPLv2 license
-
-"""
-Linux specific functions.
-"""
-
-import sys,os,struct,socket,time,ctypes
-from select import select
-from fcntl import ioctl
-import scapy.utils
-import scapy.utils6
-from scapy.config import conf
-from scapy.data import *
-from scapy.supersocket import SuperSocket
-import scapy.arch
-from scapy.error import warning, Scapy_Exception
-
-
-
-# From bits/ioctls.h
-SIOCGIFHWADDR = 0x8927 # Get hardware address
-SIOCGIFADDR = 0x8915 # get PA address
-SIOCGIFNETMASK = 0x891b # get network PA mask
-SIOCGIFNAME = 0x8910 # get iface name
-SIOCSIFLINK = 0x8911 # set iface channel
-SIOCGIFCONF = 0x8912 # get iface list
-SIOCGIFFLAGS = 0x8913 # get flags
-SIOCSIFFLAGS = 0x8914 # set flags
-SIOCGIFINDEX = 0x8933 # name -> if_index mapping
-SIOCGIFCOUNT = 0x8938 # get number of devices
-SIOCGSTAMP = 0x8906 # get packet timestamp (as a timeval)
-
-# From if.h
-IFF_UP = 0x1 # Interface is up.
-IFF_BROADCAST = 0x2 # Broadcast address valid.
-IFF_DEBUG = 0x4 # Turn on debugging.
-IFF_LOOPBACK = 0x8 # Is a loopback net.
-IFF_POINTOPOINT = 0x10 # Interface is point-to-point link.
-IFF_NOTRAILERS = 0x20 # Avoid use of trailers.
-IFF_RUNNING = 0x40 # Resources allocated.
-IFF_NOARP = 0x80 # No address resolution protocol.
-IFF_PROMISC = 0x100 # Receive all packets.
-
-# From netpacket/packet.h
-PACKET_ADD_MEMBERSHIP = 1
-PACKET_DROP_MEMBERSHIP = 2
-PACKET_RECV_OUTPUT = 3
-PACKET_RX_RING = 5
-PACKET_STATISTICS = 6
-PACKET_MR_MULTICAST = 0
-PACKET_MR_PROMISC = 1
-PACKET_MR_ALLMULTI = 2
-
-# From bits/socket.h
-SOL_PACKET = 263
-# From asm/socket.h
-SO_ATTACH_FILTER = 26
-SOL_SOCKET = 1
-
-# From net/route.h
-RTF_UP = 0x0001 # Route usable
-RTF_REJECT = 0x0200
-
-# From pcap/pcap.h
-PCAP_ERRBUF_SIZE=256
-
-
-
-LOOPBACK_NAME="lo"
-
-with os.popen("tcpdump -V 2> /dev/null") as _f:
- if _f.close() >> 8 == 0x7f:
- log_loading.warning("Failed to execute tcpdump. Check it is installed and in the PATH")
- TCPDUMP=0
- else:
- TCPDUMP=1
-del(_f)
-
-
-def get_if_raw_hwaddr(iff):
- return struct.unpack("16xh6s8x",get_if(iff,SIOCGIFHWADDR))[1]
-
-def get_if_raw_addr(iff):
- try:
- return get_if(iff, SIOCGIFADDR)[20:24]
- except IOError:
- return b"\0\0\0\0"
-
-
-def get_if_list():
- try:
- f=open("/proc/net/dev","r")
- except IOError:
- warning("Can't open /proc/net/dev !")
- return []
- lst = []
- f.readline()
- f.readline()
- for l in f:
- lst.append(l.split(":")[0].strip())
- f.close()
- return lst
-
-def get_working_if():
- for i in get_if_list():
- if i == LOOPBACK_NAME:
- continue
- ifflags = struct.unpack("16xH14x",get_if(i,SIOCGIFFLAGS))[0]
- if ifflags & IFF_UP:
- return i
- return LOOPBACK_NAME
-def attach_filter(s, filter):
- # XXX We generate the filter on the interface conf.iface
- # because tcpdump open the "any" interface and ppp interfaces
- # in cooked mode. As we use them in raw mode, the filter will not
- # work... one solution could be to use "any" interface and translate
- # the filter from cooked mode to raw mode
- # mode
- if not TCPDUMP:
- return
- try:
- f = os.popen("%s -i %s -ddd -s 1600 '%s'" % (conf.prog.tcpdump,conf.iface,filter))
- except OSError as msg:
- log_interactive.warning("Failed to execute tcpdump: (%s)")
- return
- lines = f.readlines()
- if f.close():
- raise Scapy_Exception("Filter parse error")
- nb = int(lines[0])
- bpf = b""
- for l in lines[1:]:
- bpf += struct.pack("HBBI",*[int(x) for x in l.split()])
-
- # XXX. Argl! We need to give the kernel a pointer on the BPF,
- # python object header seems to be 20 bytes. 36 bytes for x86 64bits arch.
- bpf_buf = ctypes.create_string_buffer(bpf)
- class BpfProgram(ctypes.Structure):
- _fields_ = [ ("bf_len", ctypes.c_int), ("bf_insn", ctypes.POINTER(type(bpf_buf))) ]
- #if scapy.arch.X86_64:
- # bpfh = struct.pack("HL", nb, id(bpf)+36)
- #else:
- # bpfh = struct.pack("HI", nb, id(bpf)+20)
- bpfh = BpfProgram(nb, ctypes.pointer(bpf_buf))
- s.setsockopt(SOL_SOCKET, SO_ATTACH_FILTER, bpfh)
-
-def set_promisc(s,iff,val=1):
- mreq = struct.pack("IHH8s", get_if_index(iff), PACKET_MR_PROMISC, 0, b"")
- if val:
- cmd = PACKET_ADD_MEMBERSHIP
- else:
- cmd = PACKET_DROP_MEMBERSHIP
- s.setsockopt(SOL_PACKET, cmd, mreq)
-
-
-
-def read_routes():
- try:
- f=open("/proc/net/route","rb")
- except IOError:
- warning("Can't open /proc/net/route !")
- return []
- routes = []
- s=socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
- ifreq = ioctl(s, SIOCGIFADDR,struct.pack("16s16x",LOOPBACK_NAME.encode('utf-8')))
- addrfamily = struct.unpack("h",ifreq[16:18])[0]
- if addrfamily == socket.AF_INET:
- ifreq2 = ioctl(s, SIOCGIFNETMASK,struct.pack("16s16x",LOOPBACK_NAME.encode('utf-8')))
- msk = socket.ntohl(struct.unpack("I",ifreq2[20:24])[0])
- dst = socket.ntohl(struct.unpack("I",ifreq[20:24])[0]) & msk
- ifaddr = scapy.utils.inet_ntoa(ifreq[20:24])
- routes.append((dst, msk, "0.0.0.0", LOOPBACK_NAME, ifaddr))
- else:
- warning("Interface lo: unkown address family (%i)"% addrfamily)
-
- for l in f.readlines()[1:]:
- iff,dst,gw,flags,x,x,x,msk,x,x,x = l.split()
- flags = int(flags,16)
- if flags & RTF_UP == 0:
- continue
- if flags & RTF_REJECT:
- continue
- try:
- ifreq = ioctl(s, SIOCGIFADDR,struct.pack("16s16x",iff))
- except IOError: # interface is present in routing tables but does not have any assigned IP
- ifaddr="0.0.0.0"
- else:
- addrfamily = struct.unpack("h",ifreq[16:18])[0]
- if addrfamily == socket.AF_INET:
- ifaddr = scapy.utils.inet_ntoa(ifreq[20:24])
- else:
- warning("Interface %s: unkown address family (%i)"%(iff, addrfamily))
- continue
- routes.append((socket.htonl(int(dst,16))&0xffffffff,
- socket.htonl(int(msk,16))&0xffffffff,
- scapy.utils.inet_ntoa(struct.pack("I",int(gw,16))),
- iff.decode('utf-8'), ifaddr))
-
- f.close()
- return routes
-
-############
-### IPv6 ###
-############
-
-def in6_getifaddr():
- """
- Returns a list of 3-tuples of the form (addr, scope, iface) where
- 'addr' is the address of scope 'scope' associated to the interface
- 'ifcace'.
-
- This is the list of all addresses of all interfaces available on
- the system.
- """
- ret = []
- try:
- f = open("/proc/net/if_inet6","rb")
- except IOError as err:
- return ret
- l = f.readlines()
- for i in l:
- # addr, index, plen, scope, flags, ifname
- tmp = i.split()
- addr = struct.unpack('4s4s4s4s4s4s4s4s', tmp[0])
- addr = scapy.utils6.in6_ptop(b':'.join(addr).decode('ascii'))
- ret.append((addr, int(tmp[3], 16), tmp[5].decode('ascii'))) # (addr, scope, iface)
- f.close()
- return ret
-
-def read_routes6():
- try:
- f = open("/proc/net/ipv6_route","r")
- except IOError as err:
- return []
- # 1. destination network
- # 2. destination prefix length
- # 3. source network displayed
- # 4. source prefix length
- # 5. next hop
- # 6. metric
- # 7. reference counter (?!?)
- # 8. use counter (?!?)
- # 9. flags
- # 10. device name
- routes = []
- def proc2r(p):
- ret = struct.unpack('4s4s4s4s4s4s4s4s', p.encode('ascii'))
- ret = b':'.join(ret)
- return scapy.utils6.in6_ptop(ret.decode('ascii'))
-
- lifaddr = in6_getifaddr()
- for l in f.readlines():
- d,dp,s,sp,nh,m,rc,us,fl,dev = l.split()
- fl = int(fl, 16)
-
- if fl & RTF_UP == 0:
- continue
- if fl & RTF_REJECT:
- continue
-
- d = proc2r(d) ; dp = int(dp, 16)
- s = proc2r(s) ; sp = int(sp, 16)
- nh = proc2r(nh)
-
- cset = [] # candidate set (possible source addresses)
- if dev == LOOPBACK_NAME:
- if d == '::':
- continue
- cset = ['::1']
- else:
- #devaddrs = filter(lambda x: x[2] == dev, lifaddr)
- devaddrs = [ x for x in lifaddr if x[2] == dev ]
- cset = scapy.utils6.construct_source_candidate_set(d, dp, devaddrs, LOOPBACK_NAME)
-
- if len(cset) != 0:
- routes.append((d, dp, nh, dev, cset))
- f.close()
- return routes
-
-
-
-
-def get_if(iff,cmd):
- s=socket.socket()
- ifreq = ioctl(s, cmd, struct.pack("16s16x",bytes(iff,'utf-8')))
- s.close()
- return ifreq
-
-
-def get_if_index(iff):
- return int(struct.unpack("I",get_if(iff, SIOCGIFINDEX)[16:20])[0])
-
-if os.uname()[4] == 'x86_64':
- def get_last_packet_timestamp(sock):
- ts = ioctl(sock, SIOCGSTAMP, "1234567890123456")
- s,us = struct.unpack("QQ",ts)
- return s+us/1000000.0
-else:
- def get_last_packet_timestamp(sock):
- ts = ioctl(sock, SIOCGSTAMP, "12345678")
- s,us = struct.unpack("II",ts)
- return s+us/1000000.0
-
-
-def _flush_fd(fd):
- if type(fd) is not int:
- fd = fd.fileno()
- while 1:
- r,w,e = select([fd],[],[],0)
- if r:
- os.read(fd,MTU)
- else:
- break
-
-
-
-
-
-class L3PacketSocket(SuperSocket):
- desc = "read/write packets at layer 3 using Linux PF_PACKET sockets"
- def __init__(self, type = ETH_P_ALL, filter=None, promisc=None, iface=None, nofilter=0):
- self.type = type
- self.ins = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(type))
- self.ins.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 0)
- if iface:
- self.ins.bind((iface, type))
- if not nofilter:
- if conf.except_filter:
- if filter:
- filter = "(%s) and not (%s)" % (filter, conf.except_filter)
- else:
- filter = "not (%s)" % conf.except_filter
- if filter is not None:
- attach_filter(self.ins, filter)
- _flush_fd(self.ins)
- self.ins.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 2**30)
- self.outs = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(type))
- self.outs.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 2**30)
- if promisc is None:
- promisc = conf.promisc
- self.promisc = promisc
- if self.promisc:
- if iface is None:
- self.iff = get_if_list()
- else:
- if iface.__class__ is list:
- self.iff = iface
- else:
- self.iff = [iface]
- for i in self.iff:
- set_promisc(self.ins, i)
- def close(self):
- if self.closed:
- return
- self.closed=1
- if self.promisc:
- for i in self.iff:
- set_promisc(self.ins, i, 0)
- SuperSocket.close(self)
- def recv(self, x=MTU):
- pkt, sa_ll = self.ins.recvfrom(x)
- if sa_ll[2] == socket.PACKET_OUTGOING:
- return None
- if sa_ll[3] in conf.l2types:
- cls = conf.l2types[sa_ll[3]]
- lvl = 2
- elif sa_ll[1] in conf.l3types:
- cls = conf.l3types[sa_ll[1]]
- lvl = 3
- else:
- cls = conf.default_l2
- warning("Unable to guess type (interface=%s protocol=%#x family=%i). Using %s" % (sa_ll[0],sa_ll[1],sa_ll[3],cls.name))
- lvl = 2
-
- try:
- pkt = cls(pkt)
- except KeyboardInterrupt:
- raise
- except:
- if conf.debug_dissector:
- raise
- pkt = conf.raw_layer(pkt)
- if lvl == 2:
- pkt = pkt.payload
-
- if pkt is not None:
- pkt.time = get_last_packet_timestamp(self.ins)
- return pkt
-
- def send(self, x):
- iff,a,gw = x.route()
- if iff is None:
- iff = conf.iface
- sdto = (iff, self.type)
- self.outs.bind(sdto)
- sn = self.outs.getsockname()
- ll = lambda x:x
- if type(x) in conf.l3types:
- sdto = (iff, conf.l3types[type(x)])
- if sn[3] in conf.l2types:
- ll = lambda x:conf.l2types[sn[3]]()/x
- try:
- sx = bytes(ll(x))
- x.sent_time = time.time()
- self.outs.sendto(sx, sdto)
- except OSError as msg:
- x.sent_time = time.time() # bad approximation
- if conf.auto_fragment and msg.errno == 90:
- for p in x.fragment():
- self.outs.sendto(bytes(ll(p)), sdto)
- else:
- raise
-
-
-
-class L2Socket(SuperSocket):
- desc = "read/write packets at layer 2 using Linux PF_PACKET sockets"
- def __init__(self, iface = None, type = ETH_P_ALL, filter=None, nofilter=0):
- if iface is None:
- iface = conf.iface
- self.ins = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(type))
- self.ins.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 0)
- if not nofilter:
- if conf.except_filter:
- if filter:
- filter = "(%s) and not (%s)" % (filter, conf.except_filter)
- else:
- filter = "not (%s)" % conf.except_filter
- if filter is not None:
- attach_filter(self.ins, filter)
- self.ins.bind((iface, type))
- _flush_fd(self.ins)
- self.ins.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 2**30)
- self.outs = self.ins
- self.outs.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 2**30)
- sa_ll = self.outs.getsockname()
- if sa_ll[3] in conf.l2types:
- self.LL = conf.l2types[sa_ll[3]]
- elif sa_ll[1] in conf.l3types:
- self.LL = conf.l3types[sa_ll[1]]
- else:
- self.LL = conf.default_l2
- warning("Unable to guess type (interface=%s protocol=%#x family=%i). Using %s" % (sa_ll[0],sa_ll[1],sa_ll[3],self.LL.name))
-
- def recv(self, x=MTU):
- pkt, sa_ll = self.ins.recvfrom(x)
- if sa_ll[2] == socket.PACKET_OUTGOING:
- return None
- try:
- q = self.LL(pkt)
- except KeyboardInterrupt:
- raise
- except:
- if conf.debug_dissector:
- raise
- q = conf.raw_layer(pkt)
- q.time = get_last_packet_timestamp(self.ins)
- return q
-
-
-class L2ListenSocket(SuperSocket):
- desc = "read packets at layer 2 using Linux PF_PACKET sockets"
- def __init__(self, iface = None, type = ETH_P_ALL, promisc=None, filter=None, nofilter=0):
- self.type = type
- self.outs = None
- self.ins = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(type))
- self.ins.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 0)
- if iface is not None:
- self.ins.bind((iface, type))
- if not nofilter:
- if conf.except_filter:
- if filter:
- filter = "(%s) and not (%s)" % (filter, conf.except_filter)
- else:
- filter = "not (%s)" % conf.except_filter
- if filter is not None:
- attach_filter(self.ins, filter)
- if promisc is None:
- promisc = conf.sniff_promisc
- self.promisc = promisc
- if iface is None:
- self.iff = get_if_list()
- else:
- if iface.__class__ is list:
- self.iff = iface
- else:
- self.iff = [iface]
- if self.promisc:
- for i in self.iff:
- set_promisc(self.ins, i)
- _flush_fd(self.ins)
- self.ins.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 2**30)
- def close(self):
- if self.promisc:
- for i in self.iff:
- set_promisc(self.ins, i, 0)
- SuperSocket.close(self)
-
- def recv(self, x=MTU):
- pkt, sa_ll = self.ins.recvfrom(x)
- if sa_ll[3] in conf.l2types :
- cls = conf.l2types[sa_ll[3]]
- elif sa_ll[1] in conf.l3types:
- cls = conf.l3types[sa_ll[1]]
- else:
- cls = conf.default_l2
- warning("Unable to guess type (interface=%s protocol=%#x family=%i). Using %s" % (sa_ll[0],sa_ll[1],sa_ll[3],cls.name))
-
- try:
- pkt = cls(pkt)
- except KeyboardInterrupt:
- raise
- except:
- if conf.debug_dissector:
- raise
- pkt = conf.raw_layer(pkt)
- pkt.time = get_last_packet_timestamp(self.ins)
- return pkt
-
- def send(self, x):
- raise Scapy_Exception("Can't send anything with L2ListenSocket")
-
-
-conf.L3socket = L3PacketSocket
-conf.L2socket = L2Socket
-conf.L2listen = L2ListenSocket
-
-conf.iface = get_working_if()
diff --git a/scripts/external_libs/scapy-python3-0.18/scapy/arch/pcapdnet.py b/scripts/external_libs/scapy-python3-0.18/scapy/arch/pcapdnet.py
deleted file mode 100644
index a2e8aa59..00000000
--- a/scripts/external_libs/scapy-python3-0.18/scapy/arch/pcapdnet.py
+++ /dev/null
@@ -1,565 +0,0 @@
-## This file is part of Scapy
-## See http://www.secdev.org/projects/scapy for more informations
-## Copyright (C) Philippe Biondi <phil@secdev.org>
-## This program is published under a GPLv2 license
-
-"""
-Packet sending and receiving with libdnet and libpcap/WinPcap.
-"""
-
-import time,struct,sys,socket
-if not sys.platform.startswith("win"):
- from fcntl import ioctl
-from scapy.data import *
-from scapy.config import conf
-from scapy.utils import warning
-from scapy.supersocket import SuperSocket
-from scapy.error import Scapy_Exception
-import scapy.arch
-
-if conf.use_dnet:
- try:
- from .cdnet import *
- except OSError as e:
- if conf.interactive:
- log_loading.error("Unable to import libdnet library: %s" % e)
- conf.use_dnet = False
- else:
- raise
-
-if conf.use_winpcapy:
- try:
- from .winpcapy import *
- def winpcapy_get_if_list():
- err = create_string_buffer(PCAP_ERRBUF_SIZE)
- devs = POINTER(pcap_if_t)()
- ret = []
- if pcap_findalldevs(byref(devs), err) < 0:
- return ret
- try:
- p = devs
- while p:
- ret.append(p.contents.name.decode('ascii'))
- p = p.contents.next
- return ret
- finally:
- pcap_freealldevs(devs)
-
- except OSError as e:
- if conf.interactive:
- log_loading.error("Unable to import libpcap library: %s" % e)
- conf.use_winpcapy = False
- else:
- raise
-
- # From BSD net/bpf.h
- #BIOCIMMEDIATE=0x80044270
- BIOCIMMEDIATE=-2147204496
-
- class PcapTimeoutElapsed(Scapy_Exception):
- pass
-
-if conf.use_netifaces:
- try:
- import netifaces
- except ImportError as e:
- log_loading.warning("Could not load module netifaces: %s" % e)
- conf.use_netifaces = False
-
-if conf.use_netifaces:
- def get_if_raw_hwaddr(iff):
- if iff == scapy.arch.LOOPBACK_NAME:
- return (772, '\x00'*6)
- try:
- s = netifaces.ifaddresses(iff)[netifaces.AF_LINK][0]['addr']
- return struct.pack('BBBBBB', *[ int(i, 16) for i in s.split(':') ])
- except:
- raise Scapy_Exception("Error in attempting to get hw address for interface [%s]" % iff)
- return l
- def get_if_raw_addr(ifname):
- try:
- s = netifaces.ifaddresses(ifname)[netifaces.AF_INET][0]['addr']
- return socket.inet_aton(s)
- except Exception as e:
- return None
- def get_if_list():
- #return [ i[1] for i in socket.if_nameindex() ]
- return netifaces.interfaces()
- def in6_getifaddr():
- """
- Returns a list of 3-tuples of the form (addr, scope, iface) where
- 'addr' is the address of scope 'scope' associated to the interface
- 'ifcace'.
-
- This is the list of all addresses of all interfaces available on
- the system.
- """
-
- ret = []
- interfaces = get_if_list()
- for i in interfaces:
- addrs = netifaces.ifaddresses(i)
- if netifaces.AF_INET6 not in addrs:
- continue
- for a in addrs[netifaces.AF_INET6]:
- addr = a['addr'].split('%')[0]
- scope = scapy.utils6.in6_getscope(addr)
- ret.append((addr, scope, i))
- return ret
-elif conf.use_winpcapy:
- def get_if_raw_hwaddr(iff):
- err = create_string_buffer(PCAP_ERRBUF_SIZE)
- devs = POINTER(pcap_if_t)()
- ret = b"\0\0\0\0\0\0"
- if pcap_findalldevs(byref(devs), err) < 0:
- return ret
- try:
- p = devs
- while p:
- if p.contents.name.endswith(iff.encode('ascii')):
- a = p.contents.addresses
- while a:
- if hasattr(socket, 'AF_LINK') and a.contents.addr.contents.sa_family == socket.AF_LINK:
- ap = a.contents.addr
- val = cast(ap, POINTER(sockaddr_dl))
- ret = bytes(val.contents.sdl_data[ val.contents.sdl_nlen : val.contents.sdl_nlen + val.contents.sdl_alen ])
- a = a.contents.next
- break
- p = p.contents.next
- return ret
- finally:
- pcap_freealldevs(devs)
- def get_if_raw_addr(iff):
- err = create_string_buffer(PCAP_ERRBUF_SIZE)
- devs = POINTER(pcap_if_t)()
- ret = b"\0\0\0\0"
- if pcap_findalldevs(byref(devs), err) < 0:
- return ret
- try:
- p = devs
- while p:
- if p.contents.name.endswith(iff.encode('ascii')):
- a = p.contents.addresses
- while a:
- if a.contents.addr.contents.sa_family == socket.AF_INET:
- ap = a.contents.addr
- val = cast(ap, POINTER(sockaddr_in))
- ret = bytes(val.contents.sin_addr[:4])
- a = a.contents.next
- break
- p = p.contents.next
- return ret
- finally:
- pcap_freealldevs(devs)
- get_if_list = winpcapy_get_if_list
- def in6_getifaddr():
- err = create_string_buffer(PCAP_ERRBUF_SIZE)
- devs = POINTER(pcap_if_t)()
- ret = []
- if pcap_findalldevs(byref(devs), err) < 0:
- return ret
- try:
- p = devs
- ret = []
- while p:
- a = p.contents.addresses
- while a:
- if a.contents.addr.contents.sa_family == socket.AF_INET6:
- ap = a.contents.addr
- val = cast(ap, POINTER(sockaddr_in6))
- addr = socket.inet_ntop(socket.AF_INET6, bytes(val.contents.sin6_addr[:]))
- scope = scapy.utils6.in6_getscope(addr)
- ret.append((addr, scope, p.contents.name.decode('ascii')))
- a = a.contents.next
- p = p.contents.next
- return ret
- finally:
- pcap_freealldevs(devs)
-
-elif conf.use_dnet:
- intf = dnet_intf()
- def get_if_raw_hwaddr(iff):
- return intf.get(iff)['link_addr']
- def get_if_raw_addr(iff):
- return intf.get(iff)['addr']
- def get_if_list():
- return intf.names
- def in6_getifaddr():
- ret = []
- for i in get_if_list():
- for a in intf.get(i)['addr6']:
- addr = socket.inet_ntop(socket.AF_INET6, a)
- scope = scapy.utils6.in6_getscope(addr)
- ret.append((addr, scope, i))
- return ret
-
-else:
- log_loading.warning("No known method to get ip and hw address for interfaces")
- def get_if_raw_hwaddr(iff):
- "dummy"
- return b"\0\0\0\0\0\0"
- def get_if_raw_addr(iff):
- "dummy"
- return b"\0\0\0\0"
- def get_if_list():
- "dummy"
- return []
- def in6_getifaddr():
- return []
-
-if conf.use_winpcapy:
- from ctypes import POINTER, byref, create_string_buffer
- class _PcapWrapper_pypcap:
- def __init__(self, device, snaplen, promisc, to_ms):
- self.errbuf = create_string_buffer(PCAP_ERRBUF_SIZE)
- self.iface = create_string_buffer(device.encode('ascii'))
- self.pcap = pcap_open_live(self.iface, snaplen, promisc, to_ms, self.errbuf)
- self.header = POINTER(pcap_pkthdr)()
- self.pkt_data = POINTER(c_ubyte)()
- self.bpf_program = bpf_program()
- def next(self):
- c = pcap_next_ex(self.pcap, byref(self.header), byref(self.pkt_data))
- if not c > 0:
- return
- ts = self.header.contents.ts.tv_sec
- #pkt = "".join([ chr(i) for i in self.pkt_data[:self.header.contents.len] ])
- pkt = bytes(self.pkt_data[:self.header.contents.len])
- return ts, pkt
- def datalink(self):
- return pcap_datalink(self.pcap)
- def fileno(self):
- if sys.platform.startswith("win"):
- error("Cannot get selectable PCAP fd on Windows")
- return 0
- return pcap_get_selectable_fd(self.pcap)
- def setfilter(self, f):
- filter_exp = create_string_buffer(f.encode('ascii'))
- if pcap_compile(self.pcap, byref(self.bpf_program), filter_exp, 0, -1) == -1:
- error("Could not compile filter expression %s" % f)
- return False
- else:
- if pcap_setfilter(self.pcap, byref(self.bpf_program)) == -1:
- error("Could not install filter %s" % f)
- return False
- return True
- def setnonblock(self, i):
- pcap_setnonblock(self.pcap, i, self.errbuf)
- def send(self, x):
- pcap_sendpacket(self.pcap, x, len(x))
- def close(self):
- pcap_close(self.pcap)
- open_pcap = lambda *args,**kargs: _PcapWrapper_pypcap(*args,**kargs)
- class PcapTimeoutElapsed(Scapy_Exception):
- pass
-
- class L2pcapListenSocket(SuperSocket):
- desc = "read packets at layer 2 using libpcap"
- def __init__(self, iface = None, type = ETH_P_ALL, promisc=None, filter=None):
- self.type = type
- self.outs = None
- self.iface = iface
- if iface is None:
- iface = conf.iface
- if promisc is None:
- promisc = conf.sniff_promisc
- self.promisc = promisc
- self.ins = open_pcap(iface, 1600, self.promisc, 100)
- try:
- ioctl(self.ins.fileno(),BIOCIMMEDIATE,struct.pack("I",1))
- except:
- pass
- if type == ETH_P_ALL: # Do not apply any filter if Ethernet type is given
- if conf.except_filter:
- if filter:
- filter = "(%s) and not (%s)" % (filter, conf.except_filter)
- else:
- filter = "not (%s)" % conf.except_filter
- if filter:
- self.ins.setfilter(filter)
-
- def close(self):
- self.ins.close()
-
- def recv(self, x=MTU):
- ll = self.ins.datalink()
- if ll in conf.l2types:
- cls = conf.l2types[ll]
- else:
- cls = conf.default_l2
- warning("Unable to guess datalink type (interface=%s linktype=%i). Using %s" % (self.iface, ll, cls.name))
-
- pkt = None
- while pkt is None:
- pkt = self.ins.next()
- if pkt is not None:
- ts,pkt = pkt
- if scapy.arch.WINDOWS and pkt is None:
- raise PcapTimeoutElapsed
-
- try:
- pkt = cls(pkt)
- except KeyboardInterrupt:
- raise
- except:
- if conf.debug_dissector:
- raise
- pkt = conf.raw_layer(pkt)
- pkt.time = ts
- return pkt
-
- def send(self, x):
- raise Scapy_Exception("Can't send anything with L2pcapListenSocket")
-
-
- conf.L2listen = L2pcapListenSocket
- class L2pcapSocket(SuperSocket):
- desc = "read/write packets at layer 2 using only libpcap"
- def __init__(self, iface = None, type = ETH_P_ALL, filter=None, nofilter=0):
- if iface is None:
- iface = conf.iface
- self.iface = iface
- self.ins = open_pcap(iface, 1600, 0, 100)
- try:
- ioctl(self.ins.fileno(),BIOCIMMEDIATE,struct.pack("I",1))
- except:
- pass
- if nofilter:
- if type != ETH_P_ALL: # PF_PACKET stuff. Need to emulate this for pcap
- filter = "ether proto %i" % type
- else:
- filter = None
- else:
- if conf.except_filter:
- if filter:
- filter = "(%s) and not (%s)" % (filter, conf.except_filter)
- else:
- filter = "not (%s)" % conf.except_filter
- if type != ETH_P_ALL: # PF_PACKET stuff. Need to emulate this for pcap
- if filter:
- filter = "(ether proto %i) and (%s)" % (type,filter)
- else:
- filter = "ether proto %i" % type
- if filter:
- self.ins.setfilter(filter)
- def send(self, x):
- sx = bytes(x)
- if hasattr(x, "sent_time"):
- x.sent_time = time.time()
- return self.ins.send(sx)
-
- def recv(self,x=MTU):
- ll = self.ins.datalink()
- if ll in conf.l2types:
- cls = conf.l2types[ll]
- else:
- cls = conf.default_l2
- warning("Unable to guess datalink type (interface=%s linktype=%i). Using %s" % (self.iface, ll, cls.name))
-
- pkt = self.ins.next()
- if pkt is not None:
- ts,pkt = pkt
- if pkt is None:
- return
-
- try:
- pkt = cls(pkt)
- except KeyboardInterrupt:
- raise
- except:
- if conf.debug_dissector:
- raise
- pkt = conf.raw_layer(pkt)
- pkt.time = ts
- return pkt
-
- def nonblock_recv(self):
- self.ins.setnonblock(1)
- p = self.recv(MTU)
- self.ins.setnonblock(0)
- return p
-
- def close(self):
- if hasattr(self, "ins"):
- self.ins.close()
- if hasattr(self, "outs"):
- self.outs.close()
-
- class L3pcapSocket(L2pcapSocket):
- #def __init__(self, iface = None, type = ETH_P_ALL, filter=None, nofilter=0):
- # L2pcapSocket.__init__(self, iface, type, filter, nofilter)
- def recv(self, x = MTU):
- r = L2pcapSocket.recv(self, x)
- if r:
- return r.payload
- else:
- return
- def send(self, x):
- cls = conf.l2types[1]
- sx = bytes(cls()/x)
- if hasattr(x, "sent_time"):
- x.sent_time = time.time()
- return self.ins.send(sx)
- conf.L2socket=L2pcapSocket
- conf.L3socket=L3pcapSocket
-
-if conf.use_winpcapy and conf.use_dnet:
- class L3dnetSocket(SuperSocket):
- desc = "read/write packets at layer 3 using libdnet and libpcap"
- def __init__(self, type = ETH_P_ALL, filter=None, promisc=None, iface=None, nofilter=0):
- self.iflist = {}
- self.intf = dnet_intf()
- if iface is None:
- iface = conf.iface
- self.iface = iface
- self.ins = open_pcap(iface, 1600, 0, 100)
- try:
- ioctl(self.ins.fileno(),BIOCIMMEDIATE,struct.pack("I",1))
- except:
- pass
- if nofilter:
- if type != ETH_P_ALL: # PF_PACKET stuff. Need to emulate this for pcap
- filter = "ether proto %i" % type
- else:
- filter = None
- else:
- if conf.except_filter:
- if filter:
- filter = "(%s) and not (%s)" % (filter, conf.except_filter)
- else:
- filter = "not (%s)" % conf.except_filter
- if type != ETH_P_ALL: # PF_PACKET stuff. Need to emulate this for pcap
- if filter:
- filter = "(ether proto %i) and (%s)" % (type,filter)
- else:
- filter = "ether proto %i" % type
- if filter:
- self.ins.setfilter(filter)
- def send(self, x):
- iff,a,gw = x.route()
- if iff is None:
- iff = conf.iface
- ifs,cls = self.iflist.get(iff,(None,None))
- if ifs is None:
- iftype = self.intf.get(iff)["type"]
- if iftype == INTF_TYPE_ETH:
- try:
- cls = conf.l2types[1]
- except KeyError:
- warning("Unable to find Ethernet class. Using nothing")
- ifs = dnet_eth(iff)
- else:
- ifs = dnet_ip()
- self.iflist[iff] = ifs,cls
- if cls is None:
- #sx = str(x)
- sx = bytes(x)
- else:
- sx = bytes(cls()/x)
- x.sent_time = time.time()
- ifs.send(sx)
- def recv(self,x=MTU):
- ll = self.ins.datalink()
- if ll in conf.l2types:
- cls = conf.l2types[ll]
- else:
- cls = conf.default_l2
- warning("Unable to guess datalink type (interface=%s linktype=%i). Using %s" % (self.iface, ll, cls.name))
-
- pkt = self.ins.next()
- if pkt is not None:
- ts,pkt = pkt
- if pkt is None:
- return
-
- try:
- pkt = cls(pkt)
- except KeyboardInterrupt:
- raise
- except:
- if conf.debug_dissector:
- raise
- pkt = conf.raw_layer(pkt)
- pkt.time = ts
- return pkt.payload
-
- def nonblock_recv(self):
- self.ins.setnonblock(1)
- p = self.recv()
- self.ins.setnonblock(0)
- return p
-
- def close(self):
- if hasattr(self, "ins"):
- self.ins.close()
- if hasattr(self, "outs"):
- self.outs.close()
-
- class L2dnetSocket(SuperSocket):
- desc = "read/write packets at layer 2 using libdnet and libpcap"
- def __init__(self, iface = None, type = ETH_P_ALL, filter=None, nofilter=0):
- if iface is None:
- iface = conf.iface
- self.iface = iface
- self.ins = open_pcap(iface, 1600, 0, 100)
- try:
- ioctl(self.ins.fileno(),BIOCIMMEDIATE,struct.pack("I",1))
- except:
- pass
- if nofilter:
- if type != ETH_P_ALL: # PF_PACKET stuff. Need to emulate this for pcap
- filter = "ether proto %i" % type
- else:
- filter = None
- else:
- if conf.except_filter:
- if filter:
- filter = "(%s) and not (%s)" % (filter, conf.except_filter)
- else:
- filter = "not (%s)" % conf.except_filter
- if type != ETH_P_ALL: # PF_PACKET stuff. Need to emulate this for pcap
- if filter:
- filter = "(ether proto %i) and (%s)" % (type,filter)
- else:
- filter = "ether proto %i" % type
- if filter:
- self.ins.setfilter(filter)
- self.outs = dnet_eth(iface)
- def recv(self,x=MTU):
- ll = self.ins.datalink()
- if ll in conf.l2types:
- cls = conf.l2types[ll]
- else:
- cls = conf.default_l2
- warning("Unable to guess datalink type (interface=%s linktype=%i). Using %s" % (self.iface, ll, cls.name))
-
- pkt = self.ins.next()
- if pkt is not None:
- ts,pkt = pkt
- if pkt is None:
- return
-
- try:
- pkt = cls(pkt)
- except KeyboardInterrupt:
- raise
- except:
- if conf.debug_dissector:
- raise
- pkt = conf.raw_layer(pkt)
- pkt.time = ts
- return pkt
-
- def nonblock_recv(self):
- self.ins.setnonblock(1)
- p = self.recv(MTU)
- self.ins.setnonblock(0)
- return p
-
- def close(self):
- if hasattr(self, "ins"):
- self.ins.close()
- if hasattr(self, "outs"):
- self.outs.close()
-
- conf.L3socket=L3dnetSocket
- conf.L2socket=L2dnetSocket
diff --git a/scripts/external_libs/scapy-python3-0.18/scapy/arch/solaris.py b/scripts/external_libs/scapy-python3-0.18/scapy/arch/solaris.py
deleted file mode 100644
index 3117076a..00000000
--- a/scripts/external_libs/scapy-python3-0.18/scapy/arch/solaris.py
+++ /dev/null
@@ -1,16 +0,0 @@
-## This file is part of Scapy
-## See http://www.secdev.org/projects/scapy for more informations
-## Copyright (C) Philippe Biondi <phil@secdev.org>
-## This program is published under a GPLv2 license
-
-"""
-Customization for the Solaris operation system.
-"""
-
-# IPPROTO_GRE is missing on Solaris
-import socket
-socket.IPPROTO_GRE = 47
-
-LOOPBACK_NAME="lo0"
-
-from unix import *
diff --git a/scripts/external_libs/scapy-python3-0.18/scapy/arch/unix.py b/scripts/external_libs/scapy-python3-0.18/scapy/arch/unix.py
deleted file mode 100644
index 43e694b5..00000000
--- a/scripts/external_libs/scapy-python3-0.18/scapy/arch/unix.py
+++ /dev/null
@@ -1,168 +0,0 @@
-## This file is part of Scapy
-## See http://www.secdev.org/projects/scapy for more informations
-## Copyright (C) Philippe Biondi <phil@secdev.org>
-## This program is published under a GPLv2 license
-
-"""
-Common customizations for all Unix-like operating systems other than Linux
-"""
-
-import sys,os,struct,socket,time
-from subprocess import check_output
-from fcntl import ioctl
-from scapy.error import warning
-import scapy.config
-import scapy.utils
-import scapy.utils6
-import scapy.arch
-
-scapy.config.conf.use_winpcapy = True
-scapy.config.conf.use_netifaces = True
-scapy.config.conf.use_dnet = True
-from .pcapdnet import *
-
-
-
-##################
-## Routes stuff ##
-##################
-
-
-def read_routes():
- if scapy.arch.SOLARIS:
- f=check_output(["netstat", "-rvn"], universal_newlines = True) # -f inet
- elif scapy.arch.FREEBSD:
- f=check_output(["netstat", "-rnW"], universal_newlines = True) # -W to handle long interface names
- else:
- f=check_output(["netstat", "-rn"], universal_newlines = True) # -f inet
- ok = False
- routes = []
- pending_if = []
- for l in f.split('\n'):
- l = l.strip()
- if l.find("----") >= 0: # a separation line
- continue
- if not ok:
- if_index = [ l.split().index(i) for i in ['Iface', 'Netif', 'Interface', 'Device'] if i in l.split()]
- if if_index:
- ok = True
- if_index = if_index[0]
- continue
- if not l:
- break
- if scapy.arch.SOLARIS:
- lspl = l.split()
- if len(lspl) == 10:
- dest,mask,gw,netif,mxfrg,rtt,ref,flg = lspl[:8]
- else: # missing interface
- dest,mask,gw,mxfrg,rtt,ref,flg = lspl[:7]
- netif=None
- else:
- rt = l.split()
- dest,gw,flg = rt[:3]
- netif = rt[if_index]
- if flg.find("Lc") >= 0:
- continue
- if dest == "default":
- dest = 0
- netmask = 0
- else:
- if scapy.arch.SOLARIS:
- netmask = scapy.utils.atol(mask)
- elif "/" in dest:
- dest,netmask = dest.split("/")
- netmask = scapy.utils.itom(int(netmask))
- else:
- netmask = scapy.utils.itom((dest.count(".") + 1) * 8)
- dest += ".0"*(3-dest.count("."))
- dest = scapy.utils.atol(dest)
- if not "G" in flg:
- gw = '0.0.0.0'
- if netif is not None:
- ifaddr = scapy.arch.get_if_addr(netif)
- routes.append((dest,netmask,gw,netif,ifaddr))
- else:
- pending_if.append((dest,netmask,gw))
-
- # On Solaris, netstat does not provide output interfaces for some routes
- # We need to parse completely the routing table to route their gw and
- # know their output interface
- for dest,netmask,gw in pending_if:
- gw_l = scapy.utils.atol(gw)
- max_rtmask,gw_if,gw_if_addr, = 0,None,None
- for rtdst,rtmask,_,rtif,rtaddr in routes[:]:
- if gw_l & rtmask == rtdst:
- if rtmask >= max_rtmask:
- max_rtmask = rtmask
- gw_if = rtif
- gw_if_addr = rtaddr
- if gw_if:
- routes.append((dest,netmask,gw,gw_if,gw_if_addr))
- else:
- warning("Did not find output interface to reach gateway %s" % gw)
-
- return routes
-
-############
-### IPv6 ###
-############
-
-def read_routes6():
- f = os.popen("netstat -rn -f inet6")
- ok = False
- mtu_present = False
- prio_present = False
- routes = []
- lifaddr = in6_getifaddr()
- for l in f.readlines():
- if not l:
- break
- l = l.strip()
- if not ok:
- if l.find("Destination") >= 0:
- ok = 1
- mtu_present = l.find("Mtu") >= 0
- prio_present = l.find("Prio") >= 0
- continue
- # gv 12/12/06: under debugging
- if scapy.arch.NETBSD or scapy.arch.OPENBSD:
- lspl = l.split()
- d,nh,fl = lspl[:3]
- dev = lspl[5+mtu_present+prio_present]
- expire = None
- else: # FREEBSD or DARWIN
- d,nh,fl,dev = l.split()[:4]
- if [ x for x in lifaddr if x[2] == dev] == []:
- continue
- if 'L' in fl: # drop MAC addresses
- continue
-
- if 'link' in nh:
- nh = '::'
-
- cset = [] # candidate set (possible source addresses)
- dp = 128
- if d == 'default':
- d = '::'
- dp = 0
- if '/' in d:
- d,dp = d.split("/")
- dp = int(dp)
- if '%' in d:
- d,dev = d.split('%')
- if '%' in nh:
- nh,dev = nh.split('%')
- if scapy.arch.LOOPBACK_NAME in dev:
- if d == '::' and dp == 96: #Do not use ::/96 deprecated IPV4 mapping address
- continue
- cset = ['::1']
- nh = '::'
- else:
- devaddrs = [ x for x in lifaddr if x[2] == dev ]
- cset = scapy.utils6.construct_source_candidate_set(d, dp, devaddrs, scapy.arch.LOOPBACK_NAME)
-
- if len(cset) != 0:
- routes.append((d, dp, nh, dev, cset))
-
- f.close()
- return routes
diff --git a/scripts/external_libs/scapy-python3-0.18/scapy/arch/windows/__init__.py b/scripts/external_libs/scapy-python3-0.18/scapy/arch/windows/__init__.py
deleted file mode 100644
index 3bd1ade3..00000000
--- a/scripts/external_libs/scapy-python3-0.18/scapy/arch/windows/__init__.py
+++ /dev/null
@@ -1,501 +0,0 @@
-## This file is part of Scapy
-## See http://www.secdev.org/projects/scapy for more informations
-## Copyright (C) Philippe Biondi <phil@secdev.org>
-## This program is published under a GPLv2 license
-
-"""
-Customizations needed to support Microsoft Windows.
-"""
-
-import os,re,sys,socket,time, itertools
-import subprocess as sp
-from glob import glob
-from scapy.config import conf,ConfClass
-from scapy.error import Scapy_Exception,log_loading,log_runtime
-from scapy.utils import atol, itom, inet_aton, inet_ntoa, PcapReader
-from scapy.base_classes import Gen, Net, SetGen
-import scapy.plist as plist
-from scapy.sendrecv import debug, srp1
-from scapy.layers.l2 import Ether, ARP
-from scapy.data import MTU, ETHER_BROADCAST, ETH_P_ARP
-
-conf.use_winpcapy = True
-from scapy.arch import pcapdnet
-from scapy.arch.pcapdnet import *
-
-LOOPBACK_NAME="lo0"
-WINDOWS = True
-
-
-def _where(filename, dirs=[], env="PATH"):
- """Find file in current dir or system path"""
- if not isinstance(dirs, list):
- dirs = [dirs]
- if glob(filename):
- return filename
- paths = [os.curdir] + os.environ[env].split(os.path.pathsep) + dirs
- for path in paths:
- for match in glob(os.path.join(path, filename)):
- if match:
- return os.path.normpath(match)
- raise IOError("File not found: %s" % filename)
-
-def win_find_exe(filename, installsubdir=None, env="ProgramFiles"):
- """Find executable in current dir, system path or given ProgramFiles subdir"""
- for fn in [filename, filename+".exe"]:
- try:
- if installsubdir is None:
- path = _where(fn)
- else:
- path = _where(fn, dirs=[os.path.join(os.environ[env], installsubdir)])
- except IOError:
- path = filename
- else:
- break
- return path
-
-
-class WinProgPath(ConfClass):
- _default = "<System default>"
- # We try some magic to find the appropriate executables
- pdfreader = win_find_exe("AcroRd32")
- psreader = win_find_exe("gsview32.exe", "Ghostgum/gsview")
- dot = win_find_exe("dot", "ATT/Graphviz/bin")
- tcpdump = win_find_exe("windump")
- tcpreplay = win_find_exe("tcpreplay")
- display = _default
- hexedit = win_find_exe("hexer")
- wireshark = win_find_exe("wireshark", "wireshark")
-
-conf.prog = WinProgPath()
-
-class PcapNameNotFoundError(Scapy_Exception):
- pass
-
-def get_windows_if_list():
- ps = sp.Popen(['powershell', 'Get-NetAdapter', '|', 'select Name, InterfaceIndex, InterfaceDescription, InterfaceGuid, MacAddress', '|', 'fl'], stdout = sp.PIPE)
- stdout, stdin = ps.communicate(timeout = 10)
- current_interface = None
- interface_list = []
- for i in stdout.split(b'\r\n'):
- if not i.strip():
- continue
- if i.find(b':')<0:
- continue
- name, value = [ j.strip() for j in i.split(b':') ]
- if name == b'Name':
- if current_interface:
- interface_list.append(current_interface)
- current_interface = {}
- current_interface['name'] = value.decode('ascii')
- elif name == b'InterfaceIndex':
- current_interface['win_index'] = int(value)
- elif name == b'InterfaceDescription':
- current_interface['description'] = value.decode('ascii')
- elif name == b'InterfaceGuid':
- current_interface['guid'] = value.decode('ascii')
- elif name == b'MacAddress':
- current_interface['mac'] = ':'.join([ j.decode('ascii') for j in value.split(b'-')])
- if current_interface:
- interface_list.append(current_interface)
- return interface_list
-
-class NetworkInterface(object):
- """A network interface of your local host"""
-
- def __init__(self, data=None):
- self.name = None
- self.ip = None
- self.mac = None
- self.pcap_name = None
- self.description = None
- self.data = data
- if data is not None:
- self.update(data)
-
- def update(self, data):
- """Update info about network interface according to given dnet dictionary"""
- self.name = data["name"]
- self.description = data['description']
- self.win_index = data['win_index']
- # Other attributes are optional
- self._update_pcapdata()
- try:
- self.ip = socket.inet_ntoa(get_if_raw_addr(data['guid']))
- except (KeyError, AttributeError, NameError):
- pass
- try:
- self.mac = data['mac']
- except KeyError:
- pass
-
- def _update_pcapdata(self):
- for i in winpcapy_get_if_list():
- if i.endswith(self.data['guid']):
- self.pcap_name = i
- return
-
- raise PcapNameNotFoundError
-
- def __repr__(self):
- return "<%s: %s %s %s pcap_name=%s description=%s>" % (self.__class__.__name__,
- self.name, self.ip, self.mac, self.pcap_name, self.description)
-
-from collections import UserDict
-
-class NetworkInterfaceDict(UserDict):
- """Store information about network interfaces and convert between names"""
- def load_from_powershell(self):
- for i in get_windows_if_list():
- try:
- interface = NetworkInterface(i)
- self.data[interface.name] = interface
- except (KeyError, PcapNameNotFoundError):
- pass
- if len(self.data) == 0:
- log_loading.warning("No match between your pcap and windows network interfaces found. "
- "You probably won't be able to send packets. "
- "Deactivating unneeded interfaces and restarting Scapy might help."
- "Check your winpcap and powershell installation, and access rights.")
-
- def pcap_name(self, devname):
- """Return pcap device name for given Windows device name."""
-
- try:
- pcap_name = self.data[devname].pcap_name
- except KeyError:
- raise ValueError("Unknown network interface %r" % devname)
- else:
- return pcap_name
-
- def devname(self, pcap_name):
- """Return Windows device name for given pcap device name."""
-
- for devname, iface in self.items():
- if iface.pcap_name == pcap_name:
- return iface.name
- raise ValueError("Unknown pypcap network interface %r" % pcap_name)
-
- def devname_from_index(self, if_index):
- """Return interface name from interface index"""
- for devname, iface in self.items():
- if iface.win_index == if_index:
- return iface.name
- raise ValueError("Unknown network interface index %r" % if_index)
-
- def show(self, resolve_mac=True):
- """Print list of available network interfaces in human readable form"""
-
- print("%s %s %s %s" % ("INDEX".ljust(5), "IFACE".ljust(35), "IP".ljust(15), "MAC"))
- for iface_name in sorted(self.data.keys()):
- dev = self.data[iface_name]
- mac = dev.mac
- if resolve_mac:
- mac = conf.manufdb._resolve_MAC(mac)
- print("%s %s %s %s" % (str(dev.win_index).ljust(5), str(dev.name).ljust(35), str(dev.ip).ljust(15), mac) )
-
-ifaces = NetworkInterfaceDict()
-ifaces.load_from_powershell()
-
-def pcap_name(devname):
- """Return pypcap device name for given libdnet/Scapy device name"""
- try:
- pcap_name = ifaces.pcap_name(devname)
- except ValueError:
- # pcap.pcap() will choose a sensible default for sniffing if iface=None
- pcap_name = None
- return pcap_name
-
-def devname(pcap_name):
- """Return libdnet/Scapy device name for given pypcap device name"""
- return ifaces.devname(pcap_name)
-
-def devname_from_index(if_index):
- """Return Windows adapter name for given Windows interface index"""
- return ifaces.devname_from_index(if_index)
-
-def show_interfaces(resolve_mac=True):
- """Print list of available network interfaces"""
- return ifaces.show(resolve_mac)
-
-_orig_open_pcap = pcapdnet.open_pcap
-pcapdnet.open_pcap = lambda iface,*args,**kargs: _orig_open_pcap(pcap_name(iface),*args,**kargs)
-
-_orig_get_if_raw_hwaddr = pcapdnet.get_if_raw_hwaddr
-pcapdnet.get_if_raw_hwaddr = lambda iface,*args,**kargs: [ int(i, 16) for i in ifaces[iface].mac.split(':') ]
-get_if_raw_hwaddr = pcapdnet.get_if_raw_hwaddr
-
-def read_routes():
- routes = []
- if_index = '(\d+)'
- dest = '(\d+\.\d+\.\d+\.\d+)/(\d+)'
- next_hop = '(\d+\.\d+\.\d+\.\d+)'
- metric_pattern = "(\d+)"
- delim = "\s+" # The columns are separated by whitespace
- netstat_line = delim.join([if_index, dest, next_hop, metric_pattern])
- pattern = re.compile(netstat_line)
- ps = sp.Popen(['powershell', 'Get-NetRoute', '-AddressFamily IPV4', '|', 'select ifIndex, DestinationPrefix, NextHop, RouteMetric'], stdout = sp.PIPE)
- stdout, stdin = ps.communicate(timeout = 10)
- for l in stdout.split(b'\r\n'):
- match = re.search(pattern,l.decode('utf-8'))
- if match:
- try:
- iface = devname_from_index(int(match.group(1)))
- addr = ifaces[iface].ip
- except:
- continue
- dest = atol(match.group(2))
- mask = itom(int(match.group(3)))
- gw = match.group(4)
- # try:
- # intf = pcapdnet.dnet.intf().get_dst(pcapdnet.dnet.addr(type=2, addrtxt=dest))
- # except OSError:
- # log_loading.warning("Building Scapy's routing table: Couldn't get outgoing interface for destination %s" % dest)
- # continue
- routes.append((dest, mask, gw, iface, addr))
- return routes
-
-def read_routes6():
- return []
-
-try:
- __IPYTHON__
-except NameError:
- try:
- import readline
- console = readline.GetOutputFile()
- except (ImportError, AttributeError):
- log_loading.info("Could not get readline console. Will not interpret ANSI color codes.")
- else:
- conf.readfunc = readline.rl.readline
- orig_stdout = sys.stdout
- sys.stdout = console
-
-def sndrcv(pks, pkt, timeout = 2, inter = 0, verbose=None, chainCC=0, retry=0, multi=0):
- if not isinstance(pkt, Gen):
- pkt = SetGen(pkt)
-
- if verbose is None:
- verbose = conf.verb
- debug.recv = plist.PacketList([],"Unanswered")
- debug.sent = plist.PacketList([],"Sent")
- debug.match = plist.SndRcvList([])
- nbrecv=0
- ans = []
- # do it here to fix random fields, so that parent and child have the same
- all_stimuli = tobesent = [p for p in pkt]
- notans = len(tobesent)
-
- hsent={}
- for i in tobesent:
- h = i.hashret()
- if h in hsent:
- hsent[h].append(i)
- else:
- hsent[h] = [i]
- if retry < 0:
- retry = -retry
- autostop=retry
- else:
- autostop=0
-
-
- while retry >= 0:
- found=0
-
- if timeout < 0:
- timeout = None
-
- pid=1
- try:
- if WINDOWS or pid == 0:
- try:
- try:
- i = 0
- if verbose:
- print("Begin emission:")
- for p in tobesent:
- pks.send(p)
- i += 1
- time.sleep(inter)
- if verbose:
- print("Finished to send %i packets." % i)
- except SystemExit:
- pass
- except KeyboardInterrupt:
- pass
- except:
- log_runtime.exception("--- Error sending packets")
- log_runtime.info("--- Error sending packets")
- finally:
- try:
- sent_times = [p.sent_time for p in all_stimuli if p.sent_time]
- except:
- pass
- if WINDOWS or pid > 0:
- # Timeout starts after last packet is sent (as in Unix version)
- if timeout:
- stoptime = time.time()+timeout
- else:
- stoptime = 0
- remaintime = None
- # inmask = [pks.ins.fd]
- try:
- try:
- while 1:
- if stoptime:
- remaintime = stoptime-time.time()
- if remaintime <= 0:
- break
- r = pks.recv(MTU)
- if r is None:
- continue
- ok = 0
- h = r.hashret()
- if h in hsent:
- hlst = hsent[h]
- for i in range(len(hlst)):
- if r.answers(hlst[i]):
- ans.append((hlst[i],r))
- if verbose > 1:
- os.write(1, b"*")
- ok = 1
- if not multi:
- del(hlst[i])
- notans -= 1;
- else:
- if not hasattr(hlst[i], '_answered'):
- notans -= 1;
- hlst[i]._answered = 1;
- break
- if notans == 0 and not multi:
- break
- if not ok:
- if verbose > 1:
- os.write(1, b".")
- nbrecv += 1
- if conf.debug_match:
- debug.recv.append(r)
- except KeyboardInterrupt:
- if chainCC:
- raise
- finally:
- if WINDOWS:
- for p,t in zip(all_stimuli, sent_times):
- p.sent_time = t
- finally:
- pass
-
- # remain = reduce(list.__add__, hsent.values(), [])
- remain = list(itertools.chain(*[ i for i in hsent.values() ]))
-
- if multi:
- #remain = filter(lambda p: not hasattr(p, '_answered'), remain);
- remain = [ p for p in remain if not hasattr(p, '_answered')]
-
- if autostop and len(remain) > 0 and len(remain) != len(tobesent):
- retry = autostop
-
- tobesent = remain
- if len(tobesent) == 0:
- break
- retry -= 1
-
- if conf.debug_match:
- debug.sent=plist.PacketList(remain[:],"Sent")
- debug.match=plist.SndRcvList(ans[:])
-
- #clean the ans list to delete the field _answered
- if (multi):
- for s,r in ans:
- if hasattr(s, '_answered'):
- del(s._answered)
-
- if verbose:
- print("\nReceived %i packets, got %i answers, remaining %i packets" % (nbrecv+len(ans), len(ans), notans))
- return plist.SndRcvList(ans),plist.PacketList(remain,"Unanswered")
-
-
-import scapy.sendrecv
-scapy.sendrecv.sndrcv = sndrcv
-
-def sniff(count=0, store=1, offline=None, prn = None, lfilter=None, L2socket=None, timeout=None, *arg, **karg):
- """Sniff packets
-sniff([count=0,] [prn=None,] [store=1,] [offline=None,] [lfilter=None,] + L2ListenSocket args) -> list of packets
-Select interface to sniff by setting conf.iface. Use show_interfaces() to see interface names.
- count: number of packets to capture. 0 means infinity
- store: wether to store sniffed packets or discard them
- prn: function to apply to each packet. If something is returned,
- it is displayed. Ex:
- ex: prn = lambda x: x.summary()
-lfilter: python function applied to each packet to determine
- if further action may be done
- ex: lfilter = lambda x: x.haslayer(Padding)
-offline: pcap file to read packets from, instead of sniffing them
-timeout: stop sniffing after a given time (default: None)
-L2socket: use the provided L2socket
- """
- c = 0
-
- if offline is None:
- log_runtime.info('Sniffing on %s' % conf.iface)
- if L2socket is None:
- L2socket = conf.L2listen
- s = L2socket(type=ETH_P_ALL, *arg, **karg)
- else:
- s = PcapReader(offline)
-
- lst = []
- if timeout is not None:
- stoptime = time.time()+timeout
- remain = None
- while 1:
- try:
- if timeout is not None:
- remain = stoptime-time.time()
- if remain <= 0:
- break
-
- try:
- p = s.recv(MTU)
- except PcapTimeoutElapsed:
- continue
- if p is None:
- break
- if lfilter and not lfilter(p):
- continue
- if store:
- lst.append(p)
- c += 1
- if prn:
- r = prn(p)
- if r is not None:
- print(r)
- if count > 0 and c >= count:
- break
- except KeyboardInterrupt:
- break
- s.close()
- return plist.PacketList(lst,"Sniffed")
-
-import scapy.sendrecv
-scapy.sendrecv.sniff = sniff
-
-# def get_if_list():
-# print('windows if_list')
-# return sorted(ifaces.keys())
-
-def get_working_if():
- try:
- if 'Ethernet' in ifaces and ifaces['Ethernet'].ip != '0.0.0.0':
- return 'Ethernet'
- elif 'Wi-Fi' in ifaces and ifaces['Wi-Fi'].ip != '0.0.0.0':
- return 'Wi-Fi'
- elif len(ifaces) > 0:
- return ifaces[list(ifaces.keys())[0]]
- else:
- return LOOPBACK_NAME
- except:
- return LOOPBACK_NAME
-
-conf.iface = get_working_if()
diff --git a/scripts/external_libs/scapy-python3-0.18/scapy/arch/winpcapy.py b/scripts/external_libs/scapy-python3-0.18/scapy/arch/winpcapy.py
deleted file mode 100644
index fc452a02..00000000
--- a/scripts/external_libs/scapy-python3-0.18/scapy/arch/winpcapy.py
+++ /dev/null
@@ -1,739 +0,0 @@
-#-------------------------------------------------------------------------------
-# Name: winpcapy.py
-#
-# Author: Massimo Ciani
-#
-# Created: 01/09/2009
-# Copyright: (c) Massimo Ciani 2009
-#
-#-------------------------------------------------------------------------------
-
-
-from ctypes import *
-from ctypes.util import find_library
-import sys
-
-WIN32=False
-HAVE_REMOTE=False
-
-
-if sys.platform.startswith('win'):
- WIN32=True
- HAVE_REMOTE=True
-
-if WIN32:
- SOCKET = c_uint
- _lib=CDLL('wpcap.dll')
-else:
- SOCKET = c_int
- _lib_name = find_library('pcap')
- if not _lib_name:
- raise OSError("Cannot fine libpcap.so library")
- _lib=CDLL(_lib_name)
-
-
-
-##
-## misc
-##
-u_short = c_ushort
-bpf_int32 = c_int
-u_int = c_int
-bpf_u_int32 = u_int
-pcap = c_void_p
-pcap_dumper = c_void_p
-u_char = c_ubyte
-FILE = c_void_p
-STRING = c_char_p
-
-class bpf_insn(Structure):
- _fields_=[("code",c_ushort),
- ("jt",c_ubyte),
- ("jf",c_ubyte),
- ("k",bpf_u_int32)]
-
-class bpf_program(Structure):
- pass
-bpf_program._fields_ = [('bf_len', u_int),
- ('bf_insns', POINTER(bpf_insn))]
-
-class bpf_version(Structure):
- _fields_=[("bv_major",c_ushort),
- ("bv_minor",c_ushort)]
-
-
-class timeval(Structure):
- pass
-timeval._fields_ = [('tv_sec', c_long),
- ('tv_usec', c_long)]
-
-## sockaddr is used by pcap_addr.
-## For exapmle if sa_family==socket.AF_INET then we need cast
-## with sockaddr_in
-if WIN32:
- class sockaddr(Structure):
- _fields_ = [("sa_family", c_ushort),
- ("sa_data",c_ubyte * 14)]
-
- class sockaddr_in(Structure):
- _fields_ = [("sin_family", c_ushort),
- ("sin_port", c_uint16),
- ("sin_addr", 4 * c_ubyte)]
-
- class sockaddr_in6(Structure):
- _fields_ = [("sin6_family", c_ushort),
- ("sin6_port", c_uint16),
- ("sin6_flowinfo", c_uint32),
- ("sin6_addr", 16 * c_ubyte),
- ("sin6_scope", c_uint32)]
-else:
- class sockaddr(Structure):
- _fields_ = [("sa_len", c_ubyte),
- ("sa_family",c_ubyte),
- ("sa_data",c_ubyte * 14)]
-
- class sockaddr_in(Structure):
- _fields_ = [("sin_len", c_ubyte),
- ("sin_family", c_ubyte),
- ("sin_port", c_uint16),
- ("sin_addr", 4 * c_ubyte),
- ("sin_zero", 8 * c_char)]
-
- class sockaddr_in6(Structure):
- _fields_ = [("sin6_len", c_ubyte),
- ("sin6_family", c_ubyte),
- ("sin6_port", c_uint16),
- ("sin6_flowinfo", c_uint32),
- ("sin6_addr", 16 * c_ubyte),
- ("sin6_scope", c_uint32)]
-
- class sockaddr_dl(Structure):
- _fields_ = [("sdl_len", c_ubyte),
- ("sdl_family", c_ubyte),
- ("sdl_index", c_ushort),
- ("sdl_type", c_ubyte),
- ("sdl_nlen", c_ubyte),
- ("sdl_alen", c_ubyte),
- ("sdl_slen", c_ubyte),
- ("sdl_data", 46 * c_ubyte)]
-##
-## END misc
-##
-
-##
-## Data Structures
-##
-
-## struct pcap_file_header
-## Header of a libpcap dump file.
-class pcap_file_header(Structure):
- _fields_ = [('magic', bpf_u_int32),
- ('version_major', u_short),
- ('version_minor', u_short),
- ('thiszone', bpf_int32),
- ('sigfigs', bpf_u_int32),
- ('snaplen', bpf_u_int32),
- ('linktype', bpf_u_int32)]
-
-## struct pcap_pkthdr
-## Header of a packet in the dump file.
-class pcap_pkthdr(Structure):
- _fields_ = [('ts', timeval),
- ('caplen', bpf_u_int32),
- ('len', bpf_u_int32)]
-
-## struct pcap_stat
-## Structure that keeps statistical values on an interface.
-class pcap_stat(Structure):
- pass
-### _fields_ list in Structure is final.
-### We need a temp list
-_tmpList=[]
-_tmpList.append(("ps_recv",c_uint))
-_tmpList.append(("ps_drop",c_uint))
-_tmpList.append(("ps_ifdrop",c_uint))
-if HAVE_REMOTE:
- _tmpList.append(("ps_capt",c_uint))
- _tmpList.append(("ps_sent",c_uint))
- _tmpList.append(("ps_netdrop",c_uint))
-pcap_stat._fields_=_tmpList
-
-## struct pcap_addr
-## Representation of an interface address, used by pcap_findalldevs().
-class pcap_addr(Structure):
- pass
-pcap_addr._fields_ = [('next', POINTER(pcap_addr)),
- ('addr', POINTER(sockaddr)),
- ('netmask', POINTER(sockaddr)),
- ('broadaddr', POINTER(sockaddr)),
- ('dstaddr', POINTER(sockaddr))]
-
-## struct pcap_if
-## Item in a list of interfaces, used by pcap_findalldevs().
-class pcap_if(Structure):
- pass
-pcap_if._fields_ = [('next', POINTER(pcap_if)),
- ('name', STRING),
- ('description', STRING),
- ('addresses', POINTER(pcap_addr)),
- ('flags', bpf_u_int32)]
-
-##
-## END Data Structures
-##
-
-##
-## Defines
-##
-
-##define PCAP_VERSION_MAJOR 2
-# Major libpcap dump file version.
-PCAP_VERSION_MAJOR = 2
-##define PCAP_VERSION_MINOR 4
-# Minor libpcap dump file version.
-PCAP_VERSION_MINOR = 4
-##define PCAP_ERRBUF_SIZE 256
-# Size to use when allocating the buffer that contains the libpcap errors.
-PCAP_ERRBUF_SIZE = 256
-##define PCAP_IF_LOOPBACK 0x00000001
-# interface is loopback
-PCAP_IF_LOOPBACK = 1
-##define MODE_CAPT 0
-# Capture mode, to be used when calling pcap_setmode().
-MODE_CAPT = 0
-##define MODE_STAT 1
-# Statistical mode, to be used when calling pcap_setmode().
-MODE_STAT = 1
-
-##
-## END Defines
-##
-
-##
-## Typedefs
-##
-
-#typedef int bpf_int32 (already defined)
-# 32-bit integer
-#typedef u_int bpf_u_int32 (already defined)
-# 32-bit unsigned integer
-#typedef struct pcap pcap_t
-# Descriptor of an open capture instance. This structure is opaque to the user, that handles its content through the functions provided by wpcap.dll.
-pcap_t = pcap
-#typedef struct pcap_dumper pcap_dumper_t
-# libpcap savefile descriptor.
-pcap_dumper_t = pcap_dumper
-#typedef struct pcap_if pcap_if_t
-# Item in a list of interfaces, see pcap_if.
-pcap_if_t = pcap_if
-#typedef struct pcap_addr pcap_addr_t
-# Representation of an interface address, see pcap_addr.
-pcap_addr_t = pcap_addr
-
-##
-## END Typedefs
-##
-
-
-
-
-
-# values for enumeration 'pcap_direction_t'
-#pcap_direction_t = c_int # enum
-
-##
-## Unix-compatible Functions
-## These functions are part of the libpcap library, and therefore work both on Windows and on Linux.
-##
-
-#typedef void(* pcap_handler )(u_char *user, const struct pcap_pkthdr *pkt_header, const u_char *pkt_data)
-# Prototype of the callback function that receives the packets.
-## This one is defined from programmer
-pcap_handler=CFUNCTYPE(None,POINTER(c_ubyte),POINTER(pcap_pkthdr),POINTER(c_ubyte))
-
-#pcap_t * pcap_open_live (const char *device, int snaplen, int promisc, int to_ms, char *ebuf)
-# Open a live capture from the network.
-pcap_open_live = _lib.pcap_open_live
-pcap_open_live.restype = POINTER(pcap_t)
-pcap_open_live.argtypes = [STRING, c_int, c_int, c_int, STRING]
-
-#pcap_t * pcap_open_dead (int linktype, int snaplen)
-# Create a pcap_t structure without starting a capture.
-pcap_open_dead = _lib.pcap_open_dead
-pcap_open_dead.restype = POINTER(pcap_t)
-pcap_open_dead.argtypes = [c_int, c_int]
-
-#pcap_t * pcap_open_offline (const char *fname, char *errbuf)
-# Open a savefile in the tcpdump/libpcap format to read packets.
-pcap_open_offline = _lib.pcap_open_offline
-pcap_open_offline.restype = POINTER(pcap_t)
-pcap_open_offline.argtypes = [STRING, STRING]
-
-#pcap_dumper_t * pcap_dump_open (pcap_t *p, const char *fname)
-# Open a file to write packets.
-pcap_dump_open = _lib.pcap_dump_open
-pcap_dump_open.restype = POINTER(pcap_dumper_t)
-pcap_dump_open.argtypes = [POINTER(pcap_t), STRING]
-
-#int pcap_setnonblock (pcap_t *p, int nonblock, char *errbuf)
-# Switch between blocking and nonblocking mode.
-pcap_setnonblock = _lib.pcap_setnonblock
-pcap_setnonblock.restype = c_int
-pcap_setnonblock.argtypes = [POINTER(pcap_t), c_int, STRING]
-
-#int pcap_getnonblock (pcap_t *p, char *errbuf)
-# Get the "non-blocking" state of an interface.
-pcap_getnonblock = _lib.pcap_getnonblock
-pcap_getnonblock.restype = c_int
-pcap_getnonblock.argtypes = [POINTER(pcap_t), STRING]
-
-#int pcap_findalldevs (pcap_if_t **alldevsp, char *errbuf)
-# Construct a list of network devices that can be opened with pcap_open_live().
-pcap_findalldevs = _lib.pcap_findalldevs
-pcap_findalldevs.restype = c_int
-pcap_findalldevs.argtypes = [POINTER(POINTER(pcap_if_t)), STRING]
-
-#void pcap_freealldevs (pcap_if_t *alldevsp)
-# Free an interface list returned by pcap_findalldevs().
-pcap_freealldevs = _lib.pcap_freealldevs
-pcap_freealldevs.restype = None
-pcap_freealldevs.argtypes = [POINTER(pcap_if_t)]
-
-#char * pcap_lookupdev (char *errbuf)
-# Return the first valid device in the system.
-pcap_lookupdev = _lib.pcap_lookupdev
-pcap_lookupdev.restype = STRING
-pcap_lookupdev.argtypes = [STRING]
-
-#int pcap_lookupnet (const char *device, bpf_u_int32 *netp, bpf_u_int32 *maskp, char *errbuf)
-# Return the subnet and netmask of an interface.
-pcap_lookupnet = _lib.pcap_lookupnet
-pcap_lookupnet.restype = c_int
-pcap_lookupnet.argtypes = [STRING, POINTER(bpf_u_int32), POINTER(bpf_u_int32), STRING]
-
-#int pcap_dispatch (pcap_t *p, int cnt, pcap_handler callback, u_char *user)
-# Collect a group of packets.
-pcap_dispatch = _lib.pcap_dispatch
-pcap_dispatch.restype = c_int
-pcap_dispatch.argtypes = [POINTER(pcap_t), c_int, pcap_handler, POINTER(u_char)]
-
-#int pcap_loop (pcap_t *p, int cnt, pcap_handler callback, u_char *user)
-# Collect a group of packets.
-pcap_loop = _lib.pcap_loop
-pcap_loop.restype = c_int
-pcap_loop.argtypes = [POINTER(pcap_t), c_int, pcap_handler, POINTER(u_char)]
-
-#u_char * pcap_next (pcap_t *p, struct pcap_pkthdr *h)
-# Return the next available packet.
-pcap_next = _lib.pcap_next
-pcap_next.restype = POINTER(u_char)
-pcap_next.argtypes = [POINTER(pcap_t), POINTER(pcap_pkthdr)]
-
-#int pcap_next_ex (pcap_t *p, struct pcap_pkthdr **pkt_header, const u_char **pkt_data)
-# Read a packet from an interface or from an offline capture.
-pcap_next_ex = _lib.pcap_next_ex
-pcap_next_ex.restype = c_int
-pcap_next_ex.argtypes = [POINTER(pcap_t), POINTER(POINTER(pcap_pkthdr)), POINTER(POINTER(u_char))]
-
-#void pcap_breakloop (pcap_t *)
-# set a flag that will force pcap_dispatch() or pcap_loop() to return rather than looping.
-pcap_breakloop = _lib.pcap_breakloop
-pcap_breakloop.restype = None
-pcap_breakloop.argtypes = [POINTER(pcap_t)]
-
-#int pcap_sendpacket (pcap_t *p, u_char *buf, int size)
-# Send a raw packet.
-pcap_sendpacket = _lib.pcap_sendpacket
-pcap_sendpacket.restype = c_int
-#pcap_sendpacket.argtypes = [POINTER(pcap_t), POINTER(u_char), c_int]
-pcap_sendpacket.argtypes = [POINTER(pcap_t), c_void_p, c_int]
-
-#void pcap_dump (u_char *user, const struct pcap_pkthdr *h, const u_char *sp)
-# Save a packet to disk.
-pcap_dump = _lib.pcap_dump
-pcap_dump.restype = None
-pcap_dump.argtypes = [POINTER(pcap_dumper_t), POINTER(pcap_pkthdr), POINTER(u_char)]
-
-#long pcap_dump_ftell (pcap_dumper_t *)
-# Return the file position for a "savefile".
-pcap_dump_ftell = _lib.pcap_dump_ftell
-pcap_dump_ftell.restype = c_long
-pcap_dump_ftell.argtypes = [POINTER(pcap_dumper_t)]
-
-#int pcap_compile (pcap_t *p, struct bpf_program *fp, char *str, int optimize, bpf_u_int32 netmask)
-# Compile a packet filter, converting an high level filtering expression (see Filtering expression syntax) in a program that can be interpreted by the kernel-level filtering engine.
-pcap_compile = _lib.pcap_compile
-pcap_compile.restype = c_int
-pcap_compile.argtypes = [POINTER(pcap_t), POINTER(bpf_program), STRING, c_int, bpf_u_int32]
-
-#int pcap_compile_nopcap (int snaplen_arg, int linktype_arg, struct bpf_program *program, char *buf, int optimize, bpf_u_int32 mask)
-# Compile a packet filter without the need of opening an adapter. This function converts an high level filtering expression (see Filtering expression syntax) in a program that can be interpreted by the kernel-level filtering engine.
-pcap_compile_nopcap = _lib.pcap_compile_nopcap
-pcap_compile_nopcap.restype = c_int
-pcap_compile_nopcap.argtypes = [c_int, c_int, POINTER(bpf_program), STRING, c_int, bpf_u_int32]
-
-#int pcap_setfilter (pcap_t *p, struct bpf_program *fp)
-# Associate a filter to a capture.
-pcap_setfilter = _lib.pcap_setfilter
-pcap_setfilter.restype = c_int
-pcap_setfilter.argtypes = [POINTER(pcap_t), POINTER(bpf_program)]
-
-#void pcap_freecode (struct bpf_program *fp)
-# Free a filter.
-pcap_freecode = _lib.pcap_freecode
-pcap_freecode.restype = None
-pcap_freecode.argtypes = [POINTER(bpf_program)]
-
-#int pcap_datalink (pcap_t *p)
-# Return the link layer of an adapter.
-pcap_datalink = _lib.pcap_datalink
-pcap_datalink.restype = c_int
-pcap_datalink.argtypes = [POINTER(pcap_t)]
-
-#int pcap_list_datalinks (pcap_t *p, int **dlt_buf)
-# list datalinks
-pcap_list_datalinks = _lib.pcap_list_datalinks
-pcap_list_datalinks.restype = c_int
-#pcap_list_datalinks.argtypes = [POINTER(pcap_t), POINTER(POINTER(c_int))]
-
-#int pcap_set_datalink (pcap_t *p, int dlt)
-# Set the current data link type of the pcap descriptor to the type specified by dlt. -1 is returned on failure.
-pcap_set_datalink = _lib.pcap_set_datalink
-pcap_set_datalink.restype = c_int
-pcap_set_datalink.argtypes = [POINTER(pcap_t), c_int]
-
-#int pcap_datalink_name_to_val (const char *name)
-# Translates a data link type name, which is a DLT_ name with the DLT_ removed, to the corresponding data link type value. The translation is case-insensitive. -1 is returned on failure.
-pcap_datalink_name_to_val = _lib.pcap_datalink_name_to_val
-pcap_datalink_name_to_val.restype = c_int
-pcap_datalink_name_to_val.argtypes = [STRING]
-
-#const char * pcap_datalink_val_to_name (int dlt)
-# Translates a data link type value to the corresponding data link type name. NULL is returned on failure.
-pcap_datalink_val_to_name = _lib.pcap_datalink_val_to_name
-pcap_datalink_val_to_name.restype = STRING
-pcap_datalink_val_to_name.argtypes = [c_int]
-
-#const char * pcap_datalink_val_to_description (int dlt)
-# Translates a data link type value to a short description of that data link type. NULL is returned on failure.
-pcap_datalink_val_to_description = _lib.pcap_datalink_val_to_description
-pcap_datalink_val_to_description.restype = STRING
-pcap_datalink_val_to_description.argtypes = [c_int]
-
-#int pcap_snapshot (pcap_t *p)
-# Return the dimension of the packet portion (in bytes) that is delivered to the application.
-pcap_snapshot = _lib.pcap_snapshot
-pcap_snapshot.restype = c_int
-pcap_snapshot.argtypes = [POINTER(pcap_t)]
-
-#int pcap_is_swapped (pcap_t *p)
-# returns true if the current savefile uses a different byte order than the current system.
-pcap_is_swapped = _lib.pcap_is_swapped
-pcap_is_swapped.restype = c_int
-pcap_is_swapped.argtypes = [POINTER(pcap_t)]
-
-#int pcap_major_version (pcap_t *p)
-# return the major version number of the pcap library used to write the savefile.
-pcap_major_version = _lib.pcap_major_version
-pcap_major_version.restype = c_int
-pcap_major_version.argtypes = [POINTER(pcap_t)]
-
-#int pcap_minor_version (pcap_t *p)
-# return the minor version number of the pcap library used to write the savefile.
-pcap_minor_version = _lib.pcap_minor_version
-pcap_minor_version.restype = c_int
-pcap_minor_version.argtypes = [POINTER(pcap_t)]
-
-#FILE * pcap_file (pcap_t *p)
-# Return the standard stream of an offline capture.
-pcap_file=_lib.pcap_file
-pcap_file.restype = FILE
-pcap_file.argtypes = [POINTER(pcap_t)]
-
-#int pcap_stats (pcap_t *p, struct pcap_stat *ps)
-# Return statistics on current capture.
-pcap_stats = _lib.pcap_stats
-pcap_stats.restype = c_int
-pcap_stats.argtypes = [POINTER(pcap_t), POINTER(pcap_stat)]
-
-#void pcap_perror (pcap_t *p, char *prefix)
-# print the text of the last pcap library error on stderr, prefixed by prefix.
-pcap_perror = _lib.pcap_perror
-pcap_perror.restype = None
-pcap_perror.argtypes = [POINTER(pcap_t), STRING]
-
-#char * pcap_geterr (pcap_t *p)
-# return the error text pertaining to the last pcap library error.
-pcap_geterr = _lib.pcap_geterr
-pcap_geterr.restype = STRING
-pcap_geterr.argtypes = [POINTER(pcap_t)]
-
-#char * pcap_strerror (int error)
-# Provided in case strerror() isn't available.
-pcap_strerror = _lib.pcap_strerror
-pcap_strerror.restype = STRING
-pcap_strerror.argtypes = [c_int]
-
-#const char * pcap_lib_version (void)
-# Returns a pointer to a string giving information about the version of the libpcap library being used; note that it contains more information than just a version number.
-pcap_lib_version = _lib.pcap_lib_version
-pcap_lib_version.restype = STRING
-pcap_lib_version.argtypes = []
-
-#void pcap_close (pcap_t *p)
-# close the files associated with p and deallocates resources.
-pcap_close = _lib.pcap_close
-pcap_close.restype = None
-pcap_close.argtypes = [POINTER(pcap_t)]
-
-#FILE * pcap_dump_file (pcap_dumper_t *p)
-# return the standard I/O stream of the 'savefile' opened by pcap_dump_open().
-pcap_dump_file=_lib.pcap_dump_file
-pcap_dump_file.restype=FILE
-pcap_dump_file.argtypes= [POINTER(pcap_dumper_t)]
-
-#int pcap_dump_flush (pcap_dumper_t *p)
-# Flushes the output buffer to the ``savefile,'' so that any packets written with pcap_dump() but not yet written to the ``savefile'' will be written. -1 is returned on error, 0 on success.
-pcap_dump_flush = _lib.pcap_dump_flush
-pcap_dump_flush.restype = c_int
-pcap_dump_flush.argtypes = [POINTER(pcap_dumper_t)]
-
-#void pcap_dump_close (pcap_dumper_t *p)
-# Closes a savefile.
-pcap_dump_close = _lib.pcap_dump_close
-pcap_dump_close.restype = None
-pcap_dump_close.argtypes = [POINTER(pcap_dumper_t)]
-
-if not WIN32:
-
- pcap_get_selectable_fd = _lib.pcap_get_selectable_fd
- pcap_get_selectable_fd.restype = c_int
- pcap_get_selectable_fd.argtypes = [POINTER(pcap_t)]
-
-###########################################
-## Windows-specific Extensions
-## The functions in this section extend libpcap to offer advanced functionalities
-## (like remote packet capture, packet buffer size variation or high-precision packet injection).
-## Howerver, at the moment they can be used only in Windows.
-###########################################
-if WIN32:
- HANDLE = c_void_p
-
- ##############
- ## Identifiers related to the new source syntax
- ##############
- #define PCAP_SRC_FILE 2
- #define PCAP_SRC_IFLOCAL 3
- #define PCAP_SRC_IFREMOTE 4
- #Internal representation of the type of source in use (file, remote/local interface).
- PCAP_SRC_FILE = 2
- PCAP_SRC_IFLOCAL = 3
- PCAP_SRC_IFREMOTE = 4
-
- ##############
- ## Strings related to the new source syntax
- ##############
- #define PCAP_SRC_FILE_STRING "file://"
- #define PCAP_SRC_IF_STRING "rpcap://"
- #String that will be used to determine the type of source in use (file, remote/local interface).
- PCAP_SRC_FILE_STRING="file://"
- PCAP_SRC_IF_STRING="rpcap://"
-
- ##############
- ## Flags defined in the pcap_open() function
- ##############
- # define PCAP_OPENFLAG_PROMISCUOUS 1
- # Defines if the adapter has to go in promiscuous mode.
- PCAP_OPENFLAG_PROMISCUOUS=1
- # define PCAP_OPENFLAG_DATATX_UDP 2
- # Defines if the data trasfer (in case of a remote capture) has to be done with UDP protocol.
- PCAP_OPENFLAG_DATATX_UDP=2
- # define PCAP_OPENFLAG_NOCAPTURE_RPCAP 4
- PCAP_OPENFLAG_NOCAPTURE_RPCAP=4
- # Defines if the remote probe will capture its own generated traffic.
- # define PCAP_OPENFLAG_NOCAPTURE_LOCAL 8
- PCAP_OPENFLAG_NOCAPTURE_LOCAL = 8
- # define PCAP_OPENFLAG_MAX_RESPONSIVENESS 16
- # This flag configures the adapter for maximum responsiveness.
- PCAP_OPENFLAG_MAX_RESPONSIVENESS=16
-
- ##############
- ## Sampling methods defined in the pcap_setsampling() function
- ##############
- # define PCAP_SAMP_NOSAMP 0
- # No sampling has to be done on the current capture.
- PCAP_SAMP_NOSAMP=0
- # define PCAP_SAMP_1_EVERY_N 1
- # It defines that only 1 out of N packets must be returned to the user.
- PCAP_SAMP_1_EVERY_N=1
- #define PCAP_SAMP_FIRST_AFTER_N_MS 2
- # It defines that we have to return 1 packet every N milliseconds.
- PCAP_SAMP_FIRST_AFTER_N_MS=2
-
- ##############
- ## Authentication methods supported by the RPCAP protocol
- ##############
- # define RPCAP_RMTAUTH_NULL 0
- # It defines the NULL authentication.
- RPCAP_RMTAUTH_NULL=0
- # define RPCAP_RMTAUTH_PWD 1
- # It defines the username/password authentication.
- RPCAP_RMTAUTH_PWD=1
-
-
- ##############
- ## Remote struct and defines
- ##############
- # define PCAP_BUF_SIZE 1024
- # Defines the maximum buffer size in which address, port, interface names are kept.
- PCAP_BUF_SIZE = 1024
- # define RPCAP_HOSTLIST_SIZE 1024
- # Maximum lenght of an host name (needed for the RPCAP active mode).
- RPCAP_HOSTLIST_SIZE = 1024
-
- class pcap_send_queue(Structure):
- _fields_=[("maxlen",c_uint),
- ("len",c_uint),
- ("buffer",c_char_p)]
-
- ## struct pcap_rmtauth
- ## This structure keeps the information needed to autheticate the user on a remote machine
- class pcap_rmtauth(Structure):
- _fields_=[("type",c_int),
- ("username",c_char_p),
- ("password",c_char_p)]
-
- ## struct pcap_samp
- ## This structure defines the information related to sampling
- class pcap_samp(Structure):
- _fields_=[("method",c_int),
- ("value",c_int)]
-
- #PAirpcapHandle pcap_get_airpcap_handle (pcap_t *p)
- # Returns the AirPcap handler associated with an adapter. This handler can be used to change the wireless-related settings of the CACE Technologies AirPcap wireless capture adapters.
-
- #bool pcap_offline_filter (struct bpf_program *prog, const struct pcap_pkthdr *header, const u_char *pkt_data)
- # Returns if a given filter applies to an offline packet.
- pcap_offline_filter = _lib.pcap_offline_filter
- pcap_offline_filter.restype = c_bool
- pcap_offline_filter.argtypes = [POINTER(bpf_program),POINTER(pcap_pkthdr),POINTER(u_char)]
-
- #int pcap_live_dump (pcap_t *p, char *filename, int maxsize, int maxpacks)
- # Save a capture to file.
- pcap_live_dump = _lib.pcap_live_dump
- pcap_live_dump.restype = c_int
- pcap_live_dump.argtypes = [POINTER(pcap_t), POINTER(c_char), c_int,c_int]
-
- #int pcap_live_dump_ended (pcap_t *p, int sync)
- # Return the status of the kernel dump process, i.e. tells if one of the limits defined with pcap_live_dump() has been reached.
- pcap_live_dump_ended = _lib.pcap_live_dump_ended
- pcap_live_dump_ended.restype = c_int
- pcap_live_dump_ended.argtypes = [POINTER(pcap_t), c_int]
-
- #struct pcap_stat * pcap_stats_ex (pcap_t *p, int *pcap_stat_size)
- # Return statistics on current capture.
- pcap_stats_ex = _lib.pcap_stats_ex
- pcap_stats_ex.restype = POINTER(pcap_stat)
- pcap_stats_ex.argtypes = [POINTER(pcap_t), POINTER(c_int)]
-
- #int pcap_setbuff (pcap_t *p, int dim)
- # Set the size of the kernel buffer associated with an adapter.
- pcap_setbuff = _lib.pcap_setbuff
- pcap_setbuff.restype = c_int
- pcap_setbuff.argtypes = [POINTER(pcap_t), c_int]
-
- #int pcap_setmode (pcap_t *p, int mode)
- # Set the working mode of the interface p to mode.
- pcap_setmode = _lib.pcap_setmode
- pcap_setmode.restype = c_int
- pcap_setmode.argtypes = [POINTER(pcap_t), c_int]
-
- #int pcap_setmintocopy (pcap_t *p, int size)
- # Set the minumum amount of data received by the kernel in a single call.
- pcap_setmintocopy = _lib.pcap_setmintocopy
- pcap_setmintocopy.restype = c_int
- pcap_setmintocopy.argtype = [POINTER(pcap_t), c_int]
-
- #HANDLE pcap_getevent (pcap_t *p)
- # Return the handle of the event associated with the interface p.
- pcap_getevent = _lib.pcap_getevent
- pcap_getevent.restype = HANDLE
- pcap_getevent.argtypes = [POINTER(pcap_t)]
-
- #pcap_send_queue * pcap_sendqueue_alloc (u_int memsize)
- # Allocate a send queue.
- pcap_sendqueue_alloc = _lib.pcap_sendqueue_alloc
- pcap_sendqueue_alloc.restype = POINTER(pcap_send_queue)
- pcap_sendqueue_alloc.argtypes = [c_uint]
-
- #void pcap_sendqueue_destroy (pcap_send_queue *queue)
- # Destroy a send queue.
- pcap_sendqueue_destroy = _lib.pcap_sendqueue_destroy
- pcap_sendqueue_destroy.restype = None
- pcap_sendqueue_destroy.argtypes = [POINTER(pcap_send_queue)]
-
- #int pcap_sendqueue_queue (pcap_send_queue *queue, const struct pcap_pkthdr *pkt_header, const u_char *pkt_data)
- # Add a packet to a send queue.
- pcap_sendqueue_queue = _lib.pcap_sendqueue_queue
- pcap_sendqueue_queue.restype = c_int
- pcap_sendqueue_queue.argtypes = [POINTER(pcap_send_queue), POINTER(pcap_pkthdr), POINTER(u_char)]
-
- #u_int pcap_sendqueue_transmit (pcap_t *p, pcap_send_queue *queue, int sync)
- # Send a queue of raw packets to the network.
- pcap_sendqueue_transmit = _lib.pcap_sendqueue_transmit
- pcap_sendqueue_transmit.retype = u_int
- pcap_sendqueue_transmit.argtypes = [POINTER(pcap_t), POINTER(pcap_send_queue), c_int]
-
- #int pcap_findalldevs_ex (char *source, struct pcap_rmtauth *auth, pcap_if_t **alldevs, char *errbuf)
- # Create a list of network devices that can be opened with pcap_open().
- pcap_findalldevs_ex = _lib.pcap_findalldevs_ex
- pcap_findalldevs_ex.retype = c_int
- pcap_findalldevs_ex.argtypes = [STRING, POINTER(pcap_rmtauth), POINTER(POINTER(pcap_if_t)), STRING]
-
- #int pcap_createsrcstr (char *source, int type, const char *host, const char *port, const char *name, char *errbuf)
- # Accept a set of strings (host name, port, ...), and it returns the complete source string according to the new format (e.g. 'rpcap://1.2.3.4/eth0').
- pcap_createsrcstr = _lib.pcap_createsrcstr
- pcap_createsrcstr.restype = c_int
- pcap_createsrcstr.argtypes = [STRING, c_int, STRING, STRING, STRING, STRING]
-
- #int pcap_parsesrcstr (const char *source, int *type, char *host, char *port, char *name, char *errbuf)
- # Parse the source string and returns the pieces in which the source can be split.
- pcap_parsesrcstr = _lib.pcap_parsesrcstr
- pcap_parsesrcstr.retype = c_int
- pcap_parsesrcstr.argtypes = [STRING, POINTER(c_int), STRING, STRING, STRING, STRING]
-
- #pcap_t * pcap_open (const char *source, int snaplen, int flags, int read_timeout, struct pcap_rmtauth *auth, char *errbuf)
- # Open a generic source in order to capture / send (WinPcap only) traffic.
- pcap_open = _lib.pcap_open
- pcap_open.restype = POINTER(pcap_t)
- pcap_open.argtypes = [STRING, c_int, c_int, c_int, POINTER(pcap_rmtauth), STRING]
-
- #struct pcap_samp * pcap_setsampling (pcap_t *p)
- # Define a sampling method for packet capture.
- pcap_setsampling = _lib.pcap_setsampling
- pcap_setsampling.restype = POINTER(pcap_samp)
- pcap_setsampling.argtypes = [POINTER(pcap_t)]
-
- #SOCKET pcap_remoteact_accept (const char *address, const char *port, const char *hostlist, char *connectinghost, struct pcap_rmtauth *auth, char *errbuf)
- # Block until a network connection is accepted (active mode only).
- pcap_remoteact_accept = _lib.pcap_remoteact_accept
- pcap_remoteact_accept.restype = SOCKET
- pcap_remoteact_accept.argtypes = [STRING, STRING, STRING, STRING, POINTER(pcap_rmtauth), STRING]
-
- #int pcap_remoteact_close (const char *host, char *errbuf)
- # Drop an active connection (active mode only).
- pcap_remoteact_close = _lib.pcap_remoteact_close
- pcap_remoteact_close.restypes = c_int
- pcap_remoteact_close.argtypes = [STRING, STRING]
-
- #void pcap_remoteact_cleanup ()
- # Clean the socket that is currently used in waiting active connections.
- pcap_remoteact_cleanup = _lib.pcap_remoteact_cleanup
- pcap_remoteact_cleanup.restypes = None
- pcap_remoteact_cleanup.argtypes = []
-
- #int pcap_remoteact_list (char *hostlist, char sep, int size, char *errbuf)
- # Return the hostname of the host that have an active connection with us (active mode only).
- pcap_remoteact_list = _lib.pcap_remoteact_list
- pcap_remoteact_list.restype = c_int
- pcap_remoteact_list.argtypes = [STRING, c_char, c_int, STRING]