def __init__(self, tree): TreeCellEditor.__init__(self) self.editor = None self.tree = tree flowLayout = FlowLayout(FlowLayout.LEFT, 0, 0) self.cbPanel = JPanel(flowLayout) self.cb = JCheckBox(actionPerformed=self.checked) self.cbPanel.add(self.cb) self.cbLabel = JLabel() self.cbPanel.add(self.cbLabel) self.tcbPanel = JPanel(flowLayout) self.tcb = TristateCheckBox(self.checked) self.tcbPanel.add(self.tcb) self.tcbLabel = JLabel() self.tcbPanel.add(self.tcbLabel) self.rbPanel = JPanel(flowLayout) self.rb = JRadioButton(actionPerformed=self.checked) self.rbPanel.add(self.rb) self.rbLabel = JLabel() self.rbPanel.add(self.rbLabel) self.tfPanel = JPanel(flowLayout) self.tfLabel = JLabel() self.tfPanel.add(self.tfLabel) self.tf = JTextField() self.tf.setColumns(12) self.tf.addActionListener(self) self.tfPanel.add(self.tf)
def __init__(self): DefaultTreeCellRenderer.__init__(self) flowLayout = FlowLayout(FlowLayout.LEFT, 0, 0) self.cbPanel = JPanel(flowLayout) self.cb = JCheckBox() self.cb.setBackground(None) self.cbPanel.add(self.cb) self.cbLabel = JLabel() self.cbPanel.add(self.cbLabel) self.tcbPanel = JPanel(flowLayout) self.tcb = TristateCheckBox() self.tcb.setBackground(None) self.tcbPanel.add(self.tcb) self.tcbLabel = JLabel() self.tcbPanel.add(self.tcbLabel) self.rbPanel = JPanel(flowLayout) self.rb = JRadioButton() self.rb.setBackground(None) self.rbPanel.add(self.rb) self.rbLabel = JLabel() self.rbPanel.add(self.rbLabel)
def init(self): global exampleList self.thinFont = Font("Dialog", 0, 10) self.pane = self.getContentPane() self.examples = exampleList.keys() self.examples.sort() self.exampleSelector = JList(self.examples, valueChanged=self.valueChanged) self.exampleSelector.setSelectionMode(ListSelectionModel.SINGLE_SELECTION) self.exampleSelector.setLayoutOrientation(JList.VERTICAL) self.exampleSelector.setPreferredSize(Dimension(150,500)) self.exampleSelector.setBackground(Color(0.95, 0.95, 0.98)) self.exampleSelector.setFont(self.thinFont) self.centerPanel = JPanel(BorderLayout()) self.canvas = GraphCanvas() self.canvas.setApplet(self) self.buttonRow = JPanel(FlowLayout()) self.backButton = JButton("<", actionPerformed = self.backAction) self.backButton.setFont(self.thinFont) self.continueButton = JButton("continue >", actionPerformed=self.continueAction) self.continueButton.setFont(self.thinFont) self.scaleGroup = ButtonGroup() self.linearButton = JRadioButton("linear scale", actionPerformed=self.linearAction) self.linearButton.setSelected(True) self.linearButton.setFont(self.thinFont) self.logarithmicButton = JRadioButton("logarithmic scale", actionPerformed=self.logarithmicAction) self.logarithmicButton.setFont(self.thinFont) self.aboutButton = JButton("About...", actionPerformed=self.aboutAction) self.aboutButton.setFont(self.thinFont) self.scaleGroup.add(self.linearButton) self.scaleGroup.add(self.logarithmicButton) self.buttonRow.add(self.backButton) self.buttonRow.add(self.continueButton) self.buttonRow.add(JLabel(" "*5)) self.buttonRow.add(self.linearButton) self.buttonRow.add(self.logarithmicButton) self.buttonRow.add(JLabel(" "*20)); self.buttonRow.add(self.aboutButton) self.centerPanel.add(self.canvas, BorderLayout.CENTER) self.centerPanel.add(self.buttonRow, BorderLayout.PAGE_END) self.helpText = JTextPane() self.helpText.setBackground(Color(1.0, 1.0, 0.5)) self.helpText.setPreferredSize(Dimension(800,80)) self.helpText.setText(re_sub("[ \\n]+", " ", """ Please select one of the examples in the list on the left! """)) self.pane.add(self.exampleSelector, BorderLayout.LINE_START) self.pane.add(self.centerPanel, BorderLayout.CENTER) self.pane.add(self.helpText, BorderLayout.PAGE_END) self.graph = None self.simulation = None self.touched = "" self.selected = "" self.gfxDriver = None
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
def _create_output_panel(self): self.outputPanel = JPanel() self.outputEditor = self.callbacks.createTextEditor() self.outputEditor.editable = False self.outputText = self.outputEditor.component self.clearOutputButton = JButton('Clear', actionPerformed=self.clear_stdout) self.outputButtonGroup = ButtonGroup() self.outputFileRadioButton = JRadioButton( 'Save to File:', actionPerformed=self.save_file_output) self.outputUIRadioButton = JRadioButton( 'Show in UI:', selected=True, actionPerformed=self.view_ui_output) self.outputFileTextField = JTextField(50, enabled=False, disabledTextColor=Color.black) self.outputFileBrowseButton = JButton( 'Browse...', enabled=False, actionPerformed=self.set_output_file) self.outputButtonGroup.add(self.outputFileRadioButton) self.outputButtonGroup.add(self.outputUIRadioButton) outputLayout = GroupLayout(self.outputPanel, autoCreateGaps=True, autoCreateContainerGaps=True) outputLayout.setHorizontalGroup( outputLayout.createParallelGroup().addGroup( outputLayout.createSequentialGroup().addComponent( self.outputFileRadioButton).addComponent( self.outputFileTextField, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE).addComponent( self.outputFileBrowseButton)).addComponent( self.outputUIRadioButton).addComponent( self.outputText).addComponent( self.clearOutputButton)) outputLayout.setVerticalGroup( outputLayout.createSequentialGroup().addGroup( outputLayout.createParallelGroup().addComponent( self.outputFileRadioButton).addComponent( self.outputFileTextField, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE).addComponent( self.outputFileBrowseButton)).addComponent( self.outputUIRadioButton).addComponent( self.outputText).addComponent( self.clearOutputButton)) self.outputPanel.layout = outputLayout
def __init__(self): self.mainDir = "" self.setTitle("Dots Quality Check") self.setSize(250, 300) self.setLocation(20,120) self.addWindowFocusListener(self) self.Panel = JPanel(GridLayout(0,1)) self.add(self.Panel) self.openNextButton = JButton("Open Next Random", actionPerformed=self.openRandom) self.Panel.add(self.openNextButton) self.saveButton = JButton("Save", actionPerformed=self.save, enabled=False) self.Panel.add(self.saveButton) self.cropButton = JButton("Crop values from here", actionPerformed=self.cropVals) self.Panel.add(self.cropButton) self.DiscardButton = JButton("Discard cell", actionPerformed=self.discardCell) self.Panel.add(self.DiscardButton) self.quitButton = JButton("Quit script",actionPerformed=self.quit) self.Panel.add(self.quitButton) annoPanel = JPanel() #add gridlayout self.wtRButton = JRadioButton("wt", actionCommand="wt") self.wtRButton.addActionListener(self) self.defectRButton = JRadioButton("Defect", actionCommand="defect") self.defectRButton.addActionListener(self) annoPanel.add(self.wtRButton) annoPanel.add(self.defectRButton) self.aButtonGroup = ButtonGroup() self.aButtonGroup.add(self.wtRButton) self.aButtonGroup.add(self.defectRButton) self.Panel.add(annoPanel) self.ProgBar = JProgressBar() self.ProgBar.setStringPainted(True) self.ProgBar.setValue(0) self.Panel.add(self.ProgBar) self.pathLabel = JLabel("-- No main directory chosen --") self.pathLabel.setHorizontalAlignment( SwingConstants.CENTER ) self.Panel.add(self.pathLabel) WindowManager.addWindow(self) self.show()
def add_UI_entry(self,key, dico=dict()): UI_key_dict = dict() UI_key_dict['JP'] = JPanel() UI_key_dict['JP'].setLayout(BoxLayout(UI_key_dict['JP'], BoxLayout.X_AXIS)) UI_key_dict['JRB'] = JRadioButton() self.select_key_rb_group.add(UI_key_dict['JRB']) self.hash4keys[UI_key_dict['JRB']] = key UI_key_dict['JB'] = JButton(key, actionPerformed=self.set_key) UI_key_dict['JB'].setPreferredSize(Dimension(100,25)) UI_key_dict['JPP'] = JPanel() UI_key_dict['JP'].add(UI_key_dict['JRB']) UI_key_dict['JP'].add(UI_key_dict['JB']) UI_key_dict['JP'].add(Box.createRigidArea(Dimension(15, 0))) UI_key_dict['JP'].add(UI_key_dict['JPP']) UI_key_dict['JPP'].setLayout(BoxLayout(UI_key_dict['JPP'], BoxLayout.Y_AXIS)) self.panelEntries.add(UI_key_dict['JP']) for param in self.param_list: if param not in dico.keys(): continue if param == 'DEFAULT': UI_key_dict[param] = {'JP':JPanel(), 'JRB': JRadioButton('is Default')} UI_key_dict[param]['JP'].setLayout(BoxLayout( UI_key_dict[param]['JP'], BoxLayout.X_AXIS)) UI_key_dict[param]['JP'].add(UI_key_dict[param]['JRB']) UI_key_dict[param]['JP'].add(Box.createHorizontalGlue()) self.select_default_rb_group.add(UI_key_dict[param]['JRB']) UI_key_dict['JPP'].add(UI_key_dict[param]['JP']) UI_key_dict[param]['JRB'].setSelected(dico[param]) self.hash4keys[UI_key_dict[param]['JRB']] = key continue UI_key_dict[param] = { 'JP':JPanel(), 'JL': JLabel(param+": "), 'JB': JButton(dico[param]) } self.hash4keys[UI_key_dict[param]['JB']] = key UI_key_dict[param]['JL'].setPreferredSize(Dimension(100,25)) UI_key_dict[param]['JB'].actionPerformed = self.actions_list[param] UI_key_dict[param]['JP'].setLayout(BoxLayout(UI_key_dict[param]['JP'], BoxLayout.X_AXIS)) UI_key_dict[param]['JP'].add(UI_key_dict[param]['JL']) UI_key_dict[param]['JP'].add(UI_key_dict[param]['JB']) UI_key_dict[param]['JP'].add(Box.createHorizontalGlue()) UI_key_dict['JPP'].add(UI_key_dict[param]['JP']) UI_key_dict['JPP'].add(Box.createRigidArea(Dimension(0, 20))) self.config_item_dict[key]=UI_key_dict self.pack() pass
def display(self, values): button_group = ButtonGroup() for operator in self._OPERATORS: button = JRadioButton(operator) button.setSelected(operator == values['tags_operator']) button.addItemListener(self) button_group.add(button) self._buttons.append(button) self.add(button)
def display(self, values): self.add(JLabel('<html><b>Capturing:</b></html')) button_group = ButtonGroup() for option in self._OPTIONS: button = JRadioButton(option) button.setSelected(option == values['capturing']) button.addItemListener(self) button_group.add(button) self._buttons.append(button) self.add(button)
def __init__( self, outer ) : InternalFrame.__init__( self, 'RadioButtons', outer, size = ( 400, 85 ), location = Point( 5, 225 ) ) self.add( JLabel( 'Timeout (minutes):' ) ) buttons = {} self.bg = ButtonGroup() for name in '0,15,30,60,Other'.split( ',' ) : button = JRadioButton( name, itemStateChanged = self.stateChange ) self.bg.add( button ) self.add( button ) buttons[ name ] = button self.r00 = buttons[ '0' ] self.r15 = buttons[ '15' ] self.r30 = buttons[ '30' ] self.r60 = buttons[ '60' ] self.rot = buttons[ 'Other' ] self.text = self.add( JTextField( '', 3, actionPerformed = outer.update ) ) self.message = self.add( JLabel() ) self.setting = 0 # see stateChange() and setValue() self.setVisible( 1 )
def getUiComponent(self): ui_panel = JPanel() ui_panel.setLayout(BoxLayout(ui_panel, BoxLayout.PAGE_AXIS)) ui_host_line = JPanel() ui_host_line.setLayout(BoxLayout(ui_host_line, BoxLayout.LINE_AXIS)) ui_host_line.setAlignmentX(JPanel.LEFT_ALIGNMENT) ui_host_line.add(JLabel("ElasticSearch Host: ")) self.ui_es_host = JTextField(40) self.ui_es_host.setMaximumSize(self.ui_es_host.getPreferredSize()) self.ui_es_host.setText(self.es_host) ui_host_line.add(self.ui_es_host) ui_panel.add(ui_host_line) ui_index_line = JPanel() ui_index_line.setLayout(BoxLayout(ui_index_line, BoxLayout.LINE_AXIS)) ui_index_line.setAlignmentX(JPanel.LEFT_ALIGNMENT) ui_index_line.add(JLabel("ElasticSearch Index: ")) self.ui_es_index = JTextField(40) self.ui_es_index.setText(self.es_index) self.ui_es_index.setMaximumSize(self.ui_es_index.getPreferredSize()) ui_index_line.add(self.ui_es_index) ui_panel.add(ui_index_line) ui_whitelist_line = JPanel() ui_whitelist_line.setLayout( BoxLayout(ui_whitelist_line, BoxLayout.LINE_AXIS)) ui_whitelist_line.setAlignmentX(JPanel.LEFT_ALIGNMENT) ui_whitelist_line.add(JLabel("Host whitelist: ")) self.ui_whitelist = JTextField(40) self.ui_whitelist.setText(self.whitelist) self.ui_whitelist.setMaximumSize(self.ui_whitelist.getPreferredSize()) ui_whitelist_line.add(self.ui_whitelist) ui_panel.add(ui_whitelist_line) ui_tools_panel = JPanel() ui_tools_panel.setLayout( BoxLayout(ui_tools_panel, BoxLayout.LINE_AXIS)) ui_tools_panel.setAlignmentX(JPanel.LEFT_ALIGNMENT) self.ui_tool_suite = JCheckBox( "Suite", self.tools & ECallbacks.TOOL_SUITE != 0) ui_tools_panel.add(self.ui_tool_suite) ui_tools_panel.add(Box.createRigidArea(Dimension(10, 0))) self.ui_tool_target = JCheckBox( "Target", self.tools & ECallbacks.TOOL_TARGET != 0) ui_tools_panel.add(self.ui_tool_target) ui_tools_panel.add(Box.createRigidArea(Dimension(10, 0))) self.ui_tool_proxy = JCheckBox( "Proxy", self.tools & ECallbacks.TOOL_PROXY != 0) ui_tools_panel.add(self.ui_tool_proxy) ui_tools_panel.add(Box.createRigidArea(Dimension(10, 0))) self.ui_tool_spider = JCheckBox( "Spider", self.tools & ECallbacks.TOOL_SPIDER != 0) ui_tools_panel.add(self.ui_tool_spider) ui_tools_panel.add(Box.createRigidArea(Dimension(10, 0))) self.ui_tool_scanner = JCheckBox( "Scanner", self.tools & ECallbacks.TOOL_SCANNER != 0) ui_tools_panel.add(self.ui_tool_scanner) ui_tools_panel.add(Box.createRigidArea(Dimension(10, 0))) self.ui_tool_intruder = JCheckBox( "Intruder", self.tools & ECallbacks.TOOL_INTRUDER != 0) ui_tools_panel.add(self.ui_tool_intruder) ui_tools_panel.add(Box.createRigidArea(Dimension(10, 0))) self.ui_tool_repeater = JCheckBox( "Repeater", self.tools & ECallbacks.TOOL_REPEATER != 0) ui_tools_panel.add(self.ui_tool_repeater) ui_tools_panel.add(Box.createRigidArea(Dimension(10, 0))) self.ui_tool_sequencer = JCheckBox( "Sequencer", self.tools & ECallbacks.TOOL_SEQUENCER != 0) ui_tools_panel.add(self.ui_tool_sequencer) ui_tools_panel.add(Box.createRigidArea(Dimension(10, 0))) self.ui_tool_extender = JCheckBox( "Extender", self.tools & ECallbacks.TOOL_EXTENDER != 0) ui_tools_panel.add(self.ui_tool_extender) ui_panel.add(ui_tools_panel) ui_panel.add(Box.createRigidArea(Dimension(0, 10))) ui_log_line = JPanel() ui_log_line.setLayout(BoxLayout(ui_log_line, BoxLayout.LINE_AXIS)) ui_log_line.setAlignmentX(JPanel.LEFT_ALIGNMENT) ui_debug = JRadioButton("DEBUG", self.log_level == 'DEBUG') ui_log_line.add(ui_debug) ui_log_line.add(Box.createRigidArea(Dimension(10, 0))) ui_info = JRadioButton("INFO", self.log_level == 'INFO') ui_log_line.add(ui_info) ui_log_line.add(Box.createRigidArea(Dimension(10, 0))) ui_warning = JRadioButton("WARNING", self.log_level == 'WARNING') ui_log_line.add(ui_warning) ui_log_line.add(Box.createRigidArea(Dimension(10, 0))) ui_error = JRadioButton("ERROR", self.log_level == 'ERROR') ui_log_line.add(ui_error) ui_log_line.add(Box.createRigidArea(Dimension(10, 0))) ui_critical = JRadioButton( "CRITICAL", self.log_level == 'CRITICAL') ui_log_line.add(ui_critical) ui_log_line.add(Box.createRigidArea(Dimension(10, 0))) ui_panel.add(ui_log_line) ui_panel.add(Box.createRigidArea(Dimension(0, 10))) self.ui_log_level = ButtonGroup() self.ui_log_level.add(ui_debug) self.ui_log_level.add(ui_info) self.ui_log_level.add(ui_warning) self.ui_log_level.add(ui_error) self.ui_log_level.add(ui_critical) ui_buttons_line = JPanel() ui_buttons_line.setLayout( BoxLayout(ui_buttons_line, BoxLayout.LINE_AXIS)) ui_buttons_line.setAlignmentX(JPanel.LEFT_ALIGNMENT) ui_buttons_line.add( JButton("Save config", actionPerformed=self.save_config)) ui_panel.add(ui_buttons_line) return ui_panel
class BurpExtender(IBurpExtender, IContextMenuFactory): # Implement IBurpExtender def registerExtenderCallbacks(self, callbacks): self.printHeader() # Set extension name callbacks.setExtensionName("Directory Listing Parser for Burp Suite") # Callbacks object self._callbacks = callbacks # Helpers object self._helpers = callbacks.getHelpers() # Register a factory for custom context menu items callbacks.registerContextMenuFactory(self) return # Create a menu item if the appropriate section of the UI is selected def createMenuItems(self, invocation): menu = [] # Which part of the interface the user selects ctx = invocation.getInvocationContext() # Message Viewer Req/Res, Site Map Table, and Proxy History will show menu item if selected by the user if ctx == 2 or ctx == 3 or ctx == 4 or ctx == 5 or ctx == 6: menu.append(JMenuItem("Import Directory Listing", None, actionPerformed=lambda x, inv=invocation: self.openGUI(inv))) return menu if menu else None # Create and place GUI components on JFrame def openGUI(self, invocation): try: # Get values from request or response the extension is invoked from and prepopulate GUI values invMessage = invocation.getSelectedMessages() message = invMessage[0] originalHttpService = message.getHttpService() self.originalMsgProtocol = originalHttpService.getProtocol() self.originalMsgHost = originalHttpService.getHost() self.originalMsgPort = originalHttpService.getPort() except: self.originalMsgProtocol = '' self.originalMsgHost = '' self.originalMsgPort = '' try: self.cookies = self._callbacks.getCookieJarContents() self.cookie = '' except: pass self.SSL = 'http://' self.listType = '' self.parsedList = [] # Set up main window (JFrame) self.window = JFrame("Directory Listing Parser for Burp Suite", preferredSize=(600, 475), windowClosing=self.closeUI) self.window.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE) emptyBorder = BorderFactory.createEmptyBorder(10, 10, 10, 10) self.window.contentPane.setBorder(emptyBorder) self.window.contentPane.layout = BorderLayout() # Main window title placed at the top of the main window with an invisible bottom border titlePanel = JPanel() titleBorder = BorderFactory.createEmptyBorder(0, 0, 10, 0) title = JLabel("Directory Listing Parser for Burp Suite", JLabel.CENTER) title.setBorder(titleBorder) title.setFont(Font("Default", Font.PLAIN, 18)) titlePanel.add(title) self.window.contentPane.add("North", titlePanel) # Left panel for user input, consisting of hostname, directory prefix, ssl, port, type of listing, and file self.leftPanel = JPanel() self.leftPanel.layout = GridLayout(14, 1, 3, 3) hostnameLabel = JLabel("Hostname:") if self.originalMsgHost: self.hostnameTextField = JTextField(self.originalMsgHost.rstrip()) else: self.hostnameTextField = JTextField('Hostname') dirPrefixLabel = JLabel("Full Directory Prefix (Windows):") self.dirPrefixField = JTextField('C:\\var\www\\') sslLabel = JLabel("SSL:") self.radioBtnSslEnabled = JRadioButton('Enabled (https)', actionPerformed=self.radioSsl) self.radioBtnSslDisabled = JRadioButton('Disabled (http)', actionPerformed=self.radioSsl) sslButtonGroup = ButtonGroup() sslButtonGroup.add(self.radioBtnSslEnabled) sslButtonGroup.add(self.radioBtnSslDisabled) if self.originalMsgProtocol == "https": self.radioBtnSslEnabled.setSelected(True) else: self.radioBtnSslDisabled.setSelected(True) portLabel = JLabel("Port:") if self.originalMsgPort: self.portTextField = JTextField(str(self.originalMsgPort).rstrip()) else: self.portTextField = JTextField('80') osLabel = JLabel("Type of File Listing:") self.types = ('Windows \'dir /s\'', 'Linux \'ls -lR\'', 'Linux \'ls -R\'') self.comboListingType = JComboBox(self.types) uploadLabel = JLabel("Directory Listing File:") self.uploadTextField = JTextField('') uploadButton = JButton('Choose File', actionPerformed=self.chooseFile) self.leftPanel.add(hostnameLabel) self.leftPanel.add(self.hostnameTextField) self.leftPanel.add(dirPrefixLabel) self.leftPanel.add(self.dirPrefixField) self.leftPanel.add(sslLabel) self.leftPanel.add(self.radioBtnSslEnabled) self.leftPanel.add(self.radioBtnSslDisabled) self.leftPanel.add(portLabel) self.leftPanel.add(self.portTextField) self.leftPanel.add(osLabel) self.leftPanel.add(self.comboListingType) self.leftPanel.add(uploadLabel) self.leftPanel.add(self.uploadTextField) self.leftPanel.add(uploadButton) # Right panel consisting of a text area for the URL list self.UrlPanelLabel = JLabel("URL List:") self.textArea = JTextArea() self.textArea.setEditable(True) self.textArea.setFont(Font("Default", Font.PLAIN, 14)) if self.cookies: self.textArea.append('Cookies Found:\n') for cookie in self.cookies: if cookie.getDomain() in self.originalMsgHost: self.cookie += cookie.getName() + '=' + cookie.getValue() + '; ' self.textArea.append(cookie.getName() + '=' + cookie.getValue() + '\n') scrollArea = JScrollPane(self.textArea) scrollArea.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS) scrollArea.setPreferredSize(Dimension(400, 200)) self.rightPanel = JPanel() self.rightPanel.setLayout(BorderLayout(3, 3)) self.rightPanel.add(self.UrlPanelLabel, BorderLayout.NORTH) self.rightPanel.add(scrollArea, BorderLayout.CENTER) # Panel for the generate URL list and import URL list buttons generatePanel = JPanel() generatePanel.layout = BorderLayout(3, 3) generateButton = JButton('Generate URL List', actionPerformed=self.generateUrlList) importButton = JButton('Import URL List to Burp Site Map', actionPerformed=self.confirmImport) generatePanel.add("North", generateButton) generatePanel.add("South", importButton) self.rightPanel.add("South", generatePanel) # Add the two main panels to the left and right sides self.window.contentPane.add("East", self.rightPanel) self.window.contentPane.add("West", self.leftPanel) # Create a panel to be used for the file chooser window self.uploadPanel = JPanel() self.window.pack() self.window.show() # JFileChooser and showDialog for the user to specify their directory listing input file def chooseFile(self, event): chooseFile = JFileChooser() filter = FileNameExtensionFilter("c files", ["c"]) chooseFile.addChoosableFileFilter(filter) chooseFile.showDialog(self.uploadPanel, "Choose File") chosenFile = chooseFile.getSelectedFile() self.uploadTextField.text = str(chosenFile) # Set whether https is enabled. Default is disabled (http) def radioSsl(self, event): if self.radioBtnSslEnabled.isSelected(): self.SSL = 'https://' else: self.SSL = 'http://' # Create a parser object and pass the user's specified options. Retrieve the results and print them to a text area def generateUrlList(self, event): fileListingType = self.comboListingType.selectedIndex self.listType = self.types[fileListingType] urlsMade = 0 if os.path.isfile(self.uploadTextField.text): parser = ListingParser() parser.parse(self.hostnameTextField.getText(), self.dirPrefixField.getText().rstrip(), self.SSL, self.portTextField.getText(), self.listType, self.uploadTextField.getText()) self.parsedList = parser.returnList() self.textArea.setText('') for item in self.parsedList: self.textArea.append(item + '\n') urlsMade = str(len(self.parsedList)) if self.parsedList and urlsMade: self.textArea.append('\n' + 'Total Directories Found: ' + str(parser.directoryCount)) self.textArea.append('\n' + 'Total URLs Created: ' + urlsMade) else: self.textArea.append('Error occurred during parsing.\n') self.textArea.append('Please make sure the directory listing is a valid format and all input is correct.\n') self.textArea.append('E-mail [email protected] with errors or for further help.') else: JOptionPane.showMessageDialog(None, 'ERROR: File is not valid file or not found!') def closeUI(self, event): self.window.setVisible(False) self.window.dispose() # This is initiated by the user selecting the 'import to burp' button. Checks each generated URL for a valid response and adds it to the site map def importList(self): if self.parsedList: urlsAdded = 0 # Loop through each URL and check the response. If the response code is less than 404, add to site map for item in self.parsedList: # Pass exception if urlopen returns an http error if the URL is not reachable try: code = urlopen(item).code if code < 404: javaURL = URL(item) newRequest = self._helpers.buildHttpRequest(javaURL) stringNewRequest = self._helpers.bytesToString(newRequest).rstrip() if self.cookie: stringNewRequest += '\nCookie: ' + self.cookie.rstrip('; ') + '\r\n\r\n' requestResponse = self._callbacks.makeHttpRequest(self._helpers.buildHttpService(str(javaURL.getHost()), int(javaURL.getPort()), javaURL.getProtocol() == "https"), stringNewRequest) else: requestResponse = self._callbacks.makeHttpRequest(self._helpers.buildHttpService(str(javaURL.getHost()), int(javaURL.getPort()), javaURL.getProtocol() == "https"), newRequest) self._callbacks.addToSiteMap(requestResponse) urlsAdded += 1 except Exception, e: print e pass JOptionPane.showMessageDialog(None, str(urlsAdded) + " URL(s) added to Burp site map.") else:
def loginPage(): global heading global rbAdmin global rbTeacher global rbStudent global frame global tfLoginId global tfPassword frame = JFrame("Login Form ") frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) frame.setSize(500, 500) frame.setLocation(200, 200) frame.setLayout(None) frame.setVisible(True) panel = JPanel() panel.setSize(500, 500) panel.setLocation(0, 0) panel.setLayout(None) panel.setBackground(Color.BLUE) heading = JLabel("Admin Login") heading.setBounds(200, 50, 150, 30) rbAdmin = JRadioButton("Admin", actionPerformed=clickRadio) rbTeacher = JRadioButton("Teacher", actionPerformed=clickRadio) rbStudent = JRadioButton("Student", actionPerformed=clickRadio) rbAdmin.setBounds(100, 150, 100, 20) rbTeacher.setBounds(200, 150, 100, 20) rbStudent.setBounds(300, 150, 100, 20) btnGroup = ButtonGroup() btnGroup.add(rbAdmin) btnGroup.add(rbTeacher) btnGroup.add(rbStudent) lbLoginId = JLabel("LoginId") lbPassword = JLabel("Password") lbLoginId.setBounds(100, 230, 150, 30) lbPassword.setBounds(100, 300, 150, 30) tfLoginId = JTextField() tfPassword = JTextField() tfLoginId.setBounds(250, 230, 150, 30) tfPassword.setBounds(250, 300, 150, 30) btnLogin = JButton("Login", actionPerformed=clickLogin) btnLogin.setBounds(350, 350, 100, 30) btnReg = JButton("New Institute Registration", actionPerformed=clickReg) btnReg.setBounds(350, 400, 100, 30) panel.add(heading) panel.add(rbAdmin) panel.add(rbTeacher) panel.add(rbStudent) panel.add(lbLoginId) panel.add(lbPassword) panel.add(tfLoginId) panel.add(tfPassword) panel.add(btnLogin) panel.add(btnReg) panel.setVisible(True) frame.add(panel)
class MenueFrame(JFrame, ActionListener, WindowFocusListener): # should extend JFrame def __init__(self): self.mainDir = "" self.setTitle("Dots Quality Check") self.setSize(250, 300) self.setLocation(20,120) self.addWindowFocusListener(self) self.Panel = JPanel(GridLayout(0,1)) self.add(self.Panel) self.openNextButton = JButton("Open Next Random", actionPerformed=self.openRandom) self.Panel.add(self.openNextButton) self.saveButton = JButton("Save", actionPerformed=self.save, enabled=False) self.Panel.add(self.saveButton) self.cropButton = JButton("Crop values from here", actionPerformed=self.cropVals) self.Panel.add(self.cropButton) self.DiscardButton = JButton("Discard cell", actionPerformed=self.discardCell) self.Panel.add(self.DiscardButton) self.quitButton = JButton("Quit script",actionPerformed=self.quit) self.Panel.add(self.quitButton) annoPanel = JPanel() #add gridlayout self.wtRButton = JRadioButton("wt", actionCommand="wt") self.wtRButton.addActionListener(self) self.defectRButton = JRadioButton("Defect", actionCommand="defect") self.defectRButton.addActionListener(self) annoPanel.add(self.wtRButton) annoPanel.add(self.defectRButton) self.aButtonGroup = ButtonGroup() self.aButtonGroup.add(self.wtRButton) self.aButtonGroup.add(self.defectRButton) self.Panel.add(annoPanel) self.ProgBar = JProgressBar() self.ProgBar.setStringPainted(True) self.ProgBar.setValue(0) self.Panel.add(self.ProgBar) self.pathLabel = JLabel("-- No main directory chosen --") self.pathLabel.setHorizontalAlignment( SwingConstants.CENTER ) self.Panel.add(self.pathLabel) WindowManager.addWindow(self) self.show() # - - - - B U T T O N M E T H O D S - - - - # - - - - - - - - - - - - - - - - - - - - - - - def openRandom(self, event): # when click here: get random cell and meas.measure(csv, tif, savePath) if self.mainDir == "": self.mainDir = DirectoryChooser("Random QC - Please choose main directory containing ctrl and test folders").getDirectory() self.pathLabel.setText("MainDir: " + os.path.basename(os.path.split(self.mainDir)[0])) try: # should be complete disposal! self.cT.closeWindows() finally: inFiles = glob.glob(os.path.join(self.mainDir, "*", G_OPENSUBDIR, "val_*.csv")) # glob.glob returns list of paths uncheckedCells = [cell(csvPath) for csvPath in inFiles if cell(csvPath).processed == False] if len(uncheckedCells) > 0: self.cell = random.choice(uncheckedCells) #update progressbar self.ProgBar.setMaximum(len(inFiles)-1) self.ProgBar.setValue(len(inFiles)-len(uncheckedCells)) # open imp and resultstable self.cT = correctionTable(self.cell, self) #self, openPath_csv, mF self.RBActionListener.setCell(self.cell) # delete previous Radiobutton annotation self.wtRButton.setSelected(False) self.defectRButton.setSelected(True) else: print "All cells measured!" def save(self, event): savepath = self.cell.getQcCsvPath() anaphase = self.cell.getAnOn() timeInterval = self.cT.getImp().getCalibration().frameInterval annotation = self.getAnnotation() position = str(self.cell.position) cellIndex = str(self.cell.cellNo) if not os.path.exists(os.path.split(savepath)[0]): # check if save folder present. os.makedirs(os.path.split(savepath)[0]) # create save folder, if not present f = open(savepath, "w") # Position Cell Phenotype Frame Time AnOn Distance ch0x ch0y ch0z ch0vol ch1x ch1y ch1z ch1vol f.write("Position,Cell,Phenotype,Frame,Time,Anaphase,Distance,ch0x,ch0y,ch0z,ch0vol,ch1x,ch1y,ch1z,ch1vol\n") for i in range(self.cT.getLineCount()): frame, distance, a = self.cT.getLine(i).split("\t") corrFrame = str(int(frame)-int(anaphase)) time = "%.f" % (round(timeInterval) * int(corrFrame)) if distance == "NA": ch0x, ch0y, ch0z, ch0vol, ch1x, ch1y, ch1z, ch1vol = ("NA," * 7 + "NA\n").split(",") else: ch0x, ch0y, ch0z, ch0vol, ch1x, ch1y, ch1z, ch1vol = self.cT.getXYZtable()[i] f.write(position+","+cellIndex+","+annotation+","+corrFrame+","+time+","+anaphase+","+distance+","+ch0x+","+ch0y+","+ch0z+","+ch0vol+","+ch1x+","+ch1y+","+ch1z+","+ch1vol) f.close() print "Successfully saved!" def cropVals(self, event): #"this function deletes all values with frame > current cursor" for line in range(self.cT.getSelectionEnd(), self.cT.getLineCount(), 1): frame, distance, AOCol = self.cT.getLine(line).split("\t") self.cT.setLine(line, frame + "\tNA" + "\t" + AOCol) def discardCell(self, event): if not os.path.exists(os.path.split(self.cell.getQcCsvPath() )[0]): # check if save folder present. os.makedirs(os.path.split(self.cell.getQcCsvPath() )[0]) # create save folder, if not present. f = open(self.cell.getQcCsvPath() ,"w") # Write dummy header. Position Cell Phenotype Frame Time AnOn Distance ch0x ch0y ch0z ch0vol ch1x ch1y ch1z ch1vol f.write("Position,Cell,Phenotype,Frame,Time,AnOn,Distance,ch0x,ch0y,ch0z,ch0vol,ch1x,ch1y,ch1z,ch1vol\n") f.close() print "Discarded cell - saved dummy" def quit(self, event): try: self.cT.closeWindows() finally: WindowManager.removeWindow(self) self.dispose() # Methods implementing ActionListener interfaces: def actionPerformed(self, e): # this function is called when RadioButtons are changed self.cell.annotate( e.getSource().getActionCommand() ) self.setSaveActive() def windowGainedFocus(self, e): pass def windowLostFocus(self, e): pass # - - - - - - - - - - - - - # - get and set methods - - # - - - - - - - - - - - - - def getAnnotation(self): return self.aButtonGroup.getSelection().getActionCommand() def getMainDir(self): return self.mainDir def setSaveActive(self): if (self.cell.getAnnotation() != None and self.cell.getAnOn() != None): self.saveButton.setEnabled(True) self.show() def setSaveInactive(self): self.saveButton.setEnabled(False) self.show() def setMainDir(self, path): self.mainDir = path self.pathLabel.setText("MainDir: " + os.path.basename(os.path.split(self.mainDir)[0]))
def gui(self): file_field = JTextField(self.dsm2file,15) load_btn = JButton('Load input ') chan_box = JComboBox() chan_box.setEditable(1) do_btn = JButton('Plot channel') choices = [JRadioButton('XSection'), JRadioButton('Area'), JRadioButton('Width'), JRadioButton('Perimeter'), JRadioButton('Rh'), JRadioButton('Xc'), JRadioButton('Zc')] #bg = ButtonGroup() #for choice in choices: bg.add(choice) class load_listener(ActionListener): def __init__(self,file_field,load_btn, chan_box,do_btn, choices): self.file_field = file_field self.load_btn = load_btn self.chan_box = chan_box self.do_btn = do_btn self.do_btn.setEnabled(0) self.load_btn.addActionListener(self) self.do_btn.addActionListener(self) self.choices=choices def actionPerformed(self,evt): if evt.getSource() == self.load_btn : self.ig = IrregGeom(self.file_field.getText()) import javax.swing md = javax.swing.DefaultComboBoxModel(self.ig.getChanList()) self.chan_box.setModel(md) self.do_btn.setEnabled(1) elif evt.getSource() == self.do_btn : if self.ig: for choice in self.choices: if choice.isSelected(): self.ig.plot(self.chan_box.getSelectedItem(),choice.getText()) ll = load_listener(file_field, load_btn, chan_box, do_btn,choices) p1 = JPanel() p1.setLayout(BorderLayout()) p1.add(file_field,BorderLayout.CENTER) p1.add(load_btn,BorderLayout.EAST) p2 = JPanel() p2.setLayout(BorderLayout()) p2.add(chan_box,BorderLayout.CENTER) p2.add(do_btn,BorderLayout.EAST) p3 = JPanel() p3.setLayout(GridLayout(1,2)) p3.add(choices[0]); p3.add(choices[1]) p4 = JPanel() p4.setLayout(GridLayout(1,2)) p4.add(choices[2]); p4.add(choices[3]) p5 = JPanel() p5.setLayout(GridLayout(1,2)) p5.add(choices[4]); p5.add(choices[5]) p6 = JPanel() p6.setLayout(GridLayout(1,2)) p6.add(choices[6]) # mp = JPanel() mp.setLayout(GridLayout(6,1)) mp.add(p1) mp.add(p2) mp.add(p3) mp.add(p4) mp.add(p5) mp.add(p6) return mp
def addRB(self, pane, bg, text): bg.add(pane.add(JRadioButton(text, itemStateChanged=self.toggle)))
def drawUI(self): # 最外层:垂直盒子,内放一个水平盒子+一个胶水 out_vBox_main = Box.createVerticalBox() # 次外层:水平盒子,使用说明 usage = u''' JC-AntiToken(简单防重放绕过) 适用场景:防重放的方式为,提前向一个页面发送请求取得token,替换到下一个页面中。 适用说明: 1. 请求头中Headers和Data的值必须是JSON字符串,如:{"var":"value"} 2. 左边tokenRegex的格式为: a. .*开头,.*结尾,用()括住要取出的token b. 如:.*,"token":"(.*?)".* 3. 右边tokenRegex的格式为: a. 需要三个(),第二个()括住要替换的token b. 如:(.*,"token":")(.*?)(".*) 详见:https://github.com/chroblert/JC-AntiToken ''' hBox_usage = Box.createHorizontalBox() jpanel_test = JPanel() jTextarea_usage = JTextArea() jTextarea_usage.setText(usage) jTextarea_usage.setRows(13) jTextarea_usage.setEditable(False) # jpanel_test.add(jTextarea_usage) hBox_usage.add(JScrollPane(jTextarea_usage)) # 次外层:水平盒子,内放两个垂直盒子 hBox_main = Box.createHorizontalBox() # 左垂直盒子 vBox_left = Box.createVerticalBox() # 右垂直盒子 vBox_right = Box.createVerticalBox() # 左垂直盒子内部:发送请求包拿token # URL标签 jlabel_url = JLabel(" URL: ") self.jtext_url = JTextField(generWidth) self.jtext_url.setMaximumSize(self.jtext_url.getPreferredSize()) hbox_url = Box.createHorizontalBox() hbox_url.add(jlabel_url) hbox_url.add(self.jtext_url) hglue_url = Box.createHorizontalGlue() hbox_url.add(hglue_url) # 请求方法标签 jlabel_reqMeth = JLabel("ReqMeth: ") self.jcombobox_reqMeth = JComboBox() self.jcombobox_reqMeth.addItem("GET") self.jcombobox_reqMeth.addItem("POST") hbox_reqMeth = Box.createHorizontalBox() hbox_reqMeth.add(jlabel_reqMeth) hbox_reqMeth.add(self.jcombobox_reqMeth) self.jcombobox_reqMeth.setMaximumSize( self.jcombobox_reqMeth.getPreferredSize()) hglue_reqMeth = Box.createHorizontalGlue() hbox_reqMeth.add(hglue_reqMeth) # ContentType标签 jlabel_contentType = JLabel("ConType: ") self.jcombobox_contentType = JComboBox() self.jcombobox_contentType.addItem("application/json") self.jcombobox_contentType.addItem("application/x-www-form-urlencoded") hbox_contentType = Box.createHorizontalBox() hbox_contentType.add(jlabel_contentType) hbox_contentType.add(self.jcombobox_contentType) self.jcombobox_contentType.setMaximumSize( self.jcombobox_contentType.getPreferredSize()) hglue_contentType = Box.createHorizontalGlue() hbox_contentType.add(hglue_contentType) # Charset标签 jlabel_charset = JLabel("CharSet: ") self.jcombobox_charset = JComboBox() self.jcombobox_charset.addItem("UTF-8") self.jcombobox_charset.addItem("GBK") hbox_charset = Box.createHorizontalBox() hbox_charset.add(jlabel_charset) hbox_charset.add(self.jcombobox_charset) self.jcombobox_charset.setMaximumSize( self.jcombobox_charset.getPreferredSize()) hglue_charset = Box.createHorizontalGlue() hbox_charset.add(hglue_charset) # 请求头标签 jlabel_headers = JLabel("Headers: ") self.jtext_headers = JTextField(generWidth) self.jtext_headers.setMaximumSize( self.jtext_headers.getPreferredSize()) hbox_headers = Box.createHorizontalBox() hbox_headers.add(jlabel_headers) hbox_headers.add(self.jtext_headers) hglue_headers = Box.createHorizontalGlue() hbox_headers.add(hglue_headers) # 请求参数标签 jlabel_data = JLabel(" Data: ") self.jtext_data = JTextField(generWidth) self.jtext_data.setPreferredSize(Dimension(20, 40)) self.jtext_data.setMaximumSize(self.jtext_data.getPreferredSize()) hbox_data = Box.createHorizontalBox() hbox_data.add(jlabel_data) hbox_data.add(self.jtext_data) hglue_data = Box.createHorizontalGlue() hbox_data.add(hglue_data) # token标志位置标签 hbox_radiobtn = Box.createHorizontalBox() jlabel_tokenPosition = JLabel("Token Position: ") self.radioBtn01 = JRadioButton("Header") self.radioBtn02 = JRadioButton("Body") btnGroup = ButtonGroup() btnGroup.add(self.radioBtn01) btnGroup.add(self.radioBtn02) self.radioBtn01.setSelected(True) hbox_radiobtn.add(jlabel_tokenPosition) hbox_radiobtn.add(self.radioBtn01) hbox_radiobtn.add(self.radioBtn02) # token正则表达式标签 hbox_token = Box.createHorizontalBox() hbox_token_header = Box.createHorizontalBox() hbox_token_body = Box.createHorizontalBox() # token正则表达式标签:header中 jlabel_tokenName = JLabel("tokenName: ") self.jtext_tokenName = JTextField(tokenWidth) self.jtext_tokenName.setMaximumSize( self.jtext_tokenName.getPreferredSize()) hbox_token_header.add(jlabel_tokenName) hbox_token_header.add(self.jtext_tokenName) hglue_token_header = Box.createHorizontalGlue() hbox_token_header.add(hglue_token_header) # token正则表达式标签:body中 jlabel_tokenRegex = JLabel("tokenRegex: ") self.jtext_tokenRegex = JTextField(tokenWidth) self.jtext_tokenRegex.setMaximumSize( self.jtext_tokenRegex.getPreferredSize()) hbox_token_body.add(jlabel_tokenRegex) hbox_token_body.add(self.jtext_tokenRegex) hglue_token_body = Box.createHorizontalGlue() hbox_token_body.add(hglue_token_body) # token正则表达式标签 hbox_token.add(hbox_token_header) hbox_token.add(hbox_token_body) # test测试按钮 hbox_test = Box.createHorizontalBox() jbtn_test = JButton("TEST", actionPerformed=self.btnTest) self.jlabel_test = JLabel("Result: ") hbox_test.add(jbtn_test) hbox_test.add(self.jlabel_test) # 水平胶水填充 hGlue_test = Box.createHorizontalGlue() hbox_test.add(hGlue_test) hbox_test.setBorder(BorderFactory.createLineBorder(Color.green, 2)) # 响应数据输出 hbox_resp = Box.createHorizontalBox() self.jtextarea_resp = JTextArea() jsp = JScrollPane(self.jtextarea_resp) hbox_resp.add(self.jtextarea_resp) # 左垂直盒子:添加各种水平盒子 vBox_left.add(hbox_url) vBox_left.add(hbox_reqMeth) vBox_left.add(hbox_contentType) vBox_left.add(hbox_charset) vBox_left.add(hbox_headers) vBox_left.add(hbox_data) vBox_left.add(hbox_radiobtn) vBox_left.add(hbox_token) vBox_left.add(hbox_test) vBox_left.add(hbox_resp) # 左垂直盒子:垂直胶水填充 vGlue_test = Box.createGlue() vBox_left.add(vGlue_test) # 右垂直盒子内部:指定token在请求包中的位置 # token标志位置单选按钮 hbox_radiobtn_r = Box.createHorizontalBox() jlabel_tokenPosition_r = JLabel("Token Position: ") self.radioBtn01_r = JRadioButton("Header") self.radioBtn02_r = JRadioButton("Body") btnGroup_r = ButtonGroup() btnGroup_r.add(self.radioBtn01_r) btnGroup_r.add(self.radioBtn02_r) self.radioBtn01_r.setSelected(True) hbox_radiobtn_r.add(jlabel_tokenPosition_r) hbox_radiobtn_r.add(self.radioBtn01_r) hbox_radiobtn_r.add(self.radioBtn02_r) # token正则表达式 hbox_token_r = Box.createHorizontalBox() hbox_token_header_r = Box.createHorizontalBox() hbox_token_body_r = Box.createHorizontalBox() # token正则表达式:在header中 jlabel_tokenName_r = JLabel("tokenName: ") self.jtext_tokenName_r = JTextField(tokenWidth) self.jtext_tokenName_r.setMaximumSize( self.jtext_tokenName_r.getPreferredSize()) hbox_token_header_r.add(jlabel_tokenName_r) hbox_token_header_r.add(self.jtext_tokenName_r) hglue_token_header_r = Box.createHorizontalGlue() hbox_token_header_r.add(hglue_token_header_r) # token正则表达式:在Body中 jlabel_tokenRegex_r = JLabel("tokenRegex: ") self.jtext_tokenRegex_r = JTextField(tokenWidth) self.jtext_tokenRegex_r.setMaximumSize( self.jtext_tokenRegex_r.getPreferredSize()) hbox_token_body_r.add(jlabel_tokenRegex_r) hbox_token_body_r.add(self.jtext_tokenRegex_r) hglue_token_body_r = Box.createHorizontalGlue() hbox_token_body_r.add(hglue_token_body_r) # token正则表达式 hbox_token_r.add(hbox_token_header_r) hbox_token_r.add(hbox_token_body_r) # 测试按钮 hbox_test_r = Box.createHorizontalBox() jbtn_test_r = JButton("SET", actionPerformed=self.btnTest_r) self.jlabel_test_r = JLabel("Result: ") hbox_test_r.add(jbtn_test_r) hbox_test_r.add(self.jlabel_test_r) # 水平胶水填充 hGlue02 = Box.createHorizontalGlue() hbox_test_r.add(hGlue02) hbox_test_r.setBorder(BorderFactory.createLineBorder(Color.green, 2)) # 右垂直盒子:添加各种水平盒子 vBox_right.add(hbox_radiobtn_r) vBox_right.add(hbox_token_r) vBox_right.add(hbox_test_r) vGlue = Box.createVerticalGlue() vBox_right.add(vGlue) vBox_left.setBorder(BorderFactory.createLineBorder(Color.black, 3)) vBox_right.setBorder(BorderFactory.createLineBorder(Color.black, 3)) # 次外层水平盒子:添加左右两个垂直盒子 hBox_main.add(vBox_left) hBox_main.add(vBox_right) # 最外层垂直盒子:添加次外层水平盒子,垂直胶水 out_vBox_main.add(hBox_usage) out_vBox_main.add(hBox_main) self.mainPanel = out_vBox_main self._callbacks.customizeUiComponent(self.mainPanel) self._callbacks.addSuiteTab(self)
def __init__(self): ''' Configuration Panel ''' # pconfig = JPanel(GridBagLayout()) # pconfig.setSize(Dimension(500,300)) self.setLayout(GridBagLayout()) # super(self,GridBagLayout()) self.setSize(Dimension(500,300)) ''' fila 1 ''' label = JLabel('Configuration panel') c1 = GridBagConstraints() c1.fill = GridBagConstraints.HORIZONTAL c1.weightx = 0.5 c1.gridwidth = 4 c1.gridx = 0 c1.gridy = 0 self.add(label, c1) ''' fila 2 ''' self.radioBtnOMC = JRadioButton('OpenModelica') c2 = GridBagConstraints() c2.fill = GridBagConstraints.HORIZONTAL c2.weightx = 0.5 c2.gridx = 0 c2.gridy = 1 self.add(self.radioBtnOMC, c2) self.radioBtnJM = JRadioButton('JModelica') c3 = GridBagConstraints() c3.fill = GridBagConstraints.HORIZONTAL c3.weightx = 0.5 c3.gridx = 1 c3.gridy = 1 self.add(self.radioBtnJM, c3) self.radioBtnDY = JRadioButton('Dymola') c4 = GridBagConstraints() c4.fill = GridBagConstraints.HORIZONTAL c4.weightx = 0.5 c4.gridx = 2 c4.gridy = 1 self.add(self.radioBtnDY, c4) rbBtnGroup = ButtonGroup() rbBtnGroup.add(self.radioBtnOMC) rbBtnGroup.add(self.radioBtnJM) rbBtnGroup.add(self.radioBtnDY) ''' fila 2 ''' label = JLabel('Start time') c = GridBagConstraints() c.fill = GridBagConstraints.HORIZONTAL c.weightx = 0.5 c.gridx = 0 c.gridy = 2 self.add(label, c) self.txtstart= JTextField('0') c = GridBagConstraints() c.fill = GridBagConstraints.HORIZONTAL c.weightx = 0.5 c.gridx = 1 c.gridy = 2 self.add(self.txtstart, c) label = JLabel('Stop time') c = GridBagConstraints() c.fill = GridBagConstraints.HORIZONTAL c.weightx = 0.5 c.gridx = 2 c.gridy = 2 self.add(label, c) self.txtstop= JTextField('0') c = GridBagConstraints() c.fill = GridBagConstraints.HORIZONTAL c.weightx = 0.5 c.gridx = 3 c.gridy = 2 self.add(self.txtstop, c) ''' fila 3 ''' label = JLabel('Solver') c = GridBagConstraints() c.fill = GridBagConstraints.HORIZONTAL c.weightx = 0.5 c.gridx = 0 c.gridy = 3 self.add(label, c) self.cbsolver= JComboBox(['dassl','rkfix2']) c = GridBagConstraints() c.fill = GridBagConstraints.HORIZONTAL c.weightx = 0.5 c.gridx = 1 c.gridy = 3 self.add(self.cbsolver, c) label = JLabel('Algorithm (JM)') c = GridBagConstraints() c.fill = GridBagConstraints.HORIZONTAL c.weightx = 0.5 c.gridx = 2 c.gridy = 3 self.add(label, c) self.cbalgorithm= JComboBox(['AssimuloAlg']) c = GridBagConstraints() c.fill = GridBagConstraints.HORIZONTAL c.weightx = 0.5 c.gridx = 3 c.gridy = 3 self.add(self.cbalgorithm, c) ''' fila 4 ''' label = JLabel('Interval') c = GridBagConstraints() c.fill = GridBagConstraints.HORIZONTAL c.weightx = 0.5 c.gridx = 0 c.gridy = 4 self.add(label, c) self.txtinterval= JTextField('0') c = GridBagConstraints() c.fill = GridBagConstraints.HORIZONTAL c.weightx = 0.5 c.gridx = 1 c.gridy = 4 self.add(self.txtinterval, c) ''' fila 5 ''' label = JLabel('Tolerance') c = GridBagConstraints() c.fill = GridBagConstraints.HORIZONTAL c.weightx = 0.5 c.gridx = 0 c.gridy = 5 self.add(label, c) self.txttolerance= JTextField('0') c = GridBagConstraints() c.fill = GridBagConstraints.HORIZONTAL c.weightx = 0.5 c.gridx = 1 c.gridy = 5 self.add(self.txttolerance, c) ''' fila 6 ''' label = JLabel('Output format') c = GridBagConstraints() c.fill = GridBagConstraints.HORIZONTAL c.weightx = 0.5 c.gridx = 0 c.gridy = 6 self.add(label, c) self.cboutformat= JComboBox(['.mat','.h5','.csv']) c = GridBagConstraints() c.fill = GridBagConstraints.HORIZONTAL c.weightx = 0.5 c.gridx = 1 c.gridy = 6 self.add(self.cboutformat, c) label = JLabel('Initialize (JM)') c = GridBagConstraints() c.fill = GridBagConstraints.HORIZONTAL c.weightx = 0.5 c.gridx = 2 c.gridy = 6 self.add(label, c) self.cbinitialize= JComboBox(['True','False']) c = GridBagConstraints() c.fill = GridBagConstraints.HORIZONTAL c.weightx = 0.5 c.gridx = 3 c.gridy = 6 self.add(self.cbinitialize, c) ''' fila 7 ''' bSaveCfg= JButton('Save Configuration', actionPerformed= self.saveConfiguration) c = GridBagConstraints() c.fill = GridBagConstraints.HORIZONTAL c.weightx = 0.5 c.gridwidth = 2 c.gridx = 0 c.gridy = 7 self.add(bSaveCfg, c) self.bSimulation= JButton('Load Configuration', actionPerformed= self.loadConfiguration) c = GridBagConstraints() c.fill = GridBagConstraints.HORIZONTAL c.weightx = 0.5 c.gridwidth = 2 c.gridx = 2 c.gridy = 7 self.add(self.bSimulation, c) ''' fila 8 ''' self.bSimulation= JButton('Simulate', actionPerformed= self.startSimlation) self.bSimulation.enabled= 0 c = GridBagConstraints() c.fill = GridBagConstraints.HORIZONTAL c.weightx = 1 c.gridwidth = 4 c.gridx = 0 c.gridy = 8 self.add(self.bSimulation, c) ''' file 9 ''' simProgress= JProgressBar(0, self.getWidth(), value=0, stringPainted=True) c = GridBagConstraints() c.fill = GridBagConstraints.HORIZONTAL c.weightx = 1 c.gridwidth = 4 c.gridx = 0 c.gridy = 9 self.add(simProgress, c) ''' fila 10 ''' self.lblResult= JLabel('Simulation information') c = GridBagConstraints() c.fill = GridBagConstraints.HORIZONTAL c.weightx = 1 c.gridwidth = 4 c.gridx = 0 c.gridy = 10 self.add(self.lblResult, c)
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("Burp Scope Monitor Experimental") self.GLOBAL_HANDLER_ANALYZED = False self.GLOBAL_HANDLER = False self.STATUS = False self.AUTOSAVE_REQUESTS = 10 self.AUTOSAVE_TIMEOUT = 600 # 10 minutes should be fine self.CONFIG_INSCOPE = True self.BAD_EXTENSIONS_DEFAULT = [ '.gif', '.png', '.js', '.woff', '.woff2', '.jpeg', '.jpg', '.css', '.ico', '.m3u8', '.ts', '.svg' ] self.BAD_MIMES_DEFAULT = [ 'gif', 'script', 'jpeg', 'jpg', 'png', 'video', 'mp2t' ] self.BAD_EXTENSIONS = self.BAD_EXTENSIONS_DEFAULT self.BAD_MIMES = self.BAD_MIMES_DEFAULT # create the log and a lock on which to synchronize when adding log entries self._currentlyDisplayedItem = None self.SELECTED_MODEL_ROW = 0 self.SELECTED_VIEW_ROW = 0 self._log = ArrayList() self._fullLog = ArrayList() self._lock = Lock() self._lockFile = Lock() # main split pane self._parentPane = JTabbedPane() self._splitpane = JSplitPane(JSplitPane.VERTICAL_SPLIT) ##### config pane self._config = JTabbedPane() config = JPanel() iexport = JPanel() #config.setLayout(BorderLayout()) config.setLayout(None) iexport.setLayout(None) # config radio button X_BASE = 40 Y_OFFSET = 5 Y_OPTION = 200 Y_OPTION_SPACING = 20 Y_CHECKMARK_SPACING = 20 self.showAllButton = JRadioButton(SHOW_ALL_BUTTON_LABEL, True) self.showNewButton = JRadioButton(SHOW_NEW_BUTTON_LABEL, False) self.showTestedButton = JRadioButton(SHOW_TEST_BUTTON_LABEL, False) self.showAllButton.setBounds(40, 60 + Y_OFFSET, 400, 30) self.showNewButton.setBounds(40, 80 + Y_OFFSET, 400, 30) self.showTestedButton.setBounds(40, 100 + Y_OFFSET, 400, 30) #self.showNewButton = JRadioButton(SHOW_NEW_BUTTON_LABEL, False) #self.showTestedButton = JRadioButton(SHOW_TEST_BUTTON_LABEL, False) self.showAllButton.addActionListener(self.handleRadioConfig) self.showNewButton.addActionListener(self.handleRadioConfig) self.showTestedButton.addActionListener(self.handleRadioConfig) self.clearButton = JButton("Clear") self.clearButton.addActionListener(self.handleClearButton) self.clearButton.setBounds(40, 20, 100, 30) self.startButton = JButton(MONITOR_ON_LABEL) self.startButton.addActionListener(self.handleStartButton) self.startButton.setBounds(150, 20, 200, 30) self.badExtensionsLabel = JLabel("Ignore extensions:") self.badExtensionsLabel.setBounds(X_BASE, 150, 200, 30) self.badExtensionsText = JTextArea("") self.loadBadExtensions() self.badExtensionsText.setBounds(X_BASE, 175, 310, 30) self.badExtensionsButton = JButton("Save") self.badExtensionsButton.addActionListener( self.handleBadExtensionsButton) self.badExtensionsButton.setBounds(355, 175, 70, 30) self.badExtensionsDefaultButton = JButton("Load Defaults") self.badExtensionsDefaultButton.addActionListener( self.handleBadExtensionsDefaultButton) self.badExtensionsDefaultButton.setBounds(430, 175, 120, 30) self.badMimesLabel = JLabel("Ignore mime types:") self.badMimesLabel.setBounds(X_BASE, 220, 200, 30) self.badMimesText = JTextArea("") self.loadBadMimes() self.badMimesText.setBounds(X_BASE, 245, 310, 30) self.badMimesButton = JButton("Save") self.badMimesButton.addActionListener(self.handleBadMimesButton) self.badMimesButton.setBounds(355, 245, 70, 30) self.badMimesDefaultButton = JButton("Load Defaults") self.badMimesDefaultButton.addActionListener( self.handleBadMimesDefaultButton) self.badMimesDefaultButton.setBounds(430, 245, 120, 30) self.otherLabel = JLabel("Other:") self.otherLabel.setBounds(40, 300, 120, 30) self.otherLabel2 = JLabel("Other:") self.otherLabel2.setBounds(X_BASE, Y_OPTION, 120, 30) self.autoSaveOption = JCheckBox("Auto save periodically") self.autoSaveOption.setSelected(True) self.autoSaveOption.addActionListener(self.handleAutoSaveOption) self.autoSaveOption.setBounds(X_BASE, Y_OPTION + Y_CHECKMARK_SPACING, 420, 30) self.repeaterOptionButton = JCheckBox( "Repeater request automatically marks as analyzed") self.repeaterOptionButton.setSelected(True) self.repeaterOptionButton.addActionListener( self.handleRepeaterOptionButton) self.repeaterOptionButton.setBounds(50, 330, 420, 30) self.scopeOptionButton = JCheckBox("Follow Burp Target In Scope rules") self.scopeOptionButton.setSelected(True) self.scopeOptionButton.addActionListener(self.handleScopeOptionButton) self.scopeOptionButton.setBounds(50, 350, 420, 30) self.startOptionButton = JCheckBox("Autostart Scope Monitor") self.startOptionButton.setSelected(True) self.startOptionButton.addActionListener(self.handleStartOption) self.startOptionButton.setBounds(50, 350 + Y_OPTION_SPACING, 420, 30) self.markTestedRequestsProxy = JCheckBox( "Color request in Proxy tab if analyzed") self.markTestedRequestsProxy.setSelected(True) self.markTestedRequestsProxy.addActionListener( self.handleTestedRequestsProxy) self.markTestedRequestsProxy.setBounds(50, 350 + Y_OPTION_SPACING * 2, 420, 30) self.markNotTestedRequestsProxy = JCheckBox( "Color request in Proxy tab if NOT analyzed") self.markNotTestedRequestsProxy.setSelected(True) self.markNotTestedRequestsProxy.addActionListener( self.handleNotTestedRequestsProxy) self.markNotTestedRequestsProxy.setBounds(50, 350 + Y_OPTION_SPACING * 3, 420, 30) self.saveButton = JButton("Save now") self.saveButton.addActionListener(self.handleSaveButton) self.saveButton.setBounds(X_BASE + 320, 95, 90, 30) self.loadButton = JButton("Load now") self.loadButton.addActionListener(self.handleLoadButton) self.loadButton.setBounds(X_BASE + 420, 95, 90, 30) self.selectPath = JButton("Select path") self.selectPath.addActionListener(self.selectExportFile) self.selectPath.setBounds(X_BASE + 530, 60, 120, 30) self.selectPathText = JTextArea("") self.selectPathText.setBounds(X_BASE, 60, 510, 30) self.selectPathLabel = JLabel("State file:") self.selectPathLabel.setBounds(X_BASE, 30, 200, 30) bGroup = ButtonGroup() bGroup.add(self.showAllButton) bGroup.add(self.showNewButton) bGroup.add(self.showTestedButton) config.add(self.clearButton) config.add(self.startButton) config.add(self.startOptionButton) config.add(self.showAllButton) config.add(self.showNewButton) config.add(self.showTestedButton) config.add(self.badExtensionsButton) config.add(self.badExtensionsText) config.add(self.badExtensionsLabel) config.add(self.badMimesButton) config.add(self.badMimesText) config.add(self.badMimesLabel) config.add(self.badExtensionsDefaultButton) config.add(self.badMimesDefaultButton) config.add(self.otherLabel) config.add(self.repeaterOptionButton) config.add(self.scopeOptionButton) config.add(self.markTestedRequestsProxy) config.add(self.markNotTestedRequestsProxy) iexport.add(self.saveButton) iexport.add(self.loadButton) iexport.add(self.selectPath) iexport.add(self.selectPathText) iexport.add(self.selectPathLabel) iexport.add(self.otherLabel2) iexport.add(self.autoSaveOption) self._config.addTab("General", config) self._config.addTab("Import/Export", iexport) ##### end config pane self._parentPane.addTab("Monitor", self._splitpane) self._parentPane.addTab("Config", self._config) # table of log entries self.logTable = Table(self) #self.logTable.setDefaultRenderer(self.logTable.getColumnClass(0), ColoredTableCellRenderer(self)) self.logTable.setAutoCreateRowSorter(True) self.logTable.setRowSelectionAllowed(True) renderer = ColoredTableCellRenderer(self) #column = TableColumn(0, 190, renderer, None) print 'Initiating... ' # this could be improved by fetching initial dimensions self.logTable.getColumn("URL").setPreferredWidth(720) # noscope self.logTable.getColumn("URL").setResizable(True) self.logTable.getColumn("Checked").setCellRenderer(renderer) self.logTable.getColumn("Checked").setPreferredWidth(80) self.logTable.getColumn("Checked").setMaxWidth(80) self.logTable.getColumn("Method").setPreferredWidth(120) #self.logTable.getColumn("Method").setMaxWidth(120) self.logTable.getColumn("Method").setResizable(True) self.logTable.getColumn("Time").setPreferredWidth(120) # noscope self.logTable.getColumn("Time").setResizable(True) scrollPane = JScrollPane(self.logTable) self._splitpane.setLeftComponent(scrollPane) # tabs with request/response viewers 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) ## Row sorter shit #self._tableRowSorterAutoProxyAutoAction = CustomTableRowSorter(self.logTable.getModel()) #self.logTable.setRowSorter(self._tableRowSorterAutoProxyAutoAction) markAnalyzedButton = JMenuItem("Mark Requests as Analyzed") markAnalyzedButton.addActionListener(markRequestsHandler(self, True)) markNotAnalyzedButton = JMenuItem("Mark Requests as NOT Analyzed") markNotAnalyzedButton.addActionListener( markRequestsHandler(self, False)) sendRequestMenu = JMenuItem("Send Request to Repeater") sendRequestMenu.addActionListener(sendRequestRepeater(self)) deleteRequestMenu = JMenuItem("Delete request") deleteRequestMenu.addActionListener(deleteRequestHandler(self)) self.menu = JPopupMenu("Popup") self.menu.add(markAnalyzedButton) self.menu.add(markNotAnalyzedButton) self.menu.add(sendRequestMenu) self.menu.add(deleteRequestMenu) # customize our UI components callbacks.customizeUiComponent(self._parentPane) callbacks.customizeUiComponent(self._splitpane) callbacks.customizeUiComponent(self._config) callbacks.customizeUiComponent(config) callbacks.customizeUiComponent(self.logTable) callbacks.customizeUiComponent(scrollPane) callbacks.customizeUiComponent(tabs) callbacks.registerContextMenuFactory(self) callbacks.registerExtensionStateListener(self) callbacks.registerScannerCheck(passiveScanner(self)) # add the custom tab to Burp's UI callbacks.addSuiteTab(self) # register ourselves as an HTTP listener callbacks.registerHttpListener(self) self.loadConfigs() print "Loaded!" print "Experimental import state.. " self.importState("") self.SC = sched.scheduler(time.time, time.sleep) self.SCC = self.SC.enter(10, 1, self.autoSave, (self.SC, )) self.SC.run() return
def __init__(self, parent, title, modal, app): from java.awt import CardLayout self.app = app border = BorderFactory.createEmptyBorder(5, 7, 7, 7) self.getContentPane().setBorder(border) self.setLayout(BoxLayout(self.getContentPane(), BoxLayout.Y_AXIS)) self.FAVAREALAYERNAME = "Favourite zone editing" info = JLabel(self.app.strings.getString("Create_a_new_favourite_zone")) info.setAlignmentX(Component.LEFT_ALIGNMENT) #Name nameLbl = JLabel(self.app.strings.getString("fav_zone_name")) self.nameTextField = JTextField(20) self.nameTextField.setMaximumSize(self.nameTextField.getPreferredSize()) self.nameTextField.setToolTipText(self.app.strings.getString("fav_zone_name_tooltip")) namePanel = JPanel() namePanel.setLayout(BoxLayout(namePanel, BoxLayout.X_AXIS)) namePanel.add(nameLbl) namePanel.add(Box.createHorizontalGlue()) namePanel.add(self.nameTextField) #Country countryLbl = JLabel(self.app.strings.getString("fav_zone_country")) self.countryTextField = JTextField(20) self.countryTextField.setMaximumSize(self.countryTextField.getPreferredSize()) self.countryTextField.setToolTipText(self.app.strings.getString("fav_zone_country_tooltip")) countryPanel = JPanel() countryPanel.setLayout(BoxLayout(countryPanel, BoxLayout.X_AXIS)) countryPanel.add(countryLbl) countryPanel.add(Box.createHorizontalGlue()) countryPanel.add(self.countryTextField) #Type modeLbl = JLabel(self.app.strings.getString("fav_zone_type")) RECTPANEL = "rectangle" POLYGONPANEL = "polygon" BOUNDARYPANEL = "boundary" self.modesStrings = [RECTPANEL, POLYGONPANEL, BOUNDARYPANEL] modesComboModel = DefaultComboBoxModel() for i in (self.app.strings.getString("rectangle"), self.app.strings.getString("delimited_by_a_closed_way"), self.app.strings.getString("delimited_by_an_administrative_boundary")): modesComboModel.addElement(i) self.modesComboBox = JComboBox(modesComboModel, actionListener=self, editable=False) #- Rectangle self.rectPanel = JPanel() self.rectPanel.setLayout(BoxLayout(self.rectPanel, BoxLayout.Y_AXIS)) capturePane = JPanel() capturePane.setLayout(BoxLayout(capturePane, BoxLayout.X_AXIS)) capturePane.setAlignmentX(Component.LEFT_ALIGNMENT) josmP = JPanel() self.captureRBtn = JRadioButton(self.app.strings.getString("capture_area")) self.captureRBtn.addActionListener(self) self.captureRBtn.setSelected(True) self.bboxFromJosmBtn = JButton(self.app.strings.getString("get_current_area"), actionPerformed=self.on_bboxFromJosmBtn_clicked) self.bboxFromJosmBtn.setToolTipText(self.app.strings.getString("get_capture_area_tooltip")) josmP.add(self.bboxFromJosmBtn) capturePane.add(self.captureRBtn) capturePane.add(Box.createHorizontalGlue()) capturePane.add(self.bboxFromJosmBtn) manualPane = JPanel() manualPane.setLayout(BoxLayout(manualPane, BoxLayout.X_AXIS)) manualPane.setAlignmentX(Component.LEFT_ALIGNMENT) self.manualRBtn = JRadioButton(self.app.strings.getString("use_this_bbox")) self.manualRBtn.addActionListener(self) self.bboxTextField = JTextField(20) self.bboxTextField.setMaximumSize(self.bboxTextField.getPreferredSize()) self.bboxTextField.setToolTipText(self.app.strings.getString("fav_bbox_tooltip")) self.bboxTextFieldDefaultBorder = self.bboxTextField.getBorder() self.bboxTextField.getDocument().addDocumentListener(TextListener(self)) manualPane.add(self.manualRBtn) manualPane.add(Box.createHorizontalGlue()) manualPane.add(self.bboxTextField) group = ButtonGroup() group.add(self.captureRBtn) group.add(self.manualRBtn) previewPane = JPanel() previewPane.setLayout(BoxLayout(previewPane, BoxLayout.X_AXIS)) previewPane.setAlignmentX(Component.LEFT_ALIGNMENT) bboxPreviewInfo = JTextField(self.app.strings.getString("coordinates"), editable=0, border=None) bboxPreviewInfo.setMaximumSize(bboxPreviewInfo.getPreferredSize()) self.bboxPreviewTextField = JTextField(20, editable=0, border=None) self.bboxPreviewTextField.setMaximumSize(self.bboxPreviewTextField.getPreferredSize()) previewPane.add(bboxPreviewInfo) previewPane.add(Box.createHorizontalGlue()) previewPane.add(self.bboxPreviewTextField) self.rectPanel.add(capturePane) self.rectPanel.add(Box.createRigidArea(Dimension(0, 10))) self.rectPanel.add(manualPane) self.rectPanel.add(Box.createRigidArea(Dimension(0, 20))) self.rectPanel.add(previewPane) #- Polygon (closed way) drawn by hand self.polygonPanel = JPanel(BorderLayout()) self.polygonPanel.setLayout(BoxLayout(self.polygonPanel, BoxLayout.Y_AXIS)) polyInfo = JLabel("<html>%s</html>" % self.app.strings.getString("polygon_info")) polyInfo.setFont(polyInfo.getFont().deriveFont(Font.ITALIC)) polyInfo.setAlignmentX(Component.LEFT_ALIGNMENT) editPolyPane = JPanel() editPolyPane.setAlignmentX(Component.LEFT_ALIGNMENT) editPolyBtn = JButton(self.app.strings.getString("create_fav_layer"), actionPerformed=self.create_new_zone_editing_layer) editPolyBtn.setToolTipText(self.app.strings.getString("create_fav_layer_tooltip")) editPolyPane.add(editPolyBtn) self.polygonPanel.add(polyInfo) self.polygonPanel.add(Box.createRigidArea(Dimension(0, 15))) self.polygonPanel.add(editPolyPane) self.polygonPanel.add(Box.createRigidArea(Dimension(0, 15))) #- Administrative Boundary self.boundaryPanel = JPanel() self.boundaryPanel.setLayout(BoxLayout(self.boundaryPanel, BoxLayout.Y_AXIS)) boundaryInfo = JLabel("<html>%s</html>" % app.strings.getString("boundary_info")) boundaryInfo.setFont(boundaryInfo.getFont().deriveFont(Font.ITALIC)) boundaryInfo.setAlignmentX(Component.LEFT_ALIGNMENT) boundaryTagsPanel = JPanel(GridLayout(3, 3, 5, 5)) boundaryTagsPanel.setAlignmentX(Component.LEFT_ALIGNMENT) boundaryTagsPanel.add(JLabel("name =")) self.nameTagTextField = JTextField(20) boundaryTagsPanel.add(self.nameTagTextField) boundaryTagsPanel.add(JLabel("admin_level =")) self.adminLevelTagTextField = JTextField(20) self.adminLevelTagTextField.setToolTipText(self.app.strings.getString("adminLevel_tooltip")) boundaryTagsPanel.add(self.adminLevelTagTextField) boundaryTagsPanel.add(JLabel(self.app.strings.getString("other_tag"))) self.optionalTagTextField = JTextField(20) self.optionalTagTextField.setToolTipText("key=value") boundaryTagsPanel.add(self.optionalTagTextField) downloadBoundariesPane = JPanel() downloadBoundariesPane.setAlignmentX(Component.LEFT_ALIGNMENT) downloadBoundariesBtn = JButton(self.app.strings.getString("download_boundary"), actionPerformed=self.on_downloadBoundariesBtn_clicked) downloadBoundariesBtn.setToolTipText(self.app.strings.getString("download_boundary_tooltip")) downloadBoundariesPane.add(downloadBoundariesBtn) self.boundaryPanel.add(boundaryInfo) self.boundaryPanel.add(Box.createRigidArea(Dimension(0, 15))) self.boundaryPanel.add(boundaryTagsPanel) self.boundaryPanel.add(Box.createRigidArea(Dimension(0, 10))) self.boundaryPanel.add(downloadBoundariesPane) self.editingPanels = {"rectangle": self.rectPanel, "polygon": self.polygonPanel, "boundary": self.boundaryPanel} #Main buttons self.okBtn = JButton(self.app.strings.getString("OK"), ImageProvider.get("ok"), actionPerformed=self.on_okBtn_clicked) self.cancelBtn = JButton(self.app.strings.getString("cancel"), ImageProvider.get("cancel"), actionPerformed=self.close_dialog) self.previewBtn = JButton(self.app.strings.getString("Preview_zone"), actionPerformed=self.on_previewBtn_clicked) self.previewBtn.setToolTipText(self.app.strings.getString("preview_zone_tooltip")) okBtnSize = self.okBtn.getPreferredSize() viewBtnSize = self.previewBtn.getPreferredSize() viewBtnSize.height = okBtnSize.height self.previewBtn.setPreferredSize(viewBtnSize) #layout self.add(info) self.add(Box.createRigidArea(Dimension(0, 15))) namePanel.setAlignmentX(Component.LEFT_ALIGNMENT) self.add(namePanel) self.add(Box.createRigidArea(Dimension(0, 15))) countryPanel.setAlignmentX(Component.LEFT_ALIGNMENT) self.add(countryPanel) self.add(Box.createRigidArea(Dimension(0, 15))) modeLbl.setAlignmentX(Component.LEFT_ALIGNMENT) self.add(modeLbl) self.add(Box.createRigidArea(Dimension(0, 5))) self.add(self.modesComboBox) self.modesComboBox.setAlignmentX(Component.LEFT_ALIGNMENT) self.add(Box.createRigidArea(Dimension(0, 15))) self.configPanel = JPanel(CardLayout()) self.configPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)) self.configPanel.add(self.rectPanel, RECTPANEL) self.configPanel.add(self.polygonPanel, POLYGONPANEL) self.configPanel.add(self.boundaryPanel, BOUNDARYPANEL) self.configPanel.setAlignmentX(Component.LEFT_ALIGNMENT) self.add(self.configPanel) buttonsPanel = JPanel() buttonsPanel.add(self.okBtn) buttonsPanel.add(self.cancelBtn) buttonsPanel.add(self.previewBtn) buttonsPanel.setAlignmentX(Component.LEFT_ALIGNMENT) self.add(buttonsPanel) self.addWindowListener(self) self.pack()
def __addRadioButton(self, label, listener): button = JRadioButton(label) button.setActionCommand(label) button.addActionListener(listener) self.add(button, self.__createRadioConstraints(label)) return button
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
class NewZoneDialog(JDialog, ActionListener, WindowListener): """Dialog for favourite zone editing """ def __init__(self, app): from java.awt import Dialog from java.awt import CardLayout JDialog.__init__(self, app.preferencesFrame, app.strings.getString("Create_a_new_favourite_zone"), Dialog.ModalityType.DOCUMENT_MODAL) self.app = app border = BorderFactory.createEmptyBorder(5, 7, 7, 7) self.getContentPane().setBorder(border) self.setLayout(BoxLayout(self.getContentPane(), BoxLayout.Y_AXIS)) self.FAVAREALAYERNAME = "Favourite zone editing" info = JLabel(self.app.strings.getString("Create_a_new_favourite_zone")) info.setAlignmentX(Component.LEFT_ALIGNMENT) #Name nameLbl = JLabel(self.app.strings.getString("fav_zone_name")) self.nameTextField = JTextField(20) self.nameTextField.setMaximumSize(self.nameTextField.getPreferredSize()) self.nameTextField.setToolTipText(self.app.strings.getString("fav_zone_name_tooltip")) namePanel = JPanel() namePanel.setLayout(BoxLayout(namePanel, BoxLayout.X_AXIS)) namePanel.add(nameLbl) namePanel.add(Box.createHorizontalGlue()) namePanel.add(self.nameTextField) #Country countryLbl = JLabel(self.app.strings.getString("fav_zone_country")) self.countryTextField = JTextField(20) self.countryTextField.setMaximumSize(self.countryTextField.getPreferredSize()) self.countryTextField.setToolTipText(self.app.strings.getString("fav_zone_country_tooltip")) countryPanel = JPanel() countryPanel.setLayout(BoxLayout(countryPanel, BoxLayout.X_AXIS)) countryPanel.add(countryLbl) countryPanel.add(Box.createHorizontalGlue()) countryPanel.add(self.countryTextField) #Type modeLbl = JLabel(self.app.strings.getString("fav_zone_type")) RECTPANEL = "rectangle" POLYGONPANEL = "polygon" BOUNDARYPANEL = "boundary" self.modesStrings = [RECTPANEL, POLYGONPANEL, BOUNDARYPANEL] modesComboModel = DefaultComboBoxModel() for i in (self.app.strings.getString("rectangle"), self.app.strings.getString("delimited_by_a_closed_way"), self.app.strings.getString("delimited_by_an_administrative_boundary")): modesComboModel.addElement(i) self.modesComboBox = JComboBox(modesComboModel, actionListener=self, editable=False) #- Rectangle self.rectPanel = JPanel() self.rectPanel.setLayout(BoxLayout(self.rectPanel, BoxLayout.Y_AXIS)) capturePane = JPanel() capturePane.setLayout(BoxLayout(capturePane, BoxLayout.X_AXIS)) capturePane.setAlignmentX(Component.LEFT_ALIGNMENT) josmP = JPanel() self.captureRBtn = JRadioButton(self.app.strings.getString("capture_area")) self.captureRBtn.addActionListener(self) self.captureRBtn.setSelected(True) self.bboxFromJosmBtn = JButton(self.app.strings.getString("get_current_area"), actionPerformed=self.on_bboxFromJosmBtn_clicked) self.bboxFromJosmBtn.setToolTipText(self.app.strings.getString("get_capture_area_tooltip")) josmP.add(self.bboxFromJosmBtn) capturePane.add(self.captureRBtn) capturePane.add(Box.createHorizontalGlue()) capturePane.add(self.bboxFromJosmBtn) manualPane = JPanel() manualPane.setLayout(BoxLayout(manualPane, BoxLayout.X_AXIS)) manualPane.setAlignmentX(Component.LEFT_ALIGNMENT) self.manualRBtn = JRadioButton(self.app.strings.getString("use_this_bbox")) self.manualRBtn.addActionListener(self) self.bboxTextField = JTextField(20) self.bboxTextField.setMaximumSize(self.bboxTextField.getPreferredSize()) self.bboxTextField.setToolTipText(self.app.strings.getString("fav_bbox_tooltip")) self.bboxTextFieldDefaultBorder = self.bboxTextField.getBorder() self.bboxTextField.getDocument().addDocumentListener(TextListener(self)) manualPane.add(self.manualRBtn) manualPane.add(Box.createHorizontalGlue()) manualPane.add(self.bboxTextField) group = ButtonGroup() group.add(self.captureRBtn) group.add(self.manualRBtn) previewPane = JPanel() previewPane.setLayout(BoxLayout(previewPane, BoxLayout.X_AXIS)) previewPane.setAlignmentX(Component.LEFT_ALIGNMENT) bboxPreviewInfo = JTextField(self.app.strings.getString("coordinates"), editable=0, border=None) bboxPreviewInfo.setMaximumSize(bboxPreviewInfo.getPreferredSize()) self.bboxPreviewTextField = JTextField(20, editable=0, border=None) self.bboxPreviewTextField.setMaximumSize(self.bboxPreviewTextField.getPreferredSize()) previewPane.add(bboxPreviewInfo) previewPane.add(Box.createHorizontalGlue()) previewPane.add(self.bboxPreviewTextField) self.rectPanel.add(capturePane) self.rectPanel.add(Box.createRigidArea(Dimension(0, 10))) self.rectPanel.add(manualPane) self.rectPanel.add(Box.createRigidArea(Dimension(0, 20))) self.rectPanel.add(previewPane) #- Polygon (closed way) drawn by hand self.polygonPanel = JPanel(BorderLayout()) self.polygonPanel.setLayout(BoxLayout(self.polygonPanel, BoxLayout.Y_AXIS)) polyInfo = JLabel("<html>%s</html>" % self.app.strings.getString("polygon_info")) polyInfo.setFont(polyInfo.getFont().deriveFont(Font.ITALIC)) polyInfo.setAlignmentX(Component.LEFT_ALIGNMENT) editPolyPane = JPanel() editPolyPane.setAlignmentX(Component.LEFT_ALIGNMENT) editPolyBtn = JButton(self.app.strings.getString("create_fav_layer"), actionPerformed=self.create_new_zone_editing_layer) editPolyBtn.setToolTipText(self.app.strings.getString("create_fav_layer_tooltip")) editPolyPane.add(editPolyBtn) self.polygonPanel.add(polyInfo) self.polygonPanel.add(Box.createRigidArea(Dimension(0, 15))) self.polygonPanel.add(editPolyPane) self.polygonPanel.add(Box.createRigidArea(Dimension(0, 15))) #- Administrative Boundary self.boundaryPanel = JPanel() self.boundaryPanel.setLayout(BoxLayout(self.boundaryPanel, BoxLayout.Y_AXIS)) boundaryInfo = JLabel("<html>%s</html>" % app.strings.getString("boundary_info")) boundaryInfo.setFont(boundaryInfo.getFont().deriveFont(Font.ITALIC)) boundaryInfo.setAlignmentX(Component.LEFT_ALIGNMENT) boundaryTagsPanel = JPanel(GridLayout(3, 3, 5, 5)) boundaryTagsPanel.setAlignmentX(Component.LEFT_ALIGNMENT) boundaryTagsPanel.add(JLabel("name =")) self.nameTagTextField = JTextField(20) boundaryTagsPanel.add(self.nameTagTextField) boundaryTagsPanel.add(UrlLabel("http://wiki.openstreetmap.org/wiki/Key:admin_level#admin_level", "admin_level =")) self.adminLevelTagTextField = JTextField(20) self.adminLevelTagTextField.setToolTipText(self.app.strings.getString("adminLevel_tooltip")) boundaryTagsPanel.add(self.adminLevelTagTextField) boundaryTagsPanel.add(JLabel(self.app.strings.getString("other_tag"))) self.optionalTagTextField = JTextField(20) self.optionalTagTextField.setToolTipText("key=value") boundaryTagsPanel.add(self.optionalTagTextField) downloadBoundariesPane = JPanel() downloadBoundariesPane.setAlignmentX(Component.LEFT_ALIGNMENT) downloadBoundariesBtn = JButton(self.app.strings.getString("download_boundary"), actionPerformed=self.on_downloadBoundariesBtn_clicked) downloadBoundariesBtn.setToolTipText(self.app.strings.getString("download_boundary_tooltip")) downloadBoundariesPane.add(downloadBoundariesBtn) self.boundaryPanel.add(boundaryInfo) self.boundaryPanel.add(Box.createRigidArea(Dimension(0, 15))) self.boundaryPanel.add(boundaryTagsPanel) self.boundaryPanel.add(Box.createRigidArea(Dimension(0, 10))) self.boundaryPanel.add(downloadBoundariesPane) self.editingPanels = {"rectangle": self.rectPanel, "polygon": self.polygonPanel, "boundary": self.boundaryPanel} #Main buttons self.okBtn = JButton(self.app.strings.getString("OK"), ImageProvider.get("ok"), actionPerformed=self.on_okBtn_clicked) self.cancelBtn = JButton(self.app.strings.getString("cancel"), ImageProvider.get("cancel"), actionPerformed=self.close_dialog) self.previewBtn = JButton(self.app.strings.getString("Preview_zone"), actionPerformed=self.on_previewBtn_clicked) self.previewBtn.setToolTipText(self.app.strings.getString("preview_zone_tooltip")) okBtnSize = self.okBtn.getPreferredSize() viewBtnSize = self.previewBtn.getPreferredSize() viewBtnSize.height = okBtnSize.height self.previewBtn.setPreferredSize(viewBtnSize) #layout self.add(info) self.add(Box.createRigidArea(Dimension(0, 15))) namePanel.setAlignmentX(Component.LEFT_ALIGNMENT) self.add(namePanel) self.add(Box.createRigidArea(Dimension(0, 15))) countryPanel.setAlignmentX(Component.LEFT_ALIGNMENT) self.add(countryPanel) self.add(Box.createRigidArea(Dimension(0, 15))) modeLbl.setAlignmentX(Component.LEFT_ALIGNMENT) self.add(modeLbl) self.add(Box.createRigidArea(Dimension(0, 5))) self.add(self.modesComboBox) self.modesComboBox.setAlignmentX(Component.LEFT_ALIGNMENT) self.add(Box.createRigidArea(Dimension(0, 15))) self.configPanel = JPanel(CardLayout()) self.configPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)) self.configPanel.add(self.rectPanel, RECTPANEL) self.configPanel.add(self.polygonPanel, POLYGONPANEL) self.configPanel.add(self.boundaryPanel, BOUNDARYPANEL) self.configPanel.setAlignmentX(Component.LEFT_ALIGNMENT) self.add(self.configPanel) buttonsPanel = JPanel() buttonsPanel.add(self.okBtn) buttonsPanel.add(self.cancelBtn) buttonsPanel.add(self.previewBtn) buttonsPanel.setAlignmentX(Component.LEFT_ALIGNMENT) self.add(buttonsPanel) self.addWindowListener(self) self.pack() def update_gui_from_preferences(self): self.nameTextField.setText(self.app.newZone.name) #Reset rectangle mode bboxStr = ",".join(["%0.4f" % x for x in self.app.newZone.bbox]) self.bboxTextField.setText(bboxStr) self.bboxPreviewTextField.setText(bboxStr) self.bboxFromJosmBtn.setEnabled(True) self.bboxTextField.setEnabled(False) #Reset polygon mode self.polygonAsString = "" #Reset boundary mode self.boundaryAsString = "" self.modesComboBox.setSelectedIndex(0) def actionPerformed(self, e): #Show the panel for configuring the favourite area of the #selected type if e.getSource() == self.modesComboBox: cl = self.configPanel.getLayout() selectedMode = self.modesStrings[self.modesComboBox.selectedIndex] cl.show(self.configPanel, selectedMode) #Activate bbox input for rectangular favourite zone mode elif e.getSource() == self.captureRBtn: self.bboxFromJosmBtn.setEnabled(True) self.bboxTextField.setEnabled(False) else: self.bboxFromJosmBtn.setEnabled(False) self.bboxTextField.setEnabled(True) def on_bboxFromJosmBtn_clicked(self, widget): """Read bbox currently shown in JOSM """ bbox = self.app.get_frame_bounds() self.bboxPreviewTextField.setText(",".join(["%0.4f" % x for x in bbox])) ### Manage layer for creating a new favourite zone from polygon or boundary def create_new_zone_editing_layer(self, e=None): """Open a new dataset where the user can draw a closed way to delimit the favourite area """ layer = self.get_new_zone_editing_layer() if layer is not None: self.app.mv.setActiveLayer(layer) else: Main.main.addLayer(OsmDataLayer(DataSet(), self.FAVAREALAYERNAME, None)) Main.main.parent.toFront() def get_new_zone_editing_layer(self): """Check if the layer for editing the favourite area yet exists """ for layer in self.app.mv.getAllLayers(): if layer.getName() == self.FAVAREALAYERNAME: return layer return None def remove_new_zone_editing_layer(self): layer = self.get_new_zone_editing_layer() if layer is not None: self.app.mv.removeLayer(layer) def on_zone_edited(self): """Read ways that delimit the favourite area and convert them to jts geometry """ if self.modesComboBox.getSelectedIndex() == 0: mode = "rectangle" elif self.modesComboBox.getSelectedIndex() == 1: mode = "polygon" elif self.modesComboBox.getSelectedIndex() == 2: mode = "boundary" if mode in ("polygon", "boundary"): layer = self.get_new_zone_editing_layer() if layer is not None: self.app.mv.setActiveLayer(layer) else: if mode == "polygon": msg = self.app.strings.getString("polygon_fav_layer_missing_msg") else: msg = self.app.strings.getString("boundary_fav_layer_missing_msg") JOptionPane.showMessageDialog(self, msg, self.app.strings.getString("Warning"), JOptionPane.WARNING_MESSAGE) return dataset = self.app.mv.editLayer.data areaWKT = self.read_area_from_osm_ways(mode, dataset) if areaWKT is None: print "I could not read the new favourite area." else: if mode == "polygon": self.polygonAsString = areaWKT else: self.boundaryAsString = areaWKT return mode def read_area_from_osm_ways(self, mode, dataset): """Read way in favourite area editing layer and convert them to WKT """ converter = JTSConverter(False) lines = [converter.convert(way) for way in dataset.ways] polygonizer = Polygonizer() polygonizer.add(lines) polygons = polygonizer.getPolygons() multipolygon = GeometryFactory().createMultiPolygon(list(polygons)) multipolygonWKT = WKTWriter().write(multipolygon) if multipolygonWKT == "MULTIPOLYGON EMPTY": if mode == "polygon": msg = self.app.strings.getString("empty_ways_polygon_msg") else: msg = self.app.strings.getString("empty_ways_boundaries_msg") JOptionPane.showMessageDialog(self, msg, self.app.strings.getString("Warning"), JOptionPane.WARNING_MESSAGE) return return multipolygonWKT def on_downloadBoundariesBtn_clicked(self, e): """Download puter ways of administrative boundaries from Overpass API """ adminLevel = self.adminLevelTagTextField.getText() name = self.nameTagTextField.getText() optional = self.optionalTagTextField.getText() if (adminLevel, name, optional) == ("", "", ""): JOptionPane.showMessageDialog(self, self.app.strings.getString("enter_a_tag_msg"), self.app.strings.getString("Warning"), JOptionPane.WARNING_MESSAGE) return optTag = "" if optional.find("=") != -1: if len(optional.split("=")) == 2: key, value = optional.split("=") optTag = '["%s"="%s"]' % (URLEncoder.encode(key, "UTF-8"), URLEncoder.encode(value.replace(" ", "%20"), "UTF-8")) self.create_new_zone_editing_layer() overpassurl = 'http://127.0.0.1:8111/import?url=' overpassurl += 'http://overpass-api.de/api/interpreter?data=' overpassquery = 'relation["admin_level"="%s"]' % adminLevel overpassquery += '["name"="%s"]' % URLEncoder.encode(name, "UTF-8") overpassquery += '%s;(way(r:"outer");node(w););out meta;' % optTag overpassurl += overpassquery.replace(" ", "%20") print overpassurl self.app.send_to_josm(overpassurl) ### Buttons ############################################################ def create_new_zone(self, mode): """Read data entered on gui and create a new zone """ name = self.nameTextField.getText() country = self.countryTextField.getText().upper() #error: name if name.replace(" ", "") == "": JOptionPane.showMessageDialog(self, self.app.strings.getString("missing_name_warning"), self.app.strings.getString("missing_name_warning_title"), JOptionPane.WARNING_MESSAGE) return False if name in [z.name for z in self.app.tempZones]: JOptionPane.showMessageDialog(self, self.app.strings.getString("duplicate_name_warning"), self.app.strings.getString("duplicate_name_warning_title"), JOptionPane.WARNING_MESSAGE) return False #zone type zType = mode #error: geometry type not defined if zType == "polygon" and self.polygonAsString == ""\ or zType == "boundary" and self.boundaryAsString == "": JOptionPane.showMessageDialog(self, self.app.strings.getString("zone_not_correctly_build_warning"), self.app.strings.getString("zone_not_correctly_build_warning_title"), JOptionPane.WARNING_MESSAGE) return False #geometry string if zType == "rectangle": geomString = self.bboxPreviewTextField.getText() elif zType == "polygon": geomString = self.polygonAsString else: geomString = self.boundaryAsString self.app.newZone = Zone(self.app, name, zType, geomString, country) #self.app.newZone.print_info() return True def on_okBtn_clicked(self, event): """Add new zone to temp zones """ mode = self.on_zone_edited() if self.create_new_zone(mode): self.app.tempZones.append(self.app.newZone) self.app.preferencesFrame.zonesTable.getModel().addRow([self.app.newZone.country, self.app.newZone.icon, self.app.newZone.name]) maxIndex = len(self.app.tempZones) - 1 self.app.preferencesFrame.zonesTable.setRowSelectionInterval(maxIndex, maxIndex) self.close_dialog() self.app.preferencesFrame.check_removeBtn_status() self.app.preferencesFrame.zonesTable.scrollRectToVisible( self.app.preferencesFrame.zonesTable.getCellRect( self.app.preferencesFrame.zonesTable.getRowCount() - 1, 0, True)) def on_previewBtn_clicked(self, e): """Show the favourite area on a map """ mode = self.on_zone_edited() if not self.create_new_zone(mode): return zone = self.app.newZone if zone.zType == "rectangle": wktString = zone.bbox_to_wkt_string() else: wktString = zone.wktGeom script = '/*http://stackoverflow.com/questions/11954401/wkt-and-openlayers*/' script += '\nfunction init() {' script += '\n var map = new OpenLayers.Map({' script += '\n div: "map",' script += '\n projection: new OpenLayers.Projection("EPSG:900913"),' script += '\n displayProjection: new OpenLayers.Projection("EPSG:4326"),' script += '\n layers: [' script += '\n new OpenLayers.Layer.OSM()' script += '\n ]' script += '\n });' script += '\n var wkt = new OpenLayers.Format.WKT();' script += '\n var polygonFeature = wkt.read("%s");' % wktString script += '\n var vectors = new OpenLayers.Layer.Vector("Favourite area");' script += '\n map.addLayer(vectors);' script += '\n polygonFeature.geometry.transform(map.displayProjection, map.getProjectionObject());' script += '\n vectors.addFeatures([polygonFeature]);' script += '\n map.zoomToExtent(vectors.getDataExtent());' script += '\n};' scriptFile = open(File.separator.join([self.app.SCRIPTDIR, "html", "script.js"]), "w") scriptFile.write(script) scriptFile.close() OpenBrowser.displayUrl(File.separator.join([self.app.SCRIPTDIR, "html", "favourite_area.html"])) def windowClosing(self, windowEvent): self.close_dialog() def close_dialog(self, e=None): #delete favourite zone editing layer if present self.remove_new_zone_editing_layer() self.dispose() self.app.preferencesFrame.toFront()
def openGUI(self, invocation): try: # Get values from request or response the extension is invoked from and prepopulate GUI values invMessage = invocation.getSelectedMessages() message = invMessage[0] originalHttpService = message.getHttpService() self.originalMsgProtocol = originalHttpService.getProtocol() self.originalMsgHost = originalHttpService.getHost() self.originalMsgPort = originalHttpService.getPort() except: self.originalMsgProtocol = '' self.originalMsgHost = '' self.originalMsgPort = '' try: self.cookies = self._callbacks.getCookieJarContents() self.cookie = '' except: pass self.SSL = 'http://' self.listType = '' self.parsedList = [] # Set up main window (JFrame) self.window = JFrame("Directory Listing Parser for Burp Suite", preferredSize=(600, 475), windowClosing=self.closeUI) self.window.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE) emptyBorder = BorderFactory.createEmptyBorder(10, 10, 10, 10) self.window.contentPane.setBorder(emptyBorder) self.window.contentPane.layout = BorderLayout() # Main window title placed at the top of the main window with an invisible bottom border titlePanel = JPanel() titleBorder = BorderFactory.createEmptyBorder(0, 0, 10, 0) title = JLabel("Directory Listing Parser for Burp Suite", JLabel.CENTER) title.setBorder(titleBorder) title.setFont(Font("Default", Font.PLAIN, 18)) titlePanel.add(title) self.window.contentPane.add("North", titlePanel) # Left panel for user input, consisting of hostname, directory prefix, ssl, port, type of listing, and file self.leftPanel = JPanel() self.leftPanel.layout = GridLayout(14, 1, 3, 3) hostnameLabel = JLabel("Hostname:") if self.originalMsgHost: self.hostnameTextField = JTextField(self.originalMsgHost.rstrip()) else: self.hostnameTextField = JTextField('Hostname') dirPrefixLabel = JLabel("Full Directory Prefix (Windows):") self.dirPrefixField = JTextField('C:\\var\www\\') sslLabel = JLabel("SSL:") self.radioBtnSslEnabled = JRadioButton('Enabled (https)', actionPerformed=self.radioSsl) self.radioBtnSslDisabled = JRadioButton('Disabled (http)', actionPerformed=self.radioSsl) sslButtonGroup = ButtonGroup() sslButtonGroup.add(self.radioBtnSslEnabled) sslButtonGroup.add(self.radioBtnSslDisabled) if self.originalMsgProtocol == "https": self.radioBtnSslEnabled.setSelected(True) else: self.radioBtnSslDisabled.setSelected(True) portLabel = JLabel("Port:") if self.originalMsgPort: self.portTextField = JTextField(str(self.originalMsgPort).rstrip()) else: self.portTextField = JTextField('80') osLabel = JLabel("Type of File Listing:") self.types = ('Windows \'dir /s\'', 'Linux \'ls -lR\'', 'Linux \'ls -R\'') self.comboListingType = JComboBox(self.types) uploadLabel = JLabel("Directory Listing File:") self.uploadTextField = JTextField('') uploadButton = JButton('Choose File', actionPerformed=self.chooseFile) self.leftPanel.add(hostnameLabel) self.leftPanel.add(self.hostnameTextField) self.leftPanel.add(dirPrefixLabel) self.leftPanel.add(self.dirPrefixField) self.leftPanel.add(sslLabel) self.leftPanel.add(self.radioBtnSslEnabled) self.leftPanel.add(self.radioBtnSslDisabled) self.leftPanel.add(portLabel) self.leftPanel.add(self.portTextField) self.leftPanel.add(osLabel) self.leftPanel.add(self.comboListingType) self.leftPanel.add(uploadLabel) self.leftPanel.add(self.uploadTextField) self.leftPanel.add(uploadButton) # Right panel consisting of a text area for the URL list self.UrlPanelLabel = JLabel("URL List:") self.textArea = JTextArea() self.textArea.setEditable(True) self.textArea.setFont(Font("Default", Font.PLAIN, 14)) if self.cookies: self.textArea.append('Cookies Found:\n') for cookie in self.cookies: if cookie.getDomain() in self.originalMsgHost: self.cookie += cookie.getName() + '=' + cookie.getValue() + '; ' self.textArea.append(cookie.getName() + '=' + cookie.getValue() + '\n') scrollArea = JScrollPane(self.textArea) scrollArea.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS) scrollArea.setPreferredSize(Dimension(400, 200)) self.rightPanel = JPanel() self.rightPanel.setLayout(BorderLayout(3, 3)) self.rightPanel.add(self.UrlPanelLabel, BorderLayout.NORTH) self.rightPanel.add(scrollArea, BorderLayout.CENTER) # Panel for the generate URL list and import URL list buttons generatePanel = JPanel() generatePanel.layout = BorderLayout(3, 3) generateButton = JButton('Generate URL List', actionPerformed=self.generateUrlList) importButton = JButton('Import URL List to Burp Site Map', actionPerformed=self.confirmImport) generatePanel.add("North", generateButton) generatePanel.add("South", importButton) self.rightPanel.add("South", generatePanel) # Add the two main panels to the left and right sides self.window.contentPane.add("East", self.rightPanel) self.window.contentPane.add("West", self.leftPanel) # Create a panel to be used for the file chooser window self.uploadPanel = JPanel() self.window.pack() self.window.show()
class BurpExtender(IBurpExtender, IContextMenuFactory, IHttpListener, ISessionHandlingAction, ITab): def registerExtenderCallbacks(self, callbacks): self._callbacks = callbacks self._helpers = callbacks.getHelpers() callbacks.setExtensionName("JC-AntiToken") callbacks.registerContextMenuFactory(self) # callbacks.registerHttpListener(self) callbacks.registerSessionHandlingAction(self) self.drawUI() def printcn(self, msg): print(msg.decode('utf-8').encode(sys_encoding)) def drawUI(self): # 最外层:垂直盒子,内放一个水平盒子+一个胶水 out_vBox_main = Box.createVerticalBox() # 次外层:水平盒子,使用说明 usage = u''' JC-AntiToken(简单防重放绕过) 适用场景:防重放的方式为,提前向一个页面发送请求取得token,替换到下一个页面中。 适用说明: 1. 请求头中Headers和Data的值必须是JSON字符串,如:{"var":"value"} 2. 左边tokenRegex的格式为: a. .*开头,.*结尾,用()括住要取出的token b. 如:.*,"token":"(.*?)".* 3. 右边tokenRegex的格式为: a. 需要三个(),第二个()括住要替换的token b. 如:(.*,"token":")(.*?)(".*) 详见:https://github.com/chroblert/JC-AntiToken ''' hBox_usage = Box.createHorizontalBox() jpanel_test = JPanel() jTextarea_usage = JTextArea() jTextarea_usage.setText(usage) jTextarea_usage.setRows(13) jTextarea_usage.setEditable(False) # jpanel_test.add(jTextarea_usage) hBox_usage.add(JScrollPane(jTextarea_usage)) # 次外层:水平盒子,内放两个垂直盒子 hBox_main = Box.createHorizontalBox() # 左垂直盒子 vBox_left = Box.createVerticalBox() # 右垂直盒子 vBox_right = Box.createVerticalBox() # 左垂直盒子内部:发送请求包拿token # URL标签 jlabel_url = JLabel(" URL: ") self.jtext_url = JTextField(generWidth) self.jtext_url.setMaximumSize(self.jtext_url.getPreferredSize()) hbox_url = Box.createHorizontalBox() hbox_url.add(jlabel_url) hbox_url.add(self.jtext_url) hglue_url = Box.createHorizontalGlue() hbox_url.add(hglue_url) # 请求方法标签 jlabel_reqMeth = JLabel("ReqMeth: ") self.jcombobox_reqMeth = JComboBox() self.jcombobox_reqMeth.addItem("GET") self.jcombobox_reqMeth.addItem("POST") hbox_reqMeth = Box.createHorizontalBox() hbox_reqMeth.add(jlabel_reqMeth) hbox_reqMeth.add(self.jcombobox_reqMeth) self.jcombobox_reqMeth.setMaximumSize( self.jcombobox_reqMeth.getPreferredSize()) hglue_reqMeth = Box.createHorizontalGlue() hbox_reqMeth.add(hglue_reqMeth) # ContentType标签 jlabel_contentType = JLabel("ConType: ") self.jcombobox_contentType = JComboBox() self.jcombobox_contentType.addItem("application/json") self.jcombobox_contentType.addItem("application/x-www-form-urlencoded") hbox_contentType = Box.createHorizontalBox() hbox_contentType.add(jlabel_contentType) hbox_contentType.add(self.jcombobox_contentType) self.jcombobox_contentType.setMaximumSize( self.jcombobox_contentType.getPreferredSize()) hglue_contentType = Box.createHorizontalGlue() hbox_contentType.add(hglue_contentType) # Charset标签 jlabel_charset = JLabel("CharSet: ") self.jcombobox_charset = JComboBox() self.jcombobox_charset.addItem("UTF-8") self.jcombobox_charset.addItem("GBK") hbox_charset = Box.createHorizontalBox() hbox_charset.add(jlabel_charset) hbox_charset.add(self.jcombobox_charset) self.jcombobox_charset.setMaximumSize( self.jcombobox_charset.getPreferredSize()) hglue_charset = Box.createHorizontalGlue() hbox_charset.add(hglue_charset) # 请求头标签 jlabel_headers = JLabel("Headers: ") self.jtext_headers = JTextField(generWidth) self.jtext_headers.setMaximumSize( self.jtext_headers.getPreferredSize()) hbox_headers = Box.createHorizontalBox() hbox_headers.add(jlabel_headers) hbox_headers.add(self.jtext_headers) hglue_headers = Box.createHorizontalGlue() hbox_headers.add(hglue_headers) # 请求参数标签 jlabel_data = JLabel(" Data: ") self.jtext_data = JTextField(generWidth) self.jtext_data.setPreferredSize(Dimension(20, 40)) self.jtext_data.setMaximumSize(self.jtext_data.getPreferredSize()) hbox_data = Box.createHorizontalBox() hbox_data.add(jlabel_data) hbox_data.add(self.jtext_data) hglue_data = Box.createHorizontalGlue() hbox_data.add(hglue_data) # token标志位置标签 hbox_radiobtn = Box.createHorizontalBox() jlabel_tokenPosition = JLabel("Token Position: ") self.radioBtn01 = JRadioButton("Header") self.radioBtn02 = JRadioButton("Body") btnGroup = ButtonGroup() btnGroup.add(self.radioBtn01) btnGroup.add(self.radioBtn02) self.radioBtn01.setSelected(True) hbox_radiobtn.add(jlabel_tokenPosition) hbox_radiobtn.add(self.radioBtn01) hbox_radiobtn.add(self.radioBtn02) # token正则表达式标签 hbox_token = Box.createHorizontalBox() hbox_token_header = Box.createHorizontalBox() hbox_token_body = Box.createHorizontalBox() # token正则表达式标签:header中 jlabel_tokenName = JLabel("tokenName: ") self.jtext_tokenName = JTextField(tokenWidth) self.jtext_tokenName.setMaximumSize( self.jtext_tokenName.getPreferredSize()) hbox_token_header.add(jlabel_tokenName) hbox_token_header.add(self.jtext_tokenName) hglue_token_header = Box.createHorizontalGlue() hbox_token_header.add(hglue_token_header) # token正则表达式标签:body中 jlabel_tokenRegex = JLabel("tokenRegex: ") self.jtext_tokenRegex = JTextField(tokenWidth) self.jtext_tokenRegex.setMaximumSize( self.jtext_tokenRegex.getPreferredSize()) hbox_token_body.add(jlabel_tokenRegex) hbox_token_body.add(self.jtext_tokenRegex) hglue_token_body = Box.createHorizontalGlue() hbox_token_body.add(hglue_token_body) # token正则表达式标签 hbox_token.add(hbox_token_header) hbox_token.add(hbox_token_body) # test测试按钮 hbox_test = Box.createHorizontalBox() jbtn_test = JButton("TEST", actionPerformed=self.btnTest) self.jlabel_test = JLabel("Result: ") hbox_test.add(jbtn_test) hbox_test.add(self.jlabel_test) # 水平胶水填充 hGlue_test = Box.createHorizontalGlue() hbox_test.add(hGlue_test) hbox_test.setBorder(BorderFactory.createLineBorder(Color.green, 2)) # 响应数据输出 hbox_resp = Box.createHorizontalBox() self.jtextarea_resp = JTextArea() jsp = JScrollPane(self.jtextarea_resp) hbox_resp.add(self.jtextarea_resp) # 左垂直盒子:添加各种水平盒子 vBox_left.add(hbox_url) vBox_left.add(hbox_reqMeth) vBox_left.add(hbox_contentType) vBox_left.add(hbox_charset) vBox_left.add(hbox_headers) vBox_left.add(hbox_data) vBox_left.add(hbox_radiobtn) vBox_left.add(hbox_token) vBox_left.add(hbox_test) vBox_left.add(hbox_resp) # 左垂直盒子:垂直胶水填充 vGlue_test = Box.createGlue() vBox_left.add(vGlue_test) # 右垂直盒子内部:指定token在请求包中的位置 # token标志位置单选按钮 hbox_radiobtn_r = Box.createHorizontalBox() jlabel_tokenPosition_r = JLabel("Token Position: ") self.radioBtn01_r = JRadioButton("Header") self.radioBtn02_r = JRadioButton("Body") btnGroup_r = ButtonGroup() btnGroup_r.add(self.radioBtn01_r) btnGroup_r.add(self.radioBtn02_r) self.radioBtn01_r.setSelected(True) hbox_radiobtn_r.add(jlabel_tokenPosition_r) hbox_radiobtn_r.add(self.radioBtn01_r) hbox_radiobtn_r.add(self.radioBtn02_r) # token正则表达式 hbox_token_r = Box.createHorizontalBox() hbox_token_header_r = Box.createHorizontalBox() hbox_token_body_r = Box.createHorizontalBox() # token正则表达式:在header中 jlabel_tokenName_r = JLabel("tokenName: ") self.jtext_tokenName_r = JTextField(tokenWidth) self.jtext_tokenName_r.setMaximumSize( self.jtext_tokenName_r.getPreferredSize()) hbox_token_header_r.add(jlabel_tokenName_r) hbox_token_header_r.add(self.jtext_tokenName_r) hglue_token_header_r = Box.createHorizontalGlue() hbox_token_header_r.add(hglue_token_header_r) # token正则表达式:在Body中 jlabel_tokenRegex_r = JLabel("tokenRegex: ") self.jtext_tokenRegex_r = JTextField(tokenWidth) self.jtext_tokenRegex_r.setMaximumSize( self.jtext_tokenRegex_r.getPreferredSize()) hbox_token_body_r.add(jlabel_tokenRegex_r) hbox_token_body_r.add(self.jtext_tokenRegex_r) hglue_token_body_r = Box.createHorizontalGlue() hbox_token_body_r.add(hglue_token_body_r) # token正则表达式 hbox_token_r.add(hbox_token_header_r) hbox_token_r.add(hbox_token_body_r) # 测试按钮 hbox_test_r = Box.createHorizontalBox() jbtn_test_r = JButton("SET", actionPerformed=self.btnTest_r) self.jlabel_test_r = JLabel("Result: ") hbox_test_r.add(jbtn_test_r) hbox_test_r.add(self.jlabel_test_r) # 水平胶水填充 hGlue02 = Box.createHorizontalGlue() hbox_test_r.add(hGlue02) hbox_test_r.setBorder(BorderFactory.createLineBorder(Color.green, 2)) # 右垂直盒子:添加各种水平盒子 vBox_right.add(hbox_radiobtn_r) vBox_right.add(hbox_token_r) vBox_right.add(hbox_test_r) vGlue = Box.createVerticalGlue() vBox_right.add(vGlue) vBox_left.setBorder(BorderFactory.createLineBorder(Color.black, 3)) vBox_right.setBorder(BorderFactory.createLineBorder(Color.black, 3)) # 次外层水平盒子:添加左右两个垂直盒子 hBox_main.add(vBox_left) hBox_main.add(vBox_right) # 最外层垂直盒子:添加次外层水平盒子,垂直胶水 out_vBox_main.add(hBox_usage) out_vBox_main.add(hBox_main) self.mainPanel = out_vBox_main self._callbacks.customizeUiComponent(self.mainPanel) self._callbacks.addSuiteTab(self) def getTabCaption(self): return "JC-AntiToken" def getUiComponent(self): return self.mainPanel def testBtn_onClick(self, event): print("click button") def createMenuItems(self, invocation): menu = [] if invocation.getToolFlag() == IBurpExtenderCallbacks.TOOL_REPEATER: menu.append( JMenuItem("Test menu", None, actionPerformed=self.testmenu)) return menu def testmenu(self, event): print(event) print("JCTest test menu") def processHttpMessage(self, toolflag, messageIsRequest, messageInfo): service = messageInfo.getHttpService() if messageIsRequest: pass print("Host: " + str(service.getHost())) print("Port: " + str(service.getPort())) print("Protocol: " + str(service.getProtocol())) print("-----------------------------------") def getActionName(self): return "JC-AntiToken" def performAction(self, currentRequest, macroItems): # url url = self._helpers.analyzeRequest(currentRequest).getUrl() print(url) reqInfo = self._helpers.analyzeRequest(currentRequest) # request headers headers = reqInfo.getHeaders() print("ReqHeaders: " + headers) # get cookie from request header cookie = self.getCookieFromReq(headers) print(cookie) print(type(cookie)) # offset to req body reqBodyOffset = reqInfo.getBodyOffset() reqBody = str(bytearray(currentRequest.getRequest()[reqBodyOffset:])) print("ReqBody: " + reqBody) # modify Request Body newToken = self.getNewToken(cookie) if newToken != None: # tokenInReqHeader res = False if self.tokenInHeader_r: # pass # 普通header中 for header in headers: if ":" in header: if header.split(":")[0] == self.tokenName_r: headers = [ self.tokenName_r + ": " + newToken if i.split(":")[0] == self.tokenName_r else i for i in headers ] res = True break # cookie中 if not res and cookie != None and self.tokenName_r + "=" in cookie: # pass for i in range(len(headers)): if headers[i].startwith("Cookie:"): cookies2 = headers[i] cookies3 = cookies2.split(":")[1] if ";" not in cookies3: headers[ i] = "Cookie: " + self.tokenName_r + "=" + newToken res = True break else: cookies4 = cookies3.split(";") for cookie_idx in range(len(cookies4)): if self.tokenName_r + "+" in cookies4[ cookie_idx]: cookies4[ cookie_idx] = self.tokenName_r + "=" + newToken res = True break headers[i] = "Cookie: " + ";".join(cookies4) break # query string中 if not res: meth = headers[0].split(" ")[0] url = headers[0].split(" ")[1] ver = headers[0].split(" ")[2] if self.tokenName_r + "=" not in url: pass else: if "&" not in url: url = url.split("?")[ 0] + "?" + self.tokenName_r + "=" + newToken headers[0] = meth + " " + url + " " + ver else: params = url.split("?")[1].split("&") for i in range(len(params)): if self.tokenName_r + "=" in params[i]: params[ i] = self.tokenName_r + "=" + newToken break url = url.split("?")[0] + "?" + "&".join(params) headers[0] = meth + " " + url + " " + ver # tokenInReqBody else: if re.match(self.tokenRegex_r, reqBody): try: reqBody = re.sub(self.tokenRegex_r, r'\g<1>' + newToken + r'\g<3>', reqBody, 0, re.M | re.I) except Exception as e: print(e) # print(reqBody) # reqBody = re.sub(self.tokenRegex_r,r'\g<1>'+newToken+r'\g<3>',reqBody,0,re.M|re.I) # if re.match(r'(.*?"_tokenName":")([a-zA-Z0-9]{6,})(")',reqBody): # reqBody = re.sub(r'(.*?"_tokenName":")([a-zA-Z0-9]{6,})(")',r'\1'+newToken+r'\3',reqBody,0,re.M|re.I) # rebuild request reqMessage = self._helpers.buildHttpMessage(headers, bytes(reqBody)) # forward currentRequest.setRequest(reqMessage) print("++++++++++++++++++++++++") def getCookieFromReq(self, headers): for header in headers: if re.match(r'^Cookie:', header, re.I): return re.match(r'^Cookie: (.*)', header, re.I).group(1) # get new token def getNewToken(self, cookie): print(cookie) print("getNewToken") # url = "http://myip.ipip.net" headers_cookie = { 'Cookie': cookie, } if cookie != '': self.headers.update(**headers_cookie) if self.reqMeth == "GET": resp = self.sendGetHttp(self.url, self.headers, self.data, self.contentType) else: resp = self.sendPostHttp(self.url, self.headers, self.data, self.contentType) respBody = resp.read() respInfo = resp.info() if self.tokenInHeader: if respInfo.getheader(self.tokenName) != None: newToken = respInfo.getheader(self.tokenName) print(newToken) return newToken else: regexPattern = '.*' + self.tokenName + '=(.*?);' if respInfo.getheader("set-cookie") != None: cookies = respInfo.getheader("set-cookie") if re.match(regexPattern, cookies, re.M | re.I): newToken = re.match(regexPattern, cookies, re.M | re.I).group(1) print("newToken: ", newToken) return newToken else: return None else: return None else: regexPattern = self.tokenRegex if re.match(regexPattern, respBody, re.M | re.I): newToken = re.match(regexPattern, respBody, re.M | re.I).group(1) print("newToken: ", newToken) return newToken else: return None def sendGetHttp(self, url, headers, data, contentType): context = ssl._create_unverified_context() headers_contentType = {'Content-Type': contentType} if not headers.has_key("Content-Type"): headers.update(**headers_contentType) headers_userAgent = { 'User-Agent': 'Mozilla/6.0 (iPhone; CPU iPhone OS 8_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/8.0 Mobile/10A5376e Safari/8536.25' } if not headers.has_key("User-Agent"): headers.update(**headers_userAgent) try: if data != None: # if "urlencode" in contentType: data = urllib.urlencode(data) url = url + "?" + data req = urllib2.Request(url, headers=headers) else: req = urllib2.Request(url, headers=headers) resp = urllib2.urlopen(req, context=context) return resp except urllib2.HTTPError as error: print("ERROR: ", error) return None def sendPostHttp(self, url, headers, data, contentType): context = ssl._create_unverified_context() headers_contentType = {'Content-Type': contentType} if not headers.has_key("Content-Type"): headers.update(**headers_contentType) headers_userAgent = { 'User-Agent': 'Mozilla/6.0 (iPhone; CPU iPhone OS 8_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/8.0 Mobile/10A5376e Safari/8536.25' } if not headers.has_key("User-Agent"): headers.update(**headers_userAgent) print(headers) resp = "" print("data: ", data) if data != None: if "urlencode" in contentType: data = urllib.urlencode(data) req = urllib2.Request(url, headers=headers, data=data) else: data = json.dumps(data) req = urllib2.Request(url, headers=headers, data=data) else: if "urlencode" in contentType: req = urllib2.Request(url, headers=headers) else: data = json.dumps(data) req = urllib2.Request(url, headers=headers) try: resp = urllib2.urlopen(req, context=context) return resp except urllib2.HTTPError as error: print("ERROR: ", error) return None def btnTest(self, e): self.printcn("中文测试") self.url = self.jtext_url.getText() if self.url == "": self.jlabel_test.setText("please input url") return self.reqMeth = self.jcombobox_reqMeth.getSelectedItem() # 用户设置content-type self.contentType = self.jcombobox_contentType.getSelectedItem( ) + ";charset=" + self.jcombobox_charset.getSelectedItem() # 用户有没有自定义请求头 if self.jtext_headers.getText() != "": self.headers = json.loads(self.jtext_headers.getText()) else: self.headers = {} # 用户有没有自定义请求体 if self.jtext_data.getText() != "": self.data = json.loads(self.jtext_data.getText()) else: self.data = None self.tokenName = self.jtext_tokenName.getText() self.tokenRegex = self.jtext_tokenRegex.getText() resp = '' if self.reqMeth == "GET": resp = self.sendGetHttp(self.url, self.headers, self.data, self.contentType) else: resp = self.sendPostHttp(self.url, self.headers, self.data, self.contentType) if resp == None: self.jlabel_test.setText("error,detail in extender output") return respHeader = resp.info().headers print("resp-headers: ", respHeader) # print(resp.info().getheader("content-type")) self.printcn(resp.info().getheader("set-cookie")) # print(resp.info().getheader("xxx")) respBody = resp.read() print("respBody: ", respBody) self.jtextarea_resp.setText("".join(respHeader) + "\n" + "".join(respBody)) if (self.radioBtn01.isSelected()): self.tokenInHeader = True if self.tokenName == "": self.jlabel_test.setText("please input tokenName") return else: self.tokenInHeader = False if self.tokenRegex == "": self.jlabel_test.setText("please input tokenRegex") return print(self.reqMeth) newToken = self.getNewToken("") if newToken != None: self.jlabel_test.setText("Result: " + str(newToken)) self.jlabel_test.setBackground(Color.cyan) else: self.jlabel_test.setText("Result: None") def btnTest_r(self, e): self.tokenName_r = self.jtext_tokenName_r.getText() self.tokenRegex_r = self.jtext_tokenRegex_r.getText() if (self.radioBtn01_r.isSelected()): self.tokenInHeader_r = True if self.tokenName_r == "": self.jlabel_test_r.setText("please input tokenName") return else: self.tokenInHeader_r = False if self.tokenRegex_r == "": self.jlabel_test_r.setText("please input tokenRegex") return self.jlabel_test_r.setText("SUCCESS")
def __init__(self, app): from java.awt import Dialog from java.awt import CardLayout JDialog.__init__(self, app.preferencesFrame, app.strings.getString("Create_a_new_favourite_zone"), Dialog.ModalityType.DOCUMENT_MODAL) self.app = app border = BorderFactory.createEmptyBorder(5, 7, 7, 7) self.getContentPane().setBorder(border) self.setLayout(BoxLayout(self.getContentPane(), BoxLayout.Y_AXIS)) self.FAVAREALAYERNAME = "Favourite zone editing" info = JLabel(self.app.strings.getString("Create_a_new_favourite_zone")) info.setAlignmentX(Component.LEFT_ALIGNMENT) #Name nameLbl = JLabel(self.app.strings.getString("fav_zone_name")) self.nameTextField = JTextField(20) self.nameTextField.setMaximumSize(self.nameTextField.getPreferredSize()) self.nameTextField.setToolTipText(self.app.strings.getString("fav_zone_name_tooltip")) namePanel = JPanel() namePanel.setLayout(BoxLayout(namePanel, BoxLayout.X_AXIS)) namePanel.add(nameLbl) namePanel.add(Box.createHorizontalGlue()) namePanel.add(self.nameTextField) #Country countryLbl = JLabel(self.app.strings.getString("fav_zone_country")) self.countryTextField = JTextField(20) self.countryTextField.setMaximumSize(self.countryTextField.getPreferredSize()) self.countryTextField.setToolTipText(self.app.strings.getString("fav_zone_country_tooltip")) countryPanel = JPanel() countryPanel.setLayout(BoxLayout(countryPanel, BoxLayout.X_AXIS)) countryPanel.add(countryLbl) countryPanel.add(Box.createHorizontalGlue()) countryPanel.add(self.countryTextField) #Type modeLbl = JLabel(self.app.strings.getString("fav_zone_type")) RECTPANEL = "rectangle" POLYGONPANEL = "polygon" BOUNDARYPANEL = "boundary" self.modesStrings = [RECTPANEL, POLYGONPANEL, BOUNDARYPANEL] modesComboModel = DefaultComboBoxModel() for i in (self.app.strings.getString("rectangle"), self.app.strings.getString("delimited_by_a_closed_way"), self.app.strings.getString("delimited_by_an_administrative_boundary")): modesComboModel.addElement(i) self.modesComboBox = JComboBox(modesComboModel, actionListener=self, editable=False) #- Rectangle self.rectPanel = JPanel() self.rectPanel.setLayout(BoxLayout(self.rectPanel, BoxLayout.Y_AXIS)) capturePane = JPanel() capturePane.setLayout(BoxLayout(capturePane, BoxLayout.X_AXIS)) capturePane.setAlignmentX(Component.LEFT_ALIGNMENT) josmP = JPanel() self.captureRBtn = JRadioButton(self.app.strings.getString("capture_area")) self.captureRBtn.addActionListener(self) self.captureRBtn.setSelected(True) self.bboxFromJosmBtn = JButton(self.app.strings.getString("get_current_area"), actionPerformed=self.on_bboxFromJosmBtn_clicked) self.bboxFromJosmBtn.setToolTipText(self.app.strings.getString("get_capture_area_tooltip")) josmP.add(self.bboxFromJosmBtn) capturePane.add(self.captureRBtn) capturePane.add(Box.createHorizontalGlue()) capturePane.add(self.bboxFromJosmBtn) manualPane = JPanel() manualPane.setLayout(BoxLayout(manualPane, BoxLayout.X_AXIS)) manualPane.setAlignmentX(Component.LEFT_ALIGNMENT) self.manualRBtn = JRadioButton(self.app.strings.getString("use_this_bbox")) self.manualRBtn.addActionListener(self) self.bboxTextField = JTextField(20) self.bboxTextField.setMaximumSize(self.bboxTextField.getPreferredSize()) self.bboxTextField.setToolTipText(self.app.strings.getString("fav_bbox_tooltip")) self.bboxTextFieldDefaultBorder = self.bboxTextField.getBorder() self.bboxTextField.getDocument().addDocumentListener(TextListener(self)) manualPane.add(self.manualRBtn) manualPane.add(Box.createHorizontalGlue()) manualPane.add(self.bboxTextField) group = ButtonGroup() group.add(self.captureRBtn) group.add(self.manualRBtn) previewPane = JPanel() previewPane.setLayout(BoxLayout(previewPane, BoxLayout.X_AXIS)) previewPane.setAlignmentX(Component.LEFT_ALIGNMENT) bboxPreviewInfo = JTextField(self.app.strings.getString("coordinates"), editable=0, border=None) bboxPreviewInfo.setMaximumSize(bboxPreviewInfo.getPreferredSize()) self.bboxPreviewTextField = JTextField(20, editable=0, border=None) self.bboxPreviewTextField.setMaximumSize(self.bboxPreviewTextField.getPreferredSize()) previewPane.add(bboxPreviewInfo) previewPane.add(Box.createHorizontalGlue()) previewPane.add(self.bboxPreviewTextField) self.rectPanel.add(capturePane) self.rectPanel.add(Box.createRigidArea(Dimension(0, 10))) self.rectPanel.add(manualPane) self.rectPanel.add(Box.createRigidArea(Dimension(0, 20))) self.rectPanel.add(previewPane) #- Polygon (closed way) drawn by hand self.polygonPanel = JPanel(BorderLayout()) self.polygonPanel.setLayout(BoxLayout(self.polygonPanel, BoxLayout.Y_AXIS)) polyInfo = JLabel("<html>%s</html>" % self.app.strings.getString("polygon_info")) polyInfo.setFont(polyInfo.getFont().deriveFont(Font.ITALIC)) polyInfo.setAlignmentX(Component.LEFT_ALIGNMENT) editPolyPane = JPanel() editPolyPane.setAlignmentX(Component.LEFT_ALIGNMENT) editPolyBtn = JButton(self.app.strings.getString("create_fav_layer"), actionPerformed=self.create_new_zone_editing_layer) editPolyBtn.setToolTipText(self.app.strings.getString("create_fav_layer_tooltip")) editPolyPane.add(editPolyBtn) self.polygonPanel.add(polyInfo) self.polygonPanel.add(Box.createRigidArea(Dimension(0, 15))) self.polygonPanel.add(editPolyPane) self.polygonPanel.add(Box.createRigidArea(Dimension(0, 15))) #- Administrative Boundary self.boundaryPanel = JPanel() self.boundaryPanel.setLayout(BoxLayout(self.boundaryPanel, BoxLayout.Y_AXIS)) boundaryInfo = JLabel("<html>%s</html>" % app.strings.getString("boundary_info")) boundaryInfo.setFont(boundaryInfo.getFont().deriveFont(Font.ITALIC)) boundaryInfo.setAlignmentX(Component.LEFT_ALIGNMENT) boundaryTagsPanel = JPanel(GridLayout(3, 3, 5, 5)) boundaryTagsPanel.setAlignmentX(Component.LEFT_ALIGNMENT) boundaryTagsPanel.add(JLabel("name =")) self.nameTagTextField = JTextField(20) boundaryTagsPanel.add(self.nameTagTextField) boundaryTagsPanel.add(UrlLabel("http://wiki.openstreetmap.org/wiki/Key:admin_level#admin_level", "admin_level =")) self.adminLevelTagTextField = JTextField(20) self.adminLevelTagTextField.setToolTipText(self.app.strings.getString("adminLevel_tooltip")) boundaryTagsPanel.add(self.adminLevelTagTextField) boundaryTagsPanel.add(JLabel(self.app.strings.getString("other_tag"))) self.optionalTagTextField = JTextField(20) self.optionalTagTextField.setToolTipText("key=value") boundaryTagsPanel.add(self.optionalTagTextField) downloadBoundariesPane = JPanel() downloadBoundariesPane.setAlignmentX(Component.LEFT_ALIGNMENT) downloadBoundariesBtn = JButton(self.app.strings.getString("download_boundary"), actionPerformed=self.on_downloadBoundariesBtn_clicked) downloadBoundariesBtn.setToolTipText(self.app.strings.getString("download_boundary_tooltip")) downloadBoundariesPane.add(downloadBoundariesBtn) self.boundaryPanel.add(boundaryInfo) self.boundaryPanel.add(Box.createRigidArea(Dimension(0, 15))) self.boundaryPanel.add(boundaryTagsPanel) self.boundaryPanel.add(Box.createRigidArea(Dimension(0, 10))) self.boundaryPanel.add(downloadBoundariesPane) self.editingPanels = {"rectangle": self.rectPanel, "polygon": self.polygonPanel, "boundary": self.boundaryPanel} #Main buttons self.okBtn = JButton(self.app.strings.getString("OK"), ImageProvider.get("ok"), actionPerformed=self.on_okBtn_clicked) self.cancelBtn = JButton(self.app.strings.getString("cancel"), ImageProvider.get("cancel"), actionPerformed=self.close_dialog) self.previewBtn = JButton(self.app.strings.getString("Preview_zone"), actionPerformed=self.on_previewBtn_clicked) self.previewBtn.setToolTipText(self.app.strings.getString("preview_zone_tooltip")) okBtnSize = self.okBtn.getPreferredSize() viewBtnSize = self.previewBtn.getPreferredSize() viewBtnSize.height = okBtnSize.height self.previewBtn.setPreferredSize(viewBtnSize) #layout self.add(info) self.add(Box.createRigidArea(Dimension(0, 15))) namePanel.setAlignmentX(Component.LEFT_ALIGNMENT) self.add(namePanel) self.add(Box.createRigidArea(Dimension(0, 15))) countryPanel.setAlignmentX(Component.LEFT_ALIGNMENT) self.add(countryPanel) self.add(Box.createRigidArea(Dimension(0, 15))) modeLbl.setAlignmentX(Component.LEFT_ALIGNMENT) self.add(modeLbl) self.add(Box.createRigidArea(Dimension(0, 5))) self.add(self.modesComboBox) self.modesComboBox.setAlignmentX(Component.LEFT_ALIGNMENT) self.add(Box.createRigidArea(Dimension(0, 15))) self.configPanel = JPanel(CardLayout()) self.configPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)) self.configPanel.add(self.rectPanel, RECTPANEL) self.configPanel.add(self.polygonPanel, POLYGONPANEL) self.configPanel.add(self.boundaryPanel, BOUNDARYPANEL) self.configPanel.setAlignmentX(Component.LEFT_ALIGNMENT) self.add(self.configPanel) buttonsPanel = JPanel() buttonsPanel.add(self.okBtn) buttonsPanel.add(self.cancelBtn) buttonsPanel.add(self.previewBtn) buttonsPanel.setAlignmentX(Component.LEFT_ALIGNMENT) self.add(buttonsPanel) self.addWindowListener(self) self.pack()
class ConfigurationPanel(JPanel, PropertyChangeListener): def __init__(self): ''' Configuration Panel ''' # pconfig = JPanel(GridBagLayout()) # pconfig.setSize(Dimension(500,300)) self.setLayout(GridBagLayout()) # super(self,GridBagLayout()) self.setSize(Dimension(500,300)) ''' fila 1 ''' label = JLabel('Configuration panel') c1 = GridBagConstraints() c1.fill = GridBagConstraints.HORIZONTAL c1.weightx = 0.5 c1.gridwidth = 4 c1.gridx = 0 c1.gridy = 0 self.add(label, c1) ''' fila 2 ''' self.radioBtnOMC = JRadioButton('OpenModelica') c2 = GridBagConstraints() c2.fill = GridBagConstraints.HORIZONTAL c2.weightx = 0.5 c2.gridx = 0 c2.gridy = 1 self.add(self.radioBtnOMC, c2) self.radioBtnJM = JRadioButton('JModelica') c3 = GridBagConstraints() c3.fill = GridBagConstraints.HORIZONTAL c3.weightx = 0.5 c3.gridx = 1 c3.gridy = 1 self.add(self.radioBtnJM, c3) self.radioBtnDY = JRadioButton('Dymola') c4 = GridBagConstraints() c4.fill = GridBagConstraints.HORIZONTAL c4.weightx = 0.5 c4.gridx = 2 c4.gridy = 1 self.add(self.radioBtnDY, c4) rbBtnGroup = ButtonGroup() rbBtnGroup.add(self.radioBtnOMC) rbBtnGroup.add(self.radioBtnJM) rbBtnGroup.add(self.radioBtnDY) ''' fila 2 ''' label = JLabel('Start time') c = GridBagConstraints() c.fill = GridBagConstraints.HORIZONTAL c.weightx = 0.5 c.gridx = 0 c.gridy = 2 self.add(label, c) self.txtstart= JTextField('0') c = GridBagConstraints() c.fill = GridBagConstraints.HORIZONTAL c.weightx = 0.5 c.gridx = 1 c.gridy = 2 self.add(self.txtstart, c) label = JLabel('Stop time') c = GridBagConstraints() c.fill = GridBagConstraints.HORIZONTAL c.weightx = 0.5 c.gridx = 2 c.gridy = 2 self.add(label, c) self.txtstop= JTextField('0') c = GridBagConstraints() c.fill = GridBagConstraints.HORIZONTAL c.weightx = 0.5 c.gridx = 3 c.gridy = 2 self.add(self.txtstop, c) ''' fila 3 ''' label = JLabel('Solver') c = GridBagConstraints() c.fill = GridBagConstraints.HORIZONTAL c.weightx = 0.5 c.gridx = 0 c.gridy = 3 self.add(label, c) self.cbsolver= JComboBox(['dassl','rkfix2']) c = GridBagConstraints() c.fill = GridBagConstraints.HORIZONTAL c.weightx = 0.5 c.gridx = 1 c.gridy = 3 self.add(self.cbsolver, c) label = JLabel('Algorithm (JM)') c = GridBagConstraints() c.fill = GridBagConstraints.HORIZONTAL c.weightx = 0.5 c.gridx = 2 c.gridy = 3 self.add(label, c) self.cbalgorithm= JComboBox(['AssimuloAlg']) c = GridBagConstraints() c.fill = GridBagConstraints.HORIZONTAL c.weightx = 0.5 c.gridx = 3 c.gridy = 3 self.add(self.cbalgorithm, c) ''' fila 4 ''' label = JLabel('Interval') c = GridBagConstraints() c.fill = GridBagConstraints.HORIZONTAL c.weightx = 0.5 c.gridx = 0 c.gridy = 4 self.add(label, c) self.txtinterval= JTextField('0') c = GridBagConstraints() c.fill = GridBagConstraints.HORIZONTAL c.weightx = 0.5 c.gridx = 1 c.gridy = 4 self.add(self.txtinterval, c) ''' fila 5 ''' label = JLabel('Tolerance') c = GridBagConstraints() c.fill = GridBagConstraints.HORIZONTAL c.weightx = 0.5 c.gridx = 0 c.gridy = 5 self.add(label, c) self.txttolerance= JTextField('0') c = GridBagConstraints() c.fill = GridBagConstraints.HORIZONTAL c.weightx = 0.5 c.gridx = 1 c.gridy = 5 self.add(self.txttolerance, c) ''' fila 6 ''' label = JLabel('Output format') c = GridBagConstraints() c.fill = GridBagConstraints.HORIZONTAL c.weightx = 0.5 c.gridx = 0 c.gridy = 6 self.add(label, c) self.cboutformat= JComboBox(['.mat','.h5','.csv']) c = GridBagConstraints() c.fill = GridBagConstraints.HORIZONTAL c.weightx = 0.5 c.gridx = 1 c.gridy = 6 self.add(self.cboutformat, c) label = JLabel('Initialize (JM)') c = GridBagConstraints() c.fill = GridBagConstraints.HORIZONTAL c.weightx = 0.5 c.gridx = 2 c.gridy = 6 self.add(label, c) self.cbinitialize= JComboBox(['True','False']) c = GridBagConstraints() c.fill = GridBagConstraints.HORIZONTAL c.weightx = 0.5 c.gridx = 3 c.gridy = 6 self.add(self.cbinitialize, c) ''' fila 7 ''' bSaveCfg= JButton('Save Configuration', actionPerformed= self.saveConfiguration) c = GridBagConstraints() c.fill = GridBagConstraints.HORIZONTAL c.weightx = 0.5 c.gridwidth = 2 c.gridx = 0 c.gridy = 7 self.add(bSaveCfg, c) self.bSimulation= JButton('Load Configuration', actionPerformed= self.loadConfiguration) c = GridBagConstraints() c.fill = GridBagConstraints.HORIZONTAL c.weightx = 0.5 c.gridwidth = 2 c.gridx = 2 c.gridy = 7 self.add(self.bSimulation, c) ''' fila 8 ''' self.bSimulation= JButton('Simulate', actionPerformed= self.startSimlation) self.bSimulation.enabled= 0 c = GridBagConstraints() c.fill = GridBagConstraints.HORIZONTAL c.weightx = 1 c.gridwidth = 4 c.gridx = 0 c.gridy = 8 self.add(self.bSimulation, c) ''' file 9 ''' simProgress= JProgressBar(0, self.getWidth(), value=0, stringPainted=True) c = GridBagConstraints() c.fill = GridBagConstraints.HORIZONTAL c.weightx = 1 c.gridwidth = 4 c.gridx = 0 c.gridy = 9 self.add(simProgress, c) ''' fila 10 ''' self.lblResult= JLabel('Simulation information') c = GridBagConstraints() c.fill = GridBagConstraints.HORIZONTAL c.weightx = 1 c.gridwidth = 4 c.gridx = 0 c.gridy = 10 self.add(self.lblResult, c) def startSimlation(self, event): "Invoked when the user presses the start button" self.bSimulation.enabled = False #Instances of javax.swing.SwingWorker are not reusable, so #we create new instances as needed. self.simtask = SimulationTask(self) # self.simtask.addPropertyChangeListener(self) self.simtask.execute() def saveConfiguration(self,event): if self.radioBtnOMC.isSelected() or self.radioBtnDY.isSelected(): self.config= SimulationConfigOMCDY() self.config.set_starttime(self.txtstart.getText()) self.config.set_stoptime(self.txtstop.getText()) self.config.set_tolerance(self.txttolerance.getText()) self.config.set_intervals(self.txtinterval.getText()) self.config.set_method(self.cbsolver.selectedItem) self.config.set_outputformat(self.cboutformat.selectedItem) if self.radioBtnOMC.isSelected(): nomfile= './config/simConfigurationOMC.properties' if self.radioBtnDY.isSelected(): nomfile= './config/simConfigurationDY.properties' self.config.save_Properties(nomfile, 'Simulation Configuration') if self.radioBtnJM.isSelected(): self.config= SimulationConfigJM() self.config.set_starttime(self.txtstart.getText()) self.config.set_stoptime(self.txtstop.getText()) self.config.set_intervals(self.txtinterval.text) self.config.set_method(self.cbsolver.selectedItem) self.config.set_algorithm(self.cbalgorithm.selectedItem) self.config.set_initialization(self.cbinitialize.selectedItem) self.config.set_outputformat(self.cboutformat.selectedItem) nomfile= './config/simConfigurationJM.properties' self.config.save_Properties(nomfile, 'Simulation Configuration') self.bSimulation.enabled= 1 def loadConfiguration(self, event): if self.radioBtnOMC.isSelected() or self.radioBtnDY.isSelected(): self.config= SimulationConfigOMCDY() self.config.load_Properties('./config/simConfigurationOMC.properties') self.txtstart.setText(self.config.get_starttime()) self.txtstop.setText(self.config.get_stoptime()) self.txttolerance.setText(self.config.get_tolerance()) self.txtinterval.setText(self.config.get_intervals()) self.cbsolver.selectedItem= self.config.get_method() self.cboutformat.selectedItem= self.config.get_outputformat() if self.radioBtnJM.isSelected(): self.config= SimulationConfigJM() self.config.load_Properties('./config/simConfigurationJM.properties') self.txtstart.setText(self.config.get_starttime()) self.txtstop.setText(self.config.get_stoptime()) self.txtinterval.setText(self.config.get_intervals()) self.cbsolver.selectedItem= self.config.get_method() self.cbalgorithm.selectedItem= self.config.get_algorithm() self.cbinitialize.selectedItem= self.config.get_initialization() # self.cboutformat.selectedItem= self.config.get_outputformat() self.bSimulation.enabled= 1
class BurpExtender(IBurpExtender, IHttpListener, IMessageEditorTabFactory, ITab): # # implement IBurpExtender # def registerExtenderCallbacks(self, callbacks): global EXTENSION_NAME 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 our extension name callbacks.setExtensionName(EXTENSION_NAME) # register ourselves as a Http Listener callbacks.registerHttpListener(self) # register ourselves as a message editor tab factory callbacks.registerMessageEditorTabFactory(self) # setup the UI self.initGui() # add the custom tab to Burp's UI self._callbacks.addSuiteTab(self) return # # create the Gui # 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 def reloadConf(self, event): #~ if DEBUG: #~ import pdb; pdb.set_trace() source = event.getSource() print 'APPLY button clicked. New configuration loaded.' global MAGIC_PARAMETER global PARAMETERISPOST global PARAMETERISGET global PARAMETERISCOOKIE global BASE64ENCODINGENABLED global ASCII2HEXENCODINGENABLED global URLENCODINGENABLED global INTRUDERENABLED global SCANNERENABLED MAGIC_PARAMETER = self.parameterName.getText() print 'Base64 checkbox is: ' + str(self.base64Enabled.isSelected()) if self.base64Enabled.isSelected(): BASE64ENCODINGENABLED = True else: BASE64ENCODINGENABLED = False print 'ASCII2Hex checkbox is: ' + str( self.ASCII2HexEnabled.isSelected()) if self.ASCII2HexEnabled.isSelected(): ASCII2HEXENCODINGENABLED = True else: ASCII2HEXENCODINGENABLED = False print 'URL checkbox is: ' + str(self.URLEnabled.isSelected()) if self.URLEnabled.isSelected(): URLENCODINGENABLED = True else: URLENCODINGENABLED = False print 'New Magic parameter is: ' + str(MAGIC_PARAMETER) if self.POSTparameterTypeRadioButton.isSelected(): #BODYPARAM PARAMETERISPOST = True print "parameterispost has been set to: " + str(PARAMETERISPOST) else: PARAMETERISPOST = False print "parameterispost has been set to: " + str(PARAMETERISPOST) if self.GETparameterTypeRadioButton.isSelected(): #GETPARAM PARAMETERISGET = True print "parameterisget has been set to: " + str(PARAMETERISGET) else: PARAMETERISGET = False print "parameterisget has been set to: " + str(PARAMETERISGET) if self.COOKIEparameterTypeRadioButton.isSelected(): #COOKIEPARAM PARAMETERISCOOKIE = True print "parameteriscookie has been set to: " + str( PARAMETERISCOOKIE) else: PARAMETERISCOOKIE = False print "parameteriscookie has been set to: " + str( PARAMETERISCOOKIE) if self.ScannerEnabled.isSelected(): SCANNERENABLED = True print "Scanner Enabled" else: SCANNERENABLED = False if self.IntruderEnabled.isSelected(): INTRUDERENABLED = True print "Intruder Enabled" else: INTRUDERENABLED = False # # implement IHTTPListener # def processHttpMessage(self, toolFlag, messageIsRequest, currentRequest): global PARAMETERISPOST global PARAMETERISGET global PARAMETERISCOOKIE global URLENCODINGENABLED global BASE64ENCODINGENABLED global ASCII2HEXENCODINGENABLED global INTRUDERENABLED global SCANNERENABLED #only process requests if not messageIsRequest: return #only process messages from Intruder and Scanner, otherwise exit #if (not self._callbacks.TOOL_INTRUDER == toolFlag): if ((not ( (self._callbacks.TOOL_INTRUDER == toolFlag) and INTRUDERENABLED)) and (not ((self._callbacks.TOOL_SCANNER == toolFlag) and SCANNERENABLED))): #print "exiting- toolflag:"+str(toolFlag)+' INTRUDERENABLED='+str(INTRUDERENABLED)+' SCANNERENABLED='+str(SCANNERENABLED) return #if ((not self._callbacks.TOOL_INTRUDER == toolFlag)) and ((not self._callbacks.TOOL_SCANNER == toolFlag)):#remove the comment to always enable if DEBUG: print "IHTTPListener Enabled in: " + str(toolFlag) requestInfo = self._helpers.analyzeRequest(currentRequest) timestamp = datetime.now() if DEBUG: print "Intercepting message at: ", timestamp.isoformat() #parameters = requestInfo.getParameters() dataParameter = self._helpers.getRequestParameter( currentRequest.getRequest(), MAGIC_PARAMETER) #FIXME: add exception handling for multiple parameters with the same name and/or in a different position!!! if DEBUG: print 'dataparameter:' + str(dataParameter) if (dataParameter == None): if DEBUG: print 'Parameter does not exist' return serializedValue = dataParameter.getValue() #FIXME: substitute '[AND]' placeholder with '&' charachter - we should do something more elegant here :/ serializedValue = re.sub(r'\[AND\]', '&', serializedValue) print "unserialized parameter value: ", str(serializedValue) if BASE64ENCODINGENABLED: #if base64Encode is selected serializedValue = self._helpers.base64Encode(serializedValue) if DEBUG: print "base64 encoded parameter value: ", str(serializedValue) if URLENCODINGENABLED: #if URLEncode is selected serializedValue = self._helpers.urlEncode(serializedValue) if DEBUG: print "URL ecoded parameter value: ", str(serializedValue) if ASCII2HEXENCODINGENABLED: #if ASCII2HexEncode is selected serializedValue = convert_ascii2hex(serializedValue) if DEBUG: print "ASCII2Hex ecoded parameter value: ", str( serializedValue) print "serialized parameter value: ", serializedValue if PARAMETERISPOST: if DEBUG: print "parameter is BODY" currentRequest.setRequest( self._helpers.updateParameter( currentRequest.getRequest(), self._helpers.buildParameter(MAGIC_PARAMETER, serializedValue, IParameter.PARAM_BODY))) elif PARAMETERISGET: if DEBUG: print "parameter is in URL" currentRequest.setRequest( self._helpers.updateParameter( currentRequest.getRequest(), self._helpers.buildParameter(MAGIC_PARAMETER, serializedValue, IParameter.PARAM_URL))) elif PARAMETERISCOOKIE: if DEBUG: print "parameter is a COOKIE" currentRequest.setRequest( self._helpers.updateParameter( currentRequest.getRequest(), self._helpers.buildParameter(MAGIC_PARAMETER, serializedValue, IParameter.PARAM_COOKIE))) return # # implement ITab # def getTabCaption(self): global EXTENSION_TABCAPTION return (EXTENSION_TABCAPTION) def getUiComponent(self): #~ return self._splitpane return self.tab # # implement IMessageEditorTabFactory # def createNewInstance(self, controller, editable): # create a new instance of our custom editor tab return CustomInputTab(self, controller, editable)
def getUiComponent(self): self.panel = JPanel() self.main = JPanel() self.main.setLayout(BoxLayout(self.main, BoxLayout.Y_AXIS)) self.access_key_panel = JPanel() self.main.add(self.access_key_panel) self.access_key_panel.setLayout( BoxLayout(self.access_key_panel, BoxLayout.X_AXIS)) self.access_key_panel.add(JLabel('Access Key: ')) self.access_key = JTextField('', 25) self.access_key_panel.add(self.access_key) self.secret_key_panel = JPanel() self.main.add(self.secret_key_panel) self.secret_key_panel.setLayout( BoxLayout(self.secret_key_panel, BoxLayout.X_AXIS)) self.secret_key_panel.add(JLabel('Secret Key: ')) self.secret_key = JPasswordField('', 25) self.secret_key_panel.add(self.secret_key) self.target_host_panel = JPanel() self.main.add(self.target_host_panel) self.target_host_panel.setLayout( BoxLayout(self.target_host_panel, BoxLayout.X_AXIS)) self.target_host_panel.add(JLabel('Target host: ')) self.target_host = JTextField('example.com', 25) self.target_host_panel.add(self.target_host) self.buttons_panel = JPanel() self.main.add(self.buttons_panel) self.buttons_panel.setLayout( BoxLayout(self.buttons_panel, BoxLayout.X_AXIS)) #self.save_button = JButton('Save', actionPerformed = self.saveKeys) #not implemented yet #self.buttons_panel.add(self.save_button) self.enable_button = JButton('Enable', actionPerformed=self.enableGateway) self.buttons_panel.add(self.enable_button) self.disable_button = JButton('Disable', actionPerformed=self.disableGateway) self.buttons_panel.add(self.disable_button) self.disable_button.setEnabled(False) self.protocol_panel = JPanel() self.main.add(self.protocol_panel) self.protocol_panel.setLayout( BoxLayout(self.protocol_panel, BoxLayout.Y_AXIS)) self.protocol_panel.add(JLabel("Target Protocol:")) self.https_button = JRadioButton("HTTPS", True) self.http_button = JRadioButton("HTTP", False) self.protocol_panel.add(self.http_button) self.protocol_panel.add(self.https_button) buttongroup = ButtonGroup() buttongroup.add(self.https_button) buttongroup.add(self.http_button) self.regions_title = JPanel() self.main.add(self.regions_title) self.regions_title.add(JLabel("Regions to launch API Gateways in:")) self.regions_panel = JPanel() self.main.add(self.regions_panel) glayout = GridLayout(4, 3) self.regions_panel.setLayout(glayout) for region in AVAIL_REGIONS: cur_region = region.replace('-', '_') cur_region = cur_region + '_status' setattr(self, cur_region, JCheckBox(region, True)) attr = getattr(self, cur_region) self.regions_panel.add(attr) self.status = JPanel() self.main.add(self.status) self.status.setLayout(BoxLayout(self.status, BoxLayout.X_AXIS)) self.status_indicator = JLabel(DISABLED, JLabel.CENTER) self.status.add(self.status_indicator) self.panel.add(self.main) return self.panel
class BurpExtender(IBurpExtender, ITab, IHttpListener, IMessageEditorController, AbstractTableModel, IContextMenuFactory, IExtensionStateListener): # # implement IBurpExtender # 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("Burp Scope Monitor Experimental") self.GLOBAL_HANDLER_ANALYZED = False self.GLOBAL_HANDLER = False self.STATUS = False self.AUTOSAVE_REQUESTS = 10 self.AUTOSAVE_TIMEOUT = 600 # 10 minutes should be fine self.CONFIG_INSCOPE = True self.BAD_EXTENSIONS_DEFAULT = [ '.gif', '.png', '.js', '.woff', '.woff2', '.jpeg', '.jpg', '.css', '.ico', '.m3u8', '.ts', '.svg' ] self.BAD_MIMES_DEFAULT = [ 'gif', 'script', 'jpeg', 'jpg', 'png', 'video', 'mp2t' ] self.BAD_EXTENSIONS = self.BAD_EXTENSIONS_DEFAULT self.BAD_MIMES = self.BAD_MIMES_DEFAULT # create the log and a lock on which to synchronize when adding log entries self._currentlyDisplayedItem = None self.SELECTED_MODEL_ROW = 0 self.SELECTED_VIEW_ROW = 0 self._log = ArrayList() self._fullLog = ArrayList() self._lock = Lock() self._lockFile = Lock() # main split pane self._parentPane = JTabbedPane() self._splitpane = JSplitPane(JSplitPane.VERTICAL_SPLIT) ##### config pane self._config = JTabbedPane() config = JPanel() iexport = JPanel() #config.setLayout(BorderLayout()) config.setLayout(None) iexport.setLayout(None) # config radio button X_BASE = 40 Y_OFFSET = 5 Y_OPTION = 200 Y_OPTION_SPACING = 20 Y_CHECKMARK_SPACING = 20 self.showAllButton = JRadioButton(SHOW_ALL_BUTTON_LABEL, True) self.showNewButton = JRadioButton(SHOW_NEW_BUTTON_LABEL, False) self.showTestedButton = JRadioButton(SHOW_TEST_BUTTON_LABEL, False) self.showAllButton.setBounds(40, 60 + Y_OFFSET, 400, 30) self.showNewButton.setBounds(40, 80 + Y_OFFSET, 400, 30) self.showTestedButton.setBounds(40, 100 + Y_OFFSET, 400, 30) #self.showNewButton = JRadioButton(SHOW_NEW_BUTTON_LABEL, False) #self.showTestedButton = JRadioButton(SHOW_TEST_BUTTON_LABEL, False) self.showAllButton.addActionListener(self.handleRadioConfig) self.showNewButton.addActionListener(self.handleRadioConfig) self.showTestedButton.addActionListener(self.handleRadioConfig) self.clearButton = JButton("Clear") self.clearButton.addActionListener(self.handleClearButton) self.clearButton.setBounds(40, 20, 100, 30) self.startButton = JButton(MONITOR_ON_LABEL) self.startButton.addActionListener(self.handleStartButton) self.startButton.setBounds(150, 20, 200, 30) self.badExtensionsLabel = JLabel("Ignore extensions:") self.badExtensionsLabel.setBounds(X_BASE, 150, 200, 30) self.badExtensionsText = JTextArea("") self.loadBadExtensions() self.badExtensionsText.setBounds(X_BASE, 175, 310, 30) self.badExtensionsButton = JButton("Save") self.badExtensionsButton.addActionListener( self.handleBadExtensionsButton) self.badExtensionsButton.setBounds(355, 175, 70, 30) self.badExtensionsDefaultButton = JButton("Load Defaults") self.badExtensionsDefaultButton.addActionListener( self.handleBadExtensionsDefaultButton) self.badExtensionsDefaultButton.setBounds(430, 175, 120, 30) self.badMimesLabel = JLabel("Ignore mime types:") self.badMimesLabel.setBounds(X_BASE, 220, 200, 30) self.badMimesText = JTextArea("") self.loadBadMimes() self.badMimesText.setBounds(X_BASE, 245, 310, 30) self.badMimesButton = JButton("Save") self.badMimesButton.addActionListener(self.handleBadMimesButton) self.badMimesButton.setBounds(355, 245, 70, 30) self.badMimesDefaultButton = JButton("Load Defaults") self.badMimesDefaultButton.addActionListener( self.handleBadMimesDefaultButton) self.badMimesDefaultButton.setBounds(430, 245, 120, 30) self.otherLabel = JLabel("Other:") self.otherLabel.setBounds(40, 300, 120, 30) self.otherLabel2 = JLabel("Other:") self.otherLabel2.setBounds(X_BASE, Y_OPTION, 120, 30) self.autoSaveOption = JCheckBox("Auto save periodically") self.autoSaveOption.setSelected(True) self.autoSaveOption.addActionListener(self.handleAutoSaveOption) self.autoSaveOption.setBounds(X_BASE, Y_OPTION + Y_CHECKMARK_SPACING, 420, 30) self.repeaterOptionButton = JCheckBox( "Repeater request automatically marks as analyzed") self.repeaterOptionButton.setSelected(True) self.repeaterOptionButton.addActionListener( self.handleRepeaterOptionButton) self.repeaterOptionButton.setBounds(50, 330, 420, 30) self.scopeOptionButton = JCheckBox("Follow Burp Target In Scope rules") self.scopeOptionButton.setSelected(True) self.scopeOptionButton.addActionListener(self.handleScopeOptionButton) self.scopeOptionButton.setBounds(50, 350, 420, 30) self.startOptionButton = JCheckBox("Autostart Scope Monitor") self.startOptionButton.setSelected(True) self.startOptionButton.addActionListener(self.handleStartOption) self.startOptionButton.setBounds(50, 350 + Y_OPTION_SPACING, 420, 30) self.markTestedRequestsProxy = JCheckBox( "Color request in Proxy tab if analyzed") self.markTestedRequestsProxy.setSelected(True) self.markTestedRequestsProxy.addActionListener( self.handleTestedRequestsProxy) self.markTestedRequestsProxy.setBounds(50, 350 + Y_OPTION_SPACING * 2, 420, 30) self.markNotTestedRequestsProxy = JCheckBox( "Color request in Proxy tab if NOT analyzed") self.markNotTestedRequestsProxy.setSelected(True) self.markNotTestedRequestsProxy.addActionListener( self.handleNotTestedRequestsProxy) self.markNotTestedRequestsProxy.setBounds(50, 350 + Y_OPTION_SPACING * 3, 420, 30) self.saveButton = JButton("Save now") self.saveButton.addActionListener(self.handleSaveButton) self.saveButton.setBounds(X_BASE + 320, 95, 90, 30) self.loadButton = JButton("Load now") self.loadButton.addActionListener(self.handleLoadButton) self.loadButton.setBounds(X_BASE + 420, 95, 90, 30) self.selectPath = JButton("Select path") self.selectPath.addActionListener(self.selectExportFile) self.selectPath.setBounds(X_BASE + 530, 60, 120, 30) self.selectPathText = JTextArea("") self.selectPathText.setBounds(X_BASE, 60, 510, 30) self.selectPathLabel = JLabel("State file:") self.selectPathLabel.setBounds(X_BASE, 30, 200, 30) bGroup = ButtonGroup() bGroup.add(self.showAllButton) bGroup.add(self.showNewButton) bGroup.add(self.showTestedButton) config.add(self.clearButton) config.add(self.startButton) config.add(self.startOptionButton) config.add(self.showAllButton) config.add(self.showNewButton) config.add(self.showTestedButton) config.add(self.badExtensionsButton) config.add(self.badExtensionsText) config.add(self.badExtensionsLabel) config.add(self.badMimesButton) config.add(self.badMimesText) config.add(self.badMimesLabel) config.add(self.badExtensionsDefaultButton) config.add(self.badMimesDefaultButton) config.add(self.otherLabel) config.add(self.repeaterOptionButton) config.add(self.scopeOptionButton) config.add(self.markTestedRequestsProxy) config.add(self.markNotTestedRequestsProxy) iexport.add(self.saveButton) iexport.add(self.loadButton) iexport.add(self.selectPath) iexport.add(self.selectPathText) iexport.add(self.selectPathLabel) iexport.add(self.otherLabel2) iexport.add(self.autoSaveOption) self._config.addTab("General", config) self._config.addTab("Import/Export", iexport) ##### end config pane self._parentPane.addTab("Monitor", self._splitpane) self._parentPane.addTab("Config", self._config) # table of log entries self.logTable = Table(self) #self.logTable.setDefaultRenderer(self.logTable.getColumnClass(0), ColoredTableCellRenderer(self)) self.logTable.setAutoCreateRowSorter(True) self.logTable.setRowSelectionAllowed(True) renderer = ColoredTableCellRenderer(self) #column = TableColumn(0, 190, renderer, None) print 'Initiating... ' # this could be improved by fetching initial dimensions self.logTable.getColumn("URL").setPreferredWidth(720) # noscope self.logTable.getColumn("URL").setResizable(True) self.logTable.getColumn("Checked").setCellRenderer(renderer) self.logTable.getColumn("Checked").setPreferredWidth(80) self.logTable.getColumn("Checked").setMaxWidth(80) self.logTable.getColumn("Method").setPreferredWidth(120) #self.logTable.getColumn("Method").setMaxWidth(120) self.logTable.getColumn("Method").setResizable(True) self.logTable.getColumn("Time").setPreferredWidth(120) # noscope self.logTable.getColumn("Time").setResizable(True) scrollPane = JScrollPane(self.logTable) self._splitpane.setLeftComponent(scrollPane) # tabs with request/response viewers 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) ## Row sorter shit #self._tableRowSorterAutoProxyAutoAction = CustomTableRowSorter(self.logTable.getModel()) #self.logTable.setRowSorter(self._tableRowSorterAutoProxyAutoAction) markAnalyzedButton = JMenuItem("Mark Requests as Analyzed") markAnalyzedButton.addActionListener(markRequestsHandler(self, True)) markNotAnalyzedButton = JMenuItem("Mark Requests as NOT Analyzed") markNotAnalyzedButton.addActionListener( markRequestsHandler(self, False)) sendRequestMenu = JMenuItem("Send Request to Repeater") sendRequestMenu.addActionListener(sendRequestRepeater(self)) deleteRequestMenu = JMenuItem("Delete request") deleteRequestMenu.addActionListener(deleteRequestHandler(self)) self.menu = JPopupMenu("Popup") self.menu.add(markAnalyzedButton) self.menu.add(markNotAnalyzedButton) self.menu.add(sendRequestMenu) self.menu.add(deleteRequestMenu) # customize our UI components callbacks.customizeUiComponent(self._parentPane) callbacks.customizeUiComponent(self._splitpane) callbacks.customizeUiComponent(self._config) callbacks.customizeUiComponent(config) callbacks.customizeUiComponent(self.logTable) callbacks.customizeUiComponent(scrollPane) callbacks.customizeUiComponent(tabs) callbacks.registerContextMenuFactory(self) callbacks.registerExtensionStateListener(self) callbacks.registerScannerCheck(passiveScanner(self)) # add the custom tab to Burp's UI callbacks.addSuiteTab(self) # register ourselves as an HTTP listener callbacks.registerHttpListener(self) self.loadConfigs() print "Loaded!" print "Experimental import state.. " self.importState("") self.SC = sched.scheduler(time.time, time.sleep) self.SCC = self.SC.enter(10, 1, self.autoSave, (self.SC, )) self.SC.run() return ##### CUSTOM CODE ##### def loadConfigs(self): if self._callbacks.loadExtensionSetting("CONFIG_AUTOSTART") == "False": self.startOptionButton.setSelected(False) self.startOrStop(None, False) else: self.startOptionButton.setSelected(True) self.startOrStop(None, True) if self._callbacks.loadExtensionSetting("exportFile") != "": self.selectPathText.setText( self._callbacks.loadExtensionSetting("exportFile")) if self._callbacks.loadExtensionSetting("CONFIG_REPEATER") == "True": self.repeaterOptionButton.setSelected(True) else: self.repeaterOptionButton.setSelected(False) if self._callbacks.loadExtensionSetting("CONFIG_INSCOPE") == "True": self.scopeOptionButton.setSelected(True) else: self.scopeOptionButton.setSelected(False) if self._callbacks.loadExtensionSetting("CONFIG_AUTOSAVE") == "True": self.autoSaveOption.setSelected(True) else: self.autoSaveOption.setSelected(False) if self._callbacks.loadExtensionSetting( "CONFIG_HIGHLIGHT_TESTED") == "True": self.markTestedRequestsProxy.setSelected(True) else: self.markTestedRequestsProxy.setSelected(False) if self._callbacks.loadExtensionSetting( "CONFIG_HIGHLIGHT_NOT_TESTED") == "True": self.markNotTestedRequestsProxy.setSelected(True) else: self.markNotTestedRequestsProxy.setSelected(False) return def selectExportFile(self, event): parentFrame = JFrame() fileChooser = JFileChooser() fileChooser.setDialogTitle("Specify file to save state") fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY) userSelection = fileChooser.showOpenDialog(parentFrame) if (userSelection == JFileChooser.APPROVE_OPTION): fileLoad = fileChooser.getSelectedFile() filename = fileLoad.getAbsolutePath() self.selectPathText.setText(filename) print 'Filename selected:' + filename self._callbacks.saveExtensionSetting("exportFile", filename) return def extensionUnloaded(self): print 'extension unloading.. ' print 'canceling scheduler.. ' map(self.SC.cancel, self.SC.queue) return def loadBadExtensions(self): bad = self._callbacks.loadExtensionSetting("badExtensions") if bad: self.badExtensionsText.setText(bad) # transform text to array bad = bad.replace(" ", "") self.BAD_EXTENSIONS = bad.split(",") else: print 'no bad extension saved, reverting' self.badExtensionsText.setText(", ".join(self.BAD_EXTENSIONS)) def loadBadMimes(self): bad = self._callbacks.loadExtensionSetting("badMimes") if bad: self.badMimesText.setText(bad) bad = bad.replace(" ", "") self.BAD_MIMES = bad.split(",") else: print 'no bad mimes saved, reverting' self.badMimesText.setText(", ".join(self.BAD_MIMES)) ## GLOBAL CONTEXT CODE ## def createMenuItems(self, invocation): responses = invocation.getSelectedMessages() if responses > 0: ret = LinkedList() analyzedMenuItem = JMenuItem("Mark as analyzed") notAnalyzedMenuItem = JMenuItem("Mark as NOT analyzed") for response in responses: analyzedMenuItem.addActionListener( handleMenuItems(self, response, "analyzed")) notAnalyzedMenuItem.addActionListener( handleMenuItems(self, response, "not")) ret.add(analyzedMenuItem) ret.add(notAnalyzedMenuItem) return ret def getEndpoint(self, requestResponse): url_ = str(self._helpers.analyzeRequest(requestResponse).getUrl()) o = urlparse(url_) url = o.scheme + "://" + o.netloc + o.path #print "Url3: " + url return url def getMethod(self, requestResponse): return self._helpers.analyzeRequest(requestResponse).getMethod() ##### CUSTOM CODE ##### def handleTestedRequestsProxy(self, event): self._callbacks.saveExtensionSetting( "CONFIG_HIGHLIGHT_TESTED", str(self.markTestedRequestsProxy.isSelected())) return def handleNotTestedRequestsProxy(self, event): self._callbacks.saveExtensionSetting( "CONFIG_HIGHLIGHT_NOT_TESTED", str(self.markNotTestedRequestsProxy.isSelected())) return def handleStartOption(self, event): self._callbacks.saveExtensionSetting( "CONFIG_AUTOSTART", str(self.startOptionButton.isSelected())) #print 'saving autostart: ' + str(self.startOptionButton.isSelected()) return def startOrStop(self, event, autoStart): if (self.startButton.getText() == MONITOR_OFF_LABEL) or autoStart: self.startButton.setText(MONITOR_ON_LABEL) self.startButton.setBackground(GREEN_COLOR) self.STATUS = True else: self.startButton.setText(MONITOR_OFF_LABEL) self.startButton.setBackground(RED_COLOR) self.STATUS = False def handleStartButton(self, event): self.startOrStop(event, False) def handleAutoSaveOption(self, event): self._callbacks.saveExtensionSetting( "CONFIG_AUTOSAVE", str(self.autoSaveOption.isSelected())) return def handleSaveButton(self, event): self.exportState("") def handleLoadButton(self, event): self.importState("") def handleRepeaterOptionButton(self, event): self._callbacks.saveExtensionSetting( "CONFIG_REPEATER", str(self.repeaterOptionButton.isSelected())) return def handleScopeOptionButton(self, event): self.CONFIG_INSCOPE = self.scopeOptionButton.isSelected() self._callbacks.saveExtensionSetting("CONFIG_INSCOPE", str(self.CONFIG_INSCOPE)) return def handleBadExtensionsButton(self, event): #print "before BAD array: " print self.BAD_EXTENSIONS extensions = self.badExtensionsText.getText() self._callbacks.saveExtensionSetting("badExtensions", extensions) print 'New extensions blocked: ' + extensions bad = extensions.replace(" ", "") self.BAD_EXTENSIONS = bad.split(",") #print "BAD array: " #print self.BAD_EXTENSIONS def handleBadExtensionsDefaultButton(self, event): self.BAD_EXTENSIONS = self.BAD_EXTENSIONS_DEFAULT self.badExtensionsText.setText(", ".join(self.BAD_EXTENSIONS)) self._callbacks.saveExtensionSetting("badExtensions", ", ".join(self.BAD_EXTENSIONS)) return def handleBadMimesDefaultButton(self, event): self.BAD_MIMES = self.BAD_MIMES_DEFAULT self.badMimesText.setText(", ".join(self.BAD_MIMES)) self._callbacks.saveExtensionSetting("badExtensions", ", ".join(self.BAD_MIMES)) return def handleBadMimesButton(self, event): mimes = self.badMimesText.getText() self._callbacks.saveExtensionSetting("badMimes", mimes) print 'New mimes blocked: ' + mimes bad = mimes.replace(" ", "") self.BAD_MIMES = bad.split(",") def handleClearButton(self, event): print 'Clearing table' self._lock.acquire() self._log = ArrayList() self._fullLog = ArrayList() self._lock.release() return def handleRadioConfig(self, event): #print ' radio button clicked ' #print event.getActionCommand() self._lock.acquire() if event.getActionCommand() == SHOW_ALL_BUTTON_LABEL: print "Showing all" self._log = self._fullLog elif event.getActionCommand() == SHOW_NEW_BUTTON_LABEL: print "Showing new scope only" tmpLog = ArrayList() for item in self._fullLog: if not (item._analyzed): tmpLog.add(item) self._log = tmpLog elif event.getActionCommand() == SHOW_TEST_BUTTON_LABEL: print "Showing tested scope only" tmpLog = ArrayList() for item in self._fullLog: if item._analyzed: tmpLog.add(item) self._log = tmpLog else: print "unrecognized radio label" self.fireTableDataChanged() #self._tableRowSorterAutoProxyAutoAction.toggleSortOrder(1) #self.toggleSortOrder(2) #self.logTable.toggleSortOrder(2) # refresh table? self._lock.release() # # implement ITab # def getTabCaption(self): return "Scope Monitor" def getUiComponent(self): return self._parentPane # # implement IHttpListener # def markAnalyzed(self, messageIsRequest, state): #print "markAnalyzed..." self._lock.acquire() url = self.getEndpoint(messageIsRequest) for item in self._log: if url == item._url: item._analyzed = state self._lock.release() return self._lock.release() return def processHttpMessage(self, toolFlag, messageIsRequest, messageInfo): # only process requests #print "processing httpMessage.." #print messageIsRequest print "processHttpMessage toolFlag: " + str(toolFlag) #print " -- " + str(self._callbacks.getToolName(toolFlag)) + " -- " if not (self.STATUS): return #print "global handler status: (true): " + str(self.GLOBAL_HANDLER) #print "(processHTTP) messageIsRequest" #print messageIsRequest isFromPassiveScan = False if toolFlag == 1234: print "1 processHttpMessage: processing passiveScan item" isFromPassiveScan = True if toolFlag != 1234: if messageIsRequest and not (self.GLOBAL_HANDLER): print "1.5 processHttpMessage droping message" return if self.scopeOptionButton.isSelected(): url = self._helpers.analyzeRequest(messageInfo).getUrl() if not self._callbacks.isInScope(url): #print 'Url not in scope, skipping.. ' return #print "still processing httpMessage.., request came from: " + self._callbacks.getToolName(toolFlag) if toolFlag == 1234: print "2 processHttpMessage: processing passiveScan item; setting toolFlag to proxy (4)" toolFlag = 4 #toolFlag = 4 if ((self._callbacks.getToolName(toolFlag) != "Repeater") and (self._callbacks.getToolName(toolFlag) != "Proxy") and (self._callbacks.getToolName(toolFlag) != "Target")): #print 'Aborting processHTTP, request came from: ' + str(self._callbacks.getToolName(toolFlag)) print "Droping request from " + str( self._callbacks.getToolName(toolFlag)) return #print "---> still processing from tool: " + str(self._callbacks.getToolName(toolFlag)) url = self.getEndpoint(messageInfo) method = self.getMethod(messageInfo) #print "(processHTTP) before extensions check: " + url for extension in self.BAD_EXTENSIONS: if url.endswith(extension): return if messageInfo.getResponse(): mime = self._helpers.analyzeResponse( messageInfo.getResponse()).getStatedMimeType() #print 'Declared mime:' + mime mime = mime.lower() if mime in self.BAD_MIMES: #print 'Bad mime:' + mime return #print "[httpMessage] before lock" # create a new log entry with the message details self._lock.acquire() row = self._log.size() for item in self._log: if url == item._url: if method == self._helpers.analyzeRequest( item._requestResponse).getMethod(): #print 'duplicate URL+method, skipping.. ' self._lock.release() # has it been analyzed? analyzed = False if self._callbacks.getToolName(toolFlag) == "Repeater": if self.repeaterOptionButton.isSelected(): analyzed = True #print "[httpMessage] setting analyzed as true" if self.GLOBAL_HANDLER_ANALYZED: analyzed = True item._analyzed = analyzed self.paintItems(messageInfo, item) return #print "[httpMessage] before setComment" if not (isFromPassiveScan): messageInfo.setComment(SCOPE_MONITOR_COMMENT) # reached here, must be new entry analyzed = False if self._callbacks.getToolName(toolFlag) == "Repeater": if self.repeaterOptionButton.isSelected(): analyzed = True #print "[httpMessage] setting analyzed as true" if self.GLOBAL_HANDLER_ANALYZED: analyzed = True #print "[httpMessage] after comment" #print 'in httpmessage, response:' #print self._helpers.analyzeResponse(messageInfo.getResponse()) date = datetime.datetime.fromtimestamp( time.time()).strftime('%H:%M:%S %d %b %Y') entry = LogEntry(toolFlag, self._callbacks.saveBuffersToTempFiles(messageInfo), url, analyzed, date, method) #print "toolFlag: " + str(toolFlag) #print "(processHTTP) Adding URL: " + url self._log.add(entry) self._fullLog.add(entry) self.fireTableRowsInserted(row, row) self.paintItems(messageInfo, entry) self._lock.release() #print "columnCoun:" + str(self.logTable.getColumnCount()) # # extend AbstractTableModel # def paintItems(self, messageInfo, item): ''' print "in paint Items" print "mark color is: (true)" + str(self.markTestedRequestsProxy.isSelected()) print "global handler analyzed: :" + str(self.GLOBAL_HANDLER_ANALYZED) print "item analyzed should be the same ^^:" + str(item._analyzed) ''' if (self.markTestedRequestsProxy.isSelected()) and ( item._analyzed and self.GLOBAL_HANDLER_ANALYZED): messageInfo.setHighlight("green") return if self.markNotTestedRequestsProxy.isSelected() and not ( item._analyzed): messageInfo.setHighlight("red") def getRowCount(self): try: return self._log.size() except: return 0 def getColumnCount(self): return 4 def getColumnName(self, columnIndex): if columnIndex == 0: return "Checked" if columnIndex == 1: return "URL" if columnIndex == 2: return "Method" if columnIndex == 3: return "Time" def getValueAt(self, rowIndex, columnIndex): logEntry = self._log.get(rowIndex) #self.setBackground(Color.GREEN) return self.returnEntry(rowIndex, columnIndex, logEntry) if self.showNewButton.isSelected() and not (logEntry._analyzed): return self.returnEntry(rowIndex, columnIndex, logEntry) elif self.showTestedButton.isSelected() and logEntry._analyzed: return self.returnEntry(rowIndex, columnIndex, logEntry) elif self.showAllButton.isSelected(): return self.returnEntry(rowIndex, columnIndex, logEntry) def returnEntry(self, rowIndex, columnIndex, entry): logEntry = self._log.get(rowIndex) if columnIndex == 0: if logEntry._analyzed: return "True" else: return "False" if columnIndex == 1: return self._helpers.urlDecode(logEntry._url) if columnIndex == 2: return logEntry._method if columnIndex == 3: return logEntry._date # return date 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): #print 'getRequest called' return self._currentlyDisplayedItem.getRequest() def getResponse(self): #print 'getResponse called: ' print self._currentlyDisplayedItem.getResponse() return self._currentlyDisplayedItem.getResponse() def exportRequest(self, entity, filename): line = str(entity._analyzed) + "," line = line + self._helpers.urlEncode(entity._url).replace( ",", "%2c") + "," # URL is encoded so we should be good line = line + entity._method + "," line = line + entity._date line = line + '\n' #print 'Exporting: "' + line + '"' return line def exportUrlEncode(self, url): return self._helpers.urlEncode(url).replace(",", "%2c") def exportState(self, filename): filename = self.selectPathText.getText() if filename == "": filename = self._callbacks.loadExtensionSetting("exportFile") print 'Empty filename, skipping export' return else: self._callbacks.saveExtensionSetting("exportFile", filename) print 'saving state to: ' + filename savedUrls = [] self._lockFile.acquire() try: with open(filename, 'r') as fr: savedEntries = fr.read().splitlines() savedUrls = [] for savedEntry in savedEntries: savedUrls.append(savedEntry.split(",")[1]) #print "savedUrls len: " + str(len(savedUrls)) #print "savedUrls:" #print savedUrls fr.close() except IOError: print "Autosaving skipped as file doesn't exist yet" with open(filename, 'a+') as f: for item in self._log: if self.exportUrlEncode(item._url) not in savedUrls: line = self.exportRequest(item, "xx") f.write(line) f.close() self._lockFile.release() return def importState(self, filename): filename = self.selectPathText.getText() if filename == "": filename = self._callbacks.loadExtensionSetting("exportFile") print 'Empty filename, skipping import' return else: self._callbacks.saveExtensionSetting("exportFile", filename) print 'loading state from: ' + filename self.STATUS = False self._lockFile.acquire() with open(filename, 'r') as f: proxy = self._callbacks.getProxyHistory() proxyItems = [] for item in proxy: if item.getComment(): if SCOPE_MONITOR_COMMENT in item.getComment(): proxyItems.append(item) print 'proxyItems has: ' + str(len(proxyItems)) # TODO - if no proxy items, sraight to import lines = f.read().splitlines() for line in lines: data = line.split(",") url = data[1] url = self._helpers.urlDecode(url) #print 'Saving: ' + url if not self._callbacks.isInScope(URL(url)): print '-- imported url not in scope, skipping.. ' continue analyzed = False if data[0] == "True": analyzed = True #print '.. simulating url search.. ' requestResponse = None for request in proxyItems: if url == self.getEndpoint(request): #print 'Match found when importing for url: ' + url requestResponse = request break self._log.add( LogEntry("", requestResponse, url, analyzed, data[3], data[2])) self._lockFile.release() print 'finished loading.. ' #print 'size: ' + str(self._log.size()) self.fireTableDataChanged() if self.startButton.getText() == MONITOR_ON_LABEL: self.STATUS = True return def autoSave(self, sc): #print 'autosaving.. lol what' if self.autoSaveOption.isSelected(): print "[" + self.getTime( ) + "] autosaving to " + self._callbacks.loadExtensionSetting( "exportFile") self.exportState("") self.SC.enter(self.AUTOSAVE_TIMEOUT, 1, self.autoSave, (self.SC, )) return def getTime(self): date = datetime.datetime.fromtimestamp( time.time()).strftime('%H:%M:%S') return date
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()
class NewZoneDialog(JDialog, ActionListener, WindowListener): """Dialog for favourite zone editing """ def __init__(self, parent, title, modal, app): from java.awt import CardLayout self.app = app border = BorderFactory.createEmptyBorder(5, 7, 7, 7) self.getContentPane().setBorder(border) self.setLayout(BoxLayout(self.getContentPane(), BoxLayout.Y_AXIS)) self.FAVAREALAYERNAME = "Favourite zone editing" info = JLabel(self.app.strings.getString("Create_a_new_favourite_zone")) info.setAlignmentX(Component.LEFT_ALIGNMENT) #Name nameLbl = JLabel(self.app.strings.getString("fav_zone_name")) self.nameTextField = JTextField(20) self.nameTextField.setMaximumSize(self.nameTextField.getPreferredSize()) self.nameTextField.setToolTipText(self.app.strings.getString("fav_zone_name_tooltip")) namePanel = JPanel() namePanel.setLayout(BoxLayout(namePanel, BoxLayout.X_AXIS)) namePanel.add(nameLbl) namePanel.add(Box.createHorizontalGlue()) namePanel.add(self.nameTextField) #Country countryLbl = JLabel(self.app.strings.getString("fav_zone_country")) self.countryTextField = JTextField(20) self.countryTextField.setMaximumSize(self.countryTextField.getPreferredSize()) self.countryTextField.setToolTipText(self.app.strings.getString("fav_zone_country_tooltip")) countryPanel = JPanel() countryPanel.setLayout(BoxLayout(countryPanel, BoxLayout.X_AXIS)) countryPanel.add(countryLbl) countryPanel.add(Box.createHorizontalGlue()) countryPanel.add(self.countryTextField) #Type modeLbl = JLabel(self.app.strings.getString("fav_zone_type")) RECTPANEL = "rectangle" POLYGONPANEL = "polygon" BOUNDARYPANEL = "boundary" self.modesStrings = [RECTPANEL, POLYGONPANEL, BOUNDARYPANEL] modesComboModel = DefaultComboBoxModel() for i in (self.app.strings.getString("rectangle"), self.app.strings.getString("delimited_by_a_closed_way"), self.app.strings.getString("delimited_by_an_administrative_boundary")): modesComboModel.addElement(i) self.modesComboBox = JComboBox(modesComboModel, actionListener=self, editable=False) #- Rectangle self.rectPanel = JPanel() self.rectPanel.setLayout(BoxLayout(self.rectPanel, BoxLayout.Y_AXIS)) capturePane = JPanel() capturePane.setLayout(BoxLayout(capturePane, BoxLayout.X_AXIS)) capturePane.setAlignmentX(Component.LEFT_ALIGNMENT) josmP = JPanel() self.captureRBtn = JRadioButton(self.app.strings.getString("capture_area")) self.captureRBtn.addActionListener(self) self.captureRBtn.setSelected(True) self.bboxFromJosmBtn = JButton(self.app.strings.getString("get_current_area"), actionPerformed=self.on_bboxFromJosmBtn_clicked) self.bboxFromJosmBtn.setToolTipText(self.app.strings.getString("get_capture_area_tooltip")) josmP.add(self.bboxFromJosmBtn) capturePane.add(self.captureRBtn) capturePane.add(Box.createHorizontalGlue()) capturePane.add(self.bboxFromJosmBtn) manualPane = JPanel() manualPane.setLayout(BoxLayout(manualPane, BoxLayout.X_AXIS)) manualPane.setAlignmentX(Component.LEFT_ALIGNMENT) self.manualRBtn = JRadioButton(self.app.strings.getString("use_this_bbox")) self.manualRBtn.addActionListener(self) self.bboxTextField = JTextField(20) self.bboxTextField.setMaximumSize(self.bboxTextField.getPreferredSize()) self.bboxTextField.setToolTipText(self.app.strings.getString("fav_bbox_tooltip")) self.bboxTextFieldDefaultBorder = self.bboxTextField.getBorder() self.bboxTextField.getDocument().addDocumentListener(TextListener(self)) manualPane.add(self.manualRBtn) manualPane.add(Box.createHorizontalGlue()) manualPane.add(self.bboxTextField) group = ButtonGroup() group.add(self.captureRBtn) group.add(self.manualRBtn) previewPane = JPanel() previewPane.setLayout(BoxLayout(previewPane, BoxLayout.X_AXIS)) previewPane.setAlignmentX(Component.LEFT_ALIGNMENT) bboxPreviewInfo = JTextField(self.app.strings.getString("coordinates"), editable=0, border=None) bboxPreviewInfo.setMaximumSize(bboxPreviewInfo.getPreferredSize()) self.bboxPreviewTextField = JTextField(20, editable=0, border=None) self.bboxPreviewTextField.setMaximumSize(self.bboxPreviewTextField.getPreferredSize()) previewPane.add(bboxPreviewInfo) previewPane.add(Box.createHorizontalGlue()) previewPane.add(self.bboxPreviewTextField) self.rectPanel.add(capturePane) self.rectPanel.add(Box.createRigidArea(Dimension(0, 10))) self.rectPanel.add(manualPane) self.rectPanel.add(Box.createRigidArea(Dimension(0, 20))) self.rectPanel.add(previewPane) #- Polygon (closed way) drawn by hand self.polygonPanel = JPanel(BorderLayout()) self.polygonPanel.setLayout(BoxLayout(self.polygonPanel, BoxLayout.Y_AXIS)) polyInfo = JLabel("<html>%s</html>" % self.app.strings.getString("polygon_info")) polyInfo.setFont(polyInfo.getFont().deriveFont(Font.ITALIC)) polyInfo.setAlignmentX(Component.LEFT_ALIGNMENT) editPolyPane = JPanel() editPolyPane.setAlignmentX(Component.LEFT_ALIGNMENT) editPolyBtn = JButton(self.app.strings.getString("create_fav_layer"), actionPerformed=self.create_new_zone_editing_layer) editPolyBtn.setToolTipText(self.app.strings.getString("create_fav_layer_tooltip")) editPolyPane.add(editPolyBtn) self.polygonPanel.add(polyInfo) self.polygonPanel.add(Box.createRigidArea(Dimension(0, 15))) self.polygonPanel.add(editPolyPane) self.polygonPanel.add(Box.createRigidArea(Dimension(0, 15))) #- Administrative Boundary self.boundaryPanel = JPanel() self.boundaryPanel.setLayout(BoxLayout(self.boundaryPanel, BoxLayout.Y_AXIS)) boundaryInfo = JLabel("<html>%s</html>" % app.strings.getString("boundary_info")) boundaryInfo.setFont(boundaryInfo.getFont().deriveFont(Font.ITALIC)) boundaryInfo.setAlignmentX(Component.LEFT_ALIGNMENT) boundaryTagsPanel = JPanel(GridLayout(3, 3, 5, 5)) boundaryTagsPanel.setAlignmentX(Component.LEFT_ALIGNMENT) boundaryTagsPanel.add(JLabel("name =")) self.nameTagTextField = JTextField(20) boundaryTagsPanel.add(self.nameTagTextField) boundaryTagsPanel.add(JLabel("admin_level =")) self.adminLevelTagTextField = JTextField(20) self.adminLevelTagTextField.setToolTipText(self.app.strings.getString("adminLevel_tooltip")) boundaryTagsPanel.add(self.adminLevelTagTextField) boundaryTagsPanel.add(JLabel(self.app.strings.getString("other_tag"))) self.optionalTagTextField = JTextField(20) self.optionalTagTextField.setToolTipText("key=value") boundaryTagsPanel.add(self.optionalTagTextField) downloadBoundariesPane = JPanel() downloadBoundariesPane.setAlignmentX(Component.LEFT_ALIGNMENT) downloadBoundariesBtn = JButton(self.app.strings.getString("download_boundary"), actionPerformed=self.on_downloadBoundariesBtn_clicked) downloadBoundariesBtn.setToolTipText(self.app.strings.getString("download_boundary_tooltip")) downloadBoundariesPane.add(downloadBoundariesBtn) self.boundaryPanel.add(boundaryInfo) self.boundaryPanel.add(Box.createRigidArea(Dimension(0, 15))) self.boundaryPanel.add(boundaryTagsPanel) self.boundaryPanel.add(Box.createRigidArea(Dimension(0, 10))) self.boundaryPanel.add(downloadBoundariesPane) self.editingPanels = {"rectangle": self.rectPanel, "polygon": self.polygonPanel, "boundary": self.boundaryPanel} #Main buttons self.okBtn = JButton(self.app.strings.getString("OK"), ImageProvider.get("ok"), actionPerformed=self.on_okBtn_clicked) self.cancelBtn = JButton(self.app.strings.getString("cancel"), ImageProvider.get("cancel"), actionPerformed=self.close_dialog) self.previewBtn = JButton(self.app.strings.getString("Preview_zone"), actionPerformed=self.on_previewBtn_clicked) self.previewBtn.setToolTipText(self.app.strings.getString("preview_zone_tooltip")) okBtnSize = self.okBtn.getPreferredSize() viewBtnSize = self.previewBtn.getPreferredSize() viewBtnSize.height = okBtnSize.height self.previewBtn.setPreferredSize(viewBtnSize) #layout self.add(info) self.add(Box.createRigidArea(Dimension(0, 15))) namePanel.setAlignmentX(Component.LEFT_ALIGNMENT) self.add(namePanel) self.add(Box.createRigidArea(Dimension(0, 15))) countryPanel.setAlignmentX(Component.LEFT_ALIGNMENT) self.add(countryPanel) self.add(Box.createRigidArea(Dimension(0, 15))) modeLbl.setAlignmentX(Component.LEFT_ALIGNMENT) self.add(modeLbl) self.add(Box.createRigidArea(Dimension(0, 5))) self.add(self.modesComboBox) self.modesComboBox.setAlignmentX(Component.LEFT_ALIGNMENT) self.add(Box.createRigidArea(Dimension(0, 15))) self.configPanel = JPanel(CardLayout()) self.configPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)) self.configPanel.add(self.rectPanel, RECTPANEL) self.configPanel.add(self.polygonPanel, POLYGONPANEL) self.configPanel.add(self.boundaryPanel, BOUNDARYPANEL) self.configPanel.setAlignmentX(Component.LEFT_ALIGNMENT) self.add(self.configPanel) buttonsPanel = JPanel() buttonsPanel.add(self.okBtn) buttonsPanel.add(self.cancelBtn) buttonsPanel.add(self.previewBtn) buttonsPanel.setAlignmentX(Component.LEFT_ALIGNMENT) self.add(buttonsPanel) self.addWindowListener(self) self.pack() def update_gui_from_preferences(self): self.nameTextField.setText(self.app.newZone.name) #Reset rectangle mode bboxStr = ",".join(["%0.4f" % x for x in self.app.newZone.bbox]) self.bboxTextField.setText(bboxStr) self.bboxPreviewTextField.setText(bboxStr) self.bboxFromJosmBtn.setEnabled(True) self.bboxTextField.setEnabled(False) #Reset polygon mode self.polygonAsString = "" #Reset boundary mode self.boundaryAsString = "" self.modesComboBox.setSelectedIndex(0) def actionPerformed(self, e): #Show the panel for configuring the favourite area of the #selected type if e.getSource() == self.modesComboBox: cl = self.configPanel.getLayout() selectedMode = self.modesStrings[self.modesComboBox.selectedIndex] cl.show(self.configPanel, selectedMode) #Activate bbox input for rectangular favourite zone mode elif e.getSource() == self.captureRBtn: self.bboxFromJosmBtn.setEnabled(True) self.bboxTextField.setEnabled(False) else: self.bboxFromJosmBtn.setEnabled(False) self.bboxTextField.setEnabled(True) def on_bboxFromJosmBtn_clicked(self, widget): """Read bbox currently shown in JOSM """ bbox = self.app.get_frame_bounds() self.bboxPreviewTextField.setText(",".join(["%0.4f" % x for x in bbox])) ### Manage layer for creating a new favourite zone from polygon or boundary def create_new_zone_editing_layer(self, e=None): """Open a new dataset where the user can draw a closed way to delimit the favourite area """ layer = self.get_new_zone_editing_layer() if layer is not None: self.app.mv.setActiveLayer(layer) else: Main.main.addLayer(OsmDataLayer(DataSet(), self.FAVAREALAYERNAME, None)) Main.main.parent.toFront() def get_new_zone_editing_layer(self): """Check if the layer for editing the favourite area yet exists """ for layer in self.app.mv.getAllLayers(): if layer.getName() == self.FAVAREALAYERNAME: return layer return None def remove_new_zone_editing_layer(self): layer = self.get_new_zone_editing_layer() if layer is not None: self.app.mv.removeLayer(layer) def on_zone_edited(self): """Read ways that delimit the favourite area and convert them to jts geometry """ if self.modesComboBox.getSelectedIndex() == 0: mode = "rectangle" elif self.modesComboBox.getSelectedIndex() == 1: mode = "polygon" elif self.modesComboBox.getSelectedIndex() == 2: mode = "boundary" if mode in ("polygon", "boundary"): layer = self.get_new_zone_editing_layer() if layer is not None: self.app.mv.setActiveLayer(layer) else: if mode == "polygon": msg = self.app.strings.getString("polygon_fav_layer_missing_msg") else: msg = self.app.strings.getString("boundary_fav_layer_missing_msg") JOptionPane.showMessageDialog(self, msg, self.app.strings.getString("Warning"), JOptionPane.WARNING_MESSAGE) return dataset = self.app.mv.editLayer.data areaWKT = self.read_area_from_osm_ways(mode, dataset) if areaWKT is None: print "I could not read the new favourite area." else: if mode == "polygon": self.polygonAsString = areaWKT else: self.boundaryAsString = areaWKT return mode def read_area_from_osm_ways(self, mode, dataset): """Read way in favourite area editing layer and convert them to WKT """ converter = JTSConverter(False) lines = [converter.convert(way) for way in dataset.ways] polygonizer = Polygonizer() polygonizer.add(lines) polygons = polygonizer.getPolygons() multipolygon = GeometryFactory().createMultiPolygon(list(polygons)) multipolygonWKT = WKTWriter().write(multipolygon) if multipolygonWKT == "MULTIPOLYGON EMPTY": if mode == "polygon": msg = self.app.strings.getString("empty_ways_polygon_msg") else: msg = self.app.strings.getString("empty_ways_boundaries_msg") JOptionPane.showMessageDialog(self, msg, self.app.strings.getString("Warning"), JOptionPane.WARNING_MESSAGE) return return multipolygonWKT def on_downloadBoundariesBtn_clicked(self, e): """Download puter ways of administrative boundaries from Overpass API """ adminLevel = self.adminLevelTagTextField.getText() name = self.nameTagTextField.getText() optional = self.optionalTagTextField.getText() if (adminLevel, name, optional) == ("", "", ""): JOptionPane.showMessageDialog(self, self.app.strings.getString("enter_a_tag_msg"), self.app.strings.getString("Warning"), JOptionPane.WARNING_MESSAGE) return optTag = "" if optional.find("=") != -1: if len(optional.split("=")) == 2: key, value = optional.split("=") optTag = '["%s"="%s"]' % (URLEncoder.encode(key, "UTF-8"), URLEncoder.encode(value.replace(" ", "%20"), "UTF-8")) self.create_new_zone_editing_layer() overpassurl = 'http://127.0.0.1:8111/import?url=' overpassurl += 'http://overpass-api.de/api/interpreter?data=' overpassquery = 'relation["admin_level"="%s"]' % adminLevel overpassquery += '["name"="%s"]' % URLEncoder.encode(name, "UTF-8") overpassquery += '%s;(way(r:"outer");node(w););out meta;' % optTag overpassurl += overpassquery.replace(" ", "%20") print overpassurl self.app.send_to_josm(overpassurl) ### Buttons ############################################################ def create_new_zone(self, mode): """Read data entered on gui and create a new zone """ name = self.nameTextField.getText() country = self.countryTextField.getText().upper() #error: name if name.replace(" ", "") == "": JOptionPane.showMessageDialog(self, self.app.strings.getString("missing_name_warning"), self.app.strings.getString("missing_name_warning_title"), JOptionPane.WARNING_MESSAGE) return False if name in [z.name for z in self.app.tempZones]: JOptionPane.showMessageDialog(self, self.app.strings.getString("duplicate_name_warning"), self.app.strings.getString("duplicate_name_warning_title"), JOptionPane.WARNING_MESSAGE) return False #zone type zType = mode #error: geometry type not defined if zType == "polygon" and self.polygonAsString == ""\ or zType == "boundary" and self.boundaryAsString == "": JOptionPane.showMessageDialog(self, self.app.strings.getString("zone_not_correctly_build_warning"), self.app.strings.getString("zone_not_correctly_build_warning_title"), JOptionPane.WARNING_MESSAGE) return False #geometry string if zType == "rectangle": geomString = self.bboxPreviewTextField.getText() elif zType == "polygon": geomString = self.polygonAsString else: geomString = self.boundaryAsString self.app.newZone = Zone(self.app, name, zType, geomString, country) #self.app.newZone.print_info() return True def on_okBtn_clicked(self, event): """Add new zone to temp zones """ mode = self.on_zone_edited() if self.create_new_zone(mode): self.app.tempZones.append(self.app.newZone) self.app.preferencesFrame.zonesTable.getModel().addRow([self.app.newZone.country, self.app.newZone.icon, self.app.newZone.name]) maxIndex = len(self.app.tempZones) - 1 self.app.preferencesFrame.zonesTable.setRowSelectionInterval(maxIndex, maxIndex) self.close_dialog() self.app.preferencesFrame.check_removeBtn_status() self.app.preferencesFrame.zonesTable.scrollRectToVisible( self.app.preferencesFrame.zonesTable.getCellRect( self.app.preferencesFrame.zonesTable.getRowCount() - 1, 0, True)) def on_previewBtn_clicked(self, e): """Show the favourite area on a map """ mode = self.on_zone_edited() if not self.create_new_zone(mode): return zone = self.app.newZone if zone.zType == "rectangle": wktString = zone.bbox_to_wkt_string() else: wktString = zone.wktGeom script = '/*http://stackoverflow.com/questions/11954401/wkt-and-openlayers*/' script += '\nfunction init() {' script += '\n var map = new OpenLayers.Map({' script += '\n div: "map",' script += '\n projection: new OpenLayers.Projection("EPSG:900913"),' script += '\n displayProjection: new OpenLayers.Projection("EPSG:4326"),' script += '\n layers: [' script += '\n new OpenLayers.Layer.OSM()' script += '\n ]' script += '\n });' script += '\n var wkt = new OpenLayers.Format.WKT();' script += '\n var polygonFeature = wkt.read("%s");' % wktString script += '\n var vectors = new OpenLayers.Layer.Vector("Favourite area");' script += '\n map.addLayer(vectors);' script += '\n polygonFeature.geometry.transform(map.displayProjection, map.getProjectionObject());' script += '\n vectors.addFeatures([polygonFeature]);' script += '\n map.zoomToExtent(vectors.getDataExtent());' script += '\n};' scriptFile = open(File.separator.join([self.app.SCRIPTDIR, "html", "script.js"]), "w") scriptFile.write(script) scriptFile.close() OpenBrowser.displayUrl(File.separator.join([self.app.SCRIPTDIR, "html", "favourite_area.html"])) def windowClosing(self, windowEvent): self.close_dialog() def close_dialog(self, e=None): #delete favourite zone editing layer if present self.remove_new_zone_editing_layer() self.dispose() self.app.preferencesFrame.setEnabled(True) self.app.preferencesFrame.toFront()
def __init__(self): #obtain prefixes from folder self.dict1 = self.obtain_prefixes( ) #Run prefix selection function - sets source directory, requests prefix size, outputs prefix dictionary lst = list(self.dict1.keys()) #pull prefixes only, as list self.lang = lst self.lst = JList(self.lang, valueChanged=self.listSelect ) # pass prefix list to GUI selection list # general GUI layout parameters, no data processing here self.frame = JFrame("Image Selection") self.frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE) self.frame.setLocation(100, 100) self.frame.setSize(800, 350) self.frame.setLayout(BorderLayout()) self.frame.add(self.lst, BorderLayout.NORTH) self.lst.selectionMode = ListSelectionModel.MULTIPLE_INTERVAL_SELECTION self.button1 = JButton('Select item(s)', actionPerformed=self.clickhere) #Save option radio buttons and file extension selection #set main right panel (sub panels will fit within this) rightpanel = JPanel() rightpanel.setLayout(BoxLayout(rightpanel, BoxLayout.Y_AXIS)) #set up savestate panel buttonpanel = JPanel() self.radiobutton1 = JRadioButton( "Open selected 3D stacks and max projections \n and save max projections", True) self.radiobutton2 = JRadioButton( "Open selected 3D stacks and max projections \n and DO NOT save max projections" ) infoLabel = JLabel( "<html>Hold ctrl and click multiple prefixes to select multiple options. Will load stacks and MIPs separately <br><br> Type file extension in text field below:</html>", SwingConstants.LEFT) grp = ButtonGroup() grp.add(self.radiobutton1) grp.add(self.radiobutton2) #buttonpanel.setLayout(BoxLayout(buttonpanel, BoxLayout.Y_AXIS)) buttonpanel.add(Box.createVerticalGlue()) buttonpanel.add(infoLabel) buttonpanel.add(Box.createRigidArea(Dimension(0, 5))) buttonpanel.add(self.radiobutton1) buttonpanel.add(Box.createRigidArea(Dimension(0, 5))) buttonpanel.add(self.radiobutton2) #file extension instruction panel infopanel = JPanel() infopanel.setLayout(FlowLayout(FlowLayout.LEFT)) infopanel.setMaximumSize( infopanel.setPreferredSize(Dimension(650, 100))) infopanel.add(infoLabel) #file extension input inputPanel = JPanel() inputPanel.setLayout(BoxLayout(inputPanel, BoxLayout.X_AXIS)) self.filetype = JTextField(".tif", 15) self.filetype.setMaximumSize(self.filetype.getPreferredSize()) inputPanel.add(self.filetype) ########### WIP - integrate prefix selection with main pane, with dynamically updating prefix list ##infoLabel3 = JLabel("how long is the file prefix to group by?(integer value only)") ##self.prefix_init = JTextField() ##buttonpanel.add(infoLabel3) ##buttonpanel.add(self.prefix_init) ########### !WIP #add file extension and savestate panels to main panel rightpanel.add(infopanel) rightpanel.add(inputPanel) rightpanel.add(buttonpanel, BorderLayout.EAST) #split list and radiobutton pane (construct overall window) spl = JSplitPane(JSplitPane.HORIZONTAL_SPLIT) spl.leftComponent = JScrollPane(self.lst) spl.setDividerLocation(150) spl.rightComponent = rightpanel self.frame.add(spl) self.frame.add(self.button1, BorderLayout.SOUTH) # GUI layout done, initialise GUI to select prefixes, file extension and save option self.frame.setVisible(True)
class CustomCellRenderer(DefaultTreeCellRenderer): """Renders the various tree controls (checkbox, tristate checkbox, string values etc.)""" def __init__(self): DefaultTreeCellRenderer.__init__(self) flowLayout = FlowLayout(FlowLayout.LEFT, 0, 0) self.cbPanel = JPanel(flowLayout) self.cb = JCheckBox() self.cb.setBackground(None) self.cbPanel.add(self.cb) self.cbLabel = JLabel() self.cbPanel.add(self.cbLabel) self.tcbPanel = JPanel(flowLayout) self.tcb = TristateCheckBox() self.tcb.setBackground(None) self.tcbPanel.add(self.tcb) self.tcbLabel = JLabel() self.tcbPanel.add(self.tcbLabel) self.rbPanel = JPanel(flowLayout) self.rb = JRadioButton() self.rb.setBackground(None) self.rbPanel.add(self.rb) self.rbLabel = JLabel() self.rbPanel.add(self.rbLabel) def getTreeCellRendererComponent(self, tree, value, selected, expanded, leaf, row, hasFocus): """Return a swing control appropriate for the node type of the supplied value""" if isinstance(value, DefaultMutableTreeNode): nodeData = value.getUserObject() if isinstance(nodeData, TreeNodeData): t = nodeData.getNodeType() isEnabled = nodeData.getVisible() > 0 # Boolean checkbox if t.isType([NodeType._bool]): self.cbLabel.setText(nodeData.getText()) self.cb.setEnabled(isEnabled) self.cbLabel.setEnabled(isEnabled) if nodeData.getTriValue() == 0: self.cb.setSelected(False) else: self.cb.setSelected(True) control = self.cbPanel # Tristate chekcbox elif t.isType([NodeType._tri]): control = self.tcbPanel self.tcbLabel.setText(nodeData.getText()) self.tcb.setEnabled(isEnabled) self.tcbLabel.setEnabled(isEnabled) self.tcb.setTriState(nodeData.getTriValue()) # Radio button elif t.isType([NodeType._radio]): self.rbLabel.setText(nodeData.getText()) self.rb.setEnabled(isEnabled) self.rbLabel.setEnabled(isEnabled) if nodeData.getTriValue() == 0: self.rb.setSelected(False) else: self.rb.setSelected(True) control = self.rbPanel # Text field elif t.isType([NodeType._text]): control = DefaultTreeCellRenderer.getTreeCellRendererComponent( self, tree, value, selected, expanded, leaf, row, hasFocus) control.setText(nodeData.getText() + ": " + str(nodeData.getValue())) # Default tree cell (a node with an icon and a label) else: control = DefaultTreeCellRenderer.getTreeCellRendererComponent( self, tree, value, selected, expanded, leaf, row, hasFocus) control.setText(nodeData.getText()) self.setColors(control, nodeData, selected) # Background color for the tree item # log.info("getTreeCellRendererComponent", t.getType(), isEnabled, "'" + nodeData.getText() + "'") control.setEnabled(isEnabled) return control # log.info("Warning: getTreeCellRendererComponent() fallthrough", nodeData) return DefaultTreeCellRenderer.getTreeCellRendererComponent( self, tree, value, selected, expanded, leaf, row, hasFocus) def setColors(self, control, data, selected): """Set background color fot the tree item.""" if selected: control.setForeground(self.getTextSelectionColor()) control.setBackground(self.getBackgroundSelectionColor()) else: control.setForeground(self.getTextNonSelectionColor()) control.setBackground(self.getBackgroundNonSelectionColor())
class BurpExtender(IBurpExtender, IHttpListener, IMessageEditorTabFactory, ITab): # # implement IBurpExtender # def registerExtenderCallbacks(self, callbacks): global EXTENSION_NAME 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 our extension name callbacks.setExtensionName(EXTENSION_NAME) # register ourselves as a Http Listener callbacks.registerHttpListener(self) # register ourselves as a message editor tab factory callbacks.registerMessageEditorTabFactory(self) # setup the UI self.initGui() # add the custom tab to Burp's UI self._callbacks.addSuiteTab(self) return # # create the Gui # 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 def reloadConf(self,event): #~ if DEBUG: #~ import pdb; pdb.set_trace() source = event.getSource() print 'APPLY button clicked. New configuration loaded.' global MAGIC_PARAMETER global PARAMETERISPOST global PARAMETERISGET global PARAMETERISCOOKIE global BASE64ENCODINGENABLED global ASCII2HEXENCODINGENABLED global URLENCODINGENABLED global INTRUDERENABLED global SCANNERENABLED MAGIC_PARAMETER=self.parameterName.getText() print 'Base64 checkbox is: '+str(self.base64Enabled.isSelected()) if self.base64Enabled.isSelected(): BASE64ENCODINGENABLED=True else: BASE64ENCODINGENABLED=False print 'ASCII2Hex checkbox is: '+str(self.ASCII2HexEnabled.isSelected()) if self.ASCII2HexEnabled.isSelected(): ASCII2HEXENCODINGENABLED=True else: ASCII2HEXENCODINGENABLED=False print 'URL checkbox is: '+str(self.URLEnabled.isSelected()) if self.URLEnabled.isSelected(): URLENCODINGENABLED=True else: URLENCODINGENABLED=False print 'New Magic parameter is: '+str(MAGIC_PARAMETER) if self.POSTparameterTypeRadioButton.isSelected(): #BODYPARAM PARAMETERISPOST=True print "parameterispost has been set to: " + str(PARAMETERISPOST) else: PARAMETERISPOST=False print "parameterispost has been set to: " + str(PARAMETERISPOST) if self.GETparameterTypeRadioButton.isSelected(): #GETPARAM PARAMETERISGET=True print "parameterisget has been set to: " + str(PARAMETERISGET) else: PARAMETERISGET=False print "parameterisget has been set to: " + str(PARAMETERISGET) if self.COOKIEparameterTypeRadioButton.isSelected(): #COOKIEPARAM PARAMETERISCOOKIE=True print "parameteriscookie has been set to: " + str(PARAMETERISCOOKIE) else: PARAMETERISCOOKIE=False print "parameteriscookie has been set to: " + str(PARAMETERISCOOKIE) if self.ScannerEnabled.isSelected(): SCANNERENABLED=True print "Scanner Enabled" else: SCANNERENABLED=False if self.IntruderEnabled.isSelected(): INTRUDERENABLED=True print "Intruder Enabled" else: INTRUDERENABLED=False # # implement IHTTPListener # def processHttpMessage(self, toolFlag, messageIsRequest, currentRequest): global PARAMETERISPOST global PARAMETERISGET global PARAMETERISCOOKIE global URLENCODINGENABLED global BASE64ENCODINGENABLED global ASCII2HEXENCODINGENABLED global INTRUDERENABLED global SCANNERENABLED #only process requests if not messageIsRequest: return #only process messages from Intruder and Scanner, otherwise exit #if (not self._callbacks.TOOL_INTRUDER == toolFlag): if ((not ((self._callbacks.TOOL_INTRUDER == toolFlag) and INTRUDERENABLED)) and (not ((self._callbacks.TOOL_SCANNER == toolFlag) and SCANNERENABLED))): #print "exiting- toolflag:"+str(toolFlag)+' INTRUDERENABLED='+str(INTRUDERENABLED)+' SCANNERENABLED='+str(SCANNERENABLED) return #if ((not self._callbacks.TOOL_INTRUDER == toolFlag)) and ((not self._callbacks.TOOL_SCANNER == toolFlag)):#remove the comment to always enable if DEBUG: print "IHTTPListener Enabled in: " + str(toolFlag) requestInfo = self._helpers.analyzeRequest(currentRequest) timestamp = datetime.now() if DEBUG: print "Intercepting message at: ", timestamp.isoformat() #parameters = requestInfo.getParameters() dataParameter = self._helpers.getRequestParameter(currentRequest.getRequest(), MAGIC_PARAMETER) #FIXME: add exception handling for multiple parameters with the same name and/or in a different position!!! if DEBUG: print 'dataparameter:'+str(dataParameter) if (dataParameter == None): if DEBUG: print 'Parameter does not exist' return serializedValue = dataParameter.getValue() #FIXME: substitute '[AND]' placeholder with '&' charachter - we should do something more elegant here :/ serializedValue = re.sub(r'\[AND\]', '&', serializedValue) print "unserialized parameter value: ", str(serializedValue) if BASE64ENCODINGENABLED: #if base64Encode is selected serializedValue = self._helpers.base64Encode(serializedValue) if DEBUG: print "base64 encoded parameter value: ", str(serializedValue) if URLENCODINGENABLED: #if URLEncode is selected serializedValue = self._helpers.urlEncode(serializedValue) if DEBUG: print "URL ecoded parameter value: ", str(serializedValue) if ASCII2HEXENCODINGENABLED: #if ASCII2HexEncode is selected serializedValue = convert_ascii2hex(serializedValue) if DEBUG: print "ASCII2Hex ecoded parameter value: ", str(serializedValue) print "serialized parameter value: ", serializedValue if PARAMETERISPOST: if DEBUG: print "parameter is BODY" currentRequest.setRequest(self._helpers.updateParameter(currentRequest.getRequest(),self._helpers.buildParameter(MAGIC_PARAMETER, serializedValue,IParameter.PARAM_BODY))) elif PARAMETERISGET: if DEBUG: print "parameter is in URL" currentRequest.setRequest(self._helpers.updateParameter(currentRequest.getRequest(),self._helpers.buildParameter(MAGIC_PARAMETER, serializedValue,IParameter.PARAM_URL))) elif PARAMETERISCOOKIE: if DEBUG: print "parameter is a COOKIE" currentRequest.setRequest(self._helpers.updateParameter(currentRequest.getRequest(),self._helpers.buildParameter(MAGIC_PARAMETER, serializedValue,IParameter.PARAM_COOKIE))) return # # implement ITab # def getTabCaption(self): global EXTENSION_TABCAPTION return(EXTENSION_TABCAPTION) def getUiComponent(self): #~ return self._splitpane return self.tab # # implement IMessageEditorTabFactory # def createNewInstance(self, controller, editable): # create a new instance of our custom editor tab return CustomInputTab(self, controller, editable)
class CustomCellEditor(TreeCellEditor, ActionListener): """Renders the various tree edit controls (checkbox, tristate checkbox, text box etc.)""" def __init__(self, tree): TreeCellEditor.__init__(self) self.editor = None self.tree = tree flowLayout = FlowLayout(FlowLayout.LEFT, 0, 0) self.cbPanel = JPanel(flowLayout) self.cb = JCheckBox(actionPerformed=self.checked) self.cbPanel.add(self.cb) self.cbLabel = JLabel() self.cbPanel.add(self.cbLabel) self.tcbPanel = JPanel(flowLayout) self.tcb = TristateCheckBox(self.checked) self.tcbPanel.add(self.tcb) self.tcbLabel = JLabel() self.tcbPanel.add(self.tcbLabel) self.rbPanel = JPanel(flowLayout) self.rb = JRadioButton(actionPerformed=self.checked) self.rbPanel.add(self.rb) self.rbLabel = JLabel() self.rbPanel.add(self.rbLabel) self.tfPanel = JPanel(flowLayout) self.tfLabel = JLabel() self.tfPanel.add(self.tfLabel) self.tf = JTextField() self.tf.setColumns(12) self.tf.addActionListener(self) self.tfPanel.add(self.tf) def addCellEditorListener(self, l): """Register for edit events""" self.listener = l def isCellEditable(self, event): if event != None and isinstance( event.getSource(), JTree) and isinstance(event, MouseEvent): tree = event.getSource() path = tree.getPathForLocation(event.getX(), event.getY()) userData = path.getLastPathComponent().getUserObject() if isinstance(userData, TreeNodeData) and (not userData.getNodeType().isType( [NodeType._comment, NodeType._menu ])) and (userData.getVisible() > 0): return True return False def shouldSelectCell(self, event): # log.info("shouldSelectCell") return True def cancelCellEditing(self): # log.info("Cancel editing, please!") # super(CustomCellEditor, self).cancelCellEditing() pass def stopCellEditing(self): # log.info("stopCellEditing") if self.nodeData.getNodeType().isType([NodeType._text]): # log.info("stopCellEditing for sure!") self.nodeData.setValue(str(self.tf.getText())) return True def getTreeCellEditorComponent(self, tree, value, selected, expanded, leaf, row): """Return a swing edit control appropriate for the node type of the supplied value""" self.nodeData = self.getNodeUserData(value) if self.nodeData: text = self.nodeData.getText() t = self.nodeData.getNodeType() # Boolean checkbox if t.isType([NodeType._bool]): self.editor = self.cbPanel self.cbLabel.setText(text) if self.nodeData.getTriValue() > 0: self.cb.setSelected(True) else: self.cb.setSelected(False) # Tristate checkbox elif t.isType([NodeType._tri]): # log.info("getTreeCellEditorComponent tristate") self.editor = self.tcbPanel self.tcbLabel.setText(text) self.tcb.setTriState(self.nodeData.getTriValue()) # Radio button elif t.isType([NodeType._radio]): self.editor = self.rbPanel self.rbLabel.setText(text) if self.nodeData.getTriValue() > 0: self.rb.setSelected(True) else: self.rb.setSelected(False) # Text field elif t.isType([NodeType._text]): self.editor = self.tfPanel self.tfLabel.setText(str(self.nodeData.getText()) + ":") self.tf.setText(str(self.nodeData.getValue())) else: self.editor = self.tcb self.editor.setText(text) return self.editor def getNodeUserData(self, value): """Gets the TreeNodeData from the tree node""" if isinstance(value, DefaultMutableTreeNode): nodeData = value.getUserObject() if isinstance(nodeData, TreeNodeData): return nodeData return None def getCellEditorValue(self): newNode = TreeNodeData(self.nodeData.knode, self.tree) if isinstance(self.editor, JTextField): newNode.setValue(str(self.editor.getText())) return newNode def checked(self, e): """Updates the node data when a checkbox has been clicked""" control = e.getSource() if isinstance(control, TristateCheckBox): # log.info("tristate checked") self.nodeData.setTriValue(control.getTriState()) else: # log.info("checkbox checked") if control.isSelected(): self.nodeData.setValue(2) else: self.nodeData.setValue(0) def actionPerformed(self, event): """ ENTER pressed in text field, stop editing.""" tf = event.getSource() self.listener.editingStopped(ChangeEvent(tf))
def launchGui(self, caller): self._stdout = PrintWriter(self._callbacks.getStdout(), True) self._stdout.println('Launching gui') callMessage = caller.getSelectedMessages() self.msg1 = callMessage[0] #setup frame self.frame = JFrame('Create Issue', windowClosing=self.closeUI) Border = BorderFactory.createLineBorder(Color.BLACK) #create split panel to add issue panel and template panel self.splitPane = JSplitPane(JSplitPane.HORIZONTAL_SPLIT) self.frame.add(self.splitPane) #panel setup and add to splitPane self.issuePanel = JPanel(GridLayout(0,2)) self.splitPane.setLeftComponent(self.issuePanel) #setup issue name text fields to add to panel self.issueNameField = JTextField('',15) self.issueNameLabel = JLabel("IssueName:", SwingConstants.CENTER) self.issuePanel.add(self.issueNameLabel) self.issuePanel.add(self.issueNameField) #add issue detail text area self.issueDetailField = JTextArea() self.issueDetailField.editable = True self.issueDetailField.wrapStyleWord = True self.issueDetailField.lineWrap = True self.issueDetailField.alignmentX = Component.LEFT_ALIGNMENT self.issueDetailField.size = (200, 20) self.issueDetailField.setBorder(Border) self.idfSp = JScrollPane() self.idfSp.getViewport().setView((self.issueDetailField)) self.issuePanel.add(JLabel("Issue Detail:", SwingConstants.CENTER)) self.issuePanel.add(self.idfSp) self.issueBackgroundField= JTextArea() self.issueBackgroundField.editable = True self.issueBackgroundField.wrapStyleWord = True self.issueBackgroundField.lineWrap = True self.issueBackgroundField.alignmentX = Component.LEFT_ALIGNMENT self.issueBackgroundField.size = (200, 20) self.issueBackgroundField.setBorder(Border) self.ibfSp = JScrollPane() self.ibfSp.getViewport().setView((self.issueBackgroundField)) self.issuePanel.add(JLabel("Issue Background:", SwingConstants.CENTER)) self.issuePanel.add(self.ibfSp) #add remediation detail text area self.remediationDetailField = JTextArea() self.remediationDetailField.editable = True self.remediationDetailField.wrapStyleWord = True self.remediationDetailField.lineWrap = True self.remediationDetailField.alignmentX = Component.LEFT_ALIGNMENT self.remediationDetailField.size = (200, 20) self.remediationDetailField.setBorder(Border) self.rdfSp = JScrollPane() self.rdfSp.getViewport().setView((self.remediationDetailField)) self.issuePanel.add(JLabel("Remediation Detail:", SwingConstants.CENTER)) self.issuePanel.add(self.rdfSp) self.remediationBackgroundField= JTextArea() self.remediationBackgroundField.editable = True self.remediationBackgroundField.wrapStyleWord = True self.remediationBackgroundField.lineWrap = True self.remediationBackgroundField.alignmentX = Component.LEFT_ALIGNMENT self.remediationBackgroundField.size = (200, 20) self.remediationBackgroundField.setBorder(Border) self.rbfSp = JScrollPane() self.rbfSp.getViewport().setView((self.remediationBackgroundField)) self.issuePanel.add(JLabel("Remediation Background:", SwingConstants.CENTER)) self.issuePanel.add(self.rbfSp) #add radio buttons for severity self.radioBtnSevHigh = JRadioButton('High', actionPerformed=None) self.radioBtnSevMedium = JRadioButton('Medium', actionPerformed=None) self.radioBtnSevLow = JRadioButton('Low', actionPerformed=None) severityButtonGroup = ButtonGroup() severityButtonGroup.add(self.radioBtnSevHigh) severityButtonGroup.add(self.radioBtnSevMedium) severityButtonGroup.add(self.radioBtnSevLow) self.radioBtnSevHigh.setSelected(True) self.issuePanel.add(JLabel("Severity:", SwingConstants.CENTER)) self.issuePanel.add(self.radioBtnSevHigh) self.issuePanel.add(self.radioBtnSevMedium) self.issuePanel.add(self.radioBtnSevLow) self.reqPattern = JTextField('',15) self.issuePanel.add(JLabel("Mark Pattern in Request:", SwingConstants.CENTER)) self.issuePanel.add(self.reqPattern) self.resPattern = JTextField('',15) self.issuePanel.add(JLabel("Mark Pattern in Response:", SwingConstants.CENTER)) self.issuePanel.add(self.resPattern) #add a button self.issueButton = JButton('Add!', actionPerformed=lambda x, m=self.msg1: self.logScanIssue(m)) self.issuePanel.add(self.issueButton) #template panel setup self.templatePanel = JPanel(GridLayout(1,2)) self.splitPane.setRightComponent(self.templatePanel) #add a list of templates self.templatePanel.add(JLabel("Select from Templates", SwingConstants.CENTER)) self.templateData = tuple(self.tmpl.keys()) self.templateList = JList(self.templateData) self.templateScrollPane = JScrollPane() #self.templateScrollPane.setPreferredSize(Dimension(100,125)) self.templateScrollPane.getViewport().setView((self.templateList)) self.templatePanel.add(self.templateScrollPane) self.templateButton = JButton('Apply', actionPerformed=self.applyTemplate) self.templatePanel.add(self.templateButton) #pack up the frame and display it self.frame.pack() self.show()
def createRadioButton(name, ac, ap): button = JRadioButton(name, actionPerformed=ap) button.setActionCommand(ac) return button
class BurpExtender(IBurpExtender, ITab, IScannerCheck, IScannerInsertionPoint, IContextMenuFactory): # definitions EXTENSION_NAME="IssueCreator" tmpl = dict() tmpl['XSS'] = dict() tmpl['XSS']['name'] = 'Cross-Site Scripting (reflected)' tmpl['XSS']['idetail'] = 'It is possible to inject arbitrary JavaScript into the application\'s response' tmpl['XSS']['ibackground'] = '''Reflected cross-site scripting vulnerabilities arise when data is copied from a request and echoed into the application's immediate response in an unsafe way. An attacker can use the vulnerability to construct a request which, if issued by another application user, will cause JavaScript code supplied by the attacker to execute within the user's browser in the context of that user's session with the application. The attacker-supplied code can perform a wide variety of actions, such as stealing the victim's session token or login credentials, performing arbitrary actions on the victim's behalf, and logging their keystrokes. Users can be induced to issue the attacker's crafted request in various ways. For example, the attacker can send a victim a link containing a malicious URL in an email or instant message. They can submit the link to popular web sites that allow content authoring, for example in blog comments. And they can create an innocuous looking web site which causes anyone viewing it to make arbitrary cross-domain requests to the vulnerable application (using either the GET or the POST method). The security impact of cross-site scripting vulnerabilities is dependent upon the nature of the vulnerable application, the kinds of data and functionality which it contains, and the other applications which belong to the same domain and organization. If the application is used only to display non-sensitive public content, with no authentication or access control functionality, then a cross-site scripting flaw may be considered low risk. However, if the same application resides on a domain which can access cookies for other more security-critical applications, then the vulnerability could be used to attack those other applications, and so may be considered high risk. Similarly, if the organization which owns the application is a likely target for phishing attacks, then the vulnerability could be leveraged to lend credibility to such attacks, by injecting Trojan functionality into the vulnerable application, and exploiting users' trust in the organization in order to capture credentials for other applications which it owns. In many kinds of application, such as those providing online banking functionality, cross-site scripting should always be considered high risk. ''' tmpl['XSS']['rdetail'] = ''''Input should be validated as strictly as possible on arrival, given the kind of content which it is expected to contain. For example, personal names should consist of alphabetical and a small range of typographical characters, and be relatively short; a year of birth should consist of exactly four numerals; email addresses should match a well-defined regular expression. Input which fails the validation should be rejected, not sanitized. User input should be HTML-encoded at any point where it is copied into application responses. All HTML metacharacters, including < > " ' and =, should be replaced with the corresponding HTML entities (< > etc). In cases where the application's functionality allows users to author content using a restricted subset of HTML tags and attributes (for example, blog comments which allow limited formatting and linking), it is necessary to parse the supplied HTML to validate that it does not use any dangerous syntax; this is a non-trivial task. ''' tmpl['XSS']['rbackground'] = 'do not trust user input!' tmpl['SQLi'] = dict() tmpl['SQLi']['name'] = 'SQL Injection' tmpl['SQLi']['idetail'] = 'Input parameter appears to be vulnerable to SQL injection attacks.' tmpl['SQLi']['ibackground'] = '''SQL injection vulnerabilities arise when user-controllable data is incorporated into database SQL queries in an unsafe manner. An attacker can supply crafted input to break out of the data context in which their input appears and interfere with the structure of the surrounding query. Various attacks can be delivered via SQL injection, including reading or modifying critical application data, interfering with application logic, escalating privileges within the database and executing operating system commands. ''' tmpl['SQLi']['rdetail'] = '''The most effective way to prevent SQL injection attacks is to use parameterized queries (also known as prepared statements) for all database access. This method uses two steps to incorporate potentially tainted data into SQL queries: first, the application specifies the structure of the query, leaving placeholders for each item of user input; second, the application specifies the contents of each placeholder. Because the structure of the query has already defined in the first step, it is not possible for malformed data in the second step to interfere with the query structure. You should review the documentation for your database and application platform to determine the appropriate APIs which you can use to perform parameterized queries. It is strongly recommended that you parameterize every variable data item that is incorporated into database queries, even if it is not obviously tainted, to prevent oversights occurring and avoid vulnerabilities being introduced by changes elsewhere within the code base of the application. ''' tmpl['SQLi']['rbackground'] = 'SQL Injection background' tmpl['Insecure-Cookie'] = dict() tmpl['Insecure-Cookie']['name'] = 'Cookie Was Set Without Secure Flag' tmpl['Insecure-Cookie']['idetail'] = 'Application has set a secure cookie without the secure attribute' tmpl['Insecure-Cookie']['ibackground'] = 'Client will send this cookie over the clear via http. This could be eavesdropped on.' tmpl['Insecure-Cookie']['rdetail'] = 'The application should set all cookies that are session related or sensitive in nature with the secure attribute.' tmpl['Insecure-Cookie']['rbackground'] = '...' tmpl['Your-Item'] = dict() tmpl['Your-Item']['name'] = 'My issue name' tmpl['Your-Item']['idetail'] = 'My issue detail' tmpl['Your-Item']['ibackground'] = 'the issue background here' tmpl['Your-Item']['rdetail'] = '''the remediation detail. i'll put this in triple quotes. because. ''' tmpl['Your-Item']['rbackground'] = 'this is remediation background information for my issue' def registerExtenderCallbacks(self, callbacks): # keep a reference to our callbacks object self._callbacks = callbacks # obtain an extension helpers object self._helpers = callbacks.getHelpers() # define stdout writer self._stdout = PrintWriter(callbacks.getStdout(), True) self._stdout.println(self.EXTENSION_NAME + ' by @luxcupitor') self._stdout.println('================================') self._stdout.println('') self._stdout.println('TIP: right click on items in proxy or repeater tab') self._stdout.println('and select "Add as Issue to Scanner".') self._stdout.println('') # set our extension name callbacks.setExtensionName(self.EXTENSION_NAME) # setup a context menu for the proxy tab. needs createMenuItems callbacks.registerContextMenuFactory(self) return def createMenuItems(self, caller): '''caller is the burpsuite context that invoked the menu''' menu = [] #Proxy tab is context 6/repeater request is 0/repeater response is 3 idx = caller.getInvocationContext() if idx == 6 or idx == 0 or idx == 3: menu.append(JMenuItem("Add as Issue to Scanner", None, actionPerformed=lambda x, c=caller: self.launchGui(c))) return menu if menu else None def getMatches(self, response, match): '''This finds our pattern match in the request/response and returns an int array''' start = 0 count = 0 matches = [array('i')] while start < len(response): start=self._helpers.indexOf(response, match, True, start, len(response)) if start == -1: break try: matches[count] except: matches.append(array('i')) matches[count].append(start) matches[count].append(start+len(match)) start += len(match) count += 1 return matches def logScanIssue(self, baseRequestResponse): '''This is redundant (mostly) of the doPassiveScan function''' reqPATTERN=self.reqPattern.text resPATTERN=self.resPattern.text ISSUE_NAME=self.issueNameField.text ISSUE_DETAIL=self.issueDetailField.text ISSUE_BACKGROUND=self.issueBackgroundField.text REMEDIATION_BACKGROUND=self.remediationBackgroundField.text REMEDIATION_DETAIL=self.remediationDetailField.text if self.radioBtnSevHigh.isSelected(): SEVERITY="High" elif self.radioBtnSevMedium.isSelected(): SEVERITY="Medium" else: SEVERITY="Low" CONFIDENCE="Certain" self._stdout = PrintWriter(self._callbacks.getStdout(), True) self._stdout.println('logScanIssue has been called') self._stdout.println('[-] ISSUE_NAME: ' + ISSUE_NAME) self._stdout.println('[-] ISSUE_DETAIL: ' + ISSUE_DETAIL) self._stdout.println('[-] ISSUE_BACKGROUND: ' + ISSUE_BACKGROUND) self._stdout.println('[-] REMEDIATION_DETAIL: ' + REMEDIATION_DETAIL) self._stdout.println('[-] REMEDIATION_BACKGROUND: ' + REMEDIATION_BACKGROUND) self._stdout.println('[-] SEVERITY: ' + SEVERITY) self._stdout.println('[-] CONFIDENCE: ' + CONFIDENCE) match = False if reqPATTERN == "": reqmatch = None else: reqmatch = self.getMatches(baseRequestResponse.getRequest(), reqPATTERN) match = True if resPATTERN == "": resmatch = None else: resmatch = self.getMatches(baseRequestResponse.getResponse(), resPATTERN) match = True if match: httpmsgs = [self._callbacks.applyMarkers(baseRequestResponse,reqmatch,resmatch)] issue=ScanIssue(baseRequestResponse.getHttpService(), self._helpers.analyzeRequest(baseRequestResponse).getUrl(), httpmsgs, ISSUE_NAME, ISSUE_DETAIL, SEVERITY, CONFIDENCE, ISSUE_BACKGROUND, REMEDIATION_DETAIL, REMEDIATION_BACKGROUND) self._callbacks.addScanIssue(issue) self.closeUI(None) return def launchGui(self, caller): self._stdout = PrintWriter(self._callbacks.getStdout(), True) self._stdout.println('Launching gui') callMessage = caller.getSelectedMessages() self.msg1 = callMessage[0] #setup frame self.frame = JFrame('Create Issue', windowClosing=self.closeUI) Border = BorderFactory.createLineBorder(Color.BLACK) #create split panel to add issue panel and template panel self.splitPane = JSplitPane(JSplitPane.HORIZONTAL_SPLIT) self.frame.add(self.splitPane) #panel setup and add to splitPane self.issuePanel = JPanel(GridLayout(0,2)) self.splitPane.setLeftComponent(self.issuePanel) #setup issue name text fields to add to panel self.issueNameField = JTextField('',15) self.issueNameLabel = JLabel("IssueName:", SwingConstants.CENTER) self.issuePanel.add(self.issueNameLabel) self.issuePanel.add(self.issueNameField) #add issue detail text area self.issueDetailField = JTextArea() self.issueDetailField.editable = True self.issueDetailField.wrapStyleWord = True self.issueDetailField.lineWrap = True self.issueDetailField.alignmentX = Component.LEFT_ALIGNMENT self.issueDetailField.size = (200, 20) self.issueDetailField.setBorder(Border) self.idfSp = JScrollPane() self.idfSp.getViewport().setView((self.issueDetailField)) self.issuePanel.add(JLabel("Issue Detail:", SwingConstants.CENTER)) self.issuePanel.add(self.idfSp) self.issueBackgroundField= JTextArea() self.issueBackgroundField.editable = True self.issueBackgroundField.wrapStyleWord = True self.issueBackgroundField.lineWrap = True self.issueBackgroundField.alignmentX = Component.LEFT_ALIGNMENT self.issueBackgroundField.size = (200, 20) self.issueBackgroundField.setBorder(Border) self.ibfSp = JScrollPane() self.ibfSp.getViewport().setView((self.issueBackgroundField)) self.issuePanel.add(JLabel("Issue Background:", SwingConstants.CENTER)) self.issuePanel.add(self.ibfSp) #add remediation detail text area self.remediationDetailField = JTextArea() self.remediationDetailField.editable = True self.remediationDetailField.wrapStyleWord = True self.remediationDetailField.lineWrap = True self.remediationDetailField.alignmentX = Component.LEFT_ALIGNMENT self.remediationDetailField.size = (200, 20) self.remediationDetailField.setBorder(Border) self.rdfSp = JScrollPane() self.rdfSp.getViewport().setView((self.remediationDetailField)) self.issuePanel.add(JLabel("Remediation Detail:", SwingConstants.CENTER)) self.issuePanel.add(self.rdfSp) self.remediationBackgroundField= JTextArea() self.remediationBackgroundField.editable = True self.remediationBackgroundField.wrapStyleWord = True self.remediationBackgroundField.lineWrap = True self.remediationBackgroundField.alignmentX = Component.LEFT_ALIGNMENT self.remediationBackgroundField.size = (200, 20) self.remediationBackgroundField.setBorder(Border) self.rbfSp = JScrollPane() self.rbfSp.getViewport().setView((self.remediationBackgroundField)) self.issuePanel.add(JLabel("Remediation Background:", SwingConstants.CENTER)) self.issuePanel.add(self.rbfSp) #add radio buttons for severity self.radioBtnSevHigh = JRadioButton('High', actionPerformed=None) self.radioBtnSevMedium = JRadioButton('Medium', actionPerformed=None) self.radioBtnSevLow = JRadioButton('Low', actionPerformed=None) severityButtonGroup = ButtonGroup() severityButtonGroup.add(self.radioBtnSevHigh) severityButtonGroup.add(self.radioBtnSevMedium) severityButtonGroup.add(self.radioBtnSevLow) self.radioBtnSevHigh.setSelected(True) self.issuePanel.add(JLabel("Severity:", SwingConstants.CENTER)) self.issuePanel.add(self.radioBtnSevHigh) self.issuePanel.add(self.radioBtnSevMedium) self.issuePanel.add(self.radioBtnSevLow) self.reqPattern = JTextField('',15) self.issuePanel.add(JLabel("Mark Pattern in Request:", SwingConstants.CENTER)) self.issuePanel.add(self.reqPattern) self.resPattern = JTextField('',15) self.issuePanel.add(JLabel("Mark Pattern in Response:", SwingConstants.CENTER)) self.issuePanel.add(self.resPattern) #add a button self.issueButton = JButton('Add!', actionPerformed=lambda x, m=self.msg1: self.logScanIssue(m)) self.issuePanel.add(self.issueButton) #template panel setup self.templatePanel = JPanel(GridLayout(1,2)) self.splitPane.setRightComponent(self.templatePanel) #add a list of templates self.templatePanel.add(JLabel("Select from Templates", SwingConstants.CENTER)) self.templateData = tuple(self.tmpl.keys()) self.templateList = JList(self.templateData) self.templateScrollPane = JScrollPane() #self.templateScrollPane.setPreferredSize(Dimension(100,125)) self.templateScrollPane.getViewport().setView((self.templateList)) self.templatePanel.add(self.templateScrollPane) self.templateButton = JButton('Apply', actionPerformed=self.applyTemplate) self.templatePanel.add(self.templateButton) #pack up the frame and display it self.frame.pack() self.show() def applyTemplate(self, event): selected = self.templateList.selectedIndex if selected >= 0: self.issueNameField.text = self.tmpl[self.templateData[selected]]['name'] self.issueDetailField.text = self.tmpl[self.templateData[selected]]['idetail'] self.issueBackgroundField.text = self.tmpl[self.templateData[selected]]['ibackground'] self.remediationDetailField.text = self.tmpl[self.templateData[selected]]['rdetail'] self.remediationBackgroundField.text = self.tmpl[self.templateData[selected]]['rbackground'] def show(self): self.frame.visible = True def closeUI(self, event): self.frame.setVisible(False) self.frame.dispose()
def getUiComponent(self): aws_access_key_id = self.callbacks.loadExtensionSetting( "aws_access_key_id") aws_secret_accesskey = self.callbacks.loadExtensionSetting( "aws_secret_access_key") if aws_access_key_id: self.aws_access_key_id = aws_access_key_id if aws_secret_accesskey: self.aws_secret_accesskey = aws_secret_accesskey self.panel = JPanel() self.main = JPanel() self.main.setLayout(BoxLayout(self.main, BoxLayout.Y_AXIS)) self.access_key_panel = JPanel() self.main.add(self.access_key_panel) self.access_key_panel.setLayout( BoxLayout(self.access_key_panel, BoxLayout.X_AXIS)) self.access_key_panel.add(JLabel('Access Key: ')) self.access_key = JTextField(self.aws_access_key_id, 25) self.access_key_panel.add(self.access_key) self.secret_key_panel = JPanel() self.main.add(self.secret_key_panel) self.secret_key_panel.setLayout( BoxLayout(self.secret_key_panel, BoxLayout.X_AXIS)) self.secret_key_panel.add(JLabel('Secret Key: ')) self.secret_key = JPasswordField(self.aws_secret_accesskey, 25) self.secret_key_panel.add(self.secret_key) self.target_host_panel = JPanel() self.main.add(self.target_host_panel) self.target_host_panel.setLayout( BoxLayout(self.target_host_panel, BoxLayout.X_AXIS)) self.target_host_panel.add(JLabel('Target host: ')) self.target_host = JTextField('ifconfig.io', 25) self.target_host_panel.add(self.target_host) self.buttons_panel = JPanel() self.main.add(self.buttons_panel) self.buttons_panel.setLayout( BoxLayout(self.buttons_panel, BoxLayout.X_AXIS)) self.save_button = JButton('Save Keys', actionPerformed=self.saveKeys) self.buttons_panel.add(self.save_button) self.enable_button = JButton('Enable', actionPerformed=self.enableGateway) self.buttons_panel.add(self.enable_button) self.disable_button = JButton('Disable', actionPerformed=self.disableGateway) self.buttons_panel.add(self.disable_button) self.disable_button.setEnabled(False) self.protocol_panel = JPanel() self.main.add(self.protocol_panel) self.protocol_panel.setLayout( BoxLayout(self.protocol_panel, BoxLayout.Y_AXIS)) self.protocol_panel.add(JLabel("Target Protocol:")) self.https_button = JRadioButton("HTTPS", True) self.http_button = JRadioButton("HTTP", False) self.protocol_panel.add(self.http_button) self.protocol_panel.add(self.https_button) buttongroup = ButtonGroup() buttongroup.add(self.https_button) buttongroup.add(self.http_button) self.regions_title = JPanel() self.main.add(self.regions_title) self.regions_title.add(JLabel("Regions to launch API Gateways in:")) self.regions_panel = JPanel() self.main.add(self.regions_panel) glayout = GridLayout(4, 3) self.regions_panel.setLayout(glayout) for region in AVAIL_REGIONS: cur_region = region.replace('-', '_') cur_region = cur_region + '_status' if cur_region.startswith( "ap") and cur_region != 'ap_east_1_status': setattr(self, cur_region, JCheckBox(region, True)) else: setattr(self, cur_region, JCheckBox(region, False)) attr = getattr(self, cur_region) self.regions_panel.add(attr) self.status = JPanel() self.main.add(self.status) self.status.setLayout(BoxLayout(self.status, BoxLayout.X_AXIS)) self.status_indicator = JLabel(DISABLED, JLabel.CENTER) self.status.add(self.status_indicator) self.panel.add(self.main) return self.panel
class InductionApplet(JApplet): def init(self): global exampleList self.thinFont = Font("Dialog", 0, 10) self.pane = self.getContentPane() self.examples = exampleList.keys() self.examples.sort() self.exampleSelector = JList(self.examples, valueChanged=self.valueChanged) self.exampleSelector.setSelectionMode(ListSelectionModel.SINGLE_SELECTION) self.exampleSelector.setLayoutOrientation(JList.VERTICAL) self.exampleSelector.setPreferredSize(Dimension(150,500)) self.exampleSelector.setBackground(Color(0.95, 0.95, 0.98)) self.exampleSelector.setFont(self.thinFont) self.centerPanel = JPanel(BorderLayout()) self.canvas = GraphCanvas() self.canvas.setApplet(self) self.buttonRow = JPanel(FlowLayout()) self.backButton = JButton("<", actionPerformed = self.backAction) self.backButton.setFont(self.thinFont) self.continueButton = JButton("continue >", actionPerformed=self.continueAction) self.continueButton.setFont(self.thinFont) self.scaleGroup = ButtonGroup() self.linearButton = JRadioButton("linear scale", actionPerformed=self.linearAction) self.linearButton.setSelected(True) self.linearButton.setFont(self.thinFont) self.logarithmicButton = JRadioButton("logarithmic scale", actionPerformed=self.logarithmicAction) self.logarithmicButton.setFont(self.thinFont) self.aboutButton = JButton("About...", actionPerformed=self.aboutAction) self.aboutButton.setFont(self.thinFont) self.scaleGroup.add(self.linearButton) self.scaleGroup.add(self.logarithmicButton) self.buttonRow.add(self.backButton) self.buttonRow.add(self.continueButton) self.buttonRow.add(JLabel(" "*5)) self.buttonRow.add(self.linearButton) self.buttonRow.add(self.logarithmicButton) self.buttonRow.add(JLabel(" "*20)); self.buttonRow.add(self.aboutButton) self.centerPanel.add(self.canvas, BorderLayout.CENTER) self.centerPanel.add(self.buttonRow, BorderLayout.PAGE_END) self.helpText = JTextPane() self.helpText.setBackground(Color(1.0, 1.0, 0.5)) self.helpText.setPreferredSize(Dimension(800,80)) self.helpText.setText(re_sub("[ \\n]+", " ", """ Please select one of the examples in the list on the left! """)) self.pane.add(self.exampleSelector, BorderLayout.LINE_START) self.pane.add(self.centerPanel, BorderLayout.CENTER) self.pane.add(self.helpText, BorderLayout.PAGE_END) self.graph = None self.simulation = None self.touched = "" self.selected = "" self.gfxDriver = None def start(self): self.gfxDriver = awtGfx.Driver(self.canvas) #self.gfxDriver.setAntialias(True) if self.gfxDriver.getSize()[0] < 200: # konqueror java bug work around self.gfxDriver.w = 650 self.gfxDriver.h = 380 self.graph = Graph.Cartesian(self.gfxDriver, 1, 0.0, 1000, 1.0, title="Results", xaxis="Rounds", yaxis="Success Rate") def stop(self): pass def destroy(self): pass def refresh(self): if self.graph != None: self.graph.redraw() def valueChanged(self, e): global exampleList newSelection = self.examples[self.exampleSelector.getSelectedIndex()] if newSelection != self.touched: self.touched = newSelection text = re_sub("[ \\n]+", " ", exampleList[self.touched][-1]) self.helpText.setText(text) if not e.getValueIsAdjusting() and newSelection != self.selected: self.selected = newSelection smallFontPen = copy.copy(Gfx.BLACK_PEN) smallFontPen.fontSize = Gfx.SMALL ex = exampleList[self.selected] myStyleFlags = self.graph.styleFlags if self.simulation != None: self.simulation.stop() self.gfxDriver.resizedGfx() # konqueror 3.5.5 java bug workaround self.graph = Graph.Cartesian(self.gfxDriver, 1, 0.0, ex[3], 1.0, title=ex[0], xaxis="Rounds", yaxis="Success Rate", styleFlags = myStyleFlags, axisPen = smallFontPen, captionPen = smallFontPen) self.zoomFrame = [(1, 0.0, ex[3], 1.0)] self.simulation = Simulation(self.graph, ex[1], ex[2], ex[3], ex[4]) RunAsThread(self.simulation.simulation).start() def determineCurrentZoomFrame(self): i = 0 for zf in self.zoomFrame: if self.graph.x2 <= zf[2]: break i += 1 return i def backAction(self, e): if self.simulation == None: return wasRunning = self.simulation.isRunning self.simulation.stop() if wasRunning or len(self.zoomFrame) <= 1: return zi = self.determineCurrentZoomFrame() if zi > 0 and zi < len(self.zoomFrame): x1, y1, x2, y2 = self.zoomFrame[zi-1] self.graph.adjustRange(x1, y1, x2, y2) def continueAction(self, e): if self.simulation == None: return wasRunning = self.simulation.isRunning self.simulation.stop() zi = self.determineCurrentZoomFrame() if zi == len(self.zoomFrame)-1: if wasRunning or self.simulation.world.round == self.zoomFrame[zi][2]: if self.graph.styleFlags & Graph.LOG_X == 0: self.simulation.rounds *= 2 else: self.simulation.rounds *= 10 self.zoomFrame.append((1, 0.0, self.simulation.rounds, 1.0)) self.graph.adjustRange(1, 0.0, self.simulation.rounds, 1.0) RunAsThread(self.simulation.simulation).start() else: x1, y1, x2, y2 = self.zoomFrame[zi+1] self.graph.adjustRange(x1, y1, x2, y2) def linearAction(self, e): if self.graph != None and (self.graph.styleFlags & Graph.LOG_X) != 0: if self.simulation != None: self.simulation.stop() self.graph.setStyle(self.graph.styleFlags & ~Graph.LOG_X, redraw=True) if self.simulation != None: RunAsThread(self.simulation.simulation).start() def logarithmicAction(self, e): if self.graph != None and (self.graph.styleFlags & Graph.LOG_X) == 0: if self.simulation != None: self.simulation.stop() self.graph.setStyle(self.graph.styleFlags | Graph.LOG_X, redraw=True) if self.simulation != None: RunAsThread(self.simulation.simulation).start() def aboutAction(self, e): aboutText = """Induction Applet v. 0.1 (c) 2007 University of Düsseldorf Authors: Gerhard Schurz, Eckhart Arnold """ aboutText = re_sub(" +", " ", aboutText) JOptionPane.showMessageDialog(self.getContentPane(), aboutText)