Exemplo n.º 1
0
def wrap_file_in_preferred_encoding(f):
    """Wrap an open file to automatically decode its contents when reading from
    the encoding given by locale.getpreferredencoding, or just return the file
    if that doesn't work.

    The nmap executable will write its output in whatever the system encoding
    is. Nmap's output is usually all ASCII, but time zone it prints can be in a
    different encoding. If it is not decoded correctly it will be displayed as
    garbage characters. This function assists in reading the Nmap output. We
    don't know for sure what the encoding used is, but we take a best guess and
    decode the output into a proper unicode object so that the screen display
    and XML writer interpret it correctly."""

    try:
        preferredencoding = locale.getpreferredencoding()
    except locale.Error:
        # This can happen if the LANG environment variable is set to something
        # weird.
        preferredencoding = None

    if preferredencoding is not None:
        try:
            reader = codecs.getreader(preferredencoding)
            return reader(f, "replace")
        except LookupError:
            # The lookup failed. This can happen if the preferred encoding is
            # unknown ("X-MAC-KOREAN" has been observed). Ignore it and return
            # the unwrapped file.
            log.debug("Unknown encoding \"%s\"." % preferredencoding)

    return f
Exemplo n.º 2
0
    def kill(self):
        """Kill the nmap subprocess."""
        from time import sleep

        log.debug(">>> Killing scan process %s" % self.command_process.pid)

        if sys.platform != "win32":
            try:
                from signal import SIGTERM, SIGKILL
                os.kill(self.command_process.pid, SIGTERM)
                for i in range(10):
                    sleep(0.5)
                    if self.command_process.poll() is not None:
                        # Process has been TERMinated
                        break
                else:
                    log.debug(">>> SIGTERM has not worked even after waiting for 5 seconds. Using SIGKILL.")  # noqa
                    os.kill(self.command_process.pid, SIGKILL)
                    self.command_process.wait()
            except Exception:
                pass
        else:
            try:
                import ctypes
                ctypes.windll.kernel32.TerminateProcess(
                        int(self.command_process._handle), -1)
            except Exception:
                pass
Exemplo n.º 3
0
 def close(self):
     """Clean up temporary files."""
     self.stdout_file.close()
     for filename in self.temporary_filenames:
         log.debug("Remove temporary diff file %s." % filename)
         os.remove(filename)
     self.temporary_filenames = []
Exemplo n.º 4
0
    def match_option(self, option):
        log.debug("Match option: %s" % option)

        if option == "*" or option == "":
            return True

        # NOTE: Option matching treats "_" and "-" the same, just like the
        # optcmp function in utils.cc . Also, option matching is
        # case-sensitive.
        option = option.replace("_", "-")

        ops = NmapOptions()
        ops.parse_string(self.parsed_scan.get_nmap_command())

        if "(" in option and ")" in option:
            # The syntax allows matching option arguments as
            # "opt:option_name(value)".  Since we've received only the
            # "option_name(value)" part, we need to parse it.
            optname = option[:option.find("(")]
            optval = option[option.find("(") + 1:option.find(")")]

            val = ops["--" + optname]
            if val is None:
                val = ops["-" + optname]
            if val is None:
                return False
            return str(val) == optval or str(val) == optval
        else:
            return (ops["--" + option] is not None or
                    ops["-" + option] is not None)
Exemplo n.º 5
0
 def close(self):
     """Clean up temporary files."""
     self.stdout_file.close()
     for filename in self.temporary_filenames:
         log.debug("Remove temporary diff file %s." % filename)
         os.remove(filename)
     self.temporary_filenames = []
Exemplo n.º 6
0
    def refresh_diff(self, widget):
        """This method is called whenever the diff output might have changed,
        such as when a different scan was selected in one of the choosers."""
        log.debug("Refresh diff.")

        if (self.ndiff_process is not None and
                self.ndiff_process.poll() is None):
            # Put this in the list of old processes we keep track of.
            self.old_processes.append(self.ndiff_process)
            self.ndiff_process = None

        scan_a = self.scan_chooser_a.parsed_scan
        scan_b = self.scan_chooser_b.parsed_scan

        if scan_a is None or scan_b is None:
            self.diff_view.clear()
        else:
            try:
                self.ndiff_process = zenmapCore.Diff.ndiff(scan_a, scan_b)
            except OSError as e:
                alert = HIGAlertDialog(
                    message_format=_("Error running ndiff"),
                    secondary_text=_(
                        "There was an error running the ndiff program.\n\n"
                        ) + str(e).decode(sys.getdefaultencoding(), "replace"))
                alert.run()
                alert.destroy()
            else:
                self.progress.show()
                if self.timer_id is None:
                    self.timer_id = gobject.timeout_add(
                        NDIFF_CHECK_TIMEOUT, self.check_ndiff_process)
Exemplo n.º 7
0
    def refresh_output(self, widget = None):
        """Update the output from the latest output of the command associated
        with this view, as set by set_command_execution. It has no effect if no
        command has been set."""
        log.debug("Refresh nmap output")

        if self.command_execution is None:
            return

        # Seek to the end of the most recent read.
        self.command_execution.stdout_file.seek(self.output_file_pointer)
        pos = self.command_execution.stdout_file.tell()
        new_output = self.command_execution.stdout_file.read()
        self.output_file_pointer = self.command_execution.stdout_file.tell()
        # print "read %d -> %d %d" % (pos, self.output_file_pointer, len(new_output))

        v_adj = self.scrolled.get_vadjustment()
        if new_output and v_adj is not None:
            # Find out if the view is already scrolled to the bottom.
            at_end = (v_adj.value >= v_adj.upper - v_adj.page_size)

            buf = self.text_view.get_buffer()
            prev_end_mark = buf.create_mark(None, buf.get_end_iter(), left_gravity = True)
            buf.insert(buf.get_end_iter(), new_output)
            # Highlight the new text.
            self.apply_highlighting(buf.get_iter_at_mark(prev_end_mark), buf.get_end_iter())

            if at_end:
                # If we were already scrolled to the bottom, scroll back to the
                # bottom again. Also do it in an idle handler in case the added
                # text causes a scroll bar to appear and reflow the text, making
                # the text a bit taller.
                self.text_view.scroll_mark_onscreen(self.end_mark)
                gobject.idle_add(lambda: self.text_view.scroll_mark_onscreen(self.end_mark))
Exemplo n.º 8
0
    def get_script_list(self, rules, callback):
        """Start an Nmap subprocess in the background with
        "--script-help=<rules> -oX -", and set it up to call the given callback
        when finished."""

        ops = NmapOptions()
        ops.executable = paths_config.nmap_command_path
        ops["--script-help"] = rules
        ops["-oX"] = "-"
        command_string = ops.render_string()
        # Separate stderr to avoid breaking XML parsing with "Warning: File
        # ./nse_main.lua exists, but Nmap is using...".
        stderr = tempfile.TemporaryFile(mode="rb",
                                        prefix=APP_NAME +
                                        "-script-help-stderr-")
        log.debug("Script interface: running %s" % repr(command_string))
        nmap_process = NmapCommand(command_string)
        try:
            nmap_process.run_scan(stderr=stderr)
        except Exception as e:
            callback(False, None)
            stderr.close()
            return
        stderr.close()

        self.script_list_widget.set_sensitive(False)

        gobject.timeout_add(self.NMAP_DELAY, self.script_list_timer_callback,
                            nmap_process, callback)
Exemplo n.º 9
0
 def __get_it(self, p_name, default):
     try:
         return config_parser.get(self.section_name, p_name)
     except (NoOptionError, NoSectionError):
         log.debug(">>> Using default \"%s\" for \"%s\"." %
                   (default, p_name))
         return default
Exemplo n.º 10
0
    def run_scan(self, stderr = None):
        """Run the command represented by this class."""

        # We don't need a file name for stdout output, just a handle. A
        # TemporaryFile is deleted as soon as it is closed, and in Unix is
        # unlinked immediately after creation so it's not even visible.
        f = tempfile.TemporaryFile(mode = "rb", prefix = APP_NAME + "-stdout-")
        self.stdout_file = wrap_file_in_preferred_encoding(f)
        if stderr is None:
            stderr = f

        search_paths = self.get_path()
        env = dict(os.environ)
        env["PATH"] = search_paths
        log.debug("PATH=%s" % env["PATH"])

        command_list = self.ops.render()
        log.debug("Running command: %s" % repr(command_list))

        startupinfo = None
        if sys.platform == "win32":
            # This keeps a terminal window from opening.
            startupinfo = subprocess.STARTUPINFO()
            try:
                startupinfo.dwFlags |= subprocess._subprocess.STARTF_USESHOWWINDOW
            except AttributeError:
                # This name is used before Python 2.6.5.
                startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW

        self.command_process = subprocess.Popen(command_list, bufsize=1,
                                     stdin=subprocess.PIPE,
                                     stdout=f,
                                     stderr=stderr,
                                     startupinfo = startupinfo,
                                     env=env)
Exemplo n.º 11
0
 def match_profile(self, profile):
     log.debug("Match profile: %s" % profile)
     log.debug("Comparing: %s == %s ??" % (
         str(self.parsed_scan.profile_name).lower(),
         "*%s*" % profile.lower()))
     return (profile == "*" or profile == "" or
             profile.lower() in str(self.parsed_scan.profile_name).lower())
Exemplo n.º 12
0
    def __init__(self, filename_a, filename_b, temporary_filenames=[]):
        self.temporary_filenames = temporary_filenames

        search_paths = get_path()
        env = dict(os.environ)
        env["PATH"] = search_paths
        if getattr(sys, "frozen", None) == "macosx_app":
            # These variables are set by py2app, but they can interfere with
            # Ndiff because Ndiff is also a Python application. Without removing
            # these, Ndiff will attempt to run using the py2app-bundled Python
            # library, and may run into version or architecture mismatches.
            if env.has_key("PYTHONPATH"):
                del env["PYTHONPATH"]
            if env.has_key("PYTHONHOME"):
                del env["PYTHONHOME"]

        command_list = [paths_config.ndiff_command_path, "--verbose", "--", filename_a, filename_b]
        self.stdout_file = tempfile.TemporaryFile(mode="rb", prefix=APP_NAME + "-ndiff-", suffix=".xml")

        log.debug("Running command: %s" % repr(command_list))
        # See zenmapCore.NmapCommand.py for an explanation of the shell argument.
        subprocess.Popen.__init__(
            self,
            command_list,
            stdout=self.stdout_file,
            stderr=self.stdout_file,
            env=env,
            shell=(sys.platform == "win32"),
        )
Exemplo n.º 13
0
Arquivo: Diff.py Projeto: idkqh7/nmap
    def __init__(self, filename_a, filename_b, temporary_filenames=[]):
        self.temporary_filenames = temporary_filenames

        search_paths = get_path()
        env = dict(os.environ)
        env["PATH"] = search_paths
        if getattr(sys, "frozen", None) == "macosx_app":
            # These variables are set by py2app, but they can interfere with
            # Ndiff because Ndiff is also a Python application. Without removing
            # these, Ndiff will attempt to run using the py2app-bundled Python
            # library, and may run into version or architecture mismatches.
            if env.has_key("PYTHONPATH"):
                del env["PYTHONPATH"]
            if env.has_key("PYTHONHOME"):
                del env["PYTHONHOME"]

        command_list = [
            paths_config.ndiff_command_path, "--verbose", "--", filename_a,
            filename_b
        ]
        self.stdout_file = tempfile.TemporaryFile(mode="rb",
                                                  prefix=APP_NAME + "-ndiff-",
                                                  suffix=".xml")

        log.debug("Running command: %s" % repr(command_list))
        # See zenmapCore.NmapCommand.py for an explanation of the shell argument.
        subprocess.Popen.__init__(self,
                                  command_list,
                                  stdout=self.stdout_file,
                                  stderr=self.stdout_file,
                                  env=env,
                                  shell=(sys.platform == "win32"))
Exemplo n.º 14
0
 def __get_it(self, p_name, default):
     try:
         return config_parser.get(self.section_name, p_name)
     except (NoOptionError, NoSectionError):
         log.debug(
                 ">>> Using default \"%s\" for \"%s\"." % (default, p_name))
         return default
Exemplo n.º 15
0
def wrap_file_in_preferred_encoding(f):
    """Wrap an open file to automatically decode its contents when reading from
    the encoding given by locale.getpreferredencoding, or just return the file
    if that doesn't work.

    The nmap executable will write its output in whatever the system encoding
    is. Nmap's output is usually all ASCII, but time zone it prints can be in a
    different encoding. If it is not decoded correctly it will be displayed as
    garbage characters. This function assists in reading the Nmap output. We
    don't know for sure what the encoding used is, but we take a best guess and
    decode the output into a proper unicode object so that the screen display
    and XML writer interpret it correctly."""

    try:
        preferredencoding = locale.getpreferredencoding()
    except locale.Error:
        # This can happen if the LANG environment variable is set to something
        # weird.
        preferredencoding = None

    if preferredencoding is not None:
        try:
            reader = codecs.getreader(preferredencoding)
            return reader(f, "replace")
        except LookupError:
            # The lookup failed. This can happen if the preferred encoding is
            # unknown ("X-MAC-KOREAN" has been observed). Ignore it and return
            # the unwrapped file.
            log.debug("Unknown encoding \"%s\"." % preferredencoding)

    return f
Exemplo n.º 16
0
    def kill(self):
        """Kill the nmap subprocess."""
        from time import sleep

        log.debug(">>> Killing scan process %s" % self.command_process.pid)

        if sys.platform != "win32":
            try:
                from signal import SIGTERM, SIGKILL
                os.kill(self.command_process.pid, SIGTERM)
                for i in range(10):
                    sleep(0.5)
                    if self.command_process.poll() is not None: # Process has been TERMinated
                        break
                else:
                    log.debug(">>> SIGTERM has not worked even after waiting for 5 seconds. Using SIGKILL.")
                    os.kill(self.command_process.pid, SIGKILL)
                    self.command_process.wait()
            except:
                pass
        else:
            try:
                import ctypes
                ctypes.windll.kernel32.TerminateProcess(
                        int(self.command_process._handle), -1)
            except:
                pass
Exemplo n.º 17
0
    def verify_execution(self):
        """This is a callback that is called periodically to refresh the output
        check whether any running scans have finished. The timer that schedules
        the callback is started in execute_command. When there are no more
        running scans, this function returns True so that it won't be scheduled
        again."""
        self.scan_result.refresh_nmap_output()

        finished_jobs = []
        for scan in self.jobs:
            try:
                alive = scan.scan_state()
                if alive:
                    continue
            except:
                log.debug("Scan terminated unexpectedly: %s" % scan.command)
                self.scans_store.fail_running_scan(scan)
            else:
                log.debug("Scan finished: %s" % scan.command)
                self.load_from_command(scan)
                scan.close()
            self.update_cancel_button()
            finished_jobs.append(scan)

        # Remove finished jobs from the job list
        for finished in finished_jobs:
            self.jobs.remove(finished)
        del(finished_jobs)

        return len(self.jobs) != 0
    def refresh_output(self, widget = None):
        """Update the output from the latest output of the command associated
        with this view, as set by set_command_execution. It has no effect if no
        command has been set."""
        log.debug("Refresh nmap output")

        if self.command_execution is None:
            return

        # Seek to the end of the most recent read.
        self.command_execution.stdout_file.seek(self.output_file_pointer)
        pos = self.command_execution.stdout_file.tell()
        new_output = self.command_execution.stdout_file.read()
        self.output_file_pointer = self.command_execution.stdout_file.tell()
        # print "read %d -> %d %d" % (pos, self.output_file_pointer, len(new_output))

        v_adj = self.scrolled.get_vadjustment()
        if new_output and v_adj is not None:
            # Find out if the view is already scrolled to the bottom.
            at_end = (v_adj.value >= v_adj.upper - v_adj.page_size)

            buf = self.text_view.get_buffer()
            prev_end_mark = buf.create_mark(None, buf.get_end_iter(), left_gravity = True)
            buf.insert(buf.get_end_iter(), new_output)
            # Highlight the new text.
            self.apply_highlighting(buf.get_iter_at_mark(prev_end_mark), buf.get_end_iter())

            if at_end:
                # If we were already scrolled to the bottom, scroll back to the
                # bottom again. Also do it in an idle handler in case the added
                # text causes a scroll bar to appear and reflow the text, making
                # the text a bit taller.
                self.text_view.scroll_mark_onscreen(self.end_mark)
                gobject.idle_add(lambda: self.text_view.scroll_mark_onscreen(self.end_mark))
Exemplo n.º 19
0
 def match_profile(self, profile):
     log.debug("Match profile: %s" % profile)
     log.debug("Comparing: %s == %s ??" % (
         str(self.parsed_scan.profile_name).lower(),
         "*%s*" % profile.lower()))
     return (profile == "*" or profile == "" or
             profile.lower() in str(self.parsed_scan.profile_name).lower())
Exemplo n.º 20
0
    def verify_execution(self):
        """This is a callback that is called periodically to refresh the output
        check whether any running scans have finished. The timer that schedules
        the callback is started in execute_command. When there are no more
        running scans, this function returns True so that it won't be scheduled
        again."""
        self.scan_result.refresh_nmap_output()

        finished_jobs = []
        for scan in self.jobs:
            try:
                alive = scan.scan_state()
                if alive:
                    continue
            except:
                log.debug("Scan terminated unexpectedly: %s" % scan.command)
                self.scans_store.fail_running_scan(scan)
            else:
                log.debug("Scan finished: %s" % scan.command)
                self.load_from_command(scan)
                scan.close()
            self.update_cancel_button()
            finished_jobs.append(scan)

        # Remove finished jobs from the job list
        for finished in finished_jobs:
            self.jobs.remove(finished)
        del (finished_jobs)

        return len(self.jobs) != 0
Exemplo n.º 21
0
    def match_option(self, option):
        log.debug("Match option: %s" % option)

        if option == "*" or option == "":
            return True

        ops = NmapOptions()
        ops.parse_string(self.parsed_scan.get_nmap_command())

        if "(" in option and ")" in option:
            # The syntax allows matching option arguments as
            # "opt:option_name(value)".  Since we've received only the
            # "option_name(value)" part, we need to parse it.
            optname = option[:option.find("(")]
            optval = option[option.find("(") + 1:option.find(")")]

            val = ops["--" + optname]
            if val is None:
                val = ops["-" + optname]
            if val is None:
                return False
            return str(val) == optval or str(val) == optval
        else:
            return (ops["--" + option] is not None
                    or ops["-" + option] is not None)
Exemplo n.º 22
0
    def read(self, filename):
        log.debug(">>> Trying to parse: %s" % filename)

        if ConfigParser.read(self, filename):
            self.filenames = filename

        return self.filenames
Exemplo n.º 23
0
    def match_option(self, option):
        log.debug("Match option: %s" % option)

        if option == "*" or option == "":
            return True

        # NOTE: Option matching treats "_" and "-" the same, just like the
        # optcmp function in utils.cc . Also, option matching is
        # case-sensitive.
        option = option.replace("_", "-")

        ops = NmapOptions()
        ops.parse_string(self.parsed_scan.get_nmap_command())

        if "(" in option and ")" in option:
            # The syntax allows matching option arguments as
            # "opt:option_name(value)".  Since we've received only the
            # "option_name(value)" part, we need to parse it.
            optname = option[:option.find("(")]
            optval = option[option.find("(") + 1:option.find(")")]

            val = ops["--" + optname]
            if val is None:
                val = ops["-" + optname]
            if val is None:
                return False
            return str(val) == optval or str(val) == optval
        else:
            return (ops["--" + option] is not None
                    or ops["-" + option] is not None)
Exemplo n.º 24
0
    def refresh_diff(self, widget):
        """This method is called whenever the diff output might have changed,
        such as when a different scan was selected in one of the choosers."""
        log.debug("Refresh diff.")

        if (self.ndiff_process is not None and
                self.ndiff_process.poll() is None):
            # Put this in the list of old processes we keep track of.
            self.old_processes.append(self.ndiff_process)
            self.ndiff_process = None

        scan_a = self.scan_chooser_a.parsed_scan
        scan_b = self.scan_chooser_b.parsed_scan

        if scan_a is None or scan_b is None:
            self.diff_view.clear()
        else:
            try:
                self.ndiff_process = zenmapCore.Diff.ndiff(scan_a, scan_b)
            except OSError, e:
                alert = HIGAlertDialog(
                    message_format=_("Error running ndiff"),
                    secondary_text=_(
                        "There was an error running the ndiff program.\n\n"
                        ) + str(e).decode(sys.getdefaultencoding(), "replace"))
                alert.run()
                alert.destroy()
            else:
Exemplo n.º 25
0
    def read(self, filename):
        log.debug(">>> Trying to parse: %s" % filename)

        if ConfigParser.read(self, filename):
            self.filenames = filename

        return self.filenames
Exemplo n.º 26
0
 def update_script_list_from_spec(self, spec):
     """Callback method for user edit delay."""
     log.debug("Script interface: update_script_list_from_spec %s" %
               repr(spec))
     if spec:
         self.get_script_list(spec, self.update_script_list_cb)
     else:
         self.refresh_list_scripts([])
Exemplo n.º 27
0
def _destroy_callback(window):
    open_windows.remove(window)
    if len(open_windows) == 0:
        gtk.main_quit()
    try:
        from zenmapCore.UmitDB import UmitDB
    except ImportError, e:
        log.debug(">>> Not cleaning up database: %s." % str(e))
Exemplo n.º 28
0
    def sanity_settings(self, settings):
        log.debug(">>> Sanitize %s" % str(settings))

        tuple_regex = "[\(\[]\s?(\d+)\s?,\s?(\d+)\s?,\s?(\d+)\s?[\)\]]"
        if isinstance(settings, basestring):
            settings = [int(t) for t in re.findall(tuple_regex, settings)[0]]

        return settings
Exemplo n.º 29
0
Arquivo: App.py Projeto: mogigoma/nmap
def _destroy_callback(window):
    open_windows.remove(window)
    if len(open_windows) == 0:
        gtk.main_quit()
    try:
        from zenmapCore.UmitDB import UmitDB
    except ImportError, e:
        log.debug(">>> Not cleaning up database: %s." % str(e))
Exemplo n.º 30
0
 def initial_script_list_cb(self, status, process):
     log.debug("Script interface: initial_script_list_cb %s" % repr(status))
     for child in self.script_list_container.get_children():
         self.script_list_container.remove(child)
     if status and self.handle_initial_script_list_output(process):
         self.script_list_container.pack_start(self.script_list_widget)
     else:
         self.script_list_container.pack_start(self.nmap_error_widget)
Exemplo n.º 31
0
Arquivo: App.py Projeto: mogigoma/nmap
def safe_shutdown(signum, stack):
    """Kills any active scans/tabs and shuts down the application."""
    log.debug("\n\n%s\nSAFE SHUTDOWN!\n%s\n" % ("#" * 30, "#" * 30))
    log.debug("SIGNUM: %s" % signum)

    for window in open_windows:
        window.scan_interface.kill_all_scans()

    sys.exit(signum)
Exemplo n.º 32
0
def safe_shutdown(signum, stack):
    """Kills any active scans/tabs and shuts down the application."""
    log.debug("\n\n%s\nSAFE SHUTDOWN!\n%s\n" % ("#" * 30, "#" * 30))
    log.debug("SIGNUM: %s" % signum)

    for window in open_windows:
        window.scan_interface.kill_all_scans()

    sys.exit(signum)
Exemplo n.º 33
0
    def handle_update_script_list_output(self, process):
        process.stdout_file.seek(0)
        try:
            handler = ScriptHelpXMLContentHandler.parse_nmap_script_help(
                process.stdout_file)
        except (ValueError, xml.sax.SAXParseException) as e:
            log.debug("--script-help parse exception: %s" % str(e))
            return False

        self.refresh_list_scripts(handler.script_filenames)
Exemplo n.º 34
0
def _destroy_callback(window):
    open_windows.remove(window)
    if len(open_windows) == 0:
        gtk.main_quit()
    try:
        from zenmapCore.UmitDB import UmitDB
    except ImportError as e:
        log.debug(">>> Not cleaning up database: %s." % str(e))
    else:
        # Cleaning up data base
        UmitDB().cleanup(SearchConfig().converted_save_time)
Exemplo n.º 35
0
    def match_target(self, target):
        log.debug("Match target: %s" % target)

        for spec in self.parsed_scan.get_targets():
            if target in spec:
                return True
        else:
            # We search the (rDNS) hostnames list
            for host in self.parsed_scan.get_hosts():
                if HostSearch.match_target(host, target):
                    return True
        return False
Exemplo n.º 36
0
    def match_target(self, target):
        log.debug("Match target: %s" % target)

        for spec in self.parsed_scan.get_targets():
            if target in spec:
                return True
        else:
            # We search the (rDNS) hostnames list
            for host in self.parsed_scan.get_hosts():
                if HostSearch.match_target(host, target):
                    return True
        return False
Exemplo n.º 37
0
 def add_to_port_list(self, p):
     entry = [
         None, "",
         findout_service_icon(p),
         int(p.get('portid', '0')),
         p.get('protocol', ''),
         p.get('port_state', ''),
         p.get('service_name', ''),
         get_version_string(p)
     ]
     log.debug(">>> Add Port: %s" % entry)
     self.port_list.append(entry)
Exemplo n.º 38
0
 def add_to_host_list(self, host, p):
     entry = [
         "",
         findout_service_icon(p), host,
         host.get_hostname(),
         int(p.get('portid', '0')),
         p.get('protocol', ''),
         p.get('port_state', ''),
         get_version_string(p)
     ]
     log.debug(">>> Add Host: %s" % entry)
     self.host_list.append(entry)
Exemplo n.º 39
0
 def save_changes(self):
     if self.filenames:
         log.debug("saving to %s" % self.filenames)
         try:
             fp = open(self.filenames, 'w')
         except Exception as e:
             self.failed = e
             log.error(">>> Can't save to %s: %s" % (self.filenames, e))
             return
         self.write(fp)
         self.failed = False
     else:
         log.debug(">>> UmitConfigParser can't save changes: no filename")
Exemplo n.º 40
0
 def store_result(self, scan_interface):
     """Stores the network inventory into the database."""
     log.debug(">>> Saving result into database...")
     try:
         scan_interface.inventory.save_to_db()
     except Exception as e:
         alert = HIGAlertDialog(
                 message_format=_("Can't save to database"),
                 secondary_text=_("Can't store unsaved scans to the "
                     "recent scans database:\n%s") % str(e))
         alert.run()
         alert.destroy()
         log.debug(">>> Can't save result to database: %s." % str(e))
Exemplo n.º 41
0
 def save_changes(self):
     if self.filenames:
         log.debug("saving to %s" % self.filenames)
         try:
             fp = open(self.filenames, 'w')
         except Exception as e:
             self.failed = e
             log.error(">>> Can't save to %s: %s" % (self.filenames, e))
             return
         self.write(fp)
         self.failed = False
     else:
         log.debug(">>> UmitConfigParser can't save changes: no filename")
Exemplo n.º 42
0
 def add_to_host_list(self, host, p):
     entry = [
         "",
         findout_service_icon(p),
         host,
         host.get_hostname(),
         int(p.get("portid", "0")),
         p.get("protocol", ""),
         p.get("port_state", ""),
         get_version_string(p),
     ]
     log.debug(">>> Add Host: %s" % entry)
     self.host_list.append(entry)
Exemplo n.º 43
0
 def add_to_port_list(self, p):
     entry = [
         None,
         "",
         findout_service_icon(p),
         int(p.get("portid", "0")),
         p.get("protocol", ""),
         p.get("port_state", ""),
         p.get("service_name", ""),
         get_version_string(p),
     ]
     log.debug(">>> Add Port: %s" % entry)
     self.port_list.append(entry)
Exemplo n.º 44
0
    def match_port(self, ports, port_state):
        log.debug("Match port:%s" % ports)

        # Transform a comma-delimited string containing ports into a list
        ports = filter(lambda not_empty: not_empty, ports.split(","))

        for host in self.parsed_scan.get_hosts():
            for port in ports:
                if not HostSearch.match_port(host.get_ports(), port, port_state):
                    break
            else:
                return True
        else:
            return False
Exemplo n.º 45
0
    def __init__(self, search_directory, file_extensions=["usr"]):
        SearchResult.__init__(self)
        log.debug(">>> SearchDir initialized")
        self.search_directory = search_directory

        if isinstance(file_extensions, StringTypes):
            self.file_extensions = file_extensions.split(";")
        elif isinstance(file_extensions, list):
            self.file_extensions = file_extensions
        else:
            raise Exception(
                    "Wrong file extension format! '%s'" % file_extensions)

        log.debug(">>> Getting directory's scan results")
        self.scan_results = []
        files = []
        for ext in self.file_extensions:
            files += glob(os.path.join(self.search_directory, "*.%s" % ext))

        log.debug(">>> Scan results at selected directory: %s" % files)
        for scan_file in files:
            log.debug(">>> Retrieving scan result %s" % scan_file)
            if os.access(scan_file, os.R_OK) and os.path.isfile(scan_file):

                try:
                    parsed = NmapParser()
                    parsed.parse_file(scan_file)
                except:
                    pass
                else:
                    self.scan_results.append(parsed)
Exemplo n.º 46
0
    def __init__(self, search_directory, file_extensions=["usr"]):
        SearchResult.__init__(self)
        log.debug(">>> SearchDir initialized")
        self.search_directory = search_directory

        if isinstance(file_extensions, StringTypes):
            self.file_extensions = file_extensions.split(";")
        elif isinstance(file_extensions, list):
            self.file_extensions = file_extensions
        else:
            raise Exception("Wrong file extension format! '%s'" %
                            file_extensions)

        log.debug(">>> Getting directory's scan results")
        self.scan_results = []
        files = []
        for ext in self.file_extensions:
            files += glob(os.path.join(self.search_directory, "*.%s" % ext))

        log.debug(">>> Scan results at selected directory: %s" % files)
        for scan_file in files:
            log.debug(">>> Retrieving scan result %s" % scan_file)
            if os.access(scan_file, os.R_OK) and os.path.isfile(scan_file):

                try:
                    parsed = NmapParser()
                    parsed.parse_file(scan_file)
                except Exception:
                    pass
                else:
                    self.scan_results.append(parsed)
Exemplo n.º 47
0
class Throbber(gtk.Image):
    """This is a little progress indicator that animates while a scan is
    running."""
    try:
        still = gtk.gdk.pixbuf_new_from_file(
            os.path.join(Path.pixmaps_dir, "throbber.png"))
        anim = gtk.gdk.PixbufAnimation(
            os.path.join(Path.pixmaps_dir, "throbber.gif"))
    except Exception as e:
        log.debug("Error loading throbber images: %s." % str(e))
        still = None
        anim = None

    def __init__(self):
        gtk.Image.__init__(self)
        self.set_from_pixbuf(self.still)
        self.animating = False

    def go(self):
        # Don't change anything if we're already animating.
        if not self.animating and self.anim is not None:
            self.set_from_animation(self.anim)
        self.animating = True

    def stop(self):
        if self.animating and self.still is not None:
            self.set_from_pixbuf(self.still)
        self.animating = False
Exemplo n.º 48
0
 def __create_tab(self, tab_name, section_name, tab):
     log.debug(">>> Tab name: %s" % tab_name)
     log.debug(">>>Creating profile editor section: %s" % section_name)
     vbox = HIGVBox()
     if tab.notscripttab:  # if notscripttab is set
         table = HIGTable()
         table.set_row_spacings(2)
         section = HIGSectionLabel(section_name)
         vbox._pack_noexpand_nofill(section)
         vbox._pack_noexpand_nofill(HIGSpacer(table))
         vbox.set_border_width(5)
         tab.fill_table(table, True)
     else:
         hbox = tab.get_hmain_box()
         vbox.pack_start(hbox, True, True, 0)
     self.notebook.append_page(vbox, gtk.Label(tab_name))
Exemplo n.º 49
0
 def __create_tab(self, tab_name, section_name, tab):
     log.debug(">>> Tab name: %s" % tab_name)
     log.debug(">>>Creating profile editor section: %s" % section_name)
     vbox = HIGVBox()
     if  tab.notscripttab: # if notscripttab is set
         table = HIGTable()
         table.set_row_spacings(2)
         section = HIGSectionLabel(section_name)
         vbox._pack_noexpand_nofill(section)
         vbox._pack_noexpand_nofill(HIGSpacer(table))
         vbox.set_border_width(5)
         tab.fill_table(table, True)
     else:
         hbox = tab.get_hmain_box()
         vbox.pack_start(hbox,True,True,0)
     self.notebook.append_page(vbox, gtk.Label(tab_name))
Exemplo n.º 50
0
    def filter_hosts(self, filter_string):
        start = time.clock()
        self.inventory.apply_filter(filter_string)
        filter_time = time.clock() - start
        # Update the gui
        start = time.clock()
        self.update_ui()
        gui_time = time.clock() - start

        if filter_time + gui_time > 0.0:
            log.debug("apply_filter %g ms  update_ui %g ms (%.0f%% filter)" %
                (filter_time * 1000.0, gui_time * 1000.0,
                100.0 * filter_time / (filter_time + gui_time)))

        self.filter_timeout_id = None
        return False
Exemplo n.º 51
0
    def start_scan_cb(self, widget=None):
        target = self.toolbar.selected_target
        command = self.command_toolbar.command
        profile = self.toolbar.selected_profile

        log.debug(">>> Start Scan:")
        log.debug(">>> Target: '%s'" % target)
        log.debug(">>> Profile: '%s'" % profile)
        log.debug(">>> Command: '%s'" % command)

        if target != "":
            try:
                self.toolbar.add_new_target(target)
            except IOError, e:
                # We failed to save target_list.txt; treat it as read-only.
                # Probably it's owned by root and this is a normal user.
                log.debug(">>> Error saving %s: %s" % (Path.target_list, str(e)))
Exemplo n.º 52
0
    def kill(self):
        """Kill the nmap subprocess."""
        log.debug(">>> Killing scan process %s" % self.command_process.pid)

        if sys.platform != "win32":
            try:
                from signal import SIGKILL
                os.kill(self.command_process.pid, SIGKILL)
                self.command_process.wait()
            except:
                pass
        else:
            try:
                import ctypes
                ctypes.windll.kernel32.TerminateProcess(int(self.command_process._handle), -1)
            except:
                pass
Exemplo n.º 53
0
Arquivo: UmitDB.py Projeto: Tom9X/nmap
    def cleanup(self, save_time):
        log.debug(">>> Cleaning up data base.")
        log.debug(">>> Removing results olders than %s seconds" % save_time)
        self.cursor.execute("SELECT scans_id FROM scans WHERE date < ?", (time() - save_time,))

        for sid in [sid[0] for sid in self.cursor.fetchall()]:
            log.debug(">>> Removing results with scans_id %s" % sid)
            self.cursor.execute("DELETE FROM scans WHERE scans_id = ?", (sid, ))
        else:
            connection.commit()
            log.debug(">>> Data base successfully cleaned up!")
Exemplo n.º 54
0
Arquivo: UmitDB.py Projeto: Tom9X/nmap
    def __init__(self, **kargs):
        Table.__init__(self, "scans")
        if "scans_id" in kargs.keys():
            self.scans_id = kargs["scans_id"]
        else:
            log.debug(">>> Creating new scan result entry at data base")
            fields = ["scan_name", "nmap_xml_output", "date"]

            for k in kargs.keys():
                if k not in fields:
                    raise Exception("Wrong table field passed to creation method. '%s'" % k)

            if "nmap_xml_output" not in kargs.keys() or not kargs["nmap_xml_output"]:
                raise Exception("Can't save result without xml output")

            if not self.verify_digest(md5(kargs["nmap_xml_output"]).hexdigest()):
                raise Exception("XML output registered already!")

            self.scans_id = self.insert(**kargs)
Exemplo n.º 55
0
    def add_profile(self, profile_name, **attributes):
        """Add a profile with the given name and attributes to the collection of
        profiles. If a profile with the same name exists, it is not overwritten,
        and the method returns immediately. The backing file for the profiles is
        automatically updated."""

        log.debug(">>> Add Profile '%s': %s" % (profile_name, attributes))

        try:
            self.add_section(profile_name)
        except DuplicateSectionError:
            return None

        # Set each of the attributes ("command", "description") in the
        # ConfigParser.
        for attr in attributes:
            self._set_it(profile_name, attr, attributes[attr])

        self.save_changes()
Exemplo n.º 56
0
    def kill(self):
        """Kill the nmap subprocess."""
        log.debug(">>> Killing scan process %s" % self.command_process.pid)

        if sys.platform != "win32":
            try:
                from signal import SIGKILL
                os.kill(self.command_process.pid, SIGKILL)
            except:
                pass
        else:
            try:
                # Not sure if this works. Must research a bit more about this
                # subprocess's method to see how it works.
                # In the meantime, this should not raise any exception because
                # we don't care if it killed the process as it never killed it anyway.
                from subprocess import TerminateProcess
                TerminateProcess(self.command_process._handle, 0)
            except:
                pass
Exemplo n.º 57
0
    def __init__(self, filename_a, filename_b, temporary_filenames=[]):
        self.temporary_filenames = temporary_filenames

        search_paths = get_path()
        env = dict(os.environ)
        env["PATH"] = search_paths
        if "Zenmap.app" in sys.executable:
            # These vars are set by the launcher, but they can interfere with
            # Ndiff because Ndiff is also a Python application. Without
            # removing these, Ndiff will attempt to run using the
            # bundled Python library, and may run into version or
            # architecture mismatches.
            if "PYTHONPATH" in env:
                del env["PYTHONPATH"]
            if "PYTHONHOME" in env:
                del env["PYTHONHOME"]

        command_list = [
                paths_config.ndiff_command_path,
                "--verbose",
                "--",
                filename_a,
                filename_b
                ]
        self.stdout_file = tempfile.TemporaryFile(
                mode="rb",
                prefix=APP_NAME + "-ndiff-",
                suffix=".xml"
                )

        log.debug("Running command: %s" % repr(command_list))
        # shell argument explained in zenmapCore.NmapCommand.py
        subprocess.Popen.__init__(
                self,
                command_list,
                stdout=self.stdout_file,
                stderr=self.stdout_file,
                env=env,
                shell=(sys.platform == "win32")
                )
Exemplo n.º 58
0
    def __init__(self, command):
        """Initialize an Nmap command. This creates temporary files for
        redirecting the various types of output and sets the backing
        command-line string."""
        self.command = command
        self.command_process = None

        self.stdout_file = None

        self.ops = NmapOptions()
        self.ops.parse_string(command)
        # Replace the executable name with the value of nmap_command_path.
        self.ops.executable = paths_config.nmap_command_path

        # Normally we generate a random temporary filename to save XML output
        # to. If we find -oX or -oA, the user has chosen his own output file.
        # Set self.xml_is_temp to False and don't delete the file when we're
        # done.
        self.xml_is_temp = True
        self.xml_output_filename = None
        if self.ops["-oX"]:
            self.xml_is_temp = False
            self.xml_output_filename = self.ops["-oX"]
        if self.ops["-oA"]:
            self.xml_is_temp = False
            self.xml_output_filename = self.ops["-oA"] + ".xml"

        # Escape '%' to avoid strftime expansion.
        for op in ("-oA", "-oX", "-oG", "-oN", "-oS"):
            if self.ops[op]:
                self.ops[op] = escape_nmap_filename(self.ops[op])

        if self.xml_is_temp:
            self.xml_output_filename = tempfile.mktemp(
                    prefix=APP_NAME + "-", suffix=".xml")
            self.ops["-oX"] = escape_nmap_filename(self.xml_output_filename)

        log.debug(">>> Temporary files:")
        log.debug(">>> XML OUTPUT: %s" % self.xml_output_filename)