示例#1
0
class BottomPanel(JPanel):
    def __init__(self):

        self.holdPanel = JPanel()
        self.topPanel = JPanel()
        self.bottomPanel = JPanel()

        self.holdPanel.setBackground(Color.decode('#dddee6'))
        self.topPanel.setBackground(Color.decode('#dddee6'))
        self.bottomPanel.setBackground(Color.decode('#dddee6'))

        self.topPanel.setPreferredSize(Dimension(300, 30))

        self.regBar = JProgressBar()
        self.gatePassBar = JProgressBar()
        self.regLabel = JLabel('Register : ')
        self.gatepassLabel = JLabel('          Gate Pass : '******'')
        self.gatePercentlabel = JLabel('')

        self.refreshButton = JButton('Refresh',
                                     actionPerformed=self.updateProgress)

        self.regBar.setMinimum(0)
        self.regBar.setMaximum(100)
        self.regBar.setStringPainted(True)

        self.gatePassBar.setMinimum(0)
        self.gatePassBar.setMaximum(100)
        self.gatePassBar.setStringPainted(True)

        self.setLayout(BorderLayout())

        self.updateProgress(None)

    def updateProgress(self, e):

        progress = client.get_progress()
        regTotal = progress[0]
        regRecog = progress[1]
        gateTotal = progress[2]
        gateRecog = progress[3]

        regPercent = int((regRecog * 100) / regTotal)
        gatePercent = int((gateRecog * 100) / gateTotal)

        self.regBar.setValue(regPercent)
        self.gatePassBar.setValue(gatePercent)

        self.regBar.setString(str(regPercent) + '%')
        self.gatePassBar.setString(str(gatePercent) + '%')

        self.regPercentlabel.setText(str(regRecog) + '/' + str(regTotal))
        self.gatePercentlabel.setText(
            str(gateRecog) + '/' + str(gateTotal) + '           ')

        if regPercent <= 30:
            regColor = Color.RED
        elif regPercent > 30 and regPercent < 50:
            regColor = Color.ORANGE
        elif regPercent >= 50 and regPercent <= 100:
            regColor = Color.GREEN

        if gatePercent <= 30:
            gateColor = Color.RED
        elif gatePercent > 30 and gatePercent < 50:
            gateColor = Color.ORANGE
        elif gatePercent >= 50 and gatePercent <= 100:
            gateColor = Color.GREEN

        self.regBar.setForeground(regColor)
        self.gatePassBar.setForeground(gateColor)

        self.holdPanel.add(self.regLabel)
        self.holdPanel.add(self.regBar)
        self.holdPanel.add(self.regPercentlabel)
        self.holdPanel.add(self.gatepassLabel)
        self.holdPanel.add(self.gatePassBar)
        self.holdPanel.add(self.gatePercentlabel)
        self.holdPanel.add(self.refreshButton)

        self.add(self.holdPanel, BorderLayout.CENTER)
        self.add(self.topPanel, BorderLayout.PAGE_START)
        self.add(self.bottomPanel, BorderLayout.PAGE_END)

        self.validate()
class MenueFrame(object):
   def __init__(self):
      self.mainDir = ""
   
      self.frame = JFrame("Dots Quality Check", size=(250,300))
      self.frame.setLocation(20,120)
      self.Panel = JPanel(GridLayout(0,1))
      self.frame.add(self.Panel)

      self.openNextButton = JButton('Open Next Random',actionPerformed=openRandom)
      self.Panel.add(self.openNextButton)
      
      self.saveButton = JButton('Save',actionPerformed=save)
      self.saveButton.setEnabled(False)
      self.Panel.add(self.saveButton)

      self.cropButton = JButton('Crop values from here', actionPerformed=cropVals)
      self.Panel.add(self.cropButton)

      self.DiscardButton = JButton('Discard cell', actionPerformed=discardCell)
      self.DiscardButton.setEnabled(True)
      self.Panel.add(self.DiscardButton)

      self.quitButton = JButton('Quit script',actionPerformed=quit)
      self.Panel.add(self.quitButton)

      annoPanel = JPanel()
      #add gridlayout
      wtRButton = JRadioButton("wt", actionCommand="wt")
      defectRButton = JRadioButton("Defect", actionCommand="defect")
      annoPanel.add(wtRButton)
      annoPanel.add(defectRButton)
      self.aButtonGroup = ButtonGroup()
      self.aButtonGroup.add(wtRButton)
      self.aButtonGroup.add(defectRButton)
      
      self.Panel.add(annoPanel)

      self.ProgBar = JProgressBar()
      self.ProgBar.setStringPainted(True)
      self.ProgBar.setValue(0)
      self.Panel.add(self.ProgBar)

      self.pathLabel = JLabel("-- No main directory chosen --")
      self.pathLabel.setHorizontalAlignment( SwingConstants.CENTER )
      self.Panel.add(self.pathLabel)

      
      WindowManager.addWindow(self.frame)
      self.show()

   def show(self):
      self.frame.visible = True

   def getFrame(self):
      return self.frame

   def setSaveActive(self):
      self.saveButton.setEnabled(True)
      self.show()

   def setSaveInactive(self):
      self.saveButton.setEnabled(False)
      self.show()

   def setMainDir(self, path):
      self.mainDir = path
      self.pathLabel.setText("MainDir: " + os.path.basename(os.path.split(self.mainDir)[0]))

   def getMainDir(self):
      return self.mainDir

   def setProgBarMax(self, maximum):
      self.ProgBar.setMaximum(maximum)

   def setProgBarVal(self, value):
      self.ProgBar.setValue(value)

   def close():
      WindowManager.removeWindow(self.frame)
      self.frame.dispose()     
示例#3
0
    def __init__(self, imgData):
        n = imgData.size()
        win = JFrame("Point Marker Panel")
        win.setPreferredSize(Dimension(350, 590))
        win.setSize(win.getPreferredSize())
        pan = JPanel()
        pan.setLayout(BoxLayout(pan, BoxLayout.Y_AXIS))
        win.getContentPane().add(pan)

        progressPanel = JPanel()
        progressPanel.setLayout(BoxLayout(progressPanel, BoxLayout.Y_AXIS))
        positionBar = JProgressBar()
        positionBar.setMinimum(0)
        positionBar.setMaximum(n)
        positionBar.setStringPainted(True)
        progressPanel.add(Box.createGlue())
        progressPanel.add(positionBar)

        progressBar = JProgressBar()
        progressBar.setMinimum(0)
        progressBar.setMaximum(n)
        progressBar.setStringPainted(True)
        progressPanel.add(progressBar)
        progressPanel.setBorder(BorderFactory.createEmptyBorder(0, 10, 0, 10))
        pan.add(progressPanel)

        pan.add(Box.createRigidArea(Dimension(5, 5)))
        savePanel = JPanel()
        savePanel.setLayout(BoxLayout(savePanel, BoxLayout.Y_AXIS))
        saveMessageLabel = JLabel("<html><u>Save Often</u></html>")
        savePanel.add(saveMessageLabel)
        savePanel.setAlignmentX(Component.CENTER_ALIGNMENT)
        savePanel.setBorder(BorderFactory.createEmptyBorder(0, 10, 0, 10))
        pan.add(savePanel)
        # pan.add(saveMessageLabel)

        pan.add(Box.createRigidArea(Dimension(5, 5)))
        calPanel = JPanel()
        calPanel.setLayout(BoxLayout(calPanel, BoxLayout.Y_AXIS))
        calPanelIn = JPanel()
        calPanelIn.setLayout(BoxLayout(calPanelIn, BoxLayout.X_AXIS))
        pixelSizeText = JTextField(12)
        pixelSizeText.setHorizontalAlignment(JTextField.RIGHT)
        # pixelSizeText.setMaximumSize(pixelSizeText.getPreferredSize())
        unitText = JTextField(10)
        # unitText.setMaximumSize(unitText.getPreferredSize())
        pixelSizeText.setText("Enter Pixel Size Here")
        calPanelIn.add(pixelSizeText)
        unitText.setText("Unit")
        calPanelIn.add(unitText)
        calPanelIn.setAlignmentX(Component.CENTER_ALIGNMENT)
        calPanelIn.setBorder(
            BorderFactory.createTitledBorder("Custom Calibration"))
        calPanel.add(calPanelIn)
        calPanelIn.setAlignmentX(Component.CENTER_ALIGNMENT)
        calPanel.setBorder(BorderFactory.createEmptyBorder(0, 10, 0, 10))
        pan.add(calPanel)

        pan.add(Box.createRigidArea(Dimension(5, 5)))
        helpPanel = JPanel()
        helpPanel.setLayout(BoxLayout(helpPanel, BoxLayout.Y_AXIS))
        helpLable = JLabel("<html><ul>\
                            <li>Focus on Image Window</li>\
                            <li>Select multi-point Tool</li>\
                            <li>Click to Draw Points</li>\
                            <li>Drag to Move Points</li>\
                            <li>\"Alt\" + Click to Erase Points</li>\
                            <li>Optional: Customize Calibration Above\
                                 and Refresh Images\
                                (won't be written to files)</li>\
                            </html>")
        helpLable.setBorder(BorderFactory.createTitledBorder("Usage"))
        keyTagOpen = "<span style=\"background-color: #FFFFFF\"><b><kbd>"
        keyTagClose = "</kbd></b></span>"
        keyLable = JLabel("<html><ul>\
                            <li>Next Image --- "                                                 + keyTagOpen + "&lt" + \
                                keyTagClose + "</li>\
                            <li>Previous Image --- "                                                     + keyTagOpen + ">" + \
                                keyTagClose + "</li>\
                            <li>Save --- "                                           + keyTagOpen + "`" + keyTagClose + \
                                " (upper-left to TAB key)</li>\
                            <li>Next Unmarked Image --- "                                                          + keyTagOpen + \
                                "TAB" + keyTagClose + "</li></ul>\
                            </html>"                                    )
        keyLable.setBorder(
            BorderFactory.createTitledBorder("Keyboard Shortcuts"))
        helpPanel.add(helpLable)
        helpPanel.add(keyLable)
        helpPanel.setAlignmentX(Component.CENTER_ALIGNMENT)
        helpPanel.setBorder(BorderFactory.createEmptyBorder(0, 10, 0, 10))
        pan.add(helpPanel)

        # pan.add(Box.createRigidArea(Dimension(0, 10)))
        infoPanel = JPanel()
        infoPanel.setLayout(BoxLayout(infoPanel, BoxLayout.Y_AXIS))
        infoLabel = JLabel()
        infoLabel.setBorder(BorderFactory.createTitledBorder("Project Info"))
        infoPanel.add(infoLabel)
        infoPanel.setAlignmentX(Component.CENTER_ALIGNMENT)
        infoPanel.setBorder(BorderFactory.createEmptyBorder(0, 10, 0, 10))
        pan.add(infoPanel)

        win.setVisible(True)

        self.imgData = imgData
        self.win = win
        # self.progressPanel = progressPanel
        self.positionBar = positionBar
        self.progressBar = progressBar
        self.saveMessageLabel = saveMessageLabel
        self.infoLabel = infoLabel
        self.pixelSizeText = pixelSizeText
        self.unitText = unitText
        self.update()
示例#4
0
class BurpExtender(
          IBurpExtender, ITab, IContextMenuFactory, IMessageEditorController):

    # Implement IBurpExtender
    def registerExtenderCallbacks(self, callbacks):

        callbacks.registerContextMenuFactory(self)

        self._callbacks = callbacks
        self._helpers = callbacks.getHelpers()

        callbacks.setExtensionName(EXTENSION_NAME)

        # Construct UI
        insets = Insets(3, 3, 3, 3)
        self._messageEditor = callbacks.createMessageEditor(self, True)
        attackPanel = self._constructAttackPanel(
            insets, self._messageEditor.getComponent())
        resultsPanel = self._constructResultsPanel(insets)
        aboutPanel = self._constructAboutPanel(insets)
        self._tabbedPane = JTabbedPane()
        self._tabbedPane.addTab("Attack", attackPanel)
        self._tabbedPane.addTab("Results", resultsPanel)
        self._tabbedPane.addTab("About", aboutPanel)
        callbacks.addSuiteTab(self)

    # Implement ITab
    def getTabCaption(self):
        return EXTENSION_NAME

    def getUiComponent(self):
        return self._tabbedPane

    # Implement IMessageEditorController
    def getHttpService(self):
        self._updateClassFromUI()
        return self._httpService

    def getRequest(self):
        self._updateClassFromUI()
        return self._request

    def getResponse(self):
        return None

    # Implement IContextMenuFactory
    def createMenuItems(self, contextMenuInvocation):
        messages = contextMenuInvocation.getSelectedMessages()

        # Only add menu item if a single request is selected
        if len(messages) == 1:
            self._contextMenuData = messages
            menu_item = JMenuItem(
                "Send to {}".format(EXTENSION_NAME),
                actionPerformed=self._contextMenuItemClicked
            )
            return [menu_item]

    def _contextMenuItemClicked(self, _):
        httpRequestResponse = self._contextMenuData[0]

        # Update instance variables with request data
        self._httpService = httpRequestResponse.getHttpService()
        self._request = httpRequestResponse.getRequest()

        # Update fields in tab
        self._hostTextField.setText(self._httpService.getHost())
        self._portTextField.setText(str(self._httpService.getPort()))
        self._protocolCheckBox.setSelected(
            True if self._httpService.getProtocol() == "https" else False)
        self._messageEditor.setMessage(self._request, True)

    def _startAttack(self, _):

        # Switch to results tab
        self._tabbedPane.setSelectedIndex(1)

        # Clear results table
        self._resultsTableModel.setRowCount(0)

        # Set progress bar to 0%
        self._progressBar.setValue(0)

        Thread(target=self._makeHttpRequests).start()

    def _makeHttpRequests(self):

        # Set class variables from values in UI
        self._updateClassFromUI()

        self._responses = {}

        # Set progress bar max to number of requests
        self._progressBar.setMaximum(len(self._payloads) * self._numReq)

        for payload in self._payloads:
            self._responses[payload] = []
            # Stick payload into request at specified position
            # Use lambda function for replacement string to stop slashes being
            # escaped
            request = sub("\xa7[^\xa7]*\xa7", lambda x: payload, self._request)
            request = self._updateContentLength(request)
            for _ in xrange(self._numReq):
                # Make request and work out how long it took in ms. This method
                # is crude, but it's as good as we can get with current Burp
                # APIs.
                # See https://support.portswigger.net/customer/portal/questions/16227838-request-response-timing # noqa: E501
                startTime = time()
                response = self._callbacks.makeHttpRequest(
                    self._httpService, request)
                endTime = time()
                duration = (endTime - startTime) * 1000

                self._progressBar.setValue(self._progressBar.getValue() + 1)

                self._responses[payload].append(duration)

            # If all responses for this payload have
            # been added to array, add to results table.
            results = self._responses[payload]
            numReqs = self._numReq
            statusCode = response.getStatusCode()
            analysis = self._helpers.analyzeResponse(
                response.getResponse())
            for header in analysis.getHeaders():
                if header.lower().startswith("content-length"):
                    content_length = int(header.split(": ")[1])
            meanTime = round(mean(results), 3)
            medianTime = round(median(results), 3)
            stdDevTime = round(stdDev(results), 3)
            minTime = int(min(results))
            maxTime = int(max(results))
            rowData = [
                payload, numReqs, statusCode,
                len(response.getResponse()), content_length, minTime,
                maxTime, meanTime, medianTime, stdDevTime]
            self._resultsTableModel.addRow(rowData)

    def _updateClassFromUI(self):
        host = self._hostTextField.text
        port = int(self._portTextField.text)
        protocol = "https" if self._protocolCheckBox.isSelected() else "http"
        # In an effort to prevent DNS queries introducing a delay, an attempt
        # was made to use the IP address of the destination web server instead
        # of the hostname when building the HttpService. Unfortunately it
        # caused issues with HTTPS requests, probably because of SNIs. As an
        # alternative, the hostname is resolved in the next line and hopefully
        # it will be cached at that point.
        gethostbyname(host)

        self._httpService = self._helpers.buildHttpService(
            host, port, protocol)
        self._request = self._messageEditor.getMessage()
        self._numReq = int(self._requestsNumTextField.text)
        self._payloads = set(self._payloadTextArea.text.split("\n"))

    def _addPayload(self, _):
        request = self._messageEditor.getMessage()
        selection = self._messageEditor.getSelectionBounds()
        if selection[0] == selection[1]:
            # No text selected so in/out points are same
            request.insert(selection[0], 0xa7)
            request.insert(selection[1], 0xa7)
        else:
            request.insert(selection[0], 0xa7)
            request.insert(selection[1]+1, 0xa7)
        self._messageEditor.setMessage(request, True)

    def _clearPayloads(self, _):
        request = self._messageEditor.getMessage()
        request = self._helpers.bytesToString(request).replace("\xa7", "")
        self._messageEditor.setMessage(request, True)

    def _updateContentLength(self, request):
        messageSize = len(request)
        bodyOffset = self._helpers.analyzeRequest(request).getBodyOffset()
        contentLength = messageSize - bodyOffset
        contentLengthHeader = "Content-Length: {}".format(contentLength)
        request = sub("Content-Length: \\d+", contentLengthHeader, request)
        return request

    def _constructAttackPanel(self, insets, messageEditorComponent):
        attackPanel = JPanel(GridBagLayout())

        targetHeadingLabel = JLabel("<html><b>Target</b></html>")
        targetHeadingLabelConstraints = GridBagConstraints()
        targetHeadingLabelConstraints.gridx = 0
        targetHeadingLabelConstraints.gridy = 0
        targetHeadingLabelConstraints.gridwidth = 4
        targetHeadingLabelConstraints.anchor = GridBagConstraints.LINE_START
        targetHeadingLabelConstraints.insets = insets
        attackPanel.add(targetHeadingLabel, targetHeadingLabelConstraints)

        startAttackButton = JButton("<html><b>Start Attack</b></html>",
                                    actionPerformed=self._startAttack)
        startAttackButtonConstraints = GridBagConstraints()
        startAttackButtonConstraints.gridx = 4
        startAttackButtonConstraints.gridy = 0
        startAttackButtonConstraints.insets = insets
        attackPanel.add(startAttackButton, startAttackButtonConstraints)

        hostLabel = JLabel("Host:")
        hostLabelConstraints = GridBagConstraints()
        hostLabelConstraints.gridx = 0
        hostLabelConstraints.gridy = 1
        hostLabelConstraints.anchor = GridBagConstraints.LINE_START
        hostLabelConstraints.insets = insets
        attackPanel.add(hostLabel, hostLabelConstraints)

        self._hostTextField = JTextField(25)
        self._hostTextField.setMinimumSize(
            self._hostTextField.getPreferredSize())
        hostTextFieldConstraints = GridBagConstraints()
        hostTextFieldConstraints.gridx = 1
        hostTextFieldConstraints.gridy = 1
        hostTextFieldConstraints.weightx = 1
        hostTextFieldConstraints.gridwidth = 2
        hostTextFieldConstraints.anchor = GridBagConstraints.LINE_START
        hostTextFieldConstraints.insets = insets
        attackPanel.add(self._hostTextField, hostTextFieldConstraints)

        portLabel = JLabel("Port:")
        portLabelConstraints = GridBagConstraints()
        portLabelConstraints.gridx = 0
        portLabelConstraints.gridy = 2
        portLabelConstraints.anchor = GridBagConstraints.LINE_START
        portLabelConstraints.insets = insets
        attackPanel.add(portLabel, portLabelConstraints)

        self._portTextField = JTextField(5)
        self._portTextField.setMinimumSize(
            self._portTextField.getPreferredSize())
        portTextFieldConstraints = GridBagConstraints()
        portTextFieldConstraints.gridx = 1
        portTextFieldConstraints.gridy = 2
        portTextFieldConstraints.gridwidth = 2
        portTextFieldConstraints.anchor = GridBagConstraints.LINE_START
        portTextFieldConstraints.insets = insets
        attackPanel.add(self._portTextField, portTextFieldConstraints)

        self._protocolCheckBox = JCheckBox("Use HTTPS")
        protocolCheckBoxConstraints = GridBagConstraints()
        protocolCheckBoxConstraints.gridx = 0
        protocolCheckBoxConstraints.gridy = 3
        protocolCheckBoxConstraints.gridwidth = 3
        protocolCheckBoxConstraints.anchor = GridBagConstraints.LINE_START
        protocolCheckBoxConstraints.insets = insets
        attackPanel.add(self._protocolCheckBox, protocolCheckBoxConstraints)

        requestHeadingLabel = JLabel("<html><b>Request</b></html>")
        requestHeadingLabelConstraints = GridBagConstraints()
        requestHeadingLabelConstraints.gridx = 0
        requestHeadingLabelConstraints.gridy = 4
        requestHeadingLabelConstraints.gridwidth = 4
        requestHeadingLabelConstraints.anchor = GridBagConstraints.LINE_START
        requestHeadingLabelConstraints.insets = insets
        attackPanel.add(requestHeadingLabel, requestHeadingLabelConstraints)

        messageEditorComponentConstraints = GridBagConstraints()
        messageEditorComponentConstraints.gridx = 0
        messageEditorComponentConstraints.gridy = 5
        messageEditorComponentConstraints.weightx = 1
        messageEditorComponentConstraints.weighty = .75
        messageEditorComponentConstraints.gridwidth = 4
        messageEditorComponentConstraints.gridheight = 2
        messageEditorComponentConstraints.fill = GridBagConstraints.BOTH
        messageEditorComponentConstraints.insets = insets
        attackPanel.add(
            messageEditorComponent, messageEditorComponentConstraints)

        addPayloadButton = JButton(
            "Add \xa7", actionPerformed=self._addPayload)
        addPayloadButtonConstraints = GridBagConstraints()
        addPayloadButtonConstraints.gridx = 4
        addPayloadButtonConstraints.gridy = 5
        addPayloadButtonConstraints.fill = GridBagConstraints.HORIZONTAL
        addPayloadButtonConstraints.insets = insets
        attackPanel.add(addPayloadButton, addPayloadButtonConstraints)

        clearPayloadButton = JButton(
            "Clear \xa7", actionPerformed=self._clearPayloads)
        clearPayloadButtonConstraints = GridBagConstraints()
        clearPayloadButtonConstraints.gridx = 4
        clearPayloadButtonConstraints.gridy = 6
        clearPayloadButtonConstraints.anchor = GridBagConstraints.PAGE_START
        clearPayloadButtonConstraints.fill = GridBagConstraints.HORIZONTAL
        clearPayloadButtonConstraints.insets = insets
        attackPanel.add(clearPayloadButton, clearPayloadButtonConstraints)

        payloadHeadingLabel = JLabel("<html><b>Payloads<b></html>")
        payloadHeadingLabelConstraints = GridBagConstraints()
        payloadHeadingLabelConstraints.gridx = 0
        payloadHeadingLabelConstraints.gridy = 7
        payloadHeadingLabelConstraints.gridwidth = 4
        payloadHeadingLabelConstraints.anchor = GridBagConstraints.LINE_START
        payloadHeadingLabelConstraints.insets = insets
        attackPanel.add(payloadHeadingLabel, payloadHeadingLabelConstraints)

        self._payloadTextArea = JTextArea()
        payloadScrollPane = JScrollPane(self._payloadTextArea)
        payloadScrollPaneConstraints = GridBagConstraints()
        payloadScrollPaneConstraints.gridx = 0
        payloadScrollPaneConstraints.gridy = 8
        payloadScrollPaneConstraints.weighty = .25
        payloadScrollPaneConstraints.gridwidth = 3
        payloadScrollPaneConstraints.fill = GridBagConstraints.BOTH
        payloadScrollPaneConstraints.insets = insets
        attackPanel.add(payloadScrollPane, payloadScrollPaneConstraints)

        requestsNumLabel = JLabel("Number of requests for each payload:")
        requestsNumLabelConstraints = GridBagConstraints()
        requestsNumLabelConstraints.gridx = 0
        requestsNumLabelConstraints.gridy = 9
        requestsNumLabelConstraints.gridwidth = 2
        requestsNumLabelConstraints.anchor = GridBagConstraints.LINE_START
        requestsNumLabelConstraints.insets = insets
        attackPanel.add(requestsNumLabel, requestsNumLabelConstraints)

        self._requestsNumTextField = JTextField("100", 4)
        self._requestsNumTextField.setMinimumSize(
            self._requestsNumTextField.getPreferredSize())
        requestsNumTextFieldConstraints = GridBagConstraints()
        requestsNumTextFieldConstraints.gridx = 2
        requestsNumTextFieldConstraints.gridy = 9
        requestsNumTextFieldConstraints.anchor = GridBagConstraints.LINE_START
        requestsNumTextFieldConstraints.insets = insets
        attackPanel.add(
            self._requestsNumTextField, requestsNumTextFieldConstraints)

        return attackPanel

    def _constructResultsPanel(self, insets):
        resultsPanel = JPanel(GridBagLayout())

        self._progressBar = JProgressBar()
        self._progressBar.setStringPainted(True)
        self._progressBar.setMinimum(0)
        progressBarContraints = GridBagConstraints()
        progressBarContraints.gridx = 0
        progressBarContraints.gridy = 0
        progressBarContraints.fill = GridBagConstraints.HORIZONTAL

        resultsPanel.add(self._progressBar, progressBarContraints)

        self._resultsTableModel = ResultsTableModel(COLUMNS, 0)
        resultsTable = JTable(self._resultsTableModel)
        resultsTable.setAutoCreateRowSorter(True)
        cellRenderer = ColoredTableCellRenderer()
        for index in [5, 6, 7, 8, 9]:
            column = resultsTable.columnModel.getColumn(index)
            column.cellRenderer = cellRenderer
        resultsTable.getColumnModel().getColumn(0).setPreferredWidth(99999999)
        resultsTable.getColumnModel().getColumn(1).setMinWidth(160)
        resultsTable.getColumnModel().getColumn(2).setMinWidth(100)
        resultsTable.getColumnModel().getColumn(3).setMinWidth(80)
        resultsTable.getColumnModel().getColumn(4).setMinWidth(80)
        resultsTable.getColumnModel().getColumn(5).setMinWidth(110)
        resultsTable.getColumnModel().getColumn(6).setMinWidth(110)
        resultsTable.getColumnModel().getColumn(7).setMinWidth(90)
        resultsTable.getColumnModel().getColumn(8).setMinWidth(110)
        resultsTable.getColumnModel().getColumn(9).setMinWidth(110)
        resultsTable.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS)
        resultsScrollPane = JScrollPane(resultsTable)
        resultsScrollPaneConstraints = GridBagConstraints()
        resultsScrollPaneConstraints.gridx = 0
        resultsScrollPaneConstraints.gridy = 1
        resultsScrollPaneConstraints.weightx = 1
        resultsScrollPaneConstraints.weighty = 1
        resultsScrollPaneConstraints.fill = GridBagConstraints.BOTH
        resultsPanel.add(resultsScrollPane, resultsScrollPaneConstraints)

        return resultsPanel

    def _constructAboutPanel(self, insets):
        aboutPanel = JPanel(GridBagLayout())
        with open("about.html") as file:
            aboutBody = file.read()
        aboutLabel = JLabel(
                aboutBody.format(extension_name=EXTENSION_NAME))
        aboutLabelConstraints = GridBagConstraints()
        aboutLabelConstraints.weightx = 1
        aboutLabelConstraints.weighty = 1
        aboutLabelConstraints.insets = insets
        aboutLabelConstraints.fill = GridBagConstraints.HORIZONTAL
        aboutLabelConstraints.anchor = GridBagConstraints.PAGE_START
        aboutPanel.add(aboutLabel, aboutLabelConstraints)

        return aboutPanel
示例#5
0
class Gui(JFrame):
    '''
    classdocs
    '''


    def __init__(self, pP):
        '''
        Constructor
        '''
        self.pP = pP
        self.annotationType = self.pP.getAnnotationType()
        
        self.setTitle("Random Picture Picker")

        #annotation Panel
        annoPanel = JPanel()
        annoPanel.setBorder(BorderFactory.createTitledBorder("Annotations"))
        annoPLayout = GroupLayout(annoPanel)
        annoPanel.setLayout(annoPLayout)
        annoPLayout.setAutoCreateContainerGaps(True)
        annoPLayout.setAutoCreateGaps(True)        

        # dynamic creation of annotation panel
        # yesNoIgnore, int, number, list
        if len(self.pP.getAnnotationType()) == 1:
            self.annoField = JTextField("", 16)
            annoPLayout.setHorizontalGroup(annoPLayout.createParallelGroup().addComponent(self.annoField))
            annoPLayout.setVerticalGroup(annoPLayout.createSequentialGroup().addComponent(self.annoField))
        elif len(self.pP.getAnnotationType()) > 1:
            choices = pP.getAnnotationType()
            print "choices", choices
            choiceBtns = []
            self.annoField = ButtonGroup()
            for c in choices:
                Btn = JRadioButton(c, actionCommand=c)
                self.annoField.add(Btn)
                choiceBtns.append(Btn)
          
            h = annoPLayout.createParallelGroup()
            for b in choiceBtns:
                h.addComponent(b)
            annoPLayout.setHorizontalGroup(h)
            
            v = annoPLayout.createSequentialGroup()
            for b in choiceBtns:
                v.addComponent(b)
            annoPLayout.setVerticalGroup(v)


        # Control Panel
        ctrlPanel = JPanel()
        ctrlPLayout = GroupLayout(ctrlPanel, autoCreateContainerGaps=True, autoCreateGaps=True)
        ctrlPanel.setLayout(ctrlPLayout)
        
        nextImgButton = JButton("Next >", actionPerformed=self.nextPicture)
        prevImgButton = JButton("< Prev", actionPerformed=self.pP.prevPicture)
        quitButton = JButton("Quit", actionPerformed=self.exit)

        ctrlPLayout.setHorizontalGroup(ctrlPLayout.createParallelGroup(GroupLayout.Alignment.CENTER)
                                       .addGroup(ctrlPLayout.createSequentialGroup()
                                                 .addComponent(prevImgButton)
                                                 .addComponent(nextImgButton))
                                       .addComponent(quitButton))
        ctrlPLayout.setVerticalGroup(ctrlPLayout.createSequentialGroup()
                                     .addGroup(ctrlPLayout.createParallelGroup()
                                               .addComponent(prevImgButton)
                                               .addComponent(nextImgButton))
                                     .addComponent(quitButton))
        ctrlPLayout.linkSize(SwingConstants.HORIZONTAL, quitButton)

        
        statusPanel = JPanel()   # contains status information: progress bar
        self.progressBar = JProgressBar()
        self.progressBar.setStringPainted(True)
        self.progressBar.setValue(0)
        statusPanel.add(self.progressBar)
        
        #MainLayout
        mainLayout = GroupLayout(self.getContentPane())
        self.getContentPane().setLayout(mainLayout)
        
        mainLayout.setHorizontalGroup(mainLayout.createParallelGroup(GroupLayout.Alignment.CENTER)
                                    .addComponent(annoPanel)
                                    .addComponent(ctrlPanel)
                                    .addComponent(statusPanel)
                                    )
        mainLayout.setVerticalGroup(mainLayout.createSequentialGroup()
                                    .addComponent(annoPanel)
                                    .addComponent(ctrlPanel)
                                    .addComponent(statusPanel)
                                    )
        mainLayout.linkSize(SwingConstants.HORIZONTAL, annoPanel, ctrlPanel, statusPanel)
         
      
        self.pack()
        self.setVisible(True)
        
        self.pP.nextPicture()
        
    def nextPicture(self, event):
        percent = (float(len(self.pP.usedList))/len(self.pP.pictureList))*100
        self.progressBar.setValue(int(percent))

        self.setAnnotation()
        self.pP.nextPicture()

        #try:
        #    self.setAnnotation()
        #    self.pP.nextPicture()
        #except AttributeError:
        #    print "Please choose something!"
     
    def setAnnotationField(self, a):
        if len(self.pP.getAnnotationType()) > 1:
            [Rbutton.setSelected(True) for Rbutton in self.annoField.getElements() if Rbutton.getActionCommand()==a]
        if len(self.pP.getAnnotationType()) == 1:
            self.annoField.setText(a)
        
    #rename this method to something clearer!    
    def setAnnotation(self):
        if len(self.pP.getAnnotationType()) > 1:
            annotation = self.annoField.getSelection().getActionCommand()
        if len(self.pP.getAnnotationType()) == 1:
            annotation = self.annoField.getText()
            self.annoField.setText(None)
        self.pP.getCurrentPicture().annotate(annotation)
        
    def getAnnotation(self):
        return self.annotation
    
    def exit(self, event):
        self.pP.exit()
        self.dispose()
    def __init__(self, imgData):
        n = imgData.size()
        win = JFrame("Point Marker Panel")
        win.setPreferredSize(Dimension(350, 590))
        win.setSize(win.getPreferredSize())
        pan = JPanel()
        pan.setLayout(BoxLayout(pan, BoxLayout.Y_AXIS))
        win.getContentPane().add(pan)

        progressPanel = JPanel()
        progressPanel.setLayout(BoxLayout(progressPanel, BoxLayout.Y_AXIS))
        positionBar = JProgressBar()
        positionBar.setMinimum(0)
        positionBar.setMaximum(n)
        positionBar.setStringPainted(True)
        progressPanel.add(Box.createGlue())
        progressPanel.add(positionBar)

        progressBar = JProgressBar()
        progressBar.setMinimum(0)
        progressBar.setMaximum(n)
        progressBar.setStringPainted(True)
        progressPanel.add(progressBar)
        progressPanel.setBorder(BorderFactory.createEmptyBorder(0,10,0,10))
        pan.add(progressPanel)

        pan.add(Box.createRigidArea(Dimension(5,5)))
        savePanel = JPanel()
        savePanel.setLayout(BoxLayout(savePanel, BoxLayout.Y_AXIS))
        saveMessageLabel = JLabel("<html><u>Save Often</u></html>")
        savePanel.add(saveMessageLabel)
        savePanel.setAlignmentX(Component.CENTER_ALIGNMENT)
        savePanel.setBorder(BorderFactory.createEmptyBorder(0,10,0,10))
        pan.add(savePanel)
        # pan.add(saveMessageLabel)

        pan.add(Box.createRigidArea(Dimension(5,5)))
        calPanel = JPanel()
        calPanel.setLayout(BoxLayout(calPanel, BoxLayout.Y_AXIS))
        calPanelIn = JPanel()
        calPanelIn.setLayout(BoxLayout(calPanelIn, BoxLayout.X_AXIS))
        pixelSizeText = JTextField(12)
        pixelSizeText.setHorizontalAlignment(JTextField.RIGHT)
        # pixelSizeText.setMaximumSize(pixelSizeText.getPreferredSize())
        unitText = JTextField(10)
        # unitText.setMaximumSize(unitText.getPreferredSize())
        pixelSizeText.setText("Enter Pixel Size Here")
        calPanelIn.add(pixelSizeText)
        unitText.setText("Unit")
        calPanelIn.add(unitText)
        calPanelIn.setAlignmentX(Component.CENTER_ALIGNMENT)
        calPanelIn.setBorder(BorderFactory.createTitledBorder("Custom Calibration"))
        calPanel.add(calPanelIn)
        calPanelIn.setAlignmentX(Component.CENTER_ALIGNMENT)
        calPanel.setBorder(BorderFactory.createEmptyBorder(0,10,0,10))
        pan.add(calPanel)

        pan.add(Box.createRigidArea(Dimension(5,5)))
        helpPanel = JPanel()
        helpPanel.setLayout(BoxLayout(helpPanel, BoxLayout.Y_AXIS))
        helpLable = JLabel("<html><ul>\
                            <li>Focus on Image Window</li>\
                            <li>Select multi-point Tool</li>\
                            <li>Click to Draw Points</li>\
                            <li>Drag to Move Points</li>\
                            <li>\"Alt\" + Click to Erase Points</li>\
                            <li>Optional: Customize Calibration Above\
                                 and Refresh Images\
                                (won't be written to files)</li>\
                            </html>")
        helpLable.setBorder(BorderFactory.createTitledBorder("Usage"))
        keyTagOpen = "<span style=\"background-color: #FFFFFF\"><b><kbd>"
        keyTagClose = "</kbd></b></span>"
        keyLable = JLabel("<html><ul>\
                            <li>Next Image --- " + keyTagOpen + "&lt" + \
                                keyTagClose + "</li>\
                            <li>Previous Image --- " + keyTagOpen + ">" + \
                                keyTagClose + "</li>\
                            <li>Save --- " + keyTagOpen + "`" + keyTagClose + \
                                " (upper-left to TAB key)</li>\
                            <li>Next Unmarked Image --- " + keyTagOpen + \
                                "TAB" + keyTagClose + "</li></ul>\
                            </html>")
        keyLable.setBorder(BorderFactory.createTitledBorder("Keyboard Shortcuts"))
        helpPanel.add(helpLable)
        helpPanel.add(keyLable)
        helpPanel.setAlignmentX(Component.CENTER_ALIGNMENT)
        helpPanel.setBorder(BorderFactory.createEmptyBorder(0,10,0,10))
        pan.add(helpPanel)

        # pan.add(Box.createRigidArea(Dimension(0, 10)))
        infoPanel = JPanel()
        infoPanel.setLayout(BoxLayout(infoPanel, BoxLayout.Y_AXIS))
        infoLabel = JLabel()
        infoLabel.setBorder(BorderFactory.createTitledBorder("Project Info"))
        infoPanel.add(infoLabel)
        infoPanel.setAlignmentX(Component.CENTER_ALIGNMENT)
        infoPanel.setBorder(BorderFactory.createEmptyBorder(0,10,0,10))
        pan.add(infoPanel)

        win.setVisible(True)

        self.imgData = imgData
        self.win = win
        # self.progressPanel = progressPanel
        self.positionBar = positionBar
        self.progressBar = progressBar
        self.saveMessageLabel = saveMessageLabel
        self.infoLabel = infoLabel
        self.pixelSizeText = pixelSizeText
        self.unitText = unitText
        self.update()
示例#7
0
class BurpExtender(IBurpExtender, ITab, IExtensionStateListener):
    # Define the global variables for the burp plugin
    EXTENSION_NAME = "UPnP BHunter"
    ipv4_selected = True
    services_dict = {}
    ip_service_dict = {}
    STOP_THREAD = False

    #Some  SSDP m-search parameters are based upon "UPnP Device Architecture v2.0"
    SSDP_MULTICAST_IPv4 = ["239.255.255.250"]
    SSDP_MULTICAST_IPv6 = ["FF02::C", "FF05::C"]
    SSDP_MULTICAST_PORT = 1900
    ST_ALL = "ssdp:all"
    ST_ROOTDEV = "upnp:rootdevice"
    PLACEHOLDER = "FUZZ_HERE"
    SSDP_TIMEOUT = 2

    def registerExtenderCallbacks(self, callbacks):
        # Get a reference to callbacks object
        self.callbacks = callbacks
        # Get the useful extension helpers object
        self.helpers = callbacks.getHelpers()
        # Set the extension name
        self.callbacks.setExtensionName(self.EXTENSION_NAME)
        self.callbacks.registerExtensionStateListener(self)
        # Draw plugin user interface
        self.drawPluginUI()
        self.callbacks.addSuiteTab(self)
        # Plugin loading message
        print("[+] Burp plugin UPnP BHunter loaded successfully")
        return

    def drawPluginUI(self):
        # Create the plugin user interface
        self.pluginTab = JPanel()
        self.uiTitle = JLabel('UPnP BHunter Load, Aim and Fire Console')
        self.uiTitle.setFont(Font('Tahoma', Font.BOLD, 14))
        self.uiTitle.setForeground(Color(250, 100, 0))
        self.uiPanelA = JSplitPane(JSplitPane.VERTICAL_SPLIT)
        self.uiPanelA.setMaximumSize(Dimension(2500, 1000))
        self.uiPanelA.setDividerSize(2)
        self.uiPanelB = JSplitPane(JSplitPane.VERTICAL_SPLIT)
        self.uiPanelB.setDividerSize(2)
        self.uiPanelA.setBottomComponent(self.uiPanelB)
        self.uiPanelA.setBorder(BorderFactory.createLineBorder(Color.gray))

        # Create and configure labels and text fields
        self.labeltitle_step1 = JLabel("[1st STEP] Discover UPnP Locations")
        self.labeltitle_step1.setFont(Font('Tahoma', Font.BOLD, 14))
        self.labeltitle_step2 = JLabel(
            "[2nd STEP] Select a UPnP Service and Action")
        self.labeltitle_step2.setFont(Font('Tahoma', Font.BOLD, 14))
        self.labeltitle_step3 = JLabel("[3rd STEP] Time to Attack it")
        self.labeltitle_step3.setFont(Font('Tahoma', Font.BOLD, 14))
        self.labelsubtitle_step1 = JLabel(
            "Specify the IP version address in scope and start UPnP discovery")
        self.labelsubtitle_step2 = JLabel(
            "Select which of the found UPnP services will be probed")
        self.labelsubtitle_step3 = JLabel(
            "Review and modify the request, then send it to one of the attack tools"
        )
        self.label_step1 = JLabel("Target IP")
        self.label_step2 = JLabel("Found UPnp Services")
        self.labelstatus = JLabel("             Status")
        self.labelempty_step1 = JLabel("                ")
        self.labelempty_step2 = JLabel("  ")
        self.labelupnp = JLabel("UPnP list")
        self.labelip = JLabel("IP list")
        self.labelactions = JLabel("Actions")
        self.labelNoneServiceFound = JLabel("  ")
        self.labelNoneServiceFound.setFont(Font('Tahoma', Font.BOLD, 12))
        self.labelNoneServiceFound.setForeground(Color.red)

        # Create combobox for IP version selection
        self.ip_versions = ["IPv4", "IPv6"]
        self.combo_ipversion = JComboBox(self.ip_versions)
        self.combo_ipversion.setSelectedIndex(0)
        self.combo_ipversion.setEnabled(True)

        # Create and configure progress bar
        self.progressbar = JProgressBar(0, 100)
        self.progressbar.setString("Ready")
        self.progressbar.setStringPainted(True)

        # Create and configure buttons
        self.startbutton = JButton("Start Discovery",
                                   actionPerformed=self.startHunting)
        self.clearbutton = JButton("Clear All", actionPerformed=self.clearAll)
        self.intruderbutton = JButton("Send to Intruder",
                                      actionPerformed=self.sendToIntruder)
        self.repeaterbutton = JButton("Send to Repeater",
                                      actionPerformed=self.sendToRepeater)
        #self.WANrepeaterbutton = JButton("to Repeater", actionPerformed=self.sendWANUPnPToRepeater)
        self.textarea_request = JTextArea(18, 90)
        self.intruderbutton.setEnabled(False)
        self.repeaterbutton.setEnabled(False)

        # Class neeeded to handle the target combobox in second step panel
        class TargetComboboxListener(ActionListener):
            def __init__(self, upnpcombo_targets, upnpcombo_services,
                         ip_service_dict):
                self.upnpcombo_targets = upnpcombo_targets
                self.upnpcombo_services = upnpcombo_services
                self.ip_service_dict = ip_service_dict

            def actionPerformed(self, event):
                try:
                    # Update the location url combobox depending on the IP combobox
                    selected_target = self.upnpcombo_targets.getSelectedItem()
                    if self.ip_service_dict and selected_target:
                        self.upnpcombo_services.removeAllItems()
                        for service_url in self.ip_service_dict[
                                selected_target]:
                            self.upnpcombo_services.addItem(service_url)
                        self.upnpcombo_services.setSelectedIndex(0)
                except BaseException as e:
                    print("[!] Exception selecting service: \"%s\" ") % e

        # Class neeeded to handle the service combobox in second step panel
        class ServiceComboboxListener(ActionListener):
            def __init__(self, upnpcombo_services, upnpcombo_actions,
                         services_dict):
                self.upnpcombo_services = upnpcombo_services
                self.upnpcombo_actions = upnpcombo_actions
                self.services = services_dict

            def actionPerformed(self, event):
                try:
                    # Update the location url combobox depending on the IP combobox
                    selected_service = self.upnpcombo_services.getSelectedItem(
                    )
                    if self.services and selected_service:
                        self.upnpcombo_actions.removeAllItems()
                        actions = self.services[selected_service]
                        for action in actions:
                            self.upnpcombo_actions.addItem(action)
                        self.upnpcombo_actions.setSelectedIndex(0)
                except BaseException as e:
                    print("[!] Exception selecting service: \"%s\" ") % e

        # Class neeeded to handle the action combobox in second step panel
        class ActionComboboxListener(ActionListener):
            def __init__(self, upnpcombo_services, upnpcombo_actions,
                         textarea_request, services_dict):
                self.upnpcombo_services = upnpcombo_services
                self.upnpcombo_actions = upnpcombo_actions
                self.textarea_request = textarea_request
                self.services = services_dict

            def actionPerformed(self, event):
                try:
                    # Update the location url combobox depending on the IP combobox
                    selected_action = self.upnpcombo_actions.getSelectedItem()
                    selected_service = self.upnpcombo_services.getSelectedItem(
                    )
                    if self.services and selected_action:
                        self.textarea_request.setText(
                            self.services[selected_service][selected_action])
                except BaseException as e:
                    print("[!] Exception selecting action: \"%s\" ") % e

        self.upnpactions = ["       "]
        self.upnpcombo_actions = JComboBox(self.upnpactions)
        self.upnpcombo_actions.setSelectedIndex(0)
        self.upnpcombo_actions.setEnabled(False)

        # Create the combo box, select item at index 0 (first item in list)
        self.upnpservices = ["       "]
        self.upnpcombo_services = JComboBox(self.upnpservices)
        self.upnpcombo_services.setSelectedIndex(0)
        self.upnpcombo_services.setEnabled(False)

        # Create the combo box, select item at index 0 (first item in list)
        self.upnptargets = ["       "]
        self.upnpcombo_targets = JComboBox(self.upnptargets)
        self.upnpcombo_targets.setSelectedIndex(0)
        self.upnpcombo_targets.setEnabled(False)

        # Set the action listeners for all the comboboxes
        self.upnpcombo_targets.addActionListener(
            TargetComboboxListener(self.upnpcombo_targets,
                                   self.upnpcombo_services,
                                   self.ip_service_dict))
        self.upnpcombo_services.addActionListener(
            ServiceComboboxListener(self.upnpcombo_services,
                                    self.upnpcombo_actions,
                                    self.services_dict))
        self.upnpcombo_actions.addActionListener(
            ActionComboboxListener(self.upnpcombo_services,
                                   self.upnpcombo_actions,
                                   self.textarea_request, self.services_dict))

        # Configuring first step panel
        self.panel_step1 = JPanel()
        self.panel_step1.setPreferredSize(Dimension(2250, 100))
        self.panel_step1.setBorder(EmptyBorder(10, 10, 10, 10))
        self.panel_step1.setLayout(BorderLayout(15, 15))
        self.titlepanel_step1 = JPanel()
        self.titlepanel_step1.setLayout(BorderLayout())
        self.titlepanel_step1.add(self.labeltitle_step1, BorderLayout.NORTH)
        self.titlepanel_step1.add(self.labelsubtitle_step1)
        self.targetpanel_step1 = JPanel()
        self.targetpanel_step1.add(self.label_step1)
        self.targetpanel_step1.add(self.combo_ipversion)
        self.targetpanel_step1.add(self.startbutton)
        self.targetpanel_step1.add(self.clearbutton)
        self.targetpanel_step1.add(self.labelstatus)
        self.targetpanel_step1.add(self.progressbar)
        self.emptypanel_step1 = JPanel()
        self.emptypanel_step1.setLayout(BorderLayout())
        self.emptypanel_step1.add(self.labelempty_step1, BorderLayout.WEST)

        # Assembling first step panel components
        self.panel_step1.add(self.titlepanel_step1, BorderLayout.NORTH)
        self.panel_step1.add(self.targetpanel_step1, BorderLayout.WEST)
        self.panel_step1.add(self.emptypanel_step1, BorderLayout.SOUTH)
        self.uiPanelA.setTopComponent(self.panel_step1)

        # Configure second step panel
        self.panel_step2 = JPanel()
        self.panel_step2.setPreferredSize(Dimension(2250, 100))
        self.panel_step2.setBorder(EmptyBorder(10, 10, 10, 10))
        self.panel_step2.setLayout(BorderLayout(15, 15))
        self.titlepanel_step2 = JPanel()
        self.titlepanel_step2.setLayout(BorderLayout())
        self.titlepanel_step2.add(self.labeltitle_step2, BorderLayout.NORTH)
        self.titlepanel_step2.add(self.labelsubtitle_step2)
        self.selectpanel_step2 = JPanel()
        self.selectpanel_step2.add(self.labelip)
        self.selectpanel_step2.add(self.upnpcombo_targets)
        self.selectpanel_step2.add(self.labelupnp)
        self.selectpanel_step2.add(self.upnpcombo_services)
        self.selectpanel_step2.add(self.labelactions)
        self.selectpanel_step2.add(self.upnpcombo_actions)
        self.emptypanel_step2 = JPanel()
        self.emptypanel_step2.setLayout(BorderLayout())
        self.emptypanel_step2.add(self.labelempty_step2, BorderLayout.WEST)
        self.emptypanel_step2.add(self.labelNoneServiceFound)

        # Assembling second step panel components
        self.panel_step2.add(self.titlepanel_step2, BorderLayout.NORTH)
        self.panel_step2.add(self.selectpanel_step2, BorderLayout.WEST)
        self.panel_step2.add(self.emptypanel_step2, BorderLayout.SOUTH)
        self.uiPanelB.setTopComponent(self.panel_step2)

        # Configuring third step panel
        self.panel_step3 = JPanel()
        self.panel_step3.setPreferredSize(Dimension(2250, 100))
        self.panel_step3.setBorder(EmptyBorder(10, 10, 10, 10))
        self.panel_step3.setLayout(BorderLayout(15, 15))
        self.titlepanel_step3 = JPanel()
        self.titlepanel_step3.setLayout(BorderLayout())
        self.titlepanel_step3.add(self.labeltitle_step3, BorderLayout.NORTH)
        self.titlepanel_step3.add(self.labelsubtitle_step3)
        self.underpanel_step3 = JPanel()
        self.underpanel_step3.setLayout(BorderLayout())
        self.underpanel_step3.add((JScrollPane(self.textarea_request)),
                                  BorderLayout.NORTH)
        self.actionpanel_step3 = JPanel()
        self.actionpanel_step3.add(self.intruderbutton)
        self.actionpanel_step3.add(self.repeaterbutton)
        self.extrapanel_step3 = JPanel()
        self.extrapanel_step3.setLayout(BorderLayout())
        self.extrapanel_step3.add(self.actionpanel_step3, BorderLayout.WEST)

        # Assembling thirdd step panel components
        self.panel_step3.add(self.titlepanel_step3, BorderLayout.NORTH)
        self.panel_step3.add(self.underpanel_step3, BorderLayout.WEST)
        self.panel_step3.add(self.extrapanel_step3, BorderLayout.SOUTH)
        self.uiPanelB.setBottomComponent(self.panel_step3)

        # Assembling the group of all panels
        layout = GroupLayout(self.pluginTab)
        self.pluginTab.setLayout(layout)
        layout.setHorizontalGroup(
            layout.createParallelGroup(GroupLayout.Alignment.LEADING).addGroup(
                layout.createSequentialGroup().addGap(10, 10, 10).addGroup(
                    layout.createParallelGroup(
                        GroupLayout.Alignment.LEADING).addComponent(
                            self.uiTitle).addGap(15, 15, 15).addComponent(
                                self.uiPanelA)).addContainerGap(
                                    26, Short.MAX_VALUE)))
        layout.setVerticalGroup(
            layout.createParallelGroup(GroupLayout.Alignment.LEADING).addGroup(
                layout.createSequentialGroup().addGap(15, 15, 15).addComponent(
                    self.uiTitle).addGap(15, 15, 15).addComponent(
                        self.uiPanelA).addGap(20, 20, 20).addGap(20, 20, 20)))

    def extensionUnloaded(self):
        # Unload the plugin, and if running stop the background thread
        if self.upnpcombo_services.isEnabled():
            if self.th.isAlive():
                print("[+] Stopping thread %s") % self.th.getName()
                self.STOP_THREAD = True
                self.th.join()
            else:
                print("Thread %s already dead") % self.th.getName()
        print("[+] Burp plugin UPnP BHunter successfully unloaded")
        return

    def getTabCaption(self):
        return self.EXTENSION_NAME

    def getUiComponent(self):
        return self.pluginTab

    def clearAll(self, e=None):
        # Reset all data of the plugin
        self.services_dict.clear()
        self.progressbar.setString("Ready")
        self.progressbar.setValue(0)
        self.upnpcombo_targets.removeAllItems()
        self.upnpcombo_targets.setEnabled(False)
        self.upnpcombo_services.removeAllItems()
        self.upnpcombo_services.setEnabled(False)
        self.upnpcombo_actions.removeAllItems()
        self.upnpcombo_actions.setEnabled(False)
        self.intruderbutton.setEnabled(False)
        self.repeaterbutton.setEnabled(False)
        self.labelNoneServiceFound.setText(" ")
        self.textarea_request.setText(" ")
        print("[+] Clearing all data")
        return

    def startHunting(self, e=None):
        # Starting the UPnP hunt
        def startHunting_run():

            # Initialize the internal parameters every time the start-discovery button is clicked
            self.services_dict.clear()
            found_loc = []
            discovery_files = []
            self.labelNoneServiceFound.setText(" ")
            self.intruderbutton.setEnabled(False)
            self.repeaterbutton.setEnabled(False)

            # Then determine if targerting IPv4 or IPv6 adresses
            if self.combo_ipversion.getSelectedItem() == "IPv4":
                self.ipv4_selected = True
                print("[+] Selected IPv4 address scope")
            else:
                self.ipv4_selected = False
                print("[+] Selected IPv6 address scope")

            # And here finally the hunt could start
            self.progressbar.setString("Running...")
            self.progressbar.setValue(20)
            found_loc = self.discoverUpnpLocations()
            self.progressbar.setValue(40)
            discovery_files = self.downloadXMLfiles(found_loc)
            self.progressbar.setValue(60)
            self.buildSOAPs(discovery_files)
            self.progressbar.setValue(80)
            self.progressbar.setString("Done")
            self.progressbar.setValue(100)
            self.updateComboboxList(self.services_dict)

            # Update the comboboxes list with the discovered UPnPs
            if (self.services_dict):
                self.upnpcombo_targets.setEnabled(True)
                self.upnpcombo_services.setEnabled(True)
                self.upnpcombo_actions.setEnabled(True)
                self.intruderbutton.setEnabled(True)
                self.repeaterbutton.setEnabled(True)

            if self.STOP_THREAD:
                return

        # Start a background thread to run the above nested function in order to prevent the blocking of plugin UI
        self.th = threading.Thread(target=startHunting_run)
        #self.th.daemon = True    # This does not seem to be useful
        self.th.setName("th-BHunter")
        self.th.start()

    def ssdpReqBuilder(self, ssdp_timeout, st_type, ssdp_ip, ssdp_port):
        # Builder of the two ssdp msearch request types
        msearch_req = "M-SEARCH * HTTP/1.1\r\n" \
        "HOST: {0}:{1}\r\n" \
        "MAN: \"ssdp:discover\"\r\n" \
        "MX: {2}\r\n" \
        "ST: {3}\r\n" \
        "\r\n" \
        .format(ssdp_ip, ssdp_port, ssdp_timeout, st_type)
        return msearch_req

    def sendMsearch(self, ssdp_req, ssdp_ip, ssdp_port):
        # Send the ssdp request and retrieve response
        buf_resp = set()
        if self.ipv4_selected:
            print("[+] Creating IPv4 SSDP multicast request")
            sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        else:
            print("[+] Creating IPv6 SSDP multicast request")
            sock = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)
        sock.setblocking(0)
        # Sending ssdp requests
        while len(ssdp_req):
            # Blocking socket client until the request is completely sent
            try:
                sent = sock.sendto(ssdp_req.encode("ASCII"),
                                   (ssdp_ip, ssdp_port))
                ssdp_req = ssdp_req[sent:]
            except socket.error, exc:
                if exc.errno != errno.EAGAIN:
                    print("[E] Got error %s with socket when sending") % exc
                    sock.close()
                    raise exc
                print("[!] Blocking socket until ", len(ssdp_req), " is sent.")
                select.select([], [sock], [])
                continue
        # Retrieving ssdp responses
        num_resp = 0
        while sock:
            # Blocking socket until there are ssdp responses to be read or timeout is reached
            readable, __, __ = select.select([sock], [], [], self.SSDP_TIMEOUT)
            if not readable:
                # Timeout reached without receiving any ssdp response
                if num_resp == 0:
                    print(
                        "[!] Got timeout without receiving any ssdp response.")
                break
            else:
                num_resp = num_resp + 1
                # Almost an ssdp response was received
                if readable[0]:
                    try:
                        data = sock.recv(1024)
                        if data:
                            buf_resp.add(data.decode('ASCII'))
                    except socket.error, exc:
                        print("[E] Got error %s with socket when receiving"
                              ) % exc
                        sock.close()
                        raise exc
示例#8
0
def main():
    all_files = currentSelectedItems
    total = len(all_files)
    jprog = JProgressBar(0, total)
    jprog.setStringPainted(True)
    jframe.getContentPane().add(jprog)
    jframe.getContentPane().add(jbutton)
    jframe.setVisible(True)
    try:
        statusLabel.setText("Selected " + str(total) + " items")
        discovered = 0
        for idx, item in enumerate(all_files):
            if cancelled:
                return "User cancelled"
            jprog.setValue(idx)
            statusLabel.setText("Processing %d of %d" % (idx, total))
            md5 = item.digests.md5
            # Item needs an md5 to check against, so move on if there isn't one
            if not md5:
                continue
            response = send_request(md5)
            if not response:
                return
            cm = item.getCustomMetadata()
            if response == "404":
                cm.putText("VirusTotal", "Item md5 not matched in database")
            else:
                data = json.load(response)
                malicious = data["data"]["attributes"]["last_analysis_stats"]["malicious"]
                if malicious > 0:
                    discovered += 1

                cm.putInteger("AVs identifying item as malicious", malicious)
                for scanner, res in data["data"]["attributes"]["last_analysis_results"].iteritems():
                    if res["result"] is not None:
                        cm.putText("VirusTotal " + scanner, res["result"])
                # vHash
                if SET_VHASH and ("vhash" in data["data"]["attributes"]):
                    cm.putText("vHash", data["data"]["attributes"]["vhash"])
                # Import Hash
                if SET_IMPHASH and ("pe_info" in data["data"]["attributes"]) and \
                        ("imphash" in data["data"]["attributes"]["pe_info"]):
                    cm.putText("Import Hash", data["data"]["attributes"]["pe_info"]["imphash"])
                # Authentihash
                if SET_AUTHENTIHASH and ("authentihash" in data["data"]["attributes"]):
                    cm.putText("Authentihash", data["data"]["attributes"]["authentihash"])
                # Crowd sourced yara results
                if SET_YARA and ("crowdsourced_yara_results" in data["data"]["attributes"]):
                    yara_matches = []
                    for yara in data["data"]["attributes"]["crowdsourced_yara_results"]:
                        yara_matches += [yara["rule_name"]]
                    cm.putText("Matched Yara Rules", ", ".join(yara_matches))
                # Virus Total defined tags. Often this can be a list that needs to be looped through
                if SET_TAGS and ("tags" in data["data"]["attributes"]):
                    for tag in data["data"]["attributes"]["tags"]:
                        item.addTag("VirusTotal|" + tag)

                time.sleep(SLEEP_TIME)

        jprog.setValue(total)
        statusLabel.setText("Done")
        return "VirusTotal Search has finished. %d potentially malicious items found from the %d selected." % (discovered, total)

    except Exception:
        import traceback
        print('generic exception: ' + traceback.format_exc())
        return
class MenueFrame(JFrame, ActionListener, WindowFocusListener): # should extend JFrame
    def __init__(self):
        self.mainDir = ""

        self.setTitle("Dots Quality Check")
        self.setSize(250, 300)
        self.setLocation(20,120)
        self.addWindowFocusListener(self)
        
        self.Panel = JPanel(GridLayout(0,1))
        self.add(self.Panel)
        self.openNextButton = JButton("Open Next Random", actionPerformed=self.openRandom)
        self.Panel.add(self.openNextButton)
        self.saveButton = JButton("Save", actionPerformed=self.save, enabled=False)
        self.Panel.add(self.saveButton)
        self.cropButton = JButton("Crop values from here", actionPerformed=self.cropVals)
        self.Panel.add(self.cropButton)
        self.DiscardButton = JButton("Discard cell", actionPerformed=self.discardCell)
        self.Panel.add(self.DiscardButton)
        self.quitButton = JButton("Quit script",actionPerformed=self.quit)
        self.Panel.add(self.quitButton)

        annoPanel = JPanel()
        #add gridlayout
        self.wtRButton = JRadioButton("wt", actionCommand="wt")
        self.wtRButton.addActionListener(self)
        self.defectRButton = JRadioButton("Defect", actionCommand="defect")
        self.defectRButton.addActionListener(self)
        annoPanel.add(self.wtRButton)
        annoPanel.add(self.defectRButton)
        self.aButtonGroup = ButtonGroup()
        self.aButtonGroup.add(self.wtRButton)
        self.aButtonGroup.add(self.defectRButton)
      
        self.Panel.add(annoPanel)

        self.ProgBar = JProgressBar()
        self.ProgBar.setStringPainted(True)
        self.ProgBar.setValue(0)
        self.Panel.add(self.ProgBar)

        self.pathLabel = JLabel("-- No main directory chosen --")
        self.pathLabel.setHorizontalAlignment( SwingConstants.CENTER )
        self.Panel.add(self.pathLabel)
      
        WindowManager.addWindow(self)
        self.show()

    # - - - -   B U T T O N   M E T H O D S  - - - -
    # - - - - - -  - - - - - - - - - - - - - - - - -
    def openRandom(self, event):      # when click here: get random cell and meas.measure(csv, tif, savePath)
        if self.mainDir == "":
            self.mainDir = DirectoryChooser("Random QC - Please choose main directory containing ctrl and test folders").getDirectory()
            self.pathLabel.setText("MainDir: " + os.path.basename(os.path.split(self.mainDir)[0]))
        try:
            # should be complete disposal!
            self.cT.closeWindows()
        finally:
            inFiles = glob.glob(os.path.join(self.mainDir, "*", G_OPENSUBDIR, "val_*.csv"))  # glob.glob returns list of paths
            uncheckedCells = [cell(csvPath) for csvPath in inFiles if cell(csvPath).processed == False]
            if len(uncheckedCells) > 0:
                self.cell = random.choice(uncheckedCells)
                #update progressbar
                self.ProgBar.setMaximum(len(inFiles)-1)
                self.ProgBar.setValue(len(inFiles)-len(uncheckedCells))
                # open imp and resultstable
                self.cT = correctionTable(self.cell, self) #self, openPath_csv, mF
                self.RBActionListener.setCell(self.cell)
                # delete previous Radiobutton annotation
                self.wtRButton.setSelected(False)
                self.defectRButton.setSelected(True)
            else:
                print "All cells measured!"

    def save(self, event):
        savepath = self.cell.getQcCsvPath()
        anaphase = self.cell.getAnOn()
        timeInterval = self.cT.getImp().getCalibration().frameInterval
        annotation = self.getAnnotation()
        position = str(self.cell.position)
        cellIndex = str(self.cell.cellNo)
        if not os.path.exists(os.path.split(savepath)[0]): # check if save folder present.
            os.makedirs(os.path.split(savepath)[0]) # create save folder, if not present
        f = open(savepath, "w")
        # Position Cell Phenotype Frame Time AnOn Distance ch0x ch0y ch0z ch0vol ch1x ch1y ch1z ch1vol
        f.write("Position,Cell,Phenotype,Frame,Time,Anaphase,Distance,ch0x,ch0y,ch0z,ch0vol,ch1x,ch1y,ch1z,ch1vol\n")
        for i in range(self.cT.getLineCount()):
            frame, distance, a = self.cT.getLine(i).split("\t")
            corrFrame = str(int(frame)-int(anaphase))
            time = "%.f" % (round(timeInterval) * int(corrFrame))
            if distance == "NA":
                ch0x, ch0y, ch0z, ch0vol, ch1x, ch1y, ch1z, ch1vol = ("NA," * 7 + "NA\n").split(",")
            else:
                ch0x, ch0y, ch0z, ch0vol, ch1x, ch1y, ch1z, ch1vol = self.cT.getXYZtable()[i]
            f.write(position+","+cellIndex+","+annotation+","+corrFrame+","+time+","+anaphase+","+distance+","+ch0x+","+ch0y+","+ch0z+","+ch0vol+","+ch1x+","+ch1y+","+ch1z+","+ch1vol)
        f.close()
        print "Successfully saved!"

    def cropVals(self, event): #"this function deletes all values with frame > current cursor"   
        for line in range(self.cT.getSelectionEnd(), self.cT.getLineCount(), 1):
            frame, distance, AOCol = self.cT.getLine(line).split("\t")
            self.cT.setLine(line, frame + "\tNA" + "\t" + AOCol)

    def discardCell(self, event):
        if not os.path.exists(os.path.split(self.cell.getQcCsvPath() )[0]): # check if save folder present.
            os.makedirs(os.path.split(self.cell.getQcCsvPath() )[0]) # create save folder, if not present.
        f = open(self.cell.getQcCsvPath() ,"w")
        # Write dummy header. Position Cell Phenotype Frame Time AnOn Distance ch0x ch0y ch0z ch0vol ch1x ch1y ch1z ch1vol
        f.write("Position,Cell,Phenotype,Frame,Time,AnOn,Distance,ch0x,ch0y,ch0z,ch0vol,ch1x,ch1y,ch1z,ch1vol\n")
        f.close()
        print "Discarded cell - saved dummy" 

    def quit(self, event):
        try:
            self.cT.closeWindows()
        finally:
            WindowManager.removeWindow(self)
            self.dispose()

    # Methods implementing ActionListener interfaces:
    def actionPerformed(self, e):
        # this function is called when RadioButtons are changed
        self.cell.annotate( e.getSource().getActionCommand() )
        self.setSaveActive()

    def windowGainedFocus(self, e):
        pass

    def windowLostFocus(self, e):
        pass
        

    # - - - - - - - - - - - - -
    # - get and set methods - -
    # - - - - - - - - - - - - -
    def getAnnotation(self):
        return self.aButtonGroup.getSelection().getActionCommand()

    def getMainDir(self):
        return self.mainDir

    def setSaveActive(self):
        if (self.cell.getAnnotation() != None and self.cell.getAnOn() != None):
            self.saveButton.setEnabled(True)
            self.show()

    def setSaveInactive(self):
        self.saveButton.setEnabled(False)
        self.show()

    def setMainDir(self, path):
        self.mainDir = path
        self.pathLabel.setText("MainDir: " + os.path.basename(os.path.split(self.mainDir)[0]))