示例#1
0
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()
示例#2
0
 def start_spoofing(self, vIP, tIP):
     victims = [vic.strip() for vic in vIP.split(',')]
     if ARPSpoofFrame.are_valid_ip_address(
             victims) and ARPSpoofFrame.are_valid_ip_address([tIP]):
         self.button_ARP.configure(text="Stop ARP Spoofing",
                                   command=lambda: self.stop_spoofing())
         self.controller.is_spoofing = True
         self.arp = ArpSpoof()
         for vic in victims:
             self.arp.attach(vic)
         self.arp.attach(tIP)
         self.controller.output.update_status('ARP Spoofing ' + vIP +
                                              " and " + tIP,
                                              append=False)
         self.button_start_injecting_extracting.configure(state=NORMAL)
         self.controller.notebook.tab(self.controller.notebook.index(
             self.controller.tabs['InjectorExtractorFrame']),
                                      state=NORMAL)
         self.arp.start()
     else:
         tkMessageBox.showerror(
             "Specify the target and victim",
             "Please specify the IP addresses of the victim and target and check whether the IP "
             "address notation is correct")
示例#3
0
    def initialize(self, result):
        global arpspoof
        global dnsspoof
        self.running = True
        arpspoof = ArpSpoof("ArpSpoof", self.config, self.device)
        dnsspoof = DnsSpoof("DnsSpoof", self.config, self.device)
        arp_status = {}
        dns_status = {}
        global tarp
        global tdns
        tarp = threading.Thread(target=arpspoof.initialize, args=(arp_status,))
        tarp.start()
        time.sleep(3)
        tdns = threading.Thread(target=dnsspoof.initialize, args=(dns_status,))
        tdns.start()

        tarp.join()
        tdns.join()
from PacketHandler.Injectors.accept_encoding_substituter import AcceptEncodingSubstituter
from PacketHandler.packet_sniffer import PacketSniffer
from arp_spoof import ArpSpoof
from ip_to_mac_mapper import IpToMacMapper

# Mock the network mapping
mapping = IpToMacMapper().set_all({
    '192.168.56.101': '08:00:27:B0:A1:AB',
    '192.168.56.102': '08:00:27:C6:A4:61',
    '192.168.56.104': '08:00:27:67:EA:43',
})

arp = ArpSpoof()
arp.attach('192.168.56.101')
arp.attach('192.168.56.102')
arp.start()

packet_sniffer = PacketSniffer(['192.168.56.103'], mapping, 'enp0s3')
packet_sniffer.packet_injectors.append(AcceptEncodingSubstituter(
))  # Prevent the pages from being served with compression
packet_sniffer.start()

arp.join()
packet_sniffer.join()

# @todo convert into an automated test
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))
    def initialize(self, result):
        self.running = True
        global arpspoof
        arpspoof = ArpSpoof("ArpSpoof", self.config, self.device)
        target = self.device['ip']

        if self.device["vulnerable_ports"] is None:
            result.update({"status": "no open ports"})
            return

        if "tcp" not in self.device["vulnerable_ports"].keys():
            result.update({"status": "no open ports"})
            return

        if "open" not in self.device["vulnerable_ports"]["tcp"].keys():
            result.update({"status": "no open ports"})
            return

        if self.config['vulnerability_validation']:
            arp_status = {}
            tarp = threading.Thread(target=arpspoof.initialize,
                                    args=(arp_status, ))
            tarp.start()
            time.sleep(5)

        tstatus = threading.Thread(target=self.deviceStatus, args=(result, ))
        tstatus.start()

        packetDataSize = self.config['data_size']  #bytes
        packetCount = self.config['packet_count']
        interval = self.config['interval']
        start_time = time.time()
        for port in self.device["vulnerable_ports"]["tcp"]["open"]:
            command = "hping3 -V -c %d -i %s -d %d -S -p %d -s %d -a %s %s" % (
                packetCount, interval, packetDataSize, port, port, target,
                target)
            p = subprocess.Popen(command, stdout=subprocess.PIPE, shell=True)
            (output, err) = p.communicate()
            # This makes the wait possible
            p.wait()

        result.update({
            "directed_traffic(bytes/sec)":
            (packetCount * (packetDataSize + 40)) / (time.time() - start_time),
            "attack_time:": (time.time() - start_time)
        })
        self.running = False
        tstatus.join()

        if self.config['vulnerability_validation']:
            arpspoof.shutdown()
            tarp.join()

        vulnerable = False
        if self.config['vulnerability_validation']:
            file_prefix = self.config["file_prefix"]
            filename = 'results/' + self.device[
                'time'] + '/' + file_prefix + self.device[
                    'macAddress'] + '.pcap'
            pcap = rdpcap(filename)
            sessions = pcap.sessions()
            for session in sessions:
                for packet in sessions[session]:
                    try:
                        if packet['IP'].src == packet['IP'].dst and packet[
                                'TCP'].flags == 12:
                            if packet['TCP'].dport in self.device["vulnerable_ports"]["tcp"]["open"] or packet['TCP'].sport in \
                                    self.device["vulnerable_ports"]["tcp"]["open"]:
                                vulnerable = True
                    except:
                        pass

        if vulnerable:
            result.update({"status": "vulnerable"})
        else:
            result.update({"status": "not_vulnerable"})
        return
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
示例#9
0
class ARPSpoofFrame(Frame):
    def __init__(self, parent, controller):
        Frame.__init__(self, parent)
        self.controller = controller
        self.parent = parent
        self.arp = None

        label = Label(
            self,
            text='Identify the target and victim who need to be spoofed',
            font=controller.h2_font)
        label.pack(side='top', pady=20)

        label_ip_victim = Label(
            self, text="Victim(s) IP Address (sep =','): ").pack(pady=5)
        self.entry_ip_victim = Entry(self, width=35)
        self.entry_ip_victim.pack()

        label_ip_target = Label(self, text='Target IP Address: ').pack(pady=5)
        self.entry_ip_target = Entry(self, width=35)
        self.entry_ip_target.pack()

        self.button_ARP = Button(
            self,
            text="Start ARP Spoofing",
            command=lambda: self.start_spoofing(self.entry_ip_victim.get(),
                                                self.entry_ip_target.get()))
        self.button_ARP.pack(pady=10)

        self.button_reset_config = Button(self,
                                          text="Reset Configuration",
                                          command=lambda: self.reset_config())
        self.button_reset_config.pack(pady=7)

        self.button_start_injecting_extracting = Button(
            self,
            text="Start Injecting and/or Extracting",
            command=lambda: controller.show_frame("InjectorExtractorFrame",
                                                  update=True),
            state=DISABLED)
        self.button_start_injecting_extracting.pack(pady=7)

    def update(self):
        if self.controller.is_spoofing:
            self.stop_spoofing(status_update=False)
        if self.controller.victims is not None:
            self.entry_ip_victim.delete(0, END)  # clear entry
            num_items = len(self.controller.victims)
            self.entry_ip_victim.insert(0, self.controller.victims[0])
            if num_items > 1:
                for i in range(1, num_items):
                    self.entry_ip_victim.insert(
                        END, ", ".__add__(self.controller.victims[i]))
        if self.controller.target is not None:
            self.entry_ip_target.delete(0, END)
            self.entry_ip_target.insert(0, self.controller.target)

    def reset_config(self):
        if self.controller.is_spoofing:
            self.stop_spoofing()
            self.controller.output.update_status(
                "ARP Spoofing thread terminated", append=False)
        self.controller.show_frame("LocalNetworkScanFrame",
                                   select=True,
                                   update=False)
        self.controller.notebook.tab(self.controller.notebook.index(
            self.controller.tabs['ARPSpoofFrame']),
                                     state=DISABLED)

    def start_spoofing(self, vIP, tIP):
        victims = [vic.strip() for vic in vIP.split(',')]
        if ARPSpoofFrame.are_valid_ip_address(
                victims) and ARPSpoofFrame.are_valid_ip_address([tIP]):
            self.button_ARP.configure(text="Stop ARP Spoofing",
                                      command=lambda: self.stop_spoofing())
            self.controller.is_spoofing = True
            self.arp = ArpSpoof()
            for vic in victims:
                self.arp.attach(vic)
            self.arp.attach(tIP)
            self.controller.output.update_status('ARP Spoofing ' + vIP +
                                                 " and " + tIP,
                                                 append=False)
            self.button_start_injecting_extracting.configure(state=NORMAL)
            self.controller.notebook.tab(self.controller.notebook.index(
                self.controller.tabs['InjectorExtractorFrame']),
                                         state=NORMAL)
            self.arp.start()
        else:
            tkMessageBox.showerror(
                "Specify the target and victim",
                "Please specify the IP addresses of the victim and target and check whether the IP "
                "address notation is correct")

    def stop_spoofing(self, status_update=True):
        self.button_ARP.configure(
            text="Start ARP Spoofing",
            command=lambda: self.start_spoofing(self.entry_ip_victim.get(),
                                                self.entry_ip_target.get()))
        if status_update:
            self.controller.output.update_status(
                "ARP Spoofing thread terminated", append=False)
        self.button_start_injecting_extracting.configure(state=DISABLED)
        self.controller.notebook.tab(self.controller.notebook.index(
            self.controller.tabs['InjectorExtractorFrame']),
                                     state=DISABLED)
        self.controller.is_spoofing = False
        self.arp.keep_alive = False

    @staticmethod
    def are_valid_ip_address(addresses):
        for add in addresses:
            if not (ARPSpoofFrame.is_valid_ipv4_address(add)
                    or ARPSpoofFrame.is_valid_ipv6_address(add)):
                return False
        return True

    # Copied from tzot's answer - https://stackoverflow.com/questions/319279/how-to-validate-ip-address-in-python
    @staticmethod
    def is_valid_ipv4_address(address):
        try:
            socket.inet_pton(socket.AF_INET, address)
        except AttributeError:  # no inet_pton here, sorry
            try:
                socket.inet_aton(address)
            except socket.error:
                return False
            return address.count('.') == 3
        except socket.error:  # not a valid address
            return False
        return True

    @staticmethod
    def is_valid_ipv6_address(address):
        try:
            socket.inet_pton(socket.AF_INET6, address)
        except socket.error:  # not a valid address
            return False
        return True
示例#10
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