def build_combobox(self, choices, default): ''' Generic method to construct a combobox. choices should be an iterable of strings of the choices to be made and default should be a string which is equal to one of the values within the iterable. ''' combo = JComboBox() for choice in choices: combo.addItem(choice) combo.setSelectedItem(default) return combo
def build_servers_combobox(self): combo = JComboBox() # Go through list of servers and add to combo box. for server in self.servers.keys(): if server != "default": combo_item = "{}: {}:{}".format(server, self.servers[server]['url'], self.servers[server]['port']) combo.addItem(combo_item) # If this item is the default one, set it as selected if server == self.servers['default']: combo.setSelectedItem(combo_item) return combo
def initProfilesTable(self): profile_table = JTable() self.profile_table_model = self.ProfileTableModel() profile_table.setModel(self.profile_table_model) cm = profile_table.getColumnModel() # Set column widths for i in range(0, 4): width = self.profile_table_model.column_widths.get(i) if width is not None: column = cm.getColumn(i) column.setPreferredWidth(width) column.setMaxWidth(width) profile_table.setFillsViewportHeight(True) def doAction(event): print event # Add the actions dropdown actionCol = cm.getColumn(3) actions = JComboBox() actions.addItem("Activate") actions.addItem("Unactivate") actions.addItem("Edit") actions.addItem("Export to Script") actions.addItem("Delete") actionCol.setCellEditor(DefaultCellEditor(actions)) self.profile_table_model.actions_combo = actions renderer = self.ComboBoxTableCellRenderer() actionCol.setCellRenderer(renderer) actions.addActionListener(self.ComboActionListener(self)) return profile_table
class BeautifierPanel(JPanel): def __init__(self): super(BeautifierPanel, self).__init__() self.setLayout(BorderLayout()) self.beautifyTextArea = JTextArea(5, 10) self.beautifyTextArea.setLineWrap(True) self.beautifyTextArea.setDocument(self.CustomUndoPlainDocument()) # The undo doesn't work well before replace text. Below is rough fix, so not need to know how undo work for now self.beautifyTextArea.setText(" ") self.beautifyTextArea.setText("") self.undoManager = UndoManager() self.beautifyTextArea.getDocument().addUndoableEditListener( self.undoManager) self.beautifyTextArea.getDocument().addDocumentListener( self.BeautifyDocumentListener(self)) beautifyTextWrapper = JPanel(BorderLayout()) beautifyScrollPane = JScrollPane(self.beautifyTextArea) beautifyTextWrapper.add(beautifyScrollPane, BorderLayout.CENTER) self.add(beautifyTextWrapper, BorderLayout.CENTER) self.beautifyButton = JButton("Beautify") self.beautifyButton.addActionListener(self.beautifyListener) self.undoButton = JButton("Undo") self.undoButton.addActionListener(self.undoListener) formatLabel = JLabel("Format:") self.formatsComboBox = JComboBox() for f in supportedFormats: self.formatsComboBox.addItem(f) self.statusLabel = JLabel("Status: Ready") preferredDimension = self.statusLabel.getPreferredSize() self.statusLabel.setPreferredSize( Dimension(preferredDimension.width + 20, preferredDimension.height)) self.sizeLabel = JLabel("0 B") preferredDimension = self.sizeLabel.getPreferredSize() self.sizeLabel.setPreferredSize( Dimension(preferredDimension.width + 64, preferredDimension.height)) self.sizeLabel.setHorizontalAlignment(SwingConstants.RIGHT) buttonsPanel = JPanel(FlowLayout()) buttonsPanel.add(formatLabel) buttonsPanel.add(self.formatsComboBox) buttonsPanel.add(Box.createHorizontalStrut(10)) buttonsPanel.add(self.beautifyButton) buttonsPanel.add(self.undoButton) bottomPanel = JPanel(BorderLayout()) bottomPanel.add(self.statusLabel, BorderLayout.WEST) bottomPanel.add(buttonsPanel, BorderLayout.CENTER) bottomPanel.add(self.sizeLabel, BorderLayout.EAST) self.add(bottomPanel, BorderLayout.SOUTH) self.currentBeautifyThread = None class CustomUndoPlainDocument(PlainDocument): # Code from: https://stackoverflow.com/questions/24433089/jtextarea-settext-undomanager compoundEdit = CompoundEdit() def fireUndoableEditUpdate(self, e): if self.compoundEdit == None: super(BeautifierPanel.CustomUndoPlainDocument, self).fireUndoableEditUpdate(e) else: self.compoundEdit.addEdit(e.getEdit()) def replace(self, offset, length, text, attrs): if length == 0: super(BeautifierPanel.CustomUndoPlainDocument, self).replace(offset, length, text, attrs) else: self.compoundEdit = CompoundEdit() super(BeautifierPanel.CustomUndoPlainDocument, self).fireUndoableEditUpdate( UndoableEditEvent(self, self.compoundEdit)) super(BeautifierPanel.CustomUndoPlainDocument, self).replace(offset, length, text, attrs) self.compoundEdit.end() self.compoundEdit = None def setText(self, text): self.beautifyTextArea.setText(text) def setRunningState(self): self.beautifyButton.setText("Cancel") self.undoButton.setEnabled(False) self.statusLabel.setText("Status: Running") def setReadyState(self): self.beautifyButton.setText("Beautify") self.undoButton.setEnabled(True) self.statusLabel.setText("Status: Ready") class BeautifyDocumentListener(DocumentListener): def __init__(self, beautifierPanel): super(BeautifierPanel.BeautifyDocumentListener, self).__init__() self.beautifierPanel = beautifierPanel def removeUpdate(self, e): self.updateSizeLabel() def insertUpdate(self, e): self.updateSizeLabel() def changedUpdate(self, e): pass def updateSizeLabel(self): length = len(self.beautifierPanel.beautifyTextArea.getText()) if length >= 1024: length = "%.2f KB" % (length / 1024.0) else: length = "%d B" % length self.beautifierPanel.sizeLabel.setText(length) def beautifyListener(self, e): selectedFormat = self.formatsComboBox.getSelectedItem() data = self.beautifyTextArea.getText( ) # variable "data" is "unicode" type if self.currentBeautifyThread and self.currentBeautifyThread.isAlive(): # TODO Need a graceful way to shutdown running beautify thread. self.currentBeautifyThread.callback = None self.currentBeautifyThread = None self.setReadyState() else: self.currentBeautifyThread = None self.setRunningState() def beautifyCallback(result): self.beautifyTextArea.setText(result) self.setReadyState() self.currentBeautifyThread = BeautifyThread( data, selectedFormat, beautifyCallback) self.currentBeautifyThread.start() def undoListener(self, e): if self.undoManager.canUndo(): self.undoManager.undo()
class GameSelector(ActionListener): """ generated source for class GameSelector """ theGameList = JComboBox() theRepositoryList = JComboBox() theSelectedRepository = GameRepository() theCachedRepositories = Map() class NamedItem(object): """ generated source for class NamedItem """ theKey = str() theName = str() def __init__(self, theKey, theName): """ generated source for method __init__ """ self.theKey = theKey self.theName = theName def __str__(self): """ generated source for method toString """ return self.theName def __init__(self): """ generated source for method __init__ """ super(GameSelector, self).__init__() self.theGameList = JComboBox() self.theGameList.addActionListener(self) self.theRepositoryList = JComboBox() self.theRepositoryList.addActionListener(self) self.theCachedRepositories = HashMap() self.theRepositoryList.addItem("games.ggp.org/base") self.theRepositoryList.addItem("games.ggp.org/dresden") self.theRepositoryList.addItem("games.ggp.org/stanford") self.theRepositoryList.addItem("Local Game Repository") def actionPerformed(self, e): """ generated source for method actionPerformed """ if e.getSource() == self.theRepositoryList: if self.theCachedRepositories.containsKey(theRepositoryName): self.theSelectedRepository = self.theCachedRepositories.get(theRepositoryName) else: if theRepositoryName == "Local Game Repository": self.theSelectedRepository = LocalGameRepository() else: self.theSelectedRepository = CloudGameRepository(theRepositoryName) self.theCachedRepositories.put(theRepositoryName, self.theSelectedRepository) repopulateGameList() def getSelectedGameRepository(self): """ generated source for method getSelectedGameRepository """ return self.theSelectedRepository def repopulateGameList(self): """ generated source for method repopulateGameList """ theRepository = self.getSelectedGameRepository() theKeyList = ArrayList(theRepository.getGameKeys()) Collections.sort(theKeyList) self.theGameList.removeAllItems() for theKey in theKeyList: if theGame == None: continue if theName == None: theName = theKey if 24 > len(theName): theName = theName.substring(0, 24) + "..." self.theGameList.addItem(self.NamedItem(theKey, theName)) def getRepositoryList(self): """ generated source for method getRepositoryList """ return self.theRepositoryList def getGameList(self): """ generated source for method getGameList """ return self.theGameList def getSelectedGame(self): """ generated source for method getSelectedGame """ try: return self.getSelectedGameRepository().getGame((self.theGameList.getSelectedItem()).theKey) except Exception as e: return None
class CustomTab(ITab): URL_NON_ENCODE_IDX = 0 URL_ENCODE_IDX = 1 def remove_element(self, evt): for item in self.cbList.getSelectedIndices()[::-1]: self.listModel.remove(item) def add_element(self, evt): self.listModel.addElement(self.cbText.getText()) self.cbText.setText("") def add_file(self, evt): fc = JFileChooser() ret = fc.showOpenDialog(self.tab) if ret == JFileChooser.APPROVE_OPTION: with open(fc.getSelectedFile().getCanonicalPath()) as fd: for line in fd: self.listModel.addElement(line) def clear_elements(self, evt): self.listModel.removeAllElements() def paste_elements(self, evt): data = getDefaultToolkit().getSystemClipboard().getData( DataFlavor.stringFlavor) for payload in StringIO.StringIO(data): if payload and not payload.isspace(): self.listModel.addElement(payload) def getOOBList(self): return self.listModel.toArray() def getURLEncoding(self): idx = self.cbDropDown.getSelectedIndex() if idx == self.URL_NON_ENCODE_IDX: return URLEncoding.NoEncoding elif idx == self.URL_ENCODE_IDX: return URLEncoding.Encoding else: return URLEncoding.Both def getTabCaption(self): return ("OOB") def getUiComponent(self): return self.tab def __init__(self): self.listModel = DefaultListModel() self.cbTitle = JLabel("Out-of-band Payloads") self.cbTitle.setFont(self.cbTitle.getFont().deriveFont(14.0)) self.cbTitle.setFont(self.cbTitle.getFont().deriveFont(Font.BOLD)) self.cbSubTitle = JLabel( "Add payloads to active scanner that interact " "with out-of-band services (e.g., XSSHunter)") self.cbSubTitle.setFont(self.cbSubTitle.getFont().deriveFont(12.0)) self.cbList = JList(self.listModel) self.cbList.setCellRenderer(ListRenderer()) self.cbList.setVisibleRowCount(10) self.listScrollPane = JScrollPane(self.cbList) self.cbText = JTextField(actionPerformed=self.add_element) self.cbRemoveButton = JButton("Remove", actionPerformed=self.remove_element) self.cbLoadButton = JButton("Load...", actionPerformed=self.add_file) self.cbPasteButton = JButton("Paste", actionPerformed=self.paste_elements) self.cbClearButton = JButton("Clear", actionPerformed=self.clear_elements) self.cbAddButton = JButton("Add", actionPerformed=self.add_element) self.cbDropDownLabel = JLabel("Payload Encoding: ") self.cbDropDown = JComboBox() self.cbDropDown.addItem("Non URL Encoded") self.cbDropDown.addItem("URL Encoded") self.cbDropDown.addItem("Both (two requests per payload)") self.grpOOB = JPanel() grpLayout = GroupLayout(self.grpOOB) self.grpOOB.setLayout(grpLayout) grpLayout.linkSize(SwingConstants.HORIZONTAL, self.cbRemoveButton, self.cbLoadButton, self.cbPasteButton, self.cbClearButton, self.cbAddButton) grpLayout.setAutoCreateGaps(True) grpLayout.setAutoCreateContainerGaps(True) grpLayout.setHorizontalGroup( grpLayout.createSequentialGroup().addGroup( grpLayout.createParallelGroup().addComponent( self.cbTitle).addGroup( grpLayout.createParallelGroup().addComponent( self.cbRemoveButton).addComponent( self.cbLoadButton).addComponent( self.cbPasteButton).addComponent( self.cbClearButton)).addComponent( self.cbAddButton). addComponent(self.cbDropDownLabel)).addGroup( grpLayout.createParallelGroup().addComponent( self.cbSubTitle).addComponent( self.listScrollPane).addComponent( self.cbText).addComponent(self.cbDropDown))) grpLayout.setVerticalGroup(grpLayout.createSequentialGroup().addGroup( grpLayout.createParallelGroup().addComponent(self.cbTitle) ).addGroup(grpLayout.createParallelGroup().addComponent( self.cbSubTitle)).addGroup( grpLayout.createParallelGroup().addGroup( grpLayout.createSequentialGroup().addComponent( self.cbPasteButton).addComponent( self.cbLoadButton).addComponent( self.cbRemoveButton).addComponent( self.cbClearButton)).addComponent( self.listScrollPane) ).addGroup(grpLayout.createParallelGroup().addComponent( self.cbAddButton).addComponent(self.cbText)).addGroup( grpLayout.createParallelGroup().addComponent( self.cbDropDownLabel).addComponent(self.cbDropDown))) # Tab Layout self.tab = JPanel() tabLayout = GroupLayout(self.tab) self.tab.setLayout(tabLayout) tabLayout.setAutoCreateGaps(True) tabLayout.setAutoCreateContainerGaps(True) tabLayout.setHorizontalGroup( tabLayout.createSequentialGroup().addGroup( tabLayout.createParallelGroup().addComponent( self.grpOOB, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE))) tabLayout.setVerticalGroup(tabLayout.createSequentialGroup().addGroup( tabLayout.createParallelGroup().addComponent( self.grpOOB, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE)))
class ConfigTab( ITab, JPanel ): def __init__( self, callbacks ): self._callbacks = callbacks self._helpers = callbacks.getHelpers() self.__initLayout__() def __initLayout__( self ): self._levelComboBox = JComboBox() levelComboBoxSize = Dimension( 300, 30 ) self._levelComboBox.setPreferredSize( levelComboBoxSize ) self._levelComboBox.setMaximumSize( levelComboBoxSize ) for level in range( 0, 6 ): self._levelComboBox.addItem( str( level ) ) self._techRenderedCheckBox = JCheckBox( 'Rendered', True ) self._techTimebasedCheckBox = JCheckBox( 'Time-based', True ) self._plugin_groups = {} for plugin in plugins: parent = plugin.__base__.__name__ if not self._plugin_groups.has_key( parent ): self._plugin_groups[ parent ] = [] self._plugin_groups[ parent ].append( plugin ) self._pluginCheckBoxes = [] for pluginGroup in self._plugin_groups.values(): for plugin in pluginGroup: self._pluginCheckBoxes.append( PluginCheckBox( plugin ) ) self._positionReplaceCheckBox = JCheckBox( 'Replace', True ) self._positionAppendCheckBox = JCheckBox( 'Append', False ) displayItems = ( { 'label': 'Level', 'components': ( self._levelComboBox, ), 'description': 'Level of code context escape to perform (1-5, Default:0).' }, { 'label': 'Techniques', 'components': ( self._techRenderedCheckBox, self._techTimebasedCheckBox, ), 'description': 'Techniques R(endered) T(ime-based blind). Default: RT.' }, { 'label': 'Template Engines', 'components': self._pluginCheckBoxes, 'description': 'Force back-end template engine to this value(s).' }, { 'label': 'Payload position', 'components': ( self._positionReplaceCheckBox, self._positionAppendCheckBox, ), 'description': 'Scan payload position. This feature only appears in BurpExtension.' } ) layout = GroupLayout( self ) self.setLayout( layout ) layout.setAutoCreateGaps( True ) layout.setAutoCreateContainerGaps( True ) labelWidth = 200 hgroup = layout.createParallelGroup( GroupLayout.Alignment.LEADING ) vgroup = layout.createSequentialGroup() for displayItem in displayItems: label = JLabel( displayItem.get( 'label' ) ) label.setToolTipText( displayItem.get( 'description' ) ) _hgroup = layout.createSequentialGroup().addComponent( label, labelWidth, labelWidth, labelWidth ) _vgroup = layout.createParallelGroup( GroupLayout.Alignment.BASELINE ).addComponent( label ) for component in displayItem.get( 'components' ): _hgroup.addComponent( component ) _vgroup.addComponent( component ) hgroup.addGroup( _hgroup ) vgroup.addGroup( _vgroup ) layout.setHorizontalGroup( hgroup ) layout.setVerticalGroup( vgroup ) def getTabCaption( self ): return 'Tplmap' def getUiComponent( self ): return self def getLevel( self ): return self._levelComboBox.getSelectedIndex() def getTechniques( self ): return '%s%s' % ( 'R' if self._techRenderedCheckBox.isSelected() else '', 'T' if self._techTimebasedCheckBox.isSelected() else '' ) def getEngines( self ): return [ checkbox.getPlugin() for checkbox in self._pluginCheckBoxes if checkbox.isSelected() ] def getPayloadPosition( self ): return { 'replace': self._positionReplaceCheckBox.isSelected(), 'append': self._positionAppendCheckBox.isSelected() }
class ConfigTab(ITab, JPanel): def __init__(self, callbacks): self._callbacks = callbacks self._helpers = callbacks.getHelpers() self.__initLayout__() def __initLayout__(self): self._levelComboBox = JComboBox() levelComboBoxSize = Dimension(300, 30) self._levelComboBox.setPreferredSize(levelComboBoxSize) self._levelComboBox.setMaximumSize(levelComboBoxSize) for level in range(0, 6): self._levelComboBox.addItem(str(level)) self._techRenderedCheckBox = JCheckBox('Rendered', True) self._techTimebasedCheckBox = JCheckBox('Time-based', True) self._plugin_groups = {} for plugin in plugins: parent = plugin.__base__.__name__ if not self._plugin_groups.has_key(parent): self._plugin_groups[parent] = [] self._plugin_groups[parent].append(plugin) self._pluginCheckBoxes = [] for pluginGroup in self._plugin_groups.values(): for plugin in pluginGroup: self._pluginCheckBoxes.append(PluginCheckBox(plugin)) self._positionReplaceCheckBox = JCheckBox('Replace', True) self._positionAppendCheckBox = JCheckBox('Append', False) displayItems = ({ 'label': 'Level', 'components': (self._levelComboBox, ), 'description': 'Level of code context escape to perform (1-5, Default:0).' }, { 'label': 'Techniques', 'components': ( self._techRenderedCheckBox, self._techTimebasedCheckBox, ), 'description': 'Techniques R(endered) T(ime-based blind). Default: RT.' }, { 'label': 'Template Engines', 'components': self._pluginCheckBoxes, 'description': 'Force back-end template engine to this value(s).' }, { 'label': 'Payload position', 'components': ( self._positionReplaceCheckBox, self._positionAppendCheckBox, ), 'description': 'Scan payload position. This feature only appears in BurpExtension.' }) layout = GroupLayout(self) self.setLayout(layout) layout.setAutoCreateGaps(True) layout.setAutoCreateContainerGaps(True) labelWidth = 200 hgroup = layout.createParallelGroup(GroupLayout.Alignment.LEADING) vgroup = layout.createSequentialGroup() for displayItem in displayItems: label = JLabel(displayItem.get('label')) label.setToolTipText(displayItem.get('description')) _hgroup = layout.createSequentialGroup().addComponent( label, labelWidth, labelWidth, labelWidth) _vgroup = layout.createParallelGroup( GroupLayout.Alignment.BASELINE).addComponent(label) for component in displayItem.get('components'): _hgroup.addComponent(component) _vgroup.addComponent(component) hgroup.addGroup(_hgroup) vgroup.addGroup(_vgroup) layout.setHorizontalGroup(hgroup) layout.setVerticalGroup(vgroup) def getTabCaption(self): return 'Tplmap' def getUiComponent(self): return self def getLevel(self): return self._levelComboBox.getSelectedIndex() def getTechniques(self): return '%s%s' % ('R' if self._techRenderedCheckBox.isSelected( ) else '', 'T' if self._techTimebasedCheckBox.isSelected() else '') def getEngines(self): return [ checkbox.getPlugin() for checkbox in self._pluginCheckBoxes if checkbox.isSelected() ] def getPayloadPosition(self): return { 'replace': self._positionReplaceCheckBox.isSelected(), 'append': self._positionAppendCheckBox.isSelected() }
class BurpExtender(IBurpExtender, IScannerListener, ITab): def registerExtenderCallbacks(self, callbacks): self._callbacks = callbacks self.helpers = callbacks.helpers callbacks.setExtensionName("Orchy-Webhook") self.frame = JPanel() self.frame.setSize(1024, 786) self.frame.setLayout(None) self.plugin_path = os.getcwd() self.db_file_path = os.path.join(os.getcwd(), 'burp_db.json') self.cwe_dict = json.load(open(self.db_file_path, 'r')) self.results = {} self.severity_dict = { 'Low': 1, 'Medium': 2, 'High': 3, 'Information': 0, 'Info': 0, } self.urls = [] self.confidence_dict = {'Certain': 3, 'Firm': 2, 'Tentative': 1} callbacks.registerScannerListener(self) button1 = JButton(ImageIcon( ((ImageIcon(self.plugin_path + "/refresh.jpg")).getImage()).getScaledInstance( 13, 13, SCALE_SMOOTH)), actionPerformed=self.refresh) button1.setBounds(30, 50, 22, 22) lbl0 = JLabel("Orchestron Webhook:") lbl0.setFont(Font("", Font.BOLD, 12)) lbl0.setForeground(Color(0xFF7F50)) lbl0.setBounds(60, 20, 200, 20) lbl1 = JLabel('Host') lbl1.setBounds(60, 50, 100, 20) self.txt1 = JComboBox() self.txt1.setBounds(200, 50, 220, 24) lbl2 = JLabel("Webhook Url") lbl2.setBounds(60, 80, 100, 20) self.txt2 = JTextField('', 300) self.txt2.setBounds(200, 80, 220, 24) lbl3 = JLabel("Authorization Token") lbl3.setBounds(60, 110, 200, 20) self.txt3 = JTextField('', 60) self.txt3.setBounds(200, 110, 220, 24) lbl4 = JLabel("Engagement-ID") lbl4.setBounds(60, 140, 200, 20) self.txt4 = JTextField('', 40) self.txt4.setBounds(200, 140, 220, 24) button2 = JButton('Push Results', actionPerformed=self.push) button2.setBounds(200, 170, 120, 24) self.message = JLabel('') self.message.setBounds(330, 170, 180, 24) self.frame.add(button1) self.frame.add(lbl0) self.frame.add(lbl1) self.frame.add(self.txt1) self.frame.add(lbl2) self.frame.add(self.txt2) self.frame.add(lbl3) self.frame.add(self.txt3) self.frame.add(lbl4) self.frame.add(self.txt4) self.frame.add(button2) self.frame.add(self.message) callbacks.customizeUiComponent(self.frame) callbacks.addSuiteTab(self) def refresh(self, event): self.txt1.removeAllItems() for host in self.results.keys(): self.txt1.addItem(host) self.message.text = '' def newScanIssue(self, issue): callbacks = self._callbacks # print "New Issue Identified:"+issue.getUrl().toString() if callbacks.isInScope(issue.getUrl()) == 1: self.tmp = issue.getUrl() self.scheme = self.tmp.protocol self.port = self.tmp.port self.fqdn = self.tmp.host if self.port == -1: if self.scheme == 'https': self.port = 443 elif self.scheme == 'http': self.port = 80 else: self.scheme = 'http' self.port = 80 self.host = str(self.scheme + '://' + self.fqdn + ':' + str(self.port)) if not self.results: self.results[self.host] = {'scan_dict': {}} for host in self.results.keys(): if host == self.host: if str(issue.getIssueType()) in self.cwe_dict.keys(): name = self.cwe_dict.get(str(issue.getIssueType()), '')[1] cwe_id = self.cwe_dict.get(str(issue.getIssueType()), '')[0] else: name = 'Burp IssueType - {0}'.format( str(issue.getIssueType())) cwe_id = 0 if name in self.results[host]['scan_dict'].keys(): old_evidance = self.results[host]['scan_dict'][ name].get('evidences') for httpmessage in issue.getHttpMessages(): request = (httpmessage.getRequest().tostring() if httpmessage.getRequest() else None) request = b64encode(request.encode('utf-8')) response = (httpmessage.getResponse().tostring() if httpmessage.getResponse() else None) response = b64encode(response.encode('utf-8')) info_dict = { 'url': issue.getUrl().toString(), 'name': issue.getIssueName(), 'request': request, 'response': response } old_evidance.append(info_dict) else: severity = self.severity_dict.get( issue.getSeverity(), '') confidence = self.confidence_dict.get( issue.getConfidence(), '') evidences = [] for httpmessage in issue.getHttpMessages(): request = (httpmessage.getRequest().tostring() if httpmessage.getRequest() else None) request = b64encode(request.encode('utf-8')) response = (httpmessage.getResponse().tostring() if httpmessage.getResponse() else None) response = b64encode(response.encode('utf-8')) info_dict = { 'url': issue.getUrl().toString(), 'name': issue.getIssueName(), 'request': request, 'response': response } evidences.append(info_dict) self.results[host]['scan_dict'][name] = { 'description': issue.getIssueDetail(), 'remediation': '', 'severity': severity, 'cwe': cwe_id, 'evidences': evidences } else: self.results[self.host] = {'scan_dict': {}} if str(issue.getIssueType()) in self.cwe_dict.keys(): name = self.cwe_dict.get(str(issue.getIssueType()), '')[1] cwe_id = self.cwe_dict.get(str(issue.getIssueType()), '')[0] else: name = 'Burp IssueType - {0}'.format( str(issue.getIssueType())) cwe_id = 0 severity = self.severity_dict.get(issue.getSeverity(), '') confidence = self.confidence_dict.get( issue.getConfidence(), '') evidences = [] for httpmessage in issue.getHttpMessages(): request = (httpmessage.getRequest().tostring() if httpmessage.getRequest() else None) request = b64encode(request.encode('utf-8')) response = (httpmessage.getResponse().tostring() if httpmessage.getResponse() else None) response = b64encode(response.encode('utf-8')) info_dict = { 'url': issue.getUrl().toString(), 'name': issue.getIssueName(), 'request': request, 'response': response } evidences.append(info_dict) self.results[host]['scan_dict'][name] = { 'description': issue.getIssueDetail(), 'remediation': '', 'severity': severity, 'cwe': cwe_id, 'evidences': evidences } def push(self, event): if self.txt1.getSelectedItem(): vulns = {} vulns['tool'] = 'Burp' vulns['vulnerabilities'] = [] for k, v in self.results[ self.txt1.getSelectedItem()]['scan_dict'].items(): vulnerability = { 'name': str(k), 'description': v.get('description', ''), 'remediation': '', 'severity': v.get('severity', None), 'cwe': v.get('cwe', 0), 'evidences': v.get('evidences', None) } vulns['vulnerabilities'].append(vulnerability) if self.txt2.text and self.txt3.text: webhook_url = self.txt2.text auth_token = self.txt3.text engagement_id = '' if self.txt4.text: engagement_id = self.txt4.text req_headers = { 'Authorization': 'Token ' + auth_token, 'X-Engagement-ID': engagement_id } req = requests.post(webhook_url, headers=req_headers, json={'vuls': vulns}) if req.status_code == 200: self.message.text = "Result pushed successfully" with open('./orchy_log.txt', 'a') as orchy_log: orchy_log.write(req.content + '\n') orchy_log.close() else: with open('./orchy_log.txt', 'a') as orchy_log: orchy_log.write(req.content + '\n') orchy_log.close() self.message.text = "Failed" def getTabCaption(self): return 'Orchy-Webhook' def getUiComponent(self): return self.frame
class Panel_Extension(JPanel): def get_combo_items(self, combo): itemcount = combo.getItemCount() items = [] for i in range(itemcount): items.append(combo.getItemAt(i)) return items def load_profiles(self): loaded_profiles = cb.callbacks.loadExtensionSetting("Profiles") if loaded_profiles is not None: self.profiles = loaded_profiles.splitlines() items = self.get_combo_items(self._profiles_combo) for profile in self.profiles: if profile not in items: self._profiles_combo.addItem(profile) if len(self.profiles) > 0: self.load_fields( "bao7uo WAF bypass" if "bao7uo WAF bypass" in self.profiles else self.profiles[0] ) else: self.save_fields("bao7uo WAF bypass") def save_profiles(self): cb.callbacks.saveExtensionSetting( "Profiles", "\n".join(self.profiles) if len(self.profiles) > 0 else None ) def load_fields(self, profile): self.parent.panel_update_cookies._update_values() values = self.parent.panel_update_cookies.values for key in values.keys(): if key is None: break loaded = cb.callbacks.loadExtensionSetting(profile + "_" + key) if loaded is None: break self.parent.panel_update_cookies.values[key] = loaded self.parent.panel_extension._profile_textfield.setText(profile) self.parent.panel_update_cookies._load_values() Update_cookies = cb.callbacks.loadExtensionSetting( profile + "_" + "Update_cookies" ) if Update_cookies is not None: self.parent.panel_update_cookies._rowpanel2.removeAllElements() if len(Update_cookies) > 0: self.parent.panel_update_cookies._rowpanel2.addelements( Update_cookies, True ) Remove_cookies = cb.callbacks.loadExtensionSetting( profile + "_" + "Remove_cookies" ) if Remove_cookies is not None: self.parent.panel_remove_cookies._rowpanel1.removeAllElements() if len(Remove_cookies) > 0: self.parent.panel_remove_cookies._rowpanel1.addelements( Remove_cookies, True ) def save_fields(self, profile, delete=False): items = self.get_combo_items(self._profiles_combo) if delete: if len(items) == 0: return items_profile_index = items.index(profile) if profile in self.profiles: self.profiles.remove(profile) self.save_profiles() if profile in items: self._profiles_combo.removeItem(profile) else: if profile not in self.profiles: self.profiles.append(profile) self.save_profiles() if profile not in items: self._profiles_combo.addItem(profile) items = self.get_combo_items(self._profiles_combo) items_profile_index = items.index(profile) self.parent.panel_update_cookies._update_values() values = self.parent.panel_update_cookies.values if delete: values = dict.fromkeys(values.iterkeys(), None) for key in values.keys(): cb.callbacks.saveExtensionSetting( profile + "_" + key, values[key] ) if delete: Update_cookies = None Remove_cookies = None else: Update_cookies = \ self.parent.panel_update_cookies._rowpanel2.getAllElements( True ) Remove_cookies = \ self.parent.panel_remove_cookies._rowpanel1.getAllElements( True ) cb.callbacks.saveExtensionSetting( profile + "_" + "Update_cookies", Update_cookies ) cb.callbacks.saveExtensionSetting( profile + "_" + "Remove_cookies", Remove_cookies ) if self._profiles_combo.getItemCount() > 0: if delete: select_index = items_profile_index - 1 \ if items_profile_index > 0 else 0 else: select_index = items_profile_index self._profiles_combo.setSelectedIndex(select_index) def _button_delete_profile_pressed(self, msg): self.save_fields(self._profiles_combo.getSelectedItem(), True) def _button_save_fields_pressed(self, msg): self.save_fields(self._profile_textfield.getText()) def _button_demo_pressed(self, msg): if JOptionPane.showConfirmDialog( msg.getSource().getParent().getParent(), "This will clear all session handling rules in Burp's \n" + "\"Project options -> Sessions\"\n" + "tab, even rules not produced by this extension. They\n" + "will be replaced with a sample/demo rule containing an\n" + "invoke extension session handler action.\n\n" + "A request which can be used for the demo will be sent\n" + "to the Repeater tab.\n\n" + "The demo URL will be placed in the settings, and the\n" + "contents of the \"Cookies to obtain\" list will be\n"+ "replaced with a single demo cookie named\n" + "\"ClientSideCookie\"\n\n" + "Please check the PhantomJS settings, then click on\n" + "\'Add a new \"Get Cookies\" session handler\'.\n\n" + "Are you sure you want to remove any existing session\n" + "handling rules?", "Burp Suite / WAF Cookie Fetcher", JOptionPane.YES_NO_OPTION ) == JOptionPane.YES_OPTION: panel_update_cookies = self.getParent().panel_update_cookies for field in \ panel_update_cookies.fields: if "getText" in dir(field) and "getName" in dir(field): field_name = field.getName() if field_name == "url": field.setText(cb.demo_url) if field_name == "domain": field.setText(cb.demo_domain) panel_update_cookies._rowpanel2.removeAllElements() panel_update_cookies._rowpanel2.addelement(cb.demo_cookie) cb.callbacks.loadConfigFromJson(cb.demo_json) cb.send_url_to_repeater(cb.demo_url) def _button_quit_pressed(self, msg): cb.callbacks.unloadExtension() def __init__(self): self.profiles = [] self.setBorder( BorderFactory.createTitledBorder("Profiles") ) self.setLayout(BoxLayout(self, BoxLayout.Y_AXIS)) self._rowpanel1 = JPanel() self._rowpanel1.setLayout(BoxLayout(self._rowpanel1, BoxLayout.X_AXIS)) self._profiles_combo = \ JComboBox( self.profiles ) self._profiles_combo.addItem("0"*40) self._profiles_combo.setMaximumSize( self._profiles_combo.getPreferredSize() ) self._profiles_combo.removeItem("0" * 40) self._profiles_combo_panel = border_X_panel() self._demo_panel = button_panel( "Demo", self._button_demo_pressed ) self._quit_panel = button_panel( "Unload WAF Cookie Fetcher", self._button_quit_pressed ) self._profile_textfield = \ PTTextField( "profile", "Profile name: ", "bao7uo WAF bypass", None, JButton( "Save profile", actionPerformed=self._button_save_fields_pressed ) ) self._profiles_combo_panel.add(self._profiles_combo) self._button_delete_profile = \ JButton( "Delete profile", actionPerformed=self._button_delete_profile_pressed ) self._profiles_combo_panel.add(self._button_delete_profile) self._profiles_combo.addActionListener(actionlistener(self)) self._rowpanel1.add(self._profiles_combo_panel) self._rowpanel1.add(Box.createHorizontalGlue()) self._rowpanel1.add(self._profile_textfield) self._rowpanel1.add(Box.createHorizontalGlue()) self._rowpanel1.add(self._demo_panel) self._rowpanel1.add(self._quit_panel) self.add(self._rowpanel1)
class EventsPane(WindowPane, ActionListener, DocumentListener): def __init__(self, window, api): self.api = api self.component = JPanel(BorderLayout()) # Create editor pane scrollpane = JScrollPane() self.script_area = InputPane(window) self.script_area.undo = UndoManager() line_numbers = LineNumbering(self.script_area.component) scrollpane.viewport.view = self.script_area.component scrollpane.rowHeaderView = line_numbers.component self.component.add(scrollpane, BorderLayout.CENTER) # Create Selection pane select_pane = JPanel() self.objects_box = JComboBox([], actionCommand="object") select_pane.add(self.objects_box) self.events_box = JComboBox( ["update", "click"], actionCommand="event" ) self.event_types = [EventType.UPDATE, EventType.CLICK] select_pane.add(self.events_box) self.languages = list(ScriptType.values()) self.language_box = JComboBox( [l.getName() for l in self.languages], actionCommand="language" ) select_pane.add(self.language_box) self.save_btn = JButton("Save") select_pane.add(self.save_btn) self.component.add(select_pane, BorderLayout.PAGE_START) self.events_box.addActionListener(self) self.objects_box.addActionListener(self) self.language_box.addActionListener(self) self.save_btn.addActionListener(self) self.current = None self.update_geos() interface.addEventListener("add", self.event_listener) interface.addEventListener("remove", self.event_listener) interface.addEventListener("rename", self.event_listener) # Listen to script_area changes in order to know when the save # button can be activated self.script_area.doc.addDocumentListener(self) # Hack to be able to change the objects_box self.building_objects_box = False self.active = False def activate(self): self.active = True if self.must_update_geos: self.update_geos() def deactivate(self): self.active = False def indent_selection(self): return self.script_area.indent_selection() def dedent_selection(self): return self.script_area.dedent_selection() def update_geos(self): self.must_update_geos = False try: self.building_objects_box = True self.objects_box.removeAllItems() self.geos = self.api.getAllGeos() for geo in self.geos: tp = API.Geo.getTypeString(geo) label = API.Geo.getLabel(geo) self.objects_box.addItem(tp + " " + label) finally: self.building_objects_box = False if not self.geos: self.current = None self.objects_box.enabled = False self.events_box.enabled = False self.language_box.enabled = False self.script_area.input = "" self.script_area.component.enabled = False else: changed = False if self.current is None: index, event = 0, 1 changed = True else: geo, event = self.current try: index = self.geos.index(geo) except ValueError: index, event = 0, 1 changed = True self.events_box.selectedIndex = event self.objects_box.selectedIndex = index self.events_box.enabled = True self.objects_box.enabled = True self.language_box.enabled = True self.script_area.component.enabled = True if changed: self.update_script_area() self.objects_box.repaint() self.events_box.repaint() def event_listener(self, evt, target): if self.active: self.update_geos() else: self.must_update_geos = True def current_script_changed(self): self.save_btn.enabled = True def set_save_btn(self, state): self.save_btn.enabled = state def save_current_script(self): if self.current is not None: geo, evt = self.current lang = self.language_box.selectedIndex evt, lang = self.event_types[evt], self.languages[lang] script = self.script_area.input self.api.setScript(geo, script, evt, lang) def update_script_area(self): self.save_current_script() geo_index = self.objects_box.selectedIndex if geo_index == -1: self.current = None else: geo = self.geos[geo_index] evt = self.events_box.selectedIndex self.current = geo, evt script = API.Geo.getScript(geo, self.event_types[evt]) if script is None: self.script_area.input = "" else: self.script_area.input = API.getScriptText(script) self.language_box.selectedIndex = API.getScriptType(script).ordinal() self.script_area.reset_undo() later(self.set_save_btn, False) def reset(self): self.current = None self.update_geos() # Implementation of ActionListener def actionPerformed(self, evt): if self.building_objects_box: return if evt.actionCommand == "language": self.save_btn.enabled = True else: self.update_script_area() # Implementation of DocumentListener def changedUpdate(self, evt): self.current_script_changed() def removeUpdate(self, evt): self.current_script_changed() def insertUpdate(self, evt): self.current_script_changed()
class ResourcePanel(JPanel): def __init__(self): ''' Resources Panel ''' # psimures= JPanel(GridBagLayout()) # psimures.setSize(Dimension(500,300)) self.setLayout(GridBagLayout()) # super(self,GridBagLayout()) self.setSize(Dimension(500,300)) ''' fila 1 ''' label = JLabel('Resources panel') c = GridBagConstraints() c.fill = GridBagConstraints.HORIZONTAL c.weightx = 1 c.gridwidth = 4 c.gridx = 0 c.gridy = 0 self.add(label, c) ''' fila 2 ''' self.dModelFile = [] self.cbMoFile = JComboBox(self.dModelFile) c = GridBagConstraints() c.fill = GridBagConstraints.HORIZONTAL c.weightx = 0.75 c.gridwidth = 3 c.gridx = 0 c.gridy = 1 self.add(self.cbMoFile, c) bloadmodel= JButton('Load Model',actionPerformed=self.onOpenFile) c = GridBagConstraints() c.fill = GridBagConstraints.HORIZONTAL c.weightx = 0.25 # c.gridwidth = 1 c.gridx = 3 c.gridy = 1 self.add(bloadmodel, c) ''' fila 3 ''' self.dLibFile = [] self.cbMoLib = JComboBox(self.dLibFile) c = GridBagConstraints() c.fill = GridBagConstraints.HORIZONTAL c.weightx = 0.75 c.gridwidth = 3 c.gridx = 0 c.gridy = 2 self.add(self.cbMoLib, c) bloadlib= JButton('Load Library',actionPerformed=self.onOpenFile) c = GridBagConstraints() c.fill = GridBagConstraints.HORIZONTAL c.weightx = 0.25 # c.gridwidth = 1 c.gridx = 3 c.gridy = 2 self.add(bloadlib, c) ''' fila 4 ''' self.dModel = [] self.cbModel = JComboBox(self.dModel) c = GridBagConstraints() c.fill = GridBagConstraints.HORIZONTAL c.weightx = 0.75 c.gridwidth = 3 c.gridx = 0 c.gridy = 3 self.add(self.cbModel, c) bselectmodel= JButton('Select Model',actionPerformed=self.onOpenModel) c = GridBagConstraints() c.fill = GridBagConstraints.HORIZONTAL c.weightx = 0.25 # c.gridwidth = 1 c.gridx = 3 c.gridy = 3 self.add(bselectmodel, c) ''' fila 5 ''' self.dOutPath = [] self.cbOutDir = JComboBox(self.dOutPath) c = GridBagConstraints() c.fill = GridBagConstraints.HORIZONTAL c.weightx = 0.75 c.gridwidth = 3 c.gridx = 0 c.gridy = 4 self.add(self.cbOutDir, c) bloadoutpath= JButton('Output Path',actionPerformed=self.onOpenFolder) c = GridBagConstraints() c.fill = GridBagConstraints.HORIZONTAL c.weightx = 0.25 # c.gridwidth = 1 c.gridx = 3 c.gridy = 4 self.add(bloadoutpath, c) ''' fila 6 ''' bsaveSource= JButton('Save Resources',actionPerformed=self.saveResources) c = GridBagConstraints() c.fill = GridBagConstraints.HORIZONTAL c.weightx = 0.5 c.gridwidth = 2 c.gridx = 0 c.gridy = 5 self.add(bsaveSource, c) bloadSource= JButton('Load Resources',actionPerformed=self.loadResources) c = GridBagConstraints() c.fill = GridBagConstraints.HORIZONTAL c.weightx = 0.5 c.gridwidth = 2 c.gridx = 2 c.gridy = 5 self.add(bloadSource, c) def onOpenFile(self, event): ''' remember to change the path''' chooseFile = JFileChooser() chooseFile.setCurrentDirectory(File('C:\Users\fragom\PhD_CIM\Modelica\Models')) filtro = FileNameExtensionFilter("mo files", ["mo"]) chooseFile.addChoosableFileFilter(filtro) ret = chooseFile.showDialog(self, "Choose file") if ret == JFileChooser.APPROVE_OPTION: self.faile= chooseFile.getSelectedFile() if event.getActionCommand() == "Load Model": self.cbMoFile.addItem(self.faile.getPath()) self.cbMoFile.selectedItem= self.faile.getPath() if event.getActionCommand() == "Load Library": self.cbMoLib.addItem(self.faile.getPath()) self.cbMoLib.selectedItem= self.faile.getPath() # print self.faile def onOpenModel(self, event): omcscript= CommandOMC() omc= OMCProxy("FTP") comando= omcscript.loadFile(self.cbMoFile.selectedItem) result = omc.sendExpression(comando) ''' Parametrizar este comando ''' modelname= self.cbMoFile.selectedItem.split('\\') # print modelname[-1].split('.')[0] modelname= modelname[-1].split('.')[0] comando= omcscript.getClassNames(modelname) result = omc.sendExpression(comando) # print 'result OMCProxy', result.__class__.__name__ # print 'result.res', result.res[1:-2] listname= result.res[1:-2].split(',') for nombre in listname: self.cbModel.addItem(nombre) def onOpenFolder(self, event): chooseFile = JFileChooser() chooseFile.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); ret = chooseFile.showDialog(self, "Choose folder") if ret == JFileChooser.APPROVE_OPTION: self.faile= chooseFile.getSelectedFile() self.cbOutDir.addItem(self.faile.getPath()) self.cbOutDir.selectedItem= self.faile.getPath() def saveResources(self,event): self.config= ParameterResources() self.config.set_modelPath(self.cbMoFile.selectedItem) self.config.set_modelFile(self.cbMoFile.selectedItem) self.config.set_modelName(self.cbModel.selectedItem) self.config.set_libraryPath(self.cbMoLib.selectedItem) self.config.set_libraryFile(self.cbMoLib.selectedItem) self.config.set_outputPath(self.cbOutDir.selectedItem) nomfile= './config/simParameters.properties' self.config.save_Properties(nomfile, 'Simulation resources') def loadResources(self,event): self.config= ParameterResources() nomfile= './config/simParameters.properties' self.config.load_Properties(nomfile) self.cbMoFile.addItem(self.config.get_modelFile()) self.cbMoFile.selectedItem= self.config.get_modelFile() self.cbMoLib.addItem(self.config.get_libraryFile()) self.cbMoLib.selectedItem= self.config.get_libraryFile() self.cbModel.addItem(self.config.get_modelName()) self.cbModel.selectedItem= self.config.get_modelName() self.cbOutDir.addItem(self.config.get_outputPath()) self.cbOutDir.selectedItem= self.config.get_outputPath()
class PluginUI(): def __init__(self, extender): self.extender = extender self.initComponents() def showMessage(self, msg): JOptionPane.showMessageDialog(self.mainPanel, msg) def getProcessorTechName(self): return self.comboProcessorTech.getSelectedItem() def getGeneratorTechsName(self): techList = [] if self.chkGeneral.isSelected(): techList.append('General') if self.chkMAXDB.isSelected(): techList.append('SAP_MaxDB') if self.chkMSSQL.isSelected(): techList.append('MSSQL') if self.chkMSAccess.isSelected(): techList.append('MSAccess') if self.chkPostgres.isSelected(): techList.append('PostgreSQL') if self.chkOracle.isSelected(): techList.append('Oracle') if self.chkSqlite.isSelected(): techList.append('SQLite') if self.chkMysql.isSelected(): techList.append('MySQL') return techList def pastePayloadButtonAction(self, event): clpbrd = Toolkit.getDefaultToolkit().getSystemClipboard() content = clpbrd.getContents(None) if content and content.isDataFlavorSupported(DataFlavor.stringFlavor): items = content.getTransferData(DataFlavor.stringFlavor) items = items.splitlines() for item in items: self.extender.PayloadList.append(item) self.listPayloads.setListData(self.extender.PayloadList) self.writePayloadsListFile() def loadPayloadButtonAction(self, event): fileChooser = JFileChooser() fileChooser.dialogTitle = 'Choose Payload List' fileChooser.fileSelectionMode = JFileChooser.FILES_ONLY if (fileChooser.showOpenDialog( self.mainPanel) == JFileChooser.APPROVE_OPTION): file = fileChooser.getSelectedFile() with open(file.getAbsolutePath(), 'r') as reader: for line in reader.readlines(): self.extender.PayloadList.append(line.strip('\n')) self.listPayloads.setListData(self.extender.PayloadList) self.showMessage('{} payloads loaded'.format( len(self.extender.PayloadList))) self.writePayloadsListFile() def removePayloadButtonAction(self, event): for item in self.listPayloads.getSelectedValuesList(): self.extender.PayloadList.remove(item) self.listPayloads.setListData(self.extender.PayloadList) self.writePayloadsListFile() def clearPayloadButtonAction(self, event): self.extender.PayloadList[:] = [] self.listPayloads.setListData(self.extender.PayloadList) self.writePayloadsListFile() def addPayloadButtonAction(self, event): if str(self.textNewPayload.text).strip(): self.extender.PayloadList.append(self.textNewPayload.text) self.textNewPayload.text = '' self.listPayloads.setListData(self.extender.PayloadList) self.writePayloadsListFile() def toClipboardButtonAction(self, event): self.extender.generatePayloads() result = '\n'.join(self.extender.tamperedPayloads) result = StringSelection(result) clpbrd = Toolkit.getDefaultToolkit().getSystemClipboard() clpbrd.setContents(result, None) self.showMessage('{} url encoded payload copied to clipboard'.format( len(self.extender.tamperedPayloads))) def toFileButtonAction(self, event): fileChooser = JFileChooser() fileChooser.dialogTitle = 'Save Payloads' fileChooser.fileSelectionMode = JFileChooser.FILES_ONLY if (fileChooser.showSaveDialog( self.mainPanel) == JFileChooser.APPROVE_OPTION): file = fileChooser.getSelectedFile() self.extender.generatePayloads() result = '\n' result = result.join(self.extender.tamperedPayloads) with open(file.getAbsolutePath(), 'w') as writer: writer.writelines(result) self.showMessage('{} url encoded payload written to file'.format( len(self.extender.tamperedPayloads))) def tamperPayloadButtonAction(self, event): tamperedPayloads = [] tamperFunction = self.comboProcessorTech.getSelectedItem() payloads = self.textPlainPayload.text payloads = payloads.splitlines() for payload in payloads: tamperedPayloads.append( self.extender.tamperSinglePayload(tamperFunction, payload)) result = '\n'.join(tamperedPayloads) self.textTamperedPayload.text = result def comboProcessorTechAction(self, event): varName = 'SQLiQueryTampering_comboProcessorTech' state = str(self.comboProcessorTech.getSelectedIndex()) self.extender.callbacks.saveExtensionSetting(varName, state) def OnCheck(self, event): chk = event.getSource() varName = 'SQLiQueryTampering_{}'.format(chk.text) state = str(1 if chk.isSelected() else 0) self.extender.callbacks.saveExtensionSetting(varName, state) def writePayloadsListFile(self): payloads = '\n'.join(self.extender.PayloadList) payloads = payloads.encode('utf-8') with open('payloads.lst', 'w') as writer: writer.write(payloads) def readPayloadsListFile(self): result = [] with open('payloads.lst', 'r') as reader: for line in reader.readlines(): result.append(line.strip('\n')) return result def initComponents(self): TabbedPane1 = JTabbedPane() GeneratorScrollPane = JScrollPane() GeneratorPanel = JPanel() jlbl1 = JLabel() jlbl2 = JLabel() spanePayloadList = JScrollPane() self.listPayloads = JList() pastePayloadButton = JButton( actionPerformed=self.pastePayloadButtonAction) loadPayloadButton = JButton( actionPerformed=self.loadPayloadButtonAction) removePayloadButton = JButton( actionPerformed=self.removePayloadButtonAction) clearPayloadButton = JButton( actionPerformed=self.clearPayloadButtonAction) self.textNewPayload = JTextField() addPayloadButton = JButton(actionPerformed=self.addPayloadButtonAction) jSeparator1 = JSeparator() jlbl3 = JLabel() jlbl4 = JLabel() self.chkGeneral = JCheckBox(actionPerformed=self.OnCheck) self.chkMAXDB = JCheckBox(actionPerformed=self.OnCheck) self.chkMSSQL = JCheckBox(actionPerformed=self.OnCheck) self.chkMSAccess = JCheckBox(actionPerformed=self.OnCheck) self.chkPostgres = JCheckBox(actionPerformed=self.OnCheck) self.chkOracle = JCheckBox(actionPerformed=self.OnCheck) self.chkSqlite = JCheckBox(actionPerformed=self.OnCheck) self.chkMysql = JCheckBox(actionPerformed=self.OnCheck) jlbl5 = JLabel() toClipboardButton = JButton( actionPerformed=self.toClipboardButtonAction) toFileButton = JButton(actionPerformed=self.toFileButtonAction) ProcessorScrollPane = JScrollPane() ProcessorPanel = JPanel() jLabel1 = JLabel() self.comboProcessorTech = JComboBox( itemStateChanged=self.comboProcessorTechAction) jSeparator2 = JSeparator() jLabel2 = JLabel() jLabel3 = JLabel() jScrollPane1 = JScrollPane() self.textPlainPayload = JTextArea() jLabel4 = JLabel() jScrollPane2 = JScrollPane() self.textTamperedPayload = JTextArea() tamperPayloadButton = JButton( actionPerformed=self.tamperPayloadButtonAction) jlbl1.setForeground(Color(255, 102, 51)) jlbl1.setFont(Font(jlbl1.getFont().toString(), 1, 14)) jlbl1.setText("User-Defiend Payloads") jlbl2.setText( "This payload type lets you configure a simple list of strings that are used as payloads." ) spanePayloadList.setViewportView(self.listPayloads) self.extender.PayloadList = self.readPayloadsListFile() self.listPayloads.setListData(self.extender.PayloadList) pastePayloadButton.setText("Paste") loadPayloadButton.setText("Load") removePayloadButton.setText("Remove") clearPayloadButton.setText("Clear") self.textNewPayload.setToolTipText("") addPayloadButton.setText("Add") jlbl3.setForeground(Color(255, 102, 51)) jlbl3.setFont(Font(jlbl3.getFont().toString(), 1, 14)) jlbl3.setText("Tamper Techniques") jlbl4.setText( "You can select the techniques that you want to perform processing tasks on each user-defined payload" ) self.chkGeneral.setText("General") varName = 'SQLiQueryTampering_{}'.format(self.chkGeneral.text) state = self.extender.callbacks.loadExtensionSetting(varName) if state: self.chkGeneral.setSelected(int(state)) self.chkMAXDB.setText("SAP MAX DB") varName = 'SQLiQueryTampering_{}'.format(self.chkMAXDB.text) state = self.extender.callbacks.loadExtensionSetting(varName) if state: self.chkMAXDB.setSelected(int(state)) self.chkMSSQL.setText("MS SQL Server") varName = 'SQLiQueryTampering_{}'.format(self.chkMSSQL.text) state = self.extender.callbacks.loadExtensionSetting(varName) if state: self.chkMSSQL.setSelected(int(state)) self.chkMSAccess.setText("MS Access") varName = 'SQLiQueryTampering_{}'.format(self.chkMSAccess.text) state = self.extender.callbacks.loadExtensionSetting(varName) if state: self.chkMSAccess.setSelected(int(state)) self.chkPostgres.setText("Postgres SQL") varName = 'SQLiQueryTampering_{}'.format(self.chkPostgres.text) state = self.extender.callbacks.loadExtensionSetting(varName) if state: self.chkPostgres.setSelected(int(state)) self.chkOracle.setText("Oracle") varName = 'SQLiQueryTampering_{}'.format(self.chkOracle.text) state = self.extender.callbacks.loadExtensionSetting(varName) if state: self.chkOracle.setSelected(int(state)) self.chkSqlite.setText("Sqlite") varName = 'SQLiQueryTampering_{}'.format(self.chkSqlite.text) state = self.extender.callbacks.loadExtensionSetting(varName) if state: self.chkSqlite.setSelected(int(state)) self.chkMysql.setText("MySql") varName = 'SQLiQueryTampering_{}'.format(self.chkMysql.text) state = self.extender.callbacks.loadExtensionSetting(varName) if state: self.chkMysql.setSelected(int(state)) jlbl5.setText("[?] Save the Generated/Tampered Payloads to :") toClipboardButton.setText("Clipboard") toFileButton.setText("File") GeneratorPanelLayout = GroupLayout(GeneratorPanel) GeneratorPanel.setLayout(GeneratorPanelLayout) GeneratorPanelLayout.setHorizontalGroup( GeneratorPanelLayout.createParallelGroup( GroupLayout.Alignment.LEADING). addGroup(GeneratorPanelLayout.createSequentialGroup( ).addContainerGap().addGroup( GeneratorPanelLayout.createParallelGroup( GroupLayout.Alignment.TRAILING).addComponent( jlbl2, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE).addComponent( jlbl4, GroupLayout.Alignment.LEADING, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE).addComponent( jSeparator1, GroupLayout.Alignment.LEADING). addGroup(GeneratorPanelLayout.createSequentialGroup().addGap( 6, 6, 6).addGroup( GeneratorPanelLayout.createParallelGroup( GroupLayout.Alignment.LEADING).addGroup( GeneratorPanelLayout.createSequentialGroup( ).addGroup( GeneratorPanelLayout.createParallelGroup( GroupLayout.Alignment.LEADING, False).addComponent( removePayloadButton, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE).addComponent( clearPayloadButton, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE).addComponent( loadPayloadButton, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE). addComponent(pastePayloadButton, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE).addComponent( addPayloadButton, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)). addGap(21, 21, 21).addGroup( GeneratorPanelLayout.createParallelGroup( GroupLayout.Alignment.LEADING). addComponent( self.textNewPayload).addComponent( spanePayloadList))).addComponent( jlbl1).addComponent(jlbl3). addGroup(GeneratorPanelLayout.createSequentialGroup( ).addGroup( GeneratorPanelLayout.createParallelGroup( GroupLayout.Alignment.LEADING).addComponent( self.chkGeneral).addComponent( self.chkMSSQL) ).addGap(18, 18, 18).addGroup( GeneratorPanelLayout.createParallelGroup( GroupLayout.Alignment.LEADING).addComponent( self.chkPostgres).addComponent( self.chkMAXDB) ).addGap(18, 18, 18).addGroup( GeneratorPanelLayout.createParallelGroup( GroupLayout.Alignment.LEADING).addComponent( self.chkMSAccess).addComponent( self.chkOracle) ).addGap(18, 18, 18).addGroup( GeneratorPanelLayout.createParallelGroup( GroupLayout.Alignment.LEADING).addComponent( self.chkSqlite).addComponent(self.chkMysql) )).addGroup(GeneratorPanelLayout.createSequentialGroup( ).addComponent(jlbl5).addPreferredGap( LayoutStyle.ComponentPlacement. UNRELATED).addComponent(toClipboardButton).addGap( 18, 18, 18).addComponent(toFileButton, GroupLayout.PREFERRED_SIZE, 97, GroupLayout.PREFERRED_SIZE ))))).addContainerGap())) GeneratorPanelLayout.setVerticalGroup( GeneratorPanelLayout.createParallelGroup( GroupLayout.Alignment.LEADING). addGroup(GeneratorPanelLayout.createSequentialGroup( ).addContainerGap().addComponent(jlbl1).addPreferredGap( LayoutStyle.ComponentPlacement.RELATED).addComponent( jlbl2, GroupLayout.PREFERRED_SIZE, 21, GroupLayout.PREFERRED_SIZE).addGap(18, 18, 18).addGroup( GeneratorPanelLayout.createParallelGroup( GroupLayout.Alignment.LEADING).addComponent( spanePayloadList, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE). addGroup(GeneratorPanelLayout.createSequentialGroup( ).addComponent(pastePayloadButton).addPreferredGap( LayoutStyle.ComponentPlacement.RELATED ).addComponent(loadPayloadButton).addPreferredGap( LayoutStyle.ComponentPlacement.RELATED ).addComponent(removePayloadButton).addPreferredGap( LayoutStyle.ComponentPlacement.RELATED). addComponent(clearPayloadButton))). addPreferredGap( LayoutStyle.ComponentPlacement.RELATED).addGroup( GeneratorPanelLayout.createParallelGroup( GroupLayout.Alignment.BASELINE).addComponent( self.textNewPayload, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE). addComponent(addPayloadButton)).addPreferredGap( LayoutStyle.ComponentPlacement.UNRELATED). addComponent(jSeparator1, GroupLayout.PREFERRED_SIZE, 10, GroupLayout.PREFERRED_SIZE).addPreferredGap( LayoutStyle.ComponentPlacement.RELATED). addComponent(jlbl3).addPreferredGap( LayoutStyle.ComponentPlacement.UNRELATED ).addComponent(jlbl4).addPreferredGap( LayoutStyle.ComponentPlacement.UNRELATED).addGroup( GeneratorPanelLayout.createParallelGroup( GroupLayout.Alignment.BASELINE).addComponent( self.chkGeneral).addComponent( self.chkMAXDB).addComponent( self.chkOracle).addComponent( self.chkSqlite)). addPreferredGap( LayoutStyle.ComponentPlacement.UNRELATED).addGroup( GeneratorPanelLayout.createParallelGroup( GroupLayout.Alignment.BASELINE).addComponent( self.chkMSSQL).addComponent( self.chkPostgres).addComponent( self.chkMSAccess).addComponent( self.chkMysql) ).addGap(18, 18, 18).addGroup( GeneratorPanelLayout.createParallelGroup( GroupLayout.Alignment.BASELINE).addComponent( jlbl5).addComponent(toClipboardButton). addComponent(toFileButton)).addGap(20, 20, 20))) GeneratorScrollPane.setViewportView(GeneratorPanel) TabbedPane1.addTab("Generator", GeneratorScrollPane) varName = 'SQLiQueryTampering_comboProcessorTech' state = self.extender.callbacks.loadExtensionSetting(varName) for item in self.extender.getTamperFuncsName(): self.comboProcessorTech.addItem(item) if state: self.comboProcessorTech.setSelectedIndex(int(state)) jLabel1.setText("Processor Technique :") jLabel2.setText( "Modify Plain Payloads based on the selected Processor Technique. Write one payload per line." ) jLabel3.setText("Plain Payloads:") self.textPlainPayload.setColumns(20) self.textPlainPayload.setRows(5) jScrollPane1.setViewportView(self.textPlainPayload) jLabel4.setText("Tampered Payloads:") self.textTamperedPayload.setColumns(20) self.textTamperedPayload.setRows(5) jScrollPane2.setViewportView(self.textTamperedPayload) tamperPayloadButton.setText("Tamper Payloads") ProcessorPanelLayout = GroupLayout(ProcessorPanel) ProcessorPanel.setLayout(ProcessorPanelLayout) ProcessorPanelLayout.setHorizontalGroup( ProcessorPanelLayout. createParallelGroup(GroupLayout.Alignment.LEADING).addGroup( GroupLayout.Alignment.TRAILING, ProcessorPanelLayout.createSequentialGroup().addContainerGap( GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE).addComponent( tamperPayloadButton).addContainerGap( GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ).addGroup(ProcessorPanelLayout.createSequentialGroup( ).addContainerGap().addGroup( ProcessorPanelLayout.createParallelGroup( GroupLayout.Alignment.LEADING).addComponent(jSeparator2). addComponent(jScrollPane1).addComponent(jScrollPane2).addGroup( ProcessorPanelLayout.createSequentialGroup().addGroup( ProcessorPanelLayout.createParallelGroup( GroupLayout.Alignment.LEADING).addComponent( jLabel3).addComponent(jLabel4).addGroup( ProcessorPanelLayout.createSequentialGroup( ).addComponent(jLabel1).addPreferredGap( LayoutStyle.ComponentPlacement. UNRELATED).addComponent( self.comboProcessorTech, GroupLayout.PREFERRED_SIZE, 286, GroupLayout.PREFERRED_SIZE)). addComponent(jLabel2)).addGap( 0, 78, Short.MAX_VALUE))).addContainerGap())) ProcessorPanelLayout.setVerticalGroup( ProcessorPanelLayout.createParallelGroup( GroupLayout.Alignment.LEADING).addGroup( ProcessorPanelLayout.createSequentialGroup().addGap( 33, 33, 33).addGroup( ProcessorPanelLayout.createParallelGroup( GroupLayout.Alignment.BASELINE). addComponent(jLabel1).addComponent( self.comboProcessorTech, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)).addGap( 18, 18, 18).addComponent( jSeparator2, GroupLayout.PREFERRED_SIZE, 10, GroupLayout.PREFERRED_SIZE).addGap( 12, 12, 12).addComponent(jLabel2).addGap( 18, 18, 18). addComponent(jLabel3).addPreferredGap( LayoutStyle.ComponentPlacement.UNRELATED).addComponent( jScrollPane1, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE).addPreferredGap( LayoutStyle.ComponentPlacement.UNRELATED). addComponent(jLabel4).addPreferredGap( LayoutStyle.ComponentPlacement.UNRELATED).addComponent( jScrollPane2, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE).addPreferredGap( LayoutStyle.ComponentPlacement.UNRELATED). addComponent(tamperPayloadButton).addGap(36, 36, 36))) ProcessorScrollPane.setViewportView(ProcessorPanel) TabbedPane1.addTab("Processor", ProcessorScrollPane) self.mainPanel = JPanel() layout = GroupLayout(self.mainPanel) self.mainPanel.setLayout(layout) layout.setHorizontalGroup( layout.createParallelGroup( GroupLayout.Alignment.LEADING).addComponent( TabbedPane1, GroupLayout.DEFAULT_SIZE, 701, Short.MAX_VALUE)) layout.setVerticalGroup( layout.createParallelGroup( GroupLayout.Alignment.LEADING).addComponent(TabbedPane1)) TabbedPane1.getAccessibleContext().setAccessibleName("Generator")
class BugDialog(JDialog): """Represents the dialog.""" # default issue to populate the panel with defaultIssue = Issue(name="Name", severity="Critical", host="Host", path="Path", description="Description", remediation="", reqResp=RequestResponse(request="default request", response="default response")) def loadPanel(self, issue): # type: (Issue) -> () """Populates the panel with issue.""" if issue is None: return # check if the input is the correct object assert isinstance(issue, Issue) # set textfields and textareas # selectionStart=0 selects the text in the textfield when it is in focus self.textName.text = issue.name self.textName.selectionStart = 0 self.textHost.text = issue.host self.textHost.selectionStart = 0 self.textPath.text = issue.path self.textPath.selectionStart = 0 self.textAreaDescription.text = issue.description self.textAreaDescription.selectionStart = 0 self.textAreaRemediation.text = issue.remediation self.textAreaRemediation.selectionStart = 0 # severity combobox # this is case-sensitive apparently self.comboSeverity.setSelectedItem(issue.severity) # request and response tabs # check if messages are null, some issues might not have responses. if issue.getRequest() is None: self.panelRequest.setMessage("", True) else: self.panelRequest.setMessage(issue.getRequest(), True) if issue.getResponse() is None: self.panelResponse.setMessage("", False) else: self.panelResponse.setMessage(issue.getResponse(), False) # reset the template combobox (only applicable to NewIssueDialog) self.comboTemplate.setSelectedIndex(-1) def loadTemplateIntoPanel(self, issue): # type: (Issue) -> () """Populates the panel with the template issue. Does not overwrite: name (append), host, path, severity, request and response.""" if issue is None: return # check if the input is the correct object assert isinstance(issue, Issue) # set textfields and textareas # selectionStart=0 selects the text in the textfield when it is in focus self.textName.text += " - " + issue.name self.textName.selectionStart = 0 # self.textHost.text = issue.host # self.textHost.selectionStart = 0 # self.textPath.text = issue.path # self.textPath.selectionStart = 0 self.textAreaDescription.text = issue.description self.textAreaDescription.selectionStart = 0 self.textAreaRemediation.text = issue.remediation self.textAreaRemediation.selectionStart = 0 # severity combobox # this is case-sensitive apparently # self.comboSeverity.setSelectedItem(issue.severity) # request and response tabs # self.panelRequest.setMessage(issue.getRequest(), True) # self.panelResponse.setMessage(issue.getResponse(), False) # reset the template combobox (only applicable to NewIssueDialog) self.comboTemplate.setSelectedIndex(-1) def cancelButtonAction(self, event): """Close the dialog when the cancel button is clicked.""" self.dispose() def resetButtonAction(self, event): """Reset the dialog.""" self.loadPanel(self.defaultIssue) # Inheriting forms should implement this def saveButtonAction(self, event): """Save the current issue. Inheriting classes must implement this.""" pass def __init__(self, callbacks, issue=defaultIssue, title="", modality=""): """Constructor, populates the dialog.""" # set the title self.setTitle(title) # store the issue self.issue = issue from javax.swing import JFrame self.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE) if modality is not "": from java.awt.Dialog import ModalityType modality = modality.lower() # application blocks us from clicking anything else in Burp if modality == "application": self.setModalityType(ModalityType.APPLICATION_MODAL) if modality == "document": self.setModalityType(ModalityType.DOCUMENT_MODAL) if modality == "modeless": self.setModalityType(ModalityType.DOCUMENT_MODAL) if modality == "toolkit": self.setModalityType(ModalityType.DOCUMENT_MODAL) # assert isinstance(callbacks, IBurpExtenderCallbacks) # starting converted code from NetBeans self.labelPath = JLabel("Path") self.labelSeverity = JLabel("Severity") self.tabIssue = JTabbedPane() self.textAreaDescription = JTextArea() self.textAreaRemediation = JTextArea() # JScrollPanes to hold the two jTextAreas # put the textareas in JScrollPanes self.jsPaneDescription = JScrollPane(self.textAreaDescription) self.jsPaneRemediation = JScrollPane(self.textAreaRemediation) self.panelRequest = callbacks.createMessageEditor(None, True) self.panelResponse = callbacks.createMessageEditor(None, True) self.textName = JTextField() self.textHost = JTextField() self.textPath = JTextField() self.labelHost = JLabel("Host") self.labelName = JLabel("Name") # buttons self.buttonSave = JButton("Save", actionPerformed=self.saveButtonAction) self.buttonCancel = JButton("Cancel", actionPerformed=self.cancelButtonAction) self.buttonReset = JButton("Reset", actionPerformed=self.resetButtonAction) # description and remediation textareas from java.awt import Dimension self.textAreaDescription.setPreferredSize(Dimension(400, 500)) self.textAreaDescription.setLineWrap(True) self.textAreaDescription.setWrapStyleWord(True) self.textAreaRemediation.setLineWrap(True) self.textAreaRemediation.setWrapStyleWord(True) self.tabIssue.addTab("Description", self.jsPaneDescription) self.tabIssue.addTab("Remediation", self.jsPaneRemediation) # request and response tabs # request tab self.panelRequest.setMessage("", True) self.tabIssue.addTab("Request", self.panelRequest.getComponent()) # response tab self.panelResponse.setMessage("", False) self.tabIssue.addTab("Response", self.panelResponse.getComponent()) # template self.labelTemplate = JLabel("Template") self.comboTemplate = JComboBox() # TODO: Populate this from outside using a config file from the # constructor? or perhaps the extension config self.comboSeverity = JComboBox( ["Critical", "High", "Medium", "Low", "Info"]) self.comboSeverity.setSelectedIndex(-1) # add componentlistener dlgListener = DialogListener(self) self.addComponentListener(dlgListener) if issue is None: issue = self.defaultIssue # load the issue into the edit dialog. self.loadPanel(issue) # "here be dragons" GUI code layout = GroupLayout(self.getContentPane()) self.getContentPane().setLayout(layout) layout.setHorizontalGroup( layout.createParallelGroup(GroupLayout.Alignment.CENTER).addGroup( layout.createSequentialGroup().addGroup( layout.createParallelGroup(GroupLayout.Alignment.CENTER). addGroup(layout.createSequentialGroup().addContainerGap( ).addGroup(layout.createParallelGroup().addGroup( layout.createSequentialGroup().addGroup( layout.createParallelGroup().addComponent( self.labelTemplate).addComponent( self.labelHost). addComponent(self.labelName)).addPreferredGap( LayoutStyle.ComponentPlacement.UNRELATED). addGroup(layout.createParallelGroup().addGroup( layout.createSequentialGroup().addComponent( self.comboTemplate) ).addGroup(layout.createSequentialGroup().addComponent( self.textHost, GroupLayout.PREFERRED_SIZE, 212, GroupLayout.PREFERRED_SIZE).addPreferredGap( LayoutStyle.ComponentPlacement.UNRELATED ).addComponent(self.labelPath).addPreferredGap( LayoutStyle.ComponentPlacement.RELATED ).addComponent( self.textPath, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, 800 )).addGroup( GroupLayout.Alignment.TRAILING, layout.createSequentialGroup(). addComponent(self.textName).addPreferredGap( LayoutStyle.ComponentPlacement.UNRELATED). addComponent( self.labelSeverity).addPreferredGap( LayoutStyle.ComponentPlacement. UNRELATED).addComponent( self.comboSeverity, GroupLayout.PREFERRED_SIZE, 182, GroupLayout.PREFERRED_SIZE))) ).addComponent(self.tabIssue))).addGroup( layout.createSequentialGroup().addComponent( self.buttonSave, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE).addComponent( self.buttonReset, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE).addComponent( self.buttonCancel, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, GroupLayout. PREFERRED_SIZE))).addContainerGap())) # link size of buttons together from javax.swing import SwingConstants layout.linkSize(SwingConstants.HORIZONTAL, [self.buttonCancel, self.buttonSave, self.buttonReset]) layout.setVerticalGroup(layout.createParallelGroup().addGroup( GroupLayout.Alignment.TRAILING, layout.createSequentialGroup().addContainerGap().addGroup( layout.createParallelGroup( GroupLayout.Alignment.BASELINE).addComponent( self.labelName).addComponent( self.textName, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE).addComponent( self.labelSeverity).addComponent( self.comboSeverity, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)). addPreferredGap(LayoutStyle.ComponentPlacement.RELATED).addGroup( layout.createParallelGroup( GroupLayout.Alignment.BASELINE).addComponent( self.textHost, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE).addComponent( self.labelPath).addComponent(self.textPath). addComponent(self.labelHost)).addGroup( layout.createParallelGroup( GroupLayout.Alignment.BASELINE).addComponent( self.comboTemplate, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE).addComponent( self.labelTemplate)).addPreferredGap( LayoutStyle.ComponentPlacement.RELATED). addComponent(self.tabIssue).addPreferredGap( LayoutStyle.ComponentPlacement.RELATED).addGroup( layout.createParallelGroup().addComponent( self.buttonSave).addComponent( self.buttonReset).addComponent( self.buttonCancel)).addContainerGap())) # end of converted code from NetBeans # set the template label and combobox to invisible self.labelTemplate.setVisible(False) self.comboTemplate.setVisible(False) def display(self, parent): """packs and shows the frame.""" self.pack() # setlocation must be AFTER pack # source: https://stackoverflow.com/a/22615038 self.dlgParent = parent self.setLocationRelativeTo(self.dlgParent.panel) # self.show() self.setVisible(True) def loadTemplate(self): """Reads the template file and populates the combobox for NewIssueDialog. """ templateFile = "data\\templates-cwe-1200.json" fi = open(templateFile, "r") from Utils import templateToIssue import json templateIssues = json.load(fi, object_hook=templateToIssue) self.templateIssues = templateIssues # templateNames = [t.name for t in self.templateIssues] for t in self.templateIssues: self.comboTemplate.addItem(t)
class GUI(ITab, ActionListener, KeyAdapter): def __init__(self): return def getTabCaption(self): return "BurpExtension" def getUiComponent(self): return self.UI() def UI(self): self.val="" self.tabbedPane = JTabbedPane(JTabbedPane.TOP) self.panel = JPanel() self.tabbedPane.addTab("App Details", None, self.panel, None) # Details of app currently under pentest would be pulled into here through API self.panel_1 = JPanel() self.tabbedPane.addTab("Results", None, self.panel_1, None) # passed results would go inside this and connected to reporting system via API self.panel_2 = JPanel() self.tabbedPane.addTab("Failed Cases", None, self.panel_2, None) #list of failed tests would go inside this self.textField = JTextField() self.textField.setBounds(12, 13, 207, 39) self.panel.add(self.textField) self.textField.setColumns(10) self.comboBox = JComboBox() self.comboBox.setEditable(True) self.comboBox.addItem("Default") self.comboBox.addItem("High") self.comboBox.addItem("Low") self.comboBox.setBounds(46, 65, 130, 28) self.comboBox.addActionListener(self) self.panel.add(self.comboBox) self.btnNewButton = JButton("Submit") self.btnNewButton.setBounds(60, 125, 97, 25) self.panel.add(self.btnNewButton) editorPane = JEditorPane(); editorPane.setBounds(12, 35, 1000, 800); self.panel_2.add(editorPane); self.panel_2.setLayout(BorderLayout()) return self.tabbedPane def getAppRating(self): sys.stdout.write(str(self.val)) return str(self.val) def actionPerformed(self, e): if(e.getSource()==self.comboBox): self.val = self.comboBox.getSelectedItem() else: self.addDetails() def addDetails(self): jf0 = JFrame() jf0.setTitle("Add Issue"); jf0.setLayout(None); txtEnterIssue = JTextField(); txtEnterIssue.setName("Enter Issue Name"); txtEnterIssue.setToolTipText("Enter Issue Name Here"); txtEnterIssue.setBounds(182, 58, 473, 40); jf0.add(txtEnterIssue); txtEnterIssue.setColumns(10); btnNewButton = JButton("Add"); btnNewButton.setBounds(322, 178, 139, 41); jf0.add(btnNewButton); comboBox = JComboBox(); comboBox.setMaximumRowCount(20); comboBox.setEditable(True); comboBox.setToolTipText("Objective Name"); comboBox.setBounds(182, 125, 473, 40); jf0.add(comboBox); lblNewLabel = JLabel("Issue Name Here"); lblNewLabel.setFont(Font("Tahoma", Font.PLAIN, 16)); lblNewLabel.setBounds(25, 58, 130, 40); jf0.add(lblNewLabel); lblNewLabel_1 = JLabel("Objective Name"); lblNewLabel_1.setFont(Font("Tahoma", Font.PLAIN, 16)); lblNewLabel_1.setBounds(25, 125, 130, 40); jf0.add(lblNewLabel_1); jf0.setVisible(True) jf0.setBounds(400, 300, 700, 300) jf0.EXIT_ON_CLOSE txtEnterIssue.addKeyListener(self) def keyPressed(self, e): self.search_string.__add__(self.search_string) self.jtf1.setText(self.search_string) sys.stdout.write(self.search_string)
class BurpExtender(IBurpExtender, IContextMenuFactory, ITab, IExtensionStateListener, IMessageEditorController, IHttpListener): ''' IBurpExtender: Hook into burp and inherit base classes ITab: Create new tabs inside burp IMessageEditorTabFactory: Access createNewInstance ''' def registerExtenderCallbacks(self, callbacks): # Set encoding to utf-8 to avoid some errors reload(sys) sys.setdefaultencoding('utf8') # Keep a reference to callback object and helper object self._callbacks = callbacks self._helpers = callbacks.getHelpers() # Set the extension name that shows in the burp extension menu callbacks.setExtensionName("InjectionScanner") # Create the log and a lock on which to synchronize when adding log entries self._log = ArrayList() self._logLock = Lock() self._httpLock = Lock() # The length of the basis used to fetch abnormal data, default to zero self._basisLen = 0 # 1: {POST. GET}; 2: {urlencoded, json, xml} self._postGet = 'NaN' self._dataType = 'NaN' # Scan list self._simpleList = [ '\'', '\"', '/', '/*', '#', ')', '(', ')\'', '(\'', 'and 1=1', 'and 1=2', 'and 1>2', 'and 12', '+', 'and+12', '/**/and/**/1' ] self._xmlList = ['a', 'b', 'c', 'd', 'e'] # Not setted # Response mutex: True = is blocking; False = free to go # self._mutexR = False # Other classes instance self._dataTable = Guis_DefaultTM() self._logTable = Guis_AbstractTM(self) self._xh = XMLHandler() listeners = Guis_Listeners(self, self._logTable) ''' Setting GUIs ''' # Divide the whole pane two: one upper and one lower pane self._mainSplitpane = JSplitPane(JSplitPane.VERTICAL_SPLIT) self._mainSplitpane.setResizeWeight(0.4) # Initizlize request table dataTable = JTable(self._dataTable) dataScrollPane = JScrollPane(dataTable) dataScrollPane.setPreferredSize(Dimension(0, 125)) self._dataTable.addTableModelListener(listeners) # Initialize log table logTable = Guis_LogTable(self._logTable) logScrollPane = JScrollPane(logTable) logScrollPane.setPreferredSize(Dimension(0, 125)) # Split the upper pane to two panes tableSplitpane = JSplitPane(JSplitPane.HORIZONTAL_SPLIT) tableSplitpane.setResizeWeight(0.5) # Set the data table to the left and log to the right tableSplitpane.setLeftComponent(dataScrollPane) tableSplitpane.setRightComponent(logScrollPane) # 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()) # Create buttons that do operation with the test self._basisLabel = JLabel('Basis: ' + str(self._basisLen)) self._levelLabel = JLabel('Level:') self._setBasisButton = JButton('Set Basis') self._hitOnceButton = JButton('Hit Once') self._autoScanButton = JButton('Auto Scan') self._clearLogButton = JButton('Clear Log') self._cancelButton = JButton('Cancel') self._levelSelection = JComboBox() self._levelSelection.addItem('1') self._levelSelection.addItem('2') self._levelSelection.addItem('3') self._hitOnceButton.addActionListener(listeners) self._autoScanButton.addActionListener(listeners) self._clearLogButton.addActionListener(listeners) self._setBasisButton.addActionListener(listeners) self._cancelButton.addActionListener(listeners) self._basisLabel.setPreferredSize(Dimension(100, 20)) # Create bottom pane for holding the buttons buttonPane = JPanel() buttonPane.setLayout(BorderLayout()) centerPane = JPanel() leftPane = JPanel() rightPane = JPanel() leftPane.add(self._basisLabel) centerPane.add(self._setBasisButton) centerPane.add(self._hitOnceButton) centerPane.add(self._autoScanButton) centerPane.add(self._cancelButton) centerPane.add(self._clearLogButton) rightPane.add(self._levelLabel) rightPane.add(self._levelSelection) buttonPane.add(centerPane, BorderLayout.CENTER) buttonPane.add(leftPane, BorderLayout.WEST) buttonPane.add(rightPane, BorderLayout.EAST) # Create and set the bottom panel that holds viewers and buttons utilPane = JPanel() utilPane.setLayout(BorderLayout()) utilPane.add(tabs, BorderLayout.CENTER) utilPane.add(buttonPane, BorderLayout.SOUTH) self._mainSplitpane.setLeftComponent(tableSplitpane) self._mainSplitpane.setRightComponent(utilPane) # Customize UI components callbacks.customizeUiComponent(self._mainSplitpane) callbacks.customizeUiComponent(dataTable) callbacks.customizeUiComponent(dataScrollPane) callbacks.customizeUiComponent(logTable) callbacks.customizeUiComponent(logScrollPane) callbacks.customizeUiComponent(tabs) callbacks.customizeUiComponent(buttonPane) callbacks.customizeUiComponent(utilPane) callbacks.customizeUiComponent(self._basisLabel) callbacks.customizeUiComponent(self._setBasisButton) callbacks.customizeUiComponent(self._hitOnceButton) callbacks.customizeUiComponent(self._autoScanButton) callbacks.customizeUiComponent(self._clearLogButton) callbacks.customizeUiComponent(self._levelSelection) callbacks.customizeUiComponent(self._cancelButton) # Add the custom tab to Burp's UI callbacks.addSuiteTab(self) # Register the context menu and message editor for new tabs callbacks.registerContextMenuFactory(self) # Register as a HTTP listener callbacks.registerHttpListener(self) return ''' ITab implementation ''' def getTabCaption(self): return 'InjectionScanner' def getUiComponent(self): return self._mainSplitpane ''' IContextMenuFactory implementation ''' def createMenuItems(self, invocation): menu = [] # Which part of the interface the user selects ctx = invocation.getInvocationContext() # Message viewer request will show menu item if selected by the user if ctx == 0 or ctx == 2: menu.append( swing.JMenuItem("Send to InjectionScanner", None, actionPerformed=lambda x, inv=invocation: self. sendToExtender(inv))) return menu if menu else None ''' IMessageEditorController Implementation ''' def getHttpService(self): return self._currentlyDisplayedItem.getHttpService() def getRequest(self): return self._currentlyDisplayedItem.getRequest() def getResponse(self): return self._currentlyDisplayedItem.getResponse() ''' IHttpListener implementation ''' def processHttpMessage(self, toolFlag, messageIsRequest, messageInfo): # Skip this function if the message is request if messageIsRequest: return # Lock the log entry in case race condition self._logLock.acquire() row = self._log.size() # Fetch request message requestBody = messageInfo.getRequest() requestInfo = self._helpers.analyzeResponse(requestBody) requestHeaders = requestInfo.getHeaders() if self._postGet == 'POST': requestData = self._helpers.bytesToString( requestBody[requestInfo.getBodyOffset():]) elif self._postGet == 'GET': for header in requestHeaders: if 'GET' in header: # If the request is GET, update the GET data requestUrl = re.sub('^GET\s+', '', header, re.IGNORECASE) requestUrl = re.sub('\sHTTP/1.1\S*', '', requestUrl, re.IGNORECASE) if '?' in requestUrl: requestData = re.sub('\S*\?', '', requestUrl, re.IGNORECASE) else: print('processHttpMessage: no parameter in GET url') else: print('processHttpMessage: _postGet not defined') self._logLock.release() return # Fetch the http type (GET/POST) httpType = requestHeaders[0].split(' ') # Fetch response message responseBody = messageInfo.getResponse() responseInfo = self._helpers.analyzeResponse(responseBody) responseHeaders = responseInfo.getHeaders() self._responseLength = '' # Fetch the content length self._responseLength = self.fetchContentLength(responseHeaders) # If the response message is auto-generated, ignore it. If not, add it into the log list if self._callbacks.getToolName(toolFlag) != 'Proxy': self._log.add( LogEntry(httpType[0], requestData, self._callbacks.saveBuffersToTempFiles(messageInfo), self._responseLength)) self._logTable.fireTableRowsInserted(row, row) self._logLock.release() ''' Fetch content length from the headers given ''' def fetchContentLength(self, fromHeaders): for header in fromHeaders: if re.search('^Content-Length', header, re.IGNORECASE) is not None: return re.sub('^Content-Length\:\s+', '', header, re.IGNORECASE) ''' When the user select 'Send to InjectionScanner', call this function ''' def sendToExtender(self, invocation): # Init/reset request data before sending to extender self.initRequestInfo() try: # Initialize basic information invMessage = invocation.getSelectedMessages() requestMessage = invMessage[0] requestInfo = self._helpers.analyzeRequest(requestMessage) self._requestBody = requestMessage.getRequest() # Set the _currentlyDisplayedItem so each time the data is sent to the extender self._currentlyDisplayedItem = self._callbacks.saveBuffersToTempFiles( requestMessage) # Fetch the request data bodyLen = len(self._helpers.bytesToString(self._requestBody)) if requestInfo.getBodyOffset() < bodyLen: self._requestData = self._helpers.bytesToString( self._requestBody[requestInfo.getBodyOffset():]) elif requestInfo.getBodyOffset() == bodyLen: self._requestData = '' else: print('sendToExtender: body length < body offset') # Fetch the headers and Http service requestHeaders = list(requestInfo.getHeaders()) self._httpService = requestMessage.getHttpService() # Initialize POST/GET identifier and User-Agent for header in requestHeaders: if re.search('^POST', header, re.IGNORECASE) is not None: self._postGet = 'POST' elif re.search('^GET', header, re.IGNORECASE) is not None: self._postGet = 'GET' # If the request is GET, initialize the url and GET data self._requestUrl = re.sub('^GET\s+', '', header, re.IGNORECASE) self._requestUrl = re.sub('\sHTTP/1.1\S*', '', self._requestUrl, re.IGNORECASE) if '?' in self._requestUrl: self._requestDataGet = re.sub('\S*\?', '', self._requestUrl, re.IGNORECASE) else: print('sendToExtender: no parameter in GET url') # If the request if POST, fetch the request data type by content type if self._postGet == 'POST' and re.search( '^Content-Type', header, re.IGNORECASE) is not None: contentType = re.sub('^Content-Type', '', header, re.IGNORECASE) if 'urlencoded' in contentType: self._dataType = 'urlencoded' elif 'json' in contentType: self._dataType = 'json' elif 'xml' in contentType or 'http' in conentType: self._dataType = 'xml' else: print( 'sendToExtender: _dataType is not supported, do not scan' ) # Initialze the User-Agent if it exists if re.search('^User-Agent', header, re.IGNORECASE) is not None: self._userAgent = re.sub('^User-Agent\:\s+', '', header, re.IGNORECASE) # If there's no content type in the header,fetch from data if self._postGet == 'POST' and self._dataType == '': if self._requestData != '': if self._requestData[ 0] == '{' and '}' in self._requestData and ':' in self._requestData: self._dataType = 'json' elif self._requestData[0] == '<' and self._requestData[ -1] == '>': self._dataType = 'xml' else: self._dataType = 'urlencoded' else: print( 'sendToExtender: _postGet is POST but _requestData is null' ) # Clear the table before adding elements self._dataTable.setRowCount(0) # Update request viewer self.updateRequestViewer() # Fill request data self.fillRequestData() except Exception as e: print(e) ''' Fill the data into the request table ''' def fillRequestData(self): # If _postGet is GET, also adds URL to the table if self._postGet == 'GET': dataList = self._requestDataGet.split('&') for data in dataList: if '=' in data: x = data.split('=', 1) self._dataDict[str(x[0])] = str(x[1]) self._dataTable.addRow([str(x[0]), str(x[1])]) self._dataLen += 1 self._dataTable.addRow(['URL', self._requestUrl]) self._UrlRow = self._dataLen if self._userAgent != '': self._dataTable.addRow(['User-Agent', self._userAgent]) elif self._postGet == 'POST': if self._dataType == 'urlencoded': dataList = self._requestData.split('&') for data in dataList: if '=' in data: x = data.split('=', 1) self._dataDict[str(x[0])] = str(x[1]) self._dataTable.addRow([str(x[0]), str(x[1])]) self._dataLen += 1 elif self._dataType == 'json': self._dataDict = json.loads(self._requestData) for key in self._dataDict: # Convert '"' to '\"' to be the same as that in the data value = str(self._dataDict[key]) if '\"' in value: value = value.replace('\"', '\\\"') self._dataDict[key] = value self._dataTable.addRow([str(key), self._dataDict[key]]) self._dataLen += 1 elif self._dataType == 'xml': # Use xml package to convert the xml string to dict # Note1: the xml dict will be in reverse order # Note2: the arrtibute will also be added into dict, need to be pop # Note3: special characters like \" will be considered as " xml.sax.parseString(self._requestData, self._xh) self._attr = re.sub('\>(\S*\s*)*', '', self._requestData[1:], re.IGNORECASE) self._dataDict = self._xh.getDict() self._dataDict.pop(self._attr) for key in self._dataDict: self._dataTable.addRow( [str(key), str(self._dataDict[key])]) self._dataLen += 1 else: print('fillRequestData: _dataType not defined') if self._userAgent != '': self._dataTable.addRow(['User-Agent', self._userAgent]) self._savedUserAgent = self._userAgent else: print('fillRequestData: _postGet not defined') ''' Receive & update the response after sending request to the server ''' def receiveResponse(self): # Init/reset response data before receiving response self.initResponseInfo() # Launch the http thread self._httpThread = Thread(target=self.makeRequest, args=( self._httpService, self._requestBody, )) self._httpThread.start() ''' Make Http request to a service ''' def makeRequest(self, httpService, requestBody): self._httpLock.acquire() # Disable the hit buttons before starting the thread self._hitOnceButton.setEnabled(False) self._autoScanButton.setEnabled(False) self._responseMessage = self._callbacks.makeHttpRequest( httpService, requestBody) # Enable the hit buttons self._hitOnceButton.setEnabled(True) self._autoScanButton.setEnabled(True) # Unblock the mutex self._httpLock.release() ''' updateRequestViewer ''' def updateRequestViewer(self): self._requestViewer.setMessage(self.getRequest(), True) ''' updateResponseViewer ''' def updateResponseViewer(self): self._responseViewer.setMessage(self.getResponse(), False) ''' Level 1 auto: only loop through the data, do not modify the 'submit' section ''' def autoScan1(self): # TODO: Add a 'cancel' button to stop when the user think it takes too long # TODO: Add XML support if self._postGet == 'GET': for i in range(0, self._dataLen): title = self._dataTable.getValueAt(i, 0) baseValue = self._dataDict[title] for value in self._simpleList: # TODO: update more value that should not be changed if 'submit' not in title.lower( ) and 'submit' not in self._dataDict[title].lower( ) and 'search' not in title.lower( ) and 'search' not in self._dataDict[title].lower(): # Update the table in case the loop interrupt in the middle # Note that the URL will be automatically updated due to this code, so no need to manually update the URL section self._dataTable.setValueAt(value, i, 1) # Send & request the HTTP request/response self.updateRequestViewer() self.receiveResponse() # Reset the table self._dataTable.setValueAt(baseValue, i, 1) if self._postGet == 'POST': if self._dataType == 'urlencoded' or self._dataType == 'json': for i in range(0, self._dataLen): title = self._dataTable.getValueAt(i, 0) baseValue = self._dataDict[title] if 'submit' in title.lower() or 'submit' in self._dataDict[ title].lower() or 'search' in title.lower( ) or 'search' in self._dataDict[title].lower(): continue for value in self._simpleList: self._dataTable.setValueAt(value, i, 1) self.updateRequestViewer() self.receiveResponse() # Reset the table self._dataTable.setValueAt(baseValue, i, 1) elif self._dataType == 'xml': for i in range(0, self._dataLen): title = self._dataTable.getValueAt(i, 0) baseValue = self._dataDict[title] for value in self._xmlList: # Update the table in case the loop interrupt in the middle self._dataTable.setValueAt(value, i, 1) # Send & request the HTTP request/response self.updateRequestViewer() self.receiveResponse() # Reset the table self._dataTable.setValueAt(baseValue, i, 1) ''' Level 2 auto: loop through the data as well as the user agent (if exist) ''' def autoScan2(self): # If the User-Agent does not exist, only performs level 1 auto if self._userAgent != '': baseUserAgent = self._userAgent baseExpression = 'User-Agent: ' + baseUserAgent for value in self._simpleList: oldExpression = 'User-Agent: ' + self._userAgent newExpression = 'User-Agent: ' + value # Update the values accordingly requestBodyString = self._helpers.bytesToString( self._requestBody) self._requestBody = requestBodyString.replace( oldExpression, newExpression) self._userAgent = value self.updateRequestViewer() self.receiveResponse() # Reset the value back to original after each loop requestBodyString = self._helpers.bytesToString(self._requestBody) self._requestBody = requestBodyString.replace( newExpression, baseExpression) self._savedUserAgent = baseUserAgent self.updateRequestViewer() # Perform level 1 scan also self.autoScan1() ''' Level 3 auto: Alpha: use the timer to perform blind insertion ''' # TODO: 目前只支持GET/urlencoded,后续添加更多支持 def autoScan3(self): self._timeReach = False timer = Timer(5, self.timeReach) # Modify the first element to perform blind injection title = self._dataTable.getValueAt(i, 0) oldExpression = title + '=' + self._dataDict[title] newExpression = title + '=' + '1\' and if(1=0,1, sleep(10)) --+' if self._postGet == 'GET': # Update the values accordingly requestBodyString = self._helpers.bytesToString(self._requestBody) self._requestBody = requestBodyString.replace( oldExpression, newExpression) self._requestDataGet = self._requestDataGet.replace( oldExpression, newExpression) self._requestUrl = self._requestUrl.replace( oldExpression, newExpression) self._dataDict[title] = '1\' and if(1=0,1, sleep(10)) --+' self._requestModel.setValueAt('1\' and if(1=0,1, sleep(10)) --+', 0, 1) elif self._postGet == 'POST': if self._dataType == 'urlencoded': # Update the values accordingly requestBodyString = self._helpers.bytesToString( self._requestBody) self._requestBody = requestBodyString.replace( oldExpression, newExpression) self._requestData = self._requestData.replace( oldExpression, newExpression) self._dataDict[title] = '1\' and if(1=0,1, sleep(10)) --+' self._requestModel.setValueAt( '1\' and if(1=0,1, sleep(10)) --+', 0, 1) else: print('autoScan3: _dataType not supported') else: print('autoScan3: _postGet not defined') timer.start() self.updateRequestViewer() self.receiveResponse() # Print the result if self._timeReach: print('Delay scan succeed') else: print('Delay scan failed') # Cancel the timer timer.cancel() def timeReach(self): self._timeReach = True ''' Fetch the 'abnormal' payloads that shows very different response length from the normal ones ''' def getAbnormal(self, basis, coefficient): # If the basis is not set, do nothing abnormList = ArrayList() if basis == 0: return None # Fetch the abnormals from the log list for log in self._log: if float(log._responseLen) / float(basis) < coefficient or float( basis) / float(log._responseLen) < coefficient: abnormList.append(log._payload) return abnormList ''' Turn a simple dict of key/value pairs into XML ''' def dictToXml(self, tag, d): elem = Element(tag) for key, val in d.items(): child = Element(key) child.text = str(val) # Add element in reverse order so that the result is correct elem.insert(0, child) return elem ''' initRequestInfo ''' def initRequestInfo(self): self._postGet = '' self._userAgent = '' self._requestUrl = '' self._requestBody = '' self._requestData = '' self._requestDataGet = '' self._httpService = None self._dataDict = {} self._dataType = '' self._dataLen = 0 self._attr = '' self._contentLength = 0 self._currentlyDisplayedItem = None ''' initResponseInfo ''' def initResponseInfo(self): self._responseBody = None self._responseMessage = None self._responseLength = '' ''' printRequest ''' def printRequest(self): print('----------------') print(self._postGet) print('----------------') print(self._userAgent) print('----------------') print(self._requestUrl) print('----------------') print(self._requestBody) print('----------------') print(self._requestData) print('----------------') print(self._requestDataGet) print('----------------') print(self._httpService) print('----------------') print(self._dataDict) print('----------------') print(self._dataLen) print('----------------') print(self._attr) print('----------------') ''' printResponse ''' def printResponse(self): print('----------------') print(self._responseBody) print('----------------') print(self._responseMessage) print('----------------') print(self._responseLength) print('----------------')
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")