Exemple #1
0
    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_toolbar(self):
        """Create Scan Toolbar with a set empty_target. Handles changed commands by performing
        a refresh. A clicked scan button runs the scan."""

        self.toolbar = ScanToolbar()
        self.empty_target = _("<target>")

        self.toolbar.target_entry.connect('changed',
                                          self.refresh_command_target)
        self.toolbar.profile_entry.connect('changed', self.refresh_command)

        self.toolbar.scan_button.connect('clicked', self.start_scan_cb)
Exemple #3
0
    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)
Exemple #4
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)
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."""
    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 = NetworkInventory()

        # 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)
        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.update_host_info)
        self.service_view_selection.connect('changed',
                                            self.update_service_info)

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

        self.hosts = {}
        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_scan_cb)

    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 the first
        profile."""
        if len(self.toolbar.profile_entry.get_model()) > 0:
            self.toolbar.profile_entry.set_active(0)

    def go_to_host(self, host):
        """Go to host line on nmap output result"""
        self.scan_result.scan_result_notebook.nmap_output.nmap_output.go_to_host(
            host)

    def __create_toolbar(self):
        """Create Scan Toolbar with a set empty_target. Handles changed commands by performing
        a refresh. A clicked scan button runs the scan."""

        self.toolbar = ScanToolbar()
        self.empty_target = _("<target>")

        self.toolbar.target_entry.connect('changed',
                                          self.refresh_command_target)
        self.toolbar.profile_entry.connect('changed', self.refresh_command)

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

    def __create_command_toolbar(self):
        """Assigns several events to the command toolbar, including activate
        on scan button being clicked."""

        self.command_toolbar = ScanCommandToolbar()
        self.command_toolbar.command_entry.connect(
            'activate', lambda x: self.toolbar.scan_button.clicked())

        # If you modify the command field entry at all, it will clear the profile, target fields
        # so as to not use a profile when you change the command manually, but instead just run
        # the command given in the field.
        self.command_toolbar.command_entry.connect('key-press-event',
                                                   self.clear_profile_target)

    def clear_profile_target(self, extra1=None, extra2=None):
        """Used to clear the profile & target fields, so that no profile is used upon command field
        modification."""

        self.toolbar.profile_entry.child.set_text("")
        self.toolbar.target_entry.child.set_text("")

    def refresh_command_target(self, widget):
        """Refreshes the command target only if the selected profile
        is not empty."""

        #log.debug(">>> Refresh Command Target")

        profile = self.toolbar.selected_profile
        #log.debug(">>> Profile: %s" % profile)

        if profile != '':
            target = self.toolbar.selected_target
            #log.debug(">>> Target: %s" % target)
            try:
                cmd_profile = CommandProfile()
                command = cmd_profile.get_command(profile) % target
                del (cmd_profile)

                self.command_toolbar.command = command
            except ProfileNotFound:
                pass  # Go without a profile
            except TypeError:
                pass  # The target is empty...
                #self.profile_not_found_dialog()

    def refresh_command(self, widget):
        """Try to set a new CommandProfile and delete the current profile, unless
    find some kind of problem (i.e. Profile not found or not able to be deleted."""

        #log.debug(">>> Refresh Command")
        profile = self.toolbar.selected_profile
        target = self.toolbar.selected_target

        #log.debug(">>> Profile: %s" % profile)
        #log.debug(">>> Target: %s" % target)

        if target == '':
            target = self.empty_target

        try:
            cmd_profile = CommandProfile()
            command = cmd_profile.get_command(profile) % target
            del (cmd_profile)

            self.command_toolbar.command = command
        except ProfileNotFound:
            pass
            #self.profile_not_found_dialog()
        except TypeError:
            pass  # That means that the command string convertion "%" didn't work

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

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

    def _cancel_scan_cb(self, widget):
        model, selection = self.scan_result.scan_result_notebook.scans_list.scans_list.get_selection(
        ).get_selected_rows()
        for path in selection:
            entry = model.get_value(model.get_iter(path), 0)
            if entry.running:
                self.cancel_scan(entry.command)

    def _remove_scan_cb(self, widget):
        model, selection = self.scan_result.scan_result_notebook.scans_list.scans_list.get_selection(
        ).get_selected_rows()
        selected_refs = []
        for path in selection:
            # Kill running scans and remove finished scans from the inventory.
            entry = model.get_value(model.get_iter(path), 0)
            if entry.running:
                self.cancel_scan(entry.command)
            if entry.finished:
                self.inventory.remove_scan(entry.parsed)
            # Create TreeRowReferences because those persist while we change the
            # model.
            selected_refs.append(gtk.TreeRowReference(model, path))
        # Delete the entries from the ScansListStore.
        for ref in selected_refs:
            model.remove(model.get_iter(ref.get_path()))
        self.update_ui()

    def collect_umit_info(self, command, parsed):
        profile = CommandProfile()
        profile_name = command.profile

        parsed.target = command.target
        parsed.profile_name = profile_name
        parsed.nmap_command = command.command
        parsed.profile = profile.get_command(profile_name)
        parsed.profile_description = profile.get_description(profile_name)
        parsed.profile_options = profile.get_options(profile_name)

        del (profile)

    def kill_all_scans(self):
        """Kill all running scans."""

        for scan in self.jobs:
            try:
                scan.kill()
            except AttributeError:
                pass
        del self.jobs[:]

    def cancel_scan(self, command):
        """Cancel a running scan."""
        self.scans_store.cancel_running_scan(command)
        command.kill()
        self.jobs.remove(command)

    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

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

        # Add a timeout function
        self.verify_thread_timeout_id = gobject.timeout_add(
            2000, self.verify_execution)