Ejemplo n.º 1
0
class BurpExtender(IBurpExtender, ITab, IHttpListener,
                   IMessageEditorController, AbstractTableModel,
                   IContextMenuFactory):
    def registerExtenderCallbacks(self, callbacks):
        # smart xss feature (print conclusion and observation)
        # mark resulsts
        # add automatic check pages in the same domain

        self.tagPayloads = [
            "<b>test", "<b onmouseover=test()>test",
            "<img src=err onerror=test()>", "<script>test</script>"
            "", "<scr ipt>test</scr ipt>", "<SCRIPT>test;</SCRIPT>",
            "<scri<script>pt>test;</scr</script>ipt>",
            "<SCRI<script>PT>test;</SCR</script>IPT>",
            "<scri<scr<script>ipt>pt>test;</scr</sc</script>ript>ipt>",
            "<IMG \"\"\"><SCRIPT>test</SCRIPT>\">",
            "<IMG '''><SCRIPT>test</SCRIPT>'>", "<SCR%00IPT>test</SCR%00IPT>",
            "<IFRAME SRC='f' onerror=\"test\"></IFRAME>",
            "<IFRAME SRC='f' onerror='test'></IFRAME>",
            "<<SCRIPT>test//<</SCRIPT>", "<img src=\"1\" onerror=\"test\">",
            "<img src='1' onerror='test'",
            "<STYLE TYPE=\"text/javascript\">test;</STYLE>",
            "<<SCRIPT>test//<</SCRIPT>"
        ]
        self.attributePayloads = [
            "\"\"\"><SCRIPT>test", "'''><SCRIPT>test'",
            "\"><script>test</script>", "\"><script>test</script><\"",
            "'><script>test</script>", "'><script>test</script><'",
            "\";test;\"", "';test;'", ";test;", "\";test;//",
            "\"onmouseover=test ", "onerror=\"test\"", "onerror='test'",
            "onload=\"test\"", "onload='test'"
        ]
        self.xssKey = 'xssme'
        # 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("XSSor")

        self.affectedResponses = ArrayList()
        self._log = ArrayList()
        self._lock = Lock()

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

        # table of log entries
        logTable = Table(self)
        scrollPane = JScrollPane(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())

        clearAPListBtn = JButton("Clear List",
                                 actionPerformed=self.clearAPList)
        clearAPListBtn.setBounds(10, 85, 120, 30)
        apListLabel = JLabel('Affected Pages List:')
        apListLabel.setBounds(10, 10, 140, 30)
        self.affectedModel = DefaultListModel()
        self.affectedList = JList(self.affectedModel)
        self.affectedList.addListSelectionListener(listSelectedChange(self))
        scrollAList = JScrollPane(self.affectedList)
        scrollAList.setVerticalScrollBarPolicy(
            JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED)
        scrollAList.setBounds(150, 10, 550, 200)
        scrollAList.setBorder(LineBorder(Color.BLACK))

        APtabs = JTabbedPane()
        self._requestAPViewer = callbacks.createMessageEditor(self, False)
        self._responseAPViewer = callbacks.createMessageEditor(self, False)
        APtabs.addTab("Request", self._requestAPViewer.getComponent())
        APtabs.addTab("Affeced Page Response",
                      self._responseAPViewer.getComponent())
        APtabs.setBounds(0, 250, 700, 350)
        APtabs.setSelectedIndex(1)

        self.APpnl = JPanel()
        self.APpnl.setBounds(0, 0, 1000, 1000)
        self.APpnl.setLayout(None)
        self.APpnl.add(scrollAList)
        self.APpnl.add(clearAPListBtn)
        self.APpnl.add(APtabs)
        self.APpnl.add(apListLabel)
        tabs.addTab("Affected Pages", self.APpnl)
        self.intercept = 0

        ## init conf panel
        startLabel = JLabel("Plugin status:")
        startLabel.setBounds(10, 10, 140, 30)

        payloadLabel = JLabel("Basic Payload:")
        payloadLabel.setBounds(10, 50, 140, 30)

        self.basicPayload = "<script>alert(1)</script>"
        self.basicPayloadTxt = JTextArea(self.basicPayload, 5, 30)
        self.basicPayloadTxt.setBounds(120, 50, 305, 30)

        self.bruteForceMode = JCheckBox("Brute Force Mode")
        self.bruteForceMode.setBounds(120, 80, 300, 30)
        self.bruteForceMode.addItemListener(handleBFModeChange(self))

        self.tagPayloadsCheck = JCheckBox("Tag paylods")
        self.tagPayloadsCheck.setBounds(120, 100, 300, 30)
        self.tagPayloadsCheck.setSelected(True)
        self.tagPayloadsCheck.setEnabled(False)
        self.tagPayloadsCheck.addItemListener(handleBFModeList(self))

        self.attributePayloadsCheck = JCheckBox("Attribute payloads")
        self.attributePayloadsCheck.setBounds(260, 100, 300, 30)
        self.attributePayloadsCheck.setSelected(True)
        self.attributePayloadsCheck.setEnabled(False)
        self.attributePayloadsCheck.addItemListener(handleBFModeList(self))

        payloadListLabel = JLabel("Payloads list (for BF mode):")
        payloadListLabel.setBounds(10, 130, 140, 30)

        self.payloadsModel = DefaultListModel()
        self.payloadsList = JList(self.payloadsModel)
        scrollPayloadsList = JScrollPane(self.payloadsList)
        scrollPayloadsList.setVerticalScrollBarPolicy(
            JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED)
        scrollPayloadsList.setBounds(120, 170, 300, 200)
        scrollPayloadsList.setBorder(LineBorder(
            Color.BLACK))  # add buttons to remove payloads and add

        for payload in self.tagPayloads:
            self.payloadsModel.addElement(payload)

        for payload in self.attributePayloads:
            self.payloadsModel.addElement(payload)

        self.startButton = JButton("XSSor is off",
                                   actionPerformed=self.startOrStop)
        self.startButton.setBounds(120, 10, 120, 30)
        self.startButton.setBackground(Color(255, 100, 91, 255))

        consoleTab = JTabbedPane()
        self.consoleLog = JTextArea("", 5, 30)
        scrollLog = JScrollPane(self.consoleLog)
        scrollLog.setVerticalScrollBarPolicy(
            JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED)
        scrollLog.setBounds(120, 170, 550, 200)
        scrollLog.setBorder(LineBorder(Color.BLACK))
        scrollLog.getVerticalScrollBar().addAdjustmentListener(
            autoScrollListener(self))
        consoleTab.addTab("Console", scrollLog)
        consoleTab.setBounds(0, 400, 500, 200)

        self.pnl = JPanel()
        self.pnl.setBounds(0, 0, 1000, 1000)
        self.pnl.setLayout(None)
        self.pnl.add(self.startButton)
        self.pnl.add(startLabel)
        self.pnl.add(payloadLabel)
        self.pnl.add(self.basicPayloadTxt)
        self.pnl.add(self.bruteForceMode)
        self.pnl.add(payloadListLabel)
        self.pnl.add(scrollPayloadsList)
        self.pnl.add(self.attributePayloadsCheck)
        self.pnl.add(self.tagPayloadsCheck)
        self.pnl.add(consoleTab)

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

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

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

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

        print "Thank you for installing XSSor v0.1 extension"
        print "Created by Barak Tawily"
        print "\nGithub:\nhttps://github.com/Quitten/XSSor"
        return

    #
    # implement ITab
    #

    def getTabCaption(self):
        return "XSSor"

    def getUiComponent(self):
        return self._splitpane

    #
    # implement IHttpListener
    #

    def processHttpMessage(self, toolFlag, messageIsRequest, messageInfo):
        if self.intercept == 1:
            if toolFlag == 4:
                # only process requests
                if not messageIsRequest:
                    self.checkForKey(messageInfo)

        return

    def printLog(self, message):
        self.consoleLog.setText(self.consoleLog.getText() + '\r\n' + message)

    def checkXSS(self, messageInfo, urlStr, requestBody, currentPayload):
        self.printLog('trying exploit with the payload: ' + currentPayload)
        requestURL = URL(urlStr.replace(self.xssKey, currentPayload))
        requestBody = requestBody.replace(self.xssKey,
                                          urllib.pathname2url(currentPayload))
        httpService = self._helpers.buildHttpService(
            str(requestURL.getHost()), int(requestURL.getPort()),
            requestURL.getProtocol() == "https")
        response = self._callbacks.makeHttpRequest(httpService, requestBody)
        responseInfo = self._helpers.analyzeResponse(response.getResponse())
        analyzedResponse = self._helpers.bytesToString(response.getResponse(
        ))  # change body offeset + make ui for affeccted pages
        responseBody = analyzedResponse.encode('utf-8')
        vulnOrNot = 'no'

        if currentPayload in responseBody:
            self.printLog('payload: ' + currentPayload +
                          ' found to be vulnarble')
            vulnOrNot = 'yes'
            # mark the payload
        if not len(self.affectedResponses) == 0:
            for request in self.affectedResponses:  # bug in case of no response in messageinfo
                self.printLog('checking affeccted page' +
                              str(request.getUrl()))
                requestURL = request.getUrl()
                httpService = self._helpers.buildHttpService(
                    str(requestURL.getHost()), int(requestURL.getPort()),
                    requestURL.getProtocol() == "https")
                affectedPageResponse = self._callbacks.makeHttpRequest(
                    httpService, request.getRequest())
                analyzedResponse = self._helpers.bytesToString(
                    affectedPageResponse.getResponse())
                responseBody = analyzedResponse.encode('utf-8')

            if currentPayload in responseBody:
                vulnOrNot = 'yes, affected page'
                self.printLog('affeccted page has been found as vulnerable')

        self._lock.acquire()
        row = self._log.size()
        self._log.add(
            LogEntry(
                self._helpers.analyzeRequest(response).getUrl(),
                self._callbacks.saveBuffersToTempFiles(response),
                currentPayload, vulnOrNot))
        self.fireTableRowsInserted(row, row)
        self._lock.release()

    def checkForKey(self, messageInfo):

        currentPayload = self.tagPayloads[0]
        requestInfo = self._helpers.analyzeRequest(messageInfo)
        requestHeaders = list(requestInfo.getHeaders())

        requestURL = requestInfo.getUrl()
        urlStr = str(requestURL)
        self.printLog('checking for xss key in URL: ' + urlStr)
        requestBody = self._helpers.bytesToString(messageInfo.getRequest())
        requestBody = re.sub(
            'Referer:.*\n', '', requestBody, flags=re.MULTILINE,
            count=1)  # workaround avoid xsskey in the referer newHeaders
        if self.xssKey in urlStr or self.xssKey in requestBody:
            self.printLog('xss key has been found')
            if self.bruteForceMode.isSelected():
                for i in range(0, self.payloadsModel.getSize()):
                    payload = self.payloadsModel.getElementAt(i)
                    self.checkXSS(messageInfo, urlStr, requestBody, payload)
            else:
                self.checkXSS(messageInfo, urlStr, requestBody,
                              self.basicPayloadTxt.getText())

                #

    # extend AbstractTableModel
    #

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

    def getColumnCount(self):
        return 3

    def getColumnName(self, columnIndex):
        if columnIndex == 0:
            return "URL"
        if columnIndex == 1:
            return "Payload"
        if columnIndex == 2:
            return "Vulnerable?"

        return ""

    def getValueAt(self, rowIndex, columnIndex):
        logEntry = self._log.get(rowIndex)
        if columnIndex == 0:
            # return self._callbacks.getToolName(logEntry._tool)
            return logEntry._url.toString()

        if columnIndex == 1:
            return logEntry._payload

        if columnIndex == 2:
            return logEntry._vulnOrNot

        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()

    def startOrStop(self, event):
        if self.startButton.getText() == "XSSor is off":
            self.startButton.setText("XSSor is on")
            self.startButton.setBackground(Color.GREEN)
            self.printLog('on, waiting for key word to be found (' +
                          self.xssKey + ')')
            self.intercept = 1
        else:
            self.startButton.setText("XSSor is off")
            self.startButton.setBackground(Color(255, 100, 91, 255))
            self.intercept = 0

    def clearAPList(self, event):
        self.affectedModel.clear()
        self.affectedResponses = ArrayList()

    #
    # implement IContextMenuFactory
    #
    def createMenuItems(self, invocation):
        responses = invocation.getSelectedMessages()
        if responses > 0:
            ret = LinkedList()
            affectedMenuItem = JMenuItem("XSSor: Add affected page")
            affectedMenuItem.addActionListener(
                handleMenuItems(self, responses[0], "affected"))
            ret.add(affectedMenuItem)
            return (ret)
        return null

    def addAfectedPage(self, messageInfo):
        self.affectedModel.addElement(
            str(self._helpers.analyzeRequest(messageInfo).getUrl()))
        self.affectedResponses.add(messageInfo)
Ejemplo n.º 2
0
class BurpExtender(IBurpExtender, ITab, IHttpListener, IMessageEditorController, AbstractTableModel, IContextMenuFactory):

    def registerExtenderCallbacks(self, callbacks):
        # keep a reference to our callbacks object
        self._callbacks = callbacks
        # obtain an extension helpers object
        self._helpers = callbacks.getHelpers()
        
        # set our extension name
        callbacks.setExtensionName("Autorize")
        
        # create the log and a lock on which to synchronize when adding log entries
        self._log = ArrayList()
        self._lock = Lock()
        self._enfocementStatuses = ["Authorization bypass!","Authorization enforced??? (please configure enforcement detector)","Authorization enforced!"]
        self.intercept = 0

        self.initInterceptionFilters()

        self.initEnforcementDetector()

        self.initEnforcementDetectorUnauthorized()

        self.initExport()

        self.initConfigurationTab()

        self.initTabs()
        
        self.initCallbacks()

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

        self.logTable.setAutoCreateRowSorter(True)        

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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




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


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

    def getColumnCount(self):
        return 7

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

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

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

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

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

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


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

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


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

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

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

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

        return

    def sendRequestToAutorizeWork(self,messageInfo):

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


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

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

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

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

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

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

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

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

                auth_enforced = 1
                
                for filter in filters:

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

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

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

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

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

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

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

        return impression

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

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

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

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

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

    def getCookieFromMessage(self, messageInfo):
        headers = list(self._helpers.analyzeRequest(messageInfo.getRequest()).getHeaders())
        for header in headers:
            if "Cookie:" in header:
                return header
        return None
Ejemplo n.º 3
0
class BurpExtender(IBurpExtender, ITab, IHttpListener,
                   IMessageEditorController, AbstractTableModel,
                   IContextMenuFactory):
    def registerExtenderCallbacks(self, callbacks):
        # keep a reference to our callbacks object
        self._callbacks = callbacks
        # obtain an extension helpers object
        self._helpers = callbacks.getHelpers()

        # set our extension name
        callbacks.setExtensionName("Autorize")

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

        self.initInterceptionFilters()

        self.initEnforcementDetector()

        self.initExport()

        self.initConfigurationTab()

        self.initTabs()

        self.initCallbacks()

        print "Thank you for installing Autorize v0.9 extension"
        print "by Barak Tawily"
        return

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

        exportLType = JLabel("File Type:")
        exportLType.setBounds(10, 10, 100, 30)

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

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

        exportES = [
            "All Statuses", "Authorization bypass!",
            "Authorization enforced??? (please configure enforcement detector)",
            "Authorization enforced!"
        ]
        self.exportES = JComboBox(exportES)
        self.exportES.setBounds(100, 50, 200, 30)

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

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

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

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

        self.EDFP = ArrayList()
        self.EDCT = ArrayList()

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

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

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

        EDStrings = [
            "Finger Print: (enforced message body contains)",
            "Content-Length: (constant Content-Length number of enforced response)"
        ]
        self.EDType = JComboBox(EDStrings)
        self.EDType.setBounds(80, 10, 430, 30)

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

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

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

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

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

        IFStrings = [
            "URL Contains: ", "Scope items only: (Content is not required)"
        ]
        self.IFType = JComboBox(IFStrings)
        self.IFType.setBounds(80, 10, 430, 30)

        self.IFModel = DefaultListModel()
        self.IFList = JList(self.IFModel)
        self.IFList.setBounds(80, 175, 300, 110)
        self.IFList.setBorder(LineBorder(Color.BLACK))

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    def initTabs(self):
        #
        ##  init autorize tabs
        #

        self.logTable = Table(self)
        self._splitpane = JSplitPane(JSplitPane.HORIZONTAL_SPLIT)
        self._splitpane.setResizeWeight(1)
        self.scrollPane = JScrollPane(self.logTable)
        self._splitpane.setLeftComponent(self.scrollPane)
        self.scrollPane.getVerticalScrollBar().addAdjustmentListener(
            autoScrollListener(self))
        copyURLitem = JMenuItem("Copy URL")
        copyURLitem.addActionListener(copySelectedURL(self))
        self.menu = JPopupMenu("Popup")
        self.menu.add(copyURLitem)

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

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

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

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

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

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

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

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

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

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

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

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

    def clearList(self, event):
        self._lock.acquire()
        self._log = ArrayList()
        row = self._log.size()
        self.fireTableRowsInserted(row, row)
        self._lock.release()

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

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

        for i in range(0, self._log.size()):
            color = ""
            if self._log.get(
                    i
            )._enfocementStatus == "Authorization enforced??? (please configure enforcement detector)":
                color = "yellow"
            if self._log.get(i)._enfocementStatus == "Authorization bypass!":
                color = "red"
            if self._log.get(i)._enfocementStatus == "Authorization enforced!":
                color = "LawnGreen"

            if enforcementStatusFilter == "All Statuses":
                htmlContent += "<tr bgcolor=\"%s\"><td><a href=\"%s\">%s</a></td><td>%s</td></tr>" % (
                    color, self._log.get(i)._url, self._log.get(i)._url,
                    self._log.get(i)._enfocementStatus)
            else:
                if enforcementStatusFilter == self._log.get(
                        i)._enfocementStatus:
                    htmlContent += "<tr bgcolor=\"%s\"><td><a href=\"%s\">%s</a></td><td>%s</td></tr>" % (
                        color, self._log.get(i)._url, self._log.get(i)._url,
                        self._log.get(i)._enfocementStatus)

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

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

    #
    # implement ITab
    #
    def getTabCaption(self):
        return "Autorize"

    def getUiComponent(self):
        return self._splitpane

        #

    # extend AbstractTableModel
    #

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

    def getColumnCount(self):
        return 2

    def getColumnName(self, columnIndex):
        if columnIndex == 0:
            return "URL"
        if columnIndex == 1:
            return "Authorization Enforcement Status"
        return ""

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

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

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

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

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

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

            if not messageIsRequest:
                if not self.replaceString.getText(
                ) in self._helpers.analyzeRequest(messageInfo).getHeaders():
                    if self.ignore304.isSelected():
                        firstHeader = self._helpers.analyzeResponse(
                            messageInfo.getResponse()).getHeaders()[0]
                        if "304" in firstHeader or "204" in firstHeader:
                            return
                    if self.IFList.getModel().getSize() == 0:
                        self.checkAuthorization(
                            messageInfo,
                            self._helpers.analyzeResponse(
                                messageInfo.getResponse()).getHeaders())
                    else:
                        urlString = str(
                            self._helpers.analyzeRequest(messageInfo).getUrl())
                        for i in range(0, self.IFList.getModel().getSize()):
                            if self.IFList.getModel().getElementAt(i).split(
                                    ":")[0] == "Scope items only":
                                currentURL = URL(urlString)
                                if self._callbacks.isInScope(currentURL):
                                    self.checkAuthorization(
                                        messageInfo,
                                        self._helpers.analyzeResponse(
                                            messageInfo.getResponse()).
                                        getHeaders())
                            if self.IFList.getModel().getElementAt(i).split(
                                    ":")[0] == "URL Contains":
                                if self.IFList.getModel().getElementAt(
                                        i)[14:] in urlString:
                                    self.checkAuthorization(
                                        messageInfo,
                                        self._helpers.analyzeResponse(
                                            messageInfo.getResponse()).
                                        getHeaders())
        return

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

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

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

            headers.append(self.replaceString.getText())

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

    def checkAuthorization(self, messageInfo, originalHeaders):
        message = self.makeMessage(messageInfo, True)
        requestResponse = self.makeRequest(messageInfo, message)
        analyzedResponse = self._helpers.analyzeResponse(
            requestResponse.getResponse())

        oldStatusCode = originalHeaders[0]
        newStatusCode = analyzedResponse.getHeaders()[0]
        oldContentLen = self.getContentLength(originalHeaders)
        newContentLen = self.getContentLength(analyzedResponse.getHeaders())

        impression = ""

        EDFilters = self.EDModel.toArray()
        if oldStatusCode == newStatusCode:
            if oldContentLen == newContentLen:
                impression = "Authorization bypass!"
            else:
                impression = "Authorization enforced??? (please configure enforcement detector)"
                for filter in EDFilters:
                    if str(filter).startswith("Content-Length: "):
                        if newContentLen == filter:
                            impression = "Authorization enforced!"
                    if str(filter).startswith("Finger Print: "):
                        if filter[14:] in self._helpers.bytesToString(
                                requestResponse.getResponse()
                            [analyzedResponse.getBodyOffset():]):
                            impression = "Authorization enforced!"
        else:
            impression = "Authorization enforced!"

        self._lock.acquire()
        row = self._log.size()
        self._log.add(
            LogEntry(self._callbacks.saveBuffersToTempFiles(requestResponse),
                     self._helpers.analyzeRequest(requestResponse).getUrl(),
                     messageInfo,
                     impression))  # same requests not include again.
        self.fireTableRowsInserted(row, row)
        self._lock.release()

    def getContentLength(self, analyzedResponseHeaders):
        for header in analyzedResponseHeaders:
            if "Content-Length:" in header:
                return header
        return "null"

    def getCookieFromMessage(self, messageInfo):
        headers = list(
            self._helpers.analyzeRequest(
                messageInfo.getRequest()).getHeaders())
        for header in headers:
            if "Cookie:" in header:
                return header
        return None
Ejemplo n.º 4
0
class BurpExtender(IBurpExtender, ITab, IHttpListener,
                   IMessageEditorController, AbstractTableModel,
                   IContextMenuFactory):

    #
    # implement IBurpExtender
    #

    def registerExtenderCallbacks(self, callbacks):
        # PDB debugging: connect sys.stdout and sys.stderr to Burp
        # sys.stdout = callbacks.getStdout()
        # sys.stderr = callbacks.getStderr()

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

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

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

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

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

        # Configuration Tab
        self.initConfigTab()

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

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

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

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

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

        # initialize tabs
        self.initTabs()

        # Print thank you, contact info, etc
        print("Thank you for installing Burp To Do List")
        print("created by Chris Lockard")
        print("https://github.com/chrislockard/BurpToDoList")
        return

    #
    # implement ITab
    #

    def getTabCaption(self):
        return "To Do"

    def getUiComponent(self):
        return self._splitpane

    def initConfigTab(self):
        # Init configuration tab
        self.test = JLabel("Configuration")
        self.test.setBounds(10, 10, 140, 30)

        self.panel = JPanel()
        self.panel.setBounds(0, 0, 1000, 1000)
        self.panel.setLayout(None)
        self.panel.add(self.test)

    def initTabs(self):
        # Init ToDo List Tabs
        self.logTable = Table(self)

        tableWidth = self.logTable.getPreferredSize().width
        self.logTable.getColumn("Complete?").setPreferredWidth(
            Math.round(tableWidth / 10 * 1))
        self.logTable.getColumn("Section").setPreferredWidth(
            Math.round(tableWidth / 10 * 3))
        self.logTable.getColumn("Task").setPreferredWidth(
            Math.round(tableWidth / 10 * 3))
        self.logTable.getColumn("Notes").setPreferredWidth(
            Math.round(tableWidth / 10 * 3))

        self.tableSorter = TableRowSorter(self)
        self.logTable.setRowSorter(self.tableSorter)

        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))

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

    def getColumnCount(self):
        return 4

    def getColumnName(self, columnIndex):
        if columnIndex == 0:
            return "Complete?"
        if columnIndex == 1:
            return "Section"
        if columnIndex == 2:
            return "Task"
        if columnIndex == 3:
            return "Notes"
        return ""

    def getColumnClass(self, columnIndex):
        if columnIndex == 0:
            return checkbox
        if columnIndex == 1:
            return String
        if columnIndex == 2:
            return String
        if columnIndex == 3:
            return String
        return ""

    def getValueAt(self, rowIndex, columnIndex):
        logEntry = self._log.get(rowIndex)
        if columnIndex == 0:
            return self._callbacks.getToolName(logEntry._tool)
        if columnIndex == 1:
            return logEntry._url.toString()
        if columnIndex == 2:
            pass
        if columnIndex == 3:
            pass
        return ""
Ejemplo n.º 5
0
class BurpExtender(IBurpExtender, ITab, IHttpListener, IMessageEditorController, AbstractTableModel):
    
    #
    # implement IBurpExtender
    #
    
    def	registerExtenderCallbacks(self, callbacks):
    
        # keep a reference to our callbacks object
        self._callbacks = callbacks
        
        # obtain an extension helpers object
        self._helpers = callbacks.getHelpers()
        
        # set our extension name
        callbacks.setExtensionName("Otter")
        
        # create the log and a lock on which to synchronize when adding log entries
        self._log = ArrayList()
        self._lock = Lock()
       
        # main split pane for log entries and request/response viewing
        self._settingPanel = JPanel()
        self._logPane = JSplitPane(JSplitPane.VERTICAL_SPLIT)

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

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

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

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

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

        # tabs with request/response viewers
        logTabs = JTabbedPane()
        self._origRequestViewer = callbacks.createMessageEditor(self, False)
        self._origResponseViewer = callbacks.createMessageEditor(self, False)
        self._modRequestViewer = callbacks.createMessageEditor(self, False)
        self._modResponseViewer = callbacks.createMessageEditor(self, False)
        logTabs.addTab("Original Request", self._origRequestViewer.getComponent())
        logTabs.addTab("Original Response", self._origResponseViewer.getComponent())
        logTabs.addTab("Modified Request", self._modRequestViewer.getComponent())
        logTabs.addTab("Modified Response", self._modResponseViewer.getComponent())
        self._logPane.setRightComponent(logTabs)
        
        # top most tab interface that seperates log entries from settings
        maintabs = JTabbedPane()
        maintabs.addTab("Log Entries", self._logPane)
        maintabs.addTab("Settings", self._settingPanel)
        self._maintabs = maintabs
       
        # customize the UI components
        callbacks.customizeUiComponent(maintabs)
        
        # add the custom tab to Burp's UI
        callbacks.addSuiteTab(self)
        
        # register ourselves as an HTTP listener
        callbacks.registerHttpListener(self)
        
        return
        
    #
    # implement ITab
    #
    
    def getTabCaption(self):
        return "Otter"
    
    def getUiComponent(self):
        return self._maintabs
        
    #
    # implement IHttpListener
    #
    
    def processHttpMessage(self, toolFlag, messageIsRequest, messageInfo):
   
        # Only process responses that came from the proxy. This will
        # ignore request/responses made by Otter itself.
        if not messageIsRequest and toolFlag == self._callbacks.TOOL_PROXY:
            # create a new log entry with the message details
            row = self._log.size()

            # analyze and store information about the original request/response
            responseBytes = messageInfo.getResponse()
            requestBytes = messageInfo.getRequest()
            request = self._helpers.analyzeRequest(messageInfo)
            response = self._helpers.analyzeResponse(responseBytes)
            
            # ignore out-of-scope requests.
            if not self._callbacks.isInScope(request.getUrl()):
                return

            wasModified = False
            ms = self._matchString.getText()
            rs = self._replaceString.getText()
            mss = ms.split(",")
            rss = rs.split(",")
            if len(rss) != len(mss):
                mss = [""]
                
            for i,x in enumerate(mss):
                if x == "":
                    continue
                if self._isRegexp.isSelected():
                    if search(x, requestBytes):
                        requestBytes = sub(x, rss[i], requestBytes)
                        wasModified = True
                else:
                    if fromBytes(requestBytes).find(x) >= 0:
                        requestBytes = toBytes(replace(fromBytes(requestBytes), x, rss[i]))
                        wasModified = True

            # make a modified request to test for authorization issues
            entry = None
            if wasModified:
                modReqResp = self._callbacks.makeHttpRequest(messageInfo.getHttpService(), requestBytes)
                modRequestBytes = modReqResp.getRequest()
                modResponseBytes = modReqResp.getResponse()
                modResponse = self._helpers.analyzeResponse(modResponseBytes)
                orig = self._callbacks.saveBuffersToTempFiles(messageInfo)
                mod = self._callbacks.saveBuffersToTempFiles(modReqResp)
                entry = LogEntry(orig, mod, request.getUrl(), response.getStatusCode(), len(responseBytes), modResponse.getStatusCode(), len(modResponseBytes), wasModified)
            else:
                orig = self._callbacks.saveBuffersToTempFiles(messageInfo)
                entry = LogEntry(orig, None, request.getUrl(), response.getStatusCode(), len(responseBytes), "None", 0, wasModified)

            self._lock.acquire()
            self._log.add(entry)
            self.fireTableRowsInserted(row, row)
            self._lock.release()
        return

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

    def getColumnCount(self):
        return 6

    def getColumnName(self, columnIndex):
        if columnIndex == 0:
            return "URL"
        if columnIndex == 1:
            return "Request Modified?"
        if columnIndex == 2:
            return "Orig. Status"
        if columnIndex == 3:
            return "Orig. Length"
        if columnIndex == 4:
            return "Mod. Status"
        if columnIndex == 5:
            return "Mod. Length"
        return ""

    def getValueAt(self, rowIndex, columnIndex):
        logEntry = self._log.get(rowIndex)
        if columnIndex == 0:
            return logEntry._url.toString()
        if columnIndex == 1:
            return str(logEntry._wasModified)
        if columnIndex == 2:
            return str(logEntry._origStatus)
        if columnIndex == 3:
            return str(logEntry._origLength)
        if columnIndex == 4:
            return str(logEntry._modStatus)
        if columnIndex == 5:
            return str(logEntry._modLength)
        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()
Ejemplo n.º 6
0
class BurpExtender(IBurpExtender, ITab, IHttpListener, IMessageEditorController, AbstractTableModel, IContextMenuFactory, IHttpRequestResponseWithMarkers, ITextEditor):
	def registerExtenderCallbacks(self, callbacks):
		self._callbacks = callbacks
		#Initialize callbacks to be used later

		self._helpers = callbacks.getHelpers()
		callbacks.setExtensionName("Trishul")
		
		self._log = ArrayList()
		#_log used to store our outputs for a URL, which is retrieved later by the tool

		self._lock = Lock()
		#Lock is used for locking threads while updating logs in order such that no multiple updates happen at once
		
		self.intercept = 0

		self.FOUND = "Found"
		self.CHECK = "Possible! Check Manually"
		self.NOT_FOUND = "Not Found"
		#Static Values for output


		#Initialize GUI
		self.issuesTab()

		self.advisoryReqResp()

		self.configTab()

		self.tabsInit()

		self.definecallbacks()


		print("Thank You for Installing Trishul")

		return

	#
	#Initialize Issues Tab displaying the JTree
	#

	def issuesTab(self):
		self.root = DefaultMutableTreeNode('Issues')

		frame = JFrame("Issues Tree")

		self.tree = JTree(self.root)
		self.rowSelected = ''
		self.tree.addMouseListener(mouseclick(self))
		self.issuepanel = JScrollPane()
		self.issuepanel.setPreferredSize(Dimension(300,450))
		self.issuepanel.getViewport().setView((self.tree))
		frame.add(self.issuepanel,BorderLayout.CENTER)

	#
	#Adding Issues to Issues TreePath
	#
	def addIssues(self, branch, branchData=None):
		if branchData == None:
			branch.add(DefaultMutableTreeNode('No valid data'))
		else:
			for item in branchData:
				branch.add(DefaultMutableTreeNode(item))

	#
	#Initialize the Config Tab to modify tool settings
	#
	def configTab(self):
		Config = JLabel("Config")
		self.startButton = JToggleButton("Intercept Off", actionPerformed=self.startOrStop)
		self.startButton.setBounds(40, 30, 200, 30)

		self.autoScroll = JCheckBox("Auto Scroll")
		self.autoScroll.setBounds(40, 80, 200, 30)

		self.xsscheck = JCheckBox("Detect XSS")
		self.xsscheck.setSelected(True)
		self.xsscheck.setBounds(40, 110, 200, 30)
		
		self.sqlicheck = JCheckBox("Detect SQLi")
		self.sqlicheck.setSelected(True)
		self.sqlicheck.setBounds(40, 140, 200, 30)
		
		self.ssticheck = JCheckBox("Detect SSTI")
		self.ssticheck.setSelected(True)
		self.ssticheck.setBounds(40, 170, 200, 30)

		self.blindxss = JCheckBox("Blind XSS")
		self.blindxss.setBounds(40, 200, 200, 30)

		self.BlindXSSText = JTextArea("", 5, 30)

		scrollbxssText = JScrollPane(self.BlindXSSText)
		scrollbxssText.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED)
		scrollbxssText.setBounds(40, 250, 400, 110) 

		self.configtab = JPanel()
		self.configtab.setLayout(None)
		self.configtab.setBounds(0, 0, 300, 300)
		self.configtab.add(Config)
		self.configtab.add(self.startButton)
		self.configtab.add(self.autoScroll)
		self.configtab.add(self.xsscheck)
		self.configtab.add(self.sqlicheck)
		self.configtab.add(self.ssticheck)
		self.configtab.add(self.blindxss)
		self.configtab.add(scrollbxssText)

	#
	#Turn Intercept from Proxy on or off
	#
	def startOrStop(self, event):
		if self.startButton.getText() == "Intercept Off":
			self.startButton.setText("Intercept On")
			self.startButton.setSelected(True)
			self.intercept = 1
		else:
			self.startButton.setText("Intercept Off")
			self.startButton.setSelected(False)
			self.intercept = 0

	#
	#Intialize the Advisory, Request and Response Tabs
	#
	def advisoryReqResp(self):
		self.textfield = JEditorPane("text/html", "")
		self.kit = HTMLEditorKit()
		self.textfield.setEditorKit(self.kit)
		self.doc = self.textfield.getDocument()
		self.textfield.setEditable(0)
		self.advisorypanel = JScrollPane()
		self.advisorypanel.getVerticalScrollBar()
		self.advisorypanel.setPreferredSize(Dimension(300,450))
		self.advisorypanel.getViewport().setView((self.textfield))

		self.selectedreq = []

		self._requestViewer = self._callbacks.createMessageEditor(self, False)
		self._responseViewer = self._callbacks.createMessageEditor(self, False)
		self._texteditor = self._callbacks.createTextEditor()
		self._texteditor.setEditable(False)

	#
	#Initialize Trishul Tabs
	#
	def tabsInit(self):
		self.logTable = Table(self)
		tableWidth = self.logTable.getPreferredSize().width
		self.logTable.getColumn("#").setPreferredWidth(Math.round(tableWidth / 50 * 0.1))
		self.logTable.getColumn("Method").setPreferredWidth(Math.round(tableWidth / 50 * 3))
		self.logTable.getColumn("URL").setPreferredWidth(Math.round(tableWidth / 50 * 40))
		self.logTable.getColumn("Parameters").setPreferredWidth(Math.round(tableWidth / 50 * 1))
		self.logTable.getColumn("XSS").setPreferredWidth(Math.round(tableWidth / 50 * 4))
		self.logTable.getColumn("SQLi").setPreferredWidth(Math.round(tableWidth / 50 * 4))
		self.logTable.getColumn("SSTI").setPreferredWidth(Math.round(tableWidth / 50 * 4))
		self.logTable.getColumn("Request Time").setPreferredWidth(Math.round(tableWidth / 50 * 4))

		self.tableSorter = TableRowSorter(self)
		self.logTable.setRowSorter(self.tableSorter)

		self._bottomsplit = JSplitPane(JSplitPane.HORIZONTAL_SPLIT)
		self._bottomsplit.setDividerLocation(500)
		
		self.issuetab = JTabbedPane()
		self.issuetab.addTab("Config",self.configtab)
		self.issuetab.addTab("Issues",self.issuepanel)
		self._bottomsplit.setLeftComponent(self.issuetab)

		self.tabs = JTabbedPane()
		self.tabs.addTab("Advisory",self.advisorypanel)
		self.tabs.addTab("Request", self._requestViewer.getComponent())
		self.tabs.addTab("Response", self._responseViewer.getComponent())
		self.tabs.addTab("Highlighted Response", self._texteditor.getComponent())
		self._bottomsplit.setRightComponent(self.tabs)
		
		self._splitpane = JSplitPane(JSplitPane.VERTICAL_SPLIT)
		self._splitpane.setDividerLocation(450)
		self._splitpane.setResizeWeight(1)
		self.scrollPane = JScrollPane(self.logTable)
		self._splitpane.setLeftComponent(self.scrollPane)
		self.scrollPane.getVerticalScrollBar().addAdjustmentListener(autoScrollListener(self))
		self._splitpane.setRightComponent(self._bottomsplit)

	#
	#Initialize burp callbacks
	#
	def definecallbacks(self):
		self._callbacks.registerHttpListener(self)
		self._callbacks.customizeUiComponent(self._splitpane)
		self._callbacks.customizeUiComponent(self.logTable)
		self._callbacks.customizeUiComponent(self.scrollPane)
		self._callbacks.customizeUiComponent(self._bottomsplit)
		self._callbacks.registerContextMenuFactory(self)
		self._callbacks.addSuiteTab(self)

	#
	#Menu Item to send Request to Trishul 
	#
	def createMenuItems(self, invocation):
		responses = invocation.getSelectedMessages()
		if responses > 0:
			ret = LinkedList()
			requestMenuItem = JMenuItem("Send request to Trishul")

			for response in responses:
				requestMenuItem.addActionListener(handleMenuItems(self,response, "request")) 
			ret.add(requestMenuItem)
			return ret
		return None

	#
	#Highlighting Response
	#
	def markHttpMessage( self, requestResponse, responseMarkString ):
		responseMarkers = None
		if responseMarkString:
			response = requestResponse.getResponse()
			responseMarkBytes = self._helpers.stringToBytes( responseMarkString )
			start = self._helpers.indexOf( response, responseMarkBytes, False, 0, len( response ) )
			if -1 < start:
				responseMarkers = [ array( 'i',[ start, start + len( responseMarkBytes ) ] ) ]

		requestHighlights = [array( 'i',[ 0, 5 ] )]
		return self._callbacks.applyMarkers( requestResponse, requestHighlights, responseMarkers )
	
	def getTabCaption(self):
		return "Trishul"

	def getUiComponent(self):
		return self._splitpane

	#
	#Table Model to display URL's and results based on the log size
	#
	def getRowCount(self):
		try:
			return self._log.size()
		except:
			return 0

	def getColumnCount(self):
		return 8

	def getColumnName(self, columnIndex):
		data = ['#','Method', 'URL', 'Parameters', 'XSS', 'SQLi', "SSTI", "Request Time"]
		try:
			return data[columnIndex]
		except IndexError:
			return ""

	def getColumnClass(self, columnIndex):
		data = [Integer, String, String, Integer, String, String, String, String]
		try:
			return data[columnIndex]
 		except IndexError:
			return ""

	#Get Data stored in log and display in the respective columns
	def getValueAt(self, rowIndex, columnIndex):
		logEntry = self._log.get(rowIndex)
		if columnIndex == 0:
			return rowIndex+1
		if columnIndex == 1:
			return logEntry._method
		if columnIndex == 2:
			return logEntry._url.toString()
		if columnIndex == 3:
			return len(logEntry._parameter)
		if columnIndex == 4:
			return logEntry._XSSStatus
		if columnIndex == 5:
			return logEntry._SQLiStatus
		if columnIndex == 6:
			return logEntry._SSTIStatus
		if columnIndex == 7:
			return logEntry._req_time
		return ""

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

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

	def getResponse(self):
		return self._currentlyDisplayedItem.getResponse()
	
	#For Intercepted requests perform tests in scope
	def processHttpMessage(self, toolFlag, messageIsRequest, messageInf):
		if self.intercept == 1:
			if toolFlag == self._callbacks.TOOL_PROXY:
				if not messageIsRequest:
					requestInfo = self._helpers.analyzeRequest(messageInf)
					requeststr = requestInfo.getUrl()
					parameters = requestInfo.getParameters()
					param_new = [p for p in parameters if p.getType() != 2]
					if len(param_new) != 0:
						if self._callbacks.isInScope(URL(str(requeststr))):
							start_new_thread(self.sendRequestToTrishul,(messageInf,))
		return

	#
	#Main processing of Trishul
	#
	def sendRequestToTrishul(self,messageInfo):
		request = messageInfo.getRequest()
		req_time = datetime.datetime.today()
		requestURL = self._helpers.analyzeRequest(messageInfo).getUrl()
		messageInfo = self._callbacks.makeHttpRequest(self._helpers.buildHttpService(str(requestURL.getHost()), int(requestURL.getPort()), requestURL.getProtocol() == "https"), request)
		resp_time = datetime.datetime.today()
		time_taken = (resp_time - req_time).total_seconds()
		response = messageInfo.getResponse()
		#initialozations of default value
		SQLiimp = self.NOT_FOUND
		SSTIimp = self.NOT_FOUND
		XSSimp = self.NOT_FOUND
		Comp_req = messageInfo
		requestInfo = self._helpers.analyzeRequest(messageInfo)
		self.content_resp = self._helpers.analyzeResponse(response)
		requestURL = requestInfo.getUrl()
		parameters = requestInfo.getParameters()
		requeststring = self._helpers.bytesToString(request)
		headers = requestInfo.getHeaders()
		#Used to obtain GET, POST and JSON parameters from burp api
		param_new = [p for p in parameters if p.getType() == 0 or p.getType() == 1 or p.getType() == 6]
		i = 0
		xssflag=0
		sqliflag=0
		sstiflag=0
		resultxss = []
		resultsqli = []
		resultssti = []
		xssreqresp = []
		sqlireqresp = []
		sstireqresp = []
		ssti_description = []
		sqli_description = []
		xss_description = []
		for i in range(len(param_new)):
			name =  param_new[i].getName()
			ptype =  param_new[i].getType()
			param_value = param_new[i].getValue()
			#check XSS if ticked
			if self.xsscheck.isSelected():
				score = 0
				flag1 = 0
				XSSimp = self.NOT_FOUND
				payload_array = ["<", ">", "\\\\'asd", "\\\\\"asd", "\\", "'\""]
				json_payload_array = ["<", ">", "\\\\'asd", "\\\"asd", "\\", "\'\\\""]
				payload_all = ""
				json_payload = ""
				rand_str = "testtest"
				for payload in payload_array:
					payload_all = payload_all+rand_str+payload
				payload_all = URLEncoder.encode(payload_all, "UTF-8")
				for payload in json_payload_array:
					json_payload = json_payload+rand_str+payload
				json_payload = URLEncoder.encode(json_payload, "UTF-8")
				if ptype == 0 or ptype == 1:
					new_paramters_value = self._helpers.buildParameter(name, payload_all, ptype)
					updated_request = self._helpers.updateParameter(request, new_paramters_value)
				else:
					jsonreq = re.search(r"\s([{\[].*?[}\]])$", requeststring).group(1)
					new = jsonreq.split(name+"\":",1)[1]
					if new.startswith('\"'):
						newjsonreq = jsonreq.replace(name+"\":\""+param_value,name+"\":\""+json_payload)
					else:
						newjsonreq = jsonreq.replace(name+"\":"+param_value,name+"\":\""+json_payload+"\"")
					updated_request = self._helpers.buildHttpMessage(headers, newjsonreq)

				attack = self.makeRequest(Comp_req, updated_request)
				response = attack.getResponse()
				response_str = self._helpers.bytesToString(response)
				xssreqresp.append(attack)
				if_found_payload = ""
				non_encoded_symbols = ""
				for check_payload in payload_array:
					if_found_payload = rand_str+check_payload
					if if_found_payload in response_str:
						non_encoded_symbols = non_encoded_symbols+"<br>"+check_payload.replace('<', '&lt;')
						score = score+1
						flag1 = 1
				if score > 2: XSSimp = self.CHECK
				if score > 3: XSSimp = self.FOUND
				xssflag = self.checkBetterScore(score,xssflag)
				if non_encoded_symbols == "   \\\\'asd":
					XSSimp = self.NOT_FOUND
				
				if non_encoded_symbols != '':
					xss_description.append("The Payload <b>" + payload_all.replace('<', '&lt;') + "</b> was passed in the request for the paramater <b>" + self._helpers.urlDecode(name) + "</b>. Some Tags were observed in the output unfiltered. A payload can be generated with the observed tags.<br>Symbols not encoded for parameter <b>" + name + "</b>: " + non_encoded_symbols)
				else:
					xss_description.append("")
			else:
				XSSimp = "Disabled"
			resultxss.append(XSSimp)

			if self.sqlicheck.isSelected():
				SQLiimp = self.NOT_FOUND
				score = 0
				value = "%27and%28select%2afrom%28select%28sleep%285%29%29%29a%29--"
				orig_time = datetime.datetime.today()
				if ptype == 0 or ptype == 1:
					new_paramters_value = self._helpers.buildParameter(name, value, ptype)
					updated_request = self._helpers.updateParameter(request, new_paramters_value)
				else:
					jsonreq = re.search(r"\s([{\[].*?[}\]])$", requeststring).group(1)
					new = jsonreq.split(name+"\":",1)[1]
					if new.startswith('\"'):
						newjsonreq = jsonreq.replace(name+"\":\""+param_value,name+"\":\""+value)
					else:
						newjsonreq = jsonreq.replace(name+"\":"+param_value,name+"\":\""+value+"\"")
					updated_request = self._helpers.buildHttpMessage(headers, newjsonreq)
				attack1 = self.makeRequest(Comp_req, updated_request)
				response1 = attack1.getResponse()
				new_time = datetime.datetime.today()
				response_str1 = self._helpers.bytesToString(response1)
				sqlireqresp.append(attack1)
				diff = (new_time - orig_time).total_seconds()
				if (diff - time_taken) > 3:
					score = 4
				
				self.error_array = ["check the manual that corresponds to your", "You have an error", "syntax error", "SQL syntax", "SQL statement", "ERROR:", "Error:", "MySQL","Warning:","mysql_fetch_array()"]
				found_text = ""
				for error in self.error_array:
					if error in response_str1:
						found_text = found_text + error
						score = score + 1
				if score > 1: SQLiimp = self.CHECK
				if score > 2: SQLiimp = self.FOUND
				sqliflag = self.checkBetterScore(score,sqliflag)

				if found_text != '':
					sqli_description.append("The payload <b>"+self._helpers.urlDecode(value)+"</b> was passed in the request for parameter <b>"+self._helpers.urlDecode(name)+"</b>. Some errors were generated in the response which confirms that there is an Error based SQLi. Please check the request and response for this parameter")
				elif (diff - time_taken) > 3:
					sqli_description.append("The payload <b>"+self._helpers.urlDecode(value)+"</b> was passed in the request for parameter <b>"+self._helpers.urlDecode(name)+"</b>. The response was in a delay of <b>"+str(diff)+"</b> seconds as compared to original <b>"+str(time_taken)+"</b> seconds. This indicates that there is a time based SQLi. Please check the request and response for this parameter")
				else:
					sqli_description.append("")
			else:
				SQLiimp = "Disabled"

			resultsqli.append(SQLiimp)

			if self.ssticheck.isSelected():
				score = 0
				SSTIimp = self.NOT_FOUND
				payload_array = ["${123*456}", "<%=123*567%>", "{{123*678}}"]
				json_payload_array = ["$\{123*456\}", "<%=123*567%>", "\{\{123*678\}\}"]
				payload_all = ""
				rand_str = "jjjjjjj"
				json_payload = ""
				for payload in payload_array:
					payload_all = payload_all+rand_str+payload
				for payload in json_payload_array:
					json_payload = json_payload+rand_str+payload
				payload_all = URLEncoder.encode(payload_all, "UTF-8")
				json_payload = URLEncoder.encode(json_payload, "UTF-8")
				if ptype == 0 or ptype == 1:
					new_paramters_value = self._helpers.buildParameter(name, payload_all, ptype)
					updated_request = self._helpers.updateParameter(request, new_paramters_value)
				else:
					jsonreq = re.search(r"\s([{\[].*?[}\]])$", requeststring).group(1)
					new = jsonreq.split(name+"\":",1)[1]
					if new.startswith('\"'):
						newjsonreq = jsonreq.replace(name+"\":\""+param_value,name+"\":\""+json_payload)
					else:
						newjsonreq = jsonreq.replace(name+"\":"+param_value,name+"\":\""+json_payload+"\"")
					updated_request = self._helpers.buildHttpMessage(headers, newjsonreq)
				
				attack = self.makeRequest(Comp_req, updated_request)
				response = attack.getResponse()
				response_str = self._helpers.bytesToString(response)
				self.expected_output = ["56088","69741","83394","3885","777777777777777"]
				for output in self.expected_output:
					if_found_payload = rand_str+output
					if if_found_payload in response_str:
						if output == self.expected_output[0]:
							sstireqresp.append(attack)
							ssti_description.append("Parameter <b>" + self._helpers.urlDecode(name) + "</b> is using <b>Java</b> Template<br>The value <b>" + payload_new + "</b> was passed which gave result as <b>56088</b>")
							score = 2
						if output == self.expected_output[1]:
							sstireqresp.append(attack)
							ssti_description.append("Parameter <b>" + self._helpers.urlDecode(name) + "</b> is using <b>Ruby</b> Template<br>The value <b>" + payload_new + "</b> was passed which gave result as <b>69741</b>")
							score = 2
						if output == self.expected_output[2]:
							payload_new = "{{5*'777'}}"
							json_payload_ssti = "\{\{5*'777'\}\}"
							payload = URLEncoder.encode("{{5*'777'}}", "UTF-8")
							json_ssti = URLEncoder.encode("\{\{5*'777'\}\}", "UTF-8")
							if ptype == 0 or ptype == 1:
								new_paramters = self._helpers.buildParameter(name, payload, ptype)
								ssti_updated_request = self._helpers.updateParameter(request, new_paramters)
							else:
								jsonreq = re.search(r"\s([{\[].*?[}\]])$", requeststring).group(1)
								new = jsonreq.split(name+"\":",1)[1]
								if new.startswith('\"'):
									newjsonreq = jsonreq.replace(name+"\":\""+param_value,name+"\":\""+json_ssti)
								else:
									newjsonreq = jsonreq.replace(name+"\":"+param_value,name+"\":\""+json_ssti+"\"")
								ssti_updated_request = self._helpers.buildHttpMessage(headers, newjsonreq)
							self.ssti_attack = self.makeRequest(Comp_req, ssti_updated_request)
							ssti_response = self.ssti_attack.getResponse()
							ssti_response_str = self._helpers.bytesToString(ssti_response)
							if self.expected_output[3] in ssti_response_str:
								sstireqresp.append(self.ssti_attack)
								ssti_description.append("Parameter <b>" + self._helpers.urlDecode(name) + "</b> is using <b>Twig</b> Template<br>The value <b>" + payload_new + "</b> was passed which gave result as <b>3885</b>")
								score = 2
							elif self.expected_output[4] in ssti_response_str:
								sstireqresp.append(self.ssti_attack)
								self.responseMarkString = "777777777777777"
								ssti_description.append("Parameter <b>" + self._helpers.urlDecode(name) + "</b> is using <b>Jinja2</b> Template<br>The value <b>" + payload_new + "</b> was passed which gave result as <b>777777777777777</b>")
								score = 2
						if score > 0: SSTIimp = self.CHECK
						if score > 1: SSTIimp = self.FOUND
						sstiflag = self.checkBetterScore(score,sstiflag)
			else:
				SSTIimp = "Disabled"

			resultssti.append(SSTIimp)

			if self.blindxss.isSelected():
				blindxss_value = self.BlindXSSText.getText()
				if ptype == 0 or ptype == 1:
					new_paramters_value = self._helpers.buildParameter(name, blindxss_value, ptype)
					updated_request = self._helpers.updateParameter(request, new_paramters_value)
				else:
					jsonreq = re.search(r"\s([{\[].*?[}\]])$", requeststring).group(1)
					new = jsonreq.split(name+"\":",1)[1]
					if new.startswith('\"'):
						newjsonreq = jsonreq.replace(name+"\":\""+param_value,name+"\":\""+blindxss_value)
					else:
						newjsonreq = jsonreq.replace(name+"\":"+param_value,name+"\":\""+blindxss_value+"\"")
					updated_request = self._helpers.buildHttpMessage(headers, newjsonreq)
				attack = self.makeRequest(Comp_req, updated_request)

		if XSSimp != "Disabled":
			if xssflag > 3: XSSimp = self.FOUND
			elif xssflag > 2: XSSimp = self.CHECK
			else: XSSimp = self.NOT_FOUND

		if SSTIimp != "Disabled":
			if sstiflag > 1: SSTIimp = self.FOUND
			elif sstiflag > 0: SSTIimp = self.CHECK
			else: SSTIimp = self.NOT_FOUND

		if SQLiimp != "Disabled":
			if sqliflag > 3: SQLiimp = self.FOUND
			elif sqliflag > 2: SQLiimp = self.CHECK
			else: SQLiimp = self.NOT_FOUND

		self.addToLog(messageInfo, XSSimp, SQLiimp, SSTIimp, param_new, resultxss, resultsqli, resultssti, xssreqresp, sqlireqresp, sstireqresp , xss_description, sqli_description, ssti_description, req_time.strftime('%H:%M:%S %m/%d/%y'))


	#
	#Function used to check if the score originally and mentioned is better
	#
	def checkBetterScore(self, score, ogscore):
		if score > ogscore:
			ogscore = score
		return ogscore


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

	
	def addToLog(self, messageInfo, XSSimp, SQLiimp, SSTIimp, parameters, resultxss, resultsqli, resultssti, xssreqresp, sqlireqresp, sstireqresp, xss_description, sqli_description, ssti_description, req_time):
		requestInfo = self._helpers.analyzeRequest(messageInfo)
		method = requestInfo.getMethod()
		self._lock.acquire()
		row = self._log.size()
		self._log.add(LogEntry(self._callbacks.saveBuffersToTempFiles(messageInfo), requestInfo.getUrl(),method,XSSimp,SQLiimp,SSTIimp,req_time, parameters,resultxss, resultsqli, resultssti, xssreqresp, sqlireqresp, sstireqresp, xss_description, sqli_description, ssti_description)) # same requests not include again.
		SwingUtilities.invokeLater(UpdateTableEDT(self,"insert",row,row))
		self._lock.release()
Ejemplo n.º 7
0
class ConfigurationTab():
    def __init__(self, extender):
        self._extender = extender

    def draw(self):
        """  init configuration tab
        """
        self.DEFUALT_REPLACE_TEXT = "Cookie: Insert=injected; cookie=or;\nHeader: here"
        self._extender.startButton = JToggleButton(
            "Autorize is off", actionPerformed=self.startOrStop)
        self._extender.startButton.setBounds(10, 20, 230, 30)

        self._extender.clearButton = JButton("Clear List",
                                             actionPerformed=self.clearList)
        self._extender.clearButton.setBounds(10, 80, 100, 30)
        self._extender.autoScroll = JCheckBox("Auto Scroll")
        self._extender.autoScroll.setBounds(145, 80, 130, 30)

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

        self._extender.prevent304 = JCheckBox(
            "Prevent 304 Not Modified status code")
        self._extender.prevent304.setBounds(280, 25, 300, 30)
        self._extender.interceptRequestsfromRepeater = JCheckBox(
            "Intercept requests from Repeater")
        self._extender.interceptRequestsfromRepeater.setBounds(
            280, 45, 300, 30)

        self._extender.doUnauthorizedRequest = JCheckBox(
            "Check unauthenticated")
        self._extender.doUnauthorizedRequest.setBounds(280, 65, 300, 30)
        self._extender.doUnauthorizedRequest.setSelected(True)

        self._extender.replaceQueryParam = JCheckBox(
            "Replace query params", actionPerformed=self.replaceQueryHanlder)
        self._extender.replaceQueryParam.setBounds(280, 85, 300, 30)
        self._extender.replaceQueryParam.setSelected(False)

        self._extender.saveHeadersButton = JButton(
            "Add", actionPerformed=self.saveHeaders)
        self._extender.saveHeadersButton.setBounds(315, 115, 80, 30)

        self._extender.removeHeadersButton = JButton(
            "Remove", actionPerformed=self.removeHeaders)
        self._extender.removeHeadersButton.setBounds(400, 115, 80, 30)

        savedHeadersTitles = self.getSavedHeadersTitles()
        self._extender.savedHeadersTitlesCombo = JComboBox(savedHeadersTitles)
        self._extender.savedHeadersTitlesCombo.addActionListener(
            SavedHeaderChange(self._extender))
        self._extender.savedHeadersTitlesCombo.setBounds(10, 115, 300, 30)

        self._extender.replaceString = JTextArea(self.DEFUALT_REPLACE_TEXT, 5,
                                                 30)
        self._extender.replaceString.setWrapStyleWord(True)
        self._extender.replaceString.setLineWrap(True)
        scrollReplaceString = JScrollPane(self._extender.replaceString)
        scrollReplaceString.setVerticalScrollBarPolicy(
            JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED)
        scrollReplaceString.setBounds(10, 150, 470, 150)

        fromLastRequestLabel = JLabel("From last request:")
        fromLastRequestLabel.setBounds(10, 305, 250, 30)

        self._extender.fetchCookiesHeaderButton = JButton(
            "Fetch Cookies header", actionPerformed=self.fetchCookiesHeader)
        self._extender.fetchCookiesHeaderButton.setEnabled(False)
        self._extender.fetchCookiesHeaderButton.setBounds(10, 330, 220, 30)

        self._extender.fetchAuthorizationHeaderButton = JButton(
            "Fetch Authorization header",
            actionPerformed=self.fetchAuthorizationHeader)
        self._extender.fetchAuthorizationHeaderButton.setEnabled(False)
        self._extender.fetchAuthorizationHeaderButton.setBounds(
            260, 330, 220, 30)

        self._extender.filtersTabs = JTabbedPane()
        self._extender.filtersTabs = self._extender.filtersTabs
        self._extender.filtersTabs.addTab("Enforcement Detector",
                                          self._extender.EDPnl)
        self._extender.filtersTabs.addTab("Detector Unauthenticated",
                                          self._extender.EDPnlUnauth)
        self._extender.filtersTabs.addTab("Interception Filters",
                                          self._extender.filtersPnl)
        self._extender.filtersTabs.addTab("Match/Replace",
                                          self._extender.MRPnl)
        self._extender.filtersTabs.addTab("Table Filter",
                                          self._extender.filterPnl)
        self._extender.filtersTabs.addTab("Save/Restore",
                                          self._extender.exportPnl)

        self._extender.filtersTabs.setSelectedIndex(2)
        self._extender.filtersTabs.setBounds(0, 350, 2000, 700)

        self.config_pnl = JPanel()
        self.config_pnl.setBounds(0, 0, 1000, 1000)
        self.config_pnl.setLayout(None)
        self.config_pnl.add(self._extender.startButton)
        self.config_pnl.add(self._extender.clearButton)
        self.config_pnl.add(scrollReplaceString)
        self.config_pnl.add(fromLastRequestLabel)
        self.config_pnl.add(self._extender.saveHeadersButton)
        self.config_pnl.add(self._extender.removeHeadersButton)
        self.config_pnl.add(self._extender.savedHeadersTitlesCombo)
        self.config_pnl.add(self._extender.fetchCookiesHeaderButton)
        self.config_pnl.add(self._extender.fetchAuthorizationHeaderButton)
        self.config_pnl.add(self._extender.autoScroll)
        self.config_pnl.add(self._extender.interceptRequestsfromRepeater)
        self.config_pnl.add(self._extender.ignore304)
        self.config_pnl.add(self._extender.prevent304)
        self.config_pnl.add(self._extender.doUnauthorizedRequest)
        self.config_pnl.add(self._extender.replaceQueryParam)

        self._extender._cfg_splitpane = JSplitPane(JSplitPane.VERTICAL_SPLIT)
        self._extender._cfg_splitpane.setResizeWeight(0.5)
        self._extender._cfg_splitpane.setBounds(0, 0, 1000, 1000)
        self._extender._cfg_splitpane.setRightComponent(
            self._extender.filtersTabs)
        self._extender._cfg_splitpane.setLeftComponent(self.config_pnl)

    def startOrStop(self, event):
        if self._extender.startButton.getText() == "Autorize is off":
            self._extender.startButton.setText("Autorize is on")
            self._extender.startButton.setSelected(True)
            self._extender.intercept = 1
        else:
            self._extender.startButton.setText("Autorize is off")
            self._extender.startButton.setSelected(False)
            self._extender.intercept = 0

    def clearList(self, event):
        self._extender._lock.acquire()
        oldSize = self._extender._log.size()
        self._extender._log.clear()
        SwingUtilities.invokeLater(
            UpdateTableEDT(self._extender, "delete", 0, oldSize - 1))
        self._extender._lock.release()

    def replaceQueryHanlder(self, event):
        if self._extender.replaceQueryParam.isSelected():
            self._extender.replaceString.setText("paramName=paramValue")
        else:
            self._extender.replaceString.setText(self.DEFUALT_REPLACE_TEXT)

    def saveHeaders(self, event):
        savedHeadersTitle = JOptionPane.showInputDialog(
            "Please provide saved headers title:")
        self._extender.savedHeaders.append({
            'title':
            savedHeadersTitle,
            'headers':
            self._extender.replaceString.getText()
        })
        self._extender.savedHeadersTitlesCombo.setModel(
            DefaultComboBoxModel(self.getSavedHeadersTitles()))
        self._extender.savedHeadersTitlesCombo.getModel().setSelectedItem(
            savedHeadersTitle)

    def removeHeaders(self, event):
        model = self._extender.savedHeadersTitlesCombo.getModel()
        selectedItem = model.getSelectedItem()
        if selectedItem == "Temporary headers":
            return

        delObject = None
        for savedHeaderObj in self._extender.savedHeaders:
            if selectedItem == savedHeaderObj['title']:
                delObject = savedHeaderObj
        self._extender.savedHeaders.remove(delObject)
        model.removeElement(selectedItem)

    def getSavedHeadersTitles(self):
        titles = []
        for savedHeaderObj in self._extender.savedHeaders:
            titles.append(savedHeaderObj['title'])
        return titles

    def fetchCookiesHeader(self, event):
        if self._extender.lastCookiesHeader:
            self._extender.replaceString.setText(
                self._extender.lastCookiesHeader)

    def fetchAuthorizationHeader(self, event):
        if self._extender.lastAuthorizationHeader:
            self._extender.replaceString.setText(
                self._extender.lastAuthorizationHeader)
Ejemplo n.º 8
0
class BurpExtender(IBurpExtender, ITab):
    THREAD_NUM = 20

    def registerExtenderCallbacks(self, callbacks):
        self.callbacks = callbacks
        self.helpers = callbacks.getHelpers()
        self.callbacks.setExtensionName("URLIMPORTER")
        self.threads = []

        self.__initLayout__()
        self.callbacks.addSuiteTab(self)

    def __initLayout__(self):
        self.panel = JPanel()
        self.panel.setLayout(FlowLayout())
        self.panel.setBounds(40, 80, 200, 200)
        self.UI_URLS_AREA = JTextArea('', 14, 80)
        self.UI_URLS_AREA.setLineWrap(True)
        self.UI_URLS_AREA_SCROLL = JScrollPane(self.UI_URLS_AREA)

        self.UI_HEADERS = JTextArea('', 8, 50)
        self.UI_HEADERS.setLineWrap(True)
        self.UI_HEADERS_AREA_SCROLL = JScrollPane(self.UI_HEADERS)

        self.url_add_to_sitemap_button = JButton(
            "ADD TO SITEMAP", actionPerformed=self.URLS_ADD_TO_SITEMAP)

        self.UI_HEADERS.setText(
            "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36"
        )
        self.panel.add(self.url_add_to_sitemap_button)
        self.panel.add(self.UI_URLS_AREA_SCROLL)
        self.panel.add(self.UI_HEADERS_AREA_SCROLL)

    def getTabCaption(self):
        return "CimexURLImport"

    def getUiComponent(self):
        return self.panel

    def URLS_ADD_TO_SITEMAP(self, event):
        self.q = queue.Queue()
        get_all_urls = self.UI_URLS_AREA.getText()
        get_headers = self.UI_HEADERS.getText()
        self.HEADERS = list(set(get_headers.split('\n')))
        urls_list = list(set(get_all_urls.split('\n')))

        for url in urls_list:
            url = url.rstrip()
            self.q.put(url)

        for j in range(self.THREAD_NUM):
            t = threading.Thread(target=self.ProcessQueue)
            self.threads.append(t)
            t.start()

    def ProcessQueue(self):
        while not self.q.empty():
            each_url = self.q.get()
            self.ProcessURL(each_url)
            self.q.task_done()

    def URL_SPLITTER(self, url):
        URL_SPLIT = str(url).split("://", 1)
        URL_PROTOCAL = URL_SPLIT[0]
        if URL_PROTOCAL == 'https':
            URL_PORT = 443
        elif URL_PROTOCAL == 'http':
            URL_PORT = 80
        else:
            URL_PORT = 443
        URL_HOSTNAME = URL_SPLIT[1].split('/', 1)[0].split('?', 1)[0]
        if ':' in URL_HOSTNAME:
            URL_HOSTNAME_FOR_SPLIT = URL_HOSTNAME
            URL_HOSTNAME = URL_HOSTNAME_FOR_SPLIT.split(':')[0]
            URL_PORT = int(URL_HOSTNAME_FOR_SPLIT.split(':')[1])
        URL_HOST_FULL = URL_PROTOCAL + "://" + URL_HOSTNAME
        try:
            URL_HOST_SERVICE = self.helpers.buildHttpService(
                URL_HOSTNAME, URL_PORT, URL_PROTOCAL)
        except java.lang.IllegalArgumentException:
            print("EXCEPTION BECAUSE HTTPSERVICE VALUES IS INVALID : {} : ".
                  format(url))
            print("EXCEPTION VALUES ARE :", URL_HOSTNAME, URL_PORT,
                  URL_PROTOCAL)
        return URL_SPLIT, URL_PROTOCAL, URL_HOSTNAME, URL_PORT, URL_HOST_FULL, URL_HOST_SERVICE

    def ProcessURL(self, url):
        print(url)
        if url.startswith('http://') or url.startswith('https://'):
            URL_SPLIT, URL_PROTOCAL, URL_HOSTNAME, URL_PORT, URL_HOST_FULL, URL_HOST_SERVICE = self.URL_SPLITTER(
                url)
            try:
                HEADERS = [
                    "GET /" + str(URL_SPLIT[1].split('/', 1)[1]) + " HTTP/1.1",
                    'Host: ' + str(URL_HOSTNAME)
                ]
            except:
                print("URL EXCEPTION IN HEADERS : {} : {}".format(
                    url, URL_SPLIT))
            if self.HEADERS:
                for each_header in self.HEADERS:
                    if each_header not in HEADERS:
                        HEADERS.append(each_header)
            msg = self.helpers.buildHttpMessage(HEADERS, None)
            resp = self.callbacks.makeHttpRequest(URL_HOST_SERVICE, msg)
            if resp.getResponse() != None:
                resp_analyze = self.helpers.analyzeResponse(resp.getResponse())
                self.callbacks.addToSiteMap(
                    resp)  ###! Adding Redirecting Request too in sitemap....
                resp_heads = resp_analyze.getHeaders()
                if '301' in resp_heads[0] or 'Moved' in resp_heads[
                        1] or '307' in resp_heads[0] or '302' in resp_heads[0]:
                    for each_head in resp_heads:
                        if each_head.startswith(
                                'Location:') or each_head.startswith(
                                    'location:'):
                            location_value = each_head.split(":",
                                                             1)[1].strip(' ')
                            if location_value.startswith('http'):
                                URL_SPLIT, URL_PROTOCAL, URL_HOSTNAME, URL_PORT, URL_HOST_FULL, URL_HOST_SERVICE = self.URL_SPLITTER(
                                    location_value)
                                try:
                                    HEADERS = [
                                        "GET /" +
                                        str(URL_SPLIT[1].split('/', 1)[1]) +
                                        " HTTP/1.1",
                                        'Host: ' + str(URL_HOSTNAME)
                                    ]
                                except:
                                    print(
                                        "URL EXCEPTION IN REDIRECTION HEADERS : {}"
                                        .format(URL_SPLIT))
                                    return False
                                if self.HEADERS:
                                    for each_header in self.HEADERS:
                                        if each_header not in HEADERS:
                                            HEADERS.append(each_header)
                            elif location_value.startswith('/'):
                                HEADERS = [
                                    "GET " + str(location_value) + " HTTP/1.1",
                                    'Host: ' + str(URL_HOSTNAME)
                                ]
                                if self.HEADERS:
                                    for each_header in self.HEADERS:
                                        if each_header not in HEADERS:
                                            HEADERS.append(each_header)
                            else:
                                pass
                            msg = self.helpers.buildHttpMessage(HEADERS, None)
                            resp = self.callbacks.makeHttpRequest(
                                URL_HOST_SERVICE, msg)
                            self.callbacks.addToSiteMap(resp)
Ejemplo n.º 9
0
def reloadComponent(game,dialog,node):
    c = None
    text = node.getAttribute("text") if node.hasAttribute("text") else ""
    align = int(node.getAttribute("align")) if node.hasAttribute("align") else 0
        
    #Components
    if node.nodeName=="jpanel":
        c = JPanel()
        c.setBackground(Color.BLACK)
        layout = createLayoutManager(c,node.getAttribute("layout") if node.hasAttribute("layout") else "flow")
        c.setLayout(layout)
        c.setOpaque(False)
        
        if node.getAttribute("opaque"):
            c.setOpaque(node.getAttribute("opaque")=="true")
        
        if node.getAttribute("background"):
            if(node.getAttribute("background")=="orange"):
                c.setBackground(Color.ORANGE)
            elif(node.getAttribute("background")=="green"):
                c.setBackground(Color.GREEN)            
            
        for child in node.childNodes:
            if child.nodeName!="#text":
                if node.getAttribute("layout")=="gridbag":
                    c.add(reloadComponent(game,dialog,child),getGridBagConstraints(game,child))
                else:
                    c.add(reloadComponent(game,dialog,child))
                
    elif node.nodeName=="jlabel":
        c = JLabel(text,align)
    elif node.nodeName=="jbutton":
        c = JButton(text)
        if node.hasAttribute("enabled"): c.setEnabled(node.getAttribute("enabled")=="true");
            
    elif node.nodeName=="settingspanel":
        c = SettingsPanel(game)
        for g in node.childNodes:
            if g.nodeName=="group":
                c.addGroup(int(g.getAttribute("id")),g.getAttribute("label"))
                for h in g.childNodes:
                    if h.nodeName=="heading":
                        c.addHeading(int(g.getAttribute("id")),h.getAttribute("label"))
                        for s in h.childNodes:
                            if s.nodeName=="setting":
                                #<setting id="1" name="DISPLAY_REAL_WORLD_TIME" type="checkbox" label="Show Real-World Time"></setting>
                                if s.getAttribute("items")!="":
                                    c.addSettingWithItems(int(g.getAttribute("id")),int(s.getAttribute("id")),s.getAttribute("label"),s.getAttribute("type"),s.getAttribute("items").split(","))
                                else:
                                    c.addSetting(int(g.getAttribute("id")),int(s.getAttribute("id")),s.getAttribute("label"),s.getAttribute("type"))
                                

        c.finalizeSettingsPanel()
        dialog.registerSettingsPanel(int(node.getAttribute("id")),c)
    
    elif node.nodeName=="logspanel":
        c = LogsPanel(game)
        for g in node.childNodes:
            if g.nodeName=="group":
                c.addLog(int(g.getAttribute("id")),g.getAttribute("label"))                          

        c.finalizeLogsPanel()
        dialog.registerLogsPanel(int(node.getAttribute("id")),c)
    
    elif node.nodeName=="nglcanvas":
        c = NGLCanvas(game,int(getCascadingAttribute(game,node,"width")),int(getCascadingAttribute(game,node,"height")))
        dialog.registerCanvas(int(node.getAttribute("id")),c)
    
    #Layout
    if node.parentNode.getAttribute("layout")=="absolute":
        c.setBounds(getBounds(game,node))
    elif node.parentNode.getAttribute("layout")=="box-y":
        c.setAlignmentX(Component.CENTER_ALIGNMENT);
        if node.hasAttribute("width") and node.hasAttribute("height"):
            c.setPreferredSize(Dimension(int(getCascadingAttribute(game,node,"width")),int(getCascadingAttribute(game,node,"height"))))
        if node.hasAttribute("minWidth") and node.hasAttribute("minHeight"):
            c.setMinimumSize(Dimension(int(node.getAttribute("minWidth")),int(node.getAttribute("minHeight"))))
        if node.hasAttribute("maxWidth") and node.hasAttribute("maxHeight"):
            c.setMaximumSize(Dimension(int(node.getAttribute("maxWidth")),int(node.getAttribute("maxHeight"))))
    elif node.parentNode.getAttribute("layout")=="box-x":
        c.setAlignmentY(Component.CENTER_ALIGNMENT);
        if node.hasAttribute("width") and node.hasAttribute("height"):
            c.setPreferredSize(Dimension(int(getCascadingAttribute(game,node,"width")),int(getCascadingAttribute(game,node,"height"))))
        if node.hasAttribute("minWidth") and node.hasAttribute("minHeight"):
            c.setMinimumSize(Dimension(int(node.getAttribute("minWidth")),int(node.getAttribute("minHeight"))))
        if node.hasAttribute("maxWidth") and node.hasAttribute("maxHeight"):
            c.setMaximumSize(Dimension(int(node.getAttribute("maxWidth")),int(node.getAttribute("maxHeight"))))

    if node.nodeName!="nglcanvas" and node.nodeName!="jpanel" and node.nodeName!="settingspanel": addListeners(game,c,node)
    return c;
Ejemplo n.º 10
0
class BurpExtender(IBurpExtender, ITab, IMessageEditorController, AbstractTableModel, IContextMenuFactory):

    def registerExtenderCallbacks(self, callbacks):
        # keep a reference to our callbacks object
        self._callbacks = callbacks
        # obtain an extension helpers object
        self._helpers = callbacks.getHelpers()
        
        # set our extension name
        callbacks.setExtensionName("PT Vulnerabilities Manager")
        
        self.config = SafeConfigParser()
        self.createSection('projects')
        self.createSection('general')
        self.config.read('config.ini')
        self.chooser = JFileChooser()
        # create the log and a lock on which to synchronize when adding log entries
        self._log = ArrayList()
        self._lock = Lock()
        
        self.logTable = Table(self)
        self.logTable.getColumnModel().getColumn(0).setMaxWidth(35)
        self.logTable.getColumnModel().getColumn(1).setMinWidth(100)

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

        self.initVulnerabilityTab()
        self.initProjSettingsTab()
        self.initTabs()
        self.initCallbacks()

        if self.projPath.getText() != None:
            self.loadVulnerabilities(self.projPath.getText())

        print "Thank you for installing PT Vulnerabilities Manager v1.0 extension"
        print "by Barak Tawily\n\n\n"
        print "Disclaimer:\nThis extension might create folders and files in your hardisk which might be declared as sensitive information, make sure you are creating projects under encrypted partition"
        return

    def initVulnerabilityTab(self):
        #
        ##  init vulnerability tab
        #

        nameLabel = JLabel("Vulnerability Name:")
        nameLabel.setBounds(10, 10, 140, 30)

        self.addButton = JButton("Add",actionPerformed=self.addVuln)
        self.addButton.setBounds(10, 500, 100, 30) 

        rmVulnButton = JButton("Remove",actionPerformed=self.rmVuln)
        rmVulnButton.setBounds(465, 500, 100, 30)

        mitigationLabel = JLabel("Mitigation:")
        mitigationLabel.setBounds(10, 290, 150, 30)
        
        addSSBtn = JButton("Add SS",actionPerformed=self.addSS)
        addSSBtn.setBounds(750, 40, 110, 30) 

        deleteSSBtn = JButton("Remove SS",actionPerformed=self.removeSS)
        deleteSSBtn.setBounds(750, 75, 110, 30) 

        piclistLabel = JLabel("Images list:")
        piclistLabel.setBounds(580, 10, 140, 30)

        self.screenshotsList = DefaultListModel()
        self.ssList = JList(self.screenshotsList)
        self.ssList.setBounds(580, 40, 150, 250)
        self.ssList.addListSelectionListener(ssChangedHandler(self))
        self.ssList.setBorder(BorderFactory.createLineBorder(Color.GRAY))

        previewPicLabel = JLabel("Selected image preview: (click to open in image viewer)")
        previewPicLabel.setBounds(580, 290, 500, 30)


        copyImgMenu = JMenuItem("Copy")
        copyImgMenu.addActionListener(copyImg(self))

        self.imgMenu = JPopupMenu("Popup")
        self.imgMenu.add(copyImgMenu)

        self.firstPic = JLabel()
        self.firstPic.setBorder(BorderFactory.createLineBorder(Color.GRAY))
        self.firstPic.setBounds(580, 320, 550, 400)
        self.firstPic.addMouseListener(imageClicked(self))

        self.vulnName = JTextField("")
        self.vulnName.getDocument().addDocumentListener(vulnTextChanged(self))
        self.vulnName.setBounds(140, 10, 422, 30)

        sevirities = ["Unclassified", "Critical","High","Medium","Low"]
        self.threatLevel = JComboBox(sevirities);
        self.threatLevel.setBounds(140, 45, 140, 30)

        colors = ["Color:", "Green", "Red"]
        self.colorCombo = JComboBox(colors);
        self.colorCombo.setBounds(465, 45, 100, 30)
        self.colorCombo

        severityLabel = JLabel("Threat Level:")
        severityLabel.setBounds(10, 45, 100, 30)

        descriptionLabel = JLabel("Description:")
        descriptionLabel.setBounds(10, 80, 100, 30)

        self.descriptionString = JTextArea("", 5, 30)
        self.descriptionString.setWrapStyleWord(True);
        self.descriptionString.setLineWrap(True)
        self.descriptionString.setBounds(10, 110, 555, 175)
        descriptionStringScroll = JScrollPane(self.descriptionString)
        descriptionStringScroll.setBounds(10, 110, 555, 175)
        descriptionStringScroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED)


        self.mitigationStr = JTextArea("", 5, 30)
        self.mitigationStr.setWrapStyleWord(True);
        self.mitigationStr.setLineWrap(True)
        self.mitigationStr.setBounds(10, 320, 555, 175)

        mitigationStrScroll = JScrollPane(self.mitigationStr)
        mitigationStrScroll.setBounds(10, 320, 555, 175)
        mitigationStrScroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED)

        self.pnl = JPanel()
        self.pnl.setBounds(0, 0, 1000, 1000);
        self.pnl.setLayout(None);
        self.pnl.add(addSSBtn)
        self.pnl.add(piclistLabel)
        self.pnl.add(nameLabel)
        self.pnl.add(deleteSSBtn)
        self.pnl.add(rmVulnButton)
        self.pnl.add(severityLabel)
        self.pnl.add(mitigationLabel)
        self.pnl.add(descriptionLabel)
        self.pnl.add(previewPicLabel)
        self.pnl.add(mitigationStrScroll)
        self.pnl.add(descriptionStringScroll)
        self.pnl.add(self.ssList)
        self.pnl.add(self.firstPic)
        self.pnl.add(self.addButton)
        self.pnl.add(self.vulnName)
        self.pnl.add(self.threatLevel)
        self.pnl.add(self.colorCombo)
        
    def initProjSettingsTab(self):
        # init project settings 
        
        projNameLabel = JLabel("Name:")
        projNameLabel.setBounds(10, 50, 140, 30)

        self.projName = JTextField("")
        self.projName.setBounds(140, 50, 320, 30)
        self.projName.getDocument().addDocumentListener(projTextChanged(self))

        detailsLabel = JLabel("Details:")
        detailsLabel.setBounds(10, 120, 140, 30)

        reportLabel = JLabel("Generate Report:")
        reportLabel.setBounds(10, 375, 140, 30)

        types = ["DOCX","HTML","XLSX"]
        self.reportType = JComboBox(types)
        self.reportType.setBounds(10, 400, 140, 30)

        generateReportButton = JButton("Generate", actionPerformed=self.generateReport)
        generateReportButton.setBounds(160, 400, 90, 30)


        self.projDetails = JTextArea("", 5, 30)
        self.projDetails.setWrapStyleWord(True);
        self.projDetails.setLineWrap(True)

        projDetailsScroll = JScrollPane(self.projDetails)
        projDetailsScroll.setBounds(10, 150, 450, 175)
        projDetailsScroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED)

        projPathLabel = JLabel("Path:")
        projPathLabel.setBounds(10, 90, 140, 30)

        self.projPath = JTextField("")
        self.projPath.setBounds(140, 90, 320, 30)

        chooseProjPathButton = JButton("Browse...",actionPerformed=self.chooseProjPath)
        chooseProjPathButton.setBounds(470, 90, 100, 30)
        
        importProjButton = JButton("Import",actionPerformed=self.importProj)
        importProjButton.setBounds(470, 10, 100, 30)

        exportProjButton = JButton("Export",actionPerformed=self.exportProj)
        exportProjButton.setBounds(575, 10, 100, 30)

        openProjButton = JButton("Open Directory",actionPerformed=self.openProj)
        openProjButton.setBounds(680, 10, 130, 30)

        currentProjectLabel = JLabel("Current:")
        currentProjectLabel.setBounds(10, 10, 140, 30)

        projects = self.config.options('projects')
        self.currentProject = JComboBox(projects)
        self.currentProject.addActionListener(projectChangeHandler(self))
        self.currentProject.setBounds(140, 10, 140, 30)

        self.autoSave = JCheckBox("Auto Save Mode")
        self.autoSave.setEnabled(False)  # implement this feature
        self.autoSave.setBounds(300, 10, 140, 30)
        self.autoSave.setToolTipText("Will save any changed value while focus is out")

        addProjButton = JButton("Add / Update",actionPerformed=self.addProj)
        addProjButton.setBounds(10, 330, 150, 30)

        removeProjButton = JButton("Remove Current",actionPerformed=self.rmProj)
        removeProjButton.setBounds(315, 330, 146, 30)

        generalOptions = self.config.options('general')
        if 'default project' in generalOptions:
            defaultProj = self.config.get('general','default project')
            self.currentProject.getModel().setSelectedItem(defaultProj)
            self.projPath.setText(self.config.get('projects',self.currentProject.getSelectedItem()))

        self.clearProjTab = True
        self.projectSettings = JPanel()
        self.projectSettings.setBounds(0, 0, 1000, 1000)
        self.projectSettings.setLayout(None)
        self.projectSettings.add(reportLabel)
        self.projectSettings.add(detailsLabel)
        self.projectSettings.add(projPathLabel)
        self.projectSettings.add(addProjButton)
        self.projectSettings.add(openProjButton)
        self.projectSettings.add(projNameLabel)
        self.projectSettings.add(projDetailsScroll)
        self.projectSettings.add(importProjButton)
        self.projectSettings.add(exportProjButton)
        self.projectSettings.add(removeProjButton)
        self.projectSettings.add(generateReportButton)
        self.projectSettings.add(chooseProjPathButton)
        self.projectSettings.add(currentProjectLabel)
        self.projectSettings.add(self.projPath)
        self.projectSettings.add(self.autoSave)
        self.projectSettings.add(self.projName)
        self.projectSettings.add(self.reportType)
        self.projectSettings.add(self.currentProject)

    def initTabs(self):
        #
        ##  init autorize tabs
        #
        
        self._splitpane = JSplitPane(JSplitPane.HORIZONTAL_SPLIT)
        self.scrollPane = JScrollPane(self.logTable)
        self._splitpane.setLeftComponent(self.scrollPane)
        colorsMenu = JMenu("Paint")
        redMenu = JMenuItem("Red")
        noneMenu = JMenuItem("None")
        greenMenu = JMenuItem("Green")
        redMenu.addActionListener(paintChange(self, "Red"))
        noneMenu.addActionListener(paintChange(self, None))
        greenMenu.addActionListener(paintChange(self, "Green"))
        colorsMenu.add(redMenu)
        colorsMenu.add(noneMenu)
        colorsMenu.add(greenMenu)
        
        
        self.menu = JPopupMenu("Popup")
        self.menu.add(colorsMenu)

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

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

        self.tabs.addTab("Project Settings", self.projectSettings)
        
        self.tabs.setSelectedIndex(2)
        self._splitpane.setRightComponent(self.tabs)

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

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


    def loadVulnerabilities(self, projPath):
        self.clearList(None)
        selected = False
        for root, dirs, files in os.walk(projPath): # make it go only for dirs
            for dirName in dirs:
                xmlPath = projPath+"/"+dirName+"/vulnerability.xml"
                # xmlPath = xmlPath.replace("/","//")
                document = self.getXMLDoc(xmlPath)
                nodeList = document.getDocumentElement().getChildNodes()
                vulnName = nodeList.item(0).getTextContent()
                severity = nodeList.item(1).getTextContent()
                description = nodeList.item(2).getTextContent()
                mitigation = nodeList.item(3).getTextContent()
                color = nodeList.item(4).getTextContent()
                test = vulnerability(vulnName,severity,description,mitigation,color)
                self._lock.acquire()
                row = self._log.size()
                self._log.add(test)
                self.fireTableRowsInserted(row, row)
                self._lock.release()
                if vulnName == self.vulnName.getText():
                    self.logTable.setRowSelectionInterval(row,row)
                    selected = True
        if selected == False and self._log.size() > 0:
            self.logTable.setRowSelectionInterval(0, 0)
            self.loadVulnerability(self._log.get(0))
        
    def createSection(self, sectioName):
        self.config.read('config.ini')
        if not (sectioName in self.config.sections()):
            self.config.add_section(sectioName)
            cfgfile = open("config.ini",'w')
            self.config.write(cfgfile)
            cfgfile.close()

    def saveCfg(self):
        f = open('config.ini', 'w')
        self.config.write(f)
        f.close()

    def getXMLDoc(self, xmlPath):
        try:
            document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(xmlPath)
            return document
        except:
            self._extender.popup("XML file not found")
            return

    def saveXMLDoc(self, doc, xmlPath):
        transformerFactory = TransformerFactory.newInstance()
        transformer = transformerFactory.newTransformer()
        source = DOMSource(doc)
        result = StreamResult(File(xmlPath))
        transformer.transform(source, result)

    def generateReport(self,event):
        if self.reportType.getSelectedItem() == "HTML":
            path = self.reportToHTML()
        if self.reportType.getSelectedItem() == "XLSX":
            path = self.reportToXLS()
        if self.reportType.getSelectedItem() == "DOCX":
            path = self.generateReportFromDocxTemplate('template.docx',"newfile.docx", 'word/document.xml')
        n = JOptionPane.showConfirmDialog(None, "Report generated successfuly:\n%s\nWould you like to open it?" % (path), "PT Manager", JOptionPane.YES_NO_OPTION)
        if n == JOptionPane.YES_OPTION:
            os.system('"' + path + '"') # Bug! stucking burp until the file get closed

    def exportProj(self,event):
        self.chooser.setDialogTitle("Save project")
        Ffilter = FileNameExtensionFilter("Zip files", ["zip"])
        self.chooser.setFileFilter(Ffilter)
        returnVal = self.chooser.showSaveDialog(None)
        if returnVal == JFileChooser.APPROVE_OPTION:
            dst = str(self.chooser.getSelectedFile())
            shutil.make_archive(dst,"zip",self.getCurrentProjPath())
            self.popup("Project export successfuly")

    def importProj(self,event):
        self.chooser.setDialogTitle("Select project zip to directory")
        Ffilter = FileNameExtensionFilter("Zip files", ["zip"])
        self.chooser.setFileFilter(Ffilter)
        returnVal = self.chooser.showOpenDialog(None)
        if returnVal == JFileChooser.APPROVE_OPTION:
            zipPath = str(self.chooser.getSelectedFile())
            self.chooser.setDialogTitle("Select project directory")
            self.chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY)
            returnVal = self.chooser.showOpenDialog(None)
            if returnVal == JFileChooser.APPROVE_OPTION:
                projPath = str(self.chooser.getSelectedFile()) + "/PTManager"
                with zipfile.ZipFile(zipPath, "r") as z:
                    z.extractall(projPath)

                xmlPath = projPath + "/project.xml"
                document = self.getXMLDoc(xmlPath)
                nodeList = document.getDocumentElement().getChildNodes()
                projName = nodeList.item(0).getTextContent()
                nodeList.item(1).setTextContent(projPath)
                self.saveXMLDoc(document, xmlPath)
                self.config.set('projects', projName, projPath)
                self.saveCfg()
                self.reloadProjects()
                self.currentProject.getModel().setSelectedItem(projName)
                self.clearVulnerabilityTab() 

    def reportToXLS(self):
        if not xlsxwriterImported:
            self.popup("xlsxwriter library is not imported")
            return
        workbook = xlsxwriter.Workbook(self.getCurrentProjPath() + '/PT Manager Report.xlsx')
        worksheet = workbook.add_worksheet()
        bold = workbook.add_format({'bold': True})
        worksheet.write(0, 0, "Vulnerability Name", bold)
        worksheet.write(0, 1, "Threat Level", bold)
        worksheet.write(0, 2, "Description", bold)
        worksheet.write(0, 3, "Mitigation", bold)
        row = 1
        for i in range(0,self._log.size()):
            worksheet.write(row, 0, self._log.get(i).getName())
            worksheet.write(row, 1, self._log.get(i).getSeverity())
            worksheet.write(row, 2, self._log.get(i).getDescription())
            worksheet.write(row, 3, self._log.get(i).getMitigation())
            row = row + 1
            # add requests and images as well
        workbook.close()
        return self.getCurrentProjPath() + '/PT Manager Report.xlsx'
        
    def reportToHTML(self):
        htmlContent = """<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="he" dir="ltr">
    <head>
        <title>PT Manager Report</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <style>
        body {
        background-repeat: no-repeat;
        background-attachment: fixed;
        font-family: Arial,Tahoma,sens-serif;
        font-size: 13px;
        margin: auto;
        }

        #warpcenter {
            width: 900px;
            margin: 0px auto;
        }

        table {
            border: 2px dashed #000000;
        }

        td {
            border-top: 2px dashed #000000;
            padding: 10px;
        }

        img {
                border: 0px;
        }
</style>
<script language="javascript">
    function divHideShow(divToHideOrShow) 
    {
        var div = document.getElementById(divToHideOrShow);

        if (div.style.display == "block") 
        {
            div.style.display = "none";
        }
        else 
        {
            div.style.display = "block";
        }

        
    }         
</script>
    </head>

    <body>
        <div id="warpcenter">

<h1> PT Manager Report </h1>
<h2> Project: %s</h1>
    """ % (self.projName.getText())

        for i in range(0,self._log.size()):
            name = self._log.get(i).getName()
            request = "None"
            response = "None"
            path = self.getVulnReqResPath("request",name)
            if os.path.exists(path):
                request = self.newlineToBR(self.getFileContent(path))
                
            path = self.getVulnReqResPath("response",name)
            if os.path.exists(path):
                response = self.newlineToBR(self.getFileContent(path))
            images = ""
            for fileName in os.listdir(self.projPath.getText()+"/"+self.clearStr(name)):
                if fileName.endswith(".jpg"):
                    images += "%s<br><img src=\"%s\"><br><br>" % (fileName, self.projPath.getText()+"/"+self.clearStr(name) + "/" + fileName)
            description = self.newlineToBR(self._log.get(i).getDescription())
            mitigation = self.newlineToBR(self._log.get(i).getMitigation())
            htmlContent +=  self.convertVulntoTable(i,name,self._log.get(i).getSeverity(), description,mitigation, request, response, images)
        htmlContent += "</div></body></html>"
        f = open(self.getCurrentProjPath() + '/PT Manager Report.html', 'w')
        f.writelines(htmlContent)
        f.close()
        return self.getCurrentProjPath() + '/PT Manager Report.html'

    def newlineToBR(self,string):
        return "<br />".join(string.split("\n"))

    def getFileContent(self,path):
        f = open(path, "rb")
        content = f.read()
        f.close()
        return content

    def convertVulntoTable(self, number, name, severity, description, mitigation, request = "None", response = "None", images = "None"):
        return """<div style="width: 100%%;height: 30px;text-align: center;background-color:#E0E0E0;font-size: 17px;font-weight: bold;color: #000;padding-top: 10px;">%s <a href="javascript:divHideShow('Table_%s');" style="color:#191970">(OPEN / CLOSE)</a></div>
        <div id="Table_%s" style="display: none;">
            <table width="100%%" cellspacing="0" cellpadding="0" style="margin: 0px auto;text-align: left;border-top: 0px;">
                <tr>
                    <td>
                        <div style="font-size: 16px;font-weight: bold;">
                        <span style="color:#000000">Threat Level: </span> 
                        <span style="color:#8b8989">%s</span>
                                            </td>
                                        </tr>
                                        <tr>
                                            <td>
                        <div style="font-size: 16px;font-weight: bold;">
                        <span style="color:#000000">Description</span> 
                        <a href="javascript:divHideShow('Table_%s_Command_03');" style="color:#191970">OPEN / CLOSE >>></a>
                        </div>

                        <div id="Table_%s_Command_03" style="display: none;margin-top: 25px;">
                        %s
                        </div>
                                            </td>
                                        </tr>
                                        <tr>
                                            <td>
                        <div style="font-size: 16px;font-weight: bold;">
                        <span style="color:#000000">Mitigration</span> 
                        <a href="javascript:divHideShow('Table_%s_Command_04');" style="color:#191970">OPEN / CLOSE >>></a>
                        </div>

                        <div id="Table_%s_Command_04" style="display: none;margin-top: 25px;">
                        %s
                        <b>
                                            </td>
                                        </tr>

                                        <tr>
                                            <td>
                        <div style="font-size: 16px;font-weight: bold;">
                        <span style="color:#000000">Request</span> 
                        <a href="javascript:divHideShow('Table_%s_Command_05');" style="color:#191970">OPEN / CLOSE >>></a>
                        </div>

                        <div id="Table_%s_Command_05" style="display: none;margin-top: 25px;">
                        %s
                        <b>
                                            </td>
                                        </tr>


                                                        <tr>
                                            <td>
                        <div style="font-size: 16px;font-weight: bold;">
                        <span style="color:#000000">Response</span> 
                        <a href="javascript:divHideShow('Table_%s_Command_06');" style="color:#191970">OPEN / CLOSE >>></a>
                        </div>

                        <div id="Table_%s_Command_06" style="display: none;margin-top: 25px;">
                        %s
                        <b>
                                            </td>
                                        </tr>

                                                        <tr>
                                            <td>
                        <div style="font-size: 16px;font-weight: bold;">
                        <span style="color:#000000">Images</span> 
                        <a href="javascript:divHideShow('Table_%s_Command_07');" style="color:#191970">OPEN / CLOSE >>></a>
                        </div>

                        <div id="Table_%s_Command_07" style="display: none;margin-top: 25px;">
                        %s
                        <b>
                    </td>
                </tr>
            </table>
        </div><br><br>""" % (name,number,number,severity,number,number,description,number,number,mitigation,number,number,request,number,number,response,number,number,images)

    def clearVulnerabilityTab(self, rmVuln=True):
        if rmVuln:
            self.vulnName.setText("")
        self.descriptionString.setText("")
        self.mitigationStr.setText("")
        self.colorCombo.setSelectedIndex(0)
        self.threatLevel.setSelectedIndex(0)
        self.screenshotsList.clear()
        self.addButton.setText("Add")
        self.firstPic.setIcon(None)

    def saveRequestResponse(self, type, requestResponse, vulnName):
        path = self.getVulnReqResPath(type,vulnName)
        f = open(path, 'wb')
        f.write(requestResponse)
        f.close()

    def openProj(self, event):
        os.system('explorer ' + self.projPath.getText())

    def getVulnReqResPath(self, requestOrResponse, vulnName):
        return self.getCurrentProjPath() + "/" + self.clearStr(vulnName) + "/"+requestOrResponse+"_" + self.clearStr(vulnName)

    def htmlEscape(self,data):
        return data.replace('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;').replace('"', '&quot;').replace("'", '&#39;')

    def generateReportFromDocxTemplate(self, zipname, newZipName, filename):      
        newZipName = self.getCurrentProjPath() + "/" + newZipName
        with zipfile.ZipFile(zipname, 'r') as zin:
            with zipfile.ZipFile(newZipName, 'w') as zout:
                zout.comment = zin.comment
                for item in zin.infolist():
                    if item.filename != filename:
                        zout.writestr(item, zin.read(item.filename))
                    else:
                        xml_content = zin.read(item.filename)
                        result = re.findall("(.*)<w:body>(?:.*)<\/w:body>(.*)",xml_content)[0]
                        newXML = result[0]
                        templateBody = re.findall("<w:body>(.*)<\/w:body>", xml_content)[0]
                        newBody = ""

                        for i in range(0,self._log.size()):
                            tmp = templateBody
                            tmp = tmp.replace("$vulnerability", self.htmlEscape(self._log.get(i).getName()))
                            tmp = tmp.replace("$severity", self.htmlEscape(self._log.get(i).getSeverity()))
                            tmp = tmp.replace("$description", self.htmlEscape(self._log.get(i).getDescription()))
                            tmp = tmp.replace("$mitigation", self.htmlEscape(self._log.get(i).getMitigation()))
                            newBody = newBody + tmp
                         
                        newXML = newXML + newBody
                        newXML = newXML + result[1]

        with zipfile.ZipFile(newZipName, mode='a', compression=zipfile.ZIP_DEFLATED) as zf:
            zf.writestr(filename, newXML)
        return newZipName


    def chooseProjPath(self, event):
        self.chooser.setDialogTitle("Select target directory")
        self.chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY)
        returnVal = self.chooser.showOpenDialog(None)
        if returnVal == JFileChooser.APPROVE_OPTION:
            projPath = str(self.chooser.getSelectedFile()) + "/PTManager"
            os.makedirs(projPath)
            self.projPath.setText(projPath)

    def reloadProjects(self):
        self.currentProject.setModel(DefaultComboBoxModel(self.config.options('projects')))

    def rmProj(self, event):
        if self.popUpAreYouSure() == JOptionPane.YES_OPTION:
            self._requestViewer.setMessage("None", False)
            self._responseViewer.setMessage("None", False)
            shutil.rmtree(self.projPath.getText())
            self.config.remove_option('projects',self.currentProject.getSelectedItem())
            self.reloadProjects()
            self.currentProject.setSelectedIndex(0)
            self.loadVulnerabilities(self.projPath.getText())

    def popup(self,msg):
        JOptionPane.showMessageDialog(None,msg)

    def addProj(self, event):
        projPath = self.projPath.getText()
        if projPath == None or projPath == "":
            self.popup("Please select path")
            return
        self.config.set('projects', self.projName.getText(), projPath)
        self.saveCfg()
        xml = ET.Element('project')
        name = ET.SubElement(xml, "name")
        path = ET.SubElement(xml, "path")
        details = ET.SubElement(xml, "details")
        autoSaveMode = ET.SubElement(xml, "autoSaveMode")

        name.text = self.projName.getText()
        path.text = projPath
        details.text = self.projDetails.getText()
        autoSaveMode.text = str(self.autoSave.isSelected())
        tree = ET.ElementTree(xml)
        try:
            tree.write(self.getCurrentProjPath()+'/project.xml')
        except:
            self.popup("Invalid path")
            return

        self.reloadProjects()
        self.clearVulnerabilityTab()
        self.clearList(None)
        self.currentProject.getModel().setSelectedItem(self.projName.getText())

    def resize(self, image, width, height):
        bi = BufferedImage(width, height, BufferedImage.TRANSLUCENT)
        g2d = bi.createGraphics()
        g2d.addRenderingHints(RenderingHints(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY))
        g2d.drawImage(image, 0, 0, width, height, None)
        g2d.dispose()
        return bi;

    def clearStr(self, var):
        return var.replace(" " , "_").replace("\\" , "").replace("/" , "").replace(":" , "").replace("*" , "").replace("?" , "").replace("\"" , "").replace("<" , "").replace(">" , "").replace("|" , "").replace("(" , "").replace(")" , "")

    def popUpAreYouSure(self):
        dialogResult = JOptionPane.showConfirmDialog(None,"Are you sure?","Warning",JOptionPane.YES_NO_OPTION)
        if dialogResult == 0:
            return 0
        return 1

    def removeSS(self,event):
        if self.popUpAreYouSure() == JOptionPane.YES_OPTION:
            os.remove(self.getCurrentVulnPath() + "/" + self.ssList.getSelectedValue())
            self.ssList.getModel().remove(self.ssList.getSelectedIndex())
            self.firstPic.setIcon(ImageIcon(None))
            # check if there is images and select the first one
            # bug in linux

    def addSS(self,event):
        clipboard = Toolkit.getDefaultToolkit().getSystemClipboard()
        try:
            image = clipboard.getData(DataFlavor.imageFlavor)
        except:
            self.popup("Clipboard not contains image")
            return
        vulnPath = self.projPath.getText() + "/" + self.clearStr(self.vulnName.getText())
        if not os.path.exists(vulnPath):
            os.makedirs(vulnPath)
        name = self.clearStr(self.vulnName.getText()) + str(random.randint(1, 99999))+".jpg"
        fileName = self.projPath.getText()+"/"+ self.clearStr(self.vulnName.getText()) + "/" + name
        file = File(fileName)
        bufferedImage = BufferedImage(image.getWidth(None), image.getHeight(None), BufferedImage.TYPE_INT_RGB);
        g = bufferedImage.createGraphics();
        g.drawImage(image, 0, 0, bufferedImage.getWidth(), bufferedImage.getHeight(), Color.WHITE, None);
        ImageIO.write(bufferedImage, "jpg", file)
        self.addVuln(self)
        self.ssList.setSelectedValue(name,True)

    def rmVuln(self, event):
        if self.popUpAreYouSure() == JOptionPane.YES_OPTION:
            self._requestViewer.setMessage("None", False)
            self._responseViewer.setMessage("None", False)
            shutil.rmtree(self.getCurrentVulnPath())
            self.clearVulnerabilityTab()
            self.loadVulnerabilities(self.getCurrentProjPath())

    def addVuln(self, event):
        if self.colorCombo.getSelectedItem() == "Color:":
            colorTxt = None
        else:
            colorTxt = self.colorCombo.getSelectedItem()
        self._lock.acquire()
        row = self._log.size()
        vulnObject = vulnerability(self.vulnName.getText(),self.threatLevel.getSelectedItem(),self.descriptionString.getText(),self.mitigationStr.getText() ,colorTxt)
        self._log.add(vulnObject) 
        self.fireTableRowsInserted(row, row)
        self._lock.release()

        vulnPath = self.projPath.getText() + "/" + self.clearStr(self.vulnName.getText())
        if not os.path.exists(vulnPath):
            os.makedirs(vulnPath)

        xml = ET.Element('vulnerability')
        name = ET.SubElement(xml, "name")
        severity = ET.SubElement(xml, "severity")
        description = ET.SubElement(xml, "description")
        mitigation = ET.SubElement(xml, "mitigation")
        color = ET.SubElement(xml, "color")
        name.text = self.vulnName.getText()
        severity.text = self.threatLevel.getSelectedItem()
        description.text = self.descriptionString.getText()
        mitigation.text = self.mitigationStr.getText()
        color.text = colorTxt
        tree = ET.ElementTree(xml)
        tree.write(vulnPath+'/vulnerability.xml')

        self.loadVulnerabilities(self.getCurrentProjPath())
        self.loadVulnerability(vulnObject)

    def vulnNameChanged(self):
            if os.path.exists(self.getCurrentVulnPath()) and self.vulnName.getText() != "":
                self.addButton.setText("Update")
            elif self.addButton.getText() != "Add":
                options = ["Create a new vulnerability", "Change current vulnerability name"]
                n = JOptionPane.showOptionDialog(None,
                    "Would you like to?",
                    "Vulnerability Name",
                    JOptionPane.YES_NO_CANCEL_OPTION,
                    JOptionPane.QUESTION_MESSAGE,
                    None,
                    options,
                    options[0]);

                if n == 0:
                    self.clearVulnerabilityTab(False)
                    self.addButton.setText("Add")
                else:
                    newName = JOptionPane.showInputDialog(
                    None,
                    "Enter new name:",
                    "Vulnerability Name",
                    JOptionPane.PLAIN_MESSAGE,
                    None,
                    None,
                    self.vulnName.getText())
                    row = self.logTable.getSelectedRow()
                    old = self.logTable.getValueAt(row,1)                   
                    self.changeVulnName(newName,old)
                
    def changeVulnName(self,new,old):
        newpath = self.getCurrentProjPath() + "/" + new
        oldpath = self.getCurrentProjPath() + "/" + old
        os.rename(oldpath,newpath)
        self.changeCurrentVuln(new,0, newpath + "/vulnerability.xml")

    def getCurrentVulnPath(self):
        return self.projPath.getText() + "/" + self.clearStr(self.vulnName.getText())

    def getCurrentProjPath(self):
        return self.projPath.getText()

    def loadSS(self, imgPath):
        image = ImageIO.read(File(imgPath))
        if image.getWidth() <= 550 and image.getHeight() <= 400:
            self.firstPic.setIcon(ImageIcon(image))
            self.firstPic.setSize(image.getWidth(),image.getHeight())
        else:
            self.firstPic.setIcon(ImageIcon(self.resize(image,550, 400)))
            self.firstPic.setSize(550,400)

    def clearProjectTab(self):
        self.projPath.setText("")
        self.projDetails.setText("")

    def clearList(self, event):
        self._lock.acquire()
        self._log = ArrayList()
        row = self._log.size()
        self.fireTableRowsInserted(row, row)
        self._lock.release()

    #
    # implement IContextMenuFactory
    #
    def createMenuItems(self, invocation):
        responses = invocation.getSelectedMessages();
        if responses > 0:
            ret = LinkedList()
            requestMenuItem = JMenuItem("Send to PT Manager");
            requestMenuItem.addActionListener(handleMenuItems(self,responses[0], "request"))
            ret.add(requestMenuItem);
            return(ret);
        return null;
    #
    # implement ITab
    #
    def getTabCaption(self):
        return "PT Manager"
    
    def getUiComponent(self):
        return self._splitpane

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

    def getColumnCount(self):
        return 3

    def getColumnName(self, columnIndex):
        if columnIndex == 0:
            return "#"
        if columnIndex == 1:
            return "Vulnerability Name"
        if columnIndex == 2:
            return "Threat Level"
        return ""

    def getValueAt(self, rowIndex, columnIndex):
        vulnObject = self._log.get(rowIndex)
        if columnIndex == 0:
            return rowIndex+1
        if columnIndex == 1:
            return vulnObject.getName()
        if columnIndex == 2:
            return vulnObject.getSeverity()
        if columnIndex == 3:
            return vulnObject.getMitigation()
        if columnIndex == 4:
            return vulnObject.getColor()

        return ""

    def changeCurrentVuln(self,value,fieldNumber, xmlPath = "def"):
        if xmlPath == "def":
            xmlPath = self.getCurrentVulnPath() + "/vulnerability.xml"
        document = self.getXMLDoc(xmlPath)
        nodeList = document.getDocumentElement().getChildNodes()
        nodeList.item(fieldNumber).setTextContent(value)
        self.saveXMLDoc(document, xmlPath)
        self.loadVulnerabilities(self.getCurrentProjPath())

    def loadVulnerability(self, vulnObject):
        self.addButton.setText("Update")
        self.vulnName.setText(vulnObject.getName())
        self.threatLevel.setSelectedItem(vulnObject.getSeverity())
        self.descriptionString.setText(vulnObject.getDescription())
        self.mitigationStr.setText(vulnObject.getMitigation())

        if vulnObject.getColor() == "" or vulnObject.getColor() == None:
            self.colorCombo.setSelectedItem("Color:")
        else:
            self.colorCombo.setSelectedItem(vulnObject.getColor())
        self.screenshotsList.clear()

        for fileName in os.listdir(self.projPath.getText()+"/"+self.clearStr(vulnObject.getName())):
            if fileName.endswith(".jpg"):
                self.screenshotsList.addElement(fileName)
                imgPath = self.projPath.getText()+"/"+self.clearStr(vulnObject.getName())+'/'+fileName
                # imgPath = imgPath.replace("/","//")
                self.loadSS(imgPath)

        if (self.screenshotsList.getSize() == 0):
            self.firstPic.setIcon(None)
        else:
            self.ssList.setSelectedIndex(0)

        path = self.getVulnReqResPath("request",vulnObject.getName())
        if os.path.exists(path):
            f = self.getFileContent(path)
            self._requestViewer.setMessage(f, False)
        else:
            self._requestViewer.setMessage("None", False)
        
        path = self.getVulnReqResPath("response",vulnObject.getName())
        if os.path.exists(path):
            f = self.getFileContent(path)
            self._responseViewer.setMessage(f, False)
        else:
            self._responseViewer.setMessage("None", False)