コード例 #1
0
ファイル: about.py プロジェクト: HenryStevens/jes
    def __init__(self):
        super(AboutDialog, self).__init__()

        # Open the files and build a tab pane
        self.tabbedPane = tabs = JTabbedPane()

        for title, path in self.INFO_FILES:
            textPane = JTextPane()
            textPane.editable = False
            scrollPane = JScrollPane(textPane)
            scrollPane.preferredSize = (32767, 32767)   # just a large number

            with open(path, 'r') as fd:
                infoText = fd.read().decode('utf8')
                textPane.text = infoText

            textPane.caretPosition = 0
            tabs.addTab(title, scrollPane)

        # Load this tabbed pane into the layout
        self.add(tabs, BorderLayout.CENTER)

        # Add a label at the top
        versionLabel = JLabel(JESVersion.TITLE + " version " + JESVersion.RELEASE)
        versionLabel.alignmentX = Component.CENTER_ALIGNMENT

        versionPanel = JPanel()
        versionPanel.add(versionLabel)
        self.add(versionPanel, BorderLayout.PAGE_START)

        # Make an OK button
        self.okButton = JButton(self.ok)
        self.buttonPanel.add(self.okButton)
class ReportByPointPanelReport(FormPanel):
    def __init__(self):
        FormPanel.__init__(
            self, gvsig.getResource(__file__, "reportbypointpanelreport.xml"))
        i18Swing = ToolsSwingLocator.getToolsSwingManager()
        self.setPreferredSize(400, 300)
        self.txt = JTextPane()
        self.txt.setEditable(False)
        self.txt.setCaretPosition(0)
        i18Swing.setDefaultPopupMenu(self.txt)
        self.txt.setContentType("text/html")
        self.pane = JScrollPane(self.txt)
        #self.setInitHorizontalScroll()
        self.pane.setVerticalScrollBarPolicy(
            ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS)
        #self.setInitHorizontalScroll()
        #self.pane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS)
        #self.setInitHorizontalScroll()
        self.jplReport.setLayout(BorderLayout())
        self.jplReport.add(self.pane, BorderLayout.CENTER)
        self.setInitHorizontalScroll()

    def setHTMLText(self, text):
        self.txt.setText(text)
        self.setInitHorizontalScroll()
        self.txt.setCaretPosition(0)

    def setInitHorizontalScroll(self):
        self.pane.getHorizontalScrollBar().setValue(0)
コード例 #3
0
    def __init__(self, burp, namespace=None):
        self.burp = burp
        self.log = burp.log
        self._locals = dict(Burp=burp)
        self._buffer = []
        self.history = History(self)

        if namespace is not None:
            self._locals.update(namespace)

        self.interp = JythonInterpreter(self, self._locals)

        self.textpane = JTextPane(keyTyped=self.keyTyped,
                                  keyPressed=self.keyPressed)

        self.textpane.setFont(Font('Monospaced', Font.PLAIN, 11))
        self.burp.customizeUiComponent(self.textpane)

        self.initKeyMap()

        self.document.remove(0, self.document.getLength())
        self.write('Burp Extender Jython Shell', prefix='')
        self.write(self.PS1)

        self.textpane.requestFocus()
        burp.log.info('Interactive interpreter ready...')
コード例 #4
0
    def registerExtenderCallbacks(self, callbacks):
        self.callbacks = callbacks
        self.helpers = callbacks.helpers

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

        self.scrollpane = JScrollPane()
        self.scrollpane.setViewportView(self.scriptpane)

        self._code = compile('', '<string>', 'exec')
        self._script = ''

        script = callbacks.loadExtensionSetting('script')

        if script:
            script = base64.b64decode(script)

            self.scriptpane.document.insertString(
                self.scriptpane.document.length, script, SimpleAttributeSet())

            self._script = script
            try:
                self._code = compile(script, '<string>', 'exec')
            except Exception as e:
                traceback.print_exc(file=self.callbacks.getStderr())

        callbacks.registerExtensionStateListener(self)
        callbacks.registerHttpListener(self)
        callbacks.customizeUiComponent(self.getUiComponent())
        callbacks.addSuiteTab(self)

        self.scriptpane.requestFocus()
コード例 #5
0
ファイル: console.py プロジェクト: omsai/quickpalm.future
    def __init__(self, frame, namespace=None):
        """
            Create a Jython Console.
            namespace is an optional and should be a dictionary or Map
        """
        self.frame = frame
        self.history = History(self)

        if namespace != None:
            self.locals = namespace
        else:
            self.locals = {}

        self.buffer = [] # buffer for multi-line commands                    

        self.interp = Interpreter(self, self.locals)
        sys.stdout = StdOutRedirector(self)

        self.text_pane = JTextPane(keyTyped = self.keyTyped, keyPressed = self.keyPressed)
        self.__initKeyMap()

        self.doc = self.text_pane.document
        self.__propertiesChanged()
        self.__inittext()
        self.initialLocation = self.doc.createPosition(self.doc.length-1)

        # Don't pass frame to popups. JWindows with null owners are not focusable
        # this fixes the focus problem on Win32, but make the mouse problem worse
        self.popup = Popup(None, self.text_pane)
        self.tip = Tip(None)

        # get fontmetrics info so we can position the popup
        metrics = self.text_pane.getFontMetrics(self.text_pane.getFont())
        self.dotWidth = metrics.charWidth('.')
        self.textHeight = metrics.getHeight()
コード例 #6
0
    def __init__(self, extender, namespace=None):
        self.extender = extender
        self.callbacks = extender.callbacks
        self.helpers = extender.helpers

        self._locals = dict(Burp=extender, items=[])
        self._buffer = []
        self.history = History(self)

        if namespace is not None:
            self._locals.update(namespace)

        self.interp = JythonInterpreter(self, self._locals)

        self.textpane = JTextPane(keyTyped=self.keyTyped,
                                  keyPressed=self.keyPressed)

        self.textpane.setFont(Font('Monospaced', Font.PLAIN, 11))
        self.callbacks.customizeUiComponent(self.textpane)

        self.initKeyMap()

        self.document.remove(0, self.document.getLength())
        self.write('Burp Extender Jython Shell', prefix='')
        self.write(self.PS1)

        self.textpane.requestFocus()
        self.callbacks.getStdout().write('Interactive interpreter ready...\n')
コード例 #7
0
ファイル: ProxyScripter.py プロジェクト: Izib/ProxyScripter
class BurpExtender(IBurpExtender, IExtensionStateListener, IHttpListener, IProxyListener, ITab):
    def registerExtenderCallbacks(self, callbacks):
        self.callbacks = callbacks
        self.helpers = callbacks.helpers

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

        self.scrollpane = JScrollPane()
        self.scrollpane.setViewportView(self.scriptpane)

        self._code = compile('', '<string>', 'exec')
        self._script = ''

        callbacks.registerExtensionStateListener(self)        
        callbacks.registerProxyListener(self)
        callbacks.customizeUiComponent(self.getUiComponent())
        callbacks.addSuiteTab(self)

        self.scriptpane.requestFocus()

    def extensionUnloaded(self):
        try:
            self.callbacks.saveExtensionSetting(
                'script', base64.b64encode(self._script))
        except Exception:
            traceback.print_exc(file=self.callbacks.getStderr())
        return

    def processProxyMessage(self, messageIsRequest, message):
        try:
            globals_ = {'extender': self,
                        'callbacks': self.callbacks,
                        'helpers': self.helpers
            }
            locals_  = {'messageIsRequest': messageIsRequest,
                        'message': message
            }
            exec(self.script, globals_, locals_)
        except Exception:
            traceback.print_exc(file=self.callbacks.getStderr())
        return
        
    def getTabCaption(self):
        return 'Script'

    def getUiComponent(self):
        return self.scrollpane

    @property
    def script(self):
        end = self.scriptpane.document.length
        _script = self.scriptpane.document.getText(0, end)

        if _script == self._script:
            return self._code

        self._script = _script
        self._code = compile(_script, '<string>', 'exec')
        return self._code
コード例 #8
0
ファイル: about.py プロジェクト: JoeLeclercq/jesWork
    def __init__(self):
        super(AboutDialog, self).__init__()

        # Open the files and build a tab pane
        self.tabbedPane = tabs = JTabbedPane()

        for title, path in self.INFO_FILES:
            textPane = JTextPane()
            textPane.editable = False
            scrollPane = JScrollPane(textPane)
            scrollPane.preferredSize = (32767, 32767)  # just a large number

            with open(path, 'r') as fd:
                infoText = fd.read().decode('utf8')
                textPane.text = infoText

            textPane.caretPosition = 0
            tabs.addTab(title, scrollPane)

        # Load this tabbed pane into the layout
        self.add(tabs, BorderLayout.CENTER)

        # Add a label at the top
        versionLabel = JLabel(JESVersion.TITLE + " version " +
                              JESVersion.RELEASE)
        versionLabel.alignmentX = Component.CENTER_ALIGNMENT

        versionPanel = JPanel()
        versionPanel.add(versionLabel)
        self.add(versionPanel, BorderLayout.PAGE_START)

        # Make an OK button
        self.okButton = JButton(self.ok)
        self.buttonPanel.add(self.okButton)
コード例 #9
0
ファイル: pane.py プロジェクト: HenryStevens/jes
 def updateUI(self):
     # Update the default font, if necessary,
     # when the look and feel changes.
     JTextPane.updateUI(self)
     doc = self.getStyledDocument()
     if hasattr(doc, 'setTheme'):
         # Sometimes, we don't have a CommandWindowDocument here.
         doc.setTheme(doc.themeName)
コード例 #10
0
ファイル: pane.py プロジェクト: JoeLeclercq/jesWork
 def updateUI(self):
     # Update the default font, if necessary,
     # when the look and feel changes.
     JTextPane.updateUI(self)
     doc = self.getStyledDocument()
     if hasattr(doc, 'setTheme'):
         # Sometimes, we don't have a CommandWindowDocument here.
         doc.setTheme(doc.themeName)
コード例 #11
0
ファイル: gui.py プロジェクト: Serabe/geogebra
class LineNumbering(DocumentListener):
    """Pane containing line numbers.
    
    Listens to changes in a textpane to update itself automatically.
    """
    
    def __init__(self, textpane):
        self.component = JTextPane(
            font=textpane.font,
            border=BorderFactory.createEmptyBorder(5, 5, 5, 5),
            editable=False,
            background=awtColor(220, 220, 220),
        )
        self.doc = self.component.document
        self.component.setParagraphAttributes(
            textpane.paragraphAttributes, True
        )
        self.linecount = 0
        self.style = new_style(self.doc, "default",
            foreground=awtColor(100, 100, 100),
        )
        self.reset(1)
        textpane.document.addDocumentListener(self)
    
    def reset(self, lc):
        self.linecount = lc
        self.doc.remove(0, self.doc.length)
        self.doc.insertString(0, make_line_numbers(1, lc), self.style)
    
    def resize(self, lc):
        if not lc:
            self.reset(1)
        elif len(str(lc)) != len(str(self.linecount)):
            self.reset(lc)
        elif lc > self.linecount:
            self.doc.insertString(self.doc.length, "\n", self.style)
            self.doc.insertString(self.doc.length,
                make_line_numbers(self.linecount + 1, lc),
                self.style
            )
            self.linecount = lc
        elif lc < self.linecount:
            root = self.doc.defaultRootElement
            offset = root.getElement(lc).startOffset - 1
            self.doc.remove(offset, self.doc.length - offset)
            self.linecount = lc
    
    # Implementation of DocumentListener
    def changedUpdate(self, evt):
        pass
    
    def insertUpdate(self, evt):
        self.resize(document_linecount(evt.document))
    
    def removeUpdate(self, evt):
        self.resize(document_linecount(evt.document))
コード例 #12
0
    def registerExtenderCallbacks(self, callbacks):
        self.callbacks = callbacks
        self.helpers = callbacks.helpers

        callbacks.setExtensionName("Burp Scripter Plus")

        stdout = PrintWriter(callbacks.getStdout(), True)
        stdout.println(
            """Successfully loaded Burp Scripter Plus v"""
            + VERSION
            + """\n
Repository @ https://github.com/Acceis/BurpScripterPlus
Send feedback or bug reports on twitter @G4N4P4T1"""
        )

        self.scriptpane = JTextPane()
        self.scriptpane.setFont(
            Font("Monospaced", Font.PLAIN, 12)
        )

        self.scrollpane = JScrollPane()
        self.scrollpane.setViewportView(self.scriptpane)

        self._code = compile("", "<string>", "exec")
        self._script = ""

        script = callbacks.loadExtensionSetting("script")

        if script:
            script = base64.b64decode(script)

            self.scriptpane.document.insertString(
                self.scriptpane.document.length,
                script,
                SimpleAttributeSet(),
            )

            self._script = script
            try:
                self._code = compile(
                    script, "<string>", "exec"
                )
            except Exception as e:
                traceback.print_exc(
                    file=self.callbacks.getStderr()
                )

        callbacks.registerExtensionStateListener(self)
        callbacks.registerHttpListener(self)
        callbacks.customizeUiComponent(
            self.getUiComponent()
        )
        callbacks.addSuiteTab(self)

        self.scriptpane.requestFocus()
コード例 #13
0
ファイル: pyggb.py プロジェクト: tomasp8/geogebra
 def __init__(self):
     self.textpane = JTextPane()
     self.doc = self.textpane.getStyledDocument()
     self.textpane.editable = False
     default_style = StyleContext.getDefaultStyleContext().getStyle(StyleContext.DEFAULT_STYLE)
     parent_style = self.doc.addStyle("parent", default_style)
     StyleConstants.setFontFamily(parent_style, "Monospaced")
     input_style = self.doc.addStyle("input", parent_style)
     output_style = self.doc.addStyle("output", parent_style)
     StyleConstants.setForeground(output_style, Color.BLUE)
     error_style = self.doc.addStyle("error", parent_style)
     StyleConstants.setForeground(error_style, Color.RED)
コード例 #14
0
    def registerExtenderCallbacks(self, callbacks):
        self.callbacks = callbacks
        self.helpers = callbacks.helpers

        self.checkboxEnable = JCheckBox('Enabled')
        self.checkboxEnable.setSelected(False)
        self.checkboxEnable.setEnabled(True)

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

        self.scrollpane = JScrollPane()
        self.scrollpane.setViewportView(self.scriptpane)

        self.tab = JPanel()
        layout = GroupLayout(self.tab)
        self.tab.setLayout(layout)
        layout.setAutoCreateGaps(True)
        layout.setAutoCreateContainerGaps(True)

        layout.setHorizontalGroup(layout.createParallelGroup().addComponent(
            self.checkboxEnable).addComponent(self.scrollpane))
        layout.setVerticalGroup(layout.createSequentialGroup().addComponent(
            self.checkboxEnable).addComponent(self.scrollpane))

        self._code = compile('', '<string>', 'exec')
        self._script = ''

        script = callbacks.loadExtensionSetting('script')

        if script:
            script = base64.b64decode(script)

            self.scriptpane.document.insertString(
                self.scriptpane.document.length, script, SimpleAttributeSet())

            self._script = script
            try:
                self._code = compile(script, '<string>', 'exec')
            except Exception as e:
                traceback.print_exc(file=self.callbacks.getStderr())

        callbacks.setExtensionName("Python Scripter (modified)")
        callbacks.registerSessionHandlingAction(self)
        callbacks.registerExtensionStateListener(self)
        callbacks.registerHttpListener(self)
        callbacks.customizeUiComponent(self.getUiComponent())
        callbacks.addSuiteTab(self)

        self.scriptpane.requestFocus()
        return
コード例 #15
0
    def init(self):
        global exampleList
        self.thinFont = Font("Dialog", 0, 10)

        self.pane = self.getContentPane()
        self.examples = exampleList.keys()
        self.examples.sort()
        self.exampleSelector = JList(self.examples, valueChanged=self.valueChanged)
        self.exampleSelector.setSelectionMode(ListSelectionModel.SINGLE_SELECTION)
        self.exampleSelector.setLayoutOrientation(JList.VERTICAL)
        self.exampleSelector.setPreferredSize(Dimension(150,500))
        self.exampleSelector.setBackground(Color(0.95, 0.95, 0.98))
        self.exampleSelector.setFont(self.thinFont)

        self.centerPanel = JPanel(BorderLayout())
        self.canvas = GraphCanvas()
        self.canvas.setApplet(self)
        self.buttonRow = JPanel(FlowLayout())
        self.backButton = JButton("<", actionPerformed = self.backAction)
        self.backButton.setFont(self.thinFont)
        self.continueButton = JButton("continue >",
                                      actionPerformed=self.continueAction)
        self.continueButton.setFont(self.thinFont)
        self.scaleGroup = ButtonGroup()
        self.linearButton = JRadioButton("linear scale",
                                         actionPerformed=self.linearAction)
        self.linearButton.setSelected(True)
        self.linearButton.setFont(self.thinFont)
        self.logarithmicButton = JRadioButton("logarithmic scale",
                                      actionPerformed=self.logarithmicAction)
        self.logarithmicButton.setFont(self.thinFont)
        self.aboutButton = JButton("About...",
                                   actionPerformed=self.aboutAction)
        self.aboutButton.setFont(self.thinFont)
        self.scaleGroup.add(self.linearButton)
        self.scaleGroup.add(self.logarithmicButton)
        self.buttonRow.add(self.backButton)
        self.buttonRow.add(self.continueButton)
        self.buttonRow.add(JLabel(" "*5))
        self.buttonRow.add(self.linearButton)
        self.buttonRow.add(self.logarithmicButton)
        self.buttonRow.add(JLabel(" "*20));
        self.buttonRow.add(self.aboutButton)
        self.centerPanel.add(self.canvas, BorderLayout.CENTER)
        self.centerPanel.add(self.buttonRow, BorderLayout.PAGE_END)

        self.helpText = JTextPane()
        self.helpText.setBackground(Color(1.0, 1.0, 0.5))
        self.helpText.setPreferredSize(Dimension(800,80))
        self.helpText.setText(re_sub("[ \\n]+", " ", """
        Please select one of the examples in the list on the left!
        """))
        self.pane.add(self.exampleSelector, BorderLayout.LINE_START)
        self.pane.add(self.centerPanel, BorderLayout.CENTER)
        self.pane.add(self.helpText, BorderLayout.PAGE_END)
        self.graph = None
        self.simulation = None
        self.touched = ""
        self.selected = ""
        self.gfxDriver = None
コード例 #16
0
    def __init__(self, extender, namespace=None):
        self.extender = extender
        self.callbacks = extender.callbacks
        self.helpers = extender.helpers

        self._locals = dict(Burp=extender, items=[])
        self._buffer = []
        self.history = History(self)

        if namespace is not None:
            self._locals.update(namespace)

        self.interp = JythonInterpreter(self, self._locals)

        self.textpane = JTextPane(keyTyped=self.keyTyped,
                                  keyPressed=self.keyPressed)

        self.textpane.setFont(Font('Monospaced', Font.PLAIN, 11))
        self.callbacks.customizeUiComponent(self.textpane)

        self.initKeyMap()

        self.document.remove(0, self.document.getLength())
        self.write('Burp Extender Jython Shell', prefix='')
        self.write(self.PS1)

        self.textpane.requestFocus()
        self.callbacks.getStdout().write('Interactive interpreter ready...\n')
コード例 #17
0
ファイル: browser.py プロジェクト: pdfernhout/openvirgle
    def makeComponents(self):
        # text specific operations
        self.randomUUIDButton = JButton("Generate random UUID", actionPerformed=self.randomUUIDPressed)
        self.clearButton = JButton("Clear", actionPerformed=self.clearPressed)
        self.runButton = JButton("Run as Jython", actionPerformed=self.runPressed)
        self.revertButton = JButton("Revert", actionPerformed=self.revertPressed)

        self.buttonPanel = Box(BoxLayout.X_AXIS) 
        self.buttonPanel.add(Box.createRigidArea(Dimension(5,0)))
        self.buttonPanel.add(self.randomUUIDButton)
        self.buttonPanel.add(Box.createRigidArea(Dimension(5,0)))
        self.buttonPanel.add(self.clearButton)
        self.buttonPanel.add(Box.createRigidArea(Dimension(5,0)))
        self.buttonPanel.add(self.runButton)
        self.buttonPanel.add(Box.createRigidArea(Dimension(5,0)))
        self.buttonPanel.add(self.revertButton)
        self.buttonPanel.add(Box.createRigidArea(Dimension(5,0)))
 
        self.textEditor = JTextPane()
        self.textEditor.setFont(Font("monospaced", Font.PLAIN, 12))
        #self.textEditor.setTabSize(4) # still inserts tabs instead of spaces
        TabKeyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0, False)
        MyTabActionKey = Object()
        self.textEditor.getInputMap().put(TabKeyStroke, MyTabActionKey)
        actionMap = self.textEditor.getActionMap()
        actionMap.put(MyTabActionKey, AddFourSpacesAction())
        
        self.layout = BorderLayout()
        self.add(self.buttonPanel, BorderLayout.NORTH)
        self.add(JScrollPane(self.textEditor), BorderLayout.CENTER)
コード例 #18
0
ファイル: gui.py プロジェクト: Serabe/geogebra
 def __init__(self):
     self.textpane = JTextPane()
     self.doc = self.textpane.getStyledDocument()
     self.textpane.editable = False
     style_context = StyleContext.getDefaultStyleContext()
     default_style = style_context.getStyle(StyleContext.DEFAULT_STYLE)
     parent_style = self.doc.addStyle("parent", default_style)
     StyleConstants.setFontFamily(parent_style, "Monospaced")
     input_style = self.doc.addStyle("input", parent_style)
     output_style = self.doc.addStyle("output", parent_style)
     StyleConstants.setForeground(output_style, awtColor.BLUE)
     error_style = self.doc.addStyle("error", parent_style)
     StyleConstants.setForeground(error_style, awtColor.RED)
     
     # Do a dance to set tab size
     font = Font("Monospaced", Font.PLAIN, 12)
     self.textpane.setFont(font)
     fm = self.textpane.getFontMetrics(font)
     tabw = float(fm.stringWidth(" "*4))
     tabs = [
         TabStop(tabw*i, TabStop.ALIGN_LEFT, TabStop.LEAD_NONE)
         for i in xrange(1, 51)
     ]
     attr_set = style_context.addAttribute(
         SimpleAttributeSet.EMPTY,
         StyleConstants.TabSet,
         TabSet(tabs)
     )
     self.textpane.setParagraphAttributes(attr_set, False)
コード例 #19
0
    def initUI(self):
        self.manImage = ImageIcon('bin/gui/media/' + "danglewood.gif")
        self.manImageSilent = ImageIcon('bin/gui/media/' +
                                        "danglewood-silent.png")
        self.manLabel = JLabel(self.manImage)

        self.dialogText = JTextPane()
        self.dialogText.setEditable(False)
        self.dialogTextScroller = JScrollPane(self.dialogText)

        self.dialogText.setBackground(Color(0, 24, 0))
        self.dialogText.setForeground(Color.WHITE)
        self.dialogText.setFont(Font("Arial", Font.BOLD, 15))

        self.buttonsPanel = ButtonPanel(self.consolePanel, self)

        self.dialogText.setText("Welcome to BashED!!!")
コード例 #20
0
ファイル: console.py プロジェクト: omusico/siga
    def __init__(self, frame):

        self.frame = frame  # TODO do I need a reference to frame after the constructor?
        self.history = History(self)
        self.bs = 0  # what is this?

        # command buffer
        self.buffer = []
        self.locals = {"gvSIG": sys.gvSIG}

        self.interp = Interpreter(self, self.locals)
        sys.stdout = StdOutRedirector(self)

        # create a textpane
        self.output = JTextPane(keyTyped=self.keyTyped, keyPressed=self.keyPressed)
        # TODO rename output to textpane

        # CTRL UP AND DOWN don't work
        keyBindings = [
            (KeyEvent.VK_ENTER, 0, "jython.enter", self.enter),
            (KeyEvent.VK_DELETE, 0, "jython.delete", self.delete),
            (KeyEvent.VK_HOME, 0, "jython.home", self.home),
            (KeyEvent.VK_UP, 0, "jython.up", self.history.historyUp),
            (KeyEvent.VK_DOWN, 0, "jython.down", self.history.historyDown),
            (KeyEvent.VK_PERIOD, 0, "jython.showPopup", self.showPopup),
            (KeyEvent.VK_ESCAPE, 0, "jython.hide", self.hide),
            ("(", 0, "jython.showTip", self.showTip),
            (")", 0, "jython.hideTip", self.hideTip),
            # (KeyEvent.VK_UP, InputEvent.CTRL_MASK, DefaultEditorKit.upAction, self.output.keymap.getAction(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0))),
            # (KeyEvent.VK_DOWN, InputEvent.CTRL_MASK, DefaultEditorKit.downAction, self.output.keymap.getAction(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0)))
        ]
        # TODO rename newmap to keymap
        newmap = JTextComponent.addKeymap("jython", self.output.keymap)
        for (key, modifier, name, function) in keyBindings:
            newmap.addActionForKeyStroke(KeyStroke.getKeyStroke(key, modifier), ActionDelegator(name, function))

        self.output.keymap = newmap

        self.doc = self.output.document
        # self.panel.add(BorderLayout.CENTER, JScrollPane(self.output))
        self.__propertiesChanged()
        self.__inittext()
        self.initialLocation = self.doc.createPosition(self.doc.length - 1)

        # Don't pass frame to popups. JWindows with null owners are not focusable
        # this fixes the focus problem on Win32, but make the mouse problem worse
        self.popup = Popup(None, self.output)
        self.tip = Tip(None)

        # get fontmetrics info so we can position the popup
        metrics = self.output.getFontMetrics(self.output.getFont())
        self.dotWidth = metrics.charWidth(".")
        self.textHeight = metrics.getHeight()

        # add some handles to our objects
        self.locals["console"] = self

        self.caret = self.output.getCaret()
コード例 #21
0
    def registerExtenderCallbacks(self, callbacks):
        self.callbacks = callbacks
        self.helpers = callbacks.helpers

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

        self.scrollpane = JScrollPane()
        self.scrollpane.setViewportView(self.scriptpane)

        self._code = compile('', '<string>', 'exec')
        self._script = ''

        callbacks.registerExtensionStateListener(self)
        callbacks.registerProxyListener(self)
        callbacks.customizeUiComponent(self.getUiComponent())
        callbacks.addSuiteTab(self)

        self.scriptpane.requestFocus()
コード例 #22
0
ファイル: pyggb.py プロジェクト: tomasp8/geogebra
class OutputPane(object):
    def __init__(self):
        self.textpane = JTextPane()
        self.doc = self.textpane.getStyledDocument()
        self.textpane.editable = False
        default_style = StyleContext.getDefaultStyleContext().getStyle(StyleContext.DEFAULT_STYLE)
        parent_style = self.doc.addStyle("parent", default_style)
        StyleConstants.setFontFamily(parent_style, "Monospaced")
        input_style = self.doc.addStyle("input", parent_style)
        output_style = self.doc.addStyle("output", parent_style)
        StyleConstants.setForeground(output_style, Color.BLUE)
        error_style = self.doc.addStyle("error", parent_style)
        StyleConstants.setForeground(error_style, Color.RED)
    def addtext(self, text, style="input", ensure_newline=False):
        doclen = self.doc.length
        if ensure_newline and self.doc.getText(doclen - 1, 1) != '\n':
            text = '\n' + text
        self.doc.insertString(self.doc.length, text, self.doc.getStyle(style))
        # Scroll down
        self.textpane.setCaretPosition(self.doc.length)
コード例 #23
0
ファイル: intro.py プロジェクト: zackfuqua/jes
    def __init__(self):
        super(IntroDialog, self).__init__()

        # Open the text file and make a text pane
        textPane = JTextPane()
        textPane.editable = False

        scrollPane = JScrollPane(textPane)
        scrollPane.preferredSize = (32767, 32767)   # just a large number

        with open(self.INFO_FILE, 'r') as fd:
            infoText = fd.read().decode('utf8').replace(
                "@version@", JESVersion.VERSION
            )
            textPane.text = infoText

        # Load the scroll pane into the layout
        self.add(scrollPane, BorderLayout.CENTER)

        # Make an OK button
        self.okButton = JButton(self.ok)
        self.buttonPanel.add(self.okButton)
コード例 #24
0
ファイル: bugreport.py プロジェクト: HenryStevens/jes
    def __init__(self):
        super(BugReportDialog, self).__init__()

        # Add a message
        textPane = JTextPane()
        textPane.editable = False

        version = "\n".join("    " + line for line in JESVersion.getMessage().splitlines())
        textPane.text = MESSAGE % version

        scrollPane = JScrollPane(textPane)
        scrollPane.preferredSize = (32767, 32767)   # just a large number

        # Load it into the layout
        self.add(scrollPane, BorderLayout.CENTER)

        # Make buttons
        self.sendButton = JButton(self.send)
        self.buttonPanel.add(self.sendButton)

        self.closeButton = JButton(self.close)
        self.buttonPanel.add(self.closeButton)
コード例 #25
0
    def getUiComponent(self):
        """Burp uses this method to obtain the component that should be used as
        the contents of the custom tab when it is displayed.
        Returns a awt.Component.
        """
        # GUI happens here
        from javax.swing import (JPanel, JSplitPane, JList, JTextPane,
                                 JScrollPane, ListSelectionModel, JLabel,
                                 JTabbedPane, JEditorPane)
        from java.awt import BorderLayout
        panel = JPanel(BorderLayout())

        # create a list and then JList out of it.
        colors = [
            "red", "orange", "yellow", "green", "cyan", "blue", "pink",
            "magenta", "gray", "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz"
        ]

        def listSelect(event):
            """Add the selected index to the label. Called twice when
            selecting the list item by mouse. So we need to use
            getValueIsAdjusting inside.
            """
            if not event.getValueIsAdjusting():
                doc1.insertString(0, colors[list1.selectedIndex] + "-", None)

        # create a list and assign the valueChanged
        list1 = JList(colors, valueChanged=listSelect)
        list1.selectionMode = ListSelectionModel.SINGLE_SELECTION

        # create a StyledDocument.
        from javax.swing.text import DefaultStyledDocument
        doc1 = DefaultStyledDocument()
        # create a JTextPane from doc1
        tab1 = JTextPane(doc1)

        # create a JEditorPane for tab 2
        tab2 = JEditorPane("https://example.net")
        tab2.editable = False

        # create the tabbedpane
        tabs = JTabbedPane()

        tabs.addTab("Tab 1", tab1)
        tabs.addTab("Tab 2", tab2)

        # create splitpane - horizontal split
        spl = JSplitPane(JSplitPane.HORIZONTAL_SPLIT, JScrollPane(list1), tabs)

        panel.add(spl)
        return panel
コード例 #26
0
ファイル: bugreport.py プロジェクト: JoeLeclercq/jesWork
    def __init__(self):
        super(BugReportDialog, self).__init__()

        # Add a message
        textPane = JTextPane()
        textPane.editable = False

        version = "\n".join("    " + line
                            for line in JESVersion.getMessage().splitlines())
        textPane.text = MESSAGE % version

        scrollPane = JScrollPane(textPane)
        scrollPane.preferredSize = (32767, 32767)  # just a large number

        # Load it into the layout
        self.add(scrollPane, BorderLayout.CENTER)

        # Make buttons
        self.sendButton = JButton(self.send)
        self.buttonPanel.add(self.sendButton)

        self.closeButton = JButton(self.close)
        self.buttonPanel.add(self.closeButton)
コード例 #27
0
    def registerExtenderCallbacks(self, callbacks):

        callbacks.registerExtensionStateListener(self)
        # keep a reference to our callbacks object
        self._callbacks = callbacks
        # obtain an extension helpers object
        self._helpers = callbacks.getHelpers()
        # set our extension name
        callbacks.setExtensionName("Super Payload")
        # register ourselves as a payload generator factory
        callbacks.registerIntruderPayloadGeneratorFactory(self)

        # the Super Payload UI
        self.scriptpane = JTextPane()
        self.scriptpane.setFont(Font('Monospaced', Font.PLAIN, 11))
        self.scrollpane = JScrollPane()
        self.scrollpane.setViewportView(self.scriptpane)
        callbacks.customizeUiComponent(self.getUiComponent())
        callbacks.addSuiteTab(self)
        self.scriptpane.requestFocus()

        # Compile the init script content
        self._code = compile('', '<string>', 'exec')
        self._script = ''

        script = callbacks.loadExtensionSetting('script')

        if script:
            script = base64.b64decode(script)

            self.scriptpane.document.insertString(
                self.scriptpane.document.length, script, SimpleAttributeSet())

            self._script = script
            self._code = compile(script, '<string>', 'exec')

        return
コード例 #28
0
ファイル: gui.py プロジェクト: aeriksson/geogebra
class OutputPane(object):
    
    """Pane for outpout of interactive session"""
    
    def __init__(self):
        self.textpane = JTextPane()
        self.doc = self.textpane.getStyledDocument()
        self.textpane.editable = False
        style_context = StyleContext.getDefaultStyleContext()
        default_style = style_context.getStyle(StyleContext.DEFAULT_STYLE)
        parent_style = self.doc.addStyle("parent", default_style)
        StyleConstants.setFontFamily(parent_style, "Monospaced")
        input_style = self.doc.addStyle("input", parent_style)
        output_style = self.doc.addStyle("output", parent_style)
        StyleConstants.setForeground(output_style, awtColor.BLUE)
        error_style = self.doc.addStyle("error", parent_style)
        StyleConstants.setForeground(error_style, awtColor.RED)
        
        # Do a dance to set tab size
        font = Font("Monospaced", Font.PLAIN, 12)
        self.textpane.setFont(font)
        fm = self.textpane.getFontMetrics(font)
        tabw = float(fm.stringWidth(" "*4))
        tabs = [
            TabStop(tabw*i, TabStop.ALIGN_LEFT, TabStop.LEAD_NONE)
            for i in xrange(1, 51)
        ]
        attr_set = style_context.addAttribute(
            SimpleAttributeSet.EMPTY,
            StyleConstants.TabSet,
            TabSet(tabs)
        )
        self.textpane.setParagraphAttributes(attr_set, False)
        #Dance done!
        
    def addtext(self, text, style="input", ensure_newline=False):
        doclen = self.doc.length
        if ensure_newline and doclen:
            if self.doc.getText(doclen - 1, 1) != '\n':
                text = '\n' + text
        self.doc.insertString(self.doc.length, text, self.doc.getStyle(style))
        # Scroll down
        self.textpane.setCaretPosition(self.doc.length)

    def clear(self):
        """Remove all text"""
        self.doc.remove(0, self.doc.length)
コード例 #29
0
    def menuItemClicked(self, caption, messageInfo):
        response = messageInfo[0].getResponse()
        strResponse = ''.join([chr(c%256) for c in response])
        frame = JFrame('DOM XSS',size = (300,300))
        parentPanel = JPanel()


        #printedCode = JTextPane(text = strResponse)
        #'''
        #colored code
        printedCode = JTextPane()
        styledDoc = printedCode.getStyledDocument()
        style = printedCode.addStyle('ColoredCode',None)
        self.filter2(strResponse,styledDoc,style)
        #'''
        #Scroll Bar
        scrollPanel = JScrollPane(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED)
        scrollPanel.preferredSize = 1500,800
        scrollPanel.viewport.view = printedCode

        #Final Inclusion of Panels
        parentPanel.add(scrollPanel)
        frame.add(parentPanel)
        frame.visible = True
コード例 #30
0
ファイル: gui.py プロジェクト: Serabe/geogebra
 def __init__(self, textpane):
     self.component = JTextPane(
         font=textpane.font,
         border=BorderFactory.createEmptyBorder(5, 5, 5, 5),
         editable=False,
         background=awtColor(220, 220, 220),
     )
     self.doc = self.component.document
     self.component.setParagraphAttributes(
         textpane.paragraphAttributes, True
     )
     self.linecount = 0
     self.style = new_style(self.doc, "default",
         foreground=awtColor(100, 100, 100),
     )
     self.reset(1)
     textpane.document.addDocumentListener(self)
コード例 #31
0
ファイル: ProxyScripter.py プロジェクト: Izib/ProxyScripter
    def registerExtenderCallbacks(self, callbacks):
        self.callbacks = callbacks
        self.helpers = callbacks.helpers

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

        self.scrollpane = JScrollPane()
        self.scrollpane.setViewportView(self.scriptpane)

        self._code = compile('', '<string>', 'exec')
        self._script = ''

        callbacks.registerExtensionStateListener(self)        
        callbacks.registerProxyListener(self)
        callbacks.customizeUiComponent(self.getUiComponent())
        callbacks.addSuiteTab(self)

        self.scriptpane.requestFocus()
コード例 #32
0
    def	registerExtenderCallbacks(self, callbacks):   

        callbacks.registerExtensionStateListener(self)
        # keep a reference to our callbacks object
        self._callbacks = callbacks  
        # obtain an extension helpers object
        self._helpers = callbacks.getHelpers()
        # set our extension name
        callbacks.setExtensionName("Super Payload")
        # register ourselves as a payload generator factory
        callbacks.registerIntruderPayloadGeneratorFactory(self)

        # the Super Payload UI 
        self.scriptpane = JTextPane()
        self.scriptpane.setFont(Font('Monospaced', Font.PLAIN, 11))
        self.scrollpane = JScrollPane()
        self.scrollpane.setViewportView(self.scriptpane)
        callbacks.customizeUiComponent(self.getUiComponent())
        callbacks.addSuiteTab(self)
        self.scriptpane.requestFocus()

        # Compile the init script content
        self._code = compile('', '<string>', 'exec')
        self._script = ''

        script = callbacks.loadExtensionSetting('script')

        if script:
            script = base64.b64decode(script)

            self.scriptpane.document.insertString(
                self.scriptpane.document.length,
                script,
                SimpleAttributeSet())

            self._script = script
            self._code = compile(script, '<string>', 'exec')

        
        return
コード例 #33
0
ファイル: pane.py プロジェクト: HenryStevens/jes
    def setKeymap(self, keymap):
        # Swing keeps jacking up our keymap. This is designed to ensure that
        # a JES-able keymap always gets set, regardless of who's calling this.
        if keymap is None:
            JTextPane.setKeymap(self, self.standardKeymap)
        elif keymap.getName().endswith("ForJES"):
            JTextPane.setKeymap(self, keymap)
        else:
            commandKeymap = self.addKeymap(keymap.getName() + "ForJES", keymap)

            commandKeymap.addActionForKeyStroke(key('HOME'), PythonAction(self._home))
            commandKeymap.addActionForKeyStroke(key('shift HOME'), PythonAction(self._shifthome))
            commandKeymap.addActionForKeyStroke(key('ENTER'), PythonAction(self._enter))
            commandKeymap.addActionForKeyStroke(key('UP'), PythonAction(self._up))
            commandKeymap.addActionForKeyStroke(key('DOWN'), PythonAction(self._down))

            JTextPane.setKeymap(self, commandKeymap)
コード例 #34
0
ファイル: burpscript.py プロジェクト: hxer/BurpExtender
    def registerExtenderCallbacks(self, callbacks):
        self.callbacks = callbacks
        self.helpers = callbacks.helpers
        
        # text pane
        self.scriptpane = JTextPane()
        self.scriptpane.setFont(Font('Monospaced', Font.PLAIN, 11))

        self.scrollpane = JScrollPane()
        self.scrollpane.setViewportView(self.scriptpane)
        
        # compile to bytecode
        self._code = compile('', '<string>', 'exec')
        self._script = ''
        
        #  load configuration settings for the extension that were saved using the method saveExtensionSetting().
        script = callbacks.loadExtensionSetting('script')
        
        if script:
            script = base64.b64decode(script)

            self.scriptpane.document.insertString(
                self.scriptpane.document.length,
                script,
                SimpleAttributeSet())

            self._script = script
            self._code = compile(script, '<string>', 'exec')
            
        # register
        callbacks.registerExtensionStateListener(self)
        callbacks.registerHttpListener(self)
        
        # ui
        callbacks.customizeUiComponent(self.getUiComponent())
        callbacks.addSuiteTab(self)

        self.scriptpane.requestFocus()
コード例 #35
0
ファイル: pane.py プロジェクト: JoeLeclercq/jesWork
    def setKeymap(self, keymap):
        # Swing keeps jacking up our keymap. This is designed to ensure that
        # a JES-able keymap always gets set, regardless of who's calling this.
        if keymap is None:
            JTextPane.setKeymap(self, self.standardKeymap)
        elif keymap.getName().endswith("ForJES"):
            JTextPane.setKeymap(self, keymap)
        else:
            commandKeymap = self.addKeymap(keymap.getName() + "ForJES", keymap)

            commandKeymap.addActionForKeyStroke(key('HOME'),
                                                PythonAction(self._home))
            commandKeymap.addActionForKeyStroke(key('shift HOME'),
                                                PythonAction(self._shifthome))
            commandKeymap.addActionForKeyStroke(key('ENTER'),
                                                PythonAction(self._enter))
            commandKeymap.addActionForKeyStroke(key('UP'),
                                                PythonAction(self._up))
            commandKeymap.addActionForKeyStroke(key('DOWN'),
                                                PythonAction(self._down))

            JTextPane.setKeymap(self, commandKeymap)
コード例 #36
0
class Console(object):
    PS1 = sys.ps1
    PS2 = sys.ps2

    def __init__(self, burp, namespace=None):
        self.burp = burp
        self.log = burp.log
        self._locals = dict(Burp=burp)
        self._buffer = []
        self.history = History(self)

        if namespace is not None:
            self._locals.update(namespace)

        self.interp = JythonInterpreter(self, self._locals)

        self.textpane = JTextPane(keyTyped=self.keyTyped,
                                  keyPressed=self.keyPressed)

        self.textpane.setFont(Font('Monospaced', Font.PLAIN, 11))
        self.burp.customizeUiComponent(self.textpane)

        self.initKeyMap()

        self.document.remove(0, self.document.getLength())
        self.write('Burp Extender Jython Shell', prefix='')
        self.write(self.PS1)

        self.textpane.requestFocus()
        burp.log.info('Interactive interpreter ready...')

    @property
    def document(self):
        return self.textpane.document

    def resetbuffer(self):
        self._buffer = []

    def keyTyped(self, event=None):
        if not self.inLastLine():
            event.consume()

    def keyPressed(self, event):
        if event.keyCode in (KeyEvent.VK_BACK_SPACE, KeyEvent.VK_LEFT):
            self.backspaceListener(event)

    def getText(self):
        start, end = self.__getLastLineOffsets()
        text = self.document.getText(start, end - start)
        return text.rstrip()

    def insertText(self, data):
        position = self.textpane.getCaretPosition()
        self.textpane.select(position, position)
        self.textpane.replaceSelection(data)
        self.textpane.setCaretPosition(position + len(data))

    def replaceText(self, data):
        start, end = self.__getLastLineOffsets()
        self.textpane.select(start, end)
        self.textpane.replaceSelection(data)
        self.textpane.setCaretPosition(start + len(data))

    def write(self, data, color=Color.black, prefix='\n'):
        style = SimpleAttributeSet()

        if color is not None:
            style.addAttribute(StyleConstants.Foreground, color)

        self.document.insertString(self.document.getLength(), prefix + data, style)
        self.textpane.caretPosition = self.document.getLength()

    def enterAction(self, event=None):
        text = self.getText()
        self._buffer.append(text)
        source = '\n'.join(self._buffer)
        more = self.interp.runsource(source)

        if more:
            self.write(self.PS2, color=Color.black)
        else:
            self.resetbuffer()
            self.write(self.PS1)

        self.history.append(text)

    def deleteAction(self, event=None):
        if self.inLastLine():
            if self.textpane.getSelectedText():
                self.document.remove(self.textpane.getSelectionStart(),
                     self.textpane.getSelectionEnd() - self.textpane.getSelectionStart())

            elif self.textpane.getCaretPosition() < self.document.getLength():
                self.document.remove(self.textpane.getCaretPosition(), 1)

    def deleteEndLineAction(self, event=None):
        if self.inLastLine():
            position = self.textpane.getCaretPosition()
            self.textpane.setSelectionStart(position)
            _, end = self.__getLastLineOffsets()
            self.textpane.setSelectionEnd(end - 1)
            self.textpane.cut()

    def homeAction(self, event=None):
        if self.inLastLine():
            start, end = self.__getLastLineOffsets()
            self.textpane.caretPosition = start

    def endAction(self, event=None):
        if self.inLastLine():
            start, end = self.__getLastLineOffsets()
            self.textpane.caretPosition = end - 1

    def pasteAction(self, event=None):
        if self.inLastLine():
            clipboard = Toolkit.getDefaultToolkit().getSystemClipboard()
            clipboard.getContents(self.textpane)
            contents = clipboard.getData(DataFlavor.stringFlavor)

            lines = contents.splitlines()
            for i, line in enumerate(lines):
                self.insertText(line)
                if i < len(lines) - 1:
                    self.enterAction()

    def keyboardInterruptAction(self, event=None):
        self.interp.runsource('raise KeyboardInterrupt\n')
        self.resetbuffer()
        self.write(self.PS1)

    def backspaceListener(self, event=None):
        start, end = self.__getLastLineOffsets()

        if self.textpane.getCaretPosition() <= start and \
            not self.textpane.getSelectedText():
                event.consume()

    def initKeyMap(self):
        import platform
        os_name = platform.java_ver()[-1][0]

        if os_name.startswith('Win'):
            exit_key = KeyEvent.VK_Z
            interrupt_key = KeyEvent.VK_PAUSE
        else:
            exit_key = KeyEvent.VK_D
            interrupt_key = KeyEvent.VK_C

        bindings = [
            (KeyEvent.VK_ENTER, 0, 'jython.enter', self.enterAction),
            (KeyEvent.VK_DELETE, 0, 'jython.delete', self.deleteAction),

            (KeyEvent.VK_HOME, 0, 'jython.home', self.homeAction),
            (KeyEvent.VK_LEFT, InputEvent.META_DOWN_MASK, 'jython.home', self.homeAction),
            (KeyEvent.VK_END, 0, 'jython.end', self.endAction),
            (KeyEvent.VK_RIGHT, InputEvent.META_DOWN_MASK, 'jython.end', self.endAction),

            (KeyEvent.VK_UP, 0, 'jython.up', self.history.historyUp),
            (KeyEvent.VK_DOWN, 0, 'jython.down', self.history.historyDown),

            (KeyEvent.VK_V, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(), 'jython.paste', self.pasteAction),

            (KeyEvent.VK_A, InputEvent.CTRL_MASK, 'jython.home', self.homeAction),
            (KeyEvent.VK_E, InputEvent.CTRL_MASK, 'jython.end', self.endAction),
            (KeyEvent.VK_K, InputEvent.CTRL_MASK, 'jython.deleteEndLine', self.deleteEndLineAction),
            (KeyEvent.VK_Y, InputEvent.CTRL_MASK, 'jython.paste', self.pasteAction),

            #(interrupt_key, InputEvent.CTRL_MASK, 'jython.keyboardInterrupt', self.keyboardInterruptAction),
            ]

        keymap = JTextComponent.addKeymap('jython', self.textpane.getKeymap())

        for key, modifier, name, function in bindings:
            keymap.addActionForKeyStroke(
                    KeyStroke.getKeyStroke(key, modifier),
                    ActionDelegator(name, function))

        self.textpane.keymap = keymap

    def inLastLine(self, include=True):
        start, end = self.__getLastLineOffsets()

        if self.textpane.getSelectedText():
            position = self.textpane.getSelectionStart()
        else:
            position = self.textpane.getCaretPosition()

        if include is True:
            return start <= position <= end

        return start < position <= end

    def __getLastLineOffsets(self):
        firstElement = self.document.getRootElements()[0]
        lines = firstElement.getElementCount()

        start = firstElement.getElement(lines - 1).getStartOffset()
        end = firstElement.getElement(lines - 1).getEndOffset()

        line = self.document.getText(start, end - start)

        if len(line) >= 4 and (line[0:4] == self.PS1 or line[0:4] == self.PS2):
            return start + 4, end

        return start, end
コード例 #37
0
class BurpExtender(IBurpExtender, IIntruderPayloadGeneratorFactory, IExtensionStateListener, ITab):
    
    #
    # implement IBurpExtender
    #
    def	registerExtenderCallbacks(self, callbacks):   

        callbacks.registerExtensionStateListener(self)
        # keep a reference to our callbacks object
        self._callbacks = callbacks  
        # obtain an extension helpers object
        self._helpers = callbacks.getHelpers()
        # set our extension name
        callbacks.setExtensionName("Super Payload")
        # register ourselves as a payload generator factory
        callbacks.registerIntruderPayloadGeneratorFactory(self)

        # the Super Payload UI 
        self.scriptpane = JTextPane()
        self.scriptpane.setFont(Font('Monospaced', Font.PLAIN, 11))
        self.scrollpane = JScrollPane()
        self.scrollpane.setViewportView(self.scriptpane)
        callbacks.customizeUiComponent(self.getUiComponent())
        callbacks.addSuiteTab(self)
        self.scriptpane.requestFocus()

        # Compile the init script content
        self._code = compile('', '<string>', 'exec')
        self._script = ''

        script = callbacks.loadExtensionSetting('script')

        if script:
            script = base64.b64decode(script)

            self.scriptpane.document.insertString(
                self.scriptpane.document.length,
                script,
                SimpleAttributeSet())

            self._script = script
            self._code = compile(script, '<string>', 'exec')

        
        return

    def createNewInstance(self, attack):
    	return SuperGenerator(self, attack)

    def getGeneratorName(self):
    	return "SuperPayload"

    def extensionUnloaded(self):
        try:
            self.callbacks.saveExtensionSetting(
                'script', base64.b64encode(self._script))
        except Exception:
            traceback.print_exc(file=self.callbacks.getStderr())
        return

    def getTabCaption(self):
        return 'Super Payload Script'

    def getUiComponent(self):
        return self.scrollpane

    # Get the compiled code of user script (update or not)
    @property
    def script(self):
        end = self.scriptpane.document.length
        _script = self.scriptpane.document.getText(0, end)

        if _script == self._script:
            return self._code

        self._script = _script
        self._code = compile(_script, '<string>', 'exec')
        return self._code
コード例 #38
0
class BurpExtender(IBurpExtender, IIntruderPayloadGeneratorFactory,
                   IExtensionStateListener, ITab):

    #
    # implement IBurpExtender
    #
    def registerExtenderCallbacks(self, callbacks):

        callbacks.registerExtensionStateListener(self)
        # keep a reference to our callbacks object
        self._callbacks = callbacks
        # obtain an extension helpers object
        self._helpers = callbacks.getHelpers()
        # set our extension name
        callbacks.setExtensionName("Super Payload")
        # register ourselves as a payload generator factory
        callbacks.registerIntruderPayloadGeneratorFactory(self)

        # the Super Payload UI
        self.scriptpane = JTextPane()
        self.scriptpane.setFont(Font('Monospaced', Font.PLAIN, 11))
        self.scrollpane = JScrollPane()
        self.scrollpane.setViewportView(self.scriptpane)
        callbacks.customizeUiComponent(self.getUiComponent())
        callbacks.addSuiteTab(self)
        self.scriptpane.requestFocus()

        # Compile the init script content
        self._code = compile('', '<string>', 'exec')
        self._script = ''

        script = callbacks.loadExtensionSetting('script')

        if script:
            script = base64.b64decode(script)

            self.scriptpane.document.insertString(
                self.scriptpane.document.length, script, SimpleAttributeSet())

            self._script = script
            self._code = compile(script, '<string>', 'exec')

        return

    def createNewInstance(self, attack):
        return SuperGenerator(self, attack)

    def getGeneratorName(self):
        return "SuperPayload"

    def extensionUnloaded(self):
        try:
            self.callbacks.saveExtensionSetting('script',
                                                base64.b64encode(self._script))
        except Exception:
            traceback.print_exc(file=self.callbacks.getStderr())
        return

    def getTabCaption(self):
        return 'Super Payload Script'

    def getUiComponent(self):
        return self.scrollpane

    # Get the compiled code of user script (update or not)
    @property
    def script(self):
        end = self.scriptpane.document.length
        _script = self.scriptpane.document.getText(0, end)

        if _script == self._script:
            return self._code

        self._script = _script
        self._code = compile(_script, '<string>', 'exec')
        return self._code
コード例 #39
0
ファイル: browser.py プロジェクト: pdfernhout/openvirgle
class EditorPanel_text_utf_8(EditorPanel_abstract):
    
    def basicRecordChanged(self, newRecord):
        self.textEditor.caretPosition = 0
        self.saveButton.background = self.normalSaveButtonColor
    
    def makeComponents(self):
        # text specific operations
        self.randomUUIDButton = JButton("Generate random UUID", actionPerformed=self.randomUUIDPressed)
        self.clearButton = JButton("Clear", actionPerformed=self.clearPressed)
        self.runButton = JButton("Run as Jython", actionPerformed=self.runPressed)
        self.revertButton = JButton("Revert", actionPerformed=self.revertPressed)

        self.buttonPanel = Box(BoxLayout.X_AXIS) 
        self.buttonPanel.add(Box.createRigidArea(Dimension(5,0)))
        self.buttonPanel.add(self.randomUUIDButton)
        self.buttonPanel.add(Box.createRigidArea(Dimension(5,0)))
        self.buttonPanel.add(self.clearButton)
        self.buttonPanel.add(Box.createRigidArea(Dimension(5,0)))
        self.buttonPanel.add(self.runButton)
        self.buttonPanel.add(Box.createRigidArea(Dimension(5,0)))
        self.buttonPanel.add(self.revertButton)
        self.buttonPanel.add(Box.createRigidArea(Dimension(5,0)))
 
        self.textEditor = JTextPane()
        self.textEditor.setFont(Font("monospaced", Font.PLAIN, 12))
        #self.textEditor.setTabSize(4) # still inserts tabs instead of spaces
        TabKeyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0, False)
        MyTabActionKey = Object()
        self.textEditor.getInputMap().put(TabKeyStroke, MyTabActionKey)
        actionMap = self.textEditor.getActionMap()
        actionMap.put(MyTabActionKey, AddFourSpacesAction())
        
        self.layout = BorderLayout()
        self.add(self.buttonPanel, BorderLayout.NORTH)
        self.add(JScrollPane(self.textEditor), BorderLayout.CENTER)
        
    def basicGetCurrentValueBytes(self):
        return self.textEditor.text
        
    def basicSetCurrentValueBytes(self, newValueBytes):
        self.textEditor.text = newValueBytes
        self.textEditor.caretPosition = 0
        
    # extra functionality
    def runPressed(self, event):
        print "run pressed"
        codeText = self.getCurrentValueBytes()
        print "=== run code ==="
        exec "from token import *"
        #print codeText
        self.browser.oldimport = __builtin__.__import__
        self.browser.contextUUID = self.browser.entitiesList.selectedValue
        __builtin__.__import__ = self.browser.importCodeFromRepository
        self.browser.importLevel = 0
        try:
            try:
                someGlobals = {"currentBrowser": self.browser, "contextUUID": self.browser.entitiesList.selectedValue}
                exec codeText in someGlobals
            except SyntaxError, e:
                print e
                #print "fileName", e.fileName
                #print "lineno", e.lineno
                print "offset:", e.offset
                print "text:", e.text
                lines = codeText.split('\n')
                position = 0
                for i in range(e.lineno - 1):
                    position += len(lines[i]) + 1
                position += e.offset
                self.textEditor.caretPosition = position
                self.textEditor.requestFocus()
            print "=== done ==="
        finally:
コード例 #40
0
ファイル: console.py プロジェクト: omusico/siga
class Console:
    PROMPT = sys.ps1
    PROCESS = sys.ps2
    BANNER = ["Jython Completion Shell", InteractiveConsole.getDefaultBanner()]

    def __init__(self, frame):

        self.frame = frame  # TODO do I need a reference to frame after the constructor?
        self.history = History(self)
        self.bs = 0  # what is this?

        # command buffer
        self.buffer = []
        self.locals = {"gvSIG": sys.gvSIG}

        self.interp = Interpreter(self, self.locals)
        sys.stdout = StdOutRedirector(self)

        # create a textpane
        self.output = JTextPane(keyTyped=self.keyTyped, keyPressed=self.keyPressed)
        # TODO rename output to textpane

        # CTRL UP AND DOWN don't work
        keyBindings = [
            (KeyEvent.VK_ENTER, 0, "jython.enter", self.enter),
            (KeyEvent.VK_DELETE, 0, "jython.delete", self.delete),
            (KeyEvent.VK_HOME, 0, "jython.home", self.home),
            (KeyEvent.VK_UP, 0, "jython.up", self.history.historyUp),
            (KeyEvent.VK_DOWN, 0, "jython.down", self.history.historyDown),
            (KeyEvent.VK_PERIOD, 0, "jython.showPopup", self.showPopup),
            (KeyEvent.VK_ESCAPE, 0, "jython.hide", self.hide),
            ("(", 0, "jython.showTip", self.showTip),
            (")", 0, "jython.hideTip", self.hideTip),
            # (KeyEvent.VK_UP, InputEvent.CTRL_MASK, DefaultEditorKit.upAction, self.output.keymap.getAction(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0))),
            # (KeyEvent.VK_DOWN, InputEvent.CTRL_MASK, DefaultEditorKit.downAction, self.output.keymap.getAction(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0)))
        ]
        # TODO rename newmap to keymap
        newmap = JTextComponent.addKeymap("jython", self.output.keymap)
        for (key, modifier, name, function) in keyBindings:
            newmap.addActionForKeyStroke(KeyStroke.getKeyStroke(key, modifier), ActionDelegator(name, function))

        self.output.keymap = newmap

        self.doc = self.output.document
        # self.panel.add(BorderLayout.CENTER, JScrollPane(self.output))
        self.__propertiesChanged()
        self.__inittext()
        self.initialLocation = self.doc.createPosition(self.doc.length - 1)

        # Don't pass frame to popups. JWindows with null owners are not focusable
        # this fixes the focus problem on Win32, but make the mouse problem worse
        self.popup = Popup(None, self.output)
        self.tip = Tip(None)

        # get fontmetrics info so we can position the popup
        metrics = self.output.getFontMetrics(self.output.getFont())
        self.dotWidth = metrics.charWidth(".")
        self.textHeight = metrics.getHeight()

        # add some handles to our objects
        self.locals["console"] = self

        self.caret = self.output.getCaret()

    # TODO refactor me
    def getinput(self):
        offsets = self.__lastLine()
        text = self.doc.getText(offsets[0], offsets[1] - offsets[0])
        return text

    def getDisplayPoint(self):
        """Get the point where the popup window should be displayed"""
        screenPoint = self.output.getLocationOnScreen()
        caretPoint = self.output.caret.getMagicCaretPosition()

        # TODO use SwingUtils to do this translation
        x = screenPoint.getX() + caretPoint.getX() + self.dotWidth
        y = screenPoint.getY() + caretPoint.getY() + self.textHeight
        return Point(int(x), int(y))

    def hide(self, event=None):
        """Hide the popup or tip window if visible"""
        if self.popup.visible:
            self.popup.hide()
        if self.tip.visible:
            self.tip.hide()

    def hideTip(self, event=None):
        self.tip.hide()
        # TODO this needs to insert ')' at caret!
        self.write(")")

    def showTip(self, event=None):
        # get the display point before writing text
        # otherwise magicCaretPosition is None
        displayPoint = self.getDisplayPoint()

        if self.popup.visible:
            self.popup.hide()

        line = self.getinput()
        # debug("line", line)
        # Hack 'o rama
        line = line[:-1]  # remove \n
        line += "("
        # debug("line", line)

        # TODO this needs to insert '(' at caret!
        self.write("(")

        (name, argspec, tip) = jintrospect.getCallTipJava(line, self.locals)
        # debug("name", name)
        # debug("argspec", argspec)
        # debug("tip", tip)

        if tip:
            self.tip.setLocation(displayPoint)
            self.tip.setText(tip)
            self.tip.show()

    def showPopup(self, event=None):

        line = self.getinput()
        # this is silly, I have to add the '.' and the other code removes it.
        line = line[:-1]  # remove \n
        line = line + "."
        # print >> sys.stderr, "line:",line

        # TODO get this code into Popup
        # TODO handle errors gracefully
        try:
            list = jintrospect.getAutoCompleteList(line, self.locals)
        except Exception, e:
            # TODO handle this gracefully
            print >>sys.stderr, e
            return

        if len(list) == 0:
            # print >> sys.stderr, "list was empty"
            return

        self.popup.setLocation(self.getDisplayPoint())

        self.popup.setMethods(list)
        self.popup.show()
        self.popup.list.setSelectedIndex(0)
コード例 #41
0
ファイル: burpscript.py プロジェクト: hxer/BurpExtender
class BurpExtender(IBurpExtender, IExtensionStateListener, IHttpListener, ITab):

    def registerExtenderCallbacks(self, callbacks):
        self.callbacks = callbacks
        self.helpers = callbacks.helpers
        
        # text pane
        self.scriptpane = JTextPane()
        self.scriptpane.setFont(Font('Monospaced', Font.PLAIN, 11))

        self.scrollpane = JScrollPane()
        self.scrollpane.setViewportView(self.scriptpane)
        
        # compile to bytecode
        self._code = compile('', '<string>', 'exec')
        self._script = ''
        
        #  load configuration settings for the extension that were saved using the method saveExtensionSetting().
        script = callbacks.loadExtensionSetting('script')
        
        if script:
            script = base64.b64decode(script)

            self.scriptpane.document.insertString(
                self.scriptpane.document.length,
                script,
                SimpleAttributeSet())

            self._script = script
            self._code = compile(script, '<string>', 'exec')
            
        # register
        callbacks.registerExtensionStateListener(self)
        callbacks.registerHttpListener(self)
        
        # ui
        callbacks.customizeUiComponent(self.getUiComponent())
        callbacks.addSuiteTab(self)

        self.scriptpane.requestFocus()
        
    #
    # extender unload
    #

    def extensionUnloaded(self):
        try:
            # save script, base64 encode
            self.callbacks.saveExtensionSetting(
                'script', base64.b64encode(self._script))
        except Exception:
            traceback.print_exc(file=self.callbacks.getStderr())
        return
    
    #
    # implement IHttpListener
    #
    
    def processHttpMessage(self, toolFlag, messageIsRequest, messageInfo):
        try:
            globals_ = {'extender': self,
                        'callbacks': self.callbacks,
                        'helpers': self.helpers
            }
            locals_  = {'toolFlag': toolFlag,
                        'messageIsRequest': messageIsRequest,
                        'messageInfo': messageInfo
            }
            exec(self.script, globals_, locals_)
        except Exception:
            traceback.print_exc(file=self.callbacks.getStderr())
        return

    #
    # implement ITab
    #
    def getTabCaption(self):
        return 'Script'

    def getUiComponent(self):
        return self.scrollpane
    
    #
    # script 不变时,不用重复编译, 优化性能
    #
    
    @property
    def script(self):
        end = self.scriptpane.document.length
        _script = self.scriptpane.document.getText(0, end)

        if _script == self._script:
            return self._code

        self._script = _script
        self._code = compile(_script, '<string>', 'exec')
        return self._code
コード例 #42
0
    def registerExtenderCallbacks(self, callbacks):
        print "Loading..."

        self._callbacks = callbacks
        self._callbacks.setExtensionName('Burp SSL Scanner')
        # self._callbacks.registerScannerCheck(self)
        # self._callbacks.registerExtensionStateListener(self)
        self._helpers = callbacks.getHelpers()

        # initialize the main scanning event and thread
        self.scanningEvent = Event()
        self.scannerThread = None
        self.targetURL = None

        # main split pane
        self._splitpane = JSplitPane(JSplitPane.VERTICAL_SPLIT)
        self._splitpane.setBorder(EmptyBorder(20, 20, 20, 20))
        
        # sub split pane (top)
        self._topPanel = JPanel(BorderLayout(10, 10))
        self._topPanel.setBorder(EmptyBorder(0, 0, 10, 0))

        # Setup Panel :    [Target: ] [______________________] [START BUTTON]
        self.setupPanel = JPanel(FlowLayout(FlowLayout.LEADING, 10, 10))

        self.setupPanel.add(
            JLabel("Target:", SwingConstants.LEFT), BorderLayout.LINE_START)

        self.hostField = JTextField('', 50)
        self.setupPanel.add(self.hostField)

        self.toggleButton = JButton(
            'Start scanning', actionPerformed=self.startScan)
        self.setupPanel.add(self.toggleButton)

        if 'Professional' in callbacks.getBurpVersion()[0] :
            self.addToSitemapCheckbox = JCheckBox('Add to sitemap', True)
        else :
            self.addToSitemapCheckbox = JCheckBox('Add to sitemap (requires Professional version)', False)
            self.addToSitemapCheckbox.setEnabled(False)
        self.setupPanel.add(self.addToSitemapCheckbox)

        self.scanSiteMapHostCheckbox = JCheckBox('Scan sitemap hosts', True)
        self.setupPanel.add(self.scanSiteMapHostCheckbox)

        self._topPanel.add(self.setupPanel, BorderLayout.PAGE_START)
        
        # Status bar
        self.scanStatusPanel = JPanel(FlowLayout(FlowLayout.LEADING, 10, 10))

        self.scanStatusPanel.add(JLabel("Status: ", SwingConstants.LEFT))

        self.scanStatusLabel = JLabel("Ready to scan", SwingConstants.LEFT)
        self.scanStatusPanel.add(self.scanStatusLabel)

        self._topPanel.add(self.scanStatusPanel, BorderLayout.LINE_START)

        self._splitpane.setTopComponent(self._topPanel)

        # bottom panel 
        self._bottomPanel = JPanel(BorderLayout(10, 10))
        self._bottomPanel.setBorder(EmptyBorder(10, 0, 0, 0))

        self.initialText = ('<h1 style="color: red;">Burp SSL Scanner<br />'
                            'Please note that TLS1.3 is still not supported by this extension.</h1>')
        self.currentText = self.initialText

        self.textPane = JTextPane()
        self.textScrollPane = JScrollPane(self.textPane)
        self.textPane.setContentType("text/html")
        self.textPane.setText(self.currentText)
        self.textPane.setEditable(False)

        self._bottomPanel.add(self.textScrollPane, BorderLayout.CENTER)

        self.savePanel = JPanel(FlowLayout(FlowLayout.LEADING, 10, 10))
        self.saveButton = JButton('Save to file', actionPerformed=self.saveToFile)
        self.saveButton.setEnabled(False)
        self.savePanel.add(self.saveButton)

        self.clearScannedHostButton = JButton('Clear scanned host', actionPerformed=self.clearScannedHost)
        self.savePanel.add(self.clearScannedHostButton)
        self.savePanel.add(JLabel("Clear hosts that were scanned by active scan to enable rescanning", SwingConstants.LEFT))

        self._bottomPanel.add(self.savePanel, BorderLayout.PAGE_END)

        self._splitpane.setBottomComponent(self._bottomPanel)

        callbacks.customizeUiComponent(self._splitpane)

        callbacks.addSuiteTab(self)
        
        print "SSL Scanner tab loaded"


        self.scannerMenu = ScannerMenu(self)
        callbacks.registerContextMenuFactory(self.scannerMenu)
        print "SSL Scanner custom menu loaded"


        self.scannerCheck = ScannerCheck(self, self.scanSiteMapHostCheckbox.isSelected)
        callbacks.registerScannerCheck(self.scannerCheck)
        print "SSL Scanner check registered"

        projectConfig = json.loads(self._callbacks.saveConfigAsJson())
        scanAccuracy = projectConfig['scanner']['active_scanning_optimization']['scan_accuracy']
        scanSpeed = projectConfig['scanner']['active_scanning_optimization']['scan_speed']

        print(scanAccuracy, scanSpeed)

        self.scannedHost = []

        print 'SSL Scanner loaded'
コード例 #43
0
class BurpExtender(IBurpExtender, ITab):
    def registerExtenderCallbacks(self, callbacks):
        print "Loading..."

        self._callbacks = callbacks
        self._callbacks.setExtensionName('Burp SSL Scanner')
        # self._callbacks.registerScannerCheck(self)
        # self._callbacks.registerExtensionStateListener(self)
        self._helpers = callbacks.getHelpers()

        # initialize the main scanning event and thread
        self.scanningEvent = Event()
        self.scannerThread = None
        self.targetURL = None

        # main split pane
        self._splitpane = JSplitPane(JSplitPane.VERTICAL_SPLIT)
        self._splitpane.setBorder(EmptyBorder(20, 20, 20, 20))
        
        # sub split pane (top)
        self._topPanel = JPanel(BorderLayout(10, 10))
        self._topPanel.setBorder(EmptyBorder(0, 0, 10, 0))

        # Setup Panel :    [Target: ] [______________________] [START BUTTON]
        self.setupPanel = JPanel(FlowLayout(FlowLayout.LEADING, 10, 10))

        self.setupPanel.add(
            JLabel("Target:", SwingConstants.LEFT), BorderLayout.LINE_START)

        self.hostField = JTextField('', 50)
        self.setupPanel.add(self.hostField)

        self.toggleButton = JButton(
            'Start scanning', actionPerformed=self.startScan)
        self.setupPanel.add(self.toggleButton)

        if 'Professional' in callbacks.getBurpVersion()[0] :
            self.addToSitemapCheckbox = JCheckBox('Add to sitemap', True)
        else :
            self.addToSitemapCheckbox = JCheckBox('Add to sitemap (requires Professional version)', False)
            self.addToSitemapCheckbox.setEnabled(False)
        self.setupPanel.add(self.addToSitemapCheckbox)

        self.scanSiteMapHostCheckbox = JCheckBox('Scan sitemap hosts', True)
        self.setupPanel.add(self.scanSiteMapHostCheckbox)

        self._topPanel.add(self.setupPanel, BorderLayout.PAGE_START)
        
        # Status bar
        self.scanStatusPanel = JPanel(FlowLayout(FlowLayout.LEADING, 10, 10))

        self.scanStatusPanel.add(JLabel("Status: ", SwingConstants.LEFT))

        self.scanStatusLabel = JLabel("Ready to scan", SwingConstants.LEFT)
        self.scanStatusPanel.add(self.scanStatusLabel)

        self._topPanel.add(self.scanStatusPanel, BorderLayout.LINE_START)

        self._splitpane.setTopComponent(self._topPanel)

        # bottom panel 
        self._bottomPanel = JPanel(BorderLayout(10, 10))
        self._bottomPanel.setBorder(EmptyBorder(10, 0, 0, 0))

        self.initialText = ('<h1 style="color: red;">Burp SSL Scanner<br />'
                            'Please note that TLS1.3 is still not supported by this extension.</h1>')
        self.currentText = self.initialText

        self.textPane = JTextPane()
        self.textScrollPane = JScrollPane(self.textPane)
        self.textPane.setContentType("text/html")
        self.textPane.setText(self.currentText)
        self.textPane.setEditable(False)

        self._bottomPanel.add(self.textScrollPane, BorderLayout.CENTER)

        self.savePanel = JPanel(FlowLayout(FlowLayout.LEADING, 10, 10))
        self.saveButton = JButton('Save to file', actionPerformed=self.saveToFile)
        self.saveButton.setEnabled(False)
        self.savePanel.add(self.saveButton)

        self.clearScannedHostButton = JButton('Clear scanned host', actionPerformed=self.clearScannedHost)
        self.savePanel.add(self.clearScannedHostButton)
        self.savePanel.add(JLabel("Clear hosts that were scanned by active scan to enable rescanning", SwingConstants.LEFT))

        self._bottomPanel.add(self.savePanel, BorderLayout.PAGE_END)

        self._splitpane.setBottomComponent(self._bottomPanel)

        callbacks.customizeUiComponent(self._splitpane)

        callbacks.addSuiteTab(self)
        
        print "SSL Scanner tab loaded"


        self.scannerMenu = ScannerMenu(self)
        callbacks.registerContextMenuFactory(self.scannerMenu)
        print "SSL Scanner custom menu loaded"


        self.scannerCheck = ScannerCheck(self, self.scanSiteMapHostCheckbox.isSelected)
        callbacks.registerScannerCheck(self.scannerCheck)
        print "SSL Scanner check registered"

        projectConfig = json.loads(self._callbacks.saveConfigAsJson())
        scanAccuracy = projectConfig['scanner']['active_scanning_optimization']['scan_accuracy']
        scanSpeed = projectConfig['scanner']['active_scanning_optimization']['scan_speed']

        print(scanAccuracy, scanSpeed)

        self.scannedHost = []

        print 'SSL Scanner loaded'
        
    def startScan(self, ev) :

        host = self.hostField.text
        self.scanningEvent.set()
        if(len(host) == 0):
            return
        if host.find("://") == -1:
            host = "https://" + host 
        try:
            self.targetURL = URL(host)
            if(self.targetURL.getPort() == -1):
                self.targetURL = URL("https", self.targetURL.getHost(), 443, "/")
            self.hostField.setEnabled(False)
            self.toggleButton.setEnabled(False)
            self.saveButton.setEnabled(False)
            self.addToSitemapCheckbox.setEnabled(False)
            self.currentText = self.initialText
            self.textPane.setText(self.currentText)
            self.updateText("<h2>Scanning %s:%d</h2>" % (self.targetURL.getHost(), self.targetURL.getPort()))
            print("Scanning %s:%d" % (self.targetURL.getHost(), self.targetURL.getPort()))
            self.scannerThread = Thread(target=self.scan, args=(self.targetURL, ))
            self.scannerThread.start()
        except BaseException as e:
            self.saveButton.setEnabled(False)
            print(e)
            return

    def scan(self, url, usingBurpScanner=False):

        def setScanStatusLabel(text) :
            if not usingBurpScanner :
                SwingUtilities.invokeLater(
                    ScannerRunnable(self.scanStatusLabel.setText, 
                                    (text,)))
                                
        def updateResultText(text) :
            if not usingBurpScanner :
                SwingUtilities.invokeLater(
                    ScannerRunnable(self.updateText, (text, )))

        if usingBurpScanner :
            res = result.Result(url, self._callbacks, self._helpers, False)
        else :
            res = result.Result(url, self._callbacks, self._helpers, self.addToSitemapCheckbox.isSelected())

        host, port = url.getHost(), url.getPort()

        ### Get project configuration
        projectConfig = json.loads(self._callbacks.saveConfigAsJson())
        if 'scanner' in projectConfig:
            # scanAccuracy: minimise_false_negatives, normal, minimise_false_positives
            scanAccuracy = projectConfig['scanner']['active_scanning_optimization']['scan_accuracy']
            # scanSpeed: fast, normal, thorough
            scanSpeed = projectConfig['scanner']['active_scanning_optimization']['scan_speed']
        else:
            scanAccuracy = 'normal'
            scanSpeed = 'normal'

        updateResultText('<h2>Scanning speed: %s</h2> %s' % (scanSpeed, test_details.SCANNING_SPEED_INFO[scanSpeed]))
        updateResultText('<h2>Scanning accuracy: %s</h2> %s' % (scanAccuracy, test_details.SCANNING_ACCURACY_INFO[scanAccuracy]))

        try :
            setScanStatusLabel("Checking for supported SSL/TLS versions")
            con = connection_test.ConnectionTest(res, host, port, scanSpeed, scanAccuracy)
            con.start()
            conResultText = '<hr /><br /><h3>' + res.printResult('connectable') + '</h3>' + \
                '<ul><li>' + res.printResult('offer_ssl2') + '</li>' + \
                '<li>' + res.printResult('offer_ssl3') + '</li>' + \
                '<li>' + res.printResult('offer_tls10') + '</li>' + \
                '<li>' + res.printResult('offer_tls11') + '</li>' + \
                '<li>' + res.printResult('offer_tls12') + '</li></ul>'
            updateResultText(conResultText)

            
            if not res.getResult('connectable') :
                updateResultText("<h2>Scan terminated (Connection failed)</h2>")
                raise BaseException('Connection failed')

            setScanStatusLabel("Checking for supported cipher suites (This can take a long time)")
            supportedCipher = supportedCipher_test.SupportedCipherTest(res, host, port, scanSpeed, scanAccuracy)
            supportedCipher.start()

            
            setScanStatusLabel("Checking for Cipherlist")
            cipher = cipher_test.CipherTest(res, host, port, scanSpeed, scanAccuracy)
            cipher.start()
            cipherResultText = '<h3>Available ciphers:</h3>' + \
                '<ul><li>' + res.printResult('cipher_NULL') + '</li>' + \
                '<li>' + res.printResult('cipher_ANON') + '</li>' + \
                '<li>' + res.printResult('cipher_EXP') + '</li>' + \
                '<li>' + res.printResult('cipher_LOW') + '</li>' + \
                '<li>' + res.printResult('cipher_WEAK') + '</li>' + \
                '<li>' + res.printResult('cipher_3DES') + '</li>' + \
                '<li>' + res.printResult('cipher_HIGH') + '</li>' + \
                '<li>' + res.printResult('cipher_STRONG') + '</li></ul>' 
            updateResultText(cipherResultText)
            

            setScanStatusLabel("Checking for Heartbleed")
            heartbleed = heartbleed_test.HeartbleedTest(res, host, port, scanSpeed, scanAccuracy)
            heartbleed.start()
            heartbleedResultText = res.printResult('heartbleed')
            updateResultText(heartbleedResultText)
            

            setScanStatusLabel("Checking for CCS Injection")
            ccs = ccs_test.CCSTest(res, host, port, scanSpeed, scanAccuracy)
            ccs.start()
            ccsResultText = res.printResult('ccs_injection')
            updateResultText(ccsResultText)

            
            setScanStatusLabel("Checking for TLS_FALLBACK_SCSV")
            fallback = fallback_test.FallbackTest(res, host, port, scanSpeed, scanAccuracy)
            fallback.start()
            fallbackResultText = res.printResult('fallback_support')
            updateResultText(fallbackResultText)


            setScanStatusLabel("Checking for POODLE (SSLv3)")
            poodle = poodle_test.PoodleTest(res, host, port, scanSpeed, scanAccuracy)
            poodle.start()
            poodleResultText = res.printResult('poodle_ssl3')
            updateResultText(poodleResultText)
            

            setScanStatusLabel("Checking for SWEET32")
            sweet32 = sweet32_test.Sweet32Test(res, host, port, scanSpeed, scanAccuracy)
            sweet32.start()
            sweet32ResultText = res.printResult('sweet32')
            updateResultText(sweet32ResultText)
            

            setScanStatusLabel("Checking for DROWN")
            drown = drown_test.DrownTest(res, host, port, scanSpeed, scanAccuracy)
            drown.start()
            drownResultText = res.printResult('drown')
            updateResultText(drownResultText)
            

            setScanStatusLabel("Checking for FREAK")
            freak = freak_test.FreakTest(res, host, port, scanSpeed, scanAccuracy)
            freak.start()
            freakResultText = res.printResult('freak')
            updateResultText(freakResultText)
            

            setScanStatusLabel("Checking for LUCKY13")
            lucky13 = lucky13_test.Lucky13Test(res, host, port, scanSpeed, scanAccuracy)
            lucky13.start()
            lucky13ResultText = res.printResult('lucky13')
            updateResultText(lucky13ResultText)
            

            setScanStatusLabel("Checking for CRIME")
            crime = crime_test.CrimeTest(res, host, port, scanSpeed, scanAccuracy)
            crime.start()
            crimeResultText = res.printResult('crime_tls')
            updateResultText(crimeResultText)
            

            setScanStatusLabel("Checking for BREACH")
            breach = breach_test.BreachTest(res, host, port, scanSpeed, scanAccuracy)
            breach.start(self._callbacks, self._helpers)
            breachResultText = res.printResult('breach')
            updateResultText(breachResultText)


            setScanStatusLabel("Checking for BEAST")
            beast = beast_test.BeastTest(res, host, port, scanSpeed, scanAccuracy)
            beast.start()
            beastResultText = res.printResult('beast')
            updateResultText(beastResultText)


            setScanStatusLabel("Checking for LOGJAM")
            logjam = logjam_test.LogjamTest(res, host, port, scanSpeed, scanAccuracy)
            logjam.start()
            logjamResultText = res.printResult('logjam_export') + '<br />' + res.printResult('logjam_common') 
            updateResultText(logjamResultText)
            

            updateResultText('<h2>Finished scanning</h2><br /><hr /><br /><h2>Summary</h2>')

            updateResultText('<h2>Supported ciphers (by Protocol)</h2>')
            updateResultText(res.printCipherList())
            updateResultText('<h2>Supported ciphers (by Vulnerability)</h2>')
            updateResultText(res.printCipherListByVulns())

            updateResultText('<h2>Issues found</h2>')
            updateResultText(res.printAllIssue())

        except BaseException as e :
            print(e)
            setScanStatusLabel("An error occurred. Please refer to the output/errors tab for more information.")
            time.sleep(2)

        if usingBurpScanner :
            return res.getAllIssue()
        else :
            self.scanningEvent.clear()
            SwingUtilities.invokeLater(
                    ScannerRunnable(self.toggleButton.setEnabled, (True, ))
            )
            SwingUtilities.invokeLater(
                    ScannerRunnable(self.hostField.setEnabled, (True, ))
            )
            SwingUtilities.invokeLater(
                    ScannerRunnable(self.saveButton.setEnabled, (True, ))
            )
            if 'Professional' in self._callbacks.getBurpVersion()[0] :
                SwingUtilities.invokeLater(
                    ScannerRunnable(self.addToSitemapCheckbox.setEnabled, (True, ))
                )
            setScanStatusLabel("Ready to scan")
        print("Finished scanning")

    def updateText(self, stringToAppend):
        self.currentText += ('<br />' + stringToAppend)
        self.textPane.setText(self.currentText)

    def saveToFile(self, event):
        fileChooser = JFileChooser()
        if not (self.targetURL is None):
            fileChooser.setSelectedFile(File("Burp_SSL_Scanner_Result_%s.html" \
                % (self.targetURL.getHost())))
        else:
            fileChooser.setSelectedFile(File("Burp_SSL_Scanner_Result.html"))
        if (fileChooser.showSaveDialog(self.getUiComponent()) == JFileChooser.APPROVE_OPTION):
            fw = FileWriter(fileChooser.getSelectedFile())
            fw.write(self.textPane.getText())
            fw.flush()
            fw.close()
            print "Saved results to disk"

    def clearScannedHost(self, event) :
        self.scannedHost = []

    def addHostToScannedList(self, host, port) :
        self.scannedHost.append([host, port])

    def getTabCaption(self):
        return "SSL Scanner"

    def getUiComponent(self):
        return self._splitpane
コード例 #44
0
class BurpExtender(IBurpExtender, ISessionHandlingAction,
                   IExtensionStateListener, ITab):
    def registerExtenderCallbacks(self, callbacks):
        self.callbacks = callbacks
        self.helpers = callbacks.helpers

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

        self.scrollpane = JScrollPane()
        self.scrollpane.setViewportView(self.scriptpane)

        self._code = compile('', '<string>', 'exec')
        self._script = ''

        script = callbacks.loadExtensionSetting('script')

        if script:
            script = base64.b64decode(script)

            self.scriptpane.document.insertString(
                self.scriptpane.document.length, script, SimpleAttributeSet())

            self._script = script
            self._code = compile(script, '<string>', 'exec')

        callbacks.registerExtensionStateListener(self)
        callbacks.customizeUiComponent(self.getUiComponent())
        callbacks.registerSessionHandlingAction(self)
        callbacks.addSuiteTab(self)
        self.scriptpane.requestFocus()

    def extensionUnloaded(self):
        try:
            self.callbacks.saveExtensionSetting('script',
                                                base64.b64encode(self._script))
        except Exception:
            traceback.print_exc(file=self.callbacks.getStderr())
        return

    def getActionName(self):
        return "Custom Makro Python Script"

    def performAction(self, currentRequest, macroItems):
        try:
            globals_ = {
                'extender': self,
                'callbacks': self.callbacks,
                'helpers': self.helpers,
                'IBurpCollaboratorClientContext':
                IBurpCollaboratorClientContext,
                'IBurpCollaboratorInteraction': IBurpCollaboratorInteraction,
                'IBurpExtender': IBurpExtender,
                'IBurpExtenderCallbacks': IBurpExtenderCallbacks,
                'IContextMenuFactory': IContextMenuFactory,
                'IContextMenuInvocation': IContextMenuInvocation,
                'ICookie': ICookie,
                'IExtensionHelpers': IExtensionHelpers,
                'IExtensionStateListener': IExtensionStateListener,
                'IHttpListener': IHttpListener,
                'IHttpRequestResponse': IHttpRequestResponse,
                'IHttpRequestResponsePersisted': IHttpRequestResponsePersisted,
                'IHttpRequestResponseWithMarkers':
                IHttpRequestResponseWithMarkers,
                'IHttpService': IHttpService,
                'IInterceptedProxyMessage': IInterceptedProxyMessage,
                'IIntruderAttack': IIntruderAttack,
                'IIntruderPayloadGenerator': IIntruderPayloadGenerator,
                'IIntruderPayloadGeneratorFactory':
                IIntruderPayloadGeneratorFactory,
                'IIntruderPayloadProcessor': IIntruderPayloadProcessor,
                'IMenuItemHandler': IMenuItemHandler,
                'IMessageEditor': IMessageEditor,
                'IMessageEditorController': IMessageEditorController,
                'IMessageEditorTab': IMessageEditorTab,
                'IMessageEditorTabFactory': IMessageEditorTabFactory,
                'IParameter': IParameter,
                'IProxyListener': IProxyListener,
                'IRequestInfo': IRequestInfo,
                'IResponseInfo': IResponseInfo,
                'IResponseKeywords': IResponseKeywords,
                'IResponseVariations': IResponseVariations,
                'IScanIssue': IScanIssue,
                'IScannerCheck': IScannerCheck,
                'IScannerInsertionPoint': IScannerInsertionPoint,
                'IScannerInsertionPointProvider':
                IScannerInsertionPointProvider,
                'IScannerListener': IScannerListener,
                'IScanQueueItem': IScanQueueItem,
                'IScopeChangeListener': IScopeChangeListener,
                'ISessionHandlingAction': ISessionHandlingAction,
                'ITab': ITab,
                'ITempFile': ITempFile,
                'ITextEditor': ITextEditor,
            }
            locals_ = {
                'currentRequest': currentRequest,
                'macroItems': macroItems
            }
            exec(self.script, globals_, locals_)
        except Exception:
            traceback.print_exc(file=self.callbacks.getStderr())
        return

    def getTabCaption(self):
        return 'Makro Script'

    def getUiComponent(self):
        return self.scrollpane

    @property
    def script(self):
        end = self.scriptpane.document.length
        _script = self.scriptpane.document.getText(0, end)

        if _script == self._script:
            return self._code

        self._script = _script
        self._code = compile(_script, '<string>', 'exec')
        return self._code
コード例 #45
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
コード例 #46
0
ファイル: console.py プロジェクト: 0x7678/android-ssl-bypass
class Console:
    PROMPT = sys.ps1
    PROCESS = sys.ps2
    BANNER = ["Jython Completion Shell", InteractiveConsole.getDefaultBanner()]
  
    include_single_underscore_methods = False
    include_double_underscore_methods = False

    def __init__(self, namespace=None):
        """
            Create a Jython Console.
            namespace is an optional and should be a dictionary or Map
        """
        self.history = History(self)

        if namespace != None:
            self.locals = namespace
        else:
            self.locals = {}

        self.buffer = [] # buffer for multi-line commands                    

        self.interp = Interpreter(self, self.locals)
        sys.stdout = StdOutRedirector(self)

        self.text_pane = JTextPane(keyTyped = self.keyTyped, keyPressed = self.keyPressed)
        self.__initKeyMap()

        self.doc = self.text_pane.document
        self.__propertiesChanged()
        self.__inittext()
        self.initialLocation = self.doc.createPosition(self.doc.length-1)

        # Don't pass frame to popups. JWindows with null owners are not focusable
        # this fixes the focus problem on Win32, but make the mouse problem worse
        self.popup = Popup(None, self.text_pane)
        self.tip = Tip(None)

        # get fontmetrics info so we can position the popup
        metrics = self.text_pane.getFontMetrics(self.text_pane.getFont())
        self.dotWidth = metrics.charWidth('.')
        self.textHeight = metrics.getHeight()

        # add some handles to our objects
        self.locals['console'] = self

    def insertText(self, text):
        """insert text at the current caret position"""
        # seems like there should be a better way to do this....
        # might be better as a method on the text component?
        caretPosition = self.text_pane.getCaretPosition()
        self.text_pane.select(caretPosition, caretPosition)
        self.text_pane.replaceSelection(text)
        self.text_pane.setCaretPosition(caretPosition + len(text))

    def getText(self):
        """get text from last line of console"""
        offsets = self.__lastLine()
        text = self.doc.getText(offsets[0], offsets[1]-offsets[0])
        return text.rstrip()

    def getDisplayPoint(self):
        """Get the point where the popup window should be displayed"""
        screenPoint = self.text_pane.getLocationOnScreen()
        caretPoint = self.text_pane.caret.getMagicCaretPosition()

        # BUG: sometimes caretPoint is None
        # To duplicate type "java.aw" and hit '.' to complete selection while popup is visible

        x = screenPoint.getX() + caretPoint.getX() + self.dotWidth
        y = screenPoint.getY() + caretPoint.getY() + self.textHeight
        return Point(int(x),int(y))

    def hide(self, event=None):
        """Hide the popup or tip window if visible"""
        if self.popup.visible:
            self.popup.hide()
        if self.tip.visible:
            self.tip.hide()

    def hideTip(self, event=None):
        self.tip.hide()
        self.insertText(')')

    def showTip(self, event=None):
        # get the display point before writing text
        # otherwise magicCaretPosition is None
        displayPoint = self.getDisplayPoint()

        if self.popup.visible:
            self.popup.hide()
        
        line = self.getText()

        self.insertText('(')
        
        (name, argspec, tip) = jintrospect.getCallTipJava(line, self.locals)

        if tip:
            self.tip.showTip(tip, displayPoint)
            
    def showPopup(self, event=None):
        """show code completion popup"""

        try:
            line = self.getText()
            list = jintrospect.getAutoCompleteList(line, self.locals, includeSingle=self.include_single_underscore_methods, includeDouble=self.include_double_underscore_methods)
            if len(list) > 0:
                self.popup.showMethodCompletionList(list, self.getDisplayPoint())

        except Exception, e:
            print >> sys.stderr, "Error getting completion list: ", e
コード例 #47
0
ファイル: chat.py プロジェクト: k1nk33/PyProject-Yr3
	def clientUI(self):
		'''ClientUI and Widget creation
		'''
		#  Colours
		foreground_colour = Color(30,57,68)
		background_colour = Color(247,246,242)
		window_background = Color(145,190,210)
		#  Borders
		self.border2=BorderFactory.createLineBorder(foreground_colour,1, True)
		#  Fonts
		self.font= Font("Ubuntu Light",  Font.BOLD, 20)
		self.label_font= Font("Ubuntu Light",  Font.BOLD, 17)
		self.label_2_font= Font( "Ubuntu Light",Font.BOLD, 12)
		self.btn_font=Font("Ubuntu Light", Font.BOLD, 15)
		
		#  Set the layout parameters
		self.client_layout=GroupLayout(self.getContentPane())
		self.getContentPane().setLayout(self.client_layout)	
		self.getContentPane().setBackground(window_background)
		self.client_layout.setAutoCreateGaps(True)
		self.client_layout.setAutoCreateContainerGaps(True)
		self.setPreferredSize(Dimension(400, 450))
		
		#  Create widgets and assemble the GUI
		#  Main display area
		self.main_content=JTextPane()
		self.main_content.setBackground(background_colour)
		#self.main_content.setForeground(foreground_colour)
		self.main_content.setEditable(False)
		#  Message entry area  		
		self.message=JTextArea( 2,2, border=self.border2, font=self.label_font, keyPressed=self.returnKeyPress)
		self.message.requestFocusInWindow()	
		self.message.setBackground(background_colour)
		self.message.setForeground(foreground_colour)
		self.message.setLineWrap(True)
		self.message.setWrapStyleWord(True)
		self.message.setBorder(BorderFactory.createEmptyBorder(3,3,3,3))
		self.message.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER,0), self.returnKeyPress) 
		#  BUttons
		quit_btn=JButton("Quit!", actionPerformed=ChatApp().closeEvent, border=self.border2, font=self.btn_font)
		go_btn=JButton("Send", actionPerformed=self.grabText, border=self.border2, font=self.btn_font)
		quit_btn.setBackground(background_colour)
		go_btn.setBackground(background_colour)
		quit_btn.setForeground(foreground_colour)
		go_btn.setForeground(foreground_colour)
		
		# Make scrollable
		self.scroll_content=JScrollPane(self.main_content)
		self.scroll_content.setPreferredSize(Dimension(150,275))
		self.scroll_content.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER)
		self.scroll_content.setViewportView(self.main_content)
		self.scroll_content.setBackground(Color.WHITE)
		self.scroll_message=JScrollPane(self.message)
		self.scroll_message.setPreferredSize(Dimension(150,20))
		self.scroll_message.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS)
		
		# Test user label, still not updating after first round of messages
		self.user_label=JLabel(" Users online : %s "%(str(len(self.no_users))),JLabel.RIGHT, font=self.label_2_font)
		
		#  Assemble the components
		#  Horizontal layout
		self.client_layout.setHorizontalGroup(self.client_layout.createParallelGroup()
				.addComponent(self.scroll_content)
				.addGroup(self.client_layout.createParallelGroup(GroupLayout.Alignment.CENTER)
					.addComponent(self.scroll_message))
				.addGroup(self.client_layout.createSequentialGroup()
					.addComponent(quit_btn)
					.addComponent(go_btn).addGap(20))
				.addGroup(self.client_layout.createParallelGroup()
					.addComponent(self.user_label))
		)
		
		#  Vertical layout
		self.client_layout.setVerticalGroup(self.client_layout.createSequentialGroup()
			.addGroup(self.client_layout.createParallelGroup()
				.addComponent(self.scroll_content))
				.addComponent(self.scroll_message)
				.addGroup(self.client_layout.createParallelGroup()
					.addComponent(quit_btn)
					.addComponent(go_btn))
				.addGroup(self.client_layout.createParallelGroup()
					.addComponent(self.user_label))
		)
		
		#  Finalise the GUI
		self.client_layout.linkSize(SwingConstants.HORIZONTAL, [quit_btn,go_btn, self.user_label])
		self.pack()
		self.message.requestFocusInWindow()
		self.setTitle(">>>   Client %s   <<<"%self.username)
		self.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
		self.setLocationRelativeTo(None)
		self.setVisible(True)
		#  Display the server greeting
		self.appendText('\n'+self.greeting+'\n')
コード例 #48
0
class Console:
    PROMPT = sys.ps1
    PROCESS = sys.ps2
    BANNER = ["Jython Completion Shell", InteractiveConsole.getDefaultBanner()]

    include_single_underscore_methods = False
    include_double_underscore_methods = False

    def __init__(self, namespace=None):
        """
            Create a Jython Console.
            namespace is an optional and should be a dictionary or Map
        """
        self.history = History(self)

        if namespace != None:
            self.locals = namespace
        else:
            self.locals = {}

        self.buffer = []  # buffer for multi-line commands

        self.interp = Interpreter(self, self.locals)
        sys.stdout = StdOutRedirector(self)

        self.text_pane = JTextPane(keyTyped=self.keyTyped,
                                   keyPressed=self.keyPressed)
        self.__initKeyMap()

        self.doc = self.text_pane.document
        self.__propertiesChanged()
        self.__inittext()
        self.initialLocation = self.doc.createPosition(self.doc.length - 1)

        # Don't pass frame to popups. JWindows with null owners are not focusable
        # this fixes the focus problem on Win32, but make the mouse problem worse
        self.popup = Popup(None, self.text_pane)
        self.tip = Tip(None)

        # get fontmetrics info so we can position the popup
        metrics = self.text_pane.getFontMetrics(self.text_pane.getFont())
        self.dotWidth = metrics.charWidth('.')
        self.textHeight = metrics.getHeight()

        # add some handles to our objects
        self.locals['console'] = self

    def insertText(self, text):
        """insert text at the current caret position"""
        # seems like there should be a better way to do this....
        # might be better as a method on the text component?
        caretPosition = self.text_pane.getCaretPosition()
        self.text_pane.select(caretPosition, caretPosition)
        self.text_pane.replaceSelection(text)
        self.text_pane.setCaretPosition(caretPosition + len(text))

    def getText(self):
        """get text from last line of console"""
        offsets = self.__lastLine()
        text = self.doc.getText(offsets[0], offsets[1] - offsets[0])
        return text.rstrip()

    def getDisplayPoint(self):
        """Get the point where the popup window should be displayed"""
        screenPoint = self.text_pane.getLocationOnScreen()
        caretPoint = self.text_pane.caret.getMagicCaretPosition()

        # BUG: sometimes caretPoint is None
        # To duplicate type "java.aw" and hit '.' to complete selection while popup is visible

        x = screenPoint.getX() + caretPoint.getX() + self.dotWidth
        y = screenPoint.getY() + caretPoint.getY() + self.textHeight
        return Point(int(x), int(y))

    def hide(self, event=None):
        """Hide the popup or tip window if visible"""
        if self.popup.visible:
            self.popup.hide()
        if self.tip.visible:
            self.tip.hide()

    def hideTip(self, event=None):
        self.tip.hide()
        self.insertText(')')

    def showTip(self, event=None):
        # get the display point before writing text
        # otherwise magicCaretPosition is None
        displayPoint = self.getDisplayPoint()

        if self.popup.visible:
            self.popup.hide()

        line = self.getText()

        self.insertText('(')

        (name, argspec, tip) = jintrospect.getCallTipJava(line, self.locals)

        if tip:
            self.tip.showTip(tip, displayPoint)

    def showPopup(self, event=None):
        """show code completion popup"""

        try:
            line = self.getText()
            list = jintrospect.getAutoCompleteList(
                line,
                self.locals,
                includeSingle=self.include_single_underscore_methods,
                includeDouble=self.include_double_underscore_methods)
            if len(list) > 0:
                self.popup.showMethodCompletionList(list,
                                                    self.getDisplayPoint())

        except Exception, e:
            print >> sys.stderr, "Error getting completion list: ", e
コード例 #49
0
ファイル: chat.py プロジェクト: k1nk33/PyProject-Yr3
class ChatClient(JFrame):
	
	##  Constructor method, receives the variables from the ChatApp class as parameters
	
	def __init__(self, name, greeting, tn):
		'''Constructor, initialises base class & assigns variables
		'''
		# Call to the super method to take care of the base class(es)
		super(ChatClient, self).__init__()
		#  Assign the relevent variable names
		self.username=name
		self.greeting=greeting
		self.tn = tn
		self.no_users=[]
		#  Initiate the Threaded function for receiving messages
		t1=Thread(target=self.recvFunction)
		#  Set to daemon 
		t1.daemon=True
		t1.start()
		#Call the main UI
		uI=self.clientUI()
		
	##  Main GUI building function
	
	def clientUI(self):
		'''ClientUI and Widget creation
		'''
		#  Colours
		foreground_colour = Color(30,57,68)
		background_colour = Color(247,246,242)
		window_background = Color(145,190,210)
		#  Borders
		self.border2=BorderFactory.createLineBorder(foreground_colour,1, True)
		#  Fonts
		self.font= Font("Ubuntu Light",  Font.BOLD, 20)
		self.label_font= Font("Ubuntu Light",  Font.BOLD, 17)
		self.label_2_font= Font( "Ubuntu Light",Font.BOLD, 12)
		self.btn_font=Font("Ubuntu Light", Font.BOLD, 15)
		
		#  Set the layout parameters
		self.client_layout=GroupLayout(self.getContentPane())
		self.getContentPane().setLayout(self.client_layout)	
		self.getContentPane().setBackground(window_background)
		self.client_layout.setAutoCreateGaps(True)
		self.client_layout.setAutoCreateContainerGaps(True)
		self.setPreferredSize(Dimension(400, 450))
		
		#  Create widgets and assemble the GUI
		#  Main display area
		self.main_content=JTextPane()
		self.main_content.setBackground(background_colour)
		#self.main_content.setForeground(foreground_colour)
		self.main_content.setEditable(False)
		#  Message entry area  		
		self.message=JTextArea( 2,2, border=self.border2, font=self.label_font, keyPressed=self.returnKeyPress)
		self.message.requestFocusInWindow()	
		self.message.setBackground(background_colour)
		self.message.setForeground(foreground_colour)
		self.message.setLineWrap(True)
		self.message.setWrapStyleWord(True)
		self.message.setBorder(BorderFactory.createEmptyBorder(3,3,3,3))
		self.message.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER,0), self.returnKeyPress) 
		#  BUttons
		quit_btn=JButton("Quit!", actionPerformed=ChatApp().closeEvent, border=self.border2, font=self.btn_font)
		go_btn=JButton("Send", actionPerformed=self.grabText, border=self.border2, font=self.btn_font)
		quit_btn.setBackground(background_colour)
		go_btn.setBackground(background_colour)
		quit_btn.setForeground(foreground_colour)
		go_btn.setForeground(foreground_colour)
		
		# Make scrollable
		self.scroll_content=JScrollPane(self.main_content)
		self.scroll_content.setPreferredSize(Dimension(150,275))
		self.scroll_content.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER)
		self.scroll_content.setViewportView(self.main_content)
		self.scroll_content.setBackground(Color.WHITE)
		self.scroll_message=JScrollPane(self.message)
		self.scroll_message.setPreferredSize(Dimension(150,20))
		self.scroll_message.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS)
		
		# Test user label, still not updating after first round of messages
		self.user_label=JLabel(" Users online : %s "%(str(len(self.no_users))),JLabel.RIGHT, font=self.label_2_font)
		
		#  Assemble the components
		#  Horizontal layout
		self.client_layout.setHorizontalGroup(self.client_layout.createParallelGroup()
				.addComponent(self.scroll_content)
				.addGroup(self.client_layout.createParallelGroup(GroupLayout.Alignment.CENTER)
					.addComponent(self.scroll_message))
				.addGroup(self.client_layout.createSequentialGroup()
					.addComponent(quit_btn)
					.addComponent(go_btn).addGap(20))
				.addGroup(self.client_layout.createParallelGroup()
					.addComponent(self.user_label))
		)
		
		#  Vertical layout
		self.client_layout.setVerticalGroup(self.client_layout.createSequentialGroup()
			.addGroup(self.client_layout.createParallelGroup()
				.addComponent(self.scroll_content))
				.addComponent(self.scroll_message)
				.addGroup(self.client_layout.createParallelGroup()
					.addComponent(quit_btn)
					.addComponent(go_btn))
				.addGroup(self.client_layout.createParallelGroup()
					.addComponent(self.user_label))
		)
		
		#  Finalise the GUI
		self.client_layout.linkSize(SwingConstants.HORIZONTAL, [quit_btn,go_btn, self.user_label])
		self.pack()
		self.message.requestFocusInWindow()
		self.setTitle(">>>   Client %s   <<<"%self.username)
		self.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
		self.setLocationRelativeTo(None)
		self.setVisible(True)
		#  Display the server greeting
		self.appendText('\n'+self.greeting+'\n')
	
			
	##  Function responsible for receiving and processing new messages
	
	def recvFunction(self):
		'''A function to control the receiving of data from the connection
		'''
		#  While the connection is available
		while self.tn:
			#  Try to receive data using "<<<" as the delimiter
			try:
				message = self.tn.read_until('<<<')
				#  If a message is received
				if message:
					garb, message=message.split('>>>')
					message, garb = message.split('<<<')
					message = ('\n'+message+'\n')
					#  Call the append text function
					self.appendText(message)
			#  Except if there is no data available		
			except:
				#print('No message')	
				pass
	##  Event driven function to retrieve and send data to the server
	
	def grabText(self, event): 
		'''Function to repeatedly grab new messages entered into the text 
		area and display them in the main text area. Resets the entry area
		'''
		#  Grab the text from the text area
		text=self.message.getText()
		#  Don't allow an empty string through
		if text=='':
			return
		text=text.strip()
		#  Call the append text function
		self.appendText('\nYou : '+text+'\n', self.username)
		#  Reset the text to be empty and grab focus so that it is ready for new text input
		self.message.requestFocusInWindow()
		self.message.setText('')
		#  Send the message to the server
		data=text.encode()
		self.tn.write(data+'\r\n')

	##  Function to handle appending of messages
	
	def appendText(self, message, user=None):
		'''This function takes care of appending any new messages to the content area
		'''
		message_label=JTextArea(message,2,3, font=self.label_2_font)
		#  If this is a message from the grab text function, create a new label, assign it's colours
		if user!=None:
			message_label.setBackground(Color(240,240,240))
			message_label.setForeground(Color(129,129,129))
		#  Otherwise set the format for receive function (no user passed in)	
		else:
			message_label.setBackground(Color(215,215,215))
			message_label.setForeground(Color(40,153,153))
		
		#  Format and style options for the new message labels	
		message_label.setEditable(False)
		message_label.setLineWrap(True)
		message_label.setWrapStyleWord(True)
		message_label.setBorder(BorderFactory.createLineBorder( Color(247,246,242),4))
		#  Sets the positioning of messages
		self.main_content.setCaretPosition(self.main_content.getDocument().getLength())
		doc = self.main_content.getStyledDocument()
		attr=SimpleAttributeSet()
		self.main_content.insertComponent(message_label)
		# Essential for jtextarea to be able to stack message
		doc.insertString( self.main_content.getDocument().getLength(),'\n ', attr)
		# Not sure if needed
		self.main_content.repaint()
		
		###  This is a late edit so it isn't included in the documentation. Basically trying to dynamically update the number
		###  of users label at runtime. Works for incrementing the value but not decrementing it.
		
		print(message)
		#  Only split the message if there are enough values to split (greeting messages differ in format to chat messages)
		try:
			user, text=message.split(' : ')
		except:
			return
			
		#print('Split values are %s %s'%(user, text))
		user=str(user.strip())
		#print(self.no_users)
		#print(user+' : '+text)
		#  If the user already in the list, pass
		if user in self.no_users:
			if text == ('User %s amach sa teach !'%user):
				self.no_users.remove(user)
				print('User % removed'%user)
			
		else:
			#print('User %s not in list'%user)
			if str(user) == 'You':
				#print('User is equal to "You"')
				return 
			self.no_users.append(user)
			print('User appended')
			self.number_users=len(self.no_users)
			#print('Length of user list is '+str(self.number_users))
	
		self.user_label2=JLabel(" Users online : %s "%str(len(self.no_users)),JLabel.RIGHT, font=self.label_2_font)
		#print('Label created')
		#print('Attempt to replace label')
		self.client_layout.replace(self.user_label, self.user_label2) 
		self.user_label = self.user_label2
		self.user_label.repaint()
		self.user_label.revalidate()
		print('Label updated')
	
	##  Function to control return button press in message field

	def returnKeyPress(self,event):
		'''This function creates an object for return key press when inside the message entry area,
		creates an object of KeyAdapter and tests keycode for a match, responds with grab text callback		
		'''
		key_object=Key()
		key_value=key_object.keyPressed(event)
		if key_value == 10:
			self.grabText(event)
コード例 #50
0
    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()
コード例 #51
0
class BurpExtender(
    IBurpExtender,
    IExtensionStateListener,
    IHttpListener,
    ITab,
):
    def registerExtenderCallbacks(self, callbacks):
        self.callbacks = callbacks
        self.helpers = callbacks.helpers

        callbacks.setExtensionName("Burp Scripter Plus")

        stdout = PrintWriter(callbacks.getStdout(), True)
        stdout.println(
            """Successfully loaded Burp Scripter Plus v"""
            + VERSION
            + """\n
Repository @ https://github.com/Acceis/BurpScripterPlus
Send feedback or bug reports on twitter @G4N4P4T1"""
        )

        self.scriptpane = JTextPane()
        self.scriptpane.setFont(
            Font("Monospaced", Font.PLAIN, 12)
        )

        self.scrollpane = JScrollPane()
        self.scrollpane.setViewportView(self.scriptpane)

        self._code = compile("", "<string>", "exec")
        self._script = ""

        script = callbacks.loadExtensionSetting("script")

        if script:
            script = base64.b64decode(script)

            self.scriptpane.document.insertString(
                self.scriptpane.document.length,
                script,
                SimpleAttributeSet(),
            )

            self._script = script
            try:
                self._code = compile(
                    script, "<string>", "exec"
                )
            except Exception as e:
                traceback.print_exc(
                    file=self.callbacks.getStderr()
                )

        callbacks.registerExtensionStateListener(self)
        callbacks.registerHttpListener(self)
        callbacks.customizeUiComponent(
            self.getUiComponent()
        )
        callbacks.addSuiteTab(self)

        self.scriptpane.requestFocus()

    def extensionUnloaded(self):
        try:
            self.callbacks.saveExtensionSetting(
                "script",
                base64.b64encode(
                    self._script.replace(
                        "\nmessage.build_message()", ""
                    )
                ),
            )
        except Exception:
            traceback.print_exc(
                file=self.callbacks.getStderr()
            )
        return

    def processHttpMessage(
        self, toolFlag, messageIsRequest, messageInfo
    ):
        try:
            globals_ = {}
            locals_ = {
                "extender": self,
                "toolFlag": toolFlag,
                "messageInfo": messageInfo,
                "message": get_message(
                    messageInfo,
                    self.helpers,
                    messageIsRequest,
                    self.callbacks,
                ),
            }
            exec(self.script, globals_, locals_)
        except Exception:
            traceback.print_exc(
                file=self.callbacks.getStderr()
            )
        return

    def getTabCaption(self):
        return "Script+"

    def getUiComponent(self):
        return self.scrollpane

    @property
    def script(self):
        end = self.scriptpane.document.length
        _script = (
            self.scriptpane.document.getText(0, end)
            + "\nmessage.build_message()"
        )

        if _script == self._script:
            return self._code

        self._script = _script
        self._code = compile(_script, "<string>", "exec")
        return self._code
コード例 #52
0
class BurpExtender(IBurpExtender, ISessionHandlingAction,
                   IExtensionStateListener, IHttpListener, ITab):
    def registerExtenderCallbacks(self, callbacks):
        self.callbacks = callbacks
        self.helpers = callbacks.helpers

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

        self.scrollpane = JScrollPane()
        self.scrollpane.setViewportView(self.scriptpane)

        self._code = compile('', '<string>', 'exec')
        self._script = ''

        script = callbacks.loadExtensionSetting('script')

        if script:
            script = base64.b64decode(script)

            self.scriptpane.document.insertString(
                self.scriptpane.document.length, script, SimpleAttributeSet())

            self._script = script
            try:
                self._code = compile(script, '<string>', 'exec')
            except Exception as e:
                traceback.print_exc(file=self.callbacks.getStderr())

        callbacks.setExtensionName("Python Scripter (modified)")
        callbacks.registerSessionHandlingAction(self)
        callbacks.registerExtensionStateListener(self)
        callbacks.registerHttpListener(self)
        callbacks.customizeUiComponent(self.getUiComponent())
        callbacks.addSuiteTab(self)

        self.scriptpane.requestFocus()
        return

    def getActionName(self):
        return 'Send to Python Scripter'

    def extensionUnloaded(self):
        try:
            self.callbacks.saveExtensionSetting('script',
                                                base64.b64encode(self._script))
        except Exception:
            traceback.print_exc(file=self.callbacks.getStderr())
        return

    def performAction(self, currentRequest, macroItems):
        self.processHttpMessage(self.callbacks.TOOL_MACRO, 1, currentRequest,
                                macroItems)
        return

    def processHttpMessage(self,
                           toolFlag,
                           messageIsRequest,
                           messageInfo,
                           macroItems=[]):
        try:
            globals_ = {}
            locals_ = {
                'extender': self,
                'callbacks': self.callbacks,
                'helpers': self.helpers,
                'toolFlag': toolFlag,
                'messageIsRequest': messageIsRequest,
                'messageInfo': messageInfo,
                'macroItems': macroItems
            }
            exec(self.script, globals_, locals_)
        except Exception:
            traceback.print_exc(file=self.callbacks.getStderr())
        return

    def getTabCaption(self):
        return 'Script'

    def getUiComponent(self):
        return self.scrollpane

    @property
    def script(self):
        end = self.scriptpane.document.length
        _script = self.scriptpane.document.getText(0, end)

        if _script == self._script:
            return self._code

        self._script = _script
        self._code = compile(_script, '<string>', 'exec')
        return self._code
コード例 #53
0
class BurpExtender(IBurpExtender, IExtensionStateListener, IHttpListener,
                   IProxyListener, ITab):
    def registerExtenderCallbacks(self, callbacks):
        self.callbacks = callbacks
        self.helpers = callbacks.helpers

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

        self.scrollpane = JScrollPane()
        self.scrollpane.setViewportView(self.scriptpane)

        self._code = compile('', '<string>', 'exec')
        self._script = ''

        callbacks.registerExtensionStateListener(self)
        callbacks.registerProxyListener(self)
        callbacks.customizeUiComponent(self.getUiComponent())
        callbacks.addSuiteTab(self)

        self.scriptpane.requestFocus()

    def extensionUnloaded(self):
        try:
            self.callbacks.saveExtensionSetting('script',
                                                base64.b64encode(self._script))
        except Exception:
            traceback.print_exc(file=self.callbacks.getStderr())
        return

    def processProxyMessage(self, messageIsRequest, message):
        try:
            globals_ = {
                'extender': self,
                'callbacks': self.callbacks,
                'helpers': self.helpers
            }
            locals_ = {
                'messageIsRequest': messageIsRequest,
                'message': message
            }
            exec(self.script, globals_, locals_)
        except Exception:
            traceback.print_exc(file=self.callbacks.getStderr())
        return

    def getTabCaption(self):
        return 'Script'

    def getUiComponent(self):
        return self.scrollpane

    @property
    def script(self):
        end = self.scriptpane.document.length
        _script = self.scriptpane.document.getText(0, end)

        if _script == self._script:
            return self._code

        self._script = _script
        self._code = compile(_script, '<string>', 'exec')
        return self._code