Example #1
0
    def match_option(self, option):
        log.debug("Match option: %s" % option)

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

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

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

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

            val = ops["--" + optname]
            if val is None:
                val = ops["-" + optname]
            if val is None:
                return False
            return str(val) == optval or str(val) == optval
        else:
            return (ops["--" + option] is not None or
                    ops["-" + option] is not None)
Example #2
0
    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())
Example #3
0
    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())
Example #4
0
    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("")
Example #5
0
class NmapCommand(object):
    """This class represents an Nmap command line. It is responsible for
    starting, stopping, and returning the results from a command-line scan. A
    command line is represented as a string but it is split into a list of
    arguments for execution.

    The normal output (stdout and stderr) are written to the file object
    self.stdout_file."""

    def __init__(self, command):
        """Initialize an Nmap command. This creates temporary files for
        redirecting the various types of output and sets the backing
        command-line string."""
        self.command = command
        self.command_process = None

        self.stdout_file = None

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

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

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

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

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

    def close(self):
        """Close and remove temporary output files used by the command."""
        self.stdout_file.close()
        if self.xml_is_temp:
            try:
                os.remove(self.xml_output_filename)
            except OSError, e:
                if e.errno != errno.ENOENT:
                    raise
Example #6
0
    def append(self, option, argument, label):
        opt = label
        ops = NmapOptions()
        if option is not None and option != "":
            if argument:
                ops[option] = argument
            else:
                ops[option] = True
            opt += " (%s)" % join_quoted(ops.render()[1:])

        self.list.append([option, argument, opt])
        self.options.append(option)
    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())
Example #8
0
    def __init__(self, command):
        """Initialize an Nmap command. This creates temporary files for
        redirecting the various types of output and sets the backing
        command-line string."""
        self.command = command
        self.command_process = None

        self.stdout_file = None

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

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

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

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

        log.debug(">>> Temporary files:")
        log.debug(">>> XML OUTPUT: %s" % self.xml_output_filename)
Example #9
0
    def __init__(self, command=None, profile_name=None,
            deletable=True, overwrite=False):
        HIGWindow.__init__(self)
        self.connect("delete_event", self.exit)
        self.set_title(_('Profile Editor'))
        self.set_position(gtk.WIN_POS_CENTER)

        self.deletable = deletable
        self.profile_name = profile_name
        self.overwrite = overwrite

        # Used to block recursive updating of the command entry when the
        # command entry causes the OptionBuilder widgets to change.
        self.inhibit_command_update = False

        self.__create_widgets()
        self.__pack_widgets()

        self.profile = CommandProfile()

        self.ops = NmapOptions()
        if profile_name:
            log.debug("Showing profile %s" % profile_name)
            prof = self.profile.get_profile(profile_name)

            # Interface settings
            self.profile_name_entry.set_text(profile_name)
            self.profile_description_text.get_buffer().set_text(
                    prof['description'])

            command_string = prof['command']
            self.ops.parse_string(command_string)
        if command:
            self.ops.parse_string(command)

        self.option_builder = OptionBuilder(
                Path.profile_editor, self.ops,
                self.update_command, self.help_field.get_buffer())
        log.debug("Option groups: %s" % str(self.option_builder.groups))
        log.debug("Option section names: %s" % str(
            self.option_builder.section_names))
        #log.debug("Option tabs: %s" % str(self.option_builder.tabs))

        for tab in self.option_builder.groups:
            self.__create_tab(
                    _(tab),
                    _(self.option_builder.section_names[tab]),
                    self.option_builder.tabs[tab])

        self.update_command()
Example #10
0
    def __init__(self, command):
        """Initialize an Nmap command. This creates temporary files for
        redirecting the various types of output and sets the backing
        command-line string."""
        self.command = command
        self.command_process = None

        self.stdout_file = None

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

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

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

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

        log.debug(">>> Temporary files:")
        log.debug(">>> XML OUTPUT: %s" % self.xml_output_filename)
Example #11
0
class ProfileEditor(HIGWindow):
    def __init__(self, command=None, profile_name=None,
            deletable=True, overwrite=False):
        HIGWindow.__init__(self)
        self.connect("delete_event", self.exit)
        self.set_title(_('Profile Editor'))
        self.set_position(gtk.WIN_POS_CENTER)

        self.deletable = deletable
        self.profile_name = profile_name
        self.overwrite = overwrite

        # Used to block recursive updating of the command entry when the
        # command entry causes the OptionBuilder widgets to change.
        self.inhibit_command_update = False

        self.__create_widgets()
        self.__pack_widgets()

        self.profile = CommandProfile()

        self.ops = NmapOptions()
        if profile_name:
            log.debug("Showing profile %s" % profile_name)
            prof = self.profile.get_profile(profile_name)

            # Interface settings
            self.profile_name_entry.set_text(profile_name)
            self.profile_description_text.get_buffer().set_text(
                    prof['description'])

            command_string = prof['command']
            self.ops.parse_string(command_string)
        if command:
            self.ops.parse_string(command)

        self.option_builder = OptionBuilder(
                Path.profile_editor, self.ops,
                self.update_command, self.help_field.get_buffer())
        log.debug("Option groups: %s" % str(self.option_builder.groups))
        log.debug("Option section names: %s" % str(
            self.option_builder.section_names))
        #log.debug("Option tabs: %s" % str(self.option_builder.tabs))

        for tab in self.option_builder.groups:
            self.__create_tab(
                    _(tab),
                    _(self.option_builder.section_names[tab]),
                    self.option_builder.tabs[tab])

        self.update_command()

    def command_entry_changed_cb(self, widget):
        command_string = self.command_entry.get_text().decode("UTF-8")
        self.ops.parse_string(command_string)
        self.inhibit_command_update = True
        self.option_builder.update()
        self.inhibit_command_update = False

    def update_command(self):
        """Regenerate and display the command."""
        if not self.inhibit_command_update:
            # Block recursive updating of the OptionBuilder widgets when they
            # cause a change in the command entry.
            self.command_entry.handler_block(self.command_entry_changed_cb_id)
            self.command_entry.set_text(self.ops.render_string())
            self.command_entry.handler_unblock(
                    self.command_entry_changed_cb_id)

    def update_help_name(self, widget, extra):
        self.help_field.get_buffer().set_text(
                "Profile name\n\nThis is how the profile will be identified "
                "in the drop-down combo box in the scan tab.")

    def update_help_desc(self, widget, extra):
        self.help_field.get_buffer().set_text(
                "Description\n\nThe description is a full description of what "
                "the scan does, which may be long.")

    def __create_widgets(self):

        ###
        # Vertical box to keep 3 boxes
        self.main_whole_box = HIGVBox()

        self.upper_box = HIGHBox()
        self.middle_box = HIGHBox()
        self.lower_box = HIGHBox()

        #self.main_vbox = HIGVBox()
        self.command_entry = gtk.Entry()
        self.command_entry_changed_cb_id = self.command_entry.connect(
                "changed", self.command_entry_changed_cb)

        self.scan_button = HIGButton(_("Scan"))
        self.scan_button.connect("clicked", self.run_scan)

        self.notebook = gtk.Notebook()

        # Profile info page
        self.profile_info_vbox = HIGVBox()
        self.profile_info_label = HIGSectionLabel(_('Profile Information'))
        self.profile_name_label = HIGEntryLabel(_('Profile name'))
        self.profile_name_entry = gtk.Entry()
        self.profile_name_entry.connect(
                'enter-notify-event', self.update_help_name)
        self.profile_description_label = HIGEntryLabel(_('Description'))
        self.profile_description_scroll = HIGScrolledWindow()
        self.profile_description_scroll.set_border_width(0)
        self.profile_description_text = HIGTextView()
        self.profile_description_text.connect(
                'motion-notify-event', self.update_help_desc)

        # Buttons
        self.buttons_hbox = HIGHBox()

        self.cancel_button = HIGButton(stock=gtk.STOCK_CANCEL)
        self.cancel_button.connect('clicked', self.exit)

        self.delete_button = HIGButton(stock=gtk.STOCK_DELETE)
        self.delete_button.connect('clicked', self.delete_profile)

        self.save_button = HIGButton(_("Save Changes"), stock=gtk.STOCK_SAVE)
        self.save_button.connect('clicked', self.save_profile)

        ###
        self.help_vbox = HIGVBox()
        self.help_label = HIGSectionLabel(_('Help'))
        self.help_scroll = HIGScrolledWindow()
        self.help_scroll.set_border_width(0)
        self.help_field = HIGTextView()
        self.help_field.set_cursor_visible(False)
        self.help_field.set_left_margin(5)
        self.help_field.set_editable(False)
        self.help_vbox.set_size_request(200, -1)
        ###

    def __pack_widgets(self):

        ###
        self.add(self.main_whole_box)

        # Packing command entry to upper box
        self.upper_box._pack_expand_fill(self.command_entry)
        self.upper_box._pack_noexpand_nofill(self.scan_button)

        # Packing notebook (left) and help box (right) to middle box
        self.middle_box._pack_expand_fill(self.notebook)
        self.middle_box._pack_expand_fill(self.help_vbox)

        # Packing buttons to lower box
        self.lower_box.pack_end(self.buttons_hbox)

        # Packing the three vertical boxes to the main box
        self.main_whole_box._pack_noexpand_nofill(self.upper_box)
        self.main_whole_box._pack_expand_fill(self.middle_box)
        self.main_whole_box._pack_noexpand_nofill(self.lower_box)
        ###

        # Packing profile information tab on notebook
        self.notebook.append_page(
                self.profile_info_vbox, gtk.Label(_('Profile')))
        self.profile_info_vbox.set_border_width(5)
        table = HIGTable()
        self.profile_info_vbox._pack_noexpand_nofill(self.profile_info_label)
        self.profile_info_vbox._pack_expand_fill(HIGSpacer(table))

        self.profile_description_scroll.add(self.profile_description_text)

        vbox_desc = HIGVBox()
        vbox_desc._pack_noexpand_nofill(self.profile_description_label)
        vbox_desc._pack_expand_fill(hig_box_space_holder())

        vbox_ann = HIGVBox()
        vbox_ann._pack_expand_fill(hig_box_space_holder())

        table.attach(
                self.profile_name_label, 0, 1, 0, 1, xoptions=0, yoptions=0)
        table.attach(self.profile_name_entry, 1, 2, 0, 1, yoptions=0)
        table.attach(vbox_desc, 0, 1, 1, 2, xoptions=0)
        table.attach(self.profile_description_scroll, 1, 2, 1, 2)

        # Packing buttons on button_hbox
        self.buttons_hbox._pack_expand_fill(hig_box_space_holder())
        if self.deletable:
            self.buttons_hbox._pack_noexpand_nofill(self.delete_button)
        self.buttons_hbox._pack_noexpand_nofill(self.cancel_button)
        self.buttons_hbox._pack_noexpand_nofill(self.save_button)

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

        ###
        self.help_vbox._pack_noexpand_nofill(self.help_label)
        self.help_vbox._pack_expand_fill(self.help_scroll)
        self.help_scroll.add(self.help_field)
        self.help_vbox.set_border_width(1)
        self.help_vbox.set_spacing(1)
        ###

    def __create_tab(self, tab_name, section_name, tab):
        log.debug(">>> Tab name: %s" % tab_name)
        log.debug(">>>Creating profile editor section: %s" % section_name)
        vbox = HIGVBox()
        if tab.notscripttab:  # if notscripttab is set
            table = HIGTable()
            table.set_row_spacings(2)
            section = HIGSectionLabel(section_name)
            vbox._pack_noexpand_nofill(section)
            vbox._pack_noexpand_nofill(HIGSpacer(table))
            vbox.set_border_width(5)
            tab.fill_table(table, True)
        else:
            hbox = tab.get_hmain_box()
            vbox.pack_start(hbox, True, True, 0)
        self.notebook.append_page(vbox, gtk.Label(tab_name))

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

    def clean_profile_info(self):
        self.profile_name_entry.set_text('')
        self.profile_description_text.get_buffer().set_text('')

    def set_scan_interface(self, interface):
        self.scan_interface = interface

    def exit(self, *args):
        self.destroy()

    def delete_profile(self, widget=None, extra=None):
        if self.deletable:
            dialog = HIGDialog(buttons=(gtk.STOCK_OK, gtk.RESPONSE_OK,
                                        gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL))
            alert = HIGEntryLabel('<b>' + _("Deleting Profile") + '</b>')
            text = HIGEntryLabel(_(
                'Your profile is going to be deleted! ClickOk to continue, '
                'or Cancel to go back to Profile Editor.'))
            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_CANCEL:
                return True
            self.profile.remove_profile(self.profile_name)

        self.update_profile_entry()
        self.destroy()

    def run_scan(self, widget=None):
        command_string = self.command_entry.get_text().decode("UTF-8")
        self.scan_interface.command_toolbar.command = command_string
        self.scan_interface.start_scan_cb()
        self.exit()

    def update_profile_entry(self, widget=None, extra=None):
        self.scan_interface.toolbar.profile_entry.update()
        list = self.scan_interface.toolbar.profile_entry.get_model()
        length = len(list)
        if length > 0:
            self.scan_interface.toolbar.profile_entry.set_active(0)
Example #12
0
class ProfileEditor(HIGWindow):
    def __init__(self, command=None, profile_name=None, deletable=True, overwrite=False):
        HIGWindow.__init__(self)
        self.connect("delete_event", self.exit)
        self.set_title(_('Profile Editor'))
        self.set_position(gtk.WIN_POS_CENTER)

        self.deletable = deletable
        self.profile_name = profile_name
        self.overwrite = overwrite

        # Used to block recursive updating of the command entry when the command
        # entry causes the OptionBuilder widgets to change.
        self.inhibit_command_update = False

        self.__create_widgets()
        self.__pack_widgets()

        self.profile = CommandProfile()

        self.ops = NmapOptions()
        if profile_name:
            log.debug("Showing profile %s" % profile_name)
            prof = self.profile.get_profile(profile_name)

            # Interface settings
            self.profile_name_entry.set_text(profile_name)
            self.profile_description_text.get_buffer().set_text(prof['description'])

            command_string = prof['command']
            self.ops.parse_string(command_string)
        if command:
            self.ops.parse_string(command)

        self.option_builder = OptionBuilder(Path.profile_editor, self.ops, self.update_command, self.help_field.get_buffer())
        log.debug("Option groups: %s" % str(self.option_builder.groups))
        log.debug("Option section names: %s" % str(self.option_builder.section_names))
        #log.debug("Option tabs: %s" % str(self.option_builder.tabs))

        for tab in self.option_builder.groups:
            self.__create_tab(_(tab), _(self.option_builder.section_names[tab]), self.option_builder.tabs[tab])

        self.update_command()

    def command_entry_changed_cb(self, widget):
        command_string = self.command_entry.get_text().decode("UTF-8")
        self.ops.parse_string(command_string)
        self.inhibit_command_update = True
        self.option_builder.update()
        self.inhibit_command_update = False

    def update_command(self):
        """Regenerate and display the command."""
        if not self.inhibit_command_update:
            # Block recursive updating of the OptionBuilder widgets when they
            # cause a change in the command entry.
            self.command_entry.handler_block(self.command_entry_changed_cb_id)
            self.command_entry.set_text(self.ops.render_string())
            self.command_entry.handler_unblock(self.command_entry_changed_cb_id)

    def update_help_name(self, widget, extra):
        self.help_field.get_buffer().set_text("Profile name\n\nThis is how the"
        +" profile will be identified in the drop-down combo box in the"
        +" scan tab.")

    def update_help_desc(self, widget, extra):
        self.help_field.get_buffer().set_text("Description\n\nThe description is a"
        + " full description of what the scan does, which may be long.")

    def __create_widgets(self):

        ###
        # Vertical box to keep 3 boxes
        self.main_whole_box = HIGVBox()

        self.upper_box = HIGHBox()
        self.middle_box = HIGHBox()
        self.lower_box = HIGHBox()

        #self.main_vbox = HIGVBox()
        self.command_entry = gtk.Entry()
        self.command_entry_changed_cb_id = \
            self.command_entry.connect("changed", self.command_entry_changed_cb)

        self.scan_button = HIGButton(_("Scan"))
        self.scan_button.connect("clicked", self.run_scan)

        self.notebook = gtk.Notebook()

        # Profile info page
        self.profile_info_vbox = HIGVBox()
        self.profile_info_label = HIGSectionLabel(_('Profile Information'))
        self.profile_name_label = HIGEntryLabel(_('Profile name'))
        self.profile_name_entry = gtk.Entry()
        self.profile_name_entry.connect('enter-notify-event', self.update_help_name)
        self.profile_description_label = HIGEntryLabel(_('Description'))
        self.profile_description_scroll = HIGScrolledWindow()
        self.profile_description_scroll.set_border_width(0)
        self.profile_description_text = HIGTextView()
        self.profile_description_text.connect('motion-notify-event', self.update_help_desc)

        # Buttons
        self.buttons_hbox = HIGHBox()

        self.cancel_button = HIGButton(stock=gtk.STOCK_CANCEL)
        self.cancel_button.connect('clicked', self.exit)

        self.delete_button = HIGButton(stock=gtk.STOCK_DELETE)
        self.delete_button.connect('clicked', self.delete_profile)

        self.save_button = HIGButton(_("Save Changes"), stock=gtk.STOCK_SAVE)
        self.save_button.connect('clicked', self.save_profile)

        ###
        self.help_vbox = HIGVBox()
        self.help_label = HIGSectionLabel(_('Help'))
        self.help_scroll = HIGScrolledWindow()
        self.help_scroll.set_border_width(0)
        self.help_field = HIGTextView()
        self.help_field.set_cursor_visible(False)
        self.help_field.set_left_margin(5)
        self.help_field.set_editable(False)
        self.help_vbox.set_size_request(200,-1)
        ###
    def __pack_widgets(self):

        ###
        self.add(self.main_whole_box)

        # Packing command entry to upper box
        self.upper_box._pack_expand_fill(self.command_entry)
        self.upper_box._pack_noexpand_nofill(self.scan_button)

        # Packing notebook (left) and help box (right) to middle box
        self.middle_box._pack_expand_fill(self.notebook)
        self.middle_box._pack_expand_fill(self.help_vbox)

        # Packing buttons to lower box
        self.lower_box.pack_end(self.buttons_hbox)

        # Packing the three vertical boxes to the main box
        self.main_whole_box._pack_noexpand_nofill(self.upper_box)
        self.main_whole_box._pack_expand_fill(self.middle_box)
        self.main_whole_box._pack_noexpand_nofill(self.lower_box)
        ###


        # Packing profile information tab on notebook
        self.notebook.append_page(self.profile_info_vbox, gtk.Label(_('Profile')))
        self.profile_info_vbox.set_border_width(5)
        table = HIGTable()
        self.profile_info_vbox._pack_noexpand_nofill(self.profile_info_label)
        self.profile_info_vbox._pack_expand_fill(HIGSpacer(table))

        self.profile_description_scroll.add(self.profile_description_text)

        vbox_desc = HIGVBox()
        vbox_desc._pack_noexpand_nofill(self.profile_description_label)
        vbox_desc._pack_expand_fill(hig_box_space_holder())

        vbox_ann = HIGVBox()
        vbox_ann._pack_expand_fill(hig_box_space_holder())

        table.attach(self.profile_name_label,0,1,0,1,xoptions=0,yoptions=0)
        table.attach(self.profile_name_entry,1,2,0,1,yoptions=0)
        table.attach(vbox_desc,0,1,1,2,xoptions=0)
        table.attach(self.profile_description_scroll,1,2,1,2)

        # Packing buttons on button_hbox
        self.buttons_hbox._pack_expand_fill(hig_box_space_holder())
        if self.deletable:
            self.buttons_hbox._pack_noexpand_nofill(self.delete_button)
        self.buttons_hbox._pack_noexpand_nofill(self.cancel_button)
        self.buttons_hbox._pack_noexpand_nofill(self.save_button)

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

        ###
        self.help_vbox._pack_noexpand_nofill(self.help_label)
        self.help_vbox._pack_expand_fill(self.help_scroll)
        self.help_scroll.add(self.help_field)
        self.help_vbox.set_border_width(1)
        self.help_vbox.set_spacing(1)
        ###

    def __create_tab(self, tab_name, section_name, tab):
        log.debug(">>> Tab name: %s" % tab_name)
        log.debug(">>>Creating profile editor section: %s" % section_name)
        vbox = HIGVBox()
        if  tab.notscripttab: # if notscripttab is set
            table = HIGTable()
            table.set_row_spacings(2)
            section = HIGSectionLabel(section_name)
            vbox._pack_noexpand_nofill(section)
            vbox._pack_noexpand_nofill(HIGSpacer(table))
            vbox.set_border_width(5)
            tab.fill_table(table, True)
        else:
            hbox = tab.get_hmain_box()
            vbox.pack_start(hbox,True,True,0)
        self.notebook.append_page(vbox, gtk.Label(tab_name))

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

    def clean_profile_info(self):
        self.profile_name_entry.set_text('')
        self.profile_description_text.get_buffer().set_text('')

    def set_scan_interface(self, interface):
        self.scan_interface = interface

    def exit(self, *args):
        self.destroy()

    def delete_profile(self, widget=None, extra=None):
        if self.deletable:
            dialog = HIGDialog(buttons=(gtk.STOCK_OK, gtk.RESPONSE_OK,
                                        gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL))
            alert = HIGEntryLabel('<b>'+_("Deleting Profile")+'</b>')
            text = HIGEntryLabel(_('Your profile is going to be deleted! Click\
 Ok to continue, or Cancel to go back to Profile Editor.'))
            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_CANCEL:
                return True
            self.profile.remove_profile(self.profile_name)

        self.update_profile_entry()
        self.destroy()

    def run_scan(self, widget=None):
        command_string = self.command_entry.get_text().decode("UTF-8")
        self.scan_interface.command_toolbar.command = command_string
        self.scan_interface.start_scan_cb()
        self.exit()

    def update_profile_entry(self, widget=None, extra=None):
        self.scan_interface.toolbar.profile_entry.update()
        list = self.scan_interface.toolbar.profile_entry.get_model()
        length = len(list)
        if length >0 :
            self.scan_interface.toolbar.profile_entry.set_active(0)
Example #13
0
class NmapCommand(object):
    """This class represents an Nmap command line. It is responsible for
    starting, stopping, and returning the results from a command-line scan. A
    command line is represented as a string but it is split into a list of
    arguments for execution.

    The normal output (stdout and stderr) are written to the file object
    self.stdout_file."""

    def __init__(self, command):
        """Initialize an Nmap command. This creates temporary files for
        redirecting the various types of output and sets the backing
        command-line string."""
        self.command = command
        self.command_process = None

        self.stdout_file = None

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

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

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

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

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

    def close(self):
        """Close and remove temporary output files used by the command."""
        self.stdout_file.close()
        if self.xml_is_temp:
            try:
                os.remove(self.xml_output_filename)
            except OSError as e:
                if e.errno != errno.ENOENT:
                    raise

    def kill(self):
        """Kill the nmap subprocess."""
        from time import sleep

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

        if sys.platform != "win32":
            try:
                from signal import SIGTERM, SIGKILL
                os.kill(self.command_process.pid, SIGTERM)
                for i in range(10):
                    sleep(0.5)
                    if self.command_process.poll() is not None:
                        # Process has been TERMinated
                        break
                else:
                    log.debug(">>> SIGTERM has not worked even after waiting for 5 seconds. Using SIGKILL.")  # noqa
                    os.kill(self.command_process.pid, SIGKILL)
                    self.command_process.wait()
            except Exception:
                pass
        else:
            try:
                import ctypes
                ctypes.windll.kernel32.TerminateProcess(
                        int(self.command_process._handle), -1)
            except Exception:
                pass

    def get_path(self):
        """Return a value for the PATH environment variable that is appropriate
        for the current platform. It will be the PATH from the environment plus
        possibly some platform-specific directories."""
        path_env = os.getenv("PATH")
        if path_env is None:
            search_paths = []
        else:
            search_paths = path_env.split(os.pathsep)
        for path in zenmapCore.Paths.get_extra_executable_search_paths():
            if path not in search_paths:
                search_paths.append(path)
        return os.pathsep.join(search_paths)

    def run_scan(self, stderr=None):
        """Run the command represented by this class."""

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

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

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

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

        self.command_process = subprocess.Popen(command_list, bufsize=1,
                                     stdin=subprocess.PIPE,
                                     stdout=f,
                                     stderr=stderr,
                                     startupinfo=startupinfo,
                                     env=env)

    def scan_state(self):
        """Return the current state of a running scan. A return value of True
        means the scan is running and a return value of False means the scan
        subprocess completed successfully. If the subprocess terminated with an
        error an exception is raised. The scan must have been started with
        run_scan before calling this method."""
        if self.command_process is None:
            raise Exception("Scan is not running yet!")

        state = self.command_process.poll()

        if state is None:
            return True  # True means that the process is still running
        elif state == 0:
            return False  # False means that the process had a successful exit
        else:
            log.warning("An error occurred during the scan execution!")
            log.warning("Command that raised the exception: '%s'" %
                    self.ops.render_string())
            log.warning("Scan output:\n%s" % self.get_output())

            raise Exception(
                    "An error occurred during the scan execution!\n\n'%s'" %
                    self.get_output())

    def get_output(self):
        """Return the complete contents of the self.stdout_file. This modifies
        the file pointer."""
        self.stdout_file.seek(0)
        return self.stdout_file.read()

    def get_xml_output_filename(self):
        """Return the name of the XML (-oX) output file."""
        return self.xml_output_filename