def __init__(self): self.Base = Base() self.ArpScan = ArpScan() self.ICMPv6Scan = ICMPv6Scan() if not self.Base.check_installed_software("nmap"): exit(2)
def start(webserver_context): # Read from home directory the user_key. If non-existent, get one from # cloud. config_dict = utils.get_user_config() utils.log('[MAIN] Starting.') # Set up environment state = HostState() state.user_key = config_dict['user_key'] state.secret_salt = config_dict['secret_salt'] state.host_mac = utils.get_my_mac() state.gateway_ip, _, state.host_ip = utils.get_default_route() webserver_context['host_state'] = state assert utils.is_ipv4_addr(state.gateway_ip) assert utils.is_ipv4_addr(state.host_ip) state.packet_processor = PacketProcessor(state) utils.log('Initialized:', state.__dict__) # Continously discover devices arp_scan_thread = ArpScan(state) arp_scan_thread.start() # Continuously gather SSDP data netdisco_thread = NetdiscoWrapper(state) netdisco_thread.start() # Continuously capture packets packet_capture_thread = PacketCapture(state) packet_capture_thread.start() # Continously spoof ARP if '--no_spoofing' not in sys.argv: arp_spoof_thread = ArpSpoof(state) arp_spoof_thread.start() # Continuously upload data data_upload_thread = DataUploader(state) data_upload_thread.start()
def refresh_db(database_path, arp_scan_settings): """ Refresh a darp database with the latest scan results. """ alerts = {} dbwrapper = DBWrapper(database_path) # do a scan newScan = ArpScan(**arp_scan_settings).results newDevices = [] if newScan: newDevices = newScan.get('devices') # get latest scan oldDevices = dbwrapper.latest_scan() stamp = get_safe_timestamp() for device in newDevices: dbwrapper.insert_sighting(stamp=stamp, **device) alerts = generate_mac_alerts(dbwrapper, oldDevices, newDevices, stamp) return alerts
def run(): # Create a TCP/IP socket sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Bind the socket to the port server_address = (VMSettings.arp_daemon_address, int(VMSettings.arp_daemon_port)) ArpDump.printout('starting up on %s port %s' % server_address) sock.bind(server_address) # Listen for incoming connections sock.listen(1) while True: # Wait for a connection ArpDump.printout('waiting for a connection') connection, client_address = sock.accept() try: ArpDump.printout('connection from {0}'.format(client_address)) # Receive the data in small chunks and retransmit it data_ = "" while True: data = connection.recv(2048).decode("utf-8") data_ += data #print("strike: " + data_ + "\n") if len(data_) > 1: if data[0] == '|': i = 1 strlen = "" while data_[i] != '|': strlen += data_[i] i += 1 istrlen = int(strlen) if istrlen + 2 + len(strlen) == len(data_): data_ = data_[4:] break if len(data_) > 0: data_out = ArpScan.analyze(data_) data_out_ = "|" data_out_ += str(len(data_out)) data_out_ += "|" data_out_ += data_out connection.sendall(data_out_.encode("utf-8")) finally: # Clean up the connection connection.close()
def main(): # Read from home directory the user_key. If non-existent, get one from # cloud. config_dict = utils.get_user_config() # Where user would see report url = server_config.REPORT_URL.format(user_key=config_dict['user_key']) # Open a web browser only if non-root if not is_root() and LAUNCH_WEB_BROWSER_UPON_START: if 'no_browser' not in sys.argv: webbrowser.open_new_tab(url) os_platform = sys.platform # Run as root if os_platform.startswith('linux'): elevate(graphical=False) else: elevate() assert is_root() utils.log('[MAIN] Starting.') # Set up environment state = HostState() state.user_key = config_dict['user_key'] state.secret_salt = config_dict['secret_salt'] state.host_mac = utils.get_my_mac() state.gateway_ip, _, state.host_ip = utils.get_default_route() assert utils.is_ipv4_addr(state.gateway_ip) assert utils.is_ipv4_addr(state.host_ip) state.packet_processor = PacketProcessor(state) utils.log('Initialized:', state.__dict__) # Enable kernal forwarding. if os_platform.startswith('darwin'): cmd = ['/usr/sbin/sysctl', '-w', 'net.inet.ip.forwarding=1'] elif os_platform.startswith('linux'): cmd = ['sysctl', '-w', 'net.ipv4.ip_forward=1'] else: raise RuntimeError('Unsupported platform.') assert subprocess.call(cmd) == 0 # Continously discover devices arp_scan_thread = ArpScan(state) arp_scan_thread.start() # Continuously capture packets packet_capture_thread = PacketCapture(state) packet_capture_thread.start() # Continously spoof ARP arp_spoof_thread = ArpSpoof(state) arp_spoof_thread.start() # Continuously upload data data_upload_thread = DataUploader(state) data_upload_thread.start() # UI try: ui.start_main_ui(url, state) except KeyboardInterrupt: pass # Disable kernal forwarding. if os_platform.startswith('darwin'): cmd = ['/usr/sbin/sysctl', '-w', 'net.inet.ip.forwarding=0'] elif os_platform.startswith('linux'): cmd = ['sysctl', '-w', 'net.ipv4.ip_forward=0'] assert subprocess.call(cmd) == 0 utils.log('[MAIN] Done.')
def start(webserver_context): # Read from home directory the user_key. If non-existent, get one from # cloud. config_dict = utils.get_user_config() utils.log('[MAIN] Starting.') # Set up environment state = HostState() state.user_key = config_dict['user_key'].replace('-', '') state.secret_salt = config_dict['secret_salt'] state.host_mac = utils.get_my_mac() state.gateway_ip, _, state.host_ip = utils.get_default_route() webserver_context['host_state'] = state assert utils.is_ipv4_addr(state.gateway_ip) assert utils.is_ipv4_addr(state.host_ip) state.packet_processor = PacketProcessor(state) utils.log('Initialized:', state.__dict__) # Continously discover devices arp_scan_thread = ArpScan(state) arp_scan_thread.start() # Continuously gather SSDP data netdisco_thread = NetdiscoWrapper(state) netdisco_thread.start() # Continuously capture packets packet_capture_thread = PacketCapture(state) packet_capture_thread.start() # Continously spoof ARP if '--no_spoofing' not in sys.argv: arp_spoof_thread = ArpSpoof(state) arp_spoof_thread.start() # Continuously upload data data_upload_thread = DataUploader(state) data_upload_thread.start() # Suppress scapy warnings try: logging.getLogger("scapy.runtime").setLevel(logging.ERROR) except Exception: pass # Suppress flask messages try: logging.getLogger('werkzeug').setLevel(logging.ERROR) except Exception: pass if state.persistent_mode: # Insert a dash every four characters to make user-key easier to type pretty_user_key = '' for (ix, char) in enumerate(state.user_key): if (ix > 0) and (ix % 4 == 0): pretty_user_key += '-' pretty_user_key += char path = 'persistent/' + pretty_user_key caution = 'This is your private link. Open it only on trusted computers.' # noqa else: path = '' caution = '' print('\n' * 100) print(""" =========================== Princeton IoT Inspector =========================== View the IoT Inspector report at: https://inspector.cs.princeton.edu/{0} {1} Hit Control + C to terminate this process and stop data collection. """.format(path, caution))
socket_global.bind((network_interface, 0)) # endregion # region General output Base.print_info("Network interface: ", network_interface) Base.print_info("Gateway IP address: ", gateway_ip_address) Base.print_info("Your IP address: ", your_ip_address) Base.print_info("Your MAC address: ", your_mac_address) Base.print_info("First ip address: ", first_ip_address) Base.print_info("Last ip address: ", last_ip_address) # endregion # region Set target IP address target_ip_address = "1.1.1.1" target_mac_address = "00:00:00:00:00:00" arp_scan = ArpScan() if args.target_ip is None: Base.print_info("Start ARP scan ...") results = arp_scan.scan(network_interface, 3, 3, None, True) if len(results) > 0: Base.print_info("Network devices found:") device_index = 1 for device in results: Base.print_success(str(device_index) + ") " + device['ip-address'] + " (" + device['mac-address'] + ") ", device['vendor']) device_index += 1 device_index -= 1 current_device_index = raw_input(Base.c_info + 'Set device index from range (1-' + str(device_index) + '): ')
from os import path, errno, makedirs, stat from shutil import copyfile, copytree import subprocess as sub from argparse import ArgumentParser from sys import exit, stdout from time import sleep from ipaddress import IPv4Address from socket import socket, AF_PACKET, SOCK_RAW from random import randint import re # endregion # region Check user, platform and print banner Base = Base() Scanner = Scanner() ArpScan = ArpScan() Base.check_user() Base.check_platform() Base.print_banner() # endregion # region Parse script arguments parser = ArgumentParser(description='Apple DHCP MiTM script') parser.add_argument('-l', '--listen_iface', type=str, help='Set interface name for send DHCPACK packets') parser.add_argument('-d', '--deauth_iface', type=str, help='Set interface name for send wifi deauth packets') parser.add_argument('-D', '--phishing_domain', type=str, default="auth.apple.wi-fi.com", help='Set domain name for social engineering (default="auth.apple.wi-fi.com")') parser.add_argument('-p', '--phishing_domain_path', type=str, default="apple", help='Set local path to domain name for social engineering (default="apple")') parser.add_argument('-t', '--target_ip', type=str, help='Set target IP address', default=None)
def start(): """ Initializes inspector by spawning a number of background threads. Returns the host state once all background threats are started. """ # Read from home directory the user_key. If non-existent, get one from # cloud. config_dict = utils.get_user_config() utils.log('[MAIN] Starting.') # Set up environment state = HostState() state.user_key = config_dict['user_key'].replace('-', '') state.secret_salt = config_dict['secret_salt'] state.host_mac = utils.get_my_mac() state.gateway_ip, _, state.host_ip = utils.get_default_route() # Read special command-line arguments if '--raspberry_pi_mode' in sys.argv: state.raspberry_pi_mode = True assert utils.is_ipv4_addr(state.gateway_ip) assert utils.is_ipv4_addr(state.host_ip) state.packet_processor = PacketProcessor(state) utils.log('Initialized:', state.__dict__) # Continously discover devices arp_scan_thread = ArpScan(state) arp_scan_thread.start() # Continously discover ports via SYN scans syn_scan_thread = SynScan(state) syn_scan_thread.start() # Continuously gather SSDP data netdisco_thread = NetdiscoWrapper(state) netdisco_thread.start() # Continuously capture packets packet_capture_thread = PacketCapture(state) packet_capture_thread.start() # Continously spoof ARP if '--no_spoofing' not in sys.argv: arp_spoof_thread = ArpSpoof(state) arp_spoof_thread.start() # Continuously upload data data_upload_thread = DataUploader(state) data_upload_thread.start() # Suppress scapy warnings try: logging.getLogger("scapy.runtime").setLevel(logging.ERROR) except Exception: pass # Suppress flask messages try: logging.getLogger('werkzeug').setLevel(logging.ERROR) except Exception: pass # Insert a dash every four characters to make user-key easier to type pretty_user_key = '' for (ix, char) in enumerate(state.user_key): if (ix > 0) and (ix % 4 == 0): pretty_user_key += '-' pretty_user_key += char print('\n' * 100) os_platform = utils.get_os() print(WINDOWS_STARTUP_TEXT.format(server_config.BASE_URL, pretty_user_key)) # Open a browser window on Windows 10. Note that a new webpage will be # opened in a non-privileged mode. TODO: Not sure how to do the same # for macOS, as the "open" call on macOS will open a browser window # in privileged mode. if os_platform == 'windows': utils.open_browser_on_windows('{0}/user/{1}'.format( server_config.BASE_URL, pretty_user_key)) return state
class Scanner: # region Variables Base = None ArpScan = None # endregion # region Init def __init__(self): self.Base = Base() self.ArpScan = ArpScan() if not self.Base.check_installed_software("nmap"): exit(2) # endregion # region Apple device selection def apple_device_selection(self, apple_devices): try: apple_device = None if len(apple_devices) > 0: if len(apple_devices) == 1: apple_device = apple_devices[0] self.Base.print_info("Only one Apple device found:") self.Base.print_success( apple_device[0] + " (" + apple_device[1] + ") ", apple_device[2]) if len(apple_devices) > 1: self.Base.print_info("Apple devices found:") device_index = 1 for apple_device in apple_devices: self.Base.print_success( str(device_index) + ") " + apple_device[0] + " (" + apple_device[1] + ") ", apple_device[2]) device_index += 1 device_index -= 1 current_device_index = raw_input( self.Base.c_info + 'Set device index from range (1-' + str(device_index) + '): ') if not current_device_index.isdigit(): self.Base.print_error("Your input data is not digit!") exit(1) if any([ int(current_device_index) < 1, int(current_device_index) > device_index ]): self.Base.print_error( "Your number is not within range (1-" + str(device_index) + ")") exit(1) current_device_index = int(current_device_index) - 1 apple_device = apple_devices[current_device_index] else: self.Base.print_error("Could not find Apple devices!") exit(1) return apple_device except KeyboardInterrupt: self.Base.print_info("Exit") exit(0) # endregion # region Find all devices in local network def find_ip_in_local_network(self, network_interface, timeout=3, retry=3): try: local_network_ip_addresses = [] arp_scan_results = self.ArpScan.scan(network_interface, timeout, retry) if len(arp_scan_results) > 0: for device in arp_scan_results: if self.Base.ip_address_validation(device['ip-address']): local_network_ip_addresses.append(device['ip-address']) return local_network_ip_addresses except KeyboardInterrupt: self.Base.print_info("Exit") exit(0) # endregion # region Find Apple devices in local network with ArpScan def find_apple_devices_by_mac(self, network_interface, timeout=3, retry=3): try: apple_devices = [] arp_scan_results = self.ArpScan.scan(network_interface, timeout, retry) if len(arp_scan_results) > 0: for device in arp_scan_results: if "Apple" in device['vendor']: apple_devices.append([ device['ip-address'], device['mac-address'], device['vendor'] ]) else: self.Base.print_error( "Could not find devices in local network on interface: ", network_interface) exit(2) return apple_devices except KeyboardInterrupt: self.Base.print_info("Exit") exit(0) # endregion # region Find Apple devices in local network with nmap def find_apple_devices_with_nmap(self, network_interface): try: local_network_devices = [] apple_devices = [] local_network = self.Base.get_netiface_first_ip(network_interface) + "-" + \ self.Base.get_netiface_last_ip(network_interface).split('.')[3] nmap_process = sub.Popen([ 'nmap ' + local_network + ' -n -O --osscan-guess -T5 -e ' + network_interface + ' -oX ' + current_path + '/nmap_local_network.xml' ], shell=True, stdout=sub.PIPE) nmap_process.wait() nmap_report = ET.parse(current_path + "/nmap_local_network.xml") root_tree = nmap_report.getroot() for element in root_tree: if element.tag == "host": state = element.find('status').attrib['state'] if state == 'up': ip_address = "" mac_address = "" description = "" for address in element.findall('address'): if address.attrib['addrtype'] == 'ipv4': ip_address = address.attrib['addr'] if address.attrib['addrtype'] == 'mac': mac_address = address.attrib['addr'] try: description = address.attrib[ 'vendor'] + " device" except KeyError: pass for os_info in element.find('os'): if os_info.tag == 'osmatch': try: description += ", " + os_info.attrib['name'] except TypeError: pass break local_network_devices.append( [ip_address, mac_address, description]) for network_device in local_network_devices: if "Apple" or "Mac OS" or "iOS" in network_device[2]: apple_devices.append(network_device) return apple_devices except OSError as e: if e.errno == errno.ENOENT: self.Base.print_error("Program: ", "nmap", " is not installed!") exit(1) else: self.Base.print_error( "Something went wrong while trying to run ", "`nmap`") exit(2) except KeyboardInterrupt: self.Base.print_info("Exit") exit(0)
def start(): """ Initializes inspector by spawning a number of background threads. Returns the host state once all background threats are started. """ # Read from home directory the user_key. If non-existent, get one from # cloud. config_dict = utils.get_user_config() utils.log('[MAIN] Starting.') # Set up environment state = HostState() state.user_key = config_dict['user_key'].replace('-', '') state.secret_salt = config_dict['secret_salt'] state.host_mac = utils.get_my_mac() state.gateway_ip, _, state.host_ip = utils.get_default_route() assert utils.is_ipv4_addr(state.gateway_ip) assert utils.is_ipv4_addr(state.host_ip) state.packet_processor = PacketProcessor(state) utils.log('Initialized:', state.__dict__) # Start web API webserver.start_thread(state) # Continously discover devices arp_scan_thread = ArpScan(state) arp_scan_thread.start() # Continously discover ports via SYN scans syn_scan_thread = SynScan(state) syn_scan_thread.start() # # Continuously gather SSDP data # netdisco_thread = NetdiscoWrapper(state) # netdisco_thread.start() # Continuously capture packets packet_capture_thread = PacketCapture(state) packet_capture_thread.start() # Continously spoof ARP if '--no_spoofing' not in sys.argv: arp_spoof_thread = ArpSpoof(state) arp_spoof_thread.start() # Suppress scapy warnings try: logging.getLogger("scapy.runtime").setLevel(logging.ERROR) except Exception: pass # Suppress flask messages try: logging.getLogger('werkzeug').setLevel(logging.ERROR) except Exception: pass # Insert a dash every four characters to make user-key easier to type pretty_user_key = '' for (ix, char) in enumerate(state.user_key): if (ix > 0) and (ix % 4 == 0): pretty_user_key += '-' pretty_user_key += char print( 'Ready. To test if the API works, visit http://127.0.0.1:46241/get_device_list' ) return state
arp_path = project_root_path + "/Scripts/ARP/" path.append(arp_path) from base import Base from network import ARP_raw, Sniff_raw from tm import ThreadManager from arp_scan import ArpScan from socket import socket, AF_PACKET, SOCK_RAW from time import sleep from argparse import ArgumentParser # endregion # region Check user and platform Base = Base() ArpScan = ArpScan() Sniff = Sniff_raw() TM = ThreadManager(2) Base.check_user() Base.check_platform() # endregion # region Parse script arguments parser = ArgumentParser(description='Network conflict creator script') parser.add_argument('-i', '--interface', type=str, help='Set interface name for listen and send packets') parser.add_argument('-t',
while data_[i] != '|': strlen += data_[i] i += 1 istrlen = int(strlen) if istrlen + 2 + len(strlen) == len(data_): data_ = data_[4:] break if len(data_) > 0: data_out = ArpScan.analyze(data_) data_out_ = "|" data_out_ += str(len(data_out)) data_out_ += "|" data_out_ += data_out connection.sendall(data_out_.encode("utf-8")) finally: # Clean up the connection connection.close() if __name__ == "__main__": arp_init.init() ArpDump.printout("Starting daemon...") ArpScan.start() ArpDump.printout("Starting the server...") run()