def createEditorComponent(self, properties):
        p = JPanel(GridBagLayout())
        p.setBorder(BorderFactory.createEmptyBorder(3, 3, 3, 3))

        gbc = GridBagConstraints()
        gbc.gridx = 0
        gbc.gridy = 0
        gbc.weightx = 0.0
        gbc.weighty = 0.0
        gbc.fill = GridBagConstraints.HORIZONTAL
        gbc.insets = Insets(3, 3, 3, 3)

        p.add(JLabel("Prompt:"), gbc)
        gbc.gridx = 1
        editor = NodePropertiesDialog.createTextArea(properties, self.PROMPT)
        p.add(editor, gbc)

        gbc.gridx, gbc.gridy = 1, 0
        p.add(
            NodePropertiesDialog.createCheckBox(properties, self.WAIT,
                                                "Wait until done"), gbc)

        jtp = JTabbedPane()
        jtp.addTab("Output", p)
        return jtp
Example #2
0
    def __init__(self, controller):
        '''
        Creates a new window displaying a schematic view of an ATF file,
        following the guidelines and mockup agreed with project owners.
        '''

        # Give reference to controller to delegate action response
        self.controller = controller

        # Get list of projects, languages and protocols from config settings
        self.languages = self.controller.config['languages']
        self.protocols = self.controller.config['protocols']
        self.projects = self.controller.config['projects']

        # Make text area occupy all available space and resize with parent
        # window
        self.setLayout(BorderLayout())

        self.mainPanel = JTabbedPane()
        self.mainPanel.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT)
        self.add(self.mainPanel, BorderLayout.CENTER)

        # Set empty dictionary of tab panels
        self.objectTabs = {}

        # Will need scrolling controls
        scrollingArea = JScrollPane(self.mainPanel)

        # Add notice panel
        self.add(self.addNotice(), BorderLayout.NORTH)

        # Add to parent panel
        self.add(scrollingArea, BorderLayout.CENTER)
Example #3
0
    def tagLoad(self):
        # 创建窗口 开始
        self.tabs = JTabbedPane()

        self.settings = JPanel(GridBagLayout())
        self.forward_requests_settings = JPanel(GridBagLayout())
        self.white_list_domain_settings = JPanel(GridBagLayout())

        c = GridBagConstraints()

        # 界面选项卡1-标签加载
        self.tag_1(c)
        self.tag_2(c)

        # 界面选项卡2-标签加载
        self.tag_3(c)
        self.tag_4(c)

        # 界面选项卡3-标签加载
        self.tag_5(c)

        # 添加选项卡
        self.tabs.addTab(u'基本设置', self.settings)
        self.tabs.addTab(u'http请求转发设置', self.forward_requests_settings)
        self.tabs.addTab(u'白名单域名设置', self.white_list_domain_settings)

        self._callbacks.customizeUiComponent(self.tabs)
        self._callbacks.addSuiteTab(self)
Example #4
0
class OptionsPanel(JPanel):
    def __init__(self,view):
        self.view=view
        self.layout=BorderLayout()
        self.parameters=ParametersPanel(self.view)
        self.add(self.parameters,BorderLayout.NORTH)

        self.tabs=JTabbedPane(stateChanged=self.changed)
        self.bar_tab=BarTab(self)
        self.line_tab=LineTab(self)
        self.tabs.addTab('Bar',self.bar_tab)
        self.tabs.addTab('Line',self.line_tab)
        self.add(self.tabs)

        setattr(self, 'global', GlobalPanel(self))
        self.add(getattr(self, 'global'), BorderLayout.SOUTH)
    def get_graph_type(self):
        if self.tabs.selectedIndex==0:
            return 'bar'
        elif self.tabs.selectedIndex==1:
            return 'line'
        else:
            return None

    def update(self):
        self.parameters.update(self.view.stats.params,self.view.stats.options,self.view.stats.defaults)
    def changed(self,event):
        self.view.graph.update()
Example #5
0
    def registerExtenderCallbacks(self, callbacks):
        context.addon = self
        context.version = VERSION
        context.callbacks = callbacks
        context.callbacks.setExtensionName(EXTENSION_NAME)

        api_url = context.settings.load("apiurl", DEFAULT_URI)
        auth_name = context.settings.load("auth_method", AuthMethod.anonymous)

        if auth_name == AuthMethod.email_pass:
            email = context.settings.load("email")
            passwd = context.settings.load("password")
            auth = Auth.email_pass(email, passwd)
        else:
            auth = Auth.anonymous()

        try:
            context.api = YWHApi(api_url, fetcher=BurpHTTP(), auth=auth)
        except APIException:
            context.api = YWHApi(api_url,
                                 fetcher=BurpHTTP(),
                                 auth=Auth.anonymous())

        context.tabs["Programs"] = ProgramsTab()
        context.tabs["Options"] = OptionsTab()
        tab = JTabbedPane(JTabbedPane.TOP)

        for name, panel in context.tabs.items():
            context.callbacks.customizeUiComponent(panel)
            tab.add(name, panel)

        self.getUiComponent = lambda: tab
        context.callbacks.addSuiteTab(self)
        if context.settings.load_bool("autoconnect", False):
            self.connect()
Example #6
0
 def UI(self):
     self.val=""
     self.tabbedPane = JTabbedPane(JTabbedPane.TOP)
     self.panel = JPanel()
     self.tabbedPane.addTab("App Details", None, self.panel, None) # Details of app currently under pentest would be pulled into here through API
     self.panel_1 =  JPanel()
     self.tabbedPane.addTab("Results", None, self.panel_1, None) # passed results would go inside this and connected to reporting system via API
     self.panel_2 =  JPanel()
     self.tabbedPane.addTab("Failed Cases", None, self.panel_2, None) #list of failed tests would go inside this
     self.textField = JTextField()
     self.textField.setBounds(12, 13, 207, 39)
     self.panel.add(self.textField)
     self.textField.setColumns(10)
     self.comboBox = JComboBox()
     self.comboBox.setEditable(True)
     self.comboBox.addItem("Default")
     self.comboBox.addItem("High")
     self.comboBox.addItem("Low")
     self.comboBox.setBounds(46, 65, 130, 28)
     self.comboBox.addActionListener(self)
     self.panel.add(self.comboBox) 
     self.btnNewButton = JButton("Submit")
     self.btnNewButton.setBounds(60, 125, 97, 25)
     self.panel.add(self.btnNewButton)
     editorPane = JEditorPane();
     editorPane.setBounds(12, 35, 1000, 800);
     self.panel_2.add(editorPane);
     self.panel_2.setLayout(BorderLayout())
     return self.tabbedPane
Example #7
0
 def getMainComponent(self):
     # tabsOriginal with request/response viewers
     self._tabsMain = JTabbedPane()
     # Add to the main tabs
     self._tabsMain.addTab("Positions", self._positionsController.getMainComponent())
     self._tabsMain.addTab("Sessions", self._consoleController.getMainComponent())
     self._tabsMain.addTab("Configuration", self._configurationController.getMainComponent())
     return self._tabsMain
Example #8
0
 def getUiComponent(self):
     self.HaEPanel = JPanel()
     self.HaEPanel.setBorder(None)
     self.HaEPanel.setLayout(BorderLayout(0, 0))
     self.panel = JPanel()
     self.HaEPanel.add(self.panel, BorderLayout.NORTH)
     self.panel.setLayout(BorderLayout(0, 0))
     self.tabbedPane = JTabbedPane(JTabbedPane.TOP)
     self.panel.add(self.tabbedPane, BorderLayout.CENTER)
     self.setPanel = JPanel()
     self.tabbedPane.addTab("Set", None, self.setPanel, None)
     self.setPanel.setLayout(BorderLayout(0, 0))
     self.setPanel_1 = JPanel()
     self.setPanel.add(self.setPanel_1, BorderLayout.NORTH)
     self.nameString = JLabel("Name")
     self.setPanel_1.add(self.nameString)
     self.nameTextField = JTextField()
     self.setPanel_1.add(self.nameTextField)
     self.nameTextField.setColumns(10)
     self.regexString = JLabel("Regex")
     self.setPanel_1.add(self.regexString)
     self.regexTextField = JTextField()
     self.setPanel_1.add(self.regexTextField)
     self.regexTextField.setColumns(10)
     self.extractCheckBox = JCheckBox("Extract")
     self.setPanel_1.add(self.extractCheckBox)
     self.highlightCheckBox = JCheckBox("Highlight")
     self.setPanel_1.add(self.highlightCheckBox)
     self.setPanel_2 = JPanel()
     self.setPanel.add(self.setPanel_2)
     self.colorString = JLabel("Color")
     self.setPanel_2.add(self.colorString)
     self.colorTextField = JTextField()
     self.setPanel_2.add(self.colorTextField)
     self.colorTextField.setColumns(5)
     self.addBottun = JButton("Add", actionPerformed=self.addConfig)
     self.setPanel_2.add(self.addBottun)
     self.tipString = JLabel("")
     self.setPanel_2.add(self.tipString)
     self.configPanel = JPanel()
     self.tabbedPane.addTab("Config", None, self.configPanel, None)
     self.configPanel.setLayout(BorderLayout(0, 0))
     self.configString = JLabel("This is config file content.")
     self.configString.setHorizontalAlignment(SwingConstants.CENTER)
     self.configPanel.add(self.configString, BorderLayout.NORTH)
     self.configTextArea = JTextArea()
     self.configTextArea.setEnabled(False)
     self.configTextArea.setTabSize(4)
     self.configTextArea.setLineWrap(True)
     self.configTextArea.setRows(20)
     self.configPanel.add(self.configTextArea, BorderLayout.SOUTH)
     self.scrollPane = JScrollPane(self.configTextArea)
     self.configPanel.add(self.scrollPane, BorderLayout.SOUTH)
     self.reloadButton = JButton("Reload",
                                 actionPerformed=self.reloadConfig)
     self.configPanel.add(self.reloadButton, BorderLayout.CENTER)
     return self.HaEPanel
Example #9
0
 def build_ui(self):
     """
     Builds the tabbed pane within the main extension tab
     Tabs are Config and About objects
     """
     ui_tab = JTabbedPane()
     for tab in self.tabs:
         ui_tab.add(tab.getTabCaption(), tab.getUiComponent())
     return ui_tab
Example #10
0
 def build_ui(self):
     """
     Builds the tabbed pane within the main extension tab
     Tabs are Config and About objects
     """
     ui_tab = JTabbedPane()
     for tab in self.tabs:
         ui_tab.add(tab.getTabCaption(), tab.getUiComponent())
     return ui_tab
    def initGui(self):
        #~ if DEBUG:
            #~ import pdb;
            #~ pdb.set_trace()
        tabPane = JTabbedPane(JTabbedPane.TOP)
        CreditsText = "<html># Burp Custom Deserializer<br/># Copyright (c) 2016, Marco Tinari<br/>#<br/># This program is free software: you can redistribute it and/or modify<br/># it under the terms of the GNU General Public License as published by<br/># the Free Software Foundation, either version 3 of the License, or<br/># (at your option) any later version.<br/>#<br/># This program is distributed in the hope that it will be useful,<br/># but WITHOUT ANY WARRANTY; without even the implied warranty of<br/># MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the<br/># GNU General Public License for more details.<br/>#<br/># You should have received a copy of the GNU General Public License<br/># along with this program.  If not, see <http://www.gnu.org/licenses/>.)<br/></html>"
        label1 = JLabel("<html>Usage:<br>1 - Select the desired encoding functions<br>2 - Enter the name of the parameter in the input field below and press the Apply button!</html>")
        label2 = JLabel(CreditsText)
        panel1 = JPanel()
        #set layout
        panel1.setLayout(GridLayout(11,1))
        panel2 = JPanel()
        panel1.add(label1)
        panel2.add(label2)
        tabPane.addTab("Configuration", panel1)
        tabPane.addTab("Credits", panel2)

        applyButton = JButton('Apply',actionPerformed=self.reloadConf)
        panel1.add(applyButton, BorderLayout.SOUTH)
        
        #define GET/POST/COOKIE radio button
        self.GETparameterTypeRadioButton = JRadioButton('GET parameter')
        self.POSTparameterTypeRadioButton = JRadioButton('POST parameter')
        self.COOKIEparameterTypeRadioButton = JRadioButton('COOKIE parameter')
        self.POSTparameterTypeRadioButton.setSelected(True)
        group = ButtonGroup()
        group.add(self.GETparameterTypeRadioButton)
        group.add(self.POSTparameterTypeRadioButton)
        group.add(self.COOKIEparameterTypeRadioButton)
        self.base64Enabled = JCheckBox("Base64 encode")
        self.URLEnabled = JCheckBox("URL encode")
        self.ASCII2HexEnabled = JCheckBox("ASCII to Hex")
        self.ScannerEnabled = JCheckBox("<html>Enable serialization in Burp Scanner<br>Usage:<br>1.Place unencoded values inside intruder request and define the placeholder positions<br>2.rightclick->Actively scan defined insertion points)</html>")
        self.IntruderEnabled = JCheckBox("<html>Enable serialization in Burp Intruder<br>Usage:<br>1.Place unencoded values inside intruder request and define the placeholder positions<br>2.Start the attack</html>")
        self.parameterName = JTextField("Parameter name goes here...",60)
        
        #set the tooltips
        self.parameterName.setToolTipText("Fill in the parameter name and apply")
        self.base64Enabled.setToolTipText("Enable base64 encoding/decoding")
        self.ASCII2HexEnabled.setToolTipText("Enable ASCII 2 Hex encoding/decoding") 
        self.URLEnabled.setToolTipText("Enable URL encoding/decoding")
        self.IntruderEnabled.setToolTipText("Check this if You want the extension to intercept and modify every request made by the Burp Intruder containing the selected paramter")
        self.ScannerEnabled.setToolTipText("Check this if You want the extension to intercept and modify every request made by the Burp Scanner containing the selected paramter")

        #add checkboxes to the panel            
        panel1.add(self.parameterName)
        panel1.add(self.POSTparameterTypeRadioButton)
        panel1.add(self.GETparameterTypeRadioButton)
        panel1.add(self.COOKIEparameterTypeRadioButton)
        panel1.add(self.base64Enabled)
        panel1.add(self.URLEnabled)
        panel1.add(self.ASCII2HexEnabled)
        panel1.add(self.IntruderEnabled)
        panel1.add(self.ScannerEnabled)
        #assign tabPane
        self.tab = tabPane
Example #12
0
    def initConfigurationTab(self):
        #
        ##  init configuration tab
        #
        self.prevent304 = JCheckBox("Prevent 304 Not Modified status code")
        self.prevent304.setBounds(290, 25, 300, 30)

        self.ignore304 = JCheckBox("Ignore 304/204 status code responses")
        self.ignore304.setBounds(290, 5, 300, 30)
        self.ignore304.setSelected(True)

        self.autoScroll = JCheckBox("Auto Scroll")
        #self.autoScroll.setBounds(290, 45, 140, 30)
        self.autoScroll.setBounds(160, 40, 140, 30)

        self.doUnauthorizedRequest = JCheckBox("Check unauthenticated")
        self.doUnauthorizedRequest.setBounds(290, 45, 300, 30)
        self.doUnauthorizedRequest.setSelected(True)

        startLabel = JLabel("Authorization checks:")
        startLabel.setBounds(10, 10, 140, 30)
        self.startButton = JButton("Autorize is off",
                                   actionPerformed=self.startOrStop)
        self.startButton.setBounds(160, 10, 120, 30)
        self.startButton.setBackground(Color(255, 100, 91, 255))

        self.clearButton = JButton("Clear List",
                                   actionPerformed=self.clearList)
        self.clearButton.setBounds(10, 40, 100, 30)

        self.replaceString = JTextArea("Cookie: Insert=injected; header=here;",
                                       5, 30)
        self.replaceString.setWrapStyleWord(True)
        self.replaceString.setLineWrap(True)
        self.replaceString.setBounds(10, 80, 470, 180)

        self.filtersTabs = JTabbedPane()
        self.filtersTabs.addTab("Enforcement Detector", self.EDPnl)
        self.filtersTabs.addTab("Detector Unauthenticated", self.EDPnlUnauth)
        self.filtersTabs.addTab("Interception Filters", self.filtersPnl)
        self.filtersTabs.addTab("Export", self.exportPnl)

        self.filtersTabs.setBounds(0, 280, 2000, 700)

        self.pnl = JPanel()
        self.pnl.setBounds(0, 0, 1000, 1000)
        self.pnl.setLayout(None)
        self.pnl.add(self.startButton)
        self.pnl.add(self.clearButton)
        self.pnl.add(self.replaceString)
        self.pnl.add(startLabel)
        self.pnl.add(self.autoScroll)
        self.pnl.add(self.ignore304)
        self.pnl.add(self.prevent304)
        self.pnl.add(self.doUnauthorizedRequest)
        self.pnl.add(self.filtersTabs)
Example #13
0
 def build_tabbed_panel(self):
     '''
     Build panel with tabs for each of the settings editable sections.
     '''
     tabbed_pane = JTabbedPane()
     tab_titles = ["General", "Keystrokes", "Languages", "Projects"]
     for title in tab_titles:
         panel = self.build_settings_panel(title.lower())
         tabbed_pane.addTab(title, panel)
     return tabbed_pane
Example #14
0
    def registerExtenderCallbacks(self, callbacks):
        # PDB debugging: connect sys.stdout and sys.stderr to Burp
        # sys.stdout = callbacks.getStdout()
        # sys.stderr = callbacks.getStderr()

        # keep a reference to our callbacks object
        self._callbacks = callbacks

        # obtain an extension helpers object
        self._helpers = callbacks.getHelpers()

        # set extension name
        callbacks.setExtensionName("To Do")

        # create the log and a lock on which to synchronize when adding
        # log entries
        self._log = ArrayList()
        self._lock = Lock()

        # main split pane
        self._splitpane = JSplitPane(JSplitPane.HORIZONTAL_SPLIT)

        # Configuration Tab
        self.initConfigTab()

        # table of to do entries
        logTable = Table(self)
        scrollPane = JScrollPane(logTable)
        self._splitpane.setLeftComponent(scrollPane)

        # Config tab
        self.tabs = JTabbedPane()
        self._configuration = self._callbacks.createMessageEditor(self, False)
        self.tabs.addTab("Configuration", self._configuration.getComponent())
        self._splitpane.setRightComponent(self.panel)

        # customize our UI components
        callbacks.customizeUiComponent(self._splitpane)
        callbacks.customizeUiComponent(logTable)
        callbacks.customizeUiComponent(scrollPane)

        # add the custom tab to Burp's UI
        callbacks.addSuiteTab(self)

        # register ourselves as an HTTP listener
        callbacks.registerHttpListener(self)

        # initialize tabs
        self.initTabs()

        # Print thank you, contact info, etc
        print("Thank you for installing Burp To Do List")
        print("created by Chris Lockard")
        print("https://github.com/chrislockard/BurpToDoList")
        return
Example #15
0
    def set_tabbed_pane(self, functionality_name, test_name):
        description_tab = self.set_description_tab(functionality_name, test_name)
        bugs_tab = self.set_bugs_tab()
        resources_tab = self.set_resource_tab(functionality_name, test_name)
        notes_tab = self.set_notes_tab()

        self.tabbed_pane = JTabbedPane()
        self.tabbed_pane.add("Description", description_tab)
        self.tabbed_pane.add("Bugs", bugs_tab)
        self.tabbed_pane.add("Resources", resources_tab)
        self.tabbed_pane.add("Notes", notes_tab)
Example #16
0
 def build_tabbed_panel(self):
     '''
     Build panel with tabs for each of the settings editable sections.
     '''
     tabbed_pane = JTabbedPane()
     tab_titles = ["General", "Appearance", "Keystrokes", "Languages",
                   "Projects"]
     for title in tab_titles:
         panel = self.build_settings_panel(title.lower())
         tabbed_pane.addTab(title, panel)
     return tabbed_pane
Example #17
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
Example #18
0
    def __init__(self, extender):
        self._callbacks = extender._callbacks
        self._helpers = extender._callbacks.getHelpers()
        self._callbacks.registerScannerCheck(self)
        # Creamos el contenedor de paneles.
        self.contenedor = JTabbedPane()

        # Campos del sub-tab 1 (mash up)
        self._tab1_nombre = JTextField()
        self._tab1_apellido = JTextField()
        self._tab1_FNacimiento = JTextField()
        self._tab1_mascota = JTextField()
        self._tab1_otro = JTextField()

        self._tab1_feedback_ta = JTextArea('This may take a while . . .')
        self._tab1_feedback_ta.setEditable(False)
        self._tab1_feedback_sp = JScrollPane(self._tab1_feedback_ta)

        self._tab1_minsize = JSlider(4, 16, 6)
        self._tab1_minsize.setMajorTickSpacing(1)
        self._tab1_minsize.setPaintLabels(True)

        self._tab1_maxsize = JSlider(4, 16, 10)
        self._tab1_maxsize.setMajorTickSpacing(1)
        self._tab1_maxsize.setPaintLabels(True)

        self._tab1_specialchars = JTextField('!,@,#,$,&,*')
        self._tab1_transformations = JCheckBox('1337 mode')
        self._tab1_firstcapital = JCheckBox('first capital letter')

        # Campos del sub-tab 2 (redirect)
        self._tab2_JTFa = JTextField()
        self._tab2_JTFaa = JTextField()
        self._tab2_JTFb = JTextField()
        self._tab2_JTFbb = JTextField()
        self._tab2_boton = JButton(' Redirect is Off ',
                                   actionPerformed=self.switch_redirect)
        self._tab2_boton.background = Color.lightGray
        self._tab2_encendido = False

        # Campos del sub-tab 3 (loader)
        self._tab3_urls_ta = JTextArea(15, 5)
        self._tab3_urls_sp = JScrollPane(self._tab3_urls_ta)

        # Campos del sub-tab 4 (headers)
        self._tab4_tabla_model = DefaultTableModel()
        self._tab4_headers_dict = {}

        # Campos del sub-tab 5 (reverse ip)
        self._tab5_target = JTextArea(15, 5)
        self._tab5_target_sp = JScrollPane(self._tab5_target)
    def addTabs(self, container):

        head = 'Row,Col,Cell'.split(',')
        junk = 'False,True'.split(',')
        data = [[0, 1], [0, 1]]

        info = JTable(data, head, selectionMode=LSM.SINGLE_SELECTION)
        tab1 = JPanel()
        tab1.add(JScrollPane(JTable(self.settings(info), head)))

        info = JTable(data, head, selectionMode=LSM.SINGLE_INTERVAL_SELECTION)
        tab2 = JPanel()
        tab2.add(JScrollPane(JTable(self.settings(info), head)))

        info = JTable(data,
                      head,
                      selectionMode=LSM.MULTIPLE_INTERVAL_SELECTION)
        tab3 = JPanel()
        tab3.add(JScrollPane(JTable(self.settings(info), head)))

        tabs = JTabbedPane()
        tabs.addTab('Single', tab1)
        tabs.addTab('One Group', tab2)
        tabs.addTab('Multi-Group', tab3)

        container.add(tabs)
Example #20
0
class FormattingVisitor( NodeVisitor ) :

    #---------------------------------------------------------------------------
    # Name: __init__()
    # Role: constructor
    #---------------------------------------------------------------------------
    def __init__( self, url ) :
        self.Tabs   = JTabbedPane()
        self.header = re.compile( '[hH][1-6]$' )
        self.h3Text = ''

    #---------------------------------------------------------------------------
    # Name: head()
    # Role: Invoked when open tag is first seen
    # Note: node.text() = "the combined text of this element and all its children"
    #---------------------------------------------------------------------------
    def head( self, node, depth ) :
        name = node.nodeName()
        if re.match( self.header, name ) :
            self.h3Text = [ '', node.text() ] [ name[ 1 ] == '3' ]

    #---------------------------------------------------------------------------
    # Name: tail()
    # Role: Invoked when end tag is seen
    #---------------------------------------------------------------------------
    def tail( self, node, depth ) :
        name = node.nodeName()
        if self.h3Text and name == 'table' :
            node.attr( 'border', '1' )
            ePane = JEditorPane(
                'text/html',                # mime type
                '<html>' + str( node ),     # content
                editable = 0
            )
            self.Tabs.addTab( self.h3Text, JScrollPane( ePane ) )
#           print 'addTab( "%s" )' % self.h3Text

    #---------------------------------------------------------------------------
    # Name: toString()
    # Role: Return a multi-line string of the JTabbedPane titles
    #---------------------------------------------------------------------------
    def toString( self ) :
        tp = self.Tabs
        return '\n'.join(
            [
                tp.getTitleAt( i )
                for i in range( tp.getTabCount() )
            ]
        )
Example #21
0
    def createGUI(self):
        """ Create overall UI for the extension, with an inner tab """

        # create the panel that border layout lays out a container, arranging and resizing its components to fit
        self.tab = JPanel(BorderLayout())

        # set the extension name
        self.tab.setName("Timing Attack")

        # create a tabbed pane on the top left of the timing attack tab
        self.tabbedPane = JTabbedPane()
        self.tab.add(self.tabbedPane)
        t = tab(self.callbacks)
        self.tabList.append(t)
        self.tabbedPane.addTab("1", self.tabList[0].getFirstTab())
Example #22
0
    def addTabs(self, container):
        align = [['Left', Component.LEFT_ALIGNMENT],
                 ['Center', Component.CENTER_ALIGNMENT],
                 ['Right', Component.RIGHT_ALIGNMENT]]

        names = '1,2,3 being the third number'.split(',')
        tabs = JTabbedPane()
        for aName, aConst in align:
            tab = JPanel()
            tab.setLayout(BoxLayout(tab, BoxLayout.Y_AXIS))
            for name in names:
                tab.add(JButton(name, alignmentX=aConst))
            tabs.addTab(aName, tab)

        container.add(tabs)
Example #23
0
    def	registerExtenderCallbacks(self, callbacks):
        global statement,con

        self._callbacks = callbacks
        self._helpers = callbacks.getHelpers()
        callbacks.setExtensionName("SQLite Logger")

        # select sqlite jdbc jar file
        c = classPathHacker()
        c.addFile("C:\\sqlite-jdbc-3.8.11.2.jar")

        # database filename.
        jdbc_url = "jdbc:sqlite:database" + str(datetime.date.today()) + ".db"
        driver = "org.sqlite.JDBC"
        Class.forName(driver).newInstance()
        con = DriverManager.getConnection(jdbc_url)

        # create table
        self.sql = "CREATE TABLE if not exists log(host text,path text,method text,request text,response text,time text);"
        statement = con.prepareStatement(self.sql)
        statement.executeUpdate()
        
        self._log = ArrayList()
        self._lock = Lock()

        self._splitpane = JSplitPane(JSplitPane.VERTICAL_SPLIT)

        logTable = Table(self)
        scrollPane = JScrollPane(logTable)
        self._splitpane.setLeftComponent(scrollPane)

        tabs = JTabbedPane()
        self._requestViewer = callbacks.createMessageEditor(self, False)
        self._responseViewer = callbacks.createMessageEditor(self, False)
        tabs.addTab("Request", self._requestViewer.getComponent())
        tabs.addTab("Response", self._responseViewer.getComponent())
        self._splitpane.setRightComponent(tabs)

        callbacks.customizeUiComponent(self._splitpane)
        callbacks.customizeUiComponent(logTable)
        callbacks.customizeUiComponent(scrollPane)
        callbacks.customizeUiComponent(tabs)

        callbacks.addSuiteTab(self)

        callbacks.registerHttpListener(self)
        
        return
Example #24
0
    def initTabs(self):
        #
        ##  init autorize tabs
        #
        
        self.logTable = Table(self)

        self.logTable.setAutoCreateRowSorter(True)        

        tableWidth = self.logTable.getPreferredSize().width        
        self.logTable.getColumn("ID").setPreferredWidth(Math.round(tableWidth / 50 * 2))
        self.logTable.getColumn("URL").setPreferredWidth(Math.round(tableWidth / 50 * 24))
        self.logTable.getColumn("Orig. Length").setPreferredWidth(Math.round(tableWidth / 50 * 4))
        self.logTable.getColumn("Modif. Length").setPreferredWidth(Math.round(tableWidth / 50 * 4))
        self.logTable.getColumn("Unauth. Length").setPreferredWidth(Math.round(tableWidth / 50 * 4))
        self.logTable.getColumn("Authorization Enforcement Status").setPreferredWidth(Math.round(tableWidth / 50 * 4))
        self.logTable.getColumn("Authorization Unauth. Status").setPreferredWidth(Math.round(tableWidth / 50 * 4))

        self._splitpane = JSplitPane(JSplitPane.HORIZONTAL_SPLIT)
        self._splitpane.setResizeWeight(1)
        self.scrollPane = JScrollPane(self.logTable)
        self._splitpane.setLeftComponent(self.scrollPane)
        self.scrollPane.getVerticalScrollBar().addAdjustmentListener(autoScrollListener(self))
        self.menuES0 = JCheckBoxMenuItem(self._enfocementStatuses[0],True)
        self.menuES1 = JCheckBoxMenuItem(self._enfocementStatuses[1],True)
        self.menuES2 = JCheckBoxMenuItem(self._enfocementStatuses[2],True)
        self.menuES0.addItemListener(menuTableFilter(self))
        self.menuES1.addItemListener(menuTableFilter(self))
        self.menuES2.addItemListener(menuTableFilter(self))

        copyURLitem = JMenuItem("Copy URL");
        copyURLitem.addActionListener(copySelectedURL(self))
        self.menu = JPopupMenu("Popup")
        self.menu.add(copyURLitem)
        self.menu.add(self.menuES0)
        self.menu.add(self.menuES1)
        self.menu.add(self.menuES2)

        self.tabs = JTabbedPane()
        self._requestViewer = self._callbacks.createMessageEditor(self, False)
        self._responseViewer = self._callbacks.createMessageEditor(self, False)

        self._originalrequestViewer = self._callbacks.createMessageEditor(self, False)
        self._originalresponseViewer = self._callbacks.createMessageEditor(self, False)

        self._unauthorizedrequestViewer = self._callbacks.createMessageEditor(self, False)
        self._unauthorizedresponseViewer = self._callbacks.createMessageEditor(self, False)        

        self.tabs.addTab("Modified Request", self._requestViewer.getComponent())
        self.tabs.addTab("Modified Response", self._responseViewer.getComponent())

        self.tabs.addTab("Original Request", self._originalrequestViewer.getComponent())
        self.tabs.addTab("Original Response", self._originalresponseViewer.getComponent())

        self.tabs.addTab("Unauthenticated Request", self._unauthorizedrequestViewer.getComponent())
        self.tabs.addTab("Unauthenticated Response", self._unauthorizedresponseViewer.getComponent())        

        self.tabs.addTab("Configuration", self.pnl)
        self.tabs.setSelectedIndex(6)
        self._splitpane.setRightComponent(self.tabs)
Example #25
0
    def __init__(self, payload=None, texteditor_factory=None, editable=True):
        self._idx = 0

        self._texteditor_factory = texteditor_factory
        self._textareas = {}
        self._widgets = {}

        self._listener = None

        self.this = JTabbedPane()
        self.this.setUI(SneakTabbedPaneUI(self.this))

        if payload:
            self.refresh(payload)
        self.editable = editable
        self.set_editable(editable)
Example #26
0
    def __init__(self, controller):
        '''
        Creates a new window displaying a schematic view of an ATF file,
        following the guidelines and mockup agreed with project owners.
        '''

        # Give reference to controller to delegate action response
        self.controller = controller

        # Get list of projects, languages and protocols from config settings
        self.languages = self.controller.config['languages']
        self.protocols = self.controller.config['protocols']
        self.projects = self.controller.config['projects']

        # Make text area occupy all available space and resize with parent
        # window
        self.setLayout(BorderLayout())

        self.mainPanel = JTabbedPane()
        self.mainPanel.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT)
        self.add(self.mainPanel, BorderLayout.CENTER)

        # Set empty dictionary of tab panels
        self.objectTabs = {}

        # Will need scrolling controls
        scrollingArea = JScrollPane(self.mainPanel)

        # Add notice panel
        self.add(self.addNotice(), BorderLayout.NORTH)

        # Add to parent panel
        self.add(scrollingArea, BorderLayout.CENTER)
Example #27
0
    def initTabs(self):
        #
        ##  init autorize tabs
        #
        
        self._splitpane = JSplitPane(JSplitPane.HORIZONTAL_SPLIT)
        self.scrollPane = JScrollPane(self.logTable)
        self._splitpane.setLeftComponent(self.scrollPane)
        colorsMenu = JMenu("Paint")
        redMenu = JMenuItem("Red")
        noneMenu = JMenuItem("None")
        greenMenu = JMenuItem("Green")
        redMenu.addActionListener(paintChange(self, "Red"))
        noneMenu.addActionListener(paintChange(self, None))
        greenMenu.addActionListener(paintChange(self, "Green"))
        colorsMenu.add(redMenu)
        colorsMenu.add(noneMenu)
        colorsMenu.add(greenMenu)
        
        
        self.menu = JPopupMenu("Popup")
        self.menu.add(colorsMenu)

        self.tabs = JTabbedPane()
        
        self.tabs.addTab("Request", self._requestViewer.getComponent())
        self.tabs.addTab("Response", self._responseViewer.getComponent())

        self.tabs.addTab("Vulnerability", self.pnl)

        self.tabs.addTab("Project Settings", self.projectSettings)
        
        self.tabs.setSelectedIndex(2)
        self._splitpane.setRightComponent(self.tabs)
Example #28
0
    def __init__(self, controller):
        '''
        Creates a new window displaying a schematic view of an ATF file, 
        following the guidelines and mockup agreed with project owners.
        '''
        
        #Give reference to controller to delegate action response
        self.controller = controller
        
        #Make text area occupy all available space and resize with parent window
        self.setLayout(BorderLayout())
        
        self.mainPanel = JTabbedPane()
        self.mainPanel.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
        self.add(self.mainPanel, BorderLayout.CENTER)
        
        #Set empty dictionary of tab panels
        self.objectTabs = {}

        #Will need scrolling controls
        scrollingArea = JScrollPane(self.mainPanel)
        
        #Add to parent panel
        self.add(scrollingArea, BorderLayout.CENTER)
        
        #TODO: Where to get/store this information?
        self.languages = { "akk-x-stdbab": "Akkadian Standard Babylonian", \
                          "akk": "Akkadian", "sux": "", "a":"", \
                          "akk-x-oldbab":"Akkadian Old Babylonian", "qpc": "", \
                          "na": "", "nb": "", "x/n": "", \
                          "akk-x-neoass": "Akkadian Neo Assyrian"}
Example #29
0
    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)
Example #30
0
    def create_tabbed_pane(self):
        tabbed_pane = JTabbedPane()
        tabbed_pane.add("Advisory", JScrollPane())
        tabbed_pane.add("Request", JScrollPane())
        tabbed_pane.add("Response", JScrollPane())

        self.tabbed_pane = tabbed_pane

        return tabbed_pane
Example #31
0
    def __init__(self):
        self.logTabbedPane = JTabbedPane()
        self.regTab = JPanel()
        self.bypassTab = JPanel()
        self.parkedTab = JPanel()
        self.regCols = ['Vehicle No', 'Owner', 'Admin', 'Date']
        self.parkCols = ['Vehicle No', 'Owner', 'Time']
        self.bypassCol = ['Vehicle No', 'Admin', 'Time']
        self.regTableData = []
        self.parkTableData = []
        self.bypassTableData = []

        self.loadRegData()
        self.loadParkData()
        self.loadBypassData()
        # self.setLayout(BorderLayout())
        self.initComponents()
    def	registerExtenderCallbacks(self, callbacks):
    
        # 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("Reflected XSS Detector")
        
        # create the log and a lock on which to synchronize when adding log entries
        self._log = ArrayList()
        self._lock = Lock()
        
        # main split pane
        self._splitpane = JSplitPane(JSplitPane.VERTICAL_SPLIT)
        
        # table of log entries
        logTable = Table(self)
        scrollPane = JScrollPane(logTable)
        self._splitpane.setLeftComponent(scrollPane)

        logTable.addMouseListener( CMouseListener(self) )

        # tabs with request/response viewers
        tabs = JTabbedPane()
        self._requestViewer = callbacks.createMessageEditor(self, False)
        self._responseViewer = callbacks.createMessageEditor(self, False)
        tabs.addTab("Response", self._responseViewer.getComponent())
        tabs.addTab("Request", self._requestViewer.getComponent())
        self._splitpane.setRightComponent(tabs)
        
        # customize our UI components
        callbacks.customizeUiComponent(self._splitpane)
        callbacks.customizeUiComponent(logTable)
        callbacks.customizeUiComponent(scrollPane)
        callbacks.customizeUiComponent(tabs)
        
        # add the custom tab to Burp's UI
        callbacks.addSuiteTab(self)
        
        # register ourselves as an HTTP listener
        callbacks.registerHttpListener(self)
        
        return
Example #33
0
    def tagLoad(self):
        # 创建窗口 开始
        self.tabs = JTabbedPane()

        self.scan_type_settings = JPanel(GridBagLayout())

        c = GridBagConstraints()

        # 界面选项卡加载
        self.tag_1(c)
        self.tag_2(c)

        # 添加选项卡
        self.tabs.addTab(u'扫描类型设置', self.scan_type_settings)

        self._callbacks.customizeUiComponent(self.tabs)
        self._callbacks.addSuiteTab(self)
Example #34
0
    def __init__(self, cattr):
	self.attr = cattr
	self.cbox = JColorChooser(self.attr.color)
	self.sym_panel = EditSymbolAttr(cattr.sym_prop)
	self.thickness_field = JTextField(str(cattr.thickness),2)
	self.draw_symbol_box = JCheckBox("Draw Symbol?",cattr.draw_symbol)
	self.dps_field = JTextField(str(self.attr.data_per_symbol),2)
	self.dash_box = JComboBox(CurveProps.DASH_TYPES.keys())
	self.dash_box.setSelectedItem(self.attr.dash_type)
	self.dash_box.setBorder(BorderFactory.createTitledBorder("Dash type: (Only JDK2 & Slow!)"))
	tpanelx = JPanel()
	tpanelx.add(self.thickness_field)
	tpanelx.setBorder(BorderFactory.createTitledBorder("curve thickness (integer)"))
	tpanely = JPanel()
	tpanely.add(self.dps_field)
	tpanely.setBorder(BorderFactory.createTitledBorder("data per symbol(integer)"))
	tpanel = JPanel();tpanel.setLayout(GridLayout(2,2));
	tpanel.add(self.draw_symbol_box); tpanel.add(tpanelx);
	tpanel.add(tpanely); tpanel.add(self.dash_box);
	panel1 = JPanel()
	panel1.setLayout(BorderLayout())
	panel1.add(self.cbox,BorderLayout.CENTER)
	panel1.add(tpanel, BorderLayout.SOUTH)
	panel2 = JPanel()
	panel2.setLayout(BorderLayout())
	panel2.add(self.sym_panel,BorderLayout.CENTER)
	tp1 = JTabbedPane()
	tp1.addTab("Curve Attributes",panel1)
	tp1.addTab("Symbol Attributes",panel2)
	tp1.setSelectedComponent(panel1)
	self.setLayout(BorderLayout())
	self.add(tp1,BorderLayout.CENTER)
Example #35
0
 def __init__(self):
     #-----------------------------------------------------------------------
     # Painter instance used to highlight text
     # Note: See hilightTextPane()
     #-----------------------------------------------------------------------
     self.painter = DefaultHighlighter.DefaultHighlightPainter(Color.YELLOW)
     #-----------------------------------------------------------------------
     # Input field containing the text to be highlighted
     #-----------------------------------------------------------------------
     self.textField = JTextField('')
     #-----------------------------------------------------------------------
     # Dictionary, indexed by tab name, with info about tab contents
     #-----------------------------------------------------------------------
     self.tPanes = {}
     #-----------------------------------------------------------------------
     # Tabbed Pane for information to be displayed
     #-----------------------------------------------------------------------
     self.tabs = JTabbedPane(stateChanged=self.tabPicked)
Example #36
0
    def __init__(self, callbacks, script):
        super(ScriptOutputPanel, self).__init__()
        self.callbacks = callbacks
        self.script = script
        self.script.addPropertyChangeListener(self)
        self.tabbedPane = JTabbedPane()
        self._create_output_panel()
        self._create_error_panel()
        self.tabbedPane.addTab('Output', self.outputPanel)
        self.tabbedPane.addTab('Errors', self.errorPanel)
        self.layout = BorderLayout()
        self.add(self.tabbedPane, BorderLayout.CENTER)
        self.script.stdout = EditorFileAdapter(self.outputEditor)
        self.script.stderr = EditorFileAdapter(self.errorEditor)
        self.output_file = None

        # register to be notified when the extension is unloaded so if a output_file ref is in use it can be closed
        callbacks.registerExtensionStateListener(self)
Example #37
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, JScrollPane,
                                 ListSelectionModel, JLabel, JTabbedPane)
        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():
                label1.text += "-" + colors[list1.selectedIndex]

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

        # create a JTabbedPane
        tabs = JTabbedPane()

        # add labels to it
        label1 = JLabel()
        label2 = JLabel()
        tabs.addTab("Tab 1", label1)
        tabs.addTab("Tab 2", label2)

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

        panel.add(spl)
        return panel
Example #38
0
    def registerExtenderCallbacks(self, callbacks):
        self._callbacks = callbacks
        self._helpers = callbacks.getHelpers()

        callbacks.setExtensionName("Beautifier")

        self.loadOptions()

        self.mainTabbedPane = JTabbedPane()
        self.beautifierPanel = BeautifierPanel()
        self.beautifierOptionsPanel = BeautifierOptionsPanel(self)
        self.mainTabbedPane.addTab("Beautify", self.beautifierPanel)
        self.mainTabbedPane.addTab("Options", self.beautifierOptionsPanel)

        self.selectedMessage = None

        callbacks.addSuiteTab(self)
        callbacks.registerMessageEditorTabFactory(self)
        callbacks.registerHttpListener(self)
        callbacks.registerContextMenuFactory(self)
Example #39
0
    def __init__(self):
        self.running = True
        menuBar = JMenuBar()

        menu = JMenu("File")
        menu.add(OpenAction(self))
        menu.add(CloseAction(self))
        menu.addSeparator()
        menu.add(QuitAction(self))
        self.addWindowListener(ProfelisWindowAdapter(self))
        menuBar.add(menu)

        self.setJMenuBar(menuBar)

        self.contentPane = JPanel()
        self.contentPane.layout = GridBagLayout()
        constraints = GridBagConstraints()

        self.blastLocation = JTextField(
            System.getProperty("user.home") + "/blast")
        self.databaseLocation = JTextField(
            System.getProperty("user.home") + "/blast/db")
        self.projects = JTabbedPane()

        constraints.gridx, constraints.gridy = 0, 0
        constraints.gridwidth, constraints.gridheight = 1, 1
        constraints.fill = GridBagConstraints.NONE
        constraints.weightx, constraints.weighty = 0, 0
        self.contentPane.add(JLabel("Blast Location"), constraints)
        constraints.gridx, constraints.gridy = 1, 0
        constraints.fill = GridBagConstraints.HORIZONTAL
        constraints.weightx, constraints.weighty = 1, 0
        self.contentPane.add(self.blastLocation, constraints)
        constraints.gridx, constraints.gridy = 2, 0
        constraints.fill = GridBagConstraints.NONE
        constraints.weightx, constraints.weighty = 0, 0
        self.contentPane.add(JButton(BlastAction(self)), constraints)
        constraints.gridx, constraints.gridy = 3, 0
        constraints.fill = GridBagConstraints.NONE
        constraints.weightx, constraints.weighty = 0, 0
        self.contentPane.add(JLabel("Database Location"), constraints)
        constraints.gridx, constraints.gridy = 4, 0
        constraints.fill = GridBagConstraints.HORIZONTAL
        constraints.weightx, constraints.weighty = 1, 0
        self.contentPane.add(self.databaseLocation, constraints)
        constraints.gridx, constraints.gridy = 5, 0
        constraints.fill = GridBagConstraints.NONE
        constraints.weightx, constraints.weighty = 0, 0
        self.contentPane.add(JButton(DatabaseAction(self)), constraints)
        constraints.gridx, constraints.gridy = 0, 1
        constraints.gridwidth, constraints.gridheight = 6, 1
        constraints.fill = GridBagConstraints.BOTH
        constraints.weightx, constraints.weighty = 1, 1
        self.contentPane.add(self.projects, constraints)
Example #40
0
    def set_pane(self):
        status = JTextArea()
        status.setLineWrap(True)
        status.setText("Nothing selected")
        self.status = status

        self.pane = JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
                               JScrollPane(self.tree), JTabbedPane())

        self.pane.setDividerLocation(310)
        self.pane.getLeftComponent().setMinimumSize(Dimension(310, 300))
Example #41
0
    def initConfigurationTab(self):
        #
        ##  init configuration tab
        #
        self.prevent304 = JCheckBox("Prevent 304 Not Modified status code")
        self.prevent304.setBounds(290, 25, 300, 30)

        self.ignore304 = JCheckBox("Ignore 304/204 status code responses")
        self.ignore304.setBounds(290, 5, 300, 30)
        self.ignore304.setSelected(True)

        self.autoScroll = JCheckBox("Auto Scroll")
        #self.autoScroll.setBounds(290, 45, 140, 30)
        self.autoScroll.setBounds(160, 40, 140, 30)

        self.doUnauthorizedRequest = JCheckBox("Check unauthenticated")
        self.doUnauthorizedRequest.setBounds(290, 45, 300, 30)
        self.doUnauthorizedRequest.setSelected(True)

        startLabel = JLabel("Authorization checks:")
        startLabel.setBounds(10, 10, 140, 30)
        self.startButton = JButton("Autorize is off",actionPerformed=self.startOrStop)
        self.startButton.setBounds(160, 10, 120, 30)
        self.startButton.setBackground(Color(255, 100, 91, 255))

        self.clearButton = JButton("Clear List",actionPerformed=self.clearList)
        self.clearButton.setBounds(10, 40, 100, 30)

        self.replaceString = JTextArea("Cookie: Insert=injected; header=here;", 5, 30)
        self.replaceString.setWrapStyleWord(True);
        self.replaceString.setLineWrap(True)
        self.replaceString.setBounds(10, 80, 470, 180)

        self.filtersTabs = JTabbedPane()
        self.filtersTabs.addTab("Enforcement Detector", self.EDPnl)
        self.filtersTabs.addTab("Detector Unauthenticated", self.EDPnlUnauth)
        self.filtersTabs.addTab("Interception Filters", self.filtersPnl)
        self.filtersTabs.addTab("Export", self.exportPnl)

        self.filtersTabs.setBounds(0, 280, 2000, 700)

        self.pnl = JPanel()
        self.pnl.setBounds(0, 0, 1000, 1000);
        self.pnl.setLayout(None);
        self.pnl.add(self.startButton)
        self.pnl.add(self.clearButton)
        self.pnl.add(self.replaceString)
        self.pnl.add(startLabel)
        self.pnl.add(self.autoScroll)
        self.pnl.add(self.ignore304)
        self.pnl.add(self.prevent304)
        self.pnl.add(self.doUnauthorizedRequest)
        self.pnl.add(self.filtersTabs)
Example #42
0
    def registerExtenderCallbacks(self, callbacks):

        callbacks.registerContextMenuFactory(self)

        self._callbacks = callbacks
        self._helpers = callbacks.getHelpers()

        callbacks.setExtensionName(EXTENSION_NAME)

        # Construct UI
        insets = Insets(3, 3, 3, 3)
        self._messageEditor = callbacks.createMessageEditor(self, True)
        attackPanel = self._constructAttackPanel(
            insets, self._messageEditor.getComponent())
        resultsPanel = self._constructResultsPanel(insets)
        aboutPanel = self._constructAboutPanel(insets)
        self._tabbedPane = JTabbedPane()
        self._tabbedPane.addTab("Attack", attackPanel)
        self._tabbedPane.addTab("Results", resultsPanel)
        self._tabbedPane.addTab("About", aboutPanel)
        callbacks.addSuiteTab(self)
Example #43
0
    def __init__(self, interface):
        self.interface = interface
        
        self.frame = JFrame("Python Window")

        tabs = JTabbedPane()

        # Create Interactive Pane
        interactive_pane = JPanel(BorderLayout())        
        scrollpane = JScrollPane()
        inputPanel = JPanel()
        inputPanel.layout = GridLayout(1, 1)
        self.check_disabled = LockManager()
        self.input = InteractiveInput(self.check_disabled, self.runcode)
        self.input.component.document.addDocumentListener(self)
        inputPanel.add(self.input.component)
        self.outputpane = OutputPane()
        scrollpane.viewport.view = self.outputpane.textpane
        interactive_pane.add(scrollpane, BorderLayout.CENTER)
        interactive_pane.add(inputPanel, BorderLayout.PAGE_END)

        # Create Script Pane
        script_pane = JPanel(BorderLayout())
        scrollpane = JScrollPane()
        self.script_area = script_area = InputPane()
        line_numbers = LineNumbering(self.script_area.component)
        scrollpane.viewport.view = self.script_area.component
        scrollpane.rowHeaderView = line_numbers.component
        script_pane.add(scrollpane, BorderLayout.CENTER)
        
        tabs.addTab("Interactive", interactive_pane)
        tabs.addTab("Script", script_pane)
        
        self.frame.add(tabs)
        self.frame.size = 500, 600
        self.frame.visible = False
        self.component = None
        self.make_menubar()
        self.history = InputHistory()
Example #44
0
    def __init__(self,view):
        self.view=view
        self.layout=BorderLayout()
        self.parameters=ParametersPanel(self.view)
        self.add(self.parameters,BorderLayout.NORTH)

        self.tabs=JTabbedPane(stateChanged=self.changed)
        self.bar_tab=BarTab(self)
        self.line_tab=LineTab(self)
        self.tabs.addTab('Bar',self.bar_tab)
        self.tabs.addTab('Line',self.line_tab)
        self.add(self.tabs)

        setattr(self, 'global', GlobalPanel(self))
        self.add(getattr(self, 'global'), BorderLayout.SOUTH)
    def createRequestTabs(self, requestResponse):
        requestTabs = JTabbedPane()
        requestViewer = self._extender._callbacks.createMessageEditor(self._extender, False)
        responseViewer = self._extender._callbacks.createMessageEditor(self._extender, False)
        requestTabs.addTab("Request", requestViewer.getComponent())
        requestTabs.addTab("Response", responseViewer.getComponent())
        self._extender._callbacks.customizeUiComponent(requestTabs)
        # TODO: consider adding the results when clicking the tab (lazy instantiation) since it can get slow
        requestViewer.setMessage(requestResponse.getRequest(), True)
        if requestResponse.getResponse():
            responseViewer.setMessage(requestResponse.getResponse(), False)
            requestTabs.setSelectedIndex(1)

        return requestTabs
Example #46
0
    def initTabs(self):
        #
        ##  init autorize tabs
        #
        
        self.logTable = Table(self)
        self._splitpane = JSplitPane(JSplitPane.HORIZONTAL_SPLIT)
        self._splitpane.setResizeWeight(1)
        self.scrollPane = JScrollPane(self.logTable)
        self._splitpane.setLeftComponent(self.scrollPane)
        self.scrollPane.getVerticalScrollBar().addAdjustmentListener(autoScrollListener(self))
        self.menuES0 = JCheckBoxMenuItem(self._enfocementStatuses[0],True)
        self.menuES1 = JCheckBoxMenuItem(self._enfocementStatuses[1],True)
        self.menuES2 = JCheckBoxMenuItem(self._enfocementStatuses[2],True)
        self.menuES0.addItemListener(menuTableFilter(self))
        self.menuES1.addItemListener(menuTableFilter(self))
        self.menuES2.addItemListener(menuTableFilter(self))

        copyURLitem = JMenuItem("Copy URL");
        copyURLitem.addActionListener(copySelectedURL(self))
        self.menu = JPopupMenu("Popup")
        self.menu.add(copyURLitem)
        self.menu.add(self.menuES0)
        self.menu.add(self.menuES1)
        self.menu.add(self.menuES2)

        self.tabs = JTabbedPane()
        self._requestViewer = self._callbacks.createMessageEditor(self, False)
        self._responseViewer = self._callbacks.createMessageEditor(self, False)

        self._originalrequestViewer = self._callbacks.createMessageEditor(self, False)
        self._originalresponseViewer = self._callbacks.createMessageEditor(self, False)

        self.tabs.addTab("Modified Request", self._requestViewer.getComponent())
        self.tabs.addTab("Modified Response", self._responseViewer.getComponent())

        self.tabs.addTab("Original Request", self._originalrequestViewer.getComponent())
        self.tabs.addTab("Original Response", self._originalresponseViewer.getComponent())

        self.tabs.addTab("Configuration", self.pnl)
        self.tabs.setSelectedIndex(4)
        self._splitpane.setRightComponent(self.tabs)
Example #47
0
    def	registerExtenderCallbacks(self, callbacks):
    
        # 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("Otter")
        
        # create the log and a lock on which to synchronize when adding log entries
        self._log = ArrayList()
        self._lock = Lock()
       
        # main split pane for log entries and request/response viewing
        self._settingPanel = JPanel()
        self._logPane = JSplitPane(JSplitPane.VERTICAL_SPLIT)

        # setup settings pane ui
        self._settingPanel.setBounds(0,0,1000,1000)
        self._settingPanel.setLayout(None)

        self._isRegexp = JCheckBox("Use regexp for matching.")
        self._isRegexp.setBounds(10, 10, 220, 20)

        matchLabel = JLabel("String to Match:")
        matchLabel.setBounds(10, 40, 200, 20)
        self._matchString = JTextArea("User 1 Session Information")
        self._matchString.setWrapStyleWord(True)
        self._matchString.setLineWrap(True)
        matchString = JScrollPane(self._matchString)
        matchString.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED)
        matchString.setBounds(10, 60, 400, 200)

        replaceLabel = JLabel("String to Replace:")
        replaceLabel.setBounds(10, 270, 200, 20)
        self._replaceString = JTextArea("User 2 Session Information")
        self._replaceString.setWrapStyleWord(True)
        self._replaceString.setLineWrap(True)
        replaceString = JScrollPane(self._replaceString)
        replaceString.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED)
        replaceString.setBounds(10, 290, 400, 200)

        self._settingPanel.add(self._isRegexp)
        self._settingPanel.add(matchLabel)
        self._settingPanel.add(matchString)
        self._settingPanel.add(replaceLabel)
        self._settingPanel.add(replaceString)
        
        # table of log entries
        logTable = Table(self)
        logTable.getColumnModel().getColumn(0).setPreferredWidth(700)
        logTable.getColumnModel().getColumn(1).setPreferredWidth(150)
        logTable.getColumnModel().getColumn(2).setPreferredWidth(100)
        logTable.getColumnModel().getColumn(3).setPreferredWidth(130)
        logTable.getColumnModel().getColumn(4).setPreferredWidth(100)
        logTable.getColumnModel().getColumn(5).setPreferredWidth(130)
        scrollPane = JScrollPane(logTable)
        self._logPane.setLeftComponent(scrollPane)

        # tabs with request/response viewers
        logTabs = JTabbedPane()
        self._origRequestViewer = callbacks.createMessageEditor(self, False)
        self._origResponseViewer = callbacks.createMessageEditor(self, False)
        self._modRequestViewer = callbacks.createMessageEditor(self, False)
        self._modResponseViewer = callbacks.createMessageEditor(self, False)
        logTabs.addTab("Original Request", self._origRequestViewer.getComponent())
        logTabs.addTab("Original Response", self._origResponseViewer.getComponent())
        logTabs.addTab("Modified Request", self._modRequestViewer.getComponent())
        logTabs.addTab("Modified Response", self._modResponseViewer.getComponent())
        self._logPane.setRightComponent(logTabs)
        
        # top most tab interface that seperates log entries from settings
        maintabs = JTabbedPane()
        maintabs.addTab("Log Entries", self._logPane)
        maintabs.addTab("Settings", self._settingPanel)
        self._maintabs = maintabs
       
        # customize the UI components
        callbacks.customizeUiComponent(maintabs)
        
        # add the custom tab to Burp's UI
        callbacks.addSuiteTab(self)
        
        # register ourselves as an HTTP listener
        callbacks.registerHttpListener(self)
        
        return
Example #48
0
class BurpExtender(IBurpExtender, ITab, IHttpListener, IMessageEditorController, AbstractTableModel, IContextMenuFactory):

    def registerExtenderCallbacks(self, callbacks):
        # 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("Autorize")
        
        # create the log and a lock on which to synchronize when adding log entries
        self._log = ArrayList()
        self._lock = Lock()
        self._enfocementStatuses = ["Authorization bypass!","Authorization enforced??? (please configure enforcement detector)","Authorization enforced!"]
        self.intercept = 0

        self.initInterceptionFilters()

        self.initEnforcementDetector()

        self.initEnforcementDetectorUnauthorized()

        self.initExport()

        self.initConfigurationTab()

        self.initTabs()
        
        self.initCallbacks()

        self.currentRequestNumber = 1
        
        print "Thank you for installing Autorize v0.12 extension"
        print "Created by Barak Tawily" 
        print "Contributors: Barak Tawily, Federico Dotta"
        print "\nGithub:\nhttps://github.com/Quitten/Autorize"
        return
        

    def initExport(self):
        #
        ## init enforcement detector tab
        #

        exportLType = JLabel("File Type:")
        exportLType.setBounds(10, 10, 100, 30)
       
        exportLES = JLabel("Enforcement Statuses:")
        exportLES.setBounds(10, 50, 160, 30)

        exportFileTypes = ["HTML","CSV"]
        self.exportType = JComboBox(exportFileTypes)
        self.exportType.setBounds(100, 10, 200, 30)

        exportES = ["All Statuses", self._enfocementStatuses[0], self._enfocementStatuses[1], self._enfocementStatuses[2]]
        self.exportES = JComboBox(exportES)
        self.exportES.setBounds(100, 50, 200, 30)

        exportLES = JLabel("Statuses:")
        exportLES.setBounds(10, 50, 100, 30)

        self.exportButton = JButton("Export",actionPerformed=self.export)
        self.exportButton.setBounds(390, 25, 100, 30)

        self.exportPnl = JPanel()
        self.exportPnl.setLayout(None);
        self.exportPnl.setBounds(0, 0, 1000, 1000);
        self.exportPnl.add(exportLType)
        self.exportPnl.add(self.exportType)
        self.exportPnl.add(exportLES)
        self.exportPnl.add(self.exportES)
        self.exportPnl.add(self.exportButton)

    def initEnforcementDetector(self):
        #
        ## init enforcement detector tab
        #

        # These two variable appears to be unused...
        self.EDFP = ArrayList()
        self.EDCT = ArrayList()

        EDLType = JLabel("Type:")
        EDLType.setBounds(10, 10, 140, 30)

        EDLContent = JLabel("Content:")
        EDLContent.setBounds(10, 50, 140, 30)

        EDLabelList = JLabel("Filter List:")
        EDLabelList.setBounds(10, 165, 140, 30)

        EDStrings = ["Headers (simple string): (enforced message headers contains)", "Headers (regex): (enforced messege headers contains)", "Body (simple string): (enforced messege body contains)", "Body (regex): (enforced messege body contains)", "Full request (simple string): (enforced messege contains)", "Full request (regex): (enforced messege contains)", "Content-Length: (constant Content-Length number of enforced response)"]
        self.EDType = JComboBox(EDStrings)
        self.EDType.setBounds(80, 10, 430, 30)
       
        self.EDText = JTextArea("", 5, 30)
        self.EDText.setBounds(80, 50, 300, 110)

        self.EDModel = DefaultListModel();
        self.EDList = JList(self.EDModel);
        self.EDList.setBounds(80, 175, 300, 110)
        self.EDList.setBorder(LineBorder(Color.BLACK))

        self.EDAdd = JButton("Add filter",actionPerformed=self.addEDFilter)
        self.EDAdd.setBounds(390, 85, 120, 30)
        self.EDDel = JButton("Remove filter",actionPerformed=self.delEDFilter)
        self.EDDel.setBounds(390, 210, 120, 30)

        self.EDPnl = JPanel()
        self.EDPnl.setLayout(None);
        self.EDPnl.setBounds(0, 0, 1000, 1000);
        self.EDPnl.add(EDLType)
        self.EDPnl.add(self.EDType)
        self.EDPnl.add(EDLContent)
        self.EDPnl.add(self.EDText)
        self.EDPnl.add(self.EDAdd)
        self.EDPnl.add(self.EDDel)
        self.EDPnl.add(EDLabelList)
        self.EDPnl.add(self.EDList)

    def initEnforcementDetectorUnauthorized(self):
        #
        ## init enforcement detector tab
        #

        EDLType = JLabel("Type:")
        EDLType.setBounds(10, 10, 140, 30)

        EDLContent = JLabel("Content:")
        EDLContent.setBounds(10, 50, 140, 30)

        EDLabelList = JLabel("Filter List:")
        EDLabelList.setBounds(10, 165, 140, 30)

        EDStrings = ["Headers (simple string): (enforced message headers contains)", "Headers (regex): (enforced messege headers contains)", "Body (simple string): (enforced messege body contains)", "Body (regex): (enforced messege body contains)", "Full request (simple string): (enforced messege contains)", "Full request (regex): (enforced messege contains)", "Content-Length: (constant Content-Length number of enforced response)"]
        self.EDTypeUnauth = JComboBox(EDStrings)
        self.EDTypeUnauth.setBounds(80, 10, 430, 30)
       
        self.EDTextUnauth = JTextArea("", 5, 30)
        self.EDTextUnauth.setBounds(80, 50, 300, 110)

        self.EDModelUnauth = DefaultListModel();
        self.EDListUnauth = JList(self.EDModelUnauth);
        self.EDListUnauth.setBounds(80, 175, 300, 110)
        self.EDListUnauth.setBorder(LineBorder(Color.BLACK))

        self.EDAddUnauth = JButton("Add filter",actionPerformed=self.addEDFilterUnauth)
        self.EDAddUnauth.setBounds(390, 85, 120, 30)
        self.EDDelUnauth = JButton("Remove filter",actionPerformed=self.delEDFilterUnauth)
        self.EDDelUnauth.setBounds(390, 210, 120, 30)

        self.EDPnlUnauth = JPanel()
        self.EDPnlUnauth.setLayout(None);
        self.EDPnlUnauth.setBounds(0, 0, 1000, 1000);
        self.EDPnlUnauth.add(EDLType)
        self.EDPnlUnauth.add(self.EDTypeUnauth)
        self.EDPnlUnauth.add(EDLContent)
        self.EDPnlUnauth.add(self.EDTextUnauth)
        self.EDPnlUnauth.add(self.EDAddUnauth)
        self.EDPnlUnauth.add(self.EDDelUnauth)
        self.EDPnlUnauth.add(EDLabelList)
        self.EDPnlUnauth.add(self.EDListUnauth)        

    def initInterceptionFilters(self):
        #
        ##  init interception filters tab
        #

        IFStrings = ["Scope items only: (Content is not required)","URL Contains (simple string): ","URL Contains (regex): ","URL Not Contains (simple string): ","URL Not Contains (regex): "]
        self.IFType = JComboBox(IFStrings)
        self.IFType.setBounds(80, 10, 430, 30)
       
        self.IFModel = DefaultListModel();
        self.IFList = JList(self.IFModel);
        self.IFList.setBounds(80, 175, 300, 110)
        self.IFList.setBorder(LineBorder(Color.BLACK))

        self.IFText = JTextArea("", 5, 30)
        self.IFText.setBounds(80, 50, 300, 110)

        IFLType = JLabel("Type:")
        IFLType.setBounds(10, 10, 140, 30)

        IFLContent = JLabel("Content:")
        IFLContent.setBounds(10, 50, 140, 30)

        IFLabelList = JLabel("Filter List:")
        IFLabelList.setBounds(10, 165, 140, 30)

        self.IFAdd = JButton("Add filter",actionPerformed=self.addIFFilter)
        self.IFAdd.setBounds(390, 85, 120, 30)
        self.IFDel = JButton("Remove filter",actionPerformed=self.delIFFilter)
        self.IFDel.setBounds(390, 210, 120, 30)

        self.filtersPnl = JPanel()
        self.filtersPnl.setLayout(None);
        self.filtersPnl.setBounds(0, 0, 1000, 1000);
        self.filtersPnl.add(IFLType)
        self.filtersPnl.add(self.IFType)
        self.filtersPnl.add(IFLContent)
        self.filtersPnl.add(self.IFText)
        self.filtersPnl.add(self.IFAdd)
        self.filtersPnl.add(self.IFDel)
        self.filtersPnl.add(IFLabelList)
        self.filtersPnl.add(self.IFList)


    def initConfigurationTab(self):
        #
        ##  init configuration tab
        #
        self.prevent304 = JCheckBox("Prevent 304 Not Modified status code")
        self.prevent304.setBounds(290, 25, 300, 30)

        self.ignore304 = JCheckBox("Ignore 304/204 status code responses")
        self.ignore304.setBounds(290, 5, 300, 30)
        self.ignore304.setSelected(True)

        self.autoScroll = JCheckBox("Auto Scroll")
        #self.autoScroll.setBounds(290, 45, 140, 30)
        self.autoScroll.setBounds(160, 40, 140, 30)

        self.doUnauthorizedRequest = JCheckBox("Check unauthenticated")
        self.doUnauthorizedRequest.setBounds(290, 45, 300, 30)
        self.doUnauthorizedRequest.setSelected(True)

        startLabel = JLabel("Authorization checks:")
        startLabel.setBounds(10, 10, 140, 30)
        self.startButton = JButton("Autorize is off",actionPerformed=self.startOrStop)
        self.startButton.setBounds(160, 10, 120, 30)
        self.startButton.setBackground(Color(255, 100, 91, 255))

        self.clearButton = JButton("Clear List",actionPerformed=self.clearList)
        self.clearButton.setBounds(10, 40, 100, 30)

        self.replaceString = JTextArea("Cookie: Insert=injected; header=here;", 5, 30)
        self.replaceString.setWrapStyleWord(True);
        self.replaceString.setLineWrap(True)
        self.replaceString.setBounds(10, 80, 470, 180)

        self.filtersTabs = JTabbedPane()
        self.filtersTabs.addTab("Enforcement Detector", self.EDPnl)
        self.filtersTabs.addTab("Detector Unauthenticated", self.EDPnlUnauth)
        self.filtersTabs.addTab("Interception Filters", self.filtersPnl)
        self.filtersTabs.addTab("Export", self.exportPnl)

        self.filtersTabs.setBounds(0, 280, 2000, 700)

        self.pnl = JPanel()
        self.pnl.setBounds(0, 0, 1000, 1000);
        self.pnl.setLayout(None);
        self.pnl.add(self.startButton)
        self.pnl.add(self.clearButton)
        self.pnl.add(self.replaceString)
        self.pnl.add(startLabel)
        self.pnl.add(self.autoScroll)
        self.pnl.add(self.ignore304)
        self.pnl.add(self.prevent304)
        self.pnl.add(self.doUnauthorizedRequest)
        self.pnl.add(self.filtersTabs)

    def initTabs(self):
        #
        ##  init autorize tabs
        #
        
        self.logTable = Table(self)

        self.logTable.setAutoCreateRowSorter(True)        

        tableWidth = self.logTable.getPreferredSize().width        
        self.logTable.getColumn("ID").setPreferredWidth(Math.round(tableWidth / 50 * 2))
        self.logTable.getColumn("URL").setPreferredWidth(Math.round(tableWidth / 50 * 24))
        self.logTable.getColumn("Orig. Length").setPreferredWidth(Math.round(tableWidth / 50 * 4))
        self.logTable.getColumn("Modif. Length").setPreferredWidth(Math.round(tableWidth / 50 * 4))
        self.logTable.getColumn("Unauth. Length").setPreferredWidth(Math.round(tableWidth / 50 * 4))
        self.logTable.getColumn("Authorization Enforcement Status").setPreferredWidth(Math.round(tableWidth / 50 * 4))
        self.logTable.getColumn("Authorization Unauth. Status").setPreferredWidth(Math.round(tableWidth / 50 * 4))

        self._splitpane = JSplitPane(JSplitPane.HORIZONTAL_SPLIT)
        self._splitpane.setResizeWeight(1)
        self.scrollPane = JScrollPane(self.logTable)
        self._splitpane.setLeftComponent(self.scrollPane)
        self.scrollPane.getVerticalScrollBar().addAdjustmentListener(autoScrollListener(self))
        self.menuES0 = JCheckBoxMenuItem(self._enfocementStatuses[0],True)
        self.menuES1 = JCheckBoxMenuItem(self._enfocementStatuses[1],True)
        self.menuES2 = JCheckBoxMenuItem(self._enfocementStatuses[2],True)
        self.menuES0.addItemListener(menuTableFilter(self))
        self.menuES1.addItemListener(menuTableFilter(self))
        self.menuES2.addItemListener(menuTableFilter(self))

        copyURLitem = JMenuItem("Copy URL");
        copyURLitem.addActionListener(copySelectedURL(self))
        self.menu = JPopupMenu("Popup")
        self.menu.add(copyURLitem)
        self.menu.add(self.menuES0)
        self.menu.add(self.menuES1)
        self.menu.add(self.menuES2)

        self.tabs = JTabbedPane()
        self._requestViewer = self._callbacks.createMessageEditor(self, False)
        self._responseViewer = self._callbacks.createMessageEditor(self, False)

        self._originalrequestViewer = self._callbacks.createMessageEditor(self, False)
        self._originalresponseViewer = self._callbacks.createMessageEditor(self, False)

        self._unauthorizedrequestViewer = self._callbacks.createMessageEditor(self, False)
        self._unauthorizedresponseViewer = self._callbacks.createMessageEditor(self, False)        

        self.tabs.addTab("Modified Request", self._requestViewer.getComponent())
        self.tabs.addTab("Modified Response", self._responseViewer.getComponent())

        self.tabs.addTab("Original Request", self._originalrequestViewer.getComponent())
        self.tabs.addTab("Original Response", self._originalresponseViewer.getComponent())

        self.tabs.addTab("Unauthenticated Request", self._unauthorizedrequestViewer.getComponent())
        self.tabs.addTab("Unauthenticated Response", self._unauthorizedresponseViewer.getComponent())        

        self.tabs.addTab("Configuration", self.pnl)
        self.tabs.setSelectedIndex(6)
        self._splitpane.setRightComponent(self.tabs)

    def initCallbacks(self):
        #
        ##  init callbacks
        #

        # customize our UI components
        self._callbacks.customizeUiComponent(self._splitpane)
        self._callbacks.customizeUiComponent(self.logTable)
        self._callbacks.customizeUiComponent(self.scrollPane)
        self._callbacks.customizeUiComponent(self.tabs)
        self._callbacks.customizeUiComponent(self.filtersTabs)
        self._callbacks.registerContextMenuFactory(self)
        # add the custom tab to Burp's UI
        self._callbacks.addSuiteTab(self)


    #
    ## Events functions
    #
    def startOrStop(self, event):
        if self.startButton.getText() == "Autorize is off":
            self.startButton.setText("Autorize is on")
            self.startButton.setBackground(Color.GREEN)
            self.intercept = 1
            self._callbacks.registerHttpListener(self)
        else:
            self.startButton.setText("Autorize is off")
            self.startButton.setBackground(Color(255, 100, 91, 255))
            self.intercept = 0
            self._callbacks.removeHttpListener(self)

    def addEDFilter(self, event):
        typeName = self.EDType.getSelectedItem().split(":")[0]
        self.EDModel.addElement(typeName + ": " + self.EDText.getText())

    def delEDFilter(self, event):
        index = self.EDList.getSelectedIndex();
        if not index == -1:
            self.EDModel.remove(index);

    def addEDFilterUnauth(self, event):
        typeName = self.EDTypeUnauth.getSelectedItem().split(":")[0]
        self.EDModelUnauth.addElement(typeName + ": " + self.EDTextUnauth.getText())

    def delEDFilterUnauth(self, event):
        index = self.EDListUnauth.getSelectedIndex();
        if not index == -1:
            self.EDModelUnauth.remove(index);            

    def addIFFilter(self, event):
        typeName = self.IFType.getSelectedItem().split(":")[0]
        self.IFModel.addElement(typeName + ": " + self.IFText.getText())

    def delIFFilter(self, event):
        index = self.IFList.getSelectedIndex();
        if not index == -1:
            self.IFModel.remove(index);

    def clearList(self, event):
        self._lock.acquire()
        oldSize = self._log.size()
        self._log.clear()
        self.fireTableRowsDeleted(0, oldSize - 1)
        self._lock.release()

    def export(self, event):
        if self.exportType.getSelectedItem() == "HTML":
            self.exportToHTML()
        else:
            self.exportToCSV()

    def exportToCSV(self):
        parentFrame = JFrame()
        fileChooser = JFileChooser()
        fileChooser.setSelectedFile(File("AutorizeReprort.csv"));
        fileChooser.setDialogTitle("Save Autorize Report")
        userSelection = fileChooser.showSaveDialog(parentFrame)
        if userSelection == JFileChooser.APPROVE_OPTION:
            fileToSave = fileChooser.getSelectedFile()

        enforcementStatusFilter = self.exportES.getSelectedItem()
        csvContent = "id\tURL\tOriginal length\tModified length\tUnauthorized length\tAuthorization Enforcement Status\tAuthorization Unauthenticated Status\n"

        for i in range(0,self._log.size()):

            if enforcementStatusFilter == "All Statuses":
                csvContent += "%d\t%s\t%d\t%d\t%d\t%s\t%s\n" % (self._log.get(i)._id,self._log.get(i)._url, len(self._log.get(i)._originalrequestResponse.getResponse()) if self._log.get(i)._originalrequestResponse != None else 0, len(self._log.get(i)._requestResponse.getResponse()) if self._log.get(i)._requestResponse != None else 0, len(self._log.get(i)._unauthorizedRequestResponse.getResponse()) if self._log.get(i)._unauthorizedRequestResponse != None else 0, self._log.get(i)._enfocementStatus, self._log.get(i)._enfocementStatusUnauthorized)
                
            else:
                if (enforcementStatusFilter == self._log.get(i)._enfocementStatus) or (enforcementStatusFilter == self._log.get(i)._enfocementStatusUnauthorized):
                    csvContent += "%d\t%s\t%d\t%d\t%d\t%s\t%s\n" % (self._log.get(i)._id,self._log.get(i)._url, len(self._log.get(i)._originalrequestResponse.getResponse()) if self._log.get(i)._originalrequestResponse != None else 0, len(self._log.get(i)._requestResponse.getResponse()) if self._log.get(i)._requestResponse != None else 0, len(self._log.get(i)._unauthorizedRequestResponse.getResponse()) if self._log.get(i)._unauthorizedRequestResponse != None else 0, self._log.get(i)._enfocementStatus, self._log.get(i)._enfocementStatusUnauthorized)
        
        f = open(fileToSave.getAbsolutePath(), 'w')
        f.writelines(csvContent)
        f.close()


    def exportToHTML(self):
        parentFrame = JFrame()
        fileChooser = JFileChooser()
        fileChooser.setSelectedFile(File("AutorizeReprort.html"));
        fileChooser.setDialogTitle("Save Autorize Report")
        userSelection = fileChooser.showSaveDialog(parentFrame)
        if userSelection == JFileChooser.APPROVE_OPTION:
            fileToSave = fileChooser.getSelectedFile()

        enforcementStatusFilter = self.exportES.getSelectedItem()
        htmlContent = """<html><title>Autorize Report by Barak Tawily</title>
        <style>
        .datagrid table { border-collapse: collapse; text-align: left; width: 100%; }
         .datagrid {font: normal 12px/150% Arial, Helvetica, sans-serif; background: #fff; overflow: hidden; border: 1px solid #006699; -webkit-border-radius: 3px; -moz-border-radius: 3px; border-radius: 3px; }
         .datagrid table td, .datagrid table th { padding: 3px 10px; }
         .datagrid table thead th {background:-webkit-gradient( linear, left top, left bottom, color-stop(0.05, #006699), color-stop(1, #00557F) );background:-moz-linear-gradient( center top, #006699 5%, #00557F 100% );filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#006699', endColorstr='#00557F');background-color:#006699; color:#FFFFFF; font-size: 15px; font-weight: bold; border-left: 1px solid #0070A8; } .datagrid table thead th:first-child { border: none; }.datagrid table tbody td { color: #00496B; border-left: 1px solid #E1EEF4;font-size: 12px;font-weight: normal; }.datagrid table tbody .alt td { background: #E1EEF4; color: #00496B; }.datagrid table tbody td:first-child { border-left: none; }.datagrid table tbody tr:last-child td { border-bottom: none; }.datagrid table tfoot td div { border-top: 1px solid #006699;background: #E1EEF4;} .datagrid table tfoot td { padding: 0; font-size: 12px } .datagrid table tfoot td div{ padding: 2px; }.datagrid table tfoot td ul { margin: 0; padding:0; list-style: none; text-align: right; }.datagrid table tfoot  li { display: inline; }.datagrid table tfoot li a { text-decoration: none; display: inline-block;  padding: 2px 8px; margin: 1px;color: #FFFFFF;border: 1px solid #006699;-webkit-border-radius: 3px; -moz-border-radius: 3px; border-radius: 3px; background:-webkit-gradient( linear, left top, left bottom, color-stop(0.05, #006699), color-stop(1, #00557F) );background:-moz-linear-gradient( center top, #006699 5%, #00557F 100% );filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#006699', endColorstr='#00557F');background-color:#006699; }.datagrid table tfoot ul.active, .datagrid table tfoot ul a:hover { text-decoration: none;border-color: #006699; color: #FFFFFF; background: none; background-color:#00557F;}div.dhtmlx_window_active, div.dhx_modal_cover_dv { position: fixed !important; }
        table {
        width: 100%;
        table-layout: fixed;
        }
        td {
            border: 1px solid #35f;
            overflow: hidden;
            text-overflow: ellipsis;
        }
        td.a {
            width: 13%;
            white-space: nowrap;
        }
        td.b {
            width: 9%;
            word-wrap: break-word;
        }
        </style>
        <body>
        <h1>Autorize Report<h1>
        <div class="datagrid"><table>
        <thead><tr><th width=\"3%\">ID</th><th width=\"48%\">URL</th><th width=\"9%\">Original length</th><th width=\"9%\">Modified length</th><th width=\"9%\">Unauthorized length</th><th width=\"11%\">Authorization Enforcement Status</th><th width=\"11%\">Authorization Unauthenticated Status</th></tr></thead>
        <tbody>"""

        for i in range(0,self._log.size()):
            color_modified = ""
            if self._log.get(i)._enfocementStatus == self._enfocementStatuses[0]:
                color_modified = "red"
            if self._log.get(i)._enfocementStatus == self._enfocementStatuses[1]:
                color_modified = "yellow"
            if self._log.get(i)._enfocementStatus == self._enfocementStatuses[2]:
                color_modified = "LawnGreen"

            color_unauthorized = ""
            if self._log.get(i)._enfocementStatusUnauthorized == self._enfocementStatuses[0]:
                color_unauthorized = "red"
            if self._log.get(i)._enfocementStatusUnauthorized == self._enfocementStatuses[1]:
                color_unauthorized = "yellow"
            if self._log.get(i)._enfocementStatusUnauthorized == self._enfocementStatuses[2]:
                color_unauthorized = "LawnGreen"

            if enforcementStatusFilter == "All Statuses":
                htmlContent += "<tr><td>%d</td><td><a href=\"%s\">%s</a></td><td>%d</td><td>%d</td><td>%d</td><td bgcolor=\"%s\">%s</td><td bgcolor=\"%s\">%s</td></tr>" % (self._log.get(i)._id,self._log.get(i)._url,self._log.get(i)._url, len(self._log.get(i)._originalrequestResponse.getResponse()) if self._log.get(i)._originalrequestResponse != None else 0, len(self._log.get(i)._requestResponse.getResponse()) if self._log.get(i)._requestResponse != None else 0, len(self._log.get(i)._unauthorizedRequestResponse.getResponse()) if self._log.get(i)._unauthorizedRequestResponse != None else 0, color_modified, self._log.get(i)._enfocementStatus, color_unauthorized, self._log.get(i)._enfocementStatusUnauthorized)
            else:
                if (enforcementStatusFilter == self._log.get(i)._enfocementStatus) or (enforcementStatusFilter == self._log.get(i)._enfocementStatusUnauthorized):
                    htmlContent += "<tr><td>%d</td><td><a href=\"%s\">%s</a></td><td>%d</td><td>%d</td><td>%d</td><td bgcolor=\"%s\">%s</td><td bgcolor=\"%s\">%s</td></tr>" % (self._log.get(i)._id,self._log.get(i)._url,self._log.get(i)._url, len(self._log.get(i)._originalrequestResponse.getResponse()) if self._log.get(i)._originalrequestResponse != None else 0, len(self._log.get(i)._requestResponse.getResponse()) if self._log.get(i)._requestResponse != None else 0, len(self._log.get(i)._unauthorizedRequestResponse.getResponse()) if self._log.get(i)._unauthorizedRequestResponse != None else 0, color_modified, self._log.get(i)._enfocementStatus, color_unauthorized, self._log.get(i)._enfocementStatusUnauthorized)

        htmlContent += "</tbody></table></div></body></html>"
        f = open(fileToSave.getAbsolutePath(), 'w')
        f.writelines(htmlContent)
        f.close()




    #
    # implement IContextMenuFactory
    #
    def createMenuItems(self, invocation):
        responses = invocation.getSelectedMessages();
        if responses > 0:
            ret = LinkedList()
            requestMenuItem = JMenuItem("Send request to Autorize");
            cookieMenuItem = JMenuItem("Send cookie to Autorize");
            requestMenuItem.addActionListener(handleMenuItems(self,responses[0], "request"))
            cookieMenuItem.addActionListener(handleMenuItems(self, responses[0], "cookie"))   
            ret.add(requestMenuItem);
            ret.add(cookieMenuItem);
            return(ret);
        return null;


    #
    # implement ITab
    #
    def getTabCaption(self):
        return "Autorize"
    
    def getUiComponent(self):
        return self._splitpane
        
    #
    # extend AbstractTableModel
    #
    
    def getRowCount(self):
        try:
            return self._log.size()
        except:
            return 0

    def getColumnCount(self):
        return 7

    def getColumnName(self, columnIndex):
        if columnIndex == 0:
            return "ID"
        if columnIndex == 1:
            return "URL"
        if columnIndex == 2:
            return "Orig. Length"            
        if columnIndex == 3:
            return "Modif. Length" 
        if columnIndex == 4:
            return "Unauth. Length"           
        if columnIndex == 5:
            return "Authorization Enforcement Status"
        if columnIndex == 6:
            return "Authorization Unauth. Status"
        return ""

    def getColumnClass(self, columnIndex):
        if columnIndex == 0:
            return Integer
        if columnIndex == 1:
            return String
        if columnIndex == 2:
            return Integer           
        if columnIndex == 3:
            return Integer 
        if columnIndex == 4:
            return Integer          
        if columnIndex == 5:
            return String
        if columnIndex == 6:
            return String
        return String

    def getValueAt(self, rowIndex, columnIndex):
        logEntry = self._log.get(rowIndex)
        if columnIndex == 0:
            return logEntry._id
        if columnIndex == 1:
            return logEntry._url.toString()
        if columnIndex == 2:
            return len(logEntry._originalrequestResponse.getResponse())
        if columnIndex == 3:
            return len(logEntry._requestResponse.getResponse())
        if columnIndex == 4:
            if logEntry._unauthorizedRequestResponse != None:
                return len(logEntry._unauthorizedRequestResponse.getResponse())
            else:
                #return "-"
                return 0
        if columnIndex == 5:
            return logEntry._enfocementStatus   
        if columnIndex == 6:
            return logEntry._enfocementStatusUnauthorized        
        return ""

    #
    # implement IMessageEditorController
    # this allows our request/response viewers to obtain details about the messages being displayed
    #
    
    def getHttpService(self):
        return self._currentlyDisplayedItem.getHttpService()

    def getRequest(self):
        return self._currentlyDisplayedItem.getRequest()

    def getResponse(self):
        return self._currentlyDisplayedItem.getResponse()


    #
    # implement IHttpListener
    #
    def processHttpMessage(self, toolFlag, messageIsRequest, messageInfo):

        #if (self.intercept == 1) and (toolFlag != self._callbacks.TOOL_EXTENDER):
        if (self.intercept == 1) and (toolFlag == self._callbacks.TOOL_PROXY):
            if self.prevent304.isSelected():
                if messageIsRequest:
                    requestHeaders = list(self._helpers.analyzeRequest(messageInfo).getHeaders())
                    newHeaders = list()
                    found = 0
                    for header in requestHeaders:
                        if not "If-None-Match:" in header and not "If-Modified-Since:" in header:
                            newHeaders.append(header)
                            found = 1
                    if found == 1:
                        requestInfo = self._helpers.analyzeRequest(messageInfo)
                        bodyBytes = messageInfo.getRequest()[requestInfo.getBodyOffset():]
                        bodyStr = self._helpers.bytesToString(bodyBytes)
                        messageInfo.setRequest(self._helpers.buildHttpMessage(newHeaders, bodyStr))


            if not messageIsRequest:
                if not self.replaceString.getText() in self._helpers.analyzeRequest(messageInfo).getHeaders():
                    if self.ignore304.isSelected():
                        firstHeader = self._helpers.analyzeResponse(messageInfo.getResponse()).getHeaders()[0]
                        if "304" in firstHeader or "204" in firstHeader:
                           return
                    if self.IFList.getModel().getSize() == 0:
                        self.checkAuthorization(messageInfo,self._helpers.analyzeResponse(messageInfo.getResponse()).getHeaders(),self.doUnauthorizedRequest.isSelected())
                    else:
                        urlString = str(self._helpers.analyzeRequest(messageInfo).getUrl())
                        
                        do_the_check = 1

                        for i in range(0,self.IFList.getModel().getSize()):

                            if self.IFList.getModel().getElementAt(i).split(":")[0] == "Scope items only":
                                currentURL = URL(urlString)
                                if not self._callbacks.isInScope(currentURL):
                                    do_the_check = 0
                            if self.IFList.getModel().getElementAt(i).split(":")[0] == "URL Contains (simple string)":
                                if self.IFList.getModel().getElementAt(i)[30:] not in urlString:
                                    do_the_check = 0
                            if self.IFList.getModel().getElementAt(i).split(":")[0] == "URL Contains (regex)":
                                regex_string = self.IFList.getModel().getElementAt(i)[22:]
                                p = re.compile(regex_string, re.IGNORECASE)
                                if not p.search(urlString):
                                    do_the_check = 0  
                            if self.IFList.getModel().getElementAt(i).split(":")[0] == "URL Not Contains (simple string)":
                                if self.IFList.getModel().getElementAt(i)[34:] in urlString:
                                    do_the_check = 0
                            if self.IFList.getModel().getElementAt(i).split(":")[0] == "URL Not Contains (regex)":
                                regex_string = self.IFList.getModel().getElementAt(i)[26:]
                                p = re.compile(regex_string, re.IGNORECASE)
                                if p.search(urlString):
                                    do_the_check = 0                                                                       

                        if do_the_check:
                            self.checkAuthorization(messageInfo,self._helpers.analyzeResponse(messageInfo.getResponse()).getHeaders(),self.doUnauthorizedRequest.isSelected())

        return

    def sendRequestToAutorizeWork(self,messageInfo):

        if messageInfo.getResponse() == None:
            message = self.makeMessage(messageInfo,False,False)
            requestResponse = self.makeRequest(messageInfo, message)
            self.checkAuthorization(requestResponse,self._helpers.analyzeResponse(requestResponse.getResponse()).getHeaders(),self.doUnauthorizedRequest.isSelected())
        else:
            self.checkAuthorization(messageInfo,self._helpers.analyzeResponse(messageInfo.getResponse()).getHeaders(),self.doUnauthorizedRequest.isSelected())


    def makeRequest(self, messageInfo, message):
        requestURL = self._helpers.analyzeRequest(messageInfo).getUrl()
        return self._callbacks.makeHttpRequest(self._helpers.buildHttpService(str(requestURL.getHost()), int(requestURL.getPort()), requestURL.getProtocol() == "https"), message)

    def makeMessage(self, messageInfo, removeOrNot, authorizeOrNot):
        requestInfo = self._helpers.analyzeRequest(messageInfo)
        headers = requestInfo.getHeaders()
        if removeOrNot:
            headers = list(headers)
            removeHeaders = ArrayList()
            removeHeaders.add(self.replaceString.getText()[0:self.replaceString.getText().index(":")])

            for header in headers[:]:
                for removeHeader in removeHeaders:
                    if removeHeader in header:
                        headers.remove(header)

            if authorizeOrNot:
                headers.append(self.replaceString.getText())

        msgBody = messageInfo.getRequest()[requestInfo.getBodyOffset():]
        return self._helpers.buildHttpMessage(headers, msgBody)

    def checkBypass(self,oldStatusCode,newStatusCode,oldContentLen,newContentLen,filters,requestResponse):

        analyzedResponse = self._helpers.analyzeResponse(requestResponse.getResponse())
        impression = ""

        if oldStatusCode == newStatusCode:
            if oldContentLen == newContentLen:
                impression = self._enfocementStatuses[0]
            else:

                auth_enforced = 1
                
                for filter in filters:

                    if str(filter).startswith("Headers (simple string): "):
                        if not(filter[25:] in self._helpers.bytesToString(requestResponse.getResponse()[0:analyzedResponse.getBodyOffset()])):
                            auth_enforced = 0

                    if str(filter).startswith("Headers (regex): "):
                        regex_string = filter[17:]
                        p = re.compile(regex_string, re.IGNORECASE)
                        if not p.search(self._helpers.bytesToString(requestResponse.getResponse()[0:analyzedResponse.getBodyOffset()])):
                            auth_enforced = 0

                    if str(filter).startswith("Body (simple string): "):
                        if not(filter[22:] in self._helpers.bytesToString(requestResponse.getResponse()[analyzedResponse.getBodyOffset():])):
                            auth_enforced = 0

                    if str(filter).startswith("Body (regex): "):
                        regex_string = filter[14:]
                        p = re.compile(regex_string, re.IGNORECASE)
                        if not p.search(self._helpers.bytesToString(requestResponse.getResponse()[analyzedResponse.getBodyOffset():])):
                            auth_enforced = 0

                    if str(filter).startswith("Full request (simple string): "):
                        if not(filter[30:] in self._helpers.bytesToString(requestResponse.getResponse())):
                            auth_enforced = 0

                    if str(filter).startswith("Full request (regex): "):
                        regex_string = filter[22:]
                        p = re.compile(regex_string, re.IGNORECASE)
                        if not p.search(self._helpers.bytesToString(requestResponse.getResponse())):
                            auth_enforced = 0

                    if str(filter).startswith("Content-Length: "):
                        if newContentLen != filter:
                            auth_enforced = 0
                
                if auth_enforced:
                    impression = self._enfocementStatuses[2]
                else:
                    impression = self._enfocementStatuses[1]
                         
        else:
            impression = self._enfocementStatuses[2]

        return impression

    def checkAuthorization(self, messageInfo, originalHeaders, checkUnauthorized):
        message = self.makeMessage(messageInfo,True,True)
        requestResponse = self.makeRequest(messageInfo, message)
        analyzedResponse = self._helpers.analyzeResponse(requestResponse.getResponse())
        
        oldStatusCode = originalHeaders[0]
        newStatusCode = analyzedResponse.getHeaders()[0]
        oldContentLen = self.getContentLength(originalHeaders)
        newContentLen = self.getContentLength(analyzedResponse.getHeaders())

        # Check unauthorized request
        if checkUnauthorized:
            messageUnauthorized = self.makeMessage(messageInfo,True,False)
            requestResponseUnauthorized = self.makeRequest(messageInfo, messageUnauthorized)
            analyzedResponseUnauthorized = self._helpers.analyzeResponse(requestResponseUnauthorized.getResponse())  
            statusCodeUnauthorized = analyzedResponseUnauthorized.getHeaders()[0]
            contentLenUnauthorized = self.getContentLength(analyzedResponseUnauthorized.getHeaders())

        EDFilters = self.EDModel.toArray()
        impression = self.checkBypass(oldStatusCode,newStatusCode,oldContentLen,newContentLen,EDFilters,requestResponse)

        if checkUnauthorized:
            EDFiltersUnauth = self.EDModelUnauth.toArray()
            impressionUnauthorized = self.checkBypass(oldStatusCode,statusCodeUnauthorized,oldContentLen,contentLenUnauthorized,EDFiltersUnauth,requestResponseUnauthorized)

        self._lock.acquire()
        
        row = self._log.size()
        
        if checkUnauthorized:
            self._log.add(LogEntry(self.currentRequestNumber,self._callbacks.saveBuffersToTempFiles(requestResponse), self._helpers.analyzeRequest(requestResponse).getUrl(),messageInfo,impression,self._callbacks.saveBuffersToTempFiles(requestResponseUnauthorized),impressionUnauthorized)) # same requests not include again.
        else:
            self._log.add(LogEntry(self.currentRequestNumber,self._callbacks.saveBuffersToTempFiles(requestResponse), self._helpers.analyzeRequest(requestResponse).getUrl(),messageInfo,impression,None,"Disabled")) # same requests not include again.
        
        self.fireTableRowsInserted(row, row)
        self.currentRequestNumber = self.currentRequestNumber + 1
        self._lock.release()
        
    def getContentLength(self, analyzedResponseHeaders):
        for header in analyzedResponseHeaders:
            if "Content-Length:" in header:
                return header;
        return "null"

    def getCookieFromMessage(self, messageInfo):
        headers = list(self._helpers.analyzeRequest(messageInfo.getRequest()).getHeaders())
        for header in headers:
            if "Cookie:" in header:
                return header
        return None
Example #49
0
    def __init__(self):
        super(WorkHelper, self).__init__()
        self.clipboard = Toolkit.getDefaultToolkit().getSystemClipboard()

#############################################################
# Layout:
        layout = GroupLayout(self.getContentPane())
        self.getContentPane().setLayout(layout)
        layout.setAutoCreateGaps(True)
        layout.setAutoCreateContainerGaps(True)
#############################################################

#############################################################
# Frame Area:
        Larea1 = JLabel("InputArea:")

        Sarea1 = JScrollPane()
        self.area1 = JTextArea()
        self.area1.setToolTipText("Input Area")
        self.area1.setEditable(True)
        self.area1.setBorder(BorderFactory.createLineBorder(Color.gray))
        Sarea1.setPreferredSize(Dimension(300,100))
        Sarea1.getViewport().setView((self.area1))

        bClear = JButton("Clear", actionPerformed=self.bClear)
        bClear.setToolTipText("Clears the text form both Input and Output text Areas")

        bCopyToInput = JButton("Copy to Input", actionPerformed=self.bCopyToInput)
        bCopyToInput.setToolTipText("Copy the text from the Output Area to the Input Area for further Operations")
        
        self.cCtClipB = JCheckBox("Auto-Copy");
        self.cCtClipB.setToolTipText("When 'Checked' after the Categories are created they will added to the clipboard")
        self.cCtClipB.setSelected(1)
        
        Larea2 = JLabel("OutputArea:")
        
        Sarea2 = JScrollPane()
        self.area2 = JTextArea()
        self.area2.setToolTipText("Output Area")
        self.area2.setEditable(False)
        self.area2.setBorder(BorderFactory.createLineBorder(Color.gray))
        Sarea2.setPreferredSize(Dimension(300,100))
        Sarea2.getViewport().setView((self.area2))

#############################################################
# Tabbed Area:
        tabPane = JTabbedPane(JTabbedPane.TOP)
        self.getContentPane().add(tabPane)
        #####################################################
        # Text Edit pane
        panel_TEdit = JPanel()
        layout2 = GroupLayout(panel_TEdit)
        layout2.setAutoCreateGaps(True)
        layout2.setAutoCreateContainerGaps(True)
        panel_TEdit.setLayout(layout2)
        
        bRemoveNBSP_L = JButton("Clean LText", actionPerformed=self.bRemoveNBSP_L)
        bRemoveNBSP_L.setToolTipText("Removes Spaces, Tabs from the start of every text line from the input Area")
        bRemoveNBSP_R = JButton("Clean RText", actionPerformed=self.bRemoveNBSP_R)
        bRemoveNBSP_R.setToolTipText("Removes Spaces, Tabs from the end of every text line from the input Area")
    
        
        self.ReplaceThis = JTextField()
        self.ReplaceThis = JTextField(maximumSize=Dimension(120,25))
        self.ReplaceThis.setToolTipText("Text to be replaced")

        self.ReplaceThat = JTextField()
        self.ReplaceThat = JTextField(maximumSize=Dimension(120,25))
        self.ReplaceThat.setToolTipText("Text to be placed")

        bSandReplace = JButton("Replace Text", actionPerformed=self.bSandReplace)
        bSandReplace.setToolTipText("Replace the text from This with Text from That in the Text from the Input Area and displays it in the Output Area")

        bRemNumbers = JButton("Rem Numbers", actionPerformed=self.RemNumbers)
        bRemNumbers.setToolTipText("Removes numbers from the start of every line")
        #####################################################
        # Dimension pane
        panel_Dimensions = JPanel()
        layout3 = GroupLayout(panel_Dimensions)
        layout3.setAutoCreateGaps(True)
        layout3.setAutoCreateContainerGaps(True)
        panel_Dimensions.setLayout(layout3)
        
        
        self.cCurly = JCheckBox("Curly");
        self.cCurly.setToolTipText("When 'Checked' Curly Brackets will surround the Categories")
        self.cCurly.setSelected(1)

        self.cSemiC = JCheckBox("SemiColumn");
        self.cSemiC.setToolTipText("When 'Checked' after the Categories are created at the end will be a semicolomn")
        self.cSemiC.setSelected(1)

        self.iStart = JTextField(maximumSize=Dimension(40,25))
        self.iStart.setToolTipText("The Start Index for the Making of the Categories")

        self.RThis = JTextField()
        self.RThis = JTextField(maximumSize=Dimension(120,25))
        self.RThis.setToolTipText("The Starting Index used in creating the Categorical")

        self.RThat = JTextField()
        self.RThat = JTextField(maximumSize=Dimension(120,25))
        self.RThat.setToolTipText("The Finish Index used in creating the Categorical")
        
        optioncCategories = JLabel("Options:")
        bcCat = JButton("CreatCateg", actionPerformed=self.bcCat)
        bcCat.setToolTipText("Create a categorical form starting C_Index to finish C_Index; Use the text boxes to define the indexes")

        bM_Categories = JButton("Categories", actionPerformed=self.mCategories)
        bM_Categories.setToolTipText("Make Categories using the lines from the Input Area. Use it to define Categorical questions.")
        #####################################################
        # ConfirmIt pane
        panel_ConfirmIt = JPanel()
        layout4 = GroupLayout(panel_ConfirmIt)
        layout4.setAutoCreateGaps(True)
        layout4.setAutoCreateContainerGaps(True)
        panel_ConfirmIt.setLayout(layout4)
        
        self.PID = JTextField()
        self.PID = JTextField(maximumSize=Dimension(120,25))
        self.PID.setToolTipText("The PID number used for creating links with PID and ids from every line of the Input Area")
        
        bClinks = JButton("Create Links", actionPerformed=self.bClinks)
        bClinks.setToolTipText("Create links for a project using PID and ID, ID`s are read from every line of the Input Area")
        
        bClinksNA = JButton("Create Links NA ", actionPerformed=self.bClinksNA)
        bClinksNA.setToolTipText("Create links for a project using PID and ID`s from the standard sample test for US")
        
        bClinksCA = JButton("Create Links CA", actionPerformed=self.bClinksCA)
        bClinksCA.setToolTipText("Create links for a project using PID and ID`s from the standard sample test for CA")
        
        self.Width = JTextField()
        self.Width = JTextField(maximumSize=Dimension(120,25))
        self.Width.setToolTipText("The Width used in creating the DIV html tag, note the dimension used is in px")
        
        baddDIVt = JButton("Add DIV tag", actionPerformed=self.baddDIVt)
        baddDIVt.setToolTipText("Create a DIV tag for every line in the Input Area")
        #####################################################
        # Statistics pane
        panel_Statistics = JPanel()
        layout5 = GroupLayout(panel_Statistics)
        layout5.setAutoCreateGaps(True)
        layout5.setAutoCreateContainerGaps(True)
        panel_Statistics.setLayout(layout5)         
        
        #####################################################
        # TimeTraking pane
        panel_TimeTraking = JPanel()
        layout6 = GroupLayout(panel_TimeTraking)
        layout6.setAutoCreateGaps(True)
        layout6.setAutoCreateContainerGaps(True)
        panel_TimeTraking.setLayout(layout6)     
        
        #####################################################
        # Tabbed Area Tabs
        tabPane.addTab("Text Edit", panel_TEdit)
        tabPane.addTab("Dimensions", panel_Dimensions)
        tabPane.addTab("ConfirmIt", panel_ConfirmIt)
        tabPane.addTab("Statistics", panel_Statistics)
        tabPane.addTab("TimeTraking", panel_TimeTraking)
        
        
#############################################################




#############################################################
# Aplication Layouts: 2 groups one Horizontal and one Vertical
        
        #############################################################
        # Frame Layout: 2 groups one Horizontal and one Vertical
        layout.setHorizontalGroup(layout.createSequentialGroup()
            .addGroup(layout.createParallelGroup()
                .addComponent(Larea1)
                .addComponent(Sarea1)
                .addComponent(Sarea2)
                .addGroup(layout.createSequentialGroup()
                          .addComponent(bCopyToInput)
                          .addComponent(bClear)
                          .addComponent(self.cCtClipB))
                .addComponent(Larea2))
            .addGroup(layout.createParallelGroup()
                .addComponent(tabPane))
                        )

        layout.setVerticalGroup(layout.createSequentialGroup()
            .addGroup(layout.createParallelGroup()
                      .addGroup(layout.createSequentialGroup()
                          .addComponent(Larea1)
                          .addComponent(Sarea1)
                          .addGroup(layout.createParallelGroup()
                                    .addComponent(bCopyToInput)
                                    .addComponent(bClear)
                                    .addComponent(self.cCtClipB)    )
                          .addComponent(Larea2)
                          .addComponent(Sarea2))
                      .addGroup(layout.createSequentialGroup()
                          .addComponent(tabPane))
                          )
                        )

        #############################################################
        # TEdit Layout: 2 groups one Horizontal and one Vertical
        layout2.setHorizontalGroup(layout2.createSequentialGroup()
            .addGroup(layout2.createParallelGroup()
                .addGroup(layout2.createSequentialGroup()
                    .addComponent(bRemNumbers)
                    .addComponent(bRemoveNBSP_L)
                    .addComponent(bRemoveNBSP_R))
                    .addGroup(layout2.createSequentialGroup()
                    .addComponent(bSandReplace)
                    .addComponent(self.ReplaceThis)
                    .addComponent(self.ReplaceThat))  
                      
                      
                      
                                   ))
        
        layout2.setVerticalGroup(layout2.createSequentialGroup()
            .addGroup(layout2.createParallelGroup()
                .addComponent(bRemNumbers)
                .addComponent(bRemoveNBSP_L)
                .addComponent(bRemoveNBSP_R))
                                 
                .addGroup(layout2.createParallelGroup()
                    .addComponent(bSandReplace)
                    .addComponent(self.ReplaceThis)
                    .addComponent(self.ReplaceThat))  
                                 )
            
            
        #############################################################
        # Dimensions Layout: 2 groups one Horizontal and one Vertical
        layout3.setHorizontalGroup(layout3.createSequentialGroup()
        
         .addGroup(layout3.createParallelGroup()
            .addGroup(layout3.createSequentialGroup()
                .addComponent(bM_Categories)
                .addComponent(self.iStart))
            .addGroup(layout3.createSequentialGroup()
                .addComponent(optioncCategories)
                .addComponent(self.cCurly)
                .addComponent(self.cSemiC)
                )
           
            .addGroup(layout3.createSequentialGroup()
                .addComponent(bcCat)
                .addComponent(self.RThis)
                .addComponent(self.RThat))
            .addGroup(layout3.createSequentialGroup()
                
                )

                )
        )
        
        layout3.setVerticalGroup(layout3.createSequentialGroup()
            .addGroup(layout3.createSequentialGroup()
                    .addGroup(layout3.createParallelGroup()
                        .addComponent(bM_Categories)
                        .addComponent(self.iStart))
                    
                    .addGroup(layout3.createParallelGroup()
                        .addComponent(bcCat)
                        .addComponent(self.RThis)
                        .addComponent(self.RThat))
                    .addGroup(layout3.createParallelGroup()
                        
                    .addGroup(layout3.createParallelGroup()
                        .addComponent(optioncCategories)
                        .addComponent(self.cCurly)
                        .addComponent(self.cSemiC)
                        )
                   
                                )
                        )
            
            )
        #############################################################
        # ConfimIT Layout: 2 groups one Horizontal and one Vertical
        layout4.setHorizontalGroup(layout4.createSequentialGroup()
        
         .addGroup(layout4.createParallelGroup()
            .addGroup(layout4.createSequentialGroup()
                .addComponent(bClinks)
                .addComponent(self.PID)
                )
            .addGroup(layout4.createSequentialGroup()
                .addComponent(bClinksNA)
                .addComponent(bClinksCA)
                )
            .addGroup(layout4.createSequentialGroup()
                .addComponent(baddDIVt)
                .addComponent(self.Width)
                
                )
                
                ))
        
        
        layout4.setVerticalGroup(layout4.createSequentialGroup()
            .addGroup(layout4.createSequentialGroup()
                    .addGroup(layout4.createParallelGroup()
                        .addComponent(bClinks)
                        .addComponent(self.PID))
                    .addGroup(layout4.createParallelGroup()
                        .addComponent(bClinksNA)
                        .addComponent(bClinksCA)
                        )
                    
                    .addGroup(layout4.createParallelGroup()
                        .addComponent(baddDIVt)
                        .addComponent(self.Width)
                        )
                    
                        
                        ))
        
        
        #layout2.linkSize(SwingConstants.HORIZONTAL, [self.cCurly,bM_Categories])
        #layout.linkSize(SwingConstants.HORIZONTAL, [ok, bCopyToInput, close, bM_Categories])
        #layout3.linkSize(SwingConstants.HORIZONTAL, [self.RThis,self.RThat,bRemoveNBSP_L,bRemoveNBSP_R,bM_Categories,bSandReplace,bcCat])

        
#############################################################

#############################################################
# Aplication Settings
        self.pack()
        #self.setPreferredSize(Dimension(1000, 1000))
        self.setTitle("Workhelper")
        self.setSize(800, 500)
        self.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
        self.setLocationRelativeTo(None)
        self.setVisible(True)
Example #50
0
class ModelView(JFrame):
    '''
    Initializes the ATF model view and sets its layout.
    '''
    def __init__(self, controller):
        '''
        Creates a new window displaying a schematic view of an ATF file,
        following the guidelines and mockup agreed with project owners.
        '''

        # Give reference to controller to delegate action response
        self.controller = controller

        # Get list of projects, languages and protocols from config settings
        self.languages = self.controller.config['languages']
        self.protocols = self.controller.config['protocols']
        self.projects = self.controller.config['projects']

        # Make text area occupy all available space and resize with parent
        # window
        self.setLayout(BorderLayout())

        self.mainPanel = JTabbedPane()
        self.mainPanel.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT)
        self.add(self.mainPanel, BorderLayout.CENTER)

        # Set empty dictionary of tab panels
        self.objectTabs = {}

        # Will need scrolling controls
        scrollingArea = JScrollPane(self.mainPanel)

        # Add notice panel
        self.add(self.addNotice(), BorderLayout.NORTH)

        # Add to parent panel
        self.add(scrollingArea, BorderLayout.CENTER)

    def addObject(self, objectID):
        """
        Creates new empty JPanel that'll contain the model for one object in
        the ATF file.
        """
        objectPanel = JPanel()
        objectPanel.setLayout(BoxLayout(objectPanel, BoxLayout.PAGE_AXIS))

        self.objectTabs[objectID] = objectPanel

    def display(self):
        """
        Put together all elements in main panel and display.
        """
        # Add all object tabs to window
        for objectID, tabPanel in self.objectTabs.iteritems():
            self.mainPanel.add(objectID, tabPanel)

        # Set up main model window
        self.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE)
        self.setTitle("ATF Model View")
        self.pack()
        self.setLocationRelativeTo(None)

        # Display model window
        self.visible = 1

    def addLine(self, objectID, category, text):
        """
        Add a new panel containing the text corresponding to one line in the
        ATF file.
        This panel will show the line type (ruling, comment, text,
        translation...), followed by the line content and a group of icons to
        add, edit or remove the line.
        """
        linePanel = JPanel()
        linePanel.setLayout(BorderLayout())

        label = JLabel(category)

        combo = JComboBox(text)
        combo.setEditable(True)
        combo.setPreferredSize(Dimension(500, 20))
        combo.setSize(combo.getPreferredSize())
        combo.setMinimumSize(combo.getPreferredSize())
        combo.setMaximumSize(combo.getPreferredSize())

        buttonsPanel = JPanel()
        addButton = JButton("Add")
        editButton = JButton("Edit")
        deleteButton = JButton("Delete")
        buttonsPanel.add(addButton)
        buttonsPanel.add(editButton)
        buttonsPanel.add(deleteButton)

        linePanel.add(label, BorderLayout.WEST)
        linePanel.add(combo, BorderLayout.CENTER)
        linePanel.add(buttonsPanel, BorderLayout.EAST)

        # Add metadataPanel to object tab in main panel
        self.objectTabs[objectID].add(linePanel)

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

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

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

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

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

        # Add metadataPanel to object tab in main panel
        self.objectTabs[objectID].add(metadataPanel)

    def addNotice(self):
        """
        Add a panel that notifies the user about the model view not being
        ready yet.
        """
        panel = JPanel()
        panel.setBackground(Color.yellow)
        label = JLabel("Please note Nammu's model view is under "
                       "construction.")
        panel.add(label)
        return panel
Example #51
0
    def __init__(self):
        

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

        tabPane = JTabbedPane(JTabbedPane.TOP)

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

        eachIp = self.getIp(HOSTDOMAIN)

        iList = eachIp.split(".")

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

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



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



        theName = self.getDomain1(HOSTDOMAIN)

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


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


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

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

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


#
        tabPane.addTab("Sebsitive File", panel3)
#
        frame.add(tabPane)
        frame.setVisible(True)
Example #52
0
class ModelView(JFrame):
    
    def __init__(self, controller):
        '''
        Creates a new window displaying a schematic view of an ATF file, 
        following the guidelines and mockup agreed with project owners.
        '''
        
        #Give reference to controller to delegate action response
        self.controller = controller
        
        #Make text area occupy all available space and resize with parent window
        self.setLayout(BorderLayout())
        
        self.mainPanel = JTabbedPane()
        self.mainPanel.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
        self.add(self.mainPanel, BorderLayout.CENTER)
        
        #Set empty dictionary of tab panels
        self.objectTabs = {}

        #Will need scrolling controls
        scrollingArea = JScrollPane(self.mainPanel)
        
        #Add to parent panel
        self.add(scrollingArea, BorderLayout.CENTER)
        
        #TODO: Where to get/store this information?
        self.languages = { "akk-x-stdbab": "Akkadian Standard Babylonian", \
                          "akk": "Akkadian", "sux": "", "a":"", \
                          "akk-x-oldbab":"Akkadian Old Babylonian", "qpc": "", \
                          "na": "", "nb": "", "x/n": "", \
                          "akk-x-neoass": "Akkadian Neo Assyrian"}
        
        
    def addObject(self, objectID):
        """
        Creates new empty JPanel that'll contain the model for one object in 
        the ATF file.
        """
        objectPanel = JPanel()
        objectPanel.setLayout(BoxLayout(objectPanel, BoxLayout.PAGE_AXIS))
        
        self.objectTabs[objectID] = objectPanel
  
        
    def display(self): 
        """
        Put together all elements in main panel and display.
        """
        #Add all object tabs to window
        for objectID, tabPanel in self.objectTabs.iteritems():
            self.mainPanel.add(objectID, tabPanel)
        
        #Set up main model window
        self.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE)
        self.setTitle("ATF Model View")
        self.pack()
        self.setLocationRelativeTo(None)

        #Display model window
        self.visible = 1
        
    def addLine(self, objectID, category, text):
        """
        Add a new panel containing the text corresponding to one line in the 
        ATF file. 
        This panel will show the line type (ruling, comment, text, 
        translation...), followed by the line content and a group of icons to 
        add, edit or remove the line.
        """
        linePanel = JPanel()
        linePanel.setLayout(BorderLayout())
        
        label = JLabel(category)
        
        combo = JComboBox(text)
        
        buttonsPanel = JPanel()
        addButton = JButton("Add")
        editButton = JButton("Edit")
        deleteButton = JButton("Delete")
        buttonsPanel.add(addButton)
        buttonsPanel.add(editButton)
        buttonsPanel.add(deleteButton)
        
        linePanel.add(label, BorderLayout.WEST)
        linePanel.add(combo, BorderLayout.CENTER)
        linePanel.add(buttonsPanel, BorderLayout.EAST)
        
        #Add metadataPanel to object tab in main panel
        self.objectTabs[objectID].add(linePanel)
    
    #Protocols not yet in model parsed object
    #def addMetadata(self, project, language, protocols):
    def addMetadata(self, objectID, project, language):
        """
        Add a JTable at the top of the object tab containing the metadata of
        the object presented in that tab.
        """
        metadataPanel = JPanel()
        #TODO: Need to count protocols to set up Grid dimension
        metadataPanel.setLayout(GridLayout(3,2))
        
        projectLabel = JLabel("Project: ")
        projectValue = JLabel(project)
        
        #TODO Check language not found
        languageLabel = JLabel("Language: ")
        languageValue = JLabel(self.languages[language])
        
        #TODO Protocols not yet in parsed object
        protocolsLabel = JLabel("ATF Protocols: ")
        protocolsBox = JComboBox()
        #for protocol in protocols:
        #    protocolBox.add(protocol)
        
        metadataPanel.add(projectLabel)
        metadataPanel.add(projectValue)
        metadataPanel.add(languageLabel)
        metadataPanel.add(languageValue)
        metadataPanel.add(protocolsLabel)
        metadataPanel.add(protocolsBox)
        
        #Add metadataPanel to object tab in main panel
        self.objectTabs[objectID].add(metadataPanel)
        
        

    
    #def addSide(self, sideType, content):
        
        
Example #53
0
class PreferencesFrame(JFrame, ActionListener, WindowListener, ItemListener, HyperlinkListener):
    """Dialog with preferences
    """
    def __init__(self, parent, title, app):
        from javax.swing import JCheckBox, JRadioButton, ButtonGroup
        self.app = app
        border = BorderFactory.createEmptyBorder(5, 7, 5, 7)
        self.getContentPane().setBorder(border)
        self.getContentPane().setLayout(BorderLayout(0, 5))
        self.tabbedPane = JTabbedPane()

        #1 Tab: general
        panel1 = JPanel()
        panel1.setBorder(BorderFactory.createEmptyBorder(7, 7, 7, 7))
        panel1.setLayout(BoxLayout(panel1, BoxLayout.PAGE_AXIS))

        #Checkbutton to enable/disable update check when script starts
        self.updateCBtn = JCheckBox(self.app.strings.getString("updateCBtn"))
        self.updateCBtn.setToolTipText(self.app.strings.getString("updateCBtn_tooltip"))

        #Download tools
        downloadBtn = JButton(self.app.strings.getString("updatesBtn"),
                              ImageProvider.get("dialogs", "refresh"),
                              actionPerformed=self.on_downloadBtn_clicked)
        downloadBtn.setToolTipText(self.app.strings.getString("updatesBtn_tooltip"))

        #Checkbuttons for enabling/disabling tools
        toolsPanel = JPanel(BorderLayout(0, 5))
        title = self.app.strings.getString("enable_disable_tools")
        toolsPanel.setBorder(BorderFactory.createTitledBorder(title))
        infoLbl = JLabel(self.app.strings.getString("JOSM_restart_warning"))
        infoLbl.setFont(infoLbl.getFont().deriveFont(Font.ITALIC))
        toolsPanel.add(infoLbl, BorderLayout.PAGE_START)

        toolsStatusPane = JPanel(GridLayout(len(self.app.realTools), 0))
        self.toolsCBtns = []
        for tool in self.app.realTools:
            toolCBtn = JCheckBox()
            toolCBtn.addItemListener(self)
            toolLbl = JLabel(tool.title, tool.bigIcon, JLabel.LEFT)
            self.toolsCBtns.append(toolCBtn)

            toolPane = JPanel()
            toolPane.setLayout(BoxLayout(toolPane, BoxLayout.X_AXIS))
            toolPane.add(toolCBtn)
            toolPane.add(toolLbl)
            toolsStatusPane.add(toolPane)
        toolsPanel.add(toolsStatusPane, BorderLayout.CENTER)

        #Radiobuttons for enabling/disabling layers when a new one
        #is added
        layersPanel = JPanel(GridLayout(0, 1))
        title = self.app.strings.getString("errors_layers_manager")
        layersPanel.setBorder(BorderFactory.createTitledBorder(title))
        errorLayersLbl = JLabel(self.app.strings.getString("errors_layers_info"))
        errorLayersLbl.setFont(errorLayersLbl.getFont().deriveFont(Font.ITALIC))
        layersPanel.add(errorLayersLbl)
        self.layersRBtns = {}
        group = ButtonGroup()
        for mode in self.app.layersModes:
            layerRBtn = JRadioButton(self.app.strings.getString("%s" % mode))
            group.add(layerRBtn)
            layersPanel.add(layerRBtn)
            self.layersRBtns[mode] = layerRBtn

        #Max number of errors text field
        self.maxErrorsNumberTextField = JTextField()
        self.maxErrorsNumberTextField.setToolTipText(self.app.strings.getString("maxErrorsNumberTextField_tooltip"))
        self.maxErrorsNumberTFieldDefaultBorder = self.maxErrorsNumberTextField.getBorder()
        self.maxErrorsNumberTextField.getDocument().addDocumentListener(ErrNumTextListener(self))

        #layout
        self.updateCBtn.setAlignmentX(Component.LEFT_ALIGNMENT)
        panel1.add(self.updateCBtn)
        panel1.add(Box.createRigidArea(Dimension(0, 15)))
        downloadBtn.setAlignmentX(Component.LEFT_ALIGNMENT)
        panel1.add(downloadBtn)
        panel1.add(Box.createRigidArea(Dimension(0, 15)))
        toolsPanel.setAlignmentX(Component.LEFT_ALIGNMENT)
        panel1.add(toolsPanel)
        panel1.add(Box.createRigidArea(Dimension(0, 15)))
        layersPanel.setAlignmentX(Component.LEFT_ALIGNMENT)
        panel1.add(layersPanel)
        panel1.add(Box.createRigidArea(Dimension(0, 15)))
        maxErrP = JPanel(BorderLayout(5, 0))
        maxErrP.add(JLabel(self.app.strings.getString("max_errors_number")), BorderLayout.LINE_START)
        maxErrP.add(self.maxErrorsNumberTextField, BorderLayout.CENTER)
        p = JPanel(BorderLayout())
        p.add(maxErrP, BorderLayout.PAGE_START)
        p.setAlignmentX(Component.LEFT_ALIGNMENT)
        panel1.add(p)

        self.tabbedPane.addTab(self.app.strings.getString("tab_1_title"),
                          None,
                          panel1,
                          None)

        #2 Tab: favourite zones
        panel2 = JPanel(BorderLayout(5, 15))
        panel2.setBorder(BorderFactory.createEmptyBorder(7, 7, 7, 7))

        #status
        topPanel = JPanel()
        topPanel.setLayout(BoxLayout(topPanel, BoxLayout.Y_AXIS))
        infoPanel = HtmlPanel(self.app.strings.getString("fav_zones_info"))
        infoPanel.getEditorPane().addHyperlinkListener(self)
        infoPanel.setAlignmentX(Component.LEFT_ALIGNMENT)
        self.favZoneStatusCBtn = JCheckBox(self.app.strings.getString("activate_fav_area"),
                                           actionListener=self)
        self.favZoneStatusCBtn.setToolTipText(self.app.strings.getString("activate_fav_area_tooltip"))
        self.favZoneStatusCBtn.setAlignmentX(Component.LEFT_ALIGNMENT)
        topPanel.add(infoPanel)
        topPanel.add(Box.createRigidArea(Dimension(0, 10)))
        topPanel.add(self.favZoneStatusCBtn)
        #table
        self.zonesTable = JTable()
        tableSelectionModel = self.zonesTable.getSelectionModel()
        tableSelectionModel.addListSelectionListener(ZonesTableListener(self))
        columns = ["",
                   self.app.strings.getString("Type"),
                   self.app.strings.getString("Name")]
        tableModel = ZonesTableModel([], columns)
        self.zonesTable.setModel(tableModel)
        self.scrollPane = JScrollPane(self.zonesTable)
        #map
        self.zonesMap = JMapViewer()
        self.zonesMap.setZoomContolsVisible(False)
        self.zonesMap.setMinimumSize(Dimension(100, 200))

        #buttons
        self.removeBtn = JButton(self.app.strings.getString("Remove"),
                            ImageProvider.get("dialogs", "delete"),
                            actionPerformed=self.on_removeBtn_clicked)
        self.removeBtn.setToolTipText(self.app.strings.getString("remove_tooltip"))
        newBtn = JButton(self.app.strings.getString("New"),
                         ImageProvider.get("dialogs", "add"),
                         actionPerformed=self.on_newBtn_clicked)
        newBtn.setToolTipText(self.app.strings.getString("new_tooltip"))

        #layout
        panel2.add(topPanel, BorderLayout.PAGE_START)
        panel2.add(self.scrollPane, BorderLayout.LINE_START)
        panel2.add(self.zonesMap, BorderLayout.CENTER)
        self.buttonsPanel = JPanel()
        self.buttonsPanel.add(self.removeBtn)
        self.buttonsPanel.add(newBtn)
        panel2.add(self.buttonsPanel, BorderLayout.PAGE_END)

        self.tabbedPane.addTab(self.app.strings.getString("tab_2_title"),
                          None,
                          panel2,
                          None)

        #3 Tab Tools options
        panel3 = JPanel()
        panel3.setLayout(BoxLayout(panel3, BoxLayout.Y_AXIS))
        panel3.setBorder(BorderFactory.createEmptyBorder(7, 7, 7, 7))
        for tool in self.app.realTools:
            if hasattr(tool, 'prefs'):
                p = JPanel(FlowLayout(FlowLayout.LEFT))
                p.setBorder(BorderFactory.createTitledBorder(tool.title))
                p.add(tool.prefsGui)
                panel3.add(p)

        self.tabbedPane.addTab(self.app.strings.getString("tab_3_title"),
                          None,
                          panel3,
                          None)

        self.add(self.tabbedPane, BorderLayout.CENTER)

        exitPanel = JPanel()
        saveBtn = JButton(self.app.strings.getString("OK"),
                          ImageProvider.get("ok"),
                          actionPerformed=self.on_saveBtn_clicked)
        cancelBtn = JButton(self.app.strings.getString("cancel"),
                            ImageProvider.get("cancel"),
                            actionPerformed=self.on_cancelBtn_clicked)
        saveBtn.setToolTipText(self.app.strings.getString("save_preferences"))
        saveBtn.setAlignmentX(0.5)
        exitPanel.add(saveBtn)
        exitPanel.add(cancelBtn)
        self.add(exitPanel, BorderLayout.PAGE_END)

        self.addWindowListener(self)
        self.pack()

    def windowClosing(self, windowEvent):
        self.on_cancelBtn_clicked()

    def hyperlinkUpdate(self, e):
        if e.getEventType() == HyperlinkEvent.EventType.ACTIVATED:
            OpenBrowser.displayUrl(e.getURL().toString())

    def itemStateChanged(self, e):
        """A ttol has been activated/deactivated.
           Check if at least one tool is on.
        """
        if all(not button.isSelected() for button in self.toolsCBtns):
            JOptionPane.showMessageDialog(
                Main.parent,
                self.app.strings.getString("tools_disabled_warning"),
                self.app.strings.getString("tools_disabled_warning_title"),
                JOptionPane.WARNING_MESSAGE)
            source = e.getItemSelectable()
            source.setSelected(True)

    def actionPerformed(self, e=None):
        """Enable/disable favourite zones panel
        """
        for container in (self.scrollPane, self.buttonsPanel):
            self.enableComponents(container, self.favZoneStatusCBtn.isSelected())
        if self.favZoneStatusCBtn.isSelected():
            self.check_removeBtn_status()

    def enableComponents(self, container, enable):
        components = container.getComponents()
        for component in components:
            component.setEnabled(enable)
            if isinstance(component, Container):
                self.enableComponents(component, enable)

    def on_downloadBtn_clicked(self, e):
        update_checker.Updater(self.app, "manual")

    def clean_map(self):
        """Remove all rectangles and polygons from the map
        """
        self.zonesMap.removeAllMapRectangles()
        self.zonesMap.removeAllMapPolygons()

    def update_gui_from_preferences(self):
        """Update gui status of preferences frame from config file
        """
        #print "\n- updating Preferences gui"
        onOff = {"on": True, "off": False}
        #1 Tab
        #check for update
        self.updateCBtn.setSelected(onOff[self.app.checkUpdate])

        #tools status, enabled or not
        for toolIndex, tool in enumerate(self.app.realTools):
            if "tool.%s" % tool.name in self.app.properties.keys():
                configstatus = self.app.properties.getProperty("tool.%s" % tool.name)
            else:
                configstatus = "on"     # new tool
            self.toolsCBtns[toolIndex].setSelected(onOff[configstatus])

        #layers preferences
        for mode, button in self.layersRBtns.iteritems():
            button.setSelected(mode == self.app.layersMode)

        #max errors number
        self.maxErrorsNumberTextField.setText(str(self.app.maxErrorsNumber))

        #stats panel
        self.app.dlg.update_favourite_zone_indicator()

        #2 Tab
        #favourite area
        self.update_favourite_area_gui_from_preferences()
        self.app.dlg.update_statsPanel_status()

        #3 Tab
        #tools preferences
        for tool in self.app.allTools:
            if hasattr(tool, 'prefs') and tool.prefsGui is not None:
                tool.prefsGui.update_gui(tool.prefs)

    def update_favourite_area_gui_from_preferences(self):
        #status
        self.favZoneStatusCBtn.setSelected(self.app.favouriteZoneStatus)
        #table
        #store zones to a temporary list, used to store changes
        #and save them when preferences dialog is closed
        self.app.tempZones = list(self.app.zones)
        self.zonesTable.getModel().setNumRows(0)
        for zone in self.app.tempZones:
            self.zonesTable.getModel().addRow([zone.country,
                                               zone.icon,
                                               zone.name])
        if self.app.favZone is not None:
            selectedRow = self.app.tempZones.index(self.app.favZone)
            self.zonesTable.setRowSelectionInterval(selectedRow, selectedRow)
        self.zonesTable.getColumnModel().getColumn(0).setMaxWidth(30)
        self.zonesTable.getColumnModel().getColumn(1).setMaxWidth(50)
        #enable or disable favourite zone buttons
        self.actionPerformed()

### fav area editing buttons ###########################################
    def on_removeBtn_clicked(self, e):
        rowsNum = self.zonesTable.getSelectedRows()
        rowsNum.reverse()
        for rowNum in rowsNum:
            del self.app.tempZones[rowNum]
            self.zonesTable.getModel().removeRow(rowNum)
        if len(self.app.tempZones) != 0:
            if rowNum == 0:
                self.zonesTable.setRowSelectionInterval(0, 0)
            else:
                self.zonesTable.setRowSelectionInterval(rowNum - 1, rowNum - 1)
        self.check_removeBtn_status()

    def check_removeBtn_status(self):
        if self.app.tempZones != [] and len(self.zonesTable.getSelectedRows()) != 0:
            self.removeBtn.setEnabled(True)
        else:
            self.removeBtn.setEnabled(False)
            self.clean_map()

    def on_newBtn_clicked(self, e):
        try:
            self.newZoneDialog
        except AttributeError:
            self.newZoneDialog = NewZoneDialog(self.app)
        bbox = self.app.get_frame_bounds()
        self.app.newZone = Zone(self.app,
                                self.app.strings.getString("New_zone"),
                                "rectangle",
                                ",".join(["%0.4f" % x for x in bbox]),
                                "")
        self.newZoneDialog.update_gui_from_preferences()
        self.newZoneDialog.show()

### Exit from preferences ##############################################
    def on_cancelBtn_clicked(self, event=None):
        if hasattr(self, "newZoneDialog") and self.newZoneDialog.isVisible():
            self.newZoneDialog.close_dialog()
        self.dispose()

    def on_saveBtn_clicked(self, event):
        """Read preferences from gui and save them to config.properties
           file
        """
        #print "\n- saving preferences to config file"
        onOff = {True: "on", False: "off"}

        #1 Tab
        #check for update
        self.app.properties.setProperty("check_for_update",
                                        onOff[self.updateCBtn.isSelected()])
        #tools status
        for toolIndex, tool in enumerate(self.app.realTools):
            prop = "tool.%s" % tool.name
            toolCBtn = self.toolsCBtns[toolIndex]
            self.app.properties.setProperty(prop,
                                            onOff[toolCBtn.isSelected()])

        #layers preferences
        for mode, button in self.layersRBtns.iteritems():
            if button.isSelected():
                self.app.properties.setProperty("layers_mode", mode)
                break

        #max errors number
        try:
            num = Integer.parseInt(self.maxErrorsNumberTextField.getText())
        except NumberFormatException:
            num = ""
        self.app.properties.setProperty("max_errors_number", str(num))

        #2 Tab
        #Favourite zones
        changes = {"new": [z for z in self.app.tempZones if not z in self.app.zones],
                   "deleted": [z for z in self.app.zones if not z in self.app.tempZones]}
        #delete files of removed favourite zones
        for zone in changes["deleted"]:
            f = File(File.separator.join([self.app.SCRIPTDIR,
                                          "configuration",
                                          "favourite_zones",
                                          "%s.txt" % zone.name]))
            f.delete()
        #create files for new favourite zones
        for zone in changes["new"]:
            print "\nsave new zone", zone.name
            fileName = File.separator.join([self.app.SCRIPTDIR,
                                            "configuration",
                                            "favourite_zones",
                                            "%s.txt" % zone.name])
            f = open(fileName, "w")
            zoneData = zone.geomString
            if zone.country != "":
                zoneData += "|" + zone.country
            f.write(zoneData.encode("utf-8"))
            f.close()

        self.app.zones = self.app.tempZones
        if len(self.app.zones) == 0:
            self.app.favZone = None
            self.app.properties.setProperty("favourite_area.name",
                                            "")
            self.favZoneStatusCBtn.setSelected(False)
        else:
            if len(self.zonesTable.getSelectedRows()) == 0:
                self.app.favZone = self.app.zones[0]
            else:
                self.app.favZone = self.app.zones[self.zonesTable.getSelectedRows()[0]]
            self.app.properties.setProperty("favourite_area.name",
                                            self.app.favZone.name)
        favZoneStatus = self.favZoneStatusCBtn.isSelected()
        self.app.properties.setProperty("favourite_area.status", onOff[favZoneStatus])
        self.app.favouriteZoneStatus = favZoneStatus

        #stats panel
        self.app.dlg.update_favourite_zone_indicator()
        self.app.dlg.update_statsPanel_status()

        #3 Tab
        #tools preferences
        for tool in self.app.allTools:
            if hasattr(tool, 'prefs') and tool.prefsGui is not None:
                for pref, value in tool.prefsGui.read_gui().iteritems():
                    prefKey = "tool.%s.%s" % (tool.name, pref)
                    self.app.properties.setProperty(prefKey, value)

        self.app.save_config()
        self.dispose()
Example #54
0
    def __init__(self, parent, title, app):
        from javax.swing import JCheckBox, JRadioButton, ButtonGroup
        self.app = app
        border = BorderFactory.createEmptyBorder(5, 7, 5, 7)
        self.getContentPane().setBorder(border)
        self.getContentPane().setLayout(BorderLayout(0, 5))
        self.tabbedPane = JTabbedPane()

        #1 Tab: general
        panel1 = JPanel()
        panel1.setBorder(BorderFactory.createEmptyBorder(7, 7, 7, 7))
        panel1.setLayout(BoxLayout(panel1, BoxLayout.PAGE_AXIS))

        #Checkbutton to enable/disable update check when script starts
        self.updateCBtn = JCheckBox(self.app.strings.getString("updateCBtn"))
        self.updateCBtn.setToolTipText(self.app.strings.getString("updateCBtn_tooltip"))

        #Download tools
        downloadBtn = JButton(self.app.strings.getString("updatesBtn"),
                              ImageProvider.get("dialogs", "refresh"),
                              actionPerformed=self.on_downloadBtn_clicked)
        downloadBtn.setToolTipText(self.app.strings.getString("updatesBtn_tooltip"))

        #Checkbuttons for enabling/disabling tools
        toolsPanel = JPanel(BorderLayout(0, 5))
        title = self.app.strings.getString("enable_disable_tools")
        toolsPanel.setBorder(BorderFactory.createTitledBorder(title))
        infoLbl = JLabel(self.app.strings.getString("JOSM_restart_warning"))
        infoLbl.setFont(infoLbl.getFont().deriveFont(Font.ITALIC))
        toolsPanel.add(infoLbl, BorderLayout.PAGE_START)

        toolsStatusPane = JPanel(GridLayout(len(self.app.realTools), 0))
        self.toolsCBtns = []
        for tool in self.app.realTools:
            toolCBtn = JCheckBox()
            toolCBtn.addItemListener(self)
            toolLbl = JLabel(tool.title, tool.bigIcon, JLabel.LEFT)
            self.toolsCBtns.append(toolCBtn)

            toolPane = JPanel()
            toolPane.setLayout(BoxLayout(toolPane, BoxLayout.X_AXIS))
            toolPane.add(toolCBtn)
            toolPane.add(toolLbl)
            toolsStatusPane.add(toolPane)
        toolsPanel.add(toolsStatusPane, BorderLayout.CENTER)

        #Radiobuttons for enabling/disabling layers when a new one
        #is added
        layersPanel = JPanel(GridLayout(0, 1))
        title = self.app.strings.getString("errors_layers_manager")
        layersPanel.setBorder(BorderFactory.createTitledBorder(title))
        errorLayersLbl = JLabel(self.app.strings.getString("errors_layers_info"))
        errorLayersLbl.setFont(errorLayersLbl.getFont().deriveFont(Font.ITALIC))
        layersPanel.add(errorLayersLbl)
        self.layersRBtns = {}
        group = ButtonGroup()
        for mode in self.app.layersModes:
            layerRBtn = JRadioButton(self.app.strings.getString("%s" % mode))
            group.add(layerRBtn)
            layersPanel.add(layerRBtn)
            self.layersRBtns[mode] = layerRBtn

        #Max number of errors text field
        self.maxErrorsNumberTextField = JTextField()
        self.maxErrorsNumberTextField.setToolTipText(self.app.strings.getString("maxErrorsNumberTextField_tooltip"))
        self.maxErrorsNumberTFieldDefaultBorder = self.maxErrorsNumberTextField.getBorder()
        self.maxErrorsNumberTextField.getDocument().addDocumentListener(ErrNumTextListener(self))

        #layout
        self.updateCBtn.setAlignmentX(Component.LEFT_ALIGNMENT)
        panel1.add(self.updateCBtn)
        panel1.add(Box.createRigidArea(Dimension(0, 15)))
        downloadBtn.setAlignmentX(Component.LEFT_ALIGNMENT)
        panel1.add(downloadBtn)
        panel1.add(Box.createRigidArea(Dimension(0, 15)))
        toolsPanel.setAlignmentX(Component.LEFT_ALIGNMENT)
        panel1.add(toolsPanel)
        panel1.add(Box.createRigidArea(Dimension(0, 15)))
        layersPanel.setAlignmentX(Component.LEFT_ALIGNMENT)
        panel1.add(layersPanel)
        panel1.add(Box.createRigidArea(Dimension(0, 15)))
        maxErrP = JPanel(BorderLayout(5, 0))
        maxErrP.add(JLabel(self.app.strings.getString("max_errors_number")), BorderLayout.LINE_START)
        maxErrP.add(self.maxErrorsNumberTextField, BorderLayout.CENTER)
        p = JPanel(BorderLayout())
        p.add(maxErrP, BorderLayout.PAGE_START)
        p.setAlignmentX(Component.LEFT_ALIGNMENT)
        panel1.add(p)

        self.tabbedPane.addTab(self.app.strings.getString("tab_1_title"),
                          None,
                          panel1,
                          None)

        #2 Tab: favourite zones
        panel2 = JPanel(BorderLayout(5, 15))
        panel2.setBorder(BorderFactory.createEmptyBorder(7, 7, 7, 7))

        #status
        topPanel = JPanel()
        topPanel.setLayout(BoxLayout(topPanel, BoxLayout.Y_AXIS))
        infoPanel = HtmlPanel(self.app.strings.getString("fav_zones_info"))
        infoPanel.getEditorPane().addHyperlinkListener(self)
        infoPanel.setAlignmentX(Component.LEFT_ALIGNMENT)
        self.favZoneStatusCBtn = JCheckBox(self.app.strings.getString("activate_fav_area"),
                                           actionListener=self)
        self.favZoneStatusCBtn.setToolTipText(self.app.strings.getString("activate_fav_area_tooltip"))
        self.favZoneStatusCBtn.setAlignmentX(Component.LEFT_ALIGNMENT)
        topPanel.add(infoPanel)
        topPanel.add(Box.createRigidArea(Dimension(0, 10)))
        topPanel.add(self.favZoneStatusCBtn)
        #table
        self.zonesTable = JTable()
        tableSelectionModel = self.zonesTable.getSelectionModel()
        tableSelectionModel.addListSelectionListener(ZonesTableListener(self))
        columns = ["",
                   self.app.strings.getString("Type"),
                   self.app.strings.getString("Name")]
        tableModel = ZonesTableModel([], columns)
        self.zonesTable.setModel(tableModel)
        self.scrollPane = JScrollPane(self.zonesTable)
        #map
        self.zonesMap = JMapViewer()
        self.zonesMap.setZoomContolsVisible(False)
        self.zonesMap.setMinimumSize(Dimension(100, 200))

        #buttons
        self.removeBtn = JButton(self.app.strings.getString("Remove"),
                            ImageProvider.get("dialogs", "delete"),
                            actionPerformed=self.on_removeBtn_clicked)
        self.removeBtn.setToolTipText(self.app.strings.getString("remove_tooltip"))
        newBtn = JButton(self.app.strings.getString("New"),
                         ImageProvider.get("dialogs", "add"),
                         actionPerformed=self.on_newBtn_clicked)
        newBtn.setToolTipText(self.app.strings.getString("new_tooltip"))

        #layout
        panel2.add(topPanel, BorderLayout.PAGE_START)
        panel2.add(self.scrollPane, BorderLayout.LINE_START)
        panel2.add(self.zonesMap, BorderLayout.CENTER)
        self.buttonsPanel = JPanel()
        self.buttonsPanel.add(self.removeBtn)
        self.buttonsPanel.add(newBtn)
        panel2.add(self.buttonsPanel, BorderLayout.PAGE_END)

        self.tabbedPane.addTab(self.app.strings.getString("tab_2_title"),
                          None,
                          panel2,
                          None)

        #3 Tab Tools options
        panel3 = JPanel()
        panel3.setLayout(BoxLayout(panel3, BoxLayout.Y_AXIS))
        panel3.setBorder(BorderFactory.createEmptyBorder(7, 7, 7, 7))
        for tool in self.app.realTools:
            if hasattr(tool, 'prefs'):
                p = JPanel(FlowLayout(FlowLayout.LEFT))
                p.setBorder(BorderFactory.createTitledBorder(tool.title))
                p.add(tool.prefsGui)
                panel3.add(p)

        self.tabbedPane.addTab(self.app.strings.getString("tab_3_title"),
                          None,
                          panel3,
                          None)

        self.add(self.tabbedPane, BorderLayout.CENTER)

        exitPanel = JPanel()
        saveBtn = JButton(self.app.strings.getString("OK"),
                          ImageProvider.get("ok"),
                          actionPerformed=self.on_saveBtn_clicked)
        cancelBtn = JButton(self.app.strings.getString("cancel"),
                            ImageProvider.get("cancel"),
                            actionPerformed=self.on_cancelBtn_clicked)
        saveBtn.setToolTipText(self.app.strings.getString("save_preferences"))
        saveBtn.setAlignmentX(0.5)
        exitPanel.add(saveBtn)
        exitPanel.add(cancelBtn)
        self.add(exitPanel, BorderLayout.PAGE_END)

        self.addWindowListener(self)
        self.pack()
Example #55
0
    def __init__(self, name, iconName, tooltip, shortcut, height, app):
        ToggleDialog.__init__(self, name, iconName, tooltip, shortcut, height)
        self.app = app
        tools = app.tools

        #Main panel of the dialog
        mainPnl = JPanel(BorderLayout())
        mainPnl.setBorder(BorderFactory.createEmptyBorder(0, 1, 1, 1))

### First tab: errors selection and download ###########################
        #ComboBox with tools names
        self.toolsComboModel = DefaultComboBoxModel()
        for tool in tools:
            self.add_data_to_models(tool)
        self.toolsCombo = JComboBox(self.toolsComboModel,
                                    actionListener=ToolsComboListener(app))
        renderer = ToolsComboRenderer(self.app)
        renderer.setPreferredSize(Dimension(20, 20))
        self.toolsCombo.setRenderer(renderer)
        self.toolsCombo.setToolTipText(app.strings.getString("Select_a_quality_assurance_tool"))

        #ComboBox with categories names ("views"), of the selected tool
        self.viewsCombo = JComboBox(actionListener=ViewsComboListener(app))
        self.viewsCombo.setToolTipText(app.strings.getString("Select_a_category_of_error"))

        #Popup for checks table
        self.checkPopup = JPopupMenu()
        #add favourite check
        self.menuItemAdd = JMenuItem(self.app.strings.getString("Add_to_favourites"))
        self.menuItemAdd.setIcon(ImageIcon(File.separator.join([self.app.SCRIPTDIR,
                                                                "tools",
                                                                "data",
                                                                "Favourites",
                                                                "icons",
                                                                "tool_16.png"])))
        self.menuItemAdd.addActionListener(PopupActionListener(self.app))
        self.checkPopup.add(self.menuItemAdd)
        #remove favourite check
        self.menuItemRemove = JMenuItem(self.app.strings.getString("Remove_from_favourites"))
        self.menuItemRemove.setIcon(ImageIcon(File.separator.join([self.app.SCRIPTDIR,
                                                                   "tools",
                                                                   "data",
                                                                   "Favourites",
                                                                   "icons",
                                                                   "black_tool_16.png"])))
        self.menuItemRemove.addActionListener(PopupActionListener(self.app))
        self.checkPopup.add(self.menuItemRemove)
        #Help link for selected check
        self.menuItemHelp = JMenuItem(self.app.strings.getString("check_help"))
        self.menuItemHelp.setIcon(ImageIcon(File.separator.join([self.app.SCRIPTDIR,
                                                                 "images",
                                                                 "icons",
                                                                 "info_16.png"])))
        self.checkPopup.add(self.menuItemHelp)
        self.menuItemHelp.addActionListener(PopupActionListener(self.app))

        #Table with checks of selected tool and view
        self.checksTable = JTable()
        self.iconrenderer = IconRenderer()
        self.iconrenderer.setHorizontalAlignment(JLabel.CENTER)
        scrollPane = JScrollPane(self.checksTable)
        self.checksTable.setFillsViewportHeight(True)

        tableSelectionModel = self.checksTable.getSelectionModel()
        tableSelectionModel.addListSelectionListener(ChecksTableListener(app))

        self.checksTable.addMouseListener(ChecksTableClickListener(app,
            self.checkPopup,
            self.checksTable))

        #Favourite area status indicator
        self.favAreaIndicator = JLabel()
        self.update_favourite_zone_indicator()
        self.favAreaIndicator.addMouseListener(FavAreaIndicatorListener(app))

        #label with OSM id of the object currently edited and number of
        #errors still to review
        self.checksTextFld = JTextField("",
                                        editable=0,
                                        border=None,
                                        background=None)

        #checks buttons
        btnsIconsDir = File.separator.join([app.SCRIPTDIR, "images", "icons"])
        downloadIcon = ImageIcon(File.separator.join([btnsIconsDir, "download.png"]))
        self.downloadBtn = JButton(downloadIcon,
                                   actionPerformed=app.on_downloadBtn_clicked,
                                   enabled=0)
        startIcon = ImageIcon(File.separator.join([btnsIconsDir, "start_fixing.png"]))
        self.startBtn = JButton(startIcon,
                                actionPerformed=app.on_startBtn_clicked,
                                enabled=0)
        self.downloadBtn.setToolTipText(app.strings.getString("Download_errors_in_this_area"))
        self.startBtn.setToolTipText(app.strings.getString("Start_fixing_the_selected_errors"))

        #tab layout
        panel1 = JPanel(BorderLayout(0, 1))

        comboboxesPnl = JPanel(GridLayout(0, 2, 5, 0))
        comboboxesPnl.add(self.toolsCombo)
        comboboxesPnl.add(self.viewsCombo)

        checksPnl = JPanel(BorderLayout(0, 1))
        checksPnl.add(scrollPane, BorderLayout.CENTER)
        self.statsPanel = JPanel(BorderLayout(4, 0))
        self.statsPanel_def_color = self.statsPanel.getBackground()
        self.statsPanel.add(self.checksTextFld, BorderLayout.CENTER)
        self.statsPanel.add(self.favAreaIndicator, BorderLayout.LINE_START)
        checksPnl.add(self.statsPanel, BorderLayout.PAGE_END)

        checksButtonsPnl = JPanel(GridLayout(0, 2, 0, 0))
        checksButtonsPnl.add(self.downloadBtn)
        checksButtonsPnl.add(self.startBtn)

        panel1.add(comboboxesPnl, BorderLayout.PAGE_START)
        panel1.add(checksPnl, BorderLayout.CENTER)
        panel1.add(checksButtonsPnl, BorderLayout.PAGE_END)

### Second tab: errors fixing ##########################################
        #label with error stats
        self.errorTextFld = JTextField("",
                                       editable=0,
                                       border=None,
                                       background=None)
        #label with current error description
        self.errorDesc = JLabel("")
        self.errorDesc.setAlignmentX(0.5)

        #error buttons
        errorInfoBtnIcon = ImageProvider.get("info")
        self.errorInfoBtn = JButton(errorInfoBtnIcon,
                                    actionPerformed=app.on_errorInfoBtn_clicked,
                                    enabled=0)
        notErrorIcon = ImageIcon(File.separator.join([btnsIconsDir, "not_error.png"]))
        self.notErrorBtn = JButton(notErrorIcon,
                                   actionPerformed=app.on_falsePositiveBtn_clicked,
                                   enabled=0)
        ignoreIcon = ImageIcon(File.separator.join([btnsIconsDir, "skip.png"]))
        self.ignoreBtn = JButton(ignoreIcon,
                                 actionPerformed=app.on_ignoreBtn_clicked,
                                 enabled=0)
        correctedIcon = ImageIcon(File.separator.join([btnsIconsDir, "corrected.png"]))
        self.correctedBtn = JButton(correctedIcon,
                                    actionPerformed=app.on_correctedBtn_clicked,
                                    enabled=0)
        nextIcon = ImageIcon(File.separator.join([btnsIconsDir, "next.png"]))
        self.nextBtn = JButton(nextIcon,
                               actionPerformed=app.on_nextBtn_clicked,
                               enabled=0)
        #self.nextBtn.setMnemonic(KeyEvent.VK_RIGHT)
        self.errorInfoBtn.setToolTipText(app.strings.getString("open_error_info_dialog"))
        self.notErrorBtn.setToolTipText(app.strings.getString("flag_false_positive"))
        self.ignoreBtn.setToolTipText(app.strings.getString("Skip_and_don't_show_me_this_error_again"))
        self.correctedBtn.setToolTipText(app.strings.getString("flag_corrected_error"))
        self.nextBtn.setToolTipText(app.strings.getString("Go_to_next_error"))

        #tab layout
        self.panel2 = JPanel(BorderLayout())

        self.panel2.add(self.errorTextFld, BorderLayout.PAGE_START)
        self.panel2.add(self.errorDesc, BorderLayout.CENTER)

        errorButtonsPanel = JPanel(GridLayout(0, 5, 0, 0))
        errorButtonsPanel.add(self.errorInfoBtn)
        errorButtonsPanel.add(self.notErrorBtn)
        errorButtonsPanel.add(self.ignoreBtn)
        errorButtonsPanel.add(self.correctedBtn)
        errorButtonsPanel.add(self.nextBtn)
        self.panel2.add(errorButtonsPanel, BorderLayout.PAGE_END)

        #Layout
        self.tabbedPane = JTabbedPane()
        self.tabbedPane.addTab(self.app.strings.getString("Download"),
                               None,
                               panel1,
                               self.app.strings.getString("download_tab"))
        mainPnl.add(self.tabbedPane, BorderLayout.CENTER)
        self.createLayout(mainPnl, False, None)
Example #56
0
class BurpExtender(IBurpExtender, ITab, IMessageEditorController, IContextMenuFactory, ActionListener,
                   AbstractTableModel, Runnable):

    #
    # Implement IBurpExtender
    #
    def registerExtenderCallbacks(self, callbacks):
        # Initialize the global stdout stream
        global stdout

        # 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("Burpsuite Yara Scanner")

        # Create the log and a lock on which to synchronize when adding log entries
        self._log = ArrayList()
        self._lock = Lock()

        # main split pane
        splitpane = JSplitPane(JSplitPane.VERTICAL_SPLIT)

        # table of log entries
        logTable = Table(self)
        scrollPane = JScrollPane(logTable)
        splitpane.setLeftComponent(scrollPane)

        # Options panel
        optionsPanel = JPanel()
        optionsPanel.setLayout(GridBagLayout())
        constraints = GridBagConstraints()

        yara_exe_label = JLabel("Yara Executable Location:")
        constraints.fill = GridBagConstraints.HORIZONTAL
        constraints.gridx = 0
        constraints.gridy = 0
        optionsPanel.add(yara_exe_label, constraints)

        self._yara_exe_txtField = JTextField(25)
        constraints.fill = GridBagConstraints.HORIZONTAL
        constraints.gridx = 1
        constraints.gridy = 0
        optionsPanel.add(self._yara_exe_txtField, constraints)

        yara_rules_label = JLabel("Yara Rules File:")
        constraints.fill = GridBagConstraints.HORIZONTAL
        constraints.gridx = 0
        constraints.gridy = 1
        optionsPanel.add(yara_rules_label, constraints)
		
        self._yara_rules_files = Vector()
        self._yara_rules_files.add("< None >")
        self._yara_rules_fileList = JList(self._yara_rules_files)
        constraints.fill = GridBagConstraints.HORIZONTAL
        constraints.gridx = 1
        constraints.gridy = 1
        optionsPanel.add(self._yara_rules_fileList, constraints)
        
        self._yara_rules_select_files_button = JButton("Select Files")
        self._yara_rules_select_files_button.addActionListener(self)
        constraints.fill = GridBagConstraints.HORIZONTAL
        constraints.gridx = 1
        constraints.gridy = 2
        optionsPanel.add(self._yara_rules_select_files_button, constraints)

        self._yara_clear_button = JButton("Clear Yara Results Table")
        self._yara_clear_button.addActionListener(self)
        constraints.fill = GridBagConstraints.HORIZONTAL
        constraints.gridx = 1
        constraints.gridy = 3
        optionsPanel.add(self._yara_clear_button, constraints)

        # Tabs with request/response viewers
        viewerTabs = JTabbedPane()
        self._requestViewer = callbacks.createMessageEditor(self, False)
        self._responseViewer = callbacks.createMessageEditor(self, False)
        viewerTabs.addTab("Request", self._requestViewer.getComponent())
        viewerTabs.addTab("Response", self._responseViewer.getComponent())
        splitpane.setRightComponent(viewerTabs)

        # Tabs for the Yara output and the Options
        self._mainTabs = JTabbedPane()
        self._mainTabs.addTab("Yara Output", splitpane)
        self._mainTabs.addTab("Options", optionsPanel)

        # customize our UI components
        callbacks.customizeUiComponent(splitpane)
        callbacks.customizeUiComponent(logTable)
        callbacks.customizeUiComponent(scrollPane)
        callbacks.customizeUiComponent(viewerTabs)
        callbacks.customizeUiComponent(self._mainTabs)

        # add the custom tab to Burp's UI
        callbacks.addSuiteTab(self)

        # add ourselves as a context menu factory
        callbacks.registerContextMenuFactory(self)

        # Custom Menu Item
        self.menuItem = JMenuItem("Scan with Yara")
        self.menuItem.addActionListener(self)

        # obtain our output stream
        stdout = PrintWriter(callbacks.getStdout(), True)

        # Print a startup notification
        stdout.println("Burpsuite Yara scanner initialized.")

    #
    # Implement ITab
    #
    def getTabCaption(self):
        return "Yara"

    def getUiComponent(self):
        return self._mainTabs

    #
    # Implement IContextMenuFactory
    #
    def createMenuItems(self, invocation):
        if invocation.getInvocationContext() == invocation.CONTEXT_TARGET_SITE_MAP_TREE:
            self.requestResponses = invocation.getSelectedMessages()
            return [self.menuItem]
        else:
            self.requestResponses = None
        return None

    #
    # Implement Action
    #
    def actionPerformed(self, actionEvent):
        global yara_rules
        global yara_path

        if actionEvent.getSource() is self.menuItem:
            yara_path = self._yara_exe_txtField.getText()
            yara_rules = self._yara_rules_files
            t = Thread(self)
            t.start()
        elif actionEvent.getSource() is self._yara_clear_button:
            # Delete the LogEntry objects from the log
            row = self._log.size()
            self._lock.acquire()
            self._log.clear()

            # Update the Table
            self.fireTableRowsDeleted(0, row)

            # Clear data regarding any selected LogEntry objects from the request / response viewers
            self._requestViewer.setMessage([], True)
            self._responseViewer.setMessage([], False)
            self._currentlyDisplayedItem = None
            self._lock.release()
        elif actionEvent.getSource() is self._yara_rules_select_files_button:
            fileChooser = JFileChooser()
            yarFilter = FileNameExtensionFilter("Yara Rules", ["yar"])
            fileChooser.addChoosableFileFilter(yarFilter)
            fileChooser.setFileFilter(yarFilter)
            fileChooser.setMultiSelectionEnabled(True)
            fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY)
            ret = fileChooser.showOpenDialog(None)
            if ret == JFileChooser.APPROVE_OPTION:
                self._yara_rules_files.clear()
                for file in fileChooser.getSelectedFiles():
                    self._yara_rules_files.add(file.getPath())
                self._yara_rules_fileList.setListData(self._yara_rules_files)
        else:
            stdout.println("Unknown Event Received.")

    #
    # Implement Runnable
    #
    def run(self):
        self.yaraScan()

    #
    # Extend AbstractTableModel
    #
    def getRowCount(self):
        try:
            return self._log.size()
        except:
            return 0

    def getColumnCount(self):
        return 2

    def getColumnName(self, columnIndex):
        if columnIndex == 0:
            return "Rule Name"
        if columnIndex == 1:
            return "URL"
        return ""

    def getValueAt(self, rowIndex, columnIndex):
        logEntry = self._log.get(rowIndex)
        if columnIndex == 0:
            return logEntry._ruleName
        if columnIndex == 1:
            return logEntry._url.toString()
        return ""

    #
    # Implement IMessageEditorController
    # this allows our request/response viewers to obtain details about the messages being displayed
    #

    def getHttpService(self):
        return self._currentlyDisplayedItem.getHttpService()

    def getRequest(self):
        return self._currentlyDisplayedItem.getRequest()

    def getResponse(self):
        return self._currentlyDisplayedItem.getResponse()

    #
    # Implement the Yara scanning logic
    #
    def yaraScan(self):
        # If stdout has not yet been initialized, punt.
        if stdout is None:
            return

        # If the location of the yara executable and rules files are NULL, punt.
        if yara_rules is None or yara_path is None or yara_rules.size() == 0 or yara_rules.contains("< None >") or len(yara_path) == 0:
            JOptionPane.showMessageDialog(None, "Error: Please specify the path to the yara executable and rules file in "
                                                "the options tab.")
            return

        # If iRequestResponses is None, punt.
        if self.requestResponses is None:
            JOptionPane.showMessageDialog(None, "Error: No Request/Responses were selected.")
            return
        else:
            stdout.println("Processing %d item(s)." % len(self.requestResponses))

        # Get the OS temp folder
        os_name = System.getProperty("os.name").lower()

        temp_folder = None
        if "linux" in os_name:
            temp_folder = "/tmp"
        elif "windows" in os_name:
            temp_folder = os.environ.get("TEMP")
            if temp_folder is None:
                temp_folder = os.environ.get("TMP")

        if temp_folder is None:
            stdout.println("Error: Could not determine TEMP folder location.")
            return

        # Keep track of the number of matches.
        matchCount = 0

        # Process the site map selected messages
        for idx, iRequestResponse in enumerate(self.requestResponses):
            # Process the request
            request = iRequestResponse.getRequest()
            if request is not None:
                if len(request) > 0:
                    try:
                        # Yara does not support scanning from stdin so we will need to create a temp file and scan it
                        req_filename = os.path.join(temp_folder, "req_" + str(idx) + ".tmp")
                        req_file = open(req_filename, "wb")
                        req_file.write(request)
                        req_file.close()
                        for rules in yara_rules:
                            yara_req_output = subprocess.check_output([yara_path, rules, req_filename])
                            if yara_req_output is not None and len(yara_req_output) > 0:
                                ruleName = (yara_req_output.split())[0]
                                self._lock.acquire()
                                row = self._log.size()
                                # TODO: Don't add duplicate items to the table
                                self._log.add(LogEntry(ruleName, iRequestResponse, self._helpers.analyzeRequest(iRequestResponse).getUrl()))
                                self.fireTableRowsInserted(row, row)
                                self._lock.release()
                                matchCount += 1
                    except Exception as e:
                        JOptionPane.showMessageDialog(None, "Error running Yara. Please check your configuration and rules.")
                        return
                    finally:
                        # Remove the temp file
                        if req_file is not None:
                            req_file.close()
                        os.remove(req_filename)

            # Process the response
            response = iRequestResponse.getResponse()
            if response is not None:
                if len(response) > 0:
                    try:
                        # Yara does not support scanning from stdin so we will need to create a temp file and scan it
                        resp_filename = os.path.join(temp_folder, "resp_" + str(idx) + ".tmp")
                        resp_file = open(resp_filename, "wb")
                        resp_file.write(response)
                        resp_file.close()
                        for rules in yara_rules:
                            yara_resp_output = subprocess.check_output([yara_path, rules, resp_filename])
                            if yara_resp_output is not None and len(yara_resp_output) > 0:
                                ruleName = (yara_resp_output.split())[0]
                                self._lock.acquire()
                                row = self._log.size()
                                # TODO: Don't add duplicate items to the table
                                self._log.add(LogEntry(ruleName, iRequestResponse, self._helpers.analyzeRequest(iRequestResponse).getUrl()))
                                self.fireTableRowsInserted(row, row)
                                self._lock.release()
                                matchCount += 1
                    except Exception as e:
                        JOptionPane.showMessageDialog(None, "Error running Yara. Please check your configuration and rules.")
                        return
                    finally:
                        # Remove the temp file
                        if resp_file is not None:
                            resp_file.close()
                        os.remove(resp_filename)

        # Print a completion notification
        JOptionPane.showMessageDialog(None, "Yara scanning complete. %d rule(s) matched." % matchCount)
class BurpExtender(IBurpExtender, ITab, IMessageEditorController, IContextMenuFactory):
    
    #
    # implement IBurpExtender
    #
    
    def	registerExtenderCallbacks(self, callbacks):
    
        # keep a reference to our Burp callbacks object
        self._callbacks = callbacks
        # obtain an Burp extension helpers object
        self._helpers = callbacks.getHelpers()
        # set our extension name
        callbacks.setExtensionName("AuthMatrix - v0.5.2")

        # DB that holds everything users, roles, and messages
        self._db = MatrixDB()

        # For saving/loading config
        self._fc = JFileChooser()        

        # Used by ActionListeners
        selfExtender = self
        self._selectedColumn = -1
        self._selectedRow = -1


        # Table of User entries
        self._userTable = UserTable(self, model = UserTableModel(self._db))
        roleScrollPane = JScrollPane(self._userTable)
        self._userTable.redrawTable()

        # Table of Request (AKA Message) entries
        self._messageTable = MessageTable(self, model = MessageTableModel(self._db))
        messageScrollPane = JScrollPane(self._messageTable)
        self._messageTable.redrawTable()


        # Semi-Generic Popup stuff
        def addPopup(component, popup):
            class genericMouseListener(MouseAdapter):
                def mousePressed(self, e):
                    if e.isPopupTrigger():
                        self.showMenu(e)
                def mouseReleased(self, e):
                    if e.isPopupTrigger():
                        self.showMenu(e)
                def showMenu(self, e):
                    if type(component) is JTableHeader:
                        table = component.getTable()
                        column = component.columnAtPoint(e.getPoint())
                        if type(table) is MessageTable and column >= selfExtender._db.STATIC_MESSAGE_TABLE_COLUMN_COUNT or type(table) is UserTable and column >= selfExtender._db.STATIC_USER_TABLE_COLUMN_COUNT:
                            selfExtender._selectedColumn = column
                        else:
                            return
                    else:
                        selfExtender._selectedRow = component.rowAtPoint(e.getPoint())
                    popup.show(e.getComponent(), e.getX(), e.getY())
            component.addMouseListener(genericMouseListener())

        class actionRunMessage(ActionListener):
            def actionPerformed(self,e):
                if selfExtender._selectedRow >= 0:
                    if selfExtender._selectedRow not in selfExtender._messageTable.getSelectedRows():
                        indexes = [selfExtender._db.getMessageByRow(selfExtender._selectedRow)._index]
                    else:
                        indexes = [selfExtender._db.getMessageByRow(rowNum)._index for rowNum in selfExtender._messageTable.getSelectedRows()]
                    t = Thread(target=selfExtender.runMessagesThread, args = [indexes])
                    t.start()
                    selfExtender._selectedColumn = -1
                    # Redrawing the table happens in colorcode within the thread

        class actionRemoveMessage(ActionListener):
            def actionPerformed(self,e):
                if selfExtender._selectedRow >= 0:
                    if selfExtender._selectedRow not in selfExtender._messageTable.getSelectedRows():
                        indexes = [selfExtender._db.getMessageByRow(selfExtender._selectedRow)._index]
                    else:
                        indexes = [selfExtender._db.getMessageByRow(rowNum)._index for rowNum in selfExtender._messageTable.getSelectedRows()]
                    for i in indexes:
                        selfExtender._db.deleteMessage(i)
                    selfExtender._selectedColumn = -1
                    selfExtender._messageTable.redrawTable()

        class actionRemoveUser(ActionListener):
            def actionPerformed(self,e):
                if selfExtender._selectedRow >= 0:
                    if selfExtender._selectedRow not in selfExtender._userTable.getSelectedRows():
                        indexes = [selfExtender._db.getUserByRow(selfExtender._selectedRow)._index]
                    else:
                        indexes = [selfExtender._db.getUserByRow(rowNum)._index for rowNum in selfExtender._userTable.getSelectedRows()]
                    for i in indexes:
                        selfExtender._db.deleteUser(i)
                    selfExtender._selectedColumn = -1
                    selfExtender._userTable.redrawTable()

        # TODO combine these next two classes
        class actionRemoveRoleHeaderFromMessageTable(ActionListener):
            def actionPerformed(self,e):
                if selfExtender._selectedColumn >= 0:
                    selfExtender._db.deleteRole(selfExtender._db.getRoleByMessageTableColumn(selfExtender._selectedColumn)._index)
                    selfExtender._selectedColumn = -1
                    selfExtender._userTable.redrawTable()
                    selfExtender._messageTable.redrawTable()

        class actionRemoveRoleHeaderFromUserTable(ActionListener):
            def actionPerformed(self,e):
                if selfExtender._selectedColumn >= 0:
                    selfExtender._db.deleteRole(selfExtender._db.getRoleByUserTableColumn(selfExtender._selectedColumn)._index)
                    selfExtender._selectedColumn = -1
                    selfExtender._userTable.redrawTable()
                    selfExtender._messageTable.redrawTable()


        # Message Table popups
        messagePopup = JPopupMenu()
        addPopup(self._messageTable,messagePopup)
        messageRun = JMenuItem("Run Request(s)")
        messageRun.addActionListener(actionRunMessage())
        messagePopup.add(messageRun)
        messageRemove = JMenuItem("Remove Request(s)")
        messageRemove.addActionListener(actionRemoveMessage())
        messagePopup.add(messageRemove)

        messageHeaderPopup = JPopupMenu()
        addPopup(self._messageTable.getTableHeader(),messageHeaderPopup)
        roleRemoveFromMessageTable = JMenuItem("Remove Role")
        roleRemoveFromMessageTable.addActionListener(actionRemoveRoleHeaderFromMessageTable())
        messageHeaderPopup.add(roleRemoveFromMessageTable)

        # User Table popup
        userPopup = JPopupMenu()
        addPopup(self._userTable,userPopup)
        userRemove = JMenuItem("Remove Users(s)")
        userRemove.addActionListener(actionRemoveUser())
        userPopup.add(userRemove)

        userHeaderPopup = JPopupMenu()
        addPopup(self._userTable.getTableHeader(),userHeaderPopup)
        roleRemoveFromUserTable = JMenuItem("Remove Role")
        roleRemoveFromUserTable.addActionListener(actionRemoveRoleHeaderFromUserTable())
        userHeaderPopup.add(roleRemoveFromUserTable)

        # Top pane
        topPane = JSplitPane(JSplitPane.VERTICAL_SPLIT,roleScrollPane,messageScrollPane)

        # request tabs added to this tab on click in message table
        self._tabs = JTabbedPane()

        # Button pannel
        buttons = JPanel()
        runButton = JButton("Run", actionPerformed=self.runClick)
        newUserButton = JButton("New User", actionPerformed=self.getInputUserClick)
        newRoleButton = JButton("New Role", actionPerformed=self.getInputRoleClick)
        #debugButton = JButton("Debug", actionPerformed=self.printDB)
        saveButton = JButton("Save", actionPerformed=self.saveClick)
        loadButton = JButton("Load", actionPerformed=self.loadClick)
        clearButton = JButton("Clear", actionPerformed=self.clearClick)
        buttons.add(runButton)
        buttons.add(newUserButton)
        buttons.add(newRoleButton)
        #buttons.add(debugButton)
        buttons.add(saveButton)
        buttons.add(loadButton)
        buttons.add(clearButton)

        bottomPane = JSplitPane(JSplitPane.VERTICAL_SPLIT, self._tabs, buttons)

        # Main Pane
        self._splitpane = JSplitPane(JSplitPane.VERTICAL_SPLIT, topPane, bottomPane)
        


        # customize our UI components
        callbacks.customizeUiComponent(self._splitpane)
        callbacks.customizeUiComponent(topPane)
        callbacks.customizeUiComponent(bottomPane)
        callbacks.customizeUiComponent(messageScrollPane)
        callbacks.customizeUiComponent(roleScrollPane)
        callbacks.customizeUiComponent(self._messageTable)
        callbacks.customizeUiComponent(self._userTable)
        callbacks.customizeUiComponent(self._tabs)
        callbacks.customizeUiComponent(buttons)

        self._splitpane.setResizeWeight(0.5)
        topPane.setResizeWeight(0.3)
        bottomPane.setResizeWeight(0.95)


        # Handles checkbox color coding
        # Must be bellow the customizeUiComponent calls
        self._messageTable.setDefaultRenderer(Boolean, SuccessBooleanRenderer(self._db))


        # add the custom tab to Burp's UI
        callbacks.addSuiteTab(self)        
        # register SendTo option
        callbacks.registerContextMenuFactory(self)

        return
        
    ##
    ## implement ITab
    ##
    
    def getTabCaption(self):
        return "AuthMatrix"
    
    def getUiComponent(self):
        return self._splitpane
       

    ##
    ## Creates the sendto tab in other areas of Burp
    ##

    def createMenuItems(self, invocation):

        def addRequestsToTab(e):
            for messageInfo in messages:
                # saveBuffers is required since modifying the original from its source changes the saved objects, its not a copy
                messageIndex = self._db.createNewMessage(self._callbacks.saveBuffersToTempFiles(messageInfo), 
                    self._helpers.analyzeRequest(messageInfo).getUrl())
                #self._messageTable.getModel().addRow(row)
            self._messageTable.redrawTable()

        ret = []
        messages = invocation.getSelectedMessages()

        # Check if the messages in the target tree have a response
        valid = True
        if invocation.getInvocationContext() == invocation.CONTEXT_TARGET_SITE_MAP_TREE:
            for selected in messages:
                if not selected.getResponse():
                    valid = False

        if valid:
            menuItem = JMenuItem("Send request(s) to AuthMatrix");
            menuItem.addActionListener(addRequestsToTab)
            ret.append(menuItem)
        return ret
    
    ##
    ## implement IMessageEditorController
    ## this allows our request/response viewers to obtain details about the messages being displayed
    ##

    def getHttpService(self):
        return self._currentlyDisplayedItem.getHttpService()

    def getRequest(self):
        return self._currentlyDisplayedItem.getRequest()

    def getResponse(self):
        return self._currentlyDisplayedItem.getResponse()

    ##
    ## Actions on Bottom Row Button Clicks
    ##

    def printDB(self, e):
        out = ""
        for a in self._db.arrayOfUsers:
            out += str(a._index)+" "+a._name+" : "+str(a._roles)+"\n"
        for b in self._db.arrayOfMessages:
            out += str(b._index)+" "+str(b._roles)+"\n"
        JOptionPane.showMessageDialog(self._splitpane,out)

    def getInputUserClick(self, e):
        newUser = JOptionPane.showInputDialog(self._splitpane,"Enter New User:"******"Enter New Role:")
        if not newRole is None:
            self._db.getOrCreateRole(newRole)
            self._userTable.redrawTable()
            self._messageTable.redrawTable()

    def saveClick(self, e):
        returnVal = self._fc.showSaveDialog(self._splitpane)
        if returnVal == JFileChooser.APPROVE_OPTION:
            f = self._fc.getSelectedFile()
            if f.exists():
                result = JOptionPane.showConfirmDialog(self._splitpane, "The file exists, overwrite?", "Existing File", JOptionPane.YES_NO_OPTION)
                if result != JOptionPane.YES_OPTION:
                    return
            fileName = f.getPath()
            outs = ObjectOutputStream(FileOutputStream(fileName))
            outs.writeObject(self._db.getSaveableObject())
            outs.close()

    def loadClick(self,e):
        returnVal = self._fc.showOpenDialog(self._splitpane)
        if returnVal == JFileChooser.APPROVE_OPTION:
            warning = """
            CAUTION: 

            Loading a saved configuration deserializes data. 
            This action may pose a security threat to the application.
            Only proceed when the source and contents of this file is trusted. 

            Load Selected File?
            """
            result = JOptionPane.showOptionDialog(self._splitpane, warning, "Caution", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, None, ["OK", "Cancel"],"OK")
            if result != JOptionPane.YES_OPTION:
                return
            f = self._fc.getSelectedFile()
            fileName = f.getPath()
            
            ins = ObjectInputStream(FileInputStream(fileName))
            dbData=ins.readObject()
            ins.close()

            self._db.load(dbData,self)
            self._userTable.redrawTable()
            self._messageTable.redrawTable()

    def clearClick(self,e):
        result = JOptionPane.showConfirmDialog(self._splitpane, "Clear AuthMatrix Configuration?", "Clear Config", JOptionPane.YES_NO_OPTION)
        if result == JOptionPane.YES_OPTION:
            self._db.clear()
            self._tabs.removeAll()
            self._userTable.redrawTable()
            self._messageTable.redrawTable()

    def runClick(self,e):
        t = Thread(target=self.runMessagesThread)
        self._tabs.removeAll()
        t.start()

    def changeDomainPopup(self, oldDomain, index):
        hostField = JTextField(25)
        checkbox = JCheckBox()
        domainPanel = JPanel(GridLayout(0,1))
        domainPanel.add(JLabel("Request %s: Domain %s inaccessible. Enter new domain." % (str(index),oldDomain)))

        firstline = JPanel()
        firstline.add(JLabel("Host:"))
        firstline.add(hostField)
        domainPanel.add(firstline)
        secondline = JPanel()
        secondline.add(JLabel("Replace domain for all requests?"))
        secondline.add(checkbox)
        domainPanel.add(secondline)
        result = JOptionPane.showConfirmDialog(
            self._splitpane,domainPanel, "Domain Inaccessible", JOptionPane.OK_CANCEL_OPTION)
        cancelled = (result == JOptionPane.CANCEL_OPTION)
        if cancelled:
            return (False, None, False)
        return (True, hostField.getText(), checkbox.isSelected())

    ##
    ## Methods for running messages and analyzing results
    ##

    def runMessagesThread(self, messageIndexes=None):
        self._db.lock.acquire()
        try:
            indexes = messageIndexes
            if not indexes:
                indexes = self._db.getActiveMessageIndexes()
            self.clearColorResults(indexes)
            for index in indexes:
                self.runMessage(index)
                #self.colorCodeResults()
        except:
            traceback.print_exc(file=self._callbacks.getStderr())
        finally:
            self._db.lock.release()
            self.colorCodeResults()

    # Replaces headers/cookies with user's token
    def getNewHeader(self, requestInfo, userEntry):
        headers = requestInfo.getHeaders()
        if userEntry.isCookie():
            cookieHeader = "Cookie:"
            newheader = cookieHeader
            previousCookies = []
            # note: getHeaders has to be called again here cuz of java references
            for header in requestInfo.getHeaders():
                # Find and remove existing cookie header
                if str(header).startswith(cookieHeader):
                    previousCookies = str(header)[len(cookieHeader):].replace(" ","").split(";")
                    headers.remove(header)

            newCookies = userEntry._token.replace(" ","").split(";")
            newCookieVariableNames = []
            for newCookie in newCookies:
                # If its a valid cookie
                equalsToken = newCookie.find("=")
                if equalsToken >= 0:
                    newCookieVariableNames.append(newCookie[0:equalsToken+1])

            # Add all the old unchanged cookies
            for previousCookie in previousCookies:
                # If its a valid cookie
                equalsToken = previousCookie.find("=")
                if equalsToken >= 0:
                    if previousCookie[0:equalsToken+1] not in newCookieVariableNames:
                        newCookies.append(previousCookie)

            # Remove whitespace
            newCookies = [x for x in newCookies if x]
            newheader = cookieHeader+" "+";".join(newCookies)

        else:
            # TODO: Support multiple headers with a newline somehow
            newheader = userEntry._token
            # Remove previous HTTP Header
            colon = newheader.find(":")
            if colon >= 0:
                # getHeaders has to be called again here cuz of java references
                for header in requestInfo.getHeaders():
                    # If the header already exists, remove it
                    if str(header).startswith(newheader[0:colon+1]):
                        headers.remove(header)
        headers.add(newheader)
        return headers

    def runMessage(self, messageIndex):
        messageEntry = self._db.arrayOfMessages[messageIndex]
        # Clear Previous Results:
        messageEntry._roleResults = {}
        messageEntry._userRuns = {}

        messageInfo = messageEntry._requestResponse
        requestInfo = self._helpers.analyzeRequest(messageInfo)
        reqBody = messageInfo.getRequest()[requestInfo.getBodyOffset():]
        for userIndex in self._db.getActiveUserIndexes():
            userEntry = self._db.arrayOfUsers[userIndex]
            headers = self.getNewHeader(requestInfo, userEntry)

            # Add static CSRF token if available
            # TODO: Kinda hacky, but for now it will add the token as long as there is some content in the post body
            # Even if its a GET request.  This screws up when original requests have no body though... oh well...
            newBody = reqBody
            if userEntry._staticcsrf and len(reqBody):
                delimeter = userEntry._staticcsrf.find("=")
                if delimeter >= 0:
                    csrfname = userEntry._staticcsrf[0:delimeter]
                    csrfvalue = userEntry._staticcsrf[delimeter+1:]
                    params = requestInfo.getParameters()
                    for param in params:
                        if str(param.getName())==csrfname:
                            # Handle CSRF Tokens in Body
                            if param.getType() == 1:
                                newBody = reqBody[0:param.getValueStart()-requestInfo.getBodyOffset()] + StringUtil.toBytes(csrfvalue) + reqBody[param.getValueEnd()-requestInfo.getBodyOffset():]
                            # Handle CSRF Tokens in Cookies (for Cookie==Body mitigation technique):
                            if param.getType() == 2:
                                # TODO: required moving above portion to a function
                                # TODO: also need to think about when cookie name != postarg name
                                print "Cookie CSRF Tokens are not currently supported"
                    if newBody == reqBody:
                        newBody = reqBody+StringUtil.toBytes("&"+userEntry._staticcsrf)

            # Construct and send a message with the new headers
            message = self._helpers.buildHttpMessage(headers, newBody)
            requestResponse = self._callbacks.makeHttpRequest(messageInfo.getHttpService(),message)
            messageEntry.addRunByUserIndex(userIndex, self._callbacks.saveBuffersToTempFiles(requestResponse))

        # Grab all active roleIndexes that should succeed
        activeSuccessRoles = [index for index in messageEntry._roles.keys() if messageEntry._roles[index] and not self._db.arrayOfRoles[index].isDeleted()]
        # Check Role Results of message
        for roleIndex in self._db.getActiveRoleIndexes():
            success = self.checkResult(messageEntry, roleIndex, activeSuccessRoles)
            messageEntry.setRoleResultByRoleIndex(roleIndex, success)
                    
    def colorCodeResults(self):
        self._messageTable.redrawTable()

    def clearColorResults(self, messageIndexArray = None):
        if not messageIndexArray:
            messageIndexes = self._db.getActiveMessageIndexes()
        else:
            messageIndexes = messageIndexArray
        for messageIndex in messageIndexes:
            messageEntry = self._db.arrayOfMessages[messageIndex]
            messageEntry._roleResults = {}
            messageEntry._userRuns = {}
        self._messageTable.redrawTable()

    def checkResult(self, messageEntry, roleIndex, activeSuccessRoles):
        for userIndex in self._db.getActiveUserIndexes():
            userEntry = self._db.arrayOfUsers[userIndex]

            ignoreUser = False
            # if user is not in this role, ignore it
            if not userEntry._roles[roleIndex]:
                ignoreUser = True
            # If user is in any other role that should succeed, then ignore it
            for index in userEntry._roles.keys():
                if not index == roleIndex and userEntry._roles[index] and index in activeSuccessRoles:
                    ignoreUser = True

            if not ignoreUser:
                shouldSucceed = roleIndex in activeSuccessRoles
                requestResponse = messageEntry._userRuns[userEntry._index]
                resp = StringUtil.fromBytes(requestResponse.getResponse())
                found = re.search(messageEntry._successRegex, resp, re.DOTALL)
                succeeds = found if shouldSucceed else not found
                if not succeeds:
                    return False
        return True
    def	registerExtenderCallbacks(self, callbacks):
    
        # keep a reference to our Burp callbacks object
        self._callbacks = callbacks
        # obtain an Burp extension helpers object
        self._helpers = callbacks.getHelpers()
        # set our extension name
        callbacks.setExtensionName("AuthMatrix - v0.5.2")

        # DB that holds everything users, roles, and messages
        self._db = MatrixDB()

        # For saving/loading config
        self._fc = JFileChooser()        

        # Used by ActionListeners
        selfExtender = self
        self._selectedColumn = -1
        self._selectedRow = -1


        # Table of User entries
        self._userTable = UserTable(self, model = UserTableModel(self._db))
        roleScrollPane = JScrollPane(self._userTable)
        self._userTable.redrawTable()

        # Table of Request (AKA Message) entries
        self._messageTable = MessageTable(self, model = MessageTableModel(self._db))
        messageScrollPane = JScrollPane(self._messageTable)
        self._messageTable.redrawTable()


        # Semi-Generic Popup stuff
        def addPopup(component, popup):
            class genericMouseListener(MouseAdapter):
                def mousePressed(self, e):
                    if e.isPopupTrigger():
                        self.showMenu(e)
                def mouseReleased(self, e):
                    if e.isPopupTrigger():
                        self.showMenu(e)
                def showMenu(self, e):
                    if type(component) is JTableHeader:
                        table = component.getTable()
                        column = component.columnAtPoint(e.getPoint())
                        if type(table) is MessageTable and column >= selfExtender._db.STATIC_MESSAGE_TABLE_COLUMN_COUNT or type(table) is UserTable and column >= selfExtender._db.STATIC_USER_TABLE_COLUMN_COUNT:
                            selfExtender._selectedColumn = column
                        else:
                            return
                    else:
                        selfExtender._selectedRow = component.rowAtPoint(e.getPoint())
                    popup.show(e.getComponent(), e.getX(), e.getY())
            component.addMouseListener(genericMouseListener())

        class actionRunMessage(ActionListener):
            def actionPerformed(self,e):
                if selfExtender._selectedRow >= 0:
                    if selfExtender._selectedRow not in selfExtender._messageTable.getSelectedRows():
                        indexes = [selfExtender._db.getMessageByRow(selfExtender._selectedRow)._index]
                    else:
                        indexes = [selfExtender._db.getMessageByRow(rowNum)._index for rowNum in selfExtender._messageTable.getSelectedRows()]
                    t = Thread(target=selfExtender.runMessagesThread, args = [indexes])
                    t.start()
                    selfExtender._selectedColumn = -1
                    # Redrawing the table happens in colorcode within the thread

        class actionRemoveMessage(ActionListener):
            def actionPerformed(self,e):
                if selfExtender._selectedRow >= 0:
                    if selfExtender._selectedRow not in selfExtender._messageTable.getSelectedRows():
                        indexes = [selfExtender._db.getMessageByRow(selfExtender._selectedRow)._index]
                    else:
                        indexes = [selfExtender._db.getMessageByRow(rowNum)._index for rowNum in selfExtender._messageTable.getSelectedRows()]
                    for i in indexes:
                        selfExtender._db.deleteMessage(i)
                    selfExtender._selectedColumn = -1
                    selfExtender._messageTable.redrawTable()

        class actionRemoveUser(ActionListener):
            def actionPerformed(self,e):
                if selfExtender._selectedRow >= 0:
                    if selfExtender._selectedRow not in selfExtender._userTable.getSelectedRows():
                        indexes = [selfExtender._db.getUserByRow(selfExtender._selectedRow)._index]
                    else:
                        indexes = [selfExtender._db.getUserByRow(rowNum)._index for rowNum in selfExtender._userTable.getSelectedRows()]
                    for i in indexes:
                        selfExtender._db.deleteUser(i)
                    selfExtender._selectedColumn = -1
                    selfExtender._userTable.redrawTable()

        # TODO combine these next two classes
        class actionRemoveRoleHeaderFromMessageTable(ActionListener):
            def actionPerformed(self,e):
                if selfExtender._selectedColumn >= 0:
                    selfExtender._db.deleteRole(selfExtender._db.getRoleByMessageTableColumn(selfExtender._selectedColumn)._index)
                    selfExtender._selectedColumn = -1
                    selfExtender._userTable.redrawTable()
                    selfExtender._messageTable.redrawTable()

        class actionRemoveRoleHeaderFromUserTable(ActionListener):
            def actionPerformed(self,e):
                if selfExtender._selectedColumn >= 0:
                    selfExtender._db.deleteRole(selfExtender._db.getRoleByUserTableColumn(selfExtender._selectedColumn)._index)
                    selfExtender._selectedColumn = -1
                    selfExtender._userTable.redrawTable()
                    selfExtender._messageTable.redrawTable()


        # Message Table popups
        messagePopup = JPopupMenu()
        addPopup(self._messageTable,messagePopup)
        messageRun = JMenuItem("Run Request(s)")
        messageRun.addActionListener(actionRunMessage())
        messagePopup.add(messageRun)
        messageRemove = JMenuItem("Remove Request(s)")
        messageRemove.addActionListener(actionRemoveMessage())
        messagePopup.add(messageRemove)

        messageHeaderPopup = JPopupMenu()
        addPopup(self._messageTable.getTableHeader(),messageHeaderPopup)
        roleRemoveFromMessageTable = JMenuItem("Remove Role")
        roleRemoveFromMessageTable.addActionListener(actionRemoveRoleHeaderFromMessageTable())
        messageHeaderPopup.add(roleRemoveFromMessageTable)

        # User Table popup
        userPopup = JPopupMenu()
        addPopup(self._userTable,userPopup)
        userRemove = JMenuItem("Remove Users(s)")
        userRemove.addActionListener(actionRemoveUser())
        userPopup.add(userRemove)

        userHeaderPopup = JPopupMenu()
        addPopup(self._userTable.getTableHeader(),userHeaderPopup)
        roleRemoveFromUserTable = JMenuItem("Remove Role")
        roleRemoveFromUserTable.addActionListener(actionRemoveRoleHeaderFromUserTable())
        userHeaderPopup.add(roleRemoveFromUserTable)

        # Top pane
        topPane = JSplitPane(JSplitPane.VERTICAL_SPLIT,roleScrollPane,messageScrollPane)

        # request tabs added to this tab on click in message table
        self._tabs = JTabbedPane()

        # Button pannel
        buttons = JPanel()
        runButton = JButton("Run", actionPerformed=self.runClick)
        newUserButton = JButton("New User", actionPerformed=self.getInputUserClick)
        newRoleButton = JButton("New Role", actionPerformed=self.getInputRoleClick)
        #debugButton = JButton("Debug", actionPerformed=self.printDB)
        saveButton = JButton("Save", actionPerformed=self.saveClick)
        loadButton = JButton("Load", actionPerformed=self.loadClick)
        clearButton = JButton("Clear", actionPerformed=self.clearClick)
        buttons.add(runButton)
        buttons.add(newUserButton)
        buttons.add(newRoleButton)
        #buttons.add(debugButton)
        buttons.add(saveButton)
        buttons.add(loadButton)
        buttons.add(clearButton)

        bottomPane = JSplitPane(JSplitPane.VERTICAL_SPLIT, self._tabs, buttons)

        # Main Pane
        self._splitpane = JSplitPane(JSplitPane.VERTICAL_SPLIT, topPane, bottomPane)
        


        # customize our UI components
        callbacks.customizeUiComponent(self._splitpane)
        callbacks.customizeUiComponent(topPane)
        callbacks.customizeUiComponent(bottomPane)
        callbacks.customizeUiComponent(messageScrollPane)
        callbacks.customizeUiComponent(roleScrollPane)
        callbacks.customizeUiComponent(self._messageTable)
        callbacks.customizeUiComponent(self._userTable)
        callbacks.customizeUiComponent(self._tabs)
        callbacks.customizeUiComponent(buttons)

        self._splitpane.setResizeWeight(0.5)
        topPane.setResizeWeight(0.3)
        bottomPane.setResizeWeight(0.95)


        # Handles checkbox color coding
        # Must be bellow the customizeUiComponent calls
        self._messageTable.setDefaultRenderer(Boolean, SuccessBooleanRenderer(self._db))


        # add the custom tab to Burp's UI
        callbacks.addSuiteTab(self)        
        # register SendTo option
        callbacks.registerContextMenuFactory(self)

        return
Example #59
0
    def registerExtenderCallbacks(self, callbacks):
        # Initialize the global stdout stream
        global stdout

        # 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("Burpsuite Yara Scanner")

        # Create the log and a lock on which to synchronize when adding log entries
        self._log = ArrayList()
        self._lock = Lock()

        # main split pane
        splitpane = JSplitPane(JSplitPane.VERTICAL_SPLIT)

        # table of log entries
        logTable = Table(self)
        scrollPane = JScrollPane(logTable)
        splitpane.setLeftComponent(scrollPane)

        # Options panel
        optionsPanel = JPanel()
        optionsPanel.setLayout(GridBagLayout())
        constraints = GridBagConstraints()

        yara_exe_label = JLabel("Yara Executable Location:")
        constraints.fill = GridBagConstraints.HORIZONTAL
        constraints.gridx = 0
        constraints.gridy = 0
        optionsPanel.add(yara_exe_label, constraints)

        self._yara_exe_txtField = JTextField(25)
        constraints.fill = GridBagConstraints.HORIZONTAL
        constraints.gridx = 1
        constraints.gridy = 0
        optionsPanel.add(self._yara_exe_txtField, constraints)

        yara_rules_label = JLabel("Yara Rules File:")
        constraints.fill = GridBagConstraints.HORIZONTAL
        constraints.gridx = 0
        constraints.gridy = 1
        optionsPanel.add(yara_rules_label, constraints)
		
        self._yara_rules_files = Vector()
        self._yara_rules_files.add("< None >")
        self._yara_rules_fileList = JList(self._yara_rules_files)
        constraints.fill = GridBagConstraints.HORIZONTAL
        constraints.gridx = 1
        constraints.gridy = 1
        optionsPanel.add(self._yara_rules_fileList, constraints)
        
        self._yara_rules_select_files_button = JButton("Select Files")
        self._yara_rules_select_files_button.addActionListener(self)
        constraints.fill = GridBagConstraints.HORIZONTAL
        constraints.gridx = 1
        constraints.gridy = 2
        optionsPanel.add(self._yara_rules_select_files_button, constraints)

        self._yara_clear_button = JButton("Clear Yara Results Table")
        self._yara_clear_button.addActionListener(self)
        constraints.fill = GridBagConstraints.HORIZONTAL
        constraints.gridx = 1
        constraints.gridy = 3
        optionsPanel.add(self._yara_clear_button, constraints)

        # Tabs with request/response viewers
        viewerTabs = JTabbedPane()
        self._requestViewer = callbacks.createMessageEditor(self, False)
        self._responseViewer = callbacks.createMessageEditor(self, False)
        viewerTabs.addTab("Request", self._requestViewer.getComponent())
        viewerTabs.addTab("Response", self._responseViewer.getComponent())
        splitpane.setRightComponent(viewerTabs)

        # Tabs for the Yara output and the Options
        self._mainTabs = JTabbedPane()
        self._mainTabs.addTab("Yara Output", splitpane)
        self._mainTabs.addTab("Options", optionsPanel)

        # customize our UI components
        callbacks.customizeUiComponent(splitpane)
        callbacks.customizeUiComponent(logTable)
        callbacks.customizeUiComponent(scrollPane)
        callbacks.customizeUiComponent(viewerTabs)
        callbacks.customizeUiComponent(self._mainTabs)

        # add the custom tab to Burp's UI
        callbacks.addSuiteTab(self)

        # add ourselves as a context menu factory
        callbacks.registerContextMenuFactory(self)

        # Custom Menu Item
        self.menuItem = JMenuItem("Scan with Yara")
        self.menuItem.addActionListener(self)

        # obtain our output stream
        stdout = PrintWriter(callbacks.getStdout(), True)

        # Print a startup notification
        stdout.println("Burpsuite Yara scanner initialized.")
Example #60
0
class QatDialog(ToggleDialog):
    """ToggleDialog for error type selection and buttons for reviewing
       errors in sequence
    """
    def __init__(self, name, iconName, tooltip, shortcut, height, app):
        ToggleDialog.__init__(self, name, iconName, tooltip, shortcut, height)
        self.app = app
        tools = app.tools

        #Main panel of the dialog
        mainPnl = JPanel(BorderLayout())
        mainPnl.setBorder(BorderFactory.createEmptyBorder(0, 1, 1, 1))

### First tab: errors selection and download ###########################
        #ComboBox with tools names
        self.toolsComboModel = DefaultComboBoxModel()
        for tool in tools:
            self.add_data_to_models(tool)
        self.toolsCombo = JComboBox(self.toolsComboModel,
                                    actionListener=ToolsComboListener(app))
        renderer = ToolsComboRenderer(self.app)
        renderer.setPreferredSize(Dimension(20, 20))
        self.toolsCombo.setRenderer(renderer)
        self.toolsCombo.setToolTipText(app.strings.getString("Select_a_quality_assurance_tool"))

        #ComboBox with categories names ("views"), of the selected tool
        self.viewsCombo = JComboBox(actionListener=ViewsComboListener(app))
        self.viewsCombo.setToolTipText(app.strings.getString("Select_a_category_of_error"))

        #Popup for checks table
        self.checkPopup = JPopupMenu()
        #add favourite check
        self.menuItemAdd = JMenuItem(self.app.strings.getString("Add_to_favourites"))
        self.menuItemAdd.setIcon(ImageIcon(File.separator.join([self.app.SCRIPTDIR,
                                                                "tools",
                                                                "data",
                                                                "Favourites",
                                                                "icons",
                                                                "tool_16.png"])))
        self.menuItemAdd.addActionListener(PopupActionListener(self.app))
        self.checkPopup.add(self.menuItemAdd)
        #remove favourite check
        self.menuItemRemove = JMenuItem(self.app.strings.getString("Remove_from_favourites"))
        self.menuItemRemove.setIcon(ImageIcon(File.separator.join([self.app.SCRIPTDIR,
                                                                   "tools",
                                                                   "data",
                                                                   "Favourites",
                                                                   "icons",
                                                                   "black_tool_16.png"])))
        self.menuItemRemove.addActionListener(PopupActionListener(self.app))
        self.checkPopup.add(self.menuItemRemove)
        #Help link for selected check
        self.menuItemHelp = JMenuItem(self.app.strings.getString("check_help"))
        self.menuItemHelp.setIcon(ImageIcon(File.separator.join([self.app.SCRIPTDIR,
                                                                 "images",
                                                                 "icons",
                                                                 "info_16.png"])))
        self.checkPopup.add(self.menuItemHelp)
        self.menuItemHelp.addActionListener(PopupActionListener(self.app))

        #Table with checks of selected tool and view
        self.checksTable = JTable()
        self.iconrenderer = IconRenderer()
        self.iconrenderer.setHorizontalAlignment(JLabel.CENTER)
        scrollPane = JScrollPane(self.checksTable)
        self.checksTable.setFillsViewportHeight(True)

        tableSelectionModel = self.checksTable.getSelectionModel()
        tableSelectionModel.addListSelectionListener(ChecksTableListener(app))

        self.checksTable.addMouseListener(ChecksTableClickListener(app,
            self.checkPopup,
            self.checksTable))

        #Favourite area status indicator
        self.favAreaIndicator = JLabel()
        self.update_favourite_zone_indicator()
        self.favAreaIndicator.addMouseListener(FavAreaIndicatorListener(app))

        #label with OSM id of the object currently edited and number of
        #errors still to review
        self.checksTextFld = JTextField("",
                                        editable=0,
                                        border=None,
                                        background=None)

        #checks buttons
        btnsIconsDir = File.separator.join([app.SCRIPTDIR, "images", "icons"])
        downloadIcon = ImageIcon(File.separator.join([btnsIconsDir, "download.png"]))
        self.downloadBtn = JButton(downloadIcon,
                                   actionPerformed=app.on_downloadBtn_clicked,
                                   enabled=0)
        startIcon = ImageIcon(File.separator.join([btnsIconsDir, "start_fixing.png"]))
        self.startBtn = JButton(startIcon,
                                actionPerformed=app.on_startBtn_clicked,
                                enabled=0)
        self.downloadBtn.setToolTipText(app.strings.getString("Download_errors_in_this_area"))
        self.startBtn.setToolTipText(app.strings.getString("Start_fixing_the_selected_errors"))

        #tab layout
        panel1 = JPanel(BorderLayout(0, 1))

        comboboxesPnl = JPanel(GridLayout(0, 2, 5, 0))
        comboboxesPnl.add(self.toolsCombo)
        comboboxesPnl.add(self.viewsCombo)

        checksPnl = JPanel(BorderLayout(0, 1))
        checksPnl.add(scrollPane, BorderLayout.CENTER)
        self.statsPanel = JPanel(BorderLayout(4, 0))
        self.statsPanel_def_color = self.statsPanel.getBackground()
        self.statsPanel.add(self.checksTextFld, BorderLayout.CENTER)
        self.statsPanel.add(self.favAreaIndicator, BorderLayout.LINE_START)
        checksPnl.add(self.statsPanel, BorderLayout.PAGE_END)

        checksButtonsPnl = JPanel(GridLayout(0, 2, 0, 0))
        checksButtonsPnl.add(self.downloadBtn)
        checksButtonsPnl.add(self.startBtn)

        panel1.add(comboboxesPnl, BorderLayout.PAGE_START)
        panel1.add(checksPnl, BorderLayout.CENTER)
        panel1.add(checksButtonsPnl, BorderLayout.PAGE_END)

### Second tab: errors fixing ##########################################
        #label with error stats
        self.errorTextFld = JTextField("",
                                       editable=0,
                                       border=None,
                                       background=None)
        #label with current error description
        self.errorDesc = JLabel("")
        self.errorDesc.setAlignmentX(0.5)

        #error buttons
        errorInfoBtnIcon = ImageProvider.get("info")
        self.errorInfoBtn = JButton(errorInfoBtnIcon,
                                    actionPerformed=app.on_errorInfoBtn_clicked,
                                    enabled=0)
        notErrorIcon = ImageIcon(File.separator.join([btnsIconsDir, "not_error.png"]))
        self.notErrorBtn = JButton(notErrorIcon,
                                   actionPerformed=app.on_falsePositiveBtn_clicked,
                                   enabled=0)
        ignoreIcon = ImageIcon(File.separator.join([btnsIconsDir, "skip.png"]))
        self.ignoreBtn = JButton(ignoreIcon,
                                 actionPerformed=app.on_ignoreBtn_clicked,
                                 enabled=0)
        correctedIcon = ImageIcon(File.separator.join([btnsIconsDir, "corrected.png"]))
        self.correctedBtn = JButton(correctedIcon,
                                    actionPerformed=app.on_correctedBtn_clicked,
                                    enabled=0)
        nextIcon = ImageIcon(File.separator.join([btnsIconsDir, "next.png"]))
        self.nextBtn = JButton(nextIcon,
                               actionPerformed=app.on_nextBtn_clicked,
                               enabled=0)
        #self.nextBtn.setMnemonic(KeyEvent.VK_RIGHT)
        self.errorInfoBtn.setToolTipText(app.strings.getString("open_error_info_dialog"))
        self.notErrorBtn.setToolTipText(app.strings.getString("flag_false_positive"))
        self.ignoreBtn.setToolTipText(app.strings.getString("Skip_and_don't_show_me_this_error_again"))
        self.correctedBtn.setToolTipText(app.strings.getString("flag_corrected_error"))
        self.nextBtn.setToolTipText(app.strings.getString("Go_to_next_error"))

        #tab layout
        self.panel2 = JPanel(BorderLayout())

        self.panel2.add(self.errorTextFld, BorderLayout.PAGE_START)
        self.panel2.add(self.errorDesc, BorderLayout.CENTER)

        errorButtonsPanel = JPanel(GridLayout(0, 5, 0, 0))
        errorButtonsPanel.add(self.errorInfoBtn)
        errorButtonsPanel.add(self.notErrorBtn)
        errorButtonsPanel.add(self.ignoreBtn)
        errorButtonsPanel.add(self.correctedBtn)
        errorButtonsPanel.add(self.nextBtn)
        self.panel2.add(errorButtonsPanel, BorderLayout.PAGE_END)

        #Layout
        self.tabbedPane = JTabbedPane()
        self.tabbedPane.addTab(self.app.strings.getString("Download"),
                               None,
                               panel1,
                               self.app.strings.getString("download_tab"))
        mainPnl.add(self.tabbedPane, BorderLayout.CENTER)
        self.createLayout(mainPnl, False, None)

    def add_data_to_models(self, tool):
        """Add data of a tool to the models of the dialog components
        """
        #tools combobox model
        if tool == self.app.favouritesTool:
            self.toolsComboModel.addElement(JSeparator())
        self.toolsComboModel.addElement(tool)

        #views combobox model
        tool.viewsComboModel = DefaultComboBoxModel()
        for view in tool.views:
            tool.viewsComboModel.addElement(view.title)

        #checks table, one TableModel for each view, of each tool
        columns = ["",
                   self.app.strings.getString("Check"),
                   self.app.strings.getString("Errors")]
        for view in tool.views:
            tableRows = []
            for check in view.checks:
                if check.icon is not None:
                    icon = check.icon
                else:
                    icon = ""
                errorsNumber = ""
                tableRows.append([icon, check.title, errorsNumber])
            view.tableModel = MyTableModel(tableRows, columns)

    def update_favourite_zone_indicator(self):
        #icon
        if self.app.favZone is not None:
            self.favAreaIndicator.setIcon(self.app.favZone.icon)
            #tooltip
            messageArguments = array([self.app.favZone.name], String)
            formatter = MessageFormat("")
            formatter.applyPattern(self.app.strings.getString("favAreaIndicator_tooltip"))
            msg = formatter.format(messageArguments)
            self.favAreaIndicator.setToolTipText(msg)
            #status
            self.favAreaIndicator.setVisible(self.app.favouriteZoneStatus)

    def set_checksTextFld_color(self, color):
        """Change color of textField under checksTable
        """
        colors = {"white": (255, 255, 255),
                  "black": (0, 0, 0),
                  "green": (100, 200, 0),
                  "red": (200, 0, 0)}
        if color == "default":
            self.statsPanel.background = self.statsPanel_def_color
            self.checksTextFld.foreground = colors["black"]
        else:
            self.statsPanel.background = colors[color]
            self.checksTextFld.foreground = colors["white"]

    def change_selection(self, source):
        """Change comboboxes and checks table selections after a
           selection has been made by the user
        """
        if source in ("menu", "layer", "add favourite"):
            self.app.selectionChangedFromMenuOrLayer = True
            self.toolsCombo.setSelectedItem(self.app.selectedTool)
            self.viewsCombo.setModel(self.app.selectedTool.viewsComboModel)
            self.viewsCombo.setSelectedItem(self.app.selectedView.title)

            self.checksTable.setModel(self.app.selectedTableModel)
            self.refresh_checksTable_columns_geometries()
            for i, c in enumerate(self.app.selectedView.checks):
                if c == self.app.selectedChecks[0]:
                    break
            self.checksTable.setRowSelectionInterval(i, i)
            self.app.selectionChangedFromMenuOrLayer = False
        else:
            self.app.selectionChangedFromMenuOrLayer = False
            if source == "toolsCombo":
                self.viewsCombo.setModel(self.app.selectedTool.viewsComboModel)
                self.viewsCombo.setSelectedIndex(0)
            elif source == "viewsCombo":
                self.checksTable.setModel(self.app.selectedTableModel)
                self.refresh_checksTable_columns_geometries()
                if self.app.selectedView.checks != []:  # favourite checks may be none
                    self.checksTable.setRowSelectionInterval(0, 0)

    def refresh_checksTable_columns_geometries(self):
        self.checksTable.getColumnModel().getColumn(0).setCellRenderer(self.iconrenderer)
        self.checksTable.getColumnModel().getColumn(0).setMaxWidth(25)
        self.checksTable.getColumnModel().getColumn(2).setMaxWidth(60)

    def activate_error_tab(self, status):
        if status:
            if self.tabbedPane.getTabCount() == 1:
                self.tabbedPane.addTab(self.app.strings.getString("Fix"),
                                       None,
                                       self.panel2,
                                       self.app.strings.getString("fix_tab"))
        else:
            if self.tabbedPane.getTabCount() == 2:
                self.tabbedPane.remove(1)

    def update_checks_buttons(self):
        """This method sets the status of downloadBtn and startBtn
        """
        #none check selected
        if len(self.app.selectedChecks) == 0:
            self.downloadBtn.setEnabled(False)
            self.startBtn.setEnabled(False)
        else:
            #some check selected
            self.downloadBtn.setEnabled(True)
            if len(self.app.selectedChecks) > 1:
                self.startBtn.setEnabled(False)
            else:
                #only one check is selected
                self.app.errors = self.app.selectedChecks[0].errors
                if self.app.errors is None or len(self.app.errors) == 0:
                    #errors file has not been downloaded and parsed yet
                    self.startBtn.setEnabled(False)
                else:
                    #errors file has been downloaded and parsed
                    if self.app.selectedChecks[0].toDo == 0:
                        #all errors have been corrected
                        self.startBtn.setEnabled(False)
                    else:
                        self.startBtn.setEnabled(True)
                        #self.nextBtn.setEnabled(True)

    def update_error_buttons(self, mode):
        """This method sets the status of:
           ignoreBtn, falsePositiveBtn, correctedBtn, nextBtn
        """
        if mode == "new error":
            status = True
        else:
            status = False
        if self.app.selectedChecks[0].tool.fixedFeedbackMode is None:
            self.correctedBtn.setEnabled(False)
        else:
            self.correctedBtn.setEnabled(status)
        if self.app.selectedChecks[0].tool.falseFeedbackMode is None:
            self.notErrorBtn.setEnabled(False)
        else:
            self.notErrorBtn.setEnabled(status)
        self.errorInfoBtn.setEnabled(status)
        self.ignoreBtn.setEnabled(status)

        if mode in ("reset", "review end"):
            self.nextBtn.setEnabled(False)
        elif mode in ("errors downloaded", "show stats", "new error"):
            self.nextBtn.setEnabled(True)

    def update_text_fields(self, mode, errorInfo=""):
        """This method updates the text in:
           checksTextFld, errorDesc, errorTextFld
        """
        self.errorDesc.text = ""
        if mode == "review end":
            cheksTextColor = "green"
            checksText = self.app.strings.getString("All_errors_reviewed.")
            errorText = self.app.strings.getString("All_errors_reviewed.")
        elif mode == "reset":
            cheksTextColor = "default"
            checksText = ""
            errorText = ""
        elif mode == "show stats":
            cheksTextColor = "default"
            checksText = "%s %d / %s" % (
                         self.app.strings.getString("to_do"),
                         self.app.selectedChecks[0].toDo,
                         len(self.app.selectedChecks[0].errors))
            #print "checks text", checksText
            errorText = "%s%s %d / %s" % (
                        errorInfo,
                        self.app.strings.getString("to_do"),
                        self.app.selectedChecks[0].toDo,
                        len(self.app.selectedChecks[0].errors))
            #print "error text", errorText
            if self.app.selectedError is not None and self.app.selectedError.desc != "":
                self.errorDesc.text = "<html>%s</html>" % self.app.selectedError.desc

        self.set_checksTextFld_color(cheksTextColor)
        self.checksTextFld.text = checksText
        self.errorTextFld.text = errorText
        self.update_statsPanel_status()

    def update_statsPanel_status(self):
        if self.checksTextFld.text == "" and not self.app.favouriteZoneStatus:
            self.statsPanel.setVisible(False)
        else:
            self.statsPanel.setVisible(True)