예제 #1
0
class PTTextField(JPanel):

    def getName(self):
        return self._name

    def setText(self, text):
        self._textfield.setText(text)

    def getText(self):
        return self._textfield.getText()

    def __init__(self, name, label, text, function=None, button1=None, button2=None):

        length = 1000
        self._name = name
        self._label = JLabel(label)
        self._textfield = JTextField(length) \
            if function is None \
            else JTextField(length, actionPerformed=function)
        self.add(self._label)
        self.add(self._textfield)
        if button1 is not None:
            self._button1 = button1
            self.add(self._button1)
        if button2 is not None:
            self._button2 = button2
            self.add(self._button2)
        self.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5))
        self._textfield.setText("0" * length)
        self._textfield.setMaximumSize(self._textfield.getPreferredSize())
        self.setMaximumSize(self.getPreferredSize())
        self.setText(text)
        self.setLayout(BoxLayout(self, BoxLayout.X_AXIS))
예제 #2
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
예제 #3
0
    def __init__(self, parent, title, modal, app):
        from java.awt import CardLayout
        self.app = app
        border = BorderFactory.createEmptyBorder(5, 7, 7, 7)
        self.getContentPane().setBorder(border)
        self.setLayout(BoxLayout(self.getContentPane(), BoxLayout.Y_AXIS))

        self.FAVAREALAYERNAME = "Favourite zone editing"

        info = JLabel(self.app.strings.getString("Create_a_new_favourite_zone"))
        info.setAlignmentX(Component.LEFT_ALIGNMENT)

        #Name
        nameLbl = JLabel(self.app.strings.getString("fav_zone_name"))
        self.nameTextField = JTextField(20)
        self.nameTextField.setMaximumSize(self.nameTextField.getPreferredSize())
        self.nameTextField.setToolTipText(self.app.strings.getString("fav_zone_name_tooltip"))
        namePanel = JPanel()
        namePanel.setLayout(BoxLayout(namePanel, BoxLayout.X_AXIS))
        namePanel.add(nameLbl)
        namePanel.add(Box.createHorizontalGlue())
        namePanel.add(self.nameTextField)

        #Country
        countryLbl = JLabel(self.app.strings.getString("fav_zone_country"))
        self.countryTextField = JTextField(20)
        self.countryTextField.setMaximumSize(self.countryTextField.getPreferredSize())
        self.countryTextField.setToolTipText(self.app.strings.getString("fav_zone_country_tooltip"))
        countryPanel = JPanel()
        countryPanel.setLayout(BoxLayout(countryPanel, BoxLayout.X_AXIS))
        countryPanel.add(countryLbl)
        countryPanel.add(Box.createHorizontalGlue())
        countryPanel.add(self.countryTextField)

        #Type
        modeLbl = JLabel(self.app.strings.getString("fav_zone_type"))
        RECTPANEL = "rectangle"
        POLYGONPANEL = "polygon"
        BOUNDARYPANEL = "boundary"
        self.modesStrings = [RECTPANEL, POLYGONPANEL, BOUNDARYPANEL]
        modesComboModel = DefaultComboBoxModel()
        for i in (self.app.strings.getString("rectangle"),
                  self.app.strings.getString("delimited_by_a_closed_way"),
                  self.app.strings.getString("delimited_by_an_administrative_boundary")):
            modesComboModel.addElement(i)
        self.modesComboBox = JComboBox(modesComboModel,
                                       actionListener=self,
                                       editable=False)

        #- Rectangle
        self.rectPanel = JPanel()
        self.rectPanel.setLayout(BoxLayout(self.rectPanel, BoxLayout.Y_AXIS))

        capturePane = JPanel()
        capturePane.setLayout(BoxLayout(capturePane, BoxLayout.X_AXIS))
        capturePane.setAlignmentX(Component.LEFT_ALIGNMENT)

        josmP = JPanel()
        self.captureRBtn = JRadioButton(self.app.strings.getString("capture_area"))
        self.captureRBtn.addActionListener(self)
        self.captureRBtn.setSelected(True)
        self.bboxFromJosmBtn = JButton(self.app.strings.getString("get_current_area"),
                                       actionPerformed=self.on_bboxFromJosmBtn_clicked)
        self.bboxFromJosmBtn.setToolTipText(self.app.strings.getString("get_capture_area_tooltip"))
        josmP.add(self.bboxFromJosmBtn)
        capturePane.add(self.captureRBtn)
        capturePane.add(Box.createHorizontalGlue())
        capturePane.add(self.bboxFromJosmBtn)

        manualPane = JPanel()
        manualPane.setLayout(BoxLayout(manualPane, BoxLayout.X_AXIS))
        manualPane.setAlignmentX(Component.LEFT_ALIGNMENT)
        self.manualRBtn = JRadioButton(self.app.strings.getString("use_this_bbox"))
        self.manualRBtn.addActionListener(self)
        self.bboxTextField = JTextField(20)
        self.bboxTextField.setMaximumSize(self.bboxTextField.getPreferredSize())
        self.bboxTextField.setToolTipText(self.app.strings.getString("fav_bbox_tooltip"))
        self.bboxTextFieldDefaultBorder = self.bboxTextField.getBorder()
        self.bboxTextField.getDocument().addDocumentListener(TextListener(self))
        manualPane.add(self.manualRBtn)
        manualPane.add(Box.createHorizontalGlue())
        manualPane.add(self.bboxTextField)

        group = ButtonGroup()
        group.add(self.captureRBtn)
        group.add(self.manualRBtn)

        previewPane = JPanel()
        previewPane.setLayout(BoxLayout(previewPane, BoxLayout.X_AXIS))
        previewPane.setAlignmentX(Component.LEFT_ALIGNMENT)
        bboxPreviewInfo = JTextField(self.app.strings.getString("coordinates"),
                                     editable=0,
                                     border=None)
        bboxPreviewInfo.setMaximumSize(bboxPreviewInfo.getPreferredSize())
        self.bboxPreviewTextField = JTextField(20,
                                               editable=0,
                                               border=None)
        self.bboxPreviewTextField.setMaximumSize(self.bboxPreviewTextField.getPreferredSize())
        previewPane.add(bboxPreviewInfo)
        previewPane.add(Box.createHorizontalGlue())
        previewPane.add(self.bboxPreviewTextField)

        self.rectPanel.add(capturePane)
        self.rectPanel.add(Box.createRigidArea(Dimension(0, 10)))
        self.rectPanel.add(manualPane)
        self.rectPanel.add(Box.createRigidArea(Dimension(0, 20)))
        self.rectPanel.add(previewPane)

        #- Polygon (closed way) drawn by hand
        self.polygonPanel = JPanel(BorderLayout())
        self.polygonPanel.setLayout(BoxLayout(self.polygonPanel, BoxLayout.Y_AXIS))

        polyInfo = JLabel("<html>%s</html>" % self.app.strings.getString("polygon_info"))
        polyInfo.setFont(polyInfo.getFont().deriveFont(Font.ITALIC))
        polyInfo.setAlignmentX(Component.LEFT_ALIGNMENT)

        editPolyPane = JPanel()
        editPolyPane.setAlignmentX(Component.LEFT_ALIGNMENT)
        editPolyBtn = JButton(self.app.strings.getString("create_fav_layer"),
                              actionPerformed=self.create_new_zone_editing_layer)
        editPolyBtn.setToolTipText(self.app.strings.getString("create_fav_layer_tooltip"))
        editPolyPane.add(editPolyBtn)

        self.polygonPanel.add(polyInfo)
        self.polygonPanel.add(Box.createRigidArea(Dimension(0, 15)))
        self.polygonPanel.add(editPolyPane)
        self.polygonPanel.add(Box.createRigidArea(Dimension(0, 15)))

        #- Administrative Boundary
        self.boundaryPanel = JPanel()
        self.boundaryPanel.setLayout(BoxLayout(self.boundaryPanel, BoxLayout.Y_AXIS))

        boundaryInfo = JLabel("<html>%s</html>" % app.strings.getString("boundary_info"))
        boundaryInfo.setFont(boundaryInfo.getFont().deriveFont(Font.ITALIC))
        boundaryInfo.setAlignmentX(Component.LEFT_ALIGNMENT)

        boundaryTagsPanel = JPanel(GridLayout(3, 3, 5, 5))
        boundaryTagsPanel.setAlignmentX(Component.LEFT_ALIGNMENT)
        boundaryTagsPanel.add(JLabel("name ="))
        self.nameTagTextField = JTextField(20)
        boundaryTagsPanel.add(self.nameTagTextField)
        boundaryTagsPanel.add(JLabel("admin_level ="))
        self.adminLevelTagTextField = JTextField(20)
        self.adminLevelTagTextField.setToolTipText(self.app.strings.getString("adminLevel_tooltip"))
        boundaryTagsPanel.add(self.adminLevelTagTextField)
        boundaryTagsPanel.add(JLabel(self.app.strings.getString("other_tag")))
        self.optionalTagTextField = JTextField(20)
        self.optionalTagTextField.setToolTipText("key=value")
        boundaryTagsPanel.add(self.optionalTagTextField)

        downloadBoundariesPane = JPanel()
        downloadBoundariesPane.setAlignmentX(Component.LEFT_ALIGNMENT)
        downloadBoundariesBtn = JButton(self.app.strings.getString("download_boundary"),
                                        actionPerformed=self.on_downloadBoundariesBtn_clicked)
        downloadBoundariesBtn.setToolTipText(self.app.strings.getString("download_boundary_tooltip"))
        downloadBoundariesPane.add(downloadBoundariesBtn)

        self.boundaryPanel.add(boundaryInfo)
        self.boundaryPanel.add(Box.createRigidArea(Dimension(0, 15)))
        self.boundaryPanel.add(boundaryTagsPanel)
        self.boundaryPanel.add(Box.createRigidArea(Dimension(0, 10)))
        self.boundaryPanel.add(downloadBoundariesPane)

        self.editingPanels = {"rectangle": self.rectPanel,
                              "polygon": self.polygonPanel,
                              "boundary": self.boundaryPanel}

        #Main buttons
        self.okBtn = JButton(self.app.strings.getString("OK"),
                             ImageProvider.get("ok"),
                             actionPerformed=self.on_okBtn_clicked)
        self.cancelBtn = JButton(self.app.strings.getString("cancel"),
                                 ImageProvider.get("cancel"),
                                 actionPerformed=self.close_dialog)
        self.previewBtn = JButton(self.app.strings.getString("Preview_zone"),
                                  actionPerformed=self.on_previewBtn_clicked)
        self.previewBtn.setToolTipText(self.app.strings.getString("preview_zone_tooltip"))
        okBtnSize = self.okBtn.getPreferredSize()
        viewBtnSize = self.previewBtn.getPreferredSize()
        viewBtnSize.height = okBtnSize.height
        self.previewBtn.setPreferredSize(viewBtnSize)

        #layout
        self.add(info)
        self.add(Box.createRigidArea(Dimension(0, 15)))

        namePanel.setAlignmentX(Component.LEFT_ALIGNMENT)
        self.add(namePanel)
        self.add(Box.createRigidArea(Dimension(0, 15)))

        countryPanel.setAlignmentX(Component.LEFT_ALIGNMENT)
        self.add(countryPanel)
        self.add(Box.createRigidArea(Dimension(0, 15)))

        modeLbl.setAlignmentX(Component.LEFT_ALIGNMENT)
        self.add(modeLbl)
        self.add(Box.createRigidArea(Dimension(0, 5)))

        self.add(self.modesComboBox)
        self.modesComboBox.setAlignmentX(Component.LEFT_ALIGNMENT)
        self.add(Box.createRigidArea(Dimension(0, 15)))

        self.configPanel = JPanel(CardLayout())
        self.configPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5))
        self.configPanel.add(self.rectPanel, RECTPANEL)
        self.configPanel.add(self.polygonPanel, POLYGONPANEL)
        self.configPanel.add(self.boundaryPanel, BOUNDARYPANEL)
        self.configPanel.setAlignmentX(Component.LEFT_ALIGNMENT)
        self.add(self.configPanel)
        buttonsPanel = JPanel()
        buttonsPanel.add(self.okBtn)
        buttonsPanel.add(self.cancelBtn)
        buttonsPanel.add(self.previewBtn)
        buttonsPanel.setAlignmentX(Component.LEFT_ALIGNMENT)
        self.add(buttonsPanel)

        self.addWindowListener(self)
        self.pack()
예제 #4
0
class NewZoneDialog(JDialog, ActionListener, WindowListener):
    """Dialog for favourite zone editing
    """
    def __init__(self, parent, title, modal, app):
        from java.awt import CardLayout
        self.app = app
        border = BorderFactory.createEmptyBorder(5, 7, 7, 7)
        self.getContentPane().setBorder(border)
        self.setLayout(BoxLayout(self.getContentPane(), BoxLayout.Y_AXIS))

        self.FAVAREALAYERNAME = "Favourite zone editing"

        info = JLabel(self.app.strings.getString("Create_a_new_favourite_zone"))
        info.setAlignmentX(Component.LEFT_ALIGNMENT)

        #Name
        nameLbl = JLabel(self.app.strings.getString("fav_zone_name"))
        self.nameTextField = JTextField(20)
        self.nameTextField.setMaximumSize(self.nameTextField.getPreferredSize())
        self.nameTextField.setToolTipText(self.app.strings.getString("fav_zone_name_tooltip"))
        namePanel = JPanel()
        namePanel.setLayout(BoxLayout(namePanel, BoxLayout.X_AXIS))
        namePanel.add(nameLbl)
        namePanel.add(Box.createHorizontalGlue())
        namePanel.add(self.nameTextField)

        #Country
        countryLbl = JLabel(self.app.strings.getString("fav_zone_country"))
        self.countryTextField = JTextField(20)
        self.countryTextField.setMaximumSize(self.countryTextField.getPreferredSize())
        self.countryTextField.setToolTipText(self.app.strings.getString("fav_zone_country_tooltip"))
        countryPanel = JPanel()
        countryPanel.setLayout(BoxLayout(countryPanel, BoxLayout.X_AXIS))
        countryPanel.add(countryLbl)
        countryPanel.add(Box.createHorizontalGlue())
        countryPanel.add(self.countryTextField)

        #Type
        modeLbl = JLabel(self.app.strings.getString("fav_zone_type"))
        RECTPANEL = "rectangle"
        POLYGONPANEL = "polygon"
        BOUNDARYPANEL = "boundary"
        self.modesStrings = [RECTPANEL, POLYGONPANEL, BOUNDARYPANEL]
        modesComboModel = DefaultComboBoxModel()
        for i in (self.app.strings.getString("rectangle"),
                  self.app.strings.getString("delimited_by_a_closed_way"),
                  self.app.strings.getString("delimited_by_an_administrative_boundary")):
            modesComboModel.addElement(i)
        self.modesComboBox = JComboBox(modesComboModel,
                                       actionListener=self,
                                       editable=False)

        #- Rectangle
        self.rectPanel = JPanel()
        self.rectPanel.setLayout(BoxLayout(self.rectPanel, BoxLayout.Y_AXIS))

        capturePane = JPanel()
        capturePane.setLayout(BoxLayout(capturePane, BoxLayout.X_AXIS))
        capturePane.setAlignmentX(Component.LEFT_ALIGNMENT)

        josmP = JPanel()
        self.captureRBtn = JRadioButton(self.app.strings.getString("capture_area"))
        self.captureRBtn.addActionListener(self)
        self.captureRBtn.setSelected(True)
        self.bboxFromJosmBtn = JButton(self.app.strings.getString("get_current_area"),
                                       actionPerformed=self.on_bboxFromJosmBtn_clicked)
        self.bboxFromJosmBtn.setToolTipText(self.app.strings.getString("get_capture_area_tooltip"))
        josmP.add(self.bboxFromJosmBtn)
        capturePane.add(self.captureRBtn)
        capturePane.add(Box.createHorizontalGlue())
        capturePane.add(self.bboxFromJosmBtn)

        manualPane = JPanel()
        manualPane.setLayout(BoxLayout(manualPane, BoxLayout.X_AXIS))
        manualPane.setAlignmentX(Component.LEFT_ALIGNMENT)
        self.manualRBtn = JRadioButton(self.app.strings.getString("use_this_bbox"))
        self.manualRBtn.addActionListener(self)
        self.bboxTextField = JTextField(20)
        self.bboxTextField.setMaximumSize(self.bboxTextField.getPreferredSize())
        self.bboxTextField.setToolTipText(self.app.strings.getString("fav_bbox_tooltip"))
        self.bboxTextFieldDefaultBorder = self.bboxTextField.getBorder()
        self.bboxTextField.getDocument().addDocumentListener(TextListener(self))
        manualPane.add(self.manualRBtn)
        manualPane.add(Box.createHorizontalGlue())
        manualPane.add(self.bboxTextField)

        group = ButtonGroup()
        group.add(self.captureRBtn)
        group.add(self.manualRBtn)

        previewPane = JPanel()
        previewPane.setLayout(BoxLayout(previewPane, BoxLayout.X_AXIS))
        previewPane.setAlignmentX(Component.LEFT_ALIGNMENT)
        bboxPreviewInfo = JTextField(self.app.strings.getString("coordinates"),
                                     editable=0,
                                     border=None)
        bboxPreviewInfo.setMaximumSize(bboxPreviewInfo.getPreferredSize())
        self.bboxPreviewTextField = JTextField(20,
                                               editable=0,
                                               border=None)
        self.bboxPreviewTextField.setMaximumSize(self.bboxPreviewTextField.getPreferredSize())
        previewPane.add(bboxPreviewInfo)
        previewPane.add(Box.createHorizontalGlue())
        previewPane.add(self.bboxPreviewTextField)

        self.rectPanel.add(capturePane)
        self.rectPanel.add(Box.createRigidArea(Dimension(0, 10)))
        self.rectPanel.add(manualPane)
        self.rectPanel.add(Box.createRigidArea(Dimension(0, 20)))
        self.rectPanel.add(previewPane)

        #- Polygon (closed way) drawn by hand
        self.polygonPanel = JPanel(BorderLayout())
        self.polygonPanel.setLayout(BoxLayout(self.polygonPanel, BoxLayout.Y_AXIS))

        polyInfo = JLabel("<html>%s</html>" % self.app.strings.getString("polygon_info"))
        polyInfo.setFont(polyInfo.getFont().deriveFont(Font.ITALIC))
        polyInfo.setAlignmentX(Component.LEFT_ALIGNMENT)

        editPolyPane = JPanel()
        editPolyPane.setAlignmentX(Component.LEFT_ALIGNMENT)
        editPolyBtn = JButton(self.app.strings.getString("create_fav_layer"),
                              actionPerformed=self.create_new_zone_editing_layer)
        editPolyBtn.setToolTipText(self.app.strings.getString("create_fav_layer_tooltip"))
        editPolyPane.add(editPolyBtn)

        self.polygonPanel.add(polyInfo)
        self.polygonPanel.add(Box.createRigidArea(Dimension(0, 15)))
        self.polygonPanel.add(editPolyPane)
        self.polygonPanel.add(Box.createRigidArea(Dimension(0, 15)))

        #- Administrative Boundary
        self.boundaryPanel = JPanel()
        self.boundaryPanel.setLayout(BoxLayout(self.boundaryPanel, BoxLayout.Y_AXIS))

        boundaryInfo = JLabel("<html>%s</html>" % app.strings.getString("boundary_info"))
        boundaryInfo.setFont(boundaryInfo.getFont().deriveFont(Font.ITALIC))
        boundaryInfo.setAlignmentX(Component.LEFT_ALIGNMENT)

        boundaryTagsPanel = JPanel(GridLayout(3, 3, 5, 5))
        boundaryTagsPanel.setAlignmentX(Component.LEFT_ALIGNMENT)
        boundaryTagsPanel.add(JLabel("name ="))
        self.nameTagTextField = JTextField(20)
        boundaryTagsPanel.add(self.nameTagTextField)
        boundaryTagsPanel.add(JLabel("admin_level ="))
        self.adminLevelTagTextField = JTextField(20)
        self.adminLevelTagTextField.setToolTipText(self.app.strings.getString("adminLevel_tooltip"))
        boundaryTagsPanel.add(self.adminLevelTagTextField)
        boundaryTagsPanel.add(JLabel(self.app.strings.getString("other_tag")))
        self.optionalTagTextField = JTextField(20)
        self.optionalTagTextField.setToolTipText("key=value")
        boundaryTagsPanel.add(self.optionalTagTextField)

        downloadBoundariesPane = JPanel()
        downloadBoundariesPane.setAlignmentX(Component.LEFT_ALIGNMENT)
        downloadBoundariesBtn = JButton(self.app.strings.getString("download_boundary"),
                                        actionPerformed=self.on_downloadBoundariesBtn_clicked)
        downloadBoundariesBtn.setToolTipText(self.app.strings.getString("download_boundary_tooltip"))
        downloadBoundariesPane.add(downloadBoundariesBtn)

        self.boundaryPanel.add(boundaryInfo)
        self.boundaryPanel.add(Box.createRigidArea(Dimension(0, 15)))
        self.boundaryPanel.add(boundaryTagsPanel)
        self.boundaryPanel.add(Box.createRigidArea(Dimension(0, 10)))
        self.boundaryPanel.add(downloadBoundariesPane)

        self.editingPanels = {"rectangle": self.rectPanel,
                              "polygon": self.polygonPanel,
                              "boundary": self.boundaryPanel}

        #Main buttons
        self.okBtn = JButton(self.app.strings.getString("OK"),
                             ImageProvider.get("ok"),
                             actionPerformed=self.on_okBtn_clicked)
        self.cancelBtn = JButton(self.app.strings.getString("cancel"),
                                 ImageProvider.get("cancel"),
                                 actionPerformed=self.close_dialog)
        self.previewBtn = JButton(self.app.strings.getString("Preview_zone"),
                                  actionPerformed=self.on_previewBtn_clicked)
        self.previewBtn.setToolTipText(self.app.strings.getString("preview_zone_tooltip"))
        okBtnSize = self.okBtn.getPreferredSize()
        viewBtnSize = self.previewBtn.getPreferredSize()
        viewBtnSize.height = okBtnSize.height
        self.previewBtn.setPreferredSize(viewBtnSize)

        #layout
        self.add(info)
        self.add(Box.createRigidArea(Dimension(0, 15)))

        namePanel.setAlignmentX(Component.LEFT_ALIGNMENT)
        self.add(namePanel)
        self.add(Box.createRigidArea(Dimension(0, 15)))

        countryPanel.setAlignmentX(Component.LEFT_ALIGNMENT)
        self.add(countryPanel)
        self.add(Box.createRigidArea(Dimension(0, 15)))

        modeLbl.setAlignmentX(Component.LEFT_ALIGNMENT)
        self.add(modeLbl)
        self.add(Box.createRigidArea(Dimension(0, 5)))

        self.add(self.modesComboBox)
        self.modesComboBox.setAlignmentX(Component.LEFT_ALIGNMENT)
        self.add(Box.createRigidArea(Dimension(0, 15)))

        self.configPanel = JPanel(CardLayout())
        self.configPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5))
        self.configPanel.add(self.rectPanel, RECTPANEL)
        self.configPanel.add(self.polygonPanel, POLYGONPANEL)
        self.configPanel.add(self.boundaryPanel, BOUNDARYPANEL)
        self.configPanel.setAlignmentX(Component.LEFT_ALIGNMENT)
        self.add(self.configPanel)
        buttonsPanel = JPanel()
        buttonsPanel.add(self.okBtn)
        buttonsPanel.add(self.cancelBtn)
        buttonsPanel.add(self.previewBtn)
        buttonsPanel.setAlignmentX(Component.LEFT_ALIGNMENT)
        self.add(buttonsPanel)

        self.addWindowListener(self)
        self.pack()

    def update_gui_from_preferences(self):
        self.nameTextField.setText(self.app.newZone.name)
        #Reset rectangle mode
        bboxStr = ",".join(["%0.4f" % x for x in self.app.newZone.bbox])
        self.bboxTextField.setText(bboxStr)
        self.bboxPreviewTextField.setText(bboxStr)
        self.bboxFromJosmBtn.setEnabled(True)
        self.bboxTextField.setEnabled(False)

        #Reset polygon mode
        self.polygonAsString = ""

        #Reset boundary mode
        self.boundaryAsString = ""

        self.modesComboBox.setSelectedIndex(0)

    def actionPerformed(self, e):
        #Show the panel for configuring the favourite area of the
        #selected type
        if e.getSource() == self.modesComboBox:
            cl = self.configPanel.getLayout()
            selectedMode = self.modesStrings[self.modesComboBox.selectedIndex]
            cl.show(self.configPanel, selectedMode)
        #Activate bbox input for rectangular favourite zone mode
        elif e.getSource() == self.captureRBtn:
            self.bboxFromJosmBtn.setEnabled(True)
            self.bboxTextField.setEnabled(False)
        else:
            self.bboxFromJosmBtn.setEnabled(False)
            self.bboxTextField.setEnabled(True)

    def on_bboxFromJosmBtn_clicked(self, widget):
        """Read bbox currently shown in JOSM
        """
        bbox = self.app.get_frame_bounds()
        self.bboxPreviewTextField.setText(",".join(["%0.4f" % x for x in bbox]))

### Manage layer for creating a new favourite zone from polygon or boundary
    def create_new_zone_editing_layer(self, e=None):
        """Open a new dataset where the user can draw a closed way to
           delimit the favourite area
        """
        layer = self.get_new_zone_editing_layer()
        if layer is not None:
            self.app.mv.setActiveLayer(layer)
        else:
            Main.main.addLayer(OsmDataLayer(DataSet(), self.FAVAREALAYERNAME, None))
        Main.main.parent.toFront()

    def get_new_zone_editing_layer(self):
        """Check if the layer for editing the favourite area yet exists
        """
        for layer in self.app.mv.getAllLayers():
            if layer.getName() == self.FAVAREALAYERNAME:
                return layer
        return None

    def remove_new_zone_editing_layer(self):
        layer = self.get_new_zone_editing_layer()
        if layer is not None:
            self.app.mv.removeLayer(layer)

    def on_zone_edited(self):
        """Read ways that delimit the favourite area and convert them to
           jts geometry
        """
        if self.modesComboBox.getSelectedIndex() == 0:
            mode = "rectangle"
        elif self.modesComboBox.getSelectedIndex() == 1:
            mode = "polygon"
        elif self.modesComboBox.getSelectedIndex() == 2:
            mode = "boundary"

        if mode in ("polygon", "boundary"):
            layer = self.get_new_zone_editing_layer()
            if layer is not None:
                self.app.mv.setActiveLayer(layer)
            else:
                if mode == "polygon":
                    msg = self.app.strings.getString("polygon_fav_layer_missing_msg")
                else:
                    msg = self.app.strings.getString("boundary_fav_layer_missing_msg")
                JOptionPane.showMessageDialog(self,
                                              msg,
                                              self.app.strings.getString("Warning"),
                                              JOptionPane.WARNING_MESSAGE)
                return

            dataset = self.app.mv.editLayer.data
            areaWKT = self.read_area_from_osm_ways(mode, dataset)
            if areaWKT is None:
                print "I could not read the new favourite area."
            else:
                if mode == "polygon":
                    self.polygonAsString = areaWKT
                else:
                    self.boundaryAsString = areaWKT
        return mode

    def read_area_from_osm_ways(self, mode, dataset):
        """Read way in favourite area editing layer and convert them to
           WKT
        """
        converter = JTSConverter(False)
        lines = [converter.convert(way) for way in dataset.ways]
        polygonizer = Polygonizer()
        polygonizer.add(lines)
        polygons = polygonizer.getPolygons()
        multipolygon = GeometryFactory().createMultiPolygon(list(polygons))
        multipolygonWKT = WKTWriter().write(multipolygon)
        if multipolygonWKT == "MULTIPOLYGON EMPTY":
            if mode == "polygon":
                msg = self.app.strings.getString("empty_ways_polygon_msg")
            else:
                msg = self.app.strings.getString("empty_ways_boundaries_msg")
            JOptionPane.showMessageDialog(self,
                msg,
                self.app.strings.getString("Warning"),
                JOptionPane.WARNING_MESSAGE)
            return
        return multipolygonWKT

    def on_downloadBoundariesBtn_clicked(self, e):
        """Download puter ways of administrative boundaries from
           Overpass API
        """
        adminLevel = self.adminLevelTagTextField.getText()
        name = self.nameTagTextField.getText()
        optional = self.optionalTagTextField.getText()
        if (adminLevel, name, optional) == ("", "", ""):
            JOptionPane.showMessageDialog(self,
                                          self.app.strings.getString("enter_a_tag_msg"),
                                          self.app.strings.getString("Warning"),
                                          JOptionPane.WARNING_MESSAGE)
            return
        optTag = ""
        if optional.find("=") != -1:
            if len(optional.split("=")) == 2:
                key, value = optional.split("=")
                optTag = '["%s"="%s"]' % (URLEncoder.encode(key, "UTF-8"),
                                          URLEncoder.encode(value.replace(" ", "%20"), "UTF-8"))
        self.create_new_zone_editing_layer()
        overpassurl = 'http://127.0.0.1:8111/import?url='
        overpassurl += 'http://overpass-api.de/api/interpreter?data='
        overpassquery = 'relation["admin_level"="%s"]' % adminLevel
        overpassquery += '["name"="%s"]' % URLEncoder.encode(name, "UTF-8")
        overpassquery += '%s;(way(r:"outer");node(w););out meta;' % optTag
        overpassurl += overpassquery.replace(" ", "%20")
        print overpassurl
        self.app.send_to_josm(overpassurl)

### Buttons ############################################################
    def create_new_zone(self, mode):
        """Read data entered on gui and create a new zone
        """
        name = self.nameTextField.getText()
        country = self.countryTextField.getText().upper()

        #error: name
        if name.replace(" ", "") == "":
            JOptionPane.showMessageDialog(self,
                                          self.app.strings.getString("missing_name_warning"),
                                          self.app.strings.getString("missing_name_warning_title"),
                                          JOptionPane.WARNING_MESSAGE)
            return False
        if name in [z.name for z in self.app.tempZones]:
            JOptionPane.showMessageDialog(self,
                                          self.app.strings.getString("duplicate_name_warning"),
                                          self.app.strings.getString("duplicate_name_warning_title"),
                                          JOptionPane.WARNING_MESSAGE)
            return False

        #zone type
        zType = mode
        #error: geometry type not defined
        if zType == "polygon" and self.polygonAsString == ""\
            or zType == "boundary" and self.boundaryAsString == "":
            JOptionPane.showMessageDialog(self,
                                          self.app.strings.getString("zone_not_correctly_build_warning"),
                                          self.app.strings.getString("zone_not_correctly_build_warning_title"),
                                          JOptionPane.WARNING_MESSAGE)
            return False

        #geometry string
        if zType == "rectangle":
            geomString = self.bboxPreviewTextField.getText()
        elif zType == "polygon":
            geomString = self.polygonAsString
        else:
            geomString = self.boundaryAsString

        self.app.newZone = Zone(self.app, name, zType, geomString, country)
        #self.app.newZone.print_info()
        return True

    def on_okBtn_clicked(self, event):
        """Add new zone to temp zones
        """
        mode = self.on_zone_edited()
        if self.create_new_zone(mode):
            self.app.tempZones.append(self.app.newZone)
            self.app.preferencesFrame.zonesTable.getModel().addRow([self.app.newZone.country,
                                                                    self.app.newZone.icon,
                                                                    self.app.newZone.name])
            maxIndex = len(self.app.tempZones) - 1
            self.app.preferencesFrame.zonesTable.setRowSelectionInterval(maxIndex,
                                                                         maxIndex)
            self.close_dialog()
            self.app.preferencesFrame.check_removeBtn_status()
            self.app.preferencesFrame.zonesTable.scrollRectToVisible(
                self.app.preferencesFrame.zonesTable.getCellRect(
                    self.app.preferencesFrame.zonesTable.getRowCount() - 1, 0, True))

    def on_previewBtn_clicked(self, e):
        """Show the favourite area on a map
        """
        mode = self.on_zone_edited()
        if not self.create_new_zone(mode):
            return
        zone = self.app.newZone

        if zone.zType == "rectangle":
            wktString = zone.bbox_to_wkt_string()
        else:
            wktString = zone.wktGeom
        script = '/*http://stackoverflow.com/questions/11954401/wkt-and-openlayers*/'
        script += '\nfunction init() {'
        script += '\n    var map = new OpenLayers.Map({'
        script += '\n        div: "map",'
        script += '\n        projection: new OpenLayers.Projection("EPSG:900913"),'
        script += '\n        displayProjection: new OpenLayers.Projection("EPSG:4326"),'
        script += '\n        layers: ['
        script += '\n            new OpenLayers.Layer.OSM()'
        script += '\n            ]'
        script += '\n    });'
        script += '\n    var wkt = new OpenLayers.Format.WKT();'
        script += '\n    var polygonFeature = wkt.read("%s");' % wktString
        script += '\n    var vectors = new OpenLayers.Layer.Vector("Favourite area");'
        script += '\n    map.addLayer(vectors);'
        script += '\n    polygonFeature.geometry.transform(map.displayProjection, map.getProjectionObject());'
        script += '\n    vectors.addFeatures([polygonFeature]);'
        script += '\n    map.zoomToExtent(vectors.getDataExtent());'
        script += '\n};'
        scriptFile = open(File.separator.join([self.app.SCRIPTDIR,
                                              "html",
                                              "script.js"]), "w")
        scriptFile.write(script)
        scriptFile.close()
        OpenBrowser.displayUrl(File.separator.join([self.app.SCRIPTDIR,
                                                   "html",
                                                   "favourite_area.html"]))

    def windowClosing(self, windowEvent):
        self.close_dialog()

    def close_dialog(self, e=None):
        #delete favourite zone editing layer if present
        self.remove_new_zone_editing_layer()
        self.dispose()
        self.app.preferencesFrame.setEnabled(True)
        self.app.preferencesFrame.toFront()
예제 #5
0
class BurpExtender(IBurpExtender, IScannerCheck, ITab):
    base_url = "haveibeenpwned.com"
    cmd = "ssh dl-adm query_email ~emailhere~"

    def registerExtenderCallbacks(self, callbacks):
        self._callbacks = callbacks
        self._helpers = callbacks.getHelpers()
        # set our extension name
        callbacks.setExtensionName("Cheburek")
        self._stdout = PrintWriter(callbacks.getStdout(), True)
        self._stdout.println("Hello 1337")

        # add the custom tab to Burp's UI
        self.confCommand = self._callbacks.loadExtensionSetting(
            "cheburek.command") or self.cmd

        saved_haveibeenpwnd = self._callbacks.loadExtensionSetting(
            "cheburek.haveibeenpwnd")
        if saved_haveibeenpwnd == "True":
            self.confHaveIBeenPwnd = True
        elif saved_haveibeenpwnd == "False":
            self.confHaveIBeenPwnd = False
        else:
            self.confHaveIBeenPwnd = bool(int(saved_haveibeenpwnd or True))
        saved_localcheck = self._callbacks.loadExtensionSetting(
            "cheburek.localcheck")

        if saved_localcheck == "True":
            self.confLocalCheck = True
        elif saved_localcheck == "False":
            self.confLocalCheck = False
        else:
            self.confLocalCheck = bool(int(saved_localcheck or False))

        callbacks.addSuiteTab(self)
        self.applyConfig()
        callbacks.registerScannerCheck(self)

    def applyConfig(self):
        self._callbacks.saveExtensionSetting("cheburek.command",
                                             self.confCommand)
        self._callbacks.saveExtensionSetting("cheburek.haveibeenpwnd",
                                             str(int(self.confHaveIBeenPwnd)))
        self._callbacks.saveExtensionSetting("cheburek.localcheck",
                                             str(int(self.confLocalCheck)))

    ### ITab ###
    def getTabCaption(self):
        return "Cheburek"

    def applyConfigUI(self, event):
        self.confCommand = self.uiCommand.getText()
        self.confHaveIBeenPwnd = self.uiHaveIBeenPwnd.isSelected()
        self.confLocalCheck = self.uiLocalCheck.isSelected()
        self.applyConfig()

    def resetConfigUI(self, event):
        self.uiCommand.setText(self.confCommand)
        self.uiHaveIBeenPwnd.setSelected(self.confHaveIBeenPwnd)
        self.uiLocalCheck.setSelected(self.confLocalCheck)

    def getUiComponent(self):
        self.panel = JPanel()
        self.panel.setLayout(BoxLayout(self.panel, BoxLayout.PAGE_AXIS))

        self.uiCommandLine = JPanel()
        self.uiCommandLine.setLayout(
            BoxLayout(self.uiCommandLine, BoxLayout.LINE_AXIS))
        self.uiCommandLine.setAlignmentX(JPanel.LEFT_ALIGNMENT)
        self.uiCommandLine.add(JLabel("Command line for local search: "))
        self.uiCommand = JTextField(40)
        self.uiCommand.setMaximumSize(self.uiCommand.getPreferredSize())
        self.uiCommandLine.add(self.uiCommand)
        self.panel.add(self.uiCommandLine)

        uiOptionsLine = JPanel()
        uiOptionsLine.setLayout(BoxLayout(uiOptionsLine, BoxLayout.LINE_AXIS))
        uiOptionsLine.setAlignmentX(JPanel.LEFT_ALIGNMENT)
        self.uiHaveIBeenPwnd = JCheckBox("haveibeenpwned")
        uiOptionsLine.add(self.uiHaveIBeenPwnd)
        uiOptionsLine.add(Box.createRigidArea(Dimension(10, 0)))

        self.uiLocalCheck = JCheckBox("Local check")
        uiOptionsLine.add(self.uiLocalCheck)
        uiOptionsLine.add(Box.createRigidArea(Dimension(10, 0)))
        self.panel.add(uiOptionsLine)
        self.panel.add(Box.createRigidArea(Dimension(0, 10)))

        uiButtonsLine = JPanel()
        uiButtonsLine.setLayout(BoxLayout(uiButtonsLine, BoxLayout.LINE_AXIS))
        uiButtonsLine.setAlignmentX(JPanel.LEFT_ALIGNMENT)
        uiButtonsLine.add(JButton("Apply", actionPerformed=self.applyConfigUI))
        uiButtonsLine.add(JButton("Reset", actionPerformed=self.resetConfigUI))
        self.panel.add(uiButtonsLine)

        self.uiAbout = JPanel()
        self.uiAbout.setLayout(BoxLayout(self.uiAbout, BoxLayout.LINE_AXIS))
        self.uiAbout.setAlignmentX(JPanel.LEFT_ALIGNMENT)
        self.uiAbout.add(
            JLabel(
                "<html><a href=\"https://twitter.com/_chipik\">https://twitter.com/_chipik</a></html>"
            ))
        self.panel.add(self.uiAbout)

        self.resetConfigUI(None)
        return self.panel

    # END ITAB

    def _get_matches(self, response):
        str_response = self._helpers.bytesToString(response)
        # best regex winner :)
        regex = re.compile(
            ("([a-z0-9!#$%&'*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+\/=?^_`"
             "{|}~-]+)*(@|\sat\s)(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(\.|"
             "\sdot\s))+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)"))
        emails = re.findall(regex, str_response)
        for email in emails:
            self._stdout.println('Found {}'.format(email[0]))
        return emails

    def _get_pointer(self, response, match):
        matches = []
        start = 0
        reslen = len(response)
        matchlen = len(match)
        while start < reslen:
            start = self._helpers.indexOf(response, match, True, start, reslen)
            if start == -1:
                break
            matches.append(array('i', [start, start + matchlen]))
            start += matchlen
        return matches

    # helper that do a request to https://haveibeenpwned.com/
    def _do_online_check(self, email):
        headers = {
            'User-Agent':
            'Chebuzilla/5.0 (Chebuntosh; Intel Cheb-OS-Rek 13.37; rv:59.0) ChebuGeko/20100101 Cheburefox/1337.0'
        }
        connect = httplib.HTTPSConnection(self.base_url)
        connect.request('GET',
                        '/api/v2/breachedaccount/{}'.format(email),
                        headers=headers)
        response = connect.getresponse()
        if response.status == 200:
            html = response.read()
            self._stdout.println('Got {}. Status = {}'.format(
                email, response.status))
            jresp = json.loads(html)
            rez_info = ''
            for br in jresp['Breaches']:
                rez_li = ''
                for li in br['DataClasses']:
                    rez_li = '{}<li>{}</li>'.format(rez_li, li)
                rez_info = '{}<br>{} ({})<br><ul>{}</ul>'.format(
                    rez_info, br['Title'], br['BreachDate'], rez_li)
            return rez_info
        if response.status == 404:
            self._stdout.println('Nothing :( Status = {}'.format(
                response.status))
        if response.status == 403:
            self._stdout.println('API request was blocked. Status = {}'.format(
                response.status))
        return 0

    # helper that do a local search
    def _do_local_check(self, email):
        self._stdout.println("Checking local db for {}".format(email))
        try:
            cmd = self.confCommand.replace("~emailhere~", email)
            self._stdout.println("Exec:{}".format(cmd))
            returned_output = subprocess.check_output(shlex.split(cmd))
            self._stdout.println("Result: {}".format(returned_output))
            returned_output = "Breached passwords:<br><br>{}".format(
                returned_output).replace('\n', '<br>')
        except subprocess.CalledProcessError:
            self._stdout.println("Nothing found locally for {}".format(email))
            returned_output = ''
        return returned_output

    def _check_email(self, email):
        self._stdout.println('Let\'s check {}'.format(email))
        info = info2 = issue = ''
        if self.confHaveIBeenPwnd:
            info = self._do_online_check(email)
        if self.confLocalCheck:
            info2 = self._do_local_check(email)
        if info or info2:
            issue = self._reportIssue(email, info + info2)
        return issue

    def _reportIssue(self, email, info):
        issue = CustomScanIssue(
            self._baseRequestResponse.getHttpService(),
            self._helpers.analyzeRequest(self._baseRequestResponse).getUrl(), [
                self._callbacks.applyMarkers(
                    self._baseRequestResponse, None,
                    self._get_pointer(self._baseRequestResponse.getResponse(),
                                      bytearray(email, 'utf8')))
            ], "Potentially compromised account",
            "Email address <b>{}</b> potentially has been compromised in a data breach<br><br>{}"
            .format(email, info), "Information")
        return issue

    def doPassiveScan(self, baseRequestResponse):
        self._baseRequestResponse = baseRequestResponse
        matches = self._get_matches(self._baseRequestResponse.getResponse())
        issues = []
        if (len(matches) == 0):
            return None
        else:
            for email in matches:
                issue = self._check_email(email[0])
                if issue:
                    issues.append(issue)
        return issues

    def consolidateDuplicateIssues(self, existingIssue, newIssue):
        if existingIssue.getIssueName() == newIssue.getIssueName():
            return -1
        return 0
예제 #6
0
class BurpExtender(IBurpExtender, IHttpListener, IContextMenuFactory, ITab):
    def registerExtenderCallbacks(self, callbacks):
        self.callbacks = callbacks
        self.helpers = callbacks.getHelpers()
        callbacks.setExtensionName(
            "Storing HTTP Requests/Responses into ElasticSearch")
        self.callbacks.registerHttpListener(self)
        self.callbacks.registerContextMenuFactory(self)
        self.out = callbacks.getStdout()

        self.lastTimestamp = None
        self.confESHost = self.callbacks.loadExtensionSetting(
            "elasticburp.host") or ES_host
        self.confESIndex = self.callbacks.loadExtensionSetting(
            "elasticburp.index") or ES_index
        self.confBurpTools = int(
            self.callbacks.loadExtensionSetting("elasticburp.tools")
            or Burp_Tools)
        saved_onlyresp = self.callbacks.loadExtensionSetting(
            "elasticburp.onlyresp")
        if saved_onlyresp == "True":
            self.confBurpOnlyResp = True
        elif saved_onlyresp == "False":
            self.confBurpOnlyResp = False
        else:
            self.confBurpOnlyResp = bool(
                int(saved_onlyresp or Burp_onlyResponses))

        self.callbacks.addSuiteTab(self)
        self.applyConfig()

    def applyConfig(self):
        try:
            print("Connecting to '%s', index '%s'" %
                  (self.confESHost, self.confESIndex))
            self.es = connections.create_connection(hosts=[self.confESHost])
            self.idx = Index(self.confESIndex)
            self.idx.doc_type(DocHTTPRequestResponse)
            if self.idx.exists():
                self.idx.open()
            else:
                self.idx.create()
            self.callbacks.saveExtensionSetting("elasticburp.host",
                                                self.confESHost)
            self.callbacks.saveExtensionSetting("elasticburp.index",
                                                self.confESIndex)
            self.callbacks.saveExtensionSetting("elasticburp.tools",
                                                str(self.confBurpTools))
            self.callbacks.saveExtensionSetting(
                "elasticburp.onlyresp", str(int(self.confBurpOnlyResp)))
        except Exception as e:
            JOptionPane.showMessageDialog(
                self.panel,
                "<html><p style='width: 300px'>Error while initializing ElasticSearch: %s</p></html>"
                % (str(e)), "Error", JOptionPane.ERROR_MESSAGE)

    ### ITab ###
    def getTabCaption(self):
        return "ElasticBurp"

    def applyConfigUI(self, event):
        #self.idx.close()
        self.confESHost = self.uiESHost.getText()
        self.confESIndex = self.uiESIndex.getText()
        self.confBurpTools = int(
            (self.uiCBSuite.isSelected() and IBurpExtenderCallbacks.TOOL_SUITE)
            | (self.uiCBTarget.isSelected()
               and IBurpExtenderCallbacks.TOOL_TARGET) |
            (self.uiCBProxy.isSelected() and IBurpExtenderCallbacks.TOOL_PROXY)
            | (self.uiCBSpider.isSelected()
               and IBurpExtenderCallbacks.TOOL_SPIDER)
            | (self.uiCBScanner.isSelected()
               and IBurpExtenderCallbacks.TOOL_SCANNER)
            | (self.uiCBIntruder.isSelected()
               and IBurpExtenderCallbacks.TOOL_INTRUDER)
            | (self.uiCBRepeater.isSelected()
               and IBurpExtenderCallbacks.TOOL_REPEATER)
            | (self.uiCBSequencer.isSelected()
               and IBurpExtenderCallbacks.TOOL_SEQUENCER)
            | (self.uiCBExtender.isSelected()
               and IBurpExtenderCallbacks.TOOL_EXTENDER))
        self.confBurpOnlyResp = self.uiCBOptRespOnly.isSelected()
        self.applyConfig()

    def resetConfigUI(self, event):
        self.uiESHost.setText(self.confESHost)
        self.uiESIndex.setText(self.confESIndex)
        self.uiCBSuite.setSelected(
            bool(self.confBurpTools & IBurpExtenderCallbacks.TOOL_SUITE))
        self.uiCBTarget.setSelected(
            bool(self.confBurpTools & IBurpExtenderCallbacks.TOOL_TARGET))
        self.uiCBProxy.setSelected(
            bool(self.confBurpTools & IBurpExtenderCallbacks.TOOL_PROXY))
        self.uiCBSpider.setSelected(
            bool(self.confBurpTools & IBurpExtenderCallbacks.TOOL_SPIDER))
        self.uiCBScanner.setSelected(
            bool(self.confBurpTools & IBurpExtenderCallbacks.TOOL_SCANNER))
        self.uiCBIntruder.setSelected(
            bool(self.confBurpTools & IBurpExtenderCallbacks.TOOL_INTRUDER))
        self.uiCBRepeater.setSelected(
            bool(self.confBurpTools & IBurpExtenderCallbacks.TOOL_REPEATER))
        self.uiCBSequencer.setSelected(
            bool(self.confBurpTools & IBurpExtenderCallbacks.TOOL_SEQUENCER))
        self.uiCBExtender.setSelected(
            bool(self.confBurpTools & IBurpExtenderCallbacks.TOOL_EXTENDER))
        self.uiCBOptRespOnly.setSelected(self.confBurpOnlyResp)

    def getUiComponent(self):
        self.panel = JPanel()
        self.panel.setLayout(BoxLayout(self.panel, BoxLayout.PAGE_AXIS))

        self.uiESHostLine = JPanel()
        self.uiESHostLine.setLayout(
            BoxLayout(self.uiESHostLine, BoxLayout.LINE_AXIS))
        self.uiESHostLine.setAlignmentX(JPanel.LEFT_ALIGNMENT)
        self.uiESHostLine.add(JLabel("ElasticSearch Host: "))
        self.uiESHost = JTextField(40)
        self.uiESHost.setMaximumSize(self.uiESHost.getPreferredSize())
        self.uiESHostLine.add(self.uiESHost)
        self.panel.add(self.uiESHostLine)

        self.uiESIndexLine = JPanel()
        self.uiESIndexLine.setLayout(
            BoxLayout(self.uiESIndexLine, BoxLayout.LINE_AXIS))
        self.uiESIndexLine.setAlignmentX(JPanel.LEFT_ALIGNMENT)
        self.uiESIndexLine.add(JLabel("ElasticSearch Index: "))
        self.uiESIndex = JTextField(40)
        self.uiESIndex.setMaximumSize(self.uiESIndex.getPreferredSize())
        self.uiESIndexLine.add(self.uiESIndex)
        self.panel.add(self.uiESIndexLine)

        uiToolsLine = JPanel()
        uiToolsLine.setLayout(BoxLayout(uiToolsLine, BoxLayout.LINE_AXIS))
        uiToolsLine.setAlignmentX(JPanel.LEFT_ALIGNMENT)
        self.uiCBSuite = JCheckBox("Suite")
        uiToolsLine.add(self.uiCBSuite)
        uiToolsLine.add(Box.createRigidArea(Dimension(10, 0)))
        self.uiCBTarget = JCheckBox("Target")
        uiToolsLine.add(self.uiCBTarget)
        uiToolsLine.add(Box.createRigidArea(Dimension(10, 0)))
        self.uiCBProxy = JCheckBox("Proxy")
        uiToolsLine.add(self.uiCBProxy)
        uiToolsLine.add(Box.createRigidArea(Dimension(10, 0)))
        self.uiCBSpider = JCheckBox("Spider")
        uiToolsLine.add(self.uiCBSpider)
        uiToolsLine.add(Box.createRigidArea(Dimension(10, 0)))
        self.uiCBScanner = JCheckBox("Scanner")
        uiToolsLine.add(self.uiCBScanner)
        uiToolsLine.add(Box.createRigidArea(Dimension(10, 0)))
        self.uiCBIntruder = JCheckBox("Intruder")
        uiToolsLine.add(self.uiCBIntruder)
        uiToolsLine.add(Box.createRigidArea(Dimension(10, 0)))
        self.uiCBRepeater = JCheckBox("Repeater")
        uiToolsLine.add(self.uiCBRepeater)
        uiToolsLine.add(Box.createRigidArea(Dimension(10, 0)))
        self.uiCBSequencer = JCheckBox("Sequencer")
        uiToolsLine.add(self.uiCBSequencer)
        uiToolsLine.add(Box.createRigidArea(Dimension(10, 0)))
        self.uiCBExtender = JCheckBox("Extender")
        uiToolsLine.add(self.uiCBExtender)
        self.panel.add(uiToolsLine)
        self.panel.add(Box.createRigidArea(Dimension(0, 10)))

        uiOptionsLine = JPanel()
        uiOptionsLine.setLayout(BoxLayout(uiOptionsLine, BoxLayout.LINE_AXIS))
        uiOptionsLine.setAlignmentX(JPanel.LEFT_ALIGNMENT)
        self.uiCBOptRespOnly = JCheckBox(
            "Process only responses (include requests)")
        uiOptionsLine.add(self.uiCBOptRespOnly)
        self.panel.add(uiOptionsLine)
        self.panel.add(Box.createRigidArea(Dimension(0, 10)))

        uiButtonsLine = JPanel()
        uiButtonsLine.setLayout(BoxLayout(uiButtonsLine, BoxLayout.LINE_AXIS))
        uiButtonsLine.setAlignmentX(JPanel.LEFT_ALIGNMENT)
        uiButtonsLine.add(JButton("Apply", actionPerformed=self.applyConfigUI))
        uiButtonsLine.add(JButton("Reset", actionPerformed=self.resetConfigUI))
        self.panel.add(uiButtonsLine)
        self.resetConfigUI(None)

        return self.panel

    ### IHttpListener ###
    def processHttpMessage(self, tool, isRequest, msg):
        if not tool & self.confBurpTools or isRequest and self.confBurpOnlyResp:
            return

        doc = self.genESDoc(msg)
        doc.save()

    ### IContextMenuFactory ###
    def createMenuItems(self, invocation):
        menuItems = list()
        selectedMsgs = invocation.getSelectedMessages()
        if selectedMsgs != None and len(selectedMsgs) >= 1:
            menuItems.append(
                JMenuItem("Add to ElasticSearch Index",
                          actionPerformed=self.genAddToES(
                              selectedMsgs,
                              invocation.getInputEvent().getComponent())))
        return menuItems

    def genAddToES(self, msgs, component):
        def menuAddToES(e):
            progress = ProgressMonitor(component, "Feeding ElasticSearch", "",
                                       0, len(msgs))
            i = 0
            docs = list()
            for msg in msgs:
                if not Burp_onlyResponses or msg.getResponse():
                    docs.append(
                        self.genESDoc(
                            msg, timeStampFromResponse=True).to_dict(True))
                i += 1
                progress.setProgress(i)
            success, failed = bulk(self.es, docs, True, raise_on_error=False)
            progress.close()
            JOptionPane.showMessageDialog(
                self.panel,
                "<html><p style='width: 300px'>Successful imported %d messages, %d messages failed.</p></html>"
                % (success, failed), "Finished",
                JOptionPane.INFORMATION_MESSAGE)

        return menuAddToES

    ### Interface to ElasticSearch ###
    def genESDoc(self, msg, timeStampFromResponse=False):
        httpService = msg.getHttpService()
        doc = DocHTTPRequestResponse(protocol=httpService.getProtocol(),
                                     host=httpService.getHost(),
                                     port=httpService.getPort())
        doc.meta.index = self.confESIndex

        request = msg.getRequest()
        response = msg.getResponse()

        if request:
            iRequest = self.helpers.analyzeRequest(msg)
            doc.request.method = iRequest.getMethod()
            doc.request.url = iRequest.getUrl().toString()

            headers = iRequest.getHeaders()
            for header in headers:
                try:
                    doc.add_request_header(header)
                except:
                    doc.request.requestline = header

            parameters = iRequest.getParameters()
            for parameter in parameters:
                ptype = parameter.getType()
                if ptype == IParameter.PARAM_URL:
                    typename = "url"
                elif ptype == IParameter.PARAM_BODY:
                    typename = "body"
                elif ptype == IParameter.PARAM_COOKIE:
                    typename = "cookie"
                elif ptype == IParameter.PARAM_XML:
                    typename = "xml"
                elif ptype == IParameter.PARAM_XML_ATTR:
                    typename = "xmlattr"
                elif ptype == IParameter.PARAM_MULTIPART_ATTR:
                    typename = "multipartattr"
                elif ptype == IParameter.PARAM_JSON:
                    typename = "json"
                else:
                    typename = "unknown"

                name = parameter.getName()
                value = parameter.getValue()
                doc.add_request_parameter(typename, name, value)

            ctype = iRequest.getContentType()
            if ctype == IRequestInfo.CONTENT_TYPE_NONE:
                doc.request.content_type = "none"
            elif ctype == IRequestInfo.CONTENT_TYPE_URL_ENCODED:
                doc.request.content_type = "urlencoded"
            elif ctype == IRequestInfo.CONTENT_TYPE_MULTIPART:
                doc.request.content_type = "multipart"
            elif ctype == IRequestInfo.CONTENT_TYPE_XML:
                doc.request.content_type = "xml"
            elif ctype == IRequestInfo.CONTENT_TYPE_JSON:
                doc.request.content_type = "json"
            elif ctype == IRequestInfo.CONTENT_TYPE_AMF:
                doc.request.content_type = "amf"
            else:
                doc.request.content_type = "unknown"

            bodyOffset = iRequest.getBodyOffset()
            doc.request.body = request[bodyOffset:].tostring().decode(
                "ascii", "replace")

        if response:
            iResponse = self.helpers.analyzeResponse(response)

            doc.response.status = iResponse.getStatusCode()
            doc.response.content_type = iResponse.getStatedMimeType()
            doc.response.inferred_content_type = iResponse.getInferredMimeType(
            )

            headers = iResponse.getHeaders()
            dateHeader = None
            for header in headers:
                try:
                    doc.add_response_header(header)
                    match = reDateHeader.match(header)
                    if match:
                        dateHeader = match.group(1)
                except:
                    doc.response.responseline = header

            cookies = iResponse.getCookies()
            for cookie in cookies:
                expCookie = cookie.getExpiration()
                expiration = None
                if expCookie:
                    try:
                        expiration = str(
                            datetime.fromtimestamp(expCookie.time / 1000))
                    except:
                        pass
                doc.add_response_cookie(cookie.getName(), cookie.getValue(),
                                        cookie.getDomain(), cookie.getPath(),
                                        expiration)

            bodyOffset = iResponse.getBodyOffset()
            doc.response.body = response[bodyOffset:].tostring().decode(
                "ascii", "replace")

            if timeStampFromResponse:
                if dateHeader:
                    try:
                        doc.timestamp = datetime.fromtimestamp(
                            mktime_tz(parsedate_tz(dateHeader)),
                            tz)  # try to use date from response header "Date"
                        self.lastTimestamp = doc.timestamp
                    except:
                        doc.timestamp = self.lastTimestamp  # fallback: last stored timestamp. Else: now

        return doc
예제 #7
0
class BurpExtender(IBurpExtender, IHttpListener, IContextMenuFactory, ITab):
    def registerExtenderCallbacks(self, callbacks):
        self.callbacks = callbacks
        self.helpers = callbacks.getHelpers()
        callbacks.setExtensionName("Storing HTTP Requests/Responses into ElasticSearch")
        self.callbacks.registerHttpListener(self)
        self.callbacks.registerContextMenuFactory(self)
        self.out = callbacks.getStdout()

        self.lastTimestamp = None
        self.confESHost = self.callbacks.loadExtensionSetting("elasticburp.host") or ES_host
        self.confESIndex = self.callbacks.loadExtensionSetting("elasticburp.index") or ES_index
        self.confBurpTools = int(self.callbacks.loadExtensionSetting("elasticburp.tools") or Burp_Tools)
        saved_onlyresp = self.callbacks.loadExtensionSetting("elasticburp.onlyresp") 
        if saved_onlyresp == "True":
            self.confBurpOnlyResp = True
        elif saved_onlyresp == "False":
            self.confBurpOnlyResp = False
        else:
            self.confBurpOnlyResp = bool(int(saved_onlyresp or Burp_onlyResponses))

        self.callbacks.addSuiteTab(self)
        self.applyConfig()

    def applyConfig(self):
        try:
            print("Connecting to '%s', index '%s'" % (self.confESHost, self.confESIndex))
            self.es = connections.create_connection(hosts=[self.confESHost])
            self.idx = Index(self.confESIndex)
            self.idx.doc_type(DocHTTPRequestResponse)
            if self.idx.exists():
                self.idx.open()
            else:
                self.idx.create()
            self.callbacks.saveExtensionSetting("elasticburp.host", self.confESHost)
            self.callbacks.saveExtensionSetting("elasticburp.index", self.confESIndex)
            self.callbacks.saveExtensionSetting("elasticburp.tools", str(self.confBurpTools))
            self.callbacks.saveExtensionSetting("elasticburp.onlyresp", str(int(self.confBurpOnlyResp)))
        except Exception as e:
            JOptionPane.showMessageDialog(self.panel, "<html><p style='width: 300px'>Error while initializing ElasticSearch: %s</p></html>" % (str(e)), "Error", JOptionPane.ERROR_MESSAGE)

    ### ITab ###
    def getTabCaption(self):
        return "ElasticBurp"

    def applyConfigUI(self, event):
        #self.idx.close()
        self.confESHost = self.uiESHost.getText()
        self.confESIndex = self.uiESIndex.getText()
        self.confBurpTools = int((self.uiCBSuite.isSelected() and IBurpExtenderCallbacks.TOOL_SUITE) | (self.uiCBTarget.isSelected() and IBurpExtenderCallbacks.TOOL_TARGET) | (self.uiCBProxy.isSelected() and IBurpExtenderCallbacks.TOOL_PROXY) | (self.uiCBSpider.isSelected() and IBurpExtenderCallbacks.TOOL_SPIDER) | (self.uiCBScanner.isSelected() and IBurpExtenderCallbacks.TOOL_SCANNER) | (self.uiCBIntruder.isSelected() and IBurpExtenderCallbacks.TOOL_INTRUDER) | (self.uiCBRepeater.isSelected() and IBurpExtenderCallbacks.TOOL_REPEATER) | (self.uiCBSequencer.isSelected() and IBurpExtenderCallbacks.TOOL_SEQUENCER) | (self.uiCBExtender.isSelected() and IBurpExtenderCallbacks.TOOL_EXTENDER))
        self.confBurpOnlyResp = self.uiCBOptRespOnly.isSelected()
        self.applyConfig()

    def resetConfigUI(self, event):
        self.uiESHost.setText(self.confESHost)
        self.uiESIndex.setText(self.confESIndex)
        self.uiCBSuite.setSelected(bool(self.confBurpTools & IBurpExtenderCallbacks.TOOL_SUITE))
        self.uiCBTarget.setSelected(bool(self.confBurpTools & IBurpExtenderCallbacks.TOOL_TARGET))
        self.uiCBProxy.setSelected(bool(self.confBurpTools & IBurpExtenderCallbacks.TOOL_PROXY))
        self.uiCBSpider.setSelected(bool(self.confBurpTools & IBurpExtenderCallbacks.TOOL_SPIDER))
        self.uiCBScanner.setSelected(bool(self.confBurpTools & IBurpExtenderCallbacks.TOOL_SCANNER))
        self.uiCBIntruder.setSelected(bool(self.confBurpTools & IBurpExtenderCallbacks.TOOL_INTRUDER))
        self.uiCBRepeater.setSelected(bool(self.confBurpTools & IBurpExtenderCallbacks.TOOL_REPEATER))
        self.uiCBSequencer.setSelected(bool(self.confBurpTools & IBurpExtenderCallbacks.TOOL_SEQUENCER))
        self.uiCBExtender.setSelected(bool(self.confBurpTools & IBurpExtenderCallbacks.TOOL_EXTENDER))
        self.uiCBOptRespOnly.setSelected(self.confBurpOnlyResp)

    def getUiComponent(self):
        self.panel = JPanel()
        self.panel.setLayout(BoxLayout(self.panel, BoxLayout.PAGE_AXIS))

        self.uiESHostLine = JPanel()
        self.uiESHostLine.setLayout(BoxLayout(self.uiESHostLine, BoxLayout.LINE_AXIS))
        self.uiESHostLine.setAlignmentX(JPanel.LEFT_ALIGNMENT)
        self.uiESHostLine.add(JLabel("ElasticSearch Host: "))
        self.uiESHost = JTextField(40)
        self.uiESHost.setMaximumSize(self.uiESHost.getPreferredSize())
        self.uiESHostLine.add(self.uiESHost)
        self.panel.add(self.uiESHostLine)

        self.uiESIndexLine = JPanel()
        self.uiESIndexLine.setLayout(BoxLayout(self.uiESIndexLine, BoxLayout.LINE_AXIS))
        self.uiESIndexLine.setAlignmentX(JPanel.LEFT_ALIGNMENT)
        self.uiESIndexLine.add(JLabel("ElasticSearch Index: "))
        self.uiESIndex = JTextField(40)
        self.uiESIndex.setMaximumSize(self.uiESIndex.getPreferredSize())
        self.uiESIndexLine.add(self.uiESIndex)
        self.panel.add(self.uiESIndexLine)

        uiToolsLine = JPanel()
        uiToolsLine.setLayout(BoxLayout(uiToolsLine, BoxLayout.LINE_AXIS))
        uiToolsLine.setAlignmentX(JPanel.LEFT_ALIGNMENT)
        self.uiCBSuite = JCheckBox("Suite")
        uiToolsLine.add(self.uiCBSuite)
        uiToolsLine.add(Box.createRigidArea(Dimension(10, 0)))
        self.uiCBTarget = JCheckBox("Target")
        uiToolsLine.add(self.uiCBTarget)
        uiToolsLine.add(Box.createRigidArea(Dimension(10, 0)))
        self.uiCBProxy = JCheckBox("Proxy")
        uiToolsLine.add(self.uiCBProxy)
        uiToolsLine.add(Box.createRigidArea(Dimension(10, 0)))
        self.uiCBSpider = JCheckBox("Spider")
        uiToolsLine.add(self.uiCBSpider)
        uiToolsLine.add(Box.createRigidArea(Dimension(10, 0)))
        self.uiCBScanner = JCheckBox("Scanner")
        uiToolsLine.add(self.uiCBScanner)
        uiToolsLine.add(Box.createRigidArea(Dimension(10, 0)))
        self.uiCBIntruder = JCheckBox("Intruder")
        uiToolsLine.add(self.uiCBIntruder)
        uiToolsLine.add(Box.createRigidArea(Dimension(10, 0)))
        self.uiCBRepeater = JCheckBox("Repeater")
        uiToolsLine.add(self.uiCBRepeater)
        uiToolsLine.add(Box.createRigidArea(Dimension(10, 0)))
        self.uiCBSequencer = JCheckBox("Sequencer")
        uiToolsLine.add(self.uiCBSequencer)
        uiToolsLine.add(Box.createRigidArea(Dimension(10, 0)))
        self.uiCBExtender = JCheckBox("Extender")
        uiToolsLine.add(self.uiCBExtender)
        self.panel.add(uiToolsLine)
        self.panel.add(Box.createRigidArea(Dimension(0, 10)))

        uiOptionsLine = JPanel()
        uiOptionsLine.setLayout(BoxLayout(uiOptionsLine, BoxLayout.LINE_AXIS))
        uiOptionsLine.setAlignmentX(JPanel.LEFT_ALIGNMENT)
        self.uiCBOptRespOnly = JCheckBox("Process only responses (include requests)")
        uiOptionsLine.add(self.uiCBOptRespOnly)
        self.panel.add(uiOptionsLine)
        self.panel.add(Box.createRigidArea(Dimension(0, 10)))

        uiButtonsLine = JPanel()
        uiButtonsLine.setLayout(BoxLayout(uiButtonsLine, BoxLayout.LINE_AXIS))
        uiButtonsLine.setAlignmentX(JPanel.LEFT_ALIGNMENT)
        uiButtonsLine.add(JButton("Apply", actionPerformed=self.applyConfigUI))
        uiButtonsLine.add(JButton("Reset", actionPerformed=self.resetConfigUI))
        self.panel.add(uiButtonsLine)
        self.resetConfigUI(None)

        return self.panel

    ### IHttpListener ###
    def processHttpMessage(self, tool, isRequest, msg):
        if not tool & self.confBurpTools or isRequest and self.confBurpOnlyResp:
            return

        doc = self.genESDoc(msg)
        doc.save()

    ### IContextMenuFactory ###
    def createMenuItems(self, invocation):
        menuItems = list()
        selectedMsgs = invocation.getSelectedMessages()
        if selectedMsgs != None and len(selectedMsgs) >= 1:
            menuItems.append(JMenuItem("Add to ElasticSearch Index", actionPerformed=self.genAddToES(selectedMsgs, invocation.getInputEvent().getComponent())))
        return menuItems

    def genAddToES(self, msgs, component):
        def menuAddToES(e):
            progress = ProgressMonitor(component, "Feeding ElasticSearch", "", 0, len(msgs))
            i = 0
            docs = list()
            for msg in msgs:
                if not Burp_onlyResponses or msg.getResponse():
                    docs.append(self.genESDoc(msg, timeStampFromResponse=True).to_dict(True))
                i += 1
                progress.setProgress(i)
            success, failed = bulk(self.es, docs, True, raise_on_error=False)
            progress.close()
            JOptionPane.showMessageDialog(self.panel, "<html><p style='width: 300px'>Successful imported %d messages, %d messages failed.</p></html>" % (success, failed), "Finished", JOptionPane.INFORMATION_MESSAGE)
        return menuAddToES

    ### Interface to ElasticSearch ###
    def genESDoc(self, msg, timeStampFromResponse=False):
        httpService = msg.getHttpService()
        doc = DocHTTPRequestResponse(protocol=httpService.getProtocol(), host=httpService.getHost(), port=httpService.getPort())
        doc.meta.index = self.confESIndex

        request = msg.getRequest()
        response = msg.getResponse()

        if request:
            iRequest = self.helpers.analyzeRequest(msg)
            doc.request.method = iRequest.getMethod()
            doc.request.url = iRequest.getUrl().toString()

            headers = iRequest.getHeaders()
            for header in headers:
                try:
                    doc.add_request_header(header)
                except:
                    doc.request.requestline = header

            parameters = iRequest.getParameters()
            for parameter in parameters:
                ptype = parameter.getType()
                if ptype == IParameter.PARAM_URL:
                    typename = "url"
                elif ptype == IParameter.PARAM_BODY:
                    typename = "body"
                elif ptype == IParameter.PARAM_COOKIE:
                    typename = "cookie"
                elif ptype == IParameter.PARAM_XML:
                    typename = "xml"
                elif ptype == IParameter.PARAM_XML_ATTR:
                    typename = "xmlattr"
                elif ptype == IParameter.PARAM_MULTIPART_ATTR:
                    typename = "multipartattr"
                elif ptype == IParameter.PARAM_JSON:
                    typename = "json"
                else:
                    typename = "unknown"
                
                name = parameter.getName()
                value = parameter.getValue()
                doc.add_request_parameter(typename, name, value)

            ctype = iRequest.getContentType()
            if ctype == IRequestInfo.CONTENT_TYPE_NONE:
                doc.request.content_type = "none"
            elif ctype == IRequestInfo.CONTENT_TYPE_URL_ENCODED:
                doc.request.content_type = "urlencoded"
            elif ctype == IRequestInfo.CONTENT_TYPE_MULTIPART:
                doc.request.content_type = "multipart"
            elif ctype == IRequestInfo.CONTENT_TYPE_XML:
                doc.request.content_type = "xml"
            elif ctype == IRequestInfo.CONTENT_TYPE_JSON:
                doc.request.content_type = "json"
            elif ctype == IRequestInfo.CONTENT_TYPE_AMF:
                doc.request.content_type = "amf"
            else:
                doc.request.content_type = "unknown"

            bodyOffset = iRequest.getBodyOffset()
            doc.request.body = request[bodyOffset:].tostring().decode("ascii", "replace")

        if response:
            iResponse = self.helpers.analyzeResponse(response)

            doc.response.status = iResponse.getStatusCode()
            doc.response.content_type = iResponse.getStatedMimeType()
            doc.response.inferred_content_type = iResponse.getInferredMimeType()

            headers = iResponse.getHeaders()
            dateHeader = None
            for header in headers:
                try:
                    doc.add_response_header(header)
                    match = reDateHeader.match(header)
                    if match:
                        dateHeader = match.group(1)
                except:
                    doc.response.responseline = header

            cookies = iResponse.getCookies()
            for cookie in cookies:
                expCookie = cookie.getExpiration()
                expiration = None
                if expCookie:
                    try:
                        expiration = str(datetime.fromtimestamp(expCookie.time / 1000))
                    except:
                        pass
                doc.add_response_cookie(cookie.getName(), cookie.getValue(), cookie.getDomain(), cookie.getPath(), expiration)

            bodyOffset = iResponse.getBodyOffset()
            doc.response.body = response[bodyOffset:].tostring().decode("ascii", "replace")

            if timeStampFromResponse:
                if dateHeader:
                    try:
                        doc.timestamp = datetime.fromtimestamp(mktime_tz(parsedate_tz(dateHeader)), tz) # try to use date from response header "Date"
                        self.lastTimestamp = doc.timestamp
                    except:
                        doc.timestamp = self.lastTimestamp      # fallback: last stored timestamp. Else: now

        return doc
예제 #8
0
class BurpExtender(IBurpExtender, IHttpListener, IContextMenuFactory, ITab):
    def registerExtenderCallbacks(self, callbacks):
        self.lastTimestamp = None

        self.callbacks = callbacks
        self.helpers = callbacks.getHelpers()
        sys.stdout = callbacks.getStdout()

        l = self.callbacks.loadExtensionSetting
        self.es_host = l("elasticburp.host") or 'localhost'
        self.es_index = l("elasticburp.index") or 'burp'
        self.whitelist = l("elasticburp.whitelist") or ''
        tools = l("elasticburp.tools")
        self.tools = int(tools) if tools is not None else 511
        self.log_level = l("elasticburp.logLevel") or 'INFO'
        logger.setLevel(getattr(logging, self.log_level))

        self.callbacks.setExtensionName("ElasticBurp")
        self.callbacks.registerHttpListener(self)
        self.callbacks.registerContextMenuFactory(self)
        self.callbacks.addSuiteTab(self)

    def processHttpMessage(self, tool, isRequest, msg):
        if (tool & self.tools):
            logger.warning('Indexing single document')
            doc = self.create_document(msg)
            if doc is not None:
                doc.save()

    def create_document(self, msg):
        http_service = msg.getHttpService()

        host = http_service.getHost()
        if self.whitelist and self.whitelist not in host:
            logger.warning('Skipping {} because it\'s not in '
                           'the whitelist'.format(host))
            return

        doc = ElasticBurpDocument(
            self.es_index, self.es_host, http_service.getProtocol(),
            host, http_service.getPort())

        request = msg.getRequest()
        response = msg.getResponse()

        if request:
            req = self.helpers.analyzeRequest(msg)
            doc.request['method'] = req.getMethod()
            doc.request['url'] = req.getUrl().toString()

            logger.info('Indexing {} request from {}'.format(
                doc.request['method'], doc.request['url']))

            doc.add_request_headers(req.getHeaders())

            parameters = req.getParameters()
            for parameter in parameters:
                doc.add_request_parameter(
                    PARAMETER_TYPES[parameter.getType()],
                    parameter.getName(), parameter.getValue())

            ct = CONTENT_TYPES[req.getContentType()]
            doc.request['content_type'] = ct

            bodyOffset = req.getBodyOffset()
            doc.request['body'] = request[bodyOffset:].tostring().decode(
                "ascii", "replace")

        if response:
            iResponse = self.helpers.analyzeResponse(response)

            doc.response['status'] = iResponse.getStatusCode()
            doc.response['content_type'] = iResponse.getStatedMimeType()
            doc.response['inferred_content_type'] = \
                iResponse.getInferredMimeType()

            logger.info('Indexing {} response'.format(doc.response['status']))

            doc.add_response_headers(iResponse.getHeaders())

            cookies = iResponse.getCookies()
            for cookie in cookies:
                expCookie = cookie.getExpiration()
                expiration = datetime.fromtimestamp(expCookie.time / 1000) if \
                    expCookie else None
                doc.add_response_cookie(
                    cookie.getName(), cookie.getValue(), cookie.getDomain(),
                    cookie.getPath(), expiration)

            bodyOffset = iResponse.getBodyOffset()
            doc.response['body'] = response[bodyOffset:].tostring().decode(
                "ascii", "replace")

        return doc

    def getTabCaption(self):
        return "ElasticBurp"

    def getUiComponent(self):
        ui_panel = JPanel()
        ui_panel.setLayout(BoxLayout(ui_panel, BoxLayout.PAGE_AXIS))

        ui_host_line = JPanel()
        ui_host_line.setLayout(BoxLayout(ui_host_line, BoxLayout.LINE_AXIS))
        ui_host_line.setAlignmentX(JPanel.LEFT_ALIGNMENT)
        ui_host_line.add(JLabel("ElasticSearch Host: "))
        self.ui_es_host = JTextField(40)
        self.ui_es_host.setMaximumSize(self.ui_es_host.getPreferredSize())
        self.ui_es_host.setText(self.es_host)
        ui_host_line.add(self.ui_es_host)
        ui_panel.add(ui_host_line)

        ui_index_line = JPanel()
        ui_index_line.setLayout(BoxLayout(ui_index_line, BoxLayout.LINE_AXIS))
        ui_index_line.setAlignmentX(JPanel.LEFT_ALIGNMENT)
        ui_index_line.add(JLabel("ElasticSearch Index: "))
        self.ui_es_index = JTextField(40)
        self.ui_es_index.setText(self.es_index)
        self.ui_es_index.setMaximumSize(self.ui_es_index.getPreferredSize())
        ui_index_line.add(self.ui_es_index)
        ui_panel.add(ui_index_line)

        ui_whitelist_line = JPanel()
        ui_whitelist_line.setLayout(
            BoxLayout(ui_whitelist_line, BoxLayout.LINE_AXIS))
        ui_whitelist_line.setAlignmentX(JPanel.LEFT_ALIGNMENT)
        ui_whitelist_line.add(JLabel("Host whitelist: "))
        self.ui_whitelist = JTextField(40)
        self.ui_whitelist.setText(self.whitelist)
        self.ui_whitelist.setMaximumSize(self.ui_whitelist.getPreferredSize())
        ui_whitelist_line.add(self.ui_whitelist)
        ui_panel.add(ui_whitelist_line)

        ui_tools_panel = JPanel()
        ui_tools_panel.setLayout(
            BoxLayout(ui_tools_panel, BoxLayout.LINE_AXIS))
        ui_tools_panel.setAlignmentX(JPanel.LEFT_ALIGNMENT)
        self.ui_tool_suite = JCheckBox(
            "Suite", self.tools & ECallbacks.TOOL_SUITE != 0)
        ui_tools_panel.add(self.ui_tool_suite)
        ui_tools_panel.add(Box.createRigidArea(Dimension(10, 0)))
        self.ui_tool_target = JCheckBox(
            "Target", self.tools & ECallbacks.TOOL_TARGET != 0)
        ui_tools_panel.add(self.ui_tool_target)
        ui_tools_panel.add(Box.createRigidArea(Dimension(10, 0)))
        self.ui_tool_proxy = JCheckBox(
            "Proxy", self.tools & ECallbacks.TOOL_PROXY != 0)
        ui_tools_panel.add(self.ui_tool_proxy)
        ui_tools_panel.add(Box.createRigidArea(Dimension(10, 0)))
        self.ui_tool_spider = JCheckBox(
            "Spider", self.tools & ECallbacks.TOOL_SPIDER != 0)
        ui_tools_panel.add(self.ui_tool_spider)
        ui_tools_panel.add(Box.createRigidArea(Dimension(10, 0)))
        self.ui_tool_scanner = JCheckBox(
            "Scanner", self.tools & ECallbacks.TOOL_SCANNER != 0)
        ui_tools_panel.add(self.ui_tool_scanner)
        ui_tools_panel.add(Box.createRigidArea(Dimension(10, 0)))
        self.ui_tool_intruder = JCheckBox(
            "Intruder", self.tools & ECallbacks.TOOL_INTRUDER != 0)
        ui_tools_panel.add(self.ui_tool_intruder)
        ui_tools_panel.add(Box.createRigidArea(Dimension(10, 0)))
        self.ui_tool_repeater = JCheckBox(
            "Repeater", self.tools & ECallbacks.TOOL_REPEATER != 0)
        ui_tools_panel.add(self.ui_tool_repeater)
        ui_tools_panel.add(Box.createRigidArea(Dimension(10, 0)))
        self.ui_tool_sequencer = JCheckBox(
            "Sequencer", self.tools & ECallbacks.TOOL_SEQUENCER != 0)
        ui_tools_panel.add(self.ui_tool_sequencer)
        ui_tools_panel.add(Box.createRigidArea(Dimension(10, 0)))
        self.ui_tool_extender = JCheckBox(
            "Extender", self.tools & ECallbacks.TOOL_EXTENDER != 0)
        ui_tools_panel.add(self.ui_tool_extender)
        ui_panel.add(ui_tools_panel)
        ui_panel.add(Box.createRigidArea(Dimension(0, 10)))

        ui_log_line = JPanel()
        ui_log_line.setLayout(BoxLayout(ui_log_line, BoxLayout.LINE_AXIS))
        ui_log_line.setAlignmentX(JPanel.LEFT_ALIGNMENT)
        ui_debug = JRadioButton("DEBUG", self.log_level == 'DEBUG')
        ui_log_line.add(ui_debug)
        ui_log_line.add(Box.createRigidArea(Dimension(10, 0)))
        ui_info = JRadioButton("INFO", self.log_level == 'INFO')
        ui_log_line.add(ui_info)
        ui_log_line.add(Box.createRigidArea(Dimension(10, 0)))
        ui_warning = JRadioButton("WARNING", self.log_level == 'WARNING')
        ui_log_line.add(ui_warning)
        ui_log_line.add(Box.createRigidArea(Dimension(10, 0)))
        ui_error = JRadioButton("ERROR", self.log_level == 'ERROR')
        ui_log_line.add(ui_error)
        ui_log_line.add(Box.createRigidArea(Dimension(10, 0)))
        ui_critical = JRadioButton(
            "CRITICAL", self.log_level == 'CRITICAL')
        ui_log_line.add(ui_critical)
        ui_log_line.add(Box.createRigidArea(Dimension(10, 0)))
        ui_panel.add(ui_log_line)
        ui_panel.add(Box.createRigidArea(Dimension(0, 10)))
        self.ui_log_level = ButtonGroup()
        self.ui_log_level.add(ui_debug)
        self.ui_log_level.add(ui_info)
        self.ui_log_level.add(ui_warning)
        self.ui_log_level.add(ui_error)
        self.ui_log_level.add(ui_critical)

        ui_buttons_line = JPanel()
        ui_buttons_line.setLayout(
            BoxLayout(ui_buttons_line, BoxLayout.LINE_AXIS))
        ui_buttons_line.setAlignmentX(JPanel.LEFT_ALIGNMENT)
        ui_buttons_line.add(
            JButton("Save config", actionPerformed=self.save_config))
        ui_panel.add(ui_buttons_line)

        return ui_panel

    def save_config(self, event):
        logger.warning('Saving changes in config')
        self.es_host = self.ui_es_host.getText()
        self.es_index = self.ui_es_index.getText()
        self.whitelist = self.ui_whitelist.getText()

        self.tools = int(
            (self.ui_tool_suite.isSelected() and ECallbacks.TOOL_SUITE) |
            (self.ui_tool_target.isSelected() and ECallbacks.TOOL_TARGET) |
            (self.ui_tool_proxy.isSelected() and ECallbacks.TOOL_PROXY) |
            (self.ui_tool_spider.isSelected() and ECallbacks.TOOL_SPIDER) |
            (self.ui_tool_scanner.isSelected() and ECallbacks.TOOL_SCANNER) |
            (self.ui_tool_intruder.isSelected() and ECallbacks.TOOL_INTRUDER) |
            (self.ui_tool_repeater.isSelected() and ECallbacks.TOOL_REPEATER) |
            (self.ui_tool_sequencer.isSelected() and
                ECallbacks.TOOL_SEQUENCER) |
            (self.ui_tool_extender.isSelected() and ECallbacks.TOOL_EXTENDER))
        logger.debug('Changing tools in config to %d' % self.tools)

        for button in self.ui_log_level.getElements():
            if button.isSelected():
                logger.debug('Changing logLevel to %s' % button.getText())
                self.log_level = button.getText()

        s = self.callbacks.saveExtensionSetting
        s("elasticburp.host", self.es_host)
        s("elasticburp.index", self.es_index)
        s("elasticburp.tools", str(self.tools))
        s("elasticburp.logLevel", self.log_level)
        s("elasticburp.whitelist", self.whitelist)
        logger.setLevel(getattr(logging, self.log_level))
예제 #9
0
class choice_gui:

    ################ input function

    def obtain_prefixes(self):
        self.sourceDir = DirectoryChooser(
            "Choose directory to load stack from").getDirectory()
        os.chdir(self.sourceDir)

        curdir = os.getcwd()
        listdire = os.listdir(curdir)

        prefixlist = []
        prefix_len = JOptionPane.showInputDialog(
            None,
            "how long is the file prefix to group by?(integer value only)")
        for name in listdire:
            if ".tif" in name:
                prefixname = name[:int(prefix_len)]
                prefixlist.append(prefixname)

        unique_prefix = sorted(set(prefixlist))
        self.pref_dict = {}

        for a in unique_prefix:
            pref_list = []
            for b in listdire:
                if b.startswith(a):
                    pref_list.append(b)
            self.pref_dict[a] = pref_list
        return self.pref_dict

################### event handling

    def listSelect(self, event):
        self.index = self.lst.selectedIndex

    def clickhere(self, event):
        self.lst.selectionMode = (
            ListSelectionModel.MULTIPLE_INTERVAL_SELECTION)
        print "clicked"
        self.itemSelected = list(sorted(self.lst.selectedValues[:]))
        print "item selected:", self.itemSelected
        if self.radiobutton1.isSelected():
            self.saveState = "Y"
            print "Save MIPs!"
        if self.radiobutton2.isSelected():
            self.saveState = "N"
            print "Don't save MIPs!"
        self.exeunt = JOptionPane.showConfirmDialog(
            None,
            "You have chosen to make MIPs out of \n {} \n proceed?".format(
                str(self.itemSelected)), "Proceed?", JOptionPane.YES_NO_OPTION)
        self.clickEx()

    def clickEx(self):
        if self.exeunt == JOptionPane.YES_OPTION:
            print "confirmed"
            self.fileExt = str(self.filetype.getText())
            self.frame.setVisible(False)
            if self.saveState == "Y":
                self.saveDir = DirectoryChooser(
                    "Choose directory to save MIPs to").getDirectory()
            self.createMIP()
        else:
            print "cancelled"

################### ImageJ

    def maxZprojection(self, inputimg):
        zp = ZProjector(inputimg)
        zp.setMethod(ZProjector.MAX_METHOD)
        zp.doProjection()
        Zproj = zp.getProjection()
        return Zproj

    def createMIP(self):
        print "starting createMIP"
        for a in self.itemSelected:
            ImStack = None
            for filename in self.dict1.get(a):
                self.savfileName = a
                if not filename.endswith(self.fileExt):
                    continue
                path = self.sourceDir + filename
                # Upon finding the first image, initialize the VirtualStack
                if ImStack is None:
                    imp = IJ.openImage(path)
                    ImStack = VirtualStack(imp.width, imp.height, None,
                                           self.sourceDir)
                # Add a slice, relative to the sourceDIr
                ImStack.addSlice(filename)
            #adding text overlay to output images so we can differentiate them. Overlay is non destructive - does not affect pixel values of image, and can be selected and deleted
            prefix_overlay = Overlay()
            font = Font("SansSerif", Font.PLAIN, 10)
            roi = TextRoi(0, 0, a)
            roi.setStrokeColor(Color(1.00, 1.00, 1.00))
            prefix_overlay.add(roi)
            #
            OnscreenImage = ImagePlus(self.sourceDir, ImStack)
            OnscreenImage.setOverlay(prefix_overlay)
            OnscreenImage.show()

            print "Generating MIP, waiting..."
            self.outimp = self.maxZprojection(
                OnscreenImage)  #generate max projection
            self.outimp.setOverlay(prefix_overlay)
            self.outimp.show()
            print "Max projection generated"
            if self.saveState == "Y":
                self.saveMIP()
            print "Finished!"

    def saveMIP(self):
        curdir = os.path.split(os.getcwd())[1]
        savename = self.saveDir + curdir + self.savfileName + "_MIP.tif"
        print "savename = ", savename
        print "saving...."
        IJ.save(self.outimp, savename)
        print "saved as", savename


###################

    def __init__(self):
        #obtain prefixes from folder
        self.dict1 = self.obtain_prefixes(
        )  #Run prefix selection function - sets source directory, requests prefix size, outputs prefix dictionary
        lst = list(self.dict1.keys())  #pull prefixes only, as list
        self.lang = lst
        self.lst = JList(self.lang, valueChanged=self.listSelect
                         )  # pass prefix list to GUI selection list

        # general GUI layout parameters, no data processing here
        self.frame = JFrame("Image Selection")
        self.frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE)
        self.frame.setLocation(100, 100)
        self.frame.setSize(800, 350)
        self.frame.setLayout(BorderLayout())

        self.frame.add(self.lst, BorderLayout.NORTH)
        self.lst.selectionMode = ListSelectionModel.MULTIPLE_INTERVAL_SELECTION
        self.button1 = JButton('Select item(s)',
                               actionPerformed=self.clickhere)

        #Save option radio buttons and file extension selection
        #set main right panel (sub panels will fit within this)
        rightpanel = JPanel()
        rightpanel.setLayout(BoxLayout(rightpanel, BoxLayout.Y_AXIS))

        #set up savestate panel
        buttonpanel = JPanel()
        self.radiobutton1 = JRadioButton(
            "Open selected 3D stacks and max projections \n and save max projections",
            True)
        self.radiobutton2 = JRadioButton(
            "Open selected 3D stacks and max projections \n and DO NOT save max projections"
        )
        infoLabel = JLabel(
            "<html>Hold ctrl and click multiple prefixes to select multiple options. Will load stacks and MIPs separately <br><br> Type file extension in text field below:</html>",
            SwingConstants.LEFT)
        grp = ButtonGroup()
        grp.add(self.radiobutton1)
        grp.add(self.radiobutton2)
        #buttonpanel.setLayout(BoxLayout(buttonpanel, BoxLayout.Y_AXIS))
        buttonpanel.add(Box.createVerticalGlue())
        buttonpanel.add(infoLabel)
        buttonpanel.add(Box.createRigidArea(Dimension(0, 5)))
        buttonpanel.add(self.radiobutton1)
        buttonpanel.add(Box.createRigidArea(Dimension(0, 5)))
        buttonpanel.add(self.radiobutton2)

        #file extension instruction panel
        infopanel = JPanel()
        infopanel.setLayout(FlowLayout(FlowLayout.LEFT))
        infopanel.setMaximumSize(
            infopanel.setPreferredSize(Dimension(650, 100)))
        infopanel.add(infoLabel)

        #file extension input
        inputPanel = JPanel()
        inputPanel.setLayout(BoxLayout(inputPanel, BoxLayout.X_AXIS))
        self.filetype = JTextField(".tif", 15)
        self.filetype.setMaximumSize(self.filetype.getPreferredSize())
        inputPanel.add(self.filetype)

        ########### WIP - integrate prefix selection with main pane, with dynamically updating prefix list
        ##infoLabel3 = JLabel("how long is the file prefix to group by?(integer value only)")
        ##self.prefix_init = JTextField()
        ##buttonpanel.add(infoLabel3)
        ##buttonpanel.add(self.prefix_init)
        ########### !WIP
        #add file extension and savestate panels to main panel
        rightpanel.add(infopanel)
        rightpanel.add(inputPanel)
        rightpanel.add(buttonpanel, BorderLayout.EAST)

        #split list and radiobutton pane (construct overall window)
        spl = JSplitPane(JSplitPane.HORIZONTAL_SPLIT)
        spl.leftComponent = JScrollPane(self.lst)
        spl.setDividerLocation(150)
        spl.rightComponent = rightpanel
        self.frame.add(spl)
        self.frame.add(self.button1, BorderLayout.SOUTH)

        # GUI layout done, initialise GUI to select prefixes, file extension and save option
        self.frame.setVisible(True)
예제 #10
0
    def __init__(self, app):
        from java.awt import Dialog
        from java.awt import CardLayout
        JDialog.__init__(self,
                         app.preferencesFrame,
                         app.strings.getString("Create_a_new_favourite_zone"),
                         Dialog.ModalityType.DOCUMENT_MODAL)
        self.app = app
        border = BorderFactory.createEmptyBorder(5, 7, 7, 7)
        self.getContentPane().setBorder(border)
        self.setLayout(BoxLayout(self.getContentPane(), BoxLayout.Y_AXIS))

        self.FAVAREALAYERNAME = "Favourite zone editing"

        info = JLabel(self.app.strings.getString("Create_a_new_favourite_zone"))
        info.setAlignmentX(Component.LEFT_ALIGNMENT)

        #Name
        nameLbl = JLabel(self.app.strings.getString("fav_zone_name"))
        self.nameTextField = JTextField(20)
        self.nameTextField.setMaximumSize(self.nameTextField.getPreferredSize())
        self.nameTextField.setToolTipText(self.app.strings.getString("fav_zone_name_tooltip"))
        namePanel = JPanel()
        namePanel.setLayout(BoxLayout(namePanel, BoxLayout.X_AXIS))
        namePanel.add(nameLbl)
        namePanel.add(Box.createHorizontalGlue())
        namePanel.add(self.nameTextField)

        #Country
        countryLbl = JLabel(self.app.strings.getString("fav_zone_country"))
        self.countryTextField = JTextField(20)
        self.countryTextField.setMaximumSize(self.countryTextField.getPreferredSize())
        self.countryTextField.setToolTipText(self.app.strings.getString("fav_zone_country_tooltip"))
        countryPanel = JPanel()
        countryPanel.setLayout(BoxLayout(countryPanel, BoxLayout.X_AXIS))
        countryPanel.add(countryLbl)
        countryPanel.add(Box.createHorizontalGlue())
        countryPanel.add(self.countryTextField)

        #Type
        modeLbl = JLabel(self.app.strings.getString("fav_zone_type"))
        RECTPANEL = "rectangle"
        POLYGONPANEL = "polygon"
        BOUNDARYPANEL = "boundary"
        self.modesStrings = [RECTPANEL, POLYGONPANEL, BOUNDARYPANEL]
        modesComboModel = DefaultComboBoxModel()
        for i in (self.app.strings.getString("rectangle"),
                  self.app.strings.getString("delimited_by_a_closed_way"),
                  self.app.strings.getString("delimited_by_an_administrative_boundary")):
            modesComboModel.addElement(i)
        self.modesComboBox = JComboBox(modesComboModel,
                                       actionListener=self,
                                       editable=False)

        #- Rectangle
        self.rectPanel = JPanel()
        self.rectPanel.setLayout(BoxLayout(self.rectPanel, BoxLayout.Y_AXIS))

        capturePane = JPanel()
        capturePane.setLayout(BoxLayout(capturePane, BoxLayout.X_AXIS))
        capturePane.setAlignmentX(Component.LEFT_ALIGNMENT)

        josmP = JPanel()
        self.captureRBtn = JRadioButton(self.app.strings.getString("capture_area"))
        self.captureRBtn.addActionListener(self)
        self.captureRBtn.setSelected(True)
        self.bboxFromJosmBtn = JButton(self.app.strings.getString("get_current_area"),
                                       actionPerformed=self.on_bboxFromJosmBtn_clicked)
        self.bboxFromJosmBtn.setToolTipText(self.app.strings.getString("get_capture_area_tooltip"))
        josmP.add(self.bboxFromJosmBtn)
        capturePane.add(self.captureRBtn)
        capturePane.add(Box.createHorizontalGlue())
        capturePane.add(self.bboxFromJosmBtn)

        manualPane = JPanel()
        manualPane.setLayout(BoxLayout(manualPane, BoxLayout.X_AXIS))
        manualPane.setAlignmentX(Component.LEFT_ALIGNMENT)
        self.manualRBtn = JRadioButton(self.app.strings.getString("use_this_bbox"))
        self.manualRBtn.addActionListener(self)
        self.bboxTextField = JTextField(20)
        self.bboxTextField.setMaximumSize(self.bboxTextField.getPreferredSize())
        self.bboxTextField.setToolTipText(self.app.strings.getString("fav_bbox_tooltip"))
        self.bboxTextFieldDefaultBorder = self.bboxTextField.getBorder()
        self.bboxTextField.getDocument().addDocumentListener(TextListener(self))
        manualPane.add(self.manualRBtn)
        manualPane.add(Box.createHorizontalGlue())
        manualPane.add(self.bboxTextField)

        group = ButtonGroup()
        group.add(self.captureRBtn)
        group.add(self.manualRBtn)

        previewPane = JPanel()
        previewPane.setLayout(BoxLayout(previewPane, BoxLayout.X_AXIS))
        previewPane.setAlignmentX(Component.LEFT_ALIGNMENT)
        bboxPreviewInfo = JTextField(self.app.strings.getString("coordinates"),
                                     editable=0,
                                     border=None)
        bboxPreviewInfo.setMaximumSize(bboxPreviewInfo.getPreferredSize())
        self.bboxPreviewTextField = JTextField(20,
                                               editable=0,
                                               border=None)
        self.bboxPreviewTextField.setMaximumSize(self.bboxPreviewTextField.getPreferredSize())
        previewPane.add(bboxPreviewInfo)
        previewPane.add(Box.createHorizontalGlue())
        previewPane.add(self.bboxPreviewTextField)

        self.rectPanel.add(capturePane)
        self.rectPanel.add(Box.createRigidArea(Dimension(0, 10)))
        self.rectPanel.add(manualPane)
        self.rectPanel.add(Box.createRigidArea(Dimension(0, 20)))
        self.rectPanel.add(previewPane)

        #- Polygon (closed way) drawn by hand
        self.polygonPanel = JPanel(BorderLayout())
        self.polygonPanel.setLayout(BoxLayout(self.polygonPanel, BoxLayout.Y_AXIS))

        polyInfo = JLabel("<html>%s</html>" % self.app.strings.getString("polygon_info"))
        polyInfo.setFont(polyInfo.getFont().deriveFont(Font.ITALIC))
        polyInfo.setAlignmentX(Component.LEFT_ALIGNMENT)

        editPolyPane = JPanel()
        editPolyPane.setAlignmentX(Component.LEFT_ALIGNMENT)
        editPolyBtn = JButton(self.app.strings.getString("create_fav_layer"),
                              actionPerformed=self.create_new_zone_editing_layer)
        editPolyBtn.setToolTipText(self.app.strings.getString("create_fav_layer_tooltip"))
        editPolyPane.add(editPolyBtn)

        self.polygonPanel.add(polyInfo)
        self.polygonPanel.add(Box.createRigidArea(Dimension(0, 15)))
        self.polygonPanel.add(editPolyPane)
        self.polygonPanel.add(Box.createRigidArea(Dimension(0, 15)))

        #- Administrative Boundary
        self.boundaryPanel = JPanel()
        self.boundaryPanel.setLayout(BoxLayout(self.boundaryPanel, BoxLayout.Y_AXIS))

        boundaryInfo = JLabel("<html>%s</html>" % app.strings.getString("boundary_info"))
        boundaryInfo.setFont(boundaryInfo.getFont().deriveFont(Font.ITALIC))
        boundaryInfo.setAlignmentX(Component.LEFT_ALIGNMENT)

        boundaryTagsPanel = JPanel(GridLayout(3, 3, 5, 5))
        boundaryTagsPanel.setAlignmentX(Component.LEFT_ALIGNMENT)
        boundaryTagsPanel.add(JLabel("name ="))
        self.nameTagTextField = JTextField(20)
        boundaryTagsPanel.add(self.nameTagTextField)
        boundaryTagsPanel.add(UrlLabel("http://wiki.openstreetmap.org/wiki/Key:admin_level#admin_level", "admin_level ="))
        self.adminLevelTagTextField = JTextField(20)
        self.adminLevelTagTextField.setToolTipText(self.app.strings.getString("adminLevel_tooltip"))
        boundaryTagsPanel.add(self.adminLevelTagTextField)
        boundaryTagsPanel.add(JLabel(self.app.strings.getString("other_tag")))
        self.optionalTagTextField = JTextField(20)
        self.optionalTagTextField.setToolTipText("key=value")
        boundaryTagsPanel.add(self.optionalTagTextField)

        downloadBoundariesPane = JPanel()
        downloadBoundariesPane.setAlignmentX(Component.LEFT_ALIGNMENT)
        downloadBoundariesBtn = JButton(self.app.strings.getString("download_boundary"),
                                        actionPerformed=self.on_downloadBoundariesBtn_clicked)
        downloadBoundariesBtn.setToolTipText(self.app.strings.getString("download_boundary_tooltip"))
        downloadBoundariesPane.add(downloadBoundariesBtn)

        self.boundaryPanel.add(boundaryInfo)
        self.boundaryPanel.add(Box.createRigidArea(Dimension(0, 15)))
        self.boundaryPanel.add(boundaryTagsPanel)
        self.boundaryPanel.add(Box.createRigidArea(Dimension(0, 10)))
        self.boundaryPanel.add(downloadBoundariesPane)

        self.editingPanels = {"rectangle": self.rectPanel,
                              "polygon": self.polygonPanel,
                              "boundary": self.boundaryPanel}

        #Main buttons
        self.okBtn = JButton(self.app.strings.getString("OK"),
                             ImageProvider.get("ok"),
                             actionPerformed=self.on_okBtn_clicked)
        self.cancelBtn = JButton(self.app.strings.getString("cancel"),
                                 ImageProvider.get("cancel"),
                                 actionPerformed=self.close_dialog)
        self.previewBtn = JButton(self.app.strings.getString("Preview_zone"),
                                  actionPerformed=self.on_previewBtn_clicked)
        self.previewBtn.setToolTipText(self.app.strings.getString("preview_zone_tooltip"))
        okBtnSize = self.okBtn.getPreferredSize()
        viewBtnSize = self.previewBtn.getPreferredSize()
        viewBtnSize.height = okBtnSize.height
        self.previewBtn.setPreferredSize(viewBtnSize)

        #layout
        self.add(info)
        self.add(Box.createRigidArea(Dimension(0, 15)))

        namePanel.setAlignmentX(Component.LEFT_ALIGNMENT)
        self.add(namePanel)
        self.add(Box.createRigidArea(Dimension(0, 15)))

        countryPanel.setAlignmentX(Component.LEFT_ALIGNMENT)
        self.add(countryPanel)
        self.add(Box.createRigidArea(Dimension(0, 15)))

        modeLbl.setAlignmentX(Component.LEFT_ALIGNMENT)
        self.add(modeLbl)
        self.add(Box.createRigidArea(Dimension(0, 5)))

        self.add(self.modesComboBox)
        self.modesComboBox.setAlignmentX(Component.LEFT_ALIGNMENT)
        self.add(Box.createRigidArea(Dimension(0, 15)))

        self.configPanel = JPanel(CardLayout())
        self.configPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5))
        self.configPanel.add(self.rectPanel, RECTPANEL)
        self.configPanel.add(self.polygonPanel, POLYGONPANEL)
        self.configPanel.add(self.boundaryPanel, BOUNDARYPANEL)
        self.configPanel.setAlignmentX(Component.LEFT_ALIGNMENT)
        self.add(self.configPanel)
        buttonsPanel = JPanel()
        buttonsPanel.add(self.okBtn)
        buttonsPanel.add(self.cancelBtn)
        buttonsPanel.add(self.previewBtn)
        buttonsPanel.setAlignmentX(Component.LEFT_ALIGNMENT)
        self.add(buttonsPanel)

        self.addWindowListener(self)
        self.pack()
예제 #11
0
class NewZoneDialog(JDialog, ActionListener, WindowListener):
    """Dialog for favourite zone editing
    """
    def __init__(self, app):
        from java.awt import Dialog
        from java.awt import CardLayout
        JDialog.__init__(self,
                         app.preferencesFrame,
                         app.strings.getString("Create_a_new_favourite_zone"),
                         Dialog.ModalityType.DOCUMENT_MODAL)
        self.app = app
        border = BorderFactory.createEmptyBorder(5, 7, 7, 7)
        self.getContentPane().setBorder(border)
        self.setLayout(BoxLayout(self.getContentPane(), BoxLayout.Y_AXIS))

        self.FAVAREALAYERNAME = "Favourite zone editing"

        info = JLabel(self.app.strings.getString("Create_a_new_favourite_zone"))
        info.setAlignmentX(Component.LEFT_ALIGNMENT)

        #Name
        nameLbl = JLabel(self.app.strings.getString("fav_zone_name"))
        self.nameTextField = JTextField(20)
        self.nameTextField.setMaximumSize(self.nameTextField.getPreferredSize())
        self.nameTextField.setToolTipText(self.app.strings.getString("fav_zone_name_tooltip"))
        namePanel = JPanel()
        namePanel.setLayout(BoxLayout(namePanel, BoxLayout.X_AXIS))
        namePanel.add(nameLbl)
        namePanel.add(Box.createHorizontalGlue())
        namePanel.add(self.nameTextField)

        #Country
        countryLbl = JLabel(self.app.strings.getString("fav_zone_country"))
        self.countryTextField = JTextField(20)
        self.countryTextField.setMaximumSize(self.countryTextField.getPreferredSize())
        self.countryTextField.setToolTipText(self.app.strings.getString("fav_zone_country_tooltip"))
        countryPanel = JPanel()
        countryPanel.setLayout(BoxLayout(countryPanel, BoxLayout.X_AXIS))
        countryPanel.add(countryLbl)
        countryPanel.add(Box.createHorizontalGlue())
        countryPanel.add(self.countryTextField)

        #Type
        modeLbl = JLabel(self.app.strings.getString("fav_zone_type"))
        RECTPANEL = "rectangle"
        POLYGONPANEL = "polygon"
        BOUNDARYPANEL = "boundary"
        self.modesStrings = [RECTPANEL, POLYGONPANEL, BOUNDARYPANEL]
        modesComboModel = DefaultComboBoxModel()
        for i in (self.app.strings.getString("rectangle"),
                  self.app.strings.getString("delimited_by_a_closed_way"),
                  self.app.strings.getString("delimited_by_an_administrative_boundary")):
            modesComboModel.addElement(i)
        self.modesComboBox = JComboBox(modesComboModel,
                                       actionListener=self,
                                       editable=False)

        #- Rectangle
        self.rectPanel = JPanel()
        self.rectPanel.setLayout(BoxLayout(self.rectPanel, BoxLayout.Y_AXIS))

        capturePane = JPanel()
        capturePane.setLayout(BoxLayout(capturePane, BoxLayout.X_AXIS))
        capturePane.setAlignmentX(Component.LEFT_ALIGNMENT)

        josmP = JPanel()
        self.captureRBtn = JRadioButton(self.app.strings.getString("capture_area"))
        self.captureRBtn.addActionListener(self)
        self.captureRBtn.setSelected(True)
        self.bboxFromJosmBtn = JButton(self.app.strings.getString("get_current_area"),
                                       actionPerformed=self.on_bboxFromJosmBtn_clicked)
        self.bboxFromJosmBtn.setToolTipText(self.app.strings.getString("get_capture_area_tooltip"))
        josmP.add(self.bboxFromJosmBtn)
        capturePane.add(self.captureRBtn)
        capturePane.add(Box.createHorizontalGlue())
        capturePane.add(self.bboxFromJosmBtn)

        manualPane = JPanel()
        manualPane.setLayout(BoxLayout(manualPane, BoxLayout.X_AXIS))
        manualPane.setAlignmentX(Component.LEFT_ALIGNMENT)
        self.manualRBtn = JRadioButton(self.app.strings.getString("use_this_bbox"))
        self.manualRBtn.addActionListener(self)
        self.bboxTextField = JTextField(20)
        self.bboxTextField.setMaximumSize(self.bboxTextField.getPreferredSize())
        self.bboxTextField.setToolTipText(self.app.strings.getString("fav_bbox_tooltip"))
        self.bboxTextFieldDefaultBorder = self.bboxTextField.getBorder()
        self.bboxTextField.getDocument().addDocumentListener(TextListener(self))
        manualPane.add(self.manualRBtn)
        manualPane.add(Box.createHorizontalGlue())
        manualPane.add(self.bboxTextField)

        group = ButtonGroup()
        group.add(self.captureRBtn)
        group.add(self.manualRBtn)

        previewPane = JPanel()
        previewPane.setLayout(BoxLayout(previewPane, BoxLayout.X_AXIS))
        previewPane.setAlignmentX(Component.LEFT_ALIGNMENT)
        bboxPreviewInfo = JTextField(self.app.strings.getString("coordinates"),
                                     editable=0,
                                     border=None)
        bboxPreviewInfo.setMaximumSize(bboxPreviewInfo.getPreferredSize())
        self.bboxPreviewTextField = JTextField(20,
                                               editable=0,
                                               border=None)
        self.bboxPreviewTextField.setMaximumSize(self.bboxPreviewTextField.getPreferredSize())
        previewPane.add(bboxPreviewInfo)
        previewPane.add(Box.createHorizontalGlue())
        previewPane.add(self.bboxPreviewTextField)

        self.rectPanel.add(capturePane)
        self.rectPanel.add(Box.createRigidArea(Dimension(0, 10)))
        self.rectPanel.add(manualPane)
        self.rectPanel.add(Box.createRigidArea(Dimension(0, 20)))
        self.rectPanel.add(previewPane)

        #- Polygon (closed way) drawn by hand
        self.polygonPanel = JPanel(BorderLayout())
        self.polygonPanel.setLayout(BoxLayout(self.polygonPanel, BoxLayout.Y_AXIS))

        polyInfo = JLabel("<html>%s</html>" % self.app.strings.getString("polygon_info"))
        polyInfo.setFont(polyInfo.getFont().deriveFont(Font.ITALIC))
        polyInfo.setAlignmentX(Component.LEFT_ALIGNMENT)

        editPolyPane = JPanel()
        editPolyPane.setAlignmentX(Component.LEFT_ALIGNMENT)
        editPolyBtn = JButton(self.app.strings.getString("create_fav_layer"),
                              actionPerformed=self.create_new_zone_editing_layer)
        editPolyBtn.setToolTipText(self.app.strings.getString("create_fav_layer_tooltip"))
        editPolyPane.add(editPolyBtn)

        self.polygonPanel.add(polyInfo)
        self.polygonPanel.add(Box.createRigidArea(Dimension(0, 15)))
        self.polygonPanel.add(editPolyPane)
        self.polygonPanel.add(Box.createRigidArea(Dimension(0, 15)))

        #- Administrative Boundary
        self.boundaryPanel = JPanel()
        self.boundaryPanel.setLayout(BoxLayout(self.boundaryPanel, BoxLayout.Y_AXIS))

        boundaryInfo = JLabel("<html>%s</html>" % app.strings.getString("boundary_info"))
        boundaryInfo.setFont(boundaryInfo.getFont().deriveFont(Font.ITALIC))
        boundaryInfo.setAlignmentX(Component.LEFT_ALIGNMENT)

        boundaryTagsPanel = JPanel(GridLayout(3, 3, 5, 5))
        boundaryTagsPanel.setAlignmentX(Component.LEFT_ALIGNMENT)
        boundaryTagsPanel.add(JLabel("name ="))
        self.nameTagTextField = JTextField(20)
        boundaryTagsPanel.add(self.nameTagTextField)
        boundaryTagsPanel.add(UrlLabel("http://wiki.openstreetmap.org/wiki/Key:admin_level#admin_level", "admin_level ="))
        self.adminLevelTagTextField = JTextField(20)
        self.adminLevelTagTextField.setToolTipText(self.app.strings.getString("adminLevel_tooltip"))
        boundaryTagsPanel.add(self.adminLevelTagTextField)
        boundaryTagsPanel.add(JLabel(self.app.strings.getString("other_tag")))
        self.optionalTagTextField = JTextField(20)
        self.optionalTagTextField.setToolTipText("key=value")
        boundaryTagsPanel.add(self.optionalTagTextField)

        downloadBoundariesPane = JPanel()
        downloadBoundariesPane.setAlignmentX(Component.LEFT_ALIGNMENT)
        downloadBoundariesBtn = JButton(self.app.strings.getString("download_boundary"),
                                        actionPerformed=self.on_downloadBoundariesBtn_clicked)
        downloadBoundariesBtn.setToolTipText(self.app.strings.getString("download_boundary_tooltip"))
        downloadBoundariesPane.add(downloadBoundariesBtn)

        self.boundaryPanel.add(boundaryInfo)
        self.boundaryPanel.add(Box.createRigidArea(Dimension(0, 15)))
        self.boundaryPanel.add(boundaryTagsPanel)
        self.boundaryPanel.add(Box.createRigidArea(Dimension(0, 10)))
        self.boundaryPanel.add(downloadBoundariesPane)

        self.editingPanels = {"rectangle": self.rectPanel,
                              "polygon": self.polygonPanel,
                              "boundary": self.boundaryPanel}

        #Main buttons
        self.okBtn = JButton(self.app.strings.getString("OK"),
                             ImageProvider.get("ok"),
                             actionPerformed=self.on_okBtn_clicked)
        self.cancelBtn = JButton(self.app.strings.getString("cancel"),
                                 ImageProvider.get("cancel"),
                                 actionPerformed=self.close_dialog)
        self.previewBtn = JButton(self.app.strings.getString("Preview_zone"),
                                  actionPerformed=self.on_previewBtn_clicked)
        self.previewBtn.setToolTipText(self.app.strings.getString("preview_zone_tooltip"))
        okBtnSize = self.okBtn.getPreferredSize()
        viewBtnSize = self.previewBtn.getPreferredSize()
        viewBtnSize.height = okBtnSize.height
        self.previewBtn.setPreferredSize(viewBtnSize)

        #layout
        self.add(info)
        self.add(Box.createRigidArea(Dimension(0, 15)))

        namePanel.setAlignmentX(Component.LEFT_ALIGNMENT)
        self.add(namePanel)
        self.add(Box.createRigidArea(Dimension(0, 15)))

        countryPanel.setAlignmentX(Component.LEFT_ALIGNMENT)
        self.add(countryPanel)
        self.add(Box.createRigidArea(Dimension(0, 15)))

        modeLbl.setAlignmentX(Component.LEFT_ALIGNMENT)
        self.add(modeLbl)
        self.add(Box.createRigidArea(Dimension(0, 5)))

        self.add(self.modesComboBox)
        self.modesComboBox.setAlignmentX(Component.LEFT_ALIGNMENT)
        self.add(Box.createRigidArea(Dimension(0, 15)))

        self.configPanel = JPanel(CardLayout())
        self.configPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5))
        self.configPanel.add(self.rectPanel, RECTPANEL)
        self.configPanel.add(self.polygonPanel, POLYGONPANEL)
        self.configPanel.add(self.boundaryPanel, BOUNDARYPANEL)
        self.configPanel.setAlignmentX(Component.LEFT_ALIGNMENT)
        self.add(self.configPanel)
        buttonsPanel = JPanel()
        buttonsPanel.add(self.okBtn)
        buttonsPanel.add(self.cancelBtn)
        buttonsPanel.add(self.previewBtn)
        buttonsPanel.setAlignmentX(Component.LEFT_ALIGNMENT)
        self.add(buttonsPanel)

        self.addWindowListener(self)
        self.pack()

    def update_gui_from_preferences(self):
        self.nameTextField.setText(self.app.newZone.name)
        #Reset rectangle mode
        bboxStr = ",".join(["%0.4f" % x for x in self.app.newZone.bbox])
        self.bboxTextField.setText(bboxStr)
        self.bboxPreviewTextField.setText(bboxStr)
        self.bboxFromJosmBtn.setEnabled(True)
        self.bboxTextField.setEnabled(False)

        #Reset polygon mode
        self.polygonAsString = ""

        #Reset boundary mode
        self.boundaryAsString = ""

        self.modesComboBox.setSelectedIndex(0)

    def actionPerformed(self, e):
        #Show the panel for configuring the favourite area of the
        #selected type
        if e.getSource() == self.modesComboBox:
            cl = self.configPanel.getLayout()
            selectedMode = self.modesStrings[self.modesComboBox.selectedIndex]
            cl.show(self.configPanel, selectedMode)
        #Activate bbox input for rectangular favourite zone mode
        elif e.getSource() == self.captureRBtn:
            self.bboxFromJosmBtn.setEnabled(True)
            self.bboxTextField.setEnabled(False)
        else:
            self.bboxFromJosmBtn.setEnabled(False)
            self.bboxTextField.setEnabled(True)

    def on_bboxFromJosmBtn_clicked(self, widget):
        """Read bbox currently shown in JOSM
        """
        bbox = self.app.get_frame_bounds()
        self.bboxPreviewTextField.setText(",".join(["%0.4f" % x for x in bbox]))

### Manage layer for creating a new favourite zone from polygon or boundary
    def create_new_zone_editing_layer(self, e=None):
        """Open a new dataset where the user can draw a closed way to
           delimit the favourite area
        """
        layer = self.get_new_zone_editing_layer()
        if layer is not None:
            self.app.mv.setActiveLayer(layer)
        else:
            Main.main.addLayer(OsmDataLayer(DataSet(), self.FAVAREALAYERNAME, None))
        Main.main.parent.toFront()

    def get_new_zone_editing_layer(self):
        """Check if the layer for editing the favourite area yet exists
        """
        for layer in self.app.mv.getAllLayers():
            if layer.getName() == self.FAVAREALAYERNAME:
                return layer
        return None

    def remove_new_zone_editing_layer(self):
        layer = self.get_new_zone_editing_layer()
        if layer is not None:
            self.app.mv.removeLayer(layer)

    def on_zone_edited(self):
        """Read ways that delimit the favourite area and convert them to
           jts geometry
        """
        if self.modesComboBox.getSelectedIndex() == 0:
            mode = "rectangle"
        elif self.modesComboBox.getSelectedIndex() == 1:
            mode = "polygon"
        elif self.modesComboBox.getSelectedIndex() == 2:
            mode = "boundary"

        if mode in ("polygon", "boundary"):
            layer = self.get_new_zone_editing_layer()
            if layer is not None:
                self.app.mv.setActiveLayer(layer)
            else:
                if mode == "polygon":
                    msg = self.app.strings.getString("polygon_fav_layer_missing_msg")
                else:
                    msg = self.app.strings.getString("boundary_fav_layer_missing_msg")
                JOptionPane.showMessageDialog(self,
                                              msg,
                                              self.app.strings.getString("Warning"),
                                              JOptionPane.WARNING_MESSAGE)
                return

            dataset = self.app.mv.editLayer.data
            areaWKT = self.read_area_from_osm_ways(mode, dataset)
            if areaWKT is None:
                print "I could not read the new favourite area."
            else:
                if mode == "polygon":
                    self.polygonAsString = areaWKT
                else:
                    self.boundaryAsString = areaWKT
        return mode

    def read_area_from_osm_ways(self, mode, dataset):
        """Read way in favourite area editing layer and convert them to
           WKT
        """
        converter = JTSConverter(False)
        lines = [converter.convert(way) for way in dataset.ways]
        polygonizer = Polygonizer()
        polygonizer.add(lines)
        polygons = polygonizer.getPolygons()
        multipolygon = GeometryFactory().createMultiPolygon(list(polygons))
        multipolygonWKT = WKTWriter().write(multipolygon)
        if multipolygonWKT == "MULTIPOLYGON EMPTY":
            if mode == "polygon":
                msg = self.app.strings.getString("empty_ways_polygon_msg")
            else:
                msg = self.app.strings.getString("empty_ways_boundaries_msg")
            JOptionPane.showMessageDialog(self,
                msg,
                self.app.strings.getString("Warning"),
                JOptionPane.WARNING_MESSAGE)
            return
        return multipolygonWKT

    def on_downloadBoundariesBtn_clicked(self, e):
        """Download puter ways of administrative boundaries from
           Overpass API
        """
        adminLevel = self.adminLevelTagTextField.getText()
        name = self.nameTagTextField.getText()
        optional = self.optionalTagTextField.getText()
        if (adminLevel, name, optional) == ("", "", ""):
            JOptionPane.showMessageDialog(self,
                                          self.app.strings.getString("enter_a_tag_msg"),
                                          self.app.strings.getString("Warning"),
                                          JOptionPane.WARNING_MESSAGE)
            return
        optTag = ""
        if optional.find("=") != -1:
            if len(optional.split("=")) == 2:
                key, value = optional.split("=")
                optTag = '["%s"="%s"]' % (URLEncoder.encode(key, "UTF-8"),
                                          URLEncoder.encode(value.replace(" ", "%20"), "UTF-8"))
        self.create_new_zone_editing_layer()
        overpassurl = 'http://127.0.0.1:8111/import?url='
        overpassurl += 'http://overpass-api.de/api/interpreter?data='
        overpassquery = 'relation["admin_level"="%s"]' % adminLevel
        overpassquery += '["name"="%s"]' % URLEncoder.encode(name, "UTF-8")
        overpassquery += '%s;(way(r:"outer");node(w););out meta;' % optTag
        overpassurl += overpassquery.replace(" ", "%20")
        print overpassurl
        self.app.send_to_josm(overpassurl)

### Buttons ############################################################
    def create_new_zone(self, mode):
        """Read data entered on gui and create a new zone
        """
        name = self.nameTextField.getText()
        country = self.countryTextField.getText().upper()

        #error: name
        if name.replace(" ", "") == "":
            JOptionPane.showMessageDialog(self,
                                          self.app.strings.getString("missing_name_warning"),
                                          self.app.strings.getString("missing_name_warning_title"),
                                          JOptionPane.WARNING_MESSAGE)
            return False
        if name in [z.name for z in self.app.tempZones]:
            JOptionPane.showMessageDialog(self,
                                          self.app.strings.getString("duplicate_name_warning"),
                                          self.app.strings.getString("duplicate_name_warning_title"),
                                          JOptionPane.WARNING_MESSAGE)
            return False

        #zone type
        zType = mode
        #error: geometry type not defined
        if zType == "polygon" and self.polygonAsString == ""\
            or zType == "boundary" and self.boundaryAsString == "":
            JOptionPane.showMessageDialog(self,
                                          self.app.strings.getString("zone_not_correctly_build_warning"),
                                          self.app.strings.getString("zone_not_correctly_build_warning_title"),
                                          JOptionPane.WARNING_MESSAGE)
            return False

        #geometry string
        if zType == "rectangle":
            geomString = self.bboxPreviewTextField.getText()
        elif zType == "polygon":
            geomString = self.polygonAsString
        else:
            geomString = self.boundaryAsString

        self.app.newZone = Zone(self.app, name, zType, geomString, country)
        #self.app.newZone.print_info()
        return True

    def on_okBtn_clicked(self, event):
        """Add new zone to temp zones
        """
        mode = self.on_zone_edited()
        if self.create_new_zone(mode):
            self.app.tempZones.append(self.app.newZone)
            self.app.preferencesFrame.zonesTable.getModel().addRow([self.app.newZone.country,
                                                                    self.app.newZone.icon,
                                                                    self.app.newZone.name])
            maxIndex = len(self.app.tempZones) - 1
            self.app.preferencesFrame.zonesTable.setRowSelectionInterval(maxIndex,
                                                                         maxIndex)
            self.close_dialog()
            self.app.preferencesFrame.check_removeBtn_status()
            self.app.preferencesFrame.zonesTable.scrollRectToVisible(
                self.app.preferencesFrame.zonesTable.getCellRect(
                    self.app.preferencesFrame.zonesTable.getRowCount() - 1, 0, True))

    def on_previewBtn_clicked(self, e):
        """Show the favourite area on a map
        """
        mode = self.on_zone_edited()
        if not self.create_new_zone(mode):
            return
        zone = self.app.newZone

        if zone.zType == "rectangle":
            wktString = zone.bbox_to_wkt_string()
        else:
            wktString = zone.wktGeom
        script = '/*http://stackoverflow.com/questions/11954401/wkt-and-openlayers*/'
        script += '\nfunction init() {'
        script += '\n    var map = new OpenLayers.Map({'
        script += '\n        div: "map",'
        script += '\n        projection: new OpenLayers.Projection("EPSG:900913"),'
        script += '\n        displayProjection: new OpenLayers.Projection("EPSG:4326"),'
        script += '\n        layers: ['
        script += '\n            new OpenLayers.Layer.OSM()'
        script += '\n            ]'
        script += '\n    });'
        script += '\n    var wkt = new OpenLayers.Format.WKT();'
        script += '\n    var polygonFeature = wkt.read("%s");' % wktString
        script += '\n    var vectors = new OpenLayers.Layer.Vector("Favourite area");'
        script += '\n    map.addLayer(vectors);'
        script += '\n    polygonFeature.geometry.transform(map.displayProjection, map.getProjectionObject());'
        script += '\n    vectors.addFeatures([polygonFeature]);'
        script += '\n    map.zoomToExtent(vectors.getDataExtent());'
        script += '\n};'
        scriptFile = open(File.separator.join([self.app.SCRIPTDIR,
                                              "html",
                                              "script.js"]), "w")
        scriptFile.write(script)
        scriptFile.close()
        OpenBrowser.displayUrl(File.separator.join([self.app.SCRIPTDIR,
                                                   "html",
                                                   "favourite_area.html"]))

    def windowClosing(self, windowEvent):
        self.close_dialog()

    def close_dialog(self, e=None):
        #delete favourite zone editing layer if present
        self.remove_new_zone_editing_layer()
        self.dispose()
        self.app.preferencesFrame.toFront()
예제 #12
0
        run_file = filepath + "/" + old_filename + "_run" + filetype
    else:
        stripped_filename = strip_end(old_filename,"_icons")
        stripped_filename = strip_end(stripped_filename,"_run")
        start_file = filepath + "/" + stripped_filename + filetype
        icons_file = filepath + "/" + stripped_filename + "_icons" + filetype
        run_file = filepath + "/" + stripped_filename + "_run" + filetype
    label_panel_location.text = start_file
    #row13b2.text = icons_file
    row11b2.text = run_file
    #os.rename(r'filepath/old_filename.file type',r'file path/NEW file name.file type')

row0 = JPanel()
row0.setLayout(BoxLayout(row0, BoxLayout.X_AXIS))
txt = JTextField(140)
txt.setMaximumSize( txt.getPreferredSize() );
txt.setBorder(BorderFactory.createCompoundBorder(
                   BorderFactory.createLineBorder(Color.red),
                   txt.getBorder()));
label_panel_location = JLabel()
btnpanelLocation = JButton("Set Panel Location", actionPerformed = btnpanelLocation_action)
row0.add(Box.createVerticalGlue())
row0.add(Box.createRigidArea(Dimension(20, 0)))
row0.add(btnpanelLocation)
row0.add(Box.createRigidArea(Dimension(20, 0)))
row0.add(label_panel_location)
row0.add(Box.createRigidArea(Dimension(20, 0)))

row12 = JPanel()
row12.setLayout(BoxLayout(row12, BoxLayout.X_AXIS))
row12b1 = JLabel("Dispatcher System: Modifies panels to produce a running system")
예제 #13
0
class BurpExtender(IBurpExtender, IContextMenuFactory, IHttpListener,
                   ISessionHandlingAction, ITab):
    def registerExtenderCallbacks(self, callbacks):
        self._callbacks = callbacks
        self._helpers = callbacks.getHelpers()
        callbacks.setExtensionName("JC-AntiToken")
        callbacks.registerContextMenuFactory(self)
        # callbacks.registerHttpListener(self)
        callbacks.registerSessionHandlingAction(self)
        self.drawUI()

    def printcn(self, msg):
        print(msg.decode('utf-8').encode(sys_encoding))

    def drawUI(self):
        # 最外层:垂直盒子,内放一个水平盒子+一个胶水
        out_vBox_main = Box.createVerticalBox()
        # 次外层:水平盒子,使用说明
        usage = u'''
                             JC-AntiToken(简单防重放绕过)
        适用场景:防重放的方式为,提前向一个页面发送请求取得token,替换到下一个页面中。
        适用说明:
            1. 请求头中Headers和Data的值必须是JSON字符串,如:{"var":"value"}
            2. 左边tokenRegex的格式为:
                a. .*开头,.*结尾,用()括住要取出的token
                b. 如:.*,"token":"(.*?)".*
            3. 右边tokenRegex的格式为:
                a. 需要三个(),第二个()括住要替换的token
                b. 如:(.*,"token":")(.*?)(".*)
        详见:https://github.com/chroblert/JC-AntiToken
        '''
        hBox_usage = Box.createHorizontalBox()
        jpanel_test = JPanel()
        jTextarea_usage = JTextArea()
        jTextarea_usage.setText(usage)
        jTextarea_usage.setRows(13)
        jTextarea_usage.setEditable(False)
        # jpanel_test.add(jTextarea_usage)
        hBox_usage.add(JScrollPane(jTextarea_usage))

        # 次外层:水平盒子,内放两个垂直盒子
        hBox_main = Box.createHorizontalBox()
        # 左垂直盒子
        vBox_left = Box.createVerticalBox()
        # 右垂直盒子
        vBox_right = Box.createVerticalBox()

        # 左垂直盒子内部:发送请求包拿token
        # URL标签
        jlabel_url = JLabel("       URL: ")
        self.jtext_url = JTextField(generWidth)
        self.jtext_url.setMaximumSize(self.jtext_url.getPreferredSize())
        hbox_url = Box.createHorizontalBox()
        hbox_url.add(jlabel_url)
        hbox_url.add(self.jtext_url)
        hglue_url = Box.createHorizontalGlue()
        hbox_url.add(hglue_url)
        # 请求方法标签
        jlabel_reqMeth = JLabel("ReqMeth: ")
        self.jcombobox_reqMeth = JComboBox()
        self.jcombobox_reqMeth.addItem("GET")
        self.jcombobox_reqMeth.addItem("POST")
        hbox_reqMeth = Box.createHorizontalBox()
        hbox_reqMeth.add(jlabel_reqMeth)
        hbox_reqMeth.add(self.jcombobox_reqMeth)
        self.jcombobox_reqMeth.setMaximumSize(
            self.jcombobox_reqMeth.getPreferredSize())
        hglue_reqMeth = Box.createHorizontalGlue()
        hbox_reqMeth.add(hglue_reqMeth)
        # ContentType标签
        jlabel_contentType = JLabel("ConType: ")
        self.jcombobox_contentType = JComboBox()
        self.jcombobox_contentType.addItem("application/json")
        self.jcombobox_contentType.addItem("application/x-www-form-urlencoded")
        hbox_contentType = Box.createHorizontalBox()
        hbox_contentType.add(jlabel_contentType)
        hbox_contentType.add(self.jcombobox_contentType)
        self.jcombobox_contentType.setMaximumSize(
            self.jcombobox_contentType.getPreferredSize())
        hglue_contentType = Box.createHorizontalGlue()
        hbox_contentType.add(hglue_contentType)
        # Charset标签
        jlabel_charset = JLabel("CharSet: ")
        self.jcombobox_charset = JComboBox()
        self.jcombobox_charset.addItem("UTF-8")
        self.jcombobox_charset.addItem("GBK")
        hbox_charset = Box.createHorizontalBox()
        hbox_charset.add(jlabel_charset)
        hbox_charset.add(self.jcombobox_charset)
        self.jcombobox_charset.setMaximumSize(
            self.jcombobox_charset.getPreferredSize())
        hglue_charset = Box.createHorizontalGlue()
        hbox_charset.add(hglue_charset)
        # 请求头标签
        jlabel_headers = JLabel("Headers: ")
        self.jtext_headers = JTextField(generWidth)
        self.jtext_headers.setMaximumSize(
            self.jtext_headers.getPreferredSize())
        hbox_headers = Box.createHorizontalBox()
        hbox_headers.add(jlabel_headers)
        hbox_headers.add(self.jtext_headers)
        hglue_headers = Box.createHorizontalGlue()
        hbox_headers.add(hglue_headers)
        # 请求参数标签
        jlabel_data = JLabel("     Data: ")
        self.jtext_data = JTextField(generWidth)
        self.jtext_data.setPreferredSize(Dimension(20, 40))
        self.jtext_data.setMaximumSize(self.jtext_data.getPreferredSize())
        hbox_data = Box.createHorizontalBox()
        hbox_data.add(jlabel_data)
        hbox_data.add(self.jtext_data)
        hglue_data = Box.createHorizontalGlue()
        hbox_data.add(hglue_data)
        # token标志位置标签
        hbox_radiobtn = Box.createHorizontalBox()
        jlabel_tokenPosition = JLabel("Token Position: ")
        self.radioBtn01 = JRadioButton("Header")
        self.radioBtn02 = JRadioButton("Body")
        btnGroup = ButtonGroup()
        btnGroup.add(self.radioBtn01)
        btnGroup.add(self.radioBtn02)
        self.radioBtn01.setSelected(True)
        hbox_radiobtn.add(jlabel_tokenPosition)
        hbox_radiobtn.add(self.radioBtn01)
        hbox_radiobtn.add(self.radioBtn02)
        # token正则表达式标签
        hbox_token = Box.createHorizontalBox()
        hbox_token_header = Box.createHorizontalBox()
        hbox_token_body = Box.createHorizontalBox()
        # token正则表达式标签:header中
        jlabel_tokenName = JLabel("tokenName: ")
        self.jtext_tokenName = JTextField(tokenWidth)
        self.jtext_tokenName.setMaximumSize(
            self.jtext_tokenName.getPreferredSize())
        hbox_token_header.add(jlabel_tokenName)
        hbox_token_header.add(self.jtext_tokenName)
        hglue_token_header = Box.createHorizontalGlue()
        hbox_token_header.add(hglue_token_header)
        # token正则表达式标签:body中
        jlabel_tokenRegex = JLabel("tokenRegex: ")
        self.jtext_tokenRegex = JTextField(tokenWidth)
        self.jtext_tokenRegex.setMaximumSize(
            self.jtext_tokenRegex.getPreferredSize())
        hbox_token_body.add(jlabel_tokenRegex)
        hbox_token_body.add(self.jtext_tokenRegex)
        hglue_token_body = Box.createHorizontalGlue()
        hbox_token_body.add(hglue_token_body)
        # token正则表达式标签
        hbox_token.add(hbox_token_header)
        hbox_token.add(hbox_token_body)
        # test测试按钮
        hbox_test = Box.createHorizontalBox()
        jbtn_test = JButton("TEST", actionPerformed=self.btnTest)
        self.jlabel_test = JLabel("Result: ")
        hbox_test.add(jbtn_test)
        hbox_test.add(self.jlabel_test)
        # 水平胶水填充
        hGlue_test = Box.createHorizontalGlue()
        hbox_test.add(hGlue_test)
        hbox_test.setBorder(BorderFactory.createLineBorder(Color.green, 2))
        # 响应数据输出
        hbox_resp = Box.createHorizontalBox()
        self.jtextarea_resp = JTextArea()
        jsp = JScrollPane(self.jtextarea_resp)
        hbox_resp.add(self.jtextarea_resp)
        # 左垂直盒子:添加各种水平盒子
        vBox_left.add(hbox_url)
        vBox_left.add(hbox_reqMeth)
        vBox_left.add(hbox_contentType)
        vBox_left.add(hbox_charset)
        vBox_left.add(hbox_headers)
        vBox_left.add(hbox_data)
        vBox_left.add(hbox_radiobtn)
        vBox_left.add(hbox_token)
        vBox_left.add(hbox_test)
        vBox_left.add(hbox_resp)
        # 左垂直盒子:垂直胶水填充
        vGlue_test = Box.createGlue()
        vBox_left.add(vGlue_test)

        # 右垂直盒子内部:指定token在请求包中的位置
        # token标志位置单选按钮
        hbox_radiobtn_r = Box.createHorizontalBox()
        jlabel_tokenPosition_r = JLabel("Token Position: ")
        self.radioBtn01_r = JRadioButton("Header")
        self.radioBtn02_r = JRadioButton("Body")
        btnGroup_r = ButtonGroup()
        btnGroup_r.add(self.radioBtn01_r)
        btnGroup_r.add(self.radioBtn02_r)
        self.radioBtn01_r.setSelected(True)
        hbox_radiobtn_r.add(jlabel_tokenPosition_r)
        hbox_radiobtn_r.add(self.radioBtn01_r)
        hbox_radiobtn_r.add(self.radioBtn02_r)

        # token正则表达式
        hbox_token_r = Box.createHorizontalBox()
        hbox_token_header_r = Box.createHorizontalBox()
        hbox_token_body_r = Box.createHorizontalBox()
        # token正则表达式:在header中
        jlabel_tokenName_r = JLabel("tokenName: ")
        self.jtext_tokenName_r = JTextField(tokenWidth)
        self.jtext_tokenName_r.setMaximumSize(
            self.jtext_tokenName_r.getPreferredSize())
        hbox_token_header_r.add(jlabel_tokenName_r)
        hbox_token_header_r.add(self.jtext_tokenName_r)
        hglue_token_header_r = Box.createHorizontalGlue()
        hbox_token_header_r.add(hglue_token_header_r)
        # token正则表达式:在Body中
        jlabel_tokenRegex_r = JLabel("tokenRegex: ")
        self.jtext_tokenRegex_r = JTextField(tokenWidth)
        self.jtext_tokenRegex_r.setMaximumSize(
            self.jtext_tokenRegex_r.getPreferredSize())
        hbox_token_body_r.add(jlabel_tokenRegex_r)
        hbox_token_body_r.add(self.jtext_tokenRegex_r)
        hglue_token_body_r = Box.createHorizontalGlue()
        hbox_token_body_r.add(hglue_token_body_r)
        # token正则表达式
        hbox_token_r.add(hbox_token_header_r)
        hbox_token_r.add(hbox_token_body_r)
        # 测试按钮
        hbox_test_r = Box.createHorizontalBox()
        jbtn_test_r = JButton("SET", actionPerformed=self.btnTest_r)
        self.jlabel_test_r = JLabel("Result: ")
        hbox_test_r.add(jbtn_test_r)
        hbox_test_r.add(self.jlabel_test_r)
        # 水平胶水填充
        hGlue02 = Box.createHorizontalGlue()
        hbox_test_r.add(hGlue02)
        hbox_test_r.setBorder(BorderFactory.createLineBorder(Color.green, 2))

        # 右垂直盒子:添加各种水平盒子
        vBox_right.add(hbox_radiobtn_r)
        vBox_right.add(hbox_token_r)
        vBox_right.add(hbox_test_r)
        vGlue = Box.createVerticalGlue()
        vBox_right.add(vGlue)

        vBox_left.setBorder(BorderFactory.createLineBorder(Color.black, 3))
        vBox_right.setBorder(BorderFactory.createLineBorder(Color.black, 3))

        # 次外层水平盒子:添加左右两个垂直盒子
        hBox_main.add(vBox_left)
        hBox_main.add(vBox_right)
        # 最外层垂直盒子:添加次外层水平盒子,垂直胶水
        out_vBox_main.add(hBox_usage)
        out_vBox_main.add(hBox_main)

        self.mainPanel = out_vBox_main
        self._callbacks.customizeUiComponent(self.mainPanel)
        self._callbacks.addSuiteTab(self)

    def getTabCaption(self):
        return "JC-AntiToken"

    def getUiComponent(self):
        return self.mainPanel

    def testBtn_onClick(self, event):
        print("click button")

    def createMenuItems(self, invocation):
        menu = []
        if invocation.getToolFlag() == IBurpExtenderCallbacks.TOOL_REPEATER:
            menu.append(
                JMenuItem("Test menu", None, actionPerformed=self.testmenu))
        return menu

    def testmenu(self, event):
        print(event)
        print("JCTest test menu")

    def processHttpMessage(self, toolflag, messageIsRequest, messageInfo):
        service = messageInfo.getHttpService()
        if messageIsRequest:
            pass
            print("Host: " + str(service.getHost()))
            print("Port: " + str(service.getPort()))
            print("Protocol: " + str(service.getProtocol()))
            print("-----------------------------------")

    def getActionName(self):
        return "JC-AntiToken"

    def performAction(self, currentRequest, macroItems):
        # url
        url = self._helpers.analyzeRequest(currentRequest).getUrl()
        print(url)
        reqInfo = self._helpers.analyzeRequest(currentRequest)
        # request headers
        headers = reqInfo.getHeaders()
        print("ReqHeaders: " + headers)
        # get cookie from request header
        cookie = self.getCookieFromReq(headers)
        print(cookie)
        print(type(cookie))
        # offset to req body
        reqBodyOffset = reqInfo.getBodyOffset()
        reqBody = str(bytearray(currentRequest.getRequest()[reqBodyOffset:]))
        print("ReqBody: " + reqBody)
        # modify Request Body
        newToken = self.getNewToken(cookie)
        if newToken != None:
            # tokenInReqHeader
            res = False
            if self.tokenInHeader_r:
                # pass
                # 普通header中
                for header in headers:
                    if ":" in header:
                        if header.split(":")[0] == self.tokenName_r:
                            headers = [
                                self.tokenName_r + ": " + newToken
                                if i.split(":")[0] == self.tokenName_r else i
                                for i in headers
                            ]
                            res = True
                            break
                # cookie中
                if not res and cookie != None and self.tokenName_r + "=" in cookie:
                    # pass
                    for i in range(len(headers)):
                        if headers[i].startwith("Cookie:"):
                            cookies2 = headers[i]
                            cookies3 = cookies2.split(":")[1]
                            if ";" not in cookies3:
                                headers[
                                    i] = "Cookie: " + self.tokenName_r + "=" + newToken
                                res = True
                                break
                            else:
                                cookies4 = cookies3.split(";")
                                for cookie_idx in range(len(cookies4)):
                                    if self.tokenName_r + "+" in cookies4[
                                            cookie_idx]:
                                        cookies4[
                                            cookie_idx] = self.tokenName_r + "=" + newToken
                                        res = True
                                        break
                                headers[i] = "Cookie: " + ";".join(cookies4)
                                break
                # query string中
                if not res:
                    meth = headers[0].split(" ")[0]
                    url = headers[0].split(" ")[1]
                    ver = headers[0].split(" ")[2]
                    if self.tokenName_r + "=" not in url:
                        pass
                    else:
                        if "&" not in url:
                            url = url.split("?")[
                                0] + "?" + self.tokenName_r + "=" + newToken
                            headers[0] = meth + " " + url + " " + ver
                        else:
                            params = url.split("?")[1].split("&")
                            for i in range(len(params)):
                                if self.tokenName_r + "=" in params[i]:
                                    params[
                                        i] = self.tokenName_r + "=" + newToken
                                    break
                            url = url.split("?")[0] + "?" + "&".join(params)
                            headers[0] = meth + " " + url + " " + ver
            # tokenInReqBody
            else:
                if re.match(self.tokenRegex_r, reqBody):
                    try:
                        reqBody = re.sub(self.tokenRegex_r,
                                         r'\g<1>' + newToken + r'\g<3>',
                                         reqBody, 0, re.M | re.I)
                    except Exception as e:
                        print(e)
                        # print(reqBody)
                        # reqBody = re.sub(self.tokenRegex_r,r'\g<1>'+newToken+r'\g<3>',reqBody,0,re.M|re.I)

            # if re.match(r'(.*?"_tokenName":")([a-zA-Z0-9]{6,})(")',reqBody):
            #     reqBody = re.sub(r'(.*?"_tokenName":")([a-zA-Z0-9]{6,})(")',r'\1'+newToken+r'\3',reqBody,0,re.M|re.I)
        # rebuild request
        reqMessage = self._helpers.buildHttpMessage(headers, bytes(reqBody))
        # forward
        currentRequest.setRequest(reqMessage)
        print("++++++++++++++++++++++++")

    def getCookieFromReq(self, headers):
        for header in headers:
            if re.match(r'^Cookie:', header, re.I):
                return re.match(r'^Cookie: (.*)', header, re.I).group(1)

    # get new token
    def getNewToken(self, cookie):
        print(cookie)
        print("getNewToken")
        # url = "http://myip.ipip.net"
        headers_cookie = {
            'Cookie': cookie,
        }
        if cookie != '':
            self.headers.update(**headers_cookie)
        if self.reqMeth == "GET":
            resp = self.sendGetHttp(self.url, self.headers, self.data,
                                    self.contentType)
        else:
            resp = self.sendPostHttp(self.url, self.headers, self.data,
                                     self.contentType)
        respBody = resp.read()
        respInfo = resp.info()
        if self.tokenInHeader:
            if respInfo.getheader(self.tokenName) != None:
                newToken = respInfo.getheader(self.tokenName)
                print(newToken)
                return newToken
            else:
                regexPattern = '.*' + self.tokenName + '=(.*?);'
                if respInfo.getheader("set-cookie") != None:
                    cookies = respInfo.getheader("set-cookie")
                    if re.match(regexPattern, cookies, re.M | re.I):
                        newToken = re.match(regexPattern, cookies,
                                            re.M | re.I).group(1)
                        print("newToken: ", newToken)
                        return newToken
                    else:
                        return None
                else:
                    return None
        else:
            regexPattern = self.tokenRegex
            if re.match(regexPattern, respBody, re.M | re.I):
                newToken = re.match(regexPattern, respBody,
                                    re.M | re.I).group(1)
                print("newToken: ", newToken)
                return newToken
            else:
                return None

    def sendGetHttp(self, url, headers, data, contentType):
        context = ssl._create_unverified_context()
        headers_contentType = {'Content-Type': contentType}
        if not headers.has_key("Content-Type"):
            headers.update(**headers_contentType)
        headers_userAgent = {
            'User-Agent':
            'Mozilla/6.0 (iPhone; CPU iPhone OS 8_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/8.0 Mobile/10A5376e Safari/8536.25'
        }
        if not headers.has_key("User-Agent"):
            headers.update(**headers_userAgent)
        try:
            if data != None:
                # if "urlencode" in contentType:
                data = urllib.urlencode(data)
                url = url + "?" + data
                req = urllib2.Request(url, headers=headers)
            else:
                req = urllib2.Request(url, headers=headers)
            resp = urllib2.urlopen(req, context=context)
            return resp
        except urllib2.HTTPError as error:
            print("ERROR: ", error)
            return None

    def sendPostHttp(self, url, headers, data, contentType):
        context = ssl._create_unverified_context()
        headers_contentType = {'Content-Type': contentType}
        if not headers.has_key("Content-Type"):
            headers.update(**headers_contentType)
        headers_userAgent = {
            'User-Agent':
            'Mozilla/6.0 (iPhone; CPU iPhone OS 8_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/8.0 Mobile/10A5376e Safari/8536.25'
        }
        if not headers.has_key("User-Agent"):
            headers.update(**headers_userAgent)
        print(headers)
        resp = ""
        print("data: ", data)
        if data != None:
            if "urlencode" in contentType:
                data = urllib.urlencode(data)
                req = urllib2.Request(url, headers=headers, data=data)
            else:
                data = json.dumps(data)
                req = urllib2.Request(url, headers=headers, data=data)
        else:
            if "urlencode" in contentType:
                req = urllib2.Request(url, headers=headers)
            else:
                data = json.dumps(data)
                req = urllib2.Request(url, headers=headers)
        try:
            resp = urllib2.urlopen(req, context=context)
            return resp
        except urllib2.HTTPError as error:
            print("ERROR: ", error)
            return None

    def btnTest(self, e):
        self.printcn("中文测试")
        self.url = self.jtext_url.getText()
        if self.url == "":
            self.jlabel_test.setText("please input url")
            return
        self.reqMeth = self.jcombobox_reqMeth.getSelectedItem()
        # 用户设置content-type
        self.contentType = self.jcombobox_contentType.getSelectedItem(
        ) + ";charset=" + self.jcombobox_charset.getSelectedItem()
        # 用户有没有自定义请求头
        if self.jtext_headers.getText() != "":
            self.headers = json.loads(self.jtext_headers.getText())
        else:
            self.headers = {}
        # 用户有没有自定义请求体
        if self.jtext_data.getText() != "":
            self.data = json.loads(self.jtext_data.getText())
        else:
            self.data = None
        self.tokenName = self.jtext_tokenName.getText()
        self.tokenRegex = self.jtext_tokenRegex.getText()
        resp = ''
        if self.reqMeth == "GET":
            resp = self.sendGetHttp(self.url, self.headers, self.data,
                                    self.contentType)
        else:
            resp = self.sendPostHttp(self.url, self.headers, self.data,
                                     self.contentType)
        if resp == None:
            self.jlabel_test.setText("error,detail in extender output")
            return
        respHeader = resp.info().headers
        print("resp-headers: ", respHeader)
        # print(resp.info().getheader("content-type"))
        self.printcn(resp.info().getheader("set-cookie"))
        # print(resp.info().getheader("xxx"))
        respBody = resp.read()
        print("respBody: ", respBody)
        self.jtextarea_resp.setText("".join(respHeader) + "\n" +
                                    "".join(respBody))
        if (self.radioBtn01.isSelected()):
            self.tokenInHeader = True
            if self.tokenName == "":
                self.jlabel_test.setText("please input tokenName")
                return
        else:
            self.tokenInHeader = False
            if self.tokenRegex == "":
                self.jlabel_test.setText("please input tokenRegex")
                return
        print(self.reqMeth)
        newToken = self.getNewToken("")
        if newToken != None:
            self.jlabel_test.setText("Result: " + str(newToken))
            self.jlabel_test.setBackground(Color.cyan)
        else:
            self.jlabel_test.setText("Result: None")

    def btnTest_r(self, e):
        self.tokenName_r = self.jtext_tokenName_r.getText()
        self.tokenRegex_r = self.jtext_tokenRegex_r.getText()
        if (self.radioBtn01_r.isSelected()):
            self.tokenInHeader_r = True
            if self.tokenName_r == "":
                self.jlabel_test_r.setText("please input tokenName")
                return
        else:
            self.tokenInHeader_r = False
            if self.tokenRegex_r == "":
                self.jlabel_test_r.setText("please input tokenRegex")
                return
        self.jlabel_test_r.setText("SUCCESS")
예제 #14
0
class Process_EVTX1WithUISettingsPanel(IngestModuleIngestJobSettingsPanel):
    # Note, we can't use a self.settings instance variable.
    # Rather, self.local_settings is used.
    # https://wiki.python.org/jython/UserGuide#javabean-properties
    # Jython Introspector generates a property - 'settings' on the basis
    # of getSettings() defined in this class. Since only getter function
    # is present, it creates a read-only 'settings' property. This auto-
    # generated read-only property overshadows the instance-variable -
    # 'settings'

    # We get passed in a previous version of the settings so that we can
    # prepopulate the UI
    # TODO: Update this for your UI
    def __init__(self, settings):
        self.local_settings = settings
        self.initComponents()
        self.customizeComponents()

    # TODO: Update this for your UI
    def checkBoxEvent(self, event):
        if self.checkbox.isSelected():
            self.local_settings.setSetting('All', 'true')
        else:
            self.local_settings.setSetting('All', 'false')
        if self.checkbox1.isSelected():
            self.local_settings.setSetting('Application', 'true')
        else:
            self.local_settings.setSetting('Application', 'false')
        if self.checkbox2.isSelected():
            self.local_settings.setSetting('Security', 'true')
        else:
            self.local_settings.setSetting('Security', 'false')
        if self.checkbox3.isSelected():
            self.local_settings.setSetting('System', 'true')
        else:
            self.local_settings.setSetting('System', 'false')
        if self.checkbox4.isSelected():
            self.local_settings.setSetting('Other', 'true')
            self.area.setEnabled(True)
        else:
            self.local_settings.setSetting('Other', 'false')
            self.area.setEnabled(False)
        if self.filterCheckbox.isSelected():
            self.local_settings.setSetting('Filter', 'true')
            self.filterField.setEnabled(True)
            self.filterSelector.setEnabled(True)
            self.filterInput.setEnabled(True)
        else:
            self.local_settings.setSetting('Filter', 'false')
            self.filterField.setEnabled(False)
            self.filterSelector.setEnabled(False)
            self.filterInput.setEnabled(False)
        if self.sortCheckbox.isSelected():
            self.local_settings.setSetting('SortDesc', 'true')
        else:
            self.local_settings.setSetting('SortDesc', 'false')

    def keyPressed(self, event):
        self.local_settings.setSetting('EventLogs', self.area.getText())

    # TODO: Update this for your UI
    def initComponents(self):
        self.setLayout(BoxLayout(self, BoxLayout.Y_AXIS))
        self.setAlignmentX(JComponent.LEFT_ALIGNMENT)

        self.checkbox = JCheckBox("All Logs",
                                  actionPerformed=self.checkBoxEvent)
        self.checkbox1 = JCheckBox("Application.Evtx",
                                   actionPerformed=self.checkBoxEvent)
        self.checkbox2 = JCheckBox("Security.EVTX",
                                   actionPerformed=self.checkBoxEvent)
        self.checkbox3 = JCheckBox("System.EVTX",
                                   actionPerformed=self.checkBoxEvent)
        self.checkbox4 = JCheckBox(
            "Other - Input in text area below then check this box",
            actionPerformed=self.checkBoxEvent)

        # Scrollable text area for additional log names
        self.area = JTextArea(3, 10)
        self.area.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0))
        self.area.setEnabled(False)
        self.pane = JScrollPane()
        self.pane.getViewport().add(self.area)

        self.add(self.checkbox)
        self.add(self.checkbox1)
        self.add(self.checkbox2)
        self.add(self.checkbox3)
        self.add(self.checkbox4)
        self.add(self.pane)

        self.add(JSeparator())
        self.add(JSeparator())

        self.filterCheckbox = JCheckBox("Filter",
                                        actionPerformed=self.checkBoxEvent)
        self.filterCheckbox.setLayout(
            BoxLayout(self.filterCheckbox, BoxLayout.X_AXIS))
        self.add(self.filterCheckbox)

        self.filterPanel = JPanel()
        self.filterPanel.setLayout(
            BoxLayout(self.filterPanel, BoxLayout.X_AXIS))
        self.filterField = JComboBox([
            "Computer Name", "Event Identifier", "Event Level", "Source Name",
            "Event Detail"
        ])
        self.filterField.setEnabled(False)
        self.filterField.setMaximumSize(self.filterField.getPreferredSize())
        self.filterSelector = JComboBox(
            ["equals", "not equals", "contains", "starts with", "ends with"])
        self.filterSelector.setEnabled(False)
        self.filterSelector.setMaximumSize(
            self.filterSelector.getPreferredSize())
        self.filterInput = JTextField()
        self.filterInput.setEnabled(False)
        self.filterInput.setMaximumSize(
            Dimension(512,
                      self.filterInput.getPreferredSize().height))
        self.filterPanel.add(self.filterField)
        self.filterPanel.add(self.filterSelector)
        self.filterPanel.add(self.filterInput)

        self.add(self.filterPanel)

        self.sortCheckbox = JCheckBox("Sort Event Counts Descending",
                                      actionPerformed=self.checkBoxEvent)
        self.add(self.sortCheckbox)

    # TODO: Update this for your UI
    def customizeComponents(self):
        self.checkbox.setSelected(
            self.local_settings.getSetting('All') == 'true')
        self.checkbox1.setSelected(
            self.local_settings.getSetting('Application') == 'true')
        self.checkbox2.setSelected(
            self.local_settings.getSetting('Security') == 'true')
        self.checkbox3.setSelected(
            self.local_settings.getSetting('System') == 'true')
        self.checkbox4.setSelected(
            self.local_settings.getSetting('Other') == 'true')
        self.area.setText(self.local_settings.getSetting('EventLogs'))

    # Return the settings used
    def getSettings(self):
        self.local_settings.setSetting('EventLogs', self.area.getText())
        self.local_settings.setSetting('FilterField',
                                       self.filterField.getSelectedItem())
        self.local_settings.setSetting('FilterMode',
                                       self.filterSelector.getSelectedItem())
        self.local_settings.setSetting('FilterInput',
                                       self.filterInput.getText())
        return self.local_settings