Esempio n. 1
0
    def execute_command(self, command, target = None, profile = None):
        """Run the given Nmap command. Add it to the list of running scans.
        Schedule a timer to refresh the output and check the scan for
        completion."""
        command_execution = NmapCommand(command)
        command_execution.profile = profile

        try:
            command_execution.run_scan()
        except Exception, e:
            text = str(e)
            if isinstance(e, OSError):
                # Handle ENOENT specially.
                if e.errno == errno.ENOENT:
                    # nmap_command_path comes from zenmapCore.NmapCommand.
                    text += "\n\n" + _("This means that the nmap executable was not found in your system PATH, which is") + "\n\n" + os.getenv("PATH", _("<undefined>"))
                    path_env = os.getenv("PATH")
                    if path_env is None:
                        default_paths = []
                    else:
                        default_paths = path_env.split(os.pathsep)
                    extra_paths = get_extra_executable_search_paths()
                    extra_paths = [p for p in extra_paths if p not in default_paths]
                    if len(extra_paths) > 0:
                        if len(extra_paths) == 1:
                            text += "\n\n" + _("plus the extra directory")
                        else:
                            text += "\n\n" + _("plus the extra directories")
                        text += "\n\n" + os.pathsep.join(extra_paths)
            warn_dialog = HIGAlertDialog(message_format=_("Error executing command"),
                secondary_text=text, type=gtk.MESSAGE_ERROR)
            warn_dialog.run()
            warn_dialog.destroy()
            return
Esempio n. 2
0
    def send_report(self, widget):
        bug_register = BugRegister()
        description_text = self.description
        private = False
        if self.email != "":
            description_text += "\n\n" + self.email
            private = True
        report_url = bug_register.get_report_url(self.summary,
            description_text, private = private)

        # First we try reporting the bug with a web browser because that gives
        # better feedback on what happened. If that doesn't work try with
        # urllib2.
        try:
            webbrowser.open(report_url)
        except webbrowser.Error:
            try:
                urllib2.urlopen(report_url)
                ok_dialog = HIGAlertDialog(type=gtk.MESSAGE_INFO,
                    message_format=_("Bug reported"),
                    secondary_text=_("The bug was successfully reported."))
                ok_dialog.run()
                ok_dialog.destroy()
            except urllib2.URLError, e:
                cancel_dialog = HIGAlertDialog(type=gtk.MESSAGE_ERROR,
                    message_format=_("Bug not reported"),
                    secondary_text=_("This error occurred while trying to report the bug:\n\n" + str(e)))
                cancel_dialog.run()
                cancel_dialog.destroy()
Esempio n. 3
0
    def open_file(self, widget):
        file_chooser = ResultsFileSingleChooserDialog(_("Select Scan Result"))

        response = file_chooser.run()
        file_chosen = file_chooser.get_filename()
        file_chooser.destroy()
        if response == gtk.RESPONSE_OK:
            try:
                parser = NmapParser()
                parser.parse_file(file_chosen)
            except xml.sax.SAXParseException, e:
                alert = HIGAlertDialog(
                    message_format='<b>%s</b>' % _('Error parsing file'),
                    secondary_text=_(
                        "The file is not an Nmap XML output file. "
                        "The parsing error that occurred was\n%s") % str(e))
                alert.run()
                alert.destroy()
                return False
            except Exception, e:
                alert = HIGAlertDialog(
                        message_format='<b>%s</b>' % _(
                            'Cannot open selected file'),
                        secondary_text=_("""\
                            This error occurred while trying to open the file:
                            %s""") % str(e))
                alert.run()
                alert.destroy()
                return False
Esempio n. 4
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:
Esempio n. 5
0
def run():
    if os.name == "posix":
        signal.signal(signal.SIGHUP, safe_shutdown)
    signal.signal(signal.SIGTERM, safe_shutdown)
    signal.signal(signal.SIGINT, safe_shutdown)

    DEVELOPMENT = os.environ.get(APP_NAME.upper() + "_DEVELOPMENT", False)
    if not DEVELOPMENT:
        install_excepthook()

    zenmapCore.I18N.install_gettext(Path.locale_dir)

    try:
        # Create the ~/.zenmap directory by copying from the system-wide
        # template directory.
        zenmapCore.Paths.create_user_config_dir(Path.user_config_dir, Path.config_dir)
    except (IOError, OSError), e:
        error_dialog = HIGAlertDialog(message_format = _("Error creating the per-user configuration directory"),
            secondary_text = _("""\
There was an error creating the directory %s or one of the files in it. \
The directory is created by copying the contents of %s. \
The specific error was\n\
\n\
%s\n\
\n\
%s needs to create this directory to store information such as the list of \
scan profiles. Check for access to the directory and try again.\
""") % (repr(Path.user_config_dir), repr(Path.config_dir), repr(str(e)), APP_DISPLAY_NAME))
        error_dialog.run()
        error_dialog.destroy()
        sys.exit(1)
Esempio n. 6
0
File: App.py Progetto: mogigoma/nmap
    def excepthook(type, value, tb):
        import traceback

        traceback.print_exception(type, value, tb)

        # Cause an exception if PyGTK can't open a display. Normally this just
        # produces a warning, but the lack of a display eventually causes a
        # segmentation fault. See http://live.gnome.org/PyGTK/WhatsNew210.
        import warnings
        warnings.filterwarnings("error", module="gtk")
        import gtk
        warnings.resetwarnings()

        gtk.gdk.threads_enter()

        from zenmapGUI.higwidgets.higdialogs import HIGAlertDialog
        from zenmapGUI.CrashReport import CrashReport
        if type == ImportError:
            d = HIGAlertDialog(type=gtk.MESSAGE_ERROR,
                message_format=_("Import error"),
                secondary_text=_("""A required module was not found.

""" + unicode(value)))
            d.run()
            d.destroy()
        else:
            c = CrashReport(type, value, tb)
            c.show_all()
            gtk.main()

        gtk.gdk.threads_leave()

        gtk.main_quit()
Esempio n. 7
0
File: App.py Progetto: mogigoma/nmap
    def __init__(self):
        warning_text = _('''You are trying to run %s with a non-root user!

Some %s options need root privileges to work.''') % (
            APP_DISPLAY_NAME, NMAP_DISPLAY_NAME)

        HIGAlertDialog.__init__(self, message_format=_('Non-root user'),
                                secondary_text=warning_text)
Esempio n. 8
0
    def __init__(self):
        warning_text = _('''You are trying to run %s with a non-root user!

Some %s options need root privileges to work.''') % (
            APP_DISPLAY_NAME, NMAP_DISPLAY_NAME)

        HIGAlertDialog.__init__(self, message_format=_('Non-root user'),
                                secondary_text=warning_text)
Esempio n. 9
0
    def check_ndiff_process(self):
        """Check if the ndiff subprocess is done and show the diff if it is.
        Also remove any finished processes from the old process list."""
        # Check if any old background processes have finished.
        for p in self.old_processes[:]:
            if p.poll() is not None:
                p.close()
                self.old_processes.remove(p)

        if self.ndiff_process is not None:
            # We're running the most recent scan. Check if it's done.
            status = self.ndiff_process.poll()

            if status is None:
                # Keep calling this function on a timer until the process
                # finishes.
                self.progress.pulse()
                return True

            if status == 0 or status == 1:
                # Successful completion.
                try:
                    diff = self.ndiff_process.get_scan_diff()
                except zenmapCore.Diff.NdiffParseException as e:
                    alert = HIGAlertDialog(
                        message_format=_("Error parsing ndiff output"),
                        secondary_text=str(e))
                    alert.run()
                    alert.destroy()
                else:
                    self.diff_view.show_diff(diff)
            else:
                # Unsuccessful completion.
                error_text = _(
                    "The ndiff process terminated with status code %d."
                    ) % status
                stderr = self.ndiff_process.stderr.read()
                if len(stderr) > 0:
                    error_text += "\n\n" + stderr
                alert = HIGAlertDialog(
                    message_format=_("Error running ndiff"),
                    secondary_text=error_text)
                alert.run()
                alert.destroy()

            self.progress.hide()
            self.ndiff_process.close()
            self.ndiff_process = None

        if len(self.old_processes) > 0:
            # Keep calling this callback.
            return True
        else:
            # All done.
            self.timer_id = None
            return False
Esempio n. 10
0
    def __response_cb(self, widget, response_id):
        """Intercept the "response" signal to check if someone used the "By
        extension" file type with an unknown extension."""
        if response_id == gtk.RESPONSE_OK and self.get_filetype() is None:
            ext = self.__get_extension()
            if ext == "":
                filename = self.get_filename() or ""
                dir, basename = os.path.split(filename)
                alert = HIGAlertDialog(
                    message_format=_("No filename extension"),
                    secondary_text=_("""\
The filename "%s" does not have an extension, \
and no specific file type was chosen.
Enter a known extension or select the file type from the list.""" % basename))

            else:
                alert = HIGAlertDialog(
                    message_format=_("Unknown filename extension"),
                    secondary_text=_("""\
There is no file type known for the filename extension "%s".
Enter a known extension or select the file type from the list.\
""") % self.__get_extension())
            alert.run()
            alert.destroy()
            # Go back to the dialog.
            self.emit_stop_by_name("response")
    def save_profile(self, widget):
        if self.overwrite:
            self.profile.remove_profile(self.profile_name)
        profile_name = self.profile_name_entry.get_text()
        if profile_name == "":
            alert = HIGAlertDialog(
                message_format=_("Unnamed profile"),
                secondary_text=_(
                    "You must provide a name \
for this profile."
                ),
            )
            alert.run()
            alert.destroy()

            self.profile_name_entry.grab_focus()

            return None

        command = self.ops.render_string()

        buf = self.profile_description_text.get_buffer()
        description = buf.get_text(buf.get_start_iter(), buf.get_end_iter())

        try:
            self.profile.add_profile(profile_name, command=command, description=description)
        except ValueError:
            alert = HIGAlertDialog(
                message_format=_("Disallowed profile name"),
                secondary_text=_(
                    'Sorry, the name "%s" \
is not allowed due to technical limitations. (The underlying ConfigParser \
used to store profiles does not allow it.) Choose a different \
name.'
                    % profile_name
                ),
            )
            alert.run()
            alert.destroy()
            return

        self.scan_interface.toolbar.profile_entry.update()
        self.destroy()
Esempio n. 12
0
def run():
    if os.name == "posix":
        signal.signal(signal.SIGHUP, safe_shutdown)
    signal.signal(signal.SIGTERM, safe_shutdown)
    signal.signal(signal.SIGINT, safe_shutdown)

    try:
        # Create the ~/.zenmap directory by copying from the system-wide
        # template directory.
        zenmapCore.Paths.create_user_config_dir(Path.user_config_dir, Path.config_dir)
    except (IOError, OSError), e:
        error_dialog = HIGAlertDialog(message_format = _("Error creating the per-user configuration directory"),
            secondary_text = _("""\
There was an error creating the directory %s or one of the files in it. \
The directory is created by copying the contents of %s. \
The specific error was\n\
\n\
%s\n\
\n\
%s needs to create this directory to store information such as the list of \
scan profiles. Check for access to the directory and try again.\
""") % (Path.user_config_dir, Path.config_dir, str(e), APP_DISPLAY_NAME))
        error_dialog.run()
        error_dialog.destroy()
        sys.exit(1)
Esempio n. 13
0
    def __response_cb(self, widget, response_id):
        """Intercept the "response" signal to check if someone used the "By
        extension" file type with an unknown extension."""
        if response_id == gtk.RESPONSE_OK and self.get_filetype() is None:
            ext = self.__get_extension()
            if ext == "":
                filename = self.get_filename() or ""
                dir, basename = os.path.split(filename)
                alert = HIGAlertDialog(
                        message_format=_("No filename extension"),
                        secondary_text=_("""\
The filename "%s" does not have an extension, \
and no specific file type was chosen.
Enter a known extension or select the file type from the list.""" % basename))

            else:
                alert = HIGAlertDialog(
                        message_format=_("Unknown filename extension"),
                        secondary_text=_("""\
There is no file type known for the filename extension "%s".
Enter a known extension or select the file type from the list.\
""") % self.__get_extension())
            alert.run()
            alert.destroy()
            # Go back to the dialog.
            self.emit_stop_by_name("response")
Esempio n. 14
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)
    def start_search(self):
        if not self.options["search_db"] and not self.options["directory"]:
            d = HIGAlertDialog(
                message_format=_("No search method selected!"),
                secondary_text=_("%s can search results on directories or \
inside it's own database. Please, select a method by choosing a directory or by checking \
the search data base option at the 'Search options' tab before start the search"
                                 % APP_DISPLAY_NAME))
            d.run()
            d.destroy()
            return

        self.clear_result_list()

        matched = 0
        total = 0
        if self.options["search_db"]:
            total += len(self.search_db.get_scan_results())
            for result in self.search_db.search(**self.search_dict):
                self.append_result(result)
                matched += 1

        for search_dir in self.search_dirs.itervalues():
            total += len(search_dir.get_scan_results())
            for result in search_dir.search(**self.search_dict):
                self.append_result(result)
                matched += 1

        #total += len(self.search_tabs.get_scan_results())
        #for result in self.search_tabs.search(**self.search_dict):
        #    self.append_result(result)
        #    matched += 1

        self.search_window.set_label_text("Matched <b>%s</b> out of <b>%s</b> scans." % \
                                         (str(matched), str(total)))
Esempio n. 16
0
    def excepthook(type, value, tb):
        import traceback

        traceback.print_exception(type, value, tb)

        # Cause an exception if PyGTK can't open a display. Normally this just
        # produces a warning, but the lack of a display eventually causes a
        # segmentation fault. See http://live.gnome.org/PyGTK/WhatsNew210.
        warnings.filterwarnings("error", module="gtk")
        import gtk
        warnings.resetwarnings()

        gtk.gdk.threads_enter()

        from zenmapGUI.higwidgets.higdialogs import HIGAlertDialog
        from zenmapGUI.CrashReport import CrashReport
        if type == ImportError:
            d = HIGAlertDialog(
                type=gtk.MESSAGE_ERROR,
                message_format=_("Import error"),
                secondary_text=_("""A required module was not found.

""" + unicode(value)))
            d.run()
            d.destroy()
        else:
            c = CrashReport(type, value, tb)
            c.show_all()
            gtk.main()

        gtk.gdk.threads_leave()

        gtk.main_quit()
Esempio n. 17
0
 def help(self, widget):
     d = HIGAlertDialog(
         parent=self,
         message_format=_("Help not implemented"),
         secondary_text=_("Profile editor help is not implemented yet."))
     d.run()
     d.destroy()
Esempio n. 18
0
def run():
    if os.name == "posix":
        signal.signal(signal.SIGHUP, safe_shutdown)
    signal.signal(signal.SIGTERM, safe_shutdown)
    signal.signal(signal.SIGINT, safe_shutdown)

    DEVELOPMENT = os.environ.get(APP_NAME.upper() + "_DEVELOPMENT", False)
    if not DEVELOPMENT:
        install_excepthook()

    zenmapCore.I18N.install_gettext(Path.locale_dir)

    try:
        # Create the ~/.zenmap directory by copying from the system-wide
        # template directory.
        create_user_config_dir(Path.user_config_dir, Path.config_dir)
    except (IOError, OSError), e:
        error_dialog = HIGAlertDialog(
            message_format=_(
                "Error creating the per-user configuration directory"),
            secondary_text=_("""\
There was an error creating the directory %s or one of the files in it. \
The directory is created by copying the contents of %s. \
The specific error was

%s

%s needs to create this directory to store information such as the list of \
scan profiles. Check for access to the directory and try again.""") %
            (repr(Path.user_config_dir), repr(Path.config_dir), repr(
                str(e)), APP_DISPLAY_NAME))
        error_dialog.run()
        error_dialog.destroy()
        sys.exit(1)
Esempio n. 19
0
    def execute_command(self, command, target = None, profile = None):
        """Run the given Nmap command. Add it to the list of running scans.
        Schedule a timer to refresh the output and check the scan for
        completion."""
        command_execution = NmapCommand(command)
        command_execution.profile = profile

        try:
            command_execution.run_scan()
        except Exception, e:
            text = str(e)
            if isinstance(e, OSError):
                # Handle ENOENT specially.
                if e.errno == errno.ENOENT:
                    # nmap_command_path comes from zenmapCore.NmapCommand.
                    text += "\n\n" + _("This means that the nmap executable was not found in your system PATH, which is") + "\n\n" + os.getenv("PATH", _("<undefined>"))
                    path_env = os.getenv("PATH")
                    if path_env is None:
                        default_paths = []
                    else:
                        default_paths = path_env.split(os.pathsep)
                    extra_paths = get_extra_executable_search_paths()
                    extra_paths = [p for p in extra_paths if p not in default_paths]
                    if len(extra_paths) > 0:
                        if len(extra_paths) == 1:
                            text += "\n\n" + _("plus the extra directory")
                        else:
                            text += "\n\n" + _("plus the extra directories")
                        text += "\n\n" + os.pathsep.join(extra_paths)
            warn_dialog = HIGAlertDialog(message_format=_("Error executing command"),
                secondary_text=text, type=gtk.MESSAGE_ERROR)
            warn_dialog.run()
            warn_dialog.destroy()
            return
Esempio n. 20
0
    def save_profile(self, widget):
        if self.overwrite:
            self.profile.remove_profile(self.profile_name)
        profile_name = self.profile_name_entry.get_text()
        if profile_name == '':
            alert = HIGAlertDialog(message_format=_('Unnamed profile'),\
                                   secondary_text=_('You must provide a name \
for this profile.'                  ))
            alert.run()
            alert.destroy()

            self.profile_name_entry.grab_focus()

            return None

        command = self.constructor.get_command('%s')

        buf = self.profile_description_text.get_buffer()
        description = buf.get_text(buf.get_start_iter(),\
                                      buf.get_end_iter())

        self.profile.add_profile(profile_name,\
                                 command=command,\
                                 description=description,\
                                 options=self.constructor.get_options())

        self.scan_interface.toolbar.profile_entry.update()
        self.scan_interface.refresh_command(None)
        self.destroy()
    def profile_not_found_dialog(self):
        warn_dialog = HIGAlertDialog(message_format=_("Profile not found"),
                                     secondary_text=_("The profile name you \
selected/typed couldn't be found, and probably doesn't exist. Please, check the profile \
name and try again."),
                                     type=gtk.MESSAGE_QUESTION)
        warn_dialog.run()
        warn_dialog.destroy()
Esempio n. 22
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))
Esempio n. 23
0
 def execute_command(self, command, target=None, profile=None):
     """Run the given Nmap command. Add it to the list of running scans.
     Schedule a timer to refresh the output and check the scan for
     completion."""
     try:
         command_execution = NmapCommand(command)
     except IOError, e:
         warn_dialog = HIGAlertDialog(
                     message_format=_("Error building command"),
                     secondary_text=_("Error message: %s") % str(e),
                     type=gtk.MESSAGE_ERROR)
         warn_dialog.run()
         warn_dialog.destroy()
         return
    def execute_command(self, command, target=None, profile=None):
        """If scan state is alive and user responds OK, stop the currently active scan
        and allow creation of another, and if user responds Cancel, wait the current scan to finish.
        Invokes NmapCommand for execution. Verifies if a valid nmap executable exists in PATH, if not,
        displays error with the offending PATH. Refreshes and changes to nmap output view from given file."""
        command_execution = NmapCommand(command)
        command_execution.target = target
        command_execution.profile = profile

        try:
            command_execution.run_scan()
        except Exception, e:
            text = str(e)
            if type(e) == OSError:
                # Handle ENOENT specially.
                if e.errno == errno.ENOENT:
                    # nmap_command_path comes from zenmapCore.NmapCommand.
                    text += "\n\n" + _(
                        "This means that the nmap executable was not found in your system PATH, which is"
                    ) + "\n\n" + os.getenv("PATH", _("<undefined>"))
                    path_env = os.getenv("PATH")
                    if path_env is None:
                        default_paths = []
                    else:
                        default_paths = path_env.split(os.pathsep)
                    extra_paths = get_extra_executable_search_paths()
                    extra_paths = [
                        p for p in extra_paths if p not in default_paths
                    ]
                    if len(extra_paths) > 0:
                        if len(extra_paths) == 1:
                            text += "\n\n" + _("plus the extra directory")
                        else:
                            text += "\n\n" + _("plus the extra directories")
                        text += "\n\n" + os.pathsep.join(extra_paths)
            warn_dialog = HIGAlertDialog(
                message_format=_("Error executing command"),
                secondary_text=text,
                type=gtk.MESSAGE_ERROR)
            warn_dialog.run()
            warn_dialog.destroy()
            return
Esempio n. 25
0
def show_help():
    import six.moves.urllib.request, six.moves.urllib.parse, six.moves.urllib.error
    import webbrowser

    new = 0
    if sys.hexversion >= 0x2050000:
        new = 2

    doc_path = abspath(join(Path.docs_dir, "help.html"))
    url = "file:" + six.moves.urllib.request.pathname2url(fs_enc(doc_path))
    try:
        webbrowser.open(url, new=new)
    except OSError as e:
        d = HIGAlertDialog(parent=self,
                           message_format=_("Can't find documentation files"),
                           secondary_text=_("""\
There was an error loading the documentation file %s (%s). See the \
online documentation at %s.\
""") % (doc_path, six.text_type(e), APP_DOCUMENTATION_SITE))
        d.run()
        d.destroy()
Esempio n. 26
0
    def _load(self, scan_interface, filename=None, parsed_result=None):
        """Loads the scan from a file or from a parsed result into the given
        scan interface."""
        if not (filename or parsed_result):
            return None

        if filename:
            # Load scan result from file
            log.debug(">>> Loading file: %s" % filename)
            try:
                # Parse result
                scan_interface.load_from_file(filename)
            except Exception as e:
                alert = HIGAlertDialog(message_format=_('Error loading file'),
                                       secondary_text=str(e))
                alert.run()
                alert.destroy()
                return
            scan_interface.saved_filename = filename
        elif parsed_result:
            # Load scan result from parsed object
            scan_interface.load_from_parsed_result(parsed_result)
Esempio n. 27
0
    def __save_image_callback(self, widget):
        """
        """
        if self.__save_chooser is None:
            self.__save_chooser = SaveDialog()

        response = self.__save_chooser.run()

        if response == gtk.RESPONSE_OK:
            filename = self.__save_chooser.get_filename()
            filetype = self.__save_chooser.get_filetype()

            try:
                self.radialnet.save_drawing_to_file(filename, filetype)
            except Exception as e:
                alert = HIGAlertDialog(
                    parent=self.__save_chooser,
                    type=gtk.MESSAGE_ERROR,
                    message_format=_("Error saving snapshot"),
                    secondary_text=six.text_type(e))
                alert.run()
                alert.destroy()

        self.__save_chooser.hide()
Esempio n. 28
0
class ScanInterface(HIGVBox):
    """ScanInterface contains the scan toolbar and the scan results. Each
    ScanInterface represents a single NetworkInventory as well as a set of
    running scans."""

    # The time delay between when you stop typing a filter string and filtering
    # actually begins, in milliseconds.
    FILTER_DELAY = 1000

    def __init__(self):
        HIGVBox.__init__(self)

        # The borders are consuming too much space on Maemo. Setting it to
        # 0 pixels while on Maemo
        if is_maemo():
            self.set_border_width(0)

        self.set_spacing(0)

        # True if nothing has happened here page yet, i.e., it's okay to load a
        # scan from a file here.
        self.empty = True

        # The most recent name the inventory on this page has been saved under.
        self.saved_filename = None

        # The network inventory shown by this page. It may consist of multiple
        # scans.
        self.inventory = FilteredNetworkInventory()

        # The list of currently running scans (NmapCommand objects).
        self.jobs = []

        # The list of running and finished scans shown on the Nmap Output page.
        self.scans_store = ScansListStore()

        self.top_box = HIGVBox()

        self.__create_toolbar()
        self.__create_command_toolbar()

        self.select_default_profile()

        self.scan_result = ScanResult(self.inventory, self.scans_store,
                                      scan_interface=self)
        self.host_view_selection = self.scan_result.get_host_selection()
        self.service_view_selection = self.scan_result.get_service_selection()
        self.host_view_selection.connect(
                'changed', self.host_selection_changed)
        self.service_view_selection.connect(
                'changed', self.service_selection_changed)
        host_page = self.scan_result.scan_result_notebook.open_ports.host
        host_page.host_view.get_selection().connect(
                'changed', self.service_host_selection_changed)
        self.host_view_selection.connect(
                'changed', self.host_selection_changed)

        self.scan_result.scan_result_notebook.nmap_output.connect(
                "changed", self._displayed_scan_change_cb)
        self.scan_result.scan_result_notebook.scans_list.remove_button.connect(
                "clicked", self._remove_scan_cb)

        # The hosts dict maps hostnames (as returned by HostInfo.get_hostname)
        # to HostInfo objects.
        self.hosts = {}
        # The services dict maps service names ("http") to lists of dicts of
        # the form
        # {'host': <HostInfo object>, 'hostname': u'example.com',
        #  'port_state': u'open', 'portid': u'22', 'protocol': u'tcp',
        #  'service_conf': u'10', 'service_extrainfo': u'protocol 2.0',
        #  'service_method': u'probed', 'service_name': u'ssh',
        #  'service_product': u'OpenSSH', 'service_version': u'4.3'}
        # In other words each dict has the same keys as an entry in
        # HostInfo.ports, with the addition of "host" and "hostname" keys.
        self.services = {}

        self.top_box.set_border_width(6)
        self.top_box.set_spacing(5)

        self.top_box._pack_noexpand_nofill(self.toolbar)
        self.top_box._pack_noexpand_nofill(self.command_toolbar)

        self._pack_noexpand_nofill(self.top_box)
        self._pack_expand_fill(self.scan_result)

        self.scan_result.scan_result_notebook.scans_list.cancel_button.connect(
                "clicked", self._cancel_scans_list_cb)
        self.update_cancel_button()

        # Create the filter GUI
        self.filter_bar = FilterBar()
        self.pack_start(self.filter_bar, False, True, 0)
        self.filter_bar.set_no_show_all(True)

        self.filter_timeout_id = None

        self.filter_bar.connect("changed", self.filter_changed)
        self.scan_result.filter_toggle_button.connect("toggled",
            self.filter_toggle_toggled)
        self.scan_result.filter_toggle_button.show()

    def toggle_filter_bar(self):
        self.scan_result.filter_toggle_button.clicked()

    def filter_toggle_toggled(self, widget):
        if self.scan_result.filter_toggle_button.get_active():
            # Show the filter bar
            self.filter_bar.show()
            self.filter_bar.grab_focus()
            self.filter_hosts(self.filter_bar.get_filter_string())
        else:
            # Hide the filter bar
            self.filter_bar.hide()
            self.filter_hosts("")

        self.update_ui()

    def filter_changed(self, filter_bar):
        # Restart the timer to start the filter.
        if self.filter_timeout_id:
            gobject.source_remove(self.filter_timeout_id)
        self.filter_timeout_id = gobject.timeout_add(
                self.FILTER_DELAY, self.filter_hosts,
                filter_bar.get_filter_string())

    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

    def is_changed(self):
        """Return true if this window has unsaved changes."""
        for scan in self.inventory.get_scans():
            if scan.unsaved:
                return True
        return False
    changed = property(is_changed)

    def num_scans_running(self):
        return len(self.jobs)

    def select_default_profile(self):
        """Select a "default" profile. Currently this is defined to be the
        first profile."""
        if len(self.toolbar.profile_entry.get_model()) > 0:
            self.toolbar.profile_entry.set_active(0)

    def go_to_host(self, hostname):
        """Scroll the text output to the appearance of the named host."""
        self.scan_result.scan_result_notebook.nmap_output.nmap_output.go_to_host(hostname)  # noqa

    def __create_toolbar(self):
        self.toolbar = ScanToolbar()

        self.target_entry_changed_handler = self.toolbar.target_entry.connect(
                'changed', self._target_entry_changed)
        self.profile_entry_changed_handler = \
            self.toolbar.profile_entry.connect(
                    'changed', self._profile_entry_changed)

        self.toolbar.scan_button.connect('clicked', self.start_scan_cb)
        self.toolbar.cancel_button.connect('clicked', self._cancel_scan_cb)

    def __create_command_toolbar(self):
        self.command_toolbar = ScanCommandToolbar()
        self.command_toolbar.command_entry.connect(
                'activate', lambda x: self.toolbar.scan_button.clicked())
        self.command_entry_changed_handler = \
            self.command_toolbar.command_entry.connect(
                    'changed', self._command_entry_changed)

    def _command_entry_changed(self, editable):
        ops = NmapOptions()
        ops.parse_string(self.command_toolbar.get_command())

        # Set the target and profile without propagating the "changed" signal
        # back to the command entry.
        self.set_target_quiet(join_quoted(ops.target_specs))
        self.set_profile_name_quiet("")

    def _target_entry_changed(self, editable):
        target_string = self.toolbar.get_selected_target()
        targets = split_quoted(target_string)

        ops = NmapOptions()
        ops.parse_string(self.command_toolbar.get_command())
        ops.target_specs = targets
        self.set_command_quiet(ops.render_string())

    def _profile_entry_changed(self, widget):
        """Update the command based on the contents of the target and profile
        entries. If the command corresponding to the current profile is not
        blank, use it. Otherwise use the current contents of the command
        entry."""
        profile_name = self.toolbar.get_selected_profile()
        target_string = self.toolbar.get_selected_target()

        cmd_profile = CommandProfile()
        command_string = cmd_profile.get_command(profile_name)
        del(cmd_profile)
        if command_string == "":
            command_string = self.command_toolbar.get_command()

        ops = NmapOptions()
        ops.parse_string(command_string)

        # Use the targets from the command entry, if there are any, otherwise
        # use any targets from the profile.
        targets = split_quoted(target_string)
        if len(targets) > 0:
            ops.target_specs = targets
        else:
            self.toolbar.set_selected_target(join_quoted(ops.target_specs))

        self.set_command_quiet(ops.render_string())

    def set_command_quiet(self, command_string):
        """Set the command used by this scan interface, ignoring any further
        "changed" signals."""
        self.command_toolbar.command_entry.handler_block(
                self.command_entry_changed_handler)
        self.command_toolbar.set_command(command_string)
        self.command_toolbar.command_entry.handler_unblock(
                self.command_entry_changed_handler)

    def set_target_quiet(self, target_string):
        """Set the target string used by this scan interface, ignoring any
        further "changed" signals."""
        self.toolbar.target_entry.handler_block(
                self.target_entry_changed_handler)
        self.toolbar.set_selected_target(target_string)
        self.toolbar.target_entry.handler_unblock(
                self.target_entry_changed_handler)

    def set_profile_name_quiet(self, profile_name):
        """Set the profile name used by this scan interface, ignoring any
        further "changed" signals."""
        self.toolbar.profile_entry.handler_block(
                self.profile_entry_changed_handler)
        self.toolbar.set_selected_profile(profile_name)
        self.toolbar.profile_entry.handler_unblock(
                self.profile_entry_changed_handler)

    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)))

        if command == '':
            warn_dialog = HIGAlertDialog(
                    message_format=_("Empty Nmap Command"),
                    secondary_text=_("There is no command to execute. "
                        "Maybe the selected/typed profile doesn't exist. "
                        "Please check the profile name or type the nmap "
                        "command you would like to execute."),
                    type=gtk.MESSAGE_ERROR)
            warn_dialog.run()
            warn_dialog.destroy()
            return

        self.execute_command(command, target, profile)
Esempio n. 29
0
                    path_env = os.getenv("PATH")
                    if path_env is None:
                        default_paths = []
                    else:
                        default_paths = path_env.split(os.pathsep)
                    extra_paths = get_extra_executable_search_paths()
                    extra_paths = [p for p in extra_paths if (
                        p not in default_paths)]
                    if len(extra_paths) > 0:
                        if len(extra_paths) == 1:
                            text += "\n\n" + _("plus the extra directory")
                        else:
                            text += "\n\n" + _("plus the extra directories")
                        text += "\n\n" + os.pathsep.join(extra_paths)
            warn_dialog = HIGAlertDialog(
                message_format=_("Error executing command"),
                secondary_text=text, type=gtk.MESSAGE_ERROR)
            warn_dialog.run()
            warn_dialog.destroy()
            return

        log.debug("Running command: %s" % command_execution.command)
        self.jobs.append(command_execution)

        i = self.scans_store.add_running_scan(command_execution)
        self.scan_result.scan_result_notebook.nmap_output.set_active_iter(i)

        # When scan starts, change to nmap output view tab and refresh output
        self.scan_result.change_to_nmap_output_tab()
        self.scan_result.refresh_nmap_output()
Esempio n. 30
0
        except IOError, e:
            # It's possible to run Nmap without generating an XML output file,
            # like with "nmap -V".
            if e.errno != errno.ENOENT:
                raise
        except xml.sax.SAXParseException, e:
            try:
                # Some options like --iflist cause Nmap to emit an empty XML
                # file. Ignore the exception in this case.
                st = os.stat(command.get_xml_output_filename())
            except:
                st = None
            if st is None or st.st_size > 0:
                warn_dialog = HIGAlertDialog(message_format = _("Parse error"),
                    secondary_text = _(u"""\
There was an error while parsing the XML file generated from the scan:

%s\
""") % str(e), type = gtk.MESSAGE_ERROR)
                warn_dialog.run()
                warn_dialog.destroy()
        else:
            parsed.unsaved = True

            self.scan_result.refresh_nmap_output()
            try:
                self.inventory.add_scan(parsed)
            except Exception, e:
                warn_dialog = HIGAlertDialog(message_format = _("Cannot merge scan"),
                    secondary_text = _(u"""\
There was an error while merging the new scan's XML:
Esempio n. 31
0
    def excepthook(type, value, tb):
        import traceback

        traceback.print_exception(type, value, tb)

        # Cause an exception if PyGTK can't open a display. Normally this just
        # produces a warning, but the lack of a display eventually causes a
        # segmentation fault. See http://live.gnome.org/PyGTK/WhatsNew210.
        import warnings

        warnings.filterwarnings("error", module="gtk")
        import gtk

        warnings.resetwarnings()

        gtk.gdk.threads_enter()

        from zenmapCore.Version import VERSION
        from zenmapGUI.higwidgets.higdialogs import HIGAlertDialog
        from zenmapGUI.CrashReport import CrashReport

        if type == ImportError:
            d = HIGAlertDialog(
                type=gtk.MESSAGE_ERROR,
                message_format=_("Import error"),
                secondary_text=_(
                    """\
A required module was not found.

"""
                    + value.message
                ),
            )
            d.run()
            d.destroy()
        else:
            hook = "Type: %s\nValue: %s\n" % (type, value)
            outputs = (
                "CRASH REPORTED:\n\
SYS.PLATFORM: %s\n\
OS.NAME: %s\n\
%s Version: %s\n\
TRACEBACK:\n%s"
                % (
                    sys.platform,
                    os.name,
                    APP_DISPLAY_NAME,
                    VERSION,
                    "".join(traceback.format_exception(type, value, tb)),
                )
            )

            try:
                c = CrashReport("%s: %s" % (VERSION, value), outputs)
                c.show_all()
                gtk.main()
            except:
                d = HIGAlertDialog(
                    type=gtk.MESSAGE_ERROR,
                    message_format=_("Bug not reported"),
                    secondary_text=_(
                        """A critical error \
occurred during %s execution,
and it was not properly reported to our bug tracker. Please,
copy the error message bellow and report it on our bug tracker.

The following error message was NOT reported:
%s"""
                    )
                    % (APP_DISPLAY_NAME, outputs),
                )
                d.run()
                d.destroy()

        gtk.gdk.threads_leave()

        gtk.main_quit()
Esempio n. 32
0
%s needs to create this directory to store information such as the list of \
scan profiles. Check for access to the directory and try again.\
""") % (repr(Path.user_config_dir), repr(Path.config_dir), repr(str(e)), APP_DISPLAY_NAME))
        error_dialog.run()
        error_dialog.destroy()
        sys.exit(1)

    try:
        # Read the ~/.zenmap/zenmap.conf configuration file.
        zenmapCore.UmitConf.config_parser.read(Path.user_config_file)
    except ConfigParser.ParsingError, e:
        error_dialog = HIGAlertDialog(message_format = _("Error parsing the configuration file"),
            secondary_text = _("""\
There was an error parsing the configuration file %s. \
The specific error was\n\
\n\
%s\n\
\n\
%s can continue without this file but any information in it will be ignored \
until it is repaired.\
""") % (Path.user_config_file, str(e), APP_DISPLAY_NAME))
        error_dialog.run()
        error_dialog.destroy()

    # Display a "you're not root" warning if appropriate.
    if not is_root():
        non_root = NonRootWarning()
        non_root.run()
        non_root.destroy()

    # Load files given as command-line arguments.
    filenames = option_parser.get_open_results()
Esempio n. 33
0
File: App.py Progetto: mogigoma/nmap
        error_dialog.destroy()
        sys.exit(1)

    try:
        # Read the ~/.zenmap/zenmap.conf configuration file.
        zenmapCore.UmitConf.config_parser.read(Path.user_config_file)
    except ConfigParser.ParsingError, e:
        # ParsingError can leave some values as lists instead of strings. Just
        # blow it all away if we have this problem.
        zenmapCore.UmitConf.config_parser = zenmapCore.UmitConf.config_parser.__class__()
        error_dialog = HIGAlertDialog(
                message_format=_("Error parsing the configuration file"),
                secondary_text=_("""\
There was an error parsing the configuration file %s. \
The specific error was

%s

%s can continue without this file but any information in it will be ignored \
until it is repaired.""") % (Path.user_config_file, str(e), APP_DISPLAY_NAME)
                )
        error_dialog.run()
        error_dialog.destroy()
        global_config_path = os.path.join(Path.config_dir, APP_NAME + '.conf')
        repair_dialog = HIGAlertDialog(
                type=gtk.MESSAGE_QUESTION,
                message_format=_("Restore default configuration?"),
                secondary_text=_("""\
To avoid further errors parsing the configuration file %s, \
you can copy the default configuration from %s.
Esempio n. 34
0
        error_dialog.destroy()
        sys.exit(1)

    try:
        # Read the ~/.zenmap/zenmap.conf configuration file.
        zenmapCore.UmitConf.config_parser.read(Path.user_config_file)
    except ConfigParser.ParsingError, e:
        # ParsingError can leave some values as lists instead of strings. Just
        # blow it all away if we have this problem.
        zenmapCore.UmitConf.config_parser = zenmapCore.UmitConf.config_parser.__class__(
        )
        error_dialog = HIGAlertDialog(
            message_format=_("Error parsing the configuration file"),
            secondary_text=_("""\
There was an error parsing the configuration file %s. \
The specific error was

%s

%s can continue without this file but any information in it will be ignored \
until it is repaired.""") % (Path.user_config_file, str(e), APP_DISPLAY_NAME))
        error_dialog.run()
        error_dialog.destroy()
        global_config_path = os.path.join(Path.config_dir, APP_NAME + '.conf')
        repair_dialog = HIGAlertDialog(
            type=gtk.MESSAGE_QUESTION,
            message_format=_("Restore default configuration?"),
            secondary_text=_("""\
To avoid further errors parsing the configuration file %s, \
you can copy the default configuration from %s.

Do this now? \
Esempio n. 35
0
    def _save_to_directory_cb(self, widget):
        if self.scan_interface.empty:
            alert = HIGAlertDialog(message_format=_('Nothing to save'),
                                   secondary_text=_('\
This scan has not been run yet. Start the scan with the "Scan" button first.'))
            alert.run()
            alert.destroy()
            return
        num_scans_running = self.scan_interface.num_scans_running()
        if num_scans_running > 0:
            if num_scans_running == 1:
                text = _("There is a scan still running. "
                        "Wait until it finishes and then save.")
            else:
                text = _("There are %u scans still running. Wait until they "
                        "finish and then save.") % num_scans_running
            alert = HIGAlertDialog(message_format=_('Scan is running'),
                                   secondary_text=text)
            alert.run()
            alert.destroy()
            return

        # We have multiple scans in our network inventory, so we need to
        # display a directory chooser dialog
        dir_chooser = SaveToDirectoryChooserDialog(
                title=_("Choose a directory to save scans into"))
        if dir_chooser.run() == gtk.RESPONSE_OK:
            self._save_all(self.scan_interface, dir_chooser.get_filename())
        dir_chooser.destroy()
Esempio n. 36
0
    def _save_all(self, scan_interface, directory):
        """Saves all scans in saving_page's inventory to a given directory.
        Displays an alert dialog if the save fails."""
        try:
            filenames = scan_interface.inventory.save_to_dir(directory)
            for scan in scan_interface.inventory.get_scans():
                scan.unsaved = False
        except Exception as ex:
            alert = HIGAlertDialog(message_format=_('Can\'t save file'),
                        secondary_text=str(ex))
            alert.run()
            alert.destroy()
        else:
            scan_interface.saved_filename = directory

            # Saving recent scan information
            try:
                for filename in filenames:
                    recent_scans.add_recent_scan(filename)
                recent_scans.save()
            except (OSError, IOError) as e:
                alert = HIGAlertDialog(
                        message_format=_(
                            "Can't save recent scan information"),
                        secondary_text=_(
                            "Can't open file to write.\n%s") % str(e))
                alert.run()
                alert.destroy()
Esempio n. 37
0
    def save_profile(self, widget):
        if self.overwrite:
            self.profile.remove_profile(self.profile_name)
        profile_name = self.profile_name_entry.get_text()
        if profile_name == '':
            alert = HIGAlertDialog(message_format=_('Unnamed profile'),\
                                   secondary_text=_('You must provide a name \
for this profile.'))
            alert.run()
            alert.destroy()

            self.profile_name_entry.grab_focus()

            return None

        command = self.ops.render_string()

        buf = self.profile_description_text.get_buffer()
        description = buf.get_text(buf.get_start_iter(),\
                                      buf.get_end_iter())

        try:
            self.profile.add_profile(profile_name,\
                                     command=command,\
                                     description=description)
        except ValueError:
            alert = HIGAlertDialog(message_format=_('Disallowed profile name'),\
                                   secondary_text=_('Sorry, the name "%s" \
is not allowed due to technical limitations. (The underlying ConfigParser \
used to store profiles does not allow it.) Choose a different \
name.' % profile_name))
            alert.run()
            alert.destroy()
            return

        self.scan_interface.toolbar.profile_entry.update()
        self.destroy()
Esempio n. 38
0
    def open_file(self, widget):
        file_chooser = ResultsFileSingleChooserDialog(_("Select Scan Result"))

        response = file_chooser.run()
        file_chosen = file_chooser.get_filename()
        file_chooser.destroy()
        if response == gtk.RESPONSE_OK:
            try:
                parser = NmapParser()
                parser.parse_file(file_chosen)
            except xml.sax.SAXParseException as e:
                alert = HIGAlertDialog(
                    message_format='<b>%s</b>' % _('Error parsing file'),
                    secondary_text=_(
                        "The file is not an Nmap XML output file. "
                        "The parsing error that occurred was\n%s") % str(e))
                alert.run()
                alert.destroy()
                return False
            except Exception as e:
                alert = HIGAlertDialog(message_format='<b>%s</b>' %
                                       _('Cannot open selected file'),
                                       secondary_text=_("""\
                        This error occurred while trying to open the file:
                        %s""") % str(e))
                alert.run()
                alert.destroy()
                return False

            scan_name = os.path.split(file_chosen)[-1]
            self.add_scan(scan_name, parser)

            self.combo_scan.set_active(len(self.list_scan) - 1)
Esempio n. 39
0
    def _exit_cb(self, *args):
        """Closes the window, prompting for confirmation if necessary. If one
        of the tabs couldn't be closed, the function returns True and doesn't
        exit the application."""
        if self.scan_interface.changed:
            log.debug("Found changes on closing window")
            dialog = HIGDialog(
                    buttons=(_('Close anyway').encode('utf-8'),
                        gtk.RESPONSE_CLOSE, gtk.STOCK_CANCEL,
                        gtk.RESPONSE_CANCEL))

            alert = HIGEntryLabel('<b>%s</b>' % _("Unsaved changes"))

            text = HIGEntryLabel(_("The given scan has unsaved changes.\n"
                "What do you want to do?"))
            hbox = HIGHBox()
            hbox.set_border_width(5)
            hbox.set_spacing(12)

            vbox = HIGVBox()
            vbox.set_border_width(5)
            vbox.set_spacing(12)

            image = gtk.Image()
            image.set_from_stock(
                    gtk.STOCK_DIALOG_QUESTION, gtk.ICON_SIZE_DIALOG)

            vbox.pack_start(alert)
            vbox.pack_start(text)
            hbox.pack_start(image)
            hbox.pack_start(vbox)

            dialog.vbox.pack_start(hbox)
            dialog.vbox.show_all()

            response = dialog.run()
            dialog.destroy()

            if response == gtk.RESPONSE_CANCEL:
                return True

            search_config = SearchConfig()
            if search_config.store_results:
                self.store_result(self.scan_interface)

        elif self.scan_interface.num_scans_running() > 0:
            log.debug("Trying to close a window with a running scan")
            dialog = HIGDialog(
                    buttons=(_('Close anyway').encode('utf-8'),
                        gtk.RESPONSE_CLOSE, gtk.STOCK_CANCEL,
                        gtk.RESPONSE_CANCEL))

            alert = HIGEntryLabel('<b>%s</b>' % _("Trying to close"))

            text = HIGEntryLabel(_(
                "The window you are trying to close has a scan running in "
                "the background.\nWhat do you want to do?"))
            hbox = HIGHBox()
            hbox.set_border_width(5)
            hbox.set_spacing(12)

            vbox = HIGVBox()
            vbox.set_border_width(5)
            vbox.set_spacing(12)

            image = gtk.Image()
            image.set_from_stock(
                    gtk.STOCK_DIALOG_WARNING, gtk.ICON_SIZE_DIALOG)

            vbox.pack_start(alert)
            vbox.pack_start(text)
            hbox.pack_start(image)
            hbox.pack_start(vbox)

            dialog.vbox.pack_start(hbox)
            dialog.vbox.show_all()

            response = dialog.run()
            dialog.destroy()

            if response == gtk.RESPONSE_CLOSE:
                self.scan_interface.kill_all_scans()
            elif response == gtk.RESPONSE_CANCEL:
                return True

        window = WindowConfig()
        window.x, window.y = self.get_position()
        window.width, window.height = self.get_size()
        window.save_changes()
        if config_parser.failed:
            alert = HIGAlertDialog(
                    message_format=_("Can't save Zenmap configuration"),
                    # newline before path to help avoid weird line wrapping
                    secondary_text=_(
                        'An error occurred when saving to\n%s'
                        '\nThe error was: %s.'
                        ) % (Path.user_config_file, config_parser.failed))
            alert.run()
            alert.destroy()

        self.destroy()

        return False
Esempio n. 40
0
    def check_ndiff_process(self):
        """Check if the ndiff subprocess is done and show the diff if it is.
        Also remove any finished processes from the old process list."""
        # Check if any old background processes have finished.
        for p in self.old_processes[:]:
            if p.poll() is not None:
                p.close()
                self.old_processes.remove(p)

        if self.ndiff_process is not None:
            # We're running the most recent scan. Check if it's done.
            status = self.ndiff_process.poll()

            if status is None:
                # Keep calling this function on a timer until the process
                # finishes.
                self.progress.pulse()
                return True

            if status == 0 or status == 1:
                # Successful completion.
                try:
                    diff = self.ndiff_process.get_scan_diff()
                except zenmapCore.Diff.NdiffParseException as e:
                    alert = HIGAlertDialog(
                        message_format=_("Error parsing ndiff output"),
                        secondary_text=str(e))
                    alert.run()
                    alert.destroy()
                else:
                    self.diff_view.show_diff(diff)
            else:
                # Unsuccessful completion.
                error_text = _(
                    "The ndiff process terminated with status code %d."
                ) % status
                stderr = self.ndiff_process.stderr.read()
                if len(stderr) > 0:
                    error_text += "\n\n" + stderr
                alert = HIGAlertDialog(message_format=_("Error running ndiff"),
                                       secondary_text=error_text)
                alert.run()
                alert.destroy()

            self.progress.hide()
            self.ndiff_process.close()
            self.ndiff_process = None

        if len(self.old_processes) > 0:
            # Keep calling this callback.
            return True
        else:
            # All done.
            self.timer_id = None
            return False
Esempio n. 41
0
    def _save_scan_results_cb(self, widget):
        """'Save Scan' callback function. If it's OK to save the scan, it
        displays a 'Save File' dialog and saves the scan. If not, it displays
        an appropriate alert dialog."""
        num_scans = len(self.scan_interface.inventory.get_scans())
        if num_scans == 0:
            alert = HIGAlertDialog(
                    message_format=_('Nothing to save'),
                    secondary_text=_(
                        'There are no scans with results to be saved. '
                        'Run a scan with the "Scan" button first.'))
            alert.run()
            alert.destroy()
            return
        num_scans_running = self.scan_interface.num_scans_running()
        if num_scans_running > 0:
            if num_scans_running == 1:
                text = _("There is a scan still running. "
                        "Wait until it finishes and then save.")
            else:
                text = _("There are %u scans still running. Wait until they "
                        "finish and then save.") % num_scans_running
            alert = HIGAlertDialog(message_format=_('Scan is running'),
                                   secondary_text=text)
            alert.run()
            alert.destroy()
            return

        # If there's more than one scan in the inventory, display a warning
        # dialog saying that only the most recent scan will be saved
        selected = 0
        if num_scans > 1:
            #text = _("You have %u scans loaded in the current view. "
            #        "Only the most recent scan will be saved." % num_scans)
            #alert = HIGAlertDialog(
            #        message_format=_("More than one scan loaded"),
            #       secondary_text=text)
            #alert.run()
            #alert.destroy()
            dlg = HIGDialog(
                    title="Choose a scan to save",
                    parent=self,
                    flags=gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
                    buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL,
                        gtk.STOCK_SAVE, gtk.RESPONSE_OK))
            dlg.vbox.pack_start(gtk.Label(
                "You have %u scans loaded in the current view.\n"
                "Select the scan which you would like to save." % num_scans),
                False)
            scan_combo = gtk.combo_box_new_text()
            for scan in self.scan_interface.inventory.get_scans():
                scan_combo.append_text(scan.nmap_command)
            scan_combo.set_active(0)
            dlg.vbox.pack_start(scan_combo, False)
            dlg.vbox.show_all()
            if dlg.run() == gtk.RESPONSE_OK:
                selected = scan_combo.get_active()
                dlg.destroy()
            else:
                dlg.destroy()
                return

        # Show the dialog to choose the path to save scan result
        self._save_results_filechooser_dialog = \
            SaveResultsFileChooserDialog(title=_('Save Scan'))
        # Supply a default file name if this scan was previously saved.
        if self.scan_interface.saved_filename:
            self._save_results_filechooser_dialog.set_filename(
                    self.scan_interface.saved_filename)

        response = self._save_results_filechooser_dialog.run()

        filename = None
        if (response == gtk.RESPONSE_OK):
            filename = self._save_results_filechooser_dialog.get_filename()
            format = self._save_results_filechooser_dialog.get_format()
            # add .xml to filename if there is no other extension
            if filename.find('.') == -1:
                filename += ".xml"
            self._save(self.scan_interface, filename, selected, format)

        self._save_results_filechooser_dialog.destroy()
        self._save_results_filechooser_dialog = None
    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 empty, we are not changing the command
        if target != '':
            self.toolbar.add_new_target(target)

        if (command.find("-iR") == -1 and command.find("-iL") == -1):
            if command.find("<target>") > 0:
                warn_dialog = HIGAlertDialog(
                    message_format=_("No Target Host"),
                    secondary_text=_("Target specification \
is mandatory. Either by an address in the target input box or through the '-iR' and \
'-iL' nmap options. Aborting scan."),
                    type=gtk.MESSAGE_ERROR)
                warn_dialog.run()
                warn_dialog.destroy()
                return

        if command != '':
            self.execute_command(command, target, profile)
        else:
            warn_dialog = HIGAlertDialog(
                message_format=_("Empty Nmap Command"),
                secondary_text=_("There is no command to  \
execute. Maybe the selected/typed profile doesn't exist. Please, check the profile name \
or type the nmap command you would like to execute."),
                type=gtk.MESSAGE_ERROR)
            warn_dialog.run()
            warn_dialog.destroy()
Esempio n. 43
0
    def _save(self, scan_interface, saved_filename, selected_index,
            format="xml"):
        """Saves the scan into a file with a given filename. Displays an alert
        dialog if the save fails."""
        log.debug(">>> File being saved: %s" % saved_filename)
        try:
            scan_interface.inventory.save_to_file(
                    saved_filename, selected_index, format)
            scan_interface.inventory.get_scans()[selected_index].unsaved = False  # noqa
        except (OSError, IOError) as e:
            alert = HIGAlertDialog(
                    message_format=_("Can't save file"),
                    secondary_text=_("Can't open file to write.\n%s") % str(e))
            alert.run()
            alert.destroy()
        else:
            scan_interface.saved_filename = saved_filename

            log.debug(">>> Changes on page? %s" % scan_interface.changed)
            log.debug(">>> File saved at: %s" % scan_interface.saved_filename)

            if format == "xml":
                # Saving recent scan information
                try:
                    recent_scans.add_recent_scan(saved_filename)
                    recent_scans.save()
                except (OSError, IOError) as e:
                    alert = HIGAlertDialog(
                            message_format=_(
                                "Can't save recent scan information"),
                            secondary_text=_(
                                "Can't open file to write.\n%s") % str(e))
                    alert.run()
                    alert.destroy()