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)
Пример #2
0
    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()
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)