def method_scapy_arping(self): from scapy.layers.l2 import arping for o in arping(self.mem.interfaces.selected.network(), verbose=False)[0]: h = Device(self.mem) h.ip = o[1].psrc h.mac = o[1].src.upper() h.pinged = True if h.mac != None and h.pinged == True: h.alias = self.mem.settings.value( "DeviceAlias/{}".format(h.macwithout2points( h.mac.upper())), None) h.type = self.mem.types.find_by_id( int( self.mem.settings.value( "DeviceType/{}".format( h.macwithout2points(h.mac.upper())), 0))) self.arr.append(h) #Solo si se da alias #Adds current interface ip h = Device(self.mem) h.ip = self.mem.interfaces.selected.ip() h.mac = self.mem.interfaces.selected.mac().upper() h.pinged = True h.alias = self.mem.settings.value( "DeviceAlias/{}".format(h.macwithout2points(h.mac.upper())), None) h.type = self.mem.types.find_by_id( int( self.mem.settings.value( "DeviceType/{}".format(h.macwithout2points(h.mac.upper())), 0))) self.arr.append(h)
def scan(self): try: for interface, network in config.interfaces_networks.items(): if not network.is_private(): self.logger.info( "Skipping arp ping scan on network {0:s} because it's a public network".format(str(network))) continue self.logger.info("Executing arp ping scan on network {0:s}...".format(str(network))) discovered_hosts = set() ans, unans = arping(str(network), iface=interface, timeout=1, verbose=False) for s, r in ans.res: node = NetworkNode() node.ip = IPAddress(r[ARP].psrc) node.mac = EUI(r[Ether].src) node.host = resolve_ip(r[ARP].psrc) discovered_hosts.add(node) self.scan_results[network] = discovered_hosts except socket.error as e: if e.errno == socket.errno.EPERM: # Operation not permitted self.logger.error("%s. Did you run as root?", e.strerror) else: raise self.logger.info("Arp ping scan done. Found %d unique hosts.", self.number_of_hosts_found)
def arp_ping(network, verbose=0, timeout=2, count=3): """ping network and return a list of tuples (mac-address,ip-address)""" hosts = [] for c in xrange(count): if verbose: print "arp_ping attempt %i" % c alive, dead = arping(net=network, timeout=timeout, verbose=verbose) hosts += [(x[1].hwsrc, x[1].psrc) for x in alive] return list(set(hosts))
def get_mac(self, ip): res, unans = arping(net=ip, verbose=0, timeout=3) mac_res = '' if res: for s, r in res.res: mac_res = r.src if mac_res is '': raise Exception('can not find ip: ' + str(ip) + ' mac ') return mac_res
def send_arp_req(self, timeout=1.0): """ Broadcast an ARP request with the device's IPv4 address. Returns true if the device responded to the request, false otherwise :param int timeout: maximum time to wait for an answer :return boolean: True if device answered, False otherwise """ ans, _ = arping(self.device.ip, timeout=timeout) return len(ans)
def get_mac_addr(ip_addr): ans, unans = arping(ip_addr) mac_addr_list = [] for snd, rcv in ans: mac_addr_list.append(rcv[Ether].src) if len(mac_addr_list > 0): return mac_addr_list[0] else: return None
def discover(): ip = '192.168.11.*' print ('start: {}'.format(datetime.now().strftime('%Y/%m/%d %H:%M:%S'))) answers, _ = arping(ip, timeout=1, verbose=0) for send_packet, recieve_packet in answers: print( 'MAC Address: {}, IP Address: {}'.format( recieve_packet[ARP].hwsrc, recieve_packet[ARP].psrc, )) print ('end : {}'.format(datetime.now().strftime('%Y/%m/%d %H:%M:%S')))
def discover(): ip = '192.168.10.*' print 'start: {}'.format(datetime.now().strftime('%Y/%m/%d %H:%M:%S')) answers, _ = arping(ip, timeout=1, verbose=0) for send_packet, recieve_packet in answers: print 'MAC Address: {}, IP Address: {}'.format( recieve_packet[ARP].hwsrc, # MACアドレス recieve_packet[ARP].psrc, # IPアドレス ) print 'end : {}'.format(datetime.now().strftime('%Y/%m/%d %H:%M:%S'))
def scan_local_net(net: Optional[str] = None) -> List[Dict[str, str]]: """get hosts (ip, mac) from local net by ARP protocol.""" # TODO: select network interface w/o mask - get mask from adapter # TODO: select network interface by unique prefix # TODO: error, if net is not provided and multiple interfaces found if not _can_use_scapy(): raise NotImplementedError if not net: net = get_net() ans, _ = arping(net) hosts = [{'ip': r.psrc, 'mac': r.hwsrc} for _, r in ans.res] return hosts
def get_ip_mac_list(ips): global timeout answers, uans = arping(ips, verbose=0) for answer in answers: if answer[1].psrc != "192.168.1.1": mac = answer[1].hwsrc ip = answer[1].psrc if (ip, mac) not in res: res.append((ip, mac)) timeout = timeout - 1 if not res: get_ip_mac_list(ips) and timeout > 0 return res
def discover_all_hosts(self): # A really rudimentary way of getting all the hosts in your local area network >.< # Probably doesn't work for all cases a = ARP() self_ip = a.psrc subnet = ".".join(self_ip.split(".")[:3]) + ".*" # REALLY HACKY PLEASE FIND A BETTER WAY (if time permits) # Debug print subnet hosts = {} # key: IP address, value: MAC address ans, _ = arping(subnet) for answer in ans: arp_reply = answer[1] hosts[arp_reply.psrc] = arp_reply.hwsrc # Debug print hosts return hosts
def arp_full_cycle_check(self, ip_addr): # ip_addr is the IP address which you want to get the correct MAC address for # Probing step # ans is the list of replies we get when we arping the ip address ans, unans = arping(ip_addr) if len(ans) == 1: # only 1 reply, which means there are no spoofers return ans[ARP].hwsrc # should be correct, haven't tested # return True # wait should change this to return the mac address for answer in ans: # Send a TCP/SYN to confirm their identity reply = tcp_syn_check(ip_addr) if reply is not None: return reply[ARP].hwsrc return False # should never happen? might happen if host just happens to be down and there's no answer
def add_ips(self, ips, arp_addresses=True, arp_timeout=1.0): """ Adds IPs to the allocation pool. Duplicates are filtered out, but order is preserved. `ips` is a sequence of IP addresses, like ['192.168.0.100', '192.168.0.101'], or integers or quadruples. To generate it, try calling this method in the following way: .add_ips(['192.168.250.' + str(i) for i in range(11, 255)]) This will add 192.168.250.11-254 with minimal effort. (The last element in a range is not generated) `arp_addresses` will, if True, the default, try to use scapy, if installed, to ARP every supplied address, building a lease-map for already-allocated IPs, which should minimise unnecessary DECLINEs. `arp_timeout` is the number of seconds to wait for a addresses to respond. """ ips = dict((ip, IPv4(ip)) for ip in ips) with self._lock: #Filter out duplicates allocated_ips = set(ip for (_, ip) in self._map.itervalues()) duplicate_ips = [] for (ip, ip_obj) in ips.iteritems(): if ip_obj in self._pool or ip_obj in allocated_ips: duplicate_ips.append(ip) if duplicate_ips: for ip in duplicate_ips: del ips[ip] self._logger.warn("Pruned duplicate IPs: %(ips)r" % { 'ips': duplicate_ips, }) #Try to ARP addresses if arp_addresses and arping: expiration = time.time() + self._lease_time mapped_ips = 0 self._logger.info( "Beginning ARP-lookup for %(count)i IPs in pool '%(name)s', with timeout=%(timeout).3fs" % { 'count': len(ips), 'timeout': arp_timeout, 'name': self._hostname_prefix, }) (answered, unanswered) = arping(ips.keys(), verbose=0, timeout=arp_timeout) for answer in answered: try: ip = answer[0].payload.fields['pdst'] mac = answer[1].fields['src'].lower() ip_obj = ips.pop(ip) except Exception, e: self._logger.debug( "Unable to use ARP-discovered binding %(binding)r: %(error)s" % { 'binding': answer, 'error': str(e), }) else: mapped_ips += 1 self._map[mac] = [expiration, ip_obj] self._logger.info( "ARP-discovered %(ip)s bound to %(mac)s in pool '%(name)s'; providing lease until %(time)s" % { 'ip': ip_obj, 'mac': mac, 'time': time.ctime(expiration), 'name': self._hostname_prefix, }) self._logger.info( "%(count)i IPs automatically bound in pool '%(name)s'" % { 'count': mapped_ips, 'name': self._hostname_prefix, }) self._pool.extend(ips.itervalues()) total = len(self._pool) + len(self._map)
def grab_MAC(IP): """Manipulates the packet layers to obtain the MAC address from the returned values""" ans, uans = arping(IP, verbose=verbose) for s, r in ans: return r[Ether].src
def mac_discovery(self): for r in arping(self.__iface_addr.compressed, verbose=False)[0]: mac = r[1][ARP].hwsrc[9:] for p in self.__people: if mac == p.mac: p.counter = -1
""" # ether = Ether(type=0x0806) ether = Ether(type=ETH_P_ARP) ether.show() arp = Ether() / ARP() arp.show() # ---------------------------------------------------------------------- # ARP Ping 在本地以太网络上最快速地发现主机的方法 answer, unanswer = srp(Ether(dst="ff:ff:ff:ff:ff:ff") / ARP(pdst="192.168.0.0/24"), timeout=2) answer.summary(lambda s, r: r.sprintf("%Ether.src% %ARP.psrc%")) # 以上两个命令相当于 arping("192.168.0.*", timeout=2) # ---------------------------------------------------------------------- # ARP 缓存投毒 这种攻击可以通过 VLAN 跳跃攻击投毒 ARP 缓存,使得其他客户端无法加入真正的网关地址。 # 经典的 ARP 缓存投毒: arp = Ether(dst="9c:bc:f0:12:3d:4d") / ARP( op="who-has", psrc="192.168.0.1", pdst="192.168.0.101") arp.show() send(arp, inter=RandNum(10, 40), loop=1)
def findRespondingIp(): arping('192.168.43.1/24')
def main(): global ip_lst # status.noc.stonybrook.edu parser = argparse.ArgumentParser(description="man on the side attack detector.") parser.add_argument("-i", "--ifname", help="interface to use", type=str, required=False, default="wlp1s0") parser.add_argument("-o", "--out-file", help="file to write live ip's to", type=str, required=False, default=None) parser.add_argument( "-t", "--cache-clear-interv", help="how long to wait before clearing the ARP cache", type=int, required=False, default=0, ) parser.add_argument( "-m", "--mu", help="how long to wait before pinging the next random IP", type=float, required=False, default=0 ) args = parser.parse_args() ifname = args.ifname mask = get_netmask(ifname) ip_str = get_ipaddress(ifname) print("mask: " + mask) print("ip: " + ip_str) ip = netaddr.IPNetwork(ip_str + "/" + mask) print(ip) found_ips = [] # scan whole network for live computers ans, unans = arping(str(ip.network) + "/" + str(ip.prefixlen), iface=ifname) # record all of the live IP's for i in ans: found_ips.append(i[0][ARP].pdst) print("found " + str(len(found_ips)) + " IPs") # write the IP's to a file if requested if args.out_file is not None: outfile = open(args.out_file, "w") wifi = Wireless(ifname) outfile.write("args: " + str(args) + "\n") outfile.write("essid: " + wifi.getEssid() + "\n") outfile.write("mode: " + wifi.getMode() + "\n") outfile.write("mask: " + mask + "\n") outfile.write("ip: " + ip_str + "\n") outfile.write("network: " + str(ip.network) + "/" + str(ip.prefixlen) + "\n") outfile.write("\n".join(found_ips)) outfile.write("\n") outfile.close() # schedule the ARP cache clearing if args.cache_clear_interv > 0: t = threading.Thread(target=clear_cache_timer, args=[args.cache_clear_interv]) t.start() # schedule the pinging if args.mu <= 0: sys.exit(1) ip_lst = found_ips random.shuffle(ip_lst) # signal.signal(signal.SIGALRM, ping_rnd) # signal.setitimer(signal.ITIMER_REAL, args.mu, args.mu) while True: # signal.pause() t = threading.Thread(target=ping_rnd, args=["", ""]) t.start() time.sleep(args.mu)
from scapy.all import * from scapy.layers.l2 import arping ans = arping('192.168.5.0/24') print(ans)
def main(): a = arping('192.168.0.0/16', verbose=0) # a = arping('192.168.0.255/16', verbose=0) for i in a[0]: send_packet(i[0].pdst)
def add_ips(self, ips, arp_addresses=True, arp_timeout=1.0): """ Adds IPs to the allocation pool. Duplicates are filtered out, but order is preserved. `ips` is a sequence of IP addresses, like ['192.168.0.100', '192.168.0.101'], or integers or quadruples. To generate it, try calling this method in the following way: .add_ips(['192.168.250.' + str(i) for i in range(11, 255)]) This will add 192.168.250.11-254 with minimal effort. (The last element in a range is not generated) `arp_addresses` will, if True, the default, try to use scapy, if installed, to ARP every supplied address, building a lease-map for already-allocated IPs, which should minimise unnecessary DECLINEs. `arp_timeout` is the number of seconds to wait for a addresses to respond. """ ips = dict((ip, IPv4(ip)) for ip in ips) with self._lock: #Filter out duplicates allocated_ips = set(ip for (_, ip) in self._map.itervalues()) duplicate_ips = [] for (ip, ip_obj) in ips.iteritems(): if ip_obj in self._pool or ip_obj in allocated_ips: duplicate_ips.append(ip) if duplicate_ips: for ip in duplicate_ips: del ips[ip] self._logger.warn("Pruned duplicate IPs: %(ips)r" % {'ips': duplicate_ips,}) #Try to ARP addresses if arp_addresses and arping: expiration = time.time() + self._lease_time mapped_ips = 0 self._logger.info("Beginning ARP-lookup for %(count)i IPs in pool '%(name)s', with timeout=%(timeout).3fs" % { 'count': len(ips), 'timeout': arp_timeout, 'name': self._hostname_prefix, }) (answered, unanswered) = arping(ips.keys(), verbose=0, timeout=arp_timeout) for answer in answered: try: ip = answer[0].payload.fields['pdst'] mac = answer[1].fields['src'].lower() ip_obj = ips.pop(ip) except Exception, e: self._logger.debug("Unable to use ARP-discovered binding %(binding)r: %(error)s" % { 'binding': answer, 'error': str(e), }) else: mapped_ips += 1 self._map[mac] = [expiration, ip_obj] self._logger.info("ARP-discovered %(ip)s bound to %(mac)s in pool '%(name)s'; providing lease until %(time)s" % { 'ip': ip_obj, 'mac': mac, 'time': time.ctime(expiration), 'name': self._hostname_prefix, }) self._logger.info("%(count)i IPs automatically bound in pool '%(name)s'" % { 'count': mapped_ips, 'name': self._hostname_prefix, }) self._pool.extend(ips.itervalues()) total = len(self._pool) + len(self._map)
def ipParser(startIp, endIp): #not using atm ,but will be usefull in optimization. start = struct.unpack('>I', socket.inet_aton(startIp))[0] end = struct.unpack('>I', socket.inet_aton(endIp))[0] return [socket.inet_ntoa(struct.pack('>I', i)) for i in range(start, end)] if __name__ == "__main__": #resp[0] ---> arping results #resp[0][0] ---> first packet #resp[0][0][1].hwsrc ---> captured packets, hwsrc hostList = [] ipRange = input("Enter ip range :") resp = arping(ipRange, verbose=False) hostNumber = len(resp[0]) print("[*]Given range:" + str(ipRange)) # initial parsing for item in resp[0]: hostList.append(dict({item[1].psrc: item[1].hwsrc})) for item in hostList: print("Captured IP and MAC -->", item) print("[*]Discovered hosts: ", hostNumber) while (True): print("[*]Continuing to discovery ") resp = arping(ipRange, verbose=False) parsePacket(resp, hostList) time.sleep(5)
# To print the attributes of ICMP: ICMP().show() packets: tuple = sr(IP(dst="192.168.1.254") / ICMP(code=(0, 3))) print(f'Number of packets tuple (request, response): {len(list(packets)):d}') req_resp_list: SndRcvList for req_resp_list in packets: req_resp_list.show() # Only send and receive one packet. packet: Packet = sr1(IP(dst="www.slashdot.org") / ICMP() / "XXXXXXXXXXX") packet.show() print("\n--------------------------------------------------\n") # Using traceroute results: Tuple[TracerouteResult] = traceroute(["google.fr", "yahoo.fr"]) packets: PacketList for packets in results: print("\n--------------------------------------------------\n") packets.summary() # sudo apt-get install net-tools # sudo ifconfig | grep -i mask result: Tuple[ARPingResult, PacketList] = arping("10.0.0.0/24") print("ARPing result:") print(result[0]) print(f"List of packets ({len(list(result[1])):d})") packet: Packet for packet in result[1]: packet.show()
def run(self): ans, unans = arping(str(self.ip), verbose=False, timeout=2) if ans is not None and len(ans) > 0: ans.show() self.found_ip = ans.res[0][0][ARP].pdst
import sys from scapy.layers.l2 import arping if __name__ == '__main__': print("remember to put interface in monitor mode before using this script") if "-h" in sys.argv: print("usage: {0} [ interface ]".format(sys.argv[0])) exit() device = None if len(sys.argv) > 1: device = sys.argv[1] # ans, unans = srp(Ether(dst="ff:ff:ff:ff:ff:ff") / ARP(pdst="192.168.1.0/24"), timeout=10) # ans.summary(lambda (s, r): r.sprintf("%Ether.src% %ARP.psrc%")) arping("192.168.1.*")