예제 #1
0
class ActionsPanel(JPanel):

    def __init__(self, extender):
        # Initialize self
        super(ActionsPanel, self).__init__()
        self.extender = extender
        self.setLayout(GridLayout(2, 1))
        # Create children
        self.title = JLabel('Actions')
        self.actions = JPanel(GridLayout(1, 3))
        self.start = JButton('Start')
        self.info = JButton('Info')
        # Configure children
        self.title.setFont(Fonts.Heading)
        self.title.setForeground(Colors.Orange)
        self.actions.layout.vgap = 0
        self.actions.layout.hgap = 0
        self.start.addActionListener(StartActionListener(extender))
        self.info.addActionListener(InfoActionListener(extender))
        # Add children
        self.add(self.title)
        self.add(self.actions)
        self.actions.add(self.start)
        self.actions.add(self.info)

    def refresh(self):
        pass

    def registerExtenderCallbacks(self, callbacks):
        pass
예제 #2
0
class ColorChooserDemo(java.lang.Runnable):

    #---------------------------------------------------------------------------
    # Name: run()
    # Role: Instantiate the user class
    # Note: Invoked by the Swing Event Dispatch Thread
    #---------------------------------------------------------------------------
    def run(self):
        self.frame = frame = JFrame('ColorChooserDemo',
                                    size=(200, 100),
                                    locationRelativeTo=None,
                                    defaultCloseOperation=JFrame.EXIT_ON_CLOSE)
        frame.add(JButton('Select a Color', actionPerformed=self.showCC))
        self.label = JLabel('', JLabel.CENTER)
        frame.add(self.label, BorderLayout.SOUTH)
        frame.setVisible(1)

    #---------------------------------------------------------------------------
    # Name: showCC()
    # Role: Demonstrate use of JColorChooser
    #---------------------------------------------------------------------------
    def showCC(self, event):
        result = JColorChooser().showDialog(
            None,  # Parent component
            'Color Selection',  # Dialog title
            self.label.getForeground()  # Initial color
        )
        if result:
            message = 'New color: "%s"' % result.toString()
            self.label.setForeground(result)
        else:
            message = 'Request canceled by user'
        self.label.setText(message)
예제 #3
0
class TitlePanel(JPanel):

    def __init__(self, extender):
        # Initialize self
        super(TitlePanel, self).__init__()
        self.extender = extender
        self.setLayout(GridLayout(2, 1))
        # Create children
        self.title = JLabel('Tracer')
        self.subtitle = JPanel()
        self.label = JLabel('Allows you to trace where inputs are reflected back to the user. Click "Start" to analyze the current site map.')
        # Configure children
        self.title.setFont(Fonts.Heading)
        self.title.setForeground(Colors.Orange)
        self.subtitle.layout.hgap = 0
        # Add children
        self.add(self.title)
        self.add(self.subtitle)
        self.subtitle.add(self.label)

    def refresh(self):
        pass

    def registerExtenderCallbacks(self, callbacks):
        pass
예제 #4
0
    def __init__(self, program):
        self.setLayout(BorderLayout())
        title = JLabel(program.title)
        title.setFont(Font("Arial", Font.BOLD, 28))
        title.setHorizontalAlignment(JLabel.CENTER)
        title.setVerticalAlignment(JLabel.CENTER)
        title.setBorder(createEmptyBorder(15, 5, 15, 5))

        if not program.public:
            lbl = JLabel("Private")
            lbl.setFont(Font("Arial", Font.BOLD, 20))
            lbl.setForeground(Color(0xFF2424))
            lbl.setBorder(createEmptyBorder(15, 15, 15, 15))
            leftbox = lbl
        else:
            leftbox = Box.createHorizontalGlue()
        btnbox = TitleBtnBox(program)
        btnbox.setBorder(createEmptyBorder(5, 5, 5, 5))
        self.add(leftbox, BorderLayout.LINE_START)
        self.add(title, BorderLayout.CENTER)
        self.add(btnbox, BorderLayout.LINE_END)

        same_size(leftbox, btnbox)

        self.setMaximumSize(Dimension(99999, self.getPreferredSize().height))
예제 #5
0
class TopPanel(JPanel):
    def __init__(self):

        self.login = JLabel('')
        self.setLayout(BorderLayout())
        self.refresh()

    def refresh(self):
        admin = client.get_current_admin()
        self.login.setText('          Login : '******'#ffffff'))
        self.add(self.login, BorderLayout.LINE_START)
        self.validate()
예제 #6
0
    def initPanel(self):
        IntegerPanel.initPanel(self)

        num_avail_devices = NEFGPUInterface.getNumAvailableDevices()

        if num_avail_devices < 1:
            self.tf.setEnabled(False)
            self.tf.setEditable(False)

            error_message = " %s" % (NEFGPUInterface.getErrorMessage())
            error_message_label = JLabel(error_message)
            error_message_label.setForeground(Color.red)
            self.add(error_message_label)
예제 #7
0
    def initPanel(self):
        BooleanPanel.initPanel(self)

        can_use_GPU = WeightedCostApproximator.canUseGPU()

        if not can_use_GPU:
            self.checkBox.setEnabled(False)
            self.label.setEnabled(False)

            error_message = " %s" % (
                WeightedCostApproximator.getGPUErrorMessage())
            error_message_label = JLabel(error_message)
            error_message_label.setForeground(Color.red)
            self.add(error_message_label)
예제 #8
0
    def initComponents(self):
        skCase = Case.getCurrentCase().getSleuthkitCase()
        att_contact_id = skCase.getAttributeType("YPA_CONTACT_ID")
        att_address = skCase.getAttributeType("YPA_ADDRESS")
        att_display_name = skCase.getAttributeType("YPA_DISPLAY_NAME")
        att_address_type = skCase.getAttributeType("YPA_ADDRESS_TYPE")
        att_times_contacted = skCase.getAttributeType("YPA_TIMES_CONTACTED")
        att_last_contacted = skCase.getAttributeType("YPA_LAST_CONTACT_TIME")
        att_last_updated = skCase.getAttributeType("YPA_LAST_UPDATE_TIME")

        self.att_type_list = [att_contact_id, att_address, att_display_name, att_address_type, att_times_contacted, att_last_updated, att_last_contacted]
        
        orderOptions = []
        for att in self.att_type_list:
            orderOptions.append(att.getDisplayName())
        self.setLayout(FlowLayout())

        descriptionLabel = JLabel(" YPA - Your Phone Analyzer (Report module)")
        self.add(descriptionLabel)

        orderLabel = JLabel("Address book order: ")
        self.add(orderLabel)

        self.orderComboBox = JComboBox(orderOptions)
        self.add(self.orderComboBox)

        pnl = JPanel()
        pnl.add(self.orderComboBox)
        self.add(pnl)


        art_count = len(skCase.getMatchingArtifacts("JOIN blackboard_artifact_types AS types ON blackboard_artifacts.artifact_type_id = types.artifact_type_id WHERE types.type_name LIKE 'YPA_%'"))
        if art_count == 0:
            warningLabel = JLabel(" WARNING: Please run the ingest module before this report module.")
            warningLabel.setForeground(Color.RED)
            self.add(warningLabel)
예제 #9
0
    class PositionsController(IMessageEditorController):
        def __init__(self, parent):
            self._parent = parent

        def getMainComponent(self):
            self._mainPanel = JPanel(BorderLayout())
            #Left panel
            self._leftPanel = JPanel(BorderLayout())
            self._leftPanel.setBorder(EmptyBorder(10, 10, 10, 10))
            #Left subpanel - Positions editor
            self._positionsEditor = Utils.callbacks.createTextEditor()
            #TODO Remove a normal editor?  self._positionsEditor = Utils.callbacks.createMessageEditor(self, True)
            self._positionsEditor.getComponent().setBorder(BorderFactory.createLineBorder(Color.BLACK))
            #Left subpanel - Title pane
            self._leftTitlePanel = JPanel(GridLayout(0, 1))
            self._leftTitlePanel.setBorder(EmptyBorder(0, 10, 10, 10))
            self._titleText = JLabel("Commands Position")
            self._titleText.setForeground(COLOR_BURP_TITLE_ORANGE)
            self._titleText.setFont(self._titleText.getFont().deriveFont(16.0))
            self._titleSubtitleText = JTextArea("Configure the position where commands will be inserted into the base request. Select the requests that were send Shell in the dropdown, then select the part of the request where commands need to be inserted and click the 'Add $' button.")
            self._titleSubtitleText.setEditable(False)
            self._titleSubtitleText.setLineWrap(True)
            self._titleSubtitleText.setWrapStyleWord(True)
            self._titleSubtitleText.setHighlighter(None)
            self._titleSubtitleText.setBorder(None)
            self._leftTitlePanel.add(self._titleText)
            self._leftTitlePanel.add(self._titleSubtitleText)
            #Left subpanel - Add positions editor and title
            self._leftPanel.add(self._leftTitlePanel, BorderLayout.NORTH)
            self._leftPanel.add(self._positionsEditor.getComponent(), BorderLayout.CENTER)
            #Right panel
            #self._rightPanel = JPanel(GridLayout(20, 1))
            self._rightPanel = JPanel()
            self._rightPanel.setLayout(BoxLayout(self._rightPanel, BoxLayout.Y_AXIS))
            #self._rightPanel.setPreferredSize(Dimension(150, 30))
            self._rightPanel.setBorder(EmptyBorder(10, 10, 10, 10))
            #Right panel - buttons
            self._buttonAdd = JButton("        Add $        ", actionPerformed=self.buttonAddClick)
            self._buttonClear = JButton("       Clear $       ", actionPerformed=self.buttonClearClick) #, actionPerformed=None
            # Right panel - add components
            self._rightPanel.add(self._buttonAdd)
            self._rightPanel.add(self._buttonClear)

            self._mainPanel.add(self._rightPanel, BorderLayout.EAST)
            self._mainPanel.add(self._leftPanel, BorderLayout.CENTER)

            return self._mainPanel

        def buttonAddClick(self, e):
            Utils.out("Button Add click")
            if self._positionsEditor.getSelectedText():
                #TODO: For if it's a messageeditor in stead of texteditor Utils.out(self._positionsEditor.getSelectedData())
                self.addPosition(self._positionsEditor.getSelectionBounds())
                self._parent._consoleController.startSession()
                self._buttonAdd.setEnabled(False)

        def buttonClearClick(self, e):
            Utils.out("Button Clear click")
            self.setEditor(self._parent.currentRequestRaw())
            self._buttonAdd.setEnabled(True)

        def setEditor(self, request_in_bytes):
            self._positionsEditor.setText(request_in_bytes)
            #TODO: for if I make the positions a messageExitor: self._positionsEditor.setMessage(iHttpRequestResponse.getRequest(), True)

        def addPosition(self, boundsArray):
            if len(boundsArray) == 2:
                self._parent.setCurrentRequestBounds(boundsArray[0], boundsArray[1])
                modified_request = Utils.wrapRawData(self._parent.currentRequestRaw(), boundsArray[0], boundsArray[1], "$", "$")
                self.setEditor(modified_request)
예제 #10
0
    class ConfigurationController(IMessageEditorController):
        def __init__(self, parent):
            self._parent = parent

        def getMainComponent(self):
            self._mainPanel = JPanel()
            #self._mainPanel.setLayout(BoxLayout(self._mainPanel, BoxLayout.Y_AXIS))
            self._mainPanel.setLayout(BorderLayout())
            self._titlePanel = JPanel(GridLayout(0, 1))
            self._titlePanel.setBorder(EmptyBorder(10, 20, 10, 10))
            self._titleText = JLabel("Mode configuration")
            self._titleText.setForeground(COLOR_BURP_TITLE_ORANGE)
            self._titleText.setFont(self._titleText.getFont().deriveFont(16.0))
            self._titleSubtitleText = JTextArea("Select a mode that works best for the type of exploit you are dealing with.")
            self._titleSubtitleText.setEditable(False)
            self._titleSubtitleText.setLineWrap(True)
            self._titleSubtitleText.setWrapStyleWord(True)
            self._titleSubtitleText.setHighlighter(None)
            self._titleSubtitleText.setBorder(None)

            #Local File Inclusion (LFI): Explore files
            #Command injection (visual): Shell
            #Command injection (blind):  Shell
            modes = ['Select mode...', 'Local File Inclusion (LFI) - Discover files', 'OS Command injection (visual) - Shell']
            self._cboModes = JComboBox(modes)
            self._cboModes.addActionListener(self.cboModesChanged())

            self._titlePanel.add(self._titleText)
            self._titlePanel.add(self._titleSubtitleText)
            self._titlePanel.add(self._cboModes)

            self._mainPanel.add(self._titlePanel, BorderLayout.NORTH)

            self._switchPanel = JPanel()
            self._switchPanel.setLayout(BoxLayout(self._switchPanel, BoxLayout.Y_AXIS))
            self._switchPanel.setBorder(EmptyBorder(5, 30, 10, 10))
            self._outputCompleteResponseSwitch = JCheckBox("Use full response (not only the response body)")
            self._outputCompleteResponseSwitch.setSelected(True)
            self._outputCompleteResponseSwitch.addItemListener(self.OutputCompleteResponseSwitchListener())
            self._switchPanel.add(self._outputCompleteResponseSwitch)
            self._urlEncodeSwitch = JCheckBox("Use url encode")
            self._urlEncodeSwitch.setSelected(True)
            self._urlEncodeSwitch.addItemListener(self.UrlEncodeSwitchListener())
            self._switchPanel.add(self._urlEncodeSwitch)
            self._outputIsolatorSwitch = JCheckBox("Use output isolator")
            self._outputIsolatorSwitch.setSelected(False)
            self._outputIsolatorSwitch.addItemListener(self.OutputIsolatorSwitchListener())
            self._switchPanel.add(self._outputIsolatorSwitch)
            self._removeSpacesSwitch = JCheckBox("Remove leading and trailing spaces")
            self._removeSpacesSwitch.setSelected(False)
            self._removeSpacesSwitch.addItemListener(self.SpacesSwitch())
            self._switchPanel.add(self._removeSpacesSwitch)
            self._removeHtmlTagsSwitch = JCheckBox("Remove html-tags (regex '<.*?>')")
            self._removeHtmlTagsSwitch.setSelected(False)
            self._removeHtmlTagsSwitch.addItemListener(self.HtmlTagsSwitch())
            self._switchPanel.add(self._removeHtmlTagsSwitch)
            self._tabCompletionSwitch = JCheckBox("Use tab-completion")
            self._tabCompletionSwitch.setSelected(False)
            self._tabCompletionSwitch.addItemListener(self.TabCompletionSwitchListener())
            self._switchPanel.add(self._tabCompletionSwitch)
            self._virtualPersistenceSwitch = JCheckBox("Use virtual persistence")
            self._virtualPersistenceSwitch.setSelected(False)
            self._virtualPersistenceSwitch.addItemListener(self.VirtualPersistenceSwitchListener())
            self._switchPanel.add(self._virtualPersistenceSwitch)
            self._wafSwitch = JCheckBox("WAF: Prepend each non-whitespace character (regex '\\w') with '\\'")
            self._wafSwitch.setSelected(False)
            self._wafSwitch.addItemListener(self.WafSwitch())
            self._switchPanel.add(self._wafSwitch)
            self._mainPanel.add(self._switchPanel, BorderLayout.CENTER)
            return self._mainPanel

        class cboModesChanged(ActionListener):
            def actionPerformed(self, e):
                cboModes = e.getSource()
                mode = cboModes.getSelectedItem()
                if mode == 'Local File Inclusion (LFI) - Discover files':
                    #Disable output isolator
                    Utils.shellController._outputIsolator = None
                    Utils.outputIsolator = None
                    Utils._outputIsolator = None
                    Utils.configurationController._outputIsolatorSwitch.setSelected(False)
                    Utils.configurationController._outputIsolatorSwitch.setEnabled(False)
                    #Disable remove leading and trailing spaces
                    Utils.shellController._removeSpaces = False
                    Utils.configurationController._removeSpacesSwitch.setSelected(False)
                    Utils.configurationController._removeSpacesSwitch.setEnabled(False)
                    #Disable remove html tags
                    Utils.shellController._removeHtmlTags = False
                    Utils.configurationController._removeHtmlTagsSwitch.setSelected(False)
                    Utils.configurationController._removeHtmlTagsSwitch.setEnabled(False)
                    #Disable tab-completion
                    Utils.shellController._tabCompletion = False
                    Utils.configurationController._tabCompletionSwitch.setSelected(False)
                    Utils.configurationController._tabCompletionSwitch.setEnabled(False)
                    #Disable virtual peristence
                    Utils.shellController._virtualPersistence = False
                    Utils.configurationController._virtualPersistenceSwitch.setSelected(False)
                    Utils.configurationController._virtualPersistenceSwitch.setEnabled(False)
                    #Disable WAF
                    Utils.shellController._waf = False
                    Utils.configurationController._wafSwitch.setSelected(False)
                    Utils.configurationController._wafSwitch.setEnabled(False)
                if mode == 'OS Command injection (visual) - Shell' or mode == 'Select mode...':
                    Utils.configurationController._outputIsolatorSwitch.setEnabled(True)
                    Utils.configurationController._removeSpacesSwitch.setEnabled(True)
                    Utils.configurationController._removeHtmlTagsSwitch.setEnabled(True)
                    Utils.configurationController._tabCompletionSwitch.setEnabled(True)
                    Utils.configurationController._virtualPersistenceSwitch.setEnabled(True)
                    Utils.configurationController._wafSwitch.setEnabled(True)

        class OutputIsolatorSwitchListener(ItemListener):
            def itemStateChanged(self, e):
                if e.getStateChange() == ItemEvent.SELECTED:
                    Utils.out("selected")
                    isolator = ["3535start3535", "3535end3535"]
                    Utils.shellController._outputIsolator = isolator
                    Utils.outputIsolator = isolator
                    Utils._outputIsolator = isolator
                elif e.getStateChange() == ItemEvent.DESELECTED:
                    #TODO If deselected, Virtual persistence should be disabled: unless the body only returns
                    # the command and nothing else, it's near impossible to warrant virtual persistence.
                    # One possibility I have, is to also allow to define positions in the response tab and filter
                    # out the command response like that (without using the outputisolators)
                    Utils.out("deselected")
                    Utils.shellController._outputIsolator = None
                    Utils.outputIsolator = None
                    Utils._outputIsolator = None

        class SpacesSwitch(ItemListener):
            def itemStateChanged(self, e):
                if e.getStateChange() == ItemEvent.SELECTED:
                    Utils.shellController._removeSpaces = True
                elif e.getStateChange() == ItemEvent.DESELECTED:
                    Utils.shellController._removeSpaces = False

        class HtmlTagsSwitch(ItemListener):
            def itemStateChanged(self, e):
                if e.getStateChange() == ItemEvent.SELECTED:
                    Utils.shellController._removeHtmlTags = True
                elif e.getStateChange() == ItemEvent.DESELECTED:
                    Utils.shellController._removeHtmlTags = False

        class TabCompletionSwitchListener(ItemListener):
            def itemStateChanged(self, e):
                if e.getStateChange() == ItemEvent.SELECTED:
                    Utils.shellController._tabCompletion = True
                elif e.getStateChange() == ItemEvent.DESELECTED:
                    Utils.shellController._tabCompletion = False

        class VirtualPersistenceSwitchListener(ItemListener):
            def itemStateChanged(self, e):
                if e.getStateChange() == ItemEvent.SELECTED:
                    Utils.shellController._virtualPersistence = True
                elif e.getStateChange() == ItemEvent.DESELECTED:
                    Utils.consoleController.setPwd(None)
                    Utils.shellController._virtualPersistence = False

        class UrlEncodeSwitchListener(ItemListener):
            def itemStateChanged(self, e):
                if e.getStateChange() == ItemEvent.SELECTED:
                    Utils.shellController._urlEncode = True
                elif e.getStateChange() == ItemEvent.DESELECTED:
                    Utils.shellController._urlEncode = False

        class OutputCompleteResponseSwitchListener(ItemListener):
            def itemStateChanged(self, e):
                if e.getStateChange() == ItemEvent.SELECTED:
                    Utils.shellController._outputCompleteResponse = True
                elif e.getStateChange() == ItemEvent.DESELECTED:
                    Utils.shellController._outputCompleteResponse = False

        class WafSwitch(ItemListener):
            def itemStateChanged(self, e):
                if e.getStateChange() == ItemEvent.SELECTED:
                    Utils.shellController._waf = True
                elif e.getStateChange() == ItemEvent.DESELECTED:
                    Utils.shellController._waf = False
예제 #11
0
class EmployeeDetails(JPanel):
    def __init__(self, employees):
        JPanel.__init__(self, preferredSize=(400, 200))
        layout = BoxLayout(self, BoxLayout.Y_AXIS)
        self.setLayout(layout)
        self._employees = employees
        employees.add_change_listener(self)
        self._create_status_label()
        self._create_name_editor()
        self._create_start_date_editor()
        self._create_save_button()
        self._create_vacation_display()
        self._adding_employee = False

    def _create_status_label(self):
        self._status_label = JLabel(name='status_label',
                                    font=Font(Font.SANS_SERIF, Font.PLAIN, 11))
        self.add(self._status_label)
        self._add_with_padding(self._status_label, 5)

    def _create_name_editor(self):
        self.add(JLabel(text='Employee Name:'))
        self._name_editor = FixedHeightTextField('name_input')
        self._add_with_padding(self._name_editor, 5)

    def _create_start_date_editor(self):
        self.add(JLabel(text='Start Date (yyyy-mm-dd):'))
        self._start_date_editor = FixedHeightTextField('start_input')
        self._add_with_padding(self._start_date_editor, 5)

    def _create_save_button(self):
        self._save_button = JButton('Save', name='save_button', visible=False)
        self._save_button.addActionListener(
            ListenerFactory(ActionListener, self._save_button_pushed))
        self._add_with_padding(self._save_button, 5)

    def _create_vacation_display(self):
        #        self._display = JTable()
        #        self._header = self._display.getTableHeader()
        #        self.add(self._header)
        #        self.add(self._display)
        pass

    def _add_with_padding(self, component, padding):
        self.add(component)
        self.add(Box.createRigidArea(Dimension(0, padding)))

    def show_employee(self, employee):
        self._name_editor.setText(employee.name)
        self._start_date_editor.setText(str(employee.startdate))
        self._name_editor.setEditable(False)
        self._start_date_editor.setEditable(False)
        self._save_button.setVisible(False)
        if self._adding_employee:
            self._adding_employee = False
        else:
            self._status_label.setText('')


#        self._display.setVisible(True)
#        self._display.setModel(VacationTableModel(employee))
#        self._header.setVisible(True)

    def edit_new_employee(self):
        self._name_editor.setText('')
        self._start_date_editor.setText('')
        self._name_editor.setEditable(True)
        self._start_date_editor.setEditable(True)
        self._save_button.setVisible(True)
        #        self._display.setVisible(False)
        #        self._header.setVisible(False)
        self._adding_employee = True

    def _save_button_pushed(self, event):
        self._employees.add(self._name_editor.getText(),
                            self._start_date_editor.getText())

    def employee_added(self, employee):
        self._status_label.setForeground(Color.BLACK)
        self._status_label.setText("Employee '%s' was added successfully." %
                                   employee.name)
        self._save_button.setVisible(False)

    def adding_employee_failed(self, reason):
        self._status_label.setForeground(Color.RED)
        self._status_label.setText(reason)
예제 #12
0
    def	registerExtenderCallbacks(self, callbacks):
        print "PhantomJS RIA Crawler extension"
        print "Nikolay Matyunin @autorak <*****@*****.**>"

        # keep a reference to our callbacks object and helpers object
        self._callbacks = callbacks
        self._helpers = callbacks.getHelpers()

        # extension name
        callbacks.setExtensionName("Phantom RIA Crawler")

        # Create Tab UI components
        self._jPanel = JPanel()
        self._jPanel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));

        _titleLabel = JLabel("Phantom RIA Crawler", SwingConstants.LEFT)
        _titleLabelFont = _titleLabel.font
        _titleLabelFont = _titleLabelFont.deriveFont(Font.BOLD, 12);
        _titleLabel.setFont(_titleLabelFont);
        _titleLabel.setForeground(Color(230, 142, 11))

        self._addressTextField = JTextField('')
        self._addressTextField.setColumns(50)
        _addressTextLabel = JLabel("Target URL:", SwingConstants.RIGHT)
        self._addressTextField.getDocument().addDocumentListener(self)

        self._phantomJsPathField = JTextField('phantomjs') # TODO: set permanent config value
        self._phantomJsPathField.setColumns(50)
        _phantomJsPathLabel = JLabel("PhantomJS path:", SwingConstants.RIGHT)

        self._startButton = JToggleButton('Start', actionPerformed=self.startToggled)
        self._startButton.setEnabled(False)

        _requestsMadeLabel = JLabel("DEPs found:", SwingConstants.RIGHT)
        self._requestsMadeInfo = JLabel("", SwingConstants.LEFT)
        _statesFoundLabel = JLabel("States found:", SwingConstants.RIGHT)
        self._statesFoundInfo = JLabel("", SwingConstants.LEFT)

        _separator = JSeparator(SwingConstants.HORIZONTAL)

        _configLabel = JLabel("Crawling configuration:")
        self._configButton = JButton("Load config", actionPerformed=self.loadConfigClicked)
        self._configFile = ""

        _listenersLabel= JLabel("Burp proxy listener:", SwingConstants.RIGHT)
        self._listenersCombo = JComboBox()
        self._configTimer = Timer(5000, None)
        self._configTimer.actionPerformed = self._configUpdated
        self._configTimer.stop()
        self._configUpdated(None)

        self._commandClient = CommandClient(self)

        # Layout management
        self._groupLayout = GroupLayout(self._jPanel)
        self._jPanel.setLayout(self._groupLayout)
        self._groupLayout.setAutoCreateGaps(True)
        self._groupLayout.setAutoCreateContainerGaps(True)

        self._groupLayout.setHorizontalGroup(self._groupLayout.createParallelGroup()
            .addComponent(_titleLabel)
            .addGroup(self._groupLayout.createSequentialGroup()
                .addComponent(_addressTextLabel)
                .addGroup(self._groupLayout.createParallelGroup()
                    .addComponent(self._addressTextField, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE)
                    .addGroup(self._groupLayout.createSequentialGroup()
                        .addComponent(_requestsMadeLabel)
                        .addComponent(self._requestsMadeInfo))
                    .addGroup(self._groupLayout.createSequentialGroup()
                        .addComponent(_statesFoundLabel)
                        .addComponent(self._statesFoundInfo)))
                .addComponent(self._startButton))
            .addComponent(_separator)
            .addGroup(self._groupLayout.createSequentialGroup()
                .addComponent(_configLabel)
                .addComponent(self._configButton))
            .addGroup(self._groupLayout.createSequentialGroup()
                .addComponent(_phantomJsPathLabel)
                .addComponent(self._phantomJsPathField, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE))
            .addGroup(self._groupLayout.createSequentialGroup()
                .addComponent(_listenersLabel)
                .addComponent(self._listenersCombo, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE))
        )

        self._groupLayout.setVerticalGroup(self._groupLayout.createSequentialGroup()
            .addComponent(_titleLabel)
            .addGroup(self._groupLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                .addComponent(_addressTextLabel)
                .addComponent(self._addressTextField)
                .addComponent(self._startButton))
            .addGroup(self._groupLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                .addComponent(_requestsMadeLabel)
                .addComponent(self._requestsMadeInfo))
            .addGroup(self._groupLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                .addComponent(_statesFoundLabel)
                .addComponent(self._statesFoundInfo))
            .addComponent(_separator, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
            .addGroup(self._groupLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                .addComponent(_configLabel)
                .addComponent(self._configButton))
            .addGroup(self._groupLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                .addComponent(_phantomJsPathLabel)
                .addComponent(self._phantomJsPathField))
            .addGroup(self._groupLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                .addComponent(_listenersLabel)
                .addComponent(self._listenersCombo))
        )

        self._groupLayout.linkSize(SwingConstants.HORIZONTAL, _configLabel, _phantomJsPathLabel);
        self._groupLayout.linkSize(SwingConstants.HORIZONTAL, _configLabel, _listenersLabel);
        self._groupLayout.linkSize(SwingConstants.HORIZONTAL, _statesFoundLabel, _requestsMadeLabel);


        # context menu data
        self._contextMenuData = None;
        self._running = False;

        # register callbacks
        callbacks.customizeUiComponent(self._jPanel)
        callbacks.registerContextMenuFactory(self)
        callbacks.addSuiteTab(self)

        return
예제 #13
0
class SelectionCellRenderer(TreeCellRenderer):
    def __init__(self, tree, mapContext):
        self.tree = tree
        self.mapContext = mapContext
        self.lblGroup = JLabel()
        self.lblGroup.setBackground(Color(222, 227, 233))  #.BLUE.brighter())
        self.lblGroup.setOpaque(True)
        self.lblGroup.setText(
            "plddddddddddddddddddddddddddddddddddddddddddddddddddddddd")

        self.lblGroupPreferredSize = self.lblGroup.getPreferredSize()
        #h = self.lblGroupPreferredSize.getHeight()
        #w = self.lblGroupPreferredSize.getWidth()
        #self.lblGroupPreferredSize.setSize(h, w)
        self.pnlLayer = JPanel()
        self.pnlLayer.setOpaque(False)

        self.pnlLayer.setLayout(FlowLayout(FlowLayout.LEFT))

        self.lblClean = JLabel()

        self.chkLayerVisibility = JCheckBox()
        self.chkLayerVisibility.setOpaque(False)
        self.lblLayerName = JLabel()
        self.lblLayerIcon = JLabel()
        self.lblFeatureSelecteds = JLabel()

        self.pnlLayer.add(self.chkLayerVisibility)
        self.pnlLayer.add(self.lblClean)
        self.pnlLayer.add(self.lblFeatureSelecteds)
        self.pnlLayer.add(self.lblLayerIcon)
        self.pnlLayer.add(self.lblLayerName)
        self.tree.setRowHeight(
            int(self.pnlLayer.getPreferredSize().getHeight()) - 3)
        self.lblUnknown = JLabel()

        ## Feature
        self.lblFeatureIcon = JLabel()
        self.lblFeatureName = JLabel()
        i18n = ToolsLocator.getI18nManager()
        self.lblFeatureName.setText(i18n.getTranslation("_Feature"))
        self.pnlFeature = JPanel()
        self.pnlFeature.setOpaque(False)
        self.pnlFeature.setLayout(FlowLayout(FlowLayout.LEFT))
        self.pnlFeature.add(self.lblFeatureIcon)
        self.pnlFeature.add(self.lblFeatureName)

    def getTreeCellRendererComponent(self, tree, value, selected, expanded,
                                     leaf, row, hasFocus):
        uo = value.getUserObject()
        if isinstance(uo, DataGroup):
            text = "[" + str(value.getChildCount()) + "] " + uo.getName()
            self.lblGroup.setText(text)
            self.lblGroup.setPreferredSize(self.lblGroupPreferredSize)
            return self.lblGroup
        if isinstance(uo, DataLayer):
            layer = uo.getLayer()

            self.lblLayerName.setText(uo.getName())
            self.lblLayerIcon.setIcon(getIconFromLayer(layer))
            if layer.isVisible():
                self.lblLayerName.setEnabled(True)
            else:
                self.lblLayerName.setEnabled(False)
            self.lblClean.setIcon(getIconByName("edit-clear"))
            self.chkLayerVisibility.setSelected(layer.isVisible())
            if layer.isWithinScale(
                    self.mapContext.getScaleView()):  # and layer.isVisible():
                self.chkLayerVisibility.setEnabled(True)
            else:
                self.chkLayerVisibility.setEnabled(False)
            if layer.getDataStore() != None and layer.getDataStore(
            ).getSelection() != None and layer.getDataStore().getSelection(
            ).getSize() != 0:  # and layer.isVisible():
                self.lblClean.setEnabled(True)
                self.lblFeatureSelecteds.setText(
                    str(layer.getDataStore().getSelection().getSize()))
                self.lblFeatureSelecteds.setEnabled(True)
            else:
                self.lblClean.setEnabled(False)
                self.lblFeatureSelecteds.setText("0")
                self.lblFeatureSelecteds.setEnabled(False)

            font = self.lblLayerName.getFont()
            self.lblLayerName.setForeground(Color.BLACK)
            if layer.isEditing():
                self.lblLayerName.setForeground(Color.RED)
            #if layer.isActive():
            if layer.isActive():  # and not font.isBold():
                newfont = font.deriveFont(Font.BOLD)
                self.lblLayerName.setFont(newfont)
            else:
                newfont = font.deriveFont(Font.PLAIN)
                self.lblLayerName.setFont(newfont)

            return self.pnlLayer
        if isinstance(uo, FeatureDataLayerNode):
            self.lblFeatureName.setText(uo.getFeature().toString())
            self.lblFeatureIcon.setIcon(getIconByName("edit-clear"))

            return self.pnlFeature
        self.lblUnknown.setText("")
        self.lblUnknown.setPreferredSize(Dimension(0, 0))
        return self.lblUnknown
예제 #14
0
class BurpExtender(IBurpExtender, ITab, IContextMenuFactory):
    EXTENSION_NAME = "AutoRecon"
    # subdomain = list()
    headers = {
        "User-Agent":
        "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
        "(KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36",
        "Accept":
        "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
        "Accept-Language":
        "en-US,en;q=0.9",
        "Accept-Encoding":
        "gzip, deflate, br",
    }

    def registerExtenderCallbacks(self, callbacks):
        # keep a reference to our callbacks object
        self._callbacks = callbacks
        self._helpers = callbacks.getHelpers()
        callbacks.setExtensionName(self.EXTENSION_NAME)

        callbacks.issueAlert("AutoRecon is enabled")

        # add the custom tab to Burp's UI
        self.initUI()
        # self._newpanel.setLayout(FlowLayout())
        # callbacks.customizeUiComponent(self._newpanel)
        callbacks.addSuiteTab(self)

        self.callable = [
            # self.sublister,
            # self.shodan_search,
            self.certsh_search,
            # self.anubis,
            # self.googleDig,
            # self.censys,
            # self.certspotter,
            # self.bufferover_run,
            # self.urlscan,
            # self.otx_alienvault,
            # self.threatminer,
            # self.netcraft,
            # self.threatcrowd,
            # self.dnsdumpster,
            # self.virustotal,
            # self.ptrarchive,
        ]
        # self.callable = [self.censys]

        # define stdout writer
        self._stdout = PrintWriter(callbacks.getStdout(), True)
        self._stderr = PrintWriter(callbacks.getStderr(), True)
        self._stdout.println(self.EXTENSION_NAME + " by @bourne")
        self._stdout.println(
            "================================================")
        self._stdout.println(
            'TIP: Right click on any domain and add it to scope in "autoRecon"'
        )
        self._stdout.println("")
        self.outputTxtArea.setText(
            self.EXTENSION_NAME + " by @bourne" + "\n" +
            "================================================" + "\n" +
            'TIP: Right click on any domain and add it to scope in "autoRecon"\n'
        )

        self.context = None

        callbacks.registerContextMenuFactory(self)

        return

    def initUI(self):
        self.tab = JPanel()

        # UI for Output
        self.outputLabel = JLabel("AutoRecon Log:")
        self.outputLabel.setFont(Font("Tahoma", Font.BOLD, 14))
        self.outputLabel.setForeground(Color(255, 102, 52))
        self.logPane = JScrollPane()
        self.outputTxtArea = JTextArea()
        self.outputTxtArea.setFont(Font("Consolas", Font.PLAIN, 12))
        self.outputTxtArea.setLineWrap(True)
        self.logPane.setViewportView(self.outputTxtArea)
        self.clearBtn = JButton("Clear Log", actionPerformed=self.clearLog)
        self.exportBtn = JButton("Export Log", actionPerformed=self.exportLog)
        self.parentFrm = JFileChooser()

        # Layout
        layout = GroupLayout(self.tab)
        layout.setAutoCreateGaps(True)
        layout.setAutoCreateContainerGaps(True)
        self.tab.setLayout(layout)

        layout.setHorizontalGroup(layout.createParallelGroup().addGroup(
            layout.createSequentialGroup().addGroup(
                layout.createParallelGroup().addComponent(
                    self.outputLabel).addComponent(self.logPane).addComponent(
                        self.clearBtn).addComponent(self.exportBtn))))

        layout.setVerticalGroup(layout.createParallelGroup().addGroup(
            layout.createParallelGroup().addGroup(
                layout.createSequentialGroup().addComponent(
                    self.outputLabel).addComponent(self.logPane).addComponent(
                        self.clearBtn).addComponent(self.exportBtn))))

    def getTabCaption(self):
        """Name of our tab"""
        return self.EXTENSION_NAME

    def getUiComponent(self):
        return self.tab

    def clearLog(self, event):
        self.outputTxtArea.setText(
            self.EXTENSION_NAME + " by @bourne" + "\n" +
            "================================================" + "\n" +
            'TIP: Right click on any domain and add it to scope in "autoRecon"\n'
        )

    def exportLog(self, event):
        chooseFile = JFileChooser()
        ret = chooseFile.showDialog(self.logPane, "Choose file")
        filename = chooseFile.getSelectedFile().getCanonicalPath()
        print("\n" + "Export to : " + filename)
        open(filename, "w", 0).write(self.outputTxtArea.text)

    def createMenuItems(self, context_menu):
        self.context = context_menu
        menu_list = ArrayList()
        menu_list.add(
            JMenuItem("Add domain to scope for AutoRecon",
                      actionPerformed=self.threadAnalysis))
        return menu_list

    def threadAnalysis(self, event):
        http_traffic = self.context.getSelectedMessages()

        self._stdout.println(str(len(http_traffic)) + " requests highlighted")

        for traffic in http_traffic:
            http_service = traffic.getHttpService()
            host = http_service.getHost()
            if host.startswith("www."):
                host = host[4:]

            self._stdout.println("User selected host: " + str(host))

        self.subdomain = list()
        threads = []
        for i in self.callable:
            time.sleep(1)
            thread = threading.Thread(target=i, args=(host, ))
            # thread.daemon = True
            threads.append(thread)
            thread.start()

        for i in threads:
            i.join()

        self.outputTxtArea.setText(
            self.EXTENSION_NAME + " by @bourne" + "\n" +
            "================================================" + "\n" +
            'TIP: Right click on any domain and add it to scope in "autoRecon"\n'
        )
        self.outputTxtArea.append("\n DOMAIN: " + host)
        self.outputTxtArea.append("\n Total {} subdomains found :\n\n".format(
            len(set(self.subdomain))))
        for s in set(self.subdomain):
            if not "*" in s:
                self.outputTxtArea.append("\n" + s)
                # request_url = """https://api.viewdns.info/portscan/?host={}&apikey=3b59ef16aea9a71c7e6ae2872e83008493375e9e&output=json""".format(
                #     s
                # )
                # try:
                #     # self.outputTxtArea.append(request_url)
                #     time.sleep(2)
                #     req = requests.get(request_url, verify=False, headers=self.headers, timeout=3)
                #     req = json.loads(req.text)
                # except Exception as e:
                #     self.outputTxtArea.append(str(e))

                # for i in req["response"]["port"]:
                #     if i["status"] == "open":
                #         self.outputTxtArea.append("\n\t",i["number"],i["service"])

                try:
                    req = requests.get(
                        """http://web.archive.org/cdx/search/cdx?url=*.{0}/*
                                    &output=json&fl=original&collapse=urlkey&page=/"""
                        .format(s),
                        verify=False,
                        headers=self.headers,
                        timeout=3)
                    temp = []
                    t = json.loads(req.text)
                    for i in t:
                        temp.extend(i)
                except Exception:
                    pass
                paths = []
                count = 0
                for i in range(1, len(temp)):
                    not_contains = re.compile("|".join(
                        ["js", "txt", "git", "zip"]))
                    # print(type(temp[i]))

                    if temp[i] not in paths and not_contains.search(temp[i]):
                        paths.append(temp[i])
                        count += 1
                for i in paths:
                    if ".js" in i.lower() or ".zip" in i.lower(
                    ) or ".txt" in i.lower() or ".git" in i.lower():
                        self.outputTxtArea.append("\n\t" + i)

        # thread = threading.Thread(target=self.certsh_search, args=(host,))
        # thread.daemon = True
        # thread.start()

        # thread = threading.Thread(target=self.shodan_search, args=(host,))
        # thread.daemon = True
        # thread.start()

    def certsh_search(self, host):
        BASE_URL = "https://crt.sh"
        threadLocal.response = requests.get(BASE_URL + "/?q=%." + host +
                                            "&output=json")
        # self._stdout.println(threadLocal.response)
        threadLocal.result = threadLocal.response.json()
        # self._stdout.println(result)
        threadLocal.sub = []

        for item in threadLocal.result:
            s = item["name_value"]
            t = s.split("\n")
            self.subdomain.extend(t)
            # self.subdomain.append(s)
            # self._stdout.println(item)
            self._stdout.println(self.subdomain)
            self._stdout.println("....")
            if s not in threadLocal.sub:
                threadLocal.sub.append(s)
                self._stdout.println(s)
        return

    def shodan_search(self, host):
        BASE_URL = "https://api.shodan.io/shodan/host/search/"
        SHODAN_API_KEY = "J1Rp7W8tcqmhsdiB3ZU3JVhOlPpOHp8X"
        API = "WozM2OXwuUSMSsiseIkPtyLFxYnDUrPP"
        QUERY = "hostname"

        try:
            threadLocal.response = requests.get(
                "https://api.shodan.io/shodan/host/search?key=" +
                SHODAN_API_KEY + "&query=hostname:" + host)
            # self._stdout.println(response.text)
            threadLocal.result = threadLocal.response.json()
            # self._stdout.println(result)
            threadLocal.sub = []
            for item in threadLocal.result["matches"]:
                s = item["hostnames"][0]
                self.subdomain.append(s)
                if s not in threadLocal.sub:
                    threadLocal.sub.append(s)
                    self._stdout.println(s)
            return
        except Exception as error:
            logging.exception("message")

    def anubis(self, host):
        BASE_URL = "https://jldc.me/anubis/subdomains/{0}".format(host)

        try:
            threadLocal.response = requests.get(BASE_URL)
            threadLocal.sub = []
            results = json.loads(threadLocal.response.text)
            for w in results:
                if "*" not in w and w.endswith(
                        "." + host) and w not in threadLocal.sub:
                    threadLocal.sub.append(w)
                    self.subdomain.append(w)
                    self._stdout.println(w)
            return
        except Exception as error:
            logging.exception("message")

    def bufferover_run(self, host):
        try:
            threadLocal.response = requests.get(
                "http://dns.bufferover.run/dns?q={0}".format(host))
            threadLocal.sub = []
            results = json.loads(threadLocal.response.text)["FDNS_A"]
            for w in results:
                domain = w.split(",")[1]
                if ("*" not in domain and domain.endswith("." + host)
                        and domain not in threadLocal.sub):
                    threadLocal.sub.append(domain)
                    self.subdomain.append(domain)
                    self._stdout.println(domain)
            return
        except Exception as error:
            logging.exception("message")

    def urlscan(self, host):
        BASE_URL = "https://urlscan.io/api/v1/search/?q=domain:{0}".format(
            host)

        try:
            threadLocal.response = requests.get(BASE_URL)
            threadLocal.sub = []
            results = json.loads(threadLocal.response.text)["results"]
            for w in results:
                domain = w["page"]["domain"]
                if ("*" not in domain and domain.endswith("." + host)
                        and domain not in threadLocal.sub):
                    threadLocal.sub.append(domain)
                    self.subdomain.append(domain)
                    self._stdout.println(domain)
            return
        except Exception as error:
            logging.exception("message")

    def otx_alienvault(self, host):
        BASE_URL = "https://otx.alienvault.com/api/v1/indicator/domain/{0}/passive_dns".format(
            host)

        try:
            tHeader = {
                "Host": "otx.alienvault.com",
                "User-Agent":
                "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:78.0) Gecko/20100101 Firefox/78.0",
                "Accept":
                "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
                "Accept-Language": "en-US,en;q=0.5",
                "Accept-Encoding": "gzip, deflate, br",
                "Connection": "keep-alive",
                "Upgrade-Insecure-Requests": "1",
                "Cache-Control": "max-age=0",
            }

            response = requests.get(BASE_URL)
            threadLocal.sub = []
            self._stdout.println(response.status_code)
            # results = json.loads(threadLocal.response.text)["passive_dns"]
            # for w in results:
            #     h = w["hostname"]
            #     if "*" not in h and h.endswith("." + host) and h not in threadLocal.sub:
            #         threadLocal.sub.append(h)
            #         self.subdomain.append(h)
            #         self._stdout.println(h)
            return
        except Exception as error:
            logging.exception("message")

    def threatminer(self, host):
        BASE_URL = "https://api.threatminer.org/v2/domain.php?q={0}&api=True&rt=5".format(
            host)

        try:
            threadLocal.response = requests.get(BASE_URL)
            threadLocal.sub = []
            results = json.loads(threadLocal.response.text)["results"]
            for w in results:
                if "*" not in w and w.endswith(
                        "." + host) and w not in threadLocal.sub:
                    threadLocal.sub.append(w)
                    self.subdomain.append(w)
                    self._stdout.println(w)
            return
        except Exception as error:
            logging.exception("message")

    # def censys(self, host):
    #     try:
    #         censys_certificates = censys.certificates.CensysCertificates(
    #             api_id="5d63a69e-6142-46ec-830f-7279734e76f0", api_secret="qz6uDnlOCfZPJIXVyKvheot5HUxqZjNl")
    #         certificate_query = 'parsed.names: %s' % host
    #         certificates_search_results = censys_certificates.search(
    #             certificate_query, fields=['parsed.names'])

    #         subdomains = []
    #         for search_result in certificates_search_results:
    #             subdomains.extend(search_result['parsed.names'])
    #             self._stdout.println(search_result['parsed.names'])
    #     except Exception as error:
    #         self._stderr.println(error)

    #     return threadLocal.subs

    def certspotter(self, host):
        BASE_URL = "https://certspotter.com/api/v0/certs?domain={0}".format(
            host)

        try:
            threadLocal.response = requests.get(BASE_URL)
            threadLocal.sub = []
            if threadLocal.response.status_code == 200:
                for w in (threadLocal.response.content.replace(
                        '"', " ").replace("'", " ").rsplit()):
                    if ("*" not in w and w.endswith("." + host)
                            and w not in threadLocal.sub):
                        threadLocal.sub.append(w)
                        self.subdomain.append(w)
                        self._stdout.println(w)
            return
        except Exception as error:
            logging.exception("message")

    def googleDig(self, host):
        try:
            url_1 = "https://toolbox.googleapps.com/apps/dig/#ANY/"
            url_2 = "https://toolbox.googleapps.com/apps/dig/lookup"
            s = requests.session()
            threadLocal.req = s.get(url_1)
            csrf_middleware = re.compile(
                "<input type='hidden' name='csrfmiddlewaretoken' value='(.*?)' />",
                re.S).findall(threadLocal.req.content)[0]
            # tHeader = self.headers
            # tHeader["Referer"] = url_1
            threadLocal.req = s.post(
                url_2,
                cookies={"csrftoken": csrf_middleware},
                data={
                    "csrfmiddlewaretoken": csrf_middleware,
                    "domain": host,
                    "typ": "ANY",
                },
                headers={"Referer": url_1},
                verify=False,
            )
            threadLocal.subs = []
            if threadLocal.req.status_code is 200:
                for w in (json.loads(
                        threadLocal.req.content)["response"].replace(
                            '"', " ").replace(";", " ").rsplit()):
                    if ("*" not in w and w.endswith("." + host + ".")
                            and w[:-1] not in threadLocal.subs):
                        threadLocal.subs.append(w[:-1])
                        self.subdomain.append(w[:-1])
            else:
                # warn 403
                pass
        except Exception as error:
            logging.exception("message")
        return threadLocal.subs

    def netcraft(self, host):
        try:
            threadLocal.n = 0
            threadLocal.results = ""
            url = (
                "https://searchdns.netcraft.com/?restriction=site+contains&host=*.{0}"
                "&lookup=wait..&position=limited".format(host))

            threadLocal.subs = []
            while "<b>Next page</b></a>" not in threadLocal.results:
                while 1:
                    try:
                        threadLocal.results = requests.get(url)
                        break
                    except:
                        threadLocal.n += 1
                        if threadLocal.n is 3:
                            break
                if threadLocal.n is 3:
                    break
                if threadLocal.results.status_code is 200:
                    for l in re.compile(
                            '<a href="http://toolbar.netcraft.com/site_report\?url=(.*)">'
                    ).findall(threadLocal.results.content):
                        domain = parse_url(l).host

                        if ("*" not in domain and domain.endswith("." + host)
                                and domain not in threadLocal.subs):
                            threadLocal.subs.append(domain)
                            self.subdomain.append(domain)
                else:
                    # warn 403
                    break
                try:
                    url = ("http://searchdns.netcraft.com" +
                           re.compile('<A href="(.*?)"><b>Next page</b></a>').
                           findall(threadLocal.results.content)[0])
                except:
                    break
        except Exception as error:
            logging.exception("message")
        return threadLocal.subs

    def threatcrowd(self, host):
        try:
            threadLocal.n = 0
            url = "https://www.threatcrowd.org/searchApi/v2/domain/report/?domain={0}".format(
                host)
            threadLocal.subs = []
            while 1:
                try:
                    threadLocal.results = requests.get(url)
                    break
                except:
                    threadLocal.n += 1
                    if threadLocal.n is 3:
                        break
            if threadLocal.results.status_code is 200:
                try:
                    threadLocal.subs = json.loads(
                        threadLocal.results.content)["subdomains"]
                    for i in threadLocal.subs:
                        self.subdomain.append(i)
                except:
                    threadLocal.subs = []
            else:
                # warn 403
                pass
            return threadLocal.subs
        except Exception as error:
            logging.exception("message")

    def dnsdumpster(self, host):
        try:
            url = "https://dnsdumpster.com/"
            s = requests.session()
            threadLocal.req = s.get(url)
            csrf_middleware = re.compile(
                "<input type='hidden' name='csrfmiddlewaretoken' value='(.*?)' />",
                re.S).findall(threadLocal.req.content)[0]
            threadLocal.req = s.post(
                url,
                cookies={"csrftoken": csrf_middleware},
                data={
                    "csrfmiddlewaretoken": csrf_middleware,
                    "targetip": host
                },
                headers={"Referer": url},
            )
            threadLocal.subs = []
            if threadLocal.req.status_code is 200:
                for w in (threadLocal.req.content.replace(".<", " ").replace(
                        "<", " ").replace(">", " ").rsplit()):
                    if ("*" not in w and w.endswith("." + host)
                            and w not in threadLocal.subs):
                        threadLocal.subs.append(w)
                        self.subdomain.append(w)
            else:
                # warn 403
                pass
        except Exception as error:
            logging.exception("message")
        return threadLocal.subs

    def virustotal(self, host):
        n = 0
        url = "https://www.virustotal.com/en/domain/{0}/information/".format(
            host)
        threadLocal.subs = []
        try:
            threadLocal.results = requests.get(url, headers=headers)
            if threadLocal.results.status_code is 200:
                try:
                    for l in re.compile(
                            '<div class="enum.*?">.*?<a target="_blank" href=".*?">(.*?)</a>',
                            re.S,
                    ).findall(threadLocal.results.content):
                        domain = parse_url(l).host
                        if ("*" not in domain
                                and domain.strip().endswith("." + host)
                                and domain.strip() not in threadLocal.subs):
                            threadLocal.subs.append(domain.strip())
                except:
                    pass
            else:
                # warn 403
                pass
        except:
            pass
        return threadLocal.subs

    def ptrarchive(self, host):
        n = 0
        url = "http://ptrarchive.com/tools/search2.htm?label={0}&date=ALL".format(
            host)
        threadLocal.subs = []
        try:
            threadLocal.results = requests.get(url, headers=headers)
            if threadLocal.results.status_code is 200:
                for sub in threadLocal.results.content.rsplit():
                    if ("*" in sub and sub.endswith("." + host)
                            and sub not in threadLocal.subs):
                        threadLocal.subs.append(sub)
            else:
                # warn 403
                pass
        except:
            pass
        return threadLocal.subs

    def sublister(self, host):
        BASE_URL = "https://api.sublist3r.com/search.php?domain={0}".format(
            host)

        try:
            threadLocal.response = requests.get(BASE_URL)
            threadLocal.sub = []
            if threadLocal.response.status_code == 200:
                for w in (json.loads(threadLocal.response.text)):
                    if ("*" not in w and w.endswith("." + host)
                            and w not in threadLocal.sub):
                        threadLocal.sub.append(w)
                        self.subdomain.append(w)
                        self._stdout.println(w)
            return
        except Exception as error:
            logging.exception("message")
class AutopsyImageClassificationModuleWithUISettingsPanel(
        IngestModuleIngestJobSettingsPanel):
    _logger = Logger.getLogger(
        AutopsyImageClassificationModuleFactory.moduleName)

    def log(self, level, msg):
        self._logger.logp(level, self.__class__.__name__,
                          inspect.stack()[1][3], msg)

    def __init__(self, settings):
        self.local_settings = settings
        self.config_location = os.path.join(
            os.path.dirname(os.path.abspath(__file__)), 'configs.json')
        self.init_components()
        self.customize_components()
        self.check_server_connection(None)
        self.classes_of_interest_changes_list = list()
        self.classes_of_interest_checkboxes = list()

    # Return the settings used
    def getSettings(self):
        if not os.path.isfile(self.config_location):
            self.log(
                Level.INFO,
                "Configuration file not found, loading the default configuration"
            )
            self.local_settings.setServerHost(DEFAULT_HOST)
            self.local_settings.setServerPort(DEFAULT_PORT)
            self.local_settings.setImageFormats(DEFAULT_IMAGES_FORMAT)
            self.local_settings.setMinFileSize(DEFAULT_MIN_FILE_SIZE)
            self.local_settings.setMinProbability(DEFAULT_MIN_PROBABILITY)
            self.local_settings.setClassesOfInterest(
                json.loads(DEFAULT_CLASSES_OF_INTEREST))
            # self.saveSettings(None)
            return self.local_settings
        else:
            if not os.access(self.config_location, os.R_OK):
                err_string = "Cannot access configuration file, please review the file permissions"
                raise IngestModuleException(err_string)

            with io.open(self.config_location, 'r', encoding='utf-8') as f:
                self.log(Level.INFO, "Configuration file read")
                json_configs = json.load(f)

            self.local_settings.setServerHost(json_configs['server']['host'])
            self.local_settings.setServerPort(json_configs['server']['port'])

            image_formats = json_configs['imageFormats']

            if not isinstance(image_formats, list) or len(image_formats) == 0:
                err_string = "Invalid list of image formats given"
                raise IngestModuleException(err_string)

            self.local_settings.setImageFormats(image_formats)

            self.local_settings.setMinFileSize(json_configs['minFileSize'])
            self.local_settings.setMinProbability(
                json_configs['minProbability'])
            self.local_settings.setClassesOfInterest(
                json_configs['classesOfInterest'])
            return self.local_settings

    def check_server_connection(self, e):
        message_string = "Testing connection with server..."
        self.log(Level.INFO, message_string)
        self.message.setText(message_string)
        self.error_message.setText("")

        new_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        new_socket.settimeout(1)
        try:
            new_socket.connect(
                (self.host_TF.getText(), int(self.port_TF.getText())))
            self.local_settings.setIsServerOnline(True)
            message_string = "Server is up!"
            self.log(Level.INFO, message_string)
            self.message.setText(message_string)

        except (socket.timeout, socket.error) as e:
            self.local_settings.setIsServerOnline(False)
            err_string = "Server is down"
            self.error_message.setText(err_string)
            self.message.setText("")
            self.log(Level.INFO, err_string)
        finally:
            new_socket.close()

    def save_settings(self, e):
        self.message.setText("")
        self.log(Level.INFO, "Settings save button clicked!")

        host = self.host_TF.getText()

        if not host.strip():
            err_string = "Invalid host"
            self.error_message.setText(err_string)
            return
            # raise IngestModuleException(err_string)

        port = self.port_TF.getText()
        if not host.strip():
            err_string = "Invalid port number"
            self.error_message.setText(err_string)
            return
            # raise IngestModuleException(err_string)

        image_formats_array = self.image_formats_TF.getText().strip().split(
            ';')
        if len(image_formats_array) == 0 or not image_formats_array[0]:
            err_string = "Invalid image formats"
            self.error_message.setText(err_string)
            return
            # raise IngestModuleException(err_string)

        min_probability_string = self.min_probability_TF.getText().strip()
        if not min_probability_string:
            err_string = "Invalid minimum confidence value"
            self.error_message.setText(err_string)
            return
            # raise IngestModuleException(err_string)

        min_probability = int(float(min_probability_string))

        min_file_size_string = self.min_file_size_TF.getText().strip()
        if not min_file_size_string:
            err_string = "Invalid minimum file size"
            self.error_message.setText(err_string)
            return
            # raise IngestModuleException(err_string)

        min_file_size = int(float(min_file_size_string))

        configs = {
            'server': {
                'host': host,
                'port': port
            },
            'imageFormats': image_formats_array,
            'minProbability': min_probability,
            'minFileSize': min_file_size,
            'classesOfInterest': self.local_settings.getClassesOfInterest()
        }

        with io.open(self.config_location, 'w', encoding='utf-8') as f:
            f.write(json.dumps(configs, ensure_ascii=False))

        self.error_message.setText("")

        message = "Settings saved "
        self.message.setText(message)
        self.log(Level.INFO, message + " in " + self.config_location)

    def open_text_editor(self, e):
        self.log(Level.INFO, "Lauching external text editor ")
        if sys.platform == "win32":
            subprocess.call(["notepad", self.config_location])
        else:
            opener = "open" if sys.platform == "darwin" else "xdg-open"
            subprocess.call([opener, self.config_location])

    def on_save_classes_of_interest_click(self, e):
        self.detectable_obejcts_dialog.setVisible(False)
        for item in self.classes_of_interest_changes_list:
            for class_oi in self.local_settings.getClassesOfInterest():
                if item.getText() == class_oi['name']:
                    self.log(
                        Level.INFO, "match found " + class_oi['name'] +
                        " and is selected " + str(item.isSelected()))
                    class_oi['enabled'] = item.isSelected()
                    break
        self.classes_of_interest_checkboxes = list()

    def on_cancel_classes_of_interest_click(self, e):
        self.detectable_obejcts_dialog.setVisible(False)
        self.classes_of_interest_changes_list = list()
        self.classes_of_interest_checkboxes = list()

    def on_class_checkbox_clicked(self, e):
        self.classes_of_interest_changes_list.append(e.getSource())

    def on_select_all_clicked(self, e):
        for checkbox in self.classes_of_interest_checkboxes:
            checkbox.setSelected(True)

    def on_deselect_all_clicked(self, e):
        for checkbox in self.classes_of_interest_checkboxes:
            checkbox.setSelected(False)

    def show_detectable_objects_dialog(self, e):
        parentComponent = SwingUtilities.windowForComponent(self.panel0)
        self.detectable_obejcts_dialog = JDialog(
            parentComponent, "List of Objects to Detect",
            ModalityType.APPLICATION_MODAL)
        panel = JPanel()
        self.detectable_obejcts_dialog.add(panel)
        gbPanel = GridBagLayout()
        gbcPanel = GridBagConstraints()
        panel.setLayout(gbPanel)

        y = 0
        x = 0
        for line in self.local_settings.getClassesOfInterest():
            if y > 15:
                y = 0
                x = x + 1

            class_check_box = JCheckBox(line['name'])
            self.classes_of_interest_checkboxes.append(class_check_box)
            class_check_box.setEnabled(True)
            class_check_box.setSelected(line['enabled'])
            class_check_box.addItemListener(self.on_class_checkbox_clicked)
            gbcPanel.gridx = x
            gbcPanel.gridy = y
            gbcPanel.gridwidth = 1
            gbcPanel.gridheight = 1
            gbcPanel.fill = GridBagConstraints.BOTH
            gbcPanel.weightx = 1
            gbcPanel.weighty = 1
            gbcPanel.anchor = GridBagConstraints.NORTH
            gbPanel.setConstraints(class_check_box, gbcPanel)
            panel.add(class_check_box)
            y = y + 1

        blank_1_L = JLabel(" ")
        blank_1_L.setEnabled(True)
        gbcPanel.gridx = 0
        gbcPanel.gridy = y + 1
        gbcPanel.gridwidth = 1
        gbcPanel.gridheight = 1
        gbcPanel.fill = GridBagConstraints.BOTH
        gbcPanel.weightx = 1
        gbcPanel.weighty = 0
        gbcPanel.anchor = GridBagConstraints.NORTH
        gbPanel.setConstraints(blank_1_L, gbcPanel)
        panel.add(blank_1_L)

        deselect_all_button = JButton("Deselect all")
        deselect_all_button.setEnabled(True)
        deselect_all_button.addActionListener(self.on_deselect_all_clicked)
        gbcPanel.gridx = 1
        gbcPanel.gridy = y + 2
        gbcPanel.gridwidth = 1
        gbcPanel.gridheight = 1
        gbcPanel.fill = GridBagConstraints.BOTH
        gbcPanel.weightx = 2
        gbcPanel.weighty = 1
        gbcPanel.anchor = GridBagConstraints.NORTH
        gbPanel.setConstraints(deselect_all_button, gbcPanel)
        panel.add(deselect_all_button)

        select_all_button = JButton("Select all")
        select_all_button.setEnabled(True)
        select_all_button.addActionListener(self.on_select_all_clicked)
        gbcPanel.gridx = 3
        gbcPanel.gridy = y + 2
        gbcPanel.gridwidth = 1
        gbcPanel.gridheight = 1
        gbcPanel.fill = GridBagConstraints.BOTH
        gbcPanel.weightx = 2
        gbcPanel.weighty = 1
        gbcPanel.anchor = GridBagConstraints.NORTH
        gbPanel.setConstraints(select_all_button, gbcPanel)
        panel.add(select_all_button)

        blank_2_L = JLabel(" ")
        blank_2_L.setEnabled(True)
        gbcPanel.gridx = 0
        gbcPanel.gridy = y + 3
        gbcPanel.gridwidth = 1
        gbcPanel.gridheight = 1
        gbcPanel.fill = GridBagConstraints.BOTH
        gbcPanel.weightx = 1
        gbcPanel.weighty = 0
        gbcPanel.anchor = GridBagConstraints.NORTH
        gbPanel.setConstraints(blank_2_L, gbcPanel)
        panel.add(blank_2_L)

        cancel_button = JButton("Cancel")
        cancel_button.setEnabled(True)
        cancel_button.addActionListener(
            self.on_cancel_classes_of_interest_click)
        gbcPanel.gridx = 1
        gbcPanel.gridy = y + 4
        gbcPanel.gridwidth = 1
        gbcPanel.gridheight = 1
        gbcPanel.fill = GridBagConstraints.BOTH
        gbcPanel.weightx = 2
        gbcPanel.weighty = 1
        gbcPanel.anchor = GridBagConstraints.NORTH
        gbPanel.setConstraints(cancel_button, gbcPanel)
        panel.add(cancel_button)

        save_button = JButton("Save")
        save_button.setEnabled(True)
        save_button.addActionListener(self.on_save_classes_of_interest_click)
        gbcPanel.gridx = 3
        gbcPanel.gridy = y + 4
        gbcPanel.gridwidth = 1
        gbcPanel.gridheight = 1
        gbcPanel.fill = GridBagConstraints.BOTH
        gbcPanel.weightx = 2
        gbcPanel.weighty = 1
        gbcPanel.anchor = GridBagConstraints.NORTH
        gbPanel.setConstraints(save_button, gbcPanel)
        panel.add(save_button)

        blank_3_L = JLabel(" ")
        blank_3_L.setEnabled(True)
        gbcPanel.gridx = 0
        gbcPanel.gridy = y + 5
        gbcPanel.gridwidth = 1
        gbcPanel.gridheight = 1
        gbcPanel.fill = GridBagConstraints.BOTH
        gbcPanel.weightx = 1
        gbcPanel.weighty = 0
        gbcPanel.anchor = GridBagConstraints.NORTH
        gbPanel.setConstraints(blank_3_L, gbcPanel)
        panel.add(blank_3_L)

        self.detectable_obejcts_dialog.pack()
        screenSize = Toolkit.getDefaultToolkit().getScreenSize()
        self.detectable_obejcts_dialog.setLocation(
            int((screenSize.getWidth() / 2) -
                (self.detectable_obejcts_dialog.getWidth() / 2)),
            int((screenSize.getHeight() / 2) -
                (self.detectable_obejcts_dialog.getHeight() / 2)))
        self.detectable_obejcts_dialog.setVisible(True)

    def customize_components(self):
        settings = self.getSettings()

        self.host_TF.setText(settings.getServerHost())
        self.port_TF.setText(str(settings.getServerPort()))
        self.log(Level.INFO, "[customizeComponents]")

        self.log(Level.INFO, settings.getImageFormats()[0])
        self.image_formats_TF.setText(';'.join(settings.getImageFormats()))
        self.min_probability_TF.setText(str(settings.getMinProbability()))
        self.min_file_size_TF.setText(str(settings.getMinFileSize()))

    def init_components(self):
        self.panel0 = JPanel()

        self.rbgPanel0 = ButtonGroup()
        self.gbPanel0 = GridBagLayout()
        self.gbcPanel0 = GridBagConstraints()
        self.panel0.setLayout(self.gbPanel0)

        self.host_L = JLabel("Host:")
        self.host_L.setEnabled(True)
        self.gbcPanel0.gridx = 0
        self.gbcPanel0.gridy = 1
        self.gbcPanel0.gridwidth = 1
        self.gbcPanel0.gridheight = 1
        self.gbcPanel0.fill = GridBagConstraints.BOTH
        self.gbcPanel0.weightx = 1
        self.gbcPanel0.weighty = 0
        self.gbcPanel0.anchor = GridBagConstraints.NORTH
        self.gbPanel0.setConstraints(self.host_L, self.gbcPanel0)
        self.panel0.add(self.host_L)

        self.port_L = JLabel("Port:")
        self.port_L.setEnabled(True)
        self.gbcPanel0.gridx = 1
        self.gbcPanel0.gridy = 1
        self.gbcPanel0.gridwidth = 2
        self.gbcPanel0.gridheight = 1
        self.gbcPanel0.fill = GridBagConstraints.BOTH
        self.gbcPanel0.weightx = 1
        self.gbcPanel0.weighty = 0
        self.gbcPanel0.anchor = GridBagConstraints.NORTH
        self.gbPanel0.setConstraints(self.port_L, self.gbcPanel0)
        self.panel0.add(self.port_L)

        self.host_TF = JTextField(10)
        self.gbcPanel0.gridx = 0
        self.gbcPanel0.gridy = 2
        self.gbcPanel0.gridwidth = 1
        self.gbcPanel0.gridheight = 1
        self.gbcPanel0.fill = GridBagConstraints.BOTH
        self.gbcPanel0.weightx = 1
        self.gbcPanel0.weighty = 0
        self.gbcPanel0.anchor = GridBagConstraints.NORTH
        self.gbPanel0.setConstraints(self.host_TF, self.gbcPanel0)
        self.panel0.add(self.host_TF)

        format = NumberFormat.getInstance()
        format.setGroupingUsed(False)

        port_formatter = NumberFormatter(format)
        port_formatter.setValueClass(Integer)
        port_formatter.setAllowsInvalid(False)
        port_formatter.setMinimum(Integer(0))
        port_formatter.setMaximum(Integer(65535))

        self.port_TF = JFormattedTextField(port_formatter)
        self.gbcPanel0.gridx = 1
        self.gbcPanel0.gridy = 2
        self.gbcPanel0.gridwidth = 1
        self.gbcPanel0.gridheight = 1
        self.gbcPanel0.fill = GridBagConstraints.BOTH
        self.gbcPanel0.weightx = 1
        self.gbcPanel0.weighty = 0
        self.gbcPanel0.anchor = GridBagConstraints.NORTH
        self.gbPanel0.setConstraints(self.port_TF, self.gbcPanel0)
        self.panel0.add(self.port_TF)

        self.blank_1_L = JLabel(" ")
        self.blank_1_L.setEnabled(True)
        self.gbcPanel0.gridx = 2
        self.gbcPanel0.gridy = 3
        self.gbcPanel0.gridwidth = 1
        self.gbcPanel0.gridheight = 1
        self.gbcPanel0.fill = GridBagConstraints.BOTH
        self.gbcPanel0.weightx = 1
        self.gbcPanel0.weighty = 0
        self.gbcPanel0.anchor = GridBagConstraints.NORTH
        self.gbPanel0.setConstraints(self.blank_1_L, self.gbcPanel0)
        self.panel0.add(self.blank_1_L)

        self.image_formats_L = JLabel("Format of images (separator \";\"):")
        self.port_L.setEnabled(True)
        self.gbcPanel0.gridx = 0
        self.gbcPanel0.gridy = 4
        self.gbcPanel0.gridwidth = 1
        self.gbcPanel0.gridheight = 1
        self.gbcPanel0.fill = GridBagConstraints.BOTH
        self.gbcPanel0.weightx = 1
        self.gbcPanel0.weighty = 0
        self.gbcPanel0.anchor = GridBagConstraints.NORTH
        self.gbPanel0.setConstraints(self.image_formats_L, self.gbcPanel0)
        self.panel0.add(self.image_formats_L)

        self.image_formats_TF = JTextField(10)
        self.gbcPanel0.gridx = 0
        self.gbcPanel0.gridy = 5
        self.gbcPanel0.gridwidth = 1
        self.gbcPanel0.gridheight = 1
        self.gbcPanel0.fill = GridBagConstraints.BOTH
        self.gbcPanel0.weightx = 1
        self.gbcPanel0.weighty = 0
        self.gbcPanel0.anchor = GridBagConstraints.NORTH
        self.gbPanel0.setConstraints(self.image_formats_TF, self.gbcPanel0)
        self.panel0.add(self.image_formats_TF)

        self.blank_2_L = JLabel(" ")
        self.blank_2_L.setEnabled(True)
        self.gbcPanel0.gridx = 2
        self.gbcPanel0.gridy = 6
        self.gbcPanel0.gridwidth = 1
        self.gbcPanel0.gridheight = 1
        self.gbcPanel0.fill = GridBagConstraints.BOTH
        self.gbcPanel0.weightx = 1
        self.gbcPanel0.weighty = 0
        self.gbcPanel0.anchor = GridBagConstraints.NORTH
        self.gbPanel0.setConstraints(self.blank_2_L, self.gbcPanel0)
        self.panel0.add(self.blank_2_L)

        self.min_probability_L = JLabel("Confidence minimum (%):")
        self.port_L.setEnabled(True)
        self.gbcPanel0.gridx = 0
        self.gbcPanel0.gridy = 7
        self.gbcPanel0.gridwidth = 1
        self.gbcPanel0.gridheight = 1
        self.gbcPanel0.fill = GridBagConstraints.BOTH
        self.gbcPanel0.weightx = 1
        self.gbcPanel0.weighty = 0
        self.gbcPanel0.anchor = GridBagConstraints.NORTH
        self.gbPanel0.setConstraints(self.min_probability_L, self.gbcPanel0)
        self.panel0.add(self.min_probability_L)

        min_probabilty_formatter = NumberFormatter(format)
        min_probabilty_formatter.setValueClass(Integer)
        min_probabilty_formatter.setAllowsInvalid(False)
        min_probabilty_formatter.setMinimum(Integer(0))
        min_probabilty_formatter.setMaximum(Integer(100))

        self.min_probability_TF = JFormattedTextField(min_probabilty_formatter)
        self.gbcPanel0.gridx = 0
        self.gbcPanel0.gridy = 8
        self.gbcPanel0.gridwidth = 1
        self.gbcPanel0.gridheight = 1
        self.gbcPanel0.fill = GridBagConstraints.BOTH
        self.gbcPanel0.weightx = 1
        self.gbcPanel0.weighty = 0
        self.gbcPanel0.anchor = GridBagConstraints.NORTH
        self.gbPanel0.setConstraints(self.min_probability_TF, self.gbcPanel0)
        self.panel0.add(self.min_probability_TF)

        self.blank_3_L = JLabel(" ")
        self.blank_3_L.setEnabled(True)
        self.gbcPanel0.gridx = 2
        self.gbcPanel0.gridy = 9
        self.gbcPanel0.gridwidth = 1
        self.gbcPanel0.gridheight = 1
        self.gbcPanel0.fill = GridBagConstraints.BOTH
        self.gbcPanel0.weightx = 1
        self.gbcPanel0.weighty = 0
        self.gbcPanel0.anchor = GridBagConstraints.NORTH
        self.gbPanel0.setConstraints(self.blank_3_L, self.gbcPanel0)
        self.panel0.add(self.blank_3_L)

        self.min_file_size_L = JLabel("Minimum file size (KB):")
        self.min_file_size_L.setEnabled(True)
        self.gbcPanel0.gridx = 0
        self.gbcPanel0.gridy = 10
        self.gbcPanel0.gridwidth = 1
        self.gbcPanel0.gridheight = 1
        self.gbcPanel0.fill = GridBagConstraints.BOTH
        self.gbcPanel0.weightx = 1
        self.gbcPanel0.weighty = 0
        self.gbcPanel0.anchor = GridBagConstraints.NORTH
        self.gbPanel0.setConstraints(self.min_file_size_L, self.gbcPanel0)
        self.panel0.add(self.min_file_size_L)

        min_file_size_formatter = NumberFormatter(format)
        min_file_size_formatter.setValueClass(Integer)
        min_file_size_formatter.setAllowsInvalid(False)
        min_file_size_formatter.setMinimum(Integer(0))

        self.min_file_size_TF = JFormattedTextField(min_file_size_formatter)
        self.gbcPanel0.gridx = 0
        self.gbcPanel0.gridy = 11
        self.gbcPanel0.gridwidth = 1
        self.gbcPanel0.gridheight = 1
        self.gbcPanel0.fill = GridBagConstraints.BOTH
        self.gbcPanel0.weightx = 1
        self.gbcPanel0.weighty = 0
        self.gbcPanel0.anchor = GridBagConstraints.NORTH
        self.gbPanel0.setConstraints(self.min_file_size_TF, self.gbcPanel0)
        self.panel0.add(self.min_file_size_TF)

        self.blank_4_L = JLabel(" ")
        self.blank_4_L.setEnabled(True)
        self.gbcPanel0.gridx = 2
        self.gbcPanel0.gridy = 12
        self.gbcPanel0.gridwidth = 1
        self.gbcPanel0.gridheight = 1
        self.gbcPanel0.fill = GridBagConstraints.BOTH
        self.gbcPanel0.weightx = 1
        self.gbcPanel0.weighty = 0
        self.gbcPanel0.anchor = GridBagConstraints.NORTH
        self.gbPanel0.setConstraints(self.blank_4_L, self.gbcPanel0)
        self.panel0.add(self.blank_4_L)

        self.detectable_obejcts_BTN = \
            JButton("List of Objects to Detect", actionPerformed=self.show_detectable_objects_dialog)
        # self.save_Settings_BTN.setPreferredSize(Dimension(1, 20))
        self.rbgPanel0.add(self.detectable_obejcts_BTN)
        self.gbcPanel0.gridx = 0
        self.gbcPanel0.gridy = 13
        self.gbPanel0.setConstraints(self.detectable_obejcts_BTN,
                                     self.gbcPanel0)
        self.panel0.add(self.detectable_obejcts_BTN)

        self.blank_5_L = JLabel(" ")
        self.blank_5_L.setEnabled(True)
        self.gbcPanel0.gridx = 2
        self.gbcPanel0.gridy = 14
        self.gbcPanel0.gridwidth = 1
        self.gbcPanel0.gridheight = 1
        self.gbcPanel0.fill = GridBagConstraints.BOTH
        self.gbcPanel0.weightx = 1
        self.gbcPanel0.weighty = 0
        self.gbcPanel0.anchor = GridBagConstraints.NORTH
        self.gbPanel0.setConstraints(self.blank_5_L, self.gbcPanel0)
        self.panel0.add(self.blank_5_L)

        self.error_message = JLabel("", JLabel.CENTER)
        self.error_message.setForeground(Color.red)
        self.error_message.setEnabled(True)
        self.gbcPanel0.gridx = 0
        self.gbcPanel0.gridy = 15
        self.gbcPanel0.gridwidth = 1
        self.gbcPanel0.gridheight = 1
        self.gbcPanel0.fill = GridBagConstraints.BOTH
        self.gbcPanel0.weightx = 1
        self.gbcPanel0.weighty = 0
        self.gbcPanel0.anchor = GridBagConstraints.NORTH
        self.gbPanel0.setConstraints(self.error_message, self.gbcPanel0)
        self.panel0.add(self.error_message)

        self.message = JLabel("", JLabel.CENTER)
        self.message.setEnabled(True)
        self.gbcPanel0.gridx = 0
        self.gbcPanel0.gridy = 16
        self.gbcPanel0.gridwidth = 1
        self.gbcPanel0.gridheight = 1
        self.gbcPanel0.fill = GridBagConstraints.BOTH
        self.gbcPanel0.weightx = 1
        self.gbcPanel0.weighty = 0
        self.gbcPanel0.anchor = GridBagConstraints.NORTH
        self.gbPanel0.setConstraints(self.message, self.gbcPanel0)
        self.panel0.add(self.message)

        self.save_settings_BTN = JButton("Save Settings",
                                         actionPerformed=self.save_settings)
        # self.save_Settings_BTN.setPreferredSize(Dimension(1, 20))
        self.rbgPanel0.add(self.save_settings_BTN)
        self.gbcPanel0.gridx = 0
        self.gbcPanel0.gridy = 17
        self.gbPanel0.setConstraints(self.save_settings_BTN, self.gbcPanel0)
        self.panel0.add(self.save_settings_BTN)

        self.blank_6_L = JLabel(" ")
        self.blank_6_L.setEnabled(True)
        self.gbcPanel0.gridx = 2
        self.gbcPanel0.gridy = 18
        self.gbcPanel0.gridwidth = 1
        self.gbcPanel0.gridheight = 1
        self.gbcPanel0.fill = GridBagConstraints.BOTH
        self.gbcPanel0.weightx = 1
        self.gbcPanel0.weighty = 0
        self.gbcPanel0.anchor = GridBagConstraints.NORTH
        self.gbPanel0.setConstraints(self.blank_6_L, self.gbcPanel0)
        self.panel0.add(self.blank_6_L)

        self.blank_7_L = JLabel(" ")
        self.blank_7_L.setEnabled(True)
        self.gbcPanel0.gridx = 2
        self.gbcPanel0.gridy = 19
        self.gbcPanel0.gridwidth = 1
        self.gbcPanel0.gridheight = 1
        self.gbcPanel0.fill = GridBagConstraints.BOTH
        self.gbcPanel0.weightx = 1
        self.gbcPanel0.weighty = 0
        self.gbcPanel0.anchor = GridBagConstraints.NORTH
        self.gbPanel0.setConstraints(self.blank_7_L, self.gbcPanel0)
        self.panel0.add(self.blank_7_L)

        self.check_server_connection_BTN = \
            JButton("Check server connection", actionPerformed=self.check_server_connection)
        # self.save_Settings_BTN.setPreferredSize(Dimension(1, 20))
        self.rbgPanel0.add(self.check_server_connection_BTN)
        self.gbcPanel0.gridx = 0
        self.gbcPanel0.gridy = 20
        self.gbPanel0.setConstraints(self.check_server_connection_BTN,
                                     self.gbcPanel0)
        self.panel0.add(self.check_server_connection_BTN)

        self.blank_8_L = JLabel(" ")
        self.blank_8_L.setEnabled(True)
        self.gbcPanel0.gridx = 2
        self.gbcPanel0.gridy = 21
        self.gbcPanel0.gridwidth = 1
        self.gbcPanel0.gridheight = 1
        self.gbcPanel0.fill = GridBagConstraints.BOTH
        self.gbcPanel0.weightx = 1
        self.gbcPanel0.weighty = 0
        self.gbcPanel0.anchor = GridBagConstraints.NORTH
        self.gbPanel0.setConstraints(self.blank_8_L, self.gbcPanel0)
        self.panel0.add(self.blank_8_L)

        self.text_editor_BTN = \
            JButton("Open config file", actionPerformed=self.open_text_editor)
        # self.save_Settings_BTN.setPreferredSize(Dimension(1, 20))
        self.rbgPanel0.add(self.text_editor_BTN)
        self.gbcPanel0.gridx = 0
        self.gbcPanel0.gridy = 22
        self.gbPanel0.setConstraints(self.text_editor_BTN, self.gbcPanel0)
        self.panel0.add(self.text_editor_BTN)

        self.add(self.panel0)
예제 #16
0
	def initUI(self):
		'''Initial UI and Widget creation takes place here!
		'''
		self.setContentPane = JPanel()
		#self.setDefaultLookAndFeelDecorated(True)
		#  Borders
		foreground_colour = Color(30,57,68)
		background_colour = Color(247,246,242)
		window_background = Color(145,190,210)
		self.border = BorderFactory.createLoweredBevelBorder()
		self.border2 = BorderFactory.createLineBorder(foreground_colour, 1, True)
		#  Fonts
		self.entry_font= Font("Ubuntu Light",  Font.BOLD, 20)
		self.label_font= Font("Ubuntu Light",  Font.BOLD, 17)
		self.btn_font=Font("Ubuntu Light", Font.BOLD, 15)
		#  Layout start
		layout=GroupLayout(self.getContentPane())
		self.getContentPane().setLayout(layout)	
		layout.setAutoCreateGaps(True)
		layout.setAutoCreateContainerGaps(True)
		self.setPreferredSize(Dimension(300, 150))
		#  Create the labels
		user_label= JLabel(" Username : "******"  Server  : ", JLabel.LEFT, font=self.label_font)
				
		#  Colours
		user_label.setForeground(foreground_colour)
		server_label.setForeground(foreground_colour)
		
		#  Create the text entries
		self.username=JTextField(actionPerformed=self.continueEvent, border=self.border2,  font = self.entry_font)
		self.server=JTextField(actionPerformed=self.continueEvent, border=self.border2,  font = self.entry_font)
		
		#  Colours
		self.username.setBackground(background_colour)
		self.server.setBackground(background_colour)
		self.username.setForeground(foreground_colour)
		self.server.setForeground(foreground_colour)
		
		#  Allow editable
		self.username.setEditable(True)
		self.server.setEditable(True)
		
		#  Create the buttons
		quit_btn=JButton("  Quit!  ", actionPerformed=self.closeEvent, border=self.border2, font=self.btn_font)
		go_btn=JButton("   Go!   ", actionPerformed=self.continueEvent, border=self.border2, font=self.btn_font)
		#  Colours
		quit_btn.setBackground(background_colour)
		go_btn.setBackground(background_colour)
		quit_btn.setForeground(foreground_colour)
		go_btn.setForeground(foreground_colour)
		
		#  Setting up the horizontal groups parameters
		layout.setHorizontalGroup(layout.createSequentialGroup()
		
			#  Left side
			.addGroup(layout.createParallelGroup(GroupLayout.Alignment.TRAILING)
				.addComponent(user_label)
				.addComponent(server_label))
				
			#  Right side
			.addGroup(layout.createParallelGroup(GroupLayout.Alignment.CENTER)
				.addComponent(self.username)
				.addComponent(self.server)
				.addGroup(layout.createSequentialGroup()
					.addComponent(quit_btn)
					.addComponent(go_btn)))
		)
		
		#  Setting up Vertical Groups
		layout.setVerticalGroup(layout.createSequentialGroup()
			#  Top group
			.addGroup(layout.createParallelGroup(GroupLayout.Alignment.CENTER)
				.addComponent(user_label)
				.addComponent(self.username))
			#  Middle group
			.addGroup(layout.createParallelGroup(GroupLayout.Alignment.CENTER)
				.addComponent(server_label)
				.addComponent(self.server))
			#  Bottom group
			.addGroup(layout.createParallelGroup()
				.addComponent(quit_btn)
				.addComponent(go_btn))
		)
		
		#  Finalise the GUI	
		layout.linkSize(SwingConstants.HORIZONTAL, [quit_btn,go_btn])
		self.getContentPane().setBackground(window_background)
		self.pack()
		self.setTitle('Chat Login')
		self.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
		self.setLocationRelativeTo(None)
		self.setVisible(True)
예제 #17
0
    def initComponents(self):
        TabbedPane1 = JTabbedPane()
        GeneratorScrollPane = JScrollPane()
        GeneratorPanel = JPanel()
        jlbl1 = JLabel()
        jlbl2 = JLabel()
        spanePayloadList = JScrollPane()
        self.listPayloads = JList()
        pastePayloadButton = JButton(
            actionPerformed=self.pastePayloadButtonAction)
        loadPayloadButton = JButton(
            actionPerformed=self.loadPayloadButtonAction)
        removePayloadButton = JButton(
            actionPerformed=self.removePayloadButtonAction)
        clearPayloadButton = JButton(
            actionPerformed=self.clearPayloadButtonAction)
        self.textNewPayload = JTextField()
        addPayloadButton = JButton(actionPerformed=self.addPayloadButtonAction)
        jSeparator1 = JSeparator()
        jlbl3 = JLabel()
        jlbl4 = JLabel()
        self.chkGeneral = JCheckBox(actionPerformed=self.OnCheck)
        self.chkMAXDB = JCheckBox(actionPerformed=self.OnCheck)
        self.chkMSSQL = JCheckBox(actionPerformed=self.OnCheck)
        self.chkMSAccess = JCheckBox(actionPerformed=self.OnCheck)
        self.chkPostgres = JCheckBox(actionPerformed=self.OnCheck)
        self.chkOracle = JCheckBox(actionPerformed=self.OnCheck)
        self.chkSqlite = JCheckBox(actionPerformed=self.OnCheck)
        self.chkMysql = JCheckBox(actionPerformed=self.OnCheck)
        jlbl5 = JLabel()
        toClipboardButton = JButton(
            actionPerformed=self.toClipboardButtonAction)
        toFileButton = JButton(actionPerformed=self.toFileButtonAction)
        ProcessorScrollPane = JScrollPane()
        ProcessorPanel = JPanel()
        jLabel1 = JLabel()
        self.comboProcessorTech = JComboBox(
            itemStateChanged=self.comboProcessorTechAction)
        jSeparator2 = JSeparator()
        jLabel2 = JLabel()
        jLabel3 = JLabel()
        jScrollPane1 = JScrollPane()
        self.textPlainPayload = JTextArea()
        jLabel4 = JLabel()
        jScrollPane2 = JScrollPane()
        self.textTamperedPayload = JTextArea()
        tamperPayloadButton = JButton(
            actionPerformed=self.tamperPayloadButtonAction)

        jlbl1.setForeground(Color(255, 102, 51))
        jlbl1.setFont(Font(jlbl1.getFont().toString(), 1, 14))
        jlbl1.setText("User-Defiend Payloads")

        jlbl2.setText(
            "This payload type lets you configure a simple list of strings that are used as payloads."
        )

        spanePayloadList.setViewportView(self.listPayloads)
        self.extender.PayloadList = self.readPayloadsListFile()
        self.listPayloads.setListData(self.extender.PayloadList)

        pastePayloadButton.setText("Paste")

        loadPayloadButton.setText("Load")

        removePayloadButton.setText("Remove")

        clearPayloadButton.setText("Clear")

        self.textNewPayload.setToolTipText("")

        addPayloadButton.setText("Add")

        jlbl3.setForeground(Color(255, 102, 51))
        jlbl3.setFont(Font(jlbl3.getFont().toString(), 1, 14))
        jlbl3.setText("Tamper Techniques")

        jlbl4.setText(
            "You can select the techniques that you want to perform processing tasks on each user-defined payload"
        )

        self.chkGeneral.setText("General")
        varName = 'SQLiQueryTampering_{}'.format(self.chkGeneral.text)
        state = self.extender.callbacks.loadExtensionSetting(varName)
        if state: self.chkGeneral.setSelected(int(state))

        self.chkMAXDB.setText("SAP MAX DB")
        varName = 'SQLiQueryTampering_{}'.format(self.chkMAXDB.text)
        state = self.extender.callbacks.loadExtensionSetting(varName)
        if state: self.chkMAXDB.setSelected(int(state))

        self.chkMSSQL.setText("MS SQL Server")
        varName = 'SQLiQueryTampering_{}'.format(self.chkMSSQL.text)
        state = self.extender.callbacks.loadExtensionSetting(varName)
        if state: self.chkMSSQL.setSelected(int(state))

        self.chkMSAccess.setText("MS Access")
        varName = 'SQLiQueryTampering_{}'.format(self.chkMSAccess.text)
        state = self.extender.callbacks.loadExtensionSetting(varName)
        if state: self.chkMSAccess.setSelected(int(state))

        self.chkPostgres.setText("Postgres SQL")
        varName = 'SQLiQueryTampering_{}'.format(self.chkPostgres.text)
        state = self.extender.callbacks.loadExtensionSetting(varName)
        if state: self.chkPostgres.setSelected(int(state))

        self.chkOracle.setText("Oracle")
        varName = 'SQLiQueryTampering_{}'.format(self.chkOracle.text)
        state = self.extender.callbacks.loadExtensionSetting(varName)
        if state: self.chkOracle.setSelected(int(state))

        self.chkSqlite.setText("Sqlite")
        varName = 'SQLiQueryTampering_{}'.format(self.chkSqlite.text)
        state = self.extender.callbacks.loadExtensionSetting(varName)
        if state: self.chkSqlite.setSelected(int(state))

        self.chkMysql.setText("MySql")
        varName = 'SQLiQueryTampering_{}'.format(self.chkMysql.text)
        state = self.extender.callbacks.loadExtensionSetting(varName)
        if state: self.chkMysql.setSelected(int(state))

        jlbl5.setText("[?] Save the Generated/Tampered Payloads to :")

        toClipboardButton.setText("Clipboard")

        toFileButton.setText("File")

        GeneratorPanelLayout = GroupLayout(GeneratorPanel)
        GeneratorPanel.setLayout(GeneratorPanelLayout)
        GeneratorPanelLayout.setHorizontalGroup(
            GeneratorPanelLayout.createParallelGroup(
                GroupLayout.Alignment.LEADING).
            addGroup(GeneratorPanelLayout.createSequentialGroup(
            ).addContainerGap().addGroup(
                GeneratorPanelLayout.createParallelGroup(
                    GroupLayout.Alignment.TRAILING).addComponent(
                        jlbl2, GroupLayout.DEFAULT_SIZE,
                        GroupLayout.DEFAULT_SIZE,
                        Short.MAX_VALUE).addComponent(
                            jlbl4, GroupLayout.Alignment.LEADING,
                            GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE,
                            Short.MAX_VALUE).addComponent(
                                jSeparator1, GroupLayout.Alignment.LEADING).
                addGroup(GeneratorPanelLayout.createSequentialGroup().addGap(
                    6, 6, 6).addGroup(
                        GeneratorPanelLayout.createParallelGroup(
                            GroupLayout.Alignment.LEADING).addGroup(
                                GeneratorPanelLayout.createSequentialGroup(
                                ).addGroup(
                                    GeneratorPanelLayout.createParallelGroup(
                                        GroupLayout.Alignment.LEADING,
                                        False).addComponent(
                                            removePayloadButton,
                                            GroupLayout.DEFAULT_SIZE,
                                            GroupLayout.DEFAULT_SIZE,
                                            Short.MAX_VALUE).addComponent(
                                                clearPayloadButton,
                                                GroupLayout.DEFAULT_SIZE,
                                                GroupLayout.DEFAULT_SIZE,
                                                Short.MAX_VALUE).addComponent(
                                                    loadPayloadButton,
                                                    GroupLayout.DEFAULT_SIZE,
                                                    GroupLayout.DEFAULT_SIZE,
                                                    Short.MAX_VALUE).
                                    addComponent(pastePayloadButton,
                                                 GroupLayout.DEFAULT_SIZE,
                                                 GroupLayout.DEFAULT_SIZE,
                                                 Short.MAX_VALUE).addComponent(
                                                     addPayloadButton,
                                                     GroupLayout.DEFAULT_SIZE,
                                                     GroupLayout.DEFAULT_SIZE,
                                                     Short.MAX_VALUE)).
                                addGap(21, 21, 21).addGroup(
                                    GeneratorPanelLayout.createParallelGroup(
                                        GroupLayout.Alignment.LEADING).
                                    addComponent(
                                        self.textNewPayload).addComponent(
                                            spanePayloadList))).addComponent(
                                                jlbl1).addComponent(jlbl3).
                        addGroup(GeneratorPanelLayout.createSequentialGroup(
                        ).addGroup(
                            GeneratorPanelLayout.createParallelGroup(
                                GroupLayout.Alignment.LEADING).addComponent(
                                    self.chkGeneral).addComponent(
                                        self.chkMSSQL)
                        ).addGap(18, 18, 18).addGroup(
                            GeneratorPanelLayout.createParallelGroup(
                                GroupLayout.Alignment.LEADING).addComponent(
                                    self.chkPostgres).addComponent(
                                        self.chkMAXDB)
                        ).addGap(18, 18, 18).addGroup(
                            GeneratorPanelLayout.createParallelGroup(
                                GroupLayout.Alignment.LEADING).addComponent(
                                    self.chkMSAccess).addComponent(
                                        self.chkOracle)
                        ).addGap(18, 18, 18).addGroup(
                            GeneratorPanelLayout.createParallelGroup(
                                GroupLayout.Alignment.LEADING).addComponent(
                                    self.chkSqlite).addComponent(self.chkMysql)
                        )).addGroup(GeneratorPanelLayout.createSequentialGroup(
                        ).addComponent(jlbl5).addPreferredGap(
                            LayoutStyle.ComponentPlacement.
                            UNRELATED).addComponent(toClipboardButton).addGap(
                                18, 18,
                                18).addComponent(toFileButton,
                                                 GroupLayout.PREFERRED_SIZE,
                                                 97, GroupLayout.PREFERRED_SIZE
                                                 ))))).addContainerGap()))
        GeneratorPanelLayout.setVerticalGroup(
            GeneratorPanelLayout.createParallelGroup(
                GroupLayout.Alignment.LEADING).
            addGroup(GeneratorPanelLayout.createSequentialGroup(
            ).addContainerGap().addComponent(jlbl1).addPreferredGap(
                LayoutStyle.ComponentPlacement.RELATED).addComponent(
                    jlbl2, GroupLayout.PREFERRED_SIZE, 21,
                    GroupLayout.PREFERRED_SIZE).addGap(18, 18, 18).addGroup(
                        GeneratorPanelLayout.createParallelGroup(
                            GroupLayout.Alignment.LEADING).addComponent(
                                spanePayloadList, GroupLayout.PREFERRED_SIZE,
                                GroupLayout.DEFAULT_SIZE,
                                GroupLayout.PREFERRED_SIZE).
                        addGroup(GeneratorPanelLayout.createSequentialGroup(
                        ).addComponent(pastePayloadButton).addPreferredGap(
                            LayoutStyle.ComponentPlacement.RELATED
                        ).addComponent(loadPayloadButton).addPreferredGap(
                            LayoutStyle.ComponentPlacement.RELATED
                        ).addComponent(removePayloadButton).addPreferredGap(
                            LayoutStyle.ComponentPlacement.RELATED).
                                 addComponent(clearPayloadButton))).
                     addPreferredGap(
                         LayoutStyle.ComponentPlacement.RELATED).addGroup(
                             GeneratorPanelLayout.createParallelGroup(
                                 GroupLayout.Alignment.BASELINE).addComponent(
                                     self.textNewPayload,
                                     GroupLayout.PREFERRED_SIZE,
                                     GroupLayout.DEFAULT_SIZE,
                                     GroupLayout.PREFERRED_SIZE).
                             addComponent(addPayloadButton)).addPreferredGap(
                                 LayoutStyle.ComponentPlacement.UNRELATED).
                     addComponent(jSeparator1, GroupLayout.PREFERRED_SIZE, 10,
                                  GroupLayout.PREFERRED_SIZE).addPreferredGap(
                                      LayoutStyle.ComponentPlacement.RELATED).
                     addComponent(jlbl3).addPreferredGap(
                         LayoutStyle.ComponentPlacement.UNRELATED
                     ).addComponent(jlbl4).addPreferredGap(
                         LayoutStyle.ComponentPlacement.UNRELATED).addGroup(
                             GeneratorPanelLayout.createParallelGroup(
                                 GroupLayout.Alignment.BASELINE).addComponent(
                                     self.chkGeneral).addComponent(
                                         self.chkMAXDB).addComponent(
                                             self.chkOracle).addComponent(
                                                 self.chkSqlite)).
                     addPreferredGap(
                         LayoutStyle.ComponentPlacement.UNRELATED).addGroup(
                             GeneratorPanelLayout.createParallelGroup(
                                 GroupLayout.Alignment.BASELINE).addComponent(
                                     self.chkMSSQL).addComponent(
                                         self.chkPostgres).addComponent(
                                             self.chkMSAccess).addComponent(
                                                 self.chkMysql)
                         ).addGap(18, 18, 18).addGroup(
                             GeneratorPanelLayout.createParallelGroup(
                                 GroupLayout.Alignment.BASELINE).addComponent(
                                     jlbl5).addComponent(toClipboardButton).
                             addComponent(toFileButton)).addGap(20, 20, 20)))

        GeneratorScrollPane.setViewportView(GeneratorPanel)

        TabbedPane1.addTab("Generator", GeneratorScrollPane)

        varName = 'SQLiQueryTampering_comboProcessorTech'
        state = self.extender.callbacks.loadExtensionSetting(varName)

        for item in self.extender.getTamperFuncsName():
            self.comboProcessorTech.addItem(item)

        if state: self.comboProcessorTech.setSelectedIndex(int(state))

        jLabel1.setText("Processor Technique :")

        jLabel2.setText(
            "Modify Plain Payloads based on the selected Processor Technique. Write one payload per line."
        )

        jLabel3.setText("Plain Payloads:")

        self.textPlainPayload.setColumns(20)
        self.textPlainPayload.setRows(5)
        jScrollPane1.setViewportView(self.textPlainPayload)

        jLabel4.setText("Tampered Payloads:")

        self.textTamperedPayload.setColumns(20)
        self.textTamperedPayload.setRows(5)
        jScrollPane2.setViewportView(self.textTamperedPayload)

        tamperPayloadButton.setText("Tamper Payloads")

        ProcessorPanelLayout = GroupLayout(ProcessorPanel)
        ProcessorPanel.setLayout(ProcessorPanelLayout)
        ProcessorPanelLayout.setHorizontalGroup(
            ProcessorPanelLayout.
            createParallelGroup(GroupLayout.Alignment.LEADING).addGroup(
                GroupLayout.Alignment.TRAILING,
                ProcessorPanelLayout.createSequentialGroup().addContainerGap(
                    GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE).addComponent(
                        tamperPayloadButton).addContainerGap(
                            GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            ).addGroup(ProcessorPanelLayout.createSequentialGroup(
            ).addContainerGap().addGroup(
                ProcessorPanelLayout.createParallelGroup(
                    GroupLayout.Alignment.LEADING).addComponent(jSeparator2).
                addComponent(jScrollPane1).addComponent(jScrollPane2).addGroup(
                    ProcessorPanelLayout.createSequentialGroup().addGroup(
                        ProcessorPanelLayout.createParallelGroup(
                            GroupLayout.Alignment.LEADING).addComponent(
                                jLabel3).addComponent(jLabel4).addGroup(
                                    ProcessorPanelLayout.createSequentialGroup(
                                    ).addComponent(jLabel1).addPreferredGap(
                                        LayoutStyle.ComponentPlacement.
                                        UNRELATED).addComponent(
                                            self.comboProcessorTech,
                                            GroupLayout.PREFERRED_SIZE, 286,
                                            GroupLayout.PREFERRED_SIZE)).
                        addComponent(jLabel2)).addGap(
                            0, 78, Short.MAX_VALUE))).addContainerGap()))
        ProcessorPanelLayout.setVerticalGroup(
            ProcessorPanelLayout.createParallelGroup(
                GroupLayout.Alignment.LEADING).addGroup(
                    ProcessorPanelLayout.createSequentialGroup().addGap(
                        33, 33, 33).addGroup(
                            ProcessorPanelLayout.createParallelGroup(
                                GroupLayout.Alignment.BASELINE).
                            addComponent(jLabel1).addComponent(
                                self.comboProcessorTech,
                                GroupLayout.PREFERRED_SIZE,
                                GroupLayout.DEFAULT_SIZE,
                                GroupLayout.PREFERRED_SIZE)).addGap(
                                    18, 18, 18).addComponent(
                                        jSeparator2,
                                        GroupLayout.PREFERRED_SIZE, 10,
                                        GroupLayout.PREFERRED_SIZE).addGap(
                                            12, 12,
                                            12).addComponent(jLabel2).addGap(
                                                18, 18, 18).
                    addComponent(jLabel3).addPreferredGap(
                        LayoutStyle.ComponentPlacement.UNRELATED).addComponent(
                            jScrollPane1, GroupLayout.PREFERRED_SIZE,
                            GroupLayout.DEFAULT_SIZE,
                            GroupLayout.PREFERRED_SIZE).addPreferredGap(
                                LayoutStyle.ComponentPlacement.UNRELATED).
                    addComponent(jLabel4).addPreferredGap(
                        LayoutStyle.ComponentPlacement.UNRELATED).addComponent(
                            jScrollPane2, GroupLayout.PREFERRED_SIZE,
                            GroupLayout.DEFAULT_SIZE,
                            GroupLayout.PREFERRED_SIZE).addPreferredGap(
                                LayoutStyle.ComponentPlacement.UNRELATED).
                    addComponent(tamperPayloadButton).addGap(36, 36, 36)))

        ProcessorScrollPane.setViewportView(ProcessorPanel)

        TabbedPane1.addTab("Processor", ProcessorScrollPane)

        self.mainPanel = JPanel()
        layout = GroupLayout(self.mainPanel)
        self.mainPanel.setLayout(layout)
        layout.setHorizontalGroup(
            layout.createParallelGroup(
                GroupLayout.Alignment.LEADING).addComponent(
                    TabbedPane1, GroupLayout.DEFAULT_SIZE, 701,
                    Short.MAX_VALUE))
        layout.setVerticalGroup(
            layout.createParallelGroup(
                GroupLayout.Alignment.LEADING).addComponent(TabbedPane1))

        TabbedPane1.getAccessibleContext().setAccessibleName("Generator")
예제 #18
0
class BurpExtender(IBurpExtender, ITab, IIntruderPayloadProcessor,
                   IIntruderPayloadGeneratorFactory):

    # Tool details
    TITLE = 'Password Spray'
    AUTHOR = '0xZDH'
    VERSION = 'v1.0.0'
    DESC = 'This extension allows a user to specify a lockout policy in order to automate a password spray attack via Intruder.'

    # Global variables
    filename = ''  # Password file
    lockout_attempts = 0  # Number of current passwords attempts

    # This will log to the current folder this extension is located within because
    # I didn't feel like checking the OS and specifying the log locations for each.
    logger = logging.getLogger()
    handler = RotatingFileHandler('password_spray.log',
                                  maxBytes=10**5,
                                  backupCount=2)
    logger.addHandler(handler)
    """ Implement IBurpExtender  """
    def registerExtenderCallbacks(self, callbacks):
        self._callbacks = callbacks
        self._helpers = self._callbacks.getHelpers()
        self._callbacks.setExtensionName(self.TITLE)
        self._callbacks.registerIntruderPayloadGeneratorFactory(self)
        self._callbacks.registerIntruderPayloadProcessor(self)

        self.initTab()  # Load Burp tab
        self._callbacks.addSuiteTab(self)

        print('Name: \t\t' + self.TITLE)
        print('Author: \t' + self.AUTHOR)
        print('Version: \t' + self.VERSION)
        print('Description: \t' + self.DESC)
        print('\n[+] Extension loaded.')

    """ Implement ITab """

    def getTabCaption(self):
        return self.TITLE

    def getUiComponent(self):
        return self.tab

    """ Implement IIntruderPayloadGeneratorFactory """

    def getGeneratorName(self):
        return self.TITLE

    def createNewInstance(self, attack):
        self.lockout_attempts = 0  # Reset the number of lockout attempts for each new attack
        return IntruderPayloadGenerator(self.filename)

    """ Implement IIntruderPayloadProcessor """

    def getProcessorName(self):
        return self.TITLE

    """ This function sleeps inbetween attempt cycles. If the attack is exited prior to finishing,
        there are payloads held in memory that are equal to the number of intruder threads running.
        The payloads in memory do not get purged when an attack is exited which means they will go
        be sent once the sleep method has concluded. These paylaods that are sent after an attack
        has been exited can effect the lockout reset time for specific users.

        It is recommended that the Logger++ extension is used to identify which and when were the last
        usernames/passwords attempted to allow for a proper wait time before continuing again. """

    def processPayload(self, currentPayload, originalPayload, baseValue):
        if (self.lockout_attempts >= int(self.attemptField.text)):
            self.lockout_attempts = 0  # Reset lockout count before we run the next iteration
            sleep(float(self.lockoutField.text) * 60)

        # Only increment the lockout attempts counter right before we send the payload
        self.lockout_attempts += 1

        # Write to the log file: [timestamp] password
        self.log(currentPayload)

        # Return the current, unmodified payload
        return currentPayload

    """ Build the Burp tab layout """

    def initTab(self):

        self.tab = JPanel()

        self.titleLabel = JLabel(self.TITLE)
        self.titleLabel.setFont(Font('Tahoma', 1, 15))
        self.titleLabel.setForeground(Color(255, 102,
                                            51))  # Set to Burp-like orange

        self.infoLabel = JLabel(
            'Specify the lockout policy of the target: Number of login attempts that won\'t lock out an account '
            'and the time to wait for the lockout threshold to reset.')
        self.infoLabel.setFont(Font('Tahoma', 0, 12))

        self.attemptLabel = JLabel('Number of attempts:')
        self.attemptField = JTextField('3', 15)  # Default to 3

        self.lockoutLabel = JLabel('Lockout reset time (minutes):')
        self.lockoutField = JTextField('5', 15)  # Default to 5

        self.fileButton = JButton('Password File',
                                  actionPerformed=self.getPasswordFile)
        self.fileLabel = JLabel('')

        self.setUpa = JLabel('Intruder Set Up:')
        self.setUpa.setFont(Font('Tahoma', 1, 12))

        self.setUpba = JLabel('    Intruder Attacker Type:')
        self.setUpbb = JLabel('Cluster Bomb')
        self.setUpca = JLabel('    Payload Set 1 Type:')
        self.setUpcb = JLabel('Simple List')
        self.setUpda = JLabel('    Payload Set 1 Options:')
        self.setUpdb = JLabel(
            'Load -> File containing list of emails/users to spray')
        self.setUpea = JLabel('    Payload Set 2 Type:')
        self.setUpeb = JLabel('Extension-generated')
        self.setUpfa = JLabel('    Payload Set 2 Options:')
        self.setUpfb = JLabel(
            'Select generator -> Extension payload generator -> %s' %
            self.TITLE)
        self.setUpga = JLabel('    Payload Set 2 Processing:')
        self.setUpgb = JLabel(
            'Add -> Invoke Burp Extension -> Select processor -> %s' %
            self.TITLE)

        # Build warning for users to understand
        self.warningLabela = JLabel('*** WARNING ***')
        self.warningLabela.setFont(Font('Tahoma', 1, 15))

        self.warningLabelba = JLabel(
            'If an Intruder attack is is exited prior to finishing, there will still be payloads held in memory that are equal to'
        )
        self.warningLabelbb = JLabel(
            'the number of intruder threads running. The payloads stored in memory do not get removed when an attack is exited.'
        )
        self.warningLabelbc = JLabel(
            'Payloads in memory will be sent once their sleep functions have concluded (based on user-defined \'lockout timer\').'
        )
        self.warningLabelbd = JLabel(
            'These paylaods that are sent after an attack has been exited effects the lockout reset time.'
        )

        self.warningLabelca = JLabel(
            'It is recommended that the Logger++ extension is used to identify which and when were the last usernames/passwords'
        )
        self.warningLabelcb = JLabel(
            'attempted following the sleep function to allow for a proper wait time before continuing again.'
        )

        self.warningLabelda = JLabel(
            'If exited prematurely, Before running a new attack, wait at least the time specified via \'Lockout reset time\''
        )
        self.warningLabeldb = JLabel(
            'to identify the last sent password attempt, then wait the same time limit again to fully reset the lockout timer.'
        )

        layout = GroupLayout(self.tab)
        self.tab.setLayout(layout)

        # Reference: https://github.com/SmeegeSec/Burp-Importer
        # Definitely a cleaner way to do this, but not optimizing since its just UI code - and Java...
        layout.setHorizontalGroup(
            layout.createParallelGroup(GroupLayout.Alignment.LEADING).addGroup(
                layout.createSequentialGroup().addGap(15).addGroup(
                    layout.createParallelGroup(
                        GroupLayout.Alignment.LEADING).addComponent(
                            self.titleLabel).addComponent(self.infoLabel).
                    addGroup(layout.createSequentialGroup().addGroup(
                        layout.createParallelGroup(
                            GroupLayout.Alignment.TRAILING).addComponent(
                                self.attemptLabel, GroupLayout.PREFERRED_SIZE,
                                200, GroupLayout.PREFERRED_SIZE)
                    ).addPreferredGap(
                        LayoutStyle.ComponentPlacement.UNRELATED).addGroup(
                            layout.createParallelGroup(
                                GroupLayout.Alignment.LEADING).addComponent(
                                    self.attemptField,
                                    GroupLayout.PREFERRED_SIZE, 150,
                                    GroupLayout.PREFERRED_SIZE))).
                    addGroup(layout.createSequentialGroup().addGroup(
                        layout.createParallelGroup(
                            GroupLayout.Alignment.TRAILING).addComponent(
                                self.lockoutLabel, GroupLayout.PREFERRED_SIZE,
                                200, GroupLayout.PREFERRED_SIZE)
                    ).addPreferredGap(
                        LayoutStyle.ComponentPlacement.UNRELATED).addGroup(
                            layout.createParallelGroup(
                                GroupLayout.Alignment.LEADING).addComponent(
                                    self.lockoutField,
                                    GroupLayout.PREFERRED_SIZE, 150,
                                    GroupLayout.PREFERRED_SIZE))).
                    addGroup(layout.createSequentialGroup().addGroup(
                        layout.createParallelGroup(
                            GroupLayout.Alignment.TRAILING).addComponent(
                                self.fileButton, GroupLayout.PREFERRED_SIZE,
                                150, GroupLayout.PREFERRED_SIZE)
                    ).addPreferredGap(
                        LayoutStyle.ComponentPlacement.UNRELATED).addGroup(
                            layout.createParallelGroup(
                                GroupLayout.Alignment.LEADING).addComponent(
                                    self.fileLabel, GroupLayout.PREFERRED_SIZE,
                                    400, GroupLayout.PREFERRED_SIZE)
                        )).addGroup(layout.createSequentialGroup().addGroup(
                            layout.createParallelGroup(
                                GroupLayout.Alignment.TRAILING).addComponent(
                                    self.setUpa, GroupLayout.PREFERRED_SIZE,
                                    150, GroupLayout.PREFERRED_SIZE))).
                    addGroup(layout.createSequentialGroup().addGroup(
                        layout.createParallelGroup(
                            GroupLayout.Alignment.TRAILING).addComponent(
                                self.setUpba, GroupLayout.PREFERRED_SIZE, 210,
                                GroupLayout.PREFERRED_SIZE)
                    ).addPreferredGap(
                        LayoutStyle.ComponentPlacement.UNRELATED).addGroup(
                            layout.createParallelGroup(
                                GroupLayout.Alignment.LEADING).addComponent(
                                    self.setUpbb, GroupLayout.PREFERRED_SIZE,
                                    350, GroupLayout.PREFERRED_SIZE))).
                    addGroup(layout.createSequentialGroup().addGroup(
                        layout.createParallelGroup(
                            GroupLayout.Alignment.TRAILING).addComponent(
                                self.setUpca, GroupLayout.PREFERRED_SIZE, 210,
                                GroupLayout.PREFERRED_SIZE)
                    ).addPreferredGap(
                        LayoutStyle.ComponentPlacement.UNRELATED).addGroup(
                            layout.createParallelGroup(
                                GroupLayout.Alignment.LEADING).addComponent(
                                    self.setUpcb, GroupLayout.PREFERRED_SIZE,
                                    350, GroupLayout.PREFERRED_SIZE))).
                    addGroup(layout.createSequentialGroup().addGroup(
                        layout.createParallelGroup(
                            GroupLayout.Alignment.TRAILING).addComponent(
                                self.setUpda, GroupLayout.PREFERRED_SIZE, 210,
                                GroupLayout.PREFERRED_SIZE)
                    ).addPreferredGap(
                        LayoutStyle.ComponentPlacement.UNRELATED).addGroup(
                            layout.createParallelGroup(
                                GroupLayout.Alignment.LEADING).addComponent(
                                    self.setUpdb, GroupLayout.PREFERRED_SIZE,
                                    350, GroupLayout.PREFERRED_SIZE))).
                    addGroup(layout.createSequentialGroup().addGroup(
                        layout.createParallelGroup(
                            GroupLayout.Alignment.TRAILING).addComponent(
                                self.setUpea, GroupLayout.PREFERRED_SIZE, 210,
                                GroupLayout.PREFERRED_SIZE)
                    ).addPreferredGap(
                        LayoutStyle.ComponentPlacement.UNRELATED).addGroup(
                            layout.createParallelGroup(
                                GroupLayout.Alignment.LEADING).addComponent(
                                    self.setUpeb, GroupLayout.PREFERRED_SIZE,
                                    350, GroupLayout.PREFERRED_SIZE))).
                    addGroup(layout.createSequentialGroup().addGroup(
                        layout.createParallelGroup(
                            GroupLayout.Alignment.TRAILING).addComponent(
                                self.setUpfa, GroupLayout.PREFERRED_SIZE, 210,
                                GroupLayout.PREFERRED_SIZE)
                    ).addPreferredGap(
                        LayoutStyle.ComponentPlacement.UNRELATED).addGroup(
                            layout.createParallelGroup(
                                GroupLayout.Alignment.LEADING).addComponent(
                                    self.setUpfb, GroupLayout.PREFERRED_SIZE,
                                    500, GroupLayout.PREFERRED_SIZE))).
                    addGroup(layout.createSequentialGroup().addGroup(
                        layout.createParallelGroup(
                            GroupLayout.Alignment.TRAILING).addComponent(
                                self.setUpga, GroupLayout.PREFERRED_SIZE, 210,
                                GroupLayout.PREFERRED_SIZE)
                    ).addPreferredGap(
                        LayoutStyle.ComponentPlacement.UNRELATED).addGroup(
                            layout.createParallelGroup(
                                GroupLayout.Alignment.LEADING).addComponent(
                                    self.setUpgb, GroupLayout.PREFERRED_SIZE,
                                    500, GroupLayout.PREFERRED_SIZE)))
                    # Add warning label
                    .addGroup(layout.createSequentialGroup().addGroup(
                        layout.createParallelGroup(
                            GroupLayout.Alignment.TRAILING).addComponent(
                                self.warningLabela, GroupLayout.PREFERRED_SIZE,
                                150, GroupLayout.PREFERRED_SIZE)))
                    # Add first warning text
                    .addGroup(layout.createSequentialGroup().addGroup(
                        layout.createParallelGroup(
                            GroupLayout.Alignment.TRAILING).addComponent(
                                self.warningLabelba,
                                GroupLayout.PREFERRED_SIZE, 750,
                                GroupLayout.PREFERRED_SIZE)
                    )).addGroup(layout.createSequentialGroup().addGroup(
                        layout.createParallelGroup(
                            GroupLayout.Alignment.TRAILING).addComponent(
                                self.warningLabelbb,
                                GroupLayout.PREFERRED_SIZE, 750,
                                GroupLayout.PREFERRED_SIZE)
                    )).addGroup(layout.createSequentialGroup().addGroup(
                        layout.createParallelGroup(
                            GroupLayout.Alignment.TRAILING).addComponent(
                                self.warningLabelbc,
                                GroupLayout.PREFERRED_SIZE, 750,
                                GroupLayout.PREFERRED_SIZE)
                    )).addGroup(layout.createSequentialGroup().addGroup(
                        layout.createParallelGroup(
                            GroupLayout.Alignment.TRAILING).addComponent(
                                self.warningLabelbd,
                                GroupLayout.PREFERRED_SIZE, 750,
                                GroupLayout.PREFERRED_SIZE)))
                    # Add second warning text
                    .addGroup(layout.createSequentialGroup().addGroup(
                        layout.createParallelGroup(
                            GroupLayout.Alignment.TRAILING).addComponent(
                                self.warningLabelca,
                                GroupLayout.PREFERRED_SIZE, 750,
                                GroupLayout.PREFERRED_SIZE)
                    )).addGroup(layout.createSequentialGroup().addGroup(
                        layout.createParallelGroup(
                            GroupLayout.Alignment.TRAILING).addComponent(
                                self.warningLabelcb,
                                GroupLayout.PREFERRED_SIZE, 750,
                                GroupLayout.PREFERRED_SIZE)))
                    # Add third warning text
                    .addGroup(layout.createSequentialGroup().addGroup(
                        layout.createParallelGroup(
                            GroupLayout.Alignment.TRAILING).addComponent(
                                self.warningLabelda,
                                GroupLayout.PREFERRED_SIZE, 750,
                                GroupLayout.PREFERRED_SIZE)
                    )).addGroup(layout.createSequentialGroup().addGroup(
                        layout.createParallelGroup(
                            GroupLayout.Alignment.TRAILING).addComponent(
                                self.warningLabeldb,
                                GroupLayout.PREFERRED_SIZE, 750,
                                GroupLayout.PREFERRED_SIZE))))))

        layout.setVerticalGroup(
            layout.createParallelGroup(GroupLayout.Alignment.LEADING).addGroup(
                layout.createSequentialGroup().addGap(15).addComponent(
                    self.titleLabel).addGap(10).addComponent(self.infoLabel).
                addGroup(
                    layout.createParallelGroup(GroupLayout.Alignment.LEADING).
                    addGroup(
                        layout.createSequentialGroup().addGap(25).addGroup(
                            layout.createParallelGroup(
                                GroupLayout.Alignment.BASELINE).addComponent(
                                    self.attemptLabel).addComponent(
                                        self.attemptField,
                                        GroupLayout.PREFERRED_SIZE,
                                        GroupLayout.DEFAULT_SIZE,
                                        GroupLayout.PREFERRED_SIZE)
                        ).addGap(15).addGroup(
                            layout.createParallelGroup(
                                GroupLayout.Alignment.BASELINE).addComponent(
                                    self.lockoutLabel).addComponent(
                                        self.lockoutField,
                                        GroupLayout.PREFERRED_SIZE,
                                        GroupLayout.DEFAULT_SIZE,
                                        GroupLayout.PREFERRED_SIZE)
                        ).addGap(30).addGroup(
                            layout.createParallelGroup(
                                GroupLayout.Alignment.BASELINE).addComponent(
                                    self.fileButton).addComponent(
                                        self.fileLabel,
                                        GroupLayout.PREFERRED_SIZE,
                                        GroupLayout.DEFAULT_SIZE,
                                        GroupLayout.PREFERRED_SIZE)
                        ).addGap(55).addGroup(
                            layout.createParallelGroup(
                                GroupLayout.Alignment.BASELINE).addComponent(
                                    self.setUpa)
                        ).addGap(10).addGroup(
                            layout.createParallelGroup(
                                GroupLayout.Alignment.BASELINE).addComponent(
                                    self.setUpba).addComponent(
                                        self.setUpbb,
                                        GroupLayout.PREFERRED_SIZE,
                                        GroupLayout.DEFAULT_SIZE,
                                        GroupLayout.PREFERRED_SIZE)
                        ).addGap(10).addGroup(
                            layout.createParallelGroup(
                                GroupLayout.Alignment.BASELINE).addComponent(
                                    self.setUpca).addComponent(
                                        self.setUpcb,
                                        GroupLayout.PREFERRED_SIZE,
                                        GroupLayout.DEFAULT_SIZE,
                                        GroupLayout.PREFERRED_SIZE)
                        ).addGap(10).addGroup(
                            layout.createParallelGroup(
                                GroupLayout.Alignment.BASELINE).addComponent(
                                    self.setUpda).addComponent(
                                        self.setUpdb,
                                        GroupLayout.PREFERRED_SIZE,
                                        GroupLayout.DEFAULT_SIZE,
                                        GroupLayout.PREFERRED_SIZE)
                        ).addGap(10).addGroup(
                            layout.createParallelGroup(
                                GroupLayout.Alignment.BASELINE).addComponent(
                                    self.setUpea).addComponent(
                                        self.setUpeb,
                                        GroupLayout.PREFERRED_SIZE,
                                        GroupLayout.DEFAULT_SIZE,
                                        GroupLayout.PREFERRED_SIZE)
                        ).addGap(10).addGroup(
                            layout.createParallelGroup(
                                GroupLayout.Alignment.BASELINE).addComponent(
                                    self.setUpfa).addComponent(
                                        self.setUpfb,
                                        GroupLayout.PREFERRED_SIZE,
                                        GroupLayout.DEFAULT_SIZE,
                                        GroupLayout.PREFERRED_SIZE)
                        ).addGap(10).addGroup(
                            layout.createParallelGroup(
                                GroupLayout.Alignment.BASELINE).addComponent(
                                    self.setUpga).addComponent(
                                        self.setUpgb,
                                        GroupLayout.PREFERRED_SIZE,
                                        GroupLayout.DEFAULT_SIZE,
                                        GroupLayout.PREFERRED_SIZE))
                        # Add warning label
                        .addGap(55).addGroup(
                            layout.createParallelGroup(
                                GroupLayout.Alignment.BASELINE).addComponent(
                                    self.warningLabela))
                        # Add first warning text
                        .addGap(10).addGroup(
                            layout.createParallelGroup(
                                GroupLayout.Alignment.BASELINE).addComponent(
                                    self.warningLabelba)).addGap(5).addGroup(
                                        layout.createParallelGroup(
                                            GroupLayout.Alignment.BASELINE).
                                        addComponent(self.warningLabelbb)).
                        addGap(5).addGroup(
                            layout.createParallelGroup(
                                GroupLayout.Alignment.BASELINE).addComponent(
                                    self.warningLabelbc)).addGap(5).addGroup(
                                        layout.createParallelGroup(
                                            GroupLayout.Alignment.BASELINE).
                                        addComponent(self.warningLabelbd))
                        # Add second warning text
                        .addGap(25).addGroup(
                            layout.createParallelGroup(
                                GroupLayout.Alignment.BASELINE).addComponent(
                                    self.warningLabelca)).addGap(5).addGroup(
                                        layout.createParallelGroup(
                                            GroupLayout.Alignment.BASELINE).
                                        addComponent(self.warningLabelcb))
                        # Add third warning text
                        .addGap(25).addGroup(
                            layout.createParallelGroup(
                                GroupLayout.Alignment.BASELINE).addComponent(
                                    self.warningLabelda)).addGap(5).addGroup(
                                        layout.createParallelGroup(
                                            GroupLayout.Alignment.BASELINE).
                                        addComponent(self.warningLabeldb))))))

    """ Retrieve password file """

    def getPasswordFile(self, event):
        self.passwordFile = JFileChooser()
        self.ret = self.passwordFile.showDialog(self.tab,
                                                "Choose Password File")
        self.filename = self.passwordFile.getSelectedFile().getCanonicalPath()
        self.fileLabel.setText(self.filename)

    """ Logging """

    def log(self, currentPayload):
        self.logger.warning(
            '[%s] %s' %
            (str(datetime.datetime.now()), currentPayload.tostring()))
예제 #19
0
class SourceCellRenderer(TreeCellRenderer):
    def __init__(self,tree,mapContext):
        self.tree = tree
        self.mapContext = mapContext
        ## Group
        self.lblFolder = JLabel()
        self.lblFolder.setBackground(Color(222,227,233)) #.BLUE.brighter())
        self.lblFolder.setOpaque(True)
        self.lblFolder.setText("plddddddddddddddddddddddddddddddddddddddddddddddddddddddd")
        
        ### Folder
        self.pnlFolder = JPanel()
        self.pnlFolder.setOpaque(False)
        self.pnlFolder.setLayout(FlowLayout(FlowLayout.LEFT))
        self.lblGroup = JLabel()
        #self.lblGroup.setBackground(Color(222,227,233)) #.BLUE.brighter())
        #self.lblGroup.setOpaque(True)
        self.lblGroup.setText("plddddddddddddddddddddddddddddddddddddddddddddddddddddddd")
        self.lblGroupPreferredSize = self.lblGroup.getPreferredSize()
        self.lblGroupIcon = JLabel()
        self.pnlFolder.add(self.lblGroupIcon)
        self.pnlFolder.add(self.lblGroup)
        #self.lblGroup.setBorder(
        #  BorderFactory.createLineBorder(Color(222,227,233).darker(),1)
        #)
        #self.lblGroupPreferredSize.setSize(30,200)#self.lblGroupPreferredSize.getHeight()+4, self.lblGroupPreferredSize.getWidth())
        
        ### LAYER
        self.pnlLayer = JPanel()
        self.pnlLayer.setOpaque(False)
        #self.pnlLayer.setBorder(EmptyBorder(2,2,2,2))

        self.pnlLayer.setLayout(FlowLayout(FlowLayout.LEFT))
        self.chkLayerVisibility = JCheckBox()
        self.chkLayerVisibility.setOpaque(False)
        self.pnlLayer.add(self.chkLayerVisibility)
        self.lblLayerIcon = JLabel()
        self.lblLayerName = JLabel()
        self.pnlLayer.add(self.lblLayerIcon)
        self.pnlLayer.add(self.lblLayerName)
        #self.tree.setRowHeight(int(self.pnlLayer.getPreferredSize().getHeight())) #+2
        self.tree.setRowHeight(int(self.pnlFolder.getPreferredSize().getHeight()))
        
        self.lblUnknown = JLabel()
        
    def getTreeCellRendererComponent(self, tree, value, selected, expanded, leaf, row, hasFocus):
        uo = value.getUserObject()
        if isinstance(uo, DataFolder):
            #self.lblFolder.setText(uo.getName())
            text = "[" + str(value.getChildCount()) +"] " + uo.getName()
            self.lblFolder.setText(text)
            self.lblFolder.setPreferredSize(self.lblGroupPreferredSize)
            if uo.getIcon()!=None:
                self.lblGroupIcon.setIcon(uo.getIcon())
            else:
                self.lblGroupIcon.setIcon(getIconByName("librarybrowser-folder")) #icon-folder-open"))
            
            return self.lblFolder
        if isinstance(uo, DataGroup):
            self.lblGroup.setText(uo.getName())
            self.lblGroup.setPreferredSize(self.lblGroupPreferredSize)
            if uo.getIcon()!=None:
                self.lblGroupIcon.setIcon(uo.getIcon())
            else:
                #import pdb
                #pdb.set_trace()
                self.lblGroupIcon.setIcon(getIconByName("librarybrowser-folder")) #icon-folder-open"))
            
            return self.pnlFolder
        if isinstance(uo, DataLayer):
            layer = uo.getLayer()
            self.lblLayerName.setText(layer.getName())
            self.lblLayerIcon.setIcon(getIconFromLayer(layer))
            self.chkLayerVisibility.setSelected(layer.isVisible())
            if layer.isWithinScale(self.mapContext.getScaleView()): # and layer.isVisible():
                self.chkLayerVisibility.setEnabled(True)
            else:
                self.chkLayerVisibility.setEnabled(False)

                            
            self.lblLayerName.setForeground(Color.BLACK)
            
            font = self.lblLayerName.getFont()
            self.lblLayerName.setForeground(Color.BLACK)
            if layer.isEditing():
                self.lblLayerName.setForeground(Color.RED)
            if layer.isActive() and font.isBold():
                pass
            elif layer.isActive() and not font.isBold():
                newfont = font.deriveFont(Font.BOLD)
                self.lblLayerName.setFont(newfont)
            else:
                newfont = font.deriveFont(Font.PLAIN)
                self.lblLayerName.setFont(newfont)
            #self.pnlLayer.repaint()
            return self.pnlLayer
        self.lblUnknown.setText("")
        self.lblUnknown.setPreferredSize(Dimension(0,0))

        return self.lblUnknown
예제 #20
0
파일: ui.py 프로젝트: pekkaklarck/ATDDDemo
class EmployeeDetails(JPanel):

    def __init__(self, employees):
        JPanel.__init__(self, preferredSize=(400, 200))
        layout = BoxLayout(self, BoxLayout.Y_AXIS)
        self.setLayout(layout)
        self._employees = employees
        employees.add_change_listener(self)
        self._create_status_label()
        self._create_name_editor()
        self._create_start_date_editor()
        self._create_save_button()
        self._adding_employee = False

    def _create_status_label(self):
        self._status_label = JLabel(name='status_label',
                                   font=Font(Font.SANS_SERIF, Font.PLAIN, 11))
        self.add(self._status_label)
        self._add_with_padding(self._status_label, 5)

    def _create_name_editor(self):
        self.add(JLabel(text='Employee Name:'))
        self._name_editor = FixedHeightTextField('name_input')
        self._add_with_padding(self._name_editor, 5)

    def _create_start_date_editor(self):
        self.add(JLabel(text='Start Date (yyyy-mm-dd):'))
        self._start_date_editor = FixedHeightTextField('start_input')
        self._add_with_padding(self._start_date_editor, 5)

    def _create_save_button(self):
        self._save_button = JButton('Save', name='save_button', visible=False)
        self._save_button.addActionListener(ListenerFactory(ActionListener,
                                            self._save_button_pushed))
        self._add_with_padding(self._save_button, 5)

    def _add_with_padding(self, component, padding):
        self.add(component)
        self.add(Box.createRigidArea(Dimension(0, padding)))

    def show_employee(self, employee):
        self._name_editor.setText(employee.name)
        self._start_date_editor.setText(str(employee.startdate))
        self._name_editor.setEditable(False)
        self._start_date_editor.setEditable(False)
        self._save_button.setVisible(False)
        if self._adding_employee:
            self._adding_employee = False
        else:
            self._status_label.setText('')

    def edit_new_employee(self):
        self._name_editor.setText('')
        self._start_date_editor.setText('')
        self._name_editor.setEditable(True)
        self._start_date_editor.setEditable(True)
        self._save_button.setVisible(True)
        self._adding_employee = True

    def _save_button_pushed(self, event):
        self._employees.add(self._name_editor.getText(),
                            self._start_date_editor.getText())

    def employee_added(self, employee):
        self._status_label.setForeground(Color.BLACK)
        self._status_label.setText("Employee '%s' was added successfully." % employee.name)
        self._save_button.setVisible(False)

    def adding_employee_failed(self, reason):
        self._status_label.setForeground(Color.RED)
        self._status_label.setText(reason)
예제 #21
0
class BurpExtender(IBurpExtender, ITab):
    socket_time_out = 3

    def registerExtenderCallbacks(self, callbacks):
        self.out = callbacks.getStdout()

        self.callbacks = callbacks
        self.helpers = callbacks.getHelpers()
        callbacks.setExtensionName("WhatsApp Decoder")

        self.banner = JLabel("WHATSAPP DECRYPTION AND ENCRYPTION EXTENSION BY DIKLA BARDA, ROMAN ZAIKIN", SwingConstants.CENTER)
        self.banner.setFont(Font("Serif", Font.PLAIN, 17))
        self.banner.setBorder(BorderFactory.createLineBorder(Color.BLACK))

        self.statusConn = JLabel("CONNECTION STATUS:  ")
        self.statusConnField = JLabel("NOT CONNECTED")
        self.statusAct = JLabel("ACTION STATUS:      ")
        self.statusActField = JLabel("OK")

        self.ref = JLabel("Ref object:  ")
        self.refField = JTextField("123", 80)
        self.refField.setToolTipText("Copy the Ref from burpsuit WebSocket, make sure that the parameter 'secret' is there and you copy only the 'ref' without the connection and other data, if not logout from your whatsapp web and login again.")

        self.privateKey = JLabel("Private Key:")
        self.privateKeyField = JTextField("123", 80)
        self.privateKeyField.setToolTipText("Copy the private key list from your whatsapp web according to our blog post ")

        self.publicKey = JLabel("Public Key: ")
        self.publicKeyField = JTextField("123", 80)
        self.publicKeyField.setToolTipText("Copy the public key list from your whatsapp web according to our blog post")

        self.statusPanel1 = JPanel()
        self.statusPanel1.add(self.statusConn)
        self.statusPanel1.add(self.statusConnField)

        self.statusPanel2 = JPanel()
        self.statusPanel2.add(self.statusAct)
        self.statusPanel2.add(self.statusActField)

        self.privateKeyPanel = JPanel()
        self.privateKeyPanel.add(self.privateKey)
        self.privateKeyPanel.add(self.privateKeyField)

        self.publicKeyPanel = JPanel()
        self.publicKeyPanel.add(self.publicKey)
        self.publicKeyPanel.add(self.publicKeyField)

        self.refPanel = JPanel()
        self.refPanel.add(self.ref)
        self.refPanel.add(self.refField)

        self.messageField = JTextArea("", 5, 90)
        self.messageField.setLineWrap(True)
        self.messageField.setToolTipText("If you putting in the incoming traffic you can copy it from burp suit, the outgoing is the list from aesCbcEncrypt")

        self.whatsAppMessagesPanel = JPanel()
        self.whatsAppMessagesPanel.add(self.messageField)

        self.btnSave = JButton("Connect", actionPerformed=self.saveConfig)
        self.btnRestore = JButton("Clear", actionPerformed=self.clearConfig)

        self.grpConfig = JPanel()
        self.grpConfig.add(self.btnSave)
        self.grpConfig.add(self.btnRestore)

        self.btnIncoming = JButton("Incoming", actionPerformed=self.performAction)
        self.btnOutgoing = JButton("Outgoing", actionPerformed=self.performAction)

        self.btnEncrypt = JButton("Encrypt", actionPerformed=self.performAction)
        self.btnEncrypt.setEnabled(False)  # Can't send data without a direction

        self.btnDecrypt = JButton("Decrypt", actionPerformed=self.performAction)
        self.btnDecrypt.setEnabled(False)  # Can't send data without a direction

        self.btnCrypt = JPanel()
        self.btnCrypt.add(self.btnIncoming)
        self.btnCrypt.add(self.btnEncrypt)
        self.btnCrypt.add(self.btnDecrypt)
        self.btnCrypt.add(self.btnOutgoing)

        self.tab = JPanel()
        layout = GridBagLayout()
        self.tab.setLayout(layout)

        c = GridBagConstraints()

        c.ipadx = 0
        c.ipady = 0

        c.fill = GridBagConstraints.BOTH
        #c.weightx = 0 # gap between the x items
        #c.weighty = 0 # gap between the y items

        c.anchor = GridBagConstraints.NORTHWEST

        c.gridx = 0
        c.gridy = 0
        self.tab.add(self.banner, c)

        c.gridx = 0
        c.gridy = 1
        self.tab.add(self.refPanel, c)

        c.gridx = 0
        c.gridy = 2
        self.tab.add(self.privateKeyPanel, c)

        c.gridx = 0
        c.gridy = 3
        self.tab.add(self.publicKeyPanel, c)

        c.gridx = 0
        c.gridy = 4
        c.anchor = GridBagConstraints.CENTER
        self.tab.add(self.grpConfig, c)

        c.gridx = 0
        c.gridy = 5
        self.tab.add(self.whatsAppMessagesPanel, c)

        c.gridx = 0
        c.gridy = 6
        self.tab.add(self.btnCrypt, c)

        c.gridx = 0
        c.gridy = 7
        self.tab.add(self.statusPanel1, c)

        c.gridx = 0
        c.gridy = 8
        self.tab.add(self.statusPanel2, c)

        # restore config
        self.restoreConfig()
        callbacks.addSuiteTab(self)

    def performAction(self, e=None):

        self.client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.client.settimeout(self.socket_time_out)

        self.data = self.messageField.getText()

        eventSource = e.getSource()
        eventSource.setEnabled(False)

        # Incoming data
        if eventSource == self.btnIncoming:
            self.direction = "in"
            self.btnOutgoing.setEnabled(True)
            self.btnEncrypt.setEnabled(True)
            self.btnDecrypt.setEnabled(True)

        # Outgoing data
        elif eventSource == self.btnOutgoing:
            self.direction = "out"
            self.btnIncoming.setEnabled(True)
            self.btnEncrypt.setEnabled(True)
            self.btnDecrypt.setEnabled(True)

        # Send
        elif eventSource == self.btnDecrypt:
            self.btnDecrypt.setEnabled(True)
            clientData = json.dumps({"action": "decrypt",
                                     "data": {
                                            "direction": self.direction,
                                            "msg": self.messageField.getText()
                                        }
                                     })

            self.client.sendto(clientData, ("127.0.0.1",2912))
            try:
                serverData, addr = self.client.recvfrom(2048)
                serverData = json.loads(serverData)

                if serverData["status"] == 0:
                    print serverData
                    self.messageField.setText(json.dumps(serverData["data"]))
                    self.statusActField.setForeground(Color.GREEN)
                    self.statusActField.setText("OK")
                else:
                    self.statusActField.setForeground(Color.RED)
                    self.statusActField.setText("Error: {}".format(json.dumps(serverData["data"])))

            except socket.timeout:
                pass

        elif eventSource == self.btnEncrypt:
            self.btnEncrypt.setEnabled(True)
            clientData = json.dumps({"action": "encrypt",
                                     "data": {
                                         "direction": self.direction,
                                         "msg": self.messageField.getText()
                                     }
                                     })

            self.client.sendto(clientData, ("127.0.0.1", 2912))
            try:
                serverData, addr = self.client.recvfrom(2048)
                serverData = json.loads(serverData)
                if serverData["status"] == 0:
                    if isinstance(serverData["data"], list):
                        self.messageField.setText(json.dumps(serverData["data"]))
                    else:
                        self.messageField.setText(serverData["data"])

                    self.statusActField.setForeground(Color.GREEN)
                    self.statusActField.setText("OK")
                else:
                    self.statusActField.setForeground(Color.RED)
                    self.statusActField.setText("Error: {}".format(json.dumps(serverData["data"])))

            except socket.timeout:
                pass

        self.client.close()


    def saveConfig(self, e=None):
        self.client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.client.settimeout(self.socket_time_out)

        config = {
            'ref': self.refField.getText(),
            'private': self.privateKeyField.getText(),
            'public': self.publicKeyField.getText(),
        }

        self.callbacks.saveExtensionSetting("config", pickle.dumps(config))

        try:
            clientData = json.dumps({"action":"init",
                                     "data":{
                                         "ref":json.loads(self.refField.getText()),
                                         "private":self.privateKeyField.getText(),
                                         "public":self.publicKeyField.getText()
                                     }
                                    })

            self.client.sendto(clientData, ("127.0.0.1", 2912))

            serverData, addr = self.client.recvfrom(2048)
            print (serverData)

            self.statusConnField.setText("CONNECTED")
            self.statusActField.setForeground(Color.GREEN)
            self.statusActField.setText("OK")

        except socket.timeout:
            self.statusActField.setForeground(Color.RED)
            self.statusActField.setText("Error: Can't connect to the local server make sure parser.py is running!")
            pass

        except Exception as e:
            self.statusActField.setForeground(Color.RED)
            self.statusActField.setText("Error: make Sure the ref is a correct json!")

        self.client.close()

    def clearConfig(self, e=None):
        self.refField.setText("")
        self.privateKeyField.setText("")
        self.publicKeyField.setText("")
        self.statusConnField.setText("NOT CONNECTED")
        self.statusActField.setText("OK")
        self.messageField.setText("")

    def restoreConfig(self, e=None):
        storedConfig = self.callbacks.loadExtensionSetting("config")
        if storedConfig != None:
            config = pickle.loads(storedConfig)
            self.refField.setText(config["ref"])
            self.privateKeyField.setText(config["private"])
            self.publicKeyField.setText(config["public"])

    def getTabCaption(self):
        return ("WhatsApp Decoder")

    def getUiComponent(self):
        return self.tab
예제 #22
0
    def tag_3_1(self, c):
        # 输入框-标题
        lblParams = JLabel(u'请填写域名:')
        self.setFontBold(lblParams)
        lblParams.setForeground(Color(0, 0, 153))
        c.gridx = 0
        c.gridy = 0
        c.insets = Insets(5, 5, 5, 5)
        c.fill = GridBagConstraints.NONE
        c.anchor = GridBagConstraints.FIRST_LINE_END
        self.white_list_domain_settings.add(lblParams, c)

        # 输入框
        self.white_list_text_field = JTextField()
        c.fill = GridBagConstraints.BOTH
        c.gridx = 1
        c.gridy = 0
        self.white_list_domain_settings.add(self.white_list_text_field, c)

        lblParamsNote = JLabel(u"白名单域名列表")
        self.setFontItalic(lblParamsNote)
        c.fill = GridBagConstraints.NONE
        c.gridx = 0
        c.gridy = 1
        self.white_list_domain_settings.add(lblParamsNote, c)

        # 添加 文本框
        self.white_list_text_area = JTextArea()
        self.white_list_text_area.setColumns(20)
        self.white_list_text_area.setRows(10)
        self.white_list_text_area.setEditable(False)
        c.fill = GridBagConstraints.BOTH
        self.white_list_mouse_listener = TextAreaMouseListener(
            self.white_list_text_area)
        self.white_list_text_area.addMouseListener(
            self.white_list_mouse_listener)

        # 向文本框添加数据
        for name in white_list_names:
            self.white_list_text_area.append(name + '\n' + os.linesep)
        c.gridx = 1
        c.gridy = 1
        sp = JScrollPane(self.white_list_text_area)
        self.white_list_domain_settings.add(sp, c)

        # 添加 删除 重置
        buttonsPanel = JPanel(GridBagLayout())
        _c = GridBagConstraints()
        _c.insets = Insets(3, 3, 3, 3)
        _c.gridx = 0
        _c.fill = GridBagConstraints.BOTH
        _c.weightx = 1
        _c.gridwidth = 1

        handlers = ButtonHandlers(self.white_list_text_field,
                                  self.white_list_text_area,
                                  self.white_list_mouse_listener,
                                  white_list_names)

        # 添加按钮
        self.white_list_add_button = JButton(
            u'添加', actionPerformed=handlers.handler_add)
        _c.gridy = 1
        buttonsPanel.add(self.white_list_add_button, _c)

        # 删除按钮
        self.white_list_rm_button = JButton(
            u'删除', actionPerformed=handlers.handler_rm)
        _c.gridy = 2
        buttonsPanel.add(self.white_list_rm_button, _c)

        # 重置按钮
        self.white_list_restore_button = JButton(
            u'重置', actionPerformed=handlers.handler_restore)
        _c.gridy = 3
        buttonsPanel.add(self.white_list_restore_button, _c)

        c.gridx = 2
        c.gridy = 1
        c.fill = GridBagConstraints.NONE
        self.white_list_domain_settings.add(buttonsPanel, c)
예제 #23
0
class tab():
    def __init__(self, callbacks):
        """ Method automatically called when memory is
        allocated for a new object, initiates tab object """

        print("Created a tab")
        self.callbacks = callbacks
        self.curRequest = None

        self.createTabGUI()

    def getFirstTab(self):
        """ Get the JPanel that represents the object's
        Timing Attack tab """

        self.scrollPane = JScrollPane(
            self.firstTab, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
            JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED)
        return self.scrollPane

    ###########################
    # SECTION 1: CREATING GUI #
    ###########################

    def createTabGUI(self):
        """ Create GUI for this tabbed pane """

        # panel for the whole tab
        self.firstTab = JPanel()

        # name of the extention
        self.titleTop = JLabel("Timing Attack")
        self.titleTop.setFont(Font("Tahoma", 1, 14))
        self.titleTop.setForeground(Color(255, 102, 51))

        # info about the extention
        self.infoTop = JLabel(
            "Timing Attack is a open source extention to inform how long the system takes to respond for a valid and an invalid authentication."
        )
        self.infoTop.setFont(Font("Tahoma", 0, 11))

        # labels and inputs on top half
        self.addTitle = JLabel("Enter a Valid and an Invalid Username")
        self.addTitle.setFont(Font("Tahoma", 1, 13))
        self.addTitle.setForeground(Color(255, 102, 51))
        self.validUsername = JLabel("Valid Username")
        self.validUsername.setFont(Font("Tahoma", 0, 12))
        self.invalidUsername = JLabel("Invalid Username")
        self.invalidUsername.setFont(Font("Tahoma", 0, 12))
        self.parameter = JLabel("Parameter")
        self.parameter.setFont(Font("Tahoma", 0, 12))
        self.average = JLabel("Sample Size")
        self.average.setFont(Font("Tahoma", 0, 12))
        self.addValid = JTextField("")
        self.addInvalid = JTextField("")
        self.addParameter = JTextField("")
        self.addAverage = JTextField("")
        self.submitButton1 = JButton("Submit",
                                     actionPerformed=self.timeTwoUsers)

        # result on top left
        self.resultTitle = JLabel("Result")
        self.resultTitle.setFont(Font("Tahoma", 1, 13))
        self.resultTitle.setForeground(Color(255, 102, 51))
        self.showResults = JTextArea("")
        self.showResults.setEditable(False)
        self.showResultsScroll = JScrollPane(self.showResults)
        self.twoUserViewResult = JButton("View Results",
                                         actionPerformed=self.showResultsTop)
        self.twoUserViewReq = JButton("View Request",
                                      actionPerformed=self.showRequestTop)
        self.twoUserViewValidResponse = JButton(
            "View Valid Response", actionPerformed=self.showValidResponseTop)
        self.twoUserViewInvalidResponse = JButton(
            "View Invalid Response",
            actionPerformed=self.showInvalidResponseTop)
        # Set top buttons to invisible until a request is submitted
        self.twoUserViewResult.setVisible(False)
        self.twoUserViewReq.setVisible(False)
        self.twoUserViewValidResponse.setVisible(False)
        self.twoUserViewInvalidResponse.setVisible(False)

        # labels, inputs and file on bottom half
        self.addTitleFile = JLabel("Input Username File")
        self.addTitleFile.setFont(Font("Tahoma", 1, 13))
        self.addTitleFile.setForeground(Color(255, 102, 51))
        self.inputFileButton = JButton("Choose File...",
                                       actionPerformed=self.chooseFile)
        self.separatorList = JLabel("Separator")
        self.separatorList.setFont(Font("Tahoma", 0, 12))
        self.parameterList = JLabel("Parameter")
        self.parameterList.setFont(Font("Tahoma", 0, 12))
        self.averageList = JLabel("Sample Size")
        self.averageList.setFont(Font("Tahoma", 0, 12))
        self.addSeparatorList = JTextField("")
        self.addParameterList = JTextField("")
        self.addAverageList = JTextField("")
        self.submitButton2 = JButton("Submit",
                                     actionPerformed=self.timeUserList)

        # result on bottom left
        self.resultTitleList = JLabel("Result")
        self.resultTitleList.setFont(Font("Tahoma", 1, 13))
        self.resultTitleList.setForeground(Color(255, 102, 51))
        self.showResultsList = JTextArea("")
        self.showResultsList.setEditable(False)
        self.showResultsListScroll = JScrollPane(self.showResultsList)
        self.downloadResultList = JButton("Download Display",
                                          actionPerformed=self.downloadResults)
        self.listViewResults = JButton("View Results",
                                       actionPerformed=self.showListResults)
        self.listViewReq = JButton("View Request",
                                   actionPerformed=self.showListRequest)
        self.listViewResponses = JButton(
            "View Responses", actionPerformed=self.showListResponses)
        # Set list buttons to invisible until a request is submitted
        self.downloadResultList.setVisible(False)
        self.listViewResults.setVisible(False)
        self.listViewReq.setVisible(False)
        self.listViewResponses.setVisible(False)

        # something wrong?
        self.somethingWrong = JLabel("Something Wrong?")
        self.debugOn = False
        self.viewDebug = JButton("View debug output",
                                 actionPerformed=self.showDebug)
        self.debugText = JTextArea("")
        self.debugTextScroll = JScrollPane(self.debugText)
        self.debugTextScroll.setVisible(False)

        # layout
        layout = GroupLayout(self.firstTab)
        self.firstTab.setLayout(layout)

        layout.setHorizontalGroup(
            layout.createParallelGroup(GroupLayout.Alignment.LEADING)
            # whole layout
            .addGroup(
                layout.createSequentialGroup().addGap(15)
                # title + description
                .addGroup(
                    layout.createParallelGroup(
                        GroupLayout.Alignment.LEADING).addComponent(
                            self.titleTop).addComponent(self.infoTop)
                    # titles
                    .addGroup(
                        layout.createSequentialGroup()
                        # title left
                        .addGroup(
                            layout.createParallelGroup(
                                GroupLayout.Alignment.LEADING).addComponent(
                                    self.addTitle)).addGap(168)
                        # title right
                        .addGroup(
                            layout.createParallelGroup(
                                GroupLayout.Alignment.LEADING).addComponent(
                                    self.resultTitle))).
                    addGroup(
                        layout.createSequentialGroup()
                        # left
                        .addGroup(
                            layout.createParallelGroup(
                                GroupLayout.Alignment.LEADING).addComponent(
                                    self.validUsername).addComponent(
                                        self.invalidUsername).addComponent(
                                            self.parameter).addComponent(
                                                self.average).addComponent(
                                                    self.addTitleFile).
                            addComponent(self.inputFileButton).addComponent(
                                self.separatorList).addComponent(
                                    self.parameterList).addComponent(
                                        self.averageList).addComponent(
                                            self.somethingWrong)).addGap(12).
                        addGroup(
                            layout.createParallelGroup(
                                GroupLayout.Alignment.LEADING).addComponent(
                                    self.addValid, GroupLayout.PREFERRED_SIZE,
                                    200,
                                    GroupLayout.PREFERRED_SIZE).addComponent(
                                        self.addInvalid,
                                        GroupLayout.PREFERRED_SIZE, 200,
                                        GroupLayout.PREFERRED_SIZE).
                            addComponent(
                                self.addParameter,
                                GroupLayout.PREFERRED_SIZE, 200,
                                GroupLayout.PREFERRED_SIZE).addComponent(
                                    self.addAverage,
                                    GroupLayout.PREFERRED_SIZE, 80,
                                    GroupLayout.PREFERRED_SIZE).addComponent(
                                        self.submitButton1).addComponent(
                                            self.addSeparatorList,
                                            GroupLayout.PREFERRED_SIZE, 200,
                                            GroupLayout.PREFERRED_SIZE).
                            addComponent(
                                self.addParameterList,
                                GroupLayout.PREFERRED_SIZE, 200,
                                GroupLayout.PREFERRED_SIZE).addComponent(
                                    self.addAverageList,
                                    GroupLayout.PREFERRED_SIZE, 80,
                                    GroupLayout.PREFERRED_SIZE).addComponent(
                                        self.submitButton2).addComponent(
                                            self.viewDebug)).addGap(50)
                        # right
                        .addGroup(
                            layout.createParallelGroup(
                                GroupLayout.Alignment.LEADING).addComponent(
                                    self.showResultsScroll,
                                    GroupLayout.PREFERRED_SIZE, 600,
                                    GroupLayout.PREFERRED_SIZE).
                            addGroup(layout.createSequentialGroup().addGroup(
                                layout.createParallelGroup(
                                    GroupLayout.Alignment.LEADING).
                                addComponent(self.twoUserViewResult)
                            ).addGap(15).addGroup(
                                layout.createParallelGroup(
                                    GroupLayout.Alignment.LEADING).
                                addComponent(
                                    self.twoUserViewReq)).addGap(15).addGroup(
                                        layout.createParallelGroup(
                                            GroupLayout.Alignment.LEADING).
                                        addComponent(
                                            self.twoUserViewValidResponse)
                                    ).addGap(15).addGroup(
                                        layout.createParallelGroup(
                                            GroupLayout.Alignment.LEADING).
                                        addComponent(
                                            self.twoUserViewInvalidResponse))).
                            addComponent(self.resultTitleList).addComponent(
                                self.showResultsListScroll,
                                GroupLayout.PREFERRED_SIZE, 600,
                                GroupLayout.PREFERRED_SIZE).addGroup(
                                    layout.createSequentialGroup().addGroup(
                                        layout.createParallelGroup(
                                            GroupLayout.Alignment.LEADING).
                                        addComponent(self.downloadResultList)).
                                    addGap(15).addGroup(
                                        layout.createParallelGroup(
                                            GroupLayout.Alignment.LEADING).
                                        addComponent(self.listViewResults)
                                    ).addGap(15).addGroup(
                                        layout.createParallelGroup(
                                            GroupLayout.Alignment.LEADING).
                                        addComponent(self.listViewReq)
                                    ).addGap(15).addGroup(
                                        layout.createParallelGroup(
                                            GroupLayout.Alignment.LEADING).
                                        addComponent(self.listViewResponses)
                                    )).addGap(10).addComponent(
                                        self.debugTextScroll,
                                        GroupLayout.PREFERRED_SIZE, 300,
                                        GroupLayout.PREFERRED_SIZE))))))

        layout.setVerticalGroup(
            layout.createParallelGroup(GroupLayout.Alignment.LEADING)
            # whole layout
            .addGroup(
                layout.createSequentialGroup().addGap(15).addComponent(
                    self.titleTop).addGap(10).addComponent(
                        self.infoTop).addGap(10)
                # titles
                .addGroup(
                    layout.createSequentialGroup()
                    # left
                    .addGroup(
                        layout.createParallelGroup(
                            GroupLayout.Alignment.LEADING).addComponent(
                                self.addTitle).addGap(25)
                        # right
                        .addGroup(
                            layout.createParallelGroup(
                                GroupLayout.Alignment.LEADING).addComponent(
                                    self.resultTitle))))
                # top half
                .addGroup(
                    layout.createSequentialGroup()
                    # left top half
                    .addGroup(
                        layout.createParallelGroup(
                            GroupLayout.Alignment.BASELINE).
                        addGroup(layout.createSequentialGroup().addGroup(
                            layout.createParallelGroup(
                                GroupLayout.Alignment.BASELINE).addComponent(
                                    self.validUsername).addGap(5).addComponent(
                                        self.addValid,
                                        GroupLayout.PREFERRED_SIZE,
                                        GroupLayout.DEFAULT_SIZE,
                                        GroupLayout.PREFERRED_SIZE)
                        ).addGap(5).addGroup(
                            layout.createParallelGroup(
                                GroupLayout.Alignment.BASELINE).addComponent(
                                    self.invalidUsername).addGap(
                                        5).addComponent(
                                            self.addInvalid,
                                            GroupLayout.PREFERRED_SIZE,
                                            GroupLayout.DEFAULT_SIZE,
                                            GroupLayout.PREFERRED_SIZE)
                        ).addGap(5).addGroup(
                            layout.createParallelGroup(
                                GroupLayout.Alignment.BASELINE).addComponent(
                                    self.parameter).addGap(5).addComponent(
                                        self.addParameter,
                                        GroupLayout.PREFERRED_SIZE,
                                        GroupLayout.DEFAULT_SIZE,
                                        GroupLayout.PREFERRED_SIZE)
                        ).addGap(5).addGroup(
                            layout.createParallelGroup(
                                GroupLayout.Alignment.BASELINE).addComponent(
                                    self.average).addGap(5).addComponent(
                                        self.addAverage,
                                        GroupLayout.PREFERRED_SIZE,
                                        GroupLayout.DEFAULT_SIZE,
                                        GroupLayout.PREFERRED_SIZE)
                        ).addGap(5).addGroup(
                            layout.createParallelGroup(
                                GroupLayout.Alignment.BASELINE).addComponent(
                                    self.submitButton1))).addGap(5)
                        # right top half
                        .addGroup(
                            layout.createParallelGroup(
                                GroupLayout.Alignment.BASELINE).addComponent(
                                    self.showResultsScroll,
                                    GroupLayout.PREFERRED_SIZE, 200,
                                    GroupLayout.PREFERRED_SIZE)))).addGap(5)
                # buttons + titles
                .addGroup(layout.createSequentialGroup().addGroup(
                    layout.createParallelGroup(
                        GroupLayout.Alignment.BASELINE).addComponent(
                            self.twoUserViewResult).addGap(20).addComponent(
                                self.twoUserViewReq).addGap(20).addComponent(
                                    self.twoUserViewValidResponse).addGap(20).
                    addComponent(
                        self.twoUserViewInvalidResponse)).addGap(10).addGroup(
                            layout.createParallelGroup(
                                GroupLayout.Alignment.BASELINE).addComponent(
                                    self.addTitleFile).addGap(25).addComponent(
                                        self.resultTitleList))).addGap(3)
                # bottom half
                .addGroup(
                    layout.createSequentialGroup()
                    # left bottom half
                    .addGroup(
                        layout.createParallelGroup(
                            GroupLayout.Alignment.BASELINE).
                        addGroup(layout.createSequentialGroup().addGroup(
                            layout.createParallelGroup(
                                GroupLayout.Alignment.BASELINE).addComponent(
                                    self.inputFileButton)
                        ).addGap(10).addGroup(
                            layout.createParallelGroup(
                                GroupLayout.Alignment.BASELINE).addComponent(
                                    self.separatorList).addGap(5).addComponent(
                                        self.addSeparatorList,
                                        GroupLayout.PREFERRED_SIZE,
                                        GroupLayout.DEFAULT_SIZE,
                                        GroupLayout.PREFERRED_SIZE)
                        ).addGap(5).addGroup(
                            layout.createParallelGroup(
                                GroupLayout.Alignment.BASELINE).addComponent(
                                    self.parameterList).addGap(5).addComponent(
                                        self.addParameterList,
                                        GroupLayout.PREFERRED_SIZE,
                                        GroupLayout.DEFAULT_SIZE,
                                        GroupLayout.PREFERRED_SIZE)
                        ).addGap(5).addGroup(
                            layout.createParallelGroup(
                                GroupLayout.Alignment.BASELINE).addComponent(
                                    self.averageList).addGap(5).addComponent(
                                        self.addAverageList,
                                        GroupLayout.PREFERRED_SIZE,
                                        GroupLayout.DEFAULT_SIZE,
                                        GroupLayout.PREFERRED_SIZE)
                        ).addGap(5).addGroup(
                            layout.createParallelGroup(
                                GroupLayout.Alignment.BASELINE).addComponent(
                                    self.submitButton2)
                        )).addGap(5).addGroup(
                            layout.createParallelGroup(
                                GroupLayout.Alignment.BASELINE).addComponent(
                                    self.showResultsListScroll,
                                    GroupLayout.PREFERRED_SIZE, 200,
                                    GroupLayout.PREFERRED_SIZE)))).addGap(5)
                # right bottom half
                .addGroup(layout.createSequentialGroup().addGroup(
                    layout.createParallelGroup(
                        GroupLayout.Alignment.BASELINE).addComponent(
                            self.downloadResultList).addGap(10).addComponent(
                                self.listViewResults).addGap(10).addComponent(
                                    self.listViewReq).addGap(10).addComponent(
                                        self.listViewResponses))).addGap(30)
                # something wrong section
                .addGroup(layout.createSequentialGroup().addGroup(
                    layout.createParallelGroup(
                        GroupLayout.Alignment.BASELINE).addComponent(
                            self.somethingWrong).addGap(10).addComponent(
                                self.viewDebug).addGap(10).addComponent(
                                    self.debugTextScroll,
                                    GroupLayout.PREFERRED_SIZE, 150,
                                    GroupLayout.PREFERRED_SIZE)))))
        return

    def chooseFile(self, event):
        """ Method that allows the user to choose a file of
        usernames, and it tries to load the last used directory """

        try:
            # load the directory for future imports/exports
            fileChooserDirectory = self._callbacks.loadExtensionSetting(
                "fileChooserDirectory")

        # there is not a last used directory
        except:
            # set the last used directory to blank
            fileChooserDirectory = ""

        self.chooser = JFileChooser(fileChooserDirectory)
        fileextensions = ["txt"]
        filter = FileNameExtensionFilter("TXT FILES", fileextensions)
        self.chooser.setFileFilter(filter)
        returnVal = self.chooser.showOpenDialog(self.chooser)
        if (returnVal == JFileChooser.APPROVE_OPTION):
            self.inputFileButton.text = self.chooser.getSelectedFile().getName(
            )

    ##################################
    # SECTION 2: SEND TIMING REQUEST #
    ##################################

    def timeTwoUsers(self, event):
        """ Method that sends the current request to getTwoUserTimes """

        if (self.curRequest == None):
            self.debugOutput("Timing Attack does not have a request")
            return

        # change button to say show request
        self.twoUserViewResult.setVisible(True)
        self.twoUserViewReq.setVisible(True)
        self.twoUserViewValidResponse.setVisible(True)
        self.twoUserViewInvalidResponse.setVisible(True)
        threading.Thread(target=self.getTwoUserTimes).start()
        return

    def getTwoUserTimes(self):
        """ Method that prints the time taken to return responses
        from one valid username and from one invalid username
        (called by timeTwoUsers) """

        self.twoUserViewReq.setVisible(True)
        validTime, self.validRequest, self.validResponse = self.getTime(
            self.addParameter.text, self.addValid.text, self.addAverage.text)
        invalidTime, self.invalidRequest, self.invalidResponse = self.getTime(
            self.addParameter.text, self.addInvalid.text, self.addAverage.text)
        self.showResults.text = "Valid username: "******"\t Time: "
        self.showResults.text += str(validTime) + "\n"
        self.showResults.text += "Invalid username: "******"\t Time: "
        self.showResults.text += str(invalidTime)
        self.twoUserResult = self.showResults.text

    def timeUserList(self, event):
        """ Method that reads the usernames from file and sends
            them to getUserListTimes, and if there is no file so the
            program is going to return anything """

        if (self.curRequest == None):
            self.debugOutput("Timing Attack does not have a request")
            return
        try:
            # stores the file
            file = self.chooser.getSelectedFile()

            # reads it
            scan = Scanner(file)
            readFile = ""
            while scan.hasNext():
                readFile += scan.nextLine()

            # divides the file to a list of usernames
            self.userList = readFile.split(self.addSeparatorList.text)

            # set all the list buttons to visible
            self.downloadResultList.setVisible(True)
            self.listViewResults.setVisible(True)
            self.listViewReq.setVisible(True)
            self.listViewResponses.setVisible(True)
            # gets the time for each username
            threading.Thread(target=self.getUserListTimes).start()

        # it will handle the error and send a message about it
        except:
            self.debugOutput("No File Submitted")
        return

    def getUserListTimes(self):
        """ Method that prints the time taken to return responses
        for each username from file (called by timeUserList) """

        self.listViewReq.setVisible(True)
        self.showResultsList.text = ""
        self.listResponses = ""
        self.listRequests = ""
        helpers = self.callbacks.getHelpers()
        for index, username in enumerate(self.userList):
            self.showResultsList.text += "Username: "******"\t Time: "
            time, request, response = self.getTime(self.addParameterList.text,
                                                   username,
                                                   self.addAverageList.text)
            self.showResultsList.text += str(time) + "\n"

            self.listResponses += ":: Response " + str(
                index) + " ::\n" + "Username: "******"\n\n"
            self.listResponses += helpers.bytesToString(
                response) + "\n\n\n\n\n"

            self.listRequests += ":: Request " + str(
                index) + " ::\n" + "Username: "******"\n\n"
            self.listRequests += helpers.bytesToString(request) + "\n\n\n\n\n"

        self.listResults = self.showResultsList.text
        return

    def getTime(self, paramName, paramInput, numTriesText):
        """ Method that takes in a username and returns the time taken to get
        its response (called by getTwoUserTimes and getUserListTimes) """

        try:
            numTries = int(numTriesText)
        except:
            self.debugOutput("Sample size must be an integer")

        # keeps a reference to helpers
        helpers = self.callbacks.getHelpers()

        # Get the request
        request = self.curRequest.getRequest()

        # Get request information
        requestInfo = helpers.analyzeRequest(request)

        # loop through parameters
        for i in requestInfo.getParameters():
            # find username parameter and change its value
            if (i.getName() == paramName):
                # it creates the request
                buildParam = helpers.buildParameter(paramName, paramInput,
                                                    i.getType())
                newRequest = helpers.updateParameter(request, buildParam)

        if 'newRequest' not in locals():
            self.debugOutput("Parameter " + paramName +
                             " cannot be found in request")
        # it builds an http service to send a request to the website
        httpService = self.curRequest.getHttpService()
        useHttps = True if httpService.getProtocol() == "https" else False
        httpService = helpers.buildHttpService(httpService.getHost(),
                                               httpService.getPort(), useHttps)

        getTime = 0
        for i in range(numTries):
            # starts the time and it sends the changed request with valid parameter
            start = time.clock()
            makeRequest = self.callbacks.makeHttpRequest(
                httpService, newRequest)
            makeRequest.getResponse()
            getTime += time.clock() - start

        makeRequest = self.callbacks.makeHttpRequest(httpService, newRequest)
        request = makeRequest.getRequest()
        response = makeRequest.getResponse()
        # return the response
        return getTime / numTries, request, response

    ####################################################
    # SECTION 3: VIEW REQUEST/RESPONSE/RESULTS BUTTONS #
    ####################################################

    def showListRequest(self, event):
        """ Method that shows the request from a file of usernames """
        helpers = self.callbacks.getHelpers()
        self.showResultsList.text = self.listRequests

    def showListResults(self, event):
        """ Show results for list """
        self.showResultsList.text = self.listResults

    def showListResponses(self, event):
        """ Show responses for list """
        self.showResultsList.text = self.listResponses

    def showResultsTop(self, event):
        """ Show results on top """
        self.showResults.text = self.twoUserResult

    def showRequestTop(self, event):
        """ Show request on top """
        helpers = self.callbacks.getHelpers()
        self.showResults.text = ":: Valid Request :: \n"
        self.showResults.text += helpers.bytesToString(self.validRequest)
        self.showResults.text += "\n\n\n:: Invalid Request :: \n"
        self.showResults.text += helpers.bytesToString(self.invalidRequest)

    def showValidResponseTop(self, event):
        """ Show valid response on top """
        helpers = self.callbacks.getHelpers()
        self.showResults.text = helpers.bytesToString(self.validResponse)

    def showInvalidResponseTop(self, event):
        """ Show invalid response on top """
        helpers = self.callbacks.getHelpers()
        self.showResults.text = helpers.bytesToString(self.invalidResponse)

    ##############################
    # SECTION 4: DOWNLOAD BUTTON #
    ##############################

    def downloadResults(self, event):
        """ Method that allows user to download file to get the response's time """
        try:
            if (self.showResultsList.text == ""):
                return
            file = open(self.get_download_path() + "/downloadresults.txt", "w")
            file.write(self.showResultsList.text)
            file.close()
            self.debugOutput(
                "Download successful! \nCheck your downloads folder for the file."
            )
        except:
            self.debugOutput("Download failed.")

    def get_download_path(self):
        """ Method to find path of download folder (called by downloadResults),
         and it returns the default downloads path for linux or windows """

        if os.name == 'nt':
            import winreg
            sub_key = r'SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders'
            downloads_guid = '{374DE290-123F-4565-9164-39C4925E467B}'
            with winreg.OpenKey(winreg.HKEY_CURRENT_USER, sub_key) as key:
                location = winreg.QueryValueEx(key, downloads_guid)[0]
            return location
        else:
            return os.path.join(os.path.expanduser('~'), 'downloads')

    ###########################
    # SECTION 5: DEBUG BUTTON #
    ###########################

    def debugOutput(self, message):
        """ Write a debug message in the debug box """

        self.debugText.text = message

        self.debugTextScroll.setVisible(True)
        self.viewDebug.setText("Close Debug Output")
        self.debugOn = True

    def showDebug(self, event):
        """ Open or close debug box """

        if self.debugOn:
            self.debugTextScroll.setVisible(False)
            self.viewDebug.setText("View Debug Output")
            self.debugOn = False
            self.debugText.text = ""
        else:
            self.debugTextScroll.setVisible(True)
            self.viewDebug.setText("Close Debug Output")
            self.debugOn = True

    ###################################
    # SECTION 6: TAB RECIEVES REQUEST #
    ###################################

    def getRequest(self, messageList):
        """ Method that stores the request sent from proxy """

        self.curRequest = messageList[0]

        # Show request in top box
        helpers = self.callbacks.getHelpers()
        self.showResults.text = helpers.bytesToString(
            self.curRequest.getRequest())
        # Show request in bottom box
        helpers = self.callbacks.getHelpers()
        self.showResultsList.text = helpers.bytesToString(
            self.curRequest.getRequest())
    def registerExtenderCallbacks(self, callbacks):
        self._callbacks = callbacks
        self.helpers = callbacks.helpers
        callbacks.setExtensionName("Orchy-Webhook")
        self.frame = JPanel()
        self.frame.setSize(1024, 786)
        self.frame.setLayout(None)
        self.plugin_path = os.getcwd()
        self.db_file_path = os.path.join(os.getcwd(), 'burp_db.json')
        self.cwe_dict = json.load(open(self.db_file_path, 'r'))
        self.results = {}
        self.severity_dict = {
            'Low': 1,
            'Medium': 2,
            'High': 3,
            'Information': 0,
            'Info': 0,
        }
        self.urls = []
        self.confidence_dict = {'Certain': 3, 'Firm': 2, 'Tentative': 1}

        callbacks.registerScannerListener(self)

        button1 = JButton(ImageIcon(
            ((ImageIcon(self.plugin_path +
                        "/refresh.jpg")).getImage()).getScaledInstance(
                            13, 13, SCALE_SMOOTH)),
                          actionPerformed=self.refresh)
        button1.setBounds(30, 50, 22, 22)
        lbl0 = JLabel("Orchestron Webhook:")
        lbl0.setFont(Font("", Font.BOLD, 12))
        lbl0.setForeground(Color(0xFF7F50))
        lbl0.setBounds(60, 20, 200, 20)
        lbl1 = JLabel('Host')
        lbl1.setBounds(60, 50, 100, 20)
        self.txt1 = JComboBox()
        self.txt1.setBounds(200, 50, 220, 24)
        lbl2 = JLabel("Webhook Url")
        lbl2.setBounds(60, 80, 100, 20)
        self.txt2 = JTextField('', 300)
        self.txt2.setBounds(200, 80, 220, 24)
        lbl3 = JLabel("Authorization Token")
        lbl3.setBounds(60, 110, 200, 20)
        self.txt3 = JTextField('', 60)
        self.txt3.setBounds(200, 110, 220, 24)
        lbl4 = JLabel("Engagement-ID")
        lbl4.setBounds(60, 140, 200, 20)
        self.txt4 = JTextField('', 40)
        self.txt4.setBounds(200, 140, 220, 24)
        button2 = JButton('Push Results', actionPerformed=self.push)
        button2.setBounds(200, 170, 120, 24)
        self.message = JLabel('')
        self.message.setBounds(330, 170, 180, 24)
        self.frame.add(button1)
        self.frame.add(lbl0)
        self.frame.add(lbl1)
        self.frame.add(self.txt1)
        self.frame.add(lbl2)
        self.frame.add(self.txt2)
        self.frame.add(lbl3)
        self.frame.add(self.txt3)
        self.frame.add(lbl4)
        self.frame.add(self.txt4)
        self.frame.add(button2)
        self.frame.add(self.message)

        callbacks.customizeUiComponent(self.frame)
        callbacks.addSuiteTab(self)
예제 #25
0
class BurpExtender(IBurpExtender, ITab, IExtensionStateListener):
    # Define the global variables for the burp plugin
    EXTENSION_NAME = "UPnP BHunter"
    ipv4_selected = True
    services_dict = {}
    ip_service_dict = {}
    STOP_THREAD = False

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    def getTabCaption(self):
        return self.EXTENSION_NAME

    def getUiComponent(self):
        return self.pluginTab

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

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

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

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

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

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

            if self.STOP_THREAD:
                return

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

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

    def sendMsearch(self, ssdp_req, ssdp_ip, ssdp_port):
        # Send the ssdp request and retrieve response
        buf_resp = set()
        if self.ipv4_selected:
            print("[+] Creating IPv4 SSDP multicast request")
            sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        else:
            print("[+] Creating IPv6 SSDP multicast request")
            sock = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)
        sock.setblocking(0)
        # Sending ssdp requests
        while len(ssdp_req):
            # Blocking socket client until the request is completely sent
            try:
                sent = sock.sendto(ssdp_req.encode("ASCII"),
                                   (ssdp_ip, ssdp_port))
                ssdp_req = ssdp_req[sent:]
            except socket.error, exc:
                if exc.errno != errno.EAGAIN:
                    print("[E] Got error %s with socket when sending") % exc
                    sock.close()
                    raise exc
                print("[!] Blocking socket until ", len(ssdp_req), " is sent.")
                select.select([], [sock], [])
                continue
        # Retrieving ssdp responses
        num_resp = 0
        while sock:
            # Blocking socket until there are ssdp responses to be read or timeout is reached
            readable, __, __ = select.select([sock], [], [], self.SSDP_TIMEOUT)
            if not readable:
                # Timeout reached without receiving any ssdp response
                if num_resp == 0:
                    print(
                        "[!] Got timeout without receiving any ssdp response.")
                break
            else:
                num_resp = num_resp + 1
                # Almost an ssdp response was received
                if readable[0]:
                    try:
                        data = sock.recv(1024)
                        if data:
                            buf_resp.add(data.decode('ASCII'))
                    except socket.error, exc:
                        print("[E] Got error %s with socket when receiving"
                              ) % exc
                        sock.close()
                        raise exc
예제 #26
0
class BurpExtender(IBurpExtender, IExtensionStateListener, IHttpListener, ITab,
                   FocusListener, ActionListener, MouseAdapter):
    _version = "0.2"
    _name = "PyRules"
    _varsStorage = _name + "_vars"
    _scriptStorage = _name + "_script"

    _enabled = 0
    _vars = {}

    def registerExtenderCallbacks(self, callbacks):
        print "Load:" + self._name + " " + self._version

        self.callbacks = callbacks
        self.helpers = callbacks.helpers

        #Create Tab layout
        self.jVarsPane = JTextPane()
        self.jVarsPane.setFont(Font('Monospaced', Font.PLAIN, 11))
        self.jVarsPane.addFocusListener(self)

        self.jMenuPanel = JPanel()
        self.jLeftUpPanel = JPanel()

        self.jEnable = JCheckBox()
        self.jEnable.setFont(Font('Monospaced', Font.BOLD, 11))
        self.jEnable.setForeground(Color(0, 0, 204))
        self.jEnable.setText(self._name)
        self.jEnable.addActionListener(self)

        self.jDocs = JLabel()
        self.jDocs.setFont(Font('Monospaced', Font.PLAIN, 11))
        self.jDocs.setForeground(Color(51, 102, 255))
        self.jDocs.setText(Strings.docs_titel)
        self.jDocs.setToolTipText(Strings.docs_tooltip)
        self.jDocs.addMouseListener(self)

        self.jConsoleText = JTextArea()
        self.jConsoleText.setFont(Font('Monospaced', Font.PLAIN, 10))
        self.jConsoleText.setBackground(Color(244, 246, 247))
        self.jConsoleText.setEditable(0)
        self.jConsoleText.setWrapStyleWord(1)
        self.jConsoleText.setRows(10)
        self.jScrollConsolePane = JScrollPane()
        self.jScrollConsolePane.setViewportView(self.jConsoleText)
        #set initial text
        self.jConsoleText.setText(Strings.console_disable)

        self.jMenuPanelLayout = GroupLayout(self.jMenuPanel)
        self.jMenuPanel.setLayout(self.jMenuPanelLayout)
        self.jMenuPanelLayout.setHorizontalGroup(
            self.jMenuPanelLayout.createParallelGroup(
                GroupLayout.Alignment.LEADING).addGroup(
                    self.jMenuPanelLayout.createSequentialGroup().addComponent(
                        self.jEnable).addPreferredGap(
                            LayoutStyle.ComponentPlacement.RELATED, 205,
                            32767).addComponent(self.jDocs)))

        self.jMenuPanelLayout.setVerticalGroup(
            self.jMenuPanelLayout.createParallelGroup(
                GroupLayout.Alignment.LEADING).addGroup(
                    self.jMenuPanelLayout.createSequentialGroup().addGroup(
                        self.jMenuPanelLayout.createParallelGroup(
                            GroupLayout.Alignment.BASELINE).addComponent(
                                self.jEnable).addComponent(self.jDocs)).addGap(
                                    0, 7, 32767)))

        self.jConsolePane = JPanel()
        self.jConsoleLayout = GroupLayout(self.jConsolePane)
        self.jConsolePane.setLayout(self.jConsoleLayout)
        self.jConsoleLayout.setHorizontalGroup(
            self.jConsoleLayout.createParallelGroup(
                GroupLayout.Alignment.LEADING).addComponent(
                    self.jScrollConsolePane))
        self.jConsoleLayout.setVerticalGroup(
            self.jConsoleLayout.createParallelGroup(
                GroupLayout.Alignment.LEADING).addGroup(
                    GroupLayout.Alignment.TRAILING,
                    self.jConsoleLayout.createSequentialGroup().addComponent(
                        self.jScrollConsolePane, GroupLayout.DEFAULT_SIZE, 154,
                        32767).addContainerGap()))
        self.jLeftUpPanelLayout = GroupLayout(self.jLeftUpPanel)
        self.jLeftUpPanel.setLayout(self.jLeftUpPanelLayout)
        self.jLeftUpPanelLayout.setHorizontalGroup(
            self.jLeftUpPanelLayout.createParallelGroup(
                GroupLayout.Alignment.LEADING).addComponent(
                    self.jConsolePane, GroupLayout.DEFAULT_SIZE,
                    GroupLayout.DEFAULT_SIZE,
                    32767).addComponent(self.jMenuPanel,
                                        GroupLayout.DEFAULT_SIZE,
                                        GroupLayout.DEFAULT_SIZE,
                                        GroupLayout.PREFERRED_SIZE))
        self.jLeftUpPanelLayout.setVerticalGroup(
            self.jLeftUpPanelLayout.
            createParallelGroup(GroupLayout.Alignment.LEADING).addGroup(
                GroupLayout.Alignment.TRAILING,
                self.jLeftUpPanelLayout.createSequentialGroup().addComponent(
                    self.jMenuPanel, GroupLayout.PREFERRED_SIZE,
                    GroupLayout.DEFAULT_SIZE,
                    GroupLayout.PREFERRED_SIZE).addPreferredGap(
                        LayoutStyle.ComponentPlacement.RELATED).addComponent(
                            self.jConsolePane, GroupLayout.DEFAULT_SIZE,
                            GroupLayout.DEFAULT_SIZE, 32767)))

        self.jScrollpaneLeftDown = JScrollPane()
        self.jScrollpaneLeftDown.setViewportView(self.jVarsPane)

        self.jSplitPaneLeft = JSplitPane(JSplitPane.VERTICAL_SPLIT,
                                         self.jLeftUpPanel,
                                         self.jScrollpaneLeftDown)
        self.jSplitPaneLeft.setDividerLocation(300)

        self.jScriptPane = JTextPane()
        self.jScriptPane.setFont(Font('Monospaced', Font.PLAIN, 11))
        self.jScriptPane.addMouseListener(self)

        self.JScrollPaneRight = JScrollPane()
        self.JScrollPaneRight.setViewportView(self.jScriptPane)

        self.jSplitPane = JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
                                     self.jSplitPaneLeft,
                                     self.JScrollPaneRight)
        self.jSplitPane.setDividerLocation(400)

        #Load saved saved settings
        ##Load vars
        vars = callbacks.loadExtensionSetting(self._varsStorage)
        if vars:
            vars = base64.b64decode(vars)
        else:
            # try to load the example
            try:
                with open("examples/Simple-CSRF-vars.py") as fvars:
                    vars = fvars.read()
            # load the default text
            except:
                vars = Strings.vars

        ## initiate the persistant variables
        locals_ = {}
        try:
            exec(vars, {}, locals_)
        except Exception as e:
            print e
        self._vars = locals_

        ## update the vars screen
        self.jVarsPane.document.insertString(self.jVarsPane.document.length,
                                             vars, SimpleAttributeSet())

        ##Load script
        script = callbacks.loadExtensionSetting(self._scriptStorage)
        if script:
            script = base64.b64decode(script)
        else:
            # try to load the example
            try:
                with open("examples/Simple-CSRF-script.py") as fscript:
                    script = fscript.read()
            # load the default text
            except:
                script = Strings.script

        ## compile the rules
        self._script = script
        self._code = ''

        try:
            self._code = compile(script, '<string>', 'exec')
        except Exception as e:
            print(
                '{}\nReload extension after you correct the error.'.format(e))

        ## update the rules screen
        self.jScriptPane.document.insertString(
            self.jScriptPane.document.length, script, SimpleAttributeSet())

        #Register Extension
        callbacks.customizeUiComponent(self.getUiComponent())
        callbacks.addSuiteTab(self)
        callbacks.registerExtensionStateListener(self)
        callbacks.registerHttpListener(self)

        self.jScriptPane.requestFocus()

    def getUiComponent(self):
        return self.jSplitPane

    def getTabCaption(self):
        return self._name

    def actionPerformed(self, event):
        #Check box was clicked
        if self.jEnable == event.getSource():
            if self._enabled == 1:
                self._enabled = 0
                # console content shows help
                self.jConsoleText.setText(Strings.console_disable)
            else:
                self._enabled = 1
                # console content displays the current persistent variable state
                self.jConsoleText.setText(Strings.console_state)
                self.jConsoleText.append(pformat(self._vars))
                self.jConsoleText.append(Strings.extra_line)
                self.jConsoleText.append(Strings.console_log)
        return

    def mouseClicked(self, event):
        if event.source == self.jDocs:
            uri = URI.create("https://github.com/DanNegrea/PyRules")
            if uri and Desktop.isDesktopSupported() and Desktop.getDesktop(
            ).isSupported(Desktop.Action.BROWSE):
                Desktop.getDesktop().browse(uri)
        return

    def focusGained(self, event):

        if self.jConsolePane == event.getSource():
            pass
            #print "Status pane gained focus" #debug
        return

    def focusLost(self, event):
        #Reinitialize the persistent values
        if self.jVarsPane == event.getSource():
            # get the text from the pane
            end = self.jVarsPane.document.length
            vars = self.jVarsPane.document.getText(0, end)

            # compute the new values
            locals_ = {}
            exec(vars, {}, locals_)
            self._vars = locals_

            # display the new result in console
            self.jConsoleText.append(Strings.console_state)
            self.jConsoleText.append(pformat(self._vars))
            self.jConsoleText.append(Strings.extra_line)
            self.jConsoleText.append(Strings.console_log)

            # scroll to bottom
            verticalScrollBar = self.jScrollConsolePane.getVerticalScrollBar()
            verticalScrollBar.setValue(verticalScrollBar.getMaximum())
        return

    def extensionUnloaded(self):
        try:
            #Save the latestest vars and script text
            ## save vars
            end = self.jVarsPane.document.length
            vars = self.jVarsPane.document.getText(0, end)
            vars = base64.b64encode(vars)
            self.callbacks.saveExtensionSetting(self._varsStorage, vars)
            ## save script/rules
            end = self.jScriptPane.document.length
            script = self.jScriptPane.document.getText(0, end)
            script = base64.b64encode(script)
            self.callbacks.saveExtensionSetting(self._scriptStorage, script)
        except Exception:
            traceback.print_exc(file=self.callbacks.getStderr())
        print "Unloaded"  #debug
        return

    def processHttpMessage(self, toolFlag, messageIsRequest, messageInfo):
        if self._enabled == 0:
            return

        try:
            locals_ = {
                'extender': self,
                'callbacks': self.callbacks,
                'helpers': self.helpers,
                'toolFlag': toolFlag,
                'messageIsRequest': messageIsRequest,
                'messageInfo': messageInfo,
                'log': self.log
            }
            # add the _vars as gloval variables
            locals_ = dict(locals_, **self._vars)

            # execute the script/rules
            try:
                exec(self.getCode, {}, locals_)
            # catch exit() call inside the rule
            except SystemExit:
                pass

            # update the persistant variables by searching the local variables with the same name
            for key in self._vars:
                # assumption self._vars dictionary is smaller than locals_
                if key in locals_:
                    self._vars[key] = locals_[key]
        except Exception:
            traceback.print_exc(file=self.callbacks.getStderr())
        return

    #Returns the compiled script
    @property
    def getCode(self):
        end = self.jScriptPane.document.length
        script = self.jScriptPane.document.getText(0, end)

        # if the script hasn't changed return the already compile text
        if script == self._script:
            return self._code
        self._script = script

        # compile, store and return the result
        self._code = compile(script, '<string>', 'exec')
        return self._code

    #Log the information into the console screen
    def log(self, obj):
        # if string just append. else use pformat from pprint
        if isinstance(obj, str):
            self.jConsoleText.append(obj + "\n")
        else:
            self.jConsoleText.append(pformat(obj) + "\n")
        # scroll to bottom
        verticalScrollBar = self.jScrollConsolePane.getVerticalScrollBar()
        verticalScrollBar.setValue(verticalScrollBar.getMaximum())
        return
예제 #27
0
    def registerExtenderCallbacks(self, this_callbacks):  ### IBurpExtender
        global callbacks, helpers
        global extension_enable, in_scope_only
        global remove_csrf_headers, remove_csrf_params, change_method_to_post
        global change_ct_to_json, change_ct_to_plain, change_to_get

        callbacks = this_callbacks
        helpers = callbacks.getHelpers()
        callbacks.setExtensionName(NAME)

        self.settings = JPanel(GridBagLayout())
        c = GridBagConstraints()

        self.extension_enable_box = JCheckBox('Enable extension',
                                              extension_enable)
        self.setFontBold(self.extension_enable_box)
        self.extension_enable_box.setForeground(Color(0, 0, 153))
        c.insets = Insets(5, 5, 5, 5)
        c.gridx = 0
        c.gridy = 0
        c.gridwidth = 1
        c.weightx = 1
        c.fill = GridBagConstraints.NONE
        c.anchor = GridBagConstraints.WEST
        self.settings.add(self.extension_enable_box, c)

        self.in_scope_only_box = JCheckBox('Modify only in-scope requests',
                                           in_scope_only)
        self.setFontBold(self.in_scope_only_box)
        self.in_scope_only_box.setForeground(Color(0, 0, 153))
        c.insets = Insets(40, 5, 5, 5)
        c.gridx = 0
        c.gridy = 1
        self.settings.add(self.in_scope_only_box, c)

        self.remove_csrf_headers_box = JCheckBox('Remove CSRF headers',
                                                 remove_csrf_params)
        self.setFontBold(self.remove_csrf_headers_box)
        self.remove_csrf_headers_box.setForeground(Color(0, 0, 153))
        c.insets = Insets(40, 5, 5, 5)
        c.gridx = 0
        c.gridy = 2
        self.settings.add(self.remove_csrf_headers_box, c)

        remove_csrf_headers_box_lbl = JLabel(
            'Check to remove headers with CSRF tokens from all requests.')
        self.setFontItalic(remove_csrf_headers_box_lbl)
        c.insets = Insets(5, 5, 5, 5)
        c.gridx = 0
        c.gridy = 3
        self.settings.add(remove_csrf_headers_box_lbl, c)

        self.remove_csrf_params_box = JCheckBox('Remove CSRF parameters',
                                                remove_csrf_params)
        self.setFontBold(self.remove_csrf_params_box)
        self.remove_csrf_params_box.setForeground(Color(0, 0, 153))
        c.gridx = 0
        c.gridy = 4
        self.settings.add(self.remove_csrf_params_box, c)

        remove_csrf_params_box_lbl = JLabel(
            'Check to remove URL/body parameters with CSRF tokens from all requests. URL-encoded, multipart, JSON parameters are supported.'
        )
        self.setFontItalic(remove_csrf_params_box_lbl)
        c.gridx = 0
        c.gridy = 5
        self.settings.add(remove_csrf_params_box_lbl, c)

        self.change_method_to_post_box = JCheckBox(
            'Change HTTP method to POST', change_method_to_post)
        self.setFontBold(self.change_method_to_post_box)
        self.change_method_to_post_box.setForeground(Color(0, 0, 153))
        c.gridx = 0
        c.gridy = 6
        self.settings.add(self.change_method_to_post_box, c)

        change_method_to_post_lbl = JLabel(
            'Check to convert PUT/DELETE/PATCH method to POST in all requests.'
        )
        self.setFontItalic(change_method_to_post_lbl)
        c.gridx = 0
        c.gridy = 7
        self.settings.add(change_method_to_post_lbl, c)

        self.change_ct_to_json_box = JCheckBox('Change media type to json',
                                               change_ct_to_json)
        self.setFontBold(self.change_ct_to_json_box)
        self.change_ct_to_json_box.setForeground(Color(0, 0, 153))
        c.gridx = 0
        c.gridy = 8
        self.settings.add(self.change_ct_to_json_box, c)

        change_ct_to_json_lbl = JLabel(
            'Check to convert body to json and set Content-Type to application/json in url-encoded requests.'
        )
        self.setFontItalic(change_ct_to_json_lbl)
        c.gridx = 0
        c.gridy = 9
        self.settings.add(change_ct_to_json_lbl, c)

        self.change_ct_to_plain_box = JCheckBox(
            'Change Content-Type to text/plain', change_ct_to_plain)
        self.setFontBold(self.change_ct_to_plain_box)
        self.change_ct_to_plain_box.setForeground(Color(0, 0, 153))
        c.gridx = 0
        c.gridy = 10
        self.settings.add(self.change_ct_to_plain_box, c)

        change_ct_to_plain_lbl = JLabel(
            'Check to set Content-Type to text/plain in request with non-simple media type. Simple media types - application/application/x-www-form-urlencoded, text/plain, multipart/form-data.'
        )
        self.setFontItalic(change_ct_to_plain_lbl)
        c.gridx = 0
        c.gridy = 11
        self.settings.add(change_ct_to_plain_lbl, c)

        self.change_to_get_box = JCheckBox('Change to GET', change_to_get)
        self.setFontBold(self.change_to_get_box)
        self.change_to_get_box.setForeground(Color(0, 0, 153))
        c.gridx = 0
        c.gridy = 12
        self.settings.add(self.change_to_get_box, c)

        change_to_get_lbl = JLabel(
            'Check to convert POST/PUT/DELETE/PATCH url-encoded requests to GET.'
        )
        self.setFontItalic(change_to_get_lbl)
        c.gridx = 0
        c.gridy = 13
        self.settings.add(change_to_get_lbl, c)

        self.csrf_headers_params = JPanel(GridBagLayout())
        c = GridBagConstraints()

        lblParams = JLabel("CSRF parameters:")
        self.setFontBold(lblParams)
        lblParams.setForeground(Color(0, 0, 153))
        c.gridx = 0
        c.gridy = 0
        c.insets = Insets(5, 5, 5, 5)
        c.fill = GridBagConstraints.NONE
        c.anchor = GridBagConstraints.FIRST_LINE_END
        self.csrf_headers_params.add(lblParams, c)

        self.csrf_param_text_field = JTextField()
        c.fill = GridBagConstraints.BOTH
        c.gridx = 1
        c.gridy = 0
        self.csrf_headers_params.add(self.csrf_param_text_field, c)

        lblParamsNote = JLabel(
            "Remove parameter from request if name contains")
        self.setFontItalic(lblParamsNote)
        c.fill = GridBagConstraints.NONE
        c.gridx = 0
        c.gridy = 1
        self.csrf_headers_params.add(lblParamsNote, c)

        self.csrf_params_text_area = JTextArea()
        self.csrf_params_text_area.setColumns(20)
        self.csrf_params_text_area.setRows(10)
        self.csrf_params_text_area.setEditable(False)
        c.fill = GridBagConstraints.BOTH
        self.csrf_params_mouse_listener = TextAreaMouseListener(
            self.csrf_params_text_area)
        self.csrf_params_text_area.addMouseListener(
            self.csrf_params_mouse_listener)
        for name in csrf_params_names:
            self.csrf_params_text_area.append(name + os.linesep)
        c.gridx = 1
        c.gridy = 1
        sp = JScrollPane(self.csrf_params_text_area)
        self.csrf_headers_params.add(sp, c)

        buttonsPanel = JPanel(GridBagLayout())
        _c = GridBagConstraints()
        _c.insets = Insets(3, 3, 3, 3)
        _c.gridx = 0
        _c.gridy = 0
        _c.fill = GridBagConstraints.BOTH
        _c.weightx = 1
        _c.gridwidth = 1

        handlers = ButtonHandlers(self.csrf_param_text_field,
                                  self.csrf_params_text_area,
                                  self.csrf_params_mouse_listener,
                                  csrf_params_names)
        self.csrf_param_add_button = JButton(
            'Add', actionPerformed=handlers.handler_add)
        self.csrf_param_rm_button = JButton(
            'Remove', actionPerformed=handlers.handler_rm)
        self.csrf_param_restore_button = JButton(
            'Restore', actionPerformed=handlers.handler_restore)
        buttonsPanel.add(self.csrf_param_add_button, _c)
        _c.gridy = 1
        buttonsPanel.add(self.csrf_param_rm_button, _c)
        _c.gridy = 2
        buttonsPanel.add(self.csrf_param_restore_button, _c)
        _c.gridy = 3

        c.gridx = 2
        c.gridy = 1
        c.fill = GridBagConstraints.NONE
        self.csrf_headers_params.add(buttonsPanel, c)

        lblHeaders = JLabel("CSRF headers:")
        self.setFontBold(lblHeaders)
        lblHeaders.setForeground(Color(0, 0, 153))
        c.gridx = 0
        c.gridy = 2
        c.insets = Insets(40, 5, 5, 5)
        c.fill = GridBagConstraints.NONE
        c.anchor = GridBagConstraints.FIRST_LINE_END
        self.csrf_headers_params.add(lblHeaders, c)

        self.csrf_header_text_field = JTextField()
        c.fill = GridBagConstraints.BOTH
        c.gridx = 1
        c.gridy = 2
        self.csrf_headers_params.add(self.csrf_header_text_field, c)

        lblHeadersNote = JLabel("Remove header from request if name equals to")
        self.setFontItalic(lblHeadersNote)
        c.fill = GridBagConstraints.NONE
        c.insets = Insets(5, 5, 5, 5)
        c.gridx = 0
        c.gridy = 3
        self.csrf_headers_params.add(lblHeadersNote, c)

        self.csrf_headers_text_area = JTextArea()
        self.csrf_headers_text_area.setColumns(20)
        self.csrf_headers_text_area.setRows(10)
        self.csrf_headers_text_area.setEditable(False)
        c.fill = GridBagConstraints.BOTH
        self.csrf_headers_mouse_listener = TextAreaMouseListener(
            self.csrf_headers_text_area)
        self.csrf_headers_text_area.addMouseListener(
            self.csrf_headers_mouse_listener)
        for name in csrf_headers_names:
            self.csrf_headers_text_area.append(name + os.linesep)
        c.gridx = 1
        c.gridy = 3
        sp = JScrollPane(self.csrf_headers_text_area)
        self.csrf_headers_params.add(sp, c)

        buttonsPanel = JPanel(GridBagLayout())
        _c = GridBagConstraints()
        _c.insets = Insets(3, 3, 3, 3)
        _c.gridx = 0
        _c.gridy = 0
        _c.fill = GridBagConstraints.BOTH
        _c.weightx = 1
        _c.gridwidth = 1

        handlers = ButtonHandlers(self.csrf_header_text_field,
                                  self.csrf_headers_text_area,
                                  self.csrf_headers_mouse_listener,
                                  csrf_headers_names)
        self.csrf_header_add_button = JButton(
            'Add', actionPerformed=handlers.handler_add)
        self.csrf_header_rm_button = JButton(
            'Remove', actionPerformed=handlers.handler_rm)
        self.csrf_header_restore_button = JButton(
            'Restore', actionPerformed=handlers.handler_restore)
        buttonsPanel.add(self.csrf_header_add_button, _c)
        _c.gridy = 1
        buttonsPanel.add(self.csrf_header_rm_button, _c)
        _c.gridy = 2
        buttonsPanel.add(self.csrf_header_restore_button, _c)
        _c.gridy = 3

        c.gridx = 2
        c.gridy = 3
        c.fill = GridBagConstraints.NONE
        self.csrf_headers_params.add(buttonsPanel, c)

        self.whitelist = JPanel(GridBagLayout())
        c = GridBagConstraints()

        lblWhitelist = JLabel("URLs whitelist:")
        self.setFontBold(lblWhitelist)
        lblWhitelist.setForeground(Color(0, 0, 153))
        c.gridx = 0
        c.gridy = 0
        c.insets = Insets(5, 5, 5, 5)
        c.fill = GridBagConstraints.NONE
        c.anchor = GridBagConstraints.FIRST_LINE_END
        self.whitelist.add(lblWhitelist, c)

        self.whitelist_text_field = JTextField()
        c.fill = GridBagConstraints.BOTH
        c.gridx = 1
        c.gridy = 0
        self.whitelist.add(self.whitelist_text_field, c)

        lblWhitelistNote = JLabel(
            "Do not perform request modification if URL starts with")
        self.setFontItalic(lblWhitelistNote)
        c.fill = GridBagConstraints.NONE
        c.gridx = 0
        c.gridy = 1
        self.whitelist.add(lblWhitelistNote, c)

        self.whitelist_text_area = JTextArea()
        self.whitelist_text_area.setColumns(30)
        self.whitelist_text_area.setRows(10)
        self.whitelist_text_area.setEditable(False)
        c.fill = GridBagConstraints.BOTH
        self.whitelist_mouse_listener = TextAreaMouseListener(
            self.whitelist_text_area)
        self.whitelist_text_area.addMouseListener(
            self.whitelist_mouse_listener)
        c.gridx = 1
        c.gridy = 1
        sp = JScrollPane(self.whitelist_text_area)
        self.whitelist.add(sp, c)

        buttonsPanel = JPanel(GridBagLayout())
        _c = GridBagConstraints()
        _c.insets = Insets(3, 3, 3, 3)
        _c.gridx = 0
        _c.gridy = 0
        _c.fill = GridBagConstraints.BOTH
        _c.weightx = 1
        _c.gridwidth = 1

        handlers = ButtonHandlers(self.whitelist_text_field,
                                  self.whitelist_text_area,
                                  self.whitelist_mouse_listener, [])
        self.whitelist_add_button = JButton(
            'Add', actionPerformed=handlers.handler_add)
        self.whitelist_rm_button = JButton('Remove',
                                           actionPerformed=handlers.handler_rm)
        self.whitelist_clear_button = JButton(
            'Clear', actionPerformed=handlers.handler_restore)
        buttonsPanel.add(self.whitelist_add_button, _c)
        _c.gridy = 1
        buttonsPanel.add(self.whitelist_rm_button, _c)
        _c.gridy = 2
        buttonsPanel.add(self.whitelist_clear_button, _c)
        _c.gridy = 3

        c.gridx = 2
        c.gridy = 1
        c.fill = GridBagConstraints.NONE
        self.whitelist.add(buttonsPanel, c)

        self.tabs = JTabbedPane()
        self.tabs.addTab('Settings', self.settings)
        self.tabs.addTab('CSRF params/headers to remove',
                         self.csrf_headers_params)
        self.tabs.addTab('Requests whitelist', self.whitelist)

        callbacks.customizeUiComponent(self.tabs)
        callbacks.addSuiteTab(self)

        callbacks.registerProxyListener(self)

        callbacks.registerContextMenuFactory(
            SendToWhitelist(self.whitelist_text_area))

        print "Successfully loaded %s v%s by Mikhail Egorov @0ang3el" % (
            NAME, VERSION)
예제 #28
0
class EmployeeDetails(JPanel):
    def __init__(self, employees, dateprovider):
        JPanel.__init__(self, preferredSize=(400, 200))
        layout = BoxLayout(self, BoxLayout.Y_AXIS)
        self.setLayout(layout)
        self._employees = employees
        self._dateprovider = dateprovider
        employees.add_change_listener(self)
        self._create_status_label()
        self._create_name_editor()
        self._create_start_date_editor()
        self._create_save_button()
        self._create_vacation_display()
        self._adding_employee = False

    def _create_status_label(self):
        self._status_label = JLabel(name="status_label", font=Font(Font.SANS_SERIF, Font.PLAIN, 11))
        self.add(self._status_label)
        self._add_with_padding(self._status_label, 5)

    def _create_name_editor(self):
        self.add(JLabel(text="Employee Name:"))
        self._name_editor = FixedHeightTextField("name_input")
        self._add_with_padding(self._name_editor, 5)

    def _create_start_date_editor(self):
        self.add(JLabel(text="Start Date (yyyy-mm-dd):"))
        self._start_date_editor = FixedHeightTextField("start_input")
        self._add_with_padding(self._start_date_editor, 5)

    def _create_save_button(self):
        self._save_button = JButton("Save", name="save_button", visible=False)
        self._save_button.addActionListener(ListenerFactory(ActionListener, self._save_button_pushed))
        self._add_with_padding(self._save_button, 5)

    def _create_vacation_display(self):
        self._display = JTable(name="vacation_display")
        self._header = self._display.getTableHeader()
        self.add(self._header)
        self.add(self._display)

    def _add_with_padding(self, component, padding):
        self.add(component)
        self.add(Box.createRigidArea(Dimension(0, padding)))

    def show_employee(self, employee):
        self._name_editor.setText(employee.name)
        self._start_date_editor.setText(str(employee.startdate))
        self._name_editor.setEditable(False)
        self._start_date_editor.setEditable(False)
        self._save_button.setVisible(False)
        if self._adding_employee:
            self._adding_employee = False
        else:
            self._status_label.setText("")
        self._display.setVisible(True)
        self._display.setModel(VacationTableModel(employee, self._dateprovider))
        self._header.setVisible(True)

    def edit_new_employee(self):
        self._name_editor.setText("")
        self._start_date_editor.setText("")
        self._name_editor.setEditable(True)
        self._start_date_editor.setEditable(True)
        self._save_button.setVisible(True)
        self._display.setVisible(False)
        self._header.setVisible(False)
        self._adding_employee = True

    def _save_button_pushed(self, event):
        self._employees.add(self._name_editor.getText(), self._start_date_editor.getText())

    def employee_added(self, employee):
        self._status_label.setForeground(Color.BLACK)
        self._status_label.setText("Employee '%s' was added successfully." % employee.name)
        self._save_button.setVisible(False)

    def adding_employee_failed(self, reason):
        self._status_label.setForeground(Color.RED)
        self._status_label.setText(reason)
class BurpExtender(IBurpExtender, ISessionHandlingAction, ITab,
                   IContextMenuFactory, IContextMenuInvocation, ActionListener,
                   ITextEditor):

    #
    # implement IBurpExtender
    #

    def registerExtenderCallbacks(self, callbacks):
        # save the helpers for later
        self.helpers = callbacks.getHelpers()

        # set our extension name
        callbacks.setExtensionName("Custom Request Handler")
        callbacks.registerSessionHandlingAction(self)
        callbacks.registerContextMenuFactory(self)
        self._text_editor = callbacks.createTextEditor()
        self._text_editor.setEditable(False)

        #How much loaded the table row
        self.current_column_id = 0

        #GUI
        self._split_main = JSplitPane(JSplitPane.VERTICAL_SPLIT)
        self._split_top = JSplitPane(JSplitPane.HORIZONTAL_SPLIT)
        self._split_top.setPreferredSize(Dimension(100, 50))
        self._split_top.setDividerLocation(700)
        self._split_center = JSplitPane(JSplitPane.VERTICAL_SPLIT)

        boxVertical = swing.Box.createVerticalBox()
        box_top = swing.Box.createHorizontalBox()
        boxHorizontal = swing.Box.createHorizontalBox()
        buttonHorizontal = swing.Box.createHorizontalBox()
        boxVertical.add(boxHorizontal)

        box_regex = swing.Box.createVerticalBox()
        border = BorderFactory.createTitledBorder(LineBorder(Color.BLACK),
                                                  "Extract target strings",
                                                  TitledBorder.LEFT,
                                                  TitledBorder.TOP)
        box_regex.setBorder(border)

        self._add_btn = JButton("Add")
        self._add_btn.addActionListener(self)
        self._remove_btn = JButton("Remove")
        self._remove_btn.addActionListener(self)

        items = [
            'JSON',
            'Header',
        ]
        self._dropdown = JComboBox(items)
        type_panel = JPanel(FlowLayout(FlowLayout.LEADING))
        type_panel.add(JLabel('Type:'))
        type_panel.add(self._dropdown)

        self._jLabel_param = JLabel("Name:")
        self._param_error = JLabel("Name is required")

        self._param_error.setVisible(False)
        self._param_error.setFont(Font(Font.MONOSPACED, Font.ITALIC, 12))
        self._param_error.setForeground(Color.red)

        regex_checkbox = JPanel(FlowLayout(FlowLayout.LEADING))
        self._is_use_regex = JCheckBox("Extract from regex group")
        regex_checkbox.add(self._is_use_regex)
        self._jTextIn_param = JTextField(20)
        self._jLabel_regex = JLabel("Regex:")
        self._jTextIn_regex = JTextField(20)
        self._regex_error = JLabel("No group defined")
        self._regex_error.setVisible(False)
        self._regex_error.setFont(Font(Font.MONOSPACED, Font.ITALIC, 12))
        self._regex_error.setForeground(Color.red)

        self._param_panel = JPanel(FlowLayout(FlowLayout.LEADING))
        self._param_panel.add(self._jLabel_param)
        self._param_panel.add(self._jTextIn_param)
        self._param_panel.add(self._param_error)

        self._regex_panel = JPanel(FlowLayout(FlowLayout.LEADING))
        self._regex_panel.add(self._jLabel_regex)
        self._regex_panel.add(self._jTextIn_regex)
        self._regex_panel.add(self._regex_error)
        button_panel = JPanel(FlowLayout(FlowLayout.LEADING))
        #padding
        button_panel.add(JPanel())
        button_panel.add(JPanel())
        button_panel.add(JPanel())
        button_panel.add(self._add_btn)
        button_panel.add(self._remove_btn)
        box_regex.add(type_panel)
        box_regex.add(self._param_panel)
        box_regex.add(regex_checkbox)
        box_regex.add(self._regex_panel)
        buttonHorizontal.add(button_panel)
        box_regex.add(buttonHorizontal)
        boxVertical.add(box_regex)
        box_top.add(boxVertical)

        box_file = swing.Box.createHorizontalBox()
        checkbox_panel = JPanel(FlowLayout(FlowLayout.LEADING))
        border = BorderFactory.createTitledBorder(
            LineBorder(Color.BLACK), 'Payload Sets [Simple list]',
            TitledBorder.LEFT, TitledBorder.TOP)
        box_file.setBorder(border)

        box_param = swing.Box.createVerticalBox()
        box_param.add(checkbox_panel)

        file_column_names = [
            "Type",
            "Name",
            "Payload",
        ]
        data = []
        self.file_table_model = DefaultTableModel(data, file_column_names)
        self.file_table = JTable(self.file_table_model)
        self.file_table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF)

        column_model = self.file_table.getColumnModel()
        for count in xrange(column_model.getColumnCount()):
            column = column_model.getColumn(count)
            column.setPreferredWidth(160)

        self.file_table.preferredScrollableViewportSize = Dimension(500, 70)
        self.file_table.setFillsViewportHeight(True)

        panel_dropdown = JPanel(FlowLayout(FlowLayout.LEADING))
        self._file_dropdown = JComboBox(items)
        panel_dropdown.add(JLabel('Type:'))
        panel_dropdown.add(self._file_dropdown)
        box_param.add(panel_dropdown)
        box_param.add(JScrollPane(self.file_table))
        callbacks.customizeUiComponent(self.file_table)

        file_param_panel = JPanel(FlowLayout(FlowLayout.LEADING))

        self._file_param = JLabel("Name:")
        self._file_param_text = JTextField(20)

        file_param_panel.add(self._file_param)
        file_param_panel.add(self._file_param_text)
        self._error_message = JLabel("Name is required")
        self._error_message.setVisible(False)
        self._error_message.setFont(Font(Font.MONOSPACED, Font.ITALIC, 12))
        self._error_message.setForeground(Color.red)
        file_param_panel.add(self._error_message)
        box_param.add(file_param_panel)

        box_button_file = swing.Box.createVerticalBox()
        self._file_load_btn = JButton("Load")

        self._file_clear_btn = JButton("Clear")
        self._file_clear_btn.addActionListener(self)
        self._file_load_btn.addActionListener(self)
        box_button_file.add(self._file_load_btn)
        box_button_file.add(self._file_clear_btn)
        box_file.add(box_button_file)
        box_file.add(box_param)
        boxVertical.add(box_file)

        regex_column_names = [
            "Type",
            "Name",
            "Regex",
            "Start at offset",
            "End at offset",
        ]
        #clear target.json
        with open("target.json", "w") as f:
            pass
        data = []
        self.target_table_model = DefaultTableModel(data, regex_column_names)
        self.target_table = JTable(self.target_table_model)
        self.target_table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF)
        column_model = self.target_table.getColumnModel()
        for count in xrange(column_model.getColumnCount()):
            column = column_model.getColumn(count)
            column.setPreferredWidth(100)

        self.target_table.preferredScrollableViewportSize = Dimension(500, 70)
        self.target_table.setFillsViewportHeight(True)
        callbacks.customizeUiComponent(self.target_table)
        callbacks.customizeUiComponent(boxVertical)
        table_panel = swing.Box.createVerticalBox()
        table_panel.add(JScrollPane(self.target_table))
        box_top.add(table_panel)

        self._jScrollPaneOut = JScrollPane()
        #self._split_main.setBottomComponent(self._jScrollPaneOut)
        self._split_main.setBottomComponent(self._text_editor.getComponent())
        self._split_main.setTopComponent(box_top)
        self._split_main.setDividerLocation(450)
        callbacks.customizeUiComponent(self._split_main)
        callbacks.addSuiteTab(self)
        return

    def getTabCaption(self):
        return "CRH"

    def getUiComponent(self):
        return self._split_main

    def createMenuItems(self, invocation):
        menu = []
        ctx = invocation.getInvocationContext()
        menu.append(
            swing.JMenuItem("Send to CRH",
                            None,
                            actionPerformed=lambda x, inv=invocation: self.
                            menu_action(inv)))
        return menu if menu else None

    #
    # Implementation of Menu Action
    #
    def menu_action(self, invocation):
        try:
            invMessage = invocation.getSelectedMessages()
            message = invMessage[0].getResponse()
            res_info = self.helpers.analyzeResponse(message)
            send_res = message.tostring()
            self._text_editor.setText(send_res)
        except:
            print('Failed to add data to CRH tab.')

    #
    # Implementation of event action
    #
    def actionPerformed(self, actionEvent):

        # onclick add button of extract from regex group
        if actionEvent.getSource() is self._add_btn:
            start, end = self._text_editor.getSelectionBounds()
            value = None
            regex = None
            item = self._dropdown.getSelectedItem()
            param = self._jTextIn_param.getText()

            if len(param) is 0:
                self._param_error.setVisible(True)
                return
            self._param_error.setVisible(False)
            is_selected = self._is_use_regex.isSelected()
            if is_selected:
                start = None
                end = None
                regex = self._jTextIn_regex.getText()
                if len(regex) is 0:
                    self._regex_error.setVisible(True)
                    return

                req = self._text_editor.getText()
                try:
                    pattern = re.compile(regex)
                    match = pattern.search(req)
                    value = match.group(1) if match else None
                    if value is None:
                        raise IndexError
                except IndexError:
                    self._regex_error.setVisible(True)
                    return
                self._regex_error.setVisible(False)

            data = [
                item,
                param,
                regex,
                start,
                end,
            ]
            self.target_table_model.addRow(data)

            with open("target.json", "r+") as f:
                try:
                    json_data = json.load(f)
                except ValueError:
                    json_data = dict()
                if is_selected:
                    data = {
                        param: [
                            item,
                            regex,
                        ]
                    }
                else:
                    data = {
                        param: [
                            item,
                            start,
                            end,
                        ]
                    }
                json_data.update(data)
                self.write_file(f, json.dumps(json_data))

        # onclick remove button of extract from regex group
        if actionEvent.getSource() is self._remove_btn:
            rowno = self.target_table.getSelectedRow()
            if rowno != -1:
                column_model = self.target_table.getColumnModel()
                param_name = self.target_table_model.getValueAt(rowno, 1)
                start = self.target_table_model.getValueAt(rowno, 3)

                self.target_table_model.removeRow(rowno)
                with open("target.json", 'r+') as f:
                    try:
                        json_data = json.load(f)
                    except ValueError:
                        json_data = dict()

                    for key, value in json_data.items():
                        if value[1] == start and key == param_name:
                            try:
                                del json_data[key]
                            except IndexError:
                                print('Error: {0}: No such json key.'.format(
                                    key))
                    self.write_file(f, json.dumps(json_data))

        # onclick load button of payload sets
        if actionEvent.getSource() is self._file_load_btn:
            #clear table
            self.remove_all(self.file_table_model)
            self.current_column_id = 0

            target_param = self._file_param_text.getText()
            item = self._file_dropdown.getSelectedItem()

            if len(target_param) == 0:
                self._error_message.setVisible(True)
                return
            self._error_message.setVisible(False)

            chooser = JFileChooser()
            chooser.showOpenDialog(actionEvent.getSource())
            file_path = chooser.getSelectedFile().getAbsolutePath()
            with open(file_path, 'r') as f:
                while True:
                    line = f.readline().strip()
                    if not line:
                        break
                    data = [
                        item,
                        target_param,
                        line,
                    ]
                    self.file_table_model.addRow(data)

            with open('target.json', 'r+') as f:
                try:
                    json_data = json.load(f)
                except ValueError:
                    json_data = dict()

                json_data.update({target_param: [
                    item,
                    'Set payload',
                ]})
                self.write_file(f, json.dumps(json_data))

        # onclick clear button of payload sets
        if actionEvent.getSource() is self._file_clear_btn:
            self.remove_all(self.file_table_model)

            self.current_column_id = 0

            with open("target.json", 'r+') as f:
                try:
                    json_data = json.load(f)
                except:
                    json_data = dict()

                for key, value in json_data.items():
                    if isinstance(value[1], unicode):
                        if value[1].encode('utf-8') == 'Set payload':
                            try:
                                del json_data[key]
                            except IndexError:
                                print('Error: {0}: No such json key.'.format(
                                    key))
                self.write_file(f, json.dumps(json_data))

    #
    # Implementaion of ISessionHandlingAction
    #
    def getActionName(self):
        return "custom request handler"

    def performAction(self, current_request, macro_items):

        if len(macro_items) == 0:
            return

        # extract the response headers
        final_response = macro_items[len(macro_items) - 1].getResponse()
        if final_response is None:
            return

        req = self.helpers.analyzeRequest(current_request)

        try:
            with open('target.json', 'r') as f:
                read_data = f.read()
                self.read_data = json.loads(read_data)
        except ValueError:
            sys.stderr.write('Error: json.loads()')
            return

        for key, value in self.read_data.items():
            if value[0] == 'JSON':
                self.set_json_parameter(current_request, final_response, key,
                                        value)
            elif value[0] == 'Header':
                self.set_header(current_request, final_response, key, value)

    def set_json_parameter(self, current_request, final_response, key, value):
        req = self.helpers.analyzeRequest(current_request)

        if IRequestInfo.CONTENT_TYPE_JSON != req.getContentType():
            return False

        body = current_request.getRequest()[req.getBodyOffset():].tostring()
        json_data = json.loads(body, object_pairs_hook=collections.OrderedDict)

        target_keys = filter(lambda x: x == key, json_data.keys())
        if not target_keys:
            return

        req_data = json_data
        column_model = self.file_table.getColumnModel()
        row_count = self.file_table_model.getRowCount()
        for key in target_keys:
            if value[-1] == 'Set payload':
                if row_count > self.current_column_id:
                    req_value = self.file_table_model.getValueAt(
                        self.current_column_id, 2)
                    self.current_column_id += 1
            else:
                # No selected regex
                if len(value) > 2:
                    start, end = value[1:]
                    req_value = final_response[start:end].tostring()
                else:
                    regex = value[1]
                    match = re.search(regex, final_response.tostring())
                    req_value = match.group(1) if match else None

            req_data[key] = req_value

        req = current_request.getRequest()
        json_data_start = self.helpers.indexOf(req, bytearray(body), False, 0,
                                               len(req))

        # glue together header + customized json of request
        current_request.setRequest(
            req[0:json_data_start] +
            self.helpers.stringToBytes(json.dumps(req_data)))

    def set_header(self, current_request, final_response, key, value):
        req = self.helpers.analyzeRequest(current_request)
        headers = req.getHeaders()
        target_keys = []
        for header in headers:
            if header.startswith(key):
                target_keys += [key]

        if not target_keys:
            return

        column_model = self.file_table.getColumnModel()
        row_count = self.file_table_model.getRowCount()
        req = current_request.getRequest()

        for key in target_keys:
            if value[-1] == 'Set payload':
                if row_count > self.current_column_id:
                    req_value = self.file_table_model.getValueAt(
                        self.current_column_id, 2)
                    self.current_column_id += 1
            else:
                # No selected regex
                if len(value) > 2:
                    start, end = value[1:]
                    req_value = final_response[start:end].tostring()
                else:
                    regex = value[1]
                    match = re.search(regex, final_response.string())
                    req_value = match.group(1) if match else None

            key_start = self.helpers.indexOf(req,
                                             bytearray(key.encode('utf-8')),
                                             False, 0, len(req))
            key_end = self.helpers.indexOf(req, bytearray('\r\n'), False,
                                           key_start, len(req))

            keylen = len(key)

        # glue together first line + customized hedaer + rest of request
        current_request.setRequest(
            req[0:key_start] +
            self.helpers.stringToBytes("%s: %s" %
                                       (key.encode('utf-8'), req_value)) +
            req[key_end:])

    #
    # Implementation of function for Remove all for specific table data
    #
    def remove_all(self, model):
        count = model.getRowCount()
        for i in xrange(count):
            model.removeRow(0)

    #
    # Implementaion of function for write data for specific file
    #
    def write_file(self, f, data):
        f.seek(0)
        f.write(data)
        f.truncate()
        return