def run(self):
        while True:
            index, hosts_quantity, host = self.queue.get()
            host_ip = host.get("ip")
            host_port = str(host.get("port"))

            port_postfix = "Default"
            if not self.ports and host_port:
                port_postfix = host_port
            if self.ports:
                port_postfix = str(self.ports)
            current_time = datetime.now().strftime("%H:%M:%S")
            print(
                f"тнХ Current scan host ({index}/{hosts_quantity}): {host_ip}:{port_postfix} (started at: {str(current_time)})"
            )
            nm = NmapConnector()
            nm.scan(
                host=host_ip,
                arguments=self.arguments,
                ports=(self.ports or host_port),
                sudo=self.sudo,
            )
            results = nm.get_results()
            if not results.get(host_ip):
                self.queue.task_done()
                return {}
            if results.get(host_ip).values():
                NmapProcessingResults.RESULTS.update(
                    {host_ip: results.get(host_ip)})
            self.queue.task_done()
Beispiel #2
0
    def run_script(host_info, nse_script, host_timeout=60):
        if not (isinstance(nse_script, str) and
                (nse_script.endswith(".nse") or nse_script.endswith(".lua"))):
            return
        nmap_script_name = nse_script.split(".")[0]
        script_path = (Path(".").joinpath(
            DefaultValues.CUSTOM_SCRIPTS_DIRECTORY).joinpath(
                DefaultValues.NSE_SCRIPTS_DIRECTORY).joinpath(nse_script))
        nm = NmapConnector()
        nm.scan(
            host=host_info.get("ip"),
            arguments=
            f"-Pn -sV -T4 --host-timeout {int(host_timeout)*1000}ms --script=./{str(script_path)}",
            ports=str(host_info.get("port")),
            sudo=False,
        )
        results = nm.get_results()

        script_execution_res = {}
        host_scan_results = results.get(host_info.get("ip"))
        if not host_scan_results:
            return
        host_scan_tcp = host_scan_results.get("tcp")
        if not host_scan_tcp:
            return
        for port, info in host_scan_tcp.items():
            script_list = info.get("script")
            if not script_list:
                continue
            script_info = script_list.get(nmap_script_name)
            if not script_info:
                continue
            script_execution_res.update({port: script_info})
        return script_execution_res
Beispiel #3
0
def setup_module() -> None:
    """
    Initialize HTTPServer for test NmapConnector scanning
    and NmapConnector for various tests
    :return:
    """
    global server_v4
    server_v4 = HTTPServer(
        (NmapTestDefaultValues.HOST4, NmapTestDefaultValues.PORT4),
        SimpleHTTPRequestHandler,
    )
    s_v4 = Thread(target=server_v4.serve_forever, daemon=True)
    s_v4.start()

    global server_v6
    server_v6 = HTTPServer6(
        (NmapTestDefaultValues.HOST6, NmapTestDefaultValues.PORT6),
        SimpleHTTPRequestHandler,
    )
    s_v6 = Thread(target=server_v6.serve_forever, daemon=True)
    s_v6.start()

    global nm
    nm = NmapConnector()

    global empty_nm
    empty_nm = NmapConnector()

    global nm_v4
    nm_v4 = NmapConnector()

    global nm_v6
    nm_v6 = NmapConnector()
Beispiel #4
0
    def run(self) -> None:
        """
        Run Nmap process
        :return: None
        """

        # Note: we use 'while True' with queue checker inside to prevent
        # process dying at the beginning, because we start with empty
        # queue

        while True:
            if self.queue.empty():
                # Wait while queue will get some tasks to do
                sleep(NmapProcessingDefaultManagerValues.EMPTY_QUEUE_POLLING_RATE)
                continue
            try:
                # Poll with POLLING_RATE interval
                sleep(NmapProcessingDefaultManagerValues.POLLING_RATE)

                # Get host info from queue
                index, host = self.queue.get()
                if (index, host) == (None, None):
                    self.queue.task_done()
                    return

                host_ip = host.get("ip", "")
                host_port = host.get("port", "")
                port_postfix = "Default"

                if not self.ports and host_port:
                    port_postfix = host_port
                if self.ports:
                    port_postfix = self.ports

                print(
                    f"тнХ "
                    f"Current scan host ({index}/{self.quantity}): "
                    f"{host_ip}:{port_postfix} "
                    f"(started at: {str(datetime.now().strftime('%H:%M:%S'))})"
                )

                nm = NmapConnector()
                nm.scan(
                    host=host_ip,
                    arguments=self.arguments,
                    ports=self.ports or str(host_port),
                    sudo=self.sudo,
                )

                results = nm.get_results()
                if results.get(host_ip).values():
                    self.results_pool.update({host_ip: results.get(host_ip)})
            except:
                pass
            self.queue.task_done()
            if self.queue.empty():
                return
Beispiel #5
0
    def run_script(host_info, nse_script, host_timeout=60) -> dict or None:
        """
        This function and class provide methods to run custom .nse
        scripts on particular hosts. Note - this scripts will be
        executed one by one for every host. Arguments of script
        execution can be fixed in Nmap connector call.
        :param host_info: information about current host
        :param nse_script: .nse script to run on host
        :param host_timeout: maximum timeout in seconds per host scan
        :return: results of script execution
        """
        if not (isinstance(nse_script, str) and
                (nse_script.endswith(".nse") or nse_script.endswith(".lua"))):
            return
        nmap_script_name = PurePath(nse_script).stem
        script_path = (Path(".").joinpath(
            DefaultValues.CUSTOM_SCRIPTS_DIRECTORY).joinpath(
                DefaultValues.NSE_SCRIPTS_DIRECTORY).joinpath(nse_script))
        nm = NmapConnector()
        nm.scan(
            host=host_info.get("ip"),
            arguments=
            f"-Pn -sV -T4 --host-timeout {int(host_timeout)*1000}ms --script=./{str(script_path)}",
            ports=str(host_info.get("port")),
            sudo=False,
        )
        results = nm.get_results()

        script_execution_res = {}
        host_scan_results = results.get(host_info.get("ip"))
        if not host_scan_results:
            return
        host_scan_tcp = host_scan_results.get("tcp")
        if not host_scan_tcp:
            return
        for port, info in host_scan_tcp.items():
            script_list = info.get("script")
            if not script_list:
                continue
            script_info = script_list.get(nmap_script_name)
            if not script_info:
                continue
            script_execution_res.update({port: script_info})
        return script_execution_res
Beispiel #6
0
def test_nmapconnector_init_error() -> None:
    """
    Raise NmapConnectorInitError and check output of it
    :return:
    """
    with patch(
            "grinder.nmapconnector.NmapConnector.__init__",
            side_effect=NmapConnectorInitError("test"),
    ):
        with raises(NmapConnectorInitError) as init_error:
            NmapConnector()
        assert "Error occured in Nmap Connector module: test" == str(
            init_error.value)
Beispiel #7
0
def test_nmapconnector_init() -> None:
    """
    Check if we can successfully create new NmapConnector instance
    :return:
    """
    NmapConnector()