diff options
author | 2016-03-21 16:03:47 +0200 | |
---|---|---|
committer | 2016-03-21 16:03:47 +0200 | |
commit | b89efa188810bf95a9d245e69e2961b5721c3b0f (patch) | |
tree | 454273ac6c4ae972ebb8a2c86b893296970b4fa9 /scripts/external_libs/scapy-2.3.1/scapy/arch | |
parent | f72c6df9d2e9998ae1f3529d729ab7930b35785a (diff) |
scapy python 2/3
Diffstat (limited to 'scripts/external_libs/scapy-2.3.1/scapy/arch')
7 files changed, 0 insertions, 1763 deletions
diff --git a/scripts/external_libs/scapy-2.3.1/scapy/arch/__init__.py b/scripts/external_libs/scapy-2.3.1/scapy/arch/__init__.py deleted file mode 100644 index 95f95ecf..00000000 --- a/scripts/external_libs/scapy-2.3.1/scapy/arch/__init__.py +++ /dev/null @@ -1,96 +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 Gnuplot - GNUPLOT=1 -except ImportError: - log_loading.info("Can't import python gnuplot wrapper . Won't be able to plot.") - GNUPLOT=0 - -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)) - - - -def get_if_addr(iff): - return socket.inet_ntoa(get_if_raw_addr(iff)) - -def get_if_hwaddr(iff): - addrfamily, mac = get_if_raw_hwaddr(iff) - if addrfamily in [ARPHDR_ETHER,ARPHDR_LOOPBACK]: - return str2mac(mac) - else: - raise Scapy_Exception("Unsupported address family (%i) for interface [%s]" % (addrfamily,iff)) - - -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') - - -# 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_pcap or scapy.config.conf.use_dnet: - from pcapdnet import * -elif OPENBSD or FREEBSD or NETBSD or DARWIN: - from bsd import * -elif SOLARIS: - from solaris import * -elif WINDOWS: - from windows import * - -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()) - 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-2.3.1/scapy/arch/bsd.py b/scripts/external_libs/scapy-2.3.1/scapy/arch/bsd.py deleted file mode 100644 index 1be7bd73..00000000 --- a/scripts/external_libs/scapy-2.3.1/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-2.3.1/scapy/arch/linux.py b/scripts/external_libs/scapy-2.3.1/scapy/arch/linux.py deleted file mode 100644 index 32f0a2d1..00000000 --- a/scripts/external_libs/scapy-2.3.1/scapy/arch/linux.py +++ /dev/null @@ -1,521 +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. -""" - -from __future__ import with_statement -import sys,os,struct,socket,time -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 - - - -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)) - -def get_if_raw_addr(iff): - try: - return get_if(iff, SIOCGIFADDR)[20:24] - except IOError: - return "\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()) - 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,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 = "" - for l in lines[1:]: - bpf += struct.pack("HBBI",*map(long,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. - if scapy.arch.X86_64: - bpfh = struct.pack("HL", nb, id(bpf)+36) - else: - bpfh = struct.pack("HI", nb, id(bpf)+20) - 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, "") - 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","r") - 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)) - addrfamily = struct.unpack("h",ifreq[16:18])[0] - if addrfamily == socket.AF_INET: - ifreq2 = ioctl(s, SIOCGIFNETMASK,struct.pack("16s16x",LOOPBACK_NAME)) - 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(long(dst,16))&0xffffffffL, - socket.htonl(long(msk,16))&0xffffffffL, - scapy.utils.inet_ntoa(struct.pack("I",long(gw,16))), - iff, 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","r") - except IOError, 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(':'.join(addr)) - ret.append((addr, int(tmp[3], 16), tmp[5])) # (addr, scope, iface) - return ret - -def read_routes6(): - try: - f = open("/proc/net/ipv6_route","r") - except IOError, 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) - ret = ':'.join(ret) - return scapy.utils6.in6_ptop(ret) - - 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) - 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",iff)) - 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) - _flush_fd(self.ins) - 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) - 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 = str(ll(x)) - x.sent_time = time.time() - self.outs.sendto(sx, sdto) - except socket.error,msg: - x.sent_time = time.time() # bad approximation - if conf.auto_fragment and msg[0] == 90: - for p in x.fragment(): - self.outs.sendto(str(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) - _flush_fd(self.ins) - 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)) - 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) - _flush_fd(self.ins) - 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) - 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-2.3.1/scapy/arch/pcapdnet.py b/scripts/external_libs/scapy-2.3.1/scapy/arch/pcapdnet.py deleted file mode 100644 index 94673d7d..00000000 --- a/scripts/external_libs/scapy-2.3.1/scapy/arch/pcapdnet.py +++ /dev/null @@ -1,368 +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 -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_pcap: - - - - try: - import pcap - except ImportError,e: - try: - import pcapy as pcap - except ImportError,e2: - if conf.interactive: - log_loading.error("Unable to import pcap module: %s/%s" % (e,e2)) - conf.use_pcap = False - else: - raise - if conf.use_pcap: - - # From BSD net/bpf.h - #BIOCIMMEDIATE=0x80044270 - BIOCIMMEDIATE=-2147204496 - - if hasattr(pcap,"pcap"): # python-pypcap - class _PcapWrapper_pypcap: - def __init__(self, device, snaplen, promisc, to_ms): - try: - self.pcap = pcap.pcap(device, snaplen, promisc, immediate=1, timeout_ms=to_ms) - except TypeError: - # Older pypcap versions do not support the timeout_ms argument - self.pcap = pcap.pcap(device, snaplen, promisc, immediate=1) - def __getattr__(self, attr): - return getattr(self.pcap, attr) - def __del__(self): - warning("__del__: don't know how to close the file descriptor. Bugs ahead ! Please report this bug.") - def next(self): - c = self.pcap.next() - if c is None: - return - ts, pkt = c - return ts, str(pkt) - open_pcap = lambda *args,**kargs: _PcapWrapper_pypcap(*args,**kargs) - elif hasattr(pcap,"pcapObject"): # python-libpcap - class _PcapWrapper_libpcap: - def __init__(self, *args, **kargs): - self.pcap = pcap.pcapObject() - self.pcap.open_live(*args, **kargs) - def setfilter(self, filter): - self.pcap.setfilter(filter, 0, 0) - def next(self): - c = self.pcap.next() - if c is None: - return - l,pkt,ts = c - return ts,pkt - def __getattr__(self, attr): - return getattr(self.pcap, attr) - def __del__(self): - fd = self.pcap.fileno() - os.close(fd) - open_pcap = lambda *args,**kargs: _PcapWrapper_libpcap(*args,**kargs) - elif hasattr(pcap,"open_live"): # python-pcapy - class _PcapWrapper_pcapy: - def __init__(self, *args, **kargs): - self.pcap = pcap.open_live(*args, **kargs) - def next(self): - try: - c = self.pcap.next() - except pcap.PcapError: - return None - else: - h,p = c - s,us = h.getts() - return (s+0.000001*us), p - def fileno(self): - warning("fileno: pcapy API does not permit to get capure file descriptor. Bugs ahead! Press Enter to trigger packet reading") - return 0 - def __getattr__(self, attr): - return getattr(self.pcap, attr) - def __del__(self): - warning("__del__: don't know how to close the file descriptor. Bugs ahead ! Please report this bug.") - open_pcap = lambda *args,**kargs: _PcapWrapper_pcapy(*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): - del(self.ins) - - 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 - - - - -if conf.use_dnet: - try: - import dnet - except ImportError,e: - if conf.interactive: - log_loading.error("Unable to import dnet module: %s" % e) - conf.use_dnet = False - def get_if_raw_hwaddr(iff): - "dummy" - return (0,"\0\0\0\0\0\0") - def get_if_raw_addr(iff): - "dummy" - return "\0\0\0\0" - def get_if_list(): - "dummy" - return [] - else: - raise - else: - def get_if_raw_hwaddr(iff): - if iff == scapy.arch.LOOPBACK_NAME: - return (772, '\x00'*6) - try: - l = dnet.intf().get(iff) - l = l["link_addr"] - except: - raise Scapy_Exception("Error in attempting to get hw address for interface [%s]" % iff) - return l.type,l.data - def get_if_raw_addr(ifname): - i = dnet.intf() - return i.get(ifname)["addr"].data - def get_if_list(): - return [i.get("name", None) for i in dnet.intf()] - - -if conf.use_pcap 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 == dnet.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) - else: - sx = str(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"): - del(self.ins) - if hasattr(self, "outs"): - del(self.outs) - - 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"): - del(self.ins) - if hasattr(self, "outs"): - del(self.outs) - - conf.L3socket=L3dnetSocket - conf.L2socket=L2dnetSocket - - - diff --git a/scripts/external_libs/scapy-2.3.1/scapy/arch/solaris.py b/scripts/external_libs/scapy-2.3.1/scapy/arch/solaris.py deleted file mode 100644 index 3117076a..00000000 --- a/scripts/external_libs/scapy-2.3.1/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-2.3.1/scapy/arch/unix.py b/scripts/external_libs/scapy-2.3.1/scapy/arch/unix.py deleted file mode 100644 index 151a08f5..00000000 --- a/scripts/external_libs/scapy-2.3.1/scapy/arch/unix.py +++ /dev/null @@ -1,205 +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 fcntl import ioctl -from scapy.error import warning -import scapy.config -import scapy.utils -import scapy.utils6 -import scapy.arch - -scapy.config.conf.use_pcap = 1 -scapy.config.conf.use_dnet = 1 -from pcapdnet import * - - - - - -################## -## Routes stuff ## -################## - - -def read_routes(): - if scapy.arch.SOLARIS: - f=os.popen("netstat -rvn") # -f inet - elif scapy.arch.FREEBSD: - f=os.popen("netstat -rnW") # -W to handle long interface names - else: - f=os.popen("netstat -rn") # -f inet - ok = 0 - mtu_present = False - prio_present = False - routes = [] - pending_if = [] - for l in f.readlines(): - if not l: - break - l = l.strip() - if l.find("----") >= 0: # a separation line - continue - if not ok: - if l.find("Destination") >= 0: - ok = 1 - mtu_present = l.find("Mtu") >= 0 - prio_present = l.find("Prio") >= 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[5+mtu_present+prio_present] - if flg.find("Lc") >= 0: - continue - if dest == "default": - dest = 0L - netmask = 0L - 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)) - f.close() - - # 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 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 = [] - i = dnet.intf() - for int in i: - ifname = int['name'] - v6 = [] - if int.has_key('alias_addrs'): - v6 = int['alias_addrs'] - for a in v6: - if a.type != dnet.ADDR_TYPE_IP6: - continue - - xx = str(a).split('/')[0] - addr = scapy.utils6.in6_ptop(xx) - - scope = scapy.utils6.in6_getscope(addr) - - ret.append((xx, scope, ifname)) - return ret - -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] - else: # FREEBSD or DARWIN - d,nh,fl,dev = l.split()[:4] - if filter(lambda x: x[2] == dev, lifaddr) == []: - 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: - cset = ['::1'] - nh = '::' - else: - devaddrs = filter(lambda x: x[2] == dev, lifaddr) - 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-2.3.1/scapy/arch/windows/__init__.py b/scripts/external_libs/scapy-2.3.1/scapy/arch/windows/__init__.py deleted file mode 100644 index e604266b..00000000 --- a/scripts/external_libs/scapy-2.3.1/scapy/arch/windows/__init__.py +++ /dev/null @@ -1,545 +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 -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, 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_pcap = 1 -conf.use_dnet = 1 -#from scapy.arch import pcapdnet -#from scapy.arch.pcapdnet import * - -LOOPBACK_NAME="lo0" -WINDOWS = True -IPPROTO_IPIP = 4 - - -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() - - - -import _winreg - - - -class PcapNameNotFoundError(Scapy_Exception): - pass - -class NetworkInterface(object): - """A network interface of your local host""" - - def __init__(self, dnetdict=None): - self.name = None - self.ip = None - self.mac = None - self.pcap_name = None - self.win_name = None - self.uuid = None - self.dnetdict = dnetdict - if dnetdict is not None: - self.update(dnetdict) - - def update(self, dnetdict): - """Update info about network interface according to given dnet dictionary""" - self.name = dnetdict["name"] - # Other attributes are optional - try: - self.ip = socket.inet_ntoa(dnetdict["addr"].ip) - except (KeyError, AttributeError, NameError): - pass - try: - self.mac = dnetdict["link_addr"] - except KeyError: - pass - self._update_pcapdata() - - def _update_pcapdata(self): - """Supplement more info from pypcap and the Windows registry""" - - # XXX: We try eth0 - eth29 by bruteforce and match by IP address, - # because only the IP is available in both pypcap and dnet. - # This may not work with unorthodox network configurations and is - # slow because we have to walk through the Windows registry. - for n in range(30): - guess = "eth%s" % n - win_name = pcapdnet.pcap.ex_name(guess) - if win_name.endswith("}"): - try: - uuid = win_name[win_name.index("{"):win_name.index("}")+1] - keyname = r"SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces\%s" % uuid - try: - key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, keyname) - except WindowsError: - log_loading.debug("Couldn't open 'HKEY_LOCAL_MACHINE\\%s' (for guessed pcap iface name '%s')." % (keyname, guess)) - continue - try: - fixed_ip = _winreg.QueryValueEx(key, "IPAddress")[0][0].encode("utf-8") - except (WindowsError, UnicodeDecodeError, IndexError): - fixed_ip = None - try: - dhcp_ip = _winreg.QueryValueEx(key, "DhcpIPAddress")[0].encode("utf-8") - except (WindowsError, UnicodeDecodeError, IndexError): - dhcp_ip = None - # "0.0.0.0" or None means the value is not set (at least not correctly). - # If both fixed_ip and dhcp_ip are set, fixed_ip takes precedence - if fixed_ip is not None and fixed_ip != "0.0.0.0": - ip = fixed_ip - elif dhcp_ip is not None and dhcp_ip != "0.0.0.0": - ip = dhcp_ip - else: - continue - except IOError: - continue - else: - if ip == self.ip: - self.pcap_name = guess - self.win_name = win_name - self.uuid = uuid - break - else: - raise PcapNameNotFoundError - - def __repr__(self): - return "<%s: %s %s %s pcap_name=%s win_name=%s>" % (self.__class__.__name__, - self.name, self.ip, self.mac, self.pcap_name, self.win_name) - -from UserDict import IterableUserDict - -class NetworkInterfaceDict(IterableUserDict): - """Store information about network interfaces and convert between names""" - - def load_from_dnet(self): - """Populate interface table via dnet""" - #for i in pcapdnet.dnet.intf(): - # try: - # XXX: Only Ethernet for the moment: localhost is not supported by dnet and pcap - # We only take interfaces that have an IP address, because the IP - # is used for the mapping between dnet and pcap interface names - # and this significantly improves Scapy's startup performance - # if i["name"].startswith("eth") and "addr" in i: - # self.data[i["name"]] = NetworkInterface(i) - # except (KeyError, PcapNameNotFoundError): - # pass - #if len(self.data) == 0: - # log_loading.warning("No match between your pcap and dnet network interfaces found. " - # "You probably won't be able to send packets. " - # "Deactivating unneeded interfaces and restarting Scapy might help.") - - def pcap_name(self, devname): - """Return pypcap device name for given libdnet/Scapy device name - - This mapping is necessary because pypcap numbers the devices differently.""" - - 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 libdnet/Scapy device name for given pypcap device name - - This mapping is necessary because pypcap numbers the devices differently.""" - - 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 show(self, resolve_mac=True): - """Print list of available network interfaces in human readable form""" - print "%s %s %s" % ("IFACE".ljust(5), "IP".ljust(15), "MAC") - for iface_name in sorted(self.data.keys()): - dev = self.data[iface_name] - mac = str(dev.mac) - if resolve_mac: - mac = conf.manufdb._resolve_MAC(mac) - print "%s %s %s" % (str(dev.name).ljust(5), str(dev.ip).ljust(15), mac) - -ifaces = NetworkInterfaceDict() -#ifaces.load_from_dnet() - -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 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) - -def read_routes(): - ok = 0 - routes = [] - ip = '(\d+\.\d+\.\d+\.\d+)' - # On Vista and Windows 7 the gateway can be IP or 'On-link'. - # But the exact 'On-link' string depends on the locale, so we allow any text. - gw_pattern = '(.+)' - metric_pattern = "(\d+)" - delim = "\s+" # The columns are separated by whitespace - netstat_line = delim.join([ip, ip, gw_pattern, ip, metric_pattern]) - pattern = re.compile(netstat_line) - f=os.popen("netstat -rn") - for l in f.readlines(): - match = re.search(pattern,l) - if match: - dest = match.group(1) - mask = match.group(2) - gw = match.group(3) - netif = match.group(4) - metric = match.group(5) - try: - #intf = pcapdnet.dnet.intf().get_dst(pcapdnet.dnet.addr(type=2, addrtxt=dest)) - intf={}; - except OSError: - log_loading.warning("Building Scapy's routing table: Couldn't get outgoing interface for destination %s" % dest) - continue - if not intf.has_key("addr"): - break - addr = str(intf["addr"]) - addr = addr.split("/")[0] - - dest = atol(dest) - mask = atol(mask) - # If the gateway is no IP we assume it's on-link - gw_ipmatch = re.search('\d+\.\d+\.\d+\.\d+', gw) - if gw_ipmatch: - gw = gw_ipmatch.group(0) - else: - gw = netif - routes.append((dest,mask,gw, str(intf["name"]), addr)) - f.close() - return routes - -def read_routes6(): - return [] - -def getmacbyip(ip, chainCC=0): - """Return MAC address corresponding to a given IP address""" - if isinstance(ip,Net): - ip = iter(ip).next() - tmp = map(ord, inet_aton(ip)) - if (tmp[0] & 0xf0) == 0xe0: # mcast @ - return "01:00:5e:%.2x:%.2x:%.2x" % (tmp[1]&0x7f,tmp[2],tmp[3]) - iff,a,gw = conf.route.route(ip) - if ( (iff == LOOPBACK_NAME) or (ip == conf.route.get_if_bcast(iff)) ): - return "ff:ff:ff:ff:ff:ff" - # Windows uses local IP instead of 0.0.0.0 to represent locally reachable addresses - ifip = str(pcapdnet.dnet.intf().get(iff)['addr']) - if gw != ifip.split('/')[0]: - ip = gw - - mac = conf.netcache.arp_cache.get(ip) - if mac: - return mac - - res = srp1(Ether(dst=ETHER_BROADCAST)/ARP(op="who-has", pdst=ip), - type=ETH_P_ARP, - iface = iff, - timeout=2, - verbose=0, - chainCC=chainCC, - nofilter=1) - if res is not None: - mac = res.payload.hwsrc - conf.netcache.arp_cache[ip] = mac - return mac - return None - -import scapy.layers.l2 -scapy.layers.l2.getmacbyip = getmacbyip - -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, "*") - 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, ".") - 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(), []) - if multi: - remain = filter(lambda p: not hasattr(p, '_answered'), remain); - - 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 - - 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: - 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(): - return sorted(ifaces.keys()) - -def get_working_if(): - try: - return devname(pcap.lookupdev()) - except Exception: - return 'lo0' |