Пример #1
0
def main():
  param = getparam(1)
  ping =  Ether() / IP(dst=param) / ICMP()
  if ping['Ethernet'].dst=="ff:ff:ff:ff:ff:ff":
    print "It seems that the host did'nt answer to arp"
    sys.exit(1)
  print ("Ready to sent icmp to %s @ %s" % (ping['Ethernet'].dst, ping['IP'].dst))
  print "Pinging with real MAC...",
  sys.stdout.flush()
  rep,non_rep = srp(ping ,timeout=5,verbose=0)
  if rep:
    print "Got answer...\nTrying with other sources"
    MAC1 = "00:0c:29"
    for I in range(2,16):
      ping =  Ether(src=MAC1+macr()+macr()+macr()) / IP(dst=param) / ICMP()
      rep,non_rep = srp(ping ,timeout=5,verbose=0)
      if rep:
        print ("%s pass; %i Mac address allowed" % (ping['Ethernet'].src, I))
      else:
        print ("Mmmm... Didn't answer anymore Security allow %i Mac" % I)
        sys.exit(1)
  else:
    print "The host did'nt answer"
    sys.exit(1)
  print "No port security in place"
Пример #2
0
def arp_spoof(fake_ip, mac_address):
    try:
        for _ in xrange(5):
            srp(Ether(dst="ff:ff:ff:ff:ff:ff")/ARP(psrc=fake_ip, hwsrc=mac_address), verbose=0, timeout=0.05)
            time.sleep(0.05)
    except socket.error:
        # Are you sure you're running as root?
        print "ERROR: You need to run this script as root."
        sys.exit()
Пример #3
0
def icmp_ping(ip, mac=None):

    if ip is None:
        return (None, None)

    if mac is None:
        ans, unans = srp(Ether() / IP(dst=ip) / ICMP(), timeout=2)
    else:
        ans, unans = srp(Ether(dst=mac) / IP(dst=ip) / ICMP(), timeout=2)

    if verbose:
        print "icmp_ping: ", ip, " ans = ", len(ans), ", unans = ", len(unans)
        sys.stdout.flush()
    return ans, unans
Пример #4
0
def ARPGenerator(destIP, srcMAC='random'):
    '''Procedure to generate multiple ARP Packets '''
    print "Thread ARP Generator started"
    try:
        if srcMAC == 'self':
            for _ in range(FLOODPACKETCOUNT):
                ans, unans = srp(Ether(dst=BROADCASTMAC)/ARP(pdst=destIP), timeout=1, inter=0.1)
        else:
            if srcMAC == 'random':
                srcMAC = randomMAC()
            for _ in range(FLOODPACKETCOUNT):
                ans, unans = srp(Ether(dst=BROADCASTMAC, src=srcMAC)/ARP(hwsrc=srcMAC, pdst=destIP), timeout=1, inter=0.1)
    except Exception as e:
        print "Exception occurred: ", e
Пример #5
0
def do_udp():
    """spam out some random UDP broadcasts"""

    nic = socket.gethostname() + '_0'

    while True:    
        rnd = random.uniform(5,10)
        time.sleep(rnd)
        payload = '12345678' + str(rnd)
        #build and send the packet
        srp(Ether(dst='ff:ff:ff:ff:ff:ff')/
            IP(dst="255.255.255.255")/
            UDP(sport=9898,dport=9898)/
            payload,timeout=0.001,
            iface=nic)
Пример #6
0
    def run(self):
        conf.verb = 0
        self.console.info("sending arping...")
        ans, unans = srp(Ether(dst="ff:ff:ff:ff:ff:ff") / ARP(pdst=self.network.value), timeout=2)

        self.console.info("done")
        rows, columns = (-1, -1)
        split_input = True
        try:
            # Get the size of the window. We really only care about the rows -
            # this is used for formatting large amounts of data
            rows, columns = os.popen("stty size", "r")
        except Exception:
            self.console.warn("couldn't get the terminal window size - " + "printing without formatting.")
            time.sleep(2)
            split_input = False

        counter = 0
        for snd, rcv in ans:
            if counter == 0:
                self.console.writeln("MAC\t\t\tIP")
                counter += 1
            elif counter == rows and split_input:
                # TODO: Make this more framework-friendly
                raw_input("Press any key to continue.")
                counter = 0
            self.console.writeln(rcv.sprintf("%Ether.src%\t%ARP.psrc%"))
            counter += 1
Пример #7
0
def main():
	"""
	Fonction principale du démon tipmac. Elle attend des connexions
	entrantes lui demandant d'établir la correspondance IP/MAC.
	"""

	HOST=''
	PORT=1337

	s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
	s.bind((HOST, PORT))
	s.listen(1)
	while 1 :
		conn, addr = s.accept()
		data = conn.recv(1024)
		print data
		ip = IPy.IP(data).strNormal()
		ans,unans = scapy.srp(scapy.Ether(dst="ff:ff:ff:ff:ff:ff")/scapy.ARP(pdst=ip),timeout=2)
		try :
			a  = ans[0][1].sprintf("%src%")
		except :
			a = "fail"

		conn.send(a)
		conn.close()
Пример #8
0
	def update(self):
		from scapy.all import srp,Ether,ARP,conf
		
		# Do an ARP scan of the local network
		conf.verb = 0
		ans, unans=srp(Ether(dst="ff:ff:ff:ff:ff:ff")/ARP(pdst=self.addr),timeout=2)

		# TODO - sort out timezones/summer time
		t = time.time()

		# Extract a list of machines and their IP addresses
		for snd,rcv in ans:
			mac = rcv.sprintf(r"%Ether.src%")
			ip = rcv.sprintf(r"%ARP.psrc%")
			if not mac in self.machines:
				self.machines.append(mac)
				self.addresses[mac] = ip
			self.names[mac] = self.get_name(mac,ip)
			self.last_seen[mac] = t

		fid = open(self.log,'wt')
		#fid.write("# "+time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(t))+'\n')
		# current scan time, last seen time, mac, ip
		for mac in sorted(self.last_seen,key=self.last_seen.get):
			# TODO - sort by last seen time
			fid.write(time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(t))+" , "+time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(self.last_seen[mac]))+" , "+mac+" , "+self.addresses[mac]+" , "+str('%s' % float('%.1g' % (self.last_seen[mac]-t)))+" , "+self.names[mac]+'\n')
		fid.close()
Пример #9
0
def check_dhcp_on_eth(iface, timeout):
    """Check if there is roque dhcp server in network on given iface
        @iface - name of the ethernet interface
        @timeout - scapy timeout for waiting on response
    >>> check_dhcp_on_eth('eth1')
    """

    scapy.conf.iface = iface

    scapy.conf.checkIPaddr = False
    dhcp_options = [("message-type", "discover"),
                    ("param_req_list", utils.format_options(
                        [1, 2, 3, 4, 5, 6,
                         11, 12, 13, 15, 16, 17, 18, 22, 23,
                         28, 40, 41, 42, 43, 50, 51, 54, 58, 59, 60, 66, 67])),
                    "end"]

    fam, hw = scapy.get_if_raw_hwaddr(iface)
    dhcp_discover = (
        scapy.Ether(src=hw, dst="ff:ff:ff:ff:ff:ff") /
        scapy.IP(src="0.0.0.0", dst="255.255.255.255") /
        scapy.UDP(sport=68, dport=67) /
        scapy.BOOTP(chaddr=hw) /
        scapy.DHCP(options=dhcp_options))
    ans, unans = scapy.srp(dhcp_discover, multi=True,
                           nofilter=1, timeout=timeout, verbose=0)
    return ans
Пример #10
0
def scan():
	try:
		print(colors.blue+"interfaces:"+colors.end)
		for iface in netifaces.interfaces():
			print(colors.yellow+iface+colors.end)
		print("")
		interface = input(colors.purple+"interface: "+colors.end)
		try:
			ip = netifaces.ifaddresses(interface)[2][0]['addr']
		except(ValueError, KeyError):
			printError("invalid interface")
			return
		ips = ip+"/24"
		printInfo("scanning please wait...\n", start="\n")
		print(colors.blue+"MAC - IP"+colors.end)

		start_time = datetime.now()

		conf.verb = 0
		try:
			ans, unans = srp(Ether(dst="ff:ff:ff:ff:ff:ff")/ARP(pdst = ips), timeout = 2,iface=interface,inter=0.1)
		except PermissionError:
			printError('root permissions required')
			return

		for snd,rcv in ans:
			print(rcv.sprintf(colors.yellow+"r%Ether.src% - %ARP.psrc%"+colors.end))
		stop_time = datetime.now()
		total_time = stop_time - start_time
		printSuccess("scan completed", start="\n")
		printSuccess("scan duration: "+str(total_time))
	except KeyboardInterrupt:
		printInfo("network scanner terminated", start="\n")
Пример #11
0
def get_arp(ip):
    conf.verb = 0
    ans,unans = srp(Ether(dst='ff:ff:ff:ff:ff:ff')/ARP(pdst=ip),timeout=2)
    for snd,rcv in ans:
        print('sending packet: ',snd.sprintf(r"%Ether.dst% %ARP.pdst%"),
              '\n'
              ,'\breceived packet:',rcv.sprintf(r"%ARP.psrc% %Ether.src%"))
Пример #12
0
Файл: mitm.py Проект: st4n1/src
def do_update():
    global my_ip, my_mac, router_ip, router_mac
    get_data = Ether()/ARP(op = 1, ptype = 0x800, hwlen = 6, plen = 4)
    my_ip = get_data[ARP].psrc
    my_mac = get_data[Ether].src
    index = my_ip.rfind(".")
    router_ip = my_ip[:index+2]
    try:
        router_data = srp(Ether(src=my_mac)/ARP(op = 1, ptype = 0x800, hwlen = 6, plen = 4, pdst=router_ip), timeout=6)
    except Exception as prablm:
        exit(str(prablm) + "\n[Info] you need to be root")

    if len(router_data[0]) == 0:
        print "Got No ARP Answer From %s" % router_ip
        try:
            router_mac = str(raw_input("Specify an Router MAC Address : "))
        except Exception as problm:
            exit(problm)
        except:
            exit()
        if not router_mac:
            exit("No Router MAC Address Specified")
    else:
        try:
            router_mac = router_data[0][0][0].dst
        except Exception as sec_problm:
            exit(sec_problm)
    del router_data
    del get_data
    del index
Пример #13
0
def cmd_arp_ping(ip, iface, verbose):
    """
    Send ARP packets to check if a host it's alive in the local network.

    Example:

    \b
    # habu.arp.ping 192.168.0.1
    Ether / ARP is at a4:08:f5:19:17:a4 says 192.168.0.1 / Padding
    """

    if verbose:
        logging.basicConfig(level=logging.INFO, format='%(message)s')

    conf.verb = False

    if iface:
        conf.iface = iface

    res, unans = srp(Ether(dst="ff:ff:ff:ff:ff:ff")/ARP(pdst=ip), timeout=2)

    for _, pkt in res:
        if verbose:
            print(pkt.show())
        else:
            print(pkt.summary())
Пример #14
0
def scan_lan(scan_network):
    conf.verb=0
    ans,unans=srp(Ether(dst="ff:ff:ff:ff:ff:ff")/ARP(pdst=scan_network),timeout=2)
    print ""
    
    log_file=strftime("%d_%b_%Y_%H:%M:%S_+0000", gmtime()) + "_-_scan.log"
    FILE = open(log_file,  "w")
    FILE.write("LAN Scanner - Log File\n")
    FILE.write("----------------------------------------\n")
    FILE.write("[+] Scanned network: " + scan_network + "\n")
    FILE.write("[+] Scan time: " + strftime("%d %b %Y, %H:%M:%S +0000 GMT", gmtime()) + "\n")
    FILE.write("\n")
    
    for snd,rcv in ans:
        mac_address=rcv.sprintf("%Ether.src%")
        ip_address=rcv.sprintf("%ARP.psrc%")
        
        print rcv.sprintf("[+] Found a system! MAC: %Ether.src% IP: %ARP.psrc% ")
        FILE.write(ip_address + ", " + mac_address + "\n")
    
    FILE.write("\n")
    FILE.close
    print ""
    print "[i] Completed the scan. Exiting now!"
    print ""
    print ""
    return
Пример #15
0
def main():
    """
        Entry point
    """
    # Parsing command line
    parser = OptionParser()
    parser.add_option("-t", "--timeout", type="float", dest="timeout",
                      default=1,
                      help="timeout in seconds for waiting answers",
                      metavar="TIME")
    (options, args) = parser.parse_args()

    conf.checkIPaddr = False
    fam, hw = get_if_raw_hwaddr(conf.iface)
    mac = ":".join(map(lambda x: "%.02x" % ord(x), list(hw)))
    print 'Requesting DHCP servers for', mac
    ether = Ether(dst="ff:ff:ff:ff:ff:ff", src=hw)
    ip = IP(src="0.0.0.0", dst="255.255.255.255")
    udp = UDP(sport=68, dport=67)
    bootp = BOOTP(chaddr=hw)
    dhcp = DHCP(options=[("message-type", "discover"), "end"])
    dhcp_discover = ether / ip / udp / bootp / dhcp
    ans, unans = srp(dhcp_discover, multi=True, timeout=options.timeout)
    print 'Discovered DHCP servers:'
    for p in ans:
        print p[1][Ether].src, p[1][IP].src
Пример #16
0
def check_dhcp_request(iface, server, range_start, range_end, timeout=5):
    """Provide interface, server endpoint and pool of ip adresses
        Should be used after offer received
        >>> check_dhcp_request('eth1','10.10.0.5','10.10.0.10','10.10.0.15')
    """

    scapy.conf.iface = iface

    scapy.conf.checkIPaddr = False

    fam, hw = scapy.get_if_raw_hwaddr(iface)

    ip_address = next(utils.pick_ip(range_start, range_end))

    # note lxc dhcp server does not respond to unicast
    dhcp_request = (scapy.Ether(src=hw, dst="ff:ff:ff:ff:ff:ff") /
                    scapy.IP(src="0.0.0.0", dst="255.255.255.255") /
                    scapy.UDP(sport=68, dport=67) /
                    scapy.BOOTP(chaddr=hw) /
                    scapy.DHCP(options=[("message-type", "request"),
                                        ("server_id", server),
                                        ("requested_addr", ip_address),
                                        "end"]))
    ans, unans = scapy.srp(dhcp_request, nofilter=1, multi=True,
                           timeout=timeout, verbose=0)
    return ans
Пример #17
0
def cmd_dhcp_discover(iface, timeout, verbose):
    """Send a DHCP request and show what devices has replied.

    Note: Using '-v' you can see all the options (like DNS servers) included on the responses.

    \b
    # habu.dhcp_discover
    Ether / IP / UDP 192.168.0.1:bootps > 192.168.0.5:bootpc / BOOTP / DHCP
    """

    conf.verb = False

    if iface:
        conf.iface = iface

    conf.checkIPaddr = False

    hw = get_if_raw_hwaddr(conf.iface)

    ether = Ether(dst="ff:ff:ff:ff:ff:ff")
    ip = IP(src="0.0.0.0",dst="255.255.255.255")
    udp = UDP(sport=68,dport=67)
    bootp = BOOTP(chaddr=hw)
    dhcp = DHCP(options=[("message-type","discover"),"end"])

    dhcp_discover = ether / ip / udp / bootp / dhcp

    ans, unans = srp(dhcp_discover, multi=True, timeout=5)      # Press CTRL-C after several seconds

    for _, pkt in ans:
        if verbose:
            print(pkt.show())
        else:
            print(pkt.summary())
Пример #18
0
def cmd_gateway_find(network, iface, host, tcp, dport, timeout, verbose):
    """
    Try to reach an external IP using any host has a router.

    Useful to find routers in your network.

    First, uses arping to detect alive hosts and obtain MAC addresses.

    Later, create a network packet and put each MAC address as destination.

    Last, print the devices that forwarded correctly the packets.

    Example:

    \b
    # habu.find.gateway 192.168.0.0/24
    192.168.0.1 a4:08:f5:19:17:a4 Sagemcom
    192.168.0.7 b0:98:2b:5d:22:70 Sagemcom
    192.168.0.8 b0:98:2b:5d:1f:e8 Sagemcom
    """

    if verbose:
        logging.basicConfig(level=logging.INFO, format='%(message)s')

    conf.verb = False

    if iface:
        conf.iface = iface

    res, unans = srp(Ether(dst="ff:ff:ff:ff:ff:ff")/ARP(pdst=network), timeout=2)

    neighbors = set()

    for _, pkt in res:
        neighbors.add((pkt['Ether'].src, pkt['Ether'].psrc))

    for mac,ip in neighbors:
        if tcp:
            res, unans = srp(Ether(dst=mac)/IP(dst=host)/TCP(dport=dport), timeout=timeout)
        else:
            res, unans = srp(Ether(dst=mac)/IP(dst=host)/ICMP(), timeout=timeout)
        for _,pkt in res:
            if pkt:
                if verbose:
                    print(pkt.show())
                else:
                    print(ip, mac, conf.manufdb._get_manuf(mac))
Пример #19
0
def arping(iprange):
    # Simple ARP scanner to return list of hosts on a local network. This depends on scapy, but should be rewritten to only use default Python modules.
    ans, unans = srp(Ether(dst="ff:ff:ff:ff:ff:ff") / ARP(pdst=iprange), iface="wlo1", timeout=2)
    collection = []
    for snd, rcv in ans:
        result = rcv.sprintf(r"%ARP.psrc% %Ether.src%").split()
        collection.append(result)
    return collection
Пример #20
0
def get_mac_by_ip_s(ip_address, delay):
    """try to retrieve MAC address associated with ip using Scapy library """
    responses, _ = srp(Ether(dst="ff:ff:ff:ff:ff:ff")/ARP(pdst=ip_address),
                       timeout=delay, retry=10)
    # return the MAC address from a response
    for _, response in responses:
        return response[Ether].src
    return None
Пример #21
0
def arp_ping(ip):
    if ip is None:
        return (None, None)
    ans, unans = srp(Ether(dst="ff:ff:ff:ff:ff:ff") / ARP(pdst=ip), timeout=1.5, retry=2)
    if verbose & 0x02:
        print "arp_ping: ", ip, " ans = ", len(ans), ", unans = ", len(unans)
        sys.stdout.flush()
    return (ans, unans)
Пример #22
0
def tcp_ping(hosts):
    packet = Ether()/IP(dst=hosts)/TCP(dport=80, flags='S')
    ans, unans = srp(packet, filter='tcp', verbose=0, timeout=2)

    for ret in ans:
        delta = ret[1].time - ret[0].sent_time
        if ret[1][IP].src in result:
            result[ret[1][IP].src] = delta
Пример #23
0
def arping(iprange, interface):

    ans, unans = srp(Ether(dst="ff:ff:ff:ff:ff:ff")/ARP(pdst=iprange),iface=interface, timeout=2)
    print "\n       IP       <--->       MAC\n"
    collection = []
    for snd, rcv in ans:
        result = rcv.sprintf(r"%ARP.psrc% %Ether.src%").split()
        collection.append(result)
    return collection
Пример #24
0
def getMacFromIp(hostIP):
    """getMacFromIp function takes Host IP Address, returns MAC of the Host"""
    ans, unans = srp(Ether(dst=BROADCASTMAC)/ARP(pdst=hostIP),
              timeout=2)
    result = '00:00:00:00:00:aa'
    for snd, rcv in ans:
        #result = rcv.sprintf(r"%Ether.src%")
        print rcv.sprintf(r"%Ether.src%")
    return result
Пример #25
0
 def _arp_ping(mac_address, ip_address):
     result = False
     answered,unanswered = srp(Ether(dst=mac_address)/ARP(pdst=ip_address), timeout=1, verbose=False)
     if len(answered) > 0:
         for reply in answered:
             result = []
             result.append(str(reply[0].pdst))
             result = ', '.join(result)
     return result
Пример #26
0
def araping(iprange="192.168.8.0/24"):
    conf.verb=0
    ans,unans=srp(Ether(dst="ff:ff:ff:ff:ff:ff")/ARP(pdst=iprange),
            timeout=2)
    collection=[]
    for snd,rcv in ans:
        result=rcv.sprintf(r"%ARP.psrc% %Ether.src%").split()
        collection.append(result)
    return collection
Пример #27
0
 def run(self):
     conf.verb = 0
     self.console.info("sending arping...")
     ans, unans = srp(Ether(dst="ff:ff:ff:ff:ff:ff")/
                      ARP(pdst=self.network.value), timeout=2)
     
     self.console.info("done")
     
     for snd, rcv in ans:
         self.console.writeln(rcv.sprintf("%Ether.src%\t%ARP.psrc%"))
Пример #28
0
 def scan(self):
     conf.verb = 0
     ans, unans = srp(Ether(dst="ff:ff:ff:ff:ff:ff")/ARP(pdst = ips), timeout = 2, iface=interface, inter=0.1)
     arp_data = {}
     for snd, rcv in ans:
         mac = rcv.sprintf(r"%Ether.src%")
         ip = rcv.sprintf(r"%ARP.psrc%")
         hostname = socket.gethostbyaddr(ip)[0]
         arp_data[mac] = [ip, hostname]
     return arp_data
Пример #29
0
def arp_ping(ipn):
#Main function.
    logging.info('Starting Arp Run')
    conf.verb = 0
    ans, unans = srp(Ether(dst="ff:ff:ff:ff:ff:ff")/ARP(pdst=str(ipn)), timeout=2)
    element = []
    for snd, rcv in ans:
        res = rcv.sprintf(r"%Ether.src% %ARP.psrc%").split()
        element.append(res)
    return element
Пример #30
0
def arp_scan():
    """send a broadcast arp"""

    nic = socket.gethostname() + '_0'

    while True:
        ips = []

	base = get_baseip()
	for n in xrange(1,255):
		ip = base + '.' + str(n)
		ips.append(ip)

	random.shuffle(ips)
	for ip in ips:
		time.sleep(random.uniform(2,10))        
		#send a raw ethernet arp packet
		srp(Ether(dst='ff:ff:ff:ff:ff:ff')/ARP(pdst=ip),timeout=0.001, iface=nic)

        time.sleep(1)
Пример #31
0
def scan(host):
    try:
        arp_request = scapy.ARP(pdst=host)
        broadcast_ethernet_packet = scapy.Ether(dst="FF:FF:FF:FF:FF:FF")
        packet = broadcast_ethernet_packet / arp_request  #combine 2 requests with each others using /
        answered_list = scapy.srp(
            packet, timeout=1, verbose=False
        )[0]  #srp=send and receive responce for that packet the response contains 2 lists
        unanswered_list = scapy.srp(
            packet, timeout=1, verbose=False
        )[1]  #the list for live hosts and list for down hosts (didnt respond)

        hosts_lists = []
        for host in answered_list:
            hosts = {
                "ip": host[1].psrc,
                "mac": host[1].hwsrc
            }  #answered_list contains 2 lists requests hosts[0] and responses hosts[1]
            hosts_lists.append(hosts)

        return hosts_lists
    except KeyboardInterrupt as err:
        print("[-] ctr+c ... Quiting")
Пример #32
0
 def _arp_ping(mac_address):
     result = False
     answered, unanswered = srp(Ether(dst=mac_address) /
                                ARP(pdst=self.network_address),
                                timeout=1,
                                verbose=False)
     if len(answered) > 0:
         for reply in answered:
             if reply[1].hwsrc == mac_address:
                 if type(result) is not list:
                     result = []
                 result.append(str(reply[1].psrc))
                 result = ', '.join(result)
     return result
Пример #33
0
def internetInfo():
    target_ip = input("Enter target ip e.g. 192.168.1.1/24: ")
    st = speedtest.Speedtest()
    url = "http://ipinfo.io/json"
    response = urlopen(url)
    data = json.load(response)

    host = s.gethostname() 
    ip = data['ip']
    post = data['postal']
    city = data['city']
    region = data['region']
    country = data['country']
    org = data['org']

    print(" ")
    print("INTERNET INFORMATION...")
    print("Host:",host)
    print("Local:",ip)
    print("Postal:",post)
    print("City:",city)
    print("Region:",region)
    print("Country:",country)
    print("ISP:",org)
    print(" ")
    print("RUNNING SPEED TEST...")
    print("Download speed: ", st.download())
    print("Upload speed: ", st.upload()) 
    print(" ")

    
    arp = ARP(pdst=target_ip)
    ether = Ether(dst="ff:ff:ff:ff:ff:ff")
    packet = ether/arp
    
    result = srp(packet, timeout=3, verbose=0)[0]
    clients = []
    
    for sent, received in result:
        clients.append({'ip': received.psrc, 'mac': received.hwsrc})

    print("Available devices in the network:")
    print("IP" + " "*18+"MAC")
    count = 0
    for client in clients:
        print("{:16}    {}".format(client['ip'], client['mac']))
        count += 1 
    print("Devices connected: ", count)
    print(" ")
Пример #34
0
    def startScanning(self):
        self.listNetworks.clear()
        self.progressBar.setValue(0)
        target_ip = self.targetIp + "/24"
        self.btnStart.setDisabled(True)
        try:
            # IP Address for the destination
            # create ARP packet
            arp = ARP(pdst=target_ip)
            # create the Ether broadcast packet
            # ff:ff:ff:ff:ff:ff MAC address indicates broadcasting
            ether = Ether(dst="ff:ff:ff:ff:ff:ff")
            # stack them
            packet = ether / arp

            result = srp(packet, timeout=3, verbose=0)[0]
            progress = 100 / len(result)
            # a list of clients, we will fill this in the upcoming loop
            clients = []
            for sent, received in result:
                self.progressBar.setValue(progress)
                host = "Host"
                try:
                    host = socket.gethostbyaddr(received.psrc)[0]
                    #pass
                except Exception as e:
                    print(e)
                progress += progress
                # for each response, append ip and mac address to `clients` list
                clients.append({
                    'ip': received.psrc,
                    'mac': received.hwsrc,
                    'host': host
                })
            self.progressBar.setValue(100)
            # print clients
            print("Available devices in the network:")
            self.listNetworks.addItem(
                "%-20s %-20s %-30s" %
                ("IP", "MAC",
                 "HOSTNAME"))  #print("IP" + " "*18+"%-12i").format("HOST")
            for client in clients:
                self.listNetworks.addItem(
                    "%-20s %-20s %-20s" %
                    (client['ip'], client['mac'], client['host']))
                #print("{:16}    {}     {}".format(client['ip'], client['mac'], client['host']))
            self.btnStart.setDisabled(False)
        except Exception as e:
            print(e)
def run_program():
    scan = NetworkScanner()
    scan.run("192.168.1.1/24")

    run_spoof_choice = ""

    while run_spoof_choice != 4:
        run_spoof_choice = input(
            "1. Spoof Target\n2. Spoof Manually\n3. Run Scan Again\n4. Quit\n")

        if run_spoof_choice == "1":
            target_choice = input("Which Victim? ")

            victim_ip_and_mac, gateway_ip_and_mac = scan.export_scan_result(
                target_choice)

            spoof_attack_1 = Spoof(victim_ip_and_mac, gateway_ip_and_mac)
            spoof_attack_1.run()

        elif run_spoof_choice == "2":
            target_ip = input("Victim's IP: ")

            # Manually Gets MAC Address
            arp_request = scapy.ARP(pdst=target_ip)
            broadcast = scapy.Ether(dst="ff:ff:ff:ff:ff:ff:ff")
            arp_request_broadcast = broadcast / arp_request
            answered_list = scapy.srp(arp_request_broadcast,
                                      timeout=4,
                                      verbose=False)[0]
            target_mac = answered_list[0][1].hwsrc

            print("\nVictim's MAC Address ", target_mac)

            victim_ip_and_mac = {"ip": target_ip, "mac": target_mac}
            target_choice = 00

            gateway_ip_and_mac = scan.export_scan_result(target_choice)

            spoof_attack_2 = Spoof(victim_ip_and_mac, gateway_ip_and_mac)
            spoof_attack_2.run()

        elif run_spoof_choice == "3":
            scan.run("192.168.1.1/24")

        elif run_spoof_choice == "4":
            exit()

        else:
            print("Invalid Choice")
Пример #36
0
def main(argv):
    if len(sys.argv) < 6:
        print m + "\nInvalid Arguments"
        print b + 'arp_masscan_virtual.py -i <virtual interface> -r <ip range> -p <masscan ports>'
        sys.exit()

    arp_table_dic = {}

    interface = ''
    ip_range = ''
    ports = ''

    try:
        opts, args = getopt.getopt(argv, "hi:r:p:",
                                   ["iface=", "ips=", "ports="])
    except KeyInterrupt:
        print 'arp.py -i <interface> -r <ip range>'
        sys.exit(1)
    for opt, arg in opts:
        if opt == '-h':
            print b + 'arp_masscan_virtual.py -i <virtual interface> -r <ip range> -p <masscan ports>'
            sys.exit()
        elif opt in ("-i", "--iface"):
            interface = arg
        elif opt in ("-r", "--ips"):
            ip_range = arg
        elif opt in ("-p", "--ports"):
            ports = arg

    print y + "\nScanning ..."
    from scapy.all import srp, Ether, ARP, conf
    conf.verb = 0
    ans, uans = srp(Ether(dst="FF:FF:FF:FF:FF:FF") / ARP(pdst=ip_range),
                    timeout=2,
                    iface=interface,
                    inter=0.1)
    for snd, rcv in ans:
        print c + rcv.sprintf(r"%Ether.src% - %ARP.psrc%")
        arp_table_dic[rcv.sprintf("%ARP.psrc%")] = rcv.sprintf("%Ether.src%")
    print m + "\n ARP Scan complete"

    print m + "\nARP table saved in the following dictionary"
    print arp_table_dic

    for key, value in arp_table_dic.iteritems():
        subprocess.call([
            "masscan", "-p", ports, key, "--interface", interface,
            "--router-mac", value, "---wait=0"
        ])
Пример #37
0
def get_mac(ip):
    arp_request = scapy.ARP(pdst=ip)
    #this mac is for broadcast
    broadcast = scapy.Ether(dst="ff:ff:ff:ff:ff:ff")
    arp_request_broadcast = broadcast / arp_request
    # this line will return 2 lists, answered and unanswered.Timeout will specify time to request
    while True:
        try:
            answered_list = scapy.srp(
                arp_request_broadcast, timeout=1,
                verbose=False)[0]  #verbose=False for no output on console
            mac = answered_list[0][1].hwsrc
            print(mac)
        except:
            pass
Пример #38
0
def scan(ip):
    arp_request = scapy.ARP(pdst=ip)
    broadcast = scapy.Ether(dst="ff:ff:ff:ff:ff:ff")
    arp_request_broadcast = broadcast / arp_request
    answered_list = scapy.srp(arp_request_broadcast, timeout=1, verbose=False)[
        0]  #only first element, second is [1] # add unanswered_list

    client_list = []
    for element in answered_list:
        client_dict = {
            "ip": element[1].psrc,
            "mac": element[1].hwsrc
        }  #0- send 1- response
        client_list.append(client_dict)
    return client_list
Пример #39
0
def get_mac(ip):
    arp_request = scapy.ARP(pdst=ip)
    # print(arp_request.summary())
    # scapy.ls(scapy.ARP()) this is to see which parameters does scapy.ARP() accepts and how
    broadcast = scapy.Ether(dst="ff:ff:ff:ff:ff:ff")
    # print(broadcast.summary())
    arp_request_broadcast = broadcast / arp_request
    # print(arp_request_broadcast.summary())
    answered_list = scapy.srp(arp_request_broadcast, timeout=1,
                              verbose=False)[0]
    # print(answered_list.summary())

    for element_is_variable in answered_list:

        return element_is_variable[1].hwsrc
Пример #40
0
def scan(ip):
    arp_request = scapy.ARP(pdst=ip)
    broadcast = scapy.Ether(dst="ff:ff:ff:ff:ff:ff")
    arp_request_broadcast = broadcast / arp_request
    answered_list = scapy.srp(arp_request_broadcast, timeout=1,
                              verbose=False)[0]

    clients_list = []

    for element in answered_list:
        client_dict = {"IP": element[1].psrc, "MAC_address": element[1].hwsrc}
        clients_list.append(client_dict)
    return clients_list

    print(clients_list)
Пример #41
0
def scan(ip):
    # IP Packet
    ip_packet = scapy.ARP(pdst=ip)

    # Ethernet Frame
    ether_frame = scapy.Ether(dst="ff:ff:ff:ff:ff:ff")

    # Combining above two to make an ARP request for set IP/range and broadcast MAC
    arp_request = ether_frame / ip_packet

    # Send and Receive the protocol created above. By default returns two lists [answered, unanswered]. We capture only answered ones
    answered = scapy.srp(
        arp_request, timeout=1, verbose=False
    )[0]  # Using srp instead of scapy.sr because we have custom made Ethernet frame
    return answered[0][1].hwsrc
Пример #42
0
def scan(ip):
    arp_request = scapy.ARP(pdst=ip)
    broadcast = scapy.Ether(dst="ff:ff:ff:ff:ff:ff")
    arp_req_broad = broadcast / arp_request
    answered_list = scapy.srp(arp_req_broad, timeout=1, verbose=False)[0]

    def print_results():
        print("    IP\t\t\tMAC Address")
        for value in answered_list:
            client_dict = dict()
            client_dict["IP"] = value[1].psrc
            client_dict["MAC"] = value[1].hwsrc
            print("[+] " + client_dict["IP"] + "\t\t" + client_dict["MAC"])

    print_results()
Пример #43
0
    def run_scan(self, ips):
        for ip in ips:
            packet_list = [
                scapy.Ether(dst="ff:ff:ff:ff:ff:ff") / scapy.ARP(pdst=ip)
            ]
            response = scapy.srp(packet_list, verbose=0, timeout=10)

            packet_count = len(response[0])
            for pkt in range(packet_count):
                self.__result_scan.append([
                    response[0][pkt][1].psrc, response[0][pkt][1].hwsrc,
                    MacVendor.get_vendor_mac(response[0][pkt][1].hwsrc)
                ])

        return self.__result_scan
Пример #44
0
def scan_network(ip):

    arp_request_packet = scapy.ARP(pdst=ip)

    broadcast_packet = scapy.Ether(dst="ff:ff:ff:ff:ff:ff")

    combined_packet = broadcast_packet / arp_request_packet

    answered_list = scapy.srp(combined_packet, timeout=1, verbose=False)[0]

    print("IP\t\t\tMac Address\n-----------------------------------------")

    for element in answered_list:

        print(element[1].psrc + "\t\t" + element[1].hwsrc)
Пример #45
0
def main():
    myip = input("What is Your IP ?:")
    netmask = input("What is SubnetMask ?:")
    hwaddr = 'ff:ff:ff:ff:ff:ff'

    cidr = gen_cidr(myip, netmask)
    print('Scanning on: ' + cidr + '\n')

    pkt = Ether(dst=hwaddr) / ARP(
        op=1, pdst=cidr)  # op=1:arpリクエスト(ブロードキャスト) op=2:arpレスポンス(ユニキャスト)
    ans, uans = srp(pkt, timeout=30)

    print("")
    for send, recv in ans:
        print(recv.sprintf('%ARP.psrc% is up.'))
Пример #46
0
def pingsweep(net):
    conf.verb=0

    ans,unans=srp(Ether(dst="ff:ff:ff:ff:ff:ff")/ARP(pdst=str(net.cidr)),timeout=2)

    hosts = []

    for snd,rcv in ans:
        mac = netaddr.EUI(rcv[Ether].src)
        mac.dialect = netaddr.mac_unix
        ip = rcv[ARP].psrc
        #print(ip, mac, mac.oui.registration().org)
        hosts.append([ip, mac])

    return sorted(hosts)
Пример #47
0
def scan(ip):
    arp_request = scapy.ARP(pdst=ip)
    broadcast = scapy.Ether(dst="FF:FF:FF:FF:FF:FF")
    arp_request_broadcast = broadcast/arp_request
    # devuelve 2 listas: una con paquetes contestados y otra con no contestados
    # Poniendo el 0 me devuelve sólo la lista 1
    answered_list = scapy.srp(arp_request_broadcast, timeout=2)[0]
    
    # print(answered_list.summary())

    for element in answered_list:
        print("----------------------------------------------------------------------------")
        response = element[1]
        print(response.psrc)
        print(response.hwsrc)
Пример #48
0
def scan(ip):
    arp_request = scapy.ARP(pdst=ip)
    dst = 'ff:ff:ff:ff:ff:ff'
    broadcast = scapy.Ether(dst=dst)
    arp_request_broadcast = broadcast / arp_request
    answered_list = scapy.srp(arp_request_broadcast, timeout=1,
                              verbose=False)[0]

    clients_list = []

    for element in answered_list:
        client_dict = {'ip': element[1].psrc, 'mac': element[1].hwsrc}
        clients_list.append(client_dict)

    return clients_list
Пример #49
0
def get_mac(ip):
    # use ARP to ask who has target ip
    arp_request = scapy.ARP(pdst=ip)

    # ethernet frame and append arp_request
    broadcast = scapy.Ether(dst="ff:ff:ff:ff:ff:ff")

    # combine both packets in one
    arp_request_broadcast = broadcast / arp_request

    # srp send packet with a custom ether part
    answered_list = scapy.srp(arp_request_broadcast, timeout=1,
                              verbose=False)[0]
    # we only need the one mac
    return answered_list[0][1].hwsrc
Пример #50
0
def scan(ip):
    arp_request = scapy.ARP(pdst = ip)
    #arp_request.show()
    broad_cast = scapy.Ether(dst = 'ff:ff:ff:ff:ff:ff')
    #broad_cast.show()
    arp_request_broad_cast = broad_cast/arp_request
    #arp_request_broad_cast.show()
    answered, unanswered = scapy.srp(arp_request_broad_cast, timeout = 1)
    print(answered.summary())
    
    client_list =[]
    for each in answered:
        client_dict = {'ip': each[1].psrc, 'mac': each[1].hwsrc}
        client_list.append(client_dict)
    return client_list
Пример #51
0
def scan(ip, interface):
    arp_request = scapy.ARP(pdst=ip)
    broadcast = scapy.Ether(dst='ff:ff:ff:ff:ff:ff')  # broadcast MAC address
    arp_request_broadcast = broadcast / arp_request
    # send
    answered_list = scapy.srp(arp_request_broadcast,
                              timeout=1,
                              verbose=False,
                              iface=interface)[0]

    clients_list = []
    for element in answered_list:
        client_dict = {'ip': element[1].psrc, 'mac': element[1].hwsrc}
        clients_list.append(client_dict)
        return clients_list
Пример #52
0
def get_mac(ip):
    # Create a scapy ARP object and set the destination IP to ip arg passed
    arp_request = scapy.ARP(pdst=ip)

    # Create a scapy Ethernet object and set the MAC to the broadcast MAC
    broadcast = scapy.Ether(dst="ff:ff:ff:ff:ff:ff")

    # Append an ARP and Ethernet packet and store in new variable
    arp_request_broadcast = broadcast / arp_request

    # Send Ether/ARP request and save the ARP response (the response returns two list)
    answered_list = scapy.srp(arp_request_broadcast, timeout=1,
                              verbose=False)[0]

    return answered_list[0][1].hwsrc
Пример #53
0
def scan(ip):
    arp_request = scapy.ARP(pdst=ip)
    #arp_request.show()
    broadcast = scapy.Ether(dst="ff:ff:ff:ff:ff:ff")
    #broadcast.show()
    arp_request_broadcast = broadcast / arp_request
    #arp_request_broadcast.show()
    answeredlist = scapy.srp(arp_request_broadcast, timeout=1,
                             verbose=False)[0]

    clients_list = []
    for element in answered_list:
        client_dict = {"ip": element[1].psrc, "mac": element[1].hwsrc}
        client_list.append(client_dict)
    return (client_list)
Пример #54
0
def arp_scan(iface, ip):
    print("[*]Scaning.....", ip)
    conf.verb = 0
    broadcast = "ff:ff:ff:ff:ff:ff"
    ether_layer = Ether(dst=broadcast)
    apr_layer = ARP(pdst=ip)

    packet = ether_layer / apr_layer

    ans, unans = srp(packet, iface=iface, timeout=2, inter=0.1)

    for snd, rcv in ans:
        ip = rcv[ARP].psrc
        mac = rcv[Ether].src
        print("IP-Address :", ip, '  MAC-Address :', mac)
Пример #55
0
def get_mac(ip):

    # Here, we are creating an ARP request ourselves to ask who has the specific IP we asked for.
    arp_request = scapy.ARP(pdst=ip)

    # Here, we are setting our destination MAC to broadcast MAC address to make sure
    # it is sent to all the clients who are on the same network
    broadcast = scapy.Ether(dst="ff:ff:ff:ff:ff:ff")

    # This variable is your packet that will be sent across the network, as it contains information about MAc and ARP
    arp_request_broadcast = broadcast/arp_request
    answered_list = scapy.srp(arp_request_broadcast, timeout=1, verbose = False)[0]
    # srp stands for send and receive packet.

    return answered_list[0][1].hwsrc
Пример #56
0
def ARP_scan(ip, time=1):
    arp_scaner = scapy.ARP(pdst=ip)  # создания своего арп запроса
    brodcast = scapy.Ether(dst="ff:ff:ff:ff:ff:ff")
    arp_packet = brodcast / arp_scaner
    answered = scapy.srp(arp_packet, timeout=int(time), verbose=False)[0]

    client_list = []
    for element in answered:
        client_dict = {
            "ip": element[1].psrc,
            "mac": element[1].hwsrc,
            "Ver": str(element[1].ptype)
        }
        client_list.append(client_dict)
    return client_list
Пример #57
0
def scan(ip):
    arp_request = scapy.ARP(pdst=ip)
    broadcast = scapy.Ether(dst="ff:ff:ff:ff:ff:ff")
    arp_request_broadcast = broadcast / arp_request
    # this line will return 2 lists, answered and unanswered.Timeout will specify time to request
    answered_list = scapy.srp(arp_request_broadcast, timeout=1,
                              verbose=False)[0]
    print("IP\t\t\tMAC address\n-------------------------")
    clients_list = []

    for element in answered_list:
        client_dict = {"ip": element[1].psrc, "MAC": element[1].hwsrc}
        clients_list.append(client_dict)
        #print(element[1].psrc+"\t\t" + element[1].hwsrc)
    print(clients_list)
Пример #58
0
def getMACAddresses(ip):
    arp_request = scapy.ARP(pdst=ip)
    broadcast = scapy.Ether(dst="ff:ff:ff:ff:ff:ff")
    request = broadcast / arp_request
    answered = scapy.srp(request, timeout=1, verbose=False)[0]
    print("IP\t\t\t\tMAC ADDRESS\n")
    for packet in answered:
        if flag:
            time.sleep(2)
            request = requests.get("https://api.macvendors.com/" +
                                   packet[1].hwsrc)
            print(request.text)
            print(packet[1].psrc + "\t\t\t" + packet[1].hwsrc + "\n")
        else:
            print(packet[1].psrc + "\t\t\t" + packet[1].hwsrc + "\n")
Пример #59
0
def scan(ip):
    arp_request = scapy.ARP()
    arp_request.pdst = ip
    arp_broadcast = scapy.Ether()
    arp_broadcast.dst = "ff:ff:ff:ff:ff:ff"
    arp_request_broadcast = arp_broadcast / arp_request
    answered = scapy.srp(arp_request_broadcast, timeout=1, verbose=False)[0]
    clients_list = []
    for elements in answered:
        clients_dict = {
            "ip": elements[1].psrc,
            "Mac Address": elements[1].hwsrc
        }
        clients_list.append(clients_dict)
    return clients_list
def get_mac_from_ip(ip):
    '''
    Function taking an ip address and returning the associated MAC address

    :param ip: IP address of interest
    :return: mac_address
    '''
    arp_req = scapy.ARP(pdst=ip)
    broadcast = scapy.Ether(dst="ff:ff:ff:ff:ff:ff")
    arp_req_broadcast = broadcast / arp_req
    response_list, _ = scapy.srp(arp_req_broadcast, timeout=1, verbose=False)

    mac_address = response_list[0][1].hwsrc

    return mac_address