def handleMouseEvent(self, event): if event.isPopupTrigger(): loadMenu = JMenuItem("Load .proto") loadMenu.addActionListener(self.tab.listener) popup = JPopupMenu() popup.add(loadMenu) if self.tab.descriptors: deserializeAsMenu = JMenu("Deserialize As...") popup.addSeparator() popup.add(deserializeAsMenu) for pb2, descriptors in self.tab.descriptors.iteritems(): subMenu = JMenu(pb2) deserializeAsMenu.add(subMenu) for name, descriptor in descriptors.iteritems(): protoMenu = JMenuItem(name) protoMenu.addActionListener( DeserializeProtoActionListener(self.tab, descriptor)) subMenu.add(protoMenu) popup.show(event.getComponent(), event.getX(), event.getY()) return
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 menu(self): f = JMenu("File") o = JMenuItem("Copy") o.addActionListener(ActionEventListener(self.opencopy)) self.open = o f.add(o) o = JMenuItem("New") o.addActionListener(ActionEventListener(self.new)) self.open = o f.add(o) o = JMenuItem("Open") o.addActionListener(ActionEventListener(self.opendialog)) self.open = o f.add(o) o = JMenuItem("Save") o.addActionListener(ActionEventListener(self.save)) self.open = o f.add(o) o = JMenuItem("Save As") o.addActionListener(ActionEventListener(self.saveas)) self.open = o f.add(o) return f
def createMenuItems(self, invocation): if invocation.getInvocationContext() != invocation.CONTEXT_MESSAGE_EDITOR_REQUEST: return None menuItem = JMenuItem("Evaluate Groovy") menuItem.addActionListener( GroovyActionListener(invocation.getSelectedMessages()[0], invocation.getSelectionBounds())) return [menuItem]
def createMenuItems(self, invocation): def addRequestsToTab(e): for messageInfo in messages: # saveBuffers is required since modifying the original from its source changes the saved objects, its not a copy messageIndex = self._db.createNewMessage(self._callbacks.saveBuffersToTempFiles(messageInfo), self._helpers.analyzeRequest(messageInfo).getUrl()) #self._messageTable.getModel().addRow(row) self._messageTable.redrawTable() ret = [] messages = invocation.getSelectedMessages() # Check if the messages in the target tree have a response valid = True if invocation.getInvocationContext() == invocation.CONTEXT_TARGET_SITE_MAP_TREE: for selected in messages: if not selected.getResponse(): valid = False if valid: menuItem = JMenuItem("Send request(s) to AuthMatrix"); menuItem.addActionListener(addRequestsToTab) ret.append(menuItem) return ret
def createMenuItems(self, invocation): ''' Invoked by Burp when a right-click menu is created; adds Git Bridge's options to the menu. ''' context = invocation.getInvocationContext() tool = invocation.getToolFlag() if tool == self.callbacks.TOOL_REPEATER: if context in [invocation.CONTEXT_MESSAGE_EDITOR_REQUEST, invocation.CONTEXT_MESSAGE_VIEWER_RESPONSE]: item = JMenuItem("Send to Git Bridge") item.addActionListener(self.RepeaterHandler(self.callbacks, invocation, self.log)) items = ArrayList() items.add(item) return items elif tool == self.callbacks.TOOL_SCANNER: if context in [invocation.CONTEXT_SCANNER_RESULTS]: item = JMenuItem("Send to Git Bridge") item.addActionListener(self.ScannerHandler(self.callbacks, invocation, self.log)) items = ArrayList() items.add(item) return items else: # TODO: add support for other tools pass
def actionPerformed(self, event): messages = self.browser.getSelectedMessages() numMessages = messages.size() if numMessages == 0: self.browser.showInformationDialog("No messages selected") return if numMessages > 1: self.browser.showInformationDialog("%d messages selected, choose one" % numMessages) return message = messages.get(0) replyToId = message.getJMSMessageID() replyToQueue0 = message.getJMSReplyTo() if replyToQueue0 != None: replyToQueue0 = replyToQueue0.getQueueName() p = Pattern.compile("[^\\s:/]+://[^\\s:/]*/([^\\s:/?]+)\\??.*") m = p.matcher(replyToQueue0) if m.matches(): replyToQueue0 = m.group(1) else: replyToQueue0 = None dNode = self.browser.getBrowserTree().getFirstSelectedDestinationNode() hNode = self.browser.getBrowserTree().getSelectedHermesNode() if dNode == None or hNode == None: self.browser.showInformationDialog("Unknown destination, select destination queue") return hermes = hNode.getHermes() replyToQueue1 = dNode.getDestinationName() replyToDomain = dNode.getDomain() if replyToQueue0 == None and replyToQueue1 == None: self.browser.showInformationDialog("Unknown destination, select destination queue") return # show menu if replyToQueue0 != None and replyToQueue1 != None and replyToQueue0 != replyToQueue1: menu = JPopupMenu() q0item = JMenuItem(replyToQueue0) q0item.addActionListener(MenuItemHandler(self, hermes, replyToId, replyToQueue0, replyToDomain)) menu.add(q0item) q1item = JMenuItem(replyToQueue1) q1item.addActionListener(MenuItemHandler(self, hermes, replyToId, replyToQueue1, replyToDomain)) menu.add(q1item) menu.show(self.button, 0, self.button.getHeight()) return # show new message dialog else: if replyToQueue0 != None: replyToQueue = replyToQueue0 else: replyToQueue = replyToQueue1 self.replyTo(hermes, replyToId, replyToQueue, replyToDomain)
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;
def add_check_item(self, tool, view, check, viewMenu): checkItem = JMenuItem(check.title) if check.icon is not None: checkItem.setIcon(check.icon) checkItem.addActionListener(QatMenuActionListener(self.app, "check", tool, view, check)) viewMenu.add(checkItem)
def __init__(self, app, menuTitle): JMenu.__init__(self, menuTitle) self.app = app #quat dialog item dialogItem = JCheckBoxMenuItem(self.app.dlg.toggleAction) self.add(dialogItem) self.addSeparator() #tool submenu for tool in self.app.tools: if tool.name == "favourites": self.addSeparator() toolMenu = JMenu(tool.title) toolMenu.setIcon(tool.bigIcon) if tool.uri != "": #Website link iconFile = File.separator.join([self.app.SCRIPTDIR, "images", "icons", "browser.png"]) urlItem = JMenuItem(tool.title) urlItem.setIcon(ImageIcon(iconFile)) urlItem.addActionListener(QatMenuActionListener(self.app, "link", tool)) toolMenu.add(urlItem) toolMenu.addSeparator() #View submenu for view in tool.views: viewMenu = JMenu(view.title) if tool.name == "favourites": self.app.favouritesMenu = viewMenu #Check item for check in view.checks: self.add_check_item(tool, view, check, viewMenu) toolMenu.add(viewMenu) self.add(toolMenu) #Local file with errors localFileItem = JMenuItem(self.app.strings.getString("Open_GPX")) localFileItem.setIcon(ImageProvider.get("open")) localFileItem.addActionListener(QatMenuActionListener(self.app, "local file")) self.add(localFileItem) self.addSeparator() #False positive dialog falsepositiveItem = JMenuItem(self.app.strings.getString("False_positives...")) falsepositiveItem.addActionListener(QatMenuActionListener(self.app, "dialog")) self.add(falsepositiveItem) #Preferences dialog preferencesItem = JMenuItem(self.app.strings.getString("Preferences...")) preferencesItem.addActionListener(QatMenuActionListener(self.app, "dialog")) self.add(preferencesItem) #About dialog item aboutItem = JMenuItem(self.app.strings.getString("About...")) aboutItem.addActionListener(QatMenuActionListener(self.app, "dialog")) self.add(aboutItem)
def generate_menu_items(self): for k in self.items: #print k + '\n' #menuitem = JMenuItem(k, actionPerformed=self.menuItemClicked) menuitem = JMenuItem(k) #menu.append(JMenuItem(self._actionName, None , actionPerformed= lambda x, inv=invocation: self.sqlMapScan(inv))) menuitem.addActionListener(ActionHandler(self._callbacks, k, self._helers)) self.menuitems[menuitem] = k
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;
def createMenuItems(self, invocation): menus = [] messages = invocation.getSelectedMessages() if messages: items = self.interpreter.getLocals().get('items', []) context = 'Assign' if not items else 'Append' menu = JMenuItem("%s to local variable items in Console" % (context, )) menu.addActionListener(AssignLocalsActionListener(self, 'items', messages)) menus.append(menu) return menus
def createMenuItems(self, invocation): if invocation.getInvocationContext() == invocation.CONTEXT_PROXY_HISTORY: mymenu=[] if self.isEnabled: item=JMenuItem("Multi-Browser Highlight (Running): Click to Disable ") else: item=JMenuItem("Multi-Browser Highlight (Stopped): Click to Enable ") item.addActionListener(self) mymenu.append(item) return mymenu else: return None
class SimpleMenuItem: """ An OmniMenuItem implemented on top of a single item entry. """ def __init__(self, text=None): self.menuitem = JMenuItem(text) self.menuitem.setEnabled(False) def add_action_listener(self, action_listener): self.menuitem.addActionListener(action_listener) def set_enabled(self, enabled): self.menuitem.setEnabled(enabled)
def createMenuItems(self, invocation): responses = invocation.getSelectedMessages() if responses > 0: ret = LinkedList() analyzedMenuItem = JMenuItem("Mark as analyzed") notAnalyzedMenuItem = JMenuItem("Mark as NOT analyzed") for response in responses: analyzedMenuItem.addActionListener(handleMenuItems(self,response, "analyzed")) notAnalyzedMenuItem.addActionListener(handleMenuItems(self, response, "not")) ret.add(analyzedMenuItem) ret.add(notAnalyzedMenuItem) return ret
class OmniMenuItem(IContextMenuFactory): """Menu item for burp and inql interface. IT contains same action but it is shown in multiple places""" def __init__(self, helpers=None, callbacks=None, text=''): self._helpers = helpers self._callbacks = callbacks self.menuitem = JMenuItem(text) self._burp_menuitem = JMenuItem("inql: %s" % text) self.set_enabled(False) self._callbacks.registerContextMenuFactory(self) def add_action_listener(self, action_listener): """ add a new action listener to the given UI items. """ self._action_listener = action_listener self.menuitem.addActionListener(action_listener) self._burp_menuitem.addActionListener(action_listener) def set_enabled(self, enabled): """ Enables or disables the menuitme """ self.menuitem.setEnabled(enabled) self._burp_menuitem.setEnabled(enabled) def createMenuItems(self, invocation): """ Overrides IContextMenuFactory callback :param invocation: handles menu selected invocation :return: """ try: r = invocation.getSelectedMessages()[0] info = self._helpers.analyzeRequest(r) url = str(info.getUrl()) body = r.getRequest()[info.getBodyOffset():].tostring() if not is_query(body): return None for h in info.getHeaders(): if h.lower().startswith("host:"): domain = h[5:].strip() self._action_listener.ctx(fname='dummy.query', host=domain, payload=body) mymenu = [] mymenu.append(self._burp_menuitem) except Exception as ex: return None return mymenu
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
class TestAction(ActionListener): def __init__(self, text): self.requests = {} self.menuitem = JMenuItem(text) self.menuitem.addActionListener(self) self.enabled = True self.menuitem.setEnabled(self.enabled) def actionPerformed(self, e): self.enabled = not self.enabled self.menuitem.setEnabled(self.enabled) def ctx(self, host=None, payload=None, fname=None): pass
def set_context_menu(self, component, scanner_issue): self.context_menu = JPopupMenu() repeater = JMenuItem("Send to Repeater") repeater.addActionListener(PopupListener(scanner_issue, self.callbacks)) intruder = JMenuItem("Send to Intruder") intruder.addActionListener(PopupListener(scanner_issue, self.callbacks)) hunt = JMenuItem("Send to HUNT") self.context_menu.add(repeater) self.context_menu.add(intruder) context_menu_listener = ContextMenuListener(component, self.context_menu) component.addMouseListener(context_menu_listener)
def createMenuItems(self, invocation): responses = invocation.getSelectedMessages() if responses > 0: ret = LinkedList() requestMenuItem = JMenuItem("Send request to Autorize") cookieMenuItem = JMenuItem("Send cookie to Autorize") for response in responses: requestMenuItem.addActionListener( HandleMenuItems(self._extender, response, "request")) cookieMenuItem.addActionListener( HandleMenuItems(self._extender, response, "cookie")) ret.add(requestMenuItem) ret.add(cookieMenuItem) return ret return None
def createMenuItems(self, invocation): messages = invocation.getSelectedMessages() def addRequestsToTab(e): for messageInfo in messages: # saveBuffers is required since modifying the original from its source changes the saved objects, its not a copy messageIndex = self._db.createNewMessage(self._callbacks.saveBuffersToTempFiles(messageInfo), self._helpers.analyzeRequest(messageInfo).getUrl()) #self._messageTable.getModel().addRow(row) self._messageTable.redrawTable() ret = [] menuItem = JMenuItem("Send request(s) to AuthMatrix"); menuItem.addActionListener(addRequestsToTab) ret.append(menuItem) return(ret)
class CustomHeaderSetterAction(ActionListener): """ Set Custom Header Action """ def __init__(self, overrideheaders, text="Set Custom Header"): self.requests = {} self.menuitem = JMenuItem(text) self.menuitem.setEnabled(False) self.menuitem.addActionListener(self) self._overrideheaders = overrideheaders self._host = None def actionPerformed(self, e): """ Overrides ActionListener behaviour, when clicked it opens the headers property editor for the given host. :param e: unused :return: """ if self._host: try: self._overrideheaders[self._host] except KeyError: print("No custom header for %s, generating an empty set" % self._host) self._overrideheaders[self._host] = [] PropertyEditor.get_instance( "Set Custom Header for %s" % self._host, columns=["Header", "Value"], data=self._overrideheaders[self._host], empty=["X-New-Header", "X-New-Header-Value"]) def ctx(self, host=None, payload=None, fname=None): """ implements the context setting behaviour :param host: when host is not null set it and enable the menuitem. :param payload: ignored :param fname: ignored :return: """ if host: self.menuitem.setEnabled(True) else: self.menuitem.setEnabled(False) self._host = host
def createMenuItems(self, invocation): messages = invocation.getSelectedMessages() def addRequestsToTab(e): for messageInfo in messages: # saveBuffers is required since modifying the original from its source changes the saved objects, its not a copy messageIndex = self._db.createNewMessage( self._callbacks.saveBuffersToTempFiles(messageInfo), self._helpers.analyzeRequest(messageInfo).getUrl()) #self._messageTable.getModel().addRow(row) self._messageTable.redrawTable() ret = [] menuItem = JMenuItem("Send request(s) to AuthMatrix") menuItem.addActionListener(addRequestsToTab) ret.append(menuItem) return (ret)
class BurpExtender(IBurpExtender, IContextMenuFactory, ActionListener): def __init__(self): self.menuItem = JMenuItem('sqldude') self.menuItem.addActionListener(self) def _build(self): #Grab first selected message, bail if none iRequestInfo = self._helpers.analyzeRequest(self.ctxMenuInvocation.getSelectedMessages()[0]) if iRequestInfo is None: print('Request info object is null, bailing') return #print(len(iRequestInfo.getParameters())) #for i in iRequestInfo.getParameters(): # print(i.getName()) #print('cookies: ' + ''.join(cookies)) #parms = [i for i in iRequestInfo.getParameters() if i.getType() == IParameter.PARAM_BODY] parms = filter(lambda x: x.getType() == IParameter.PARAM_BODY, iRequestInfo.getParameters()) cookies = filter(lambda x: x.getType() == IParameter.PARAM_COOKIE, iRequestInfo.getParameters()) #print('parms ' + ''.join(parms)) payload = 'sqlmap -u \'%s\' --cookies=\'%s\'' % (iRequestInfo.getUrl(), ';'.join([('%s=%s' % (c.getName(),c.getValue())) for c in cookies ]) ) if len(parms) > 0: p = ['%s=%s' % (p.getName(), p.getValue()) for p in parms] payload = '%s --data=\'%s\'' % (payload, '&'.join(p)) #print('Found Cookies:\n\t' + '\n\t'.join([('%s=%s' % (c.getName(), c.getValue())) for c in cookies])) s = StringSelection(payload) Toolkit.getDefaultToolkit().getSystemClipboard().setContents(s,s) #put string on clipboard print(payload) def actionPerformed(self, actionEvent): self._build() def registerExtenderCallbacks(self, callbacks): self._helpers = callbacks.getHelpers() callbacks.setExtensionName('sqldude') callbacks.registerContextMenuFactory(self) self.mCallBacks = callbacks print('sqldude up') return def createMenuItems(self, ctxMenuInvocation): self.ctxMenuInvocation = ctxMenuInvocation return [self.menuItem]
def createMenuItems(self, invocation): ret = [] try: if (invocation.getInvocationContext() == invocation.CONTEXT_TARGET_SITE_MAP_TABLE): menu = JMenuItem("Send to WAFEx") messages = invocation.getSelectedMessages() def listener(e): """ Generates a new WAFEx model. """ #self._generateWAFExModel(messages) self._addToGeneration(messages) menu.addActionListener(listener) ret.append(menu) except Exception as e: print(e) return ret
class CustomContextMenu(IContextMenuFactory, ActionListener): AVAILABLE_TOOLS = ( IBurpExtenderCallbacks.TOOL_PROXY, ) AVAILABLE_CONTEXT = ( IContextMenuInvocation.CONTEXT_MESSAGE_VIEWER_REQUEST, IContextMenuInvocation.CONTEXT_MESSAGE_VIEWER_RESPONSE ) def __init__(self, extender): self._extender = extender def can_create_menu(self): if (self._invocation.getToolFlag() in CustomContextMenu.AVAILABLE_TOOLS): if self._invocation.getInvocationContext() in CustomContextMenu.AVAILABLE_CONTEXT: if len(self._invocation.getSelectionBounds()) == 2: if len(self._invocation.getSelectedMessages()) == 1: return True return False def createMenuItems(self, invocation): self._invocation = invocation if self.can_create_menu(): self._item = JMenuItem("Select text!") self._item.addActionListener(self) return [self._item] return [] def actionPerformed(self, event): if event.getActionCommand() == self._item.getText(): start, end = self._invocation.getSelectionBounds() message = self._invocation.getSelectedMessages()[0] ctx = self._invocation.getInvocationContext() message = message.getRequest() if ctx == IContextMenuInvocation.CONTEXT_MESSAGE_VIEWER_REQUEST else message.getResponse() selected_text = self._extender._helpers.bytesToString(message)[start:end] JOptionPane.showMessageDialog(None, selected_text, "Selected text", JOptionPane.INFORMATION_MESSAGE) self._extender._stdout.println("[+] Selected text:\n%s" % selected_text)
class OmniMenuItem(IContextMenuFactory): def __init__(self, helpers=None, callbacks=None, text=''): self._helpers = helpers self._callbacks = callbacks self.menuitem = JMenuItem(text) self._burp_menuitem = JMenuItem("inql: %s" % text) self.set_enabled(False) self._callbacks.registerContextMenuFactory(self) def add_action_listener(self, action_listener): self._action_listener = action_listener self.menuitem.addActionListener(action_listener) self._burp_menuitem.addActionListener(action_listener) def set_enabled(self, enabled): self.menuitem.setEnabled(enabled) self._burp_menuitem.setEnabled(enabled) def createMenuItems(self, invocation): """ Overrides IContextMenuFactory callback :param invocation: handles menu selected invocation :return: """ try: r = invocation.getSelectedMessages()[0] info = self._helpers.analyzeRequest(r) url = str(info.getUrl()) if not any([x in url for x in URLS]): return None body = r.getRequest()[info.getBodyOffset():].tostring() for h in info.getHeaders(): if h.lower().startswith("host:"): domain = h[5:].strip() self._action_listener.ctx(fname='dummy.query', host=domain, payload=body) mymenu = [] mymenu.append(self._burp_menuitem) except Exception as ex: return None return mymenu
def createMenuItems(self, invocation): # Do not create a menu item unless getting a context menu from the proxy history or scanner results is_intruder_results = invocation.getInvocationContext( ) == invocation.CONTEXT_INTRUDER_ATTACK_RESULTS is_proxy_history = invocation.getInvocationContext( ) == invocation.CONTEXT_PROXY_HISTORY is_scanner_results = invocation.getInvocationContext( ) == invocation.CONTEXT_SCANNER_RESULTS is_target_tree = invocation.getInvocationContext( ) == invocation.CONTEXT_TARGET_SITE_MAP_TREE is_correct_context = is_proxy_history or is_scanner_results or is_target_tree or is_intruder_results if not is_correct_context: return request_response = invocation.getSelectedMessages()[0] functionality = self.view.get_checklist()["Functionality"] # Create the menu item for the Burp context menu bugcatcher_menu = JMenu("Send to HUNT - Methodology") # TODO: Sort the functionality by name and by vuln class for functionality_name in functionality: tests = functionality[functionality_name]["tests"] menu_test = JMenu(functionality_name) # Create a menu item and an action listener per vulnerability # class on each functionality for test_name in tests: item_test = JMenuItem(test_name) menu_action_listener = MenuActionListener( self.view, self.callbacks, request_response, functionality_name, test_name) item_test.addActionListener(menu_action_listener) menu_test.add(item_test) bugcatcher_menu.add(menu_test) burp_menu = [] burp_menu.append(bugcatcher_menu) return burp_menu
def initTabs(self): # ## init autorize tabs # self.logTable = Table(self) self._splitpane = JSplitPane(JSplitPane.HORIZONTAL_SPLIT) self._splitpane.setResizeWeight(1) self.scrollPane = JScrollPane(self.logTable) self._splitpane.setLeftComponent(self.scrollPane) self.scrollPane.getVerticalScrollBar().addAdjustmentListener(autoScrollListener(self)) self.menuES0 = JCheckBoxMenuItem(self._enfocementStatuses[0],True) self.menuES1 = JCheckBoxMenuItem(self._enfocementStatuses[1],True) self.menuES2 = JCheckBoxMenuItem(self._enfocementStatuses[2],True) self.menuES0.addItemListener(menuTableFilter(self)) self.menuES1.addItemListener(menuTableFilter(self)) self.menuES2.addItemListener(menuTableFilter(self)) copyURLitem = JMenuItem("Copy URL"); copyURLitem.addActionListener(copySelectedURL(self)) self.menu = JPopupMenu("Popup") self.menu.add(copyURLitem) self.menu.add(self.menuES0) self.menu.add(self.menuES1) self.menu.add(self.menuES2) self.tabs = JTabbedPane() self._requestViewer = self._callbacks.createMessageEditor(self, False) self._responseViewer = self._callbacks.createMessageEditor(self, False) self._originalrequestViewer = self._callbacks.createMessageEditor(self, False) self._originalresponseViewer = self._callbacks.createMessageEditor(self, False) self.tabs.addTab("Modified Request", self._requestViewer.getComponent()) self.tabs.addTab("Modified Response", self._responseViewer.getComponent()) self.tabs.addTab("Original Request", self._originalrequestViewer.getComponent()) self.tabs.addTab("Original Response", self._originalresponseViewer.getComponent()) self.tabs.addTab("Configuration", self.pnl) self.tabs.setSelectedIndex(4) self._splitpane.setRightComponent(self.tabs)
def createMenuItems(self, invocation): self.invocation = invocation context = invocation.getInvocationContext() if context in [invocation.CONTEXT_TARGET_SITE_MAP_TREE]: sendToGAT = JMenuItem("Enviar Issues para GAT CORE") # sendToGAT.setForeground(Color.ORANGE) FONT = sendToGAT.getFont() sendToGAT.setFont( Font(FONT.getFontName(), Font.BOLD, FONT.getSize())) sendToGAT.addActionListener(self.actionTarget) menuItems = ArrayList() menuItems.add(sendToGAT) return menuItems else: # TODO: add support for other tools pass
def createMenuItems(self, invocation): iContext = invocation.getInvocationContext() self.selectedMessage = invocation.getSelectedMessages()[0] menuItems = [] sendRequestMenu = JMenuItem("Send to Beautifier (request)") sendRequestMenu.addActionListener(self.sendRequestToBeautifier) sendResponseMenu = JMenuItem("Send to Beautifier (response)") sendResponseMenu.addActionListener(self.sendResponseToBeautifier) if iContext == IContextMenuInvocation.CONTEXT_MESSAGE_EDITOR_REQUEST or \ iContext == IContextMenuInvocation.CONTEXT_MESSAGE_VIEWER_REQUEST: menuItems.append(sendRequestMenu) elif iContext == IContextMenuInvocation.CONTEXT_MESSAGE_EDITOR_RESPONSE or \ iContext == IContextMenuInvocation.CONTEXT_MESSAGE_VIEWER_RESPONSE: menuItems.append(sendResponseMenu) elif iContext == IContextMenuInvocation.CONTEXT_PROXY_HISTORY: menuItems.append(sendRequestMenu) menuItems.append(sendResponseMenu) return menuItems
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 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 createMenuItems(self, invocation): self.messages = invocation.getSelectedMessages() menuItem = JMenuItem("Send request(s) to ParamChecker") menuItem.addActionListener(self.handleMessage) return [menuItem]
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]
def createMenuItem(text, command, manager): mi = JMenuItem(text) mi.setActionCommand(command) mi.addActionListener(manager) return mi
def new_item(title, cmd, key, mod=shortcut): item = JMenuItem(title, actionCommand=cmd) item.accelerator = KeyStroke.getKeyStroke(key, mod) item.addActionListener(self) return item
class RepeaterSenderAction(IProxyListener, ActionListener, IContextMenuFactory): def __init__(self, callbacks, helpers, text, overrideheaders): self.requests = {} self._helpers = helpers self._callbacks = callbacks self.menuitem = JMenuItem(text) self._burp_menuitem = JMenuItem("inql: %s" % text) self._callbacks.registerProxyListener(self) self.menuitem.addActionListener(self) self.menuitem.setEnabled(False) self._burp_menuitem.addActionListener(self) self._burp_menuitem.setEnabled(False) self._index = 0 self._host = None self._payload = None self._fname = None for r in self._callbacks.getProxyHistory(): self._process_request(self._helpers.analyzeRequest(r), r.getRequest()) self._callbacks.registerContextMenuFactory(self) self._overrideheaders = overrideheaders def processProxyMessage(self, messageIsRequest, message): """ Implements IProxyListener method :param messageIsRequest: True if BURP Message is a request :param message: message content :return: None """ if messageIsRequest: self._process_request( self._helpers.analyzeRequest(message.getMessageInfo()), message.getMessageInfo().getRequest()) def _process_request(self, reqinfo, reqbody): """ Process request and extract key values :param reqinfo: :param reqbody: :return: """ url = str(reqinfo.getUrl()) if any([url.endswith(x) for x in URLS]): for h in reqinfo.getHeaders(): if h.lower().startswith("host:"): domain = h[5:].strip() method = reqinfo.getMethod() try: self.requests[domain] except KeyError: self.requests[domain] = { 'POST': None, 'PUT': None, 'GET': None } self.requests[domain][method] = (reqinfo, reqbody) def actionPerformed(self, e): """ Overrides ActionListener behaviour. Send current query to repeater. :param e: unused :return: None """ req = self.requests[self._host]['POST'] or self.requests[ self._host]['PUT'] or self.requests[self._host]['GET'] if req: info = req[0] body = req[1] nobody = body[:info.getBodyOffset()].tostring() rstripoffset = info.getBodyOffset() - len(nobody.rstrip()) headers = body[:info.getBodyOffset() - rstripoffset].tostring() try: self._overrideheaders[self._host] except KeyError: self._overrideheaders[self._host] = [] repeater_body = StringUtil.toBytes( string_join( override_headers(headers, self._overrideheaders[self._host]), body[info.getBodyOffset() - rstripoffset:info.getBodyOffset()].tostring(), self._payload)) self._callbacks.sendToRepeater( info.getUrl().getHost(), info.getUrl().getPort(), info.getUrl().getProtocol() == 'https', repeater_body, 'GraphQL #%s' % self._index) self._index += 1 def ctx(self, host=None, payload=None, fname=None): """ When a fname is specified and is a query file or a request is selected in the other tabs, enables the context menu to send to repeater tab :param host: should be not null :param payload: should be not null :param fname: should be not null :return: None """ self._host = host self._payload = payload self._fname = fname if not self._fname.endswith('.query'): self.menuitem.setEnabled(False) self._burp_menuitem.setEnabled(False) return try: self.requests[host] self.menuitem.setEnabled(True) self._burp_menuitem.setEnabled(True) except KeyError: self.menuitem.setEnabled(False) self._burp_menuitem.setEnabled(False) def createMenuItems(self, invocation): """ Overrides IContextMenuFactory callback :param invocation: handles menu selected invocation :return: """ try: r = invocation.getSelectedMessages()[0] info = self._helpers.analyzeRequest(r) url = str(info.getUrl()) if not any([x in url for x in URLS]): return None body = r.getRequest()[info.getBodyOffset():].tostring() for h in info.getHeaders(): if h.lower().startswith("host:"): domain = h[5:].strip() self.ctx(fname='dummy.query', host=domain, payload=body) mymenu = [] mymenu.append(self._burp_menuitem) except Exception as ex: return None return mymenu
def registerExtenderCallbacks(self, callbacks): # keep a reference to our Burp callbacks object self._callbacks = callbacks # obtain an Burp extension helpers object self._helpers = callbacks.getHelpers() # set our extension name callbacks.setExtensionName("AuthMatrix - v0.4") # DB that holds everything users, roles, and messages self._db = MatrixDB() # For saving/loading config self._fc = JFileChooser() # Used by ActionListeners selfExtender = self self._selectedColumn = -1 self._selectedRow = -1 # Table of User entries self._userTable = UserTable(self, model=UserTableModel(self._db)) roleScrollPane = JScrollPane(self._userTable) self._userTable.redrawTable() # Table of Request (AKA Message) entries self._messageTable = MessageTable(self, model=MessageTableModel(self._db)) messageScrollPane = JScrollPane(self._messageTable) self._messageTable.redrawTable() # Semi-Generic Popup stuff def addPopup(component, popup): class genericMouseListener(MouseAdapter): def mousePressed(self, e): if e.isPopupTrigger(): self.showMenu(e) def mouseReleased(self, e): if e.isPopupTrigger(): self.showMenu(e) def showMenu(self, e): if type(component) is JTableHeader: table = component.getTable() column = component.columnAtPoint(e.getPoint()) if type( table ) is MessageTable and column >= selfExtender._db.STATIC_MESSAGE_TABLE_COLUMN_COUNT or type( table ) is UserTable and column >= selfExtender._db.STATIC_USER_TABLE_COLUMN_COUNT: selfExtender._selectedColumn = column else: return else: selfExtender._selectedRow = component.rowAtPoint( e.getPoint()) popup.show(e.getComponent(), e.getX(), e.getY()) component.addMouseListener(genericMouseListener()) class actionRunMessage(ActionListener): def actionPerformed(self, e): if selfExtender._selectedRow >= 0: if selfExtender._selectedRow not in selfExtender._messageTable.getSelectedRows( ): indexes = [ selfExtender._db.getMessageByRow( selfExtender._selectedRow)._index ] else: indexes = [ selfExtender._db.getMessageByRow(rowNum)._index for rowNum in selfExtender._messageTable.getSelectedRows() ] t = Thread(target=selfExtender.runMessagesThread, args=[indexes]) t.start() selfExtender._selectedColumn = -1 # Redrawing the table happens in colorcode within the thread class actionRemoveMessage(ActionListener): def actionPerformed(self, e): if selfExtender._selectedRow >= 0: if selfExtender._selectedRow not in selfExtender._messageTable.getSelectedRows( ): indexes = [ selfExtender._db.getMessageByRow( selfExtender._selectedRow)._index ] else: indexes = [ selfExtender._db.getMessageByRow(rowNum)._index for rowNum in selfExtender._messageTable.getSelectedRows() ] for i in indexes: selfExtender._db.deleteMessage(i) selfExtender._selectedColumn = -1 selfExtender._messageTable.redrawTable() class actionRemoveUser(ActionListener): def actionPerformed(self, e): if selfExtender._selectedRow >= 0: if selfExtender._selectedRow not in selfExtender._userTable.getSelectedRows( ): indexes = [ selfExtender._db.getUserByRow( selfExtender._selectedRow)._index ] else: indexes = [ selfExtender._db.getUserByRow(rowNum)._index for rowNum in selfExtender._userTable.getSelectedRows() ] for i in indexes: selfExtender._db.deleteUser(i) selfExtender._selectedColumn = -1 selfExtender._userTable.redrawTable() # TODO combine these next two classes # TODO Also, clean up the variable names where M and U are in place of MessageTable and UserTable class actionRemoveRoleHeaderFromM(ActionListener): def actionPerformed(self, e): if selfExtender._selectedColumn >= 0: selfExtender._db.deleteRole( selfExtender._db.getRoleByMColumn( selfExtender._selectedColumn)._index) selfExtender._selectedColumn = -1 selfExtender._userTable.redrawTable() selfExtender._messageTable.redrawTable() class actionRemoveRoleHeaderFromU(ActionListener): def actionPerformed(self, e): if selfExtender._selectedColumn >= 0: selfExtender._db.deleteRole( selfExtender._db.getRoleByUColumn( selfExtender._selectedColumn)._index) selfExtender._selectedColumn = -1 selfExtender._userTable.redrawTable() selfExtender._messageTable.redrawTable() # Message Table popups messagePopup = JPopupMenu() addPopup(self._messageTable, messagePopup) messageRun = JMenuItem("Run Request(s)") messageRun.addActionListener(actionRunMessage()) messagePopup.add(messageRun) messageRemove = JMenuItem("Remove Request(s)") messageRemove.addActionListener(actionRemoveMessage()) messagePopup.add(messageRemove) messageHeaderPopup = JPopupMenu() addPopup(self._messageTable.getTableHeader(), messageHeaderPopup) roleRemoveFromM = JMenuItem("Remove Role") roleRemoveFromM.addActionListener(actionRemoveRoleHeaderFromM()) messageHeaderPopup.add(roleRemoveFromM) # User Table popup userPopup = JPopupMenu() addPopup(self._userTable, userPopup) userRemove = JMenuItem("Remove Users(s)") userRemove.addActionListener(actionRemoveUser()) userPopup.add(userRemove) userHeaderPopup = JPopupMenu() addPopup(self._userTable.getTableHeader(), userHeaderPopup) roleRemoveFromU = JMenuItem("Remove Role") roleRemoveFromU.addActionListener(actionRemoveRoleHeaderFromU()) userHeaderPopup.add(roleRemoveFromU) # Top pane topPane = JSplitPane(JSplitPane.VERTICAL_SPLIT, roleScrollPane, messageScrollPane) topPane.setResizeWeight(0.3) # request tabs added to this tab on click in message table self._tabs = JTabbedPane() # Button pannel buttons = JPanel() runButton = JButton("Run", actionPerformed=self.runClick) newUserButton = JButton("New User", actionPerformed=self.getInputUserClick) newRoleButton = JButton("New Role", actionPerformed=self.getInputRoleClick) #debugButton = JButton("Debug", actionPerformed=self.printDB) saveButton = JButton("Save", actionPerformed=self.saveClick) loadButton = JButton("Load", actionPerformed=self.loadClick) clearButton = JButton("Clear", actionPerformed=self.clearClick) buttons.add(runButton) buttons.add(newUserButton) buttons.add(newRoleButton) #buttons.add(debugButton) buttons.add(saveButton) buttons.add(loadButton) buttons.add(clearButton) bottomPane = JSplitPane(JSplitPane.VERTICAL_SPLIT, self._tabs, buttons) bottomPane.setResizeWeight(0.95) # Main Pane self._splitpane = JSplitPane(JSplitPane.VERTICAL_SPLIT, topPane, bottomPane) self._splitpane.setResizeWeight(0.5) # customize our UI components callbacks.customizeUiComponent(self._splitpane) callbacks.customizeUiComponent(topPane) callbacks.customizeUiComponent(bottomPane) callbacks.customizeUiComponent(messageScrollPane) callbacks.customizeUiComponent(roleScrollPane) callbacks.customizeUiComponent(self._messageTable) callbacks.customizeUiComponent(self._userTable) callbacks.customizeUiComponent(self._tabs) callbacks.customizeUiComponent(buttons) # Handles checkbox color coding # Must be bellow the customizeUiComponent calls self._messageTable.setDefaultRenderer(Boolean, SuccessBooleanRenderer(self._db)) # add the custom tab to Burp's UI callbacks.addSuiteTab(self) # register SendTo option callbacks.registerContextMenuFactory(self) return
class BurpExtender(IBurpExtender, ITab, IMessageEditorController, IContextMenuFactory, ActionListener, AbstractTableModel, Runnable): # # Implement IBurpExtender # def registerExtenderCallbacks(self, callbacks): # Initialize the global stdout stream global stdout # Keep a reference to our callbacks object self._callbacks = callbacks # Obtain an extension helpers object self._helpers = callbacks.getHelpers() # set our extension name callbacks.setExtensionName("Burpsuite Yara Scanner") # Create the log and a lock on which to synchronize when adding log entries self._log = ArrayList() self._lock = Lock() # main split pane splitpane = JSplitPane(JSplitPane.VERTICAL_SPLIT) # table of log entries logTable = Table(self) scrollPane = JScrollPane(logTable) splitpane.setLeftComponent(scrollPane) # Options panel optionsPanel = JPanel() optionsPanel.setLayout(GridBagLayout()) constraints = GridBagConstraints() yara_exe_label = JLabel("Yara Executable Location:") constraints.fill = GridBagConstraints.HORIZONTAL constraints.gridx = 0 constraints.gridy = 0 optionsPanel.add(yara_exe_label, constraints) self._yara_exe_txtField = JTextField(25) constraints.fill = GridBagConstraints.HORIZONTAL constraints.gridx = 1 constraints.gridy = 0 optionsPanel.add(self._yara_exe_txtField, constraints) yara_rules_label = JLabel("Yara Rules File:") constraints.fill = GridBagConstraints.HORIZONTAL constraints.gridx = 0 constraints.gridy = 1 optionsPanel.add(yara_rules_label, constraints) self._yara_rules_files = Vector() self._yara_rules_files.add("< None >") self._yara_rules_fileList = JList(self._yara_rules_files) constraints.fill = GridBagConstraints.HORIZONTAL constraints.gridx = 1 constraints.gridy = 1 optionsPanel.add(self._yara_rules_fileList, constraints) self._yara_rules_select_files_button = JButton("Select Files") self._yara_rules_select_files_button.addActionListener(self) constraints.fill = GridBagConstraints.HORIZONTAL constraints.gridx = 1 constraints.gridy = 2 optionsPanel.add(self._yara_rules_select_files_button, constraints) self._yara_clear_button = JButton("Clear Yara Results Table") self._yara_clear_button.addActionListener(self) constraints.fill = GridBagConstraints.HORIZONTAL constraints.gridx = 1 constraints.gridy = 3 optionsPanel.add(self._yara_clear_button, constraints) # Tabs with request/response viewers viewerTabs = JTabbedPane() self._requestViewer = callbacks.createMessageEditor(self, False) self._responseViewer = callbacks.createMessageEditor(self, False) viewerTabs.addTab("Request", self._requestViewer.getComponent()) viewerTabs.addTab("Response", self._responseViewer.getComponent()) splitpane.setRightComponent(viewerTabs) # Tabs for the Yara output and the Options self._mainTabs = JTabbedPane() self._mainTabs.addTab("Yara Output", splitpane) self._mainTabs.addTab("Options", optionsPanel) # customize our UI components callbacks.customizeUiComponent(splitpane) callbacks.customizeUiComponent(logTable) callbacks.customizeUiComponent(scrollPane) callbacks.customizeUiComponent(viewerTabs) callbacks.customizeUiComponent(self._mainTabs) # add the custom tab to Burp's UI callbacks.addSuiteTab(self) # add ourselves as a context menu factory callbacks.registerContextMenuFactory(self) # Custom Menu Item self.menuItem = JMenuItem("Scan with Yara") self.menuItem.addActionListener(self) # obtain our output stream stdout = PrintWriter(callbacks.getStdout(), True) # Print a startup notification stdout.println("Burpsuite Yara scanner initialized.") # # Implement ITab # def getTabCaption(self): return "Yara" def getUiComponent(self): return self._mainTabs # # Implement IContextMenuFactory # def createMenuItems(self, invocation): if invocation.getInvocationContext() == invocation.CONTEXT_TARGET_SITE_MAP_TREE: self.requestResponses = invocation.getSelectedMessages() return [self.menuItem] else: self.requestResponses = None return None # # Implement Action # def actionPerformed(self, actionEvent): global yara_rules global yara_path if actionEvent.getSource() is self.menuItem: yara_path = self._yara_exe_txtField.getText() yara_rules = self._yara_rules_files t = Thread(self) t.start() elif actionEvent.getSource() is self._yara_clear_button: # Delete the LogEntry objects from the log row = self._log.size() self._lock.acquire() self._log.clear() # Update the Table self.fireTableRowsDeleted(0, row) # Clear data regarding any selected LogEntry objects from the request / response viewers self._requestViewer.setMessage([], True) self._responseViewer.setMessage([], False) self._currentlyDisplayedItem = None self._lock.release() elif actionEvent.getSource() is self._yara_rules_select_files_button: fileChooser = JFileChooser() yarFilter = FileNameExtensionFilter("Yara Rules", ["yar"]) fileChooser.addChoosableFileFilter(yarFilter) fileChooser.setFileFilter(yarFilter) fileChooser.setMultiSelectionEnabled(True) fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY) ret = fileChooser.showOpenDialog(None) if ret == JFileChooser.APPROVE_OPTION: self._yara_rules_files.clear() for file in fileChooser.getSelectedFiles(): self._yara_rules_files.add(file.getPath()) self._yara_rules_fileList.setListData(self._yara_rules_files) else: stdout.println("Unknown Event Received.") # # Implement Runnable # def run(self): self.yaraScan() # # Extend AbstractTableModel # def getRowCount(self): try: return self._log.size() except: return 0 def getColumnCount(self): return 2 def getColumnName(self, columnIndex): if columnIndex == 0: return "Rule Name" if columnIndex == 1: return "URL" return "" def getValueAt(self, rowIndex, columnIndex): logEntry = self._log.get(rowIndex) if columnIndex == 0: return logEntry._ruleName if columnIndex == 1: return logEntry._url.toString() return "" # # Implement IMessageEditorController # this allows our request/response viewers to obtain details about the messages being displayed # def getHttpService(self): return self._currentlyDisplayedItem.getHttpService() def getRequest(self): return self._currentlyDisplayedItem.getRequest() def getResponse(self): return self._currentlyDisplayedItem.getResponse() # # Implement the Yara scanning logic # def yaraScan(self): # If stdout has not yet been initialized, punt. if stdout is None: return # If the location of the yara executable and rules files are NULL, punt. if yara_rules is None or yara_path is None or yara_rules.size() == 0 or yara_rules.contains("< None >") or len(yara_path) == 0: JOptionPane.showMessageDialog(None, "Error: Please specify the path to the yara executable and rules file in " "the options tab.") return # If iRequestResponses is None, punt. if self.requestResponses is None: JOptionPane.showMessageDialog(None, "Error: No Request/Responses were selected.") return else: stdout.println("Processing %d item(s)." % len(self.requestResponses)) # Get the OS temp folder os_name = System.getProperty("os.name").lower() temp_folder = None if "linux" in os_name: temp_folder = "/tmp" elif "windows" in os_name: temp_folder = os.environ.get("TEMP") if temp_folder is None: temp_folder = os.environ.get("TMP") if temp_folder is None: stdout.println("Error: Could not determine TEMP folder location.") return # Keep track of the number of matches. matchCount = 0 # Process the site map selected messages for idx, iRequestResponse in enumerate(self.requestResponses): # Process the request request = iRequestResponse.getRequest() if request is not None: if len(request) > 0: try: # Yara does not support scanning from stdin so we will need to create a temp file and scan it req_filename = os.path.join(temp_folder, "req_" + str(idx) + ".tmp") req_file = open(req_filename, "wb") req_file.write(request) req_file.close() for rules in yara_rules: yara_req_output = subprocess.check_output([yara_path, rules, req_filename]) if yara_req_output is not None and len(yara_req_output) > 0: ruleName = (yara_req_output.split())[0] self._lock.acquire() row = self._log.size() # TODO: Don't add duplicate items to the table self._log.add(LogEntry(ruleName, iRequestResponse, self._helpers.analyzeRequest(iRequestResponse).getUrl())) self.fireTableRowsInserted(row, row) self._lock.release() matchCount += 1 except Exception as e: JOptionPane.showMessageDialog(None, "Error running Yara. Please check your configuration and rules.") return finally: # Remove the temp file if req_file is not None: req_file.close() os.remove(req_filename) # Process the response response = iRequestResponse.getResponse() if response is not None: if len(response) > 0: try: # Yara does not support scanning from stdin so we will need to create a temp file and scan it resp_filename = os.path.join(temp_folder, "resp_" + str(idx) + ".tmp") resp_file = open(resp_filename, "wb") resp_file.write(response) resp_file.close() for rules in yara_rules: yara_resp_output = subprocess.check_output([yara_path, rules, resp_filename]) if yara_resp_output is not None and len(yara_resp_output) > 0: ruleName = (yara_resp_output.split())[0] self._lock.acquire() row = self._log.size() # TODO: Don't add duplicate items to the table self._log.add(LogEntry(ruleName, iRequestResponse, self._helpers.analyzeRequest(iRequestResponse).getUrl())) self.fireTableRowsInserted(row, row) self._lock.release() matchCount += 1 except Exception as e: JOptionPane.showMessageDialog(None, "Error running Yara. Please check your configuration and rules.") return finally: # Remove the temp file if resp_file is not None: resp_file.close() os.remove(resp_filename) # Print a completion notification JOptionPane.showMessageDialog(None, "Yara scanning complete. %d rule(s) matched." % matchCount)
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 registerExtenderCallbacks(self, callbacks): # keep a reference to our Burp callbacks object self._callbacks = callbacks # obtain an Burp extension helpers object self._helpers = callbacks.getHelpers() # set our extension name callbacks.setExtensionName("AuthMatrix - v0.5.2") # DB that holds everything users, roles, and messages self._db = MatrixDB() # For saving/loading config self._fc = JFileChooser() # Used by ActionListeners selfExtender = self self._selectedColumn = -1 self._selectedRow = -1 # Table of User entries self._userTable = UserTable(self, model = UserTableModel(self._db)) roleScrollPane = JScrollPane(self._userTable) self._userTable.redrawTable() # Table of Request (AKA Message) entries self._messageTable = MessageTable(self, model = MessageTableModel(self._db)) messageScrollPane = JScrollPane(self._messageTable) self._messageTable.redrawTable() # Semi-Generic Popup stuff def addPopup(component, popup): class genericMouseListener(MouseAdapter): def mousePressed(self, e): if e.isPopupTrigger(): self.showMenu(e) def mouseReleased(self, e): if e.isPopupTrigger(): self.showMenu(e) def showMenu(self, e): if type(component) is JTableHeader: table = component.getTable() column = component.columnAtPoint(e.getPoint()) if type(table) is MessageTable and column >= selfExtender._db.STATIC_MESSAGE_TABLE_COLUMN_COUNT or type(table) is UserTable and column >= selfExtender._db.STATIC_USER_TABLE_COLUMN_COUNT: selfExtender._selectedColumn = column else: return else: selfExtender._selectedRow = component.rowAtPoint(e.getPoint()) popup.show(e.getComponent(), e.getX(), e.getY()) component.addMouseListener(genericMouseListener()) class actionRunMessage(ActionListener): def actionPerformed(self,e): if selfExtender._selectedRow >= 0: if selfExtender._selectedRow not in selfExtender._messageTable.getSelectedRows(): indexes = [selfExtender._db.getMessageByRow(selfExtender._selectedRow)._index] else: indexes = [selfExtender._db.getMessageByRow(rowNum)._index for rowNum in selfExtender._messageTable.getSelectedRows()] t = Thread(target=selfExtender.runMessagesThread, args = [indexes]) t.start() selfExtender._selectedColumn = -1 # Redrawing the table happens in colorcode within the thread class actionRemoveMessage(ActionListener): def actionPerformed(self,e): if selfExtender._selectedRow >= 0: if selfExtender._selectedRow not in selfExtender._messageTable.getSelectedRows(): indexes = [selfExtender._db.getMessageByRow(selfExtender._selectedRow)._index] else: indexes = [selfExtender._db.getMessageByRow(rowNum)._index for rowNum in selfExtender._messageTable.getSelectedRows()] for i in indexes: selfExtender._db.deleteMessage(i) selfExtender._selectedColumn = -1 selfExtender._messageTable.redrawTable() class actionRemoveUser(ActionListener): def actionPerformed(self,e): if selfExtender._selectedRow >= 0: if selfExtender._selectedRow not in selfExtender._userTable.getSelectedRows(): indexes = [selfExtender._db.getUserByRow(selfExtender._selectedRow)._index] else: indexes = [selfExtender._db.getUserByRow(rowNum)._index for rowNum in selfExtender._userTable.getSelectedRows()] for i in indexes: selfExtender._db.deleteUser(i) selfExtender._selectedColumn = -1 selfExtender._userTable.redrawTable() # TODO combine these next two classes class actionRemoveRoleHeaderFromMessageTable(ActionListener): def actionPerformed(self,e): if selfExtender._selectedColumn >= 0: selfExtender._db.deleteRole(selfExtender._db.getRoleByMessageTableColumn(selfExtender._selectedColumn)._index) selfExtender._selectedColumn = -1 selfExtender._userTable.redrawTable() selfExtender._messageTable.redrawTable() class actionRemoveRoleHeaderFromUserTable(ActionListener): def actionPerformed(self,e): if selfExtender._selectedColumn >= 0: selfExtender._db.deleteRole(selfExtender._db.getRoleByUserTableColumn(selfExtender._selectedColumn)._index) selfExtender._selectedColumn = -1 selfExtender._userTable.redrawTable() selfExtender._messageTable.redrawTable() # Message Table popups messagePopup = JPopupMenu() addPopup(self._messageTable,messagePopup) messageRun = JMenuItem("Run Request(s)") messageRun.addActionListener(actionRunMessage()) messagePopup.add(messageRun) messageRemove = JMenuItem("Remove Request(s)") messageRemove.addActionListener(actionRemoveMessage()) messagePopup.add(messageRemove) messageHeaderPopup = JPopupMenu() addPopup(self._messageTable.getTableHeader(),messageHeaderPopup) roleRemoveFromMessageTable = JMenuItem("Remove Role") roleRemoveFromMessageTable.addActionListener(actionRemoveRoleHeaderFromMessageTable()) messageHeaderPopup.add(roleRemoveFromMessageTable) # User Table popup userPopup = JPopupMenu() addPopup(self._userTable,userPopup) userRemove = JMenuItem("Remove Users(s)") userRemove.addActionListener(actionRemoveUser()) userPopup.add(userRemove) userHeaderPopup = JPopupMenu() addPopup(self._userTable.getTableHeader(),userHeaderPopup) roleRemoveFromUserTable = JMenuItem("Remove Role") roleRemoveFromUserTable.addActionListener(actionRemoveRoleHeaderFromUserTable()) userHeaderPopup.add(roleRemoveFromUserTable) # Top pane topPane = JSplitPane(JSplitPane.VERTICAL_SPLIT,roleScrollPane,messageScrollPane) # request tabs added to this tab on click in message table self._tabs = JTabbedPane() # Button pannel buttons = JPanel() runButton = JButton("Run", actionPerformed=self.runClick) newUserButton = JButton("New User", actionPerformed=self.getInputUserClick) newRoleButton = JButton("New Role", actionPerformed=self.getInputRoleClick) #debugButton = JButton("Debug", actionPerformed=self.printDB) saveButton = JButton("Save", actionPerformed=self.saveClick) loadButton = JButton("Load", actionPerformed=self.loadClick) clearButton = JButton("Clear", actionPerformed=self.clearClick) buttons.add(runButton) buttons.add(newUserButton) buttons.add(newRoleButton) #buttons.add(debugButton) buttons.add(saveButton) buttons.add(loadButton) buttons.add(clearButton) bottomPane = JSplitPane(JSplitPane.VERTICAL_SPLIT, self._tabs, buttons) # Main Pane self._splitpane = JSplitPane(JSplitPane.VERTICAL_SPLIT, topPane, bottomPane) # customize our UI components callbacks.customizeUiComponent(self._splitpane) callbacks.customizeUiComponent(topPane) callbacks.customizeUiComponent(bottomPane) callbacks.customizeUiComponent(messageScrollPane) callbacks.customizeUiComponent(roleScrollPane) callbacks.customizeUiComponent(self._messageTable) callbacks.customizeUiComponent(self._userTable) callbacks.customizeUiComponent(self._tabs) callbacks.customizeUiComponent(buttons) self._splitpane.setResizeWeight(0.5) topPane.setResizeWeight(0.3) bottomPane.setResizeWeight(0.95) # Handles checkbox color coding # Must be bellow the customizeUiComponent calls self._messageTable.setDefaultRenderer(Boolean, SuccessBooleanRenderer(self._db)) # add the custom tab to Burp's UI callbacks.addSuiteTab(self) # register SendTo option callbacks.registerContextMenuFactory(self) return
def registerExtenderCallbacks(self, callbacks): # keep a reference to our callbacks object self._callbacks = callbacks # obtain an extension helpers object self._helpers = callbacks.getHelpers() # set our extension name callbacks.setExtensionName("Burp Scope Monitor Experimental") self.GLOBAL_HANDLER_ANALYZED = False self.GLOBAL_HANDLER = False self.STATUS = False self.AUTOSAVE_REQUESTS = 10 self.AUTOSAVE_TIMEOUT = 600 # 10 minutes should be fine self.CONFIG_INSCOPE = True self.BAD_EXTENSIONS_DEFAULT = [ '.gif', '.png', '.js', '.woff', '.woff2', '.jpeg', '.jpg', '.css', '.ico', '.m3u8', '.ts', '.svg' ] self.BAD_MIMES_DEFAULT = [ 'gif', 'script', 'jpeg', 'jpg', 'png', 'video', 'mp2t' ] self.BAD_EXTENSIONS = self.BAD_EXTENSIONS_DEFAULT self.BAD_MIMES = self.BAD_MIMES_DEFAULT # create the log and a lock on which to synchronize when adding log entries self._currentlyDisplayedItem = None self.SELECTED_MODEL_ROW = 0 self.SELECTED_VIEW_ROW = 0 self._log = ArrayList() self._fullLog = ArrayList() self._lock = Lock() self._lockFile = Lock() # main split pane self._parentPane = JTabbedPane() self._splitpane = JSplitPane(JSplitPane.VERTICAL_SPLIT) ##### config pane self._config = JTabbedPane() config = JPanel() iexport = JPanel() #config.setLayout(BorderLayout()) config.setLayout(None) iexport.setLayout(None) # config radio button X_BASE = 40 Y_OFFSET = 5 Y_OPTION = 200 Y_OPTION_SPACING = 20 Y_CHECKMARK_SPACING = 20 self.showAllButton = JRadioButton(SHOW_ALL_BUTTON_LABEL, True) self.showNewButton = JRadioButton(SHOW_NEW_BUTTON_LABEL, False) self.showTestedButton = JRadioButton(SHOW_TEST_BUTTON_LABEL, False) self.showAllButton.setBounds(40, 60 + Y_OFFSET, 400, 30) self.showNewButton.setBounds(40, 80 + Y_OFFSET, 400, 30) self.showTestedButton.setBounds(40, 100 + Y_OFFSET, 400, 30) #self.showNewButton = JRadioButton(SHOW_NEW_BUTTON_LABEL, False) #self.showTestedButton = JRadioButton(SHOW_TEST_BUTTON_LABEL, False) self.showAllButton.addActionListener(self.handleRadioConfig) self.showNewButton.addActionListener(self.handleRadioConfig) self.showTestedButton.addActionListener(self.handleRadioConfig) self.clearButton = JButton("Clear") self.clearButton.addActionListener(self.handleClearButton) self.clearButton.setBounds(40, 20, 100, 30) self.startButton = JButton(MONITOR_ON_LABEL) self.startButton.addActionListener(self.handleStartButton) self.startButton.setBounds(150, 20, 200, 30) self.badExtensionsLabel = JLabel("Ignore extensions:") self.badExtensionsLabel.setBounds(X_BASE, 150, 200, 30) self.badExtensionsText = JTextArea("") self.loadBadExtensions() self.badExtensionsText.setBounds(X_BASE, 175, 310, 30) self.badExtensionsButton = JButton("Save") self.badExtensionsButton.addActionListener( self.handleBadExtensionsButton) self.badExtensionsButton.setBounds(355, 175, 70, 30) self.badExtensionsDefaultButton = JButton("Load Defaults") self.badExtensionsDefaultButton.addActionListener( self.handleBadExtensionsDefaultButton) self.badExtensionsDefaultButton.setBounds(430, 175, 120, 30) self.badMimesLabel = JLabel("Ignore mime types:") self.badMimesLabel.setBounds(X_BASE, 220, 200, 30) self.badMimesText = JTextArea("") self.loadBadMimes() self.badMimesText.setBounds(X_BASE, 245, 310, 30) self.badMimesButton = JButton("Save") self.badMimesButton.addActionListener(self.handleBadMimesButton) self.badMimesButton.setBounds(355, 245, 70, 30) self.badMimesDefaultButton = JButton("Load Defaults") self.badMimesDefaultButton.addActionListener( self.handleBadMimesDefaultButton) self.badMimesDefaultButton.setBounds(430, 245, 120, 30) self.otherLabel = JLabel("Other:") self.otherLabel.setBounds(40, 300, 120, 30) self.otherLabel2 = JLabel("Other:") self.otherLabel2.setBounds(X_BASE, Y_OPTION, 120, 30) self.autoSaveOption = JCheckBox("Auto save periodically") self.autoSaveOption.setSelected(True) self.autoSaveOption.addActionListener(self.handleAutoSaveOption) self.autoSaveOption.setBounds(X_BASE, Y_OPTION + Y_CHECKMARK_SPACING, 420, 30) self.repeaterOptionButton = JCheckBox( "Repeater request automatically marks as analyzed") self.repeaterOptionButton.setSelected(True) self.repeaterOptionButton.addActionListener( self.handleRepeaterOptionButton) self.repeaterOptionButton.setBounds(50, 330, 420, 30) self.scopeOptionButton = JCheckBox("Follow Burp Target In Scope rules") self.scopeOptionButton.setSelected(True) self.scopeOptionButton.addActionListener(self.handleScopeOptionButton) self.scopeOptionButton.setBounds(50, 350, 420, 30) self.startOptionButton = JCheckBox("Autostart Scope Monitor") self.startOptionButton.setSelected(True) self.startOptionButton.addActionListener(self.handleStartOption) self.startOptionButton.setBounds(50, 350 + Y_OPTION_SPACING, 420, 30) self.markTestedRequestsProxy = JCheckBox( "Color request in Proxy tab if analyzed") self.markTestedRequestsProxy.setSelected(True) self.markTestedRequestsProxy.addActionListener( self.handleTestedRequestsProxy) self.markTestedRequestsProxy.setBounds(50, 350 + Y_OPTION_SPACING * 2, 420, 30) self.markNotTestedRequestsProxy = JCheckBox( "Color request in Proxy tab if NOT analyzed") self.markNotTestedRequestsProxy.setSelected(True) self.markNotTestedRequestsProxy.addActionListener( self.handleNotTestedRequestsProxy) self.markNotTestedRequestsProxy.setBounds(50, 350 + Y_OPTION_SPACING * 3, 420, 30) self.saveButton = JButton("Save now") self.saveButton.addActionListener(self.handleSaveButton) self.saveButton.setBounds(X_BASE + 320, 95, 90, 30) self.loadButton = JButton("Load now") self.loadButton.addActionListener(self.handleLoadButton) self.loadButton.setBounds(X_BASE + 420, 95, 90, 30) self.selectPath = JButton("Select path") self.selectPath.addActionListener(self.selectExportFile) self.selectPath.setBounds(X_BASE + 530, 60, 120, 30) self.selectPathText = JTextArea("") self.selectPathText.setBounds(X_BASE, 60, 510, 30) self.selectPathLabel = JLabel("State file:") self.selectPathLabel.setBounds(X_BASE, 30, 200, 30) bGroup = ButtonGroup() bGroup.add(self.showAllButton) bGroup.add(self.showNewButton) bGroup.add(self.showTestedButton) config.add(self.clearButton) config.add(self.startButton) config.add(self.startOptionButton) config.add(self.showAllButton) config.add(self.showNewButton) config.add(self.showTestedButton) config.add(self.badExtensionsButton) config.add(self.badExtensionsText) config.add(self.badExtensionsLabel) config.add(self.badMimesButton) config.add(self.badMimesText) config.add(self.badMimesLabel) config.add(self.badExtensionsDefaultButton) config.add(self.badMimesDefaultButton) config.add(self.otherLabel) config.add(self.repeaterOptionButton) config.add(self.scopeOptionButton) config.add(self.markTestedRequestsProxy) config.add(self.markNotTestedRequestsProxy) iexport.add(self.saveButton) iexport.add(self.loadButton) iexport.add(self.selectPath) iexport.add(self.selectPathText) iexport.add(self.selectPathLabel) iexport.add(self.otherLabel2) iexport.add(self.autoSaveOption) self._config.addTab("General", config) self._config.addTab("Import/Export", iexport) ##### end config pane self._parentPane.addTab("Monitor", self._splitpane) self._parentPane.addTab("Config", self._config) # table of log entries self.logTable = Table(self) #self.logTable.setDefaultRenderer(self.logTable.getColumnClass(0), ColoredTableCellRenderer(self)) self.logTable.setAutoCreateRowSorter(True) self.logTable.setRowSelectionAllowed(True) renderer = ColoredTableCellRenderer(self) #column = TableColumn(0, 190, renderer, None) print 'Initiating... ' # this could be improved by fetching initial dimensions self.logTable.getColumn("URL").setPreferredWidth(720) # noscope self.logTable.getColumn("URL").setResizable(True) self.logTable.getColumn("Checked").setCellRenderer(renderer) self.logTable.getColumn("Checked").setPreferredWidth(80) self.logTable.getColumn("Checked").setMaxWidth(80) self.logTable.getColumn("Method").setPreferredWidth(120) #self.logTable.getColumn("Method").setMaxWidth(120) self.logTable.getColumn("Method").setResizable(True) self.logTable.getColumn("Time").setPreferredWidth(120) # noscope self.logTable.getColumn("Time").setResizable(True) scrollPane = JScrollPane(self.logTable) self._splitpane.setLeftComponent(scrollPane) # tabs with request/response viewers tabs = JTabbedPane() self._requestViewer = callbacks.createMessageEditor(self, False) self._responseViewer = callbacks.createMessageEditor(self, False) tabs.addTab("Request", self._requestViewer.getComponent()) tabs.addTab("Response", self._responseViewer.getComponent()) self._splitpane.setRightComponent(tabs) ## Row sorter shit #self._tableRowSorterAutoProxyAutoAction = CustomTableRowSorter(self.logTable.getModel()) #self.logTable.setRowSorter(self._tableRowSorterAutoProxyAutoAction) markAnalyzedButton = JMenuItem("Mark Requests as Analyzed") markAnalyzedButton.addActionListener(markRequestsHandler(self, True)) markNotAnalyzedButton = JMenuItem("Mark Requests as NOT Analyzed") markNotAnalyzedButton.addActionListener( markRequestsHandler(self, False)) sendRequestMenu = JMenuItem("Send Request to Repeater") sendRequestMenu.addActionListener(sendRequestRepeater(self)) deleteRequestMenu = JMenuItem("Delete request") deleteRequestMenu.addActionListener(deleteRequestHandler(self)) self.menu = JPopupMenu("Popup") self.menu.add(markAnalyzedButton) self.menu.add(markNotAnalyzedButton) self.menu.add(sendRequestMenu) self.menu.add(deleteRequestMenu) # customize our UI components callbacks.customizeUiComponent(self._parentPane) callbacks.customizeUiComponent(self._splitpane) callbacks.customizeUiComponent(self._config) callbacks.customizeUiComponent(config) callbacks.customizeUiComponent(self.logTable) callbacks.customizeUiComponent(scrollPane) callbacks.customizeUiComponent(tabs) callbacks.registerContextMenuFactory(self) callbacks.registerExtensionStateListener(self) callbacks.registerScannerCheck(passiveScanner(self)) # add the custom tab to Burp's UI callbacks.addSuiteTab(self) # register ourselves as an HTTP listener callbacks.registerHttpListener(self) self.loadConfigs() print "Loaded!" print "Experimental import state.. " self.importState("") self.SC = sched.scheduler(time.time, time.sleep) self.SCC = self.SC.enter(10, 1, self.autoSave, (self.SC, )) self.SC.run() return
class QatDialog(ToggleDialog): """ToggleDialog for error type selection and buttons for reviewing errors in sequence """ def __init__(self, name, iconName, tooltip, shortcut, height, app): ToggleDialog.__init__(self, name, iconName, tooltip, shortcut, height) self.app = app tools = app.tools #Main panel of the dialog mainPnl = JPanel(BorderLayout()) mainPnl.setBorder(BorderFactory.createEmptyBorder(0, 1, 1, 1)) ### First tab: errors selection and download ########################### #ComboBox with tools names self.toolsComboModel = DefaultComboBoxModel() for tool in tools: self.add_data_to_models(tool) self.toolsCombo = JComboBox(self.toolsComboModel, actionListener=ToolsComboListener(app)) renderer = ToolsComboRenderer(self.app) renderer.setPreferredSize(Dimension(20, 20)) self.toolsCombo.setRenderer(renderer) self.toolsCombo.setToolTipText(app.strings.getString("Select_a_quality_assurance_tool")) #ComboBox with categories names ("views"), of the selected tool self.viewsCombo = JComboBox(actionListener=ViewsComboListener(app)) self.viewsCombo.setToolTipText(app.strings.getString("Select_a_category_of_error")) #Popup for checks table self.checkPopup = JPopupMenu() #add favourite check self.menuItemAdd = JMenuItem(self.app.strings.getString("Add_to_favourites")) self.menuItemAdd.setIcon(ImageIcon(File.separator.join([self.app.SCRIPTDIR, "tools", "data", "Favourites", "icons", "tool_16.png"]))) self.menuItemAdd.addActionListener(PopupActionListener(self.app)) self.checkPopup.add(self.menuItemAdd) #remove favourite check self.menuItemRemove = JMenuItem(self.app.strings.getString("Remove_from_favourites")) self.menuItemRemove.setIcon(ImageIcon(File.separator.join([self.app.SCRIPTDIR, "tools", "data", "Favourites", "icons", "black_tool_16.png"]))) self.menuItemRemove.addActionListener(PopupActionListener(self.app)) self.checkPopup.add(self.menuItemRemove) #Help link for selected check self.menuItemHelp = JMenuItem(self.app.strings.getString("check_help")) self.menuItemHelp.setIcon(ImageIcon(File.separator.join([self.app.SCRIPTDIR, "images", "icons", "info_16.png"]))) self.checkPopup.add(self.menuItemHelp) self.menuItemHelp.addActionListener(PopupActionListener(self.app)) #Table with checks of selected tool and view self.checksTable = JTable() self.iconrenderer = IconRenderer() self.iconrenderer.setHorizontalAlignment(JLabel.CENTER) scrollPane = JScrollPane(self.checksTable) self.checksTable.setFillsViewportHeight(True) tableSelectionModel = self.checksTable.getSelectionModel() tableSelectionModel.addListSelectionListener(ChecksTableListener(app)) self.checksTable.addMouseListener(ChecksTableClickListener(app, self.checkPopup, self.checksTable)) #Favourite area status indicator self.favAreaIndicator = JLabel() self.update_favourite_zone_indicator() self.favAreaIndicator.addMouseListener(FavAreaIndicatorListener(app)) #label with OSM id of the object currently edited and number of #errors still to review self.checksTextFld = JTextField("", editable=0, border=None, background=None) #checks buttons btnsIconsDir = File.separator.join([app.SCRIPTDIR, "images", "icons"]) downloadIcon = ImageIcon(File.separator.join([btnsIconsDir, "download.png"])) self.downloadBtn = JButton(downloadIcon, actionPerformed=app.on_downloadBtn_clicked, enabled=0) startIcon = ImageIcon(File.separator.join([btnsIconsDir, "start_fixing.png"])) self.startBtn = JButton(startIcon, actionPerformed=app.on_startBtn_clicked, enabled=0) self.downloadBtn.setToolTipText(app.strings.getString("Download_errors_in_this_area")) self.startBtn.setToolTipText(app.strings.getString("Start_fixing_the_selected_errors")) #tab layout panel1 = JPanel(BorderLayout(0, 1)) comboboxesPnl = JPanel(GridLayout(0, 2, 5, 0)) comboboxesPnl.add(self.toolsCombo) comboboxesPnl.add(self.viewsCombo) checksPnl = JPanel(BorderLayout(0, 1)) checksPnl.add(scrollPane, BorderLayout.CENTER) self.statsPanel = JPanel(BorderLayout(4, 0)) self.statsPanel_def_color = self.statsPanel.getBackground() self.statsPanel.add(self.checksTextFld, BorderLayout.CENTER) self.statsPanel.add(self.favAreaIndicator, BorderLayout.LINE_START) checksPnl.add(self.statsPanel, BorderLayout.PAGE_END) checksButtonsPnl = JPanel(GridLayout(0, 2, 0, 0)) checksButtonsPnl.add(self.downloadBtn) checksButtonsPnl.add(self.startBtn) panel1.add(comboboxesPnl, BorderLayout.PAGE_START) panel1.add(checksPnl, BorderLayout.CENTER) panel1.add(checksButtonsPnl, BorderLayout.PAGE_END) ### Second tab: errors fixing ########################################## #label with error stats self.errorTextFld = JTextField("", editable=0, border=None, background=None) #label with current error description self.errorDesc = JLabel("") self.errorDesc.setAlignmentX(0.5) #error buttons errorInfoBtnIcon = ImageProvider.get("info") self.errorInfoBtn = JButton(errorInfoBtnIcon, actionPerformed=app.on_errorInfoBtn_clicked, enabled=0) notErrorIcon = ImageIcon(File.separator.join([btnsIconsDir, "not_error.png"])) self.notErrorBtn = JButton(notErrorIcon, actionPerformed=app.on_falsePositiveBtn_clicked, enabled=0) ignoreIcon = ImageIcon(File.separator.join([btnsIconsDir, "skip.png"])) self.ignoreBtn = JButton(ignoreIcon, actionPerformed=app.on_ignoreBtn_clicked, enabled=0) correctedIcon = ImageIcon(File.separator.join([btnsIconsDir, "corrected.png"])) self.correctedBtn = JButton(correctedIcon, actionPerformed=app.on_correctedBtn_clicked, enabled=0) nextIcon = ImageIcon(File.separator.join([btnsIconsDir, "next.png"])) self.nextBtn = JButton(nextIcon, actionPerformed=app.on_nextBtn_clicked, enabled=0) #self.nextBtn.setMnemonic(KeyEvent.VK_RIGHT) self.errorInfoBtn.setToolTipText(app.strings.getString("open_error_info_dialog")) self.notErrorBtn.setToolTipText(app.strings.getString("flag_false_positive")) self.ignoreBtn.setToolTipText(app.strings.getString("Skip_and_don't_show_me_this_error_again")) self.correctedBtn.setToolTipText(app.strings.getString("flag_corrected_error")) self.nextBtn.setToolTipText(app.strings.getString("Go_to_next_error")) #tab layout self.panel2 = JPanel(BorderLayout()) self.panel2.add(self.errorTextFld, BorderLayout.PAGE_START) self.panel2.add(self.errorDesc, BorderLayout.CENTER) errorButtonsPanel = JPanel(GridLayout(0, 5, 0, 0)) errorButtonsPanel.add(self.errorInfoBtn) errorButtonsPanel.add(self.notErrorBtn) errorButtonsPanel.add(self.ignoreBtn) errorButtonsPanel.add(self.correctedBtn) errorButtonsPanel.add(self.nextBtn) self.panel2.add(errorButtonsPanel, BorderLayout.PAGE_END) #Layout self.tabbedPane = JTabbedPane() self.tabbedPane.addTab(self.app.strings.getString("Download"), None, panel1, self.app.strings.getString("download_tab")) mainPnl.add(self.tabbedPane, BorderLayout.CENTER) self.createLayout(mainPnl, False, None) def add_data_to_models(self, tool): """Add data of a tool to the models of the dialog components """ #tools combobox model if tool == self.app.favouritesTool: self.toolsComboModel.addElement(JSeparator()) self.toolsComboModel.addElement(tool) #views combobox model tool.viewsComboModel = DefaultComboBoxModel() for view in tool.views: tool.viewsComboModel.addElement(view.title) #checks table, one TableModel for each view, of each tool columns = ["", self.app.strings.getString("Check"), self.app.strings.getString("Errors")] for view in tool.views: tableRows = [] for check in view.checks: if check.icon is not None: icon = check.icon else: icon = "" errorsNumber = "" tableRows.append([icon, check.title, errorsNumber]) view.tableModel = MyTableModel(tableRows, columns) def update_favourite_zone_indicator(self): #icon if self.app.favZone is not None: self.favAreaIndicator.setIcon(self.app.favZone.icon) #tooltip messageArguments = array([self.app.favZone.name], String) formatter = MessageFormat("") formatter.applyPattern(self.app.strings.getString("favAreaIndicator_tooltip")) msg = formatter.format(messageArguments) self.favAreaIndicator.setToolTipText(msg) #status self.favAreaIndicator.setVisible(self.app.favouriteZoneStatus) def set_checksTextFld_color(self, color): """Change color of textField under checksTable """ colors = {"white": (255, 255, 255), "black": (0, 0, 0), "green": (100, 200, 0), "red": (200, 0, 0)} if color == "default": self.statsPanel.background = self.statsPanel_def_color self.checksTextFld.foreground = colors["black"] else: self.statsPanel.background = colors[color] self.checksTextFld.foreground = colors["white"] def change_selection(self, source): """Change comboboxes and checks table selections after a selection has been made by the user """ if source in ("menu", "layer", "add favourite"): self.app.selectionChangedFromMenuOrLayer = True self.toolsCombo.setSelectedItem(self.app.selectedTool) self.viewsCombo.setModel(self.app.selectedTool.viewsComboModel) self.viewsCombo.setSelectedItem(self.app.selectedView.title) self.checksTable.setModel(self.app.selectedTableModel) self.refresh_checksTable_columns_geometries() for i, c in enumerate(self.app.selectedView.checks): if c == self.app.selectedChecks[0]: break self.checksTable.setRowSelectionInterval(i, i) self.app.selectionChangedFromMenuOrLayer = False else: self.app.selectionChangedFromMenuOrLayer = False if source == "toolsCombo": self.viewsCombo.setModel(self.app.selectedTool.viewsComboModel) self.viewsCombo.setSelectedIndex(0) elif source == "viewsCombo": self.checksTable.setModel(self.app.selectedTableModel) self.refresh_checksTable_columns_geometries() if self.app.selectedView.checks != []: # favourite checks may be none self.checksTable.setRowSelectionInterval(0, 0) def refresh_checksTable_columns_geometries(self): self.checksTable.getColumnModel().getColumn(0).setCellRenderer(self.iconrenderer) self.checksTable.getColumnModel().getColumn(0).setMaxWidth(25) self.checksTable.getColumnModel().getColumn(2).setMaxWidth(60) def activate_error_tab(self, status): if status: if self.tabbedPane.getTabCount() == 1: self.tabbedPane.addTab(self.app.strings.getString("Fix"), None, self.panel2, self.app.strings.getString("fix_tab")) else: if self.tabbedPane.getTabCount() == 2: self.tabbedPane.remove(1) def update_checks_buttons(self): """This method sets the status of downloadBtn and startBtn """ #none check selected if len(self.app.selectedChecks) == 0: self.downloadBtn.setEnabled(False) self.startBtn.setEnabled(False) else: #some check selected self.downloadBtn.setEnabled(True) if len(self.app.selectedChecks) > 1: self.startBtn.setEnabled(False) else: #only one check is selected self.app.errors = self.app.selectedChecks[0].errors if self.app.errors is None or len(self.app.errors) == 0: #errors file has not been downloaded and parsed yet self.startBtn.setEnabled(False) else: #errors file has been downloaded and parsed if self.app.selectedChecks[0].toDo == 0: #all errors have been corrected self.startBtn.setEnabled(False) else: self.startBtn.setEnabled(True) #self.nextBtn.setEnabled(True) def update_error_buttons(self, mode): """This method sets the status of: ignoreBtn, falsePositiveBtn, correctedBtn, nextBtn """ if mode == "new error": status = True else: status = False if self.app.selectedChecks[0].tool.fixedFeedbackMode is None: self.correctedBtn.setEnabled(False) else: self.correctedBtn.setEnabled(status) if self.app.selectedChecks[0].tool.falseFeedbackMode is None: self.notErrorBtn.setEnabled(False) else: self.notErrorBtn.setEnabled(status) self.errorInfoBtn.setEnabled(status) self.ignoreBtn.setEnabled(status) if mode in ("reset", "review end"): self.nextBtn.setEnabled(False) elif mode in ("errors downloaded", "show stats", "new error"): self.nextBtn.setEnabled(True) def update_text_fields(self, mode, errorInfo=""): """This method updates the text in: checksTextFld, errorDesc, errorTextFld """ self.errorDesc.text = "" if mode == "review end": cheksTextColor = "green" checksText = self.app.strings.getString("All_errors_reviewed.") errorText = self.app.strings.getString("All_errors_reviewed.") elif mode == "reset": cheksTextColor = "default" checksText = "" errorText = "" elif mode == "show stats": cheksTextColor = "default" checksText = "%s %d / %s" % ( self.app.strings.getString("to_do"), self.app.selectedChecks[0].toDo, len(self.app.selectedChecks[0].errors)) #print "checks text", checksText errorText = "%s%s %d / %s" % ( errorInfo, self.app.strings.getString("to_do"), self.app.selectedChecks[0].toDo, len(self.app.selectedChecks[0].errors)) #print "error text", errorText if self.app.selectedError is not None and self.app.selectedError.desc != "": self.errorDesc.text = "<html>%s</html>" % self.app.selectedError.desc self.set_checksTextFld_color(cheksTextColor) self.checksTextFld.text = checksText self.errorTextFld.text = errorText self.update_statsPanel_status() def update_statsPanel_status(self): if self.checksTextFld.text == "" and not self.app.favouriteZoneStatus: self.statsPanel.setVisible(False) else: self.statsPanel.setVisible(True)
class main(JFrame): def __init__(self): super(main,self).__init__() self.Config() self.windows() self.ruta="" def windows(self): self.setTitle("IDE Meta Compilador") self.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) self.setLayout(None) self.setLocationRelativeTo(None) self.setVisible(True) def Config(self): self.panel = JScrollPane() self.txtArea_Principal =JTextArea() self.jScrollPane1 =JScrollPane() self.txtTerminal =JTextArea() self.Menu =JMenuBar() self.menu_Archivo =JMenu() self.menu_Nuevo =JMenuItem() self.menuabrir =JMenuItem() self.menucerrar =JMenuItem() self.menuguardar =JMenuItem() self.menuguardarcomo =JMenuItem() self.menusalir =JMenuItem() self.menu_Edicion =JMenu() self.menu_cortar =JMenuItem() self.menu_copiar =JMenuItem() self.menu_pegar =JMenuItem() self.menu_Tablas =JMenu() self.menu_TablasEstaticas =JMenu() self.submenu_palabrasReservadas =JMenuItem() self.submenu_CaracteresEspeciales =JMenuItem() self.submenu_operadores =JMenu() self.ta_di_conu_enteros =JMenuItem() self.ta_di_conu_reales =JMenuItem() self.ta_di_conu_cientificos =JMenuItem() self.menu_TablaasDinamicas =JMenu() self.submenu_simbolos =JMenuItem() self.submenu_identificadores =JMenuItem() self.submenu_errores =JMenuItem() self.submenu_constantesNumericas =JMenu() self.ta_es_op_aritmeticos =JMenuItem() self.ta_es_op_relacionales =JMenuItem() self.ta_es_op_logicos =JMenuItem() self.submenu_Constantes_No_Numericas =JMenu() self.tab_caracteres =JMenuItem() self.tab_cadenas =JMenuItem() self.menu_Analisis =JMenu() self.ana_lexico =JMenuItem() self.ana_sintactico =JMenuItem() self.ana_semantico =JMenuItem() self.menu_Acerca_de =JMenu() self.btn_integrantes =JMenuItem() ######################### self.jf = JFileChooser() ######################### self.txtArea_Principal.setColumns(20) self.txtArea_Principal.setRows(5) self.txtArea_Principal.setAutoscrolls(False) self.txtArea_Principal.setEnabled(False) self.panel.setViewportView(self.txtArea_Principal) self.getContentPane().add(self.panel) self.panel.setBounds(0, 0, 1080, 450) self.txtTerminal.setColumns(20) self.txtTerminal.setRows(5) self.txtTerminal.setAutoscrolls(False) self.txtTerminal.setFocusable(False) self.jScrollPane1.setViewportView(self.txtTerminal) self.getContentPane().add(self.jScrollPane1) self.jScrollPane1.setBounds(0, 460, 1080, 150) # >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>MENU ARCHIVOS<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< self.menu_Archivo.setText("Archivo") self.menu_Nuevo.addActionListener(lambda event : self.nuevo(event)) self.menu_Nuevo.setText("Nuevo") self.menu_Archivo.add(self.menu_Nuevo) self.menuabrir.setText("Abrir") self.menuabrir.addActionListener(lambda event : self.abrir(event)) self.menu_Archivo.add(self.menuabrir) self.menucerrar.setText("Cerrar") self.menucerrar.addActionListener(lambda event : self.cerrar(event)) self.menu_Archivo.add(self.menucerrar) self.menuguardar.setText("Guardar") self.menuguardar.addActionListener(lambda event : self.guardar(event)) self.menu_Archivo.add(self.menuguardar) self.menuguardarcomo.setText("Guardar como") self.menuguardarcomo.addActionListener(lambda event : self.guardarcomo(event)) self.menu_Archivo.add(self.menuguardarcomo) self.menusalir.setText("Salir") self.menusalir.addActionListener(lambda event : self.salir(event)) self.menu_Archivo.add(self.menusalir) self.Menu.add(self.menu_Archivo) # >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>MENU EDICION<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< self.menu_Edicion.setText("Edicion") self.menu_cortar.setText("Cortar") self.menu_cortar.addActionListener(lambda event : self.cortar(event)) self.menu_Edicion.add(self.menu_cortar) self.menu_copiar.setText("Copiar") self.menu_copiar.addActionListener(lambda event : self.copiar(event)) self.menu_Edicion.add(self.menu_copiar) self.menu_pegar.setText("Pegar") self.menu_pegar.addActionListener(lambda event : self.pegar(event)) self.menu_Edicion.add(self.menu_pegar) self.Menu.add(self.menu_Edicion) # >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>MENU TABLAS<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< self.menu_Tablas.setText("Tablas") self.menu_TablasEstaticas.setText("Tablas Estaticas") self.submenu_palabrasReservadas.setText("Tabla de palabras reservadas") self.menu_TablasEstaticas.add(self.submenu_palabrasReservadas) self.submenu_CaracteresEspeciales.setText("Tabla de caracteres especiales") self.menu_TablasEstaticas.add(self.submenu_CaracteresEspeciales) self.submenu_operadores.setText("Tabla de operadores") self.ta_es_op_aritmeticos.setText("Aritmeticos") self.submenu_operadores.add(self.ta_es_op_aritmeticos) self.ta_es_op_relacionales.setText("Relacionales") self.submenu_operadores.add(self.ta_es_op_relacionales) self.ta_es_op_logicos.setText("Logicos") self.submenu_operadores.add(self.ta_es_op_logicos) self.menu_TablasEstaticas.add(self.submenu_operadores) self.menu_Tablas.add(self.menu_TablasEstaticas) self.menu_TablaasDinamicas.setText("Tablas Dinamicas") self.submenu_simbolos.setText("Tabla de simbolos") self.menu_TablaasDinamicas.add(self.submenu_simbolos) self.submenu_identificadores.setText("Tabla de identificadores") self.menu_TablaasDinamicas.add(self.submenu_identificadores) self.submenu_errores.setText("Tabla de errores") self.menu_TablaasDinamicas.add(self.submenu_errores) self.submenu_constantesNumericas.setText("Tabla de constantes numericas") self.ta_di_conu_enteros.setText("Enteros") self.ta_di_conu_enteros.addActionListener(lambda event : self.numeroenteros(event)) self.submenu_constantesNumericas.add(self.ta_di_conu_enteros) self.ta_di_conu_reales.setText("Reales") self.ta_di_conu_reales.addActionListener(lambda event : self.numeroreales(event)) self.submenu_constantesNumericas.add(self.ta_di_conu_reales) self.ta_di_conu_cientificos.setText("Cientificos") self.submenu_constantesNumericas.add(self.ta_di_conu_cientificos) self.menu_TablaasDinamicas.add(self.submenu_constantesNumericas) self.submenu_Constantes_No_Numericas.setText("Tabla de constantes no numericas") self.tab_caracteres.setText("Caracteres") self.submenu_Constantes_No_Numericas.add(self.tab_caracteres) self.tab_cadenas.setText("Cadenas") self.submenu_Constantes_No_Numericas.add(self.tab_cadenas) self.menu_TablaasDinamicas.add(self.submenu_Constantes_No_Numericas) self.menu_Tablas.add(self.menu_TablaasDinamicas) self.Menu.add(self.menu_Tablas) # >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>MENU ANALISIS<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< self.menu_Analisis.setText("Analisis") self.ana_lexico.setText("Lexico") self.ana_lexico.addActionListener(lambda event : self.lexico(event)) self.menu_Analisis.add(self.ana_lexico) self.ana_sintactico.setText("Sintactico") self.ana_sintactico.addActionListener(lambda event : self.sintactico(event)) self.menu_Analisis.add(self.ana_sintactico) self.ana_semantico.setText("Semantico") self.menu_Analisis.add(self.ana_semantico) self.Menu.add(self.menu_Analisis) # >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>MENU ACERCA DE<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< self.menu_Acerca_de.setText("Acerca de") self.btn_integrantes.setText("Integrante del proyecto") self.btn_integrantes.addActionListener(lambda event : self.integrantes(event)) self.menu_Acerca_de.add(self.btn_integrantes) self.Menu.add(self.menu_Acerca_de) self.setJMenuBar(self.Menu) self.setBounds(0, 0, 1095, 670) ###################################### def integrantes(self,event): informacion() def cortar(self,event): self.txtArea_Principal.cut() def copiar(self,event): self.txtArea_Principal.copy() def pegar(self,event): self.txtArea_Principal.paste() def salir(self,event): self.dispose() ###################################### def guardarcomo(self,event): pass def guardar(self,event): if self.ruta == "": self.txtTerminal.setText("no hay un directorio abierto") else: agregar(self.ruta,str(self.txtArea_Principal.getText())) def cerrar(self,event): self.txtArea_Principal.setText("") self.txtArea_Principal.setEnabled(False) self.ruta="" def abrir(self,event): self.jf.showOpenDialog(self) self.ruta = self.jf.getSelectedFile() self.txtArea_Principal.setEnabled(True) self.txtArea_Principal.setText(abrir(self.ruta)) def nuevo(self,event): if self.ruta == "": print("no pasa nada") else: print("hay un archivo existente") self.ruta ="" self.txtArea_Principal.setEnabled(True) self.txtArea_Principal.setText("") ###################################### def lexico(self,event): self.txtTerminal.setText("") archivo = open("{}".format(self.ruta),"r") texto = "" for a in prueba(self.txtArea_Principal.getText()): texto += a+"\n" self.txtTerminal.setText(texto) def sintactico(self,event): self.txtTerminal.setText("") texto="" for a in prueba_sintactica(self.txtArea_Principal.getText()): texto +=a+"\n" self.txtTerminal.setText(texto)
class BurpExtender(IBurpExtender, IContextMenuFactory, ActionListener): def __init__(self): self.menuItem = JMenuItem('Generate betterXSS PoC') self.menuItem.addActionListener(self) def _build(self): #Grab first selected message, bail if none iRequestInfo = self._helpers.analyzeRequest( self.ctxMenuInvocation.getSelectedMessages()[0]) if iRequestInfo is None: print('Request info object is null, bailing') return method = iRequestInfo.getMethod() url = iRequestInfo.getUrl() parms = filter(lambda x: x.getType() == IParameter.PARAM_BODY, iRequestInfo.getParameters()) #print('parms ' + ''.join(parms)) c = iRequestInfo.getContentType() if (c == -1): print 'error: unknown content type' elif (c == 0): print 'error: no content type' elif (c == 1): enc = 'application/x-www-form-urlencoded' if len(parms) > 0: p = ['%s=%s' % (p.getName(), p.getValue()) for p in parms] postData = '%s' % ('&'.join(p)) elif (c == 2): enc = 'multipart/form-data' if len(parms) > 0: p = ['%s=%s' % (p.getName(), p.getValue()) for p in parms] postData = '%s' % ('&'.join(p)) elif (c == 3): enc = 'text/xml' elif (c == 4): enc = 'application/json' elif (c == 5): p = ['%s:%s' % (p.getName(), p.getValue()) for p in parms] enc = 'application/x-amf' base = ''' <!-- betterXSS PoC - generated with love by thatpentestguy --> <script> function sendRequest(method, url, enc, postData) { var req = createXMLHTTPObject(); if (!req) return; req.open(method,url,true); if (typeof enc !== 'undefined'){ req.setRequestHeader('Content-type', enc) } req.onreadystatechange = function () { if (req.readyState != 4) return; if (req.status != 200 && req.status != 304) { return; } } if (req.readyState == 4) return; (typeof postData === 'undefined') ? req.send() : req.send(postData); } var XMLHttpFactories = [ function () {return new XMLHttpRequest()}, function () {return new ActiveXObject("Msxml2.XMLHTTP")}, function () {return new ActiveXObject("Msxml3.XMLHTTP")}, function () {return new ActiveXObject("Microsoft.XMLHTTP")} ]; function createXMLHTTPObject() { var xmlhttp = false; for (var i=0;i<XMLHttpFactories.length;i++) { try { xmlhttp = XMLHttpFactories[i](); } catch (e) { continue; } break; } return xmlhttp; }''' if (1 <= c <= 5): base = base + 'sendRequest(\'%s\',\'%s\',\'%s\',\'%s\');' % ( method, url, enc, postData) else: base = base + 'sendRequest(\'%s\',\'%s\');' % (method, url) base = base + '\n</script>' s = StringSelection(base) Toolkit.getDefaultToolkit().getSystemClipboard().setContents( s, s) #put string on clipboard print(base) def actionPerformed(self, actionEvent): self._build() def registerExtenderCallbacks(self, callbacks): self._helpers = callbacks.getHelpers() callbacks.setExtensionName('betterXSS') callbacks.registerContextMenuFactory(self) self.mCallBacks = callbacks print('betterXSS successfully loaded') return def createMenuItems(self, ctxMenuInvocation): self.ctxMenuInvocation = ctxMenuInvocation return [self.menuItem]
def createMenuItems(self, invocation): menu = [] jmi1 = JMenuItem() jmi1.setText("Send to Results") jm1 = JMenu("Send to Failed Cases") jmi_obj1 = JMenuItem() jmi_obj2 = JMenuItem() jmi_obj3 = JMenuItem() jmi_obj4 = JMenuItem() jmi_obj5 = JMenuItem() jmi_obj6 = JMenuItem() jmi_obj7 = JMenuItem() jmi_obj8 = JMenuItem() jmi_obj9 = JMenuItem() jmi_obj10 = JMenuItem() jmi_obj11 = JMenuItem() jmi_obj12 = JMenuItem() jmi_obj13 = JMenuItem() jmi_obj14 = JMenuItem() jmi_obj15 = JMenuItem() jmi_obj16 = JMenuItem() jmi_obj1.setText("Objective-1") jmi_obj2.setText("Objective-2") jmi_obj3.setText("Objective-3") jmi_obj4.setText("Objective-4") jmi_obj5.setText("Objective-5") jmi_obj6.setText("Objective-6") jmi_obj7.setText("Objective-7") jmi_obj8.setText("Objective-8") jmi_obj9.setText("Objective-9") jmi_obj10.setText("Objective-10") jmi_obj11.setText("Objective-11") jmi_obj12.setText("Objective-12") jmi_obj13.setText("Objective-13") jmi_obj14.setText("Objective-14") jmi_obj15.setText("Objective-15") jmi_obj16.setText("Objective-16") jmi1.setVisible(True) jmi1.addActionListener(self) menu.append(jmi1) if(self._itabobject.getAppRating()=="Low"): jm1.add(jmi_obj1) jm1.add(jmi_obj2) jm1.add(jmi_obj3) jm1.add(jmi_obj4) jm1.add(jmi_obj5) menu.append(jm1) elif(self._itabobject.getAppRating()=="High"): jm1.add(jmi_obj1) jm1.add(jmi_obj2) jm1.add(jmi_obj3) jm1.add(jmi_obj4) jm1.add(jmi_obj5) jm1.add(jmi_obj6) jm1.add(jmi_obj7) jm1.add(jmi_obj8) jm1.add(jmi_obj9) jm1.add(jmi_obj10) jm1.add(jmi_obj11) jm1.add(jmi_obj12) jm1.add(jmi_obj13) jm1.add(jmi_obj14) jm1.add(jmi_obj15) jm1.add(jmi_obj16) menu.append(jm1) else: menu = [] return menu
def draw(self): """ init autorize tabs """ self._extender.logTable = Table(self._extender) tableWidth = self._extender.logTable.getPreferredSize().width self._extender.logTable.getColumn("ID").setPreferredWidth( Math.round(tableWidth / 50 * 2)) self._extender.logTable.getColumn("Method").setPreferredWidth( Math.round(tableWidth / 50 * 3)) self._extender.logTable.getColumn("URL").setPreferredWidth( Math.round(tableWidth / 50 * 25)) self._extender.logTable.getColumn("Orig. Length").setPreferredWidth( Math.round(tableWidth / 50 * 4)) self._extender.logTable.getColumn("Modif. Length").setPreferredWidth( Math.round(tableWidth / 50 * 4)) self._extender.logTable.getColumn("Unauth. Length").setPreferredWidth( Math.round(tableWidth / 50 * 4)) self._extender.logTable.getColumn( "Authorization Enforcement Status").setPreferredWidth( Math.round(tableWidth / 50 * 4)) self._extender.logTable.getColumn( "Authorization Unauth. Status").setPreferredWidth( Math.round(tableWidth / 50 * 4)) self._extender.tableSorter = TableRowSorter(self._extender.tableModel) rowFilter = TableRowFilter(self._extender) self._extender.tableSorter.setRowFilter(rowFilter) self._extender.logTable.setRowSorter(self._extender.tableSorter) self._extender._splitpane = JSplitPane(JSplitPane.HORIZONTAL_SPLIT) self._extender._splitpane.setResizeWeight(1) self._extender.scrollPane = JScrollPane(self._extender.logTable) self._extender._splitpane.setLeftComponent(self._extender.scrollPane) self._extender.scrollPane.getVerticalScrollBar().addAdjustmentListener( AutoScrollListener(self._extender)) copyURLitem = JMenuItem("Copy URL") copyURLitem.addActionListener(CopySelectedURL(self._extender)) sendRequestMenu = JMenuItem("Send Original Request to Repeater") sendRequestMenu.addActionListener( SendRequestRepeater(self._extender, self._extender._callbacks, True)) sendRequestMenu2 = JMenuItem("Send Modified Request to Repeater") sendRequestMenu2.addActionListener( SendRequestRepeater(self._extender, self._extender._callbacks, False)) sendResponseMenu = JMenuItem("Send Responses to Comparer") sendResponseMenu.addActionListener( SendResponseComparer(self._extender, self._extender._callbacks)) retestSelecteditem = JMenuItem("Retest selected request") retestSelecteditem.addActionListener( RetestSelectedRequest(self._extender)) deleteSelectedItem = JMenuItem("Delete") deleteSelectedItem.addActionListener( DeleteSelectedRequest(self._extender)) self._extender.menu = JPopupMenu("Popup") self._extender.menu.add(sendRequestMenu) self._extender.menu.add(sendRequestMenu2) self._extender.menu.add(sendResponseMenu) self._extender.menu.add(copyURLitem) self._extender.menu.add(retestSelecteditem) # self.menu.add(deleteSelectedItem) disabling this feature until bug will be fixed. message_editor = MessageEditor(self._extender) self._extender.tabs = JTabbedPane() self._extender._requestViewer = self._extender._callbacks.createMessageEditor( message_editor, False) self._extender._responseViewer = self._extender._callbacks.createMessageEditor( message_editor, False) self._extender._originalrequestViewer = self._extender._callbacks.createMessageEditor( message_editor, False) self._extender._originalresponseViewer = self._extender._callbacks.createMessageEditor( message_editor, False) self._extender._unauthorizedrequestViewer = self._extender._callbacks.createMessageEditor( message_editor, False) self._extender._unauthorizedresponseViewer = self._extender._callbacks.createMessageEditor( message_editor, False) self._extender.tabs.addTab( "Modified Request", self._extender._requestViewer.getComponent()) self._extender.tabs.addTab( "Modified Response", self._extender._responseViewer.getComponent()) self._extender.tabs.addTab( "Original Request", self._extender._originalrequestViewer.getComponent()) self._extender.tabs.addTab( "Original Response", self._extender._originalresponseViewer.getComponent()) self._extender.tabs.addTab( "Unauthenticated Request", self._extender._unauthorizedrequestViewer.getComponent()) self._extender.tabs.addTab( "Unauthenticated Response", self._extender._unauthorizedresponseViewer.getComponent()) self._extender.tabs.addTab("Configuration", self._extender.pnl) self._extender.tabs.setSelectedIndex(6) self._extender._splitpane.setRightComponent(self._extender.tabs)
class BurpExtender(IBurpExtender, IContextMenuFactory, ActionListener): def __init__(self): self.menuItem = JMenuItem("Generate betterXSS PoC") self.menuItem.addActionListener(self) def _build(self): # Grab first selected message, bail if none iRequestInfo = self._helpers.analyzeRequest(self.ctxMenuInvocation.getSelectedMessages()[0]) if iRequestInfo is None: print ("Request info object is null, bailing") return method = iRequestInfo.getMethod() url = iRequestInfo.getUrl() parms = filter(lambda x: x.getType() == IParameter.PARAM_BODY, iRequestInfo.getParameters()) # print('parms ' + ''.join(parms)) c = iRequestInfo.getContentType() if c == -1: print "error: unknown content type" elif c == 0: print "error: no content type" elif c == 1: enc = "application/x-www-form-urlencoded" if len(parms) > 0: p = ["%s=%s" % (p.getName(), p.getValue()) for p in parms] postData = "%s" % ("&".join(p)) elif c == 2: enc = "multipart/form-data" if len(parms) > 0: p = ["%s=%s" % (p.getName(), p.getValue()) for p in parms] postData = "%s" % ("&".join(p)) elif c == 3: enc = "text/xml" elif c == 4: enc = "application/json" elif c == 5: p = ["%s:%s" % (p.getName(), p.getValue()) for p in parms] enc = "application/x-amf" base = """ <!-- betterXSS PoC - generated with love by thatpentestguy --> <script> function sendRequest(method, url, enc, postData) { var req = createXMLHTTPObject(); if (!req) return; req.open(method,url,true); if (typeof enc !== 'undefined'){ req.setRequestHeader('Content-type', enc) } req.onreadystatechange = function () { if (req.readyState != 4) return; if (req.status != 200 && req.status != 304) { return; } } if (req.readyState == 4) return; (typeof postData === 'undefined') ? req.send() : req.send(postData); } var XMLHttpFactories = [ function () {return new XMLHttpRequest()}, function () {return new ActiveXObject("Msxml2.XMLHTTP")}, function () {return new ActiveXObject("Msxml3.XMLHTTP")}, function () {return new ActiveXObject("Microsoft.XMLHTTP")} ]; function createXMLHTTPObject() { var xmlhttp = false; for (var i=0;i<XMLHttpFactories.length;i++) { try { xmlhttp = XMLHttpFactories[i](); } catch (e) { continue; } break; } return xmlhttp; }""" if 1 <= c <= 5: base = base + "sendRequest('%s','%s','%s','%s');" % (method, url, enc, postData) else: base = base + "sendRequest('%s','%s');" % (method, url) base = base + "\n</script>" s = StringSelection(base) Toolkit.getDefaultToolkit().getSystemClipboard().setContents(s, s) # put string on clipboard print (base) def actionPerformed(self, actionEvent): self._build() def registerExtenderCallbacks(self, callbacks): self._helpers = callbacks.getHelpers() callbacks.setExtensionName("betterXSS") callbacks.registerContextMenuFactory(self) self.mCallBacks = callbacks print ("betterXSS successfully loaded") return def createMenuItems(self, ctxMenuInvocation): self.ctxMenuInvocation = ctxMenuInvocation return [self.menuItem]
def registerExtenderCallbacks(self, callbacks): self._panel = JPanel() self._panel.setLayout(BorderLayout()) #self._panel.setSize(400,400) # sourrounding try\except because Burp is not giving enough info try: # creating all the UI elements # create the split pane self._split_pane_horizontal = JSplitPane( JSplitPane.HORIZONTAL_SPLIT) self._split_panel_vertical = JSplitPane(JSplitPane.VERTICAL_SPLIT) # create panels self._panel_top = JPanel() self._panel_top.setLayout(BorderLayout()) self._panel_bottom = JPanel() self._panel_bottom.setLayout(BorderLayout()) self._panel_right = JPanel() self._panel_right.setLayout(BorderLayout()) self._panel_request = JPanel() self._panel_request.setLayout(BorderLayout()) self._panel_response = JPanel() self._panel_response.setLayout(BorderLayout()) # create the tabbed pane used to show request\response self._tabbed_pane = JTabbedPane(JTabbedPane.TOP) # create the tabbed pane used to show aslan++\concretization file self._tabbed_pane_editor = JTabbedPane(JTabbedPane.TOP) # create the bottom command for selecting the SQL file and # generating the model self._button_generate = JButton( 'Generate!', actionPerformed=self._generate_model) self._button_save = JButton('Save', actionPerformed=self._save_model) self._button_select_sql = JButton( 'Select SQL', actionPerformed=self._select_sql_file) self._text_field_sql_file = JTextField(20) self._panel_bottom_commands = JPanel() layout = GroupLayout(self._panel_bottom_commands) layout.setAutoCreateGaps(True) layout.setAutoCreateContainerGaps(True) seq_layout = layout.createSequentialGroup() seq_layout.addComponent(self._text_field_sql_file) seq_layout.addComponent(self._button_select_sql) seq_layout.addComponent(self._button_generate) seq_layout.addComponent(self._button_save) layout.setHorizontalGroup(seq_layout) # create the message editors that will be used to show request and response self._message_editor_request = callbacks.createMessageEditor( None, True) self._message_editor_response = callbacks.createMessageEditor( None, True) # create the table that will be used to show the messages selected for # the translation self._columns_names = ('Host', 'Method', 'URL') dataModel = NonEditableModel(self._table_data, self._columns_names) self._table = JTable(dataModel) self._scrollPane = JScrollPane() self._scrollPane.getViewport().setView((self._table)) popmenu = JPopupMenu() delete_item = JMenuItem("Delete") delete_item.addActionListener(self) popmenu.add(delete_item) self._table.setComponentPopupMenu(popmenu) self._table.addMouseListener(self) # add all the elements self._panel_request.add( self._message_editor_request.getComponent()) self._panel_response.add( self._message_editor_response.getComponent()) self._tabbed_pane.addTab("Request", self._panel_request) self._tabbed_pane.addTab("Response", self._panel_response) self._panel_top.add(self._scrollPane, BorderLayout.CENTER) self._panel_bottom.add(self._tabbed_pane, BorderLayout.CENTER) scroll = JScrollPane(self._panel_bottom) self._panel_right.add(self._tabbed_pane_editor, BorderLayout.CENTER) self._panel_right.add(self._panel_bottom_commands, BorderLayout.PAGE_END) self._split_panel_vertical.setTopComponent(self._panel_top) self._split_panel_vertical.setBottomComponent(scroll) self._split_pane_horizontal.setLeftComponent( self._split_panel_vertical) self._split_pane_horizontal.setRightComponent(self._panel_right) self._panel.addComponentListener(self) self._panel.add(self._split_pane_horizontal) self._callbacks = callbacks callbacks.setExtensionName("WAFEx") callbacks.addSuiteTab(self) callbacks.registerContextMenuFactory(self) except Exception as e: exc_type, exc_obj, exc_tb = sys.exc_info() fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1] print(exc_type, fname, exc_tb.tb_lineno)
def __init__(self, windowManager, commandConsoleFactory, subject, windowTitle): self._windowManager = windowManager self.onCloseRequestListener = None # EDIT MENU transferActionListener = _TransferActionListener() editMenu = JMenu( 'Edit' ) if Platform.getPlatform() is Platform.MAC: command_key_mask = ActionEvent.META_MASK else: command_key_mask = ActionEvent.CTRL_MASK; self.__editUndoItem = JMenuItem( 'Undo' ) undoAction = _action( 'undo', self.__onUndo ) self.__editUndoItem.setActionCommand( undoAction.getValue( Action.NAME ) ) self.__editUndoItem.addActionListener( undoAction ) self.__editUndoItem.setAccelerator( KeyStroke.getKeyStroke( KeyEvent.VK_Z, command_key_mask ) ) self.__editUndoItem.setMnemonic( KeyEvent.VK_U ) editMenu.add( self.__editUndoItem ) self.__editRedoItem = JMenuItem( 'Redo' ) redoAction = _action( 'redo', self.__onRedo ) self.__editRedoItem.setActionCommand( redoAction.getValue( Action.NAME ) ) self.__editRedoItem.addActionListener( redoAction ) self.__editRedoItem.setAccelerator( KeyStroke.getKeyStroke( KeyEvent.VK_Y, command_key_mask ) ) self.__editRedoItem.setMnemonic( KeyEvent.VK_R ) editMenu.add( self.__editRedoItem ) editMenu.addSeparator() editCutItem = JMenuItem( 'Cut' ) editCutItem.setActionCommand( TransferHandler.getCutAction().getValue( Action.NAME ) ) editCutItem.addActionListener( transferActionListener ) editCutItem.setAccelerator( KeyStroke.getKeyStroke( KeyEvent.VK_X, command_key_mask ) ) editCutItem.setMnemonic( KeyEvent.VK_T ) editMenu.add( editCutItem ) editCopyItem = JMenuItem( 'Copy' ) editCopyItem.setActionCommand( TransferHandler.getCopyAction().getValue( Action.NAME ) ) editCopyItem.addActionListener( transferActionListener ) editCopyItem.setAccelerator( KeyStroke.getKeyStroke( KeyEvent.VK_C, command_key_mask ) ) editCopyItem.setMnemonic( KeyEvent.VK_C ) editMenu.add( editCopyItem ) editPasteItem = JMenuItem( 'Paste' ) editPasteItem.setActionCommand( TransferHandler.getPasteAction().getValue( Action.NAME ) ) editPasteItem.addActionListener( transferActionListener ) editPasteItem.setAccelerator( KeyStroke.getKeyStroke( KeyEvent.VK_V, command_key_mask ) ) editPasteItem.setMnemonic( KeyEvent.VK_P ) editMenu.add( editPasteItem ) editMenu.addSeparator() self.__showUndoHistoryItem = JMenuItem( 'Show undo history' ) self.__showUndoHistoryItem.addActionListener( _action( 'Show undo history', self.__onShowUndoHistory ) ) editMenu.add( self.__showUndoHistoryItem ) # HELP MENU helpMenu = JMenu( 'Help' ) helpToggleTooltipHighlightsItem = JMenuItem( 'Toggle tooltip highlights' ) toggleTooltipHighlightsAction = _action( 'Toggle tooltip highlights', self.__onToggleTooltipHighlights ) helpToggleTooltipHighlightsItem.setActionCommand( toggleTooltipHighlightsAction.getValue( Action.NAME ) ) helpToggleTooltipHighlightsItem.addActionListener( toggleTooltipHighlightsAction ) helpToggleTooltipHighlightsItem.setAccelerator( KeyStroke.getKeyStroke( KeyEvent.VK_F2, 0 ) ) helpMenu.add( helpToggleTooltipHighlightsItem ) helpMenu.add( _action( 'Show all tip boxes', self.__onShowAllTipBoxes ) ) # MENU BAR menuBar = JMenuBar() menuBar.add( editMenu ) menuBar.add( helpMenu ) # BROWSER # Initialise here, as the browser listener may invoke methods upon the browser's creation class _BrowserListener (TabbedBrowser.TabbedBrowserListener): def createNewBrowserWindow(_self, subject): self._onOpenNewWindow( subject ) def onTabbledBrowserChangePage(_self, browser): pass def inspectFragment(fragment, sourceElement, triggeringEvent): return self._windowManager.world.inspectFragment( fragment, sourceElement, triggeringEvent ) def onChangeHistoryChanged(history): self.__refreshChangeHistoryControls( history ) self._browser = TabbedBrowser( self._windowManager.world.rootSubject, subject, inspectFragment, _BrowserListener(), commandConsoleFactory ) self._browser.getComponent().setPreferredSize( Dimension( 800, 600 ) ) changeHistory = self._browser.getChangeHistory() self._browser.getChangeHistory().addChangeHistoryListener(onChangeHistoryChanged) # MAIN PANEL windowPanel = JPanel() windowPanel.setLayout( BoxLayout( windowPanel, BoxLayout.Y_AXIS ) ) windowPanel.add( self._browser.getComponent() ) # WINDOW class _WindowLister (WindowListener): def windowActivated(listenerSelf, event): pass def windowClosed(listenerSelf, event): pass def windowClosing(listenerSelf, event): if self.onCloseRequestListener is not None: self.onCloseRequestListener( self ) def windowDeactivated(listenerSelf, event): pass def windowDeiconified(listenerSelf, event): pass def windowIconified(listenerSelf, event): pass def windowOpened(listenerSelf, event): pass self.__frame = JFrame( windowTitle ) self.__frame.setJMenuBar( menuBar ) self.__frame.add( windowPanel ) self.__frame.addWindowListener( _WindowLister() ) self.__frame.setDefaultCloseOperation( JFrame.DO_NOTHING_ON_CLOSE ) self.__frame.pack() # Cause command history controls to refresh self.__refreshChangeHistoryControls( None )
class BurpExtender(IBurpExtender, IContextMenuFactory, ActionListener): #List of BLACKLISTed HTTP headers, feel free to edit :) BLACKLIST = ['Content-Length', 'Host', 'Cookie', 'User-Agent', 'Referer', 'Accept-Encoding', 'Accept-Language', 'Connection', 'Accept', 'Pragma', 'Cache-Control', 'Proxy-Connection'] OPTS = {} def __init__(self): self.fMap = { IRequestInfo.CONTENT_TYPE_URL_ENCODED : self.handleURLEncoded, IRequestInfo.CONTENT_TYPE_JSON : self.handleJSON, IRequestInfo.CONTENT_TYPE_XML: self.handleXML, IRequestInfo.CONTENT_TYPE_NONE : self.handleNone, IRequestInfo.CONTENT_TYPE_UNKNOWN : self.handleNone } self.menuItem = JMenuItem('curlit') self.menuItem.addActionListener(self) def _build(self): #Grab first selected message, bail if none iRequestInfo = self._helpers.analyzeRequest(self.ctxMenuInvocation.getSelectedMessages()[0]) self.body = ''.join(map(chr, self.ctxMenuInvocation.getSelectedMessages()[0].getRequest())).split('\r\n\r\n')[1] if iRequestInfo is None: return #Build payload - add your static flags here, like -s or -i payload = ('curl -isk ') # % (msg.getUrl())) #Turn all headers into dictionary, remove BLACKLISTed ones headers = dict(item.split(': ') for item in iRequestInfo.getHeaders()[1:]) headers = dict( (k,v) for k, v in headers.iteritems() if k not in self.BLACKLIST ) #print('Whitelisted Headers:\n\t' + '\n\t'.join(headers)) #om nom cookies cookies = [c for c in iRequestInfo.getParameters() if c.getType() == IParameter.PARAM_COOKIE] #print('Found Cookies:\n\t' + '\n\t'.join([('%s=%s' % (c.getName(), c.getValue())) for c in cookies])) #print('DEBUG: Dumping All Parms') #for p in iRequestInfo.getParameters(): print ('\t%s : %s - %d' % (p.getName(), p.getValue(), p.getType())) #Set other command line args self.OPTS['-X'] = iRequestInfo.getMethod() self.OPTS['-b'] = '; '.join([('%s=%s' % (c.getName(), c.getValue())) for c in cookies]) #Add all the headers to the payload for k,v in headers.iteritems(): payload += '-H \'%s: %s\' \\\n' % (k, v) #Invoke handlers to handle content type #print('content type: ' + str(iRequestInfo.getContentType())) reqType = iRequestInfo.getContentType() #print("Content Type Found: %d" % reqType) if reqType in self.fMap: #print('Invoking %s' % self.fMap[reqType].func_name) self.fMap[reqType](iRequestInfo) #Add all the OPTS to the payload for k,v, in self.OPTS.iteritems(): payload += ('%s \'%s\' \\\n' % (k, v)) #Append URL to end of payload payload += '"%s"' % iRequestInfo.getUrl().toString() #Nasty - invocation of some java code to get the string on the clipboard s = StringSelection(payload) Toolkit.getDefaultToolkit().getSystemClipboard().setContents(s,s) #put string on clipboard print(payload) #print string self.OPTS = {} def actionPerformed(self, actionEvent): self._build() def handleXML(self, requestInfo): self.OPTS['-d'] = ''.join([line.strip() for line in xml.dom.minidom.parseString(self.body).toprettyxml().split('\n')]) pass def handleJSON(self, requestInfo): #No point in using the parameter objects, should just shove the body in #Ghetto format by loading string then dumping #THIS SHOULD WORK BUT JYTHON DOESNT HAVE THE DAMN JSON MODULE self.OPTS['-d'] = json.dumps(json.loads(self.body)) def handleNone(self, requestInfo): if len(self.body) > 0: self.OPTS['-d'] = self.body def handleMultiPart(): pass def handleAMF(): pass def handleURLEncoded(self, requestInfo): self.OPTS['-d'] = '&'.join( [('%s=%s' % (p.getName(), p.getValue())) for p in requestInfo.getParameters() if p.getType() == IParameter.PARAM_BODY]) def registerExtenderCallbacks(self, callbacks): self._helpers = callbacks.getHelpers() callbacks.setExtensionName('curlit') callbacks.registerContextMenuFactory(self) self.mCallBacks = callbacks print('curlit up') return def createMenuItems(self, ctxMenuInvocation): self.ctxMenuInvocation = ctxMenuInvocation return [self.menuItem]
class BurpExtender(IBurpExtender, IScannerListener, IContextMenuFactory, ActionListener, IMessageEditorController, ITab, ITextEditor, IHttpService, IScanIssue, IHttpRequestResponseWithMarkers): def __init__(self): self.menuItem = JMenuItem('send to manualReporter') 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("Manual Reporter") callbacks.registerContextMenuFactory(self) self._callbacks.registerScannerListener(self) print "[+] Manual Reporter Extension Loaded!" print "[-] by SEDZ - 2016" # create report file csv self.createReport() self.masterFindingsList = [] ####### ------- NEW ------- ####### def getSelectedScanIssues(self): issues = self.ctxMenuInvocation.getSelectedIssues() # parses currently selected finding to a string if len(issues) >= 1 : # one or more issues can be sent (cmd select for example within target...) for self.m in issues: #print self.m # burp.sfg@3b784b06 # type <type 'burp.sfg'> # add requestResponseWithMarkers to be global so can be included in scanIssue requestResponse = self.m.getHttpMessages() #print "RequestResponse: ", requestResponse # returns l = array.tolist(requestResponse) #print l #print l[0] # if there is more than one request response to a finding... if len(l) > 1: k = len(l) q = 1 for r in l: #call functionality to handle issues self.processRequest(r, q, k) q = q + 1 elif len(l) == 1: k = "" q = "" #call functionality to handle issues self.processRequest(l[0], q, k) else: # bug: some issues do not have request responses. k = "" q = "" #call functionality to handle issues self.processRequestWithoutRR(q, k) def processRequest(self, requestResponse, multipartOne, MulitpartTwo): r = requestResponse # get request data and convert to string requestDetail = r.getRequest() fName = self.m.getIssueName() # retrive issue name print "[+] Finding Name: ", self.m.getIssueName() url = self._helpers.analyzeRequest(r).getUrl() print "[+] Finding sent to report: [%s] " % str(url) # GET request details & Markers requestMarkers = r.getRequestMarkers() reqMarkersParsed = self.parseMarkers(requestMarkers) requestData = self._helpers.bytesToString(requestDetail) # converts & Prints out the entire request as string # GET response details & Markers responseDetail = r.getResponse() responseMarkers = r.getResponseMarkers() resMarkersParsed = self.parseMarkers(responseMarkers) responseData = self._helpers.bytesToString(responseDetail) # converts & Prints out the entire request as string # base64 encode requestresponses: enRequest = requestData.encode('base64','strict') enResponse = responseData.encode('base64','strict') # Handles issues with more than on request and response to the issue eg: 1/2, 2/2 multipart = str(multipartOne) + "/" + str(MulitpartTwo) Cbuffer = "" # prepare to write out to file finding = [fName, url, enRequest, reqMarkersParsed, enResponse, resMarkersParsed, multipart, Cbuffer] # write out to file self.report(finding) if multipartOne != "" : print "[!] Part %s added to report" % multipart else: print "[!] Finding added to report." def processRequestWithoutRR(self, multipartOne, MulitpartTwo): fName = self.m.getIssueName() # retrive issue name print "[+] Finding Name: ", self.m.getIssueName() url = self.m.getUrl() print "[+] Finding sent to report: [%s] " % str(url).encode('utf-8') requestData = self.m.getIssueDetail() # converts & Prints out the entire request as string # certifcates if requestData is not None: # removes html as the scanissue is all in html cleaner = re.compile('<.*?>') cleanReqData = re.sub(cleaner, '\n', requestData) cleanRequestData = cleanReqData.replace(' ','') # this could still be tidied to produce better output. # handle none unicode cleanRequestData = cleanRequestData.encode('utf-8') # base64 encode requestresponses: enRequest = cleanRequestData.encode('base64','strict') else: enRequest = None # Handles issues with more than on request and response to the issue eg: 1/2, 2/2 multipart = str(multipartOne) + "/" + str(MulitpartTwo) Cbuffer = "" # prepare to write out to file finding = [fName, url, enRequest, "", "", "", multipart, Cbuffer] # write out to file self.report(finding) if multipartOne != "" : print "[!] Part %s added to report" % multipart else: print "[!] Finding added to report." # takes an array of markers and cycles through them to collect the int coordinates. def parseMarkers(self, markers): markersOut = [] c = 0 if len(markers) >= 1: for i in range(0, len(markers)): c = c + 1 #print "[+] Marker Pair %s:" % str(c) start = markers[i][0] #print "[+] start: ", start end = markers[i][1] #print "[+] end: ", end setM = [c,start,end] markersOut.append(setM) return markersOut def report(self, finding): f = open(self.c, "a") report = csv.writer(f) report.writerow(finding) f.close() def createReport(self): # Until I work out a different way specify a path for the report here # uncomment to find out the path of the outfile path = os.getcwd() # potential for date to add in to the name... outfile = "Burp_Findings_Report.csv" print "[+] Report Location:", str(path)+"/"+outfile report = str(path)+"/"+outfile self.c = report #clear report c = open(self.c, "w") c.close() return self.c # API hook... def getHttpMessages(self): return [self.m] # Actions on menu click... def actionPerformed(self, actionEvent): print "*" * 60 try: # When clicked!! self.getSelectedScanIssues() except: tb = traceback.format_exc() print tb # create Menu def createMenuItems(self, ctxMenuInvocation): self.ctxMenuInvocation = ctxMenuInvocation return [self.menuItem]