Exemplo n.º 1
0
    def getUiComponent(self):
        """Burp uses this method to obtain the component that should be used as
        the contents of the custom tab when it is displayed.
        Returns a awt.Component.
        """
        # GUI happens here
        from javax.swing import (JPanel, JSplitPane, JLabel, JList,
                                 JScrollPane, ListSelectionModel)
        from java.awt import BorderLayout
        panel = JPanel(BorderLayout())

        # create a list and then JList out of it.
        colors = [
            "red", "orange", "yellow", "green", "cyan", "blue", "pink",
            "magenta", "gray", "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz"
        ]
        list1 = JList(colors)
        # set the selection mode to single items
        # ListSelectionModel.SINGLE_SELECTION = 0
        # https://docs.oracle.com/javase/8/docs/api/constant-values.html
        list1.selectionMode = ListSelectionModel.SINGLE_SELECTION

        # create splitpane - horizontal split
        spl = JSplitPane(JSplitPane.HORIZONTAL_SPLIT, JScrollPane(list1),
                         JLabel("right pane"))

        panel.add(spl)
        return panel
Exemplo n.º 2
0
 def run( self ) :
     frame = JFrame(
         'List3',
         size = ( 200, 200 ),
         layout = BorderLayout(),
         defaultCloseOperation = JFrame.EXIT_ON_CLOSE
     )
     data = (
         'Now is the time for all good spam ' +
         'to come to the aid of their eggs'
     ).split( ' ' )
     self.info = JList( data )
     frame.add(
         JScrollPane(
             self.info,
             preferredSize = ( 200, 110 )
         ),
         BorderLayout.NORTH
     )
     panel = JPanel( layout = GridLayout( 0, 2 ) )
     panel.add(
         JButton(
             'Count',
             actionPerformed = self.count
         )
     )
     self.text = panel.add( JTextField( 10 ) )
     frame.add( panel, BorderLayout.CENTER )
     self.msg  = JLabel( 'Occurance count' )
     frame.add( self.msg, BorderLayout.SOUTH )
     frame.setVisible( 1 )
Exemplo n.º 3
0
    def __init__(self):

        self.setBorder(
            BorderFactory.createTitledBorder(
                            "Registered session handling actions"
                            )
            )

        self.setLayout(BoxLayout(self, BoxLayout.Y_AXIS))
        self._rowpanel1 = JPanel()
        self._rowpanel1.setLayout(BoxLayout(self._rowpanel1, BoxLayout.X_AXIS))

        self.listModel = DefaultListModel()

        self.List = JList(self.listModel)

        self.List.setSelectionMode(
                    ListSelectionModel.MULTIPLE_INTERVAL_SELECTION
                    )
        self.List.setSelectedIndex(0)
        self.List.setVisibleRowCount(5)

        self.ScrollPane = JScrollPane(self.List)

        self.remove_button = JButton(
                                "De-register selected",
                                actionPerformed=self.button_remove_pressed
                            )

        self._rowpanel1.add(self.ScrollPane)
        self._rowpanel1.add(self.remove_button)

        self.add(self._rowpanel1)
Exemplo n.º 4
0
    def getUiComponent(self):
        """Burp uses this method to obtain the component that should be used as
        the contents of the custom tab when it is displayed.
        Returns a awt.Component.
        """
        # GUI happens here
        from javax.swing import (JPanel, JSplitPane, JLabel, JList,
                                 JScrollPane, ListSelectionModel)
        from java.awt import BorderLayout
        panel = JPanel(BorderLayout())

        # create a list and then JList out of it.
        colors = [
            "red", "orange", "yellow", "green", "cyan", "blue", "pink",
            "magenta", "gray", "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz"
        ]

        def listSelect(event):
            """Add the selected index to the label."""
            label1.text += "-" + colors[list1.selectedIndex]

        # create a list and assign the valueChanged
        list1 = JList(colors, valueChanged=listSelect)
        list1.selectionMode = ListSelectionModel.SINGLE_SELECTION

        # create splitpane - horizontal split
        label1 = JLabel("right pane")
        spl = JSplitPane(JSplitPane.HORIZONTAL_SPLIT, JScrollPane(list1),
                         label1)

        panel.add(spl)
        return panel
Exemplo n.º 5
0
class ParameterPanel(JPanel):
    def __init__(self,view,name,values,default):
        self.view=view
        self.layout=BorderLayout()
        self.name=name
        self.values_data=values
        self.values=JList(values,border=BorderFactory.createLineBorder(Color.black,1),
                                 valueChanged=self.adjust)
        self.add(JLabel(name,horizontalAlignment=SwingConstants.LEFT),BorderLayout.NORTH)
        self.new_value=JTextField('',actionPerformed=self.create_new_value)
        self.add(self.new_value,BorderLayout.SOUTH)
        self.add(self.values)
        self.values.setSelectedValue(default,True)
    def adjust(self,event):
        if not event.valueIsAdjusting:
            self.view.graph.update()
    def create_new_value(self,event):
        value=self.new_value.text
        self.new_value.text=''
        try:
            value=eval(value)
        except:
            return
        if value not in self.values_data:
            selected=self.values.selectedValue
            self.values_data.append(value)
            self.values_data.sort()
            model=DefaultListModel()
            for v in self.values_data:
                model.addElement(v)
            self.values.model=model
            self.values.setSelectedValue(selected,True)
Exemplo n.º 6
0
    def run(self):
        frame = JFrame('List10',
                       size=(200, 220),
                       layout=GridLayout(1, 2),
                       defaultCloseOperation=JFrame.EXIT_ON_CLOSE)

        panel = JPanel(layout=GridLayout(0, 1))
        self.buttons = {}
        for name in 'First,Last,Before,After,Remove'.split(','):
            self.buttons[name] = panel.add(
                JButton(name, enabled=0, actionPerformed=self.doit))

        self.text = panel.add(JTextField(10, keyReleased=self.textCheck))

        frame.add(panel)

        data = ('Now is the time for all good spam ' +
                'to come to the aid of their eggs').split(' ')
        model = DefaultListModel()
        for word in data:
            model.addElement(word)
        self.List = JList(model,
                          valueChanged=self.textCheck,
                          selectionMode=ListSelectionModel.SINGLE_SELECTION)
        frame.add(JScrollPane(self.List, preferredSize=(200, 100)))
        frame.setVisible(1)
Exemplo n.º 7
0
class ProgramsTab(JPanel):
    def __init__(self):
        self.programs = []
        self.setLayout(BoxLayout(self, BoxLayout.PAGE_AXIS))

        self.JprogramList = JList()
        self.JprogramList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION)
        self.JprogramList.addListSelectionListener(self.handle_select)
        scrollPane = JScrollPane(self.JprogramList)
        scrollPane.setMinimumSize(Dimension(300, 0))

        self.splitPane = SplitPanel(scrollPane, JPanel())
        self.add(self.splitPane)
        context.addon.register_on_connect(self.load_program_list)
        context.addon.register_on_error(self.display_error)

    def load_program_list(self):
        self.display_program_list(context.api.get_programs())

    def display_program_list(self, programs):
        self.programs = programs

        model = DefaultListModel()
        for program in programs:
            model.addElement(program)

        self.JprogramList.setModel(model)
        self.JprogramList.setCellRenderer(ProgramRenderer())

        if self.programs:
            async_call(
                lambda: context.api.get_program_details(self.programs[0].slug),
                self.load_program_details,
            )
        else:
            self.splitPane.setRightComponent(JPanel())

    def display_error(self, error):
        self.JprogramList.setListData(tuple())
        self.splitPane.setRightComponent(JLabel("You are disconnected"))

    def load_program_details(self, pgm_details):
        pane = ProgramPane(pgm_details)
        loc = self.splitPane.getDividerLocation()
        self.splitPane.setRightComponent(pane)
        self.splitPane.setDividerLocation(loc)

    def handle_select(self, event):
        jlist = event.source
        if event.valueIsAdjusting:
            return None
        selected_idx = jlist.getSelectedIndex()
        if selected_idx < 0 or selected_idx > len(self.programs):
            return None

        slug = self.programs[selected_idx].slug
        async_call(
            lambda: context.api.get_program_details(slug), self.load_program_details
        )
Exemplo n.º 8
0
 def createList(self, content):
     model = DefaultListModel()
     for elem in content:
         model.addElement(elem)
     list = JList(model)
     list.addListSelectionListener(self)
     listPane = JScrollPane(list) 
     listPane.setPreferredSize(Dimension(250, 400))
     return listPane, list, model
Exemplo n.º 9
0
 def createList(self, content):
     model = DefaultListModel()
     for elem in content:
         model.addElement(elem)
     list = JList(model)
     list.addListSelectionListener(self)
     listPane = JScrollPane(list)
     listPane.setPreferredSize(Dimension(250, 400))
     return listPane, list, model
Exemplo n.º 10
0
 def __init__(self, message, options):
     self._selection_list = JList(options)
     self._selection_list.setVisibleRowCount(4)
     selected_message = JLabel(message)
     panel = JPanel(layout=GridLayout(2, 1))
     panel.add(selected_message)
     panel.add(JScrollPane(self._selection_list))
     pane = WrappedOptionPane(panel, PLAIN_MESSAGE, OK_CANCEL_OPTION)
     _SwingDialog.__init__(self, pane)
    def getUiComponent(self):
        self.spePanel = JPanel()
        self.spePanel.setBorder(None)
        self.spePanel.setLayout(None)

        self.logPane = JScrollPane()
        self.outputTxtArea = JTextArea()
        self.outputTxtArea.setFont(Font("Consolas", Font.PLAIN, 12))
        self.outputTxtArea.setLineWrap(True)
        self.logPane.setViewportView(self.outputTxtArea)
        self.spePanel.add(self.logPane)

        self.clearBtn = JButton("Clear", actionPerformed=self.clearRst)
        self.exportBtn = JButton("Export", actionPerformed=self.exportRst)
        self.parentFrm = JFileChooser()

        self.spePanel.add(self.clearBtn)
        self.spePanel.add(self.exportBtn)

        self.logPane.setBounds(20, 50, 800, 600)

        self.clearBtn.setBounds(20, 650, 100, 30)
        self.exportBtn.setBounds(600, 650, 100, 30)

        self.sensitiveParamsRegularListPanel = JList(self.sensitiveParamR)
        self.sensitiveParamsRegularListPanel.setVisibleRowCount(
            len(self.sensitiveParamR))

        #self.spePanel.add(self.sensitiveParamsRegularListPanel)

        #self.sensitiveParamsRegularListPanel.setBounds(850,50,150,600)

        self.sensitiveParamsRegularListScrollPanel = JScrollPane()
        self.sensitiveParamsRegularListScrollPanel.setViewportView(
            self.sensitiveParamsRegularListPanel)
        self.spePanel.add(self.sensitiveParamsRegularListScrollPanel)
        self.sensitiveParamsRegularListScrollPanel.setBounds(850, 50, 150, 600)

        self.addAndSaveNewParamRegularButton = JButton(
            'add&&save', actionPerformed=self.addAndSaveNewParamRegular)
        self.spePanel.add(self.addAndSaveNewParamRegularButton)
        self.addAndSaveNewParamRegularButton.setBounds(1000, 50, 150, 30)

        self.addAndSaveNewParamRegularTextField = JTextField('NewParamRegular')
        self.spePanel.add(self.addAndSaveNewParamRegularTextField)
        self.addAndSaveNewParamRegularTextField.setBounds(1150, 50, 100, 30)

        self.alertSaveSuccess = JOptionPane()
        self.spePanel.add(self.alertSaveSuccess)

        self.delParamRegularButton = JButton(
            "delete", actionPerformed=self.delParamRegular)
        self.spePanel.add(self.delParamRegularButton)
        self.delParamRegularButton.setBounds(1000, 90, 100, 30)

        return self.spePanel
Exemplo n.º 12
0
class EmployeeList(object):

    def __init__(self, employees):
        self._employees = employees
        self._employees.add_change_listener(self)
        self._list = JList(preferredSize=(200, 200), name='employee_list')
        self._populate_list()

    def _populate_list(self):
        self._list.setListData(self._employee_names())

    def _employee_names(self):
        return [e.name for e in self._employees.all()]

    def add_selection_listener(self, listener):
        self._list.addListSelectionListener(listener)

    def selected_employee(self):
        return self._employees.all()[self._list.getSelectedIndex()]

    def employee_added(self, employee):
        self._populate_list()
        self._list.setSelectedValue(employee.name, True)

    def adding_employee_failed(self, error):
        pass

    def clear_selection(self):
        self._list.clearSelection()

    @property
    def widget(self):
        return (self._list)
        return JScrollPane(self._list)
Exemplo n.º 13
0
class EmployeeList(object):
    def __init__(self, employees):
        self._employees = employees
        self._employees.add_change_listener(self)
        self._list = JList(preferredSize=(200, 200), name='employee_list')
        self._populate_list()

    def _populate_list(self):
        self._list.setListData(self._employee_names())

    def _employee_names(self):
        return [e.name for e in self._employees.all()]

    def add_selection_listener(self, listener):
        self._list.addListSelectionListener(listener)

    def selected_employee(self):
        return self._employees.all()[self._list.getSelectedIndex()]

    def employee_added(self, employee):
        self._populate_list()
        self._list.setSelectedValue(employee.name, True)

    def adding_employee_failed(self, error):
        pass

    def clear_selection(self):
        self._list.clearSelection()

    @property
    def widget(self):
        return self._list
Exemplo n.º 14
0
    def initEnforcementDetector(self):
        #
        ## init enforcement detector tab
        #

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

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

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

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

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

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

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

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

        self.EDPnl = JPanel()
        self.EDPnl.setLayout(None)
        self.EDPnl.setBounds(0, 0, 1000, 1000)
        self.EDPnl.add(EDLType)
        self.EDPnl.add(self.EDType)
        self.EDPnl.add(EDLContent)
        self.EDPnl.add(self.EDText)
        self.EDPnl.add(self.EDAdd)
        self.EDPnl.add(self.EDDel)
        self.EDPnl.add(EDLabelList)
        self.EDPnl.add(self.EDList)
class MultipleSelectionDialog(_SwingDialog):
    def __init__(self, message, options):
        self._selection_list = JList(options)
        self._selection_list.setVisibleRowCount(8)
        panel = self._create_panel(message, JScrollPane(self._selection_list))
        pane = WrappedOptionPane(panel, PLAIN_MESSAGE, OK_CANCEL_OPTION)
        _SwingDialog.__init__(self, pane)

    def _get_value(self, pane):
        if pane.getValue() != OK_OPTION:
            return None
        return list(self._selection_list.getSelectedValuesList())
Exemplo n.º 16
0
def testBuiltinListener():
    model = DefaultListModel()
    lst = JList(model)
    model.addElement(u'Test')
    events = []
    addEventListener(lst, ListSelectionListener, 'valueChanged',
                     events.append)

    lst.setSelectionInterval(0, 0)
    assert len(events) == 1
    assert events[0].firstIndex == 0
    assert events[0].lastIndex == 0
Exemplo n.º 17
0
Arquivo: popup.py Projeto: cabeen/qit
    def __init__(self, frame, textComponent):
        JWindow.__init__(self, frame)
        self.textComponent = textComponent
        self.size = (200, 200)
        self.list = JList(keyPressed=self.key)
        self.list.setBackground(Color(255, 255, 225))  # TODO move this color
        self.getContentPane().add(JScrollPane(self.list))
        self.list.setSelectedIndex(0)

        self.originalData = ""
        self.data = ""
        self.typed = ""
Exemplo n.º 18
0
def testListSelectionEventVarargs():
    def selectionListener(*args):
        _event, holder[0] = args

    model = DefaultListModel()
    lst = JList(model)
    model.addElement(u'Test')
    holder = [None]
    addEventListener(lst, ListSelectionListener, 'valueChanged',
                     selectionListener, 2)

    lst.setSelectionInterval(0, 0)
    assert holder[0] == 2
Exemplo n.º 19
0
def testListSelectionEventKwargs():
    def selectionListener(event, **kwargs):
        holder[0] = kwargs

    model = DefaultListModel()
    lst = JList(model)
    model.addElement(u'Test')
    holder = [None]
    addEventListener(lst, ListSelectionListener, 'valueChanged',
                     selectionListener, test=2)

    lst.setSelectionInterval(0, 0)
    assert holder[0] == {'test': 2}
Exemplo n.º 20
0
class MultipleSelectionDialog(_SwingDialog):

    def __init__(self, message, options):
        self._selection_list = JList(options)
        self._selection_list.setVisibleRowCount(8)
        panel = self._create_panel(message, JScrollPane(self._selection_list))
        pane = WrappedOptionPane(panel, PLAIN_MESSAGE, OK_CANCEL_OPTION)
        _SwingDialog.__init__(self, pane)

    def _get_value(self, pane):
        if pane.getValue() != OK_OPTION:
            return None
        return list(self._selection_list.getSelectedValuesList())
Exemplo n.º 21
0
    def __init__(self, burp_callbacks):
        self._burp_callbacks = burp_callbacks

        self._type_list_component = JList(
            blackboxprotobuf.known_messages.keys())
        self._type_list_component.setSelectionMode(
            ListSelectionModel.SINGLE_SELECTION)

        self._component = JSplitPane(JSplitPane.HORIZONTAL_SPLIT)
        self._component.setLeftComponent(JScrollPane(
            self._type_list_component))
        self._component.setRightComponent(self.createButtonPane())
        self._component.setResizeWeight(0.9)
Exemplo n.º 22
0
    def getUiComponent(self):
        """Burp uses this method to obtain the component that should be used as
        the contents of the custom tab when it is displayed.
        Returns a awt.Component.
        """
        # GUI happens here
        from javax.swing import (JPanel, JSplitPane, JList, JTextPane,
                                 JScrollPane, ListSelectionModel, JLabel,
                                 JTabbedPane, JEditorPane)
        from java.awt import BorderLayout
        panel = JPanel(BorderLayout())

        # create a list and then JList out of it.
        colors = [
            "red", "orange", "yellow", "green", "cyan", "blue", "pink",
            "magenta", "gray", "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz"
        ]

        def listSelect(event):
            """Add the selected index to the label. Called twice when
            selecting the list item by mouse. So we need to use
            getValueIsAdjusting inside.
            """
            if not event.getValueIsAdjusting():
                doc1.insertString(0, colors[list1.selectedIndex] + "-", None)

        # create a list and assign the valueChanged
        list1 = JList(colors, valueChanged=listSelect)
        list1.selectionMode = ListSelectionModel.SINGLE_SELECTION

        # create a StyledDocument.
        from javax.swing.text import DefaultStyledDocument
        doc1 = DefaultStyledDocument()
        # create a JTextPane from doc1
        tab1 = JTextPane(doc1)

        # create a JEditorPane for tab 2
        tab2 = JEditorPane("https://example.net")
        tab2.editable = False

        # create the tabbedpane
        tabs = JTabbedPane()

        tabs.addTab("Tab 1", tab1)
        tabs.addTab("Tab 2", tab2)

        # create splitpane - horizontal split
        spl = JSplitPane(JSplitPane.HORIZONTAL_SPLIT, JScrollPane(list1), tabs)

        panel.add(spl)
        return panel
Exemplo n.º 23
0
    def __init__(self):
        self.programs = []
        self.setLayout(BoxLayout(self, BoxLayout.PAGE_AXIS))

        self.JprogramList = JList()
        self.JprogramList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION)
        self.JprogramList.addListSelectionListener(self.handle_select)
        scrollPane = JScrollPane(self.JprogramList)
        scrollPane.setMinimumSize(Dimension(300, 0))

        self.splitPane = SplitPanel(scrollPane, JPanel())
        self.add(self.splitPane)
        context.addon.register_on_connect(self.load_program_list)
        context.addon.register_on_error(self.display_error)
Exemplo n.º 24
0
class TypeDefinitionTab(burp.ITab):
    """Implements an interface for editing known message type definitions."""
    def __init__(self, burp_callbacks):
        self._burp_callbacks = burp_callbacks

        self._type_list_component = JList(
            blackboxprotobuf.known_messages.keys())
        self._type_list_component.setSelectionMode(
            ListSelectionModel.SINGLE_SELECTION)

        self._component = JSplitPane(JSplitPane.HORIZONTAL_SPLIT)
        self._component.setLeftComponent(JScrollPane(
            self._type_list_component))
        self._component.setRightComponent(self.createButtonPane())
        self._component.setResizeWeight(0.9)

    def getTabCaption(self):
        """Returns name on tab"""
        return "Protobuf Type Editor"

    def getUiComponent(self):
        """Returns Java AWT component for tab"""
        return self._component

    def createButtonPane(self):
        """Create AWT window panel for buttons"""
        self._button_listener = TypeDefinitionButtonListener(self)

        panel = JPanel()
        panel.setLayout(BoxLayout(panel, BoxLayout.Y_AXIS))

        panel.add(self.createButton("New Type", "new-type"))
        panel.add(self.createButton("Edit Type", "edit-type"))
        panel.add(self.createButton("Delete Type", "delete-type"))
        panel.add(self.createButton("Save All Types To File", "save-types"))
        panel.add(self.createButton("Load All Types To File", "load-types"))
        return panel

    def createButton(self, text, command):
        """Generate new button with the given text and command string"""
        button = JButton(text)
        button.setAlignmentX(Component.CENTER_ALIGNMENT)
        button.setActionCommand(command)
        button.addActionListener(self._button_listener)
        return button

    def updateList(self):
        """Let the UI know that the list of message types has been updated"""
        self._type_list_component.setListData(
            blackboxprotobuf.known_messages.keys())
Exemplo n.º 25
0
def testListSelectionEvent():
    def selectionListener(event):
        eventHolder[0] = event

    model = DefaultListModel()
    lst = JList(model)
    model.addElement(u'Test')
    eventHolder = [None]
    addEventListener(lst, ListSelectionListener, 'valueChanged',
                     selectionListener)

    lst.setSelectionInterval(0, 0)
    event = eventHolder[0]
    assert event.firstIndex == 0
    assert event.lastIndex == 0
Exemplo n.º 26
0
 def run(self):
     frame = JFrame('List1',
                    size=(250, 200),
                    defaultCloseOperation=JFrame.EXIT_ON_CLOSE)
     data = 'Now is the time for all good spam'.split(' ')
     frame.add(JList(data))
     frame.setVisible(1)
Exemplo n.º 27
0
    def run(self):
        frame = JFrame('List6a',
                       size=(200, 220),
                       layout=GridLayout(1, 2),
                       defaultCloseOperation=JFrame.EXIT_ON_CLOSE)

        panel = JPanel(layout=GridLayout(0, 1))
        self.buttons = {}
        for name in 'First,Last,Before,After,Remove'.split(','):
            self.buttons[name] = panel.add(self.button(name))

        self.text = panel.add(JTextField(10))
        self.text.addInputMethodListener(IML())
        #       self.addTextListener( self )
        frame.add(panel)

        data = ('Now is the time for all good spam ' +
                'to come to the aid of their eggs').split(' ')
        model = DefaultListModel()
        for word in data:
            model.addElement(word)
        self.info = JList(model,
                          valueChanged=self.selection,
                          selectionMode=ListSelectionModel.SINGLE_SELECTION)
        frame.add(JScrollPane(self.info, preferredSize=(200, 100)))
        frame.setVisible(1)
Exemplo n.º 28
0
class MultipleSelectionDialog(_SwingDialog):

    def __init__(self, message, options):
        self._selection_list = JList(options)
        self._selection_list.setVisibleRowCount(4)
        selected_message = JLabel(message)
        panel = JPanel(layout=GridLayout(2, 1))
        panel.add(selected_message)
        panel.add(JScrollPane(self._selection_list))
        pane = WrappedOptionPane(panel, PLAIN_MESSAGE, OK_CANCEL_OPTION)
        _SwingDialog.__init__(self, pane)

    def _get_value(self, pane):
        if pane.getValue() != OK_OPTION:
            return None
        return list(self._selection_list.getSelectedValuesList())
Exemplo n.º 29
0
    def init(self):
        global exampleList
        self.thinFont = Font("Dialog", 0, 10)

        self.pane = self.getContentPane()
        self.examples = exampleList.keys()
        self.examples.sort()
        self.exampleSelector = JList(self.examples, valueChanged=self.valueChanged)
        self.exampleSelector.setSelectionMode(ListSelectionModel.SINGLE_SELECTION)
        self.exampleSelector.setLayoutOrientation(JList.VERTICAL)
        self.exampleSelector.setPreferredSize(Dimension(150,500))
        self.exampleSelector.setBackground(Color(0.95, 0.95, 0.98))
        self.exampleSelector.setFont(self.thinFont)

        self.centerPanel = JPanel(BorderLayout())
        self.canvas = GraphCanvas()
        self.canvas.setApplet(self)
        self.buttonRow = JPanel(FlowLayout())
        self.backButton = JButton("<", actionPerformed = self.backAction)
        self.backButton.setFont(self.thinFont)
        self.continueButton = JButton("continue >",
                                      actionPerformed=self.continueAction)
        self.continueButton.setFont(self.thinFont)
        self.scaleGroup = ButtonGroup()
        self.linearButton = JRadioButton("linear scale",
                                         actionPerformed=self.linearAction)
        self.linearButton.setSelected(True)
        self.linearButton.setFont(self.thinFont)
        self.logarithmicButton = JRadioButton("logarithmic scale",
                                      actionPerformed=self.logarithmicAction)
        self.logarithmicButton.setFont(self.thinFont)
        self.aboutButton = JButton("About...",
                                   actionPerformed=self.aboutAction)
        self.aboutButton.setFont(self.thinFont)
        self.scaleGroup.add(self.linearButton)
        self.scaleGroup.add(self.logarithmicButton)
        self.buttonRow.add(self.backButton)
        self.buttonRow.add(self.continueButton)
        self.buttonRow.add(JLabel(" "*5))
        self.buttonRow.add(self.linearButton)
        self.buttonRow.add(self.logarithmicButton)
        self.buttonRow.add(JLabel(" "*20));
        self.buttonRow.add(self.aboutButton)
        self.centerPanel.add(self.canvas, BorderLayout.CENTER)
        self.centerPanel.add(self.buttonRow, BorderLayout.PAGE_END)

        self.helpText = JTextPane()
        self.helpText.setBackground(Color(1.0, 1.0, 0.5))
        self.helpText.setPreferredSize(Dimension(800,80))
        self.helpText.setText(re_sub("[ \\n]+", " ", """
        Please select one of the examples in the list on the left!
        """))
        self.pane.add(self.exampleSelector, BorderLayout.LINE_START)
        self.pane.add(self.centerPanel, BorderLayout.CENTER)
        self.pane.add(self.helpText, BorderLayout.PAGE_END)
        self.graph = None
        self.simulation = None
        self.touched = ""
        self.selected = ""
        self.gfxDriver = None
Exemplo n.º 30
0
    def __init__(self, out_of_scope):
        ColumnPanel.__init__(self)

        out_of_scope_list = JList(tuple(out_of_scope))
        self.add(JScrollPane(out_of_scope_list))
        self.setBorder(make_title_border("Out of scope"))
        self.setMaximumSize(Dimension(9999999, self.getPreferredSize().height))
Exemplo n.º 31
0
 def __init__(self):
     self.frame = JFrame("Python Window")
     self.historyList = JList(DefaultListModel())
     self.historyList.cellRenderer = MyListCellRenderer()
     #self.historyPanel.layout = BoxLayout(
     #    self.historyPanel,
     #    BoxLayout.Y_AXIS
     #)
     scrollpane = JScrollPane()
     #    JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
     #    JScrollPane.HORIZONTAL_SCROLLBAR_NEVER
     #)
     # scrollpane.preferredSize = 400, 800
     inputPanel = JPanel()
     inputPanel.layout = GridLayout(1, 1)
     self.input = JTextArea("")
     self.input.border = BorderFactory.createEmptyBorder(5, 5, 5, 5)
     self.input.tabSize = 4
     self.input.font = Font("Monospaced", Font.PLAIN, 12)
     #self.input.preferredSize = 500, 200 
     self.input.addKeyListener(self)
     #self.button = JButton('Run', actionPerformed=self.run)
     inputPanel.add(self.input)
     #inputPanel.add(self.button)
     scrollpane.viewport.view = self.historyList
     self.frame.add(scrollpane, BorderLayout.CENTER)
     self.frame.add(inputPanel, BorderLayout.PAGE_END)
     self.frame.size = 500, 600
     self.frame.visible = False
Exemplo n.º 32
0
    def initInterceptionFilters(self):
        #
        ##  init interception filters tab
        #

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

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

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

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

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

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

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

        self.filtersPnl = JPanel()
        self.filtersPnl.setLayout(None)
        self.filtersPnl.setBounds(0, 0, 1000, 1000)
        self.filtersPnl.add(IFLType)
        self.filtersPnl.add(self.IFType)
        self.filtersPnl.add(IFLContent)
        self.filtersPnl.add(self.IFText)
        self.filtersPnl.add(self.IFAdd)
        self.filtersPnl.add(self.IFDel)
        self.filtersPnl.add(IFLabelList)
        self.filtersPnl.add(self.IFList)
Exemplo n.º 33
0
 def run( self ) :
     frame = JFrame(
         'List1a',
         size = ( 250, 200 ),
         defaultCloseOperation = JFrame.EXIT_ON_CLOSE
     )
     frame.add( JList( self.data() ) )
     frame.setVisible( 1 )
Exemplo n.º 34
0
Arquivo: ashdi.py Projeto: sjp38/ash
def getContentPane():
    global contentPane
    global devicesList
    global devicesPanel

    if not contentPane:
        global devicesListLabel
        devicesListLabel = JLabel("Devices")

        global devicesList
        devicesList = JList([])
        devicesList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION)
        listScroller = JScrollPane(devicesList)
        listScroller.setPreferredSize(Dimension(600, 400))

        global connectButton
        global focusButton
        allDevsButton = JButton(ALL_DEVICES, actionPerformed=handleAllDevsBtn)
        connectedDevsButton = JButton(CONNECTED_DEVICES,
                actionPerformed=handleConnectedDevBtn)
        connectButton = JButton(CONNECT, actionPerformed=handleConnectBtn)
        focusButton = JButton(FOCUS, actionPerformed=handleFocusBtn)
        focusButton.setVisible(False)
        goInButton = JButton("Go in device", actionPerformed=handleGoInBtn)

        deviceListButtons = JPanel()
        deviceListButtons.add(allDevsButton)
        deviceListButtons.add(connectedDevsButton)
        deviceListButtons.add(connectButton)
        deviceListButtons.add(focusButton)
        deviceListButtons.add(goInButton)

        devicesPanel = JPanel()
        devicesPanel.setLayout(BoxLayout(devicesPanel, BoxLayout.Y_AXIS))
        devicesPanel.add(devicesListLabel)
        devicesPanel.add(listScroller)
        devicesPanel.add(deviceListButtons)

        contentPane = JPanel()
        contentPane.setLayout(BorderLayout())
        contentPane.add(devicesPanel, BorderLayout.WEST)
        contentPane.add(getControlPanel(), BorderLayout.EAST)
        contentPane.add(getScreenPanel(), BorderLayout.CENTER)
        getScreenPanel().setVisible(False)
    return contentPane
Exemplo n.º 35
0
    def getUiComponent(self):
        """Burp uses this method to obtain the component that should be used as
        the contents of the custom tab when it is displayed.
        Returns a awt.Component.
        """
        # GUI happens here
        from javax.swing import (JPanel, JSplitPane, JList, JScrollPane,
                                 ListSelectionModel, JLabel, JTabbedPane)
        from java.awt import BorderLayout
        panel = JPanel(BorderLayout())

        # create a list and then JList out of it.
        colors = [
            "red", "orange", "yellow", "green", "cyan", "blue", "pink",
            "magenta", "gray", "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz"
        ]

        def listSelect(event):
            """Add the selected index to the label. Called twice when
            selecting the list item by mouse. So we need to use
            getValueIsAdjusting inside.
            """
            if not event.getValueIsAdjusting():
                label1.text += "-" + colors[list1.selectedIndex]

        # create a list and assign the valueChanged
        list1 = JList(colors, valueChanged=listSelect)
        list1.selectionMode = ListSelectionModel.SINGLE_SELECTION

        # create a JTabbedPane
        tabs = JTabbedPane()

        # add labels to it
        label1 = JLabel()
        label2 = JLabel()
        tabs.addTab("Tab 1", label1)
        tabs.addTab("Tab 2", label2)

        # create splitpane - horizontal split
        spl = JSplitPane(JSplitPane.HORIZONTAL_SPLIT, JScrollPane(list1), tabs)

        panel.add(spl)
        return panel
Exemplo n.º 36
0
class List3( java.lang.Runnable ) :

    #---------------------------------------------------------------------------
    # Name: run()
    # Role: Create and display the application window
    #---------------------------------------------------------------------------
    def run( self ) :
        frame = JFrame(
            'List3',
            size = ( 200, 200 ),
            layout = BorderLayout(),
            defaultCloseOperation = JFrame.EXIT_ON_CLOSE
        )
        data = (
            'Now is the time for all good spam ' +
            'to come to the aid of their eggs'
        ).split( ' ' )
        self.info = JList( data )
        frame.add(
            JScrollPane(
                self.info,
                preferredSize = ( 200, 110 )
            ),
            BorderLayout.NORTH
        )
        panel = JPanel( layout = GridLayout( 0, 2 ) )
        panel.add(
            JButton(
                'Count',
                actionPerformed = self.count
            )
        )
        self.text = panel.add( JTextField( 10 ) )
        frame.add( panel, BorderLayout.CENTER )
        self.msg  = JLabel( 'Occurance count' )
        frame.add( self.msg, BorderLayout.SOUTH )
        frame.setVisible( 1 )

    #---------------------------------------------------------------------------
    # Name: count()
    # Role: Retrieve the "word" from the input field, and count the number of
    #       times it occurs in the list
    #---------------------------------------------------------------------------
    def count( self, event ) :
        word = self.text.getText()
        model = self.info.getModel()
        occurs = 0
        for index in range( model.getSize() ) :
            if model.getElementAt( index ) == word :
                occurs += 1
        self.msg.setText(
            '"%s" occurs %d time(s)' %
           ( word, occurs )
        )
        self.text.setText( '' )
Exemplo n.º 37
0
    def check(self, e):
        is_list = type(self.component) == type(JList())

        if is_list:
            is_selection = self.component.getSelectedValue() != None
            is_trigger = e.isPopupTrigger()
            is_context_menu = is_selection and is_trigger
            index = self.component.locationToIndex(e.getPoint())
            self.component.setSelectedIndex(index)

        self.context_menu.show(self.component, e.getX(), e.getY())
Exemplo n.º 38
0
    def __init__(self, frame, textComponent):
        JWindow.__init__(self, frame)
        self.textComponent = textComponent
        self.size = (200,200)
        self.list = JList(keyPressed=self.key)
        self.list.setBackground(Color(255,255,225)) # TODO move this color
        self.getContentPane().add(JScrollPane(self.list))
        self.list.setSelectedIndex(0)

        self.originalData = ""
        self.data = ""
        self.typed = ""
Exemplo n.º 39
0
 def __init__(self,view,name,values,default):
     self.view=view
     self.layout=BorderLayout()
     self.name=name
     self.values_data=values
     self.values=JList(values,border=BorderFactory.createLineBorder(Color.black,1),
                              valueChanged=self.adjust)
     self.add(JLabel(name,horizontalAlignment=SwingConstants.LEFT),BorderLayout.NORTH)
     self.new_value=JTextField('',actionPerformed=self.create_new_value)
     self.add(self.new_value,BorderLayout.SOUTH)
     self.add(self.values)
     self.values.setSelectedValue(default,True)
Exemplo n.º 40
0
    def BuildWindow(self):
        contentPane = self.getContentPane()
        contentPane.setLayout(BorderLayout())
        self.fileListUpdateButton = JButton("Update file list", actionPerformed=self.OnUpdateFileList)
        self.fileNamesList = JList(DefaultListModel(), mouseClicked=self.mouseClicked)
        self.specialReloadButton = JButton("Special reload module (or double click)", actionPerformed=self.OnSpecialReloadOfModule)
        contentPane.add("North", self.fileListUpdateButton)
        contentPane.add("Center", JScrollPane(self.fileNamesList))
        reloadButtonPanel = JPanel(BorderLayout())
        reloadButtonPanel.add("North", self.specialReloadButton)
        contentPane.add("South", reloadButtonPanel)

        self.loadFileList()
Exemplo n.º 41
0
    def initEnforcementDetector(self):
        #
        ## init enforcement detector tab
        #

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

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

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

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

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

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

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

        self.EDPnl = JPanel()
        self.EDPnl.setLayout(None);
        self.EDPnl.setBounds(0, 0, 1000, 1000);
        self.EDPnl.add(EDLType)
        self.EDPnl.add(self.EDType)
        self.EDPnl.add(EDLContent)
        self.EDPnl.add(self.EDText)
        self.EDPnl.add(self.EDAdd)
        self.EDPnl.add(self.EDDel)
        self.EDPnl.add(EDLabelList)
        self.EDPnl.add(self.EDList)
Exemplo n.º 42
0
class EmployeeList(object):
    def __init__(self, employees):
        self._employees = employees
        self._employees.add_change_listener(self)
        self._list = JList(preferredSize=(200, 200), name="employee_list")
        self._populate_list()

    def _populate_list(self):
        self._list.setListData(self._employee_names())

    def _employee_names(self):
        return [e.name for e in self._employees.all()]

    def add_selection_listener(self, listener):
        self._list.addListSelectionListener(listener)

    def selected_employee(self):
        return self._employees.all()[self._list.getSelectedIndex()]

    def employee_added(self, employee):
        self._populate_list()
        self._list.setSelectedValue(employee.name, True)

    def adding_employee_failed(self, error):
        pass

    def clear_selection(self):
        self._list.clearSelection()

    @property
    def widget(self):
        # BUGZ: EmployeeList is not scrollable. Adding more employees than
        # fits in the visible area makes some of them unreachable via UI.
        # Uncomment the following line to fix the bug:
        # return JScrollPane(self._list)
        return self._list
Exemplo n.º 43
0
    def initInterceptionFilters(self):
        #
        ##  init interception filters tab
        #

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

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

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

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

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

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

        self.filtersPnl = JPanel()
        self.filtersPnl.setLayout(None);
        self.filtersPnl.setBounds(0, 0, 1000, 1000);
        self.filtersPnl.add(IFLType)
        self.filtersPnl.add(self.IFType)
        self.filtersPnl.add(IFLContent)
        self.filtersPnl.add(self.IFText)
        self.filtersPnl.add(self.IFAdd)
        self.filtersPnl.add(self.IFDel)
        self.filtersPnl.add(IFLabelList)
        self.filtersPnl.add(self.IFList)
Exemplo n.º 44
0
class PythonWindow(KeyListener):
    def __init__(self):
        self.frame = JFrame("Python Window")
        self.historyList = JList(DefaultListModel())
        self.historyList.cellRenderer = MyListCellRenderer()
        #self.historyPanel.layout = BoxLayout(
        #    self.historyPanel,
        #    BoxLayout.Y_AXIS
        #)
        scrollpane = JScrollPane()
        #    JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
        #    JScrollPane.HORIZONTAL_SCROLLBAR_NEVER
        #)
        # scrollpane.preferredSize = 400, 800
        inputPanel = JPanel()
        inputPanel.layout = GridLayout(1, 1)
        self.input = JTextArea("")
        self.input.border = BorderFactory.createEmptyBorder(5, 5, 5, 5)
        self.input.tabSize = 4
        self.input.font = Font("Monospaced", Font.PLAIN, 12)
        #self.input.preferredSize = 500, 200 
        self.input.addKeyListener(self)
        #self.button = JButton('Run', actionPerformed=self.run)
        inputPanel.add(self.input)
        #inputPanel.add(self.button)
        scrollpane.viewport.view = self.historyList
        self.frame.add(scrollpane, BorderLayout.CENTER)
        self.frame.add(inputPanel, BorderLayout.PAGE_END)
        self.frame.size = 500, 600
        self.frame.visible = False
    def toggle_visibility(self):
        self.frame.visible = not self.frame.visible
    def add(self, text, type="input"):
        self.historyList.model.addElement({"text": text, "type": type})
        self.historyList.validate()
        self.frame.validate()
        last = self.historyList.model.getSize() - 1
        self.historyList.ensureIndexIsVisible(last)
    def write(self, text):
        self.add(text, "output")
    def run(self, evt):
        source = self.input.text
        if not source.strip():
            self.input.text = ""
            return
        processed_source = source.replace("$", "geo.")
        code = interface.compileinteractive(processed_source)
        if code in ("continue", "error"):
            code = interface.compilemodule(processed_source)
            if code == "error":
                return
        self.add(source.strip())
        result = interface.run(code)
        if result == "OK":
            self.input.text = ""
    def keyPressed(self, evt):
        pass
    def keyReleased(self, evt):
        pass
    def keyTyped(self, evt):
        if evt.keyChar == '\n':
            # Only try to run compound statements when they end with
            # two \n
            source = self.input.text
            lines = source.split("\n")
            if lines[0].rstrip().endswith(":") and not source.endswith("\n\n"):
                for i, c in enumerate(lines[-2]):
                    if c not in ' \t': break
                else:
                    self.run(evt)
                    return
                prefix = lines[-2][:i]
                if lines[-2].endswith(":"):
                    prefix += '\t'
                self.input.text = source + prefix
            else:
                self.run(evt)
Exemplo n.º 45
0
 def __init__(self, employees):
     self._employees = employees
     self._employees.add_change_listener(self)
     self._list = JList(preferredSize=(200, 200), name="employee_list")
     self._populate_list()
Exemplo n.º 46
0
class MandersPlugin(ImageListener, WindowAdapter):

	def __init__(self):
		self.imp = None
		self.preview = None
		self.createMainWindow()
		self.cells = None
		self.files = []
		self.results = ResultsTable()
		ImagePlus.addImageListener(self)
		self.selectInputDir()
		self.selectOutputDir()
		self.pairs = []
		self.methods = []
		self.processNextFile()

	def selectInputDir(self):
		inputDialog = DirectoryChooser("Please select a directory contaning your images")
		inputDir = inputDialog.getDirectory()
		for imageFile in os.listdir(inputDir):
			self.files.append(inputDir + imageFile)

	def selectOutputDir(self):
		outputDialog = DirectoryChooser("Please select a directory to save your results")
		self.outputDir = outputDialog.getDirectory()
		
	def closeImage(self):
		if self.imp is not None:
			self.imp.close()
			self.imp = None
		if self.preview is not None:
			self.preview.close()
			self.preview = None

	def openImage(self, imageFile):
		try:
			images = BF.openImagePlus(imageFile)
			self.imp = images[0]
		except UnknownFormatException:
			return None
		if self.imp.getNChannels() < 2:
			IJ.error("Bad image format", "Image must contain at lease 2 channels!")
			return None
		if not self.pairs or \
			not self.methods:
			self.getOptionsDialog(self.imp)
		title = self.imp.title
		self.imp.title = title[:title.rfind('.')]
		return self.imp

	def getOptionsDialog(self, imp):
		thr_methods = ["None", "Default", "Huang", "Intermodes", "IsoData",  "Li", "MaxEntropy","Mean", "MinError(I)", "Minimum", "Moments", "Otsu", "Percentile", "RenyiEntropy", "Shanbhag" , "Triangle", "Yen"]
		gd = GenericDialog("Please select channels to collocalize")
		for i in range(1, imp.getNChannels() + 1):
			gd.addChoice("Threshold method for channel %i" % i, thr_methods, "None")
		gd.showDialog()
		if gd.wasCanceled():
			self.exit()
		channels = []
		for i in range(1, imp.getNChannels() + 1):
			method = gd.getNextChoice()
			self.methods.append(method)
			if method != "None":
				channels.append(i)
		for x in channels:
			for y in channels:
				if x < y:
					self.pairs.append((x, y))

	def processNextFile(self):
		if self.files:
			imageFile = self.files.pop(0)
			return self.processFile(imageFile)
		else:
			return False
			
	def processFile(self, imageFile):
		imp = self.openImage(imageFile)
		if imp is not None:
			cell = Cell(imp.NSlices, 1)
			self.cells = DelegateListModel([])
			self.cells.append(cell)
			self.showMainWindow(self.cells)
			if self.checkbox3D.isSelected():
				self.displayImage(imp)
			else:
				self.displayImage(imp, False)
				self.preview = self.previewImage(imp)
				self.displayImage(self.preview)
			return True
		else:
			return self.processNextFile()
	
	def displayImage(self, imp, show = True):
		imp.setDisplayMode(IJ.COMPOSITE)
		enhancer = ContrastEnhancer()
		enhancer.setUseStackHistogram(True)
		splitter = ChannelSplitter()
		for c in range(1, imp.getNChannels() + 1):
			imp.c = c
			enhancer.stretchHistogram(imp, 0.35)
		if show:
			imp.show()

	def previewImage(self, imp):
		roi = imp.getRoi()
		splitter = ChannelSplitter()
		channels = []
		for c in range(1, imp.getNChannels() + 1):
			channel = ImagePlus("Channel %i" % c, splitter.getChannel(imp, c))
			projector = ZProjector(channel)
			projector.setMethod(ZProjector.MAX_METHOD)
			projector.doProjection()
			channels.append(projector.getProjection())
		image = RGBStackMerge.mergeChannels(channels, False)
		image.title = imp.title + " MAX Intensity"
		image.luts = imp.luts
		imp.setRoi(roi)
		return image

	def getCroppedChannels(self, imp, cell):
		splitter = ChannelSplitter()
		imp.setRoi(None)
		if cell.mode3D:
			cropRoi = cell.getCropRoi()
		else:
			cropRoi = cell.roi
		if cropRoi is None:
			return None
		crop = cropRoi.getBounds()
		channels = []
		for c in range(1, imp.getNChannels() + 1):
			slices = ImageStack(crop.width, crop.height)
			channel = splitter.getChannel(imp, c)
			for z in range(1, channel.getSize() + 1):
				zslice = channel.getProcessor(z)
				zslice.setRoi(cropRoi)
				nslice = zslice.crop()
				if cell.mode3D:
					oroi = cell.slices[z - 1].roi	
				else:
					oroi = cell.roi
				if oroi is not None:
					roi = oroi.clone()
					bounds = roi.getBounds()
					roi.setLocation(bounds.x - crop.x, bounds.y - crop.y)
					nslice.setColor(Color.black)
					nslice.fillOutside(roi)
					slices.addSlice(nslice)
			channels.append(ImagePlus("Channel %i" % c, slices))
		return channels

	def getThreshold(self, imp, method):
		thresholder = Auto_Threshold()
		duplicator = Duplicator()
		tmp = duplicator.run(imp)
		return thresholder.exec(tmp, method, False, False, True, False, False, True)

	def getContainer(self, impA, impB):
		imgA = ImagePlusAdapter.wrap(impA)
		imgB = ImagePlusAdapter.wrap(impB)
		return DataContainer(imgA, imgB, 1, 1, "imageA", "imageB")

	def getManders(self, imp, cell):
	
		### Crop channels according to cell mask
		channels = self.getCroppedChannels(imp, cell)
		if channels is None:
			return None
			
		### Calculate channel thresholds
		thrs = []
		thrimps = []
		for c, method in enumerate(self.methods):
			if method != "None":
				thr, thrimp = self.getThreshold(channels[c], method)
			else:
				thr, thrimp = None, None
			thrs.append(thr)
			thrimps.append(thrimp)
		
		### Calculate manders colocalization
		manders = MandersColocalization()
		raws = []
		thrds = []
		for chA, chB in self.pairs:
			container = self.getContainer(channels[chA - 1], channels[chB - 1])
			img1 = container.getSourceImage1()
			img2 = container.getSourceImage2()
			mask = container.getMask()
			cursor = TwinCursor(img1.randomAccess(), img2.randomAccess(), Views.iterable(mask).localizingCursor())
			rtype = img1.randomAccess().get().createVariable()
			raw = manders.calculateMandersCorrelation(cursor, rtype)
			rthr1 = rtype.copy()
			rthr2 = rtype.copy()
			rthr1.set(thrs[chA - 1])
			rthr2.set(thrs[chB - 1])
			cursor.reset()
			thrd = manders.calculateMandersCorrelation(cursor, rthr1, rthr2, ThresholdMode.Above)
			raws.append(raw)
			thrds.append(thrd)
		
		return (channels, thrimps, thrs, raws, thrds)

	def saveMultichannelImage(self, title, channels, luts):
		tmp = RGBStackMerge.mergeChannels(channels, False)
		tmp.luts = luts
		saver = FileSaver(tmp)
		saver.saveAsTiffStack(self.outputDir + title + ".tif")
		tmp.close()

	def createMainWindow(self):
		self.frame = JFrame('Select cells and ROIs',
			defaultCloseOperation = JFrame.DISPOSE_ON_CLOSE
		)
		self.frame.setLayout(GridBagLayout())
		self.frame.addWindowListener(self)

		self.frame.add(JLabel("Cells"),
			GridBagConstraints(0, 0, 1, 1, 0, 0,
				GridBagConstraints.CENTER, GridBagConstraints.NONE,
				Insets(5, 2, 2, 0), 0, 0
		))
		
		self.cellList = JList(DelegateListModel([]),
			selectionMode = ListSelectionModel.SINGLE_SELECTION,
			cellRenderer = MyRenderer(),
			selectedIndex = 0,
			valueChanged = self.selectCell
		)
		self.frame.add(JScrollPane(self.cellList),
			GridBagConstraints(0, 1, 1, 5, .5, 1,
				GridBagConstraints.CENTER, GridBagConstraints.BOTH,
				Insets(0, 2, 2, 0), 0, 0
		))

		self.frame.add(JButton('Add cell', actionPerformed = self.addCell),
			GridBagConstraints(1, 2, 1, 2, 0, .25,
				GridBagConstraints.CENTER, GridBagConstraints.NONE,
				Insets(0, 0, 0, 0), 0, 0
		))
    	
		self.frame.add(JButton('Remove cell', actionPerformed = self.removeCell),
			GridBagConstraints(1, 4, 1, 2, 0, .25,
				GridBagConstraints.CENTER, GridBagConstraints.NONE,
				Insets(0, 5, 0, 5), 0, 0
		))
		
		self.frame.add(JLabel("Slices"),
			GridBagConstraints(0, 6, 1, 1, 0, 0,
				GridBagConstraints.CENTER, GridBagConstraints.NONE,
				Insets(5, 2, 2, 0), 0, 0
		))
		
		self.sliceList = JList(DelegateListModel([]),
			selectionMode = ListSelectionModel.SINGLE_SELECTION,
			cellRenderer = MyRenderer(),
			selectedIndex = 0,
			valueChanged = self.selectSlice
		)
		self.frame.add(JScrollPane(self.sliceList),
			GridBagConstraints(0, 7, 1, 5, .5, 1,
				GridBagConstraints.CENTER, GridBagConstraints.BOTH,
				Insets(0, 2, 2, 0), 0, 0
		))

		self.frame.add(JButton('Update ROI', actionPerformed = self.updateSlice),
			GridBagConstraints(1, 8, 1, 2, 0, .25,
				GridBagConstraints.CENTER, GridBagConstraints.NONE,
				Insets(0, 0, 0, 0), 0, 0
		))

		self.frame.add(JButton('Done', actionPerformed = self.doneSelecting),
			GridBagConstraints(1, 10, 1, 2, 0, .25,
				GridBagConstraints.CENTER, GridBagConstraints.NONE,
				Insets(0, 0, 0, 0), 0, 0
		))

		self.checkbox3D = JCheckBox('3D selection mode', True, actionPerformed=self.toggle3D)
		self.frame.add(self.checkbox3D,
			GridBagConstraints(0, 13, 2, 1, 0, 1,
				GridBagConstraints.WEST, GridBagConstraints.NONE,
				Insets(0, 0, 0, 0), 0, 0
		))

	def showMainWindow(self, cells = None):
		if cells is not None:
			self.cellList.model = cells
			if cells:
				self.cellList.selectedIndex = 0
		self.frame.pack()
		self.frame.visible = True

	def hideMainWindow(self):
		self.frame.visible = False

	def closeMainWindow(self):
		self.frame.dispose()

	def toggle3D(self, event):
		mode3D = self.checkbox3D.isSelected()
		if mode3D:
			self.sliceList.enabled = True
			if self.imp is not None:
				self.imp.show()
			if self.preview is not None:
				self.preview.hide()
		else:
			self.sliceList.enabled = False
			if self.preview is None:
				self.preview = self.previewImage(self.imp)
				self.displayImage(self.preview)
			else:
				self.preview.show()
			if self.imp is not None:
				self.imp.hide()
		selectedCell = self.cellList.selectedIndex
		if selectedCell >= 0:
			cell = self.cells[selectedCell]
			self.sliceList.model = cell.slices
			self.sliceList.selectedIndex = 0
		
	def addCell(self, event):
		size = len(self.cells)
		if (size > 0):
			last = self.cells[size - 1]
			n = last.n + 1
		else:
			n = 1
		self.cells.append(Cell(self.imp.NSlices, n))
		self.cellList.selectedIndex = size

	def removeCell(self, event):
		selected = self.cellList.selectedIndex
		if selected >= 0:
			self.cells.remove(self.cells[selected])
			if (selected >= 1):
				self.cellList.selectedIndex = selected - 1
			else:
				self.cellList.selectedIndex = 0

	def selectCell(self, event):
		selected = self.cellList.selectedIndex
		if selected >= 0:
			cell = self.cells[selected]
			self.sliceList.model = cell.slices
			self.sliceList.selectedIndex = 0
		else:
			self.sliceList.model = DelegateListModel([])
		if self.preview is not None:
			self.preview.setRoi(cell.roi)

	def selectSlice(self, event):
		selectedCell = self.cellList.selectedIndex
		selectedSlice = self.sliceList.selectedIndex
		if selectedCell >= 0 and selectedSlice >= 0:
			cell = self.cells[selectedCell]
			image = self.imp
			mode3D = self.checkbox3D.isSelected()
			if image is not None and cell is not None and mode3D:
				roi = cell.slices[selectedSlice].roi
				if (image.z - 1 != selectedSlice):
					image.z = selectedSlice + 1				
				image.setRoi(roi, True)
			if self.preview is not None and not mode3D:
				self.preview.setRoi(cell.roi, True)

	def updateSlice(self, event):
		if self.checkbox3D.isSelected():
			self.updateSlice3D(self.imp)
		else:
			self.updateSlice2D(self.preview)

	def updateSlice3D(self, imp):
		selectedCell = self.cellList.selectedIndex
		selectedSlice = self.sliceList.selectedIndex
		if selectedCell >= 0 and selectedSlice >= 0 and imp is not None:
			cell = self.cells[selectedCell]
			impRoi = imp.getRoi()
			if cell is not None and impRoi is not None:
				index = selectedSlice + 1
				roi = ShapeRoi(impRoi, position = index)
				cell.mode3D = True
				cell.name = "Cell %i (3D)" % cell.n
				cell.slices[selectedSlice].roi = roi
				if (index + 1 <= len(cell.slices)):
					imp.z = index + 1			
			self.cellList.repaint(self.cellList.getCellBounds(selectedCell, selectedCell))
			self.sliceList.repaint(self.sliceList.getCellBounds(selectedSlice, selectedSlice))

	def updateSlice2D(self, imp):
		selectedCell = self.cellList.selectedIndex
		if selectedCell >= 0 and imp is not None:
			cell = self.cells[selectedCell]
			impRoi = imp.getRoi()
			if cell is not None and impRoi is not None:
				roi = ShapeRoi(impRoi, position = 1)
				cell.mode3D = False
				cell.name = "Cell %i (2D)" % cell.n
				cell.roi = roi	
			self.cellList.repaint(self.cellList.getCellBounds(selectedCell, selectedCell))
	
	def imageOpened(self, imp):
		pass

	def imageClosed(self, imp):
		pass

	def imageUpdated(self, imp):
		if self.checkbox3D.isSelected():
			if imp is not None:
				selectedCell = self.cellList.selectedIndex
				selectedSlice = imp.z - 1
			if imp == self.imp and selectedSlice != self.sliceList.selectedIndex:
				self.sliceList.selectedIndex = selectedSlice

	def doneSelecting(self, event):
		oluts = self.imp.luts
		luts = []
		channels = []
		for c, method in enumerate(self.methods):
			if method != "None":
				luts.append(oluts[c])
				channels.append(c)
		for cell in self.cells:
			manders = self.getManders(self.imp, cell)
			if manders is not None:
				chimps, thrimps, thrs, raws, thrds = manders
				index = self.cells.index(cell) + 1
				title = "Cell_%i-" % index + self.imp.title
				self.saveMultichannelImage(title, chimps, oluts)
				title = "Cell_%i_thrd-" % index + self.imp.title
				self.saveMultichannelImage(title, thrimps, luts)
				self.results.incrementCounter()
				row = self.results.getCounter() - 1
				for i, thr in enumerate(thrs):
					if thr is not None:
						self.results.setValue("Threshold %i" % (i + 1), row, int(thr))
				for i, pair in enumerate(self.pairs):
					self.results.setValue("%i-%i M1 raw" % pair, row, float(raws[i].m1))
					self.results.setValue("%i-%i M2 raw" % pair, row, float(raws[i].m2))
					self.results.setValue("%i-%i M1 thrd" % pair, row, float(thrds[i].m1))
					self.results.setValue("%i-%i M2 thrd" % pair, row, float(thrds[i].m2))
		self.closeImage()
		if not self.processNextFile():
			print "All done - happy analysis!"
			self.results.show("Manders collocalization results")
			self.exit()

	def windowClosing(self, e):
		print "Closing plugin - BYE!!!"
		self.exit()

	def exit(self):
		ImagePlus.removeImageListener(self)
		self.closeImage()
		self.closeMainWindow()
Exemplo n.º 47
0
	def createMainWindow(self):
		self.frame = JFrame('Select cells and ROIs',
			defaultCloseOperation = JFrame.DISPOSE_ON_CLOSE
		)
		self.frame.setLayout(GridBagLayout())
		self.frame.addWindowListener(self)

		self.frame.add(JLabel("Cells"),
			GridBagConstraints(0, 0, 1, 1, 0, 0,
				GridBagConstraints.CENTER, GridBagConstraints.NONE,
				Insets(5, 2, 2, 0), 0, 0
		))
		
		self.cellList = JList(DelegateListModel([]),
			selectionMode = ListSelectionModel.SINGLE_SELECTION,
			cellRenderer = MyRenderer(),
			selectedIndex = 0,
			valueChanged = self.selectCell
		)
		self.frame.add(JScrollPane(self.cellList),
			GridBagConstraints(0, 1, 1, 5, .5, 1,
				GridBagConstraints.CENTER, GridBagConstraints.BOTH,
				Insets(0, 2, 2, 0), 0, 0
		))

		self.frame.add(JButton('Add cell', actionPerformed = self.addCell),
			GridBagConstraints(1, 2, 1, 2, 0, .25,
				GridBagConstraints.CENTER, GridBagConstraints.NONE,
				Insets(0, 0, 0, 0), 0, 0
		))
    	
		self.frame.add(JButton('Remove cell', actionPerformed = self.removeCell),
			GridBagConstraints(1, 4, 1, 2, 0, .25,
				GridBagConstraints.CENTER, GridBagConstraints.NONE,
				Insets(0, 5, 0, 5), 0, 0
		))
		
		self.frame.add(JLabel("Slices"),
			GridBagConstraints(0, 6, 1, 1, 0, 0,
				GridBagConstraints.CENTER, GridBagConstraints.NONE,
				Insets(5, 2, 2, 0), 0, 0
		))
		
		self.sliceList = JList(DelegateListModel([]),
			selectionMode = ListSelectionModel.SINGLE_SELECTION,
			cellRenderer = MyRenderer(),
			selectedIndex = 0,
			valueChanged = self.selectSlice
		)
		self.frame.add(JScrollPane(self.sliceList),
			GridBagConstraints(0, 7, 1, 5, .5, 1,
				GridBagConstraints.CENTER, GridBagConstraints.BOTH,
				Insets(0, 2, 2, 0), 0, 0
		))

		self.frame.add(JButton('Update ROI', actionPerformed = self.updateSlice),
			GridBagConstraints(1, 8, 1, 2, 0, .25,
				GridBagConstraints.CENTER, GridBagConstraints.NONE,
				Insets(0, 0, 0, 0), 0, 0
		))

		self.frame.add(JButton('Done', actionPerformed = self.doneSelecting),
			GridBagConstraints(1, 10, 1, 2, 0, .25,
				GridBagConstraints.CENTER, GridBagConstraints.NONE,
				Insets(0, 0, 0, 0), 0, 0
		))

		self.checkbox3D = JCheckBox('3D selection mode', True, actionPerformed=self.toggle3D)
		self.frame.add(self.checkbox3D,
			GridBagConstraints(0, 13, 2, 1, 0, 1,
				GridBagConstraints.WEST, GridBagConstraints.NONE,
				Insets(0, 0, 0, 0), 0, 0
		))
Exemplo n.º 48
0
class Popup(JWindow):
    """Popup window to display list of methods for completion"""
    
    MAX_HEIGHT = 300
    MIN_WIDTH = 200
    MAX_WIDTH = 400
    
    def __init__(self, frame, textComponent):
        JWindow.__init__(self, frame)
        self.textComponent = textComponent
        self.size = (200,200)
        self.list = JList(keyPressed=self.key)
        self.list.setBackground(Color(255,255,225)) # TODO move this color
        self.getContentPane().add(JScrollPane(self.list))
        self.list.setSelectedIndex(0)

        self.originalData = ""
        self.data = ""
        self.typed = ""

    def key(self, e):
        # print >> sys.stderr, "Other Listener"
        if not self.visible:
            return

        code = e.getKeyCode()
        
        if code == KeyEvent.VK_ESCAPE:
            self.hide()

        elif code == KeyEvent.VK_ENTER or code == KeyEvent.VK_TAB:
            self.chooseSelected()
            e.consume()

        elif code == KeyEvent.VK_SPACE:
            # TODO for functions: choose the selected option, add parenthesis
            # and put the cursor between them.  example: obj.function(^cursor_here)
            self.chooseSelected()

        elif code == KeyEvent.VK_PERIOD:
            self.chooseSelected()
            #e.consume()
            
        # This fails because the key listener in console gets it first
        elif code == KeyEvent.VK_LEFT_PARENTHESIS:
            self.chooseSelected()

        elif code == 8: # BACKSPACE
            if len(self.typed) == 0:
                self.hide()
            self.typed = self.typed[:-1]
            print >> sys.stderr, self.typed
            self.data = filter(self.originalData, self.typed)
            self.list.setListData(self.data)
            self.list.setSelectedIndex(0)
                
        elif code == KeyEvent.VK_UP:
            self.previous()
            # consume event to avoid history previous
            e.consume()
            
        elif code == KeyEvent.VK_DOWN:
            self.next()
            # consume event to avoid history next
            e.consume()
            
        else:
            char = e.getKeyChar()
            if Character.isJavaLetterOrDigit(char):
                self.typed += char 
                self.data = filter(self.data, self.typed)
                self.list.setListData(self.data)
                self.list.setSelectedIndex(0)
                
    def next(self):
        index = self.list.getSelectedIndex()
        max = (self.list.getModel().getSize() - 1)
        
        if index < max:
            index += 1
            self.list.setSelectedIndex(index)
            self.list.ensureIndexIsVisible(index)
        
    def previous(self):
        index = self.list.getSelectedIndex()

        if index > 0:
            index -= 1
            self.list.setSelectedIndex(index)
            self.list.ensureIndexIsVisible(index)

    def chooseSelected(self):
        """Choose the selected value in the list"""
        value = self.list.getSelectedValue()
        if value != None:
            startPosition = self.dotPosition + 1
            caretPosition = self.textComponent.getCaretPosition()
            self.textComponent.select(startPosition, caretPosition) 
            self.textComponent.replaceSelection(value)
            self.textComponent.setCaretPosition(startPosition + len(value))
        self.hide()

    def setMethods(self, methodList):
        methodList.sort()
        self.data = methodList
        self.originalData = methodList
        self.typed = ""
        self.list.setListData(methodList)

    def show(self):
        # when the popup becomes visible, get the cursor
        # so we know how to replace the selection
        self.dotPosition = self.textComponent.getCaretPosition()
        self.setSize(self.getPreferredSize())
        JWindow.show(self)

    def showMethodCompletionList(self, list, displayPoint):
        self.setLocation(displayPoint)
        self.setMethods(list)
        self.show()
        self.list.setSelectedIndex(0)

    def getPreferredSize(self):
        # need to add a magic amount to the size to avoid scrollbars
        # I'm sure there's a better way to do this
        MAGIC = 20
        size = self.list.getPreferredScrollableViewportSize()
        height = size.height + MAGIC
        width = size.width + MAGIC
        if height > Popup.MAX_HEIGHT:
            height = Popup.MAX_HEIGHT
        if width > Popup.MAX_WIDTH:
            width = Popup.MAX_WIDTH
        if width < Popup.MIN_WIDTH:
            widht = Popup.MIN_WIDTH
        return Dimension(width, height)
Exemplo n.º 49
0
    def initComponents(self):
        self.panel0 = JPanel()

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

        self.Error_Message = JLabel( "") 
        self.Error_Message.setEnabled(True)
        self.gbcPanel0.gridx = 2
        self.gbcPanel0.gridy = 31
        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.Label_1 = JLabel("Volatility Executable Directory")
        self.Label_1.setEnabled(True)
        self.gbcPanel0.gridx = 2 
        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.Label_1, self.gbcPanel0 ) 
        self.panel0.add( self.Label_1 ) 

        self.Program_Executable_TF = JTextField(10) 
        self.Program_Executable_TF.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.Program_Executable_TF, self.gbcPanel0 ) 
        self.panel0.add( self.Program_Executable_TF ) 

        self.Find_Program_Exec_BTN = JButton( "Find Dir", actionPerformed=self.Find_Dir)
        self.Find_Program_Exec_BTN.setEnabled(True)
        self.rbgPanel0.add( self.Find_Program_Exec_BTN ) 
        self.gbcPanel0.gridx = 6 
        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.Find_Program_Exec_BTN, self.gbcPanel0 ) 
        self.panel0.add( self.Find_Program_Exec_BTN ) 

        self.Blank_1 = JLabel( " ") 
        self.Blank_1.setEnabled(True)
        self.gbcPanel0.gridx = 2 
        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.Blank_1, self.gbcPanel0 ) 
        self.panel0.add( self.Blank_1 ) 

        self.Version_Label_1 = JLabel( "Version:") 
        self.Blank_1.setEnabled(True)
        self.gbcPanel0.gridx = 2 
        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.Version_Label_1, self.gbcPanel0 ) 
        self.panel0.add( self.Version_Label_1 ) 
        
        self.Version_List = ("2.5", "2.6") 
        self.Version_CB = JComboBox( self.Version_List)
        self.Version_CB.itemStateChanged = self.onchange_version        
        self.gbcPanel0.gridx = 6 
        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.Version_CB, self.gbcPanel0 ) 
        self.panel0.add( self.Version_CB ) 

        self.Blank_3 = JLabel( " ") 
        self.Blank_3.setEnabled(True)
        self.gbcPanel0.gridx = 2 
        self.gbcPanel0.gridy = 13
        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, self.gbcPanel0 ) 
        self.panel0.add( self.Blank_3 ) 

        self.Plugin_Label_1 = JLabel( "Plugins:") 
        self.Blank_1.setEnabled(True)
        self.gbcPanel0.gridx = 2 
        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.Plugin_Label_1, self.gbcPanel0 ) 
        self.panel0.add( self.Plugin_Label_1 ) 
        
        self.Plugin_list = self.get_plugins()
        self.Plugin_LB = JList( self.Plugin_list, valueChanged=self.onchange_plugins_lb)
        self.Plugin_LB.setVisibleRowCount( 3 ) 
        self.scpPlugin_LB = JScrollPane( self.Plugin_LB ) 
        self.gbcPanel0.gridx = 6 
        self.gbcPanel0.gridy = 15 
        self.gbcPanel0.gridwidth = 1 
        self.gbcPanel0.gridheight = 1 
        self.gbcPanel0.fill = GridBagConstraints.BOTH 
        self.gbcPanel0.weightx = 1 
        self.gbcPanel0.weighty = 1 
        self.gbcPanel0.anchor = GridBagConstraints.NORTH 
        self.gbPanel0.setConstraints( self.scpPlugin_LB, self.gbcPanel0 ) 
        self.panel0.add( self.scpPlugin_LB ) 

        self.Blank_4 = JLabel( " ") 
        self.Blank_4.setEnabled(True)
        self.gbcPanel0.gridx = 2 
        self.gbcPanel0.gridy = 17
        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, self.gbcPanel0 ) 
        self.panel0.add( self.Blank_4 ) 

        self.Profile_Label_1 = JLabel( "Profile:") 
        self.Blank_1.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.Profile_Label_1, self.gbcPanel0 ) 
        self.panel0.add( self.Profile_Label_1 ) 
        
        self.Profile_List = self.get_profiles()
        self.Profile_CB = JComboBox( self.Profile_List)
        self.Profile_CB.itemStateChanged = self.onchange_profile_cb        
        self.gbcPanel0.gridx = 6 
        self.gbcPanel0.gridy = 19 
        self.gbcPanel0.gridwidth = 1 
        self.gbcPanel0.gridheight = 1 
        self.gbcPanel0.fill = GridBagConstraints.BOTH 
        self.gbcPanel0.weightx = 1 
        self.gbcPanel0.weighty = 1 
        self.gbcPanel0.anchor = GridBagConstraints.NORTH 
        self.gbPanel0.setConstraints( self.Profile_CB, self.gbcPanel0 ) 
        self.panel0.add( self.Profile_CB ) 

        self.Blank_5 = JLabel( " ") 
        self.Blank_5.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_5, self.gbcPanel0 ) 
        self.panel0.add( self.Blank_5 ) 

        self.Label_2 = JLabel("Additional Parameters To Run With:")
        self.Label_2.setEnabled(True)
        self.gbcPanel0.gridx = 2 
        self.gbcPanel0.gridy = 23 
        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.Label_2, self.gbcPanel0 ) 
        self.panel0.add( self.Label_2 ) 

        self.Additional_Parms_TF = JTextField(10,focusLost=self.keyPressed) 
        #self.Additional_Parms_TF.getDocument().addDocumentListener()
        self.Additional_Parms_TF.setEnabled(True)
        self.gbcPanel0.gridx = 2 
        self.gbcPanel0.gridy = 25 
        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.Additional_Parms_TF, self.gbcPanel0 ) 
        self.panel0.add( self.Additional_Parms_TF ) 

        self.Blank_6 = JLabel( " ") 
        self.Blank_6.setEnabled(True)
        self.gbcPanel0.gridx = 2 
        self.gbcPanel0.gridy = 27
        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, self.gbcPanel0 ) 
        self.panel0.add( self.Blank_6 ) 

        self.Label_3 = JLabel( "Message:") 
        self.Label_3.setEnabled(True)
        self.gbcPanel0.gridx = 2 
        self.gbcPanel0.gridy = 29
        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.Label_3, self.gbcPanel0 ) 
        self.panel0.add( self.Label_3 ) 
		
        self.add(self.panel0)
Exemplo n.º 50
0
class BurpExtender(IBurpExtender, ITab, IMessageEditorController, AbstractTableModel, IContextMenuFactory):

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

        table {
            border: 2px dashed #000000;
        }

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

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

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

        
    }         
</script>
    </head>

    <body>
        <div id="warpcenter">

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    def getColumnCount(self):
        return 3

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

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

        return ""

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

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

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

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

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

        path = self.getVulnReqResPath("request",vulnObject.getName())
        if os.path.exists(path):
            f = self.getFileContent(path)
            self._requestViewer.setMessage(f, False)
        else:
            self._requestViewer.setMessage("None", False)
        
        path = self.getVulnReqResPath("response",vulnObject.getName())
        if os.path.exists(path):
            f = self.getFileContent(path)
            self._responseViewer.setMessage(f, False)
        else:
            self._responseViewer.setMessage("None", False)
Exemplo n.º 51
0
    def initVulnerabilityTab(self):
        #
        ##  init vulnerability tab
        #

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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


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

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

        self.pnl = JPanel()
        self.pnl.setBounds(0, 0, 1000, 1000);
        self.pnl.setLayout(None);
        self.pnl.add(addSSBtn)
        self.pnl.add(piclistLabel)
        self.pnl.add(nameLabel)
        self.pnl.add(deleteSSBtn)
        self.pnl.add(rmVulnButton)
        self.pnl.add(severityLabel)
        self.pnl.add(mitigationLabel)
        self.pnl.add(descriptionLabel)
        self.pnl.add(previewPicLabel)
        self.pnl.add(mitigationStrScroll)
        self.pnl.add(descriptionStringScroll)
        self.pnl.add(self.ssList)
        self.pnl.add(self.firstPic)
        self.pnl.add(self.addButton)
        self.pnl.add(self.vulnName)
        self.pnl.add(self.threatLevel)
        self.pnl.add(self.colorCombo)
Exemplo n.º 52
0
    def initComponents(self):
        self.panel0 = JPanel()

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

        self.Exec_Program_CB = JCheckBox("Execute Program", actionPerformed=self.checkBoxEvent)
        self.gbcPanel0.gridx = 2 
        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.Exec_Program_CB, self.gbcPanel0 ) 
        self.panel0.add( self.Exec_Program_CB ) 

        self.Program_Executable_TF = JTextField(20) 
        self.Program_Executable_TF.setEnabled(False)
        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.Program_Executable_TF, self.gbcPanel0 ) 
        self.panel0.add( self.Program_Executable_TF ) 

        self.Find_Program_Exec_BTN = JButton( "Find Exec", actionPerformed=self.onClick)
        self.Find_Program_Exec_BTN.setEnabled(False)
        self.rbgPanel0.add( self.Find_Program_Exec_BTN ) 
        self.gbcPanel0.gridx = 6 
        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.Find_Program_Exec_BTN, self.gbcPanel0 ) 
        self.panel0.add( self.Find_Program_Exec_BTN ) 

        self.Imp_File_CB = JCheckBox( "Import File", actionPerformed=self.checkBoxEvent) 
        self.gbcPanel0.gridx = 2 
        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.Imp_File_CB, self.gbcPanel0 ) 
        self.panel0.add( self.Imp_File_CB ) 

        self.File_Imp_TF = JTextField(20) 
        self.File_Imp_TF.setEnabled(False)
        self.gbcPanel0.gridx = 2 
        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.File_Imp_TF, self.gbcPanel0 ) 
        self.panel0.add( self.File_Imp_TF ) 

        self.Find_Imp_File_BTN = JButton( "Find File", actionPerformed=self.onClick) 
        self.Find_Imp_File_BTN.setEnabled(False)
        self.rbgPanel0.add( self.Find_Imp_File_BTN ) 
        self.gbcPanel0.gridx = 6 
        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.Find_Imp_File_BTN, self.gbcPanel0 ) 
        self.panel0.add( self.Find_Imp_File_BTN ) 

        self.Check_Box_CB = JCheckBox( "Check Box 1", actionPerformed=self.checkBoxEvent) 
        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.Check_Box_CB, self.gbcPanel0 ) 
        self.panel0.add( self.Check_Box_CB ) 

        self.dataComboBox_CB = ("Chocolate", "Ice Cream", "Apple Pie") 
        self.ComboBox_CB = JComboBox( self.dataComboBox_CB)
        self.ComboBox_CB.itemStateChanged = self.onchange_cb        
        self.gbcPanel0.gridx = 2 
        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.ComboBox_CB, self.gbcPanel0 ) 
        self.panel0.add( self.ComboBox_CB ) 
        
        self.dataList_Box_LB = ("Chocolate", "Ice Cream", "Apple Pie", "Pudding", "Candy" )
        self.List_Box_LB = JList( self.dataList_Box_LB, valueChanged=self.onchange_lb)
        #self.List_Box_LB.itemStateChanged = self.onchange_lb
        self.List_Box_LB.setVisibleRowCount( 3 ) 
        self.scpList_Box_LB = JScrollPane( self.List_Box_LB ) 
        self.gbcPanel0.gridx = 6 
        self.gbcPanel0.gridy = 15 
        self.gbcPanel0.gridwidth = 1 
        self.gbcPanel0.gridheight = 1 
        self.gbcPanel0.fill = GridBagConstraints.BOTH 
        self.gbcPanel0.weightx = 1 
        self.gbcPanel0.weighty = 1 
        self.gbcPanel0.anchor = GridBagConstraints.NORTH 
        self.gbPanel0.setConstraints( self.scpList_Box_LB, self.gbcPanel0 ) 
        self.panel0.add( self.scpList_Box_LB ) 

        # self.Radio_Button_RB = JRadioButton( "Radio Button"  ) 
        # self.rbgPanel0.add( self.Radio_Button_RB ) 
        # self.gbcPanel0.gridx = 7 
        # self.gbcPanel0.gridy = 17
        # 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.Radio_Button_RB, self.gbcPanel0 ) 
        # self.panel0.add( self.Radio_Button_RB ) 

        # self.Label_1 = JLabel( "Error Message:") 
        # self.Label_1.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.Label_1, self.gbcPanel0 ) 
        # self.panel0.add( self.Label_1 ) 
		
        # self.Error_Message = JLabel( "") 
        # self.Error_Message.setEnabled(True)
        # self.gbcPanel0.gridx = 6
        # 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.Error_Message, self.gbcPanel0 ) 
        # self.panel0.add( self.Error_Message ) 
		
        self.add(self.panel0)
Exemplo n.º 53
0
class VolatilitySettingsWithUISettingsPanel(IngestModuleIngestJobSettingsPanel):
    # Note, we can't use a self.settings instance variable.
    # Rather, self.local_settings is used.
    # https://wiki.python.org/jython/UserGuide#javabean-properties
    # Jython Introspector generates a property - 'settings' on the basis
    # of getSettings() defined in this class. Since only getter function
    # is present, it creates a read-only 'settings' property. This auto-
    # generated read-only property overshadows the instance-variable -
    # 'settings'
    
    # We get passed in a previous version of the settings so that we can
    # prepopulate the UI
    # TODO: Update this for your UI
    
    _logger = Logger.getLogger(VolatilityIngestModuleFactory.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.initComponents()
        self.customizeComponents()
    
    # Check the checkboxs to see what actions need to be taken
    def checkBoxEvent(self, event):
        if self.Exclude_File_Sources_CB.isSelected():
            self.local_settings.setSetting('Exclude_File_Sources', 'true')
        else:
            self.local_settings.setSetting('Exclude_File_Sources', 'false')

    def get_plugins(self):
        head, tail = os.path.split(os.path.abspath(__file__))
        settings_db = os.path.join(head, "GUI_Settings.db3")
        try: 
            Class.forName("org.sqlite.JDBC").newInstance()
            dbConn = DriverManager.getConnection("jdbc:sqlite:%s"  % settings_db)
            self.Error_Message.setText("Database opened")
        except SQLException as e:
            self.Error_Message.setText("Error Opening Settings DB!")
 
        try:
           stmt = dbConn.createStatement()
           SQL_Statement = "select plugin_name from plugins where volatility_version = '" + self.Version_CB.getSelectedItem() + "';" 
           resultSet = stmt.executeQuery(SQL_Statement)
           plugin_list = []
           while resultSet.next():
              plugin_list.append(resultSet.getString("plugin_name"))

           stmt.close()
           dbConn.close()
           return plugin_list
        except SQLException as e:
            self.Error_Message.setText("Error Reading plugins")
            stmt.close()
            dbConn.close()
            return "Error"

    def get_profiles(self):
        head, tail = os.path.split(os.path.abspath(__file__)) 
        settings_db = os.path.join(head, "GUI_Settings.db3")
        try: 
            Class.forName("org.sqlite.JDBC").newInstance()
            dbConn = DriverManager.getConnection("jdbc:sqlite:%s"  % settings_db)
            self.Error_Message.setText("Database opened")
        except SQLException as e:
            self.Error_Message.setText("Error Opening Settings DB!")
 
        try:
           stmt = dbConn.createStatement()
           SQL_Statement = "select profile_name from profiles where volatility_version = '" + self.Version_CB.getSelectedItem() + "';" 
           resultSet = stmt.executeQuery(SQL_Statement)
           profile_list = []
           while resultSet.next():
              profile_list.append(resultSet.getString("profile_name"))

           stmt.close()
           dbConn.close()
           return profile_list
        except SQLException as e:
            self.Error_Message.setText("Error Reading plugins")
            stmt.close()
            dbConn.close()
            return "Error"

    # When button to find file is clicked then open dialog to find the file and return it.       
    def Find_Dir(self, e):

       chooseFile = JFileChooser()
       filter = FileNameExtensionFilter("All", ["*.*"])
       chooseFile.addChoosableFileFilter(filter)
       #chooseFile.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY)

       ret = chooseFile.showDialog(self.panel0, "Find Volatility Directory")

       if ret == JFileChooser.APPROVE_OPTION:
           file = chooseFile.getSelectedFile()
           Canonical_file = file.getCanonicalPath()
           #text = self.readPath(file)
           self.local_settings.setSetting('Volatility_Directory', Canonical_file)
           self.Program_Executable_TF.setText(Canonical_file)

    def keyPressed(self, event):
        self.local_settings.setSetting('AdditionalParms', self.Additional_Parms_TF.getText()) 
        #self.Error_Message.setText(self.Additional_Parms_TF.getText())
        
    def onchange_version(self, event):
        self.local_settings.setSetting('Version', event.item)        
        plugin_list = self.get_plugins()
        profile_list = self.get_profiles()
        self.Profile_CB.removeAllItems()
        self.Plugin_LB.clearSelection()
        self.Plugin_LB.setListData(plugin_list)
        for profile in profile_list:
            self.Profile_CB.addItem(profile)
        #self.Profile_CB.addItems(profile)
        self.panel0.repaint()
        
    def onchange_plugins_lb(self, event):
        self.local_settings.setSetting('PluginListBox' , '')
        list_selected = self.Plugin_LB.getSelectedValuesList()
        self.local_settings.setSetting('PluginListBox', str(list_selected))      
 
    def onchange_profile_cb(self, event):
        self.local_settings.setSetting('Profile', event.item) 

    # Create the initial data fields/layout in the UI
    def initComponents(self):
        self.panel0 = JPanel()

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

        self.Error_Message = JLabel( "") 
        self.Error_Message.setEnabled(True)
        self.gbcPanel0.gridx = 2
        self.gbcPanel0.gridy = 31
        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.Label_1 = JLabel("Volatility Executable Directory")
        self.Label_1.setEnabled(True)
        self.gbcPanel0.gridx = 2 
        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.Label_1, self.gbcPanel0 ) 
        self.panel0.add( self.Label_1 ) 

        self.Program_Executable_TF = JTextField(10) 
        self.Program_Executable_TF.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.Program_Executable_TF, self.gbcPanel0 ) 
        self.panel0.add( self.Program_Executable_TF ) 

        self.Find_Program_Exec_BTN = JButton( "Find Dir", actionPerformed=self.Find_Dir)
        self.Find_Program_Exec_BTN.setEnabled(True)
        self.rbgPanel0.add( self.Find_Program_Exec_BTN ) 
        self.gbcPanel0.gridx = 6 
        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.Find_Program_Exec_BTN, self.gbcPanel0 ) 
        self.panel0.add( self.Find_Program_Exec_BTN ) 

        self.Blank_1 = JLabel( " ") 
        self.Blank_1.setEnabled(True)
        self.gbcPanel0.gridx = 2 
        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.Blank_1, self.gbcPanel0 ) 
        self.panel0.add( self.Blank_1 ) 

        self.Version_Label_1 = JLabel( "Version:") 
        self.Blank_1.setEnabled(True)
        self.gbcPanel0.gridx = 2 
        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.Version_Label_1, self.gbcPanel0 ) 
        self.panel0.add( self.Version_Label_1 ) 
        
        self.Version_List = ("2.5", "2.6") 
        self.Version_CB = JComboBox( self.Version_List)
        self.Version_CB.itemStateChanged = self.onchange_version        
        self.gbcPanel0.gridx = 6 
        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.Version_CB, self.gbcPanel0 ) 
        self.panel0.add( self.Version_CB ) 

        self.Blank_3 = JLabel( " ") 
        self.Blank_3.setEnabled(True)
        self.gbcPanel0.gridx = 2 
        self.gbcPanel0.gridy = 13
        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, self.gbcPanel0 ) 
        self.panel0.add( self.Blank_3 ) 

        self.Plugin_Label_1 = JLabel( "Plugins:") 
        self.Blank_1.setEnabled(True)
        self.gbcPanel0.gridx = 2 
        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.Plugin_Label_1, self.gbcPanel0 ) 
        self.panel0.add( self.Plugin_Label_1 ) 
        
        self.Plugin_list = self.get_plugins()
        self.Plugin_LB = JList( self.Plugin_list, valueChanged=self.onchange_plugins_lb)
        self.Plugin_LB.setVisibleRowCount( 3 ) 
        self.scpPlugin_LB = JScrollPane( self.Plugin_LB ) 
        self.gbcPanel0.gridx = 6 
        self.gbcPanel0.gridy = 15 
        self.gbcPanel0.gridwidth = 1 
        self.gbcPanel0.gridheight = 1 
        self.gbcPanel0.fill = GridBagConstraints.BOTH 
        self.gbcPanel0.weightx = 1 
        self.gbcPanel0.weighty = 1 
        self.gbcPanel0.anchor = GridBagConstraints.NORTH 
        self.gbPanel0.setConstraints( self.scpPlugin_LB, self.gbcPanel0 ) 
        self.panel0.add( self.scpPlugin_LB ) 

        self.Blank_4 = JLabel( " ") 
        self.Blank_4.setEnabled(True)
        self.gbcPanel0.gridx = 2 
        self.gbcPanel0.gridy = 17
        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, self.gbcPanel0 ) 
        self.panel0.add( self.Blank_4 ) 

        self.Profile_Label_1 = JLabel( "Profile:") 
        self.Blank_1.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.Profile_Label_1, self.gbcPanel0 ) 
        self.panel0.add( self.Profile_Label_1 ) 
        
        self.Profile_List = self.get_profiles()
        self.Profile_CB = JComboBox( self.Profile_List)
        self.Profile_CB.itemStateChanged = self.onchange_profile_cb        
        self.gbcPanel0.gridx = 6 
        self.gbcPanel0.gridy = 19 
        self.gbcPanel0.gridwidth = 1 
        self.gbcPanel0.gridheight = 1 
        self.gbcPanel0.fill = GridBagConstraints.BOTH 
        self.gbcPanel0.weightx = 1 
        self.gbcPanel0.weighty = 1 
        self.gbcPanel0.anchor = GridBagConstraints.NORTH 
        self.gbPanel0.setConstraints( self.Profile_CB, self.gbcPanel0 ) 
        self.panel0.add( self.Profile_CB ) 

        self.Blank_5 = JLabel( " ") 
        self.Blank_5.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_5, self.gbcPanel0 ) 
        self.panel0.add( self.Blank_5 ) 

        self.Label_2 = JLabel("Additional Parameters To Run With:")
        self.Label_2.setEnabled(True)
        self.gbcPanel0.gridx = 2 
        self.gbcPanel0.gridy = 23 
        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.Label_2, self.gbcPanel0 ) 
        self.panel0.add( self.Label_2 ) 

        self.Additional_Parms_TF = JTextField(10,focusLost=self.keyPressed) 
        #self.Additional_Parms_TF.getDocument().addDocumentListener()
        self.Additional_Parms_TF.setEnabled(True)
        self.gbcPanel0.gridx = 2 
        self.gbcPanel0.gridy = 25 
        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.Additional_Parms_TF, self.gbcPanel0 ) 
        self.panel0.add( self.Additional_Parms_TF ) 

        self.Blank_6 = JLabel( " ") 
        self.Blank_6.setEnabled(True)
        self.gbcPanel0.gridx = 2 
        self.gbcPanel0.gridy = 27
        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, self.gbcPanel0 ) 
        self.panel0.add( self.Blank_6 ) 

        self.Label_3 = JLabel( "Message:") 
        self.Label_3.setEnabled(True)
        self.gbcPanel0.gridx = 2 
        self.gbcPanel0.gridy = 29
        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.Label_3, self.gbcPanel0 ) 
        self.panel0.add( self.Label_3 ) 
		
        self.add(self.panel0)

    # Custom load any data field and initialize the values
    def customizeComponents(self):
        self.Program_Executable_TF.setText(self.local_settings.getSetting('Volatility_Directory'))
        #pass
        
    # Return the settings used
    def getSettings(self):
        return self.local_settings
Exemplo n.º 54
0
class BurpExtender(IBurpExtender, ITab, IMessageEditorController, IContextMenuFactory, ActionListener,
                   AbstractTableModel, Runnable):

    #
    # Implement IBurpExtender
    #
    def registerExtenderCallbacks(self, callbacks):
        # Initialize the global stdout stream
        global stdout

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

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

        # set our extension name
        callbacks.setExtensionName("Burpsuite Yara Scanner")

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

        # main split pane
        splitpane = JSplitPane(JSplitPane.VERTICAL_SPLIT)

        # table of log entries
        logTable = Table(self)
        scrollPane = JScrollPane(logTable)
        splitpane.setLeftComponent(scrollPane)

        # Options panel
        optionsPanel = JPanel()
        optionsPanel.setLayout(GridBagLayout())
        constraints = GridBagConstraints()

        yara_exe_label = JLabel("Yara Executable Location:")
        constraints.fill = GridBagConstraints.HORIZONTAL
        constraints.gridx = 0
        constraints.gridy = 0
        optionsPanel.add(yara_exe_label, constraints)

        self._yara_exe_txtField = JTextField(25)
        constraints.fill = GridBagConstraints.HORIZONTAL
        constraints.gridx = 1
        constraints.gridy = 0
        optionsPanel.add(self._yara_exe_txtField, constraints)

        yara_rules_label = JLabel("Yara Rules File:")
        constraints.fill = GridBagConstraints.HORIZONTAL
        constraints.gridx = 0
        constraints.gridy = 1
        optionsPanel.add(yara_rules_label, constraints)
		
        self._yara_rules_files = Vector()
        self._yara_rules_files.add("< None >")
        self._yara_rules_fileList = JList(self._yara_rules_files)
        constraints.fill = GridBagConstraints.HORIZONTAL
        constraints.gridx = 1
        constraints.gridy = 1
        optionsPanel.add(self._yara_rules_fileList, constraints)
        
        self._yara_rules_select_files_button = JButton("Select Files")
        self._yara_rules_select_files_button.addActionListener(self)
        constraints.fill = GridBagConstraints.HORIZONTAL
        constraints.gridx = 1
        constraints.gridy = 2
        optionsPanel.add(self._yara_rules_select_files_button, constraints)

        self._yara_clear_button = JButton("Clear Yara Results Table")
        self._yara_clear_button.addActionListener(self)
        constraints.fill = GridBagConstraints.HORIZONTAL
        constraints.gridx = 1
        constraints.gridy = 3
        optionsPanel.add(self._yara_clear_button, constraints)

        # Tabs with request/response viewers
        viewerTabs = JTabbedPane()
        self._requestViewer = callbacks.createMessageEditor(self, False)
        self._responseViewer = callbacks.createMessageEditor(self, False)
        viewerTabs.addTab("Request", self._requestViewer.getComponent())
        viewerTabs.addTab("Response", self._responseViewer.getComponent())
        splitpane.setRightComponent(viewerTabs)

        # Tabs for the Yara output and the Options
        self._mainTabs = JTabbedPane()
        self._mainTabs.addTab("Yara Output", splitpane)
        self._mainTabs.addTab("Options", optionsPanel)

        # customize our UI components
        callbacks.customizeUiComponent(splitpane)
        callbacks.customizeUiComponent(logTable)
        callbacks.customizeUiComponent(scrollPane)
        callbacks.customizeUiComponent(viewerTabs)
        callbacks.customizeUiComponent(self._mainTabs)

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

        # add ourselves as a context menu factory
        callbacks.registerContextMenuFactory(self)

        # Custom Menu Item
        self.menuItem = JMenuItem("Scan with Yara")
        self.menuItem.addActionListener(self)

        # obtain our output stream
        stdout = PrintWriter(callbacks.getStdout(), True)

        # Print a startup notification
        stdout.println("Burpsuite Yara scanner initialized.")

    #
    # Implement ITab
    #
    def getTabCaption(self):
        return "Yara"

    def getUiComponent(self):
        return self._mainTabs

    #
    # Implement IContextMenuFactory
    #
    def createMenuItems(self, invocation):
        if invocation.getInvocationContext() == invocation.CONTEXT_TARGET_SITE_MAP_TREE:
            self.requestResponses = invocation.getSelectedMessages()
            return [self.menuItem]
        else:
            self.requestResponses = None
        return None

    #
    # Implement Action
    #
    def actionPerformed(self, actionEvent):
        global yara_rules
        global yara_path

        if actionEvent.getSource() is self.menuItem:
            yara_path = self._yara_exe_txtField.getText()
            yara_rules = self._yara_rules_files
            t = Thread(self)
            t.start()
        elif actionEvent.getSource() is self._yara_clear_button:
            # Delete the LogEntry objects from the log
            row = self._log.size()
            self._lock.acquire()
            self._log.clear()

            # Update the Table
            self.fireTableRowsDeleted(0, row)

            # Clear data regarding any selected LogEntry objects from the request / response viewers
            self._requestViewer.setMessage([], True)
            self._responseViewer.setMessage([], False)
            self._currentlyDisplayedItem = None
            self._lock.release()
        elif actionEvent.getSource() is self._yara_rules_select_files_button:
            fileChooser = JFileChooser()
            yarFilter = FileNameExtensionFilter("Yara Rules", ["yar"])
            fileChooser.addChoosableFileFilter(yarFilter)
            fileChooser.setFileFilter(yarFilter)
            fileChooser.setMultiSelectionEnabled(True)
            fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY)
            ret = fileChooser.showOpenDialog(None)
            if ret == JFileChooser.APPROVE_OPTION:
                self._yara_rules_files.clear()
                for file in fileChooser.getSelectedFiles():
                    self._yara_rules_files.add(file.getPath())
                self._yara_rules_fileList.setListData(self._yara_rules_files)
        else:
            stdout.println("Unknown Event Received.")

    #
    # Implement Runnable
    #
    def run(self):
        self.yaraScan()

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

    def getColumnCount(self):
        return 2

    def getColumnName(self, columnIndex):
        if columnIndex == 0:
            return "Rule Name"
        if columnIndex == 1:
            return "URL"
        return ""

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

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

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

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

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

    #
    # Implement the Yara scanning logic
    #
    def yaraScan(self):
        # If stdout has not yet been initialized, punt.
        if stdout is None:
            return

        # If the location of the yara executable and rules files are NULL, punt.
        if yara_rules is None or yara_path is None or yara_rules.size() == 0 or yara_rules.contains("< None >") or len(yara_path) == 0:
            JOptionPane.showMessageDialog(None, "Error: Please specify the path to the yara executable and rules file in "
                                                "the options tab.")
            return

        # If iRequestResponses is None, punt.
        if self.requestResponses is None:
            JOptionPane.showMessageDialog(None, "Error: No Request/Responses were selected.")
            return
        else:
            stdout.println("Processing %d item(s)." % len(self.requestResponses))

        # Get the OS temp folder
        os_name = System.getProperty("os.name").lower()

        temp_folder = None
        if "linux" in os_name:
            temp_folder = "/tmp"
        elif "windows" in os_name:
            temp_folder = os.environ.get("TEMP")
            if temp_folder is None:
                temp_folder = os.environ.get("TMP")

        if temp_folder is None:
            stdout.println("Error: Could not determine TEMP folder location.")
            return

        # Keep track of the number of matches.
        matchCount = 0

        # Process the site map selected messages
        for idx, iRequestResponse in enumerate(self.requestResponses):
            # Process the request
            request = iRequestResponse.getRequest()
            if request is not None:
                if len(request) > 0:
                    try:
                        # Yara does not support scanning from stdin so we will need to create a temp file and scan it
                        req_filename = os.path.join(temp_folder, "req_" + str(idx) + ".tmp")
                        req_file = open(req_filename, "wb")
                        req_file.write(request)
                        req_file.close()
                        for rules in yara_rules:
                            yara_req_output = subprocess.check_output([yara_path, rules, req_filename])
                            if yara_req_output is not None and len(yara_req_output) > 0:
                                ruleName = (yara_req_output.split())[0]
                                self._lock.acquire()
                                row = self._log.size()
                                # TODO: Don't add duplicate items to the table
                                self._log.add(LogEntry(ruleName, iRequestResponse, self._helpers.analyzeRequest(iRequestResponse).getUrl()))
                                self.fireTableRowsInserted(row, row)
                                self._lock.release()
                                matchCount += 1
                    except Exception as e:
                        JOptionPane.showMessageDialog(None, "Error running Yara. Please check your configuration and rules.")
                        return
                    finally:
                        # Remove the temp file
                        if req_file is not None:
                            req_file.close()
                        os.remove(req_filename)

            # Process the response
            response = iRequestResponse.getResponse()
            if response is not None:
                if len(response) > 0:
                    try:
                        # Yara does not support scanning from stdin so we will need to create a temp file and scan it
                        resp_filename = os.path.join(temp_folder, "resp_" + str(idx) + ".tmp")
                        resp_file = open(resp_filename, "wb")
                        resp_file.write(response)
                        resp_file.close()
                        for rules in yara_rules:
                            yara_resp_output = subprocess.check_output([yara_path, rules, resp_filename])
                            if yara_resp_output is not None and len(yara_resp_output) > 0:
                                ruleName = (yara_resp_output.split())[0]
                                self._lock.acquire()
                                row = self._log.size()
                                # TODO: Don't add duplicate items to the table
                                self._log.add(LogEntry(ruleName, iRequestResponse, self._helpers.analyzeRequest(iRequestResponse).getUrl()))
                                self.fireTableRowsInserted(row, row)
                                self._lock.release()
                                matchCount += 1
                    except Exception as e:
                        JOptionPane.showMessageDialog(None, "Error running Yara. Please check your configuration and rules.")
                        return
                    finally:
                        # Remove the temp file
                        if resp_file is not None:
                            resp_file.close()
                        os.remove(resp_filename)

        # Print a completion notification
        JOptionPane.showMessageDialog(None, "Yara scanning complete. %d rule(s) matched." % matchCount)
Exemplo n.º 55
0
 def __init__(self, message, options):
     self._selection_list = JList(options)
     self._selection_list.setVisibleRowCount(8)
     panel = self._create_panel(message, JScrollPane(self._selection_list))
     pane = WrappedOptionPane(panel, PLAIN_MESSAGE, OK_CANCEL_OPTION)
     _SwingDialog.__init__(self, pane)
Exemplo n.º 56
0
class BurpExtender(IBurpExtender, ITab, IHttpListener, IMessageEditorController, AbstractTableModel, IContextMenuFactory):

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

        self.initInterceptionFilters()

        self.initEnforcementDetector()

        self.initEnforcementDetectorUnauthorized()

        self.initExport()

        self.initConfigurationTab()

        self.initTabs()
        
        self.initCallbacks()

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

        self.logTable.setAutoCreateRowSorter(True)        

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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




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


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

    def getColumnCount(self):
        return 7

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

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

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

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

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

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


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

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


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

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

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

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

        return

    def sendRequestToAutorizeWork(self,messageInfo):

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


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

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

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

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

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

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

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

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

                auth_enforced = 1
                
                for filter in filters:

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

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

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

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

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

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

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

        return impression

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

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

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

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

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

    def getCookieFromMessage(self, messageInfo):
        headers = list(self._helpers.analyzeRequest(messageInfo.getRequest()).getHeaders())
        for header in headers:
            if "Cookie:" in header:
                return header
        return None
Exemplo n.º 57
0
    def initComponents(self):
        self.panel0 = JPanel()

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

        self.Label_1 = JLabel("Protocol:")
        self.Label_1.setEnabled(True)
        self.gbcPanel0.gridx = 2 
        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.Label_1, self.gbcPanel0 ) 
        self.panel0.add( self.Label_1 ) 

        self.Protocol_TF = JTextField(20, focusLost=self.setProtocol) 
        self.Protocol_TF.setEnabled(True)
        self.gbcPanel0.gridx = 4 
        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.Protocol_TF, self.gbcPanel0 ) 
        self.panel0.add( self.Protocol_TF ) 

        self.Blank_1 = JLabel( " ") 
        self.Blank_1.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, self.gbcPanel0 ) 
        self.panel0.add( self.Blank_1 ) 

        self.Label_2 = JLabel("Cuckoo IP Address")
        self.Label_2.setEnabled(True)
        self.gbcPanel0.gridx = 2 
        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.Label_2, self.gbcPanel0 ) 
        self.panel0.add( self.Label_2 ) 

        self.IP_Address_TF = JTextField(20, focusLost=self.setIPAddress) 
        self.IP_Address_TF.setEnabled(True)
        self.gbcPanel0.gridx = 4 
        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.IP_Address_TF, self.gbcPanel0 ) 
        self.panel0.add( self.IP_Address_TF ) 

        self.Blank_2 = JLabel( " ") 
        self.Blank_2.setEnabled(True)
        self.gbcPanel0.gridx = 2 
        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.Blank_2, self.gbcPanel0 ) 
        self.panel0.add( self.Blank_2 ) 

        self.Label_3 = JLabel("Port Number")
        self.Label_3.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.Label_3, self.gbcPanel0 ) 
        self.panel0.add( self.Label_3 ) 

        self.Port_Number_TF = JTextField(20, focusLost=self.setPortNumber) 
        self.Port_Number_TF.setEnabled(True)
        self.gbcPanel0.gridx = 4 
        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.Port_Number_TF, self.gbcPanel0 ) 
        self.panel0.add( self.Port_Number_TF ) 

        self.Blank_3 = JLabel( " ") 
        self.Blank_3.setEnabled(True)
        self.gbcPanel0.gridx = 2 
        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.Blank_3, self.gbcPanel0 ) 
        self.panel0.add( self.Blank_3 ) 

        
        self.Blank_5 = JLabel( "Tag to Choose: ") 
        self.Blank_5.setEnabled(True)
        self.gbcPanel0.gridx = 2 
        self.gbcPanel0.gridy = 13
        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, self.gbcPanel0 ) 
        self.panel0.add( self.Blank_5 ) 

        self.find_tags()
        self.List_Box_LB = JList( self.tag_list, valueChanged=self.onchange_lb)
        self.List_Box_LB.setVisibleRowCount( 3 ) 
        self.scpList_Box_LB = JScrollPane( self.List_Box_LB ) 
        self.gbcPanel0.gridx = 4 
        self.gbcPanel0.gridy = 13 
        self.gbcPanel0.gridwidth = 1 
        self.gbcPanel0.gridheight = 1 
        self.gbcPanel0.fill = GridBagConstraints.BOTH 
        self.gbcPanel0.weightx = 1 
        self.gbcPanel0.weighty = 1 
        self.gbcPanel0.anchor = GridBagConstraints.NORTH 
        self.gbPanel0.setConstraints( self.scpList_Box_LB, self.gbcPanel0 ) 
        self.panel0.add( self.scpList_Box_LB ) 

        self.Blank_6 = JLabel( " ") 
        self.Blank_6.setEnabled(True)
        self.gbcPanel0.gridx = 2 
        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.Blank_6, self.gbcPanel0 ) 
        self.panel0.add( self.Blank_6 ) 

        self.Submit_File_CB = JCheckBox("Submit a File", actionPerformed=self.checkBoxEvent)
        self.gbcPanel0.gridx = 2 
        self.gbcPanel0.gridy = 17 
        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.Submit_File_CB, self.gbcPanel0 ) 
        self.panel0.add( self.Submit_File_CB ) 

        # self.Submit_URL_CB = JCheckBox("Submit a URL", actionPerformed=self.checkBoxEvent)
        # self.gbcPanel0.gridx = 2 
        # self.gbcPanel0.gridy = 23 
        # 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.Submit_URL_CB, self.gbcPanel0 ) 
        # self.panel0.add( self.Submit_URL_CB ) 

        self.Check_Server_Status_BTN = JButton( "Check Server Status", actionPerformed=self.Check_Server) 
        self.Check_Server_Status_BTN.setEnabled(True)
        self.rbgPanel0.add( self.Check_Server_Status_BTN ) 
        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.Check_Server_Status_BTN, self.gbcPanel0 ) 
        self.panel0.add( self.Check_Server_Status_BTN ) 

        self.Error_Message = JLabel( "") 
        self.Error_Message.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.Error_Message, self.gbcPanel0 ) 
        self.panel0.add( self.Error_Message ) 


        self.add(self.panel0)
Exemplo n.º 58
0
class GUI_TestWithUISettingsPanel(IngestModuleIngestJobSettingsPanel):
    # Note, we can't use a self.settings instance variable.
    # Rather, self.local_settings is used.
    # https://wiki.python.org/jython/UserGuide#javabean-properties
    # Jython Introspector generates a property - 'settings' on the basis
    # of getSettings() defined in this class. Since only getter function
    # is present, it creates a read-only 'settings' property. This auto-
    # generated read-only property overshadows the instance-variable -
    # 'settings'
    
    # We get passed in a previous version of the settings so that we can
    # prepopulate the UI
    # TODO: Update this for your UI
    def __init__(self, settings):
        self.local_settings = settings
        self.initComponents()
        self.customizeComponents()
    
    # TODO: Update this for your UI
    def checkBoxEvent(self, event):
        if self.Exec_Program_CB.isSelected():
            self.local_settings.setSetting('Exec_Prog_Flag', 'true')
            self.Program_Executable_TF.setEnabled(True)
            self.Find_Program_Exec_BTN.setEnabled(True)
        else:
            self.local_settings.setSetting('Exec_Prog_Flag', 'false')
            self.Program_Executable_TF.setText("")
            self.Program_Executable_TF.setEnabled(False)
            self.Find_Program_Exec_BTN.setEnabled(False)

        if self.Imp_File_CB.isSelected():
            self.local_settings.setSetting('Imp_File_Flag', 'true')
            self.File_Imp_TF.setEnabled(True)
            self.Find_Imp_File_BTN.setEnabled(True)
        else:
            self.local_settings.setSetting('Imp_File_Flag', 'false')
            self.File_Imp_TF.setText("")
            self.local_settings.setSetting('File_Imp_TF', "")
            self.File_Imp_TF.setEnabled(False)
            self.Find_Imp_File_BTN.setEnabled(False)

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

    def onchange_cb(self, event):
        self.local_settings.setSetting('ComboBox', event.item) 
        #self.Error_Message.setText(event.item)

    def onchange_lb(self, event):
        self.local_settings.setSetting('ListBox', "")
        list_selected = self.List_Box_LB.getSelectedValuesList()
        self.local_settings.setSetting('ListBox', str(list_selected))      
        # if (len(list_selected) > 0):
            # self.Error_Message.setText(str(list_selected))
        # else:
            # self.Error_Message.setText("")

    def onClick(self, e):

       chooseFile = JFileChooser()
       filter = FileNameExtensionFilter("SQLite", ["sqlite"])
       chooseFile.addChoosableFileFilter(filter)

       ret = chooseFile.showDialog(self.panel0, "Select SQLite")

       if ret == JFileChooser.APPROVE_OPTION:
           file = chooseFile.getSelectedFile()
           Canonical_file = file.getCanonicalPath()
           #text = self.readPath(file)
           if self.File_Imp_TF.isEnabled():
              self.File_Imp_TF.setText(Canonical_file)
              self.local_settings.setSetting('File_Imp_TF', Canonical_file)
           else:
              self.local_settings.setSetting('ExecFile', Canonical_file)
              self.Program_Executable_TF.setText(Canonical_file)

    # TODO: Update this for your UI
    def initComponents(self):
        self.panel0 = JPanel()

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

        self.Exec_Program_CB = JCheckBox("Execute Program", actionPerformed=self.checkBoxEvent)
        self.gbcPanel0.gridx = 2 
        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.Exec_Program_CB, self.gbcPanel0 ) 
        self.panel0.add( self.Exec_Program_CB ) 

        self.Program_Executable_TF = JTextField(20) 
        self.Program_Executable_TF.setEnabled(False)
        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.Program_Executable_TF, self.gbcPanel0 ) 
        self.panel0.add( self.Program_Executable_TF ) 

        self.Find_Program_Exec_BTN = JButton( "Find Exec", actionPerformed=self.onClick)
        self.Find_Program_Exec_BTN.setEnabled(False)
        self.rbgPanel0.add( self.Find_Program_Exec_BTN ) 
        self.gbcPanel0.gridx = 6 
        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.Find_Program_Exec_BTN, self.gbcPanel0 ) 
        self.panel0.add( self.Find_Program_Exec_BTN ) 

        self.Imp_File_CB = JCheckBox( "Import File", actionPerformed=self.checkBoxEvent) 
        self.gbcPanel0.gridx = 2 
        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.Imp_File_CB, self.gbcPanel0 ) 
        self.panel0.add( self.Imp_File_CB ) 

        self.File_Imp_TF = JTextField(20) 
        self.File_Imp_TF.setEnabled(False)
        self.gbcPanel0.gridx = 2 
        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.File_Imp_TF, self.gbcPanel0 ) 
        self.panel0.add( self.File_Imp_TF ) 

        self.Find_Imp_File_BTN = JButton( "Find File", actionPerformed=self.onClick) 
        self.Find_Imp_File_BTN.setEnabled(False)
        self.rbgPanel0.add( self.Find_Imp_File_BTN ) 
        self.gbcPanel0.gridx = 6 
        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.Find_Imp_File_BTN, self.gbcPanel0 ) 
        self.panel0.add( self.Find_Imp_File_BTN ) 

        self.Check_Box_CB = JCheckBox( "Check Box 1", actionPerformed=self.checkBoxEvent) 
        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.Check_Box_CB, self.gbcPanel0 ) 
        self.panel0.add( self.Check_Box_CB ) 

        self.dataComboBox_CB = ("Chocolate", "Ice Cream", "Apple Pie") 
        self.ComboBox_CB = JComboBox( self.dataComboBox_CB)
        self.ComboBox_CB.itemStateChanged = self.onchange_cb        
        self.gbcPanel0.gridx = 2 
        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.ComboBox_CB, self.gbcPanel0 ) 
        self.panel0.add( self.ComboBox_CB ) 
        
        self.dataList_Box_LB = ("Chocolate", "Ice Cream", "Apple Pie", "Pudding", "Candy" )
        self.List_Box_LB = JList( self.dataList_Box_LB, valueChanged=self.onchange_lb)
        #self.List_Box_LB.itemStateChanged = self.onchange_lb
        self.List_Box_LB.setVisibleRowCount( 3 ) 
        self.scpList_Box_LB = JScrollPane( self.List_Box_LB ) 
        self.gbcPanel0.gridx = 6 
        self.gbcPanel0.gridy = 15 
        self.gbcPanel0.gridwidth = 1 
        self.gbcPanel0.gridheight = 1 
        self.gbcPanel0.fill = GridBagConstraints.BOTH 
        self.gbcPanel0.weightx = 1 
        self.gbcPanel0.weighty = 1 
        self.gbcPanel0.anchor = GridBagConstraints.NORTH 
        self.gbPanel0.setConstraints( self.scpList_Box_LB, self.gbcPanel0 ) 
        self.panel0.add( self.scpList_Box_LB ) 

        # self.Radio_Button_RB = JRadioButton( "Radio Button"  ) 
        # self.rbgPanel0.add( self.Radio_Button_RB ) 
        # self.gbcPanel0.gridx = 7 
        # self.gbcPanel0.gridy = 17
        # 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.Radio_Button_RB, self.gbcPanel0 ) 
        # self.panel0.add( self.Radio_Button_RB ) 

        # self.Label_1 = JLabel( "Error Message:") 
        # self.Label_1.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.Label_1, self.gbcPanel0 ) 
        # self.panel0.add( self.Label_1 ) 
		
        # self.Error_Message = JLabel( "") 
        # self.Error_Message.setEnabled(True)
        # self.gbcPanel0.gridx = 6
        # 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.Error_Message, self.gbcPanel0 ) 
        # self.panel0.add( self.Error_Message ) 
		
        self.add(self.panel0)

    # TODO: Update this for your UI
    def customizeComponents(self):
        self.Exec_Program_CB.setSelected(self.local_settings.getSetting('Exec_Prog_Flag') == 'true')
        self.Imp_File_CB.setSelected(self.local_settings.getSetting('Imp_File_Flag') == 'true')
        self.Check_Box_CB.setSelected(self.local_settings.getSetting('Check_Box_1') == 'true')

    # Return the settings used
    def getSettings(self):
        return self.local_settings
Exemplo n.º 59
0
    def registerExtenderCallbacks(self, callbacks):
        # Initialize the global stdout stream
        global stdout

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

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

        # set our extension name
        callbacks.setExtensionName("Burpsuite Yara Scanner")

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

        # main split pane
        splitpane = JSplitPane(JSplitPane.VERTICAL_SPLIT)

        # table of log entries
        logTable = Table(self)
        scrollPane = JScrollPane(logTable)
        splitpane.setLeftComponent(scrollPane)

        # Options panel
        optionsPanel = JPanel()
        optionsPanel.setLayout(GridBagLayout())
        constraints = GridBagConstraints()

        yara_exe_label = JLabel("Yara Executable Location:")
        constraints.fill = GridBagConstraints.HORIZONTAL
        constraints.gridx = 0
        constraints.gridy = 0
        optionsPanel.add(yara_exe_label, constraints)

        self._yara_exe_txtField = JTextField(25)
        constraints.fill = GridBagConstraints.HORIZONTAL
        constraints.gridx = 1
        constraints.gridy = 0
        optionsPanel.add(self._yara_exe_txtField, constraints)

        yara_rules_label = JLabel("Yara Rules File:")
        constraints.fill = GridBagConstraints.HORIZONTAL
        constraints.gridx = 0
        constraints.gridy = 1
        optionsPanel.add(yara_rules_label, constraints)
		
        self._yara_rules_files = Vector()
        self._yara_rules_files.add("< None >")
        self._yara_rules_fileList = JList(self._yara_rules_files)
        constraints.fill = GridBagConstraints.HORIZONTAL
        constraints.gridx = 1
        constraints.gridy = 1
        optionsPanel.add(self._yara_rules_fileList, constraints)
        
        self._yara_rules_select_files_button = JButton("Select Files")
        self._yara_rules_select_files_button.addActionListener(self)
        constraints.fill = GridBagConstraints.HORIZONTAL
        constraints.gridx = 1
        constraints.gridy = 2
        optionsPanel.add(self._yara_rules_select_files_button, constraints)

        self._yara_clear_button = JButton("Clear Yara Results Table")
        self._yara_clear_button.addActionListener(self)
        constraints.fill = GridBagConstraints.HORIZONTAL
        constraints.gridx = 1
        constraints.gridy = 3
        optionsPanel.add(self._yara_clear_button, constraints)

        # Tabs with request/response viewers
        viewerTabs = JTabbedPane()
        self._requestViewer = callbacks.createMessageEditor(self, False)
        self._responseViewer = callbacks.createMessageEditor(self, False)
        viewerTabs.addTab("Request", self._requestViewer.getComponent())
        viewerTabs.addTab("Response", self._responseViewer.getComponent())
        splitpane.setRightComponent(viewerTabs)

        # Tabs for the Yara output and the Options
        self._mainTabs = JTabbedPane()
        self._mainTabs.addTab("Yara Output", splitpane)
        self._mainTabs.addTab("Options", optionsPanel)

        # customize our UI components
        callbacks.customizeUiComponent(splitpane)
        callbacks.customizeUiComponent(logTable)
        callbacks.customizeUiComponent(scrollPane)
        callbacks.customizeUiComponent(viewerTabs)
        callbacks.customizeUiComponent(self._mainTabs)

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

        # add ourselves as a context menu factory
        callbacks.registerContextMenuFactory(self)

        # Custom Menu Item
        self.menuItem = JMenuItem("Scan with Yara")
        self.menuItem.addActionListener(self)

        # obtain our output stream
        stdout = PrintWriter(callbacks.getStdout(), True)

        # Print a startup notification
        stdout.println("Burpsuite Yara scanner initialized.")
Exemplo n.º 60
0
class CuckooSettingsWithUISettingsPanel(IngestModuleIngestJobSettingsPanel):
    # Note, we can't use a self.settings instance variable.
    # Rather, self.local_settings is used.
    # https://wiki.python.org/jython/UserGuide#javabean-properties
    # Jython Introspector generates a property - 'settings' on the basis
    # of getSettings() defined in this class. Since only getter function
    # is present, it creates a read-only 'settings' property. This auto-
    # generated read-only property overshadows the instance-variable -
    # 'settings'
    
    # We get passed in a previous version of the settings so that we can
    # prepopulate the UI
    # TODO: Update this for your UI
    def __init__(self, settings):
        self.local_settings = settings
        self.tag_list = []
        self.initComponents()
        self.customizeComponents()
        self.path_to_cuckoo_exe = os.path.join(os.path.dirname(os.path.abspath(__file__)), "cuckoo_api.exe")
 
    # Check the checkboxs to see what actions need to be taken
    def checkBoxEvent(self, event):
        if self.Submit_File_CB.isSelected():
            self.local_settings.setSetting('Submit_File', 'true')
            self.local_settings.setSetting('Submit_URL', 'false')
        else:
            self.local_settings.setSetting('Submit_File', 'false')
            
    def onchange_lb(self, event):
        self.local_settings.cleartag_list()
        list_selected = self.List_Box_LB.getSelectedValuesList()
        self.local_settings.setSetting('tag_list', str(list_selected))      

    def find_tags(self):
        
        sql_statement = "SELECT distinct(display_name) u_tag_name FROM content_tags INNER JOIN tag_names ON " + \
                        " content_tags.tag_name_id = tag_names.tag_name_id;"
        skCase = Case.getCurrentCase().getSleuthkitCase()
        dbquery = skCase.executeQuery(sql_statement)
        resultSet = dbquery.getResultSet()
        while resultSet.next():
             self.tag_list.append(resultSet.getString("u_tag_name"))
        dbquery.close()

    # Check to see if the Cuckoo server is available and you can talk to it
    def Check_Server(self, e):

       pipe = Popen([self.path_to_cuckoo_exe, self.Protocol_TF.getText(),self.IP_Address_TF.getText(), self.Port_Number_TF.getText(), "cuckoo_status" ], stdout=PIPE, stderr=PIPE)
        
       out_text = pipe.communicate()[0]
       self.Error_Message.setText("Cuckoo Status is " + out_text)
       #self.log(Level.INFO, "Cuckoo Status is ==> " + out_text)

           
    def setIPAddress(self, event):
        self.local_settings.setSetting('IP_Address', self.IP_Address_TF.getText()) 

    def setProtocol(self, event):
        self.local_settings.setSetting('Protocol', self.Protocol_TF.getText()) 

    def setPortNumber(self, event):
        self.local_settings.setSetting('Port_Number', self.Port_Number_TF.getText()) 

    # Create the initial data fields/layout in the UI
    def initComponents(self):
        self.panel0 = JPanel()

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

        self.Label_1 = JLabel("Protocol:")
        self.Label_1.setEnabled(True)
        self.gbcPanel0.gridx = 2 
        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.Label_1, self.gbcPanel0 ) 
        self.panel0.add( self.Label_1 ) 

        self.Protocol_TF = JTextField(20, focusLost=self.setProtocol) 
        self.Protocol_TF.setEnabled(True)
        self.gbcPanel0.gridx = 4 
        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.Protocol_TF, self.gbcPanel0 ) 
        self.panel0.add( self.Protocol_TF ) 

        self.Blank_1 = JLabel( " ") 
        self.Blank_1.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, self.gbcPanel0 ) 
        self.panel0.add( self.Blank_1 ) 

        self.Label_2 = JLabel("Cuckoo IP Address")
        self.Label_2.setEnabled(True)
        self.gbcPanel0.gridx = 2 
        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.Label_2, self.gbcPanel0 ) 
        self.panel0.add( self.Label_2 ) 

        self.IP_Address_TF = JTextField(20, focusLost=self.setIPAddress) 
        self.IP_Address_TF.setEnabled(True)
        self.gbcPanel0.gridx = 4 
        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.IP_Address_TF, self.gbcPanel0 ) 
        self.panel0.add( self.IP_Address_TF ) 

        self.Blank_2 = JLabel( " ") 
        self.Blank_2.setEnabled(True)
        self.gbcPanel0.gridx = 2 
        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.Blank_2, self.gbcPanel0 ) 
        self.panel0.add( self.Blank_2 ) 

        self.Label_3 = JLabel("Port Number")
        self.Label_3.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.Label_3, self.gbcPanel0 ) 
        self.panel0.add( self.Label_3 ) 

        self.Port_Number_TF = JTextField(20, focusLost=self.setPortNumber) 
        self.Port_Number_TF.setEnabled(True)
        self.gbcPanel0.gridx = 4 
        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.Port_Number_TF, self.gbcPanel0 ) 
        self.panel0.add( self.Port_Number_TF ) 

        self.Blank_3 = JLabel( " ") 
        self.Blank_3.setEnabled(True)
        self.gbcPanel0.gridx = 2 
        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.Blank_3, self.gbcPanel0 ) 
        self.panel0.add( self.Blank_3 ) 

        
        self.Blank_5 = JLabel( "Tag to Choose: ") 
        self.Blank_5.setEnabled(True)
        self.gbcPanel0.gridx = 2 
        self.gbcPanel0.gridy = 13
        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, self.gbcPanel0 ) 
        self.panel0.add( self.Blank_5 ) 

        self.find_tags()
        self.List_Box_LB = JList( self.tag_list, valueChanged=self.onchange_lb)
        self.List_Box_LB.setVisibleRowCount( 3 ) 
        self.scpList_Box_LB = JScrollPane( self.List_Box_LB ) 
        self.gbcPanel0.gridx = 4 
        self.gbcPanel0.gridy = 13 
        self.gbcPanel0.gridwidth = 1 
        self.gbcPanel0.gridheight = 1 
        self.gbcPanel0.fill = GridBagConstraints.BOTH 
        self.gbcPanel0.weightx = 1 
        self.gbcPanel0.weighty = 1 
        self.gbcPanel0.anchor = GridBagConstraints.NORTH 
        self.gbPanel0.setConstraints( self.scpList_Box_LB, self.gbcPanel0 ) 
        self.panel0.add( self.scpList_Box_LB ) 

        self.Blank_6 = JLabel( " ") 
        self.Blank_6.setEnabled(True)
        self.gbcPanel0.gridx = 2 
        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.Blank_6, self.gbcPanel0 ) 
        self.panel0.add( self.Blank_6 ) 

        self.Submit_File_CB = JCheckBox("Submit a File", actionPerformed=self.checkBoxEvent)
        self.gbcPanel0.gridx = 2 
        self.gbcPanel0.gridy = 17 
        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.Submit_File_CB, self.gbcPanel0 ) 
        self.panel0.add( self.Submit_File_CB ) 

        # self.Submit_URL_CB = JCheckBox("Submit a URL", actionPerformed=self.checkBoxEvent)
        # self.gbcPanel0.gridx = 2 
        # self.gbcPanel0.gridy = 23 
        # 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.Submit_URL_CB, self.gbcPanel0 ) 
        # self.panel0.add( self.Submit_URL_CB ) 

        self.Check_Server_Status_BTN = JButton( "Check Server Status", actionPerformed=self.Check_Server) 
        self.Check_Server_Status_BTN.setEnabled(True)
        self.rbgPanel0.add( self.Check_Server_Status_BTN ) 
        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.Check_Server_Status_BTN, self.gbcPanel0 ) 
        self.panel0.add( self.Check_Server_Status_BTN ) 

        self.Error_Message = JLabel( "") 
        self.Error_Message.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.Error_Message, self.gbcPanel0 ) 
        self.panel0.add( self.Error_Message ) 


        self.add(self.panel0)

    # Custom load any data field and initialize the values
    def customizeComponents(self):
        #self.Exclude_File_Sources_CB.setSelected(self.local_settings.getExclude_File_Sources())
        #self.Run_Cuckoo_CB.setSelected(self.local_settings.getSetting('Submit_File') == 'true')
        #self.Import_Cuckoo_CB.setSelected(self.local_settings.getImport_Cuckoo())
        self.Port_Number_TF.setText(self.local_settings.getSetting('Port_Number'))
        self.IP_Address_TF.setText(self.local_settings.getSetting('IP_Address'))
        self.Protocol_TF.setText(self.local_settings.getSetting('Protocol'))
        

    # Return the settings used
    def getSettings(self):
        return self.local_settings