Ejemplo n.º 1
0
    def addMetadata(self, objectID, project, language):
        """
        Add a JTable at the top of the object tab containing the metadata of
        the object presented in that tab.
        """
        metadataPanel = JPanel()
        # TODO: Need to count protocols to set up Grid dimension
        metadataPanel.setLayout(GridLayout(3, 2))

        projectLabel = JLabel("Project: ")
        projectValue = JLabel(project)

        languageLabel = JLabel("Language: ")
        languageValue = JLabel(language)
        # If language code is in the settings, then display name instead
        # of code
        for lang, code in self.languages.iteritems():
            if code == language:
                languageValue.setText(lang)

        # TODO Protocols not yet in parsed object
        protocolsLabel = JLabel("ATF Protocols: ")
        protocolsBox = JComboBox(self.protocols)

        metadataPanel.add(projectLabel)
        metadataPanel.add(projectValue)
        metadataPanel.add(languageLabel)
        metadataPanel.add(languageValue)
        metadataPanel.add(protocolsLabel)
        metadataPanel.add(protocolsBox)

        # Add metadataPanel to object tab in main panel
        self.objectTabs[objectID].add(metadataPanel)
Ejemplo n.º 2
0
class StatusPanel(JPanel):
    def __init__(self):
        JPanel()
        self.setLayout(GridLayout(1,1))
        #self.add(JLabel('SELWB 1.0'))
        self.statusLabel = JLabel('Idle', SwingConstants.CENTER)
        self.statusLabel.setBackground(Color.GREEN)
        self.statusLabel.setOpaque(True)
        self.add(self.statusLabel)

    def setStatus(self, str, bgColor = Color.GREEN):
        self.statusLabel.setText(str)
        self.statusLabel.setBackground(bgColor)
Ejemplo n.º 3
0
class SummPanel(JPanel):
    def __init__(self, isTemporal):
        self.isTemporal = isTemporal
        JPanel()
        self.setLayout(GridLayout(6,2))
        self.add(JLabel('Total data'))
        self.add(JLabel(''))
        self.add(JLabel('# Pops' if not isTemporal else "# Gens"))
        self.totalPops = JLabel('0', SwingConstants.RIGHT)
        self.add(self.totalPops)
        self.add(JLabel('# Loci'))
        self.totalLoci = JLabel('0', SwingConstants.RIGHT)
        self.add(self.totalLoci)
        self.add(JLabel('Selected'))
        self.add(JLabel(''))
        self.add(JLabel('# Pops' if not isTemporal else "# Gens"))
        self.selPops = JLabel('0', SwingConstants.RIGHT)
        self.add(self.selPops)
        self.add(JLabel('# Loci'))
        self.selLoci = JLabel('0', SwingConstants.RIGHT)
        self.add(self.selLoci)

    def update(self, rec, popNames, remPops, remLoci):
        total_pops = countPops(rec)
        sel_pops = total_pops - len (remPops)
        total_loci = len(rec.loci_list)
        sel_loci = total_loci - len(remLoci)
        self.totalPops.setText(str(total_pops))
        self.selPops.setText(str(sel_pops))
        self.totalLoci.setText(str(total_loci))
        self.selLoci.setText(str(sel_loci))
Ejemplo n.º 4
0
def getContentPane():
    global contentPane
    global REMAP_WIDTH
    global REMAP_HEIGHT
    global MARGIN
    if not contentPane:
        global mainScreen
        global mainScreenImg
        mainScreen = JLabel()

        cursorImg = BufferedImage(16,16,BufferedImage.TYPE_INT_ARGB)
        blankCursor = Toolkit.getDefaultToolkit().createCustomCursor(cursorImg, Point(0,0), "blank cursor")
        mainScreen.setCursor(blankCursor)
        mainScreen.setPreferredSize(
                Dimension(REMAP_WIDTH + MARGIN, REMAP_HEIGHT + MARGIN))
        mainScreen.setText("main screen!")
        image = BufferedImage(REMAP_WIDTH + MARGIN, REMAP_HEIGHT + MARGIN
                , BufferedImage.TYPE_INT_ARGB)
        g = image.createGraphics()
        g.setColor(Color.BLACK)
        g.fillRect(0, 0, REMAP_WIDTH + MARGIN, REMAP_HEIGHT + MARGIN)
        g.setColor(Color.WHITE)
        g.setFont(Font("Serif", Font.BOLD, 20))
        g.drawString("Cursor will display on your device.", 50, 30)
        mainScreenImg = image
        mainScreen.setIcon(swing.ImageIcon(image))

        mouseListener = ScrMouseListener()
        mainScreen.addMouseListener(mouseListener)
        mainScreen.addMouseMotionListener(mouseListener)
        mainScreen.addMouseWheelListener(mouseListener)

        keyListener = ScrKeyListener()
        mainScreen.addKeyListener(keyListener)
        
        mainScreen.setFocusable(True)

        scrPanel = JPanel()
        scrPanel.setLayout(BoxLayout(scrPanel, BoxLayout.Y_AXIS))
        scrPanel.add(mainScreen)


        contentPane = JPanel()
        contentPane.setLayout(BorderLayout())
        contentPane.add(scrPanel, BorderLayout.WEST)
#        contentPAne.add(controlPanel(). BorderLayout.EAST)

    return contentPane
Ejemplo n.º 5
0
class LoadDialog(JDialog, ActionListener):
    def __init__(self, frame, what):
        JDialog.__init__(self,frame, what, False)
        self.frame   = frame

        pane = self.getRootPane().getContentPane()

        panel = JPanel()
        panel.add(JLabel('Current population'))
        self.status = JLabel("                                ")
        panel.add(self.status)
        pane.add(panel)
        
        self.pack()
        self.show()

    def update_status(self, curr):
        self.status.setText("%d" % (curr,))
        Thread.yield()
Ejemplo n.º 6
0
class StopWatch(Runnable):
    def __init__(self):
        self.frame = JFrame("StopWatch", defaultCloseOperation=JFrame.EXIT_ON_CLOSE)
        self.start = JButton("Start", actionPerformed=self.start)
        self.frame.add(self.start, BorderLayout.WEST)
        self.stop = JButton("Stop", actionPerformed=self.stop)
        self.frame.add(self.stop, BorderLayout.EAST)
        self.label = JLabel(" " * 45)
        self.frame.add(self.label, BorderLayout.SOUTH)
        self.frame.pack()

    def start(self, event):
        self.started = Calendar.getInstance().getTimeInMillis()
        self.label.setText("Running")

    def stop(self, event):
        elapsed = Calendar.getInstance().getTimeInMillis() - self.started
        self.label.setText("Elapsed: %.2f seconds" % (float(elapsed) / 1000.0))

    def run(self):
        self.frame.setVisible(1)
Ejemplo n.º 7
0
class BeautifierPanel(JPanel):
    def __init__(self):
        super(BeautifierPanel, self).__init__()
        self.setLayout(BorderLayout())

        self.beautifyTextArea = JTextArea(5, 10)
        self.beautifyTextArea.setLineWrap(True)
        self.beautifyTextArea.setDocument(self.CustomUndoPlainDocument())
        # The undo doesn't work well before replace text. Below is rough fix, so not need to know how undo work for now
        self.beautifyTextArea.setText(" ")
        self.beautifyTextArea.setText("")

        self.undoManager = UndoManager()
        self.beautifyTextArea.getDocument().addUndoableEditListener(
            self.undoManager)
        self.beautifyTextArea.getDocument().addDocumentListener(
            self.BeautifyDocumentListener(self))

        beautifyTextWrapper = JPanel(BorderLayout())
        beautifyScrollPane = JScrollPane(self.beautifyTextArea)
        beautifyTextWrapper.add(beautifyScrollPane, BorderLayout.CENTER)
        self.add(beautifyTextWrapper, BorderLayout.CENTER)

        self.beautifyButton = JButton("Beautify")
        self.beautifyButton.addActionListener(self.beautifyListener)
        self.undoButton = JButton("Undo")
        self.undoButton.addActionListener(self.undoListener)

        formatLabel = JLabel("Format:")
        self.formatsComboBox = JComboBox()
        for f in supportedFormats:
            self.formatsComboBox.addItem(f)

        self.statusLabel = JLabel("Status: Ready")
        preferredDimension = self.statusLabel.getPreferredSize()
        self.statusLabel.setPreferredSize(
            Dimension(preferredDimension.width + 20,
                      preferredDimension.height))
        self.sizeLabel = JLabel("0 B")
        preferredDimension = self.sizeLabel.getPreferredSize()
        self.sizeLabel.setPreferredSize(
            Dimension(preferredDimension.width + 64,
                      preferredDimension.height))
        self.sizeLabel.setHorizontalAlignment(SwingConstants.RIGHT)

        buttonsPanel = JPanel(FlowLayout())
        buttonsPanel.add(formatLabel)
        buttonsPanel.add(self.formatsComboBox)
        buttonsPanel.add(Box.createHorizontalStrut(10))
        buttonsPanel.add(self.beautifyButton)
        buttonsPanel.add(self.undoButton)

        bottomPanel = JPanel(BorderLayout())
        bottomPanel.add(self.statusLabel, BorderLayout.WEST)
        bottomPanel.add(buttonsPanel, BorderLayout.CENTER)
        bottomPanel.add(self.sizeLabel, BorderLayout.EAST)
        self.add(bottomPanel, BorderLayout.SOUTH)

        self.currentBeautifyThread = None

    class CustomUndoPlainDocument(PlainDocument):
        # Code from: https://stackoverflow.com/questions/24433089/jtextarea-settext-undomanager
        compoundEdit = CompoundEdit()

        def fireUndoableEditUpdate(self, e):
            if self.compoundEdit == None:
                super(BeautifierPanel.CustomUndoPlainDocument,
                      self).fireUndoableEditUpdate(e)
            else:
                self.compoundEdit.addEdit(e.getEdit())

        def replace(self, offset, length, text, attrs):
            if length == 0:
                super(BeautifierPanel.CustomUndoPlainDocument,
                      self).replace(offset, length, text, attrs)
            else:
                self.compoundEdit = CompoundEdit()
                super(BeautifierPanel.CustomUndoPlainDocument,
                      self).fireUndoableEditUpdate(
                          UndoableEditEvent(self, self.compoundEdit))
                super(BeautifierPanel.CustomUndoPlainDocument,
                      self).replace(offset, length, text, attrs)
                self.compoundEdit.end()
                self.compoundEdit = None

    def setText(self, text):
        self.beautifyTextArea.setText(text)

    def setRunningState(self):
        self.beautifyButton.setText("Cancel")
        self.undoButton.setEnabled(False)
        self.statusLabel.setText("Status: Running")

    def setReadyState(self):
        self.beautifyButton.setText("Beautify")
        self.undoButton.setEnabled(True)
        self.statusLabel.setText("Status: Ready")

    class BeautifyDocumentListener(DocumentListener):
        def __init__(self, beautifierPanel):
            super(BeautifierPanel.BeautifyDocumentListener, self).__init__()
            self.beautifierPanel = beautifierPanel

        def removeUpdate(self, e):
            self.updateSizeLabel()

        def insertUpdate(self, e):
            self.updateSizeLabel()

        def changedUpdate(self, e):
            pass

        def updateSizeLabel(self):
            length = len(self.beautifierPanel.beautifyTextArea.getText())
            if length >= 1024:
                length = "%.2f KB" % (length / 1024.0)
            else:
                length = "%d B" % length
            self.beautifierPanel.sizeLabel.setText(length)

    def beautifyListener(self, e):
        selectedFormat = self.formatsComboBox.getSelectedItem()
        data = self.beautifyTextArea.getText(
        )  # variable "data" is "unicode" type

        if self.currentBeautifyThread and self.currentBeautifyThread.isAlive():
            # TODO Need a graceful way to shutdown running beautify thread.
            self.currentBeautifyThread.callback = None
            self.currentBeautifyThread = None
            self.setReadyState()
        else:
            self.currentBeautifyThread = None
            self.setRunningState()

            def beautifyCallback(result):
                self.beautifyTextArea.setText(result)
                self.setReadyState()

            self.currentBeautifyThread = BeautifyThread(
                data, selectedFormat, beautifyCallback)
            self.currentBeautifyThread.start()

    def undoListener(self, e):
        if self.undoManager.canUndo():
            self.undoManager.undo()
Ejemplo n.º 8
0
class Config(ITab):
    """Defines the Configuration tab"""

    def __init__(self, callbacks, parent):
        # Initialze self stuff
        self._callbacks = callbacks
        self.config = {}
        self.ext_stats = {}
        self.url_reqs = []
        self.parse_files = False
        self.tab = JPanel(GridBagLayout())
        self.view_port_text = JTextArea("===SpyDir===")
        self.delim = JTextField(30)
        self.ext_white_list = JTextField(30)
        # I'm not sure if these fields are necessary still
        # why not just use Burp func to handle this?
        # leaving them in case I need it for the HTTP handler later
        # self.cookies = JTextField(30)
        # self.headers = JTextField(30)
        self.url = JTextField(30)
        self.parent_window = parent
        self.plugins = {}
        self.loaded_p_list = set()
        self.loaded_plugins = False
        self.config['Plugin Folder'] = None
        self.double_click = False
        self.source_input = ""
        self.print_stats = True
        self.curr_conf = JLabel()
        self.window = JFrame("Select plugins",
                             preferredSize=(200, 250),
                             windowClosing=self.p_close)
        self.window.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE)
        self.window.setVisible(False)

        # Initialize local stuff
        tab_constraints = GridBagConstraints()
        status_field = JScrollPane(self.view_port_text)

        # Configure view port
        self.view_port_text.setEditable(False)

        labels = self.build_ui()

        # Add things to rows
        tab_constraints.anchor = GridBagConstraints.FIRST_LINE_END
        tab_constraints.gridx = 1
        tab_constraints.gridy = 0
        tab_constraints.fill = GridBagConstraints.HORIZONTAL
        self.tab.add(JButton(
            "Resize screen", actionPerformed=self.resize),
                     tab_constraints)
        tab_constraints.gridx = 0
        tab_constraints.gridy = 1
        tab_constraints.anchor = GridBagConstraints.FIRST_LINE_START
        self.tab.add(labels, tab_constraints)

        tab_constraints.gridx = 1
        tab_constraints.gridy = 1
        tab_constraints.fill = GridBagConstraints.BOTH
        tab_constraints.weightx = 1.0
        tab_constraints.weighty = 1.0

        tab_constraints.anchor = GridBagConstraints.FIRST_LINE_END
        self.tab.add(status_field, tab_constraints)
        try:
            self._callbacks.customizeUiComponent(self.tab)
        except Exception:
            pass

    def build_ui(self):
        """Builds the configuration screen"""
        labels = JPanel(GridLayout(21, 1))
        checkbox = JCheckBox("Attempt to parse files for URL patterns?",
                             False, actionPerformed=self.set_parse)
        stats_box = JCheckBox("Show stats?", True,
                              actionPerformed=self.set_show_stats)
        # The two year old in me is laughing heartily
        plug_butt = JButton("Specify plugins location",
                            actionPerformed=self.set_plugin_loc)
        load_plug_butt = JButton("Select plugins",
                                 actionPerformed=self.p_build_ui)
        parse_butt = JButton("Parse directory", actionPerformed=self.parse)
        clear_butt = JButton("Clear text", actionPerformed=self.clear)
        spider_butt = JButton("Send to Spider", actionPerformed=self.scan)
        save_butt = JButton("Save config", actionPerformed=self.save)
        rest_butt = JButton("Restore config", actionPerformed=self.restore)
        source_butt = JButton("Input Source File/Directory",
                              actionPerformed=self.get_source_input)

        # Build grid
        labels.add(source_butt)
        labels.add(self.curr_conf)
        labels.add(JLabel("String Delimiter:"))
        labels.add(self.delim)
        labels.add(JLabel("Extension Whitelist:"))
        labels.add(self.ext_white_list)
        labels.add(JLabel("URL:"))
        labels.add(self.url)
        # Leaving these here for now.
        # labels.add(JLabel("Cookies:"))
        # labels.add(self.cookies)
        # labels.add(JLabel("HTTP Headers:"))
        # labels.add(self.headers)
        labels.add(checkbox)
        labels.add(stats_box)
        labels.add(plug_butt)
        labels.add(parse_butt)
        labels.add(JButton("Show all endpoints",
                           actionPerformed=self.print_endpoints))
        labels.add(clear_butt)
        labels.add(spider_butt)
        labels.add(JLabel(""))
        labels.add(save_butt)
        labels.add(rest_butt)
        labels.add(load_plug_butt)
        # Tool tips!
        self.delim.setToolTipText("Use to manipulate the final URL. "
                                  "See About tab for example.")
        self.ext_white_list.setToolTipText("Define a comma delimited list of"
                                           " file extensions to parse. Use *"
                                           " to parse all files.")
        self.url.setToolTipText("Enter the target URL")
        checkbox.setToolTipText("Parse files line by line using plugins"
                                " to enumerate language/framework specific"
                                " endpoints")
        parse_butt.setToolTipText("Attempt to enumerate application endpoints")
        clear_butt.setToolTipText("Clear status window and the parse results")
        spider_butt.setToolTipText("Process discovered endpoints")
        save_butt.setToolTipText("Saves the current config settings")
        rest_butt.setToolTipText("<html>Restores previous config settings:"
                                 "<br/>-Input Directory<br/>-String Delim"
                                 "<br/>-Ext WL<br/>-URL<br/>-Plugins")
        source_butt.setToolTipText("Select the application's "
                                   "source directory or file to parse")

        return labels

    def set_url(self, menu_url):
        """Changes the configuration URL to the one from the menu event"""
        self.url.setText(menu_url)

    # Event functions
    def set_parse(self, event):
        """
        Handles the click event from the UI checkbox
        to attempt code level parsing
        """
        self.parse_files = not self.parse_files
        if self.parse_files:
            if not self.loaded_plugins:
                self._plugins_missing_warning()

    def restore(self, event):
        """Attempts to restore the previously saved configuration."""
        jdump = None
        try:
            jdump = loads(self._callbacks.loadExtensionSetting("config"))
        except Exception as exc:  # Generic exception thrown directly to user
            self.update_scroll(
                "[!!] Error during restore!\n\tException: %s" % str(exc))
        if jdump is not None:
            self.url.setText(jdump.get('URL'))
            # self.cookies.setText(jdump.get('Cookies'))
            # self.headers.setText(jdump.get("Headers"))
            ewl = ""
            for ext in jdump.get('Extension Whitelist'):
                ewl += ext + ", "
            self.ext_white_list.setText(ewl[:-2])
            self.delim.setText(jdump.get('String Delimiter'))
            self.source_input = jdump.get("Input Directory")
            self.config['Plugin Folder'] = jdump.get("Plugin Folder")
            if (self.config['Plugin Folder'] is not None and
                    (len(self.plugins.values()) < 1)):
                self._load_plugins(self.config['Plugin Folder'])
            self._update()
            self.update_scroll("[^] Restore complete!")
        else:
            self.update_scroll("[!!] Restore failed!")

    def save(self, event=None):
        """
        Saves the configuration details to a Burp Suite's persistent store.
        """
        self._update()
        try:
            if not self._callbacks.isInScope(URL(self.url.getText())):
                self.update_scroll("[!!] URL provided is NOT in Burp Scope!")
        except MalformedURLException:  # If url field is blank we'll
            pass                       # still save the settings.

        try:
            self._callbacks.saveExtensionSetting("config", dumps(self.config))
            self.update_scroll("[^] Settings saved!")
        except Exception:
            self.update_scroll("[!!] Error saving settings to Burp Suite!")

    def parse(self, event):
        """
        Handles the click event from the UI.
        Attempts to parse the given directory
            (and/or source files) for url endpoints
        Saves the items found within the url_reqs list
        """
        self._update()

        file_set = set()
        fcount = 0
        other_dirs = set()
        self.ext_stats = {}
        if self.loaded_plugins:
            self.update_scroll("[^] Attempting to parse files" +
                               " for URL patterns. This might take a minute.")
        if path.isdir(self.source_input):
            for dirname, _, filenames in walk(self.source_input):
                for filename in filenames:
                    fcount += 1
                    ext = path.splitext(filename)[1]
                    count = self.ext_stats.get(ext, 0) + 1
                    filename = "%s/%s" % (dirname, filename)
                    self.ext_stats.update({ext: count})
                    if self.parse_files:
                        # i can haz threading?
                        file_set.update(self._code_as_endpoints(filename, ext))
                    elif self._ext_test(ext):
                        r_files, oths = self._files_as_endpoints(filename, ext)
                        file_set.update(r_files)
                        other_dirs.update(oths)
        elif path.isfile(self.source_input):
            ext = path.splitext(self.source_input)[1]
            file_set.update(self._code_as_endpoints(self.source_input, ext))
        else:
            self.update_scroll("[!!] Input Directory is not valid!")
        if len(other_dirs) > 0:
            self.update_scroll("[*] Found files matching file extension in:\n")
            for other_dir in other_dirs:
                self.update_scroll(" " * 4 + "%s\n" % other_dir)
        for item in file_set:
            if item.startswith("http://") or item.startswith("https://"):
                proto = item.split("//")[0] + '//'
                item = item.replace(proto, "")
            self.url_reqs.append(proto + item.replace('//', '/'))
        self._print_parsed_status(fcount)
        return (other_dirs, self.url_reqs)

    def scan(self, event):
        """
        handles the click event from the UI.
        Adds the given URL to the burp scope and sends the requests
        to the burp spider
        """
        temp_url = self.url.getText()
        if not self._callbacks.isInScope(URL(temp_url)):
            if not self.double_click:
                self.update_scroll("[!!] URL is not in scope! Press Send to "
                                   "Spider again to add to scope and scan!")
                self.double_click = True
                return
            else:
                self._callbacks.sendToSpider(URL(temp_url))
        self.update_scroll(
            "[^] Sending %d requests to Spider" % len(self.url_reqs))
        for req in self.url_reqs:
            self._callbacks.sendToSpider(URL(req))

    def clear(self, event):
        """Clears the viewport and the current parse exts"""
        self.view_port_text.setText("===SpyDir===")
        self.ext_stats = {}

    def print_endpoints(self, event):
        """Prints the discovered endpoints to the status window."""
        req_str = ""
        if len(self.url_reqs) > 0:
            self.update_scroll("[*] Printing all discovered endpoints:")
            for req in self.url_reqs:
                req_str += "    %s\n" % req
        else:
            req_str = "[!!] No endpoints discovered"
        self.update_scroll(req_str)

    def set_show_stats(self, event):
        """Modifies the show stats setting"""
        self.print_stats = not self.print_stats

    def get_source_input(self, event):
        """Sets the source dir/file for parsing"""
        source_chooser = JFileChooser()
        source_chooser.setFileSelectionMode(
            JFileChooser.FILES_AND_DIRECTORIES)
        source_chooser.showDialog(self.tab, "Choose Source Location")
        chosen_source = source_chooser.getSelectedFile()
        try:
            self.source_input = chosen_source.getAbsolutePath()
        except AttributeError:
            pass
        if self.source_input is not None:
            self.update_scroll("[*] Source location: %s" % self.source_input)
            self.curr_conf.setText(self.source_input)

    # Plugin functions
    def _parse_file(self, filename, file_url):
        """
        Attempts to parse a file with the loaded plugins
        Returns set of endpoints
        """
        file_set = set()
        with open(filename, 'r') as plug_in:
            lines = plug_in.readlines()
        ext = path.splitext(filename)[1].upper()
        if ext in self.plugins.keys():
            for plug in self.plugins.get(ext):
                if plug.enabled:
                    res = plug.run(lines)
                    if len(res) > 0:
                        for i in res:
                            i = file_url + i
                            file_set.add(i)
        elif ext == '.TXT' and self._ext_test(ext):
            for i in lines:
                i = file_url + i
                file_set.add(i.strip())
        return file_set

    def set_plugin_loc(self, event):
        """Attempts to load plugins from a specified location"""
        if self.config['Plugin Folder'] is not None:
            choose_plugin_location = JFileChooser(self.config['Plugin Folder'])
        else:
            choose_plugin_location = JFileChooser()
        choose_plugin_location.setFileSelectionMode(
            JFileChooser.DIRECTORIES_ONLY)
        choose_plugin_location.showDialog(self.tab, "Choose Folder")
        chosen_folder = choose_plugin_location.getSelectedFile()
        self.config['Plugin Folder'] = chosen_folder.getAbsolutePath()
        self._load_plugins(self.config['Plugin Folder'])

    def _load_plugins(self, folder):
        """
        Parses a local directory to get the plugins
            related to code level scanning
        """
        report = ""
        if len(self.plugins.keys()) > 0:
            report = "[^] Plugins reloaded!"
        for _, _, filenames in walk(folder):
            for p_name in filenames:
                n_e = path.splitext(p_name)  # n_e = name_extension
                if n_e[1] == ".py":
                    f_loc = "%s/%s" % (folder, p_name)
                    loaded_plug = self._validate_plugin(n_e[0], f_loc)
                    if loaded_plug:
                        self.loaded_p_list.add(loaded_plug)
                        if not report.startswith("[^]"):
                            report += "%s loaded\n" % loaded_plug.get_name()

        self._dictify(self.loaded_p_list)
        if len(self.plugins.keys()) > 0:
            self.loaded_plugins = True
        else:
            report = "[!!] Plugins load failure"
            self.loaded_plugins = False
        self.update_scroll(report)
        return report

    def _validate_plugin(self, p_name, f_loc):
        """
        Attempts to verify the manditory plugin functions to prevent broken
        plugins from loading.
        Generates an error message if plugin does not contain an appropriate
        function.
        """
        # Load the plugin
        try:
            plug = load_source(p_name, f_loc)
        except Exception as exc:  # this needs to be generic.
            self.update_scroll(
                "[!!] Error loading: %s\n\tType:%s Error: %s"
                % (f_loc, type(exc), str(exc)))
        # Verify the plugin's functions
        funcs = dir(plug)
        err = []
        if "get_name" not in funcs:
            err.append("get_name()")
        if "get_ext" not in funcs:
            err.append("get_ext()")
        if "run" not in funcs:
            err.append("run()")

        # Report errors & return
        if len(err) < 1:
            return Plugin(plug, True)
        else:
            for issue in err:
                self.update_scroll("[!!] %s is missing: %s func" %
                                   (p_name, issue))
            return None

    def _dictify(self, plist):
        """Converts the list of loaded plugins (plist) into a dictionary"""
        for p in plist:
            exts = p.get_ext().upper()
            for ext in exts.split(","):
                prev_load = self.plugins.get(ext, [])
                prev_load.append(p)
                self.plugins[ext] = prev_load

    # Status window functions
    def _print_parsed_status(self, fcount):
        """Prints the parsed directory status information"""
        if self.parse_files and not self.loaded_plugins:
            self._plugins_missing_warning()
        if len(self.url_reqs) > 0:
            self.update_scroll("[*] Example URL: %s" % self.url_reqs[0])

        if self.print_stats:
            report = (("[*] Found: %r files to be requested.\n\n" +
                       "[*] Stats: \n    " +
                       "Found: %r files.\n") % (len(self.url_reqs), fcount))
            if len(self.ext_stats) > 0:
                report += ("[*] Extensions found: %s"
                           % str(dumps(self.ext_stats,
                                       sort_keys=True, indent=4)))
        else:
            report = ("[*] Found: %r files to be requested.\n" %
                      len(self.url_reqs))
        self.update_scroll(report)
        return report

    def _plugins_missing_warning(self):
        """Prints a warning message"""
        self.update_scroll("[!!] No plugins loaded!")

    def update_scroll(self, text):
        """Updates the view_port_text with the new information"""
        temp = self.view_port_text.getText().strip()
        if text not in temp or text[0:4] == "[!!]":
            self.view_port_text.setText("%s\n%s" % (temp, text))
        elif not temp.endswith("[^] Status unchanged"):
            self.view_port_text.setText("%s\n[^] Status unchanged" % temp)

    # Internal functions
    def _code_as_endpoints(self, filename, ext):
        file_set = set()
        file_url = self.config.get("URL")
        if self.loaded_plugins:
            if self._ext_test(ext):
                file_set.update(
                    self._parse_file(filename, file_url))
            else:
                file_set.update(
                    self._parse_file(filename, file_url))
        return file_set

    def _files_as_endpoints(self, filename, ext):
        """Generates endpoints via files with the appropriate extension(s)"""
        file_url = self.config.get("URL")
        broken_splt = ""
        other_dirs = set()  # directories outside of the String Delim.
        file_set = set()
        str_del = self.config.get("String Delimiter")
        if not str_del:
            self.update_scroll("[!!] No available String Delimiter!")
            return
        spl_str = filename.split(str_del)

        try:
            # Fix for index out of bounds exception while parsing
            # subfolders _not_ included by the split
            if len(spl_str) > 1:
                file_url += ((spl_str[1])
                             .replace('\\', '/'))
            else:
                broken_splt = filename.split(self.source_input)[1]
                other_dirs.add(broken_splt)
        except Exception as exc:  # Generic exception thrown directly to user
            self.update_scroll("[!!] Error parsing: " +
                               "%s\n\tException: %s"
                               % (filename, str(exc)))
        if self._ext_test(ext):
            if file_url != self.config.get("URL"):
                file_set.add(file_url)
        else:
            other_dirs.discard(broken_splt)
        return file_set, other_dirs

    def _ext_test(self, ext):
        """Litmus test for extension whitelist"""
        val = False
        if len(self.config.get("Extension Whitelist")) > 0:
            val = (len(ext) > 0 and
                   (ext.strip().upper()
                    in self.config.get("Extension Whitelist")))
        elif "*" in self.config.get("Extension Whitelist"):
            val = True
        return val

    def _update(self):
        """Updates internal data"""
        self.config["Input Directory"] = self.source_input
        self.config["String Delimiter"] = self.delim.getText()

        white_list_text = self.ext_white_list.getText()
        self.config["Extension Whitelist"] = white_list_text.upper().split(',')
        file_url = self.url.getText()
        if not file_url.endswith('/') and file_url != "":
            file_url += '/'

        self.config["URL"] = file_url
        # self.config["Cookies"] = self.cookies.getText()
        # self.config["Headers"] = self.headers.getText()
        del self.url_reqs[:]
        self.curr_conf.setText(self.source_input)

    # Window sizing functions
    def resize(self, event):
        """Resizes the window to better fit Burp"""
        if self.parent_window is not None:
            par_size = self.parent_window.getSize()
            par_size.setSize(par_size.getWidth() * .99,
                             par_size.getHeight() * .9)
            self.tab.setPreferredSize(par_size)
            self.parent_window.validate()
            self.parent_window.switch_focus()

    def p_close(self, event):
        """
        Handles the window close event.
        """
        self.window.setVisible(False)
        self.window.dispose()

    def p_build_ui(self, event):
        """
        Adds a list of checkboxes, one for each loaded plugin
        to the Selct plugins window
        """
        if not self.loaded_p_list:
            self.update_scroll("[!!] No plugins loaded!")
            return

        scroll_pane = JScrollPane()
        scroll_pane.setPreferredSize(Dimension(200, 250))
        check_frame = JPanel(GridBagLayout())
        constraints = GridBagConstraints()
        constraints.fill = GridBagConstraints.HORIZONTAL
        constraints.gridy = 0
        constraints.anchor = GridBagConstraints.FIRST_LINE_START

        for plug in self.loaded_p_list:
            check_frame.add(JCheckBox(plug.get_name(), plug.enabled,
                                      actionPerformed=self.update_box),
                            constraints)
            constraints.gridy += 1

        vport = JViewport()
        vport.setView(check_frame)
        scroll_pane.setViewport(vport)
        self.window.contentPane.add(scroll_pane)
        self.window.pack()
        self.window.setVisible(True)

    def update_box(self, event):
        """
        Handles the check/uncheck event for the plugin's box.
        """
        for plug in self.loaded_p_list:
            if plug.get_name() == event.getActionCommand():
                plug.enabled = not plug.enabled
                if plug.enabled:
                    self.update_scroll("[^] Enabled: %s" %
                                       event.getActionCommand())
                else:
                    self.update_scroll("[^] Disabled: %s" %
                                       event.getActionCommand())

    # ITab required functions
    @staticmethod
    def getTabCaption():
        """Returns the name of the Burp Suite Tab"""
        return "SpyDir"

    def getUiComponent(self):
        """Returns the UI component for the Burp Suite tab"""
        return self.tab
Ejemplo n.º 9
0
class EmployeeDetails(JPanel):

    def __init__(self, employees):
        JPanel.__init__(self, preferredSize=(400, 200))
        layout = BoxLayout(self, BoxLayout.Y_AXIS)
        self.setLayout(layout)
        self._employees = employees
        employees.add_change_listener(self)
        self._create_status_label()
        self._create_name_editor()
        self._create_start_date_editor()
        self._create_save_button()
        self._adding_employee = False

    def _create_status_label(self):
        self._status_label = JLabel(name='status_label',
                                   font=Font(Font.SANS_SERIF, Font.PLAIN, 11))
        self.add(self._status_label)
        self._add_with_padding(self._status_label, 5)

    def _create_name_editor(self):
        self.add(JLabel(text='Employee Name:'))
        self._name_editor = FixedHeightTextField('name_input')
        self._add_with_padding(self._name_editor, 5)

    def _create_start_date_editor(self):
        self.add(JLabel(text='Start Date (yyyy-mm-dd):'))
        self._start_date_editor = FixedHeightTextField('start_input')
        self._add_with_padding(self._start_date_editor, 5)

    def _create_save_button(self):
        self._save_button = JButton('Save', name='save_button', visible=False)
        self._save_button.addActionListener(ListenerFactory(ActionListener,
                                            self._save_button_pushed))
        self._add_with_padding(self._save_button, 5)

    def _add_with_padding(self, component, padding):
        self.add(component)
        self.add(Box.createRigidArea(Dimension(0, padding)))

    def show_employee(self, employee):
        self._name_editor.setText(employee.name)
        self._start_date_editor.setText(str(employee.startdate))
        self._name_editor.setEditable(False)
        self._start_date_editor.setEditable(False)
        self._save_button.setVisible(False)
        if self._adding_employee:
            self._adding_employee = False
        else:
            self._status_label.setText('')

    def edit_new_employee(self):
        self._name_editor.setText('')
        self._start_date_editor.setText('')
        self._name_editor.setEditable(True)
        self._start_date_editor.setEditable(True)
        self._save_button.setVisible(True)
        self._adding_employee = True

    def _save_button_pushed(self, event):
        self._employees.add(self._name_editor.getText(),
                            self._start_date_editor.getText())

    def employee_added(self, employee):
        self._status_label.setForeground(Color.BLACK)
        self._status_label.setText("Employee '%s' was added successfully." % employee.name)
        self._save_button.setVisible(False)

    def adding_employee_failed(self, reason):
        self._status_label.setForeground(Color.RED)
        self._status_label.setText(reason)
class FilamentGame_ModelEditor(EditorExtension, JPanel, MouseListener, MouseMotionListener):
    def getExtensionName(self):
        return "Filament Model Tool"

    def initializeExtension(self, manager):
        self.manager = manager
        self.frame = JFrame(self.getExtensionName())
        self.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)

        # instance setup
        self.state = State.NOTHING
        self.entity = Entity()

        # Setupgui
        self.setupGui()
        self.addMouseListener(self)
        self.addMouseMotionListener(self)
        self.setPreferredSize(Dimension(500, 500))
        self.frame.pack()
        self.frame.setResizable(False)
        self.frame.setVisible(True)
        self.cameraPos = [0, 0]

    def setupGui(self):

        cPanel = JPanel()

        # Draw Shape Button
        self.drawShapeButton = JButton("Draw", actionPerformed=self.drawShapeButtonAction)
        cPanel.add(self.drawShapeButton)

        drawShapeButton = JButton("Clear", actionPerformed=self.clearShapeButtonAction)
        cPanel.add(drawShapeButton)

        # Label
        self.infoLabel = JLabel("Shape Editor")
        cPanel.add(self.infoLabel)

        self.frame.add(BorderLayout.NORTH, cPanel)
        self.frame.add(BorderLayout.CENTER, self)

    def entitySelected(self, entity):
        self.entity = entity
        self.repaint()

    def sceneChanged(self, scene):
        self.scene = scene
        self.entity = Entity()
        self.repaint()

    # BUTTONS
    def drawShapeButtonAction(self, e):
        if self.state == State.NOTHING:
            self.state = State.DRAW_SHAPE
            self.infoLabel.setText("Click to Draw Shape")
            self.drawShapeButton.setText("Stop Drawing")
        elif self.state != State.NOTHING:
            self.state = State.NOTHING
            self.infoLabel.setText("")
            self.drawShapeButton.setText("Draw")
        self.revalidate()

    def clearShapeButtonAction(self, e):
        if self.state != State.NOTHING:
            self.drawShapeButtonAction(e)
        self.state = State.NOTHING
        polygon = self.entity.getModel().pol
        polygon.reset()
        self.repaint()

    # DRAWING
    def paintComponent(self, g):
        self.super__paintComponent(g)
        g.scale(1, -1)
        g.translate(-self.cameraPos[0] + self.getWidth() / 2, -self.cameraPos[1] - self.getHeight() / 2)
        self.drawGrid(g)
        polygon = self.entity.getModel().pol
        x = []
        y = []
        g.setColor(Color.BLACK)
        for i in range(polygon.npoints):
            x = x + [int(polygon.xpoints[i])]
            y = y + [int(polygon.ypoints[i])]
            g.drawRect(int(polygon.xpoints[i]) - 2, int(polygon.ypoints[i]) - 2, 4, 4)
        g.fillPolygon(x, y, polygon.npoints)

    def drawGrid(self, g):
        g.setColor(Color.RED)
        g.drawLine(50, 0, -50, 0)
        g.drawLine(0, 50, 0, -50)

    # MOUSE LISTENER
    def mouseCicked(self, e):
        return

    def mouseEntered(self, e):
        return

    def mouseExited(self, e):
        return

    def mousePressed(self, e):
        self.anchor = e.getPoint()
        self.oldCamPos = self.cameraPos

    def findMousePos(self, p):
        w = self.getWidth()
        h = self.getHeight()
        cX = self.cameraPos[0]
        cY = self.cameraPos[1]

        y = h - p.y

        x = p.x - w / 2 + cX
        y = y - h / 2 + cY

        return [x, y]

    def mouseReleased(self, e):
        if self.state == State.DRAW_SHAPE:
            try:
                p = self.findMousePos(e.getPoint())
                self.entity.getModel().pol.addPoint(p[0], p[1])
            except IllegalPathStateException:
                print "Error Building Polygon path!"
        self.repaint()

    def mouseMoved(self, e):
        return

    def mouseDragged(self, e):
        if self.state == State.NOTHING:
            self.cameraPos = [
                self.oldCamPos[0] + self.anchor.x - e.getX(),
                self.oldCamPos[1] - self.anchor.y + e.getY(),
            ]
            print str(self.cameraPos)
            self.repaint()

    def update(self, delta):
        return
Ejemplo n.º 11
0
class JTabbedPaneClass:

    #判断域名返回IP地址
    def getIp(self, domain):
        domain = domain.split(":")[0]
        ipExpression = re.compile('^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$')
        domainExpression = re.compile(
            "^(([a-zA-Z]|[a-zA-Z][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z]|[A-Za-z][A-Za-z0-9\-]*[A-Za-z0-9])$"
        )
        if ipExpression.match(domain):
            return domain
        elif domainExpression.match(domain):
            myAddr = socket.getaddrinfo(domain, 'http')[0][4][0]
            return myAddr

        else:
            return "domain error"

    #提取域名或IP信息
    def getDomain1(self, theDomain):
        domain1 = theDomain.split(":")[0]

        return domain1

    def __init__(self):

        frame = JFrame("S1riu5 Spy")
        frame.setSize(700, 690)
        frame.setLocationRelativeTo(None)
        frame.setLayout(BorderLayout())

        tabPane = JTabbedPane(JTabbedPane.TOP)

        #第一个Tab用来做C段查询

        eachIp = self.getIp(HOSTDOMAIN)

        iList = eachIp.split(".")

        theIP = iList[0] + "." + iList[1] + "." + iList[2] + ".1/24"

        panel1 = JPanel()
        label = JLabel("IP CIDR:")
        self.textfield1 = JTextField(theIP, 15)
        button = JButton("SCAN", actionPerformed=self.cNmapScan)
        self.textArea = JTextArea(40, 65)
        self.textArea.append("IP: " + eachIp)
        self.textArea.setLineWrap(True)  #激活自动换行功能
        self.textArea.setWrapStyleWord(True)
        # 激活断行不断字功能

        panel1.add(label)
        panel1.add(self.textfield1)
        panel1.add(button)
        panel1.add(JScrollPane(self.textArea))  #设置自动滚动条
        tabPane.addTab("C segment query ", panel1)

        #第二个Tab用来做子域名查询

        theName = self.getDomain1(HOSTDOMAIN)

        self.textArea2 = JTextArea(40, 65)
        #self.textArea.append("IP: " + eachIp)
        self.textArea2.setLineWrap(True)  #激活自动换行功能
        self.textArea2.setWrapStyleWord(True)  # 激活断行不断字功能

        label2 = JLabel("Domain: ")
        self.textfield2 = JTextField(theName, 15)
        button2 = JButton("SCAN", actionPerformed=self.subDomain)
        self.panel2 = JPanel()
        self.panel2.add(label2)
        self.panel2.add(self.textfield2)
        self.panel2.add(button2)
        #self.panel2.add(scrollPane)
        self.panel2.add(JScrollPane(self.textArea2))
        tabPane.addTab("subDomains", self.panel2)

        #第三个Tab用来做敏感文件扫描

        self.tableData0 = [["1", "2"]]
        colNames2 = ('url', 'http code')
        dataModel3 = DefaultTableModel(self.tableData0, colNames2)
        self.table3 = JTable(dataModel3)
        ##

        label3 = JLabel("URL: ")
        self.textfield3 = JTextField(HOSTDOMAIN, 15)
        self.textArea3 = JTextArea(40, 65)
        #self.textArea.append("IP: " + eachIp)
        self.textArea3.setLineWrap(True)  #激活自动换行功能
        self.textArea3.setWrapStyleWord(True)  # 激活断行不断字功能
        a = 0
        b = 0
        self.label4 = JLabel(str(a) + "/" + str(b))
        #
        self.chkbox1 = JCheckBox('ASP')
        self.chkbox2 = JCheckBox('ASPX')
        self.chkbox3 = JCheckBox('JSP')
        self.chkbox4 = JCheckBox('PHP')
        self.chkbox5 = JCheckBox('MDB')
        self.chkbox6 = JCheckBox('DIR')
        button3 = JButton("SCAN", actionPerformed=self.senFileScan)
        panel3 = JPanel()

        panel3.add(label3)
        panel3.add(self.textfield3)
        panel3.add(self.chkbox1)
        panel3.add(self.chkbox2)
        panel3.add(self.chkbox3)
        panel3.add(self.chkbox4)
        panel3.add(self.chkbox5)
        panel3.add(self.chkbox6)
        panel3.add(button3)
        panel3.add(self.label4)
        panel3.add(JScrollPane(self.textArea3))

        #
        tabPane.addTab("Sebsitive File", panel3)
        #
        frame.add(tabPane)
        frame.setVisible(True)

    #用来在第一个TAB打印nmap信息
    def setResult(self, text):
        self.textArea.append(text)

    #用来在第二个TAB打印获得信息
    def setResult2(self, textId, textDomain, textIp):
        text = str(
            textId
        ) + "----------------" + textDomain + "----------------" + str(
            textIp) + os.linesep
        self.textArea2.append(text)
        #self.textArea2.append("----------------------------------------" + os.linesep)

    #用来在第三个TAB打印文件扫描的结果
    def setResult3(self, theMess01):

        self.textArea3.append(theMess01)

    def setLabel(self, a, b):
        hg = str(a) + "/" + str(b)
        self.label4.setText(hg)

    #C段扫描的主引擎
    def cNmapScan(self, event):

        self.textArea.setText("")

        #-------------------------------------------------------------------------------
        def ipRange(ipaddr):
            """
            Creates a generator that iterates through all of the IP addresses.
            The range can be specified in multiple formats.
        
                "192.168.1.0-192.168.1.255"    : beginning-end
                "192.168.1.0/24"               : CIDR
                "192.168.1.*"                  : wildcard
            
        
            """
            def ipaddr_to_binary(ipaddr):
                """
                A useful routine to convert a ipaddr string into a 32 bit long integer
                """
                # from Greg Jorgensens python mailing list message
                q = ipaddr.split('.')
                return reduce(lambda a, b: long(a) * 256 + long(b), q)

            #-------------------------------------------------------------------------------
            def binary_to_ipaddr(ipbinary):
                """
                Convert a 32-bit long integer into an ipaddr dotted-quad string
                """
                # This one is from Rikard Bosnjakovic
                return socket.inet_ntoa(struct.pack('!I', ipbinary))

            def ipaddr_to_binary(ipaddr):
                """
                A useful routine to convert a ipaddr string into a 32 bit long integer
                """
                # from Greg Jorgensens python mailing list message
                q = ipaddr.split('.')
                return reduce(lambda a, b: long(a) * 256 + long(b), q)

            #-------------------------------------------------------------------------------
            def binary_to_ipaddr(ipbinary):
                """
                Convert a 32-bit long integer into an ipaddr dotted-quad string
                """
                # This one is from Rikard Bosnjakovic
                return socket.inet_ntoa(struct.pack('!I', ipbinary))

            #-------------------------------------------------------------------------------
            def cidr_iprange(ipaddr, cidrmask):
                """
                Creates a generator that iterated through all of the IP addresses
                in a range given in CIDR notation
                """
                # Get all the binary one's
                mask = (long(2)**long(32 - long(cidrmask))) - 1

                b = ipaddr_to_binary(ipaddr)
                e = ipaddr_to_binary(ipaddr)
                b = long(b & ~mask)
                e = long(e | mask)

                while (b <= e):
                    yield binary_to_ipaddr(b)
                    b = b + 1

            #-------------------------------------------------------------------------------
            def wildcard_iprange(ipaddr):
                """
                Creates a generator that iterates through all of the IP address
                in a range given with wild card notation
                """
                beginning = []
                end = []

                tmp = ipaddr.split('.')
                for i in tmp:
                    if i == '*':
                        beginning.append("0")
                        end.append("255")
                    else:
                        beginning.append(i)
                        end.append(i)

                b = beginning[:]
                e = end[:]

                while int(b[0]) <= int(e[0]):
                    while int(b[1]) <= int(e[1]):
                        while int(b[2]) <= int(e[2]):
                            while int(b[3]) <= int(e[3]):
                                yield b[0] + '.' + b[1] + '.' + b[2] + '.' + b[
                                    3]
                                b[3] = "%d" % (int(b[3]) + 1)

                            b[2] = "%d" % (int(b[2]) + 1)
                            b[3] = beginning[3]

                        b[1] = "%d" % (int(b[1]) + 1)
                        b[2] = beginning[2]

                    b[0] = "%d" % (int(b[0]) + 1)
                    b[1] = beginning[1]

            # Did we get the IP address in the span format?
            span_re = re.compile(
                r'''(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})   # The beginning IP Address
                                     \s*-\s*
                                     (\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})   # The end IP Address
                                  ''', re.VERBOSE)

            res = span_re.match(ipaddr)
            if res:
                beginning = res.group(1)
                end = res.group(2)
                return span_iprange(beginning, end)

            # Did we get the IP address in the CIDR format?
            cidr_re = re.compile(
                r'''(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})   # The IP Address
                                     /(\d{1,2})                             # The mask
                                  ''', re.VERBOSE)

            res = cidr_re.match(ipaddr)
            if res:
                addr = res.group(1)
                cidrmask = res.group(2)
                return cidr_iprange(addr, cidrmask)

            # Did we get the IP address in the wildcard format?
            wild_re = re.compile(
                r'''(\d{1,3}|\*)\.
                                     (\d{1,3}|\*)\.
                                     (\d{1,3}|\*)\.
                                     (\d{1,3}|\*)   # The IP Address
                                  ''', re.VERBOSE)

            res = wild_re.match(ipaddr)
            if res:
                return wildcard_iprange(ipaddr)
            return "The ip address given to ipaddr is improperly formatted"

        ipCidr = self.textfield1.getText()

        domainExpression = re.compile(
            "^(([a-zA-Z]|[a-zA-Z][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z]|[A-Za-z][A-Za-z0-9\-]*[A-Za-z0-9])$"
        )

        if domainExpression.match(ipCidr):
            JOptionPane.showMessageDialog(None, "You must enter IP", "s1riu5",
                                          JOptionPane.INFORMATION_MESSAGE)

        else:
            ipList = list(ipRange(ipCidr))
            print len(ipList)
            if len(ipList) == 256:
                del ipList[0]
                del ipList[254]

            global NMAPPATH

            scan = ScanList(ipList, self,
                            [NMAPPATH, "-Pn", "-sT", "-sV", "--open"])
            scan.start()

    def subDomain(self, event):
        print self.textfield2.getText()
        b = subDomainThread(self.textfield2.getText(), self)
        b.start()

    def senFileScan(self, event):
        #print "Hello"

        urlListASP = ["/admin.asp"]
        urlListASPX = ["/admin.aspx"]
        urlListJSP = ["/admin.jsp"]
        urlListPHP = ["/admin.php"]
        urlListMDB = ["/admin.mdb"]
        urlListDIR = ["/admin/"]

        if self.chkbox1.isSelected():

            domainTextObj1 = open("path/ASP.txt", "r")
            for each1 in domainTextObj1.readlines():
                each1 = each1.strip()
                urlListASP.append(each1)
            domainTextObj1.close()

        if self.chkbox2.isSelected():
            domainTextObj2 = open("path/ASPX.txt", "r")
            for each2 in domainTextObj2.readlines():
                each2 = each2.strip()
                urlListASPX.append(each2)
            domainTextObj2.close()

        if self.chkbox3.isSelected():
            domainTextObj3 = open("path/JSP.txt", "r")
            for each3 in domainTextObj3.readlines():
                each3 = each3.strip()
                urlListJSP.append(each3)
            domainTextObj3.close()
        if self.chkbox4.isSelected():
            domainTextObj4 = open("path/PHP.txt", "r")
            for each4 in domainTextObj4.readlines():
                each4 = each4.strip()
                urlListPHP.append(each4)
            domainTextObj4.close()
        if self.chkbox5.isSelected():
            domainTextObj5 = open("path/MDB.txt", "r")
            for each5 in domainTextObj5.readlines():
                each5 = each5.strip()
                urlListMDB.append(each5)
            domainTextObj5.close()
        if self.chkbox6.isSelected():
            domainTextObj6 = open("path/DIR.txt", "r")
            for each6 in domainTextObj6.readlines():
                each6 = each6.strip()
                urlListDIR.append(each6)
            domainTextObj6.close()

        app = []
        app = urlListASP + urlListASPX + urlListJSP + urlListPHP + urlListMDB + urlListDIR
        app1 = list(set(app))

        theUrlText = self.textfield3.getText()

        #if str(theUrlText[0 : 7]) == "http://":
        #   theUrlText = "http://" + theUrlText

        print len(app1)
        print len(app)

        #fileObj1 = eachFileScan(theUrlText, app)
        #fileObj1.start()
        ab = numControl(theUrlText, app1, self)
        ab.start()
Ejemplo n.º 12
0
class ConfirmDialogDemo(java.lang.Runnable):

    #---------------------------------------------------------------------------
    # Name: run()
    # Role: Instantiate the user class
    # Note: Invoked by the Swing Event Dispatch Thread
    #---------------------------------------------------------------------------
    def run(self):
        frame = self.frame = JFrame('ConfirmDialogDemo',
                                    size=(300, 300),
                                    layout=BorderLayout(),
                                    locationRelativeTo=None,
                                    defaultCloseOperation=JFrame.EXIT_ON_CLOSE)
        frame.add(self.makePane())
        self.label = JLabel('', JLabel.CENTER)
        frame.add(self.label, BorderLayout.SOUTH)
        frame.setVisible(1)

    #---------------------------------------------------------------------------
    # Name: makePane()
    # Role: Instantiate, populate, and return the primary application panel
    #---------------------------------------------------------------------------
    def makePane(self):
        #-----------------------------------------------------------------------
        # Panel Header
        #-----------------------------------------------------------------------
        panel = JPanel(FlowLayout())
        panel.add(
            JLabel('<html><h2>ConfirmDialog options:</h2>', JLabel.CENTER))

        #-----------------------------------------------------------------------
        # ConfirmDialog argument values
        #-----------------------------------------------------------------------
        choices = JPanel(
            border=BorderFactory.createEmptyBorder(
                20,  # top
                20,  # left
                5,  # bottom
                20  # right
            ), )
        choices.setLayout(BoxLayout(choices, BoxLayout.PAGE_AXIS))

        #-----------------------------------------------------------------------
        # Required: Message to be displayed
        #-----------------------------------------------------------------------
        picks = JPanel(GridLayout(0, 2))
        picks.add(
            JLabel('<html><font color="red">Message:</font>', JLabel.RIGHT))
        self.message = picks.add(JTextField(10))

        #-----------------------------------------------------------------------
        # Optional: Dialog box title
        #-----------------------------------------------------------------------
        picks.add(JLabel('Title:', JLabel.RIGHT))
        self.title = picks.add(JTextField(10))

        #-----------------------------------------------------------------------
        # Optional: Option Type
        #-----------------------------------------------------------------------
        picks.add(JLabel('optionType:', JLabel.RIGHT))
        JOP = JOptionPane  # Make the next few lines shorter
        optionTypes = [('Yes or No', JOP.YES_NO_OPTION),
                       ('Yes, No, or Cancel', JOP.YES_NO_CANCEL_OPTION),
                       ('OK or Cancel', JOP.OK_CANCEL_OPTION)]
        optionList, self.optionDict = [], {}
        for name, value in optionTypes:
            optionList.append(name)
            self.optionDict[name] = value

        self.optType = picks.add(JComboBox(optionList))
        picks.add(self.optType)

        #-----------------------------------------------------------------------
        # Optional: Message Type
        #-----------------------------------------------------------------------
        picks.add(JLabel('messageType:', JLabel.RIGHT))
        messageTypes = [('Unspecified', None),
                        ('Plain', JOptionPane.PLAIN_MESSAGE),
                        ('Error', JOptionPane.ERROR_MESSAGE),
                        ('Informational', JOptionPane.INFORMATION_MESSAGE),
                        ('Warning', JOptionPane.WARNING_MESSAGE),
                        ('Question', JOptionPane.QUESTION_MESSAGE)]
        msgList, self.msgDict = [], {}
        for name, value in messageTypes:
            msgList.append(name)
            self.msgDict[name] = value
        self.msgType = picks.add(JComboBox(msgList))
        picks.add(self.msgType)

        choices.add(picks)
        panel.add(choices)
        panel.add(
            JButton('Display Dialog Box', actionPerformed=self.showDialog))
        return panel

    #---------------------------------------------------------------------------
    # Name: showDialog()
    # Role: ActionListener event handler used to display the user specified
    #       Dialog
    #---------------------------------------------------------------------------
    def showDialog(self, event):
        msg = self.message.getText()
        title = self.title.getText()
        opt = self.optionDict[self.optType.getSelectedItem()]
        kind = self.msgDict[self.msgType.getSelectedItem()]
        if msg:
            if title:
                if kind:
                    result = JOptionPane.showConfirmDialog(
                        self.frame, msg, title, opt, kind)
                else:
                    result = JOptionPane.showConfirmDialog(
                        self.frame, msg, title, opt)
            else:
                result = JOptionPane.showConfirmDialog(
                    self.frame,
                    msg,
                )
            self.statusUpdate('result = %d' % result)
        else:
            JOptionPane.showMessageDialog(self.frame,
                                          'A message value is required!',
                                          'Required value not specified',
                                          JOptionPane.ERROR_MESSAGE)
            self.statusUpdate('Enter a message, and try again.')

    #---------------------------------------------------------------------------
    # Name: statusUpdate()
    # Role: Update the application status field
    #---------------------------------------------------------------------------
    def statusUpdate(self, statusMessage):
        self.label.setText(statusMessage)
Ejemplo n.º 13
0
class EmployeeDetails(JPanel):
    def __init__(self, employees):
        JPanel.__init__(self, preferredSize=(400, 200))
        layout = BoxLayout(self, BoxLayout.Y_AXIS)
        self.setLayout(layout)
        self._employees = employees
        employees.add_change_listener(self)
        self._create_status_label()
        self._create_name_editor()
        self._create_start_date_editor()
        self._create_save_button()
        self._create_vacation_display()
        self._adding_employee = False

    def _create_status_label(self):
        self._status_label = JLabel(name='status_label',
                                    font=Font(Font.SANS_SERIF, Font.PLAIN, 11))
        self.add(self._status_label)
        self._add_with_padding(self._status_label, 5)

    def _create_name_editor(self):
        self.add(JLabel(text='Employee Name:'))
        self._name_editor = FixedHeightTextField('name_input')
        self._add_with_padding(self._name_editor, 5)

    def _create_start_date_editor(self):
        self.add(JLabel(text='Start Date (yyyy-mm-dd):'))
        self._start_date_editor = FixedHeightTextField('start_input')
        self._add_with_padding(self._start_date_editor, 5)

    def _create_save_button(self):
        self._save_button = JButton('Save', name='save_button', visible=False)
        self._save_button.addActionListener(
            ListenerFactory(ActionListener, self._save_button_pushed))
        self._add_with_padding(self._save_button, 5)

    def _create_vacation_display(self):
        #        self._display = JTable()
        #        self._header = self._display.getTableHeader()
        #        self.add(self._header)
        #        self.add(self._display)
        pass

    def _add_with_padding(self, component, padding):
        self.add(component)
        self.add(Box.createRigidArea(Dimension(0, padding)))

    def show_employee(self, employee):
        self._name_editor.setText(employee.name)
        self._start_date_editor.setText(str(employee.startdate))
        self._name_editor.setEditable(False)
        self._start_date_editor.setEditable(False)
        self._save_button.setVisible(False)
        if self._adding_employee:
            self._adding_employee = False
        else:
            self._status_label.setText('')


#        self._display.setVisible(True)
#        self._display.setModel(VacationTableModel(employee))
#        self._header.setVisible(True)

    def edit_new_employee(self):
        self._name_editor.setText('')
        self._start_date_editor.setText('')
        self._name_editor.setEditable(True)
        self._start_date_editor.setEditable(True)
        self._save_button.setVisible(True)
        #        self._display.setVisible(False)
        #        self._header.setVisible(False)
        self._adding_employee = True

    def _save_button_pushed(self, event):
        self._employees.add(self._name_editor.getText(),
                            self._start_date_editor.getText())

    def employee_added(self, employee):
        self._status_label.setForeground(Color.BLACK)
        self._status_label.setText("Employee '%s' was added successfully." %
                                   employee.name)
        self._save_button.setVisible(False)

    def adding_employee_failed(self, reason):
        self._status_label.setForeground(Color.RED)
        self._status_label.setText(reason)
Ejemplo n.º 14
0
    def initComponents(self):
        TabbedPane1 = JTabbedPane()
        GeneratorScrollPane = JScrollPane()
        GeneratorPanel = JPanel()
        jlbl1 = JLabel()
        jlbl2 = JLabel()
        spanePayloadList = JScrollPane()
        self.listPayloads = JList()
        pastePayloadButton = JButton(
            actionPerformed=self.pastePayloadButtonAction)
        loadPayloadButton = JButton(
            actionPerformed=self.loadPayloadButtonAction)
        removePayloadButton = JButton(
            actionPerformed=self.removePayloadButtonAction)
        clearPayloadButton = JButton(
            actionPerformed=self.clearPayloadButtonAction)
        self.textNewPayload = JTextField()
        addPayloadButton = JButton(actionPerformed=self.addPayloadButtonAction)
        jSeparator1 = JSeparator()
        jlbl3 = JLabel()
        jlbl4 = JLabel()
        self.chkGeneral = JCheckBox(actionPerformed=self.OnCheck)
        self.chkMAXDB = JCheckBox(actionPerformed=self.OnCheck)
        self.chkMSSQL = JCheckBox(actionPerformed=self.OnCheck)
        self.chkMSAccess = JCheckBox(actionPerformed=self.OnCheck)
        self.chkPostgres = JCheckBox(actionPerformed=self.OnCheck)
        self.chkOracle = JCheckBox(actionPerformed=self.OnCheck)
        self.chkSqlite = JCheckBox(actionPerformed=self.OnCheck)
        self.chkMysql = JCheckBox(actionPerformed=self.OnCheck)
        jlbl5 = JLabel()
        toClipboardButton = JButton(
            actionPerformed=self.toClipboardButtonAction)
        toFileButton = JButton(actionPerformed=self.toFileButtonAction)
        ProcessorScrollPane = JScrollPane()
        ProcessorPanel = JPanel()
        jLabel1 = JLabel()
        self.comboProcessorTech = JComboBox(
            itemStateChanged=self.comboProcessorTechAction)
        jSeparator2 = JSeparator()
        jLabel2 = JLabel()
        jLabel3 = JLabel()
        jScrollPane1 = JScrollPane()
        self.textPlainPayload = JTextArea()
        jLabel4 = JLabel()
        jScrollPane2 = JScrollPane()
        self.textTamperedPayload = JTextArea()
        tamperPayloadButton = JButton(
            actionPerformed=self.tamperPayloadButtonAction)

        jlbl1.setForeground(Color(255, 102, 51))
        jlbl1.setFont(Font(jlbl1.getFont().toString(), 1, 14))
        jlbl1.setText("User-Defiend Payloads")

        jlbl2.setText(
            "This payload type lets you configure a simple list of strings that are used as payloads."
        )

        spanePayloadList.setViewportView(self.listPayloads)
        self.extender.PayloadList = self.readPayloadsListFile()
        self.listPayloads.setListData(self.extender.PayloadList)

        pastePayloadButton.setText("Paste")

        loadPayloadButton.setText("Load")

        removePayloadButton.setText("Remove")

        clearPayloadButton.setText("Clear")

        self.textNewPayload.setToolTipText("")

        addPayloadButton.setText("Add")

        jlbl3.setForeground(Color(255, 102, 51))
        jlbl3.setFont(Font(jlbl3.getFont().toString(), 1, 14))
        jlbl3.setText("Tamper Techniques")

        jlbl4.setText(
            "You can select the techniques that you want to perform processing tasks on each user-defined payload"
        )

        self.chkGeneral.setText("General")
        varName = 'SQLiQueryTampering_{}'.format(self.chkGeneral.text)
        state = self.extender.callbacks.loadExtensionSetting(varName)
        if state: self.chkGeneral.setSelected(int(state))

        self.chkMAXDB.setText("SAP MAX DB")
        varName = 'SQLiQueryTampering_{}'.format(self.chkMAXDB.text)
        state = self.extender.callbacks.loadExtensionSetting(varName)
        if state: self.chkMAXDB.setSelected(int(state))

        self.chkMSSQL.setText("MS SQL Server")
        varName = 'SQLiQueryTampering_{}'.format(self.chkMSSQL.text)
        state = self.extender.callbacks.loadExtensionSetting(varName)
        if state: self.chkMSSQL.setSelected(int(state))

        self.chkMSAccess.setText("MS Access")
        varName = 'SQLiQueryTampering_{}'.format(self.chkMSAccess.text)
        state = self.extender.callbacks.loadExtensionSetting(varName)
        if state: self.chkMSAccess.setSelected(int(state))

        self.chkPostgres.setText("Postgres SQL")
        varName = 'SQLiQueryTampering_{}'.format(self.chkPostgres.text)
        state = self.extender.callbacks.loadExtensionSetting(varName)
        if state: self.chkPostgres.setSelected(int(state))

        self.chkOracle.setText("Oracle")
        varName = 'SQLiQueryTampering_{}'.format(self.chkOracle.text)
        state = self.extender.callbacks.loadExtensionSetting(varName)
        if state: self.chkOracle.setSelected(int(state))

        self.chkSqlite.setText("Sqlite")
        varName = 'SQLiQueryTampering_{}'.format(self.chkSqlite.text)
        state = self.extender.callbacks.loadExtensionSetting(varName)
        if state: self.chkSqlite.setSelected(int(state))

        self.chkMysql.setText("MySql")
        varName = 'SQLiQueryTampering_{}'.format(self.chkMysql.text)
        state = self.extender.callbacks.loadExtensionSetting(varName)
        if state: self.chkMysql.setSelected(int(state))

        jlbl5.setText("[?] Save the Generated/Tampered Payloads to :")

        toClipboardButton.setText("Clipboard")

        toFileButton.setText("File")

        GeneratorPanelLayout = GroupLayout(GeneratorPanel)
        GeneratorPanel.setLayout(GeneratorPanelLayout)
        GeneratorPanelLayout.setHorizontalGroup(
            GeneratorPanelLayout.createParallelGroup(
                GroupLayout.Alignment.LEADING).
            addGroup(GeneratorPanelLayout.createSequentialGroup(
            ).addContainerGap().addGroup(
                GeneratorPanelLayout.createParallelGroup(
                    GroupLayout.Alignment.TRAILING).addComponent(
                        jlbl2, GroupLayout.DEFAULT_SIZE,
                        GroupLayout.DEFAULT_SIZE,
                        Short.MAX_VALUE).addComponent(
                            jlbl4, GroupLayout.Alignment.LEADING,
                            GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE,
                            Short.MAX_VALUE).addComponent(
                                jSeparator1, GroupLayout.Alignment.LEADING).
                addGroup(GeneratorPanelLayout.createSequentialGroup().addGap(
                    6, 6, 6).addGroup(
                        GeneratorPanelLayout.createParallelGroup(
                            GroupLayout.Alignment.LEADING).addGroup(
                                GeneratorPanelLayout.createSequentialGroup(
                                ).addGroup(
                                    GeneratorPanelLayout.createParallelGroup(
                                        GroupLayout.Alignment.LEADING,
                                        False).addComponent(
                                            removePayloadButton,
                                            GroupLayout.DEFAULT_SIZE,
                                            GroupLayout.DEFAULT_SIZE,
                                            Short.MAX_VALUE).addComponent(
                                                clearPayloadButton,
                                                GroupLayout.DEFAULT_SIZE,
                                                GroupLayout.DEFAULT_SIZE,
                                                Short.MAX_VALUE).addComponent(
                                                    loadPayloadButton,
                                                    GroupLayout.DEFAULT_SIZE,
                                                    GroupLayout.DEFAULT_SIZE,
                                                    Short.MAX_VALUE).
                                    addComponent(pastePayloadButton,
                                                 GroupLayout.DEFAULT_SIZE,
                                                 GroupLayout.DEFAULT_SIZE,
                                                 Short.MAX_VALUE).addComponent(
                                                     addPayloadButton,
                                                     GroupLayout.DEFAULT_SIZE,
                                                     GroupLayout.DEFAULT_SIZE,
                                                     Short.MAX_VALUE)).
                                addGap(21, 21, 21).addGroup(
                                    GeneratorPanelLayout.createParallelGroup(
                                        GroupLayout.Alignment.LEADING).
                                    addComponent(
                                        self.textNewPayload).addComponent(
                                            spanePayloadList))).addComponent(
                                                jlbl1).addComponent(jlbl3).
                        addGroup(GeneratorPanelLayout.createSequentialGroup(
                        ).addGroup(
                            GeneratorPanelLayout.createParallelGroup(
                                GroupLayout.Alignment.LEADING).addComponent(
                                    self.chkGeneral).addComponent(
                                        self.chkMSSQL)
                        ).addGap(18, 18, 18).addGroup(
                            GeneratorPanelLayout.createParallelGroup(
                                GroupLayout.Alignment.LEADING).addComponent(
                                    self.chkPostgres).addComponent(
                                        self.chkMAXDB)
                        ).addGap(18, 18, 18).addGroup(
                            GeneratorPanelLayout.createParallelGroup(
                                GroupLayout.Alignment.LEADING).addComponent(
                                    self.chkMSAccess).addComponent(
                                        self.chkOracle)
                        ).addGap(18, 18, 18).addGroup(
                            GeneratorPanelLayout.createParallelGroup(
                                GroupLayout.Alignment.LEADING).addComponent(
                                    self.chkSqlite).addComponent(self.chkMysql)
                        )).addGroup(GeneratorPanelLayout.createSequentialGroup(
                        ).addComponent(jlbl5).addPreferredGap(
                            LayoutStyle.ComponentPlacement.
                            UNRELATED).addComponent(toClipboardButton).addGap(
                                18, 18,
                                18).addComponent(toFileButton,
                                                 GroupLayout.PREFERRED_SIZE,
                                                 97, GroupLayout.PREFERRED_SIZE
                                                 ))))).addContainerGap()))
        GeneratorPanelLayout.setVerticalGroup(
            GeneratorPanelLayout.createParallelGroup(
                GroupLayout.Alignment.LEADING).
            addGroup(GeneratorPanelLayout.createSequentialGroup(
            ).addContainerGap().addComponent(jlbl1).addPreferredGap(
                LayoutStyle.ComponentPlacement.RELATED).addComponent(
                    jlbl2, GroupLayout.PREFERRED_SIZE, 21,
                    GroupLayout.PREFERRED_SIZE).addGap(18, 18, 18).addGroup(
                        GeneratorPanelLayout.createParallelGroup(
                            GroupLayout.Alignment.LEADING).addComponent(
                                spanePayloadList, GroupLayout.PREFERRED_SIZE,
                                GroupLayout.DEFAULT_SIZE,
                                GroupLayout.PREFERRED_SIZE).
                        addGroup(GeneratorPanelLayout.createSequentialGroup(
                        ).addComponent(pastePayloadButton).addPreferredGap(
                            LayoutStyle.ComponentPlacement.RELATED
                        ).addComponent(loadPayloadButton).addPreferredGap(
                            LayoutStyle.ComponentPlacement.RELATED
                        ).addComponent(removePayloadButton).addPreferredGap(
                            LayoutStyle.ComponentPlacement.RELATED).
                                 addComponent(clearPayloadButton))).
                     addPreferredGap(
                         LayoutStyle.ComponentPlacement.RELATED).addGroup(
                             GeneratorPanelLayout.createParallelGroup(
                                 GroupLayout.Alignment.BASELINE).addComponent(
                                     self.textNewPayload,
                                     GroupLayout.PREFERRED_SIZE,
                                     GroupLayout.DEFAULT_SIZE,
                                     GroupLayout.PREFERRED_SIZE).
                             addComponent(addPayloadButton)).addPreferredGap(
                                 LayoutStyle.ComponentPlacement.UNRELATED).
                     addComponent(jSeparator1, GroupLayout.PREFERRED_SIZE, 10,
                                  GroupLayout.PREFERRED_SIZE).addPreferredGap(
                                      LayoutStyle.ComponentPlacement.RELATED).
                     addComponent(jlbl3).addPreferredGap(
                         LayoutStyle.ComponentPlacement.UNRELATED
                     ).addComponent(jlbl4).addPreferredGap(
                         LayoutStyle.ComponentPlacement.UNRELATED).addGroup(
                             GeneratorPanelLayout.createParallelGroup(
                                 GroupLayout.Alignment.BASELINE).addComponent(
                                     self.chkGeneral).addComponent(
                                         self.chkMAXDB).addComponent(
                                             self.chkOracle).addComponent(
                                                 self.chkSqlite)).
                     addPreferredGap(
                         LayoutStyle.ComponentPlacement.UNRELATED).addGroup(
                             GeneratorPanelLayout.createParallelGroup(
                                 GroupLayout.Alignment.BASELINE).addComponent(
                                     self.chkMSSQL).addComponent(
                                         self.chkPostgres).addComponent(
                                             self.chkMSAccess).addComponent(
                                                 self.chkMysql)
                         ).addGap(18, 18, 18).addGroup(
                             GeneratorPanelLayout.createParallelGroup(
                                 GroupLayout.Alignment.BASELINE).addComponent(
                                     jlbl5).addComponent(toClipboardButton).
                             addComponent(toFileButton)).addGap(20, 20, 20)))

        GeneratorScrollPane.setViewportView(GeneratorPanel)

        TabbedPane1.addTab("Generator", GeneratorScrollPane)

        varName = 'SQLiQueryTampering_comboProcessorTech'
        state = self.extender.callbacks.loadExtensionSetting(varName)

        for item in self.extender.getTamperFuncsName():
            self.comboProcessorTech.addItem(item)

        if state: self.comboProcessorTech.setSelectedIndex(int(state))

        jLabel1.setText("Processor Technique :")

        jLabel2.setText(
            "Modify Plain Payloads based on the selected Processor Technique. Write one payload per line."
        )

        jLabel3.setText("Plain Payloads:")

        self.textPlainPayload.setColumns(20)
        self.textPlainPayload.setRows(5)
        jScrollPane1.setViewportView(self.textPlainPayload)

        jLabel4.setText("Tampered Payloads:")

        self.textTamperedPayload.setColumns(20)
        self.textTamperedPayload.setRows(5)
        jScrollPane2.setViewportView(self.textTamperedPayload)

        tamperPayloadButton.setText("Tamper Payloads")

        ProcessorPanelLayout = GroupLayout(ProcessorPanel)
        ProcessorPanel.setLayout(ProcessorPanelLayout)
        ProcessorPanelLayout.setHorizontalGroup(
            ProcessorPanelLayout.
            createParallelGroup(GroupLayout.Alignment.LEADING).addGroup(
                GroupLayout.Alignment.TRAILING,
                ProcessorPanelLayout.createSequentialGroup().addContainerGap(
                    GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE).addComponent(
                        tamperPayloadButton).addContainerGap(
                            GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            ).addGroup(ProcessorPanelLayout.createSequentialGroup(
            ).addContainerGap().addGroup(
                ProcessorPanelLayout.createParallelGroup(
                    GroupLayout.Alignment.LEADING).addComponent(jSeparator2).
                addComponent(jScrollPane1).addComponent(jScrollPane2).addGroup(
                    ProcessorPanelLayout.createSequentialGroup().addGroup(
                        ProcessorPanelLayout.createParallelGroup(
                            GroupLayout.Alignment.LEADING).addComponent(
                                jLabel3).addComponent(jLabel4).addGroup(
                                    ProcessorPanelLayout.createSequentialGroup(
                                    ).addComponent(jLabel1).addPreferredGap(
                                        LayoutStyle.ComponentPlacement.
                                        UNRELATED).addComponent(
                                            self.comboProcessorTech,
                                            GroupLayout.PREFERRED_SIZE, 286,
                                            GroupLayout.PREFERRED_SIZE)).
                        addComponent(jLabel2)).addGap(
                            0, 78, Short.MAX_VALUE))).addContainerGap()))
        ProcessorPanelLayout.setVerticalGroup(
            ProcessorPanelLayout.createParallelGroup(
                GroupLayout.Alignment.LEADING).addGroup(
                    ProcessorPanelLayout.createSequentialGroup().addGap(
                        33, 33, 33).addGroup(
                            ProcessorPanelLayout.createParallelGroup(
                                GroupLayout.Alignment.BASELINE).
                            addComponent(jLabel1).addComponent(
                                self.comboProcessorTech,
                                GroupLayout.PREFERRED_SIZE,
                                GroupLayout.DEFAULT_SIZE,
                                GroupLayout.PREFERRED_SIZE)).addGap(
                                    18, 18, 18).addComponent(
                                        jSeparator2,
                                        GroupLayout.PREFERRED_SIZE, 10,
                                        GroupLayout.PREFERRED_SIZE).addGap(
                                            12, 12,
                                            12).addComponent(jLabel2).addGap(
                                                18, 18, 18).
                    addComponent(jLabel3).addPreferredGap(
                        LayoutStyle.ComponentPlacement.UNRELATED).addComponent(
                            jScrollPane1, GroupLayout.PREFERRED_SIZE,
                            GroupLayout.DEFAULT_SIZE,
                            GroupLayout.PREFERRED_SIZE).addPreferredGap(
                                LayoutStyle.ComponentPlacement.UNRELATED).
                    addComponent(jLabel4).addPreferredGap(
                        LayoutStyle.ComponentPlacement.UNRELATED).addComponent(
                            jScrollPane2, GroupLayout.PREFERRED_SIZE,
                            GroupLayout.DEFAULT_SIZE,
                            GroupLayout.PREFERRED_SIZE).addPreferredGap(
                                LayoutStyle.ComponentPlacement.UNRELATED).
                    addComponent(tamperPayloadButton).addGap(36, 36, 36)))

        ProcessorScrollPane.setViewportView(ProcessorPanel)

        TabbedPane1.addTab("Processor", ProcessorScrollPane)

        self.mainPanel = JPanel()
        layout = GroupLayout(self.mainPanel)
        self.mainPanel.setLayout(layout)
        layout.setHorizontalGroup(
            layout.createParallelGroup(
                GroupLayout.Alignment.LEADING).addComponent(
                    TabbedPane1, GroupLayout.DEFAULT_SIZE, 701,
                    Short.MAX_VALUE))
        layout.setVerticalGroup(
            layout.createParallelGroup(
                GroupLayout.Alignment.LEADING).addComponent(TabbedPane1))

        TabbedPane1.getAccessibleContext().setAccessibleName("Generator")
class BurpExtender(IBurpExtender, IBurpExtenderCallbacks,
                   IIntruderPayloadProcessor, ITab, IExtensionStateListener):
    def registerExtenderCallbacks(self, callbacks):
        self._helpers = callbacks.getHelpers()
        callbacks.setExtensionName("JWT FuzzHelper")
        callbacks.registerIntruderPayloadProcessor(self)
        callbacks.registerExtensionStateListener(self)

        self._stdout = PrintWriter(callbacks.getStdout(), True)
        self._stderr = PrintWriter(callbacks.getStderr(), True)

        # Warn user if extension has not found pyjwt or rsa
        did_import = lambda lib: True if lib in sys.modules else False
        if not did_import("pyjwt"):
            self._stdout.println(
                "[WARNING] 'pyjwt' not found. Have you set your path correctly?"
            )
        if not did_import("rsa"):
            self._stdout.println(
                "[WARNING] 'rsa' not found. Have you set your path correctly?")

        # Holds values passed by user from Configuration panel
        self._fuzzoptions = {
            "target": "Header",
            "selector": None,
            "signature": False,
            "algorithm": "HS256",
            "key": ""
        }

        self._isNone = lambda val: isinstance(val, type(None))

        # Configuration panel Layout
        self._configurationPanel = JPanel()
        gridBagLayout = GridBagLayout()
        gridBagLayout.columnWidths = [0, 0, 0]
        gridBagLayout.rowHeights = [10, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
        gridBagLayout.columnWeights = [0.0, 0.0, 0.0]
        gridBagLayout.rowWeights = [
            0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0
        ]
        self._configurationPanel.setLayout(gridBagLayout)

        # Setup tabs
        self._tabs = JTabbedPane()
        self._tabs.addTab('Configuration', self._configurationPanel)
        #self._tabs.addTab('Help',self._helpPanel)

        # Target Options
        targetLabel = JLabel("Target Selection (Required): ")
        targetLabel.setFont(Font("Tahoma", Font.BOLD, 12))
        c = GridBagConstraints()
        c.gridx = 0
        c.gridy = 1
        c.insets = Insets(0, 10, 0, 0)
        c.anchor = GridBagConstraints.LINE_END
        self._configurationPanel.add(targetLabel, c)

        options = ['Header', 'Payload']
        self._targetComboBox = JComboBox(options)
        c = GridBagConstraints()
        c.gridx = 1
        c.gridy = 1
        c.anchor = GridBagConstraints.LINE_START
        self._configurationPanel.add(self._targetComboBox, c)

        # Help Button
        self._helpButton = JButton("Help", actionPerformed=self.helpMenu)
        c = GridBagConstraints()
        c.gridx = 2
        c.gridy = 1
        c.anchor = GridBagConstraints.FIRST_LINE_START
        self._configurationPanel.add(self._helpButton, c)

        # Selector Options
        self._selectorLabel = JLabel(
            "JSON Selector [Object Identifier-Index Syntax] (Required): ")
        self._selectorLabel.setFont(Font("Tahoma", Font.BOLD, 12))
        c = GridBagConstraints()
        c.gridx = 0
        c.gridy = 2
        c.insets = Insets(0, 10, 0, 0)
        c.anchor = GridBagConstraints.LINE_END
        self._configurationPanel.add(self._selectorLabel, c)

        self._selectorTextField = JTextField('', 50)
        c = GridBagConstraints()
        c.gridx = 1
        c.gridy = 2
        self._configurationPanel.add(self._selectorTextField, c)

        # Regex option

        self._regexLabel = JLabel("Use regex as JSON Selector? (Optional): ")
        self._regexLabel.setFont(Font("Tahoma", Font.BOLD, 12))
        c = GridBagConstraints()
        c.gridx = 0
        c.gridy = 3
        c.insets = Insets(0, 0, 0, 0)
        c.anchor = GridBagConstraints.LINE_END
        self._configurationPanel.add(self._regexLabel, c)

        self._regexCheckBox = JCheckBox("", actionPerformed=self.regexSelector)
        c = GridBagConstraints()
        c.gridx = 1
        c.gridy = 3
        c.anchor = GridBagConstraints.FIRST_LINE_START
        self._configurationPanel.add(self._regexCheckBox, c)

        # Signature Options
        generateSignatureLabel = JLabel("Generate signature? (Required): ")
        generateSignatureLabel.setFont(Font("Tahoma", Font.BOLD, 12))
        c = GridBagConstraints()
        c.gridx = 0
        c.gridy = 4
        c.insets = Insets(0, 10, 0, 0)
        c.anchor = GridBagConstraints.LINE_END
        self._configurationPanel.add(generateSignatureLabel, c)

        options = ["False", "True"]
        self._generateSignatureComboBox = JComboBox(options)
        c = GridBagConstraints()
        c.gridx = 1
        c.gridy = 4
        c.anchor = GridBagConstraints.LINE_START
        self._configurationPanel.add(self._generateSignatureComboBox, c)

        signatureAlgorithmLabel = JLabel("Signature Algorithm (Optional): ")
        signatureAlgorithmLabel.setFont(Font("Tahoma", Font.BOLD, 12))
        c = GridBagConstraints()
        c.gridx = 0
        c.gridy = 5
        c.insets = Insets(0, 10, 0, 0)
        c.anchor = GridBagConstraints.LINE_END
        self._configurationPanel.add(signatureAlgorithmLabel, c)

        options = [
            "None", "HS256", "HS384", "HS512", "ES256", "ES384", "ES512",
            "RS256", "RS384", "RS512", "PS256", "PS256", "PS384", "PS512"
        ]
        self._algorithmSelectionComboBox = JComboBox(options)
        c = GridBagConstraints()
        c.gridx = 1
        c.gridy = 5
        c.anchor = GridBagConstraints.LINE_START
        self._configurationPanel.add(self._algorithmSelectionComboBox, c)

        # Signing key options
        self._signingKeyLabel = JLabel("Signing Key (Optional): ")
        self._signingKeyLabel.setFont(Font("Tahoma", Font.BOLD, 12))
        c = GridBagConstraints()
        c.gridx = 0
        c.gridy = 6
        c.insets = Insets(0, 10, 0, 0)
        c.anchor = GridBagConstraints.LINE_END
        self._configurationPanel.add(self._signingKeyLabel, c)

        self.addSigningKeyTextArea()
        self._fromFileTextField = JTextField('', 50)

        fromFileLabel = JLabel("Signing key from file? (Optional): ")
        fromFileLabel.setFont(Font("Tahoma", Font.BOLD, 12))
        c = GridBagConstraints()
        c.gridx = 0
        c.gridy = 7
        c.insets = Insets(0, 0, 0, 0)
        c.anchor = GridBagConstraints.LINE_END
        self._configurationPanel.add(fromFileLabel, c)

        self._fromFileCheckBox = JCheckBox("", actionPerformed=self.fromFile)
        c = GridBagConstraints()
        c.gridx = 1
        c.gridy = 7
        c.anchor = GridBagConstraints.FIRST_LINE_START
        self._configurationPanel.add(self._fromFileCheckBox, c)

        self._saveButton = JButton("Save Configuration",
                                   actionPerformed=self.saveOptions)
        self._saveButton.setText("Save Configuration")
        c = GridBagConstraints()
        c.gridx = 1
        c.gridy = 8
        c.anchor = GridBagConstraints.FIRST_LINE_START
        self._configurationPanel.add(self._saveButton, c)

        callbacks.customizeUiComponent(self._configurationPanel)
        callbacks.customizeUiComponent(self._tabs)
        callbacks.addSuiteTab(self)

        self._stdout.println("[JWT FuzzHelper] Loaded successfully")
        return

    def getProcessorName(self):
        return "JWT Fuzzer"

    def extensionUnloaded(self):
        del self._configurationPanel
        return

    # Intruder logic function
    def processPayload(self, currentPayload, originalPayload, baseValue):
        dataParameter = self._helpers.bytesToString(
            self._helpers.urlDecode(baseValue))

        # utf-8 encode
        header, payload, signature = [
            unicode(s).encode('utf-8') for s in dataParameter.split(".", 3)
        ]
        decoded_header = self._helpers.bytesToString(
            self._helpers.base64Decode(header + "=" * (-len(header) % 4)))
        decoded_payload = self._helpers.bytesToString(
            self._helpers.base64Decode(payload + "=" * (-len(payload) % 4)))

        # Decode header and payload, preserving order if they are JSON objects

        # Decode header
        try:
            header_dict = json.loads(decoded_header,
                                     object_pairs_hook=OrderedDict)
        except ValueError:
            raise RuntimeException(
                "[JWT FuzzHelper] Error: ValueError. Failed to decode header!")
        except Exception as e:
            self._stderr.println(
                "[ERROR] Encountered an unknown error when decoding header:\n{}\nCarrying on..."
                .format(e))

        # Decode payload
        # Payload does not have to be a JSON object.
        #   Ref: https://github.com/auth0/node-jsonwebtoken#usage
        payload_is_string = False
        try:
            payload_dict = json.loads(decoded_payload,
                                      object_pairs_hook=OrderedDict)
        except ValueError:
            payload_is_string = True
            payload_dict = decoded_payload
        except Exception as e:
            self._stderr.println(
                "[ERROR] Encountered an unknown error when decoding payload:\n{}\nCarrying on..."
                .format(e))

        target = header_dict if self._fuzzoptions[
            "target"] == "Header" else payload_dict
        selector = self._fuzzoptions["selector"]

        # If using Object Identifier-Index then retrieve the
        # value specified by the selector,
        # if this value does not exist, assume the user
        # wants to add the value that would have been specified
        # by the selector to the desired JWT segment (this behavior will
        # be noted in the help docs)

        intruderPayload = self._helpers.bytesToString(currentPayload)
        if not self._fuzzoptions["regex"]:
            if selector != [""]:
                try:
                    value = self.getValue(target, selector)
                except Exception:
                    target = self.buildDict(target, selector)

            if not self._isNone(selector) and selector != [""]:
                target = self.setValue(target, selector, intruderPayload)

        # Simple match-replace for regex
        if self._fuzzoptions["regex"]:
            target_string = target if payload_is_string else json.dumps(target)
            target_string = re.sub(selector, intruderPayload, target_string)
            target = target_string if payload_is_string else json.loads(
                target_string, object_pairs_hook=OrderedDict)
            if self._fuzzoptions["target"] == "Payload":
                payload_dict = target
            else:
                header_dict = target

        algorithm = self._fuzzoptions["algorithm"]
        if self._fuzzoptions["signature"]:
            # pyjwt requires lowercase 'none'. If user wants to try
            # "none", "NonE", "nOnE", etc... they should use .alg
            # as selector, delete sig from intruder and use those
            # permutations as their fuzz list (outlined in help docs)
            # and keep "Generate Signature" as False
            algorithm = "none" if algorithm.lower() == "none" else algorithm
            header_dict["alg"] = algorithm

        header = json.dumps(header_dict, separators=(",", ":"))
        payload = payload_dict if payload_is_string else json.dumps(
            payload_dict, separators=(",", ":"))
        header = self._helpers.base64Encode(header).strip("=")
        payload = self._helpers.base64Encode(payload).strip("=")

        contents = header + "." + payload

        key = self._fuzzoptions["key"]
        if self._fuzzoptions["signature"]:
            # pyjwt throws error when using a public key in symmetric alg (for good reason of course),
            # must do natively to support algorithmic sub attacks
            if algorithm.startswith("HS"):
                if algorithm == "HS256":
                    hmac_algorithm = hashlib.sha256
                elif algorithm == "HS384":
                    hmac_algorithm = hashlib.sha384
                else:
                    hmac_algorithm = hashlib.sha512

                signature = self._helpers.base64Encode(
                    hmac.new(key, contents,
                             hmac_algorithm).digest()).strip("=")

                modified_jwt = contents + "." + signature

            # JWT can't sign non-JSON payloads. WTF. This block is for non-JSON payloads.
            elif algorithm.startswith("RS") and payload_is_string:
                if algorithm == "RS256":
                    rsa_algorithm = "SHA-256"
                elif algorithm == "RS384":
                    rsa_algorithm = "SHA-384"
                else:
                    rsa_algorithm = "SHA-512"
                privkey = rsa.PrivateKey.load_pkcs1(key)
                signature = rsa.sign(contents, privkey, rsa_algorithm)
                signature = base64.b64encode(signature).encode(
                    'utf-8').replace("=", "")
                modified_jwt = contents + "." + signature
            else:
                # Use pyjwt when using asymmetric alg
                if algorithm == "none":
                    key = ""
                modified_jwt = jwt.encode(payload_dict,
                                          key,
                                          algorithm=algorithm,
                                          headers=header_dict)
        else:
            modified_jwt = contents + "." + signature

        return self._helpers.stringToBytes(modified_jwt)

    #-----------------------
    # getValue:
    #   @return: A value at arbitrary depth in dictionary
    #   @throws: TypeError
    #-----------------------
    def getValue(self, dictionary, values):
        return reduce(dict.__getitem__, values, dictionary)

    #-----------------------
    # buildDict:
    #   @note: Will build dictionary of arbitrary depth
    #-----------------------
    def buildDict(self, dictionary, keys):
        if self._isNone(keys):
            return dictionary

        root = current = dictionary
        for key in keys:
            if key not in current:
                current[key] = {}
            current = current[key]
        return root

    #----------------------
    # setValue:
    #   @note: Will set key of arbitrary depth
    #-----------------------
    def setValue(self, dictionary, keys, value):
        root = current = dictionary
        for i, key in enumerate(keys):
            if i == len(keys) - 1:
                current[key] = value
                break
            if key in current:
                current = current[key]
            else:
                # Should never happen
                current = self.buildDict(current, keys)
        return root

    #-----------------------
    # addSigningKeyTextArea:
    #   @note: Will toggle if fromFile selected. Be DRY.
    #----------------------
    def addSigningKeyTextArea(self):
        self._signingKeyTextArea = JTextArea()
        self._signingKeyTextArea.setColumns(50)
        self._signingKeyTextArea.setRows(10)
        self._signingKeyScrollPane = JScrollPane(self._signingKeyTextArea)
        c = GridBagConstraints()
        c.gridx = 1
        c.gridy = 6
        c.anchor = GridBagConstraints.LINE_START
        self._configurationPanel.add(self._signingKeyScrollPane, c)

    def addSigningKeyFromFileTextField(self):
        c = GridBagConstraints()
        c.gridx = 1
        c.gridy = 6
        self._configurationPanel.add(self._fromFileTextField, c)

    #-----------------------
    # End Helpers
    #-----------------------

    #-----------------------
    # Implement ITab
    #-----------------------

    def getTabCaption(self):
        return "JWT FuzzHelper"

    def getUiComponent(self):
        return self._tabs

    #---------------------------
    # Save configuration options
    #---------------------------

    def saveOptions(self, event):
        self._fuzzoptions["target"] = self._targetComboBox.getSelectedItem()
        self._fuzzoptions["selector"] = self._selectorTextField.getText()
        self._fuzzoptions[
            "signature"] = True if self._generateSignatureComboBox.getSelectedItem(
            ) == "True" else False
        self._fuzzoptions[
            "algorithm"] = self._algorithmSelectionComboBox.getSelectedItem()

        if self._fromFileCheckBox.isSelected():
            filename = self._fromFileTextField.getText()
            if os.path.isdir(filename):
                self._stderr.println("{} is a directory".format(filename))
                return
            if os.path.exists(filename):
                with open(filename, 'rb') as f:
                    self._fuzzoptions["key"] = f.read()
        else:
            self._fuzzoptions["key"] = unicode(
                self._signingKeyTextArea.getText()).encode("utf-8")
        # RSA keys need to end with a line break. Many headaches because of this.
        if not self._fuzzoptions["key"].endswith(
                "\n") and self._fuzzoptions["algorithm"].startswith("RS"):
            self._fuzzoptions["key"] += "\n"
        self._stdout.println("[JWT FuzzHelper] Saved options:\n{}".format(
            self._fuzzoptions))

        # Sanity check selector if it's not a regular expression
        self._fuzzoptions["regex"] = self._regexCheckBox.isSelected()
        if not self._regexCheckBox.isSelected():
            m = re.search("(\.\w+)+", self._fuzzoptions["selector"])
            if self._fuzzoptions["selector"] != "." and (
                    isinstance(m, type(None))
                    or m.group(0) != self._fuzzoptions["selector"]):
                self._saveButton.setText("Invalid JSON Selector!")
            else:
                self._fuzzoptions["selector"] = self._fuzzoptions[
                    "selector"].split(".")[1:]
                self._saveButton.setText("Saved!")
        # Sanity check the regular expression
        else:
            try:
                re.compile(self._fuzzoptions["selector"])
                self._saveButton.setText("Saved!")
            except re.error:
                self._saveButton.setText("Invalid Regex!")
        return

    #-------------------------
    # From file options
    #------------------------
    def fromFile(self, event):
        if self._fromFileCheckBox.isSelected():
            self._signingKeyLabel.setText("Path to Signing Key (Optional): ")
            self._configurationPanel.remove(self._signingKeyScrollPane)
            self.addSigningKeyFromFileTextField()
        else:
            self._signingKeyLabel.setText("Signing Key (Optional): ")
            self._configurationPanel.remove(self._fromFileTextField)
            self.addSigningKeyTextArea()
        self._configurationPanel.repaint()
        return

    def regexSelector(self, event):
        if self._regexCheckBox.isSelected():
            self._selectorLabel.setText("Selector [Regex] (Required): ")
        else:
            self._selectorLabel.setText(
                "JSON Selector [Object Identifier-Index Syntax] (Required): ")
        self._configurationPanel.repaint()
        return

    #-------------------------
    # Help popup
    #-------------------------
    def helpMenu(self, event):
        self._helpPopup = JFrame('JWT Fuzzer', size=(550, 450))
        self._helpPopup.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE)
        helpPanel = JPanel()
        helpPanel.setPreferredSize(Dimension(550, 450))
        helpPanel.setBorder(EmptyBorder(10, 10, 10, 10))
        helpPanel.setLayout(BoxLayout(helpPanel, BoxLayout.Y_AXIS))
        self._helpPopup.setContentPane(helpPanel)
        helpHeadingText = JLabel("<html><h2>JWT Fuzzer</h2></html>")
        authorText = JLabel("<html><p>@author: &lt;pinnace&gt;</p></html>")
        aboutText = JLabel(
            "<html><br /> <p>This extension adds an Intruder payload processor for JWTs.</p><br /></html>"
        )
        repositoryText = JLabel("<html>Documentation and source code:</html>")
        repositoryLink = JLabel(
            "<html>- <a href=\"https://github.com/pinnace/burp-jwt-fuzzhelper-extension\">https://github.com/pinnace/burp-jwt-fuzzhelper-extension</a></html>"
        )
        licenseText = JLabel(
            "<html><br/><p>JWT Fuzzer uses a GPL 3 license. This license does not apply to the dependency below:<p></html>"
        )
        dependencyLink = JLabel(
            "<html>- <a href=\"https://github.com/jpadilla/pyjwt/blob/master/LICENSE\">pyjwt</a></html>"
        )
        dependencyLink.addMouseListener(ClickListener())
        dependencyLink.setCursor(Cursor.getPredefinedCursor(
            Cursor.HAND_CURSOR))
        repositoryLink.addMouseListener(ClickListener())
        repositoryLink.setCursor(Cursor.getPredefinedCursor(
            Cursor.HAND_CURSOR))

        helpPanel.add(helpHeadingText)
        helpPanel.add(authorText)
        helpPanel.add(aboutText)
        helpPanel.add(repositoryText)
        helpPanel.add(repositoryLink)
        helpPanel.add(licenseText)
        helpPanel.add(dependencyLink)

        self._helpPopup.setSize(Dimension(550, 450))
        self._helpPopup.pack()
        self._helpPopup.setLocationRelativeTo(None)
        self._helpPopup.setVisible(True)
        return
Ejemplo n.º 16
0
class SelectionCellRenderer(TreeCellRenderer):
    def __init__(self, tree, mapContext):
        self.tree = tree
        self.mapContext = mapContext
        self.lblGroup = JLabel()
        self.lblGroup.setBackground(Color(222, 227, 233))  #.BLUE.brighter())
        self.lblGroup.setOpaque(True)
        self.lblGroup.setText(
            "plddddddddddddddddddddddddddddddddddddddddddddddddddddddd")

        self.lblGroupPreferredSize = self.lblGroup.getPreferredSize()
        #h = self.lblGroupPreferredSize.getHeight()
        #w = self.lblGroupPreferredSize.getWidth()
        #self.lblGroupPreferredSize.setSize(h, w)
        self.pnlLayer = JPanel()
        self.pnlLayer.setOpaque(False)

        self.pnlLayer.setLayout(FlowLayout(FlowLayout.LEFT))

        self.lblClean = JLabel()

        self.chkLayerVisibility = JCheckBox()
        self.chkLayerVisibility.setOpaque(False)
        self.lblLayerName = JLabel()
        self.lblLayerIcon = JLabel()
        self.lblFeatureSelecteds = JLabel()

        self.pnlLayer.add(self.chkLayerVisibility)
        self.pnlLayer.add(self.lblClean)
        self.pnlLayer.add(self.lblFeatureSelecteds)
        self.pnlLayer.add(self.lblLayerIcon)
        self.pnlLayer.add(self.lblLayerName)
        self.tree.setRowHeight(
            int(self.pnlLayer.getPreferredSize().getHeight()) - 3)
        self.lblUnknown = JLabel()

        ## Feature
        self.lblFeatureIcon = JLabel()
        self.lblFeatureName = JLabel()
        i18n = ToolsLocator.getI18nManager()
        self.lblFeatureName.setText(i18n.getTranslation("_Feature"))
        self.pnlFeature = JPanel()
        self.pnlFeature.setOpaque(False)
        self.pnlFeature.setLayout(FlowLayout(FlowLayout.LEFT))
        self.pnlFeature.add(self.lblFeatureIcon)
        self.pnlFeature.add(self.lblFeatureName)

    def getTreeCellRendererComponent(self, tree, value, selected, expanded,
                                     leaf, row, hasFocus):
        uo = value.getUserObject()
        if isinstance(uo, DataGroup):
            text = "[" + str(value.getChildCount()) + "] " + uo.getName()
            self.lblGroup.setText(text)
            self.lblGroup.setPreferredSize(self.lblGroupPreferredSize)
            return self.lblGroup
        if isinstance(uo, DataLayer):
            layer = uo.getLayer()

            self.lblLayerName.setText(uo.getName())
            self.lblLayerIcon.setIcon(getIconFromLayer(layer))
            if layer.isVisible():
                self.lblLayerName.setEnabled(True)
            else:
                self.lblLayerName.setEnabled(False)
            self.lblClean.setIcon(getIconByName("edit-clear"))
            self.chkLayerVisibility.setSelected(layer.isVisible())
            if layer.isWithinScale(
                    self.mapContext.getScaleView()):  # and layer.isVisible():
                self.chkLayerVisibility.setEnabled(True)
            else:
                self.chkLayerVisibility.setEnabled(False)
            if layer.getDataStore() != None and layer.getDataStore(
            ).getSelection() != None and layer.getDataStore().getSelection(
            ).getSize() != 0:  # and layer.isVisible():
                self.lblClean.setEnabled(True)
                self.lblFeatureSelecteds.setText(
                    str(layer.getDataStore().getSelection().getSize()))
                self.lblFeatureSelecteds.setEnabled(True)
            else:
                self.lblClean.setEnabled(False)
                self.lblFeatureSelecteds.setText("0")
                self.lblFeatureSelecteds.setEnabled(False)

            font = self.lblLayerName.getFont()
            self.lblLayerName.setForeground(Color.BLACK)
            if layer.isEditing():
                self.lblLayerName.setForeground(Color.RED)
            #if layer.isActive():
            if layer.isActive():  # and not font.isBold():
                newfont = font.deriveFont(Font.BOLD)
                self.lblLayerName.setFont(newfont)
            else:
                newfont = font.deriveFont(Font.PLAIN)
                self.lblLayerName.setFont(newfont)

            return self.pnlLayer
        if isinstance(uo, FeatureDataLayerNode):
            self.lblFeatureName.setText(uo.getFeature().toString())
            self.lblFeatureIcon.setIcon(getIconByName("edit-clear"))

            return self.pnlFeature
        self.lblUnknown.setText("")
        self.lblUnknown.setPreferredSize(Dimension(0, 0))
        return self.lblUnknown
Ejemplo n.º 17
0
class Config(ITab):
    """Defines the Configuration tab"""

    def __init__(self, callbacks, parent):
        # Initialze self stuff
        self._callbacks = callbacks
        self.config = {}
        self.ext_stats = {}
        self.url_reqs = []
        self.parse_files = False
        self.tab = JPanel(GridBagLayout())
        self.view_port_text = JTextArea("===SpyDir===")
        self.delim = JTextField(30)
        self.ext_white_list = JTextField(30)
        # I'm not sure if these fields are necessary still
        # why not just use Burp func to handle this?
        # leaving them in case I need it for the HTTP handler later
        # self.cookies = JTextField(30)
        # self.headers = JTextField(30)
        self.url = JTextField(30)
        self.parent_window = parent
        self.plugins = {}
        self.loaded_p_list = set()
        self.loaded_plugins = False
        self.config['Plugin Folder'] = None
        self.double_click = False
        self.source_input = ""
        self.print_stats = True
        self.curr_conf = JLabel()
        self.window = JFrame("Select plugins",
                             preferredSize=(200, 250),
                             windowClosing=self.p_close)
        self.window.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE)
        self.window.setVisible(False)
        self.path_vars = JTextField(30)


        # Initialize local stuff
        tab_constraints = GridBagConstraints()
        status_field = JScrollPane(self.view_port_text)

        # Configure view port
        self.view_port_text.setEditable(False)

        labels = self.build_ui()

        # Add things to rows
        tab_constraints.anchor = GridBagConstraints.FIRST_LINE_END
        tab_constraints.gridx = 1
        tab_constraints.gridy = 0
        tab_constraints.fill = GridBagConstraints.HORIZONTAL
        self.tab.add(JButton(
            "Resize screen", actionPerformed=self.resize),
                     tab_constraints)
        tab_constraints.gridx = 0
        tab_constraints.gridy = 1
        tab_constraints.anchor = GridBagConstraints.FIRST_LINE_START
        self.tab.add(labels, tab_constraints)

        tab_constraints.gridx = 1
        tab_constraints.gridy = 1
        tab_constraints.fill = GridBagConstraints.BOTH
        tab_constraints.weightx = 1.0
        tab_constraints.weighty = 1.0

        tab_constraints.anchor = GridBagConstraints.FIRST_LINE_END
        self.tab.add(status_field, tab_constraints)
        try:
            self._callbacks.customizeUiComponent(self.tab)
        except Exception:
            pass

    def build_ui(self):
        """Builds the configuration screen"""
        labels = JPanel(GridLayout(21, 1))
        checkbox = JCheckBox("Attempt to parse files for URL patterns?",
                             False, actionPerformed=self.set_parse)
        stats_box = JCheckBox("Show stats?", True,
                              actionPerformed=self.set_show_stats)
        # The two year old in me is laughing heartily
        plug_butt = JButton("Specify plugins location",
                            actionPerformed=self.set_plugin_loc)
        load_plug_butt = JButton("Select plugins",
                                 actionPerformed=self.p_build_ui)
        parse_butt = JButton("Parse directory", actionPerformed=self.parse)
        clear_butt = JButton("Clear text", actionPerformed=self.clear)
        spider_butt = JButton("Send to Spider", actionPerformed=self.scan)
        save_butt = JButton("Save config", actionPerformed=self.save)
        rest_butt = JButton("Restore config", actionPerformed=self.restore)
        source_butt = JButton("Input Source File/Directory",
                              actionPerformed=self.get_source_input)

        # Build grid
        labels.add(source_butt)
        labels.add(self.curr_conf)
        labels.add(JLabel("String Delimiter:"))
        labels.add(self.delim)
        labels.add(JLabel("Extension Whitelist:"))
        labels.add(self.ext_white_list)
        labels.add(JLabel("URL:"))
        labels.add(self.url)
        labels.add(JLabel("Path Variables"))
        labels.add(self.path_vars)
        # Leaving these here for now.
        # labels.add(JLabel("Cookies:"))
        # labels.add(self.cookies)
        # labels.add(JLabel("HTTP Headers:"))
        # labels.add(self.headers)
        labels.add(checkbox)
        labels.add(stats_box)
        labels.add(plug_butt)
        labels.add(parse_butt)
        labels.add(JButton("Show all endpoints",
                           actionPerformed=self.print_endpoints))
        labels.add(clear_butt)
        labels.add(spider_butt)
        labels.add(JLabel(""))
        labels.add(save_butt)
        labels.add(rest_butt)
        labels.add(load_plug_butt)
        # Tool tips!
        self.delim.setToolTipText("Use to manipulate the final URL. "
                                  "See About tab for example.")
        self.ext_white_list.setToolTipText("Define a comma delimited list of"
                                           " file extensions to parse. Use *"
                                           " to parse all files.")
        self.url.setToolTipText("Enter the target URL")
        checkbox.setToolTipText("Parse files line by line using plugins"
                                " to enumerate language/framework specific"
                                " endpoints")
        parse_butt.setToolTipText("Attempt to enumerate application endpoints")
        clear_butt.setToolTipText("Clear status window and the parse results")
        spider_butt.setToolTipText("Process discovered endpoints")
        save_butt.setToolTipText("Saves the current config settings")
        rest_butt.setToolTipText("<html>Restores previous config settings:"
                                 "<br/>-Input Directory<br/>-String Delim"
                                 "<br/>-Ext WL<br/>-URL<br/>-Plugins")
        source_butt.setToolTipText("Select the application's "
                                   "source directory or file to parse")
        self.path_vars.setToolTipText("Supply a JSON object with values"
                                      "for dynamically enumerated query"
                                      "string variables")

        return labels

    def set_url(self, menu_url):
        """Changes the configuration URL to the one from the menu event"""
        self.url.setText(menu_url)

    # Event functions
    def set_parse(self, event):
        """
        Handles the click event from the UI checkbox
        to attempt code level parsing
        """
        self.parse_files = not self.parse_files
        if self.parse_files:
            if not self.loaded_plugins:
                self._plugins_missing_warning()

    def restore(self, event):
        """Attempts to restore the previously saved configuration."""
        jdump = None
        try:
            jdump = loads(self._callbacks.loadExtensionSetting("config"))
        except Exception as exc:  # Generic exception thrown directly to user
            self.update_scroll(
                "[!!] Error during restore!\n\tException: %s" % str(exc))
        if jdump is not None:
            self.url.setText(jdump.get('URL'))
            # self.cookies.setText(jdump.get('Cookies'))
            # self.headers.setText(jdump.get("Headers"))
            ewl = ""
            for ext in jdump.get('Extension Whitelist'):
                ewl += ext + ", "
            self.ext_white_list.setText(ewl[:-2])
            self.delim.setText(jdump.get('String Delimiter'))
            self.source_input = jdump.get("Input Directory")
            self.config['Plugin Folder'] = jdump.get("Plugin Folder")
            if (self.config['Plugin Folder'] is not None and
                    (len(self.plugins.values()) < 1)):
                self._load_plugins(self.config['Plugin Folder'])
            self._update()
            self.update_scroll("[^] Restore complete!")
        else:
            self.update_scroll("[!!] Restore failed!")

    def save(self, event=None):
        """
        Saves the configuration details to a Burp Suite's persistent store.
        """
        self._update()
        try:
            if not self._callbacks.isInScope(URL(self.url.getText())):
                self.update_scroll("[!!] URL provided is NOT in Burp Scope!")
        except MalformedURLException:  # If url field is blank we'll
            pass                       # still save the settings.
        try:
            self._callbacks.saveExtensionSetting("config", dumps(self.config))
            self.update_scroll("[^] Settings saved!")
        except Exception:
            self.update_scroll("[!!] Error saving settings to Burp Suite!")

    def parse(self, event):
        """
        Handles the click event from the UI.
        Attempts to parse the given directory
            (and/or source files) for url endpoints
        Saves the items found within the url_reqs list
        """
        self._update()

        file_set = set()
        fcount = 0
        other_dirs = set()
        self.ext_stats = {}
        if self.loaded_plugins:
            self.update_scroll("[^] Attempting to parse files" +
                               " for URL patterns. This might take a minute.")
        if path.isdir(self.source_input):
            for dirname, _, filenames in walk(self.source_input):
                for filename in filenames:
                    fcount += 1
                    ext = path.splitext(filename)[1]
                    count = self.ext_stats.get(ext, 0) + 1
                    filename = "%s/%s" % (dirname, filename)
                    self.ext_stats.update({ext: count})
                    if self.parse_files and self._ext_test(ext):
                        # i can haz threading?
                        file_set.update(self._code_as_endpoints(filename, ext))
                    elif self._ext_test(ext):
                        r_files, oths = self._files_as_endpoints(filename, ext)
                        file_set.update(r_files)
                        other_dirs.update(oths)
        elif path.isfile(self.source_input):
            ext = path.splitext(self.source_input)[1]
            file_set.update(self._code_as_endpoints(self.source_input, ext))
        else:
            self.update_scroll("[!!] Input Directory is not valid!")
        if len(other_dirs) > 0:
            self.update_scroll("[*] Found files matching file extension in:\n")
            for other_dir in other_dirs:
                self.update_scroll(" " * 4 + "%s\n" % other_dir)
        self._handle_path_vars(file_set)
        self._print_parsed_status(fcount)
        return (other_dirs, self.url_reqs)

    def _handle_path_vars(self, file_set):
        proto = 'http://'
        for item in file_set:
            if item.startswith("http://") or item.startswith("https://"):
                proto = item.split("//")[0] + '//'
                item = item.replace(proto, "")
                item = self._path_vars(item)
            self.url_reqs.append(proto + item.replace('//', '/'))

    def _path_vars(self, item):
        p_vars = None
        if self.path_vars.getText():
            try:
                p_vars = loads(str(self.path_vars.getText()))
            except:
                self.update_scroll("[!] Error reading supplied Path Variables!")
        if p_vars is not None:
            rep_str = ""
            try:
                for k in p_vars.keys():
                    rep_str += "[^] Replacing %s with %s!\n" % (k, str(p_vars.get(k)))
                self.update_scroll(rep_str)
                for k in p_vars.keys():
                    if str(k) in item:
                        item = item.replace(k, str(p_vars.get(k)))
            except AttributeError:
                self.update_scroll("[!] Error reading supplied Path Variables! This needs to be a JSON dictionary!")
        return item
            
            
    def scan(self, event):
        """
        handles the click event from the UI.
        Adds the given URL to the burp scope and sends the requests
        to the burp spider
        """
        temp_url = self.url.getText()
        if not self._callbacks.isInScope(URL(temp_url)):
            if not self.double_click:
                self.update_scroll("[!!] URL is not in scope! Press Send to "
                                   "Spider again to add to scope and scan!")
                self.double_click = True
                return
            else:
                self._callbacks.sendToSpider(URL(temp_url))
        self.update_scroll(
            "[^] Sending %d requests to Spider" % len(self.url_reqs))
        for req in self.url_reqs:
            self._callbacks.sendToSpider(URL(req))

    def clear(self, event):
        """Clears the viewport and the current parse exts"""
        self.view_port_text.setText("===SpyDir===")
        self.ext_stats = {}

    def print_endpoints(self, event):
        """Prints the discovered endpoints to the status window."""
        req_str = ""
        if len(self.url_reqs) > 0:
            self.update_scroll("[*] Printing all discovered endpoints:")
            for req in sorted(self.url_reqs):
                req_str += "    %s\n" % req
        else:
            req_str = "[!!] No endpoints discovered"
        self.update_scroll(req_str)

    def set_show_stats(self, event):
        """Modifies the show stats setting"""
        self.print_stats = not self.print_stats

    def get_source_input(self, event):
        """Sets the source dir/file for parsing"""
        source_chooser = JFileChooser()
        source_chooser.setFileSelectionMode(
            JFileChooser.FILES_AND_DIRECTORIES)
        source_chooser.showDialog(self.tab, "Choose Source Location")
        chosen_source = source_chooser.getSelectedFile()
        try:
            self.source_input = chosen_source.getAbsolutePath()
        except AttributeError:
            pass
        if self.source_input is not None:
            self.update_scroll("[*] Source location: %s" % self.source_input)
            self.curr_conf.setText(self.source_input)

    # Plugin functions
    def _parse_file(self, filename, file_url):
        """
        Attempts to parse a file with the loaded plugins
        Returns set of endpoints
        """
        file_set = set()
        with open(filename, 'r') as plug_in:
            lines = plug_in.readlines()
        ext = path.splitext(filename)[1].upper()
        if ext in self.plugins.keys() and self._ext_test(ext):
            for plug in self.plugins.get(ext):
                if plug.enabled:
                    res = plug.run(lines)
                    if len(res) > 0:
                        for i in res:
                            i = file_url + i
                            file_set.add(i)
        elif ext == '.TXT' and self._ext_test(ext):
            for i in lines:
                i = file_url + i
                file_set.add(i.strip())
        return file_set

    def set_plugin_loc(self, event):
        """Attempts to load plugins from a specified location"""
        if self.config['Plugin Folder'] is not None:
            choose_plugin_location = JFileChooser(self.config['Plugin Folder'])
        else:
            choose_plugin_location = JFileChooser()
        choose_plugin_location.setFileSelectionMode(
            JFileChooser.DIRECTORIES_ONLY)
        choose_plugin_location.showDialog(self.tab, "Choose Folder")
        chosen_folder = choose_plugin_location.getSelectedFile()
        self.config['Plugin Folder'] = chosen_folder.getAbsolutePath()
        self._load_plugins(self.config['Plugin Folder'])

    def _load_plugins(self, folder):
        """
        Parses a local directory to get the plugins
            related to code level scanning
        """
        report = ""
        if len(self.plugins.keys()) > 0:
            report = "[^] Plugins reloaded!"
        for _, _, filenames in walk(folder):
            for p_name in filenames:
                n_e = path.splitext(p_name)  # n_e = name_extension
                if n_e[1] == ".py":
                    f_loc = "%s/%s" % (folder, p_name)
                    loaded_plug = self._validate_plugin(n_e[0], f_loc)
                    if loaded_plug:
                        for p in self.loaded_p_list:
                            if p.get_name() == loaded_plug.get_name():
                                self.loaded_p_list.discard(p)
                        self.loaded_p_list.add(loaded_plug)
                        if not report.startswith("[^]"):
                            report += "%s loaded\n" % loaded_plug.get_name()

        self._dictify(self.loaded_p_list)
        if len(self.plugins.keys()) > 0:
            self.loaded_plugins = True
        else:
            report = "[!!] Plugins load failure"
            self.loaded_plugins = False
        self.update_scroll(report)
        return report

    def _validate_plugin(self, p_name, f_loc):
        """
        Attempts to verify the manditory plugin functions to prevent broken
        plugins from loading.
        Generates an error message if plugin does not contain an appropriate
        function.
        """
        # Load the plugin
        try:
            plug = load_source(p_name, f_loc)
        except Exception as exc:  # this needs to be generic.
            self.update_scroll(
                "[!!] Error loading: %s\n\tType:%s Error: %s"
                % (f_loc, type(exc), str(exc)))
        # Verify the plugin's functions
        funcs = dir(plug)
        err = []
        if "get_name" not in funcs:
            err.append("get_name()")
        if "get_ext" not in funcs:
            err.append("get_ext()")
        if "run" not in funcs:
            err.append("run()")

        # Report errors & return
        if len(err) < 1:
            return Plugin(plug, True)
        for issue in err:
            self.update_scroll("[!!] %s is missing: %s func" %
                               (p_name, issue))
        return None

    def _dictify(self, plist):
        """Converts the list of loaded plugins (plist) into a dictionary"""
        for p in plist:
            exts = p.get_ext().upper()
            for ext in exts.split(","):
                prev_load = self.plugins.get(ext, [])
                prev_load.append(p)
                self.plugins[ext] = prev_load

    # Status window functions
    def _print_parsed_status(self, fcount):
        """Prints the parsed directory status information"""
        if self.parse_files and not self.loaded_plugins:
            self._plugins_missing_warning()
        if len(self.url_reqs) > 0:
            self.update_scroll("[*] Example URL: %s" % self.url_reqs[0])

        if self.print_stats:
            report = (("[*] Found: %r files to be requested.\n\n" +
                       "[*] Stats: \n    " +
                       "Found: %r files.\n") % (len(self.url_reqs), fcount))
            if len(self.ext_stats) > 0:
                report += ("[*] Extensions found: %s"
                           % str(dumps(self.ext_stats,
                                       sort_keys=True, indent=4)))
        else:
            report = ("[*] Found: %r files to be requested.\n" %
                      len(self.url_reqs))
        self.update_scroll(report)
        return report

    def _plugins_missing_warning(self):
        """Prints a warning message"""
        self.update_scroll("[!!] No plugins loaded!")

    def update_scroll(self, text):
        """Updates the view_port_text with the new information"""
        temp = self.view_port_text.getText().strip()
        if text not in temp or text[0:4] == "[!!]":
            self.view_port_text.setText("%s\n%s" % (temp, text))
        elif not temp.endswith("[^] Status unchanged"):
            self.view_port_text.setText("%s\n[^] Status unchanged" % temp)

    # Internal functions
    def _code_as_endpoints(self, filename, ext):
        file_set = set()
        file_url = self.config.get("URL")
        if self.loaded_plugins or ext == '.txt':
            if self._ext_test(ext):
                file_set.update(
                    self._parse_file(filename, file_url))
            else:
                file_set.update(
                    self._parse_file(filename, file_url))
        return file_set

    def _files_as_endpoints(self, filename, ext):
        """Generates endpoints via files with the appropriate extension(s)"""
        file_url = self.config.get("URL")
        broken_splt = ""
        other_dirs = set()  # directories outside of the String Delim.
        file_set = set()
        str_del = self.config.get("String Delimiter")
        if not str_del:
            self.update_scroll("[!!] No available String Delimiter!")
            return
        spl_str = filename.split(str_del)

        try:
            # Fix for index out of bounds exception while parsing
            # subfolders _not_ included by the split
            if len(spl_str) > 1:
                file_url += ((spl_str[1])
                             .replace('\\', '/'))
            else:
                broken_splt = filename.split(self.source_input)[1]
                other_dirs.add(broken_splt)
        except Exception as exc:  # Generic exception thrown directly to user
            self.update_scroll("[!!] Error parsing: " +
                               "%s\n\tException: %s"
                               % (filename, str(exc)))
        if self._ext_test(ext):
            if file_url != self.config.get("URL"):
                file_set.add(file_url)
        else:
            other_dirs.discard(broken_splt)
        return file_set, other_dirs

    def _ext_test(self, ext):
        """Litmus test for extension whitelist"""
        val = False
        if "*" in self.config.get("Extension Whitelist"):
            val = True
        else:
            val = (len(ext) > 0 and
                   (ext.strip().upper()
                    in self.config.get("Extension Whitelist")))
        return val

    def _update(self):
        """Updates internal data"""
        self.config["Input Directory"] = self.source_input
        self.config["String Delimiter"] = self.delim.getText()

        white_list_text = self.ext_white_list.getText()
        self.config["Extension Whitelist"] = white_list_text.upper().split(',')
        file_url = self.url.getText()
        if not (file_url.startswith('https://') or file_url.startswith('http://')):
            self.update_scroll("[!] Assuming protocol! Default value: 'http://'")
            file_url = 'http://' + file_url
            self.url.setText(file_url)

        if not file_url.endswith('/') and file_url != "":
            file_url += '/'

        self.config["URL"] = file_url
        # self.config["Cookies"] = self.cookies.getText()
        # self.config["Headers"] = self.headers.getText()
        del self.url_reqs[:]
        self.curr_conf.setText(self.source_input)

    # Window sizing functions
    def resize(self, event):
        """Resizes the window to better fit Burp"""
        if self.parent_window is not None:
            par_size = self.parent_window.getSize()
            par_size.setSize(par_size.getWidth() * .99,
                             par_size.getHeight() * .9)
            self.tab.setPreferredSize(par_size)
            self.parent_window.validate()
            self.parent_window.switch_focus()

    def p_close(self, event):
        """
        Handles the window close event.
        """
        self.window.setVisible(False)
        self.window.dispose()

    def p_build_ui(self, event):
        """
        Adds a list of checkboxes, one for each loaded plugin
        to the Selct plugins window
        """
        if not self.loaded_p_list:
            self.update_scroll("[!!] No plugins loaded!")
            return

        scroll_pane = JScrollPane()
        scroll_pane.setPreferredSize(Dimension(200, 250))
        check_frame = JPanel(GridBagLayout())
        constraints = GridBagConstraints()
        constraints.fill = GridBagConstraints.HORIZONTAL
        constraints.gridy = 0
        constraints.anchor = GridBagConstraints.FIRST_LINE_START

        for plug in self.loaded_p_list:
            check_frame.add(JCheckBox(plug.get_name(), plug.enabled,
                                      actionPerformed=self.update_box),
                            constraints)
            constraints.gridy += 1

        vport = JViewport()
        vport.setView(check_frame)
        scroll_pane.setViewport(vport)
        self.window.contentPane.add(scroll_pane)
        self.window.pack()
        self.window.setVisible(True)

    def update_box(self, event):
        """
        Handles the check/uncheck event for the plugin's box.
        """
        for plug in self.loaded_p_list:
            if plug.get_name() == event.getActionCommand():
                plug.enabled = not plug.enabled
                if plug.enabled:
                    self.update_scroll("[^] Enabled: %s" %
                                       event.getActionCommand())
                else:
                    self.update_scroll("[^] Disabled: %s" %
                                       event.getActionCommand())

    # ITab required functions
    @staticmethod
    def getTabCaption():
        """Returns the name of the Burp Suite Tab"""
        return "SpyDir"

    def getUiComponent(self):
        """Returns the UI component for the Burp Suite tab"""
        return self.tab
Ejemplo n.º 18
0
class BurpExtender(IBurpExtender, ITab, IIntruderPayloadProcessor,
                   IIntruderPayloadGeneratorFactory):

    # Tool details
    TITLE = 'Password Spray'
    AUTHOR = '0xZDH'
    VERSION = 'v1.0.0'
    DESC = 'This extension allows a user to specify a lockout policy in order to automate a password spray attack via Intruder.'

    # Global variables
    filename = ''  # Password file
    lockout_attempts = 0  # Number of current passwords attempts

    # This will log to the current folder this extension is located within because
    # I didn't feel like checking the OS and specifying the log locations for each.
    logger = logging.getLogger()
    handler = RotatingFileHandler('password_spray.log',
                                  maxBytes=10**5,
                                  backupCount=2)
    logger.addHandler(handler)
    """ Implement IBurpExtender  """
    def registerExtenderCallbacks(self, callbacks):
        self._callbacks = callbacks
        self._helpers = self._callbacks.getHelpers()
        self._callbacks.setExtensionName(self.TITLE)
        self._callbacks.registerIntruderPayloadGeneratorFactory(self)
        self._callbacks.registerIntruderPayloadProcessor(self)

        self.initTab()  # Load Burp tab
        self._callbacks.addSuiteTab(self)

        print('Name: \t\t' + self.TITLE)
        print('Author: \t' + self.AUTHOR)
        print('Version: \t' + self.VERSION)
        print('Description: \t' + self.DESC)
        print('\n[+] Extension loaded.')

    """ Implement ITab """

    def getTabCaption(self):
        return self.TITLE

    def getUiComponent(self):
        return self.tab

    """ Implement IIntruderPayloadGeneratorFactory """

    def getGeneratorName(self):
        return self.TITLE

    def createNewInstance(self, attack):
        self.lockout_attempts = 0  # Reset the number of lockout attempts for each new attack
        return IntruderPayloadGenerator(self.filename)

    """ Implement IIntruderPayloadProcessor """

    def getProcessorName(self):
        return self.TITLE

    """ This function sleeps inbetween attempt cycles. If the attack is exited prior to finishing,
        there are payloads held in memory that are equal to the number of intruder threads running.
        The payloads in memory do not get purged when an attack is exited which means they will go
        be sent once the sleep method has concluded. These paylaods that are sent after an attack
        has been exited can effect the lockout reset time for specific users.

        It is recommended that the Logger++ extension is used to identify which and when were the last
        usernames/passwords attempted to allow for a proper wait time before continuing again. """

    def processPayload(self, currentPayload, originalPayload, baseValue):
        if (self.lockout_attempts >= int(self.attemptField.text)):
            self.lockout_attempts = 0  # Reset lockout count before we run the next iteration
            sleep(float(self.lockoutField.text) * 60)

        # Only increment the lockout attempts counter right before we send the payload
        self.lockout_attempts += 1

        # Write to the log file: [timestamp] password
        self.log(currentPayload)

        # Return the current, unmodified payload
        return currentPayload

    """ Build the Burp tab layout """

    def initTab(self):

        self.tab = JPanel()

        self.titleLabel = JLabel(self.TITLE)
        self.titleLabel.setFont(Font('Tahoma', 1, 15))
        self.titleLabel.setForeground(Color(255, 102,
                                            51))  # Set to Burp-like orange

        self.infoLabel = JLabel(
            'Specify the lockout policy of the target: Number of login attempts that won\'t lock out an account '
            'and the time to wait for the lockout threshold to reset.')
        self.infoLabel.setFont(Font('Tahoma', 0, 12))

        self.attemptLabel = JLabel('Number of attempts:')
        self.attemptField = JTextField('3', 15)  # Default to 3

        self.lockoutLabel = JLabel('Lockout reset time (minutes):')
        self.lockoutField = JTextField('5', 15)  # Default to 5

        self.fileButton = JButton('Password File',
                                  actionPerformed=self.getPasswordFile)
        self.fileLabel = JLabel('')

        self.setUpa = JLabel('Intruder Set Up:')
        self.setUpa.setFont(Font('Tahoma', 1, 12))

        self.setUpba = JLabel('    Intruder Attacker Type:')
        self.setUpbb = JLabel('Cluster Bomb')
        self.setUpca = JLabel('    Payload Set 1 Type:')
        self.setUpcb = JLabel('Simple List')
        self.setUpda = JLabel('    Payload Set 1 Options:')
        self.setUpdb = JLabel(
            'Load -> File containing list of emails/users to spray')
        self.setUpea = JLabel('    Payload Set 2 Type:')
        self.setUpeb = JLabel('Extension-generated')
        self.setUpfa = JLabel('    Payload Set 2 Options:')
        self.setUpfb = JLabel(
            'Select generator -> Extension payload generator -> %s' %
            self.TITLE)
        self.setUpga = JLabel('    Payload Set 2 Processing:')
        self.setUpgb = JLabel(
            'Add -> Invoke Burp Extension -> Select processor -> %s' %
            self.TITLE)

        # Build warning for users to understand
        self.warningLabela = JLabel('*** WARNING ***')
        self.warningLabela.setFont(Font('Tahoma', 1, 15))

        self.warningLabelba = JLabel(
            'If an Intruder attack is is exited prior to finishing, there will still be payloads held in memory that are equal to'
        )
        self.warningLabelbb = JLabel(
            'the number of intruder threads running. The payloads stored in memory do not get removed when an attack is exited.'
        )
        self.warningLabelbc = JLabel(
            'Payloads in memory will be sent once their sleep functions have concluded (based on user-defined \'lockout timer\').'
        )
        self.warningLabelbd = JLabel(
            'These paylaods that are sent after an attack has been exited effects the lockout reset time.'
        )

        self.warningLabelca = JLabel(
            'It is recommended that the Logger++ extension is used to identify which and when were the last usernames/passwords'
        )
        self.warningLabelcb = JLabel(
            'attempted following the sleep function to allow for a proper wait time before continuing again.'
        )

        self.warningLabelda = JLabel(
            'If exited prematurely, Before running a new attack, wait at least the time specified via \'Lockout reset time\''
        )
        self.warningLabeldb = JLabel(
            'to identify the last sent password attempt, then wait the same time limit again to fully reset the lockout timer.'
        )

        layout = GroupLayout(self.tab)
        self.tab.setLayout(layout)

        # Reference: https://github.com/SmeegeSec/Burp-Importer
        # Definitely a cleaner way to do this, but not optimizing since its just UI code - and Java...
        layout.setHorizontalGroup(
            layout.createParallelGroup(GroupLayout.Alignment.LEADING).addGroup(
                layout.createSequentialGroup().addGap(15).addGroup(
                    layout.createParallelGroup(
                        GroupLayout.Alignment.LEADING).addComponent(
                            self.titleLabel).addComponent(self.infoLabel).
                    addGroup(layout.createSequentialGroup().addGroup(
                        layout.createParallelGroup(
                            GroupLayout.Alignment.TRAILING).addComponent(
                                self.attemptLabel, GroupLayout.PREFERRED_SIZE,
                                200, GroupLayout.PREFERRED_SIZE)
                    ).addPreferredGap(
                        LayoutStyle.ComponentPlacement.UNRELATED).addGroup(
                            layout.createParallelGroup(
                                GroupLayout.Alignment.LEADING).addComponent(
                                    self.attemptField,
                                    GroupLayout.PREFERRED_SIZE, 150,
                                    GroupLayout.PREFERRED_SIZE))).
                    addGroup(layout.createSequentialGroup().addGroup(
                        layout.createParallelGroup(
                            GroupLayout.Alignment.TRAILING).addComponent(
                                self.lockoutLabel, GroupLayout.PREFERRED_SIZE,
                                200, GroupLayout.PREFERRED_SIZE)
                    ).addPreferredGap(
                        LayoutStyle.ComponentPlacement.UNRELATED).addGroup(
                            layout.createParallelGroup(
                                GroupLayout.Alignment.LEADING).addComponent(
                                    self.lockoutField,
                                    GroupLayout.PREFERRED_SIZE, 150,
                                    GroupLayout.PREFERRED_SIZE))).
                    addGroup(layout.createSequentialGroup().addGroup(
                        layout.createParallelGroup(
                            GroupLayout.Alignment.TRAILING).addComponent(
                                self.fileButton, GroupLayout.PREFERRED_SIZE,
                                150, GroupLayout.PREFERRED_SIZE)
                    ).addPreferredGap(
                        LayoutStyle.ComponentPlacement.UNRELATED).addGroup(
                            layout.createParallelGroup(
                                GroupLayout.Alignment.LEADING).addComponent(
                                    self.fileLabel, GroupLayout.PREFERRED_SIZE,
                                    400, GroupLayout.PREFERRED_SIZE)
                        )).addGroup(layout.createSequentialGroup().addGroup(
                            layout.createParallelGroup(
                                GroupLayout.Alignment.TRAILING).addComponent(
                                    self.setUpa, GroupLayout.PREFERRED_SIZE,
                                    150, GroupLayout.PREFERRED_SIZE))).
                    addGroup(layout.createSequentialGroup().addGroup(
                        layout.createParallelGroup(
                            GroupLayout.Alignment.TRAILING).addComponent(
                                self.setUpba, GroupLayout.PREFERRED_SIZE, 210,
                                GroupLayout.PREFERRED_SIZE)
                    ).addPreferredGap(
                        LayoutStyle.ComponentPlacement.UNRELATED).addGroup(
                            layout.createParallelGroup(
                                GroupLayout.Alignment.LEADING).addComponent(
                                    self.setUpbb, GroupLayout.PREFERRED_SIZE,
                                    350, GroupLayout.PREFERRED_SIZE))).
                    addGroup(layout.createSequentialGroup().addGroup(
                        layout.createParallelGroup(
                            GroupLayout.Alignment.TRAILING).addComponent(
                                self.setUpca, GroupLayout.PREFERRED_SIZE, 210,
                                GroupLayout.PREFERRED_SIZE)
                    ).addPreferredGap(
                        LayoutStyle.ComponentPlacement.UNRELATED).addGroup(
                            layout.createParallelGroup(
                                GroupLayout.Alignment.LEADING).addComponent(
                                    self.setUpcb, GroupLayout.PREFERRED_SIZE,
                                    350, GroupLayout.PREFERRED_SIZE))).
                    addGroup(layout.createSequentialGroup().addGroup(
                        layout.createParallelGroup(
                            GroupLayout.Alignment.TRAILING).addComponent(
                                self.setUpda, GroupLayout.PREFERRED_SIZE, 210,
                                GroupLayout.PREFERRED_SIZE)
                    ).addPreferredGap(
                        LayoutStyle.ComponentPlacement.UNRELATED).addGroup(
                            layout.createParallelGroup(
                                GroupLayout.Alignment.LEADING).addComponent(
                                    self.setUpdb, GroupLayout.PREFERRED_SIZE,
                                    350, GroupLayout.PREFERRED_SIZE))).
                    addGroup(layout.createSequentialGroup().addGroup(
                        layout.createParallelGroup(
                            GroupLayout.Alignment.TRAILING).addComponent(
                                self.setUpea, GroupLayout.PREFERRED_SIZE, 210,
                                GroupLayout.PREFERRED_SIZE)
                    ).addPreferredGap(
                        LayoutStyle.ComponentPlacement.UNRELATED).addGroup(
                            layout.createParallelGroup(
                                GroupLayout.Alignment.LEADING).addComponent(
                                    self.setUpeb, GroupLayout.PREFERRED_SIZE,
                                    350, GroupLayout.PREFERRED_SIZE))).
                    addGroup(layout.createSequentialGroup().addGroup(
                        layout.createParallelGroup(
                            GroupLayout.Alignment.TRAILING).addComponent(
                                self.setUpfa, GroupLayout.PREFERRED_SIZE, 210,
                                GroupLayout.PREFERRED_SIZE)
                    ).addPreferredGap(
                        LayoutStyle.ComponentPlacement.UNRELATED).addGroup(
                            layout.createParallelGroup(
                                GroupLayout.Alignment.LEADING).addComponent(
                                    self.setUpfb, GroupLayout.PREFERRED_SIZE,
                                    500, GroupLayout.PREFERRED_SIZE))).
                    addGroup(layout.createSequentialGroup().addGroup(
                        layout.createParallelGroup(
                            GroupLayout.Alignment.TRAILING).addComponent(
                                self.setUpga, GroupLayout.PREFERRED_SIZE, 210,
                                GroupLayout.PREFERRED_SIZE)
                    ).addPreferredGap(
                        LayoutStyle.ComponentPlacement.UNRELATED).addGroup(
                            layout.createParallelGroup(
                                GroupLayout.Alignment.LEADING).addComponent(
                                    self.setUpgb, GroupLayout.PREFERRED_SIZE,
                                    500, GroupLayout.PREFERRED_SIZE)))
                    # Add warning label
                    .addGroup(layout.createSequentialGroup().addGroup(
                        layout.createParallelGroup(
                            GroupLayout.Alignment.TRAILING).addComponent(
                                self.warningLabela, GroupLayout.PREFERRED_SIZE,
                                150, GroupLayout.PREFERRED_SIZE)))
                    # Add first warning text
                    .addGroup(layout.createSequentialGroup().addGroup(
                        layout.createParallelGroup(
                            GroupLayout.Alignment.TRAILING).addComponent(
                                self.warningLabelba,
                                GroupLayout.PREFERRED_SIZE, 750,
                                GroupLayout.PREFERRED_SIZE)
                    )).addGroup(layout.createSequentialGroup().addGroup(
                        layout.createParallelGroup(
                            GroupLayout.Alignment.TRAILING).addComponent(
                                self.warningLabelbb,
                                GroupLayout.PREFERRED_SIZE, 750,
                                GroupLayout.PREFERRED_SIZE)
                    )).addGroup(layout.createSequentialGroup().addGroup(
                        layout.createParallelGroup(
                            GroupLayout.Alignment.TRAILING).addComponent(
                                self.warningLabelbc,
                                GroupLayout.PREFERRED_SIZE, 750,
                                GroupLayout.PREFERRED_SIZE)
                    )).addGroup(layout.createSequentialGroup().addGroup(
                        layout.createParallelGroup(
                            GroupLayout.Alignment.TRAILING).addComponent(
                                self.warningLabelbd,
                                GroupLayout.PREFERRED_SIZE, 750,
                                GroupLayout.PREFERRED_SIZE)))
                    # Add second warning text
                    .addGroup(layout.createSequentialGroup().addGroup(
                        layout.createParallelGroup(
                            GroupLayout.Alignment.TRAILING).addComponent(
                                self.warningLabelca,
                                GroupLayout.PREFERRED_SIZE, 750,
                                GroupLayout.PREFERRED_SIZE)
                    )).addGroup(layout.createSequentialGroup().addGroup(
                        layout.createParallelGroup(
                            GroupLayout.Alignment.TRAILING).addComponent(
                                self.warningLabelcb,
                                GroupLayout.PREFERRED_SIZE, 750,
                                GroupLayout.PREFERRED_SIZE)))
                    # Add third warning text
                    .addGroup(layout.createSequentialGroup().addGroup(
                        layout.createParallelGroup(
                            GroupLayout.Alignment.TRAILING).addComponent(
                                self.warningLabelda,
                                GroupLayout.PREFERRED_SIZE, 750,
                                GroupLayout.PREFERRED_SIZE)
                    )).addGroup(layout.createSequentialGroup().addGroup(
                        layout.createParallelGroup(
                            GroupLayout.Alignment.TRAILING).addComponent(
                                self.warningLabeldb,
                                GroupLayout.PREFERRED_SIZE, 750,
                                GroupLayout.PREFERRED_SIZE))))))

        layout.setVerticalGroup(
            layout.createParallelGroup(GroupLayout.Alignment.LEADING).addGroup(
                layout.createSequentialGroup().addGap(15).addComponent(
                    self.titleLabel).addGap(10).addComponent(self.infoLabel).
                addGroup(
                    layout.createParallelGroup(GroupLayout.Alignment.LEADING).
                    addGroup(
                        layout.createSequentialGroup().addGap(25).addGroup(
                            layout.createParallelGroup(
                                GroupLayout.Alignment.BASELINE).addComponent(
                                    self.attemptLabel).addComponent(
                                        self.attemptField,
                                        GroupLayout.PREFERRED_SIZE,
                                        GroupLayout.DEFAULT_SIZE,
                                        GroupLayout.PREFERRED_SIZE)
                        ).addGap(15).addGroup(
                            layout.createParallelGroup(
                                GroupLayout.Alignment.BASELINE).addComponent(
                                    self.lockoutLabel).addComponent(
                                        self.lockoutField,
                                        GroupLayout.PREFERRED_SIZE,
                                        GroupLayout.DEFAULT_SIZE,
                                        GroupLayout.PREFERRED_SIZE)
                        ).addGap(30).addGroup(
                            layout.createParallelGroup(
                                GroupLayout.Alignment.BASELINE).addComponent(
                                    self.fileButton).addComponent(
                                        self.fileLabel,
                                        GroupLayout.PREFERRED_SIZE,
                                        GroupLayout.DEFAULT_SIZE,
                                        GroupLayout.PREFERRED_SIZE)
                        ).addGap(55).addGroup(
                            layout.createParallelGroup(
                                GroupLayout.Alignment.BASELINE).addComponent(
                                    self.setUpa)
                        ).addGap(10).addGroup(
                            layout.createParallelGroup(
                                GroupLayout.Alignment.BASELINE).addComponent(
                                    self.setUpba).addComponent(
                                        self.setUpbb,
                                        GroupLayout.PREFERRED_SIZE,
                                        GroupLayout.DEFAULT_SIZE,
                                        GroupLayout.PREFERRED_SIZE)
                        ).addGap(10).addGroup(
                            layout.createParallelGroup(
                                GroupLayout.Alignment.BASELINE).addComponent(
                                    self.setUpca).addComponent(
                                        self.setUpcb,
                                        GroupLayout.PREFERRED_SIZE,
                                        GroupLayout.DEFAULT_SIZE,
                                        GroupLayout.PREFERRED_SIZE)
                        ).addGap(10).addGroup(
                            layout.createParallelGroup(
                                GroupLayout.Alignment.BASELINE).addComponent(
                                    self.setUpda).addComponent(
                                        self.setUpdb,
                                        GroupLayout.PREFERRED_SIZE,
                                        GroupLayout.DEFAULT_SIZE,
                                        GroupLayout.PREFERRED_SIZE)
                        ).addGap(10).addGroup(
                            layout.createParallelGroup(
                                GroupLayout.Alignment.BASELINE).addComponent(
                                    self.setUpea).addComponent(
                                        self.setUpeb,
                                        GroupLayout.PREFERRED_SIZE,
                                        GroupLayout.DEFAULT_SIZE,
                                        GroupLayout.PREFERRED_SIZE)
                        ).addGap(10).addGroup(
                            layout.createParallelGroup(
                                GroupLayout.Alignment.BASELINE).addComponent(
                                    self.setUpfa).addComponent(
                                        self.setUpfb,
                                        GroupLayout.PREFERRED_SIZE,
                                        GroupLayout.DEFAULT_SIZE,
                                        GroupLayout.PREFERRED_SIZE)
                        ).addGap(10).addGroup(
                            layout.createParallelGroup(
                                GroupLayout.Alignment.BASELINE).addComponent(
                                    self.setUpga).addComponent(
                                        self.setUpgb,
                                        GroupLayout.PREFERRED_SIZE,
                                        GroupLayout.DEFAULT_SIZE,
                                        GroupLayout.PREFERRED_SIZE))
                        # Add warning label
                        .addGap(55).addGroup(
                            layout.createParallelGroup(
                                GroupLayout.Alignment.BASELINE).addComponent(
                                    self.warningLabela))
                        # Add first warning text
                        .addGap(10).addGroup(
                            layout.createParallelGroup(
                                GroupLayout.Alignment.BASELINE).addComponent(
                                    self.warningLabelba)).addGap(5).addGroup(
                                        layout.createParallelGroup(
                                            GroupLayout.Alignment.BASELINE).
                                        addComponent(self.warningLabelbb)).
                        addGap(5).addGroup(
                            layout.createParallelGroup(
                                GroupLayout.Alignment.BASELINE).addComponent(
                                    self.warningLabelbc)).addGap(5).addGroup(
                                        layout.createParallelGroup(
                                            GroupLayout.Alignment.BASELINE).
                                        addComponent(self.warningLabelbd))
                        # Add second warning text
                        .addGap(25).addGroup(
                            layout.createParallelGroup(
                                GroupLayout.Alignment.BASELINE).addComponent(
                                    self.warningLabelca)).addGap(5).addGroup(
                                        layout.createParallelGroup(
                                            GroupLayout.Alignment.BASELINE).
                                        addComponent(self.warningLabelcb))
                        # Add third warning text
                        .addGap(25).addGroup(
                            layout.createParallelGroup(
                                GroupLayout.Alignment.BASELINE).addComponent(
                                    self.warningLabelda)).addGap(5).addGroup(
                                        layout.createParallelGroup(
                                            GroupLayout.Alignment.BASELINE).
                                        addComponent(self.warningLabeldb))))))

    """ Retrieve password file """

    def getPasswordFile(self, event):
        self.passwordFile = JFileChooser()
        self.ret = self.passwordFile.showDialog(self.tab,
                                                "Choose Password File")
        self.filename = self.passwordFile.getSelectedFile().getCanonicalPath()
        self.fileLabel.setText(self.filename)

    """ Logging """

    def log(self, currentPayload):
        self.logger.warning(
            '[%s] %s' %
            (str(datetime.datetime.now()), currentPayload.tostring()))
class MenueFrame(JFrame, ActionListener, WindowFocusListener): # should extend JFrame
    def __init__(self):
        self.mainDir = ""

        self.setTitle("Dots Quality Check")
        self.setSize(250, 300)
        self.setLocation(20,120)
        self.addWindowFocusListener(self)
        
        self.Panel = JPanel(GridLayout(0,1))
        self.add(self.Panel)
        self.openNextButton = JButton("Open Next Random", actionPerformed=self.openRandom)
        self.Panel.add(self.openNextButton)
        self.saveButton = JButton("Save", actionPerformed=self.save, enabled=False)
        self.Panel.add(self.saveButton)
        self.cropButton = JButton("Crop values from here", actionPerformed=self.cropVals)
        self.Panel.add(self.cropButton)
        self.DiscardButton = JButton("Discard cell", actionPerformed=self.discardCell)
        self.Panel.add(self.DiscardButton)
        self.quitButton = JButton("Quit script",actionPerformed=self.quit)
        self.Panel.add(self.quitButton)

        annoPanel = JPanel()
        #add gridlayout
        self.wtRButton = JRadioButton("wt", actionCommand="wt")
        self.wtRButton.addActionListener(self)
        self.defectRButton = JRadioButton("Defect", actionCommand="defect")
        self.defectRButton.addActionListener(self)
        annoPanel.add(self.wtRButton)
        annoPanel.add(self.defectRButton)
        self.aButtonGroup = ButtonGroup()
        self.aButtonGroup.add(self.wtRButton)
        self.aButtonGroup.add(self.defectRButton)
      
        self.Panel.add(annoPanel)

        self.ProgBar = JProgressBar()
        self.ProgBar.setStringPainted(True)
        self.ProgBar.setValue(0)
        self.Panel.add(self.ProgBar)

        self.pathLabel = JLabel("-- No main directory chosen --")
        self.pathLabel.setHorizontalAlignment( SwingConstants.CENTER )
        self.Panel.add(self.pathLabel)
      
        WindowManager.addWindow(self)
        self.show()

    # - - - -   B U T T O N   M E T H O D S  - - - -
    # - - - - - -  - - - - - - - - - - - - - - - - -
    def openRandom(self, event):      # when click here: get random cell and meas.measure(csv, tif, savePath)
        if self.mainDir == "":
            self.mainDir = DirectoryChooser("Random QC - Please choose main directory containing ctrl and test folders").getDirectory()
            self.pathLabel.setText("MainDir: " + os.path.basename(os.path.split(self.mainDir)[0]))
        try:
            # should be complete disposal!
            self.cT.closeWindows()
        finally:
            inFiles = glob.glob(os.path.join(self.mainDir, "*", G_OPENSUBDIR, "val_*.csv"))  # glob.glob returns list of paths
            uncheckedCells = [cell(csvPath) for csvPath in inFiles if cell(csvPath).processed == False]
            if len(uncheckedCells) > 0:
                self.cell = random.choice(uncheckedCells)
                #update progressbar
                self.ProgBar.setMaximum(len(inFiles)-1)
                self.ProgBar.setValue(len(inFiles)-len(uncheckedCells))
                # open imp and resultstable
                self.cT = correctionTable(self.cell, self) #self, openPath_csv, mF
                self.RBActionListener.setCell(self.cell)
                # delete previous Radiobutton annotation
                self.wtRButton.setSelected(False)
                self.defectRButton.setSelected(True)
            else:
                print "All cells measured!"

    def save(self, event):
        savepath = self.cell.getQcCsvPath()
        anaphase = self.cell.getAnOn()
        timeInterval = self.cT.getImp().getCalibration().frameInterval
        annotation = self.getAnnotation()
        position = str(self.cell.position)
        cellIndex = str(self.cell.cellNo)
        if not os.path.exists(os.path.split(savepath)[0]): # check if save folder present.
            os.makedirs(os.path.split(savepath)[0]) # create save folder, if not present
        f = open(savepath, "w")
        # Position Cell Phenotype Frame Time AnOn Distance ch0x ch0y ch0z ch0vol ch1x ch1y ch1z ch1vol
        f.write("Position,Cell,Phenotype,Frame,Time,Anaphase,Distance,ch0x,ch0y,ch0z,ch0vol,ch1x,ch1y,ch1z,ch1vol\n")
        for i in range(self.cT.getLineCount()):
            frame, distance, a = self.cT.getLine(i).split("\t")
            corrFrame = str(int(frame)-int(anaphase))
            time = "%.f" % (round(timeInterval) * int(corrFrame))
            if distance == "NA":
                ch0x, ch0y, ch0z, ch0vol, ch1x, ch1y, ch1z, ch1vol = ("NA," * 7 + "NA\n").split(",")
            else:
                ch0x, ch0y, ch0z, ch0vol, ch1x, ch1y, ch1z, ch1vol = self.cT.getXYZtable()[i]
            f.write(position+","+cellIndex+","+annotation+","+corrFrame+","+time+","+anaphase+","+distance+","+ch0x+","+ch0y+","+ch0z+","+ch0vol+","+ch1x+","+ch1y+","+ch1z+","+ch1vol)
        f.close()
        print "Successfully saved!"

    def cropVals(self, event): #"this function deletes all values with frame > current cursor"   
        for line in range(self.cT.getSelectionEnd(), self.cT.getLineCount(), 1):
            frame, distance, AOCol = self.cT.getLine(line).split("\t")
            self.cT.setLine(line, frame + "\tNA" + "\t" + AOCol)

    def discardCell(self, event):
        if not os.path.exists(os.path.split(self.cell.getQcCsvPath() )[0]): # check if save folder present.
            os.makedirs(os.path.split(self.cell.getQcCsvPath() )[0]) # create save folder, if not present.
        f = open(self.cell.getQcCsvPath() ,"w")
        # Write dummy header. Position Cell Phenotype Frame Time AnOn Distance ch0x ch0y ch0z ch0vol ch1x ch1y ch1z ch1vol
        f.write("Position,Cell,Phenotype,Frame,Time,AnOn,Distance,ch0x,ch0y,ch0z,ch0vol,ch1x,ch1y,ch1z,ch1vol\n")
        f.close()
        print "Discarded cell - saved dummy" 

    def quit(self, event):
        try:
            self.cT.closeWindows()
        finally:
            WindowManager.removeWindow(self)
            self.dispose()

    # Methods implementing ActionListener interfaces:
    def actionPerformed(self, e):
        # this function is called when RadioButtons are changed
        self.cell.annotate( e.getSource().getActionCommand() )
        self.setSaveActive()

    def windowGainedFocus(self, e):
        pass

    def windowLostFocus(self, e):
        pass
        

    # - - - - - - - - - - - - -
    # - get and set methods - -
    # - - - - - - - - - - - - -
    def getAnnotation(self):
        return self.aButtonGroup.getSelection().getActionCommand()

    def getMainDir(self):
        return self.mainDir

    def setSaveActive(self):
        if (self.cell.getAnnotation() != None and self.cell.getAnOn() != None):
            self.saveButton.setEnabled(True)
            self.show()

    def setSaveInactive(self):
        self.saveButton.setEnabled(False)
        self.show()

    def setMainDir(self, path):
        self.mainDir = path
        self.pathLabel.setText("MainDir: " + os.path.basename(os.path.split(self.mainDir)[0]))
Ejemplo n.º 20
0
class BurpExtender(IBurpExtender, IContextMenuFactory, IHttpListener,
                   ISessionHandlingAction, ITab):
    def registerExtenderCallbacks(self, callbacks):
        self._callbacks = callbacks
        self._helpers = callbacks.getHelpers()
        callbacks.setExtensionName("JC-AntiToken")
        callbacks.registerContextMenuFactory(self)
        # callbacks.registerHttpListener(self)
        callbacks.registerSessionHandlingAction(self)
        self.drawUI()

    def printcn(self, msg):
        print(msg.decode('utf-8').encode(sys_encoding))

    def drawUI(self):
        # 最外层:垂直盒子,内放一个水平盒子+一个胶水
        out_vBox_main = Box.createVerticalBox()
        # 次外层:水平盒子,使用说明
        usage = u'''
                             JC-AntiToken(简单防重放绕过)
        适用场景:防重放的方式为,提前向一个页面发送请求取得token,替换到下一个页面中。
        适用说明:
            1. 请求头中Headers和Data的值必须是JSON字符串,如:{"var":"value"}
            2. 左边tokenRegex的格式为:
                a. .*开头,.*结尾,用()括住要取出的token
                b. 如:.*,"token":"(.*?)".*
            3. 右边tokenRegex的格式为:
                a. 需要三个(),第二个()括住要替换的token
                b. 如:(.*,"token":")(.*?)(".*)
        详见:https://github.com/chroblert/JC-AntiToken
        '''
        hBox_usage = Box.createHorizontalBox()
        jpanel_test = JPanel()
        jTextarea_usage = JTextArea()
        jTextarea_usage.setText(usage)
        jTextarea_usage.setRows(13)
        jTextarea_usage.setEditable(False)
        # jpanel_test.add(jTextarea_usage)
        hBox_usage.add(JScrollPane(jTextarea_usage))

        # 次外层:水平盒子,内放两个垂直盒子
        hBox_main = Box.createHorizontalBox()
        # 左垂直盒子
        vBox_left = Box.createVerticalBox()
        # 右垂直盒子
        vBox_right = Box.createVerticalBox()

        # 左垂直盒子内部:发送请求包拿token
        # URL标签
        jlabel_url = JLabel("       URL: ")
        self.jtext_url = JTextField(generWidth)
        self.jtext_url.setMaximumSize(self.jtext_url.getPreferredSize())
        hbox_url = Box.createHorizontalBox()
        hbox_url.add(jlabel_url)
        hbox_url.add(self.jtext_url)
        hglue_url = Box.createHorizontalGlue()
        hbox_url.add(hglue_url)
        # 请求方法标签
        jlabel_reqMeth = JLabel("ReqMeth: ")
        self.jcombobox_reqMeth = JComboBox()
        self.jcombobox_reqMeth.addItem("GET")
        self.jcombobox_reqMeth.addItem("POST")
        hbox_reqMeth = Box.createHorizontalBox()
        hbox_reqMeth.add(jlabel_reqMeth)
        hbox_reqMeth.add(self.jcombobox_reqMeth)
        self.jcombobox_reqMeth.setMaximumSize(
            self.jcombobox_reqMeth.getPreferredSize())
        hglue_reqMeth = Box.createHorizontalGlue()
        hbox_reqMeth.add(hglue_reqMeth)
        # ContentType标签
        jlabel_contentType = JLabel("ConType: ")
        self.jcombobox_contentType = JComboBox()
        self.jcombobox_contentType.addItem("application/json")
        self.jcombobox_contentType.addItem("application/x-www-form-urlencoded")
        hbox_contentType = Box.createHorizontalBox()
        hbox_contentType.add(jlabel_contentType)
        hbox_contentType.add(self.jcombobox_contentType)
        self.jcombobox_contentType.setMaximumSize(
            self.jcombobox_contentType.getPreferredSize())
        hglue_contentType = Box.createHorizontalGlue()
        hbox_contentType.add(hglue_contentType)
        # Charset标签
        jlabel_charset = JLabel("CharSet: ")
        self.jcombobox_charset = JComboBox()
        self.jcombobox_charset.addItem("UTF-8")
        self.jcombobox_charset.addItem("GBK")
        hbox_charset = Box.createHorizontalBox()
        hbox_charset.add(jlabel_charset)
        hbox_charset.add(self.jcombobox_charset)
        self.jcombobox_charset.setMaximumSize(
            self.jcombobox_charset.getPreferredSize())
        hglue_charset = Box.createHorizontalGlue()
        hbox_charset.add(hglue_charset)
        # 请求头标签
        jlabel_headers = JLabel("Headers: ")
        self.jtext_headers = JTextField(generWidth)
        self.jtext_headers.setMaximumSize(
            self.jtext_headers.getPreferredSize())
        hbox_headers = Box.createHorizontalBox()
        hbox_headers.add(jlabel_headers)
        hbox_headers.add(self.jtext_headers)
        hglue_headers = Box.createHorizontalGlue()
        hbox_headers.add(hglue_headers)
        # 请求参数标签
        jlabel_data = JLabel("     Data: ")
        self.jtext_data = JTextField(generWidth)
        self.jtext_data.setPreferredSize(Dimension(20, 40))
        self.jtext_data.setMaximumSize(self.jtext_data.getPreferredSize())
        hbox_data = Box.createHorizontalBox()
        hbox_data.add(jlabel_data)
        hbox_data.add(self.jtext_data)
        hglue_data = Box.createHorizontalGlue()
        hbox_data.add(hglue_data)
        # token标志位置标签
        hbox_radiobtn = Box.createHorizontalBox()
        jlabel_tokenPosition = JLabel("Token Position: ")
        self.radioBtn01 = JRadioButton("Header")
        self.radioBtn02 = JRadioButton("Body")
        btnGroup = ButtonGroup()
        btnGroup.add(self.radioBtn01)
        btnGroup.add(self.radioBtn02)
        self.radioBtn01.setSelected(True)
        hbox_radiobtn.add(jlabel_tokenPosition)
        hbox_radiobtn.add(self.radioBtn01)
        hbox_radiobtn.add(self.radioBtn02)
        # token正则表达式标签
        hbox_token = Box.createHorizontalBox()
        hbox_token_header = Box.createHorizontalBox()
        hbox_token_body = Box.createHorizontalBox()
        # token正则表达式标签:header中
        jlabel_tokenName = JLabel("tokenName: ")
        self.jtext_tokenName = JTextField(tokenWidth)
        self.jtext_tokenName.setMaximumSize(
            self.jtext_tokenName.getPreferredSize())
        hbox_token_header.add(jlabel_tokenName)
        hbox_token_header.add(self.jtext_tokenName)
        hglue_token_header = Box.createHorizontalGlue()
        hbox_token_header.add(hglue_token_header)
        # token正则表达式标签:body中
        jlabel_tokenRegex = JLabel("tokenRegex: ")
        self.jtext_tokenRegex = JTextField(tokenWidth)
        self.jtext_tokenRegex.setMaximumSize(
            self.jtext_tokenRegex.getPreferredSize())
        hbox_token_body.add(jlabel_tokenRegex)
        hbox_token_body.add(self.jtext_tokenRegex)
        hglue_token_body = Box.createHorizontalGlue()
        hbox_token_body.add(hglue_token_body)
        # token正则表达式标签
        hbox_token.add(hbox_token_header)
        hbox_token.add(hbox_token_body)
        # test测试按钮
        hbox_test = Box.createHorizontalBox()
        jbtn_test = JButton("TEST", actionPerformed=self.btnTest)
        self.jlabel_test = JLabel("Result: ")
        hbox_test.add(jbtn_test)
        hbox_test.add(self.jlabel_test)
        # 水平胶水填充
        hGlue_test = Box.createHorizontalGlue()
        hbox_test.add(hGlue_test)
        hbox_test.setBorder(BorderFactory.createLineBorder(Color.green, 2))
        # 响应数据输出
        hbox_resp = Box.createHorizontalBox()
        self.jtextarea_resp = JTextArea()
        jsp = JScrollPane(self.jtextarea_resp)
        hbox_resp.add(self.jtextarea_resp)
        # 左垂直盒子:添加各种水平盒子
        vBox_left.add(hbox_url)
        vBox_left.add(hbox_reqMeth)
        vBox_left.add(hbox_contentType)
        vBox_left.add(hbox_charset)
        vBox_left.add(hbox_headers)
        vBox_left.add(hbox_data)
        vBox_left.add(hbox_radiobtn)
        vBox_left.add(hbox_token)
        vBox_left.add(hbox_test)
        vBox_left.add(hbox_resp)
        # 左垂直盒子:垂直胶水填充
        vGlue_test = Box.createGlue()
        vBox_left.add(vGlue_test)

        # 右垂直盒子内部:指定token在请求包中的位置
        # token标志位置单选按钮
        hbox_radiobtn_r = Box.createHorizontalBox()
        jlabel_tokenPosition_r = JLabel("Token Position: ")
        self.radioBtn01_r = JRadioButton("Header")
        self.radioBtn02_r = JRadioButton("Body")
        btnGroup_r = ButtonGroup()
        btnGroup_r.add(self.radioBtn01_r)
        btnGroup_r.add(self.radioBtn02_r)
        self.radioBtn01_r.setSelected(True)
        hbox_radiobtn_r.add(jlabel_tokenPosition_r)
        hbox_radiobtn_r.add(self.radioBtn01_r)
        hbox_radiobtn_r.add(self.radioBtn02_r)

        # token正则表达式
        hbox_token_r = Box.createHorizontalBox()
        hbox_token_header_r = Box.createHorizontalBox()
        hbox_token_body_r = Box.createHorizontalBox()
        # token正则表达式:在header中
        jlabel_tokenName_r = JLabel("tokenName: ")
        self.jtext_tokenName_r = JTextField(tokenWidth)
        self.jtext_tokenName_r.setMaximumSize(
            self.jtext_tokenName_r.getPreferredSize())
        hbox_token_header_r.add(jlabel_tokenName_r)
        hbox_token_header_r.add(self.jtext_tokenName_r)
        hglue_token_header_r = Box.createHorizontalGlue()
        hbox_token_header_r.add(hglue_token_header_r)
        # token正则表达式:在Body中
        jlabel_tokenRegex_r = JLabel("tokenRegex: ")
        self.jtext_tokenRegex_r = JTextField(tokenWidth)
        self.jtext_tokenRegex_r.setMaximumSize(
            self.jtext_tokenRegex_r.getPreferredSize())
        hbox_token_body_r.add(jlabel_tokenRegex_r)
        hbox_token_body_r.add(self.jtext_tokenRegex_r)
        hglue_token_body_r = Box.createHorizontalGlue()
        hbox_token_body_r.add(hglue_token_body_r)
        # token正则表达式
        hbox_token_r.add(hbox_token_header_r)
        hbox_token_r.add(hbox_token_body_r)
        # 测试按钮
        hbox_test_r = Box.createHorizontalBox()
        jbtn_test_r = JButton("SET", actionPerformed=self.btnTest_r)
        self.jlabel_test_r = JLabel("Result: ")
        hbox_test_r.add(jbtn_test_r)
        hbox_test_r.add(self.jlabel_test_r)
        # 水平胶水填充
        hGlue02 = Box.createHorizontalGlue()
        hbox_test_r.add(hGlue02)
        hbox_test_r.setBorder(BorderFactory.createLineBorder(Color.green, 2))

        # 右垂直盒子:添加各种水平盒子
        vBox_right.add(hbox_radiobtn_r)
        vBox_right.add(hbox_token_r)
        vBox_right.add(hbox_test_r)
        vGlue = Box.createVerticalGlue()
        vBox_right.add(vGlue)

        vBox_left.setBorder(BorderFactory.createLineBorder(Color.black, 3))
        vBox_right.setBorder(BorderFactory.createLineBorder(Color.black, 3))

        # 次外层水平盒子:添加左右两个垂直盒子
        hBox_main.add(vBox_left)
        hBox_main.add(vBox_right)
        # 最外层垂直盒子:添加次外层水平盒子,垂直胶水
        out_vBox_main.add(hBox_usage)
        out_vBox_main.add(hBox_main)

        self.mainPanel = out_vBox_main
        self._callbacks.customizeUiComponent(self.mainPanel)
        self._callbacks.addSuiteTab(self)

    def getTabCaption(self):
        return "JC-AntiToken"

    def getUiComponent(self):
        return self.mainPanel

    def testBtn_onClick(self, event):
        print("click button")

    def createMenuItems(self, invocation):
        menu = []
        if invocation.getToolFlag() == IBurpExtenderCallbacks.TOOL_REPEATER:
            menu.append(
                JMenuItem("Test menu", None, actionPerformed=self.testmenu))
        return menu

    def testmenu(self, event):
        print(event)
        print("JCTest test menu")

    def processHttpMessage(self, toolflag, messageIsRequest, messageInfo):
        service = messageInfo.getHttpService()
        if messageIsRequest:
            pass
            print("Host: " + str(service.getHost()))
            print("Port: " + str(service.getPort()))
            print("Protocol: " + str(service.getProtocol()))
            print("-----------------------------------")

    def getActionName(self):
        return "JC-AntiToken"

    def performAction(self, currentRequest, macroItems):
        # url
        url = self._helpers.analyzeRequest(currentRequest).getUrl()
        print(url)
        reqInfo = self._helpers.analyzeRequest(currentRequest)
        # request headers
        headers = reqInfo.getHeaders()
        print("ReqHeaders: " + headers)
        # get cookie from request header
        cookie = self.getCookieFromReq(headers)
        print(cookie)
        print(type(cookie))
        # offset to req body
        reqBodyOffset = reqInfo.getBodyOffset()
        reqBody = str(bytearray(currentRequest.getRequest()[reqBodyOffset:]))
        print("ReqBody: " + reqBody)
        # modify Request Body
        newToken = self.getNewToken(cookie)
        if newToken != None:
            # tokenInReqHeader
            res = False
            if self.tokenInHeader_r:
                # pass
                # 普通header中
                for header in headers:
                    if ":" in header:
                        if header.split(":")[0] == self.tokenName_r:
                            headers = [
                                self.tokenName_r + ": " + newToken
                                if i.split(":")[0] == self.tokenName_r else i
                                for i in headers
                            ]
                            res = True
                            break
                # cookie中
                if not res and cookie != None and self.tokenName_r + "=" in cookie:
                    # pass
                    for i in range(len(headers)):
                        if headers[i].startwith("Cookie:"):
                            cookies2 = headers[i]
                            cookies3 = cookies2.split(":")[1]
                            if ";" not in cookies3:
                                headers[
                                    i] = "Cookie: " + self.tokenName_r + "=" + newToken
                                res = True
                                break
                            else:
                                cookies4 = cookies3.split(";")
                                for cookie_idx in range(len(cookies4)):
                                    if self.tokenName_r + "+" in cookies4[
                                            cookie_idx]:
                                        cookies4[
                                            cookie_idx] = self.tokenName_r + "=" + newToken
                                        res = True
                                        break
                                headers[i] = "Cookie: " + ";".join(cookies4)
                                break
                # query string中
                if not res:
                    meth = headers[0].split(" ")[0]
                    url = headers[0].split(" ")[1]
                    ver = headers[0].split(" ")[2]
                    if self.tokenName_r + "=" not in url:
                        pass
                    else:
                        if "&" not in url:
                            url = url.split("?")[
                                0] + "?" + self.tokenName_r + "=" + newToken
                            headers[0] = meth + " " + url + " " + ver
                        else:
                            params = url.split("?")[1].split("&")
                            for i in range(len(params)):
                                if self.tokenName_r + "=" in params[i]:
                                    params[
                                        i] = self.tokenName_r + "=" + newToken
                                    break
                            url = url.split("?")[0] + "?" + "&".join(params)
                            headers[0] = meth + " " + url + " " + ver
            # tokenInReqBody
            else:
                if re.match(self.tokenRegex_r, reqBody):
                    try:
                        reqBody = re.sub(self.tokenRegex_r,
                                         r'\g<1>' + newToken + r'\g<3>',
                                         reqBody, 0, re.M | re.I)
                    except Exception as e:
                        print(e)
                        # print(reqBody)
                        # reqBody = re.sub(self.tokenRegex_r,r'\g<1>'+newToken+r'\g<3>',reqBody,0,re.M|re.I)

            # if re.match(r'(.*?"_tokenName":")([a-zA-Z0-9]{6,})(")',reqBody):
            #     reqBody = re.sub(r'(.*?"_tokenName":")([a-zA-Z0-9]{6,})(")',r'\1'+newToken+r'\3',reqBody,0,re.M|re.I)
        # rebuild request
        reqMessage = self._helpers.buildHttpMessage(headers, bytes(reqBody))
        # forward
        currentRequest.setRequest(reqMessage)
        print("++++++++++++++++++++++++")

    def getCookieFromReq(self, headers):
        for header in headers:
            if re.match(r'^Cookie:', header, re.I):
                return re.match(r'^Cookie: (.*)', header, re.I).group(1)

    # get new token
    def getNewToken(self, cookie):
        print(cookie)
        print("getNewToken")
        # url = "http://myip.ipip.net"
        headers_cookie = {
            'Cookie': cookie,
        }
        if cookie != '':
            self.headers.update(**headers_cookie)
        if self.reqMeth == "GET":
            resp = self.sendGetHttp(self.url, self.headers, self.data,
                                    self.contentType)
        else:
            resp = self.sendPostHttp(self.url, self.headers, self.data,
                                     self.contentType)
        respBody = resp.read()
        respInfo = resp.info()
        if self.tokenInHeader:
            if respInfo.getheader(self.tokenName) != None:
                newToken = respInfo.getheader(self.tokenName)
                print(newToken)
                return newToken
            else:
                regexPattern = '.*' + self.tokenName + '=(.*?);'
                if respInfo.getheader("set-cookie") != None:
                    cookies = respInfo.getheader("set-cookie")
                    if re.match(regexPattern, cookies, re.M | re.I):
                        newToken = re.match(regexPattern, cookies,
                                            re.M | re.I).group(1)
                        print("newToken: ", newToken)
                        return newToken
                    else:
                        return None
                else:
                    return None
        else:
            regexPattern = self.tokenRegex
            if re.match(regexPattern, respBody, re.M | re.I):
                newToken = re.match(regexPattern, respBody,
                                    re.M | re.I).group(1)
                print("newToken: ", newToken)
                return newToken
            else:
                return None

    def sendGetHttp(self, url, headers, data, contentType):
        context = ssl._create_unverified_context()
        headers_contentType = {'Content-Type': contentType}
        if not headers.has_key("Content-Type"):
            headers.update(**headers_contentType)
        headers_userAgent = {
            'User-Agent':
            'Mozilla/6.0 (iPhone; CPU iPhone OS 8_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/8.0 Mobile/10A5376e Safari/8536.25'
        }
        if not headers.has_key("User-Agent"):
            headers.update(**headers_userAgent)
        try:
            if data != None:
                # if "urlencode" in contentType:
                data = urllib.urlencode(data)
                url = url + "?" + data
                req = urllib2.Request(url, headers=headers)
            else:
                req = urllib2.Request(url, headers=headers)
            resp = urllib2.urlopen(req, context=context)
            return resp
        except urllib2.HTTPError as error:
            print("ERROR: ", error)
            return None

    def sendPostHttp(self, url, headers, data, contentType):
        context = ssl._create_unverified_context()
        headers_contentType = {'Content-Type': contentType}
        if not headers.has_key("Content-Type"):
            headers.update(**headers_contentType)
        headers_userAgent = {
            'User-Agent':
            'Mozilla/6.0 (iPhone; CPU iPhone OS 8_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/8.0 Mobile/10A5376e Safari/8536.25'
        }
        if not headers.has_key("User-Agent"):
            headers.update(**headers_userAgent)
        print(headers)
        resp = ""
        print("data: ", data)
        if data != None:
            if "urlencode" in contentType:
                data = urllib.urlencode(data)
                req = urllib2.Request(url, headers=headers, data=data)
            else:
                data = json.dumps(data)
                req = urllib2.Request(url, headers=headers, data=data)
        else:
            if "urlencode" in contentType:
                req = urllib2.Request(url, headers=headers)
            else:
                data = json.dumps(data)
                req = urllib2.Request(url, headers=headers)
        try:
            resp = urllib2.urlopen(req, context=context)
            return resp
        except urllib2.HTTPError as error:
            print("ERROR: ", error)
            return None

    def btnTest(self, e):
        self.printcn("中文测试")
        self.url = self.jtext_url.getText()
        if self.url == "":
            self.jlabel_test.setText("please input url")
            return
        self.reqMeth = self.jcombobox_reqMeth.getSelectedItem()
        # 用户设置content-type
        self.contentType = self.jcombobox_contentType.getSelectedItem(
        ) + ";charset=" + self.jcombobox_charset.getSelectedItem()
        # 用户有没有自定义请求头
        if self.jtext_headers.getText() != "":
            self.headers = json.loads(self.jtext_headers.getText())
        else:
            self.headers = {}
        # 用户有没有自定义请求体
        if self.jtext_data.getText() != "":
            self.data = json.loads(self.jtext_data.getText())
        else:
            self.data = None
        self.tokenName = self.jtext_tokenName.getText()
        self.tokenRegex = self.jtext_tokenRegex.getText()
        resp = ''
        if self.reqMeth == "GET":
            resp = self.sendGetHttp(self.url, self.headers, self.data,
                                    self.contentType)
        else:
            resp = self.sendPostHttp(self.url, self.headers, self.data,
                                     self.contentType)
        if resp == None:
            self.jlabel_test.setText("error,detail in extender output")
            return
        respHeader = resp.info().headers
        print("resp-headers: ", respHeader)
        # print(resp.info().getheader("content-type"))
        self.printcn(resp.info().getheader("set-cookie"))
        # print(resp.info().getheader("xxx"))
        respBody = resp.read()
        print("respBody: ", respBody)
        self.jtextarea_resp.setText("".join(respHeader) + "\n" +
                                    "".join(respBody))
        if (self.radioBtn01.isSelected()):
            self.tokenInHeader = True
            if self.tokenName == "":
                self.jlabel_test.setText("please input tokenName")
                return
        else:
            self.tokenInHeader = False
            if self.tokenRegex == "":
                self.jlabel_test.setText("please input tokenRegex")
                return
        print(self.reqMeth)
        newToken = self.getNewToken("")
        if newToken != None:
            self.jlabel_test.setText("Result: " + str(newToken))
            self.jlabel_test.setBackground(Color.cyan)
        else:
            self.jlabel_test.setText("Result: None")

    def btnTest_r(self, e):
        self.tokenName_r = self.jtext_tokenName_r.getText()
        self.tokenRegex_r = self.jtext_tokenRegex_r.getText()
        if (self.radioBtn01_r.isSelected()):
            self.tokenInHeader_r = True
            if self.tokenName_r == "":
                self.jlabel_test_r.setText("please input tokenName")
                return
        else:
            self.tokenInHeader_r = False
            if self.tokenRegex_r == "":
                self.jlabel_test_r.setText("please input tokenRegex")
                return
        self.jlabel_test_r.setText("SUCCESS")
Ejemplo n.º 21
0
class JTabbedPaneClass:


    #判断域名返回IP地址
    def getIp(self, domain):
        domain = domain.split(":")[0]
        ipExpression = re.compile('^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$')
        domainExpression = re.compile("^(([a-zA-Z]|[a-zA-Z][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z]|[A-Za-z][A-Za-z0-9\-]*[A-Za-z0-9])$")
        if ipExpression.match(domain):
            return domain
        elif domainExpression.match(domain):
            myAddr = socket.getaddrinfo(domain,'http')[0][4][0]
            return myAddr
        
        else:
            return "domain error"


    #提取域名或IP信息
    def getDomain1(self, theDomain):
        domain1 = theDomain.split(":")[0]

        return domain1



    def __init__(self):
        

        frame = JFrame("S1riu5 Spy")
        frame.setSize(700, 690)
        frame.setLocationRelativeTo(None);
        frame.setLayout(BorderLayout())

        tabPane = JTabbedPane(JTabbedPane.TOP)

        #第一个Tab用来做C段查询

        eachIp = self.getIp(HOSTDOMAIN)

        iList = eachIp.split(".")

        theIP = iList[0] + "." + iList[1] + "." + iList[2] + ".1/24"  

        panel1 = JPanel()
        label = JLabel("IP CIDR:")
        self.textfield1 = JTextField(theIP, 15)
        button = JButton("SCAN", actionPerformed = self.cNmapScan)
        self.textArea = JTextArea(40, 65)
        self.textArea.append("IP: " + eachIp)
        self.textArea.setLineWrap(True)                  #激活自动换行功能 
        self.textArea.setWrapStyleWord(True);            # 激活断行不断字功能
                   
        panel1.add(label)
        panel1.add(self.textfield1)
        panel1.add(button)
        panel1.add(JScrollPane(self.textArea))            #设置自动滚动条
        tabPane.addTab("C segment query ", panel1)
        



        #第二个Tab用来做子域名查询



        theName = self.getDomain1(HOSTDOMAIN)

        self.textArea2 = JTextArea(40, 65)
        #self.textArea.append("IP: " + eachIp)
        self.textArea2.setLineWrap(True)                  #激活自动换行功能 
        self.textArea2.setWrapStyleWord(True)           # 激活断行不断字功能
                   


        label2 = JLabel("Domain: ")
        self.textfield2 = JTextField(theName, 15)
        button2 = JButton("SCAN", actionPerformed = self.subDomain)
        self.panel2 = JPanel()
        self.panel2.add(label2)
        self.panel2.add(self.textfield2)
        self.panel2.add(button2)
        #self.panel2.add(scrollPane)
        self.panel2.add(JScrollPane(self.textArea2))
        tabPane.addTab("subDomains", self.panel2)


        #第三个Tab用来做敏感文件扫描

        self.tableData0 = [["1", "2"]]
        colNames2 = ('url','http code')
        dataModel3 = DefaultTableModel(self.tableData0, colNames2)
        self.table3 = JTable(dataModel3)
##
 
        label3 = JLabel("URL: ")
        self.textfield3 = JTextField(HOSTDOMAIN, 15)
        self.textArea3 = JTextArea(40, 65)
        #self.textArea.append("IP: " + eachIp)
        self.textArea3.setLineWrap(True)                  #激活自动换行功能 
        self.textArea3.setWrapStyleWord(True)          # 激活断行不断字功能
        a = 0
        b = 0 
        self.label4 = JLabel(str(a) + "/" + str(b))
#
        self.chkbox1 = JCheckBox('ASP')
        self.chkbox2 = JCheckBox('ASPX')
        self.chkbox3 = JCheckBox('JSP')
        self.chkbox4 = JCheckBox('PHP')
        self.chkbox5 = JCheckBox('MDB')
        self.chkbox6 = JCheckBox('DIR')
        button3 = JButton("SCAN", actionPerformed = self.senFileScan)
        panel3 = JPanel()

        panel3.add(label3)
        panel3.add(self.textfield3)
        panel3.add(self.chkbox1)
        panel3.add(self.chkbox2)
        panel3.add(self.chkbox3)
        panel3.add(self.chkbox4)
        panel3.add(self.chkbox5)
        panel3.add(self.chkbox6)
        panel3.add(button3)
        panel3.add(self.label4)
        panel3.add(JScrollPane(self.textArea3))


#
        tabPane.addTab("Sebsitive File", panel3)
#
        frame.add(tabPane)
        frame.setVisible(True)
    #用来在第一个TAB打印nmap信息  
    def setResult(self,text):
        self.textArea.append(text)

    #用来在第二个TAB打印获得信息
    def setResult2(self,textId, textDomain, textIp):
        text = str(textId) + "----------------" + textDomain + "----------------" + str(textIp) + os.linesep
        self.textArea2.append(text)
        #self.textArea2.append("----------------------------------------" + os.linesep)

    #用来在第三个TAB打印文件扫描的结果
    def setResult3(self, theMess01):

    	self.textArea3.append(theMess01)


    def setLabel(self, a, b):
    	hg = str(a) + "/" + str(b)
    	self.label4.setText(hg)


    #C段扫描的主引擎
    def cNmapScan(self, event):

        self.textArea.setText("")
            #-------------------------------------------------------------------------------
        def ipRange(ipaddr):
            """
            Creates a generator that iterates through all of the IP addresses.
            The range can be specified in multiple formats.
        
                "192.168.1.0-192.168.1.255"    : beginning-end
                "192.168.1.0/24"               : CIDR
                "192.168.1.*"                  : wildcard
            
        
            """
            def ipaddr_to_binary(ipaddr):
                """
                A useful routine to convert a ipaddr string into a 32 bit long integer
                """
                # from Greg Jorgensens python mailing list message 
                q = ipaddr.split('.')
                return reduce(lambda a,b: long(a)*256 + long(b), q)
               
            #-------------------------------------------------------------------------------
            def binary_to_ipaddr(ipbinary):
                """
                Convert a 32-bit long integer into an ipaddr dotted-quad string
                """
                # This one is from Rikard Bosnjakovic
                return socket.inet_ntoa(struct.pack('!I', ipbinary))
            
            def ipaddr_to_binary(ipaddr):
                """
                A useful routine to convert a ipaddr string into a 32 bit long integer
                """
                # from Greg Jorgensens python mailing list message 
                q = ipaddr.split('.')
                return reduce(lambda a,b: long(a)*256 + long(b), q)
           
            #-------------------------------------------------------------------------------
            def binary_to_ipaddr(ipbinary):
                """
                Convert a 32-bit long integer into an ipaddr dotted-quad string
                """
                # This one is from Rikard Bosnjakovic
                return socket.inet_ntoa(struct.pack('!I', ipbinary))
            
            #-------------------------------------------------------------------------------
            def cidr_iprange(ipaddr, cidrmask):
                """
                Creates a generator that iterated through all of the IP addresses
                in a range given in CIDR notation
                """
                # Get all the binary one's
                mask = (long(2)**long(32-long(cidrmask))) - 1
            
                b = ipaddr_to_binary(ipaddr) 
                e = ipaddr_to_binary(ipaddr) 
                b = long(b & ~mask)
                e = long(e | mask)
            
                while (b <= e):
                    yield binary_to_ipaddr(b)
                    b = b + 1
         
            #-------------------------------------------------------------------------------
            def wildcard_iprange(ipaddr):
                """
                Creates a generator that iterates through all of the IP address
                in a range given with wild card notation
                """
                beginning = [] 
                end = [] 
                
                tmp = ipaddr.split('.')
                for i in tmp:
                    if i == '*':
                        beginning.append("0")
                        end.append("255") 
                    else:
                        beginning.append(i)
                        end.append(i) 
            
                b = beginning[:]
                e = end[:]
                
                while int(b[0]) <= int(e[0]):
                    while int(b[1]) <= int(e[1]):
                        while int(b[2]) <= int(e[2]):
                            while int(b[3]) <= int(e[3]):
                                yield b[0] + '.' + b[1] + '.' + b[2] + '.' + b[3]
                                b[3] = "%d" % (int(b[3]) + 1)
            
                            b[2] = "%d" % (int(b[2]) + 1)
                            b[3] = beginning[3]
            
                        b[1] = "%d" % (int(b[1]) + 1)
                        b[2] = beginning[2]
            
                    b[0] = "%d" % (int(b[0]) + 1)
                    b[1] = beginning[1]       
            
            # Did we get the IP address in the span format? 
            span_re = re.compile(r'''(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})   # The beginning IP Address
                                     \s*-\s*
                                     (\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})   # The end IP Address
                                  ''', re.VERBOSE)
        
            res = span_re.match(ipaddr)
            if res:
                beginning = res.group(1)
                end = res.group(2)
                return span_iprange(beginning, end)
                                         
            # Did we get the IP address in the CIDR format? 
            cidr_re = re.compile(r'''(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})   # The IP Address
                                     /(\d{1,2})                             # The mask
                                  ''', re.VERBOSE)
        
            res = cidr_re.match(ipaddr)
            if res:
                addr = res.group(1)
                cidrmask = res.group(2)
                return cidr_iprange(addr, cidrmask)
        
            # Did we get the IP address in the wildcard format? 
            wild_re = re.compile(r'''(\d{1,3}|\*)\.
                                     (\d{1,3}|\*)\.
                                     (\d{1,3}|\*)\.
                                     (\d{1,3}|\*)   # The IP Address
                                  ''', re.VERBOSE)
        
            res = wild_re.match(ipaddr)
            if res:
                return wildcard_iprange(ipaddr)
            return "The ip address given to ipaddr is improperly formatted"


        ipCidr = self.textfield1.getText()

        domainExpression = re.compile("^(([a-zA-Z]|[a-zA-Z][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z]|[A-Za-z][A-Za-z0-9\-]*[A-Za-z0-9])$")

        if domainExpression.match(ipCidr):
            JOptionPane.showMessageDialog(None, "You must enter IP", "s1riu5", JOptionPane.INFORMATION_MESSAGE)
        

        else:
            ipList = list(ipRange(ipCidr))
            print len(ipList)
            if len(ipList) == 256:
                del ipList[0]
                del ipList[254]
    
            global NMAPPATH

            scan=ScanList(ipList, self, [NMAPPATH,"-Pn", "-sT", "-sV", "--open"])
            scan.start()

    
  

    def subDomain(self, event):
    	print self.textfield2.getText()
        b = subDomainThread(self.textfield2.getText(), self)
        b.start()

        


    def senFileScan(self, event):
        #print "Hello"

        urlListASP = ["/admin.asp"]
        urlListASPX = ["/admin.aspx"]
        urlListJSP = ["/admin.jsp"]
        urlListPHP = ["/admin.php"]
        urlListMDB = ["/admin.mdb"]
        urlListDIR = ["/admin/"]
        

        if self.chkbox1.isSelected():
            
            domainTextObj1 = open("path/ASP.txt", "r")
            for each1 in domainTextObj1.readlines():
                each1 = each1.strip()
                urlListASP.append(each1)
            domainTextObj1.close()

        if self.chkbox2.isSelected():
            domainTextObj2 = open("path/ASPX.txt", "r")
            for each2 in domainTextObj2.readlines():
                each2 = each2.strip()
                urlListASPX.append(each2)
            domainTextObj2.close()
            
        if self.chkbox3.isSelected():
            domainTextObj3 = open("path/JSP.txt", "r")
            for each3 in domainTextObj3.readlines():
                each3 = each3.strip()
                urlListJSP.append(each3)
            domainTextObj3.close()
        if self.chkbox4.isSelected():
            domainTextObj4 = open("path/PHP.txt", "r")
            for each4 in domainTextObj4.readlines():
                each4 = each4.strip()
                urlListPHP.append(each4)
            domainTextObj4.close()
        if self.chkbox5.isSelected():
            domainTextObj5 = open("path/MDB.txt", "r")
            for each5 in domainTextObj5.readlines():
                each5 = each5.strip()
                urlListMDB.append(each5)
            domainTextObj5.close()
        if self.chkbox6.isSelected():
            domainTextObj6 = open("path/DIR.txt", "r")
            for each6 in domainTextObj6.readlines():
                each6 = each6.strip()
                urlListDIR.append(each6)
            domainTextObj6.close()

        app = []
        app = urlListASP + urlListASPX + urlListJSP + urlListPHP + urlListMDB + urlListDIR
        app1 = list(set(app))
        

        theUrlText = self.textfield3.getText()

        


        #if str(theUrlText[0 : 7]) == "http://":
         #   theUrlText = "http://" + theUrlText
        

        print len(app1)
        print len(app)


        #fileObj1 = eachFileScan(theUrlText, app)
        #fileObj1.start()
        ab = numControl(theUrlText, app1, self)
        ab.start()
Ejemplo n.º 22
0
class informacion(JFrame):
    def __init__(self):
        self.windows()
        self.config()

    def windows(self):
        self.setTitle("Informacion")
        #self.setSize(100,100)
        self.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE)
        self.setLayout(None)
        self.setLocationRelativeTo(None)
        self.setVisible(True)

    def config(self):
        self.integrantes = JLabel()
        self.victor = JLabel()
        self.osvaldo = JLabel()
        self.pedro = JLabel()
        self.python = JLabel()
        self.carita = JLabel()

        self.integrantes.setText("Integrantes")
        self.getContentPane().add(self.integrantes)
        self.integrantes.setBounds(76, 60, 100, 14)

        self.victor.setText("Victor Esau Jimenez Cholo")
        self.getContentPane().add(self.victor)
        self.victor.setBounds(38, 85, 180, 14)

        self.osvaldo.setText("Luis Osvaldo Perez Hernandez")
        self.getContentPane().add(self.osvaldo)
        self.osvaldo.setBounds(38, 105, 180, 14)

        self.pedro.setText("Pedro Guzman Primo")
        self.getContentPane().add(self.pedro)
        self.pedro.setBounds(38, 130, 150, 14)

        self.python.setText("HECHO CON  PYTHON ")
        self.getContentPane().add(self.python)
        self.python.setBounds(245, 85, 129, 14)

        self.carita.setText(":)")
        self.getContentPane().add(self.carita)
        self.carita.setBounds(288, 105, 8, 14)

        self.setBounds(0, 0, 416, 284)
Ejemplo n.º 23
0
class VadCheckModuleSettingsPanel(IngestModuleIngestJobSettingsPanel):
    # Note, we can't use a self.settings instance variable.
    # Rather, self.local_settings is used.
    # https://wiki.python.org/jython/UserGuide#javabean-properties
    # Jython Introspector generates a property - 'settings' on the basis
    # of getSettings() defined in this class. Since only getter function
    # is present, it creates a read-only 'settings' property. This auto-
    # generated read-only property overshadows the instance-variable -
    # 'settings'

    # We get passed in a previous version of the settings so that we can
    # prepopulate the UI
    # TODO: Update this for your UI
    def __init__(self, settings):
        #print("init: " + settings.getSetting("runVadTranscriber") + " " + settings.getSetting("minPercVoiced") + " " + settings.getSetting("minTotalVoiced"))
        #print("init local_settings: " + self.local_settings.getSetting("vadAggressivness") + " " + self.local_settings.getSetting("minPercVoiced") + " " + self.local_settings.getSetting("minTotalVoiced"))
        self.local_settings = GenericIngestModuleJobSettings()
        #initComponents will initialize sliders which will call lambdas for updating settings using current values in sliders
        #which would overwrite settings.
        self.initComponents()
        #print("init local_settings 2: " + self.local_settings.getSetting("vadAggressivness") + " " + self.local_settings.getSetting("minPercVoiced") + " " + self.local_settings.getSetting("minTotalVoiced"))
        #now safe to set settings
        self.local_settings = settings
        #print("init 2: " + self.local_settings.getSetting("runVadTranscriber") + " " + self.local_settings.getSetting("minPercVoiced") + " " + self.local_settings.getSetting("minTotalVoiced"))
        self.customizeComponents()
    
    _logger = Logger.getLogger(VadCheckModuleFactory.moduleName)

    def log(self, level, msg):
        self._logger.logp(level, self.__class__.__name__, inspect.stack()[1][3], msg)

    # def makeGuiCallback(self, key, guiGetAction):
    #     def callback(event):
    #         #self.log(Level.INFO, "setting key = " + key + " val =" + str(event.getSource().getValue()))
    #         value = str(guiGetAction(event.getSource()))
    #         print("setting key = " + key + " val =" + value)
    #         self.local_settings.setSetting(key, value)
    #         print("test in settings key = " + key + " val =" + self.local_settings.getSetting(key))
    #     return callback    

    def initComponents(self):
        #print("initComponents 1: " + self.local_settings.getSetting("vadAggressivness") + " " + self.local_settings.getSetting("minPercVoiced") + " " + self.local_settings.getSetting("minTotalVoiced"))
        self.setLayout(BoxLayout(self, BoxLayout.Y_AXIS))

        self.label2 = JLabel()
        self.label2.setText("Minimum percentage of segments with speech")
        self.label3 = JLabel()
        self.label3.setText("Minimum total duration of segment with speech (s)")

        #sliderGetAction = lambda slider: slider.getValue()
        self.minPercVoiced = JSlider()#stateChanged=self.makeGuiCallback("minPercVoiced", sliderGetAction))
        self.minPercVoiced.setMajorTickSpacing(20)
        self.minPercVoiced.setMinorTickSpacing(5)
        self.minPercVoiced.setPaintLabels(True)
        self.minPercVoiced.setPaintTicks(True)

        self.minTotalVoiced = JSlider()#stateChanged=self.makeGuiCallback("minTotalVoiced", sliderGetAction))
        self.minTotalVoiced.setMajorTickSpacing(60)
        self.minTotalVoiced.setMaximum(180)
        self.minTotalVoiced.setMinorTickSpacing(10)
        self.minTotalVoiced.setPaintLabels(True)
        self.minTotalVoiced.setPaintTicks(True)
        #print("initComponents 2: " + self.local_settings.getSetting("vadAggressivness") + " " + self.local_settings.getSetting("minPercVoiced") + " " + self.local_settings.getSetting("minTotalVoiced"))

        #checkboxGetAction = lambda checkbox: checkbox.isSelected()
        self.runVadTranscriber = JCheckBox("Transcribe files with speech detected ? (slow)")#,
            #actionPerformed=self.makeGuiCallback("runVadTranscriber", checkboxGetAction))
        self.showTextSegmentStartTime = JCheckBox("Show text segment start time ?")

        self.add(self.label2)
        self.add(self.minPercVoiced)
        self.add(self.label3)
        self.add(self.minTotalVoiced)
        self.add(self.showTextSegmentStartTime)
        self.add(self.runVadTranscriber)

        self.vadTranscriberLanguage = makeLanguageSelectionComboBox(self, "english")
        #this is needed because of https://bugs.jython.org/issue1749824
        #class ComboActionListener(ActionListener):
        #    def actionPerformed(self, e):
        #        value = e.getSource().getSelectedItem()
        #        self.local_settings.setSetting(key, value)

        #self.vadTranscriberLanguage.actionListener = ComboActionListener()

    #local_settings is of type https://github.com/sleuthkit/autopsy/blob/bbdea786db487c781edf2cf9032a2ba3166e97e0/Core/src/org/sleuthkit/autopsy/ingest/GenericIngestModuleJobSettings.java
    def customizeComponents(self):
        def setValue(key, default, stringToPythonObj, guiSetAction):
            string = self.local_settings.getSetting(key)
            #print("customizeComponents " + key + " stored value was " + str(string))
            #print("string is None " + str(string is None) + " stringToPythonObj(string) " + str(stringToPythonObj(string)))
            checkedValue = default if string is None else stringToPythonObj(string)
            obj = getattr(self, key)
            guiSetAction(obj, checkedValue)
            #self.log(Level.INFO, "setValue for key " + key + " " + str(checkedValue))
        
        sliderSetAction = lambda obj, val: obj.setValue(val)
        checkBoxSetAction = lambda obj, val: obj.setSelected(val)
        comboBoxSetAction = lambda obj, val: obj.setSelectedItem(val)

        setValue("minPercVoiced", minPercVoicedDefault, int, sliderSetAction)
        setValue("minTotalVoiced", minTotalVoicedDefault, int, sliderSetAction)
        setValue("runVadTranscriber", runVadTranscriberDefault, eval, checkBoxSetAction)
        setValue("showTextSegmentStartTime", showTextSegmentStartTimeDefault, eval, checkBoxSetAction)
        setValue("vadTranscriberLanguage", runVadTranscriberDefault, lambda x: x, comboBoxSetAction)

    # Return the settings used
    #note: exceptions thrown here will be caught and not logged.
    def getSettings(self):
        #print("getSettings: " + self.local_settings.getSetting("runVadTranscriber") + " " + self.local_settings.getSetting("minPercVoiced") + " " + self.local_settings.getSetting("minTotalVoiced"))
        
        self.local_settings.setSetting("minPercVoiced", str(self.minPercVoiced.getValue()))
        self.local_settings.setSetting("minTotalVoiced", str(self.minTotalVoiced.getValue()))
        self.local_settings.setSetting("runVadTranscriber", str(self.runVadTranscriber.isSelected()))
        self.local_settings.setSetting("showTextSegmentStartTime", str(self.showTextSegmentStartTime.isSelected()))
        self.local_settings.setSetting("vadTranscriberLanguage", str(self.vadTranscriberLanguage.getSelectedItem()))
 
        return self.local_settings
class VisibilityCellRenderer(TreeCellRenderer):
    def __init__(self, tree, mapContext):
        self.tree = tree
        self.mapContext = mapContext
        self.lblGroup = JLabel()
        self.lblGroup.setBackground(Color(222, 227, 233))  #.BLUE.brighter())
        self.lblGroup.setOpaque(True)
        self.lblGroup.setText(
            "plddddddddddddddddddddddddddddddddddddddddddddddddddddddd")
        self.lblGroupPreferredSize = self.lblGroup.getPreferredSize()
        #border = BorderFactory.createEtchedBorder(EtchedBorder.LOWERED)
        #border = BorderFactory.createLineBorder(Color(222,227,233).darker(),1)
        #self.lblGroup.setBorder(border)
        #self.lblGroupPreferredSize.setSize(30,200)#self.lblGroupPreferredSize.getHeight()+4, self.lblGroupPreferredSize.getWidth())
        self.pnlLayer = JPanel()
        self.pnlLayer.setOpaque(False)
        #self.pnlLayer.setBorder(EmptyBorder(2,2,2,2))

        self.pnlLayer.setLayout(FlowLayout(FlowLayout.LEFT))
        self.chkLayerVisibility = JCheckBox()
        self.chkLayerVisibility.setOpaque(False)
        self.pnlLayer.add(self.chkLayerVisibility)
        self.lblLayerIcon = JLabel()
        self.lblLayerName = JLabel()
        self.lblLayerName.setText(
            "plddddddddddddddddddddddddddddddddddddddddddddddddddddddd")

        self.tree.setRowHeight(
            int(self.pnlLayer.getPreferredSize().getHeight()) - 3)  #+2
        self.pnlLayer.add(self.lblLayerIcon)
        self.pnlLayer.add(self.lblLayerName)

        self.lblUnknown = JLabel()

    def getTreeCellRendererComponent(self, tree, value, selected, expanded,
                                     leaf, row, hasFocus):
        uo = value.getUserObject()
        if isinstance(uo, DataGroup):
            text = "[" + str(value.getChildCount()) + "] " + uo.getName()
            self.lblGroup.setText(text)
            self.lblGroup.setPreferredSize(self.lblGroupPreferredSize)
            return self.lblGroup
        if isinstance(uo, DataLayer):
            layer = uo.getLayer()
            self.lblLayerName.setText(layer.getName())
            self.lblLayerIcon.setIcon(getIconFromLayer(layer))
            self.chkLayerVisibility.setSelected(layer.isVisible())
            if layer.isWithinScale(
                    self.mapContext.getScaleView()):  # and layer.isVisible():
                self.chkLayerVisibility.setEnabled(True)
            else:
                self.chkLayerVisibility.setEnabled(False)

            self.lblLayerName.setForeground(Color.BLACK)

            font = self.lblLayerName.getFont()
            self.lblLayerName.setForeground(Color.BLACK)
            if layer.isEditing():
                self.lblLayerName.setForeground(Color.RED)
            if layer.isActive() and font.isBold():
                pass
            elif layer.isActive() and not font.isBold():
                newfont = font.deriveFont(Font.BOLD)
                self.lblLayerName.setFont(newfont)
            else:
                newfont = font.deriveFont(Font.PLAIN)
                self.lblLayerName.setFont(newfont)
            self.pnlLayer.repaint()
            return self.pnlLayer
        self.lblUnknown.setText("")
        self.lblUnknown.setPreferredSize(Dimension(0, 0))

        return self.lblUnknown
Ejemplo n.º 25
0
class BurpExtender(IBurpExtender, IExtensionStateListener, IHttpListener, ITab,
                   FocusListener, ActionListener, MouseAdapter):
    _version = "0.2"
    _name = "PyRules"
    _varsStorage = _name + "_vars"
    _scriptStorage = _name + "_script"

    _enabled = 0
    _vars = {}

    def registerExtenderCallbacks(self, callbacks):
        print "Load:" + self._name + " " + self._version

        self.callbacks = callbacks
        self.helpers = callbacks.helpers

        #Create Tab layout
        self.jVarsPane = JTextPane()
        self.jVarsPane.setFont(Font('Monospaced', Font.PLAIN, 11))
        self.jVarsPane.addFocusListener(self)

        self.jMenuPanel = JPanel()
        self.jLeftUpPanel = JPanel()

        self.jEnable = JCheckBox()
        self.jEnable.setFont(Font('Monospaced', Font.BOLD, 11))
        self.jEnable.setForeground(Color(0, 0, 204))
        self.jEnable.setText(self._name)
        self.jEnable.addActionListener(self)

        self.jDocs = JLabel()
        self.jDocs.setFont(Font('Monospaced', Font.PLAIN, 11))
        self.jDocs.setForeground(Color(51, 102, 255))
        self.jDocs.setText(Strings.docs_titel)
        self.jDocs.setToolTipText(Strings.docs_tooltip)
        self.jDocs.addMouseListener(self)

        self.jConsoleText = JTextArea()
        self.jConsoleText.setFont(Font('Monospaced', Font.PLAIN, 10))
        self.jConsoleText.setBackground(Color(244, 246, 247))
        self.jConsoleText.setEditable(0)
        self.jConsoleText.setWrapStyleWord(1)
        self.jConsoleText.setRows(10)
        self.jScrollConsolePane = JScrollPane()
        self.jScrollConsolePane.setViewportView(self.jConsoleText)
        #set initial text
        self.jConsoleText.setText(Strings.console_disable)

        self.jMenuPanelLayout = GroupLayout(self.jMenuPanel)
        self.jMenuPanel.setLayout(self.jMenuPanelLayout)
        self.jMenuPanelLayout.setHorizontalGroup(
            self.jMenuPanelLayout.createParallelGroup(
                GroupLayout.Alignment.LEADING).addGroup(
                    self.jMenuPanelLayout.createSequentialGroup().addComponent(
                        self.jEnable).addPreferredGap(
                            LayoutStyle.ComponentPlacement.RELATED, 205,
                            32767).addComponent(self.jDocs)))

        self.jMenuPanelLayout.setVerticalGroup(
            self.jMenuPanelLayout.createParallelGroup(
                GroupLayout.Alignment.LEADING).addGroup(
                    self.jMenuPanelLayout.createSequentialGroup().addGroup(
                        self.jMenuPanelLayout.createParallelGroup(
                            GroupLayout.Alignment.BASELINE).addComponent(
                                self.jEnable).addComponent(self.jDocs)).addGap(
                                    0, 7, 32767)))

        self.jConsolePane = JPanel()
        self.jConsoleLayout = GroupLayout(self.jConsolePane)
        self.jConsolePane.setLayout(self.jConsoleLayout)
        self.jConsoleLayout.setHorizontalGroup(
            self.jConsoleLayout.createParallelGroup(
                GroupLayout.Alignment.LEADING).addComponent(
                    self.jScrollConsolePane))
        self.jConsoleLayout.setVerticalGroup(
            self.jConsoleLayout.createParallelGroup(
                GroupLayout.Alignment.LEADING).addGroup(
                    GroupLayout.Alignment.TRAILING,
                    self.jConsoleLayout.createSequentialGroup().addComponent(
                        self.jScrollConsolePane, GroupLayout.DEFAULT_SIZE, 154,
                        32767).addContainerGap()))
        self.jLeftUpPanelLayout = GroupLayout(self.jLeftUpPanel)
        self.jLeftUpPanel.setLayout(self.jLeftUpPanelLayout)
        self.jLeftUpPanelLayout.setHorizontalGroup(
            self.jLeftUpPanelLayout.createParallelGroup(
                GroupLayout.Alignment.LEADING).addComponent(
                    self.jConsolePane, GroupLayout.DEFAULT_SIZE,
                    GroupLayout.DEFAULT_SIZE,
                    32767).addComponent(self.jMenuPanel,
                                        GroupLayout.DEFAULT_SIZE,
                                        GroupLayout.DEFAULT_SIZE,
                                        GroupLayout.PREFERRED_SIZE))
        self.jLeftUpPanelLayout.setVerticalGroup(
            self.jLeftUpPanelLayout.
            createParallelGroup(GroupLayout.Alignment.LEADING).addGroup(
                GroupLayout.Alignment.TRAILING,
                self.jLeftUpPanelLayout.createSequentialGroup().addComponent(
                    self.jMenuPanel, GroupLayout.PREFERRED_SIZE,
                    GroupLayout.DEFAULT_SIZE,
                    GroupLayout.PREFERRED_SIZE).addPreferredGap(
                        LayoutStyle.ComponentPlacement.RELATED).addComponent(
                            self.jConsolePane, GroupLayout.DEFAULT_SIZE,
                            GroupLayout.DEFAULT_SIZE, 32767)))

        self.jScrollpaneLeftDown = JScrollPane()
        self.jScrollpaneLeftDown.setViewportView(self.jVarsPane)

        self.jSplitPaneLeft = JSplitPane(JSplitPane.VERTICAL_SPLIT,
                                         self.jLeftUpPanel,
                                         self.jScrollpaneLeftDown)
        self.jSplitPaneLeft.setDividerLocation(300)

        self.jScriptPane = JTextPane()
        self.jScriptPane.setFont(Font('Monospaced', Font.PLAIN, 11))
        self.jScriptPane.addMouseListener(self)

        self.JScrollPaneRight = JScrollPane()
        self.JScrollPaneRight.setViewportView(self.jScriptPane)

        self.jSplitPane = JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
                                     self.jSplitPaneLeft,
                                     self.JScrollPaneRight)
        self.jSplitPane.setDividerLocation(400)

        #Load saved saved settings
        ##Load vars
        vars = callbacks.loadExtensionSetting(self._varsStorage)
        if vars:
            vars = base64.b64decode(vars)
        else:
            # try to load the example
            try:
                with open("examples/Simple-CSRF-vars.py") as fvars:
                    vars = fvars.read()
            # load the default text
            except:
                vars = Strings.vars

        ## initiate the persistant variables
        locals_ = {}
        try:
            exec(vars, {}, locals_)
        except Exception as e:
            print e
        self._vars = locals_

        ## update the vars screen
        self.jVarsPane.document.insertString(self.jVarsPane.document.length,
                                             vars, SimpleAttributeSet())

        ##Load script
        script = callbacks.loadExtensionSetting(self._scriptStorage)
        if script:
            script = base64.b64decode(script)
        else:
            # try to load the example
            try:
                with open("examples/Simple-CSRF-script.py") as fscript:
                    script = fscript.read()
            # load the default text
            except:
                script = Strings.script

        ## compile the rules
        self._script = script
        self._code = ''

        try:
            self._code = compile(script, '<string>', 'exec')
        except Exception as e:
            print(
                '{}\nReload extension after you correct the error.'.format(e))

        ## update the rules screen
        self.jScriptPane.document.insertString(
            self.jScriptPane.document.length, script, SimpleAttributeSet())

        #Register Extension
        callbacks.customizeUiComponent(self.getUiComponent())
        callbacks.addSuiteTab(self)
        callbacks.registerExtensionStateListener(self)
        callbacks.registerHttpListener(self)

        self.jScriptPane.requestFocus()

    def getUiComponent(self):
        return self.jSplitPane

    def getTabCaption(self):
        return self._name

    def actionPerformed(self, event):
        #Check box was clicked
        if self.jEnable == event.getSource():
            if self._enabled == 1:
                self._enabled = 0
                # console content shows help
                self.jConsoleText.setText(Strings.console_disable)
            else:
                self._enabled = 1
                # console content displays the current persistent variable state
                self.jConsoleText.setText(Strings.console_state)
                self.jConsoleText.append(pformat(self._vars))
                self.jConsoleText.append(Strings.extra_line)
                self.jConsoleText.append(Strings.console_log)
        return

    def mouseClicked(self, event):
        if event.source == self.jDocs:
            uri = URI.create("https://github.com/DanNegrea/PyRules")
            if uri and Desktop.isDesktopSupported() and Desktop.getDesktop(
            ).isSupported(Desktop.Action.BROWSE):
                Desktop.getDesktop().browse(uri)
        return

    def focusGained(self, event):

        if self.jConsolePane == event.getSource():
            pass
            #print "Status pane gained focus" #debug
        return

    def focusLost(self, event):
        #Reinitialize the persistent values
        if self.jVarsPane == event.getSource():
            # get the text from the pane
            end = self.jVarsPane.document.length
            vars = self.jVarsPane.document.getText(0, end)

            # compute the new values
            locals_ = {}
            exec(vars, {}, locals_)
            self._vars = locals_

            # display the new result in console
            self.jConsoleText.append(Strings.console_state)
            self.jConsoleText.append(pformat(self._vars))
            self.jConsoleText.append(Strings.extra_line)
            self.jConsoleText.append(Strings.console_log)

            # scroll to bottom
            verticalScrollBar = self.jScrollConsolePane.getVerticalScrollBar()
            verticalScrollBar.setValue(verticalScrollBar.getMaximum())
        return

    def extensionUnloaded(self):
        try:
            #Save the latestest vars and script text
            ## save vars
            end = self.jVarsPane.document.length
            vars = self.jVarsPane.document.getText(0, end)
            vars = base64.b64encode(vars)
            self.callbacks.saveExtensionSetting(self._varsStorage, vars)
            ## save script/rules
            end = self.jScriptPane.document.length
            script = self.jScriptPane.document.getText(0, end)
            script = base64.b64encode(script)
            self.callbacks.saveExtensionSetting(self._scriptStorage, script)
        except Exception:
            traceback.print_exc(file=self.callbacks.getStderr())
        print "Unloaded"  #debug
        return

    def processHttpMessage(self, toolFlag, messageIsRequest, messageInfo):
        if self._enabled == 0:
            return

        try:
            locals_ = {
                'extender': self,
                'callbacks': self.callbacks,
                'helpers': self.helpers,
                'toolFlag': toolFlag,
                'messageIsRequest': messageIsRequest,
                'messageInfo': messageInfo,
                'log': self.log
            }
            # add the _vars as gloval variables
            locals_ = dict(locals_, **self._vars)

            # execute the script/rules
            try:
                exec(self.getCode, {}, locals_)
            # catch exit() call inside the rule
            except SystemExit:
                pass

            # update the persistant variables by searching the local variables with the same name
            for key in self._vars:
                # assumption self._vars dictionary is smaller than locals_
                if key in locals_:
                    self._vars[key] = locals_[key]
        except Exception:
            traceback.print_exc(file=self.callbacks.getStderr())
        return

    #Returns the compiled script
    @property
    def getCode(self):
        end = self.jScriptPane.document.length
        script = self.jScriptPane.document.getText(0, end)

        # if the script hasn't changed return the already compile text
        if script == self._script:
            return self._code
        self._script = script

        # compile, store and return the result
        self._code = compile(script, '<string>', 'exec')
        return self._code

    #Log the information into the console screen
    def log(self, obj):
        # if string just append. else use pformat from pprint
        if isinstance(obj, str):
            self.jConsoleText.append(obj + "\n")
        else:
            self.jConsoleText.append(pformat(obj) + "\n")
        # scroll to bottom
        verticalScrollBar = self.jScrollConsolePane.getVerticalScrollBar()
        verticalScrollBar.setValue(verticalScrollBar.getMaximum())
        return
Ejemplo n.º 26
0
class extender():

    def __init__(self):
        self.jLabel1 = JLabel()
        self.jCheckBox1 = JCheckBox()
        self.jScrollPane1 = JScrollPane()
        self.jTable1 = JTable()
        self.jTabbedPane1 = JTabbedPane()
        self.jPanel1 = JPanel()
        self.jButton1 = JButton("Add")
        self.jButton2 = JButton("Remove")
        self.jLabel2 = JLabel()
        self.jLabel3 = JLabel()
        self.jLabel4 = JLabel()
        self.jLabel5 = JLabel()
        self.jLabel6 = JLabel()
        self.jTextField1 = JTextField()
        self.jTextField2 = JTextField()
        self.jTextField3 = JTextField()
        
        method = ["http", "https"]
        self.jComboBox1 = JComboBox(method)
        
        self.jLabel7 = JLabel()
        self.jLabel8 = JLabel()
        self.jTextField4 = JTextField()
        self.jButton3 = JButton()
        self.jPanel2 = JPanel()
        self.jScrollPane3 = JScrollPane()
        self.jTextArea2 = JTextArea()

        self.jLabel1.setFont(Font("굴림", 1, 12))
        self.jLabel1.setText("Use local files to serve remote locations.")

        self.jCheckBox1.setText("Enable Map Local")
        
        self.jScrollPane1.setViewportView(self.jTable1)

        self.jLabel2.setText("Protocol:")

        self.jLabel3.setText("Host:")

        self.jLabel4.setText("Path:")

        self.jLabel5.setText("Query:")

        self.jLabel6.setText("Map From")

        self.jLabel7.setText("Map To")

        self.jLabel8.setText("Local Path:")

        self.jButton3.setText("Choose")
        
        jPanel1Layout = GroupLayout(self.jPanel1)
        self.jPanel1.setLayout(jPanel1Layout)
        
        from java.lang import Short
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(jPanel1Layout.createParallelGroup(GroupLayout.Alignment.TRAILING)
                            .addComponent(self.jLabel3)
                            .addComponent(self.jLabel2)
                            .addComponent(self.jLabel4)
                            .addComponent(self.jLabel5)
                            .addComponent(self.jLabel6))
                        .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(GroupLayout.Alignment.LEADING)
                            .addComponent(self.jTextField1)
                            .addComponent(self.jTextField2)
                            .addComponent(self.jTextField3)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(self.jComboBox1, GroupLayout.PREFERRED_SIZE, 86, GroupLayout.PREFERRED_SIZE)
                                .addGap(0, 0, Short.MAX_VALUE))))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addContainerGap()
                                .addComponent(self.jLabel7))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGap(30, 30, 30)
                                .addComponent(self.jLabel8)
                                .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(self.jTextField4, GroupLayout.DEFAULT_SIZE, 2000, Short.MAX_VALUE)
                                .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(self.jButton3, GroupLayout.PREFERRED_SIZE, 95, GroupLayout.PREFERRED_SIZE))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGap(0, 0, Short.MAX_VALUE)
                                .addComponent(self.jButton1, GroupLayout.PREFERRED_SIZE, 79, GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(self.jButton2, GroupLayout.PREFERRED_SIZE, 79, GroupLayout.PREFERRED_SIZE)))
                        .addGap(0, 18, Short.MAX_VALUE)))
                .addContainerGap())
        )
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(GroupLayout.Alignment.LEADING)
            .addGroup(GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(self.jLabel6)
                .addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                    .addComponent(self.jLabel2)
                    .addComponent(self.jComboBox1, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                    .addComponent(self.jLabel3)
                    .addComponent(self.jTextField1, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                    .addComponent(self.jLabel4)
                    .addComponent(self.jTextField2, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                    .addComponent(self.jLabel5)
                    .addComponent(self.jTextField3, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(self.jLabel7)
                .addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                    .addComponent(self.jLabel8)
                    .addComponent(self.jTextField4, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                    .addComponent(self.jButton3))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                    .addComponent(self.jButton1)
                    .addComponent(self.jButton2))
                .addContainerGap(19, Short.MAX_VALUE))
        )

        self.jTabbedPane1.addTab("Edit Mapping", self.jPanel1)

        self.jTextArea2.setColumns(20)
        self.jTextArea2.setRows(5)
        self.jScrollPane3.setViewportView(self.jTextArea2)

        jPanel2Layout = GroupLayout(self.jPanel2)
        self.jPanel2.setLayout(jPanel2Layout)
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(self.jScrollPane3, GroupLayout.DEFAULT_SIZE, 729, Short.MAX_VALUE)
                .addContainerGap())
        )
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(self.jScrollPane3, GroupLayout.DEFAULT_SIZE, 255, Short.MAX_VALUE)
                .addContainerGap())
        )

        self.jTabbedPane1.addTab("Viewer", self.jPanel2)
        
        self.panel = JPanel()
        layout = GroupLayout(self.panel)
        self.panel.setLayout(layout)
        
        layout.setHorizontalGroup(
            layout.createParallelGroup(GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
                    .addComponent(self.jScrollPane1)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
                            .addComponent(self.jCheckBox1)
                            .addComponent(self.jLabel1, GroupLayout.PREFERRED_SIZE, 285, GroupLayout.PREFERRED_SIZE))
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addComponent(self.jTabbedPane1))
                .addContainerGap())
        )
        layout.setVerticalGroup(
            layout.createParallelGroup(GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(self.jLabel1)
                .addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(self.jCheckBox1)
                .addGap(18, 18, 18)
                .addComponent(self.jScrollPane1, GroupLayout.PREFERRED_SIZE, 140, GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(self.jTabbedPane1)
                .addContainerGap())
        )
Ejemplo n.º 27
0
class Pipeline():
    def __init__(self):
        #If a swing interface is asked for this will be the JFrame.
        self.frame = None
        #Keeps track of the number of queries processed.
        self.jobCount = 0
        #Keeps track of the query currently being processed.
        self.currentJob = ""
        #Keeps track of the massage to be displayed.
        self.message = 0
        #Messages to be displayed at each stage in the processing of a single query.
        self.messages = [
            "Searching for genes via genemark",
            "Extending genes found via genemark",
            "Searching for intergenic genes", "Removing overlapping genes",
            "Searching for promoters", "Using transterm to find terminators",
            "Removing transcription signals which conflict with genes",
            "Writing Artemis file", "Writing summary file"
        ]
        self.exception = None

    def initializeDisplay(self, queries, swing):
        """
    queries: A list of the fasts files to be processed.
    swing:   If true then updates about progress will be displayed in a swing window, otherwise they will be written to stdout.
    
    Initializes the interface for telling the user about progress in the pipeline.  Queries is used to count the
    number of queries the pipeline will process and to size the swing display(if it is used) so that text
    isn't cutoff at the edge of the window.  The swing display is setup if swing is true.
    """

        self.numJobs = len(queries)
        if swing:
            self.frame = JFrame("Neofelis")
            self.frame.addWindowListener(PipelineWindowAdapter(self))
            contentPane = JPanel(GridBagLayout())
            self.frame.setContentPane(contentPane)
            self.globalLabel = JLabel(max(queries, key=len))
            self.globalProgress = JProgressBar(0, self.numJobs)
            self.currentLabel = JLabel(max(self.messages, key=len))
            self.currentProgress = JProgressBar(0, len(self.messages))
            self.doneButton = JButton(DoneAction(self.frame))
            self.doneButton.setEnabled(False)

            constraints = GridBagConstraints()

            constraints.gridx, constraints.gridy = 0, 0
            constraints.gridwidth, constraints.gridheight = 1, 1
            constraints.weightx = 1
            constraints.fill = GridBagConstraints.HORIZONTAL
            contentPane.add(self.globalLabel, constraints)
            constraints.gridy = 1
            contentPane.add(self.globalProgress, constraints)
            constraints.gridy = 2
            contentPane.add(self.currentLabel, constraints)
            constraints.gridy = 3
            contentPane.add(self.currentProgress, constraints)
            constraints.gridy = 4
            constraints.weightx = 0
            constraints.fill = GridBagConstraints.NONE
            constraints.anchor = GridBagConstraints.LINE_END
            contentPane.add(self.doneButton, constraints)

            self.frame.pack()
            self.frame.setResizable(False)
            self.globalLabel.setText(" ")
            self.currentLabel.setText(" ")
            self.frame.setLocationRelativeTo(None)
            self.frame.setVisible(True)

    def updateProgress(self, job):
        """
    query: Name of the query currently being processed.
    
    This function use used for updating the progress shown in the interface.  If job is not equal to currentJob then
    global progress is incremented and shown and the currentProgress is reset and shown.  If job is equal to currentJob
    then the globalProgress does not change and currentProgress is incremented.
    """
        if self.exception:
            raise self.exception

        if self.frame:
            if job != self.currentJob:
                self.currentProgress.setValue(
                    self.currentProgress.getMaximum())
                self.globalLabel.setText(job)
                self.globalProgress.setValue(self.jobCount)
                print "Processing %s, %.2f%% done" % (
                    job, 100.0 * self.jobCount / self.numJobs)
                self.jobCount += 1
                self.currentJob = job
                self.message = -1
            self.message += 1
            print "    %s, %.2f%% done" % (self.messages[self.message], 100.0 *
                                           self.message / len(self.messages))
            self.currentProgress.setValue(self.message)
            self.currentLabel.setText(self.messages[self.message])
        else:
            if job != self.currentJob:
                print "Processing %s, %.2f%% done" % (
                    job, 100.0 * self.jobCount / self.numJobs)
                self.jobCount += 1
                self.currentJob = job
                self.message = -1
            self.message += 1
            print "    %s, %.2f%% done" % (self.messages[self.message], 100.0 *
                                           self.message / len(self.messages))

    def finished(self):
        """
    This function is to be called at the end of the pipeline.  Informs the user that the pipeline is finished
    and if a swing interface is being used the Done button is enabled.
    """
        print "Processing 100.00% done"
        if self.frame:
            self.globalLabel.setText("Finished")
            self.globalProgress.setValue(self.globalProgress.getMaximum())
            self.currentLabel.setText(" ")
            self.currentProgress.setValue(self.currentProgress.getMaximum())
            self.doneButton.setEnabled(True)
            while self.frame.isVisible():
                pass

    def run(self,
            blastLocation,
            genemarkLocation,
            transtermLocation,
            database,
            eValue,
            matrix,
            minLength,
            scaffoldingDistance,
            ldfCutoff,
            queries,
            swing=False,
            email=""):
        """
    blastLocation:       Directory blast was installed in.
    genemarkLocation:    Directory genemark was installed in.
    transtermLocation:   Directory transterm was installed in.
    database:            Name of the blast database to use.
    eValue:              The e value used whenever a blast search is done.
    matrix:              The matrix to use when running genemark.  If None then genemark is run heuristically.
    minLength:           Minimum length of any genes included in the resulting annotation.
    scaffoldingDistance: The maximum length allowed between genes when contiguous regions of genes are being identified
    ldfCutoff:           Minimum LDF allowed for any promoters included in the resulting annotation
    queries:             A list of faster files to process.
    swing:               If true a swing window will be used to updated the user about the pipeline's progress.
    email:               If this is a non-empty string an email will be sent to the address in the string when the pipeline is done.  The local machine will be used as
                         an SMTP server and this will not work if it isn't.
    
    The main pipeline function.  For every query genemark is used to predict genes, these genes are then extended to any preferable starts.  Then the pipeline searches
    for any intergenic genes(genes between those found by genemark) and these are combined with the extended genemark genes.  Then the genes are pruned to remove
    any undesirable genes found in the intergenic stage.  BPROM and Transterm are used to find promoters and terminators, which are then pruned to remove any
    signals which are inside or too far away from any genes.  Finally, all the remaining genes, promoters, and terminators ar written to an artemis file in the directory
    of the query with the same name but with a .art extension, and .dat and .xls files will be generating describing the blast results of the final genes.
    """
        self.initializeDisplay(queries, swing)

        try:
            for query in queries:
                name = os.path.splitext(query)[0]
                queryDirectory, name = os.path.split(name)

                genome = utils.loadGenome(query)
                swapFileName = "query" + str(id(self)) + ".fas"
                queryFile = open(swapFileName, "w")
                queryFile.write(">" + name + "\n")
                for i in range(0, len(genome), 50):
                    queryFile.write(genome[i:min(i + 50, len(genome))] + "\n")
                queryFile.close()

                self.updateProgress(query)
                initialGenes = genemark.findGenes(swapFileName, name,
                                                  blastLocation, database,
                                                  eValue, genemarkLocation,
                                                  matrix, self)
                #artemis.writeArtemisFile(os.path.splitext(query)[0] + ".genemark.art", genome, initialGenes.values())

                self.updateProgress(query)
                extendedGenes = extend.extendGenes(swapFileName, initialGenes,
                                                   name, blastLocation,
                                                   database, eValue, self)
                #artemis.writeArtemisFile(os.path.splitext(query)[0] + ".extended.art", genome, extendedGenes.values())

                self.updateProgress(query)
                intergenicGenes = intergenic.findIntergenics(
                    swapFileName, extendedGenes, name, minLength,
                    blastLocation, database, eValue, self)
                #artemis.writeArtemisFile(os.path.splitext(query)[0] + ".intergenic.art", genome, intergenicGenes.values())
                genes = {}
                for k, v in extendedGenes.items() + intergenicGenes.items():
                    genes[k] = v

                self.updateProgress(query)
                scaffolded = scaffolds.refineScaffolds(genes,
                                                       scaffoldingDistance)

                self.updateProgress(query)
                initialPromoters = promoters.findPromoters(swapFileName, name)

                self.updateProgress(query)
                initialTerminators = terminators.findTerminators(
                    swapFileName, name, genes.values(), transtermLocation)

                self.updateProgress(query)
                filteredSignals = signals.filterSignals(
                    scaffolded.values(), initialPromoters + initialTerminators)
                filteredPromoters = filter(
                    lambda x: isinstance(x, promoters.Promoter),
                    filteredSignals)
                filteredTerminators = filter(
                    lambda x: isinstance(x, terminators.Terminator),
                    filteredSignals)

                self.updateProgress(query)
                artemis.writeArtemisFile(
                    os.path.splitext(query)[0] + ".art", genome,
                    scaffolded.values(), filteredPromoters,
                    filteredTerminators)

                self.updateProgress(query)
                report.report(name, scaffolded, os.path.splitext(query)[0])

            if email:
                message = MIMEText("Your genome has been annotated.")
                message["Subject"] = "Annotation complete"
                message["From"] = "Neofelis"
                message["To"] = email

                smtp = smtplib.SMTP("tmpl.arizona.edu", 587)
                smtp.ehlo()
                smtp.starttls()
                smtp.ehlo
                smtp.sendmail("Neofelis", [email], message.as_string())
                smtp.close()

            self.finished()
        except PipelineException:
            return
Ejemplo n.º 28
0
class BurpExtender(IBurpExtender, ITab, IExtensionStateListener):
    # Define the global variables for the burp plugin
    EXTENSION_NAME = "UPnP BHunter"
    ipv4_selected = True
    services_dict = {}
    ip_service_dict = {}
    STOP_THREAD = False

    #Some  SSDP m-search parameters are based upon "UPnP Device Architecture v2.0"
    SSDP_MULTICAST_IPv4 = ["239.255.255.250"]
    SSDP_MULTICAST_IPv6 = ["FF02::C", "FF05::C"]
    SSDP_MULTICAST_PORT = 1900
    ST_ALL = "ssdp:all"
    ST_ROOTDEV = "upnp:rootdevice"
    PLACEHOLDER = "FUZZ_HERE"
    SSDP_TIMEOUT = 2

    def registerExtenderCallbacks(self, callbacks):
        # Get a reference to callbacks object
        self.callbacks = callbacks
        # Get the useful extension helpers object
        self.helpers = callbacks.getHelpers()
        # Set the extension name
        self.callbacks.setExtensionName(self.EXTENSION_NAME)
        self.callbacks.registerExtensionStateListener(self)
        # Draw plugin user interface
        self.drawPluginUI()
        self.callbacks.addSuiteTab(self)
        # Plugin loading message
        print("[+] Burp plugin UPnP BHunter loaded successfully")
        return

    def drawPluginUI(self):
        # Create the plugin user interface
        self.pluginTab = JPanel()
        self.uiTitle = JLabel('UPnP BHunter Load, Aim and Fire Console')
        self.uiTitle.setFont(Font('Tahoma', Font.BOLD, 14))
        self.uiTitle.setForeground(Color(250, 100, 0))
        self.uiPanelA = JSplitPane(JSplitPane.VERTICAL_SPLIT)
        self.uiPanelA.setMaximumSize(Dimension(2500, 1000))
        self.uiPanelA.setDividerSize(2)
        self.uiPanelB = JSplitPane(JSplitPane.VERTICAL_SPLIT)
        self.uiPanelB.setDividerSize(2)
        self.uiPanelA.setBottomComponent(self.uiPanelB)
        self.uiPanelA.setBorder(BorderFactory.createLineBorder(Color.gray))

        # Create and configure labels and text fields
        self.labeltitle_step1 = JLabel("[1st STEP] Discover UPnP Locations")
        self.labeltitle_step1.setFont(Font('Tahoma', Font.BOLD, 14))
        self.labeltitle_step2 = JLabel(
            "[2nd STEP] Select a UPnP Service and Action")
        self.labeltitle_step2.setFont(Font('Tahoma', Font.BOLD, 14))
        self.labeltitle_step3 = JLabel("[3rd STEP] Time to Attack it")
        self.labeltitle_step3.setFont(Font('Tahoma', Font.BOLD, 14))
        self.labelsubtitle_step1 = JLabel(
            "Specify the IP version address in scope and start UPnP discovery")
        self.labelsubtitle_step2 = JLabel(
            "Select which of the found UPnP services will be probed")
        self.labelsubtitle_step3 = JLabel(
            "Review and modify the request, then send it to one of the attack tools"
        )
        self.label_step1 = JLabel("Target IP")
        self.label_step2 = JLabel("Found UPnp Services")
        self.labelstatus = JLabel("             Status")
        self.labelempty_step1 = JLabel("                ")
        self.labelempty_step2 = JLabel("  ")
        self.labelupnp = JLabel("UPnP list")
        self.labelip = JLabel("IP list")
        self.labelactions = JLabel("Actions")
        self.labelNoneServiceFound = JLabel("  ")
        self.labelNoneServiceFound.setFont(Font('Tahoma', Font.BOLD, 12))
        self.labelNoneServiceFound.setForeground(Color.red)

        # Create combobox for IP version selection
        self.ip_versions = ["IPv4", "IPv6"]
        self.combo_ipversion = JComboBox(self.ip_versions)
        self.combo_ipversion.setSelectedIndex(0)
        self.combo_ipversion.setEnabled(True)

        # Create and configure progress bar
        self.progressbar = JProgressBar(0, 100)
        self.progressbar.setString("Ready")
        self.progressbar.setStringPainted(True)

        # Create and configure buttons
        self.startbutton = JButton("Start Discovery",
                                   actionPerformed=self.startHunting)
        self.clearbutton = JButton("Clear All", actionPerformed=self.clearAll)
        self.intruderbutton = JButton("Send to Intruder",
                                      actionPerformed=self.sendToIntruder)
        self.repeaterbutton = JButton("Send to Repeater",
                                      actionPerformed=self.sendToRepeater)
        #self.WANrepeaterbutton = JButton("to Repeater", actionPerformed=self.sendWANUPnPToRepeater)
        self.textarea_request = JTextArea(18, 90)
        self.intruderbutton.setEnabled(False)
        self.repeaterbutton.setEnabled(False)

        # Class neeeded to handle the target combobox in second step panel
        class TargetComboboxListener(ActionListener):
            def __init__(self, upnpcombo_targets, upnpcombo_services,
                         ip_service_dict):
                self.upnpcombo_targets = upnpcombo_targets
                self.upnpcombo_services = upnpcombo_services
                self.ip_service_dict = ip_service_dict

            def actionPerformed(self, event):
                try:
                    # Update the location url combobox depending on the IP combobox
                    selected_target = self.upnpcombo_targets.getSelectedItem()
                    if self.ip_service_dict and selected_target:
                        self.upnpcombo_services.removeAllItems()
                        for service_url in self.ip_service_dict[
                                selected_target]:
                            self.upnpcombo_services.addItem(service_url)
                        self.upnpcombo_services.setSelectedIndex(0)
                except BaseException as e:
                    print("[!] Exception selecting service: \"%s\" ") % e

        # Class neeeded to handle the service combobox in second step panel
        class ServiceComboboxListener(ActionListener):
            def __init__(self, upnpcombo_services, upnpcombo_actions,
                         services_dict):
                self.upnpcombo_services = upnpcombo_services
                self.upnpcombo_actions = upnpcombo_actions
                self.services = services_dict

            def actionPerformed(self, event):
                try:
                    # Update the location url combobox depending on the IP combobox
                    selected_service = self.upnpcombo_services.getSelectedItem(
                    )
                    if self.services and selected_service:
                        self.upnpcombo_actions.removeAllItems()
                        actions = self.services[selected_service]
                        for action in actions:
                            self.upnpcombo_actions.addItem(action)
                        self.upnpcombo_actions.setSelectedIndex(0)
                except BaseException as e:
                    print("[!] Exception selecting service: \"%s\" ") % e

        # Class neeeded to handle the action combobox in second step panel
        class ActionComboboxListener(ActionListener):
            def __init__(self, upnpcombo_services, upnpcombo_actions,
                         textarea_request, services_dict):
                self.upnpcombo_services = upnpcombo_services
                self.upnpcombo_actions = upnpcombo_actions
                self.textarea_request = textarea_request
                self.services = services_dict

            def actionPerformed(self, event):
                try:
                    # Update the location url combobox depending on the IP combobox
                    selected_action = self.upnpcombo_actions.getSelectedItem()
                    selected_service = self.upnpcombo_services.getSelectedItem(
                    )
                    if self.services and selected_action:
                        self.textarea_request.setText(
                            self.services[selected_service][selected_action])
                except BaseException as e:
                    print("[!] Exception selecting action: \"%s\" ") % e

        self.upnpactions = ["       "]
        self.upnpcombo_actions = JComboBox(self.upnpactions)
        self.upnpcombo_actions.setSelectedIndex(0)
        self.upnpcombo_actions.setEnabled(False)

        # Create the combo box, select item at index 0 (first item in list)
        self.upnpservices = ["       "]
        self.upnpcombo_services = JComboBox(self.upnpservices)
        self.upnpcombo_services.setSelectedIndex(0)
        self.upnpcombo_services.setEnabled(False)

        # Create the combo box, select item at index 0 (first item in list)
        self.upnptargets = ["       "]
        self.upnpcombo_targets = JComboBox(self.upnptargets)
        self.upnpcombo_targets.setSelectedIndex(0)
        self.upnpcombo_targets.setEnabled(False)

        # Set the action listeners for all the comboboxes
        self.upnpcombo_targets.addActionListener(
            TargetComboboxListener(self.upnpcombo_targets,
                                   self.upnpcombo_services,
                                   self.ip_service_dict))
        self.upnpcombo_services.addActionListener(
            ServiceComboboxListener(self.upnpcombo_services,
                                    self.upnpcombo_actions,
                                    self.services_dict))
        self.upnpcombo_actions.addActionListener(
            ActionComboboxListener(self.upnpcombo_services,
                                   self.upnpcombo_actions,
                                   self.textarea_request, self.services_dict))

        # Configuring first step panel
        self.panel_step1 = JPanel()
        self.panel_step1.setPreferredSize(Dimension(2250, 100))
        self.panel_step1.setBorder(EmptyBorder(10, 10, 10, 10))
        self.panel_step1.setLayout(BorderLayout(15, 15))
        self.titlepanel_step1 = JPanel()
        self.titlepanel_step1.setLayout(BorderLayout())
        self.titlepanel_step1.add(self.labeltitle_step1, BorderLayout.NORTH)
        self.titlepanel_step1.add(self.labelsubtitle_step1)
        self.targetpanel_step1 = JPanel()
        self.targetpanel_step1.add(self.label_step1)
        self.targetpanel_step1.add(self.combo_ipversion)
        self.targetpanel_step1.add(self.startbutton)
        self.targetpanel_step1.add(self.clearbutton)
        self.targetpanel_step1.add(self.labelstatus)
        self.targetpanel_step1.add(self.progressbar)
        self.emptypanel_step1 = JPanel()
        self.emptypanel_step1.setLayout(BorderLayout())
        self.emptypanel_step1.add(self.labelempty_step1, BorderLayout.WEST)

        # Assembling first step panel components
        self.panel_step1.add(self.titlepanel_step1, BorderLayout.NORTH)
        self.panel_step1.add(self.targetpanel_step1, BorderLayout.WEST)
        self.panel_step1.add(self.emptypanel_step1, BorderLayout.SOUTH)
        self.uiPanelA.setTopComponent(self.panel_step1)

        # Configure second step panel
        self.panel_step2 = JPanel()
        self.panel_step2.setPreferredSize(Dimension(2250, 100))
        self.panel_step2.setBorder(EmptyBorder(10, 10, 10, 10))
        self.panel_step2.setLayout(BorderLayout(15, 15))
        self.titlepanel_step2 = JPanel()
        self.titlepanel_step2.setLayout(BorderLayout())
        self.titlepanel_step2.add(self.labeltitle_step2, BorderLayout.NORTH)
        self.titlepanel_step2.add(self.labelsubtitle_step2)
        self.selectpanel_step2 = JPanel()
        self.selectpanel_step2.add(self.labelip)
        self.selectpanel_step2.add(self.upnpcombo_targets)
        self.selectpanel_step2.add(self.labelupnp)
        self.selectpanel_step2.add(self.upnpcombo_services)
        self.selectpanel_step2.add(self.labelactions)
        self.selectpanel_step2.add(self.upnpcombo_actions)
        self.emptypanel_step2 = JPanel()
        self.emptypanel_step2.setLayout(BorderLayout())
        self.emptypanel_step2.add(self.labelempty_step2, BorderLayout.WEST)
        self.emptypanel_step2.add(self.labelNoneServiceFound)

        # Assembling second step panel components
        self.panel_step2.add(self.titlepanel_step2, BorderLayout.NORTH)
        self.panel_step2.add(self.selectpanel_step2, BorderLayout.WEST)
        self.panel_step2.add(self.emptypanel_step2, BorderLayout.SOUTH)
        self.uiPanelB.setTopComponent(self.panel_step2)

        # Configuring third step panel
        self.panel_step3 = JPanel()
        self.panel_step3.setPreferredSize(Dimension(2250, 100))
        self.panel_step3.setBorder(EmptyBorder(10, 10, 10, 10))
        self.panel_step3.setLayout(BorderLayout(15, 15))
        self.titlepanel_step3 = JPanel()
        self.titlepanel_step3.setLayout(BorderLayout())
        self.titlepanel_step3.add(self.labeltitle_step3, BorderLayout.NORTH)
        self.titlepanel_step3.add(self.labelsubtitle_step3)
        self.underpanel_step3 = JPanel()
        self.underpanel_step3.setLayout(BorderLayout())
        self.underpanel_step3.add((JScrollPane(self.textarea_request)),
                                  BorderLayout.NORTH)
        self.actionpanel_step3 = JPanel()
        self.actionpanel_step3.add(self.intruderbutton)
        self.actionpanel_step3.add(self.repeaterbutton)
        self.extrapanel_step3 = JPanel()
        self.extrapanel_step3.setLayout(BorderLayout())
        self.extrapanel_step3.add(self.actionpanel_step3, BorderLayout.WEST)

        # Assembling thirdd step panel components
        self.panel_step3.add(self.titlepanel_step3, BorderLayout.NORTH)
        self.panel_step3.add(self.underpanel_step3, BorderLayout.WEST)
        self.panel_step3.add(self.extrapanel_step3, BorderLayout.SOUTH)
        self.uiPanelB.setBottomComponent(self.panel_step3)

        # Assembling the group of all panels
        layout = GroupLayout(self.pluginTab)
        self.pluginTab.setLayout(layout)
        layout.setHorizontalGroup(
            layout.createParallelGroup(GroupLayout.Alignment.LEADING).addGroup(
                layout.createSequentialGroup().addGap(10, 10, 10).addGroup(
                    layout.createParallelGroup(
                        GroupLayout.Alignment.LEADING).addComponent(
                            self.uiTitle).addGap(15, 15, 15).addComponent(
                                self.uiPanelA)).addContainerGap(
                                    26, Short.MAX_VALUE)))
        layout.setVerticalGroup(
            layout.createParallelGroup(GroupLayout.Alignment.LEADING).addGroup(
                layout.createSequentialGroup().addGap(15, 15, 15).addComponent(
                    self.uiTitle).addGap(15, 15, 15).addComponent(
                        self.uiPanelA).addGap(20, 20, 20).addGap(20, 20, 20)))

    def extensionUnloaded(self):
        # Unload the plugin, and if running stop the background thread
        if self.upnpcombo_services.isEnabled():
            if self.th.isAlive():
                print("[+] Stopping thread %s") % self.th.getName()
                self.STOP_THREAD = True
                self.th.join()
            else:
                print("Thread %s already dead") % self.th.getName()
        print("[+] Burp plugin UPnP BHunter successfully unloaded")
        return

    def getTabCaption(self):
        return self.EXTENSION_NAME

    def getUiComponent(self):
        return self.pluginTab

    def clearAll(self, e=None):
        # Reset all data of the plugin
        self.services_dict.clear()
        self.progressbar.setString("Ready")
        self.progressbar.setValue(0)
        self.upnpcombo_targets.removeAllItems()
        self.upnpcombo_targets.setEnabled(False)
        self.upnpcombo_services.removeAllItems()
        self.upnpcombo_services.setEnabled(False)
        self.upnpcombo_actions.removeAllItems()
        self.upnpcombo_actions.setEnabled(False)
        self.intruderbutton.setEnabled(False)
        self.repeaterbutton.setEnabled(False)
        self.labelNoneServiceFound.setText(" ")
        self.textarea_request.setText(" ")
        print("[+] Clearing all data")
        return

    def startHunting(self, e=None):
        # Starting the UPnP hunt
        def startHunting_run():

            # Initialize the internal parameters every time the start-discovery button is clicked
            self.services_dict.clear()
            found_loc = []
            discovery_files = []
            self.labelNoneServiceFound.setText(" ")
            self.intruderbutton.setEnabled(False)
            self.repeaterbutton.setEnabled(False)

            # Then determine if targerting IPv4 or IPv6 adresses
            if self.combo_ipversion.getSelectedItem() == "IPv4":
                self.ipv4_selected = True
                print("[+] Selected IPv4 address scope")
            else:
                self.ipv4_selected = False
                print("[+] Selected IPv6 address scope")

            # And here finally the hunt could start
            self.progressbar.setString("Running...")
            self.progressbar.setValue(20)
            found_loc = self.discoverUpnpLocations()
            self.progressbar.setValue(40)
            discovery_files = self.downloadXMLfiles(found_loc)
            self.progressbar.setValue(60)
            self.buildSOAPs(discovery_files)
            self.progressbar.setValue(80)
            self.progressbar.setString("Done")
            self.progressbar.setValue(100)
            self.updateComboboxList(self.services_dict)

            # Update the comboboxes list with the discovered UPnPs
            if (self.services_dict):
                self.upnpcombo_targets.setEnabled(True)
                self.upnpcombo_services.setEnabled(True)
                self.upnpcombo_actions.setEnabled(True)
                self.intruderbutton.setEnabled(True)
                self.repeaterbutton.setEnabled(True)

            if self.STOP_THREAD:
                return

        # Start a background thread to run the above nested function in order to prevent the blocking of plugin UI
        self.th = threading.Thread(target=startHunting_run)
        #self.th.daemon = True    # This does not seem to be useful
        self.th.setName("th-BHunter")
        self.th.start()

    def ssdpReqBuilder(self, ssdp_timeout, st_type, ssdp_ip, ssdp_port):
        # Builder of the two ssdp msearch request types
        msearch_req = "M-SEARCH * HTTP/1.1\r\n" \
        "HOST: {0}:{1}\r\n" \
        "MAN: \"ssdp:discover\"\r\n" \
        "MX: {2}\r\n" \
        "ST: {3}\r\n" \
        "\r\n" \
        .format(ssdp_ip, ssdp_port, ssdp_timeout, st_type)
        return msearch_req

    def sendMsearch(self, ssdp_req, ssdp_ip, ssdp_port):
        # Send the ssdp request and retrieve response
        buf_resp = set()
        if self.ipv4_selected:
            print("[+] Creating IPv4 SSDP multicast request")
            sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        else:
            print("[+] Creating IPv6 SSDP multicast request")
            sock = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)
        sock.setblocking(0)
        # Sending ssdp requests
        while len(ssdp_req):
            # Blocking socket client until the request is completely sent
            try:
                sent = sock.sendto(ssdp_req.encode("ASCII"),
                                   (ssdp_ip, ssdp_port))
                ssdp_req = ssdp_req[sent:]
            except socket.error, exc:
                if exc.errno != errno.EAGAIN:
                    print("[E] Got error %s with socket when sending") % exc
                    sock.close()
                    raise exc
                print("[!] Blocking socket until ", len(ssdp_req), " is sent.")
                select.select([], [sock], [])
                continue
        # Retrieving ssdp responses
        num_resp = 0
        while sock:
            # Blocking socket until there are ssdp responses to be read or timeout is reached
            readable, __, __ = select.select([sock], [], [], self.SSDP_TIMEOUT)
            if not readable:
                # Timeout reached without receiving any ssdp response
                if num_resp == 0:
                    print(
                        "[!] Got timeout without receiving any ssdp response.")
                break
            else:
                num_resp = num_resp + 1
                # Almost an ssdp response was received
                if readable[0]:
                    try:
                        data = sock.recv(1024)
                        if data:
                            buf_resp.add(data.decode('ASCII'))
                    except socket.error, exc:
                        print("[E] Got error %s with socket when receiving"
                              ) % exc
                        sock.close()
                        raise exc
Ejemplo n.º 29
0
class BurpExtender(IBurpExtender, ITab, IContextMenuFactory, DocumentListener, ChangeListener):

    #
    # implement IBurpExtender
    #
    def	registerExtenderCallbacks(self, callbacks):
        print "PhantomJS RIA Crawler extension"
        print "Nikolay Matyunin @autorak <*****@*****.**>"

        # keep a reference to our callbacks object and helpers object
        self._callbacks = callbacks
        self._helpers = callbacks.getHelpers()

        # extension name
        callbacks.setExtensionName("Phantom RIA Crawler")

        # Create Tab UI components
        self._jPanel = JPanel()
        self._jPanel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));

        _titleLabel = JLabel("Phantom RIA Crawler", SwingConstants.LEFT)
        _titleLabelFont = _titleLabel.font
        _titleLabelFont = _titleLabelFont.deriveFont(Font.BOLD, 12);
        _titleLabel.setFont(_titleLabelFont);
        _titleLabel.setForeground(Color(230, 142, 11))

        self._addressTextField = JTextField('')
        self._addressTextField.setColumns(50)
        _addressTextLabel = JLabel("Target URL:", SwingConstants.RIGHT)
        self._addressTextField.getDocument().addDocumentListener(self)

        self._phantomJsPathField = JTextField('phantomjs') # TODO: set permanent config value
        self._phantomJsPathField.setColumns(50)
        _phantomJsPathLabel = JLabel("PhantomJS path:", SwingConstants.RIGHT)

        self._startButton = JToggleButton('Start', actionPerformed=self.startToggled)
        self._startButton.setEnabled(False)

        _requestsMadeLabel = JLabel("DEPs found:", SwingConstants.RIGHT)
        self._requestsMadeInfo = JLabel("", SwingConstants.LEFT)
        _statesFoundLabel = JLabel("States found:", SwingConstants.RIGHT)
        self._statesFoundInfo = JLabel("", SwingConstants.LEFT)

        _separator = JSeparator(SwingConstants.HORIZONTAL)

        _configLabel = JLabel("Crawling configuration:")
        self._configButton = JButton("Load config", actionPerformed=self.loadConfigClicked)
        self._configFile = ""

        _listenersLabel= JLabel("Burp proxy listener:", SwingConstants.RIGHT)
        self._listenersCombo = JComboBox()
        self._configTimer = Timer(5000, None)
        self._configTimer.actionPerformed = self._configUpdated
        self._configTimer.stop()
        self._configUpdated(None)

        self._commandClient = CommandClient(self)

        # Layout management
        self._groupLayout = GroupLayout(self._jPanel)
        self._jPanel.setLayout(self._groupLayout)
        self._groupLayout.setAutoCreateGaps(True)
        self._groupLayout.setAutoCreateContainerGaps(True)

        self._groupLayout.setHorizontalGroup(self._groupLayout.createParallelGroup()
            .addComponent(_titleLabel)
            .addGroup(self._groupLayout.createSequentialGroup()
                .addComponent(_addressTextLabel)
                .addGroup(self._groupLayout.createParallelGroup()
                    .addComponent(self._addressTextField, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE)
                    .addGroup(self._groupLayout.createSequentialGroup()
                        .addComponent(_requestsMadeLabel)
                        .addComponent(self._requestsMadeInfo))
                    .addGroup(self._groupLayout.createSequentialGroup()
                        .addComponent(_statesFoundLabel)
                        .addComponent(self._statesFoundInfo)))
                .addComponent(self._startButton))
            .addComponent(_separator)
            .addGroup(self._groupLayout.createSequentialGroup()
                .addComponent(_configLabel)
                .addComponent(self._configButton))
            .addGroup(self._groupLayout.createSequentialGroup()
                .addComponent(_phantomJsPathLabel)
                .addComponent(self._phantomJsPathField, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE))
            .addGroup(self._groupLayout.createSequentialGroup()
                .addComponent(_listenersLabel)
                .addComponent(self._listenersCombo, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE))
        )

        self._groupLayout.setVerticalGroup(self._groupLayout.createSequentialGroup()
            .addComponent(_titleLabel)
            .addGroup(self._groupLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                .addComponent(_addressTextLabel)
                .addComponent(self._addressTextField)
                .addComponent(self._startButton))
            .addGroup(self._groupLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                .addComponent(_requestsMadeLabel)
                .addComponent(self._requestsMadeInfo))
            .addGroup(self._groupLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                .addComponent(_statesFoundLabel)
                .addComponent(self._statesFoundInfo))
            .addComponent(_separator, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
            .addGroup(self._groupLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                .addComponent(_configLabel)
                .addComponent(self._configButton))
            .addGroup(self._groupLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                .addComponent(_phantomJsPathLabel)
                .addComponent(self._phantomJsPathField))
            .addGroup(self._groupLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                .addComponent(_listenersLabel)
                .addComponent(self._listenersCombo))
        )

        self._groupLayout.linkSize(SwingConstants.HORIZONTAL, _configLabel, _phantomJsPathLabel);
        self._groupLayout.linkSize(SwingConstants.HORIZONTAL, _configLabel, _listenersLabel);
        self._groupLayout.linkSize(SwingConstants.HORIZONTAL, _statesFoundLabel, _requestsMadeLabel);


        # context menu data
        self._contextMenuData = None;
        self._running = False;

        # register callbacks
        callbacks.customizeUiComponent(self._jPanel)
        callbacks.registerContextMenuFactory(self)
        callbacks.addSuiteTab(self)

        return

    #
    # implement ITab and Tab ChangeListener
    #
    def getTabCaption(self):
        return "Phantom RIA Crawler"
    def getUiComponent(self):
        return self._jPanel
    def stateChanged(self, ev):
        self._configUpdated()

    def _configUpdated(self, ev):
        config = self._callbacks.saveConfig()

        # update proxy listeners
        index = 0
        listeners = DefaultComboBoxModel()
        while (("proxy.listener" + str(index)) in config):
            listenerItem = config["proxy.listener" + str(index)]
            listenerItems = listenerItem.split(".")
            if (listenerItems[0] == "1"):
                address = ".".join(listenerItems[2][1:].split("|"))
                if (len(address) == 0):
                    address = "127.0.0.1"
                listeners.addElement(address + " : " + listenerItems[1])

            index = index + 1
        self._listenersCombo.setModel(listeners)
        return;

    #
    # implement button actions
    #
    def startToggled(self, ev):
        if (self._startButton.getModel().isSelected()):
            try:
                os.chdir(sys.path[0] + os.sep + "riacrawler" + os.sep + "scripts")
            except Exception as e:
                print >> sys.stderr, "RIA crawler scripts loading error", "I/O error({0}): {1}".format(e.errno, e.strerror)
                self._startButton.setSelected(False)
                return

            phantomJsPath = self._phantomJsPathField.text
            target = self._addressTextField.text

            config = "crawler.config"
            if (self._configFile):
                config = self._configFile

            listenerAddress = self._listenersCombo.getSelectedItem().replace(" ", "")
            p = Popen("{0} --proxy={3} main.js --target={1} --config={2}".format(phantomJsPath, target, config, listenerAddress), shell=True)
            self._running = True
            self._requestsMadeInfo.setText("")
            self._statesFoundInfo.setText("")
            self._commandClient.startCrawling()
        else:
            if (self._running):
                self._commandClient.stopCrawling()
            self._running = False

    def syncCrawlingState(self, result):
        print "RIA crawling state: ", result
        self._requestsMadeInfo.setText(str(result["requests_made"]))
        self._statesFoundInfo.setText(str(result["states_detected"]))
        if (result["running"] == False):
            self._commandClient.stopCrawling()
            self._running = False
            self._startButton.setSelected(False)

    def loadConfigClicked(self, ev):
        openFile = JFileChooser();
        openFile.showOpenDialog(None);
        self._configFile = openFile.getSelectedFile()

    #
    # implement DocumentListener for _addressTextField
    #
    def removeUpdate(self, ev):
        self.updateStartButton()
    def insertUpdate(self, ev):
        self.updateStartButton()
    def updateStartButton(self):
        self._startButton.setEnabled(len(self._addressTextField.text) > 0)


    #
    # implement IContextMenuFactory
    #
    def createMenuItems(self, contextMenuInvocation):
        menuItemList = ArrayList()

        context = contextMenuInvocation.getInvocationContext()
        if (context == IContextMenuInvocation.CONTEXT_MESSAGE_VIEWER_REQUEST or context == IContextMenuInvocation.CONTEXT_MESSAGE_EDITOR_REQUEST or
            context == IContextMenuInvocation.CONTEXT_PROXY_HISTORY or context == IContextMenuInvocation.CONTEXT_TARGET_SITE_MAP_TABLE):

            self._contextMenuData = contextMenuInvocation.getSelectedMessages()
            menuItemList.add(JMenuItem("Send to Phantom RIA Crawler", actionPerformed = self.menuItemClicked))

        return menuItemList


    def menuItemClicked(self, event):
        if (self._running == True):
            self._callbacks.issueAlert("Can't set data to Phantom RIA Crawler: crawling is running already.")
            return;

        dataIsSet = False;
        for message in self._contextMenuData:
            request = self._helpers.analyzeRequest(message)

            url = request.getUrl().toString()
            print url
            if (url):
                dataisSet = True;
                self._addressTextField.setText(url)
Ejemplo n.º 30
0
class Demo(JFrame, Runnable):
    def __init__(self):
        super(Demo, self).__init__()

        self.initUI()

    def initUI(self):

        self.panel = JPanel(size=(50, 50))

        self.panel.setLayout(FlowLayout())
        self.panel.setToolTipText("GPU Demo")

        self.textfield1 = JTextField('Smoothing Parameter', 15)
        self.panel.add(self.textfield1)

        joclButton = JButton("JOCL", actionPerformed=self.onJocl)
        joclButton.setBounds(100, 500, 100, 30)
        joclButton.setToolTipText("JOCL Button")
        self.panel.add(joclButton)

        javaButton = JButton("Java", actionPerformed=self.onJava)
        javaButton.setBounds(100, 500, 100, 30)
        javaButton.setToolTipText("Java Button")
        self.panel.add(javaButton)

        qButton = JButton("Quit", actionPerformed=self.onQuit)
        qButton.setBounds(200, 500, 80, 30)
        qButton.setToolTipText("Quit Button")
        self.panel.add(qButton)
        newImage = ImageIO.read(io.File("input.png"))
        resizedImage = newImage.getScaledInstance(600, 600, 10)
        newIcon = ImageIcon(resizedImage)
        label1 = JLabel("Input Image", newIcon, JLabel.CENTER)

        label1.setVerticalTextPosition(JLabel.TOP)
        label1.setHorizontalTextPosition(JLabel.RIGHT)
        label1.setSize(10, 10)
        label1.setBackground(Color.orange)
        self.panel.add(label1)

        self.getContentPane().add(self.panel)

        self.clockLabel = JLabel()
        self.clockLabel.setSize(1, 1)
        self.clockLabel.setBackground(Color.orange)

        self.clockLabel.setVerticalTextPosition(JLabel.BOTTOM)
        self.clockLabel.setHorizontalTextPosition(JLabel.LEFT)

        myClockFont = Font("Serif", Font.PLAIN, 50)
        self.clockLabel.setFont(myClockFont)

        self.panel.add(self.clockLabel)

        self.setTitle("GPU Demo")
        self.setSize(1200, 600)
        self.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
        self.setLocationRelativeTo(None)
        self.setVisible(True)

    def onQuit(self, e):
        System.exit(0)

    def onJocl(self, e):
        self.clockLabel.setText('running')
        self.started = Calendar.getInstance().getTimeInMillis()
        #print self.textfield1.getText()
        #time.sleep(5)
        iters = toInt(self.textfield1.getText())
        jocl_smoother(iters)
        elapsed = Calendar.getInstance().getTimeInMillis() - self.started
        self.clockLabel.setText('JOCL Elapsed: %.2f seconds' %
                                (float(elapsed) / 1000.0))

    def onJava(self, e):
        self.clockLabel.setText('running')
        self.started = Calendar.getInstance().getTimeInMillis()
        #print self.textfield1.getText()
        #time.sleep(5)
        iters = toInt(self.textfield1.getText())
        java_smoother(iters)
        elapsed = Calendar.getInstance().getTimeInMillis() - self.started
        self.clockLabel.setText('Java Elapsed: %.2f seconds' %
                                (float(elapsed) / 1000.0))
Ejemplo n.º 31
0
class Pipeline():
  def __init__(self):
    #If a swing interface is asked for this will be the JFrame.
    self.frame = None
    #Keeps track of the number of queries processed.
    self.jobCount = 0
    #Keeps track of the query currently being processed.
    self.currentJob = ""
    #Keeps track of the massage to be displayed.
    self.message = 0
    #Messages to be displayed at each stage in the processing of a single query.
    self.messages = ["Searching for genes via genemark",
                     "Extending genes found via genemark",
                     "Searching for intergenic genes",
                     "Removing overlapping genes",
                     "Searching for promoters",
                     "Using transterm to find terminators",
                     "Removing transcription signals which conflict with genes",
                     "Using tRNAscan to find transfer RNAs",
                     "Writing Artemis file",
                     "Writing summary .xml, .html, and .xls files"]
    self.exception = None

  def initializeDisplay(self, queries, swing):
    """
    queries: A list of the fasts files to be processed.
    swing:   If true then updates about progress will be displayed in a swing window, otherwise they will be written to stdout.
    
    Initializes the interface for telling the user about progress in the pipeline.  Queries is used to count the
    number of queries the pipeline will process and to size the swing display(if it is used) so that text
    isn't cutoff at the edge of the window.  The swing display is setup if swing is true.
    """
  
    self.numJobs = len(queries)
    if swing:
      self.frame = JFrame("Neofelis")
      self.frame.addWindowListener(PipelineWindowAdapter(self))
      contentPane = JPanel(GridBagLayout())
      self.frame.setContentPane(contentPane)
      self.globalLabel = JLabel(max(queries, key = len))
      self.globalProgress = JProgressBar(0, self.numJobs)
      self.currentLabel = JLabel(max(self.messages, key = len))
      self.currentProgress = JProgressBar(0, len(self.messages))
      self.doneButton = JButton(DoneAction(self.frame))
      self.doneButton.setEnabled(False)

      constraints = GridBagConstraints()
      
      constraints.gridx, constraints.gridy = 0, 0
      constraints.gridwidth, constraints.gridheight = 1, 1
      constraints.weightx = 1
      constraints.fill = GridBagConstraints.HORIZONTAL
      contentPane.add(self.globalLabel, constraints)
      constraints.gridy = 1
      contentPane.add(self.globalProgress, constraints)
      constraints.gridy = 2
      contentPane.add(self.currentLabel, constraints)
      constraints.gridy = 3
      contentPane.add(self.currentProgress, constraints)
      constraints.gridy = 4
      constraints.weightx = 0
      constraints.fill = GridBagConstraints.NONE
      constraints.anchor = GridBagConstraints.LINE_END
      contentPane.add(self.doneButton, constraints)
    
      self.frame.pack()
      self.frame.setResizable(False)
      self.globalLabel.setText(" ")
      self.currentLabel.setText(" ")
      self.frame.setLocationRelativeTo(None)
      self.frame.setVisible(True)

  def updateProgress(self, job):
    """
    query: Name of the query currently being processed.
    
    This function use used for updating the progress shown in the interface.  If job is not equal to currentJob then
    global progress is incremented and shown and the currentProgress is reset and shown.  If job is equal to currentJob
    then the globalProgress does not change and currentProgress is increased.
    """
    if self.exception:
      raise self.exception
    
    if self.frame:
      if job != self.currentJob:
        self.currentProgress.setValue(self.currentProgress.getMaximum())
        self.globalLabel.setText(job)
        self.globalProgress.setValue(self.jobCount)
        print "Processing %s, %.2f%% done" % (job, 100.0*self.jobCount/self.numJobs)
        self.jobCount += 1
        self.currentJob = job
        self.message = -1
      self.message += 1
      print "    %s, %.2f%% done" % (self.messages[self.message], 100.0*self.message/len(self.messages))
      self.currentProgress.setValue(self.message)
      self.currentLabel.setText(self.messages[self.message])
    else:
      if job != self.currentJob:
        print "Processing %s, %.2f%% done" % (job, 100.0*self.jobCount/self.numJobs)
        self.jobCount += 1
        self.currentJob = job
        self.message = -1
      self.message += 1
      print "    %s, %.2f%% done" % (self.messages[self.message], 100.0*self.message/len(self.messages))

  def finished(self):
    """
    This function is to be called at the end of the pipeline.  Informs the user that the pipeline is finished
    and if a swing interface is being used the Done button is enabled.
    """
    print "Processing 100.00% done"
    if self.frame:
      self.globalLabel.setText("Finished")
      self.globalProgress.setValue(self.globalProgress.getMaximum())
      self.currentLabel.setText(" ")
      self.currentProgress.setValue(self.currentProgress.getMaximum())
      self.doneButton.setEnabled(True)
      while self.frame.isVisible():
        pass

  def run(self, blastLocation, genemarkLocation, transtermLocation, tRNAscanLocation, database, eValue, matrix, minLength, scaffoldingDistance, promoterScoreCutoff, queries, swing = False, email = ""):
    """
    blastLocation:       Directory blast was installed in.
    genemarkLocation:    Directory genemark was installed in.
    transtermLocation:   Directory transterm was installed in.
    tRNAscanLocation:    Directory tRNAscan was installed in.
    database:            Name of the blast database to use.
    eValue:              The e value used whenever a blast search is done.
    matrix:              The matrix to use when running genemark.  If None then genemark is run heuristically.
    minLength:           Minimum length of any genes included in the resulting annotation.
    scaffoldingDistance: The maximum length allowed between genes when contiguous regions of genes are being identified
    promoterScoreCutoff: Minimum score allowed for any promoters included in the resulting annotation
    queries:             A list of faster files to process.
    swing:               If true a swing window will be used to updated the user about the pipeline's progress.
    email:               If this is a non-empty string an email will be sent to the address in the string when the pipeline is done.  This will be attempted with the sendmail command on the local computer.
    
    The main pipeline function.  For every query genemark is used to predict genes, these genes are then extended to any preferable starts.  Then the pipeline searches
    for any intergenic genes(genes between those found by genemark) and these are combined with the extended genemark genes.  Then the genes are pruned to remove
    any undesirable genes found in the intergenic stage.  BPROM and Transterm are used to find promoters and terminators, which are then pruned to remove any
    signals which are inside or too far away from any genes.  Next, tRNAscan is used to find any transfer RNAs in the genome.  Finally, all the remaining genes,
    promoters, and terminators are written to an artemis file in the directory of the query with the same name but with a .art extension, and .xml, .html, and
    .xls files will be generating describing the blast results of the final genes.
    """
    self.initializeDisplay(queries, swing)

    try:
      for query in queries:
        name = os.path.splitext(query)[0]
        queryDirectory, name = os.path.split(name)
        
        genome = utils.loadGenome(query)
        swapFileName = "query" + str(id(self)) + ".fas"
        queryFile = open(swapFileName, "w")
        queryFile.write(">" + name + "\n")
        for i in range(0, len(genome), 50):
          queryFile.write(genome[i:min(i+50, len(genome))] + "\n")
        queryFile.close()

        self.updateProgress(query)
        initialGenes = genemark.findGenes(swapFileName, name, blastLocation, database, eValue, genemarkLocation, matrix, self)
      
        self.updateProgress(query)
        extendedGenes = extend.extendGenes(swapFileName, initialGenes, name, blastLocation, database, eValue, self)
    
        self.updateProgress(query)
        intergenicGenes = intergenic.findIntergenics(swapFileName, extendedGenes, name, minLength, blastLocation, database, eValue, self)

        genes = {}
        for k, v in extendedGenes.items() + intergenicGenes.items():
          genes[k] = v
        
        self.updateProgress(query)
        scaffolded = scaffolds.refineScaffolds(genes, scaffoldingDistance)
 
        self.updateProgress(query)
        initialPromoters = promoters.findPromoters(swapFileName, name, promoterScoreCutoff, self.frame)
    
        self.updateProgress(query)
        initialTerminators = terminators.findTerminators(swapFileName, name, genes.values(), transtermLocation)
      
        self.updateProgress(query)
        filteredSignals = signals.filterSignals(scaffolded.values(), initialPromoters + initialTerminators)
        filteredPromoters = filter(lambda x: isinstance(x, promoters.Promoter), filteredSignals)
        filteredTerminators = filter(lambda x: isinstance(x, terminators.Terminator), filteredSignals)

        self.updateProgress(query)
        transferRNAs = rna.findtRNAs(tRNAscanLocation, swapFileName)

        os.remove(swapFileName)

        self.updateProgress(query)
        artemis.writeArtemisFile(os.path.splitext(query)[0] + ".art", genome, scaffolded.values(), filteredPromoters, filteredTerminators, transferRNAs)

        self.updateProgress(query)
        report.report(name, scaffolded, os.path.splitext(query)[0])

      if email:
        if not os.path.isfile("EMAIL_MESSAGE"):
          message = open("EMAIL_MESSAGE", "w")
          message.write("Subject: Annotation Complete\nYour genome has been annotated.\n")
          message.close()
        
        sent = False
        while not sent:
          message = open("EMAIL_MESSAGE", "r")
          sendmailProcess = subprocess.Popen(["/usr/sbin/sendmail", "-F", "Neofelis", "-f", "*****@*****.**", email],
                                             stdin = message,
                                             stdout = subprocess.PIPE)
          result = ""
          nextRead = sendmailProcess.stdout.read()
          while nextRead:
            result += nextRead
            nextRead = sendmailProcess.stdout.read()
          sent = not result.strip()
          message.close()
    
      self.finished()
    except PipelineException:
      return
Ejemplo n.º 32
0
class ProjectIngestSettingsPanel(IngestModuleIngestJobSettingsPanel):
    def __init__(self, settings):
        self.local_settings = settings
        self.initComponents()
        self.customizeComponents()

    # def event(self, event):
    #     self.local_settings.setSetting('adb', 'true' if self.adb.isSelected() else 'false')
    #     #self.local_settings.setSetting('clean_temp', 'true' if self.clean_temp.isSelected() else 'false')
    #     self.local_settings.setSetting('old_report', 'true' if self.json_reports.isSelected() else 'false')
    #     # self.local_settings.setSetting('app', self.app.getSelectedItem().split(' (')[0].lower())

    def initComponents(self):
        self.apps_checkboxes_list = []

        self.setLayout(BoxLayout(self, BoxLayout.PAGE_AXIS))
        
        # title 
        self.p_title = SettingsUtils.createPanel()
        self.lb_title = JLabel("Android Forensics")
        self.lb_title.setFont(self.lb_title.getFont().deriveFont(Font.BOLD, 11))
        self.p_title.add(self.lb_title)
        self.add(self.p_title)
        # end of title
        
        
        # info menu
        self.p_info = SettingsUtils.createPanel()
        self.lb_info = JLabel("")
        self.lb_info2 = JLabel("")
        self.p_info.add(self.lb_info)
        self.p_info.add(self.lb_info2)
        
       
        self.add(self.p_info)

        # end of info menu

        # method menu

        self.p_method = SettingsUtils.createPanel()
        self.bg_method = ButtonGroup()
        self.rb_selectedDatasource = SettingsUtils.createRadioButton("Analyse selected datasource", "method_datasource", self.onMethodChange)
        self.rb_importReportFile = SettingsUtils.createRadioButton("Import previous generated report file","method_importfile" ,self.onMethodChange)
        self.rb_liveExtraction = SettingsUtils.createRadioButton("Live extraction with ADB","method_adb", self.onMethodChange)
        self.rb_selectedDatasource.setSelected(True)

        self.bg_method.add(self.rb_selectedDatasource)
        self.bg_method.add(self.rb_importReportFile)
        self.bg_method.add(self.rb_liveExtraction)

        self.p_method.add(JLabel("Analysis method"))
        self.p_method.add(self.rb_selectedDatasource)
        self.p_method.add(self.rb_importReportFile)
        self.p_method.add(self.rb_liveExtraction)
        self.add(self.p_method)

        # end of method menu

        #app checkboxes menu
        self.p_apps = SettingsUtils.createPanel()
        
        sorted_items = OrderedDict(sorted(Utils.get_all_packages().items()))

        for app, app_id in sorted_items.iteritems():
            #(app, app_id)
            checkbox = SettingsUtils.addApplicationCheckbox(app, app_id, self.getSelectedApps)
            self.add(checkbox)
            self.apps_checkboxes_list.append(checkbox)
            self.p_apps.add(checkbox)

        self.add(self.p_apps)
        # end of checkboxes menu

    def customizeComponents(self):
        self.onMethodChange("") #initialize method option
        self.getSelectedApps("") #initialize selected apps
    
    def onMethodChange(self, event):
        self.method = self.bg_method.getSelection().getActionCommand()
        self.local_settings.setSetting("method", self.method)

        if self.method == "method_datasource":
            self.lb_info.setText("This method is used when there is no data source but you have the device.")
            self.lb_info2.setText("It will extract the content of the selected applications from the device, analyze and index the forensic artifacts.")
            self.toggleCheckboxes(False)
            
        elif self.method == "method_importfile":
            self.lb_info.setText("This method is used when you already have a report in json format previously generated by the application.")
            self.lb_info2.setText("It will analyze the report previously added to the data source and index the forensic artifacts.")
            self.toggleCheckboxes(False)
    
        elif self.method == "method_adb":
            self.lb_info.setText("This method is used when the application data has already been collected.")
            self.lb_info2.setText("It will analyze the data source previously added to the data source and index the forensic artifacts.")
            self.toggleCheckboxes(True)

        # self.local_settings.setSetting("apps", self.getSelectedApps())
        
    def getSettings(self):
        return self.local_settings
    
    def getMethod(self):
        return self.bg_method.getSelection().getActionCommand()
    
    def getSelectedApps(self, event):
        selected_apps = []
        
        for cb_app in self.apps_checkboxes_list:
            if cb_app.isSelected():
                selected_apps.append(cb_app.getActionCommand())
        
        self.local_settings.setSetting("apps", json.dumps(selected_apps))
    
    def toggleCheckboxes(self, visible):
        for cb_app in self.apps_checkboxes_list:
            cb_app.setVisible(visible)
Ejemplo n.º 33
0
class Demo(JFrame, Runnable):

    def __init__(self):
        super(Demo, self).__init__()

        self.initUI()

    def initUI(self):
       
        self.panel = JPanel(size=(50,50))
        

        self.panel.setLayout(FlowLayout( ))
        self.panel.setToolTipText("GPU Demo")

#TODO- change this so that it deletes itself when text is entered
        self.textfield1 = JTextField('Smoothing Parameter',15)        
        self.panel.add(self.textfield1)
      
        joclButton = JButton("JOCL",actionPerformed=self.onJocl)
        joclButton.setBounds(100, 500, 100, 30)
        joclButton.setToolTipText("JOCL Button")
        self.panel.add(joclButton)
        
        javaButton = JButton("Java",actionPerformed=self.onJava)
        javaButton.setBounds(100, 500, 100, 30)
        javaButton.setToolTipText("Java Button")
        self.panel.add(javaButton)

        qButton = JButton("Quit", actionPerformed=self.onQuit)
        qButton.setBounds(200, 500, 80, 30)
        qButton.setToolTipText("Quit Button")
        self.panel.add(qButton)
        newImage = ImageIO.read(io.File(getDataDir() + "input.png"))
        resizedImage =  newImage.getScaledInstance(600, 600,10)
        newIcon = ImageIcon(resizedImage)
        label1 = JLabel("Input Image",newIcon, JLabel.CENTER)

        label1.setVerticalTextPosition(JLabel.TOP)
        label1.setHorizontalTextPosition(JLabel.RIGHT)
        label1.setSize(10,10)
        label1.setBackground(Color.orange)
        self.panel.add(label1)
        
        self.getContentPane().add(self.panel)
        
        self.clockLabel = JLabel()
        self.clockLabel.setSize(1,1)
        self.clockLabel.setBackground(Color.orange)
        
        self.clockLabel.setVerticalTextPosition(JLabel.BOTTOM)
        self.clockLabel.setHorizontalTextPosition(JLabel.LEFT)
        
        myClockFont = Font("Serif", Font.PLAIN, 50)
        self.clockLabel.setFont(myClockFont)
        
        
        self.panel.add(self.clockLabel)
        
        self.setTitle("Structure-oriented smoothing OpenCL Demo")
        self.setSize(1200, 700)
        self.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
        self.setLocationRelativeTo(None)
        self.setVisible(True)
        
    def onQuit(self, e): System.exit(0)
    
    def onJocl(self, e): 
     self.clockLabel.setText('running')
     self.started = Calendar.getInstance().getTimeInMillis();
     #print self.textfield1.getText()  
     #time.sleep(5)
     iters = toInt(self.textfield1.getText())
     jocl_smoother(iters)
     elapsed = Calendar.getInstance().getTimeInMillis() - self.started;
     self.clockLabel.setText( 'JOCL Elapsed: %.2f seconds' % ( float( elapsed ) / 1000.0 ) )
    
    def onJava(self, e): 
     self.clockLabel.setText('running')
     self.started = Calendar.getInstance().getTimeInMillis();
     #print self.textfield1.getText()  
     #time.sleep(5)
     iters = toInt(self.textfield1.getText())
     java_smoother(iters)
     elapsed = Calendar.getInstance().getTimeInMillis() - self.started;
     self.clockLabel.setText( 'Java Elapsed: %.2f seconds' % ( float( elapsed ) / 1000.0 ) )
Ejemplo n.º 34
0
    def __init__(self, arg_dict):
        super(CumulusUI, self).__init__()

        # Load argument from the command line
        self.start_time = arg_dict['start_time']
        self.end_time = arg_dict['end_time']
        self.dss_path = arg_dict['dss_path']
        self.cwms_home = arg_dict['cwms_home']
        self.config = arg_dict['config']

        # Get the DSS Path if one was saved in the "cumulus.config" file
        if os.path.isfile(self.config):
            with open(os.path.join(APPDATA, "cumulus.config")) as f:
                self.dss_path = f.read()

        # Get the basins and products, load JSON, create lists for JList, and create dictionaries
        self.basin_download = json.loads(self.http_get(url_basins))        
        self.jlist_basins = ["{}:{}".format(b['office_symbol'], b['name']) for b in self.basin_download]
        self.basin_meta = dict(zip(self.jlist_basins, self.basin_download))
        self.jlist_basins.sort()

        self.product_download = json.loads(self.http_get(url_products))
        self.jlist_products = ["{}".format(p['name'].replace("_", " ").title()) for p in self.product_download]
        self.product_meta = dict(zip(self.jlist_products, self.product_download))
        self.jlist_products.sort()

        btn_submit = JButton()
        lbl_start_date = JLabel()
        lbl_end_date = JLabel()
        self.txt_select_file = JTextField()
        btn_select_file = JButton()
        lbl_origin = JLabel()
        lbl_extent = JLabel()
        lbl_select_file = JLabel()

        self.txt_start_time = JTextField()
        self.txt_end_time = JTextField()

        jScrollPane1 = JScrollPane()
        self.lst_product = JList()
        self.lst_product = JList(self.jlist_products, valueChanged = self.choose_product)
        
        jScrollPane2 = JScrollPane()
        self.lst_watershed = JList()
        self.lst_watershed = JList(self.jlist_basins, valueChanged = self.choose_watershed)

        self.cwms_dssname = JCheckBox()

        self.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE)
        self.setTitle("Cumulus CAVI UI")
        self.setLocation(Point(10, 10))
        self.setLocationByPlatform(True)
        self.setName("CumulusCaviUi")
        self.setResizable(False)

        btn_submit.setFont(Font("Tahoma", 0, 18))
        btn_submit.setText("Submit")
        btn_submit.actionPerformed = self.submit

        lbl_start_date.setText("Start Date/Time")

        lbl_end_date.setText("End Date/Time")

        self.txt_select_file.setToolTipText("FQPN to output file (.dss)")

        btn_select_file.setText("...")
        btn_select_file.setToolTipText("Select File...")
        btn_select_file.actionPerformed = self.select_file

        lbl_origin.setText("Minimum (x,y):")

        lbl_extent.setText("Maximum (x,y):")

        lbl_select_file.setText("Output File Location")

        self.txt_start_time.setToolTipText("Start Time")
        self.txt_end_time.setToolTipText("End Time")

        self.lst_product.setBorder(BorderFactory.createTitledBorder(None, "Available Products", TitledBorder.CENTER, TitledBorder.TOP, Font("Tahoma", 0, 14)))
        self.lst_product.setFont(Font("Tahoma", 0, 14))
        jScrollPane1.setViewportView(self.lst_product)
        self.lst_product.getAccessibleContext().setAccessibleName("Available Products")
        self.lst_product.getAccessibleContext().setAccessibleParent(jScrollPane2)

        self.lst_watershed.setBorder(BorderFactory.createTitledBorder(None, "Available Watersheds", TitledBorder.CENTER, TitledBorder.TOP, Font("Tahoma", 0, 14)))
        self.lst_watershed.setFont(Font("Tahoma", 0, 14))
        self.lst_watershed.setSelectionMode(ListSelectionModel.SINGLE_SELECTION)
        jScrollPane2.setViewportView(self.lst_watershed)

        self.cwms_dssname.setText("CWMS DSS filename")
        self.cwms_dssname.setToolTipText("Parameter.yyyy.mm.dss")
        self.cwms_dssname.setVisible(False)

        layout = GroupLayout(self.getContentPane());
        self.getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING, False)
                    .addComponent(lbl_select_file)
                    .addComponent(jScrollPane1)
                    .addComponent(jScrollPane2)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(GroupLayout.Alignment.TRAILING)
                            .addComponent(btn_submit)
                            .addComponent(self.txt_select_file, GroupLayout.PREFERRED_SIZE, 377, GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btn_select_file))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
                            .addComponent(lbl_start_date)
                            .addComponent(self.txt_start_time, GroupLayout.PREFERRED_SIZE, 170, GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
                            .addComponent(self.txt_end_time, GroupLayout.PREFERRED_SIZE, 170, GroupLayout.PREFERRED_SIZE)
                            .addComponent(lbl_end_date))))
                .addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        )
        layout.setVerticalGroup(
            layout.createParallelGroup(GroupLayout.Alignment.LEADING)
            .addGroup(GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(25, 25, 25)
                .addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                    .addComponent(lbl_start_date)
                    .addComponent(lbl_end_date))
                .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
                    .addComponent(self.txt_start_time, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                    .addComponent(self.txt_end_time, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(jScrollPane2, GroupLayout.PREFERRED_SIZE, 201, GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, GroupLayout.PREFERRED_SIZE, 201, GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, Short.MAX_VALUE)
                .addComponent(lbl_select_file)
                .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                    .addComponent(self.txt_select_file, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                    .addComponent(btn_select_file))
                .addGap(18, 18, 18)
                .addComponent(btn_submit)
                .addContainerGap())
        )

        self.txt_select_file.setText(self.dss_path)
        self.txt_start_time.setText(self.start_time)
        self.txt_end_time.setText(self.end_time)

        self.pack()
        self.setLocationRelativeTo(None)
class MenueFrame(object):
   def __init__(self):
      self.mainDir = ""
   
      self.frame = JFrame("Dots Quality Check", size=(250,300))
      self.frame.setLocation(20,120)
      self.Panel = JPanel(GridLayout(0,1))
      self.frame.add(self.Panel)

      self.openNextButton = JButton('Open Next Random',actionPerformed=openRandom)
      self.Panel.add(self.openNextButton)
      
      self.saveButton = JButton('Save',actionPerformed=save)
      self.saveButton.setEnabled(False)
      self.Panel.add(self.saveButton)

      self.cropButton = JButton('Crop values from here', actionPerformed=cropVals)
      self.Panel.add(self.cropButton)

      self.DiscardButton = JButton('Discard cell', actionPerformed=discardCell)
      self.DiscardButton.setEnabled(True)
      self.Panel.add(self.DiscardButton)

      self.quitButton = JButton('Quit script',actionPerformed=quit)
      self.Panel.add(self.quitButton)

      annoPanel = JPanel()
      #add gridlayout
      wtRButton = JRadioButton("wt", actionCommand="wt")
      defectRButton = JRadioButton("Defect", actionCommand="defect")
      annoPanel.add(wtRButton)
      annoPanel.add(defectRButton)
      self.aButtonGroup = ButtonGroup()
      self.aButtonGroup.add(wtRButton)
      self.aButtonGroup.add(defectRButton)
      
      self.Panel.add(annoPanel)

      self.ProgBar = JProgressBar()
      self.ProgBar.setStringPainted(True)
      self.ProgBar.setValue(0)
      self.Panel.add(self.ProgBar)

      self.pathLabel = JLabel("-- No main directory chosen --")
      self.pathLabel.setHorizontalAlignment( SwingConstants.CENTER )
      self.Panel.add(self.pathLabel)

      
      WindowManager.addWindow(self.frame)
      self.show()

   def show(self):
      self.frame.visible = True

   def getFrame(self):
      return self.frame

   def setSaveActive(self):
      self.saveButton.setEnabled(True)
      self.show()

   def setSaveInactive(self):
      self.saveButton.setEnabled(False)
      self.show()

   def setMainDir(self, path):
      self.mainDir = path
      self.pathLabel.setText("MainDir: " + os.path.basename(os.path.split(self.mainDir)[0]))

   def getMainDir(self):
      return self.mainDir

   def setProgBarMax(self, maximum):
      self.ProgBar.setMaximum(maximum)

   def setProgBarVal(self, value):
      self.ProgBar.setValue(value)

   def close():
      WindowManager.removeWindow(self.frame)
      self.frame.dispose()     
Ejemplo n.º 36
0
class BurpExtender(IBurpExtender, ITab):
    socket_time_out = 3

    def registerExtenderCallbacks(self, callbacks):
        self.out = callbacks.getStdout()

        self.callbacks = callbacks
        self.helpers = callbacks.getHelpers()
        callbacks.setExtensionName("WhatsApp Decoder")

        self.banner = JLabel("WHATSAPP DECRYPTION AND ENCRYPTION EXTENSION BY DIKLA BARDA, ROMAN ZAIKIN", SwingConstants.CENTER)
        self.banner.setFont(Font("Serif", Font.PLAIN, 17))
        self.banner.setBorder(BorderFactory.createLineBorder(Color.BLACK))

        self.statusConn = JLabel("CONNECTION STATUS:  ")
        self.statusConnField = JLabel("NOT CONNECTED")
        self.statusAct = JLabel("ACTION STATUS:      ")
        self.statusActField = JLabel("OK")

        self.ref = JLabel("Ref object:  ")
        self.refField = JTextField("123", 80)
        self.refField.setToolTipText("Copy the Ref from burpsuit WebSocket, make sure that the parameter 'secret' is there and you copy only the 'ref' without the connection and other data, if not logout from your whatsapp web and login again.")

        self.privateKey = JLabel("Private Key:")
        self.privateKeyField = JTextField("123", 80)
        self.privateKeyField.setToolTipText("Copy the private key list from your whatsapp web according to our blog post ")

        self.publicKey = JLabel("Public Key: ")
        self.publicKeyField = JTextField("123", 80)
        self.publicKeyField.setToolTipText("Copy the public key list from your whatsapp web according to our blog post")

        self.statusPanel1 = JPanel()
        self.statusPanel1.add(self.statusConn)
        self.statusPanel1.add(self.statusConnField)

        self.statusPanel2 = JPanel()
        self.statusPanel2.add(self.statusAct)
        self.statusPanel2.add(self.statusActField)

        self.privateKeyPanel = JPanel()
        self.privateKeyPanel.add(self.privateKey)
        self.privateKeyPanel.add(self.privateKeyField)

        self.publicKeyPanel = JPanel()
        self.publicKeyPanel.add(self.publicKey)
        self.publicKeyPanel.add(self.publicKeyField)

        self.refPanel = JPanel()
        self.refPanel.add(self.ref)
        self.refPanel.add(self.refField)

        self.messageField = JTextArea("", 5, 90)
        self.messageField.setLineWrap(True)
        self.messageField.setToolTipText("If you putting in the incoming traffic you can copy it from burp suit, the outgoing is the list from aesCbcEncrypt")

        self.whatsAppMessagesPanel = JPanel()
        self.whatsAppMessagesPanel.add(self.messageField)

        self.btnSave = JButton("Connect", actionPerformed=self.saveConfig)
        self.btnRestore = JButton("Clear", actionPerformed=self.clearConfig)

        self.grpConfig = JPanel()
        self.grpConfig.add(self.btnSave)
        self.grpConfig.add(self.btnRestore)

        self.btnIncoming = JButton("Incoming", actionPerformed=self.performAction)
        self.btnOutgoing = JButton("Outgoing", actionPerformed=self.performAction)

        self.btnEncrypt = JButton("Encrypt", actionPerformed=self.performAction)
        self.btnEncrypt.setEnabled(False)  # Can't send data without a direction

        self.btnDecrypt = JButton("Decrypt", actionPerformed=self.performAction)
        self.btnDecrypt.setEnabled(False)  # Can't send data without a direction

        self.btnCrypt = JPanel()
        self.btnCrypt.add(self.btnIncoming)
        self.btnCrypt.add(self.btnEncrypt)
        self.btnCrypt.add(self.btnDecrypt)
        self.btnCrypt.add(self.btnOutgoing)

        self.tab = JPanel()
        layout = GridBagLayout()
        self.tab.setLayout(layout)

        c = GridBagConstraints()

        c.ipadx = 0
        c.ipady = 0

        c.fill = GridBagConstraints.BOTH
        #c.weightx = 0 # gap between the x items
        #c.weighty = 0 # gap between the y items

        c.anchor = GridBagConstraints.NORTHWEST

        c.gridx = 0
        c.gridy = 0
        self.tab.add(self.banner, c)

        c.gridx = 0
        c.gridy = 1
        self.tab.add(self.refPanel, c)

        c.gridx = 0
        c.gridy = 2
        self.tab.add(self.privateKeyPanel, c)

        c.gridx = 0
        c.gridy = 3
        self.tab.add(self.publicKeyPanel, c)

        c.gridx = 0
        c.gridy = 4
        c.anchor = GridBagConstraints.CENTER
        self.tab.add(self.grpConfig, c)

        c.gridx = 0
        c.gridy = 5
        self.tab.add(self.whatsAppMessagesPanel, c)

        c.gridx = 0
        c.gridy = 6
        self.tab.add(self.btnCrypt, c)

        c.gridx = 0
        c.gridy = 7
        self.tab.add(self.statusPanel1, c)

        c.gridx = 0
        c.gridy = 8
        self.tab.add(self.statusPanel2, c)

        # restore config
        self.restoreConfig()
        callbacks.addSuiteTab(self)

    def performAction(self, e=None):

        self.client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.client.settimeout(self.socket_time_out)

        self.data = self.messageField.getText()

        eventSource = e.getSource()
        eventSource.setEnabled(False)

        # Incoming data
        if eventSource == self.btnIncoming:
            self.direction = "in"
            self.btnOutgoing.setEnabled(True)
            self.btnEncrypt.setEnabled(True)
            self.btnDecrypt.setEnabled(True)

        # Outgoing data
        elif eventSource == self.btnOutgoing:
            self.direction = "out"
            self.btnIncoming.setEnabled(True)
            self.btnEncrypt.setEnabled(True)
            self.btnDecrypt.setEnabled(True)

        # Send
        elif eventSource == self.btnDecrypt:
            self.btnDecrypt.setEnabled(True)
            clientData = json.dumps({"action": "decrypt",
                                     "data": {
                                            "direction": self.direction,
                                            "msg": self.messageField.getText()
                                        }
                                     })

            self.client.sendto(clientData, ("127.0.0.1",2912))
            try:
                serverData, addr = self.client.recvfrom(2048)
                serverData = json.loads(serverData)

                if serverData["status"] == 0:
                    print serverData
                    self.messageField.setText(json.dumps(serverData["data"]))
                    self.statusActField.setForeground(Color.GREEN)
                    self.statusActField.setText("OK")
                else:
                    self.statusActField.setForeground(Color.RED)
                    self.statusActField.setText("Error: {}".format(json.dumps(serverData["data"])))

            except socket.timeout:
                pass

        elif eventSource == self.btnEncrypt:
            self.btnEncrypt.setEnabled(True)
            clientData = json.dumps({"action": "encrypt",
                                     "data": {
                                         "direction": self.direction,
                                         "msg": self.messageField.getText()
                                     }
                                     })

            self.client.sendto(clientData, ("127.0.0.1", 2912))
            try:
                serverData, addr = self.client.recvfrom(2048)
                serverData = json.loads(serverData)
                if serverData["status"] == 0:
                    if isinstance(serverData["data"], list):
                        self.messageField.setText(json.dumps(serverData["data"]))
                    else:
                        self.messageField.setText(serverData["data"])

                    self.statusActField.setForeground(Color.GREEN)
                    self.statusActField.setText("OK")
                else:
                    self.statusActField.setForeground(Color.RED)
                    self.statusActField.setText("Error: {}".format(json.dumps(serverData["data"])))

            except socket.timeout:
                pass

        self.client.close()


    def saveConfig(self, e=None):
        self.client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.client.settimeout(self.socket_time_out)

        config = {
            'ref': self.refField.getText(),
            'private': self.privateKeyField.getText(),
            'public': self.publicKeyField.getText(),
        }

        self.callbacks.saveExtensionSetting("config", pickle.dumps(config))

        try:
            clientData = json.dumps({"action":"init",
                                     "data":{
                                         "ref":json.loads(self.refField.getText()),
                                         "private":self.privateKeyField.getText(),
                                         "public":self.publicKeyField.getText()
                                     }
                                    })

            self.client.sendto(clientData, ("127.0.0.1", 2912))

            serverData, addr = self.client.recvfrom(2048)
            print (serverData)

            self.statusConnField.setText("CONNECTED")
            self.statusActField.setForeground(Color.GREEN)
            self.statusActField.setText("OK")

        except socket.timeout:
            self.statusActField.setForeground(Color.RED)
            self.statusActField.setText("Error: Can't connect to the local server make sure parser.py is running!")
            pass

        except Exception as e:
            self.statusActField.setForeground(Color.RED)
            self.statusActField.setText("Error: make Sure the ref is a correct json!")

        self.client.close()

    def clearConfig(self, e=None):
        self.refField.setText("")
        self.privateKeyField.setText("")
        self.publicKeyField.setText("")
        self.statusConnField.setText("NOT CONNECTED")
        self.statusActField.setText("OK")
        self.messageField.setText("")

    def restoreConfig(self, e=None):
        storedConfig = self.callbacks.loadExtensionSetting("config")
        if storedConfig != None:
            config = pickle.loads(storedConfig)
            self.refField.setText(config["ref"])
            self.privateKeyField.setText(config["private"])
            self.publicKeyField.setText(config["public"])

    def getTabCaption(self):
        return ("WhatsApp Decoder")

    def getUiComponent(self):
        return self.tab
Ejemplo n.º 37
0
class EmployeeDetails(JPanel):
    def __init__(self, employees, dateprovider):
        JPanel.__init__(self, preferredSize=(400, 200))
        layout = BoxLayout(self, BoxLayout.Y_AXIS)
        self.setLayout(layout)
        self._employees = employees
        self._dateprovider = dateprovider
        employees.add_change_listener(self)
        self._create_status_label()
        self._create_name_editor()
        self._create_start_date_editor()
        self._create_save_button()
        self._create_vacation_display()
        self._adding_employee = False

    def _create_status_label(self):
        self._status_label = JLabel(name="status_label", font=Font(Font.SANS_SERIF, Font.PLAIN, 11))
        self.add(self._status_label)
        self._add_with_padding(self._status_label, 5)

    def _create_name_editor(self):
        self.add(JLabel(text="Employee Name:"))
        self._name_editor = FixedHeightTextField("name_input")
        self._add_with_padding(self._name_editor, 5)

    def _create_start_date_editor(self):
        self.add(JLabel(text="Start Date (yyyy-mm-dd):"))
        self._start_date_editor = FixedHeightTextField("start_input")
        self._add_with_padding(self._start_date_editor, 5)

    def _create_save_button(self):
        self._save_button = JButton("Save", name="save_button", visible=False)
        self._save_button.addActionListener(ListenerFactory(ActionListener, self._save_button_pushed))
        self._add_with_padding(self._save_button, 5)

    def _create_vacation_display(self):
        self._display = JTable(name="vacation_display")
        self._header = self._display.getTableHeader()
        self.add(self._header)
        self.add(self._display)

    def _add_with_padding(self, component, padding):
        self.add(component)
        self.add(Box.createRigidArea(Dimension(0, padding)))

    def show_employee(self, employee):
        self._name_editor.setText(employee.name)
        self._start_date_editor.setText(str(employee.startdate))
        self._name_editor.setEditable(False)
        self._start_date_editor.setEditable(False)
        self._save_button.setVisible(False)
        if self._adding_employee:
            self._adding_employee = False
        else:
            self._status_label.setText("")
        self._display.setVisible(True)
        self._display.setModel(VacationTableModel(employee, self._dateprovider))
        self._header.setVisible(True)

    def edit_new_employee(self):
        self._name_editor.setText("")
        self._start_date_editor.setText("")
        self._name_editor.setEditable(True)
        self._start_date_editor.setEditable(True)
        self._save_button.setVisible(True)
        self._display.setVisible(False)
        self._header.setVisible(False)
        self._adding_employee = True

    def _save_button_pushed(self, event):
        self._employees.add(self._name_editor.getText(), self._start_date_editor.getText())

    def employee_added(self, employee):
        self._status_label.setForeground(Color.BLACK)
        self._status_label.setText("Employee '%s' was added successfully." % employee.name)
        self._save_button.setVisible(False)

    def adding_employee_failed(self, reason):
        self._status_label.setForeground(Color.RED)
        self._status_label.setText(reason)
Ejemplo n.º 38
0
class AlbumArt(SongContextView):

    def __init__(self):
        # set up the layout
        self.__component = JPanel(GridBagLayout())
        self.__image = JLabel()
        self.__album = JLabel()
        self.__artist = JLabel()
        self.__application = None
        self.__image.setVerticalAlignment(SwingConstants.TOP)
        self.__album.setVerticalAlignment(SwingConstants.TOP)
        self.__artist.setVerticalAlignment(SwingConstants.TOP)
        gbc = GridBagConstraints()
        gbc.fill = GridBagConstraints.VERTICAL
        gbc.anchor = GridBagConstraints.NORTHWEST
        gbc.gridx = 0
        gbc.gridy = 0
        gbc.weighty = 2
        gbc.gridheight = 2
        self.__component.add(self.__image, gbc)
        gbc.fill = GridBagConstraints.HORIZONTAL
        gbc.anchor = GridBagConstraints.NORTHWEST
        gbc.gridx = 1
        gbc.gridy = 0
        gbc.gridheight = 1
        gbc.weighty = 0
        gbc.insets = Insets(0, 10, 0, 10)
        self.__component.add(self.__album, gbc)
        gbc.fill = GridBagConstraints.BOTH
        gbc.anchor = GridBagConstraints.NORTHWEST
        gbc.gridx = 1
        gbc.gridy = 1
        gbc.weightx = 2
        gbc.weighty = 2
        gbc.gridheight = 1
        self.__component.add(self.__artist, gbc)


    # Is called when this view should be updated.
    def update(self, song):
        # check for None!
        if (song != None):
            albumArt = song.getImage()
            if (albumArt != None):
                self.__image.setIcon(ImageIcon(ImageScaler.scale(albumArt, 300, 300)));
            else:
                self.__image.setIcon(None);

            self.__album.setText("<html><font size='+3'>" + song.getAlbum() + "</font></html>");
            self.__artist.setText("<html><font color='#555555' size='-1'>by " + song.getArtist() + "</font></html>");
        else:
            self.__image.setIcon(None);
            self.__album.setText(None);
            self.__artist.setText(None);



    # Every SongContextView needs to be accompanied by a
    # SongContextComponentShowHideAction.
    # Return the action's id here.
    def getShowHideActionId(self):
        return "jython.albumart.showhide"


    # The visual component to be shown in this view.
    def getComponent(self):
        return self.__component


    def setApplication(self, application):
        self.__application = application


    def getApplication(self):
        return self.__application


    def getId(self):
        return "jython.albumart"


    def init(self):
        pass

    def shutdown(self):
        pass