class EditSymbolAttr(JPanel): def __init__(self, sattr): self.attr = sattr self.cbox = JColorChooser(self.attr.color) self.sz_field = JTextField(str(self.attr.size)) szpanel = JPanel() szpanel.add(self.sz_field) szpanel.setBorder(BorderFactory.createTitledBorder("symbol size (integer)")) self.filled_box = JCheckBox("Filled ?:",self.attr.filled) self.shape_cbox = JComboBox(SymbolProps.sym_shape_map.keys()) self.shape_cbox.setSelectedItem(self.attr.shape) self.shape_cbox.setBorder(BorderFactory.createTitledBorder("Shape")) panel1 = JPanel() panel1.setLayout(BorderLayout()) panel1.add(szpanel,BorderLayout.NORTH) panel2 = JPanel() panel2.setLayout(GridLayout(1,2)) panel2.add(self.shape_cbox) panel2.add(self.filled_box) panel1.add(panel2,BorderLayout.SOUTH) self.setLayout(BorderLayout()) self.add(self.cbox,BorderLayout.CENTER) self.add(panel1,BorderLayout.SOUTH) def setAttribute(self,sattr): self.attr = sattr self.cbox.color = self.attr.color self.sz_field.text = str(self.attr.size) self.shape_cbox.setSelectedItem(self.attr.shape) def update(self): self.attr.color = self.cbox.getColor() self.attr.size = string.atoi(self.sz_field.getText()) self.attr.filled = self.filled_box.isSelected() self.attr.shape = self.shape_cbox.getSelectedItem() self.attr.sym = self.attr.createSymbol()
class _AccountAdder: def __init__(self, contactslist): self.contactslist = contactslist self.mainframe = JFrame("Add New Contact") self.account = JComboBox(self.contactslist.clientsByName.keys()) self.contactname = JTextField() self.buildpane() def buildpane(self): buttons = JPanel() buttons.add(JButton("OK", actionPerformed=self.add)) buttons.add(JButton("Cancel", actionPerformed=self.cancel)) acct = JPanel(GridLayout(1, 2), doublebuffered) acct.add(JLabel("Account")) acct.add(self.account) mainpane = self.mainframe.getContentPane() mainpane.setLayout(BoxLayout(mainpane, BoxLayout.Y_AXIS)) mainpane.add(self.contactname) mainpane.add(acct) mainpane.add(buttons) self.mainframe.pack() self.mainframe.show() #action listeners def add(self, ae): acct = self.contactslist.clientsByName[self.account.getSelectedItem()] acct.addContact(self.contactname.getText()) self.mainframe.dispose() def cancel(self, ae): self.mainframe.dispose()
class PrefsPanel(JPanel): """JPanle with gui for tool preferences """ def __init__(self, app): strings = app.strings self.setLayout(GridLayout(3, 2, 5, 5)) userLbl = JLabel(strings.getString("osmose_pref_username")) self.userTextField = JTextField(20) self.userTextField.setToolTipText( strings.getString("osmose_pref_username_tooltip")) levelLbl = JLabel(strings.getString("osmose_pref_level")) self.levels = ["1", "1,2", "1,2,3", "2", "3"] self.levelsCombo = JComboBox(self.levels) self.levelsCombo.setToolTipText( strings.getString("osmose_pref_level_tooltip")) limitLbl = JLabel(strings.getString("osmose_pref_limit")) self.limitTextField = JTextField(20) self.limitTextField.setToolTipText( strings.getString("osmose_pref_limit_tooltip")) self.add(userLbl) self.add(self.userTextField) self.add(levelLbl) self.add(self.levelsCombo) self.add(limitLbl) self.add(self.limitTextField) def update_gui(self, preferences): """Update preferences gui """ self.userTextField.setText(preferences["username"]) self.levelsCombo.setSelectedIndex( self.levels.index(preferences["level"])) self.limitTextField.setText(str(preferences["limit"])) def read_gui(self): """Read preferences from gui """ username = self.userTextField.getText() level = self.levelsCombo.getSelectedItem() limit = self.limitTextField.getText() try: limit = Integer.parseInt(limit) if limit > 500: limit = 500 limit = str(limit) except NumberFormatException: limit = "" preferences = { "username": username.strip(), "level": level, "limit": limit } return preferences
class EditCurveAttr(JPanel): def __init__(self, cattr): self.attr = cattr self.cbox = JColorChooser(self.attr.color) self.sym_panel = EditSymbolAttr(cattr.sym_prop) self.thickness_field = JTextField(str(cattr.thickness), 2) self.draw_symbol_box = JCheckBox("Draw Symbol?", cattr.draw_symbol) self.dps_field = JTextField(str(self.attr.data_per_symbol), 2) self.dash_box = JComboBox(CurveProps.DASH_TYPES.keys()) self.dash_box.setSelectedItem(self.attr.dash_type) self.dash_box.setBorder( BorderFactory.createTitledBorder("Dash type: (Only JDK2 & Slow!)")) tpanelx = JPanel() tpanelx.add(self.thickness_field) tpanelx.setBorder( BorderFactory.createTitledBorder("curve thickness (integer)")) tpanely = JPanel() tpanely.add(self.dps_field) tpanely.setBorder( BorderFactory.createTitledBorder("data per symbol(integer)")) tpanel = JPanel() tpanel.setLayout(GridLayout(2, 2)) tpanel.add(self.draw_symbol_box) tpanel.add(tpanelx) tpanel.add(tpanely) tpanel.add(self.dash_box) panel1 = JPanel() panel1.setLayout(BorderLayout()) panel1.add(self.cbox, BorderLayout.CENTER) panel1.add(tpanel, BorderLayout.SOUTH) panel2 = JPanel() panel2.setLayout(BorderLayout()) panel2.add(self.sym_panel, BorderLayout.CENTER) tp1 = JTabbedPane() tp1.addTab("Curve Attributes", panel1) tp1.addTab("Symbol Attributes", panel2) tp1.setSelectedComponent(panel1) self.setLayout(BorderLayout()) self.add(tp1, BorderLayout.CENTER) def setAttribute(self, cattr): self.attr = cattr self.cbox.color = self.attr.color self.sym_panel.setAttribute(cattr.sym_prop) self.thickness_field.text = str(cattr.thickness) self.dps_field.text = str(cattr.data_per_symbol) self.draw_symbol_box.setSelected(cattr.draw_symbol) self.dash_box.setSelectedItem(cattr.dash_type) def update(self): self.attr.color = self.cbox.getColor() self.attr.thickness = string.atoi(self.thickness_field.text) self.attr.data_per_symbol = string.atoi(self.dps_field.text) self.attr.draw_symbol = self.draw_symbol_box.isSelected() self.attr.dash_type = self.dash_box.getSelectedItem() #print 'Updating Self.draw_symbol',self.draw_symbol,self.attr self.sym_panel.update()
class PrefsPanel(JPanel): """JPanle with gui for tool preferences """ def __init__(self, app): strings = app.strings self.setLayout(GridLayout(3, 2, 5, 5)) userLbl = JLabel(strings.getString("osmose_pref_username")) self.userTextField = JTextField(20) self.userTextField.setToolTipText(strings.getString("osmose_pref_username_tooltip")) levelLbl = JLabel(strings.getString("osmose_pref_level")) self.levels = ["1", "1,2", "1,2,3", "2", "3"] self.levelsCombo = JComboBox(self.levels) self.levelsCombo.setToolTipText(strings.getString("osmose_pref_level_tooltip")) limitLbl = JLabel(strings.getString("osmose_pref_limit")) self.limitTextField = JTextField(20) self.limitTextField.setToolTipText(strings.getString("osmose_pref_limit_tooltip")) self.add(userLbl) self.add(self.userTextField) self.add(levelLbl) self.add(self.levelsCombo) self.add(limitLbl) self.add(self.limitTextField) def update_gui(self, preferences): """Update preferences gui """ self.userTextField.setText(preferences["username"]) self.levelsCombo.setSelectedIndex(self.levels.index(preferences["level"])) self.limitTextField.setText(str(preferences["limit"])) def read_gui(self): """Read preferences from gui """ username = self.userTextField.getText() level = self.levelsCombo.getSelectedItem() limit = self.limitTextField.getText() try: limit = Integer.parseInt(limit) if limit > 500: limit = 500 limit = str(limit) except NumberFormatException: limit = "" preferences = {"username": username.strip(), "level": level, "limit": limit} return preferences
class EditCurveAttr(JPanel): def __init__(self, cattr): self.attr = cattr self.cbox = JColorChooser(self.attr.color) self.sym_panel = EditSymbolAttr(cattr.sym_prop) self.thickness_field = JTextField(str(cattr.thickness),2) self.draw_symbol_box = JCheckBox("Draw Symbol?",cattr.draw_symbol) self.dps_field = JTextField(str(self.attr.data_per_symbol),2) self.dash_box = JComboBox(CurveProps.DASH_TYPES.keys()) self.dash_box.setSelectedItem(self.attr.dash_type) self.dash_box.setBorder(BorderFactory.createTitledBorder("Dash type: (Only JDK2 & Slow!)")) tpanelx = JPanel() tpanelx.add(self.thickness_field) tpanelx.setBorder(BorderFactory.createTitledBorder("curve thickness (integer)")) tpanely = JPanel() tpanely.add(self.dps_field) tpanely.setBorder(BorderFactory.createTitledBorder("data per symbol(integer)")) tpanel = JPanel();tpanel.setLayout(GridLayout(2,2)); tpanel.add(self.draw_symbol_box); tpanel.add(tpanelx); tpanel.add(tpanely); tpanel.add(self.dash_box); panel1 = JPanel() panel1.setLayout(BorderLayout()) panel1.add(self.cbox,BorderLayout.CENTER) panel1.add(tpanel, BorderLayout.SOUTH) panel2 = JPanel() panel2.setLayout(BorderLayout()) panel2.add(self.sym_panel,BorderLayout.CENTER) tp1 = JTabbedPane() tp1.addTab("Curve Attributes",panel1) tp1.addTab("Symbol Attributes",panel2) tp1.setSelectedComponent(panel1) self.setLayout(BorderLayout()) self.add(tp1,BorderLayout.CENTER) def setAttribute(self,cattr): self.attr = cattr self.cbox.color = self.attr.color self.sym_panel.setAttribute(cattr.sym_prop) self.thickness_field.text = str(cattr.thickness) self.dps_field.text = str(cattr.data_per_symbol) self.draw_symbol_box.setSelected(cattr.draw_symbol) self.dash_box.setSelectedItem(cattr.dash_type) def update(self): self.attr.color = self.cbox.getColor() self.attr.thickness = string.atoi(self.thickness_field.text) self.attr.data_per_symbol = string.atoi(self.dps_field.text) self.attr.draw_symbol = self.draw_symbol_box.isSelected() self.attr.dash_type = self.dash_box.getSelectedItem() #print 'Updating Self.draw_symbol',self.draw_symbol,self.attr self.sym_panel.update()
class C5Panel(JPanel): def __init__(self,hostname): self.hostname=hostname JPanel.__init__(self,BorderLayout()) self.cbActionListener=foo2(self) #imglist=os.listdir('./img') #try:imglist.remove('.svn') #except:pass imglist=['01-CircleOfFifths.gif','Fifths.png','circle-o-fifths.jpg','Circle_Of_Fifths.gif','Keywheel.gif','circle-of-fifths.gif','ColorFifths.jpg','cof.gif'] self.cb=JComboBox(imglist,actionListener=self.cbActionListener)# #self.cb.addItemListener(self.cbCB) tb=JPanel() tb.setLayout(FlowLayout(FlowLayout.CENTER)) tb.add(self.cb) self.add(tb,'Center') self.img=None if hostname[0:7]=='http://': self.img=ImageIO.read(URL(self.hostname+'/static/sightreadingtrainer/img/'+imglist[0])) else: self.img=ImageIO.read(File(self.hostname+'img/'+imglist[0])) icon=ImageIcon(self.img) self.label=JLabel(icon) self.add(self.label,'North') def cbCB(self,e): try: item=self.cb.getSelectedItem() if DEBUG:print item if self.hostname[0:7]=='http://': self.img=ImageIO.read(URL(self.hostname+'/static/sightreadingtrainer/img/'+item)) else: self.img=ImageIO.read(File(self.hostname+'img/'+item)) if DEBUG:print self.img icon=ImageIcon(self.img) self.label.setIcon(icon) except Exception,e: if DEBUG:print e
def create_gui(): global dropdown, current_file frame = JFrame('', defaultCloseOperation = JFrame.DISPOSE_ON_CLOSE, size = (400, 150)); frame.setBounds(350,350,400,150); container_panel = JPanel(GridBagLayout()); c = GridBagConstraints(); dropdown = JComboBox(list(img_paths.keys())); c.fill = GridBagConstraints.HORIZONTAL; c.gridx = 0; c.gridy = 0; c.weightx = 0.5; c.gridwidth = 3; container_panel.add(dropdown, c); add_file_button = JButton('<html>Add Image/File</html>', actionPerformed=select_file); c.fill = GridBagConstraints.HORIZONTAL; c.gridx = 3; c.gridy = 0; c.weightx = 0.5; c.gridwidth = 1; container_panel.add(add_file_button, c); process_file_button = JButton('<html>Process Selected Image</html>', actionPerformed=process_current_img); c.fill = GridBagConstraints.HORIZONTAL; c.gridx = 0; c.gridy = 1; c.weightx = 0.5; c.gridwidth = 2; container_panel.add(process_file_button, c); process_all_button = JButton('<html>Process Entire Stack</html>', actionPerformed=process_stack); c.fill = GridBagConstraints.HORIZONTAL; c.gridx = 2; c.gridy = 1; c.weightx = 0.5; c.gridwidth = 2; container_panel.add(process_all_button, c); current_file = dropdown.getSelectedItem(); frame.add(container_panel); frame.visible = True;
class SignInputPanel(PropertyInputPanel,DocumentListener): def __init__(self,property): PropertyInputPanel.__init__(self,property) self.comboBox = JComboBox(["Unconstrained", "Positive", "Negative"]) self.add(self.comboBox) def isValueSet(self): return True def getValue(self): item = self.comboBox.getSelectedItem() if item=="Positive": return 1 elif item =="Negative": return -1 else: return 0 def setValue(self, value): pass
class EditSymbolAttr(JPanel): def __init__(self, sattr): self.attr = sattr self.cbox = JColorChooser(self.attr.color) self.sz_field = JTextField(str(self.attr.size)) szpanel = JPanel() szpanel.add(self.sz_field) szpanel.setBorder( BorderFactory.createTitledBorder("symbol size (integer)")) self.filled_box = JCheckBox("Filled ?:", self.attr.filled) self.shape_cbox = JComboBox(SymbolProps.sym_shape_map.keys()) self.shape_cbox.setSelectedItem(self.attr.shape) self.shape_cbox.setBorder(BorderFactory.createTitledBorder("Shape")) panel1 = JPanel() panel1.setLayout(BorderLayout()) panel1.add(szpanel, BorderLayout.NORTH) panel2 = JPanel() panel2.setLayout(GridLayout(1, 2)) panel2.add(self.shape_cbox) panel2.add(self.filled_box) panel1.add(panel2, BorderLayout.SOUTH) self.setLayout(BorderLayout()) self.add(self.cbox, BorderLayout.CENTER) self.add(panel1, BorderLayout.SOUTH) def setAttribute(self, sattr): self.attr = sattr self.cbox.color = self.attr.color self.sz_field.text = str(self.attr.size) self.shape_cbox.setSelectedItem(self.attr.shape) def update(self): self.attr.color = self.cbox.getColor() self.attr.size = string.atoi(self.sz_field.getText()) self.attr.filled = self.filled_box.isSelected() self.attr.shape = self.shape_cbox.getSelectedItem() self.attr.sym = self.attr.createSymbol()
class Export(): def __init__(self, extender): self._extender = extender self.BYPASSSED_STR = extender.BYPASSSED_STR self.ENFORCED_STR = extender.ENFORCED_STR self.IS_ENFORCED_STR = extender.IS_ENFORCED_STR self._log = extender._log self.save_restore = SaveRestore(extender) def draw(self): """ init Save/Restore """ exportLabel = JLabel("Export:") exportLabel.setBounds(10, 10, 100, 30) labelFont = exportLabel.getFont() boldFont = Font(labelFont.getFontName(), Font.BOLD, labelFont.getSize()) exportLabel.setFont(boldFont) exportLType = JLabel("File Type:") exportLType.setBounds(10, 50, 100, 30) exportFileTypes = ["HTML", "CSV"] self.exportType = JComboBox(exportFileTypes) self.exportType.setBounds(100, 50, 200, 30) exportES = ["All Statuses", "As table filter", self._extender.BYPASSSED_STR, self._extender.IS_ENFORCED_STR, self._extender.ENFORCED_STR] self.exportES = JComboBox(exportES) self.exportES.setBounds(100, 90, 200, 30) exportLES = JLabel("Statuses:") exportLES.setBounds(10, 90, 100, 30) self.exportButton = JButton("Export", actionPerformed=self.export) self.exportButton.setBounds(390, 50, 100, 30) saveRestoreLabel = JLabel("Save / Restore:") saveRestoreLabel.setBounds(10, 250, 100, 30) saveRestoreLabel.setFont(boldFont) self.saveStateButton = JButton("Save state", actionPerformed=self.saveStateAction) self.saveStateButton.setBounds(10, 200, 100, 30) self.restoreStateButton = JButton("Restore state", actionPerformed=self.restoreStateAction) self.restoreStateButton.setBounds(390, 200, 100, 30) self._extender.exportPnl = JPanel() exportPnl = self._extender.exportPnl exportPnl.setLayout(None) exportPnl.setBounds(0, 0, 1000, 1000) exportPnl.add(exportLabel) exportPnl.add(exportLType) exportPnl.add(self.exportType) exportPnl.add(exportLES) exportPnl.add(self.exportES) exportPnl.add(self.exportButton) exportPnl.add(saveRestoreLabel) exportPnl.add(self.saveStateButton) exportPnl.add(self.restoreStateButton) def export(self, event): if self.exportType.getSelectedItem() == "HTML": self.exportToHTML() else: self.exportToCSV() def saveStateAction(self, event): self.save_restore.saveState() def restoreStateAction(self, event): self.save_restore.restoreState() def exportToHTML(self): parentFrame = JFrame() fileChooser = JFileChooser() fileChooser.setSelectedFile(File("AutorizeReport.html")) fileChooser.setDialogTitle("Save Autorize Report") userSelection = fileChooser.showSaveDialog(parentFrame) if userSelection == JFileChooser.APPROVE_OPTION: fileToSave = fileChooser.getSelectedFile() enforcementStatusFilter = self.exportES.getSelectedItem() htmlContent = """<html><title>Autorize Report by Barak Tawily</title> <style> .datagrid table { border-collapse: collapse; text-align: left; width: 100%; } .datagrid {font: normal 12px/150% Arial, Helvetica, sans-serif; background: #fff; overflow: hidden; border: 1px solid #006699; -webkit-border-radius: 3px; -moz-border-radius: 3px; border-radius: 3px; } .datagrid table td, .datagrid table th { padding: 3px 10px; } .datagrid table thead th {background:-webkit-gradient( linear, left top, left bottom, color-stop(0.05, #006699), color-stop(1, #00557F) );background:-moz-linear-gradient( center top, #006699 5%, #00557F 100% );filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#006699', endColorstr='#00557F');background-color:#006699; color:#FFFFFF; font-size: 15px; font-weight: bold; border-left: 1px solid #0070A8; } .datagrid table thead th:first-child { border: none; }.datagrid table tbody td { color: #00496B; border-left: 1px solid #E1EEF4;font-size: 12px;font-weight: normal; }.datagrid table tbody .alt td { background: #E1EEF4; color: #00496B; }.datagrid table tbody td:first-child { border-left: none; }.datagrid table tbody tr:last-child td { border-bottom: none; }.datagrid table tfoot td div { border-top: 1px solid #006699;background: #E1EEF4;} .datagrid table tfoot td { padding: 0; font-size: 12px } .datagrid table tfoot td div{ padding: 2px; }.datagrid table tfoot td ul { margin: 0; padding:0; list-style: none; text-align: right; }.datagrid table tfoot li { display: inline; }.datagrid table tfoot li a { text-decoration: none; display: inline-block; padding: 2px 8px; margin: 1px;color: #FFFFFF;border: 1px solid #006699;-webkit-border-radius: 3px; -moz-border-radius: 3px; border-radius: 3px; background:-webkit-gradient( linear, left top, left bottom, color-stop(0.05, #006699), color-stop(1, #00557F) );background:-moz-linear-gradient( center top, #006699 5%, #00557F 100% );filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#006699', endColorstr='#00557F');background-color:#006699; }.datagrid table tfoot ul.active, .datagrid table tfoot ul a:hover { text-decoration: none;border-color: #006699; color: #FFFFFF; background: none; background-color:#00557F;}div.dhtmlx_window_active, div.dhx_modal_cover_dv { position: fixed !important; } table { width: 100%; table-layout: fixed; } td { border: 1px solid #35f; overflow: hidden; text-overflow: ellipsis; } td.a { width: 13%; white-space: nowrap; } td.b { width: 9%; word-wrap: break-word; } </style> <body> <h1>Autorize Report<h1> <div class="datagrid"><table> <thead><tr><th width=\"3%\">ID</th><th width=\"5%\">Method</th><th width=\"43%\">URL</th><th width=\"9%\">Original length</th><th width=\"9%\">Modified length</th><th width=\"9%\">Unauthorized length</th><th width=\"11%\">Authorization Enforcement Status</th><th width=\"11%\">Authorization Unauthenticated Status</th></tr></thead> <tbody>""" for i in range(0,self._log.size()): color_modified = "" if self._log.get(i)._enfocementStatus == self.BYPASSSED_STR: color_modified = "red" elif self._log.get(i)._enfocementStatus == self.IS_ENFORCED_STR: color_modified = "yellow" elif self._log.get(i)._enfocementStatus == self.ENFORCED_STR: color_modified = "LawnGreen" color_unauthorized = "" if self._log.get(i)._enfocementStatusUnauthorized == self.BYPASSSED_STR: color_unauthorized = "red" elif self._log.get(i)._enfocementStatusUnauthorized == self.IS_ENFORCED_STR: color_unauthorized = "yellow" elif self._log.get(i)._enfocementStatusUnauthorized == self.ENFORCED_STR: color_unauthorized = "LawnGreen" if enforcementStatusFilter == "All Statuses": htmlContent += "<tr><td>%d</td><td>%s</td><td><a href=\"%s\">%s</a></td><td>%d</td><td>%d</td><td>%d</td><td bgcolor=\"%s\">%s</td><td bgcolor=\"%s\">%s</td></tr>" % (self._log.get(i)._id, self._log.get(i)._method, self._log.get(i)._url, self._log.get(i)._url, len(self._log.get(i)._originalrequestResponse.getResponse()) if self._log.get(i)._originalrequestResponse is not None else 0, len(self._log.get(i)._requestResponse.getResponse()) if self._log.get(i)._requestResponse is not None else 0, len(self._log.get(i)._unauthorizedRequestResponse.getResponse()) if self._log.get(i)._unauthorizedRequestResponse is not None else 0, color_modified, self._log.get(i)._enfocementStatus, color_unauthorized, self._log.get(i)._enfocementStatusUnauthorized) elif enforcementStatusFilter == "As table filter": if ((self._extender.showAuthBypassModified.isSelected() and self.BYPASSSED_STR == self._log.get(i)._enfocementStatus) or (self._extender.showAuthPotentiallyEnforcedModified.isSelected() and "Is enforced???" == self._log.get(i)._enfocementStatus) or (self._extender.showAuthEnforcedModified.isSelected() and self.ENFORCED_STR == self._log.get(i)._enfocementStatus) or (self._extender.showAuthBypassUnauthenticated.isSelected() and self.BYPASSSED_STR == self._log.get(i)._enfocementStatusUnauthorized) or (self._extender.showAuthPotentiallyEnforcedUnauthenticated.isSelected() and "Is enforced???" == self._log.get(i)._enfocementStatusUnauthorized) or (self._extender.showAuthEnforcedUnauthenticated.isSelected() and self.ENFORCED_STR == self._log.get(i)._enfocementStatusUnauthorized) or (self._extender.showDisabledUnauthenticated.isSelected() and "Disabled" == self._log.get(i)._enfocementStatusUnauthorized)): htmlContent += "<tr><td>%d</td><td>%s</td><td><a href=\"%s\">%s</a></td><td>%d</td><td>%d</td><td>%d</td><td bgcolor=\"%s\">%s</td><td bgcolor=\"%s\">%s</td></tr>" % (self._log.get(i)._id, self._log.get(i)._method, self._log.get(i)._url, self._log.get(i)._url, len(self._log.get(i)._originalrequestResponse.getResponse()) if self._log.get(i)._originalrequestResponse is not None else 0, len(self._log.get(i)._requestResponse.getResponse()) if self._log.get(i)._requestResponse is not None else 0, len(self._log.get(i)._unauthorizedRequestResponse.getResponse()) if self._log.get(i)._unauthorizedRequestResponse is not None else 0, color_modified, self._log.get(i)._enfocementStatus, color_unauthorized, self._log.get(i)._enfocementStatusUnauthorized) else: if (enforcementStatusFilter == self._log.get(i)._enfocementStatus) or (enforcementStatusFilter == self._log.get(i)._enfocementStatusUnauthorized): htmlContent += "<tr><td>%d</td><td>%s</td><td><a href=\"%s\">%s</a></td><td>%d</td><td>%d</td><td>%d</td><td bgcolor=\"%s\">%s</td><td bgcolor=\"%s\">%s</td></tr>" % (self._log.get(i)._id, self._log.get(i)._method, self._log.get(i)._url, self._log.get(i)._url, len(self._log.get(i)._originalrequestResponse.getResponse()) if self._log.get(i)._originalrequestResponse is not None else 0, len(self._log.get(i)._requestResponse.getResponse()) if self._log.get(i)._requestResponse is not None else 0, len(self._log.get(i)._unauthorizedRequestResponse.getResponse()) if self._log.get(i)._unauthorizedRequestResponse is not None else 0, color_modified, self._log.get(i)._enfocementStatus, color_unauthorized, self._log.get(i)._enfocementStatusUnauthorized) htmlContent += "</tbody></table></div></body></html>" f = open(fileToSave.getAbsolutePath(), 'w') f.writelines(htmlContent) f.close() def exportToCSV(self): parentFrame = JFrame() fileChooser = JFileChooser() fileChooser.setSelectedFile(File("AutorizeReport.csv")) fileChooser.setDialogTitle("Save Autorize Report") userSelection = fileChooser.showSaveDialog(parentFrame) if userSelection == JFileChooser.APPROVE_OPTION: fileToSave = fileChooser.getSelectedFile() enforcementStatusFilter = self.exportES.getSelectedItem() csvContent = "id\tMethod\tURL\tOriginal length\tModified length\tUnauthorized length\tAuthorization Enforcement Status\tAuthorization Unauthenticated Status\n" for i in range(0,self._log.size()): if enforcementStatusFilter == "All Statuses": csvContent += "%d\t%s\t%s\t%d\t%d\t%d\t%s\t%s\n" % (self._log.get(i)._id, self._log.get(i)._method, self._log.get(i)._url, len(self._log.get(i)._originalrequestResponse.getResponse()) if self._log.get(i)._originalrequestResponse is not None else 0, len(self._log.get(i)._requestResponse.getResponse()) if self._log.get(i)._requestResponse is not None else 0, len(self._log.get(i)._unauthorizedRequestResponse.getResponse()) if self._log.get(i)._unauthorizedRequestResponse is not None else 0, self._log.get(i)._enfocementStatus, self._log.get(i)._enfocementStatusUnauthorized) elif enforcementStatusFilter == "As table filter": if ((self._extender.showAuthBypassModified.isSelected() and self.BYPASSSED_STR == self._log.get(i)._enfocementStatus) or (self._extender.showAuthPotentiallyEnforcedModified.isSelected() and "Is enforced???" == self._log.get(i)._enfocementStatus) or (self._extender.showAuthEnforcedModified.isSelected() and self.ENFORCED_STR == self._log.get(i)._enfocementStatus) or (self._extender.showAuthBypassUnauthenticated.isSelected() and self.BYPASSSED_STR == self._log.get(i)._enfocementStatusUnauthorized) or (self._extender.showAuthPotentiallyEnforcedUnauthenticated.isSelected() and "Is enforced???" == self._log.get(i)._enfocementStatusUnauthorized) or (self._extender.showAuthEnforcedUnauthenticated.isSelected() and self.ENFORCED_STR == self._log.get(i)._enfocementStatusUnauthorized) or (self._extender.showDisabledUnauthenticated.isSelected() and "Disabled" == self._log.get(i)._enfocementStatusUnauthorized)): csvContent += "%d\t%s\t%s\t%d\t%d\t%d\t%s\t%s\n" % (self._log.get(i)._id, self._log.get(i)._method, self._log.get(i)._url, len(self._log.get(i)._originalrequestResponse.getResponse()) if self._log.get(i)._originalrequestResponse is not None else 0, len(self._log.get(i)._requestResponse.getResponse()) if self._log.get(i)._requestResponse is not None else 0, len(self._log.get(i)._unauthorizedRequestResponse.getResponse()) if self._log.get(i)._unauthorizedRequestResponse is not None else 0, self._log.get(i)._enfocementStatus, self._log.get(i)._enfocementStatusUnauthorized) else: if (enforcementStatusFilter == self._log.get(i)._enfocementStatus) or (enforcementStatusFilter == self._log.get(i)._enfocementStatusUnauthorized): csvContent += "%d\t%s\t%s\t%d\t%d\t%d\t%s\t%s\n" % (self._log.get(i)._id, self._log.get(i)._method, self._log.get(i)._url, len(self._log.get(i)._originalrequestResponse.getResponse()) if self._log.get(i)._originalrequestResponse is not None else 0, len(self._log.get(i)._requestResponse.getResponse()) if self._log.get(i)._requestResponse is not None else 0, len(self._log.get(i)._unauthorizedRequestResponse.getResponse()) if self._log.get(i)._unauthorizedRequestResponse is not None else 0, self._log.get(i)._enfocementStatus, self._log.get(i)._enfocementStatusUnauthorized) f = open(fileToSave.getAbsolutePath(), 'w') f.writelines(csvContent) f.close()
class BurpExtender(IBurpExtender, ITab, IMessageEditorController, AbstractTableModel, IContextMenuFactory): def registerExtenderCallbacks(self, callbacks): # keep a reference to our callbacks object self._callbacks = callbacks # obtain an extension helpers object self._helpers = callbacks.getHelpers() # set our extension name callbacks.setExtensionName("PT Vulnerabilities Manager") self.config = SafeConfigParser() self.createSection('projects') self.createSection('general') self.config.read('config.ini') self.chooser = JFileChooser() # create the log and a lock on which to synchronize when adding log entries self._log = ArrayList() self._lock = Lock() self.logTable = Table(self) self.logTable.getColumnModel().getColumn(0).setMaxWidth(35) self.logTable.getColumnModel().getColumn(1).setMinWidth(100) self._requestViewer = self._callbacks.createMessageEditor(self, False) self._responseViewer = self._callbacks.createMessageEditor(self, False) self.initVulnerabilityTab() self.initProjSettingsTab() self.initTabs() self.initCallbacks() if self.projPath.getText() != None: self.loadVulnerabilities(self.projPath.getText()) print "Thank you for installing PT Vulnerabilities Manager v1.0 extension" print "by Barak Tawily\n\n\n" print "Disclaimer:\nThis extension might create folders and files in your hardisk which might be declared as sensitive information, make sure you are creating projects under encrypted partition" return def initVulnerabilityTab(self): # ## init vulnerability tab # nameLabel = JLabel("Vulnerability Name:") nameLabel.setBounds(10, 10, 140, 30) self.addButton = JButton("Add",actionPerformed=self.addVuln) self.addButton.setBounds(10, 500, 100, 30) rmVulnButton = JButton("Remove",actionPerformed=self.rmVuln) rmVulnButton.setBounds(465, 500, 100, 30) mitigationLabel = JLabel("Mitigation:") mitigationLabel.setBounds(10, 290, 150, 30) addSSBtn = JButton("Add SS",actionPerformed=self.addSS) addSSBtn.setBounds(750, 40, 110, 30) deleteSSBtn = JButton("Remove SS",actionPerformed=self.removeSS) deleteSSBtn.setBounds(750, 75, 110, 30) piclistLabel = JLabel("Images list:") piclistLabel.setBounds(580, 10, 140, 30) self.screenshotsList = DefaultListModel() self.ssList = JList(self.screenshotsList) self.ssList.setBounds(580, 40, 150, 250) self.ssList.addListSelectionListener(ssChangedHandler(self)) self.ssList.setBorder(BorderFactory.createLineBorder(Color.GRAY)) previewPicLabel = JLabel("Selected image preview: (click to open in image viewer)") previewPicLabel.setBounds(580, 290, 500, 30) copyImgMenu = JMenuItem("Copy") copyImgMenu.addActionListener(copyImg(self)) self.imgMenu = JPopupMenu("Popup") self.imgMenu.add(copyImgMenu) self.firstPic = JLabel() self.firstPic.setBorder(BorderFactory.createLineBorder(Color.GRAY)) self.firstPic.setBounds(580, 320, 550, 400) self.firstPic.addMouseListener(imageClicked(self)) self.vulnName = JTextField("") self.vulnName.getDocument().addDocumentListener(vulnTextChanged(self)) self.vulnName.setBounds(140, 10, 422, 30) sevirities = ["Unclassified", "Critical","High","Medium","Low"] self.threatLevel = JComboBox(sevirities); self.threatLevel.setBounds(140, 45, 140, 30) colors = ["Color:", "Green", "Red"] self.colorCombo = JComboBox(colors); self.colorCombo.setBounds(465, 45, 100, 30) self.colorCombo severityLabel = JLabel("Threat Level:") severityLabel.setBounds(10, 45, 100, 30) descriptionLabel = JLabel("Description:") descriptionLabel.setBounds(10, 80, 100, 30) self.descriptionString = JTextArea("", 5, 30) self.descriptionString.setWrapStyleWord(True); self.descriptionString.setLineWrap(True) self.descriptionString.setBounds(10, 110, 555, 175) descriptionStringScroll = JScrollPane(self.descriptionString) descriptionStringScroll.setBounds(10, 110, 555, 175) descriptionStringScroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED) self.mitigationStr = JTextArea("", 5, 30) self.mitigationStr.setWrapStyleWord(True); self.mitigationStr.setLineWrap(True) self.mitigationStr.setBounds(10, 320, 555, 175) mitigationStrScroll = JScrollPane(self.mitigationStr) mitigationStrScroll.setBounds(10, 320, 555, 175) mitigationStrScroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED) self.pnl = JPanel() self.pnl.setBounds(0, 0, 1000, 1000); self.pnl.setLayout(None); self.pnl.add(addSSBtn) self.pnl.add(piclistLabel) self.pnl.add(nameLabel) self.pnl.add(deleteSSBtn) self.pnl.add(rmVulnButton) self.pnl.add(severityLabel) self.pnl.add(mitigationLabel) self.pnl.add(descriptionLabel) self.pnl.add(previewPicLabel) self.pnl.add(mitigationStrScroll) self.pnl.add(descriptionStringScroll) self.pnl.add(self.ssList) self.pnl.add(self.firstPic) self.pnl.add(self.addButton) self.pnl.add(self.vulnName) self.pnl.add(self.threatLevel) self.pnl.add(self.colorCombo) def initProjSettingsTab(self): # init project settings projNameLabel = JLabel("Name:") projNameLabel.setBounds(10, 50, 140, 30) self.projName = JTextField("") self.projName.setBounds(140, 50, 320, 30) self.projName.getDocument().addDocumentListener(projTextChanged(self)) detailsLabel = JLabel("Details:") detailsLabel.setBounds(10, 120, 140, 30) reportLabel = JLabel("Generate Report:") reportLabel.setBounds(10, 375, 140, 30) types = ["DOCX","HTML","XLSX"] self.reportType = JComboBox(types) self.reportType.setBounds(10, 400, 140, 30) generateReportButton = JButton("Generate", actionPerformed=self.generateReport) generateReportButton.setBounds(160, 400, 90, 30) self.projDetails = JTextArea("", 5, 30) self.projDetails.setWrapStyleWord(True); self.projDetails.setLineWrap(True) projDetailsScroll = JScrollPane(self.projDetails) projDetailsScroll.setBounds(10, 150, 450, 175) projDetailsScroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED) projPathLabel = JLabel("Path:") projPathLabel.setBounds(10, 90, 140, 30) self.projPath = JTextField("") self.projPath.setBounds(140, 90, 320, 30) chooseProjPathButton = JButton("Browse...",actionPerformed=self.chooseProjPath) chooseProjPathButton.setBounds(470, 90, 100, 30) importProjButton = JButton("Import",actionPerformed=self.importProj) importProjButton.setBounds(470, 10, 100, 30) exportProjButton = JButton("Export",actionPerformed=self.exportProj) exportProjButton.setBounds(575, 10, 100, 30) openProjButton = JButton("Open Directory",actionPerformed=self.openProj) openProjButton.setBounds(680, 10, 130, 30) currentProjectLabel = JLabel("Current:") currentProjectLabel.setBounds(10, 10, 140, 30) projects = self.config.options('projects') self.currentProject = JComboBox(projects) self.currentProject.addActionListener(projectChangeHandler(self)) self.currentProject.setBounds(140, 10, 140, 30) self.autoSave = JCheckBox("Auto Save Mode") self.autoSave.setEnabled(False) # implement this feature self.autoSave.setBounds(300, 10, 140, 30) self.autoSave.setToolTipText("Will save any changed value while focus is out") addProjButton = JButton("Add / Update",actionPerformed=self.addProj) addProjButton.setBounds(10, 330, 150, 30) removeProjButton = JButton("Remove Current",actionPerformed=self.rmProj) removeProjButton.setBounds(315, 330, 146, 30) generalOptions = self.config.options('general') if 'default project' in generalOptions: defaultProj = self.config.get('general','default project') self.currentProject.getModel().setSelectedItem(defaultProj) self.projPath.setText(self.config.get('projects',self.currentProject.getSelectedItem())) self.clearProjTab = True self.projectSettings = JPanel() self.projectSettings.setBounds(0, 0, 1000, 1000) self.projectSettings.setLayout(None) self.projectSettings.add(reportLabel) self.projectSettings.add(detailsLabel) self.projectSettings.add(projPathLabel) self.projectSettings.add(addProjButton) self.projectSettings.add(openProjButton) self.projectSettings.add(projNameLabel) self.projectSettings.add(projDetailsScroll) self.projectSettings.add(importProjButton) self.projectSettings.add(exportProjButton) self.projectSettings.add(removeProjButton) self.projectSettings.add(generateReportButton) self.projectSettings.add(chooseProjPathButton) self.projectSettings.add(currentProjectLabel) self.projectSettings.add(self.projPath) self.projectSettings.add(self.autoSave) self.projectSettings.add(self.projName) self.projectSettings.add(self.reportType) self.projectSettings.add(self.currentProject) def initTabs(self): # ## init autorize tabs # self._splitpane = JSplitPane(JSplitPane.HORIZONTAL_SPLIT) self.scrollPane = JScrollPane(self.logTable) self._splitpane.setLeftComponent(self.scrollPane) colorsMenu = JMenu("Paint") redMenu = JMenuItem("Red") noneMenu = JMenuItem("None") greenMenu = JMenuItem("Green") redMenu.addActionListener(paintChange(self, "Red")) noneMenu.addActionListener(paintChange(self, None)) greenMenu.addActionListener(paintChange(self, "Green")) colorsMenu.add(redMenu) colorsMenu.add(noneMenu) colorsMenu.add(greenMenu) self.menu = JPopupMenu("Popup") self.menu.add(colorsMenu) self.tabs = JTabbedPane() self.tabs.addTab("Request", self._requestViewer.getComponent()) self.tabs.addTab("Response", self._responseViewer.getComponent()) self.tabs.addTab("Vulnerability", self.pnl) self.tabs.addTab("Project Settings", self.projectSettings) self.tabs.setSelectedIndex(2) self._splitpane.setRightComponent(self.tabs) def initCallbacks(self): # ## init callbacks # # customize our UI components self._callbacks.customizeUiComponent(self._splitpane) self._callbacks.customizeUiComponent(self.logTable) self._callbacks.customizeUiComponent(self.scrollPane) self._callbacks.customizeUiComponent(self.tabs) self._callbacks.registerContextMenuFactory(self) # add the custom tab to Burp's UI self._callbacks.addSuiteTab(self) def loadVulnerabilities(self, projPath): self.clearList(None) selected = False for root, dirs, files in os.walk(projPath): # make it go only for dirs for dirName in dirs: xmlPath = projPath+"/"+dirName+"/vulnerability.xml" # xmlPath = xmlPath.replace("/","//") document = self.getXMLDoc(xmlPath) nodeList = document.getDocumentElement().getChildNodes() vulnName = nodeList.item(0).getTextContent() severity = nodeList.item(1).getTextContent() description = nodeList.item(2).getTextContent() mitigation = nodeList.item(3).getTextContent() color = nodeList.item(4).getTextContent() test = vulnerability(vulnName,severity,description,mitigation,color) self._lock.acquire() row = self._log.size() self._log.add(test) self.fireTableRowsInserted(row, row) self._lock.release() if vulnName == self.vulnName.getText(): self.logTable.setRowSelectionInterval(row,row) selected = True if selected == False and self._log.size() > 0: self.logTable.setRowSelectionInterval(0, 0) self.loadVulnerability(self._log.get(0)) def createSection(self, sectioName): self.config.read('config.ini') if not (sectioName in self.config.sections()): self.config.add_section(sectioName) cfgfile = open("config.ini",'w') self.config.write(cfgfile) cfgfile.close() def saveCfg(self): f = open('config.ini', 'w') self.config.write(f) f.close() def getXMLDoc(self, xmlPath): try: document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(xmlPath) return document except: self._extender.popup("XML file not found") return def saveXMLDoc(self, doc, xmlPath): transformerFactory = TransformerFactory.newInstance() transformer = transformerFactory.newTransformer() source = DOMSource(doc) result = StreamResult(File(xmlPath)) transformer.transform(source, result) def generateReport(self,event): if self.reportType.getSelectedItem() == "HTML": path = self.reportToHTML() if self.reportType.getSelectedItem() == "XLSX": path = self.reportToXLS() if self.reportType.getSelectedItem() == "DOCX": path = self.generateReportFromDocxTemplate('template.docx',"newfile.docx", 'word/document.xml') n = JOptionPane.showConfirmDialog(None, "Report generated successfuly:\n%s\nWould you like to open it?" % (path), "PT Manager", JOptionPane.YES_NO_OPTION) if n == JOptionPane.YES_OPTION: os.system('"' + path + '"') # Bug! stucking burp until the file get closed def exportProj(self,event): self.chooser.setDialogTitle("Save project") Ffilter = FileNameExtensionFilter("Zip files", ["zip"]) self.chooser.setFileFilter(Ffilter) returnVal = self.chooser.showSaveDialog(None) if returnVal == JFileChooser.APPROVE_OPTION: dst = str(self.chooser.getSelectedFile()) shutil.make_archive(dst,"zip",self.getCurrentProjPath()) self.popup("Project export successfuly") def importProj(self,event): self.chooser.setDialogTitle("Select project zip to directory") Ffilter = FileNameExtensionFilter("Zip files", ["zip"]) self.chooser.setFileFilter(Ffilter) returnVal = self.chooser.showOpenDialog(None) if returnVal == JFileChooser.APPROVE_OPTION: zipPath = str(self.chooser.getSelectedFile()) self.chooser.setDialogTitle("Select project directory") self.chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY) returnVal = self.chooser.showOpenDialog(None) if returnVal == JFileChooser.APPROVE_OPTION: projPath = str(self.chooser.getSelectedFile()) + "/PTManager" with zipfile.ZipFile(zipPath, "r") as z: z.extractall(projPath) xmlPath = projPath + "/project.xml" document = self.getXMLDoc(xmlPath) nodeList = document.getDocumentElement().getChildNodes() projName = nodeList.item(0).getTextContent() nodeList.item(1).setTextContent(projPath) self.saveXMLDoc(document, xmlPath) self.config.set('projects', projName, projPath) self.saveCfg() self.reloadProjects() self.currentProject.getModel().setSelectedItem(projName) self.clearVulnerabilityTab() def reportToXLS(self): if not xlsxwriterImported: self.popup("xlsxwriter library is not imported") return workbook = xlsxwriter.Workbook(self.getCurrentProjPath() + '/PT Manager Report.xlsx') worksheet = workbook.add_worksheet() bold = workbook.add_format({'bold': True}) worksheet.write(0, 0, "Vulnerability Name", bold) worksheet.write(0, 1, "Threat Level", bold) worksheet.write(0, 2, "Description", bold) worksheet.write(0, 3, "Mitigation", bold) row = 1 for i in range(0,self._log.size()): worksheet.write(row, 0, self._log.get(i).getName()) worksheet.write(row, 1, self._log.get(i).getSeverity()) worksheet.write(row, 2, self._log.get(i).getDescription()) worksheet.write(row, 3, self._log.get(i).getMitigation()) row = row + 1 # add requests and images as well workbook.close() return self.getCurrentProjPath() + '/PT Manager Report.xlsx' def reportToHTML(self): htmlContent = """<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" lang="he" dir="ltr"> <head> <title>PT Manager Report</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <style> body { background-repeat: no-repeat; background-attachment: fixed; font-family: Arial,Tahoma,sens-serif; font-size: 13px; margin: auto; } #warpcenter { width: 900px; margin: 0px auto; } table { border: 2px dashed #000000; } td { border-top: 2px dashed #000000; padding: 10px; } img { border: 0px; } </style> <script language="javascript"> function divHideShow(divToHideOrShow) { var div = document.getElementById(divToHideOrShow); if (div.style.display == "block") { div.style.display = "none"; } else { div.style.display = "block"; } } </script> </head> <body> <div id="warpcenter"> <h1> PT Manager Report </h1> <h2> Project: %s</h1> """ % (self.projName.getText()) for i in range(0,self._log.size()): name = self._log.get(i).getName() request = "None" response = "None" path = self.getVulnReqResPath("request",name) if os.path.exists(path): request = self.newlineToBR(self.getFileContent(path)) path = self.getVulnReqResPath("response",name) if os.path.exists(path): response = self.newlineToBR(self.getFileContent(path)) images = "" for fileName in os.listdir(self.projPath.getText()+"/"+self.clearStr(name)): if fileName.endswith(".jpg"): images += "%s<br><img src=\"%s\"><br><br>" % (fileName, self.projPath.getText()+"/"+self.clearStr(name) + "/" + fileName) description = self.newlineToBR(self._log.get(i).getDescription()) mitigation = self.newlineToBR(self._log.get(i).getMitigation()) htmlContent += self.convertVulntoTable(i,name,self._log.get(i).getSeverity(), description,mitigation, request, response, images) htmlContent += "</div></body></html>" f = open(self.getCurrentProjPath() + '/PT Manager Report.html', 'w') f.writelines(htmlContent) f.close() return self.getCurrentProjPath() + '/PT Manager Report.html' def newlineToBR(self,string): return "<br />".join(string.split("\n")) def getFileContent(self,path): f = open(path, "rb") content = f.read() f.close() return content def convertVulntoTable(self, number, name, severity, description, mitigation, request = "None", response = "None", images = "None"): return """<div style="width: 100%%;height: 30px;text-align: center;background-color:#E0E0E0;font-size: 17px;font-weight: bold;color: #000;padding-top: 10px;">%s <a href="javascript:divHideShow('Table_%s');" style="color:#191970">(OPEN / CLOSE)</a></div> <div id="Table_%s" style="display: none;"> <table width="100%%" cellspacing="0" cellpadding="0" style="margin: 0px auto;text-align: left;border-top: 0px;"> <tr> <td> <div style="font-size: 16px;font-weight: bold;"> <span style="color:#000000">Threat Level: </span> <span style="color:#8b8989">%s</span> </td> </tr> <tr> <td> <div style="font-size: 16px;font-weight: bold;"> <span style="color:#000000">Description</span> <a href="javascript:divHideShow('Table_%s_Command_03');" style="color:#191970">OPEN / CLOSE >>></a> </div> <div id="Table_%s_Command_03" style="display: none;margin-top: 25px;"> %s </div> </td> </tr> <tr> <td> <div style="font-size: 16px;font-weight: bold;"> <span style="color:#000000">Mitigration</span> <a href="javascript:divHideShow('Table_%s_Command_04');" style="color:#191970">OPEN / CLOSE >>></a> </div> <div id="Table_%s_Command_04" style="display: none;margin-top: 25px;"> %s <b> </td> </tr> <tr> <td> <div style="font-size: 16px;font-weight: bold;"> <span style="color:#000000">Request</span> <a href="javascript:divHideShow('Table_%s_Command_05');" style="color:#191970">OPEN / CLOSE >>></a> </div> <div id="Table_%s_Command_05" style="display: none;margin-top: 25px;"> %s <b> </td> </tr> <tr> <td> <div style="font-size: 16px;font-weight: bold;"> <span style="color:#000000">Response</span> <a href="javascript:divHideShow('Table_%s_Command_06');" style="color:#191970">OPEN / CLOSE >>></a> </div> <div id="Table_%s_Command_06" style="display: none;margin-top: 25px;"> %s <b> </td> </tr> <tr> <td> <div style="font-size: 16px;font-weight: bold;"> <span style="color:#000000">Images</span> <a href="javascript:divHideShow('Table_%s_Command_07');" style="color:#191970">OPEN / CLOSE >>></a> </div> <div id="Table_%s_Command_07" style="display: none;margin-top: 25px;"> %s <b> </td> </tr> </table> </div><br><br>""" % (name,number,number,severity,number,number,description,number,number,mitigation,number,number,request,number,number,response,number,number,images) def clearVulnerabilityTab(self, rmVuln=True): if rmVuln: self.vulnName.setText("") self.descriptionString.setText("") self.mitigationStr.setText("") self.colorCombo.setSelectedIndex(0) self.threatLevel.setSelectedIndex(0) self.screenshotsList.clear() self.addButton.setText("Add") self.firstPic.setIcon(None) def saveRequestResponse(self, type, requestResponse, vulnName): path = self.getVulnReqResPath(type,vulnName) f = open(path, 'wb') f.write(requestResponse) f.close() def openProj(self, event): os.system('explorer ' + self.projPath.getText()) def getVulnReqResPath(self, requestOrResponse, vulnName): return self.getCurrentProjPath() + "/" + self.clearStr(vulnName) + "/"+requestOrResponse+"_" + self.clearStr(vulnName) def htmlEscape(self,data): return data.replace('&', '&').replace('<', '<').replace('>', '>').replace('"', '"').replace("'", ''') def generateReportFromDocxTemplate(self, zipname, newZipName, filename): newZipName = self.getCurrentProjPath() + "/" + newZipName with zipfile.ZipFile(zipname, 'r') as zin: with zipfile.ZipFile(newZipName, 'w') as zout: zout.comment = zin.comment for item in zin.infolist(): if item.filename != filename: zout.writestr(item, zin.read(item.filename)) else: xml_content = zin.read(item.filename) result = re.findall("(.*)<w:body>(?:.*)<\/w:body>(.*)",xml_content)[0] newXML = result[0] templateBody = re.findall("<w:body>(.*)<\/w:body>", xml_content)[0] newBody = "" for i in range(0,self._log.size()): tmp = templateBody tmp = tmp.replace("$vulnerability", self.htmlEscape(self._log.get(i).getName())) tmp = tmp.replace("$severity", self.htmlEscape(self._log.get(i).getSeverity())) tmp = tmp.replace("$description", self.htmlEscape(self._log.get(i).getDescription())) tmp = tmp.replace("$mitigation", self.htmlEscape(self._log.get(i).getMitigation())) newBody = newBody + tmp newXML = newXML + newBody newXML = newXML + result[1] with zipfile.ZipFile(newZipName, mode='a', compression=zipfile.ZIP_DEFLATED) as zf: zf.writestr(filename, newXML) return newZipName def chooseProjPath(self, event): self.chooser.setDialogTitle("Select target directory") self.chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY) returnVal = self.chooser.showOpenDialog(None) if returnVal == JFileChooser.APPROVE_OPTION: projPath = str(self.chooser.getSelectedFile()) + "/PTManager" os.makedirs(projPath) self.projPath.setText(projPath) def reloadProjects(self): self.currentProject.setModel(DefaultComboBoxModel(self.config.options('projects'))) def rmProj(self, event): if self.popUpAreYouSure() == JOptionPane.YES_OPTION: self._requestViewer.setMessage("None", False) self._responseViewer.setMessage("None", False) shutil.rmtree(self.projPath.getText()) self.config.remove_option('projects',self.currentProject.getSelectedItem()) self.reloadProjects() self.currentProject.setSelectedIndex(0) self.loadVulnerabilities(self.projPath.getText()) def popup(self,msg): JOptionPane.showMessageDialog(None,msg) def addProj(self, event): projPath = self.projPath.getText() if projPath == None or projPath == "": self.popup("Please select path") return self.config.set('projects', self.projName.getText(), projPath) self.saveCfg() xml = ET.Element('project') name = ET.SubElement(xml, "name") path = ET.SubElement(xml, "path") details = ET.SubElement(xml, "details") autoSaveMode = ET.SubElement(xml, "autoSaveMode") name.text = self.projName.getText() path.text = projPath details.text = self.projDetails.getText() autoSaveMode.text = str(self.autoSave.isSelected()) tree = ET.ElementTree(xml) try: tree.write(self.getCurrentProjPath()+'/project.xml') except: self.popup("Invalid path") return self.reloadProjects() self.clearVulnerabilityTab() self.clearList(None) self.currentProject.getModel().setSelectedItem(self.projName.getText()) def resize(self, image, width, height): bi = BufferedImage(width, height, BufferedImage.TRANSLUCENT) g2d = bi.createGraphics() g2d.addRenderingHints(RenderingHints(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY)) g2d.drawImage(image, 0, 0, width, height, None) g2d.dispose() return bi; def clearStr(self, var): return var.replace(" " , "_").replace("\\" , "").replace("/" , "").replace(":" , "").replace("*" , "").replace("?" , "").replace("\"" , "").replace("<" , "").replace(">" , "").replace("|" , "").replace("(" , "").replace(")" , "") def popUpAreYouSure(self): dialogResult = JOptionPane.showConfirmDialog(None,"Are you sure?","Warning",JOptionPane.YES_NO_OPTION) if dialogResult == 0: return 0 return 1 def removeSS(self,event): if self.popUpAreYouSure() == JOptionPane.YES_OPTION: os.remove(self.getCurrentVulnPath() + "/" + self.ssList.getSelectedValue()) self.ssList.getModel().remove(self.ssList.getSelectedIndex()) self.firstPic.setIcon(ImageIcon(None)) # check if there is images and select the first one # bug in linux def addSS(self,event): clipboard = Toolkit.getDefaultToolkit().getSystemClipboard() try: image = clipboard.getData(DataFlavor.imageFlavor) except: self.popup("Clipboard not contains image") return vulnPath = self.projPath.getText() + "/" + self.clearStr(self.vulnName.getText()) if not os.path.exists(vulnPath): os.makedirs(vulnPath) name = self.clearStr(self.vulnName.getText()) + str(random.randint(1, 99999))+".jpg" fileName = self.projPath.getText()+"/"+ self.clearStr(self.vulnName.getText()) + "/" + name file = File(fileName) bufferedImage = BufferedImage(image.getWidth(None), image.getHeight(None), BufferedImage.TYPE_INT_RGB); g = bufferedImage.createGraphics(); g.drawImage(image, 0, 0, bufferedImage.getWidth(), bufferedImage.getHeight(), Color.WHITE, None); ImageIO.write(bufferedImage, "jpg", file) self.addVuln(self) self.ssList.setSelectedValue(name,True) def rmVuln(self, event): if self.popUpAreYouSure() == JOptionPane.YES_OPTION: self._requestViewer.setMessage("None", False) self._responseViewer.setMessage("None", False) shutil.rmtree(self.getCurrentVulnPath()) self.clearVulnerabilityTab() self.loadVulnerabilities(self.getCurrentProjPath()) def addVuln(self, event): if self.colorCombo.getSelectedItem() == "Color:": colorTxt = None else: colorTxt = self.colorCombo.getSelectedItem() self._lock.acquire() row = self._log.size() vulnObject = vulnerability(self.vulnName.getText(),self.threatLevel.getSelectedItem(),self.descriptionString.getText(),self.mitigationStr.getText() ,colorTxt) self._log.add(vulnObject) self.fireTableRowsInserted(row, row) self._lock.release() vulnPath = self.projPath.getText() + "/" + self.clearStr(self.vulnName.getText()) if not os.path.exists(vulnPath): os.makedirs(vulnPath) xml = ET.Element('vulnerability') name = ET.SubElement(xml, "name") severity = ET.SubElement(xml, "severity") description = ET.SubElement(xml, "description") mitigation = ET.SubElement(xml, "mitigation") color = ET.SubElement(xml, "color") name.text = self.vulnName.getText() severity.text = self.threatLevel.getSelectedItem() description.text = self.descriptionString.getText() mitigation.text = self.mitigationStr.getText() color.text = colorTxt tree = ET.ElementTree(xml) tree.write(vulnPath+'/vulnerability.xml') self.loadVulnerabilities(self.getCurrentProjPath()) self.loadVulnerability(vulnObject) def vulnNameChanged(self): if os.path.exists(self.getCurrentVulnPath()) and self.vulnName.getText() != "": self.addButton.setText("Update") elif self.addButton.getText() != "Add": options = ["Create a new vulnerability", "Change current vulnerability name"] n = JOptionPane.showOptionDialog(None, "Would you like to?", "Vulnerability Name", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, None, options, options[0]); if n == 0: self.clearVulnerabilityTab(False) self.addButton.setText("Add") else: newName = JOptionPane.showInputDialog( None, "Enter new name:", "Vulnerability Name", JOptionPane.PLAIN_MESSAGE, None, None, self.vulnName.getText()) row = self.logTable.getSelectedRow() old = self.logTable.getValueAt(row,1) self.changeVulnName(newName,old) def changeVulnName(self,new,old): newpath = self.getCurrentProjPath() + "/" + new oldpath = self.getCurrentProjPath() + "/" + old os.rename(oldpath,newpath) self.changeCurrentVuln(new,0, newpath + "/vulnerability.xml") def getCurrentVulnPath(self): return self.projPath.getText() + "/" + self.clearStr(self.vulnName.getText()) def getCurrentProjPath(self): return self.projPath.getText() def loadSS(self, imgPath): image = ImageIO.read(File(imgPath)) if image.getWidth() <= 550 and image.getHeight() <= 400: self.firstPic.setIcon(ImageIcon(image)) self.firstPic.setSize(image.getWidth(),image.getHeight()) else: self.firstPic.setIcon(ImageIcon(self.resize(image,550, 400))) self.firstPic.setSize(550,400) def clearProjectTab(self): self.projPath.setText("") self.projDetails.setText("") def clearList(self, event): self._lock.acquire() self._log = ArrayList() row = self._log.size() self.fireTableRowsInserted(row, row) self._lock.release() # # implement IContextMenuFactory # def createMenuItems(self, invocation): responses = invocation.getSelectedMessages(); if responses > 0: ret = LinkedList() requestMenuItem = JMenuItem("Send to PT Manager"); requestMenuItem.addActionListener(handleMenuItems(self,responses[0], "request")) ret.add(requestMenuItem); return(ret); return null; # # implement ITab # def getTabCaption(self): return "PT Manager" def getUiComponent(self): return self._splitpane # # extend AbstractTableModel # def getRowCount(self): try: return self._log.size() except: return 0 def getColumnCount(self): return 3 def getColumnName(self, columnIndex): if columnIndex == 0: return "#" if columnIndex == 1: return "Vulnerability Name" if columnIndex == 2: return "Threat Level" return "" def getValueAt(self, rowIndex, columnIndex): vulnObject = self._log.get(rowIndex) if columnIndex == 0: return rowIndex+1 if columnIndex == 1: return vulnObject.getName() if columnIndex == 2: return vulnObject.getSeverity() if columnIndex == 3: return vulnObject.getMitigation() if columnIndex == 4: return vulnObject.getColor() return "" def changeCurrentVuln(self,value,fieldNumber, xmlPath = "def"): if xmlPath == "def": xmlPath = self.getCurrentVulnPath() + "/vulnerability.xml" document = self.getXMLDoc(xmlPath) nodeList = document.getDocumentElement().getChildNodes() nodeList.item(fieldNumber).setTextContent(value) self.saveXMLDoc(document, xmlPath) self.loadVulnerabilities(self.getCurrentProjPath()) def loadVulnerability(self, vulnObject): self.addButton.setText("Update") self.vulnName.setText(vulnObject.getName()) self.threatLevel.setSelectedItem(vulnObject.getSeverity()) self.descriptionString.setText(vulnObject.getDescription()) self.mitigationStr.setText(vulnObject.getMitigation()) if vulnObject.getColor() == "" or vulnObject.getColor() == None: self.colorCombo.setSelectedItem("Color:") else: self.colorCombo.setSelectedItem(vulnObject.getColor()) self.screenshotsList.clear() for fileName in os.listdir(self.projPath.getText()+"/"+self.clearStr(vulnObject.getName())): if fileName.endswith(".jpg"): self.screenshotsList.addElement(fileName) imgPath = self.projPath.getText()+"/"+self.clearStr(vulnObject.getName())+'/'+fileName # imgPath = imgPath.replace("/","//") self.loadSS(imgPath) if (self.screenshotsList.getSize() == 0): self.firstPic.setIcon(None) else: self.ssList.setSelectedIndex(0) path = self.getVulnReqResPath("request",vulnObject.getName()) if os.path.exists(path): f = self.getFileContent(path) self._requestViewer.setMessage(f, False) else: self._requestViewer.setMessage("None", False) path = self.getVulnReqResPath("response",vulnObject.getName()) if os.path.exists(path): f = self.getFileContent(path) self._responseViewer.setMessage(f, False) else: self._responseViewer.setMessage("None", False)
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 ConfigurableConfigPanel(ConfigPanel, ActionListener, DocumentListener, ChangeListener): """ generated source for class ConfigurableConfigPanel """ serialVersionUID = 1L associatedFile = File() associatedFileField = JTextField() params = JSONObject() savedParams = str() loadButton = JButton() saveAsButton = JButton() saveButton = JButton() name = JTextField() strategy = JComboBox() metagameStrategy = JComboBox() stateMachine = JComboBox() cacheStateMachine = JCheckBox() maxPlys = JSpinner() heuristicFocus = JSpinner() heuristicMobility = JSpinner() heuristicOpponentFocus = JSpinner() heuristicOpponentMobility = JSpinner() mcDecayRate = JSpinner() rightPanel = JPanel() def __init__(self): """ generated source for method __init__ """ super(ConfigurableConfigPanel, self).__init__(GridBagLayout()) leftPanel = JPanel(GridBagLayout()) leftPanel.setBorder(TitledBorder("Major Parameters")) self.rightPanel = JPanel(GridBagLayout()) self.rightPanel.setBorder(TitledBorder("Minor Parameters")) self.strategy = JComboBox([None]*) self.metagameStrategy = JComboBox([None]*) self.stateMachine = JComboBox([None]*) self.cacheStateMachine = JCheckBox() self.maxPlys = JSpinner(SpinnerNumberModel(1, 1, 100, 1)) self.heuristicFocus = JSpinner(SpinnerNumberModel(1, 0, 10, 1)) self.heuristicMobility = JSpinner(SpinnerNumberModel(1, 0, 10, 1)) self.heuristicOpponentFocus = JSpinner(SpinnerNumberModel(1, 0, 10, 1)) self.heuristicOpponentMobility = JSpinner(SpinnerNumberModel(1, 0, 10, 1)) self.mcDecayRate = JSpinner(SpinnerNumberModel(0, 0, 99, 1)) self.name = JTextField() self.name.setColumns(20) self.name.setText("Player #" + Random().nextInt(100000)) self.loadButton = JButton(loadButtonMethod()) self.saveButton = JButton(saveButtonMethod()) self.saveAsButton = JButton(saveAsButtonMethod()) self.associatedFileField = JTextField() self.associatedFileField.setEnabled(False) buttons = JPanel() buttons.add(self.loadButton) buttons.add(self.saveButton) buttons.add(self.saveAsButton) nRow = 0 leftPanel.add(JLabel("Name"), GridBagConstraints(0, nRow, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5)) __nRow_0 = nRow nRow += 1 leftPanel.add(self.name, GridBagConstraints(1, __nRow_0, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, Insets(5, 5, 5, 5), 5, 5)) leftPanel.add(JLabel("Gaming Strategy"), GridBagConstraints(0, nRow, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5)) __nRow_1 = nRow nRow += 1 leftPanel.add(self.strategy, GridBagConstraints(1, __nRow_1, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, Insets(5, 5, 5, 5), 5, 5)) leftPanel.add(JLabel("Metagame Strategy"), GridBagConstraints(0, nRow, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5)) __nRow_2 = nRow nRow += 1 leftPanel.add(self.metagameStrategy, GridBagConstraints(1, __nRow_2, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, Insets(5, 5, 5, 5), 5, 5)) leftPanel.add(JLabel("State Machine"), GridBagConstraints(0, nRow, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5)) __nRow_3 = nRow nRow += 1 leftPanel.add(self.stateMachine, GridBagConstraints(1, __nRow_3, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, Insets(5, 5, 5, 5), 5, 5)) __nRow_4 = nRow nRow += 1 leftPanel.add(buttons, GridBagConstraints(1, __nRow_4, 2, 1, 1.0, 1.0, GridBagConstraints.SOUTHEAST, GridBagConstraints.NONE, Insets(5, 5, 0, 5), 0, 0)) leftPanel.add(self.associatedFileField, GridBagConstraints(0, nRow, 2, 1, 1.0, 0.0, GridBagConstraints.SOUTHEAST, GridBagConstraints.HORIZONTAL, Insets(0, 5, 5, 5), 0, 0)) layoutRightPanel() add(leftPanel, GridBagConstraints(0, 0, 1, 1, 0.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, Insets(5, 5, 5, 5), 5, 5)) add(self.rightPanel, GridBagConstraints(1, 0, 1, 1, 1.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, Insets(5, 5, 5, 5), 5, 5)) self.params = JSONObject() syncJSONtoUI() self.strategy.addActionListener(self) self.metagameStrategy.addActionListener(self) self.stateMachine.addActionListener(self) self.cacheStateMachine.addActionListener(self) self.maxPlys.addChangeListener(self) self.heuristicFocus.addChangeListener(self) self.heuristicMobility.addChangeListener(self) self.heuristicOpponentFocus.addChangeListener(self) self.heuristicOpponentMobility.addChangeListener(self) self.mcDecayRate.addChangeListener(self) self.name.getDocument().addDocumentListener(self) def layoutRightPanel(self): """ generated source for method layoutRightPanel """ nRow = 0 self.rightPanel.removeAll() self.rightPanel.add(JLabel("State machine cache?"), GridBagConstraints(0, nRow, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5)) __nRow_5 = nRow nRow += 1 self.rightPanel.add(self.cacheStateMachine, GridBagConstraints(1, __nRow_5, 1, 1, 1.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5)) if self.strategy.getSelectedItem().__str__() == "Heuristic": __nRow_6 = nRow nRow += 1 __nRow_7 = nRow nRow += 1 __nRow_8 = nRow nRow += 1 __nRow_9 = nRow nRow += 1 __nRow_10 = nRow nRow += 1 self.rightPanel.add(JLabel("Max plys?"), GridBagConstraints(0, nRow, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5)) self.rightPanel.add(self.maxPlys, GridBagConstraints(1, __nRow_6, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5)) self.rightPanel.add(JLabel("Focus Heuristic Weight"), GridBagConstraints(0, nRow, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5)) self.rightPanel.add(self.heuristicFocus, GridBagConstraints(1, __nRow_7, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5)) self.rightPanel.add(JLabel("Mobility Heuristic Weight"), GridBagConstraints(0, nRow, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5)) self.rightPanel.add(self.heuristicMobility, GridBagConstraints(1, __nRow_8, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5)) self.rightPanel.add(JLabel("Opponent Focus Heuristic Weight"), GridBagConstraints(0, nRow, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5)) self.rightPanel.add(self.heuristicOpponentFocus, GridBagConstraints(1, __nRow_9, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5)) self.rightPanel.add(JLabel("Opponent Mobility Heuristic Weight"), GridBagConstraints(0, nRow, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5)) self.rightPanel.add(self.heuristicOpponentMobility, GridBagConstraints(1, __nRow_10, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5)) if self.strategy.getSelectedItem().__str__() == "Monte Carlo": __nRow_11 = nRow nRow += 1 self.rightPanel.add(JLabel("Goal Decay Rate"), GridBagConstraints(0, nRow, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5)) self.rightPanel.add(self.mcDecayRate, GridBagConstraints(1, __nRow_11, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5)) __nRow_12 = nRow nRow += 1 self.rightPanel.add(JLabel(), GridBagConstraints(2, __nRow_12, 1, 1, 1.0, 1.0, GridBagConstraints.SOUTHEAST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5)) self.rightPanel.repaint() @SuppressWarnings("unchecked") def getParameter(self, name, defaultValue): """ generated source for method getParameter """ try: if self.params.has(name): return self.params.get(name) else: return defaultValue except JSONException as je: return defaultValue def actionPerformed(self, arg0): """ generated source for method actionPerformed """ if arg0.getSource() == self.strategy: self.layoutRightPanel() syncJSONtoUI() def changedUpdate(self, e): """ generated source for method changedUpdate """ syncJSONtoUI() def insertUpdate(self, e): """ generated source for method insertUpdate """ syncJSONtoUI() def removeUpdate(self, e): """ generated source for method removeUpdate """ syncJSONtoUI() def stateChanged(self, arg0): """ generated source for method stateChanged """ syncJSONtoUI() def syncJSONtoUI(self): """ generated source for method syncJSONtoUI """ if settingUI: return self.params = getJSONfromUI() self.saveButton.setEnabled(self.savedParams == None or not self.params.__str__() == self.savedParams) def getJSONfromUI(self): """ generated source for method getJSONfromUI """ newParams = JSONObject() try: if not self.name.getText().isEmpty(): newParams.put("name", self.name.getText()) newParams.put("strategy", self.strategy.getSelectedItem().__str__()) newParams.put("metagameStrategy", self.metagameStrategy.getSelectedItem().__str__()) newParams.put("stateMachine", self.stateMachine.getSelectedItem().__str__()) newParams.put("cacheStateMachine", self.cacheStateMachine.isSelected()) newParams.put("maxPlys", self.maxPlys.getModel().getValue()) newParams.put("heuristicFocus", self.heuristicFocus.getModel().getValue()) newParams.put("heuristicMobility", self.heuristicMobility.getModel().getValue()) newParams.put("heuristicOpponentFocus", self.heuristicOpponentFocus.getModel().getValue()) newParams.put("heuristicOpponentMobility", self.heuristicOpponentMobility.getModel().getValue()) newParams.put("mcDecayRate", self.mcDecayRate.getModel().getValue()) except JSONException as je: je.printStackTrace() return newParams settingUI = False def setUIfromJSON(self): """ generated source for method setUIfromJSON """ self.settingUI = True try: if self.params.has("name"): self.name.setText(self.params.getString("name")) if self.params.has("strategy"): self.strategy.setSelectedItem(self.params.getString("strategy")) if self.params.has("metagameStrategy"): self.metagameStrategy.setSelectedItem(self.params.getString("metagameStrategy")) if self.params.has("stateMachine"): self.stateMachine.setSelectedItem(self.params.getString("stateMachine")) if self.params.has("cacheStateMachine"): self.cacheStateMachine.setSelected(self.params.getBoolean("cacheStateMachine")) if self.params.has("maxPlys"): self.maxPlys.getModel().setValue(self.params.getInt("maxPlys")) if self.params.has("heuristicFocus"): self.heuristicFocus.getModel().setValue(self.params.getInt("heuristicFocus")) if self.params.has("heuristicMobility"): self.heuristicMobility.getModel().setValue(self.params.getInt("heuristicMobility")) if self.params.has("heuristicOpponentFocus"): self.heuristicOpponentFocus.getModel().setValue(self.params.getInt("heuristicOpponentFocus")) if self.params.has("heuristicOpponentMobility"): self.heuristicOpponentMobility.getModel().setValue(self.params.getInt("heuristicOpponentMobility")) if self.params.has("mcDecayRate"): self.mcDecayRate.getModel().setValue(self.params.getInt("mcDecayRate")) except JSONException as je: je.printStackTrace() finally: self.settingUI = False def loadParamsJSON(self, fromFile): """ generated source for method loadParamsJSON """ if not fromFile.exists(): return self.associatedFile = fromFile self.associatedFileField.setText(self.associatedFile.getPath()) self.params = JSONObject() try: try: while (line = br.readLine()) != None: pdata.append(line) finally: br.close() self.params = JSONObject(pdata.__str__()) self.savedParams = self.params.__str__() self.setUIfromJSON() self.syncJSONtoUI() except Exception as e: e.printStackTrace() def saveParamsJSON(self, saveAs): """ generated source for method saveParamsJSON """ try: if saveAs or self.associatedFile == None: fc.setFileFilter(PlayerFilter()) if returnVal == JFileChooser.APPROVE_OPTION and fc.getSelectedFile() != None: if toFile.__name__.contains("."): self.associatedFile = File(toFile.getParentFile(), toFile.__name__.substring(0, toFile.__name__.lastIndexOf(".")) + ".player") else: self.associatedFile = File(toFile.getParentFile(), toFile.__name__ + ".player") self.associatedFileField.setText(self.associatedFile.getPath()) else: return bw.write(self.params.__str__()) bw.close() self.savedParams = self.params.__str__() self.syncJSONtoUI() except IOException as ie: ie.printStackTrace() def saveButtonMethod(self): """ generated source for method saveButtonMethod """ return AbstractAction("Save") def saveAsButtonMethod(self): """ generated source for method saveAsButtonMethod """ return AbstractAction("Save As") def loadButtonMethod(self): """ generated source for method loadButtonMethod """ return AbstractAction("Load") class PlayerFilter(FileFilter): """ generated source for class PlayerFilter """ def accept(self, f): """ generated source for method accept """ if f.isDirectory(): return True return f.__name__.endsWith(".player") def getDescription(self): """ generated source for method getDescription """ return "GGP Players (*.player)"
class Process_EVTX1WithUISettingsPanel(IngestModuleIngestJobSettingsPanel): # Note, we can't use a self.settings instance variable. # Rather, self.local_settings is used. # https://wiki.python.org/jython/UserGuide#javabean-properties # Jython Introspector generates a property - 'settings' on the basis # of getSettings() defined in this class. Since only getter function # is present, it creates a read-only 'settings' property. This auto- # generated read-only property overshadows the instance-variable - # 'settings' # We get passed in a previous version of the settings so that we can # prepopulate the UI # TODO: Update this for your UI def __init__(self, settings): self.local_settings = settings self.initComponents() self.customizeComponents() # TODO: Update this for your UI def checkBoxEvent(self, event): if self.checkbox.isSelected(): self.local_settings.setSetting('All', 'true') else: self.local_settings.setSetting('All', 'false') if self.checkbox1.isSelected(): self.local_settings.setSetting('Application', 'true') else: self.local_settings.setSetting('Application', 'false') if self.checkbox2.isSelected(): self.local_settings.setSetting('Security', 'true') else: self.local_settings.setSetting('Security', 'false') if self.checkbox3.isSelected(): self.local_settings.setSetting('System', 'true') else: self.local_settings.setSetting('System', 'false') if self.checkbox4.isSelected(): self.local_settings.setSetting('Other', 'true') self.area.setEnabled(True) else: self.local_settings.setSetting('Other', 'false') self.area.setEnabled(False) if self.filterCheckbox.isSelected(): self.local_settings.setSetting('Filter', 'true') self.filterField.setEnabled(True) self.filterSelector.setEnabled(True) self.filterInput.setEnabled(True) else: self.local_settings.setSetting('Filter', 'false') self.filterField.setEnabled(False) self.filterSelector.setEnabled(False) self.filterInput.setEnabled(False) if self.sortCheckbox.isSelected(): self.local_settings.setSetting('SortDesc', 'true') else: self.local_settings.setSetting('SortDesc', 'false') def keyPressed(self, event): self.local_settings.setSetting('EventLogs', self.area.getText()) # TODO: Update this for your UI def initComponents(self): self.setLayout(BoxLayout(self, BoxLayout.Y_AXIS)) self.setAlignmentX(JComponent.LEFT_ALIGNMENT) self.checkbox = JCheckBox("All Logs", actionPerformed=self.checkBoxEvent) self.checkbox1 = JCheckBox("Application.Evtx", actionPerformed=self.checkBoxEvent) self.checkbox2 = JCheckBox("Security.EVTX", actionPerformed=self.checkBoxEvent) self.checkbox3 = JCheckBox("System.EVTX", actionPerformed=self.checkBoxEvent) self.checkbox4 = JCheckBox( "Other - Input in text area below then check this box", actionPerformed=self.checkBoxEvent) # Scrollable text area for additional log names self.area = JTextArea(3, 10) self.area.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0)) self.area.setEnabled(False) self.pane = JScrollPane() self.pane.getViewport().add(self.area) self.add(self.checkbox) self.add(self.checkbox1) self.add(self.checkbox2) self.add(self.checkbox3) self.add(self.checkbox4) self.add(self.pane) self.add(JSeparator()) self.add(JSeparator()) self.filterCheckbox = JCheckBox("Filter", actionPerformed=self.checkBoxEvent) self.filterCheckbox.setLayout( BoxLayout(self.filterCheckbox, BoxLayout.X_AXIS)) self.add(self.filterCheckbox) self.filterPanel = JPanel() self.filterPanel.setLayout( BoxLayout(self.filterPanel, BoxLayout.X_AXIS)) self.filterField = JComboBox([ "Computer Name", "Event Identifier", "Event Level", "Source Name", "Event Detail" ]) self.filterField.setEnabled(False) self.filterField.setMaximumSize(self.filterField.getPreferredSize()) self.filterSelector = JComboBox( ["equals", "not equals", "contains", "starts with", "ends with"]) self.filterSelector.setEnabled(False) self.filterSelector.setMaximumSize( self.filterSelector.getPreferredSize()) self.filterInput = JTextField() self.filterInput.setEnabled(False) self.filterInput.setMaximumSize( Dimension(512, self.filterInput.getPreferredSize().height)) self.filterPanel.add(self.filterField) self.filterPanel.add(self.filterSelector) self.filterPanel.add(self.filterInput) self.add(self.filterPanel) self.sortCheckbox = JCheckBox("Sort Event Counts Descending", actionPerformed=self.checkBoxEvent) self.add(self.sortCheckbox) # TODO: Update this for your UI def customizeComponents(self): self.checkbox.setSelected( self.local_settings.getSetting('All') == 'true') self.checkbox1.setSelected( self.local_settings.getSetting('Application') == 'true') self.checkbox2.setSelected( self.local_settings.getSetting('Security') == 'true') self.checkbox3.setSelected( self.local_settings.getSetting('System') == 'true') self.checkbox4.setSelected( self.local_settings.getSetting('Other') == 'true') self.area.setText(self.local_settings.getSetting('EventLogs')) # Return the settings used def getSettings(self): self.local_settings.setSetting('EventLogs', self.area.getText()) self.local_settings.setSetting('FilterField', self.filterField.getSelectedItem()) self.local_settings.setSetting('FilterMode', self.filterSelector.getSelectedItem()) self.local_settings.setSetting('FilterInput', self.filterInput.getText()) return self.local_settings
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 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 Gui(MouseAdapter): IMG_MIN_SIZE = 200 IMG_MAX_SIZE = 500 def __init__(self): self.pos1 = None self.puzzle = None def mouseEntered(self, event): self.in_canvas = True def mouseExited(self, event): self.in_canvas = False def mouseReleased(self, event): if not self.in_canvas or self.puzzle == None: return width = self.images_dict[0].getWidth() height = self.images_dict[0].getHeight() def valid_pos(pos): return pos >= 0 and pos < self.puzzle.level() x = (event.getX() - self.canvas.initial_x) / width y = (event.getY() - self.canvas.initial_y) / height if not valid_pos(x) or not valid_pos(y): return pos = Point(x, y) if self.pos1 != None: #then is second click if self.pos1.equals(pos): self.pos1 = None else: self.play_event(self.pos1.y, self.pos1.x, pos.y, pos.x) self.pos1 = None else: self.pos1 = pos self.canvas.set_selected(self.pos1) self.canvas.repaint() def draw(self): try: UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); except: pass self.images_dict = dict() self.canvas = Canvas(self.images_dict, None) self.canvas.addMouseListener(self) self.frame = JFrame("SimplePyzzle", visible = 1) self.frame.setMinimumSize(Dimension(300, 300)) self.frame.setLocationRelativeTo(None) self.generate_button = JButton("Generate Puzzle") self.bottom_panel = JPanel() self.combo_box_list = [9, 16, 25, 36, 49] self.combo_box = JComboBox(self.combo_box_list) self.frame.contentPane.add(self.canvas, BorderLayout.CENTER) self.frame.contentPane.add(self.bottom_panel, BorderLayout.SOUTH) self.bottom_panel.add(self.generate_button, BorderLayout.EAST) self.bottom_panel.add(self.combo_box, BorderLayout.WEST) self.generate_button.actionPerformed = self.generate_board self.frame.setSize(500, 500) self.frame.defaultCloseOperation = JFrame.EXIT_ON_CLOSE; self.frame.pack() def generate_board(self, event): chooser = JFileChooser() status = chooser.showOpenDialog(self.frame) if status != JFileChooser.APPROVE_OPTION: return imageFile = chooser.getSelectedFile() self.puzzle = SimplePyzzle(float(int(self.combo_box.getSelectedItem()))) self.draw_board() self.load_images(imageFile, self.puzzle.level()) self.canvas.set_puzzle(self.puzzle) width = self.images_dict[0].getWidth() height = self.images_dict[0].getHeight() size = Dimension(width * self.puzzle.level(), height * self.puzzle.level()) self.frame.setPreferredSize(size) self.frame.setSize(size) def show_error(self, error): JOptionPane.showMessageDialog(self.frame, \ error, \ "Error!", \ JOptionPane.ERROR_MESSAGE) def load_images(self, file, length): try: image = ImageIO.read(file); except IIOException: self.show_error(u"You have to pick an image!") return image_biggest_side = image.getWidth() if image.getWidth() > image.getHeight\ else image.getHeight() imageSize = image_biggest_side if image_biggest_side > Gui.IMG_MAX_SIZE: imageSize = Gui.IMG_MAX_SIZE if image_biggest_side < Gui.IMG_MIN_SIZE: imageSize = Gui.IMG_MIN_SIZE resized_image = resize_image(image, imageSize, imageSize) images = split_image(resized_image, length) self.images_dict.clear() for i in range(len(images)): self.images_dict[i] = images[i] def play_event(self, x1, y1, x2, y2): status = self.puzzle.play(x1, y1, x2, y2) self.draw_board() if status == SimplePyzzle.END_GAME: JOptionPane.showMessageDialog (None, \ "Grats! You solved the puzzle", \ "Puzzle solved!", \ JOptionPane.INFORMATION_MESSAGE); def draw_board(self): self.canvas.repaint()
class NewAccountGUI: def __init__(self, amgui): self.amgui = amgui self.am = amgui.acctmanager self.buildgwinfo() self.autologin = JCheckBox("Automatically Log In") self.acctname = JTextField() self.gwoptions = JPanel(doublebuffered) self.gwoptions.border = TitledBorder("Gateway Options") self.buildgwoptions("Twisted") self.mainframe = JFrame("New Account Window") self.buildpane() def buildgwinfo(self): self.gateways = { "Twisted": { "ident": JTextField(), "passwd": JPasswordField(), "host": JTextField("twistedmatrix.com"), "port": JTextField("8787"), "service": JTextField("twisted.words"), "persp": JTextField() }, "AIM": { "ident": JTextField(), "passwd": JPasswordField(), "host": JTextField("toc.oscar.aol.com"), "port": JTextField("9898") }, "IRC": { "ident": JTextField(), "passwd": JPasswordField(), "host": JTextField(), "port": JTextField("6667"), "channels": JTextField() } } self.displayorder = { "Twisted": [["Identity Name", "ident"], ["Password", "passwd"], ["Host", "host"], ["Port", "port"], ["Service Name", "service"], ["Perspective Name", "persp"]], "AIM": [["Screen Name", "ident"], ["Password", "passwd"], ["Host", "host"], ["Port", "port"]], "IRC": [["Nickname", "ident"], ["Password", "passwd"], ["Host", "host"], ["Port", "port"], ["Channels", "channels"]] } def buildgwoptions(self, gw): self.gwoptions.removeAll() self.gwoptions.layout = GridLayout(len(self.gateways[gw]), 2) for mapping in self.displayorder[gw]: self.gwoptions.add(JLabel(mapping[0])) self.gwoptions.add(self.gateways[gw][mapping[1]]) def buildpane(self): gw = JPanel(GridLayout(1, 2), doublebuffered) gw.add(JLabel("Gateway")) self.gwlist = JComboBox( self.gateways.keys()) #, actionPerformed=self.changegw) self.gwlist.setSelectedItem("Twisted") gw.add(self.gwlist) stdoptions = JPanel(GridLayout(2, 2), doublebuffered) stdoptions.border = TitledBorder("Standard Options") stdoptions.add(JLabel()) stdoptions.add(self.autologin) stdoptions.add(JLabel("Account Name")) stdoptions.add(self.acctname) buttons = JPanel(FlowLayout(), doublebuffered) buttons.add(JButton("OK", actionPerformed=self.addaccount)) buttons.add(JButton("Cancel", actionPerformed=self.cancel)) mainpane = self.mainframe.getContentPane() mainpane.layout = BoxLayout(mainpane, BoxLayout.Y_AXIS) mainpane.add(gw) mainpane.add(self.gwoptions) mainpane.add(stdoptions) mainpane.add(buttons) def show(self): self.mainframe.setLocation(100, 100) self.mainframe.pack() self.mainframe.show() #actionlisteners def changegw(self, ae): self.buildgwoptions(self.gwlist.getSelectedItem()) self.mainframe.pack() self.mainframe.show() def addaccount(self, ae): gwselection = self.gwlist.getSelectedItem() gw = self.gateways[gwselection] name = gw["ident"].text passwd = gw["passwd"].text host = gw["host"].text port = int(gw["port"].text) autologin = self.autologin.isSelected() acctname = self.acctname.text if gwselection == "Twisted": sname = gw["service"].text perspective = gw["persp"].text self.am.addAccount( PBAccount(acctname, autologin, name, passwd, host, port, [[stype, sname, perspective]])) elif gwselection == "AIM": self.am.addAccount( TOCAccount(acctname, autologin, name, passwd, host, port)) elif gwselection == "IRC": channels = gw["channels"].text self.am.addAccount( IRCAccount(acctname, autologin, name, passwd, host, port, channels)) self.amgui.update() print "Added new account" self.mainframe.dispose() def cancel(self, ae): print "Cancelling new account creation" self.mainframe.dispose()
class BurpExtender(IBurpExtender, ITab, IExtensionStateListener): # Define the global variables for the burp plugin EXTENSION_NAME = "UPnP BHunter" ipv4_selected = True services_dict = {} ip_service_dict = {} STOP_THREAD = False #Some SSDP m-search parameters are based upon "UPnP Device Architecture v2.0" SSDP_MULTICAST_IPv4 = ["239.255.255.250"] SSDP_MULTICAST_IPv6 = ["FF02::C", "FF05::C"] SSDP_MULTICAST_PORT = 1900 ST_ALL = "ssdp:all" ST_ROOTDEV = "upnp:rootdevice" PLACEHOLDER = "FUZZ_HERE" SSDP_TIMEOUT = 2 def registerExtenderCallbacks(self, callbacks): # Get a reference to callbacks object self.callbacks = callbacks # Get the useful extension helpers object self.helpers = callbacks.getHelpers() # Set the extension name self.callbacks.setExtensionName(self.EXTENSION_NAME) self.callbacks.registerExtensionStateListener(self) # Draw plugin user interface self.drawPluginUI() self.callbacks.addSuiteTab(self) # Plugin loading message print("[+] Burp plugin UPnP BHunter loaded successfully") return def drawPluginUI(self): # Create the plugin user interface self.pluginTab = JPanel() self.uiTitle = JLabel('UPnP BHunter Load, Aim and Fire Console') self.uiTitle.setFont(Font('Tahoma', Font.BOLD, 14)) self.uiTitle.setForeground(Color(250, 100, 0)) self.uiPanelA = JSplitPane(JSplitPane.VERTICAL_SPLIT) self.uiPanelA.setMaximumSize(Dimension(2500, 1000)) self.uiPanelA.setDividerSize(2) self.uiPanelB = JSplitPane(JSplitPane.VERTICAL_SPLIT) self.uiPanelB.setDividerSize(2) self.uiPanelA.setBottomComponent(self.uiPanelB) self.uiPanelA.setBorder(BorderFactory.createLineBorder(Color.gray)) # Create and configure labels and text fields self.labeltitle_step1 = JLabel("[1st STEP] Discover UPnP Locations") self.labeltitle_step1.setFont(Font('Tahoma', Font.BOLD, 14)) self.labeltitle_step2 = JLabel( "[2nd STEP] Select a UPnP Service and Action") self.labeltitle_step2.setFont(Font('Tahoma', Font.BOLD, 14)) self.labeltitle_step3 = JLabel("[3rd STEP] Time to Attack it") self.labeltitle_step3.setFont(Font('Tahoma', Font.BOLD, 14)) self.labelsubtitle_step1 = JLabel( "Specify the IP version address in scope and start UPnP discovery") self.labelsubtitle_step2 = JLabel( "Select which of the found UPnP services will be probed") self.labelsubtitle_step3 = JLabel( "Review and modify the request, then send it to one of the attack tools" ) self.label_step1 = JLabel("Target IP") self.label_step2 = JLabel("Found UPnp Services") self.labelstatus = JLabel(" Status") self.labelempty_step1 = JLabel(" ") self.labelempty_step2 = JLabel(" ") self.labelupnp = JLabel("UPnP list") self.labelip = JLabel("IP list") self.labelactions = JLabel("Actions") self.labelNoneServiceFound = JLabel(" ") self.labelNoneServiceFound.setFont(Font('Tahoma', Font.BOLD, 12)) self.labelNoneServiceFound.setForeground(Color.red) # Create combobox for IP version selection self.ip_versions = ["IPv4", "IPv6"] self.combo_ipversion = JComboBox(self.ip_versions) self.combo_ipversion.setSelectedIndex(0) self.combo_ipversion.setEnabled(True) # Create and configure progress bar self.progressbar = JProgressBar(0, 100) self.progressbar.setString("Ready") self.progressbar.setStringPainted(True) # Create and configure buttons self.startbutton = JButton("Start Discovery", actionPerformed=self.startHunting) self.clearbutton = JButton("Clear All", actionPerformed=self.clearAll) self.intruderbutton = JButton("Send to Intruder", actionPerformed=self.sendToIntruder) self.repeaterbutton = JButton("Send to Repeater", actionPerformed=self.sendToRepeater) #self.WANrepeaterbutton = JButton("to Repeater", actionPerformed=self.sendWANUPnPToRepeater) self.textarea_request = JTextArea(18, 90) self.intruderbutton.setEnabled(False) self.repeaterbutton.setEnabled(False) # Class neeeded to handle the target combobox in second step panel class TargetComboboxListener(ActionListener): def __init__(self, upnpcombo_targets, upnpcombo_services, ip_service_dict): self.upnpcombo_targets = upnpcombo_targets self.upnpcombo_services = upnpcombo_services self.ip_service_dict = ip_service_dict def actionPerformed(self, event): try: # Update the location url combobox depending on the IP combobox selected_target = self.upnpcombo_targets.getSelectedItem() if self.ip_service_dict and selected_target: self.upnpcombo_services.removeAllItems() for service_url in self.ip_service_dict[ selected_target]: self.upnpcombo_services.addItem(service_url) self.upnpcombo_services.setSelectedIndex(0) except BaseException as e: print("[!] Exception selecting service: \"%s\" ") % e # Class neeeded to handle the service combobox in second step panel class ServiceComboboxListener(ActionListener): def __init__(self, upnpcombo_services, upnpcombo_actions, services_dict): self.upnpcombo_services = upnpcombo_services self.upnpcombo_actions = upnpcombo_actions self.services = services_dict def actionPerformed(self, event): try: # Update the location url combobox depending on the IP combobox selected_service = self.upnpcombo_services.getSelectedItem( ) if self.services and selected_service: self.upnpcombo_actions.removeAllItems() actions = self.services[selected_service] for action in actions: self.upnpcombo_actions.addItem(action) self.upnpcombo_actions.setSelectedIndex(0) except BaseException as e: print("[!] Exception selecting service: \"%s\" ") % e # Class neeeded to handle the action combobox in second step panel class ActionComboboxListener(ActionListener): def __init__(self, upnpcombo_services, upnpcombo_actions, textarea_request, services_dict): self.upnpcombo_services = upnpcombo_services self.upnpcombo_actions = upnpcombo_actions self.textarea_request = textarea_request self.services = services_dict def actionPerformed(self, event): try: # Update the location url combobox depending on the IP combobox selected_action = self.upnpcombo_actions.getSelectedItem() selected_service = self.upnpcombo_services.getSelectedItem( ) if self.services and selected_action: self.textarea_request.setText( self.services[selected_service][selected_action]) except BaseException as e: print("[!] Exception selecting action: \"%s\" ") % e self.upnpactions = [" "] self.upnpcombo_actions = JComboBox(self.upnpactions) self.upnpcombo_actions.setSelectedIndex(0) self.upnpcombo_actions.setEnabled(False) # Create the combo box, select item at index 0 (first item in list) self.upnpservices = [" "] self.upnpcombo_services = JComboBox(self.upnpservices) self.upnpcombo_services.setSelectedIndex(0) self.upnpcombo_services.setEnabled(False) # Create the combo box, select item at index 0 (first item in list) self.upnptargets = [" "] self.upnpcombo_targets = JComboBox(self.upnptargets) self.upnpcombo_targets.setSelectedIndex(0) self.upnpcombo_targets.setEnabled(False) # Set the action listeners for all the comboboxes self.upnpcombo_targets.addActionListener( TargetComboboxListener(self.upnpcombo_targets, self.upnpcombo_services, self.ip_service_dict)) self.upnpcombo_services.addActionListener( ServiceComboboxListener(self.upnpcombo_services, self.upnpcombo_actions, self.services_dict)) self.upnpcombo_actions.addActionListener( ActionComboboxListener(self.upnpcombo_services, self.upnpcombo_actions, self.textarea_request, self.services_dict)) # Configuring first step panel self.panel_step1 = JPanel() self.panel_step1.setPreferredSize(Dimension(2250, 100)) self.panel_step1.setBorder(EmptyBorder(10, 10, 10, 10)) self.panel_step1.setLayout(BorderLayout(15, 15)) self.titlepanel_step1 = JPanel() self.titlepanel_step1.setLayout(BorderLayout()) self.titlepanel_step1.add(self.labeltitle_step1, BorderLayout.NORTH) self.titlepanel_step1.add(self.labelsubtitle_step1) self.targetpanel_step1 = JPanel() self.targetpanel_step1.add(self.label_step1) self.targetpanel_step1.add(self.combo_ipversion) self.targetpanel_step1.add(self.startbutton) self.targetpanel_step1.add(self.clearbutton) self.targetpanel_step1.add(self.labelstatus) self.targetpanel_step1.add(self.progressbar) self.emptypanel_step1 = JPanel() self.emptypanel_step1.setLayout(BorderLayout()) self.emptypanel_step1.add(self.labelempty_step1, BorderLayout.WEST) # Assembling first step panel components self.panel_step1.add(self.titlepanel_step1, BorderLayout.NORTH) self.panel_step1.add(self.targetpanel_step1, BorderLayout.WEST) self.panel_step1.add(self.emptypanel_step1, BorderLayout.SOUTH) self.uiPanelA.setTopComponent(self.panel_step1) # Configure second step panel self.panel_step2 = JPanel() self.panel_step2.setPreferredSize(Dimension(2250, 100)) self.panel_step2.setBorder(EmptyBorder(10, 10, 10, 10)) self.panel_step2.setLayout(BorderLayout(15, 15)) self.titlepanel_step2 = JPanel() self.titlepanel_step2.setLayout(BorderLayout()) self.titlepanel_step2.add(self.labeltitle_step2, BorderLayout.NORTH) self.titlepanel_step2.add(self.labelsubtitle_step2) self.selectpanel_step2 = JPanel() self.selectpanel_step2.add(self.labelip) self.selectpanel_step2.add(self.upnpcombo_targets) self.selectpanel_step2.add(self.labelupnp) self.selectpanel_step2.add(self.upnpcombo_services) self.selectpanel_step2.add(self.labelactions) self.selectpanel_step2.add(self.upnpcombo_actions) self.emptypanel_step2 = JPanel() self.emptypanel_step2.setLayout(BorderLayout()) self.emptypanel_step2.add(self.labelempty_step2, BorderLayout.WEST) self.emptypanel_step2.add(self.labelNoneServiceFound) # Assembling second step panel components self.panel_step2.add(self.titlepanel_step2, BorderLayout.NORTH) self.panel_step2.add(self.selectpanel_step2, BorderLayout.WEST) self.panel_step2.add(self.emptypanel_step2, BorderLayout.SOUTH) self.uiPanelB.setTopComponent(self.panel_step2) # Configuring third step panel self.panel_step3 = JPanel() self.panel_step3.setPreferredSize(Dimension(2250, 100)) self.panel_step3.setBorder(EmptyBorder(10, 10, 10, 10)) self.panel_step3.setLayout(BorderLayout(15, 15)) self.titlepanel_step3 = JPanel() self.titlepanel_step3.setLayout(BorderLayout()) self.titlepanel_step3.add(self.labeltitle_step3, BorderLayout.NORTH) self.titlepanel_step3.add(self.labelsubtitle_step3) self.underpanel_step3 = JPanel() self.underpanel_step3.setLayout(BorderLayout()) self.underpanel_step3.add((JScrollPane(self.textarea_request)), BorderLayout.NORTH) self.actionpanel_step3 = JPanel() self.actionpanel_step3.add(self.intruderbutton) self.actionpanel_step3.add(self.repeaterbutton) self.extrapanel_step3 = JPanel() self.extrapanel_step3.setLayout(BorderLayout()) self.extrapanel_step3.add(self.actionpanel_step3, BorderLayout.WEST) # Assembling thirdd step panel components self.panel_step3.add(self.titlepanel_step3, BorderLayout.NORTH) self.panel_step3.add(self.underpanel_step3, BorderLayout.WEST) self.panel_step3.add(self.extrapanel_step3, BorderLayout.SOUTH) self.uiPanelB.setBottomComponent(self.panel_step3) # Assembling the group of all panels layout = GroupLayout(self.pluginTab) self.pluginTab.setLayout(layout) layout.setHorizontalGroup( layout.createParallelGroup(GroupLayout.Alignment.LEADING).addGroup( layout.createSequentialGroup().addGap(10, 10, 10).addGroup( layout.createParallelGroup( GroupLayout.Alignment.LEADING).addComponent( self.uiTitle).addGap(15, 15, 15).addComponent( self.uiPanelA)).addContainerGap( 26, Short.MAX_VALUE))) layout.setVerticalGroup( layout.createParallelGroup(GroupLayout.Alignment.LEADING).addGroup( layout.createSequentialGroup().addGap(15, 15, 15).addComponent( self.uiTitle).addGap(15, 15, 15).addComponent( self.uiPanelA).addGap(20, 20, 20).addGap(20, 20, 20))) def extensionUnloaded(self): # Unload the plugin, and if running stop the background thread if self.upnpcombo_services.isEnabled(): if self.th.isAlive(): print("[+] Stopping thread %s") % self.th.getName() self.STOP_THREAD = True self.th.join() else: print("Thread %s already dead") % self.th.getName() print("[+] Burp plugin UPnP BHunter successfully unloaded") return def getTabCaption(self): return self.EXTENSION_NAME def getUiComponent(self): return self.pluginTab def clearAll(self, e=None): # Reset all data of the plugin self.services_dict.clear() self.progressbar.setString("Ready") self.progressbar.setValue(0) self.upnpcombo_targets.removeAllItems() self.upnpcombo_targets.setEnabled(False) self.upnpcombo_services.removeAllItems() self.upnpcombo_services.setEnabled(False) self.upnpcombo_actions.removeAllItems() self.upnpcombo_actions.setEnabled(False) self.intruderbutton.setEnabled(False) self.repeaterbutton.setEnabled(False) self.labelNoneServiceFound.setText(" ") self.textarea_request.setText(" ") print("[+] Clearing all data") return def startHunting(self, e=None): # Starting the UPnP hunt def startHunting_run(): # Initialize the internal parameters every time the start-discovery button is clicked self.services_dict.clear() found_loc = [] discovery_files = [] self.labelNoneServiceFound.setText(" ") self.intruderbutton.setEnabled(False) self.repeaterbutton.setEnabled(False) # Then determine if targerting IPv4 or IPv6 adresses if self.combo_ipversion.getSelectedItem() == "IPv4": self.ipv4_selected = True print("[+] Selected IPv4 address scope") else: self.ipv4_selected = False print("[+] Selected IPv6 address scope") # And here finally the hunt could start self.progressbar.setString("Running...") self.progressbar.setValue(20) found_loc = self.discoverUpnpLocations() self.progressbar.setValue(40) discovery_files = self.downloadXMLfiles(found_loc) self.progressbar.setValue(60) self.buildSOAPs(discovery_files) self.progressbar.setValue(80) self.progressbar.setString("Done") self.progressbar.setValue(100) self.updateComboboxList(self.services_dict) # Update the comboboxes list with the discovered UPnPs if (self.services_dict): self.upnpcombo_targets.setEnabled(True) self.upnpcombo_services.setEnabled(True) self.upnpcombo_actions.setEnabled(True) self.intruderbutton.setEnabled(True) self.repeaterbutton.setEnabled(True) if self.STOP_THREAD: return # Start a background thread to run the above nested function in order to prevent the blocking of plugin UI self.th = threading.Thread(target=startHunting_run) #self.th.daemon = True # This does not seem to be useful self.th.setName("th-BHunter") self.th.start() def ssdpReqBuilder(self, ssdp_timeout, st_type, ssdp_ip, ssdp_port): # Builder of the two ssdp msearch request types msearch_req = "M-SEARCH * HTTP/1.1\r\n" \ "HOST: {0}:{1}\r\n" \ "MAN: \"ssdp:discover\"\r\n" \ "MX: {2}\r\n" \ "ST: {3}\r\n" \ "\r\n" \ .format(ssdp_ip, ssdp_port, ssdp_timeout, st_type) return msearch_req def sendMsearch(self, ssdp_req, ssdp_ip, ssdp_port): # Send the ssdp request and retrieve response buf_resp = set() if self.ipv4_selected: print("[+] Creating IPv4 SSDP multicast request") sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) else: print("[+] Creating IPv6 SSDP multicast request") sock = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM) sock.setblocking(0) # Sending ssdp requests while len(ssdp_req): # Blocking socket client until the request is completely sent try: sent = sock.sendto(ssdp_req.encode("ASCII"), (ssdp_ip, ssdp_port)) ssdp_req = ssdp_req[sent:] except socket.error, exc: if exc.errno != errno.EAGAIN: print("[E] Got error %s with socket when sending") % exc sock.close() raise exc print("[!] Blocking socket until ", len(ssdp_req), " is sent.") select.select([], [sock], []) continue # Retrieving ssdp responses num_resp = 0 while sock: # Blocking socket until there are ssdp responses to be read or timeout is reached readable, __, __ = select.select([sock], [], [], self.SSDP_TIMEOUT) if not readable: # Timeout reached without receiving any ssdp response if num_resp == 0: print( "[!] Got timeout without receiving any ssdp response.") break else: num_resp = num_resp + 1 # Almost an ssdp response was received if readable[0]: try: data = sock.recv(1024) if data: buf_resp.add(data.decode('ASCII')) except socket.error, exc: print("[E] Got error %s with socket when receiving" ) % exc sock.close() raise exc
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")
class BurpExtender(IBurpExtender, ISessionHandlingAction, ITab, IContextMenuFactory, IContextMenuInvocation, ActionListener, ITextEditor): # # implement IBurpExtender # def registerExtenderCallbacks(self, callbacks): # save the helpers for later self.helpers = callbacks.getHelpers() # set our extension name callbacks.setExtensionName("Custom Request Handler") callbacks.registerSessionHandlingAction(self) callbacks.registerContextMenuFactory(self) self._text_editor = callbacks.createTextEditor() self._text_editor.setEditable(False) #How much loaded the table row self.current_column_id = 0 #GUI self._split_main = JSplitPane(JSplitPane.VERTICAL_SPLIT) self._split_top = JSplitPane(JSplitPane.HORIZONTAL_SPLIT) self._split_top.setPreferredSize(Dimension(100, 50)) self._split_top.setDividerLocation(700) self._split_center = JSplitPane(JSplitPane.VERTICAL_SPLIT) boxVertical = swing.Box.createVerticalBox() box_top = swing.Box.createHorizontalBox() boxHorizontal = swing.Box.createHorizontalBox() buttonHorizontal = swing.Box.createHorizontalBox() boxVertical.add(boxHorizontal) box_regex = swing.Box.createVerticalBox() border = BorderFactory.createTitledBorder(LineBorder(Color.BLACK), "Extract target strings", TitledBorder.LEFT, TitledBorder.TOP) box_regex.setBorder(border) self._add_btn = JButton("Add") self._add_btn.addActionListener(self) self._remove_btn = JButton("Remove") self._remove_btn.addActionListener(self) items = [ 'JSON', 'Header', ] self._dropdown = JComboBox(items) type_panel = JPanel(FlowLayout(FlowLayout.LEADING)) type_panel.add(JLabel('Type:')) type_panel.add(self._dropdown) self._jLabel_param = JLabel("Name:") self._param_error = JLabel("Name is required") self._param_error.setVisible(False) self._param_error.setFont(Font(Font.MONOSPACED, Font.ITALIC, 12)) self._param_error.setForeground(Color.red) regex_checkbox = JPanel(FlowLayout(FlowLayout.LEADING)) self._is_use_regex = JCheckBox("Extract from regex group") regex_checkbox.add(self._is_use_regex) self._jTextIn_param = JTextField(20) self._jLabel_regex = JLabel("Regex:") self._jTextIn_regex = JTextField(20) self._regex_error = JLabel("No group defined") self._regex_error.setVisible(False) self._regex_error.setFont(Font(Font.MONOSPACED, Font.ITALIC, 12)) self._regex_error.setForeground(Color.red) self._param_panel = JPanel(FlowLayout(FlowLayout.LEADING)) self._param_panel.add(self._jLabel_param) self._param_panel.add(self._jTextIn_param) self._param_panel.add(self._param_error) self._regex_panel = JPanel(FlowLayout(FlowLayout.LEADING)) self._regex_panel.add(self._jLabel_regex) self._regex_panel.add(self._jTextIn_regex) self._regex_panel.add(self._regex_error) button_panel = JPanel(FlowLayout(FlowLayout.LEADING)) #padding button_panel.add(JPanel()) button_panel.add(JPanel()) button_panel.add(JPanel()) button_panel.add(self._add_btn) button_panel.add(self._remove_btn) box_regex.add(type_panel) box_regex.add(self._param_panel) box_regex.add(regex_checkbox) box_regex.add(self._regex_panel) buttonHorizontal.add(button_panel) box_regex.add(buttonHorizontal) boxVertical.add(box_regex) box_top.add(boxVertical) box_file = swing.Box.createHorizontalBox() checkbox_panel = JPanel(FlowLayout(FlowLayout.LEADING)) border = BorderFactory.createTitledBorder( LineBorder(Color.BLACK), 'Payload Sets [Simple list]', TitledBorder.LEFT, TitledBorder.TOP) box_file.setBorder(border) box_param = swing.Box.createVerticalBox() box_param.add(checkbox_panel) file_column_names = [ "Type", "Name", "Payload", ] data = [] self.file_table_model = DefaultTableModel(data, file_column_names) self.file_table = JTable(self.file_table_model) self.file_table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF) column_model = self.file_table.getColumnModel() for count in xrange(column_model.getColumnCount()): column = column_model.getColumn(count) column.setPreferredWidth(160) self.file_table.preferredScrollableViewportSize = Dimension(500, 70) self.file_table.setFillsViewportHeight(True) panel_dropdown = JPanel(FlowLayout(FlowLayout.LEADING)) self._file_dropdown = JComboBox(items) panel_dropdown.add(JLabel('Type:')) panel_dropdown.add(self._file_dropdown) box_param.add(panel_dropdown) box_param.add(JScrollPane(self.file_table)) callbacks.customizeUiComponent(self.file_table) file_param_panel = JPanel(FlowLayout(FlowLayout.LEADING)) self._file_param = JLabel("Name:") self._file_param_text = JTextField(20) file_param_panel.add(self._file_param) file_param_panel.add(self._file_param_text) self._error_message = JLabel("Name is required") self._error_message.setVisible(False) self._error_message.setFont(Font(Font.MONOSPACED, Font.ITALIC, 12)) self._error_message.setForeground(Color.red) file_param_panel.add(self._error_message) box_param.add(file_param_panel) box_button_file = swing.Box.createVerticalBox() self._file_load_btn = JButton("Load") self._file_clear_btn = JButton("Clear") self._file_clear_btn.addActionListener(self) self._file_load_btn.addActionListener(self) box_button_file.add(self._file_load_btn) box_button_file.add(self._file_clear_btn) box_file.add(box_button_file) box_file.add(box_param) boxVertical.add(box_file) regex_column_names = [ "Type", "Name", "Regex", "Start at offset", "End at offset", ] #clear target.json with open("target.json", "w") as f: pass data = [] self.target_table_model = DefaultTableModel(data, regex_column_names) self.target_table = JTable(self.target_table_model) self.target_table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF) column_model = self.target_table.getColumnModel() for count in xrange(column_model.getColumnCount()): column = column_model.getColumn(count) column.setPreferredWidth(100) self.target_table.preferredScrollableViewportSize = Dimension(500, 70) self.target_table.setFillsViewportHeight(True) callbacks.customizeUiComponent(self.target_table) callbacks.customizeUiComponent(boxVertical) table_panel = swing.Box.createVerticalBox() table_panel.add(JScrollPane(self.target_table)) box_top.add(table_panel) self._jScrollPaneOut = JScrollPane() #self._split_main.setBottomComponent(self._jScrollPaneOut) self._split_main.setBottomComponent(self._text_editor.getComponent()) self._split_main.setTopComponent(box_top) self._split_main.setDividerLocation(450) callbacks.customizeUiComponent(self._split_main) callbacks.addSuiteTab(self) return def getTabCaption(self): return "CRH" def getUiComponent(self): return self._split_main def createMenuItems(self, invocation): menu = [] ctx = invocation.getInvocationContext() menu.append( swing.JMenuItem("Send to CRH", None, actionPerformed=lambda x, inv=invocation: self. menu_action(inv))) return menu if menu else None # # Implementation of Menu Action # def menu_action(self, invocation): try: invMessage = invocation.getSelectedMessages() message = invMessage[0].getResponse() res_info = self.helpers.analyzeResponse(message) send_res = message.tostring() self._text_editor.setText(send_res) except: print('Failed to add data to CRH tab.') # # Implementation of event action # def actionPerformed(self, actionEvent): # onclick add button of extract from regex group if actionEvent.getSource() is self._add_btn: start, end = self._text_editor.getSelectionBounds() value = None regex = None item = self._dropdown.getSelectedItem() param = self._jTextIn_param.getText() if len(param) is 0: self._param_error.setVisible(True) return self._param_error.setVisible(False) is_selected = self._is_use_regex.isSelected() if is_selected: start = None end = None regex = self._jTextIn_regex.getText() if len(regex) is 0: self._regex_error.setVisible(True) return req = self._text_editor.getText() try: pattern = re.compile(regex) match = pattern.search(req) value = match.group(1) if match else None if value is None: raise IndexError except IndexError: self._regex_error.setVisible(True) return self._regex_error.setVisible(False) data = [ item, param, regex, start, end, ] self.target_table_model.addRow(data) with open("target.json", "r+") as f: try: json_data = json.load(f) except ValueError: json_data = dict() if is_selected: data = { param: [ item, regex, ] } else: data = { param: [ item, start, end, ] } json_data.update(data) self.write_file(f, json.dumps(json_data)) # onclick remove button of extract from regex group if actionEvent.getSource() is self._remove_btn: rowno = self.target_table.getSelectedRow() if rowno != -1: column_model = self.target_table.getColumnModel() param_name = self.target_table_model.getValueAt(rowno, 1) start = self.target_table_model.getValueAt(rowno, 3) self.target_table_model.removeRow(rowno) with open("target.json", 'r+') as f: try: json_data = json.load(f) except ValueError: json_data = dict() for key, value in json_data.items(): if value[1] == start and key == param_name: try: del json_data[key] except IndexError: print('Error: {0}: No such json key.'.format( key)) self.write_file(f, json.dumps(json_data)) # onclick load button of payload sets if actionEvent.getSource() is self._file_load_btn: #clear table self.remove_all(self.file_table_model) self.current_column_id = 0 target_param = self._file_param_text.getText() item = self._file_dropdown.getSelectedItem() if len(target_param) == 0: self._error_message.setVisible(True) return self._error_message.setVisible(False) chooser = JFileChooser() chooser.showOpenDialog(actionEvent.getSource()) file_path = chooser.getSelectedFile().getAbsolutePath() with open(file_path, 'r') as f: while True: line = f.readline().strip() if not line: break data = [ item, target_param, line, ] self.file_table_model.addRow(data) with open('target.json', 'r+') as f: try: json_data = json.load(f) except ValueError: json_data = dict() json_data.update({target_param: [ item, 'Set payload', ]}) self.write_file(f, json.dumps(json_data)) # onclick clear button of payload sets if actionEvent.getSource() is self._file_clear_btn: self.remove_all(self.file_table_model) self.current_column_id = 0 with open("target.json", 'r+') as f: try: json_data = json.load(f) except: json_data = dict() for key, value in json_data.items(): if isinstance(value[1], unicode): if value[1].encode('utf-8') == 'Set payload': try: del json_data[key] except IndexError: print('Error: {0}: No such json key.'.format( key)) self.write_file(f, json.dumps(json_data)) # # Implementaion of ISessionHandlingAction # def getActionName(self): return "custom request handler" def performAction(self, current_request, macro_items): if len(macro_items) == 0: return # extract the response headers final_response = macro_items[len(macro_items) - 1].getResponse() if final_response is None: return req = self.helpers.analyzeRequest(current_request) try: with open('target.json', 'r') as f: read_data = f.read() self.read_data = json.loads(read_data) except ValueError: sys.stderr.write('Error: json.loads()') return for key, value in self.read_data.items(): if value[0] == 'JSON': self.set_json_parameter(current_request, final_response, key, value) elif value[0] == 'Header': self.set_header(current_request, final_response, key, value) def set_json_parameter(self, current_request, final_response, key, value): req = self.helpers.analyzeRequest(current_request) if IRequestInfo.CONTENT_TYPE_JSON != req.getContentType(): return False body = current_request.getRequest()[req.getBodyOffset():].tostring() json_data = json.loads(body, object_pairs_hook=collections.OrderedDict) target_keys = filter(lambda x: x == key, json_data.keys()) if not target_keys: return req_data = json_data column_model = self.file_table.getColumnModel() row_count = self.file_table_model.getRowCount() for key in target_keys: if value[-1] == 'Set payload': if row_count > self.current_column_id: req_value = self.file_table_model.getValueAt( self.current_column_id, 2) self.current_column_id += 1 else: # No selected regex if len(value) > 2: start, end = value[1:] req_value = final_response[start:end].tostring() else: regex = value[1] match = re.search(regex, final_response.tostring()) req_value = match.group(1) if match else None req_data[key] = req_value req = current_request.getRequest() json_data_start = self.helpers.indexOf(req, bytearray(body), False, 0, len(req)) # glue together header + customized json of request current_request.setRequest( req[0:json_data_start] + self.helpers.stringToBytes(json.dumps(req_data))) def set_header(self, current_request, final_response, key, value): req = self.helpers.analyzeRequest(current_request) headers = req.getHeaders() target_keys = [] for header in headers: if header.startswith(key): target_keys += [key] if not target_keys: return column_model = self.file_table.getColumnModel() row_count = self.file_table_model.getRowCount() req = current_request.getRequest() for key in target_keys: if value[-1] == 'Set payload': if row_count > self.current_column_id: req_value = self.file_table_model.getValueAt( self.current_column_id, 2) self.current_column_id += 1 else: # No selected regex if len(value) > 2: start, end = value[1:] req_value = final_response[start:end].tostring() else: regex = value[1] match = re.search(regex, final_response.string()) req_value = match.group(1) if match else None key_start = self.helpers.indexOf(req, bytearray(key.encode('utf-8')), False, 0, len(req)) key_end = self.helpers.indexOf(req, bytearray('\r\n'), False, key_start, len(req)) keylen = len(key) # glue together first line + customized hedaer + rest of request current_request.setRequest( req[0:key_start] + self.helpers.stringToBytes("%s: %s" % (key.encode('utf-8'), req_value)) + req[key_end:]) # # Implementation of function for Remove all for specific table data # def remove_all(self, model): count = model.getRowCount() for i in xrange(count): model.removeRow(0) # # Implementaion of function for write data for specific file # def write_file(self, f, data): f.seek(0) f.write(data) f.truncate() return
class NewAtfView(JDialog): ''' Prompt user to choose some options to create a template for a new ATF file. ''' def __init__(self, controller, projects, languages, protocols): self.modalityType = Dialog.ModalityType.APPLICATION_MODAL self.controller = controller self.projects = projects self.languages = languages self.protocols = protocols self.cancelled = False self.springLayout = SpringLayout() self.pane = self.getContentPane() def display(self): ''' Displays window. ''' self.build() self.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE) self.setResizable(False) self.setTitle("New ATF template") self.pack() self.setLocationRelativeTo(None) self.visible = 1 def build(self): ''' Puts all the window components together in the JFrame ''' layout = BoxLayout(self.getContentPane(), BoxLayout.Y_AXIS) self.setLayout(layout) # Create all necessary panels ampersand_panel = self.build_ampersand_row() project_panel = self.build_projects_row() language_panel = self.build_language_row() buttons_panel = self.build_buttons_row() # Add panels to main JFrame self.add(ampersand_panel) self.add(project_panel) self.add(language_panel) self.add(buttons_panel) def build_ampersand_row(self): ''' Builds the &-line row. ''' # Build own panel with SpringLayout. panel = JPanel() layout = SpringLayout() panel.setLayout(layout) # Create necessary components and add them to panel. ampersand_label = JLabel("CDLI's ID: ") self.left_field = JTextField('&') equals_label = JLabel('=') self.right_field = JTextField() tooltip_text = ("<html><body>This is the ID and text's designation " "according to<br/>the CDLI catalog. If your text is " "not yet in the<br/>catalog, please email " "[email protected] to get<br/>an ID and designation." ) help_label = self.build_help_label(tooltip_text) panel.add(ampersand_label) panel.add(self.left_field) panel.add(equals_label) panel.add(self.right_field) panel.add(help_label) # Set up constraints to tell panel how to position components. layout.putConstraint(SpringLayout.WEST, ampersand_label, 20, SpringLayout.WEST, panel) layout.putConstraint(SpringLayout.NORTH, ampersand_label, 23, SpringLayout.NORTH, panel) layout.putConstraint(SpringLayout.WEST, self.left_field, 90, SpringLayout.WEST, panel) layout.putConstraint(SpringLayout.NORTH, self.left_field, 20, SpringLayout.NORTH, panel) layout.putConstraint(SpringLayout.WEST, equals_label, 5, SpringLayout.EAST, self.left_field) layout.putConstraint(SpringLayout.NORTH, equals_label, 23, SpringLayout.NORTH, panel) layout.putConstraint(SpringLayout.WEST, self.right_field, 5, SpringLayout.EAST, equals_label) layout.putConstraint(SpringLayout.NORTH, self.right_field, 20, SpringLayout.NORTH, panel) layout.putConstraint(SpringLayout.WEST, help_label, 5, SpringLayout.EAST, self.right_field) layout.putConstraint(SpringLayout.NORTH, help_label, 23, SpringLayout.NORTH, panel) layout.putConstraint(SpringLayout.EAST, panel, 15, SpringLayout.EAST, help_label) layout.putConstraint(SpringLayout.SOUTH, panel, 10, SpringLayout.SOUTH, help_label) # Add this to NewAtf JFrame return panel def build_projects_row(self): ''' Builds the projects row. ''' # Build own panel with SpringLayout. panel = JPanel() layout = SpringLayout() panel.setLayout(layout) # Create necessary components and add them to panel. project_label = JLabel('Project: ') self.right_combo = JComboBox() self.right_combo.setEditable(True) def create_project_list(): ''' Prepares list of projects and subprojects ordered with the default one first. ''' default_project = self.projects['default'][0].split('/')[0] if '/' in self.projects['default']: default_subproject = self.projects['default'].split('/')[1] else: default_subproject = '' projects = [default_project] subprojects = [default_subproject] # User created projects might not be in default dictionary for project in self.projects.keys(): if (project != default_project and project != 'default'): projects.append(project) # Default project might not have subproject if default_project in self.projects.keys(): if default_subproject: for subproject in self.projects[default_project]: if (subproject != default_subproject): subprojects.append(subproject) return projects, subprojects self.left_combo = JComboBox(create_project_list()[0]) # Make left combo keep size no matter how long project names are self.left_combo.setPreferredSize(Dimension(125, 30)) self.left_combo.setMinimumSize(self.left_combo.getPreferredSize()) self.left_combo.setMaximumSize(self.left_combo.getPreferredSize()) self.left_combo.setSize(self.left_combo.getPreferredSize()) self.right_combo = JComboBox(create_project_list()[1]) # Prevent right combo to change sizes dynamically self.right_combo.setPreferredSize(Dimension(100, 30)) self.right_combo.setMinimumSize(self.left_combo.getPreferredSize()) self.right_combo.setMaximumSize(self.left_combo.getPreferredSize()) self.right_combo.setSize(self.left_combo.getPreferredSize()) action_listener = ComboActionListener(self.right_combo, self.projects) self.left_combo.addActionListener(action_listener) self.left_combo.setEditable(True) self.right_combo.setEditable(True) slash_label = JLabel('/') tooltip_text = ("<html><body>Choose project from list or insert a new " "one.<br/>You can leave the right-hand field blank." "</body><html>") help_label = self.build_help_label(tooltip_text) panel.add(project_label) panel.add(self.left_combo) panel.add(slash_label) panel.add(self.right_combo) panel.add(help_label) # Set up constraints to tell panel how to position components. layout.putConstraint(SpringLayout.WEST, project_label, 15, SpringLayout.WEST, panel) layout.putConstraint(SpringLayout.NORTH, project_label, 18, SpringLayout.NORTH, panel) layout.putConstraint(SpringLayout.WEST, self.left_combo, 90, SpringLayout.WEST, panel) layout.putConstraint(SpringLayout.NORTH, self.left_combo, 15, SpringLayout.NORTH, panel) layout.putConstraint(SpringLayout.WEST, slash_label, 5, SpringLayout.EAST, self.left_combo) layout.putConstraint(SpringLayout.NORTH, slash_label, 18, SpringLayout.NORTH, panel) layout.putConstraint(SpringLayout.WEST, self.right_combo, 5, SpringLayout.EAST, slash_label) layout.putConstraint(SpringLayout.NORTH, self.right_combo, 15, SpringLayout.NORTH, panel) layout.putConstraint(SpringLayout.WEST, help_label, 5, SpringLayout.EAST, self.right_combo) layout.putConstraint(SpringLayout.NORTH, help_label, 18, SpringLayout.NORTH, panel) layout.putConstraint(SpringLayout.EAST, panel, 15, SpringLayout.EAST, help_label) layout.putConstraint(SpringLayout.SOUTH, panel, 10, SpringLayout.SOUTH, help_label) # Add this to NewAtf JFrame return panel def build_language_row(self): ''' Builds the language row. ''' # Build own panel with SpringLayout. panel = JPanel() layout = SpringLayout() panel.setLayout(layout) # Get language list from settings.yaml, removing the default one from # the list languages = self.languages.keys() languages.remove('default') # Create necessary components and add them to panel. language_label = JLabel('Language: ') self.language_combo = JComboBox(languages) # Set selected language to default self.language_combo.setSelectedItem(self.languages['default']) tooltip_text = "Choose a language from the dropdown menu." help_label = self.build_help_label(tooltip_text) panel.add(language_label) panel.add(self.language_combo) panel.add(help_label) # Set up constraints to tell panel how to position components. layout.putConstraint(SpringLayout.WEST, language_label, 15, SpringLayout.WEST, panel) layout.putConstraint(SpringLayout.NORTH, language_label, 18, SpringLayout.NORTH, panel) layout.putConstraint(SpringLayout.WEST, self.language_combo, 90, SpringLayout.WEST, panel) layout.putConstraint(SpringLayout.NORTH, self.language_combo, 15, SpringLayout.NORTH, panel) layout.putConstraint(SpringLayout.WEST, help_label, 5, SpringLayout.EAST, self.language_combo) layout.putConstraint(SpringLayout.NORTH, help_label, 18, SpringLayout.NORTH, panel) layout.putConstraint(SpringLayout.EAST, panel, 15, SpringLayout.EAST, help_label) layout.putConstraint(SpringLayout.SOUTH, panel, 10, SpringLayout.SOUTH, help_label) # Add this to NewAtf JFrame return panel def build_buttons_row(self): ''' Add OK/Cancel/Blank buttons. ''' # Build own panel with SpringLayout. panel = JPanel() layout = SpringLayout() panel.setLayout(layout) # Create necessary components and add them to panel. create_button = JButton('Create template', actionPerformed=self.create_template) leave_button = JButton('Leave blank', actionPerformed=self.blank) cancel_button = JButton('Cancel', actionPerformed=self.cancel) panel.add(create_button) panel.add(leave_button) panel.add(cancel_button) # Set up constraints to tell panel how to position components. layout.putConstraint(SpringLayout.WEST, create_button, 15, SpringLayout.WEST, panel) layout.putConstraint(SpringLayout.NORTH, create_button, 15, SpringLayout.NORTH, panel) layout.putConstraint(SpringLayout.WEST, leave_button, 5, SpringLayout.EAST, create_button) layout.putConstraint(SpringLayout.NORTH, leave_button, 15, SpringLayout.NORTH, panel) layout.putConstraint(SpringLayout.WEST, cancel_button, 5, SpringLayout.EAST, leave_button) layout.putConstraint(SpringLayout.NORTH, cancel_button, 15, SpringLayout.NORTH, panel) layout.putConstraint(SpringLayout.EAST, panel, 15, SpringLayout.EAST, cancel_button) layout.putConstraint(SpringLayout.SOUTH, panel, 10, SpringLayout.SOUTH, cancel_button) # Add this to NewAtf JFrame return panel def build_help_label(self, tooltip_text): icon = ImageIcon(find_image_resource('smallhelp')) label = JLabel() label.setIcon(icon) label.setToolTipText(tooltip_text) return label def cancel(self, event): self.cancelled = True self.dispose() def blank(self, event): self.controller.show_template() self.dispose() def create_template(self, event): ''' Put together user selected elements of the template following ATF file format. ''' # &-line # E.g. &X001001 = JCS 48, 089 and_line = "{} = {}".format(self.left_field.getText().encode('utf-8'), self.right_field.getText().encode('utf-8')) # Project line # E.g. #project: cams/gkab # E.g. #project: rimanum project_line = "#project: {}".format( self.left_combo.getSelectedItem().encode('utf-8')) if self.right_combo.getSelectedItem(): project_line = "{}/{}".format( project_line, self.right_combo.getSelectedItem().encode('utf-8')) # Language line # E.g. #atf: lang akk-x-stdbab language = self.language_combo.getSelectedItem() language_code = self.languages[language] # Protocol line/s # E.g. #atf: use unicode protocols = '' for protocol in self.protocols: protocols += '#atf: use {}\n'.format(protocol) # Put together all lines to create the template and show in ATF area self.controller.template = ('{}\n' '{}\n' '#atf: lang {}\n' '{}\n'.format(and_line, project_line, language_code, protocols) ) self.controller.show_template() self.dispose()
class BurpExtender(IBurpExtender, ITab, IContextMenuFactory, DocumentListener, ChangeListener): # # implement IBurpExtender # def registerExtenderCallbacks(self, callbacks): print "PhantomJS RIA Crawler extension" print "Nikolay Matyunin @autorak <*****@*****.**>" # keep a reference to our callbacks object and helpers object self._callbacks = callbacks self._helpers = callbacks.getHelpers() # extension name callbacks.setExtensionName("Phantom RIA Crawler") # Create Tab UI components self._jPanel = JPanel() self._jPanel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5)); _titleLabel = JLabel("Phantom RIA Crawler", SwingConstants.LEFT) _titleLabelFont = _titleLabel.font _titleLabelFont = _titleLabelFont.deriveFont(Font.BOLD, 12); _titleLabel.setFont(_titleLabelFont); _titleLabel.setForeground(Color(230, 142, 11)) self._addressTextField = JTextField('') self._addressTextField.setColumns(50) _addressTextLabel = JLabel("Target URL:", SwingConstants.RIGHT) self._addressTextField.getDocument().addDocumentListener(self) self._phantomJsPathField = JTextField('phantomjs') # TODO: set permanent config value self._phantomJsPathField.setColumns(50) _phantomJsPathLabel = JLabel("PhantomJS path:", SwingConstants.RIGHT) self._startButton = JToggleButton('Start', actionPerformed=self.startToggled) self._startButton.setEnabled(False) _requestsMadeLabel = JLabel("DEPs found:", SwingConstants.RIGHT) self._requestsMadeInfo = JLabel("", SwingConstants.LEFT) _statesFoundLabel = JLabel("States found:", SwingConstants.RIGHT) self._statesFoundInfo = JLabel("", SwingConstants.LEFT) _separator = JSeparator(SwingConstants.HORIZONTAL) _configLabel = JLabel("Crawling configuration:") self._configButton = JButton("Load config", actionPerformed=self.loadConfigClicked) self._configFile = "" _listenersLabel= JLabel("Burp proxy listener:", SwingConstants.RIGHT) self._listenersCombo = JComboBox() self._configTimer = Timer(5000, None) self._configTimer.actionPerformed = self._configUpdated self._configTimer.stop() self._configUpdated(None) self._commandClient = CommandClient(self) # Layout management self._groupLayout = GroupLayout(self._jPanel) self._jPanel.setLayout(self._groupLayout) self._groupLayout.setAutoCreateGaps(True) self._groupLayout.setAutoCreateContainerGaps(True) self._groupLayout.setHorizontalGroup(self._groupLayout.createParallelGroup() .addComponent(_titleLabel) .addGroup(self._groupLayout.createSequentialGroup() .addComponent(_addressTextLabel) .addGroup(self._groupLayout.createParallelGroup() .addComponent(self._addressTextField, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE) .addGroup(self._groupLayout.createSequentialGroup() .addComponent(_requestsMadeLabel) .addComponent(self._requestsMadeInfo)) .addGroup(self._groupLayout.createSequentialGroup() .addComponent(_statesFoundLabel) .addComponent(self._statesFoundInfo))) .addComponent(self._startButton)) .addComponent(_separator) .addGroup(self._groupLayout.createSequentialGroup() .addComponent(_configLabel) .addComponent(self._configButton)) .addGroup(self._groupLayout.createSequentialGroup() .addComponent(_phantomJsPathLabel) .addComponent(self._phantomJsPathField, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE)) .addGroup(self._groupLayout.createSequentialGroup() .addComponent(_listenersLabel) .addComponent(self._listenersCombo, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE)) ) self._groupLayout.setVerticalGroup(self._groupLayout.createSequentialGroup() .addComponent(_titleLabel) .addGroup(self._groupLayout.createParallelGroup(GroupLayout.Alignment.BASELINE) .addComponent(_addressTextLabel) .addComponent(self._addressTextField) .addComponent(self._startButton)) .addGroup(self._groupLayout.createParallelGroup(GroupLayout.Alignment.BASELINE) .addComponent(_requestsMadeLabel) .addComponent(self._requestsMadeInfo)) .addGroup(self._groupLayout.createParallelGroup(GroupLayout.Alignment.BASELINE) .addComponent(_statesFoundLabel) .addComponent(self._statesFoundInfo)) .addComponent(_separator, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addGroup(self._groupLayout.createParallelGroup(GroupLayout.Alignment.BASELINE) .addComponent(_configLabel) .addComponent(self._configButton)) .addGroup(self._groupLayout.createParallelGroup(GroupLayout.Alignment.BASELINE) .addComponent(_phantomJsPathLabel) .addComponent(self._phantomJsPathField)) .addGroup(self._groupLayout.createParallelGroup(GroupLayout.Alignment.BASELINE) .addComponent(_listenersLabel) .addComponent(self._listenersCombo)) ) self._groupLayout.linkSize(SwingConstants.HORIZONTAL, _configLabel, _phantomJsPathLabel); self._groupLayout.linkSize(SwingConstants.HORIZONTAL, _configLabel, _listenersLabel); self._groupLayout.linkSize(SwingConstants.HORIZONTAL, _statesFoundLabel, _requestsMadeLabel); # context menu data self._contextMenuData = None; self._running = False; # register callbacks callbacks.customizeUiComponent(self._jPanel) callbacks.registerContextMenuFactory(self) callbacks.addSuiteTab(self) return # # implement ITab and Tab ChangeListener # def getTabCaption(self): return "Phantom RIA Crawler" def getUiComponent(self): return self._jPanel def stateChanged(self, ev): self._configUpdated() def _configUpdated(self, ev): config = self._callbacks.saveConfig() # update proxy listeners index = 0 listeners = DefaultComboBoxModel() while (("proxy.listener" + str(index)) in config): listenerItem = config["proxy.listener" + str(index)] listenerItems = listenerItem.split(".") if (listenerItems[0] == "1"): address = ".".join(listenerItems[2][1:].split("|")) if (len(address) == 0): address = "127.0.0.1" listeners.addElement(address + " : " + listenerItems[1]) index = index + 1 self._listenersCombo.setModel(listeners) return; # # implement button actions # def startToggled(self, ev): if (self._startButton.getModel().isSelected()): try: os.chdir(sys.path[0] + os.sep + "riacrawler" + os.sep + "scripts") except Exception as e: print >> sys.stderr, "RIA crawler scripts loading error", "I/O error({0}): {1}".format(e.errno, e.strerror) self._startButton.setSelected(False) return phantomJsPath = self._phantomJsPathField.text target = self._addressTextField.text config = "crawler.config" if (self._configFile): config = self._configFile listenerAddress = self._listenersCombo.getSelectedItem().replace(" ", "") p = Popen("{0} --proxy={3} main.js --target={1} --config={2}".format(phantomJsPath, target, config, listenerAddress), shell=True) self._running = True self._requestsMadeInfo.setText("") self._statesFoundInfo.setText("") self._commandClient.startCrawling() else: if (self._running): self._commandClient.stopCrawling() self._running = False def syncCrawlingState(self, result): print "RIA crawling state: ", result self._requestsMadeInfo.setText(str(result["requests_made"])) self._statesFoundInfo.setText(str(result["states_detected"])) if (result["running"] == False): self._commandClient.stopCrawling() self._running = False self._startButton.setSelected(False) def loadConfigClicked(self, ev): openFile = JFileChooser(); openFile.showOpenDialog(None); self._configFile = openFile.getSelectedFile() # # implement DocumentListener for _addressTextField # def removeUpdate(self, ev): self.updateStartButton() def insertUpdate(self, ev): self.updateStartButton() def updateStartButton(self): self._startButton.setEnabled(len(self._addressTextField.text) > 0) # # implement IContextMenuFactory # def createMenuItems(self, contextMenuInvocation): menuItemList = ArrayList() context = contextMenuInvocation.getInvocationContext() if (context == IContextMenuInvocation.CONTEXT_MESSAGE_VIEWER_REQUEST or context == IContextMenuInvocation.CONTEXT_MESSAGE_EDITOR_REQUEST or context == IContextMenuInvocation.CONTEXT_PROXY_HISTORY or context == IContextMenuInvocation.CONTEXT_TARGET_SITE_MAP_TABLE): self._contextMenuData = contextMenuInvocation.getSelectedMessages() menuItemList.add(JMenuItem("Send to Phantom RIA Crawler", actionPerformed = self.menuItemClicked)) return menuItemList def menuItemClicked(self, event): if (self._running == True): self._callbacks.issueAlert("Can't set data to Phantom RIA Crawler: crawling is running already.") return; dataIsSet = False; for message in self._contextMenuData: request = self._helpers.analyzeRequest(message) url = request.getUrl().toString() print url if (url): dataisSet = True; self._addressTextField.setText(url)
class BurpExtender(IBurpExtender, IContextMenuFactory, ActionListener, IMessageEditorController, ITab, ITextEditor, IHttpService, IScanIssue, IHttpRequestResponseWithMarkers): def __init__(self): self.menuItem = JMenuItem('Generate Finding') self.menuItem.addActionListener(self) # implement IBurpExtender def registerExtenderCallbacks(self, callbacks): # keep a reference to our callbacks object (Burp Extensibility Feature) self._callbacks = callbacks self._helpers = callbacks.getHelpers() # set our extension name callbacks.setExtensionName("Generate Finding") callbacks.registerContextMenuFactory(self) # -- Request Response Viewers -- # # create the lower half for the Request Response tabs... # Request and response from selection self._tabbedPane = JTabbedPane() tabs = self._tabbedPane self._requestViewer = callbacks.createMessageEditor(self, True) self._responseViewer = callbacks.createMessageEditor(self, True) self._requestHighlight = callbacks.createTextEditor() self._responseHighlight = callbacks.createTextEditor() tabs.addTab("Supporting Request", self._requestViewer.getComponent()) tabs.addTab("Supporting Response", self._responseViewer.getComponent()) tabs.addTab("Request Marker Selection", self._requestHighlight.getComponent()) tabs.addTab("Response Marker Selection", self._responseHighlight.getComponent()) #self._mainFrame.setRightComponent(tabs) # set to the lower split pane print "*" * 60 print "[+] Request/Response tabs created" # -- Define Issue Details GUI & Layout-- # # Labels and Input boxes... # Issue Name self.issueNameLabel = JLabel(" Issue Name:") self.issueNameValue = JTextArea(text = str(issueNamePlaceholder), editable = True, wrapStyleWord = True, lineWrap = True, alignmentX = Component.LEFT_ALIGNMENT, size = (1, 20) ) # Issue Detail self.issueDetailLabel = JLabel(" Issue Detail:") #self.issueDetailValue = JTextField(str(issueDetailPlaceholder), 15) self.issueDetailValue = JTextArea(text = str(issueDetailPlaceholder), editable = True, wrapStyleWord = True, lineWrap = True, alignmentX = Component.LEFT_ALIGNMENT, size = (100, 20) ) # IssueBackground self.issueBackgroundLabel = JLabel(" Issue Background:") self.issueBackgroundValue = JTextArea(text = str(issueBackgroundPlaceholder), editable = True, wrapStyleWord = True, lineWrap = True, alignmentX = Component.LEFT_ALIGNMENT, size = (100, 20) ) # Remediation Detail self.issueRemediationLabel = JLabel(" Remediation Detail:") self.issueRemediationValue = JTextArea(text = str(remediationDetailPlaceholder), editable = True, wrapStyleWord = True, lineWrap = True, alignmentX = Component.LEFT_ALIGNMENT, size = (100, 20) ) # Remediation Background self.issueRemBackgroundLabel = JLabel(" Remediation Background:") self.issueRemBackgroundValue = JTextArea(text = str(remediationBackgroundPlaceholder), editable = True, wrapStyleWord = True, lineWrap = True, alignmentX = Component.LEFT_ALIGNMENT, size = (100, 20) ) # Issue URL self.issueURLLabel = JLabel(" URL (path = http://domain/path):") self.issueURLValue = JTextArea(text = str(issueURLPlaceholder), editable = True, wrapStyleWord = True, lineWrap = True, alignmentX = Component.LEFT_ALIGNMENT, size = (1, 20) ) # Issue Port self.issuePortLabel = JLabel(" Port:") self.issuePortValue = JTextArea(text = str(issuePortPlaceholder), editable = True, wrapStyleWord = True, lineWrap = True, alignmentX = Component.LEFT_ALIGNMENT, size = (1, 20) ) # Confidence self.confidenceValuesList = ("Certain","Firm","Tentative") self.issueConfienceLabel = JLabel(" Confidence [Certain, Firm or Tentative]") self.issueConfidenceValue = JComboBox(self.confidenceValuesList) # Severity self.severityValuesList = ("High","Medium","Low","Information") self.issueSeverityLabel = JLabel(" Severity [High, Medium Low or Informational]") self.issueSeverityValue = JComboBox(self.severityValuesList) # Add Finding button self.addFindingButton = JButton("Generate Finding", actionPerformed=self.createScanIssue, alignmentX=Component.CENTER_ALIGNMENT) # -- Group items for display -- # # Group items self.grpIssueSummary = JPanel(GridLayout(0,1)) self.grpIssueSummary.add(self.issueNameLabel) self.grpIssueSummary.add(self.issueNameValue) self.grpIssueSummary.add(self.issueDetailLabel) self.grpIssueSummary.add(self.issueDetailValue) self.grpIssueSummary.add(self.issueBackgroundLabel) self.grpIssueSummary.add(self.issueBackgroundValue) self.grpIssueSummary.add(self.issueRemediationLabel) self.grpIssueSummary.add(self.issueRemediationValue) self.grpIssueSummary.add(self.issueRemBackgroundLabel) self.grpIssueSummary.add(self.issueRemBackgroundValue) self.grpIssueSummary.add(self.issueURLLabel) self.grpIssueSummary.add(self.issueURLValue) self.grpIssueSummary.add(self.issuePortLabel) self.grpIssueSummary.add(self.issuePortValue) self.grpIssueSummary.add(self.issueURLLabel) self.grpIssueSummary.add(self.issueURLValue) self.grpIssueSummary.add(self.issuePortLabel) self.grpIssueSummary.add(self.issuePortValue) self.grpRatingBoxes = JPanel() self.grpRatingBoxes.add(self.issueSeverityLabel) self.grpRatingBoxes.add(self.issueSeverityValue) self.grpRatingBoxes.add(self.issueConfienceLabel) self.grpRatingBoxes.add(self.issueConfidenceValue) self.grpRatingBoxes.add(self.addFindingButton) # add grps to details frame self._detailsPanel = JPanel(GridLayout(0,1)) self._detailsPanel.add(self.grpIssueSummary) self._detailsPanel.add(self.grpRatingBoxes) self._findingDetailsPane = JScrollPane(self._detailsPanel) # create the main frame to hold details self._detailsViewer = self._findingDetailsPane # creates a form for details #tabs.addTab("Finding Details", self._detailsViewer) self._mainFrame = JSplitPane(JSplitPane.VERTICAL_SPLIT, self._detailsViewer, tabs) self._mainFrame.setOneTouchExpandable(True); self._mainFrame.setDividerLocation(0.5) self._mainFrame.setResizeWeight(0.50) print "[+] Finding details panel created" print "[+] Rendering..." # customize our UI components callbacks.customizeUiComponent(self._mainFrame) callbacks.customizeUiComponent(self._tabbedPane) callbacks.customizeUiComponent(self._detailsPanel) callbacks.customizeUiComponent(tabs) # add the custom tab to Burp's UI callbacks.addSuiteTab(self) print "[+] Done" print "[!] Added suite tab initialize complete!" return def getTabCaption(self): return "Generate Finding" def getUiComponent(self): return self._mainFrame # initiaizes when button is clicked in 'Generate Finding Tab' def createScanIssue(self, event): print "[!] Finding Detail: " print "\t[+] Name:\n\t\t", self.issueNameValue.getText().strip() name = self.issueNameValue.getText() print "\t[+] Description:\n\t\t", self.issueDetailValue.getText().strip() description = self.issueDetailValue.getText() print "\t[+] Background:\n\t\t", self.issueBackgroundValue.getText().strip() background = self.issueBackgroundValue.getText() print "\t[+] Remediation:\n\t\t", self.issueRemediationValue.getText().strip() remediation = self.issueRemediationValue.getText() print "\t[+] Remediation Background:\n\t\t", self.issueRemBackgroundValue.getText().strip() remBackground = self.issueRemBackgroundValue.getText() print "\t[+] URL Detail:\n\t\t", self.issueURLValue.getText() urlDetail = self.issueURLValue.getText() print "\t[+] Port Number:\n\t\t", self.issuePortValue.getText() portNumber = self.issuePortValue.getText() print "\t[+] Confidence Rating:\n\t\t", self.issueConfidenceValue.getSelectedItem() confidenceRating = self.issueConfidenceValue.getSelectedItem() print "\t[+] Severity Rating:\n\t\t", self.issueSeverityValue.getSelectedItem() severityRating = self.issueSeverityValue.getSelectedItem() #print "\t[+] Payload Markers:\n\t\t", self.getSelectionBounds() # get highlighted data from request/response tabs in 'Generate Finding' #print "[!] Request Selected data:", self._requestViewer.getSelectedData() #highRequest = self._requestViewer.getSelectedData() #print "converted:", self._helpers.bytesToString(highRequest) #print "[!] Response Selected data:", self._responseViewer.getSelectedData() #highResponse = self._responseViewer.getSelectedData() #print "converted:", self._helpers.bytesToString(highResponse) # current message is used - should work as long as menu item 'Generate Finding' is not reset or used before finding has been generated. requestResponse = self.current_message print "\t[+] RequestResponse:\n\t\t", requestResponse print "\t[+] Service:\n\t\t", requestResponse.getHttpService() # Collect request and Response Markers... #print "[**] Request Bounds: ", self._requestHighlight.getSelectionBounds() requestBounds = self._requestHighlight.getSelectionBounds() #print "[**] Response Bounds: ", self._responseHighlight.getSelectionBounds() responseBounds = self._responseHighlight.getSelectionBounds() # applyMarkers to request/response # callbacks.applyMarkers(requestResponse, None, [array('i', (data[1], data[2]))]) self.reqMarkers = [requestBounds[0],requestBounds[1]] print "\t[+] Request Reporting Markers:\n\t\t", self.reqMarkers self.resMarkers = [responseBounds[0],responseBounds[1]] print "\t[+] Response Reporting Markers:\n\t\t", self.resMarkers print "*" * 60 print "[!] Attempting to create custom scan issue." # Call AddScanItem class to create scan issue!! finding_array = [urlDetail, name, 134217728, severityRating, confidenceRating, background, remBackground, description, remediation, requestResponse] issue = ScanIssue(self, finding_array, self.current_message, self.reqMarkers, self.resMarkers, self._helpers, self._callbacks) self._callbacks.addScanIssue(issue) # Done print "[+] Finding Generated!" def getRequestResponseText(self): messages = self.ctxMenuInvocation.getSelectedMessages() # parses currently selected finding to a string if len(messages) == 1 : for self.m in messages: requestResponse = self.m # add requestResponseWithMarkers to be global so can be included in scanIssue self.current_message = requestResponse # get request data and convert to string requestDetail = requestResponse.getRequest() try: requestData = self._helpers.bytesToString(requestDetail) # converts & Prints out the entire request as string except: requestData = '[-] No Request Detail in this RequestResponse' pass # get response data and convert to string responseDetail = requestResponse.getResponse() try: responseData = self._helpers.bytesToString(responseDetail) # converts & Prints out the entire request as string except: responseData = '[-] No Response Detail in this RequestResponse' pass requestData = self._helpers.bytesToString(requestDetail) # converts & Prints out the entire request as string # send request string to 'Supporting Request' tab - 'True' because it is a request! self._requestViewer.setMessage(requestData, True) # for higlighting markers.. self._requestHighlight.setText(requestData) # send response string to 'Supporting Response' tab self._responseViewer.setMessage(responseData, False) # set False as is a response not request... # for higlighting markers.. self._responseHighlight.setText(responseData) def getFindingDetails(self): messages = self.ctxMenuInvocation.getSelectedMessages() print "*" * 60 print "[+] Handling selected request: ", self.current_message if len(messages) == 1: for m in messages: # URL #print "[!] Selected Request's URL: \n", self._helpers.analyzeRequest(m).getUrl() self.issueURLValue.setText(str(self._helpers.analyzeRequest(m).getUrl())) # update finding info # Protocol #print "[!] Request's Protocol: \n", m.getProtocol() # Request Port #print "[!] Request's Port: \n", m.getPort() self.issuePortValue.setText(str(m.getPort())) # update finding info print "*" * 60 # API hook... def getHttpMessages(self): return [self.m] # Actions on menu click... def actionPerformed(self, actionEvent): print "*" * 60 print "[+] Request sent to 'Generate Finding'" try: # When clicked!! self.getRequestResponseText() self.getFindingDetails() except: tb = traceback.format_exc() print tb # create Menu def createMenuItems(self, ctxMenuInvocation): self.ctxMenuInvocation = ctxMenuInvocation return [self.menuItem]
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
masterBox.add(controlBox) # display dialog and collect options if document.hasSelection == True: if 1 == Application.request("New Risk", masterBox, ("Cancel", "OK")): #create the new risk node document.addEntityAsSuccessor = True #eCls = document.getEntityClassByName('Risk') #newRisk = document.addEntity(eCls)[0] # attach to currently selected node #newRisk.title = riskNameField.text selectedEntity = document.selection[0] editor = selectedEntity.annotationEditor editor.insert("Risk: [", {}) editor.insert(riskNameField.text, {}) editor.insert(" | Type: ", {}) editor.insert(riskTypeComboBox.getSelectedItem(), {}) editor.insert(" | Likelihood: ", {}) editor.insert(riskLikelihood.getSelectedItem(), {}) editor.insert(" | Severity: ", {}) editor.insert(riskSeverity.getSelectedItem(), {}) editor.insert("]\n", {}) editor.flush() #if selectedEntity.user['HasRisks'] > 0: #selectedEntity.user['HasRisks'] = selectedEntity.user['HasRisks'] + 1 #else: # selectedEntity.user['HasRisks'] = 1 #document.modifyAttribute([selectedEntity],"symbol",document.getSymbolByName("WRITING_BALLOON_SHOUT")) selectedEntity.symbol = document.getSymbolByName( Application.WRITING_BALLOON_SHOUT) #else: # Application.alert("Please select an item").
class BurpExtender(IBurpExtender, IBurpExtenderCallbacks, IIntruderPayloadProcessor, ITab, IExtensionStateListener): def registerExtenderCallbacks( self, callbacks): self._helpers = callbacks.getHelpers() callbacks.setExtensionName("JWT FuzzHelper") callbacks.registerIntruderPayloadProcessor(self) callbacks.registerExtensionStateListener(self) self._stdout = PrintWriter(callbacks.getStdout(), True) self._stderr = PrintWriter(callbacks.getStderr(), True) # Holds values passed by user from Configuration panel self._fuzzoptions = { "target" : "Header", "selector" : None, "signature" : False, "algorithm" : "HS256", "key" : "", "key_cmd" : "" } self._isNone = lambda val: isinstance(val, type(None)) # Configuration panel Layout self._configurationPanel = JPanel() gridBagLayout = GridBagLayout() gridBagLayout.columnWidths = [ 0, 0, 0] gridBagLayout.rowHeights = [ 10, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ] gridBagLayout.columnWeights = [ 0.0, 0.0, 0.0 ] gridBagLayout.rowWeights = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0] self._configurationPanel.setLayout(gridBagLayout) # Setup tabs self._tabs = JTabbedPane() self._tabs.addTab('Configuration',self._configurationPanel) #self._tabs.addTab('Help',self._helpPanel) # Target Options targetLabel = JLabel("Target Selection (Required): ") targetLabel.setFont(Font("Tahoma",Font.BOLD, 12)) c = GridBagConstraints() c.gridx = 0 c.gridy = 1 c.insets = Insets(0,10,0,0) c.anchor = GridBagConstraints.LINE_END self._configurationPanel.add(targetLabel,c) options = [ 'Header', 'Payload' ] self._targetComboBox = JComboBox(options) c = GridBagConstraints() c.gridx = 1 c.gridy = 1 c.anchor = GridBagConstraints.LINE_START self._configurationPanel.add(self._targetComboBox,c) # Help Button self._helpButton = JButton("Help", actionPerformed=self.helpMenu) c = GridBagConstraints() c.gridx = 2 c.gridy = 1 c.anchor = GridBagConstraints.FIRST_LINE_START self._configurationPanel.add(self._helpButton,c) # Selector Options self._selectorLabel = JLabel("JSON Selector [Object Identifier-Index Syntax] (Required): ") self._selectorLabel.setFont(Font("Tahoma",Font.BOLD, 12)) c = GridBagConstraints() c.gridx = 0 c.gridy = 2 c.insets = Insets(0,10,0,0) c.anchor = GridBagConstraints.LINE_END self._configurationPanel.add(self._selectorLabel, c) self._selectorTextField = JTextField('',50) c = GridBagConstraints() c.gridx = 1 c.gridy = 2 self._configurationPanel.add(self._selectorTextField, c) # Regex option self._regexLabel = JLabel("Use regex as JSON Selector? (Optional): ") self._regexLabel.setFont(Font("Tahoma",Font.BOLD, 12)) c = GridBagConstraints() c.gridx = 0 c.gridy = 3 c.insets = Insets(0,0,0,0) c.anchor = GridBagConstraints.LINE_END self._configurationPanel.add(self._regexLabel,c) self._regexCheckBox = JCheckBox("", actionPerformed=self.regexSelector) c = GridBagConstraints() c.gridx = 1 c.gridy = 3 c.anchor = GridBagConstraints.FIRST_LINE_START self._configurationPanel.add(self._regexCheckBox,c) # Signature Options generateSignatureLabel = JLabel("Generate signature? (Required): ") generateSignatureLabel.setFont(Font("Tahoma",Font.BOLD, 12)) c = GridBagConstraints() c.gridx = 0 c.gridy = 4 c.insets = Insets(0,10,0,0) c.anchor = GridBagConstraints.LINE_END self._configurationPanel.add(generateSignatureLabel,c) options = ["False", "True"] self._generateSignatureComboBox = JComboBox(options) c = GridBagConstraints() c.gridx = 1 c.gridy = 4 c.anchor = GridBagConstraints.LINE_START self._configurationPanel.add(self._generateSignatureComboBox,c) signatureAlgorithmLabel = JLabel("Signature Algorithm (Optional): ") signatureAlgorithmLabel.setFont(Font("Tahoma",Font.BOLD, 12)) c = GridBagConstraints() c.gridx = 0 c.gridy = 5 c.insets = Insets(0,10,0,0) c.anchor = GridBagConstraints.LINE_END self._configurationPanel.add(signatureAlgorithmLabel,c) options = ["None", "HS256","HS384","HS512","ES256","ES384","ES512","RS256","RS384","RS512","PS256","PS256","PS384","PS512"] self._algorithmSelectionComboBox = JComboBox(options) c = GridBagConstraints() c.gridx = 1 c.gridy = 5 c.anchor = GridBagConstraints.LINE_START self._configurationPanel.add(self._algorithmSelectionComboBox,c) # Signing key options self._signingKeyLabel = JLabel("Signing Key (Optional): ") self._signingKeyLabel.setFont(Font("Tahoma",Font.BOLD, 12)) c = GridBagConstraints() c.gridx = 0 c.gridy = 6 c.insets = Insets(0,10,0,0) c.anchor = GridBagConstraints.LINE_END self._configurationPanel.add(self._signingKeyLabel,c) self.addSigningKeyTextArea() self._fromFileTextField = JTextField('',50) fromFileLabel = JLabel("Signing key from file? (Optional): ") fromFileLabel.setFont(Font("Tahoma",Font.BOLD, 12)) c = GridBagConstraints() c.gridx = 0 c.gridy = 7 c.insets = Insets(0,0,0,0) c.anchor = GridBagConstraints.LINE_END self._configurationPanel.add(fromFileLabel,c) self._fromFileCheckBox = JCheckBox("", actionPerformed=self.fromFile) c = GridBagConstraints() c.gridx = 1 c.gridy = 7 c.anchor = GridBagConstraints.FIRST_LINE_START self._configurationPanel.add(self._fromFileCheckBox,c) self._fromCmdTextField = JTextField('',50) fromCmdLabel = JLabel("Signing key from command? (Optional): ") fromCmdLabel.setFont(Font("Tahoma",Font.BOLD, 12)) c = GridBagConstraints() c.gridx = 0 c.gridy = 8 c.insets = Insets(0,0,0,0) c.anchor = GridBagConstraints.LINE_END self._configurationPanel.add(fromCmdLabel,c) self._fromCmdCheckBox = JCheckBox("", actionPerformed=self.fromCmd) c = GridBagConstraints() c.gridx = 1 c.gridy = 8 c.anchor = GridBagConstraints.FIRST_LINE_START self._configurationPanel.add(self._fromCmdCheckBox,c) self._saveButton = JButton("Save Configuration", actionPerformed=self.saveOptions) self._saveButton.setText("Save Configuration") c = GridBagConstraints() c.gridx = 1 c.gridy = 9 c.anchor = GridBagConstraints.FIRST_LINE_START self._configurationPanel.add(self._saveButton,c) callbacks.customizeUiComponent(self._configurationPanel) callbacks.customizeUiComponent(self._tabs) callbacks.addSuiteTab(self) self._stdout.println("[JWT FuzzHelper] Loaded successfully") return def getProcessorName(self): return "JWT Fuzzer" def extensionUnloaded(self): del self._configurationPanel return # Intruder logic function def processPayload(self, currentPayload, originalPayload, baseValue): dataParameter = self._helpers.bytesToString( self._helpers.urlDecode(baseValue) ) # utf-8 encode header,payload,signature = [unicode(s).encode('utf-8') for s in dataParameter.split(".",3)] decoded_header = self._helpers.bytesToString( self._helpers.base64Decode(header + "=" * (-len(header) % 4)) ) decoded_payload = self._helpers.bytesToString( self._helpers.base64Decode(payload+"=" * (-len(payload) % 4)) ) # Decode header and payload, preserving order if they are JSON objects # Decode header try: header_dict = json.loads(decoded_header, object_pairs_hook=OrderedDict) except ValueError: raise RuntimeException("[JWT FuzzHelper] Error: ValueError. Failed to decode header!") except Exception as e: self._stderr.println("[ERROR] Encountered an unknown error when decoding header:\n{}\nCarrying on...".format(e)) # Decode payload # Payload does not have to be a JSON object. # Ref: https://github.com/auth0/node-jsonwebtoken#usage payload_is_string = False try: payload_dict = json.loads(decoded_payload, object_pairs_hook=OrderedDict) except ValueError: payload_is_string = True payload_dict = decoded_payload except Exception as e: self._stderr.println("[ERROR] Encountered an unknown error when decoding payload:\n{}\nCarrying on...".format(e)) target = header_dict if self._fuzzoptions["target"] == "Header" else payload_dict selector = self._fuzzoptions["selector"] # If using Object Identifier-Index then retrieve the # value specified by the selector, # if this value does not exist, assume the user # wants to add the value that would have been specified # by the selector to the desired JWT segment (this behavior will # be noted in the help docs) intruderPayload = self._helpers.bytesToString(currentPayload) if not self._fuzzoptions["regex"]: if selector != [""]: try: value = self.getValue(target, selector) except Exception: target = self.buildDict(target, selector) if not self._isNone(selector) and selector != [""]: target = self.setValue(target, selector, intruderPayload) # Simple match-replace for regex if self._fuzzoptions["regex"]: target_string = target if payload_is_string else json.dumps(target) target_string = re.sub(selector, intruderPayload, target_string) target = target_string if payload_is_string else json.loads(target_string, object_pairs_hook=OrderedDict) if self._fuzzoptions["target"] == "Payload": payload_dict = target else: header_dict = target algorithm = self._fuzzoptions["algorithm"] if self._fuzzoptions["signature"]: # pyjwt requires lowercase 'none'. If user wants to try # "none", "NonE", "nOnE", etc... they should use .alg # as selector, delete sig from intruder and use those # permutations as their fuzz list (outlined in help docs) # and keep "Generate Signature" as False algorithm = "none" if algorithm.lower() == "none" else algorithm header_dict["alg"] = algorithm header = json.dumps(header_dict, separators=(",",":")) payload = payload_dict if payload_is_string else json.dumps(payload_dict, separators=(",",":")) header = self._helpers.base64Encode(header).strip("=") payload = self._helpers.base64Encode(payload).strip("=") contents = header + "." + payload key = self._fuzzoptions["key"] if len(self._fuzzoptions["key_cmd"]) > 0: # we provide 'contents' value as an only argument to key-generating command # it is expected that the command will print only the signature signature = check_output([self._fuzzoptions["key_cmd"], contents]) modified_jwt = contents + "." + signature elif self._fuzzoptions["signature"]: # pyjwt throws error when using a public key in symmetric alg (for good reason of course), # must do natively to support algorithmic sub attacks if algorithm.startswith("HS"): if algorithm == "HS256": hmac_algorithm = hashlib.sha256 elif algorithm == "HS384": hmac_algorithm = hashlib.sha384 else: hmac_algorithm = hashlib.sha512 signature = self._helpers.base64Encode( hmac.new( key, contents, hmac_algorithm ).digest() ).strip("=") modified_jwt = contents + "." +signature # JWT can't sign non-JSON payloads. WTF. This block is for non-JSON payloads. elif algorithm.startswith("RS") and payload_is_string: if algorithm == "RS256": rsa_algorithm = "SHA-256" elif algorithm == "RS384": rsa_algorithm = "SHA-384" else: rsa_algorithm = "SHA-512" privkey = rsa.PrivateKey.load_pkcs1(key) signature = rsa.sign(contents,privkey,rsa_algorithm) signature = base64.b64encode(signature).encode('utf-8').replace("=", "") modified_jwt = contents + "." + signature else: # Use pyjwt when using asymmetric alg if algorithm == "none": key = "" modified_jwt = jwt.encode(payload_dict,key,algorithm=algorithm,headers=header_dict) else: modified_jwt = contents + "." + signature return self._helpers.stringToBytes(modified_jwt) #----------------------- # getValue: # @return: A value at arbitrary depth in dictionary # @throws: TypeError #----------------------- def getValue(self, dictionary, values): return reduce(dict.__getitem__, values, dictionary) #----------------------- # buildDict: # @note: Will build dictionary of arbitrary depth #----------------------- def buildDict(self, dictionary, keys): if self._isNone(keys): return dictionary root = current = dictionary for key in keys: if key not in current: current[key] = {} current = current[key] return root #---------------------- # setValue: # @note: Will set key of arbitrary depth #----------------------- def setValue(self, dictionary, keys, value): root = current = dictionary for i,key in enumerate(keys): if i == len(keys) - 1: current[key] = value break if key in current: current = current[key] else: # Should never happen current = self.buildDict(current, keys) return root #----------------------- # addSigningKeyTextArea: # @note: Will toggle if fromFile selected. Be DRY. #---------------------- def addSigningKeyTextArea(self): self._signingKeyTextArea = JTextArea() self._signingKeyTextArea.setColumns(50) self._signingKeyTextArea.setRows(10) self._signingKeyScrollPane = JScrollPane(self._signingKeyTextArea) c = GridBagConstraints() c.gridx = 1 c.gridy = 6 c.anchor = GridBagConstraints.LINE_START self._configurationPanel.add(self._signingKeyScrollPane,c) def addSigningKeyFromFileTextField(self): c = GridBagConstraints() c.gridx = 1 c.gridy = 6 self._configurationPanel.add(self._fromFileTextField, c) def addSigningKeyFromCmdTextField(self): c = GridBagConstraints() c.gridx = 1 c.gridy = 6 self._configurationPanel.add(self._fromCmdTextField, c) #----------------------- # End Helpers #----------------------- #----------------------- # Implement ITab #----------------------- def getTabCaption(self): return "JWT FuzzHelper" def getUiComponent(self): return self._tabs #--------------------------- # Save configuration options #--------------------------- def saveOptions(self,event): self._fuzzoptions["target"] = self._targetComboBox.getSelectedItem() self._fuzzoptions["selector"] = self._selectorTextField.getText() self._fuzzoptions["signature"] = True if self._generateSignatureComboBox.getSelectedItem() == "True" else False self._fuzzoptions["algorithm"] = self._algorithmSelectionComboBox.getSelectedItem() self._fuzzoptions["key_cmd"] = "" if self._fromFileCheckBox.isSelected(): filename = self._fromFileTextField.getText() if os.path.isdir(filename): self._stderr.println("{} is a directory".format(filename)) return if os.path.exists(filename): with open(filename, 'rb') as f: self._fuzzoptions["key"] = f.read() elif self._fromCmdCheckBox.isSelected(): self._fuzzoptions["key_cmd"] = self._fromCmdTextField.getText() else: self._fuzzoptions["key"] = unicode(self._signingKeyTextArea.getText()).encode("utf-8") # RSA keys need to end with a line break. Many headaches because of this. if not self._fuzzoptions["key"].endswith("\n") and self._fuzzoptions["algorithm"].startswith("RS"): self._fuzzoptions["key"] += "\n" self._stdout.println("[JWT FuzzHelper] Saved options:\n{}".format(self._fuzzoptions)) # Sanity check selector if it's not a regular expression self._fuzzoptions["regex"] = self._regexCheckBox.isSelected() if not self._regexCheckBox.isSelected(): m = re.search("(\.\w+)+",self._fuzzoptions["selector"]) if self._fuzzoptions["selector"] != "." and (isinstance(m,type(None)) or m.group(0) != self._fuzzoptions["selector"]): self._saveButton.setText("Invalid JSON Selector!") else: self._fuzzoptions["selector"] = self._fuzzoptions["selector"].split(".")[1:] self._saveButton.setText("Saved!") # Sanity check the regular expression else: try: re.compile(self._fuzzoptions["selector"]) self._saveButton.setText("Saved!") except re.error: self._saveButton.setText("Invalid Regex!") return #------------------------- # From file options #------------------------ def fromFile(self,event): if self._fromFileCheckBox.isSelected(): self._signingKeyLabel.setText("Path to Signing Key (Optional): ") self._configurationPanel.remove(self._signingKeyScrollPane) self.addSigningKeyFromFileTextField() else: self._signingKeyLabel.setText("Signing Key (Optional): ") self._configurationPanel.remove(self._fromFileTextField) self.addSigningKeyTextArea() self._configurationPanel.repaint() return def fromCmd(self,event): if self._fromCmdCheckBox.isSelected(): self._signingKeyLabel.setText("Path to Signing Cmd (Optional): ") self._configurationPanel.remove(self._signingKeyScrollPane) self.addSigningKeyFromCmdTextField() else: self._signingKeyLabel.setText("Signing Key (Optional): ") self._configurationPanel.remove(self._fromCmdTextField) self.addSigningKeyTextArea() self._configurationPanel.repaint() return def regexSelector(self,event): if self._regexCheckBox.isSelected(): self._selectorLabel.setText("Selector [Regex] (Required): ") else: self._selectorLabel.setText("JSON Selector [Object Identifier-Index Syntax] (Required): ") self._configurationPanel.repaint() return #------------------------- # Help popup #------------------------- def helpMenu(self,event): self._helpPopup = JFrame('JWT Fuzzer', size=(550, 450) ); self._helpPopup.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE) helpPanel = JPanel() helpPanel.setPreferredSize(Dimension(550, 450)) helpPanel.setBorder(EmptyBorder(10, 10, 10, 10)) helpPanel.setLayout(BoxLayout(helpPanel, BoxLayout.Y_AXIS)) self._helpPopup.setContentPane(helpPanel) helpHeadingText = JLabel("<html><h2>JWT Fuzzer</h2></html>") authorText = JLabel("<html><p>@author: <pinnace></p></html>") aboutText = JLabel("<html><br /> <p>This extension adds an Intruder payload processor for JWTs.</p><br /></html>") repositoryText = JLabel("<html>Documentation and source code:</html>") repositoryLink = JLabel("<html>- <a href=\"https://github.com/pinnace/burp-jwt-fuzzhelper-extension\">https://github.com/pinnace/burp-jwt-fuzzhelper-extension</a></html>") licenseText = JLabel("<html><br/><p>JWT Fuzzer uses a GPL 3 license. This license does not apply to the dependency below:<p></html>") dependencyLink = JLabel("<html>- <a href=\"https://github.com/jpadilla/pyjwt/blob/master/LICENSE\">pyjwt</a></html>") dependencyLink.addMouseListener(ClickListener()) dependencyLink.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)) repositoryLink.addMouseListener(ClickListener()) repositoryLink.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)) helpPanel.add(helpHeadingText) helpPanel.add(authorText) helpPanel.add(aboutText) helpPanel.add(repositoryText) helpPanel.add(repositoryLink) helpPanel.add(licenseText) helpPanel.add(dependencyLink) self._helpPopup.setSize(Dimension(550, 450)) self._helpPopup.pack() self._helpPopup.setLocationRelativeTo(None) self._helpPopup.setVisible(True) return
class NewAtfView(JDialog): ''' Prompt user to choose some options to create a template for a new ATF file. ''' def __init__(self, controller, projects, languages, protocols): self.modalityType = Dialog.ModalityType.APPLICATION_MODAL self.controller = controller self.projects = projects self.languages = languages self.protocols = protocols self.cancelled = False self.springLayout = SpringLayout() self.pane = self.getContentPane() def display(self): ''' Displays window. ''' self.build() self.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE) self.setResizable(False) self.setTitle("New ATF template") self.pack() self.setLocationRelativeTo(None) self.visible = 1 def build(self): ''' Puts all the window components together in the JFrame ''' layout = BoxLayout(self.getContentPane(), BoxLayout.Y_AXIS) self.setLayout(layout) # Create all necessary panels ampersand_panel = self.build_ampersand_row() project_panel = self.build_projects_row() language_panel = self.build_language_row() buttons_panel = self.build_buttons_row() # Add panels to main JFrame self.add(ampersand_panel) self.add(project_panel) self.add(language_panel) self.add(buttons_panel) def build_ampersand_row(self): ''' Builds the &-line row. ''' # Build own panel with SpringLayout. panel = JPanel() layout = SpringLayout() panel.setLayout(layout) # Create necessary components and add them to panel. ampersand_label = JLabel("CDLI's ID: ") self.left_field = JTextField('&') equals_label = JLabel('=') self.right_field = JTextField() tooltip_text = ("<html><body>This is the ID and text's designation " "according to<br/>the CDLI catalog. If your text is " "not yet in the<br/>catalog, please email " "[email protected] to get<br/>an ID and designation.") help_label = self.build_help_label(tooltip_text) panel.add(ampersand_label) panel.add(self.left_field) panel.add(equals_label) panel.add(self.right_field) panel.add(help_label) # Set up constraints to tell panel how to position components. layout.putConstraint(SpringLayout.WEST, ampersand_label, 20, SpringLayout.WEST, panel) layout.putConstraint(SpringLayout.NORTH, ampersand_label, 23, SpringLayout.NORTH, panel) layout.putConstraint(SpringLayout.WEST, self.left_field, 90, SpringLayout.WEST, panel) layout.putConstraint(SpringLayout.NORTH, self.left_field, 20, SpringLayout.NORTH, panel) layout.putConstraint(SpringLayout.WEST, equals_label, 5, SpringLayout.EAST, self.left_field) layout.putConstraint(SpringLayout.NORTH, equals_label, 23, SpringLayout.NORTH, panel) layout.putConstraint(SpringLayout.WEST, self.right_field, 5, SpringLayout.EAST, equals_label) layout.putConstraint(SpringLayout.NORTH, self.right_field, 20, SpringLayout.NORTH, panel) layout.putConstraint(SpringLayout.WEST, help_label, 5, SpringLayout.EAST, self.right_field) layout.putConstraint(SpringLayout.NORTH, help_label, 23, SpringLayout.NORTH, panel) layout.putConstraint(SpringLayout.EAST, panel, 15, SpringLayout.EAST, help_label) layout.putConstraint(SpringLayout.SOUTH, panel, 10, SpringLayout.SOUTH, help_label) # Add this to NewAtf JFrame return panel def build_projects_row(self): ''' Builds the projects row. ''' # Build own panel with SpringLayout. panel = JPanel() layout = SpringLayout() panel.setLayout(layout) # Create necessary components and add them to panel. project_label = JLabel('Project: ') self.right_combo = JComboBox() self.right_combo.setEditable(True) def create_project_list(): ''' Prepares list of projects and subprojects ordered with the default one first. ''' default_project = self.projects['default'][0].split('/')[0] if '/' in self.projects['default']: default_subproject = self.projects['default'].split('/')[1] else: default_subproject = '' projects = [default_project] subprojects = [default_subproject] # User created projects might not be in default dictionary for project in self.projects.keys(): if (project != default_project and project != 'default'): projects.append(project) # Default project might not have subproject if default_project in self.projects.keys(): if default_subproject: for subproject in self.projects[default_project]: if (subproject != default_subproject): subprojects.append(subproject) return projects, subprojects self.left_combo = JComboBox(create_project_list()[0]) # Make left combo keep size no matter how long project names are self.left_combo.setPreferredSize(Dimension(125, 30)) self.left_combo.setMinimumSize(self.left_combo.getPreferredSize()) self.left_combo.setMaximumSize(self.left_combo.getPreferredSize()) self.left_combo.setSize(self.left_combo.getPreferredSize()) self.right_combo = JComboBox(create_project_list()[1]) # Prevent right combo to change sizes dynamically self.right_combo.setPreferredSize(Dimension(100, 30)) self.right_combo.setMinimumSize(self.left_combo.getPreferredSize()) self.right_combo.setMaximumSize(self.left_combo.getPreferredSize()) self.right_combo.setSize(self.left_combo.getPreferredSize()) action_listener = ComboActionListener(self.right_combo, self.projects) self.left_combo.addActionListener(action_listener) self.left_combo.setEditable(True) self.right_combo.setEditable(True) slash_label = JLabel('/') tooltip_text = ("<html><body>Choose project from list or insert a new " "one.<br/>You can leave the right-hand field blank." "</body><html>") help_label = self.build_help_label(tooltip_text) panel.add(project_label) panel.add(self.left_combo) panel.add(slash_label) panel.add(self.right_combo) panel.add(help_label) # Set up constraints to tell panel how to position components. layout.putConstraint(SpringLayout.WEST, project_label, 15, SpringLayout.WEST, panel) layout.putConstraint(SpringLayout.NORTH, project_label, 18, SpringLayout.NORTH, panel) layout.putConstraint(SpringLayout.WEST, self.left_combo, 90, SpringLayout.WEST, panel) layout.putConstraint(SpringLayout.NORTH, self.left_combo, 15, SpringLayout.NORTH, panel) layout.putConstraint(SpringLayout.WEST, slash_label, 5, SpringLayout.EAST, self.left_combo) layout.putConstraint(SpringLayout.NORTH, slash_label, 18, SpringLayout.NORTH, panel) layout.putConstraint(SpringLayout.WEST, self.right_combo, 5, SpringLayout.EAST, slash_label) layout.putConstraint(SpringLayout.NORTH, self.right_combo, 15, SpringLayout.NORTH, panel) layout.putConstraint(SpringLayout.WEST, help_label, 5, SpringLayout.EAST, self.right_combo) layout.putConstraint(SpringLayout.NORTH, help_label, 18, SpringLayout.NORTH, panel) layout.putConstraint(SpringLayout.EAST, panel, 15, SpringLayout.EAST, help_label) layout.putConstraint(SpringLayout.SOUTH, panel, 10, SpringLayout.SOUTH, help_label) # Add this to NewAtf JFrame return panel def build_language_row(self): ''' Builds the language row. ''' # Build own panel with SpringLayout. panel = JPanel() layout = SpringLayout() panel.setLayout(layout) # Get language list from settings.yaml, removing the default one from # the list languages = self.languages.keys() languages.remove('default') # Create necessary components and add them to panel. language_label = JLabel('Language: ') self.language_combo = JComboBox(languages) # Set selected language to default self.language_combo.setSelectedItem(self.languages['default']) tooltip_text = "Choose a language from the dropdown menu." help_label = self.build_help_label(tooltip_text) panel.add(language_label) panel.add(self.language_combo) panel.add(help_label) # Set up constraints to tell panel how to position components. layout.putConstraint(SpringLayout.WEST, language_label, 15, SpringLayout.WEST, panel) layout.putConstraint(SpringLayout.NORTH, language_label, 18, SpringLayout.NORTH, panel) layout.putConstraint(SpringLayout.WEST, self.language_combo, 90, SpringLayout.WEST, panel) layout.putConstraint(SpringLayout.NORTH, self.language_combo, 15, SpringLayout.NORTH, panel) layout.putConstraint(SpringLayout.WEST, help_label, 5, SpringLayout.EAST, self.language_combo) layout.putConstraint(SpringLayout.NORTH, help_label, 18, SpringLayout.NORTH, panel) layout.putConstraint(SpringLayout.EAST, panel, 15, SpringLayout.EAST, help_label) layout.putConstraint(SpringLayout.SOUTH, panel, 10, SpringLayout.SOUTH, help_label) # Add this to NewAtf JFrame return panel def build_buttons_row(self): ''' Add OK/Cancel/Blank buttons. ''' # Build own panel with SpringLayout. panel = JPanel() layout = SpringLayout() panel.setLayout(layout) # Create necessary components and add them to panel. create_button = JButton('Create template', actionPerformed=self.create_template) leave_button = JButton('Leave blank', actionPerformed=self.blank) cancel_button = JButton('Cancel', actionPerformed=self.cancel) panel.add(create_button) panel.add(leave_button) panel.add(cancel_button) # Set up constraints to tell panel how to position components. layout.putConstraint(SpringLayout.WEST, create_button, 15, SpringLayout.WEST, panel) layout.putConstraint(SpringLayout.NORTH, create_button, 15, SpringLayout.NORTH, panel) layout.putConstraint(SpringLayout.WEST, leave_button, 5, SpringLayout.EAST, create_button) layout.putConstraint(SpringLayout.NORTH, leave_button, 15, SpringLayout.NORTH, panel) layout.putConstraint(SpringLayout.WEST, cancel_button, 5, SpringLayout.EAST, leave_button) layout.putConstraint(SpringLayout.NORTH, cancel_button, 15, SpringLayout.NORTH, panel) layout.putConstraint(SpringLayout.EAST, panel, 15, SpringLayout.EAST, cancel_button) layout.putConstraint(SpringLayout.SOUTH, panel, 10, SpringLayout.SOUTH, cancel_button) # Add this to NewAtf JFrame return panel def build_help_label(self, tooltip_text): icon = ImageIcon(find_image_resource('smallhelp')) label = JLabel() label.setIcon(icon) label.setToolTipText(tooltip_text) return label def cancel(self, event): self.cancelled = True self.dispose() def blank(self, event): self.controller.show_template() self.dispose() def create_template(self, event): ''' Put together user selected elements of the template following ATF file format. ''' # &-line # E.g. &X001001 = JCS 48, 089 and_line = "{} = {}".format(self.left_field.getText().encode('utf-8'), self.right_field.getText().encode('utf-8')) # Project line # E.g. #project: cams/gkab # E.g. #project: rimanum project_line = "#project: {}".format( self.left_combo.getSelectedItem().encode('utf-8')) if self.right_combo.getSelectedItem(): project_line = "{}/{}".format( project_line, self.right_combo.getSelectedItem().encode('utf-8')) # Language line # E.g. #atf: lang akk-x-stdbab language = self.language_combo.getSelectedItem() language_code = self.languages[language] # Protocol line/s # E.g. #atf: use unicode protocols = '' for protocol in self.protocols: protocols += '#atf: use {}\n'.format(protocol) # Put together all lines to create the template and show in ATF area self.controller.template = ('{}\n' '{}\n' '#atf: lang {}\n' '{}\n'.format(and_line, project_line, language_code, protocols)) self.controller.show_template() self.dispose()
class NewAccountGUI: def __init__(self, amgui): self.amgui = amgui self.am = amgui.acctmanager self.buildgwinfo() self.autologin = JCheckBox("Automatically Log In") self.acctname = JTextField() self.gwoptions = JPanel(doublebuffered) self.gwoptions.border = TitledBorder("Gateway Options") self.buildgwoptions("Twisted") self.mainframe = JFrame("New Account Window") self.buildpane() def buildgwinfo(self): self.gateways = { "Twisted": { "ident": JTextField(), "passwd": JPasswordField(), "host": JTextField("twistedmatrix.com"), "port": JTextField("8787"), "service": JTextField("twisted.words"), "persp": JTextField(), }, "AIM": { "ident": JTextField(), "passwd": JPasswordField(), "host": JTextField("toc.oscar.aol.com"), "port": JTextField("9898"), }, "IRC": { "ident": JTextField(), "passwd": JPasswordField(), "host": JTextField(), "port": JTextField("6667"), "channels": JTextField(), }, } self.displayorder = { "Twisted": [ ["Identity Name", "ident"], ["Password", "passwd"], ["Host", "host"], ["Port", "port"], ["Service Name", "service"], ["Perspective Name", "persp"], ], "AIM": [["Screen Name", "ident"], ["Password", "passwd"], ["Host", "host"], ["Port", "port"]], "IRC": [ ["Nickname", "ident"], ["Password", "passwd"], ["Host", "host"], ["Port", "port"], ["Channels", "channels"], ], } def buildgwoptions(self, gw): self.gwoptions.removeAll() self.gwoptions.layout = GridLayout(len(self.gateways[gw]), 2) for mapping in self.displayorder[gw]: self.gwoptions.add(JLabel(mapping[0])) self.gwoptions.add(self.gateways[gw][mapping[1]]) def buildpane(self): gw = JPanel(GridLayout(1, 2), doublebuffered) gw.add(JLabel("Gateway")) self.gwlist = JComboBox(self.gateways.keys()) # , actionPerformed=self.changegw) self.gwlist.setSelectedItem("Twisted") gw.add(self.gwlist) stdoptions = JPanel(GridLayout(2, 2), doublebuffered) stdoptions.border = TitledBorder("Standard Options") stdoptions.add(JLabel()) stdoptions.add(self.autologin) stdoptions.add(JLabel("Account Name")) stdoptions.add(self.acctname) buttons = JPanel(FlowLayout(), doublebuffered) buttons.add(JButton("OK", actionPerformed=self.addaccount)) buttons.add(JButton("Cancel", actionPerformed=self.cancel)) mainpane = self.mainframe.getContentPane() mainpane.layout = BoxLayout(mainpane, BoxLayout.Y_AXIS) mainpane.add(gw) mainpane.add(self.gwoptions) mainpane.add(stdoptions) mainpane.add(buttons) def show(self): self.mainframe.setLocation(100, 100) self.mainframe.pack() self.mainframe.show() # actionlisteners def changegw(self, ae): self.buildgwoptions(self.gwlist.getSelectedItem()) self.mainframe.pack() self.mainframe.show() def addaccount(self, ae): gwselection = self.gwlist.getSelectedItem() gw = self.gateways[gwselection] name = gw["ident"].text passwd = gw["passwd"].text host = gw["host"].text port = int(gw["port"].text) autologin = self.autologin.isSelected() acctname = self.acctname.text if gwselection == "Twisted": sname = gw["service"].text perspective = gw["persp"].text self.am.addAccount(PBAccount(acctname, autologin, name, passwd, host, port, [[stype, sname, perspective]])) elif gwselection == "AIM": self.am.addAccount(TOCAccount(acctname, autologin, name, passwd, host, port)) elif gwselection == "IRC": channels = gw["channels"].text self.am.addAccount(IRCAccount(acctname, autologin, name, passwd, host, port, channels)) self.amgui.update() print "Added new account" self.mainframe.dispose() def cancel(self, ae): print "Cancelling new account creation" self.mainframe.dispose()
class BurpExtender(IBurpExtender, ITab, IHttpListener, IMessageEditorController, AbstractTableModel, IContextMenuFactory): def registerExtenderCallbacks(self, callbacks): # keep a reference to our callbacks object self._callbacks = callbacks # obtain an extension helpers object self._helpers = callbacks.getHelpers() # set our extension name callbacks.setExtensionName("Autorize") # create the log and a lock on which to synchronize when adding log entries self._log = ArrayList() self._lock = Lock() self.intercept = 0 self.initInterceptionFilters() self.initEnforcementDetector() self.initExport() self.initConfigurationTab() self.initTabs() self.initCallbacks() print "Thank you for installing Autorize v0.9 extension" print "by Barak Tawily" return def initExport(self): # ## init enforcement detector tab # exportLType = JLabel("File Type:") exportLType.setBounds(10, 10, 100, 30) exportLES = JLabel("Enforcement Statuses:") exportLES.setBounds(10, 50, 160, 30) exportFileTypes = ["HTML"] self.exportType = JComboBox(exportFileTypes) self.exportType.setBounds(100, 10, 200, 30) exportES = [ "All Statuses", "Authorization bypass!", "Authorization enforced??? (please configure enforcement detector)", "Authorization enforced!" ] self.exportES = JComboBox(exportES) self.exportES.setBounds(100, 50, 200, 30) exportLES = JLabel("Statuses:") exportLES.setBounds(10, 50, 100, 30) self.exportButton = JButton("Export", actionPerformed=self.exportToHTML) self.exportButton.setBounds(390, 25, 100, 30) self.exportPnl = JPanel() self.exportPnl.setLayout(None) self.exportPnl.setBounds(0, 0, 1000, 1000) self.exportPnl.add(exportLType) self.exportPnl.add(self.exportType) self.exportPnl.add(exportLES) self.exportPnl.add(self.exportES) self.exportPnl.add(self.exportButton) def initEnforcementDetector(self): # ## init enforcement detector tab # self.EDFP = ArrayList() self.EDCT = ArrayList() EDLType = JLabel("Type:") EDLType.setBounds(10, 10, 140, 30) EDLContent = JLabel("Content:") EDLContent.setBounds(10, 50, 140, 30) EDLabelList = JLabel("Filter List:") EDLabelList.setBounds(10, 165, 140, 30) EDStrings = [ "Finger Print: (enforced message body contains)", "Content-Length: (constant Content-Length number of enforced response)" ] self.EDType = JComboBox(EDStrings) self.EDType.setBounds(80, 10, 430, 30) self.EDText = JTextArea("", 5, 30) self.EDText.setBounds(80, 50, 300, 110) self.EDModel = DefaultListModel() self.EDList = JList(self.EDModel) self.EDList.setBounds(80, 175, 300, 110) self.EDList.setBorder(LineBorder(Color.BLACK)) self.EDAdd = JButton("Add filter", actionPerformed=self.addEDFilter) self.EDAdd.setBounds(390, 85, 120, 30) self.EDDel = JButton("Remove filter", actionPerformed=self.delEDFilter) self.EDDel.setBounds(390, 210, 120, 30) self.EDPnl = JPanel() self.EDPnl.setLayout(None) self.EDPnl.setBounds(0, 0, 1000, 1000) self.EDPnl.add(EDLType) self.EDPnl.add(self.EDType) self.EDPnl.add(EDLContent) self.EDPnl.add(self.EDText) self.EDPnl.add(self.EDAdd) self.EDPnl.add(self.EDDel) self.EDPnl.add(EDLabelList) self.EDPnl.add(self.EDList) def initInterceptionFilters(self): # ## init interception filters tab # IFStrings = [ "URL Contains: ", "Scope items only: (Content is not required)" ] self.IFType = JComboBox(IFStrings) self.IFType.setBounds(80, 10, 430, 30) self.IFModel = DefaultListModel() self.IFList = JList(self.IFModel) self.IFList.setBounds(80, 175, 300, 110) self.IFList.setBorder(LineBorder(Color.BLACK)) self.IFText = JTextArea("", 5, 30) self.IFText.setBounds(80, 50, 300, 110) IFLType = JLabel("Type:") IFLType.setBounds(10, 10, 140, 30) IFLContent = JLabel("Content:") IFLContent.setBounds(10, 50, 140, 30) IFLabelList = JLabel("Filter List:") IFLabelList.setBounds(10, 165, 140, 30) self.IFAdd = JButton("Add filter", actionPerformed=self.addIFFilter) self.IFAdd.setBounds(390, 85, 120, 30) self.IFDel = JButton("Remove filter", actionPerformed=self.delIFFilter) self.IFDel.setBounds(390, 210, 120, 30) self.filtersPnl = JPanel() self.filtersPnl.setLayout(None) self.filtersPnl.setBounds(0, 0, 1000, 1000) self.filtersPnl.add(IFLType) self.filtersPnl.add(self.IFType) self.filtersPnl.add(IFLContent) self.filtersPnl.add(self.IFText) self.filtersPnl.add(self.IFAdd) self.filtersPnl.add(self.IFDel) self.filtersPnl.add(IFLabelList) self.filtersPnl.add(self.IFList) def initConfigurationTab(self): # ## init configuration tab # self.prevent304 = JCheckBox("Prevent 304 Not Modified status code") self.prevent304.setBounds(290, 25, 300, 30) self.ignore304 = JCheckBox("Ignore 304/204 status code responses") self.ignore304.setBounds(290, 5, 300, 30) self.ignore304.setSelected(True) self.autoScroll = JCheckBox("Auto Scroll") self.autoScroll.setBounds(290, 45, 140, 30) startLabel = JLabel("Authorization checks:") startLabel.setBounds(10, 10, 140, 30) self.startButton = JButton("Autorize is off", actionPerformed=self.startOrStop) self.startButton.setBounds(160, 10, 120, 30) self.startButton.setBackground(Color(255, 100, 91, 255)) self.clearButton = JButton("Clear List", actionPerformed=self.clearList) self.clearButton.setBounds(10, 40, 100, 30) self.replaceString = JTextArea("Cookie: Insert=injected; header=here;", 5, 30) self.replaceString.setWrapStyleWord(True) self.replaceString.setLineWrap(True) self.replaceString.setBounds(10, 80, 470, 180) self.filtersTabs = JTabbedPane() self.filtersTabs.addTab("Enforcement Detector", self.EDPnl) self.filtersTabs.addTab("Interception Filters", self.filtersPnl) self.filtersTabs.addTab("Export", self.exportPnl) self.filtersTabs.setBounds(0, 280, 2000, 700) self.pnl = JPanel() self.pnl.setBounds(0, 0, 1000, 1000) self.pnl.setLayout(None) self.pnl.add(self.startButton) self.pnl.add(self.clearButton) self.pnl.add(self.replaceString) self.pnl.add(startLabel) self.pnl.add(self.autoScroll) self.pnl.add(self.ignore304) self.pnl.add(self.prevent304) self.pnl.add(self.filtersTabs) def initTabs(self): # ## init autorize tabs # self.logTable = Table(self) self._splitpane = JSplitPane(JSplitPane.HORIZONTAL_SPLIT) self._splitpane.setResizeWeight(1) self.scrollPane = JScrollPane(self.logTable) self._splitpane.setLeftComponent(self.scrollPane) self.scrollPane.getVerticalScrollBar().addAdjustmentListener( autoScrollListener(self)) copyURLitem = JMenuItem("Copy URL") copyURLitem.addActionListener(copySelectedURL(self)) self.menu = JPopupMenu("Popup") self.menu.add(copyURLitem) self.tabs = JTabbedPane() self._requestViewer = self._callbacks.createMessageEditor(self, False) self._responseViewer = self._callbacks.createMessageEditor(self, False) self._originalrequestViewer = self._callbacks.createMessageEditor( self, False) self._originalresponseViewer = self._callbacks.createMessageEditor( self, False) self.tabs.addTab("Modified Request", self._requestViewer.getComponent()) self.tabs.addTab("Modified Response", self._responseViewer.getComponent()) self.tabs.addTab("Original Request", self._originalrequestViewer.getComponent()) self.tabs.addTab("Original Response", self._originalresponseViewer.getComponent()) self.tabs.addTab("Configuration", self.pnl) self.tabs.setSelectedIndex(4) self._splitpane.setRightComponent(self.tabs) def initCallbacks(self): # ## init callbacks # # customize our UI components self._callbacks.customizeUiComponent(self._splitpane) self._callbacks.customizeUiComponent(self.logTable) self._callbacks.customizeUiComponent(self.scrollPane) self._callbacks.customizeUiComponent(self.tabs) self._callbacks.customizeUiComponent(self.filtersTabs) self._callbacks.registerContextMenuFactory(self) # add the custom tab to Burp's UI self._callbacks.addSuiteTab(self) # ## Events functions # def startOrStop(self, event): if self.startButton.getText() == "Autorize is off": self.startButton.setText("Autorize is on") self.startButton.setBackground(Color.GREEN) self.intercept = 1 self._callbacks.registerHttpListener(self) else: self.startButton.setText("Autorize is off") self.startButton.setBackground(Color(255, 100, 91, 255)) self.intercept = 0 self._callbacks.removeHttpListener(self) def addEDFilter(self, event): typeName = self.EDType.getSelectedItem().split(":")[0] self.EDModel.addElement(typeName + ": " + self.EDText.getText()) def delEDFilter(self, event): index = self.EDList.getSelectedIndex() if not index == -1: self.EDModel.remove(index) def addIFFilter(self, event): typeName = self.IFType.getSelectedItem().split(":")[0] self.IFModel.addElement(typeName + ": " + self.IFText.getText()) def delIFFilter(self, event): index = self.IFList.getSelectedIndex() if not index == -1: self.IFModel.remove(index) def clearList(self, event): self._lock.acquire() self._log = ArrayList() row = self._log.size() self.fireTableRowsInserted(row, row) self._lock.release() def exportToHTML(self, event): parentFrame = JFrame() fileChooser = JFileChooser() fileChooser.setSelectedFile(File("AutorizeReprort.html")) fileChooser.setDialogTitle("Save Autorize Report") userSelection = fileChooser.showSaveDialog(parentFrame) if userSelection == JFileChooser.APPROVE_OPTION: fileToSave = fileChooser.getSelectedFile() enforcementStatusFilter = self.exportES.getSelectedItem() htmlContent = """<html><title>Autorize Report by Barak Tawily</title> <style> .datagrid table { border-collapse: collapse; text-align: left; width: 100%; } .datagrid {font: normal 12px/150% Arial, Helvetica, sans-serif; background: #fff; overflow: hidden; border: 1px solid #006699; -webkit-border-radius: 3px; -moz-border-radius: 3px; border-radius: 3px; } .datagrid table td, .datagrid table th { padding: 3px 10px; } .datagrid table thead th {background:-webkit-gradient( linear, left top, left bottom, color-stop(0.05, #006699), color-stop(1, #00557F) );background:-moz-linear-gradient( center top, #006699 5%, #00557F 100% );filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#006699', endColorstr='#00557F');background-color:#006699; color:#FFFFFF; font-size: 15px; font-weight: bold; border-left: 1px solid #0070A8; } .datagrid table thead th:first-child { border: none; }.datagrid table tbody td { color: #00496B; border-left: 1px solid #E1EEF4;font-size: 12px;font-weight: normal; }.datagrid table tbody .alt td { background: #E1EEF4; color: #00496B; }.datagrid table tbody td:first-child { border-left: none; }.datagrid table tbody tr:last-child td { border-bottom: none; }.datagrid table tfoot td div { border-top: 1px solid #006699;background: #E1EEF4;} .datagrid table tfoot td { padding: 0; font-size: 12px } .datagrid table tfoot td div{ padding: 2px; }.datagrid table tfoot td ul { margin: 0; padding:0; list-style: none; text-align: right; }.datagrid table tfoot li { display: inline; }.datagrid table tfoot li a { text-decoration: none; display: inline-block; padding: 2px 8px; margin: 1px;color: #FFFFFF;border: 1px solid #006699;-webkit-border-radius: 3px; -moz-border-radius: 3px; border-radius: 3px; background:-webkit-gradient( linear, left top, left bottom, color-stop(0.05, #006699), color-stop(1, #00557F) );background:-moz-linear-gradient( center top, #006699 5%, #00557F 100% );filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#006699', endColorstr='#00557F');background-color:#006699; }.datagrid table tfoot ul.active, .datagrid table tfoot ul a:hover { text-decoration: none;border-color: #006699; color: #FFFFFF; background: none; background-color:#00557F;}div.dhtmlx_window_active, div.dhx_modal_cover_dv { position: fixed !important; } table { width: 100%; table-layout: fixed; } td { border: 1px solid #35f; overflow: hidden; text-overflow: ellipsis; } td.a { width: 13%; white-space: nowrap; } td.b { width: 9%; word-wrap: break-word; } </style> <body> <h1>Autorize Report<h1> <div class="datagrid"><table> <thead><tr><th>URL</th><th>Authorization Enforcement Status</th></tr></thead> <tbody>""" for i in range(0, self._log.size()): color = "" if self._log.get( i )._enfocementStatus == "Authorization enforced??? (please configure enforcement detector)": color = "yellow" if self._log.get(i)._enfocementStatus == "Authorization bypass!": color = "red" if self._log.get(i)._enfocementStatus == "Authorization enforced!": color = "LawnGreen" if enforcementStatusFilter == "All Statuses": htmlContent += "<tr bgcolor=\"%s\"><td><a href=\"%s\">%s</a></td><td>%s</td></tr>" % ( color, self._log.get(i)._url, self._log.get(i)._url, self._log.get(i)._enfocementStatus) else: if enforcementStatusFilter == self._log.get( i)._enfocementStatus: htmlContent += "<tr bgcolor=\"%s\"><td><a href=\"%s\">%s</a></td><td>%s</td></tr>" % ( color, self._log.get(i)._url, self._log.get(i)._url, self._log.get(i)._enfocementStatus) htmlContent += "</tbody></table></div></body></html>" f = open(fileToSave.getAbsolutePath(), 'w') f.writelines(htmlContent) f.close() # # implement IContextMenuFactory # def createMenuItems(self, invocation): responses = invocation.getSelectedMessages() if responses > 0: ret = LinkedList() requestMenuItem = JMenuItem("Send request to Autorize") cookieMenuItem = JMenuItem("Send cookie to Autorize") requestMenuItem.addActionListener( handleMenuItems(self, responses[0], "request")) cookieMenuItem.addActionListener( handleMenuItems(self, responses[0], "cookie")) ret.add(requestMenuItem) ret.add(cookieMenuItem) return (ret) return null # # implement ITab # def getTabCaption(self): return "Autorize" def getUiComponent(self): return self._splitpane # # extend AbstractTableModel # def getRowCount(self): try: return self._log.size() except: return 0 def getColumnCount(self): return 2 def getColumnName(self, columnIndex): if columnIndex == 0: return "URL" if columnIndex == 1: return "Authorization Enforcement Status" return "" def getValueAt(self, rowIndex, columnIndex): logEntry = self._log.get(rowIndex) if columnIndex == 0: return logEntry._url.toString() if columnIndex == 1: return logEntry._enfocementStatus return "" # # implement IMessageEditorController # this allows our request/response viewers to obtain details about the messages being displayed # def getHttpService(self): return self._currentlyDisplayedItem.getHttpService() def getRequest(self): return self._currentlyDisplayedItem.getRequest() def getResponse(self): return self._currentlyDisplayedItem.getResponse() # # implement IHttpListener # def processHttpMessage(self, toolFlag, messageIsRequest, messageInfo): if self.intercept == 1: if self.prevent304.isSelected(): if messageIsRequest: requestHeaders = list( self._helpers.analyzeRequest(messageInfo).getHeaders()) newHeaders = list() found = 0 for header in requestHeaders: if not "If-None-Match:" in header and not "If-Modified-Since:" in header: newHeaders.append(header) found = 1 if found == 1: requestInfo = self._helpers.analyzeRequest(messageInfo) bodyBytes = messageInfo.getRequest()[requestInfo. getBodyOffset():] bodyStr = self._helpers.bytesToString(bodyBytes) messageInfo.setRequest( self._helpers.buildHttpMessage( newHeaders, bodyStr)) if not messageIsRequest: if not self.replaceString.getText( ) in self._helpers.analyzeRequest(messageInfo).getHeaders(): if self.ignore304.isSelected(): firstHeader = self._helpers.analyzeResponse( messageInfo.getResponse()).getHeaders()[0] if "304" in firstHeader or "204" in firstHeader: return if self.IFList.getModel().getSize() == 0: self.checkAuthorization( messageInfo, self._helpers.analyzeResponse( messageInfo.getResponse()).getHeaders()) else: urlString = str( self._helpers.analyzeRequest(messageInfo).getUrl()) for i in range(0, self.IFList.getModel().getSize()): if self.IFList.getModel().getElementAt(i).split( ":")[0] == "Scope items only": currentURL = URL(urlString) if self._callbacks.isInScope(currentURL): self.checkAuthorization( messageInfo, self._helpers.analyzeResponse( messageInfo.getResponse()). getHeaders()) if self.IFList.getModel().getElementAt(i).split( ":")[0] == "URL Contains": if self.IFList.getModel().getElementAt( i)[14:] in urlString: self.checkAuthorization( messageInfo, self._helpers.analyzeResponse( messageInfo.getResponse()). getHeaders()) return def makeRequest(self, messageInfo, message): requestURL = self._helpers.analyzeRequest(messageInfo).getUrl() return self._callbacks.makeHttpRequest( self._helpers.buildHttpService( str(requestURL.getHost()), int(requestURL.getPort()), requestURL.getProtocol() == "https"), message) def makeMessage(self, messageInfo, removeOrNot): requestInfo = self._helpers.analyzeRequest(messageInfo) headers = requestInfo.getHeaders() if removeOrNot: headers = list(headers) removeHeaders = ArrayList() removeHeaders.add(self.replaceString.getText() [0:self.replaceString.getText().index(":")]) for header in headers[:]: for removeHeader in removeHeaders: if removeHeader in header: headers.remove(header) headers.append(self.replaceString.getText()) msgBody = messageInfo.getRequest()[requestInfo.getBodyOffset():] return self._helpers.buildHttpMessage(headers, msgBody) def checkAuthorization(self, messageInfo, originalHeaders): message = self.makeMessage(messageInfo, True) requestResponse = self.makeRequest(messageInfo, message) analyzedResponse = self._helpers.analyzeResponse( requestResponse.getResponse()) oldStatusCode = originalHeaders[0] newStatusCode = analyzedResponse.getHeaders()[0] oldContentLen = self.getContentLength(originalHeaders) newContentLen = self.getContentLength(analyzedResponse.getHeaders()) impression = "" EDFilters = self.EDModel.toArray() if oldStatusCode == newStatusCode: if oldContentLen == newContentLen: impression = "Authorization bypass!" else: impression = "Authorization enforced??? (please configure enforcement detector)" for filter in EDFilters: if str(filter).startswith("Content-Length: "): if newContentLen == filter: impression = "Authorization enforced!" if str(filter).startswith("Finger Print: "): if filter[14:] in self._helpers.bytesToString( requestResponse.getResponse() [analyzedResponse.getBodyOffset():]): impression = "Authorization enforced!" else: impression = "Authorization enforced!" self._lock.acquire() row = self._log.size() self._log.add( LogEntry(self._callbacks.saveBuffersToTempFiles(requestResponse), self._helpers.analyzeRequest(requestResponse).getUrl(), messageInfo, impression)) # same requests not include again. self.fireTableRowsInserted(row, row) self._lock.release() def getContentLength(self, analyzedResponseHeaders): for header in analyzedResponseHeaders: if "Content-Length:" in header: return header return "null" def getCookieFromMessage(self, messageInfo): headers = list( self._helpers.analyzeRequest( messageInfo.getRequest()).getHeaders()) for header in headers: if "Cookie:" in header: return header return None
class BurpExtender(IBurpExtender, ITab, IHttpListener, IMessageEditorController, AbstractTableModel, IContextMenuFactory): def registerExtenderCallbacks(self, callbacks): # keep a reference to our callbacks object self._callbacks = callbacks # obtain an extension helpers object self._helpers = callbacks.getHelpers() # set our extension name callbacks.setExtensionName("Autorize") # create the log and a lock on which to synchronize when adding log entries self._log = ArrayList() self._lock = Lock() self._enfocementStatuses = ["Authorization bypass!","Authorization enforced??? (please configure enforcement detector)","Authorization enforced!"] self.intercept = 0 self.initInterceptionFilters() self.initEnforcementDetector() self.initEnforcementDetectorUnauthorized() self.initExport() self.initConfigurationTab() self.initTabs() self.initCallbacks() self.currentRequestNumber = 1 print "Thank you for installing Autorize v0.12 extension" print "Created by Barak Tawily" print "Contributors: Barak Tawily, Federico Dotta" print "\nGithub:\nhttps://github.com/Quitten/Autorize" return def initExport(self): # ## init enforcement detector tab # exportLType = JLabel("File Type:") exportLType.setBounds(10, 10, 100, 30) exportLES = JLabel("Enforcement Statuses:") exportLES.setBounds(10, 50, 160, 30) exportFileTypes = ["HTML","CSV"] self.exportType = JComboBox(exportFileTypes) self.exportType.setBounds(100, 10, 200, 30) exportES = ["All Statuses", self._enfocementStatuses[0], self._enfocementStatuses[1], self._enfocementStatuses[2]] self.exportES = JComboBox(exportES) self.exportES.setBounds(100, 50, 200, 30) exportLES = JLabel("Statuses:") exportLES.setBounds(10, 50, 100, 30) self.exportButton = JButton("Export",actionPerformed=self.export) self.exportButton.setBounds(390, 25, 100, 30) self.exportPnl = JPanel() self.exportPnl.setLayout(None); self.exportPnl.setBounds(0, 0, 1000, 1000); self.exportPnl.add(exportLType) self.exportPnl.add(self.exportType) self.exportPnl.add(exportLES) self.exportPnl.add(self.exportES) self.exportPnl.add(self.exportButton) def initEnforcementDetector(self): # ## init enforcement detector tab # # These two variable appears to be unused... self.EDFP = ArrayList() self.EDCT = ArrayList() EDLType = JLabel("Type:") EDLType.setBounds(10, 10, 140, 30) EDLContent = JLabel("Content:") EDLContent.setBounds(10, 50, 140, 30) EDLabelList = JLabel("Filter List:") EDLabelList.setBounds(10, 165, 140, 30) EDStrings = ["Headers (simple string): (enforced message headers contains)", "Headers (regex): (enforced messege headers contains)", "Body (simple string): (enforced messege body contains)", "Body (regex): (enforced messege body contains)", "Full request (simple string): (enforced messege contains)", "Full request (regex): (enforced messege contains)", "Content-Length: (constant Content-Length number of enforced response)"] self.EDType = JComboBox(EDStrings) self.EDType.setBounds(80, 10, 430, 30) self.EDText = JTextArea("", 5, 30) self.EDText.setBounds(80, 50, 300, 110) self.EDModel = DefaultListModel(); self.EDList = JList(self.EDModel); self.EDList.setBounds(80, 175, 300, 110) self.EDList.setBorder(LineBorder(Color.BLACK)) self.EDAdd = JButton("Add filter",actionPerformed=self.addEDFilter) self.EDAdd.setBounds(390, 85, 120, 30) self.EDDel = JButton("Remove filter",actionPerformed=self.delEDFilter) self.EDDel.setBounds(390, 210, 120, 30) self.EDPnl = JPanel() self.EDPnl.setLayout(None); self.EDPnl.setBounds(0, 0, 1000, 1000); self.EDPnl.add(EDLType) self.EDPnl.add(self.EDType) self.EDPnl.add(EDLContent) self.EDPnl.add(self.EDText) self.EDPnl.add(self.EDAdd) self.EDPnl.add(self.EDDel) self.EDPnl.add(EDLabelList) self.EDPnl.add(self.EDList) def initEnforcementDetectorUnauthorized(self): # ## init enforcement detector tab # EDLType = JLabel("Type:") EDLType.setBounds(10, 10, 140, 30) EDLContent = JLabel("Content:") EDLContent.setBounds(10, 50, 140, 30) EDLabelList = JLabel("Filter List:") EDLabelList.setBounds(10, 165, 140, 30) EDStrings = ["Headers (simple string): (enforced message headers contains)", "Headers (regex): (enforced messege headers contains)", "Body (simple string): (enforced messege body contains)", "Body (regex): (enforced messege body contains)", "Full request (simple string): (enforced messege contains)", "Full request (regex): (enforced messege contains)", "Content-Length: (constant Content-Length number of enforced response)"] self.EDTypeUnauth = JComboBox(EDStrings) self.EDTypeUnauth.setBounds(80, 10, 430, 30) self.EDTextUnauth = JTextArea("", 5, 30) self.EDTextUnauth.setBounds(80, 50, 300, 110) self.EDModelUnauth = DefaultListModel(); self.EDListUnauth = JList(self.EDModelUnauth); self.EDListUnauth.setBounds(80, 175, 300, 110) self.EDListUnauth.setBorder(LineBorder(Color.BLACK)) self.EDAddUnauth = JButton("Add filter",actionPerformed=self.addEDFilterUnauth) self.EDAddUnauth.setBounds(390, 85, 120, 30) self.EDDelUnauth = JButton("Remove filter",actionPerformed=self.delEDFilterUnauth) self.EDDelUnauth.setBounds(390, 210, 120, 30) self.EDPnlUnauth = JPanel() self.EDPnlUnauth.setLayout(None); self.EDPnlUnauth.setBounds(0, 0, 1000, 1000); self.EDPnlUnauth.add(EDLType) self.EDPnlUnauth.add(self.EDTypeUnauth) self.EDPnlUnauth.add(EDLContent) self.EDPnlUnauth.add(self.EDTextUnauth) self.EDPnlUnauth.add(self.EDAddUnauth) self.EDPnlUnauth.add(self.EDDelUnauth) self.EDPnlUnauth.add(EDLabelList) self.EDPnlUnauth.add(self.EDListUnauth) def initInterceptionFilters(self): # ## init interception filters tab # IFStrings = ["Scope items only: (Content is not required)","URL Contains (simple string): ","URL Contains (regex): ","URL Not Contains (simple string): ","URL Not Contains (regex): "] self.IFType = JComboBox(IFStrings) self.IFType.setBounds(80, 10, 430, 30) self.IFModel = DefaultListModel(); self.IFList = JList(self.IFModel); self.IFList.setBounds(80, 175, 300, 110) self.IFList.setBorder(LineBorder(Color.BLACK)) self.IFText = JTextArea("", 5, 30) self.IFText.setBounds(80, 50, 300, 110) IFLType = JLabel("Type:") IFLType.setBounds(10, 10, 140, 30) IFLContent = JLabel("Content:") IFLContent.setBounds(10, 50, 140, 30) IFLabelList = JLabel("Filter List:") IFLabelList.setBounds(10, 165, 140, 30) self.IFAdd = JButton("Add filter",actionPerformed=self.addIFFilter) self.IFAdd.setBounds(390, 85, 120, 30) self.IFDel = JButton("Remove filter",actionPerformed=self.delIFFilter) self.IFDel.setBounds(390, 210, 120, 30) self.filtersPnl = JPanel() self.filtersPnl.setLayout(None); self.filtersPnl.setBounds(0, 0, 1000, 1000); self.filtersPnl.add(IFLType) self.filtersPnl.add(self.IFType) self.filtersPnl.add(IFLContent) self.filtersPnl.add(self.IFText) self.filtersPnl.add(self.IFAdd) self.filtersPnl.add(self.IFDel) self.filtersPnl.add(IFLabelList) self.filtersPnl.add(self.IFList) def initConfigurationTab(self): # ## init configuration tab # self.prevent304 = JCheckBox("Prevent 304 Not Modified status code") self.prevent304.setBounds(290, 25, 300, 30) self.ignore304 = JCheckBox("Ignore 304/204 status code responses") self.ignore304.setBounds(290, 5, 300, 30) self.ignore304.setSelected(True) self.autoScroll = JCheckBox("Auto Scroll") #self.autoScroll.setBounds(290, 45, 140, 30) self.autoScroll.setBounds(160, 40, 140, 30) self.doUnauthorizedRequest = JCheckBox("Check unauthenticated") self.doUnauthorizedRequest.setBounds(290, 45, 300, 30) self.doUnauthorizedRequest.setSelected(True) startLabel = JLabel("Authorization checks:") startLabel.setBounds(10, 10, 140, 30) self.startButton = JButton("Autorize is off",actionPerformed=self.startOrStop) self.startButton.setBounds(160, 10, 120, 30) self.startButton.setBackground(Color(255, 100, 91, 255)) self.clearButton = JButton("Clear List",actionPerformed=self.clearList) self.clearButton.setBounds(10, 40, 100, 30) self.replaceString = JTextArea("Cookie: Insert=injected; header=here;", 5, 30) self.replaceString.setWrapStyleWord(True); self.replaceString.setLineWrap(True) self.replaceString.setBounds(10, 80, 470, 180) self.filtersTabs = JTabbedPane() self.filtersTabs.addTab("Enforcement Detector", self.EDPnl) self.filtersTabs.addTab("Detector Unauthenticated", self.EDPnlUnauth) self.filtersTabs.addTab("Interception Filters", self.filtersPnl) self.filtersTabs.addTab("Export", self.exportPnl) self.filtersTabs.setBounds(0, 280, 2000, 700) self.pnl = JPanel() self.pnl.setBounds(0, 0, 1000, 1000); self.pnl.setLayout(None); self.pnl.add(self.startButton) self.pnl.add(self.clearButton) self.pnl.add(self.replaceString) self.pnl.add(startLabel) self.pnl.add(self.autoScroll) self.pnl.add(self.ignore304) self.pnl.add(self.prevent304) self.pnl.add(self.doUnauthorizedRequest) self.pnl.add(self.filtersTabs) def initTabs(self): # ## init autorize tabs # self.logTable = Table(self) self.logTable.setAutoCreateRowSorter(True) tableWidth = self.logTable.getPreferredSize().width self.logTable.getColumn("ID").setPreferredWidth(Math.round(tableWidth / 50 * 2)) self.logTable.getColumn("URL").setPreferredWidth(Math.round(tableWidth / 50 * 24)) self.logTable.getColumn("Orig. Length").setPreferredWidth(Math.round(tableWidth / 50 * 4)) self.logTable.getColumn("Modif. Length").setPreferredWidth(Math.round(tableWidth / 50 * 4)) self.logTable.getColumn("Unauth. Length").setPreferredWidth(Math.round(tableWidth / 50 * 4)) self.logTable.getColumn("Authorization Enforcement Status").setPreferredWidth(Math.round(tableWidth / 50 * 4)) self.logTable.getColumn("Authorization Unauth. Status").setPreferredWidth(Math.round(tableWidth / 50 * 4)) self._splitpane = JSplitPane(JSplitPane.HORIZONTAL_SPLIT) self._splitpane.setResizeWeight(1) self.scrollPane = JScrollPane(self.logTable) self._splitpane.setLeftComponent(self.scrollPane) self.scrollPane.getVerticalScrollBar().addAdjustmentListener(autoScrollListener(self)) self.menuES0 = JCheckBoxMenuItem(self._enfocementStatuses[0],True) self.menuES1 = JCheckBoxMenuItem(self._enfocementStatuses[1],True) self.menuES2 = JCheckBoxMenuItem(self._enfocementStatuses[2],True) self.menuES0.addItemListener(menuTableFilter(self)) self.menuES1.addItemListener(menuTableFilter(self)) self.menuES2.addItemListener(menuTableFilter(self)) copyURLitem = JMenuItem("Copy URL"); copyURLitem.addActionListener(copySelectedURL(self)) self.menu = JPopupMenu("Popup") self.menu.add(copyURLitem) self.menu.add(self.menuES0) self.menu.add(self.menuES1) self.menu.add(self.menuES2) self.tabs = JTabbedPane() self._requestViewer = self._callbacks.createMessageEditor(self, False) self._responseViewer = self._callbacks.createMessageEditor(self, False) self._originalrequestViewer = self._callbacks.createMessageEditor(self, False) self._originalresponseViewer = self._callbacks.createMessageEditor(self, False) self._unauthorizedrequestViewer = self._callbacks.createMessageEditor(self, False) self._unauthorizedresponseViewer = self._callbacks.createMessageEditor(self, False) self.tabs.addTab("Modified Request", self._requestViewer.getComponent()) self.tabs.addTab("Modified Response", self._responseViewer.getComponent()) self.tabs.addTab("Original Request", self._originalrequestViewer.getComponent()) self.tabs.addTab("Original Response", self._originalresponseViewer.getComponent()) self.tabs.addTab("Unauthenticated Request", self._unauthorizedrequestViewer.getComponent()) self.tabs.addTab("Unauthenticated Response", self._unauthorizedresponseViewer.getComponent()) self.tabs.addTab("Configuration", self.pnl) self.tabs.setSelectedIndex(6) self._splitpane.setRightComponent(self.tabs) def initCallbacks(self): # ## init callbacks # # customize our UI components self._callbacks.customizeUiComponent(self._splitpane) self._callbacks.customizeUiComponent(self.logTable) self._callbacks.customizeUiComponent(self.scrollPane) self._callbacks.customizeUiComponent(self.tabs) self._callbacks.customizeUiComponent(self.filtersTabs) self._callbacks.registerContextMenuFactory(self) # add the custom tab to Burp's UI self._callbacks.addSuiteTab(self) # ## Events functions # def startOrStop(self, event): if self.startButton.getText() == "Autorize is off": self.startButton.setText("Autorize is on") self.startButton.setBackground(Color.GREEN) self.intercept = 1 self._callbacks.registerHttpListener(self) else: self.startButton.setText("Autorize is off") self.startButton.setBackground(Color(255, 100, 91, 255)) self.intercept = 0 self._callbacks.removeHttpListener(self) def addEDFilter(self, event): typeName = self.EDType.getSelectedItem().split(":")[0] self.EDModel.addElement(typeName + ": " + self.EDText.getText()) def delEDFilter(self, event): index = self.EDList.getSelectedIndex(); if not index == -1: self.EDModel.remove(index); def addEDFilterUnauth(self, event): typeName = self.EDTypeUnauth.getSelectedItem().split(":")[0] self.EDModelUnauth.addElement(typeName + ": " + self.EDTextUnauth.getText()) def delEDFilterUnauth(self, event): index = self.EDListUnauth.getSelectedIndex(); if not index == -1: self.EDModelUnauth.remove(index); def addIFFilter(self, event): typeName = self.IFType.getSelectedItem().split(":")[0] self.IFModel.addElement(typeName + ": " + self.IFText.getText()) def delIFFilter(self, event): index = self.IFList.getSelectedIndex(); if not index == -1: self.IFModel.remove(index); def clearList(self, event): self._lock.acquire() oldSize = self._log.size() self._log.clear() self.fireTableRowsDeleted(0, oldSize - 1) self._lock.release() def export(self, event): if self.exportType.getSelectedItem() == "HTML": self.exportToHTML() else: self.exportToCSV() def exportToCSV(self): parentFrame = JFrame() fileChooser = JFileChooser() fileChooser.setSelectedFile(File("AutorizeReprort.csv")); fileChooser.setDialogTitle("Save Autorize Report") userSelection = fileChooser.showSaveDialog(parentFrame) if userSelection == JFileChooser.APPROVE_OPTION: fileToSave = fileChooser.getSelectedFile() enforcementStatusFilter = self.exportES.getSelectedItem() csvContent = "id\tURL\tOriginal length\tModified length\tUnauthorized length\tAuthorization Enforcement Status\tAuthorization Unauthenticated Status\n" for i in range(0,self._log.size()): if enforcementStatusFilter == "All Statuses": csvContent += "%d\t%s\t%d\t%d\t%d\t%s\t%s\n" % (self._log.get(i)._id,self._log.get(i)._url, len(self._log.get(i)._originalrequestResponse.getResponse()) if self._log.get(i)._originalrequestResponse != None else 0, len(self._log.get(i)._requestResponse.getResponse()) if self._log.get(i)._requestResponse != None else 0, len(self._log.get(i)._unauthorizedRequestResponse.getResponse()) if self._log.get(i)._unauthorizedRequestResponse != None else 0, self._log.get(i)._enfocementStatus, self._log.get(i)._enfocementStatusUnauthorized) else: if (enforcementStatusFilter == self._log.get(i)._enfocementStatus) or (enforcementStatusFilter == self._log.get(i)._enfocementStatusUnauthorized): csvContent += "%d\t%s\t%d\t%d\t%d\t%s\t%s\n" % (self._log.get(i)._id,self._log.get(i)._url, len(self._log.get(i)._originalrequestResponse.getResponse()) if self._log.get(i)._originalrequestResponse != None else 0, len(self._log.get(i)._requestResponse.getResponse()) if self._log.get(i)._requestResponse != None else 0, len(self._log.get(i)._unauthorizedRequestResponse.getResponse()) if self._log.get(i)._unauthorizedRequestResponse != None else 0, self._log.get(i)._enfocementStatus, self._log.get(i)._enfocementStatusUnauthorized) f = open(fileToSave.getAbsolutePath(), 'w') f.writelines(csvContent) f.close() def exportToHTML(self): parentFrame = JFrame() fileChooser = JFileChooser() fileChooser.setSelectedFile(File("AutorizeReprort.html")); fileChooser.setDialogTitle("Save Autorize Report") userSelection = fileChooser.showSaveDialog(parentFrame) if userSelection == JFileChooser.APPROVE_OPTION: fileToSave = fileChooser.getSelectedFile() enforcementStatusFilter = self.exportES.getSelectedItem() htmlContent = """<html><title>Autorize Report by Barak Tawily</title> <style> .datagrid table { border-collapse: collapse; text-align: left; width: 100%; } .datagrid {font: normal 12px/150% Arial, Helvetica, sans-serif; background: #fff; overflow: hidden; border: 1px solid #006699; -webkit-border-radius: 3px; -moz-border-radius: 3px; border-radius: 3px; } .datagrid table td, .datagrid table th { padding: 3px 10px; } .datagrid table thead th {background:-webkit-gradient( linear, left top, left bottom, color-stop(0.05, #006699), color-stop(1, #00557F) );background:-moz-linear-gradient( center top, #006699 5%, #00557F 100% );filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#006699', endColorstr='#00557F');background-color:#006699; color:#FFFFFF; font-size: 15px; font-weight: bold; border-left: 1px solid #0070A8; } .datagrid table thead th:first-child { border: none; }.datagrid table tbody td { color: #00496B; border-left: 1px solid #E1EEF4;font-size: 12px;font-weight: normal; }.datagrid table tbody .alt td { background: #E1EEF4; color: #00496B; }.datagrid table tbody td:first-child { border-left: none; }.datagrid table tbody tr:last-child td { border-bottom: none; }.datagrid table tfoot td div { border-top: 1px solid #006699;background: #E1EEF4;} .datagrid table tfoot td { padding: 0; font-size: 12px } .datagrid table tfoot td div{ padding: 2px; }.datagrid table tfoot td ul { margin: 0; padding:0; list-style: none; text-align: right; }.datagrid table tfoot li { display: inline; }.datagrid table tfoot li a { text-decoration: none; display: inline-block; padding: 2px 8px; margin: 1px;color: #FFFFFF;border: 1px solid #006699;-webkit-border-radius: 3px; -moz-border-radius: 3px; border-radius: 3px; background:-webkit-gradient( linear, left top, left bottom, color-stop(0.05, #006699), color-stop(1, #00557F) );background:-moz-linear-gradient( center top, #006699 5%, #00557F 100% );filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#006699', endColorstr='#00557F');background-color:#006699; }.datagrid table tfoot ul.active, .datagrid table tfoot ul a:hover { text-decoration: none;border-color: #006699; color: #FFFFFF; background: none; background-color:#00557F;}div.dhtmlx_window_active, div.dhx_modal_cover_dv { position: fixed !important; } table { width: 100%; table-layout: fixed; } td { border: 1px solid #35f; overflow: hidden; text-overflow: ellipsis; } td.a { width: 13%; white-space: nowrap; } td.b { width: 9%; word-wrap: break-word; } </style> <body> <h1>Autorize Report<h1> <div class="datagrid"><table> <thead><tr><th width=\"3%\">ID</th><th width=\"48%\">URL</th><th width=\"9%\">Original length</th><th width=\"9%\">Modified length</th><th width=\"9%\">Unauthorized length</th><th width=\"11%\">Authorization Enforcement Status</th><th width=\"11%\">Authorization Unauthenticated Status</th></tr></thead> <tbody>""" for i in range(0,self._log.size()): color_modified = "" if self._log.get(i)._enfocementStatus == self._enfocementStatuses[0]: color_modified = "red" if self._log.get(i)._enfocementStatus == self._enfocementStatuses[1]: color_modified = "yellow" if self._log.get(i)._enfocementStatus == self._enfocementStatuses[2]: color_modified = "LawnGreen" color_unauthorized = "" if self._log.get(i)._enfocementStatusUnauthorized == self._enfocementStatuses[0]: color_unauthorized = "red" if self._log.get(i)._enfocementStatusUnauthorized == self._enfocementStatuses[1]: color_unauthorized = "yellow" if self._log.get(i)._enfocementStatusUnauthorized == self._enfocementStatuses[2]: color_unauthorized = "LawnGreen" if enforcementStatusFilter == "All Statuses": htmlContent += "<tr><td>%d</td><td><a href=\"%s\">%s</a></td><td>%d</td><td>%d</td><td>%d</td><td bgcolor=\"%s\">%s</td><td bgcolor=\"%s\">%s</td></tr>" % (self._log.get(i)._id,self._log.get(i)._url,self._log.get(i)._url, len(self._log.get(i)._originalrequestResponse.getResponse()) if self._log.get(i)._originalrequestResponse != None else 0, len(self._log.get(i)._requestResponse.getResponse()) if self._log.get(i)._requestResponse != None else 0, len(self._log.get(i)._unauthorizedRequestResponse.getResponse()) if self._log.get(i)._unauthorizedRequestResponse != None else 0, color_modified, self._log.get(i)._enfocementStatus, color_unauthorized, self._log.get(i)._enfocementStatusUnauthorized) else: if (enforcementStatusFilter == self._log.get(i)._enfocementStatus) or (enforcementStatusFilter == self._log.get(i)._enfocementStatusUnauthorized): htmlContent += "<tr><td>%d</td><td><a href=\"%s\">%s</a></td><td>%d</td><td>%d</td><td>%d</td><td bgcolor=\"%s\">%s</td><td bgcolor=\"%s\">%s</td></tr>" % (self._log.get(i)._id,self._log.get(i)._url,self._log.get(i)._url, len(self._log.get(i)._originalrequestResponse.getResponse()) if self._log.get(i)._originalrequestResponse != None else 0, len(self._log.get(i)._requestResponse.getResponse()) if self._log.get(i)._requestResponse != None else 0, len(self._log.get(i)._unauthorizedRequestResponse.getResponse()) if self._log.get(i)._unauthorizedRequestResponse != None else 0, color_modified, self._log.get(i)._enfocementStatus, color_unauthorized, self._log.get(i)._enfocementStatusUnauthorized) htmlContent += "</tbody></table></div></body></html>" f = open(fileToSave.getAbsolutePath(), 'w') f.writelines(htmlContent) f.close() # # implement IContextMenuFactory # def createMenuItems(self, invocation): responses = invocation.getSelectedMessages(); if responses > 0: ret = LinkedList() requestMenuItem = JMenuItem("Send request to Autorize"); cookieMenuItem = JMenuItem("Send cookie to Autorize"); requestMenuItem.addActionListener(handleMenuItems(self,responses[0], "request")) cookieMenuItem.addActionListener(handleMenuItems(self, responses[0], "cookie")) ret.add(requestMenuItem); ret.add(cookieMenuItem); return(ret); return null; # # implement ITab # def getTabCaption(self): return "Autorize" def getUiComponent(self): return self._splitpane # # extend AbstractTableModel # def getRowCount(self): try: return self._log.size() except: return 0 def getColumnCount(self): return 7 def getColumnName(self, columnIndex): if columnIndex == 0: return "ID" if columnIndex == 1: return "URL" if columnIndex == 2: return "Orig. Length" if columnIndex == 3: return "Modif. Length" if columnIndex == 4: return "Unauth. Length" if columnIndex == 5: return "Authorization Enforcement Status" if columnIndex == 6: return "Authorization Unauth. Status" return "" def getColumnClass(self, columnIndex): if columnIndex == 0: return Integer if columnIndex == 1: return String if columnIndex == 2: return Integer if columnIndex == 3: return Integer if columnIndex == 4: return Integer if columnIndex == 5: return String if columnIndex == 6: return String return String def getValueAt(self, rowIndex, columnIndex): logEntry = self._log.get(rowIndex) if columnIndex == 0: return logEntry._id if columnIndex == 1: return logEntry._url.toString() if columnIndex == 2: return len(logEntry._originalrequestResponse.getResponse()) if columnIndex == 3: return len(logEntry._requestResponse.getResponse()) if columnIndex == 4: if logEntry._unauthorizedRequestResponse != None: return len(logEntry._unauthorizedRequestResponse.getResponse()) else: #return "-" return 0 if columnIndex == 5: return logEntry._enfocementStatus if columnIndex == 6: return logEntry._enfocementStatusUnauthorized return "" # # implement IMessageEditorController # this allows our request/response viewers to obtain details about the messages being displayed # def getHttpService(self): return self._currentlyDisplayedItem.getHttpService() def getRequest(self): return self._currentlyDisplayedItem.getRequest() def getResponse(self): return self._currentlyDisplayedItem.getResponse() # # implement IHttpListener # def processHttpMessage(self, toolFlag, messageIsRequest, messageInfo): #if (self.intercept == 1) and (toolFlag != self._callbacks.TOOL_EXTENDER): if (self.intercept == 1) and (toolFlag == self._callbacks.TOOL_PROXY): if self.prevent304.isSelected(): if messageIsRequest: requestHeaders = list(self._helpers.analyzeRequest(messageInfo).getHeaders()) newHeaders = list() found = 0 for header in requestHeaders: if not "If-None-Match:" in header and not "If-Modified-Since:" in header: newHeaders.append(header) found = 1 if found == 1: requestInfo = self._helpers.analyzeRequest(messageInfo) bodyBytes = messageInfo.getRequest()[requestInfo.getBodyOffset():] bodyStr = self._helpers.bytesToString(bodyBytes) messageInfo.setRequest(self._helpers.buildHttpMessage(newHeaders, bodyStr)) if not messageIsRequest: if not self.replaceString.getText() in self._helpers.analyzeRequest(messageInfo).getHeaders(): if self.ignore304.isSelected(): firstHeader = self._helpers.analyzeResponse(messageInfo.getResponse()).getHeaders()[0] if "304" in firstHeader or "204" in firstHeader: return if self.IFList.getModel().getSize() == 0: self.checkAuthorization(messageInfo,self._helpers.analyzeResponse(messageInfo.getResponse()).getHeaders(),self.doUnauthorizedRequest.isSelected()) else: urlString = str(self._helpers.analyzeRequest(messageInfo).getUrl()) do_the_check = 1 for i in range(0,self.IFList.getModel().getSize()): if self.IFList.getModel().getElementAt(i).split(":")[0] == "Scope items only": currentURL = URL(urlString) if not self._callbacks.isInScope(currentURL): do_the_check = 0 if self.IFList.getModel().getElementAt(i).split(":")[0] == "URL Contains (simple string)": if self.IFList.getModel().getElementAt(i)[30:] not in urlString: do_the_check = 0 if self.IFList.getModel().getElementAt(i).split(":")[0] == "URL Contains (regex)": regex_string = self.IFList.getModel().getElementAt(i)[22:] p = re.compile(regex_string, re.IGNORECASE) if not p.search(urlString): do_the_check = 0 if self.IFList.getModel().getElementAt(i).split(":")[0] == "URL Not Contains (simple string)": if self.IFList.getModel().getElementAt(i)[34:] in urlString: do_the_check = 0 if self.IFList.getModel().getElementAt(i).split(":")[0] == "URL Not Contains (regex)": regex_string = self.IFList.getModel().getElementAt(i)[26:] p = re.compile(regex_string, re.IGNORECASE) if p.search(urlString): do_the_check = 0 if do_the_check: self.checkAuthorization(messageInfo,self._helpers.analyzeResponse(messageInfo.getResponse()).getHeaders(),self.doUnauthorizedRequest.isSelected()) return def sendRequestToAutorizeWork(self,messageInfo): if messageInfo.getResponse() == None: message = self.makeMessage(messageInfo,False,False) requestResponse = self.makeRequest(messageInfo, message) self.checkAuthorization(requestResponse,self._helpers.analyzeResponse(requestResponse.getResponse()).getHeaders(),self.doUnauthorizedRequest.isSelected()) else: self.checkAuthorization(messageInfo,self._helpers.analyzeResponse(messageInfo.getResponse()).getHeaders(),self.doUnauthorizedRequest.isSelected()) def makeRequest(self, messageInfo, message): requestURL = self._helpers.analyzeRequest(messageInfo).getUrl() return self._callbacks.makeHttpRequest(self._helpers.buildHttpService(str(requestURL.getHost()), int(requestURL.getPort()), requestURL.getProtocol() == "https"), message) def makeMessage(self, messageInfo, removeOrNot, authorizeOrNot): requestInfo = self._helpers.analyzeRequest(messageInfo) headers = requestInfo.getHeaders() if removeOrNot: headers = list(headers) removeHeaders = ArrayList() removeHeaders.add(self.replaceString.getText()[0:self.replaceString.getText().index(":")]) for header in headers[:]: for removeHeader in removeHeaders: if removeHeader in header: headers.remove(header) if authorizeOrNot: headers.append(self.replaceString.getText()) msgBody = messageInfo.getRequest()[requestInfo.getBodyOffset():] return self._helpers.buildHttpMessage(headers, msgBody) def checkBypass(self,oldStatusCode,newStatusCode,oldContentLen,newContentLen,filters,requestResponse): analyzedResponse = self._helpers.analyzeResponse(requestResponse.getResponse()) impression = "" if oldStatusCode == newStatusCode: if oldContentLen == newContentLen: impression = self._enfocementStatuses[0] else: auth_enforced = 1 for filter in filters: if str(filter).startswith("Headers (simple string): "): if not(filter[25:] in self._helpers.bytesToString(requestResponse.getResponse()[0:analyzedResponse.getBodyOffset()])): auth_enforced = 0 if str(filter).startswith("Headers (regex): "): regex_string = filter[17:] p = re.compile(regex_string, re.IGNORECASE) if not p.search(self._helpers.bytesToString(requestResponse.getResponse()[0:analyzedResponse.getBodyOffset()])): auth_enforced = 0 if str(filter).startswith("Body (simple string): "): if not(filter[22:] in self._helpers.bytesToString(requestResponse.getResponse()[analyzedResponse.getBodyOffset():])): auth_enforced = 0 if str(filter).startswith("Body (regex): "): regex_string = filter[14:] p = re.compile(regex_string, re.IGNORECASE) if not p.search(self._helpers.bytesToString(requestResponse.getResponse()[analyzedResponse.getBodyOffset():])): auth_enforced = 0 if str(filter).startswith("Full request (simple string): "): if not(filter[30:] in self._helpers.bytesToString(requestResponse.getResponse())): auth_enforced = 0 if str(filter).startswith("Full request (regex): "): regex_string = filter[22:] p = re.compile(regex_string, re.IGNORECASE) if not p.search(self._helpers.bytesToString(requestResponse.getResponse())): auth_enforced = 0 if str(filter).startswith("Content-Length: "): if newContentLen != filter: auth_enforced = 0 if auth_enforced: impression = self._enfocementStatuses[2] else: impression = self._enfocementStatuses[1] else: impression = self._enfocementStatuses[2] return impression def checkAuthorization(self, messageInfo, originalHeaders, checkUnauthorized): message = self.makeMessage(messageInfo,True,True) requestResponse = self.makeRequest(messageInfo, message) analyzedResponse = self._helpers.analyzeResponse(requestResponse.getResponse()) oldStatusCode = originalHeaders[0] newStatusCode = analyzedResponse.getHeaders()[0] oldContentLen = self.getContentLength(originalHeaders) newContentLen = self.getContentLength(analyzedResponse.getHeaders()) # Check unauthorized request if checkUnauthorized: messageUnauthorized = self.makeMessage(messageInfo,True,False) requestResponseUnauthorized = self.makeRequest(messageInfo, messageUnauthorized) analyzedResponseUnauthorized = self._helpers.analyzeResponse(requestResponseUnauthorized.getResponse()) statusCodeUnauthorized = analyzedResponseUnauthorized.getHeaders()[0] contentLenUnauthorized = self.getContentLength(analyzedResponseUnauthorized.getHeaders()) EDFilters = self.EDModel.toArray() impression = self.checkBypass(oldStatusCode,newStatusCode,oldContentLen,newContentLen,EDFilters,requestResponse) if checkUnauthorized: EDFiltersUnauth = self.EDModelUnauth.toArray() impressionUnauthorized = self.checkBypass(oldStatusCode,statusCodeUnauthorized,oldContentLen,contentLenUnauthorized,EDFiltersUnauth,requestResponseUnauthorized) self._lock.acquire() row = self._log.size() if checkUnauthorized: self._log.add(LogEntry(self.currentRequestNumber,self._callbacks.saveBuffersToTempFiles(requestResponse), self._helpers.analyzeRequest(requestResponse).getUrl(),messageInfo,impression,self._callbacks.saveBuffersToTempFiles(requestResponseUnauthorized),impressionUnauthorized)) # same requests not include again. else: self._log.add(LogEntry(self.currentRequestNumber,self._callbacks.saveBuffersToTempFiles(requestResponse), self._helpers.analyzeRequest(requestResponse).getUrl(),messageInfo,impression,None,"Disabled")) # same requests not include again. self.fireTableRowsInserted(row, row) self.currentRequestNumber = self.currentRequestNumber + 1 self._lock.release() def getContentLength(self, analyzedResponseHeaders): for header in analyzedResponseHeaders: if "Content-Length:" in header: return header; return "null" def getCookieFromMessage(self, messageInfo): headers = list(self._helpers.analyzeRequest(messageInfo.getRequest()).getHeaders()) for header in headers: if "Cookie:" in header: return header return None
#controlBox.add(requirementIDField) #masterBox.add(controlBox) # requirement URL #controlBox = Box(BoxLayout.X_AXIS) #controlBox.add(JLabel("Requirement URL: ")) #requirementURLField = JTextField(20) #controlBox.add(requirementURLField) #masterBox.add(controlBox) #requirement_text = Application.askForString("Requirement text:","As a user I...") # display dialog and collect options if 1 == Application.request("New Requirement", masterBox, ("Cancel", "OK")): #create the new requirement node nodeType = nodeTypeComboBox.getSelectedItem() eCls = document.getEntityClassByName(nodeType) if len(document.selection) > 0: selectedNode = document.selection[0] newRequirement = document.addEntityToTarget( eCls, selectedNode)[0] # no need to clearSelection each iteration else: newRequirement = document.addEntityToTarget( eCls, None)[0] # no need to clearSelection each iteration componentName = componentNameField.text newRequirement.title = componentName #newRequirement.annotation = requirementTextField.text editor = newRequirement.annotationEditor #if requirementURLField.text != '': # editor.insert(requirementTextField.text, { Application.LINK: requirementURLField.text } ) #else:
def __init__(self, view): JPanel.__init__(self) self.view = view self.background = Color.white self.config_panel_height = 60 mainPanel = JPanel(background=self.background, layout=BorderLayout()) mainPanel.border = self.RoundedBorder() configPanel = JPanel(background=self.background, visible=False) self.layout = BorderLayout() self.add(mainPanel, BorderLayout.NORTH) self.add(configPanel, BorderLayout.SOUTH) self.config_button = JButton(Icon.arrowdown, rolloverIcon=ShadedIcon.arrowdown, toolTipText='configure', actionPerformed=self.configure, borderPainted=False, focusPainted=False, contentAreaFilled=False) self.add(self.config_button) self.configPanel = configPanel self.slider = JSlider(0, 1, 0, background=self.background) self.slider.snapToTicks = True mainPanel.add(self.slider) self.slider.addChangeListener(self) self.min_time = JLabel(' 0.0000 ', opaque=True, background=self.background) self.max_time = JLabel(' 0.0000 ', opaque=True, background=self.background) self.left_panel = JPanel(background=self.background) self.left_panel.add(JButton(Icon.restart, rolloverIcon=ShadedIcon.restart, toolTipText='restart', actionPerformed=self.start, borderPainted=False, focusPainted=False, contentAreaFilled=False)) self.left_panel.add(self.min_time) self.left_panel.add(JButton(icon=Icon.start, rolloverIcon=ShadedIcon.start, toolTipText='jump to beginning', actionPerformed=lambda x: self.slider.setValue(self.slider.minimum), borderPainted=False, focusPainted=False, contentAreaFilled=False)) self.right_panel = JPanel(background=self.background) self.right_panel.add(JButton(icon=Icon.end, rolloverIcon=ShadedIcon.end, toolTipText='jump to end', actionPerformed=lambda x: self.slider.setValue(self.slider.maximum), borderPainted=False, focusPainted=False, contentAreaFilled=False)) self.right_panel.add(self.max_time) self.playpause_button = JButton(Icon.play, actionPerformed=self.pause, rolloverIcon=ShadedIcon.play, toolTipText='continue', borderPainted=False, focusPainted=False, contentAreaFilled=False) self.right_panel.add(self.playpause_button) mainPanel.add(self.left_panel, BorderLayout.WEST) mainPanel.add(self.right_panel, BorderLayout.EAST) pdf = JPanel(layout=BorderLayout(), opaque=False) pdf.add(JButton(Icon.pdf, rolloverIcon=ShadedIcon.pdf, toolTipText='save pdf', actionPerformed=self.save_pdf, borderPainted=False, focusPainted=False, contentAreaFilled=False)) pdf.add(JLabel('pdf', horizontalAlignment=javax.swing.SwingConstants.CENTER), BorderLayout.NORTH) pdf.maximumSize = pdf.preferredSize configPanel.add(pdf) self.data = JPanel(layout=BorderLayout(), opaque=False) self.data.add(JButton(Icon.data, rolloverIcon=ShadedIcon.data, toolTipText='examine data', actionPerformed=self.show_data, borderPainted=False, focusPainted=False, contentAreaFilled=False)) self.data.add(JLabel('data', horizontalAlignment=javax.swing.SwingConstants.CENTER), BorderLayout.NORTH) self.data.maximumSize = self.data.preferredSize configPanel.add(self.data) mode = JPanel(layout=BorderLayout(), opaque=False) cb = JComboBox(['default', 'rate', 'direct']) if self.view.network.mode in [SimulationMode.DEFAULT, SimulationMode.PRECISE]: cb.setSelectedIndex(0) elif self.view.network.mode in [SimulationMode.RATE]: cb.setSelectedIndex(1) elif self.view.network.mode in [SimulationMode.DIRECT, SimulationMode.APPROXIMATE]: cb.setSelectedIndex(2) cb.addActionListener(self) self.mode_combobox = cb mode.add(cb) mode.add(JLabel('mode'), BorderLayout.NORTH) mode.maximumSize = mode.preferredSize configPanel.add(mode) dt = JPanel(layout=BorderLayout(), opaque=False) cb = JComboBox(['0.001', '0.0005', '0.0002', '0.0001']) cb.setSelectedIndex(0) self.view.dt = float(cb.getSelectedItem()) cb.addActionListener(self) self.dt_combobox = cb dt.add(cb) dt.add(JLabel('time step'), BorderLayout.NORTH) dt.maximumSize = dt.preferredSize configPanel.add(dt) rate = JPanel(layout=BorderLayout(), opaque=False) self.rate_combobox = JComboBox(['fastest', '1x', '0.5x', '0.2x', '0.1x', '0.05x', '0.02x', '0.01x', '0.005x', '0.002x', '0.001x']) self.rate_combobox.setSelectedIndex(4) self.view.set_target_rate(self.rate_combobox.getSelectedItem()) self.rate_combobox.addActionListener(self) rate.add(self.rate_combobox) rate.add(JLabel('speed'), BorderLayout.NORTH) rate.maximumSize = rate.preferredSize configPanel.add(rate) spin1 = JPanel(layout=BorderLayout(), opaque=False) self.record_time_spinner = JSpinner(SpinnerNumberModel((self.view.timelog.tick_limit - 1) * self.view.dt, 0.1, 100, 1), stateChanged=self.tick_limit) spin1.add(self.record_time_spinner) spin1.add(JLabel('recording time'), BorderLayout.NORTH) spin1.maximumSize = spin1.preferredSize configPanel.add(spin1) spin2 = JPanel(layout=BorderLayout(), opaque=False) self.filter_spinner = JSpinner(SpinnerNumberModel(self.view.tau_filter, 0, 0.5, 0.01), stateChanged=self.tau_filter) spin2.add(self.filter_spinner) spin2.add(JLabel('filter'), BorderLayout.NORTH) spin2.maximumSize = spin2.preferredSize configPanel.add(spin2) spin3 = JPanel(layout=BorderLayout(), opaque=False) self.time_shown_spinner = JSpinner(SpinnerNumberModel(self.view.time_shown, 0.01, 50, 0.1), stateChanged=self.time_shown) spin3.add(self.time_shown_spinner) spin3.add(JLabel('time shown'), BorderLayout.NORTH) spin3.maximumSize = spin3.preferredSize configPanel.add(spin3) spin4 = JPanel(layout=BorderLayout(), opaque=False) self.freq_spinner = JSpinner(SpinnerNumberModel(1000.0/self.view.data_update_period, 1, 50, 1), stateChanged=self.update_frequency) spin4.add(self.freq_spinner) spin4.add(JLabel('freq (Hz)'), BorderLayout.NORTH) spin4.maximumSize = spin4.preferredSize configPanel.add(spin4) layout = JPanel(layout=BorderLayout(), opaque=False) layout.add(JButton(icon=Icon.save, rolloverIcon=ShadedIcon.save, actionPerformed=self.save, borderPainted=False, focusPainted=False, contentAreaFilled=False, margin=java.awt.Insets(0, 0, 0, 0), toolTipText='save layout'), BorderLayout.WEST) layout.add(JButton(icon=Icon.restore, rolloverIcon=ShadedIcon.restore, actionPerformed=self.restore, borderPainted=False, focusPainted=False, contentAreaFilled=False, margin=java.awt.Insets(0, 0, 0, 0), toolTipText='restore layout'), BorderLayout.EAST) layout.add(JLabel('layout', horizontalAlignment=javax.swing.SwingConstants.CENTER), BorderLayout.NORTH) layout.maximumSize = layout.preferredSize configPanel.add(layout) configPanel.setPreferredSize(java.awt.Dimension(20, self.config_panel_height)) configPanel.visible = False for c in [dt, rate, spin1, spin2, spin3]: c.border = javax.swing.border.EmptyBorder(0, 10, 0, 10)
class TimeControl(JPanel, ChangeListener, ActionListener): def __init__(self, view): JPanel.__init__(self) self.view = view self.background = Color.white self.config_panel_height = 60 mainPanel = JPanel(background=self.background, layout=BorderLayout()) mainPanel.border = self.RoundedBorder() configPanel = JPanel(background=self.background, visible=False) self.layout = BorderLayout() self.add(mainPanel, BorderLayout.NORTH) self.add(configPanel, BorderLayout.SOUTH) self.config_button = JButton(Icon.arrowdown, rolloverIcon=ShadedIcon.arrowdown, toolTipText='configure', actionPerformed=self.configure, borderPainted=False, focusPainted=False, contentAreaFilled=False) self.add(self.config_button) self.configPanel = configPanel self.slider = JSlider(0, 1, 0, background=self.background) self.slider.snapToTicks = True mainPanel.add(self.slider) self.slider.addChangeListener(self) self.min_time = JLabel(' 0.0000 ', opaque=True, background=self.background) self.max_time = JLabel(' 0.0000 ', opaque=True, background=self.background) self.left_panel = JPanel(background=self.background) self.left_panel.add(JButton(Icon.restart, rolloverIcon=ShadedIcon.restart, toolTipText='restart', actionPerformed=self.start, borderPainted=False, focusPainted=False, contentAreaFilled=False)) self.left_panel.add(self.min_time) self.left_panel.add(JButton(icon=Icon.start, rolloverIcon=ShadedIcon.start, toolTipText='jump to beginning', actionPerformed=lambda x: self.slider.setValue(self.slider.minimum), borderPainted=False, focusPainted=False, contentAreaFilled=False)) self.right_panel = JPanel(background=self.background) self.right_panel.add(JButton(icon=Icon.end, rolloverIcon=ShadedIcon.end, toolTipText='jump to end', actionPerformed=lambda x: self.slider.setValue(self.slider.maximum), borderPainted=False, focusPainted=False, contentAreaFilled=False)) self.right_panel.add(self.max_time) self.playpause_button = JButton(Icon.play, actionPerformed=self.pause, rolloverIcon=ShadedIcon.play, toolTipText='continue', borderPainted=False, focusPainted=False, contentAreaFilled=False) self.right_panel.add(self.playpause_button) mainPanel.add(self.left_panel, BorderLayout.WEST) mainPanel.add(self.right_panel, BorderLayout.EAST) pdf = JPanel(layout=BorderLayout(), opaque=False) pdf.add(JButton(Icon.pdf, rolloverIcon=ShadedIcon.pdf, toolTipText='save pdf', actionPerformed=self.save_pdf, borderPainted=False, focusPainted=False, contentAreaFilled=False)) pdf.add(JLabel('pdf', horizontalAlignment=javax.swing.SwingConstants.CENTER), BorderLayout.NORTH) pdf.maximumSize = pdf.preferredSize configPanel.add(pdf) self.data = JPanel(layout=BorderLayout(), opaque=False) self.data.add(JButton(Icon.data, rolloverIcon=ShadedIcon.data, toolTipText='examine data', actionPerformed=self.show_data, borderPainted=False, focusPainted=False, contentAreaFilled=False)) self.data.add(JLabel('data', horizontalAlignment=javax.swing.SwingConstants.CENTER), BorderLayout.NORTH) self.data.maximumSize = self.data.preferredSize configPanel.add(self.data) mode = JPanel(layout=BorderLayout(), opaque=False) cb = JComboBox(['default', 'rate', 'direct']) if self.view.network.mode in [SimulationMode.DEFAULT, SimulationMode.PRECISE]: cb.setSelectedIndex(0) elif self.view.network.mode in [SimulationMode.RATE]: cb.setSelectedIndex(1) elif self.view.network.mode in [SimulationMode.DIRECT, SimulationMode.APPROXIMATE]: cb.setSelectedIndex(2) cb.addActionListener(self) self.mode_combobox = cb mode.add(cb) mode.add(JLabel('mode'), BorderLayout.NORTH) mode.maximumSize = mode.preferredSize configPanel.add(mode) dt = JPanel(layout=BorderLayout(), opaque=False) cb = JComboBox(['0.001', '0.0005', '0.0002', '0.0001']) cb.setSelectedIndex(0) self.view.dt = float(cb.getSelectedItem()) cb.addActionListener(self) self.dt_combobox = cb dt.add(cb) dt.add(JLabel('time step'), BorderLayout.NORTH) dt.maximumSize = dt.preferredSize configPanel.add(dt) rate = JPanel(layout=BorderLayout(), opaque=False) self.rate_combobox = JComboBox(['fastest', '1x', '0.5x', '0.2x', '0.1x', '0.05x', '0.02x', '0.01x', '0.005x', '0.002x', '0.001x']) self.rate_combobox.setSelectedIndex(4) self.view.set_target_rate(self.rate_combobox.getSelectedItem()) self.rate_combobox.addActionListener(self) rate.add(self.rate_combobox) rate.add(JLabel('speed'), BorderLayout.NORTH) rate.maximumSize = rate.preferredSize configPanel.add(rate) spin1 = JPanel(layout=BorderLayout(), opaque=False) self.record_time_spinner = JSpinner(SpinnerNumberModel((self.view.timelog.tick_limit - 1) * self.view.dt, 0.1, 100, 1), stateChanged=self.tick_limit) spin1.add(self.record_time_spinner) spin1.add(JLabel('recording time'), BorderLayout.NORTH) spin1.maximumSize = spin1.preferredSize configPanel.add(spin1) spin2 = JPanel(layout=BorderLayout(), opaque=False) self.filter_spinner = JSpinner(SpinnerNumberModel(self.view.tau_filter, 0, 0.5, 0.01), stateChanged=self.tau_filter) spin2.add(self.filter_spinner) spin2.add(JLabel('filter'), BorderLayout.NORTH) spin2.maximumSize = spin2.preferredSize configPanel.add(spin2) spin3 = JPanel(layout=BorderLayout(), opaque=False) self.time_shown_spinner = JSpinner(SpinnerNumberModel(self.view.time_shown, 0.01, 50, 0.1), stateChanged=self.time_shown) spin3.add(self.time_shown_spinner) spin3.add(JLabel('time shown'), BorderLayout.NORTH) spin3.maximumSize = spin3.preferredSize configPanel.add(spin3) spin4 = JPanel(layout=BorderLayout(), opaque=False) self.freq_spinner = JSpinner(SpinnerNumberModel(1000.0/self.view.data_update_period, 1, 50, 1), stateChanged=self.update_frequency) spin4.add(self.freq_spinner) spin4.add(JLabel('freq (Hz)'), BorderLayout.NORTH) spin4.maximumSize = spin4.preferredSize configPanel.add(spin4) layout = JPanel(layout=BorderLayout(), opaque=False) layout.add(JButton(icon=Icon.save, rolloverIcon=ShadedIcon.save, actionPerformed=self.save, borderPainted=False, focusPainted=False, contentAreaFilled=False, margin=java.awt.Insets(0, 0, 0, 0), toolTipText='save layout'), BorderLayout.WEST) layout.add(JButton(icon=Icon.restore, rolloverIcon=ShadedIcon.restore, actionPerformed=self.restore, borderPainted=False, focusPainted=False, contentAreaFilled=False, margin=java.awt.Insets(0, 0, 0, 0), toolTipText='restore layout'), BorderLayout.EAST) layout.add(JLabel('layout', horizontalAlignment=javax.swing.SwingConstants.CENTER), BorderLayout.NORTH) layout.maximumSize = layout.preferredSize configPanel.add(layout) configPanel.setPreferredSize(java.awt.Dimension(20, self.config_panel_height)) configPanel.visible = False for c in [dt, rate, spin1, spin2, spin3]: c.border = javax.swing.border.EmptyBorder(0, 10, 0, 10) def show_data(self, event): frame = JFrame('%s Data' % self.view.network.name) frame.visible = True frame.add(timeview.data.DataPanel(self.view)) frame.size = (500, 600) def forward_one_frame(self, event): self.slider.setValue(self.slider.value + 1) def backward_one_frame(self, event): self.slider.setValue(self.slider.value - 1) def set_max_time(self, maximum): self.slider.maximum = maximum self.max_time.text = ' %1.4f ' % (self.view.dt * maximum) def set_min_time(self, minimum): self.slider.minimum = minimum self.min_time.text = ' %1.4f ' % (self.view.dt * minimum) def stateChanged(self, event): self.view.current_tick = self.slider.value self.view.area.repaint() def start(self, event): self.view.restart = True def configure(self, event): view_state = self.view.frame.getExtendedState() if self.configPanel.visible: self.view.frame.setSize(self.view.frame.width, self.view.frame.height - self.config_panel_height) self.configPanel.visible = False self.config_button.icon = Icon.arrowdown self.config_button.rolloverIcon = ShadedIcon.arrowdown self.config_button.toolTipText = 'configure' else: if(view_state & self.view.frame.MAXIMIZED_BOTH == self.view.frame.MAXIMIZED_BOTH): self.view.frame.setSize(self.view.frame.width, self.view.frame.height) else: self.view.frame.setSize(self.view.frame.width, self.view.frame.height + self.config_panel_height) self.configPanel.visible = True self.config_button.icon = Icon.arrowup self.config_button.rolloverIcon = ShadedIcon.arrowup self.config_button.toolTipText = 'hide configuration' self.view.frame.setExtendedState(view_state) self.view.frame.layout.layoutContainer(self.view.frame) self.layout.layoutContainer(self) self.view.frame.layout.layoutContainer(self.view.frame) self.layout.layoutContainer(self) self.view.frame.layout.layoutContainer(self.view.frame) self.view.frame.repaint() def pause(self, event): self.view.paused = not self.view.paused if self.view.paused: self.playpause_button.icon = Icon.play self.playpause_button.rolloverIcon = ShadedIcon.play self.playpause_button.toolTipText = 'continue' else: self.playpause_button.icon = Icon.pause self.playpause_button.rolloverIcon = ShadedIcon.pause self.playpause_button.toolTipText = 'pause' def tau_filter(self, event): self.view.tau_filter = float(event.source.value) self.view.area.repaint() def time_shown(self, event): self.view.time_shown = float(event.source.value) self.view.area.repaint() def actionPerformed(self, event): dt = float(self.dt_combobox.getSelectedItem()) if dt != self.view.dt: self.view.dt = dt self.record_time_spinner.value = (self.view.timelog.tick_limit - 1) * self.view.dt self.dt_combobox.repaint() self.view.restart = True self.view.set_target_rate(self.rate_combobox.getSelectedItem()) if self.mode_combobox is not None: mode = self.mode_combobox.getSelectedItem() if mode == 'default': requested = SimulationMode.DEFAULT elif mode == 'rate': requested = SimulationMode.RATE elif mode == 'direct': requested = SimulationMode.DIRECT if requested != self.view.network.mode: self.view.requested_mode = requested def tick_limit(self, event): self.view.timelog.tick_limit = int(event.source.value / self.view.dt) + 1 def update_frequency(self, event): self.view.data_update_period = 1000.0 / event.source.value def save(self, event): self.view.save() def restore(self, event): self.view.restore() def save_pdf(self, event): from com.itextpdf.text.pdf import PdfWriter from com.itextpdf.text import Document fileChooser = JFileChooser() fileChooser.setSelectedFile(java.io.File('%s.pdf' % self.view.network.name)) if fileChooser.showSaveDialog(self) == JFileChooser.APPROVE_OPTION: f = fileChooser.getSelectedFile() doc = Document() writer = PdfWriter.getInstance(doc, java.io.FileOutputStream(f)) doc.open() cb = writer.getDirectContent() w = self.view.area.size.width h = self.view.area.size.height pw = 550 ph = 800 tp = cb.createTemplate(pw, ph) g2 = tp.createGraphicsShapes(pw, ph) at = java.awt.geom.AffineTransform() s = min(float(pw) / w, float(ph) / h) at.scale(s, s) g2.transform(at) self.view.area.pdftemplate = tp, s self.view.area.paint(g2) self.view.area.pdftemplate = None g2.dispose() cb.addTemplate(tp, 20, 0) doc.close() class RoundedBorder(javax.swing.border.AbstractBorder): def __init__(self): self.color = Color(0.7, 0.7, 0.7) def getBorderInsets(self, component): return java.awt.Insets(5, 5, 5, 5) def paintBorder(self, c, g, x, y, width, height): g.color = self.color g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON) g.drawRoundRect(x, y, width - 1, height - 1, 10, 10)